ngram
listlengths 0
82k
|
|---|
[
"# self.new_reserva_view.show() print(inspect.stack()[0][3]) self.close() if __name__ == '__main__': import sys",
"def open_new_libros_window(self): self.new_libros_view = NewLibrosWindow() self.new_libros_view.show() print(inspect.stack()[0][3]) self.close() def open_edit_libros_window(self):",
"= NewReserva() # self.new_reserva_view.show() print(inspect.stack()[0][3]) self.close() def open_delete_reserva_window(self): # self.new_reserva_view",
"# self.new_reserva_view = NewReserva() # self.new_reserva_view.show() print(inspect.stack()[0][3]) self.close() def open_delete_reserva_window(self):",
"import NewLibrosWindow from ui_mant_libros_edit import EditLibrosWindow from ui_mant_libros_id_edit import GetIdEditWindow",
"self.setGeometry(650, 300, 150, 100) def createButtons(self): btn_new_libros = QtGui.QPushButton('Nuevo') btn_new_libros.clicked.connect(self.open_new_libros_window)",
"hbox.addWidget(btn_new_libros) hbox.addWidget(btn_edit_libros) hbox.addWidget(btn_list_libros) hbox.addWidget(btn_delete_libros) vbox = QtGui.QVBoxLayout() vbox.addLayout(hbox) self.setLayout(vbox) def",
"self.close() def open_delete_reserva_window(self): # self.new_reserva_view = NewReserva() # self.new_reserva_view.show() print(inspect.stack()[0][3])",
"'__main__': import sys app = QtGui.QApplication(sys.argv) mainWin = MenuLibros() mainWin.show()",
"= QtGui.QPushButton('Listar') btn_list_libros.clicked.connect(self.close) btn_delete_libros = QtGui.QPushButton('Eliminar') btn_delete_libros.clicked.connect(self.close) hbox = QtGui.QHBoxLayout()",
"QtGui.QPushButton('Editar') btn_edit_libros.clicked.connect(self.open_edit_libros_window) btn_list_libros = QtGui.QPushButton('Listar') btn_list_libros.clicked.connect(self.close) btn_delete_libros = QtGui.QPushButton('Eliminar') btn_delete_libros.clicked.connect(self.close)",
"GetIdEditWindow() self.edit_libros_view.show() print(inspect.stack()[0][3]) self.close() def open_list_reserva_window(self): # self.new_reserva_view = NewReserva()",
"300, 150, 100) def createButtons(self): btn_new_libros = QtGui.QPushButton('Nuevo') btn_new_libros.clicked.connect(self.open_new_libros_window) btn_edit_libros",
"para editar Libros \"\"\" def __init__(self): super(MenuLibros, self).__init__() self.createButtons() self.setWindowTitle('Mantenimiento",
"QtGui.QPushButton('Nuevo') btn_new_libros.clicked.connect(self.open_new_libros_window) btn_edit_libros = QtGui.QPushButton('Editar') btn_edit_libros.clicked.connect(self.open_edit_libros_window) btn_list_libros = QtGui.QPushButton('Listar') btn_list_libros.clicked.connect(self.close)",
"self.edit_libros_view.show() print(inspect.stack()[0][3]) self.close() def open_list_reserva_window(self): # self.new_reserva_view = NewReserva() #",
"QtGui.QHBoxLayout() hbox.addWidget(btn_new_libros) hbox.addWidget(btn_edit_libros) hbox.addWidget(btn_list_libros) hbox.addWidget(btn_delete_libros) vbox = QtGui.QVBoxLayout() vbox.addLayout(hbox) self.setLayout(vbox)",
"150, 100) def createButtons(self): btn_new_libros = QtGui.QPushButton('Nuevo') btn_new_libros.clicked.connect(self.open_new_libros_window) btn_edit_libros =",
"from PyQt4 import QtGui from ui_mant_libros_new import NewLibrosWindow from ui_mant_libros_edit",
"QtGui.QVBoxLayout() vbox.addLayout(hbox) self.setLayout(vbox) def open_new_libros_window(self): self.new_libros_view = NewLibrosWindow() self.new_libros_view.show() print(inspect.stack()[0][3])",
"# Debug only import inspect class MenuLibros(QtGui.QWidget): \"\"\" Ventana-menu para",
"Libros \"\"\" def __init__(self): super(MenuLibros, self).__init__() self.createButtons() self.setWindowTitle('Mantenimiento Libros') self.setWindowIcon(QtGui.QIcon('images/user-plus.png'))",
"QtGui.QPushButton('Eliminar') btn_delete_libros.clicked.connect(self.close) hbox = QtGui.QHBoxLayout() hbox.addWidget(btn_new_libros) hbox.addWidget(btn_edit_libros) hbox.addWidget(btn_list_libros) hbox.addWidget(btn_delete_libros) vbox",
"PyQt4 import QtGui from ui_mant_libros_new import NewLibrosWindow from ui_mant_libros_edit import",
"self.new_reserva_view = NewReserva() # self.new_reserva_view.show() print(inspect.stack()[0][3]) self.close() if __name__ ==",
"btn_delete_libros = QtGui.QPushButton('Eliminar') btn_delete_libros.clicked.connect(self.close) hbox = QtGui.QHBoxLayout() hbox.addWidget(btn_new_libros) hbox.addWidget(btn_edit_libros) hbox.addWidget(btn_list_libros)",
"Ventana-menu para editar Libros \"\"\" def __init__(self): super(MenuLibros, self).__init__() self.createButtons()",
"self.close() def open_list_reserva_window(self): # self.new_reserva_view = NewReserva() # self.new_reserva_view.show() print(inspect.stack()[0][3])",
"import QtGui from ui_mant_libros_new import NewLibrosWindow from ui_mant_libros_edit import EditLibrosWindow",
"100) def createButtons(self): btn_new_libros = QtGui.QPushButton('Nuevo') btn_new_libros.clicked.connect(self.open_new_libros_window) btn_edit_libros = QtGui.QPushButton('Editar')",
"self.createButtons() self.setWindowTitle('Mantenimiento Libros') self.setWindowIcon(QtGui.QIcon('images/user-plus.png')) self.setWindowTitle(\"Mantenimiento Libros\") self.setGeometry(650, 300, 150, 100)",
"self.setLayout(vbox) def open_new_libros_window(self): self.new_libros_view = NewLibrosWindow() self.new_libros_view.show() print(inspect.stack()[0][3]) self.close() def",
"self.new_reserva_view.show() print(inspect.stack()[0][3]) self.close() def open_delete_reserva_window(self): # self.new_reserva_view = NewReserva() #",
"ui_mant_libros_edit import EditLibrosWindow from ui_mant_libros_id_edit import GetIdEditWindow # Debug only",
"self.new_reserva_view = NewReserva() # self.new_reserva_view.show() print(inspect.stack()[0][3]) self.close() def open_delete_reserva_window(self): #",
"self.close() def open_edit_libros_window(self): self.edit_libros_view = GetIdEditWindow() self.edit_libros_view.show() print(inspect.stack()[0][3]) self.close() def",
"import GetIdEditWindow # Debug only import inspect class MenuLibros(QtGui.QWidget): \"\"\"",
"print(inspect.stack()[0][3]) self.close() def open_list_reserva_window(self): # self.new_reserva_view = NewReserva() # self.new_reserva_view.show()",
"= NewLibrosWindow() self.new_libros_view.show() print(inspect.stack()[0][3]) self.close() def open_edit_libros_window(self): self.edit_libros_view = GetIdEditWindow()",
"self.setWindowIcon(QtGui.QIcon('images/user-plus.png')) self.setWindowTitle(\"Mantenimiento Libros\") self.setGeometry(650, 300, 150, 100) def createButtons(self): btn_new_libros",
"EditLibrosWindow from ui_mant_libros_id_edit import GetIdEditWindow # Debug only import inspect",
"class MenuLibros(QtGui.QWidget): \"\"\" Ventana-menu para editar Libros \"\"\" def __init__(self):",
"Debug only import inspect class MenuLibros(QtGui.QWidget): \"\"\" Ventana-menu para editar",
"hbox.addWidget(btn_delete_libros) vbox = QtGui.QVBoxLayout() vbox.addLayout(hbox) self.setLayout(vbox) def open_new_libros_window(self): self.new_libros_view =",
"GetIdEditWindow # Debug only import inspect class MenuLibros(QtGui.QWidget): \"\"\" Ventana-menu",
"from ui_mant_libros_edit import EditLibrosWindow from ui_mant_libros_id_edit import GetIdEditWindow # Debug",
"import sys app = QtGui.QApplication(sys.argv) mainWin = MenuLibros() mainWin.show() sys.exit(app.exec_())",
"vbox = QtGui.QVBoxLayout() vbox.addLayout(hbox) self.setLayout(vbox) def open_new_libros_window(self): self.new_libros_view = NewLibrosWindow()",
"btn_new_libros.clicked.connect(self.open_new_libros_window) btn_edit_libros = QtGui.QPushButton('Editar') btn_edit_libros.clicked.connect(self.open_edit_libros_window) btn_list_libros = QtGui.QPushButton('Listar') btn_list_libros.clicked.connect(self.close) btn_delete_libros",
"self.setWindowTitle(\"Mantenimiento Libros\") self.setGeometry(650, 300, 150, 100) def createButtons(self): btn_new_libros =",
"vbox.addLayout(hbox) self.setLayout(vbox) def open_new_libros_window(self): self.new_libros_view = NewLibrosWindow() self.new_libros_view.show() print(inspect.stack()[0][3]) self.close()",
"open_list_reserva_window(self): # self.new_reserva_view = NewReserva() # self.new_reserva_view.show() print(inspect.stack()[0][3]) self.close() def",
"btn_delete_libros.clicked.connect(self.close) hbox = QtGui.QHBoxLayout() hbox.addWidget(btn_new_libros) hbox.addWidget(btn_edit_libros) hbox.addWidget(btn_list_libros) hbox.addWidget(btn_delete_libros) vbox =",
"btn_new_libros = QtGui.QPushButton('Nuevo') btn_new_libros.clicked.connect(self.open_new_libros_window) btn_edit_libros = QtGui.QPushButton('Editar') btn_edit_libros.clicked.connect(self.open_edit_libros_window) btn_list_libros =",
"NewLibrosWindow from ui_mant_libros_edit import EditLibrosWindow from ui_mant_libros_id_edit import GetIdEditWindow #",
"Libros') self.setWindowIcon(QtGui.QIcon('images/user-plus.png')) self.setWindowTitle(\"Mantenimiento Libros\") self.setGeometry(650, 300, 150, 100) def createButtons(self):",
"def open_delete_reserva_window(self): # self.new_reserva_view = NewReserva() # self.new_reserva_view.show() print(inspect.stack()[0][3]) self.close()",
"\"\"\" def __init__(self): super(MenuLibros, self).__init__() self.createButtons() self.setWindowTitle('Mantenimiento Libros') self.setWindowIcon(QtGui.QIcon('images/user-plus.png')) self.setWindowTitle(\"Mantenimiento",
"MenuLibros(QtGui.QWidget): \"\"\" Ventana-menu para editar Libros \"\"\" def __init__(self): super(MenuLibros,",
"__name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) mainWin =",
"from ui_mant_libros_new import NewLibrosWindow from ui_mant_libros_edit import EditLibrosWindow from ui_mant_libros_id_edit",
"super(MenuLibros, self).__init__() self.createButtons() self.setWindowTitle('Mantenimiento Libros') self.setWindowIcon(QtGui.QIcon('images/user-plus.png')) self.setWindowTitle(\"Mantenimiento Libros\") self.setGeometry(650, 300,",
"btn_list_libros.clicked.connect(self.close) btn_delete_libros = QtGui.QPushButton('Eliminar') btn_delete_libros.clicked.connect(self.close) hbox = QtGui.QHBoxLayout() hbox.addWidget(btn_new_libros) hbox.addWidget(btn_edit_libros)",
"QtGui.QPushButton('Listar') btn_list_libros.clicked.connect(self.close) btn_delete_libros = QtGui.QPushButton('Eliminar') btn_delete_libros.clicked.connect(self.close) hbox = QtGui.QHBoxLayout() hbox.addWidget(btn_new_libros)",
"# self.new_reserva_view = NewReserva() # self.new_reserva_view.show() print(inspect.stack()[0][3]) self.close() if __name__",
"NewReserva() # self.new_reserva_view.show() print(inspect.stack()[0][3]) self.close() def open_delete_reserva_window(self): # self.new_reserva_view =",
"= NewReserva() # self.new_reserva_view.show() print(inspect.stack()[0][3]) self.close() if __name__ == '__main__':",
"def open_edit_libros_window(self): self.edit_libros_view = GetIdEditWindow() self.edit_libros_view.show() print(inspect.stack()[0][3]) self.close() def open_list_reserva_window(self):",
"# self.new_reserva_view.show() print(inspect.stack()[0][3]) self.close() def open_delete_reserva_window(self): # self.new_reserva_view = NewReserva()",
"self.new_reserva_view.show() print(inspect.stack()[0][3]) self.close() if __name__ == '__main__': import sys app",
"print(inspect.stack()[0][3]) self.close() def open_delete_reserva_window(self): # self.new_reserva_view = NewReserva() # self.new_reserva_view.show()",
"Libros\") self.setGeometry(650, 300, 150, 100) def createButtons(self): btn_new_libros = QtGui.QPushButton('Nuevo')",
"import EditLibrosWindow from ui_mant_libros_id_edit import GetIdEditWindow # Debug only import",
"\"\"\" Ventana-menu para editar Libros \"\"\" def __init__(self): super(MenuLibros, self).__init__()",
"open_delete_reserva_window(self): # self.new_reserva_view = NewReserva() # self.new_reserva_view.show() print(inspect.stack()[0][3]) self.close() if",
"open_edit_libros_window(self): self.edit_libros_view = GetIdEditWindow() self.edit_libros_view.show() print(inspect.stack()[0][3]) self.close() def open_list_reserva_window(self): #",
"= QtGui.QPushButton('Eliminar') btn_delete_libros.clicked.connect(self.close) hbox = QtGui.QHBoxLayout() hbox.addWidget(btn_new_libros) hbox.addWidget(btn_edit_libros) hbox.addWidget(btn_list_libros) hbox.addWidget(btn_delete_libros)",
"ui_mant_libros_new import NewLibrosWindow from ui_mant_libros_edit import EditLibrosWindow from ui_mant_libros_id_edit import",
"inspect class MenuLibros(QtGui.QWidget): \"\"\" Ventana-menu para editar Libros \"\"\" def",
"= QtGui.QVBoxLayout() vbox.addLayout(hbox) self.setLayout(vbox) def open_new_libros_window(self): self.new_libros_view = NewLibrosWindow() self.new_libros_view.show()",
"= GetIdEditWindow() self.edit_libros_view.show() print(inspect.stack()[0][3]) self.close() def open_list_reserva_window(self): # self.new_reserva_view =",
"self).__init__() self.createButtons() self.setWindowTitle('Mantenimiento Libros') self.setWindowIcon(QtGui.QIcon('images/user-plus.png')) self.setWindowTitle(\"Mantenimiento Libros\") self.setGeometry(650, 300, 150,",
"ui_mant_libros_id_edit import GetIdEditWindow # Debug only import inspect class MenuLibros(QtGui.QWidget):",
"def createButtons(self): btn_new_libros = QtGui.QPushButton('Nuevo') btn_new_libros.clicked.connect(self.open_new_libros_window) btn_edit_libros = QtGui.QPushButton('Editar') btn_edit_libros.clicked.connect(self.open_edit_libros_window)",
"= QtGui.QPushButton('Editar') btn_edit_libros.clicked.connect(self.open_edit_libros_window) btn_list_libros = QtGui.QPushButton('Listar') btn_list_libros.clicked.connect(self.close) btn_delete_libros = QtGui.QPushButton('Eliminar')",
"createButtons(self): btn_new_libros = QtGui.QPushButton('Nuevo') btn_new_libros.clicked.connect(self.open_new_libros_window) btn_edit_libros = QtGui.QPushButton('Editar') btn_edit_libros.clicked.connect(self.open_edit_libros_window) btn_list_libros",
"self.close() if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv)",
"btn_edit_libros = QtGui.QPushButton('Editar') btn_edit_libros.clicked.connect(self.open_edit_libros_window) btn_list_libros = QtGui.QPushButton('Listar') btn_list_libros.clicked.connect(self.close) btn_delete_libros =",
"only import inspect class MenuLibros(QtGui.QWidget): \"\"\" Ventana-menu para editar Libros",
"from ui_mant_libros_id_edit import GetIdEditWindow # Debug only import inspect class",
"__init__(self): super(MenuLibros, self).__init__() self.createButtons() self.setWindowTitle('Mantenimiento Libros') self.setWindowIcon(QtGui.QIcon('images/user-plus.png')) self.setWindowTitle(\"Mantenimiento Libros\") self.setGeometry(650,",
"= QtGui.QPushButton('Nuevo') btn_new_libros.clicked.connect(self.open_new_libros_window) btn_edit_libros = QtGui.QPushButton('Editar') btn_edit_libros.clicked.connect(self.open_edit_libros_window) btn_list_libros = QtGui.QPushButton('Listar')",
"self.edit_libros_view = GetIdEditWindow() self.edit_libros_view.show() print(inspect.stack()[0][3]) self.close() def open_list_reserva_window(self): # self.new_reserva_view",
"hbox.addWidget(btn_edit_libros) hbox.addWidget(btn_list_libros) hbox.addWidget(btn_delete_libros) vbox = QtGui.QVBoxLayout() vbox.addLayout(hbox) self.setLayout(vbox) def open_new_libros_window(self):",
"btn_list_libros = QtGui.QPushButton('Listar') btn_list_libros.clicked.connect(self.close) btn_delete_libros = QtGui.QPushButton('Eliminar') btn_delete_libros.clicked.connect(self.close) hbox =",
"btn_edit_libros.clicked.connect(self.open_edit_libros_window) btn_list_libros = QtGui.QPushButton('Listar') btn_list_libros.clicked.connect(self.close) btn_delete_libros = QtGui.QPushButton('Eliminar') btn_delete_libros.clicked.connect(self.close) hbox",
"print(inspect.stack()[0][3]) self.close() def open_edit_libros_window(self): self.edit_libros_view = GetIdEditWindow() self.edit_libros_view.show() print(inspect.stack()[0][3]) self.close()",
"def open_list_reserva_window(self): # self.new_reserva_view = NewReserva() # self.new_reserva_view.show() print(inspect.stack()[0][3]) self.close()",
"QtGui from ui_mant_libros_new import NewLibrosWindow from ui_mant_libros_edit import EditLibrosWindow from",
"self.new_libros_view.show() print(inspect.stack()[0][3]) self.close() def open_edit_libros_window(self): self.edit_libros_view = GetIdEditWindow() self.edit_libros_view.show() print(inspect.stack()[0][3])",
"import inspect class MenuLibros(QtGui.QWidget): \"\"\" Ventana-menu para editar Libros \"\"\"",
"hbox = QtGui.QHBoxLayout() hbox.addWidget(btn_new_libros) hbox.addWidget(btn_edit_libros) hbox.addWidget(btn_list_libros) hbox.addWidget(btn_delete_libros) vbox = QtGui.QVBoxLayout()",
"editar Libros \"\"\" def __init__(self): super(MenuLibros, self).__init__() self.createButtons() self.setWindowTitle('Mantenimiento Libros')",
"self.new_libros_view = NewLibrosWindow() self.new_libros_view.show() print(inspect.stack()[0][3]) self.close() def open_edit_libros_window(self): self.edit_libros_view =",
"hbox.addWidget(btn_list_libros) hbox.addWidget(btn_delete_libros) vbox = QtGui.QVBoxLayout() vbox.addLayout(hbox) self.setLayout(vbox) def open_new_libros_window(self): self.new_libros_view",
"= QtGui.QHBoxLayout() hbox.addWidget(btn_new_libros) hbox.addWidget(btn_edit_libros) hbox.addWidget(btn_list_libros) hbox.addWidget(btn_delete_libros) vbox = QtGui.QVBoxLayout() vbox.addLayout(hbox)",
"NewReserva() # self.new_reserva_view.show() print(inspect.stack()[0][3]) self.close() if __name__ == '__main__': import",
"def __init__(self): super(MenuLibros, self).__init__() self.createButtons() self.setWindowTitle('Mantenimiento Libros') self.setWindowIcon(QtGui.QIcon('images/user-plus.png')) self.setWindowTitle(\"Mantenimiento Libros\")",
"self.setWindowTitle('Mantenimiento Libros') self.setWindowIcon(QtGui.QIcon('images/user-plus.png')) self.setWindowTitle(\"Mantenimiento Libros\") self.setGeometry(650, 300, 150, 100) def",
"if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) mainWin",
"NewLibrosWindow() self.new_libros_view.show() print(inspect.stack()[0][3]) self.close() def open_edit_libros_window(self): self.edit_libros_view = GetIdEditWindow() self.edit_libros_view.show()",
"open_new_libros_window(self): self.new_libros_view = NewLibrosWindow() self.new_libros_view.show() print(inspect.stack()[0][3]) self.close() def open_edit_libros_window(self): self.edit_libros_view",
"print(inspect.stack()[0][3]) self.close() if __name__ == '__main__': import sys app =",
"== '__main__': import sys app = QtGui.QApplication(sys.argv) mainWin = MenuLibros()"
] |
[
"# Define possible command line arguments parser = argparse.ArgumentParser( description=\"Find",
"cards you want to find the odds for.\") parser.add_argument(\"-b\", \"--board\",",
"card_re = re.compile('[AKQJT98765432][scdh]') for card in all_cards: if card !=",
"the input file and returns the hole cards and board",
"hole_cards, args.n, args.exact, board, args.input # Parses a line taken",
"in the following format: As, Jc, Td, 3h.\") parser.add_argument(\"cards\", nargs=\"*\",",
"raw_hole_cards: if hole_card != \"?\": current_card = holdem_functions.Card(hole_card) current_hole_cards.append(current_card) else:",
"board: print(\"Board cannot have unknown cards\") exit() return create_cards(board) #",
"Mocks actual argparse object class LibArgs: def __init__(self, board, exact,",
"must have a length of 3, 4, or 5.\") exit()",
"not None): print(\"Unknown hole cards must come in pairs\") exit()",
"hole_cards, board # Error check the command line arguments def",
"an input file. \" \"Commandline arguments for hole cards and",
"and board def parse_file_args(line): if line is None or len(line)",
"cannot have unknown cards\") exit() return create_cards(board) # Instantiates new",
"print(\"Error opening file \" + file_name) exit() # Check to",
"create_cards(board) # Instantiates new cards from the arguments and returns",
"provide a non-zero even number of hole cards\") exit() #",
"not card_re.match(card): print(\"Invalid card given.\") exit() else: if all_cards.count(card) !=",
"exit() hole_cards.append((current_hole_cards[0], current_hole_cards[1])) current_hole_cards = [] if hole_cards.count((None, None)) >",
"arguments def error_check_arguments(args): # Check that the number of Monte",
"args.input try: input_file = open(file_name, 'r') input_file.close() except IOError: print(\"Error",
"all_cards = list(args.cards) if args.board: all_cards.extend(args.board) error_check_cards(all_cards) # Error check",
"is None or len(line) == 0: print(line) print(\"Invalid format\") exit()",
"input file and returns the hole cards and board def",
"board hole_cards, board = None, None if not args.input: hole_cards,",
"list of board cards: e.g. [As Ks Ad Kd] def",
"\"Commandline arguments for hole cards and board will \" \"be",
"all_cards.extend(args.board) error_check_cards(all_cards) # Error check the command line arguments def",
"hole_cards.count((None, None)) > 1: print(\"Can only have one set of",
"3: print(\"Board must have a length of 3, 4, or",
"returns them in a tuple def create_cards(card_strings): return [holdem_functions.Card(arg) for",
"line arguments and check for errors args = parser.parse_args() error_check_arguments(args)",
"in board: print(\"Board cannot have unknown cards\") exit() return create_cards(board)",
"cards and boards from an input file. \" \"Commandline arguments",
"tuple of two-tuple hole_cards: e.g. ((As, Ks), (Ad, Kd), (Jh,",
"which holds the arguments for library calls # Mocks actual",
"exit() # Returns tuple of two-tuple hole_cards: e.g. ((As, Ks),",
"hole_card != \"?\": current_card = holdem_functions.Card(hole_card) current_hole_cards.append(current_card) else: current_hole_cards.append(None) if",
"the following format: As, Jc, Td, 3h.\") parser.add_argument(\"cards\", nargs=\"*\", type=str,",
"is None or len(raw_hole_cards) < 2 or len(raw_hole_cards) % 2):",
"Check to make sure all cards are of a valid",
"line taken from the input file and returns the hole",
"((As, Ks), (Ad, Kd), (Jh, Th)) def create_hole_cards(raw_hole_cards): # Checking",
"if len(current_hole_cards) == 2: if None in current_hole_cards: if (current_hole_cards[0]",
"for card in all_cards: if card != \"?\" and not",
"current_hole_cards.append(None) if len(current_hole_cards) == 2: if None in current_hole_cards: if",
"or len(board) < 3: print(\"Board must have a length of",
"= [] if hole_cards.count((None, None)) > 1: print(\"Can only have",
"hole cards + board are formatted properly and unique def",
"hole_cards): self.board = board self.cards = hole_cards self.n = num",
"or len(line) == 0: print(line) print(\"Invalid format\") exit() values =",
"Carlo simulations\") parser.add_argument(\"-i\", \"--input\", type=str, help=\"Read hole cards and boards",
"Returns list of board cards: e.g. [As Ks Ad Kd]",
"or current_hole_cards[1] is not None): print(\"Unknown hole cards must come",
"hole cards hole_cards, current_hole_cards = [], [] for hole_card in",
"that the number of Monte Carlo simulations is a positive",
"board = None if len(values) == 2: board = values[1].split()",
"enumerating every possible \" \"board\") parser.add_argument(\"-n\", type=int, default=100000, help=\"Run N",
"= board self.cards = hole_cards self.n = num self.input =",
"import re import holdem_calc.holdem_functions as holdem_functions # Wrapper class which",
"= None, None if not args.input: hole_cards, board = parse_cards(args.cards,",
"re.compile('[AKQJT98765432][scdh]') for card in all_cards: if card != \"?\" and",
"is a positive number if args.n <= 0: print(\"Number of",
"exit() # Check that we can open the specified input",
"import argparse import re import holdem_calc.holdem_functions as holdem_functions # Wrapper",
"arguments for library calls # Mocks actual argparse object class",
"parse_board(board): if len(board) > 5 or len(board) < 3: print(\"Board",
"def error_check_arguments(args): # Check that the number of Monte Carlo",
"number of Monte Carlo simulations is a positive number if",
"Kd] def parse_board(board): if len(board) > 5 or len(board) <",
"set of unknown hole cards\") return tuple(hole_cards) # Returns list",
"cards\") return tuple(hole_cards) # Returns list of board cards: e.g.",
"of board cards: e.g. [As Ks Ad Kd] def parse_board(board):",
"parse_cards(args.cards, args.board) return hole_cards, args.n, args.exact, board, args.input # Parses",
"self.n = num self.input = input_file self.exact = exact #",
"of hole cards hole_cards, current_hole_cards = [], [] for hole_card",
"given in the following format: As, Jc, Td, 3h.\") parser.add_argument(\"cards\",",
"calls # Mocks actual argparse object class LibArgs: def __init__(self,",
"current_hole_cards[1])) current_hole_cards = [] if hole_cards.count((None, None)) > 1: print(\"Can",
"board def parse_file_args(line): if line is None or len(line) ==",
"IOError: print(\"Error opening file \" + file_name) exit() # Check",
"hole_cards, current_hole_cards = [], [] for hole_card in raw_hole_cards: if",
"by enumerating every possible \" \"board\") parser.add_argument(\"-n\", type=int, default=100000, help=\"Run",
"(Jh, Th)) def create_hole_cards(raw_hole_cards): # Checking that there are an",
"[] for hole_card in raw_hole_cards: if hole_card != \"?\": current_card",
"odds by enumerating every possible \" \"board\") parser.add_argument(\"-n\", type=int, default=100000,",
"simulations is a positive number if args.n <= 0: print(\"Number",
"cards and board will \" \"be ignored\") # Parse command",
"= args.input try: input_file = open(file_name, 'r') input_file.close() except IOError:",
"card_re.match(card): print(\"Invalid card given.\") exit() else: if all_cards.count(card) != 1",
"# Mocks actual argparse object class LibArgs: def __init__(self, board,",
"open the specified input file if args.input: file_name = args.input",
"# Returns tuple of two-tuple hole_cards: e.g. ((As, Ks), (Ad,",
"num self.input = input_file self.exact = exact # Parses arguments",
"def parse_cards(cards, board): hole_cards = create_hole_cards(cards) if board: board =",
"Parses arguments passed to holdem_calc as a library call def",
"find the odds for.\") parser.add_argument(\"-b\", \"--board\", nargs=\"*\", type=str, metavar=\"card\", help=\"Add",
"parse_cards(cards, board): hole_cards = create_hole_cards(cards) if board: board = parse_board(board)",
"input_file self.exact = exact # Parses arguments passed to holdem_calc",
"return hole_cards, args.n, args.exact, board, args.input # Parses a line",
"if card != \"?\" and not card_re.match(card): print(\"Invalid card given.\")",
"can open the specified input file if args.input: file_name =",
"values[1].split() all_cards.extend(board) error_check_cards(all_cards) return parse_cards(hole_cards, board) # Parses hole cards",
"if args.n <= 0: print(\"Number of Monte Carlo simulations must",
"\"?\": print(\"The cards given must be unique.\") exit() # Returns",
"if len(values) > 2 or len(values) < 1: print(line) print(\"Invalid",
"type=str, metavar=\"card\", help=\"Add board cards\") parser.add_argument(\"-e\", \"--exact\", action=\"store_true\", help=\"Find exact",
"> 5 or len(board) < 3: print(\"Board must have a",
"Th)) def create_hole_cards(raw_hole_cards): # Checking that there are an even",
"format all_cards = list(args.cards) if args.board: all_cards.extend(args.board) error_check_cards(all_cards) # Checking",
"try: input_file = open(file_name, 'r') input_file.close() except IOError: print(\"Error opening",
"Check that the number of Monte Carlo simulations is a",
"exit() else: if all_cards.count(card) != 1 and card != \"?\":",
"input file. \" \"Commandline arguments for hole cards and board",
"as holdem_functions # Wrapper class which holds the arguments for",
"type=str, metavar=\"hole card\", help=\"Hole cards you want to find the",
"ignored\") # Parse command line arguments and check for errors",
"exact # Parses arguments passed to holdem_calc as a library",
"\"--board\", nargs=\"*\", type=str, metavar=\"card\", help=\"Add board cards\") parser.add_argument(\"-e\", \"--exact\", action=\"store_true\",",
"def error_check_cards(all_cards): card_re = re.compile('[AKQJT98765432][scdh]') for card in all_cards: if",
"simulations must be positive.\") exit() # Check that we can",
"= [], [] for hole_card in raw_hole_cards: if hole_card !=",
"metavar=\"card\", help=\"Add board cards\") parser.add_argument(\"-e\", \"--exact\", action=\"store_true\", help=\"Find exact odds",
"board are formatted properly and unique def error_check_cards(all_cards): card_re =",
"board, args.input # Parses command line arguments to holdem_calc def",
"None or current_hole_cards[1] is not None): print(\"Unknown hole cards must",
"None or len(raw_hole_cards) < 2 or len(raw_hole_cards) % 2): print(\"You",
"board = parse_cards(args.cards, args.board) return hole_cards, args.n, args.exact, board, args.input",
"the hole cards + board are formatted properly and unique",
"def parse_board(board): if len(board) > 5 or len(board) < 3:",
"for.\") parser.add_argument(\"-b\", \"--board\", nargs=\"*\", type=str, metavar=\"card\", help=\"Add board cards\") parser.add_argument(\"-e\",",
"an even number of hole cards if (raw_hole_cards is None",
"board): hole_cards = create_hole_cards(cards) if board: board = parse_board(board) return",
"are formatted properly and unique def error_check_cards(all_cards): card_re = re.compile('[AKQJT98765432][scdh]')",
"help=\"Run N Monte Carlo simulations\") parser.add_argument(\"-i\", \"--input\", type=str, help=\"Read hole",
"format: As, Jc, Td, 3h.\") parser.add_argument(\"cards\", nargs=\"*\", type=str, metavar=\"hole card\",",
"def parse_args(): # Define possible command line arguments parser =",
"nargs=\"*\", type=str, metavar=\"hole card\", help=\"Hole cards you want to find",
"arguments and returns them in a tuple def create_cards(card_strings): return",
"len(board) < 3: print(\"Board must have a length of 3,",
"(Ad, Kd), (Jh, Th)) def create_hole_cards(raw_hole_cards): # Checking that there",
"< 2 or len(raw_hole_cards) % 2): print(\"You must provide a",
"\" + file_name) exit() # Check to make sure all",
"if len(board) > 5 or len(board) < 3: print(\"Board must",
"Monte Carlo simulations is a positive number if args.n <=",
"of Monte Carlo simulations must be positive.\") exit() # Check",
"if \"?\" in board: print(\"Board cannot have unknown cards\") exit()",
"error_check_arguments(args): # Check that the number of Monte Carlo simulations",
"print(line) print(\"Invalid format\") exit() values = line.split(\"|\") if len(values) >",
"= list(args.cards) if args.board: all_cards.extend(args.board) error_check_cards(all_cards) # Checking that the",
"hole_cards = create_hole_cards(cards) if board: board = parse_board(board) return hole_cards,",
"argparse.ArgumentParser( description=\"Find the odds that a Texas Hold'em hand will",
"args.board: all_cards.extend(args.board) error_check_cards(all_cards) # Checking that the hole cards +",
"two-tuple hole_cards: e.g. ((As, Ks), (Ad, Kd), (Jh, Th)) def",
"hole cards\") exit() # Create two-tuples out of hole cards",
"library call def parse_lib_args(args): error_check_arguments(args) # Parse hole cards and",
"cards from the arguments and returns them in a tuple",
"is not None or current_hole_cards[1] is not None): print(\"Unknown hole",
"of two-tuple hole_cards: e.g. ((As, Ks), (Ad, Kd), (Jh, Th))",
"command line arguments and check for errors args = parser.parse_args()",
"card in all_cards: if card != \"?\" and not card_re.match(card):",
"cards\") exit() # Create two-tuples out of hole cards hole_cards,",
"\"board\") parser.add_argument(\"-n\", type=int, default=100000, help=\"Run N Monte Carlo simulations\") parser.add_argument(\"-i\",",
"help=\"Find exact odds by enumerating every possible \" \"board\") parser.add_argument(\"-n\",",
"> 2 or len(values) < 1: print(line) print(\"Invalid format\") exit()",
"2 or len(values) < 1: print(line) print(\"Invalid format\") exit() hole_cards",
"create_hole_cards(raw_hole_cards): # Checking that there are an even number of",
"have a length of 3, 4, or 5.\") exit() if",
"Parses hole cards and board def parse_cards(cards, board): hole_cards =",
"!= \"?\" and not card_re.match(card): print(\"Invalid card given.\") exit() else:",
"Returns tuple of two-tuple hole_cards: e.g. ((As, Ks), (Ad, Kd),",
"length of 3, 4, or 5.\") exit() if \"?\" in",
"input_file, hole_cards): self.board = board self.cards = hole_cards self.n =",
"will \" \"be ignored\") # Parse command line arguments and",
"following format: As, Jc, Td, 3h.\") parser.add_argument(\"cards\", nargs=\"*\", type=str, metavar=\"hole",
"action=\"store_true\", help=\"Find exact odds by enumerating every possible \" \"board\")",
"cards\") parser.add_argument(\"-e\", \"--exact\", action=\"store_true\", help=\"Find exact odds by enumerating every",
"hole cards\") return tuple(hole_cards) # Returns list of board cards:",
"positive number if args.n <= 0: print(\"Number of Monte Carlo",
"None if not args.input: hole_cards, board = parse_cards(args.cards, args.board) return",
"2: board = values[1].split() all_cards.extend(board) error_check_cards(all_cards) return parse_cards(hole_cards, board) #",
"two-tuples out of hole cards hole_cards, current_hole_cards = [], []",
"args.board) return hole_cards, args.n, args.exact, board, args.input # Parses command",
"board will \" \"be ignored\") # Parse command line arguments",
"# Wrapper class which holds the arguments for library calls",
"cards hole_cards, current_hole_cards = [], [] for hole_card in raw_hole_cards:",
"Monte Carlo simulations must be positive.\") exit() # Check that",
"board self.cards = hole_cards self.n = num self.input = input_file",
"import holdem_calc.holdem_functions as holdem_functions # Wrapper class which holds the",
"if len(values) == 2: board = values[1].split() all_cards.extend(board) error_check_cards(all_cards) return",
"the arguments and returns them in a tuple def create_cards(card_strings):",
"# Parse command line arguments and check for errors args",
"boards from an input file. \" \"Commandline arguments for hole",
"be unique.\") exit() # Returns tuple of two-tuple hole_cards: e.g.",
"board cards: e.g. [As Ks Ad Kd] def parse_board(board): if",
"None or len(line) == 0: print(line) print(\"Invalid format\") exit() values",
"that the hole cards + board are formatted properly and",
"> 1: print(\"Can only have one set of unknown hole",
"have unknown cards\") exit() return create_cards(board) # Instantiates new cards",
"Td, 3h.\") parser.add_argument(\"cards\", nargs=\"*\", type=str, metavar=\"hole card\", help=\"Hole cards you",
"help=\"Hole cards you want to find the odds for.\") parser.add_argument(\"-b\",",
"odds that a Texas Hold'em hand will win. Note \"",
"Define possible command line arguments parser = argparse.ArgumentParser( description=\"Find the",
"line arguments to holdem_calc def parse_args(): # Define possible command",
"are an even number of hole cards if (raw_hole_cards is",
"to make sure all cards are of a valid format",
"\"--input\", type=str, help=\"Read hole cards and boards from an input",
"print(\"You must provide a non-zero even number of hole cards\")",
"card given.\") exit() else: if all_cards.count(card) != 1 and card",
"in raw_hole_cards: if hole_card != \"?\": current_card = holdem_functions.Card(hole_card) current_hole_cards.append(current_card)",
"and boards from an input file. \" \"Commandline arguments for",
"len(line) == 0: print(line) print(\"Invalid format\") exit() values = line.split(\"|\")",
"2 or len(raw_hole_cards) % 2): print(\"You must provide a non-zero",
"non-zero even number of hole cards\") exit() # Create two-tuples",
"parser.add_argument(\"-i\", \"--input\", type=str, help=\"Read hole cards and boards from an",
"args.input # Parses command line arguments to holdem_calc def parse_args():",
"library calls # Mocks actual argparse object class LibArgs: def",
"# Checking that the hole cards + board are formatted",
"odds for.\") parser.add_argument(\"-b\", \"--board\", nargs=\"*\", type=str, metavar=\"card\", help=\"Add board cards\")",
"args.input: file_name = args.input try: input_file = open(file_name, 'r') input_file.close()",
"if all_cards.count(card) != 1 and card != \"?\": print(\"The cards",
"exit() if \"?\" in board: print(\"Board cannot have unknown cards\")",
"if line is None or len(line) == 0: print(line) print(\"Invalid",
"hole_cards, board = None, None if not args.input: hole_cards, board",
"of unknown hole cards\") return tuple(hole_cards) # Returns list of",
"holdem_calc.holdem_functions as holdem_functions # Wrapper class which holds the arguments",
"!= \"?\": print(\"The cards given must be unique.\") exit() #",
"None): print(\"Unknown hole cards must come in pairs\") exit() hole_cards.append((current_hole_cards[0],",
"given.\") exit() else: if all_cards.count(card) != 1 and card !=",
"holds the arguments for library calls # Mocks actual argparse",
"the hole cards and board def parse_file_args(line): if line is",
"cards\") exit() return create_cards(board) # Instantiates new cards from the",
"as a library call def parse_lib_args(args): error_check_arguments(args) # Parse hole",
"Note \" \"that cards must be given in the following",
"= parse_board(board) return hole_cards, board # Error check the command",
"class which holds the arguments for library calls # Mocks",
"formatted properly and unique def error_check_cards(all_cards): card_re = re.compile('[AKQJT98765432][scdh]') for",
"None)) > 1: print(\"Can only have one set of unknown",
"args.exact, board, args.input # Parses a line taken from the",
"to holdem_calc def parse_args(): # Define possible command line arguments",
"description=\"Find the odds that a Texas Hold'em hand will win.",
"== 2: if None in current_hole_cards: if (current_hole_cards[0] is not",
"or len(raw_hole_cards) % 2): print(\"You must provide a non-zero even",
"= list(hole_cards) board = None if len(values) == 2: board",
"= re.compile('[AKQJT98765432][scdh]') for card in all_cards: if card != \"?\"",
"# Parses arguments passed to holdem_calc as a library call",
"parse_lib_args(args): error_check_arguments(args) # Parse hole cards and board hole_cards, board",
"Ad Kd] def parse_board(board): if len(board) > 5 or len(board)",
"holdem_calc as a library call def parse_lib_args(args): error_check_arguments(args) # Parse",
"number of hole cards\") exit() # Create two-tuples out of",
"exact, num, input_file, hole_cards): self.board = board self.cards = hole_cards",
"is not None): print(\"Unknown hole cards must come in pairs\")",
"len(raw_hole_cards) % 2): print(\"You must provide a non-zero even number",
"Create two-tuples out of hole cards hole_cards, current_hole_cards = [],",
"every possible \" \"board\") parser.add_argument(\"-n\", type=int, default=100000, help=\"Run N Monte",
"5.\") exit() if \"?\" in board: print(\"Board cannot have unknown",
"= values[0].split() all_cards = list(hole_cards) board = None if len(values)",
"object class LibArgs: def __init__(self, board, exact, num, input_file, hole_cards):",
"current_hole_cards.append(current_card) else: current_hole_cards.append(None) if len(current_hole_cards) == 2: if None in",
"if (current_hole_cards[0] is not None or current_hole_cards[1] is not None):",
"unique def error_check_cards(all_cards): card_re = re.compile('[AKQJT98765432][scdh]') for card in all_cards:",
"\" \"board\") parser.add_argument(\"-n\", type=int, default=100000, help=\"Run N Monte Carlo simulations\")",
"cards and board def parse_file_args(line): if line is None or",
"self.exact = exact # Parses arguments passed to holdem_calc as",
"len(board) > 5 or len(board) < 3: print(\"Board must have",
"a Texas Hold'em hand will win. Note \" \"that cards",
"input_file.close() except IOError: print(\"Error opening file \" + file_name) exit()",
"args.n, args.exact, board, args.input # Parses command line arguments to",
"# Checking that there are an even number of hole",
"actual argparse object class LibArgs: def __init__(self, board, exact, num,",
"passed to holdem_calc as a library call def parse_lib_args(args): error_check_arguments(args)",
"cards must be given in the following format: As, Jc,",
"# Check that the number of Monte Carlo simulations is",
"if board: board = parse_board(board) return hole_cards, board # Error",
"else: if all_cards.count(card) != 1 and card != \"?\": print(\"The",
"cards given must be unique.\") exit() # Returns tuple of",
"that a Texas Hold'em hand will win. Note \" \"that",
"if (raw_hole_cards is None or len(raw_hole_cards) < 2 or len(raw_hole_cards)",
"line.split(\"|\") if len(values) > 2 or len(values) < 1: print(line)",
"# Create two-tuples out of hole cards hole_cards, current_hole_cards =",
"the odds that a Texas Hold'em hand will win. Note",
"are of a valid format all_cards = list(args.cards) if args.board:",
"file if args.input: file_name = args.input try: input_file = open(file_name,",
"and returns them in a tuple def create_cards(card_strings): return [holdem_functions.Card(arg)",
"hole_cards: e.g. ((As, Ks), (Ad, Kd), (Jh, Th)) def create_hole_cards(raw_hole_cards):",
"def create_hole_cards(raw_hole_cards): # Checking that there are an even number",
"of hole cards\") exit() # Create two-tuples out of hole",
"file and returns the hole cards and board def parse_file_args(line):",
"unknown cards\") exit() return create_cards(board) # Instantiates new cards from",
"the arguments for library calls # Mocks actual argparse object",
"cards: e.g. [As Ks Ad Kd] def parse_board(board): if len(board)",
"Jc, Td, 3h.\") parser.add_argument(\"cards\", nargs=\"*\", type=str, metavar=\"hole card\", help=\"Hole cards",
"pairs\") exit() hole_cards.append((current_hole_cards[0], current_hole_cards[1])) current_hole_cards = [] if hole_cards.count((None, None))",
"file \" + file_name) exit() # Check to make sure",
"a library call def parse_lib_args(args): error_check_arguments(args) # Parse hole cards",
"1: print(\"Can only have one set of unknown hole cards\")",
"hole_cards = values[0].split() all_cards = list(hole_cards) board = None if",
"\"?\" and not card_re.match(card): print(\"Invalid card given.\") exit() else: if",
"Check that we can open the specified input file if",
"possible command line arguments parser = argparse.ArgumentParser( description=\"Find the odds",
"and not card_re.match(card): print(\"Invalid card given.\") exit() else: if all_cards.count(card)",
"hole cards and board will \" \"be ignored\") # Parse",
"[] if hole_cards.count((None, None)) > 1: print(\"Can only have one",
"format\") exit() hole_cards = values[0].split() all_cards = list(hole_cards) board =",
"cards must come in pairs\") exit() hole_cards.append((current_hole_cards[0], current_hole_cards[1])) current_hole_cards =",
"must be given in the following format: As, Jc, Td,",
"LibArgs: def __init__(self, board, exact, num, input_file, hole_cards): self.board =",
"we can open the specified input file if args.input: file_name",
"\" \"that cards must be given in the following format:",
"# Parses hole cards and board def parse_cards(cards, board): hole_cards",
"the specified input file if args.input: file_name = args.input try:",
"format\") exit() values = line.split(\"|\") if len(values) > 2 or",
"# Parses command line arguments to holdem_calc def parse_args(): #",
"and board will \" \"be ignored\") # Parse command line",
"\" \"Commandline arguments for hole cards and board will \"",
"args = parser.parse_args() error_check_arguments(args) # Parse hole cards and board",
"len(values) > 2 or len(values) < 1: print(line) print(\"Invalid format\")",
"must be positive.\") exit() # Check that we can open",
"parser.add_argument(\"cards\", nargs=\"*\", type=str, metavar=\"hole card\", help=\"Hole cards you want to",
"hole cards and board def parse_file_args(line): if line is None",
"def parse_lib_args(args): error_check_arguments(args) # Parse hole cards and board hole_cards,",
"board # Error check the command line arguments def error_check_arguments(args):",
"print(\"Invalid format\") exit() hole_cards = values[0].split() all_cards = list(hole_cards) board",
"e.g. [As Ks Ad Kd] def parse_board(board): if len(board) >",
"in current_hole_cards: if (current_hole_cards[0] is not None or current_hole_cards[1] is",
"out of hole cards hole_cards, current_hole_cards = [], [] for",
"\" \"be ignored\") # Parse command line arguments and check",
"% 2): print(\"You must provide a non-zero even number of",
"hole_card in raw_hole_cards: if hole_card != \"?\": current_card = holdem_functions.Card(hole_card)",
"len(raw_hole_cards) < 2 or len(raw_hole_cards) % 2): print(\"You must provide",
"Wrapper class which holds the arguments for library calls #",
"self.input = input_file self.exact = exact # Parses arguments passed",
"or len(raw_hole_cards) < 2 or len(raw_hole_cards) % 2): print(\"You must",
"print(\"Invalid card given.\") exit() else: if all_cards.count(card) != 1 and",
"!= \"?\": current_card = holdem_functions.Card(hole_card) current_hole_cards.append(current_card) else: current_hole_cards.append(None) if len(current_hole_cards)",
"None in current_hole_cards: if (current_hole_cards[0] is not None or current_hole_cards[1]",
"holdem_functions # Wrapper class which holds the arguments for library",
"that there are an even number of hole cards if",
"arguments passed to holdem_calc as a library call def parse_lib_args(args):",
"As, Jc, Td, 3h.\") parser.add_argument(\"cards\", nargs=\"*\", type=str, metavar=\"hole card\", help=\"Hole",
"from the input file and returns the hole cards and",
"input_file = open(file_name, 'r') input_file.close() except IOError: print(\"Error opening file",
"# Error check the command line arguments def error_check_arguments(args): #",
"args.board: all_cards.extend(args.board) error_check_cards(all_cards) # Error check the command line arguments",
"make sure all cards are of a valid format all_cards",
"print(line) print(\"Invalid format\") exit() hole_cards = values[0].split() all_cards = list(hole_cards)",
"win. Note \" \"that cards must be given in the",
"print(\"Invalid format\") exit() values = line.split(\"|\") if len(values) > 2",
"cards + board are formatted properly and unique def error_check_cards(all_cards):",
"opening file \" + file_name) exit() # Check to make",
"if hole_card != \"?\": current_card = holdem_functions.Card(hole_card) current_hole_cards.append(current_card) else: current_hole_cards.append(None)",
"current_card = holdem_functions.Card(hole_card) current_hole_cards.append(current_card) else: current_hole_cards.append(None) if len(current_hole_cards) == 2:",
"arguments to holdem_calc def parse_args(): # Define possible command line",
"cards if (raw_hole_cards is None or len(raw_hole_cards) < 2 or",
"current_hole_cards = [] if hole_cards.count((None, None)) > 1: print(\"Can only",
"print(\"Board must have a length of 3, 4, or 5.\")",
"\"?\": current_card = holdem_functions.Card(hole_card) current_hole_cards.append(current_card) else: current_hole_cards.append(None) if len(current_hole_cards) ==",
"unknown hole cards\") return tuple(hole_cards) # Returns list of board",
"for errors args = parser.parse_args() error_check_arguments(args) # Parse hole cards",
"parser.parse_args() error_check_arguments(args) # Parse hole cards and board hole_cards, board",
"exit() values = line.split(\"|\") if len(values) > 2 or len(values)",
"# Parses a line taken from the input file and",
"error_check_cards(all_cards) # Checking that the hole cards + board are",
"argparse object class LibArgs: def __init__(self, board, exact, num, input_file,",
"all_cards = list(hole_cards) board = None if len(values) == 2:",
"None if len(values) == 2: board = values[1].split() all_cards.extend(board) error_check_cards(all_cards)",
"# Returns list of board cards: e.g. [As Ks Ad",
"of Monte Carlo simulations is a positive number if args.n",
"None, None if not args.input: hole_cards, board = parse_cards(args.cards, args.board)",
"must be unique.\") exit() # Returns tuple of two-tuple hole_cards:",
"Hold'em hand will win. Note \" \"that cards must be",
"len(values) == 2: board = values[1].split() all_cards.extend(board) error_check_cards(all_cards) return parse_cards(hole_cards,",
"sure all cards are of a valid format all_cards =",
"\"--exact\", action=\"store_true\", help=\"Find exact odds by enumerating every possible \"",
"or len(values) < 1: print(line) print(\"Invalid format\") exit() hole_cards =",
"board, exact, num, input_file, hole_cards): self.board = board self.cards =",
"= input_file self.exact = exact # Parses arguments passed to",
"board = parse_board(board) return hole_cards, board # Error check the",
"of hole cards if (raw_hole_cards is None or len(raw_hole_cards) <",
"argparse import re import holdem_calc.holdem_functions as holdem_functions # Wrapper class",
"args.board) return hole_cards, args.n, args.exact, board, args.input # Parses a",
"all_cards.extend(args.board) error_check_cards(all_cards) # Checking that the hole cards + board",
"all_cards = list(args.cards) if args.board: all_cards.extend(args.board) error_check_cards(all_cards) # Checking that",
"Parses a line taken from the input file and returns",
"board) # Parses hole cards and board def parse_cards(cards, board):",
"Parses command line arguments to holdem_calc def parse_args(): # Define",
"parse_cards(hole_cards, board) # Parses hole cards and board def parse_cards(cards,",
"error_check_cards(all_cards): card_re = re.compile('[AKQJT98765432][scdh]') for card in all_cards: if card",
"Checking that there are an even number of hole cards",
"you want to find the odds for.\") parser.add_argument(\"-b\", \"--board\", nargs=\"*\",",
"a valid format all_cards = list(args.cards) if args.board: all_cards.extend(args.board) error_check_cards(all_cards)",
"exact odds by enumerating every possible \" \"board\") parser.add_argument(\"-n\", type=int,",
"parse_args(): # Define possible command line arguments parser = argparse.ArgumentParser(",
"= parser.parse_args() error_check_arguments(args) # Parse hole cards and board hole_cards,",
"Parse hole cards and board hole_cards, board = None, None",
"only have one set of unknown hole cards\") return tuple(hole_cards)",
"all cards are of a valid format all_cards = list(args.cards)",
"+ board are formatted properly and unique def error_check_cards(all_cards): card_re",
"a tuple def create_cards(card_strings): return [holdem_functions.Card(arg) for arg in card_strings]",
"\"that cards must be given in the following format: As,",
"file_name) exit() # Check to make sure all cards are",
"even number of hole cards if (raw_hole_cards is None or",
"else: current_hole_cards.append(None) if len(current_hole_cards) == 2: if None in current_hole_cards:",
"= values[1].split() all_cards.extend(board) error_check_cards(all_cards) return parse_cards(hole_cards, board) # Parses hole",
"cards and board hole_cards, board = None, None if not",
"must come in pairs\") exit() hole_cards.append((current_hole_cards[0], current_hole_cards[1])) current_hole_cards = []",
"parse_file_args(line): if line is None or len(line) == 0: print(line)",
"num, input_file, hole_cards): self.board = board self.cards = hole_cards self.n",
"board = values[1].split() all_cards.extend(board) error_check_cards(all_cards) return parse_cards(hole_cards, board) # Parses",
"if None in current_hole_cards: if (current_hole_cards[0] is not None or",
"new cards from the arguments and returns them in a",
"3, 4, or 5.\") exit() if \"?\" in board: print(\"Board",
"def __init__(self, board, exact, num, input_file, hole_cards): self.board = board",
"\"be ignored\") # Parse command line arguments and check for",
"a positive number if args.n <= 0: print(\"Number of Monte",
"= create_hole_cards(cards) if board: board = parse_board(board) return hole_cards, board",
"file_name = args.input try: input_file = open(file_name, 'r') input_file.close() except",
"hole cards and board hole_cards, board = None, None if",
"holdem_calc def parse_args(): # Define possible command line arguments parser",
"positive.\") exit() # Check that we can open the specified",
"# Instantiates new cards from the arguments and returns them",
"error_check_cards(all_cards) return parse_cards(hole_cards, board) # Parses hole cards and board",
"default=100000, help=\"Run N Monte Carlo simulations\") parser.add_argument(\"-i\", \"--input\", type=str, help=\"Read",
"command line arguments parser = argparse.ArgumentParser( description=\"Find the odds that",
"(raw_hole_cards is None or len(raw_hole_cards) < 2 or len(raw_hole_cards) %",
"must provide a non-zero even number of hole cards\") exit()",
"print(\"Board cannot have unknown cards\") exit() return create_cards(board) # Instantiates",
"the command line arguments def error_check_arguments(args): # Check that the",
"type=str, help=\"Read hole cards and boards from an input file.",
"[], [] for hole_card in raw_hole_cards: if hole_card != \"?\":",
"Texas Hold'em hand will win. Note \" \"that cards must",
"and card != \"?\": print(\"The cards given must be unique.\")",
"and board hole_cards, board = None, None if not args.input:",
"args.input: hole_cards, board = parse_cards(args.cards, args.board) return hole_cards, args.n, args.exact,",
"current_hole_cards = [], [] for hole_card in raw_hole_cards: if hole_card",
"not None or current_hole_cards[1] is not None): print(\"Unknown hole cards",
"arguments and check for errors args = parser.parse_args() error_check_arguments(args) #",
"Carlo simulations must be positive.\") exit() # Check that we",
"unique.\") exit() # Returns tuple of two-tuple hole_cards: e.g. ((As,",
"args.exact, board, args.input # Parses command line arguments to holdem_calc",
"class LibArgs: def __init__(self, board, exact, num, input_file, hole_cards): self.board",
"args.input # Parses a line taken from the input file",
"nargs=\"*\", type=str, metavar=\"card\", help=\"Add board cards\") parser.add_argument(\"-e\", \"--exact\", action=\"store_true\", help=\"Find",
"line is None or len(line) == 0: print(line) print(\"Invalid format\")",
"= holdem_functions.Card(hole_card) current_hole_cards.append(current_card) else: current_hole_cards.append(None) if len(current_hole_cards) == 2: if",
"= exact # Parses arguments passed to holdem_calc as a",
"hand will win. Note \" \"that cards must be given",
"even number of hole cards\") exit() # Create two-tuples out",
"exit() # Create two-tuples out of hole cards hole_cards, current_hole_cards",
"2): print(\"You must provide a non-zero even number of hole",
"== 0: print(line) print(\"Invalid format\") exit() values = line.split(\"|\") if",
"4, or 5.\") exit() if \"?\" in board: print(\"Board cannot",
"the number of Monte Carlo simulations is a positive number",
"metavar=\"hole card\", help=\"Hole cards you want to find the odds",
"all_cards: if card != \"?\" and not card_re.match(card): print(\"Invalid card",
"valid format all_cards = list(args.cards) if args.board: all_cards.extend(args.board) error_check_cards(all_cards) #",
"if args.board: all_cards.extend(args.board) error_check_cards(all_cards) # Error check the command line",
"print(\"Number of Monte Carlo simulations must be positive.\") exit() #",
"print(\"Unknown hole cards must come in pairs\") exit() hole_cards.append((current_hole_cards[0], current_hole_cards[1]))",
"1: print(line) print(\"Invalid format\") exit() hole_cards = values[0].split() all_cards =",
"hole cards must come in pairs\") exit() hole_cards.append((current_hole_cards[0], current_hole_cards[1])) current_hole_cards",
"card != \"?\" and not card_re.match(card): print(\"Invalid card given.\") exit()",
"= None if len(values) == 2: board = values[1].split() all_cards.extend(board)",
"args.n, args.exact, board, args.input # Parses a line taken from",
"values[0].split() all_cards = list(hole_cards) board = None if len(values) ==",
"error_check_cards(all_cards) # Error check the command line arguments def error_check_arguments(args):",
"return parse_cards(hole_cards, board) # Parses hole cards and board def",
"specified input file if args.input: file_name = args.input try: input_file",
"list(args.cards) if args.board: all_cards.extend(args.board) error_check_cards(all_cards) # Error check the command",
"check the command line arguments def error_check_arguments(args): # Check that",
"__init__(self, board, exact, num, input_file, hole_cards): self.board = board self.cards",
"= num self.input = input_file self.exact = exact # Parses",
"from an input file. \" \"Commandline arguments for hole cards",
"and board def parse_cards(cards, board): hole_cards = create_hole_cards(cards) if board:",
"exit() # Check to make sure all cards are of",
"len(current_hole_cards) == 2: if None in current_hole_cards: if (current_hole_cards[0] is",
"current_hole_cards[1] is not None): print(\"Unknown hole cards must come in",
"exit() return create_cards(board) # Instantiates new cards from the arguments",
"to holdem_calc as a library call def parse_lib_args(args): error_check_arguments(args) #",
"current_hole_cards: if (current_hole_cards[0] is not None or current_hole_cards[1] is not",
"board cards\") parser.add_argument(\"-e\", \"--exact\", action=\"store_true\", help=\"Find exact odds by enumerating",
"cards and board def parse_cards(cards, board): hole_cards = create_hole_cards(cards) if",
"5 or len(board) < 3: print(\"Board must have a length",
"board: board = parse_board(board) return hole_cards, board # Error check",
"a length of 3, 4, or 5.\") exit() if \"?\"",
"Kd), (Jh, Th)) def create_hole_cards(raw_hole_cards): # Checking that there are",
"all_cards.extend(board) error_check_cards(all_cards) return parse_cards(hole_cards, board) # Parses hole cards and",
"tuple(hole_cards) # Returns list of board cards: e.g. [As Ks",
"= open(file_name, 'r') input_file.close() except IOError: print(\"Error opening file \"",
"Error check the command line arguments def error_check_arguments(args): # Check",
"if args.input: file_name = args.input try: input_file = open(file_name, 'r')",
"if args.board: all_cards.extend(args.board) error_check_cards(all_cards) # Checking that the hole cards",
"<reponame>MrStonkus/PokerAi<gh_stars>0 import argparse import re import holdem_calc.holdem_functions as holdem_functions #",
"possible \" \"board\") parser.add_argument(\"-n\", type=int, default=100000, help=\"Run N Monte Carlo",
"hole_cards.append((current_hole_cards[0], current_hole_cards[1])) current_hole_cards = [] if hole_cards.count((None, None)) > 1:",
"!= 1 and card != \"?\": print(\"The cards given must",
"board, args.input # Parses a line taken from the input",
"self.board = board self.cards = hole_cards self.n = num self.input",
"command line arguments to holdem_calc def parse_args(): # Define possible",
"number of hole cards if (raw_hole_cards is None or len(raw_hole_cards)",
"in all_cards: if card != \"?\" and not card_re.match(card): print(\"Invalid",
"and unique def error_check_cards(all_cards): card_re = re.compile('[AKQJT98765432][scdh]') for card in",
"that we can open the specified input file if args.input:",
"0: print(\"Number of Monte Carlo simulations must be positive.\") exit()",
"def parse_file_args(line): if line is None or len(line) == 0:",
"card\", help=\"Hole cards you want to find the odds for.\")",
"have one set of unknown hole cards\") return tuple(hole_cards) #",
"format all_cards = list(args.cards) if args.board: all_cards.extend(args.board) error_check_cards(all_cards) # Error",
"them in a tuple def create_cards(card_strings): return [holdem_functions.Card(arg) for arg",
"# Check that we can open the specified input file",
"= argparse.ArgumentParser( description=\"Find the odds that a Texas Hold'em hand",
"a line taken from the input file and returns the",
"arguments for hole cards and board will \" \"be ignored\")",
"e.g. ((As, Ks), (Ad, Kd), (Jh, Th)) def create_hole_cards(raw_hole_cards): #",
"N Monte Carlo simulations\") parser.add_argument(\"-i\", \"--input\", type=str, help=\"Read hole cards",
"= parse_cards(args.cards, args.board) return hole_cards, args.n, args.exact, board, args.input #",
"input file if args.input: file_name = args.input try: input_file =",
"and returns the hole cards and board def parse_file_args(line): if",
"in a tuple def create_cards(card_strings): return [holdem_functions.Card(arg) for arg in",
"board def parse_cards(cards, board): hole_cards = create_hole_cards(cards) if board: board",
"of a valid format all_cards = list(args.cards) if args.board: all_cards.extend(args.board)",
"of 3, 4, or 5.\") exit() if \"?\" in board:",
"error_check_arguments(args) # Parse hole cards and board hole_cards, board =",
"given must be unique.\") exit() # Returns tuple of two-tuple",
"check for errors args = parser.parse_args() error_check_arguments(args) # Parse hole",
"all_cards.count(card) != 1 and card != \"?\": print(\"The cards given",
"1 and card != \"?\": print(\"The cards given must be",
"print(\"Can only have one set of unknown hole cards\") return",
"open(file_name, 'r') input_file.close() except IOError: print(\"Error opening file \" +",
"parser.add_argument(\"-n\", type=int, default=100000, help=\"Run N Monte Carlo simulations\") parser.add_argument(\"-i\", \"--input\",",
"simulations\") parser.add_argument(\"-i\", \"--input\", type=str, help=\"Read hole cards and boards from",
"< 1: print(line) print(\"Invalid format\") exit() hole_cards = values[0].split() all_cards",
"len(values) < 1: print(line) print(\"Invalid format\") exit() hole_cards = values[0].split()",
"Instantiates new cards from the arguments and returns them in",
"taken from the input file and returns the hole cards",
"type=int, default=100000, help=\"Run N Monte Carlo simulations\") parser.add_argument(\"-i\", \"--input\", type=str,",
"return hole_cards, board # Error check the command line arguments",
"come in pairs\") exit() hole_cards.append((current_hole_cards[0], current_hole_cards[1])) current_hole_cards = [] if",
"to find the odds for.\") parser.add_argument(\"-b\", \"--board\", nargs=\"*\", type=str, metavar=\"card\",",
"hole cards and board def parse_cards(cards, board): hole_cards = create_hole_cards(cards)",
"the odds for.\") parser.add_argument(\"-b\", \"--board\", nargs=\"*\", type=str, metavar=\"card\", help=\"Add board",
"be given in the following format: As, Jc, Td, 3h.\")",
"hole_cards self.n = num self.input = input_file self.exact = exact",
"want to find the odds for.\") parser.add_argument(\"-b\", \"--board\", nargs=\"*\", type=str,",
"3h.\") parser.add_argument(\"cards\", nargs=\"*\", type=str, metavar=\"hole card\", help=\"Hole cards you want",
"parser = argparse.ArgumentParser( description=\"Find the odds that a Texas Hold'em",
"parser.add_argument(\"-e\", \"--exact\", action=\"store_true\", help=\"Find exact odds by enumerating every possible",
"for hole cards and board will \" \"be ignored\") #",
"self.cards = hole_cards self.n = num self.input = input_file self.exact",
"hole cards if (raw_hole_cards is None or len(raw_hole_cards) < 2",
"or 5.\") exit() if \"?\" in board: print(\"Board cannot have",
"arguments parser = argparse.ArgumentParser( description=\"Find the odds that a Texas",
"= line.split(\"|\") if len(values) > 2 or len(values) < 1:",
"# Check to make sure all cards are of a",
"one set of unknown hole cards\") return tuple(hole_cards) # Returns",
"call def parse_lib_args(args): error_check_arguments(args) # Parse hole cards and board",
"create_hole_cards(cards) if board: board = parse_board(board) return hole_cards, board #",
"number if args.n <= 0: print(\"Number of Monte Carlo simulations",
"for hole_card in raw_hole_cards: if hole_card != \"?\": current_card =",
"< 3: print(\"Board must have a length of 3, 4,",
"parse_board(board) return hole_cards, board # Error check the command line",
"help=\"Add board cards\") parser.add_argument(\"-e\", \"--exact\", action=\"store_true\", help=\"Find exact odds by",
"'r') input_file.close() except IOError: print(\"Error opening file \" + file_name)",
"# Parse hole cards and board hole_cards, board = None,",
"if hole_cards.count((None, None)) > 1: print(\"Can only have one set",
"errors args = parser.parse_args() error_check_arguments(args) # Parse hole cards and",
"re import holdem_calc.holdem_functions as holdem_functions # Wrapper class which holds",
"hole_cards, args.n, args.exact, board, args.input # Parses command line arguments",
"be positive.\") exit() # Check that we can open the",
"return tuple(hole_cards) # Returns list of board cards: e.g. [As",
"return create_cards(board) # Instantiates new cards from the arguments and",
"Checking that the hole cards + board are formatted properly",
"from the arguments and returns them in a tuple def",
"cards are of a valid format all_cards = list(args.cards) if",
"parser.add_argument(\"-b\", \"--board\", nargs=\"*\", type=str, metavar=\"card\", help=\"Add board cards\") parser.add_argument(\"-e\", \"--exact\",",
"Parse command line arguments and check for errors args =",
"line arguments def error_check_arguments(args): # Check that the number of",
"file. \" \"Commandline arguments for hole cards and board will",
"command line arguments def error_check_arguments(args): # Check that the number",
"list(args.cards) if args.board: all_cards.extend(args.board) error_check_cards(all_cards) # Checking that the hole",
"there are an even number of hole cards if (raw_hole_cards",
"board = None, None if not args.input: hole_cards, board =",
"= hole_cards self.n = num self.input = input_file self.exact =",
"properly and unique def error_check_cards(all_cards): card_re = re.compile('[AKQJT98765432][scdh]') for card",
"== 2: board = values[1].split() all_cards.extend(board) error_check_cards(all_cards) return parse_cards(hole_cards, board)",
"print(\"The cards given must be unique.\") exit() # Returns tuple",
"hole_cards, board = parse_cards(args.cards, args.board) return hole_cards, args.n, args.exact, board,",
"returns the hole cards and board def parse_file_args(line): if line",
"[As Ks Ad Kd] def parse_board(board): if len(board) > 5",
"exit() hole_cards = values[0].split() all_cards = list(hole_cards) board = None",
"values = line.split(\"|\") if len(values) > 2 or len(values) <",
"list(hole_cards) board = None if len(values) == 2: board =",
"Ks Ad Kd] def parse_board(board): if len(board) > 5 or",
"not args.input: hole_cards, board = parse_cards(args.cards, args.board) return hole_cards, args.n,",
"= list(args.cards) if args.board: all_cards.extend(args.board) error_check_cards(all_cards) # Error check the",
"a non-zero even number of hole cards\") exit() # Create",
"line arguments parser = argparse.ArgumentParser( description=\"Find the odds that a",
"holdem_functions.Card(hole_card) current_hole_cards.append(current_card) else: current_hole_cards.append(None) if len(current_hole_cards) == 2: if None",
"args.n <= 0: print(\"Number of Monte Carlo simulations must be",
"Monte Carlo simulations\") parser.add_argument(\"-i\", \"--input\", type=str, help=\"Read hole cards and",
"help=\"Read hole cards and boards from an input file. \"",
"for library calls # Mocks actual argparse object class LibArgs:",
"hole cards and boards from an input file. \" \"Commandline",
"2: if None in current_hole_cards: if (current_hole_cards[0] is not None",
"0: print(line) print(\"Invalid format\") exit() values = line.split(\"|\") if len(values)",
"except IOError: print(\"Error opening file \" + file_name) exit() #",
"card != \"?\": print(\"The cards given must be unique.\") exit()",
"\"?\" in board: print(\"Board cannot have unknown cards\") exit() return",
"will win. Note \" \"that cards must be given in",
"+ file_name) exit() # Check to make sure all cards",
"Ks), (Ad, Kd), (Jh, Th)) def create_hole_cards(raw_hole_cards): # Checking that",
"Carlo simulations is a positive number if args.n <= 0:",
"<= 0: print(\"Number of Monte Carlo simulations must be positive.\")",
"(current_hole_cards[0] is not None or current_hole_cards[1] is not None): print(\"Unknown",
"in pairs\") exit() hole_cards.append((current_hole_cards[0], current_hole_cards[1])) current_hole_cards = [] if hole_cards.count((None,",
"and check for errors args = parser.parse_args() error_check_arguments(args) # Parse",
"return hole_cards, args.n, args.exact, board, args.input # Parses command line",
"if not args.input: hole_cards, board = parse_cards(args.cards, args.board) return hole_cards,"
] |
[
"any python function that accepts a user object Wrap any",
"# success! go back to the home page # code",
"that are available to purchase products = get_listings(user_email) return render_template('available_products.html',",
"to place the product order success = place_order(new_owner, product_title) error_message",
"message='Please login') @app.route('/login', methods=['POST']) def login_post(): email = request.form.get('email') password",
"error_message = \"Registration Failed.\" # if there is any error",
"\"The passwords do not match\" else: # use backend api",
"at the backend, go back to the update page. if",
"app def authenticate(inner_function): \"\"\" :param inner_function: any python function that",
"info below:') @app.route('/updateuser', methods=['POST']) def update_user_post(): # retrieves current logged",
"methods=['POST']) def update_user_post(): # retrieves current logged in user's email",
"owner_email) if not success: error_message = \"Product Creation Failed.\" #",
"wrap a function, we can put a decoration on that",
"request.args.get('pTitle') # use backend api to place the product order",
"following sessions. \"\"\" # success! go back to the home",
"password) if not success: error_message = \"Registration Failed.\" # if",
"= create_product(price, title, description, last_modified_date, owner_email) if not success: error_message",
"password != <PASSWORD>: error_message = \"The passwords do not match\"",
"that accepts a user object Wrap any python function and",
"call the inner_function # with user as parameter return inner_function(user)",
"will call the inner_function with the logged in user object.",
"message='') @app.route('/register', methods=['POST']) def register_post(): email = request.form.get('email') name =",
"if there is any error messages when ordering product #",
"@app.route('/register', methods=['GET']) def register_get(): # templates are stored in the",
"= request.form.get('shippingaddress') postal_code = request.form.get('postalcode') error_message = None # use",
"user purchased products products = get_transaction(user.email) return render_template('index.html', user=user, owned_products=user_products,",
"accepts a user object Wrap any python function and check",
"page. if error_message: return render_template('updateuser.html', message=error_message) else: return redirect('/', code=303)",
"use backend api to place the product order success =",
"redirect('/login') @app.route('/updateuser', methods=['Get']) def update_user_get(): return render_template('updateuser.html', message='Please enter new",
"current_date[0:2]) price = int(request.form.get('price')) title = request.form.get('title') description = request.form.get('description')",
"@app.route('/placeorder', methods=['POST']) def place_order_post(): new_owner = session['logged_in'] product_title = request.args.get('pTitle')",
"return redirect('/login') @app.route('/updateuser', methods=['Get']) def update_user_get(): return render_template('updateuser.html', message='Please enter",
"the wrapped version of the inner_function: return wrapped_inner @app.route('/login', methods=['GET'])",
"Creation Failed.\" # if there is any error messages when",
"is an object that contains sharing information between a user's",
"purchase below:\", pTitle=request.args.get('pTitle'), pPrice=request.args.get('pPrice')) @app.route('/placeorder', methods=['POST']) def place_order_post(): new_owner =",
"in. If login, it will call the inner_function with the",
"name = request.form.get('name') shipping_address = request.form.get('shippingaddress') postal_code = request.form.get('postalcode') error_message",
"can put a decoration on that function. Example: @authenticate def",
"a function, we can put a decoration on that function.",
"They will be past along between every request the browser",
"error_message = \"Updating of User Profile Failed.\" # if there",
"= request.form.get('new_description') title = request.form.get('title') # use backend api to",
"to purchase products = get_listings(user_email) return render_template('available_products.html', available_products=products) @app.route('/placeorder', methods=['GET'])",
"logged in user's email owner_email = session['logged_in'] today = date.today()",
"back to the register page. if error_message: return render_template('register.html', message=error_message)",
"made to this services. Here we store the user object",
"render_template('updateproduct.html', message=error_message, pName=request.args.get('pName')) else: return redirect('/', code=303) @app.route('/createproduct', methods=['Get']) def",
"redirect('/', code=303) @app.route('/listings', methods=['GET']) def available_products_get(): # retrieves current logged",
"= request.form.get('password') user = login(email, password) if user: session['logged_in'] =",
"go back to the available product listings page. if error_message:",
"in user object. To wrap a function, we can put",
"decoration on that function. Example: @authenticate def home_page(user): pass \"\"\"",
"current_date = today.strftime(\"%d/%m/%Y\") last_modified_date = (current_date[6:10] + \"-\" + current_date[3:5]",
"login_get(): return render_template('login.html', message='Please login') @app.route('/login', methods=['POST']) def login_post(): email",
"@app.route('/placeorder', methods=['GET']) def place_order_get(): return render_template('placeorder.html', message=\"Please confirm the purchase",
"home page # code 303 is to force a 'GET'",
"# use backend api to register the user success =",
"def login_get(): return render_template('login.html', message='Please login') @app.route('/login', methods=['POST']) def login_post():",
"code=303) @app.route('/logout') def logout(): if 'logged_in' in session: session.pop('logged_in', None)",
"services. Here we store the user object into the session,",
"# if there is any error messages when registering new",
"backend, go back to the available product listings page. if",
"Profile Failed.\" # if there is any error messages when",
"user's email user_email = session['logged_in'] name = request.form.get('name') shipping_address =",
"page. if error_message: return render_template('updateproduct.html', message=error_message, pName=request.args.get('pName')) else: return redirect('/',",
"error_message: return render_template('register.html', message=error_message) else: return redirect('/login') @app.route('/updateuser', methods=['Get']) def",
"# at the backend, go back to the register page.",
"message=\"Please enter new product info below:\", pName=request.args.get('pName')) @app.route('/updateproduct', methods=['POST']) def",
"the backend, go back to the create product page. if",
"request.form.get('postalcode') error_message = None # use backend api to update",
"methods=['GET']) def register_get(): # templates are stored in the templates",
"# if there is any error messages when ordering product",
"and the end server. Typically it is packed and stored",
"use backend api to update the user attributes success =",
"the backend, go back to the update page. if error_message:",
"session: email = session['logged_in'] try: user = User.query.filter_by(email=email).one_or_none() if user:",
"when registering new user # at the backend, go back",
"match\" else: # use backend api to register the user",
"session['logged_in'] # gets other user products that are available to",
"description, last_modified_date, owner_email) if not success: error_message = \"Product Creation",
"+ current_date[0:2]) price = int(request.form.get('price')) title = request.form.get('title') description =",
"Wrap any python function and check the current session to",
"products = get_transaction(user.email) return render_template('index.html', user=user, owned_products=user_products, orders=products) @app.route('/register', methods=['GET'])",
"the backend, go back to the available product listings page.",
"def update_user_post(): # retrieves current logged in user's email user_email",
"products that the logged in user owns user_products = get_products(user.email)",
"store the key in the session if 'logged_in' in session:",
"products = get_listings(user_email) return render_template('available_products.html', available_products=products) @app.route('/placeorder', methods=['GET']) def place_order_get():",
"user object Wrap any python function and check the current",
"error_message = None if not success: error_message = \"Placing Order",
"an object that contains sharing information between a user's browser",
"user object into the session, so we can tell if",
"= \"The passwords do not match\" else: # use backend",
"login page return redirect('/login') # return the wrapped version of",
"def update_user_get(): return render_template('updateuser.html', message='Please enter new info below:') @app.route('/updateuser',",
"backend api to register the user success = register(name, email,",
"not success: error_message = \"Product Update Failed\" # if there",
"sessions. \"\"\" # success! go back to the home page",
"\"Placing Order Failed\" # if there is any error messages",
"register the user success = register(name, email, password) if not",
"current_date[3:5] + \"-\" + current_date[0:2]) price = int(request.form.get('price')) title =",
"the logged in user object. To wrap a function, we",
"return render_template('register.html', message='') @app.route('/register', methods=['POST']) def register_post(): email = request.form.get('email')",
"@app.route('/logout') def logout(): if 'logged_in' in session: session.pop('logged_in', None) return",
"session, so we can tell if the client has already",
"render_template('updateuser.html', message='Please enter new info below:') @app.route('/updateuser', methods=['POST']) def update_user_post():",
"it is packed and stored in the browser cookies. They",
"so we can tell if the client has already login",
"to the create product page. if error_message: return render_template('updateproduct.html', message=error_message,",
"object into the session, so we can tell if the",
"function. Example: @authenticate def home_page(user): pass \"\"\" def wrapped_inner(): #",
"product_title) error_message = None if not success: error_message = \"Placing",
"else: return redirect('/', code=303) @app.route('/listings', methods=['GET']) def available_products_get(): # retrieves",
"to update the user attributes success = update_product(new_price, new_title, new_description,",
"None if not success: error_message = \"Placing Order Failed\" #",
"the current session to see if the user has logged",
"if error_message: return render_template('available_products.html', message=error_message) else: return redirect('/', code=303) @app.route('/logout')",
"of the inner_function: return wrapped_inner @app.route('/login', methods=['GET']) def login_get(): return",
"folder return render_template('register.html', message='') @app.route('/register', methods=['POST']) def register_post(): email =",
"user # at the backend, go back to the register",
"= request.form.get('email') password = request.form.get('password') user = login(email, password) if",
"messages when updateing user profile # at the backend, go",
"go back to the create product page. if error_message: return",
"the templates folder return render_template('register.html', message='') @app.route('/register', methods=['POST']) def register_post():",
"user_products = get_products(user.email) # gets list of user purchased products",
"to the available product listings page. if error_message: return render_template('available_products.html',",
"@app.route('/login', methods=['POST']) def login_post(): email = request.form.get('email') password = request.form.get('password')",
"methods=['Get']) def create_product_get(): return render_template('createproduct.html', message='Please enter product info below:')",
"def home_page(user): pass \"\"\" def wrapped_inner(): # check did we",
"owned_products=user_products, orders=products) @app.route('/register', methods=['GET']) def register_get(): # templates are stored",
"from datetime import date from qbay import app def authenticate(inner_function):",
"the user attributes success = create_product(price, title, description, last_modified_date, owner_email)",
"the update page. if error_message: return render_template('updateuser.html', message=error_message) else: return",
"user attributes success = create_product(price, title, description, last_modified_date, owner_email) if",
"will be past along between every request the browser made",
"Failed.\" # if there is any error messages when registering",
"Example: @authenticate def home_page(user): pass \"\"\" def wrapped_inner(): # check",
"it will call the inner_function with the logged in user",
"qbay import app def authenticate(inner_function): \"\"\" :param inner_function: any python",
"did we store the key in the session if 'logged_in'",
"return render_template('createproduct.html', message=error_message) else: return redirect('/', code=303) @app.route('/listings', methods=['GET']) def",
"if user: # if the user exists, call the inner_function",
"the following sessions. \"\"\" # success! go back to the",
"update page. if error_message: return render_template('updateuser.html', message=error_message) else: return redirect('/',",
"list of products that the logged in user owns user_products",
"def available_products_get(): # retrieves current logged in user's email user_email",
"every request the browser made to this services. Here we",
"call the inner_function with the logged in user object. To",
"api to register the user success = register(name, email, password)",
"message=error_message) else: return redirect('/', code=303) @app.route('/listings', methods=['GET']) def available_products_get(): #",
"available_products=products) @app.route('/placeorder', methods=['GET']) def place_order_get(): return render_template('placeorder.html', message=\"Please confirm the",
"place the product order success = place_order(new_owner, product_title) error_message =",
"'GET' request return redirect('/', code=303) else: return render_template('login.html', message='login failed')",
"new_title = request.form.get('new_title') new_description = request.form.get('new_description') title = request.form.get('title') #",
"# use backend api to place the product order success",
"if 'logged_in' in session: email = session['logged_in'] try: user =",
"success: error_message = \"Registration Failed.\" # if there is any",
"request.form.get('new_description') title = request.form.get('title') # use backend api to update",
"messages when registering new user # at the backend, go",
"redirect from qbay.models import * from datetime import date from",
"between a user's browser and the end server. Typically it",
"update_user_post(): # retrieves current logged in user's email user_email =",
"return render_template('updateuser.html', message='Please enter new info below:') @app.route('/updateuser', methods=['POST']) def",
"page # code 303 is to force a 'GET' request",
"request.form.get('password') password2 = request.form.get('password2') error_message = None if password !=",
"# templates are stored in the templates folder return render_template('register.html',",
"message='login failed') @app.route('/') @authenticate def home(user): # gets a list",
"\"Updating of User Profile Failed.\" # if there is any",
"@app.route('/register', methods=['POST']) def register_post(): email = request.form.get('email') name = request.form.get('name')",
"backend, go back to the register page. if error_message: return",
"request.form.get('password') user = login(email, password) if user: session['logged_in'] = user.email",
"function that accepts a user object Wrap any python function",
"any error messages when updateing user profile # at the",
"request.form.get('new_title') new_description = request.form.get('new_description') title = request.form.get('title') # use backend",
"any python function and check the current session to see",
"is any error messages when ordering product # at the",
"as parameter return inner_function(user) except Exception: return redirect('/login') else: #",
"the product order success = place_order(new_owner, product_title) error_message = None",
"enter product info below:') @app.route('/createproduct', methods=['POST']) def create_product_post(): # retrieves",
"this services. Here we store the user object into the",
"we can tell if the client has already login in",
"render_template('createproduct.html', message=error_message) else: return redirect('/', code=303) @app.route('/listings', methods=['GET']) def available_products_get():",
"redirect('/', code=303) @app.route('/updateproduct', methods=['Get']) def update_product_get(): return render_template('updateproduct.html', message=\"Please enter",
"pPrice=request.args.get('pPrice')) @app.route('/placeorder', methods=['POST']) def place_order_post(): new_owner = session['logged_in'] product_title =",
"message=error_message) else: return redirect('/', code=303) @app.route('/logout') def logout(): if 'logged_in'",
"= login(email, password) if user: session['logged_in'] = user.email \"\"\" Session",
"name = request.form.get('name') password = request.form.get('password') password2 = request.form.get('password2') error_message",
"@app.route('/updateuser', methods=['Get']) def update_user_get(): return render_template('updateuser.html', message='Please enter new info",
"render_template, request, session, redirect from qbay.models import * from datetime",
"user's email user_email = session['logged_in'] # gets other user products",
"server. Typically it is packed and stored in the browser",
"from qbay import app def authenticate(inner_function): \"\"\" :param inner_function: any",
"user exists, call the inner_function # with user as parameter",
"user profile # at the backend, go back to the",
"def login_post(): email = request.form.get('email') password = request.form.get('password') user =",
"return render_template('login.html', message='login failed') @app.route('/') @authenticate def home(user): # gets",
"user_email = session['logged_in'] name = request.form.get('name') shipping_address = request.form.get('shippingaddress') postal_code",
"email = request.form.get('email') name = request.form.get('name') password = request.form.get('password') password2",
"attributes success = create_product(price, title, description, last_modified_date, owner_email) if not",
"api to place the product order success = place_order(new_owner, product_title)",
"methods=['GET']) def place_order_get(): return render_template('placeorder.html', message=\"Please confirm the purchase below:\",",
"back to the create product page. if error_message: return render_template('updateproduct.html',",
"if error_message: return render_template('createproduct.html', message=error_message) else: return redirect('/', code=303) @app.route('/listings',",
"# at the backend, go back to the update page.",
"render_template('register.html', message=error_message) else: return redirect('/login') @app.route('/updateuser', methods=['Get']) def update_user_get(): return",
"if not success: error_message = \"Placing Order Failed\" # if",
"register_post(): email = request.form.get('email') name = request.form.get('name') password = request.form.get('password')",
"description = request.form.get('description') error_message = None # use backend api",
"return redirect('/', code=303) @app.route('/logout') def logout(): if 'logged_in' in session:",
"there is any error messages when ordering product # at",
"session to see if the user has logged in. If",
"last_modified_date = (current_date[6:10] + \"-\" + current_date[3:5] + \"-\" +",
"gets list of user purchased products products = get_transaction(user.email) return",
"the logged in user owns user_products = get_products(user.email) # gets",
"in user's email user_email = session['logged_in'] name = request.form.get('name') shipping_address",
"at the backend, go back to the available product listings",
"login(email, password) if user: session['logged_in'] = user.email \"\"\" Session is",
"of products that the logged in user owns user_products =",
"\"\"\" Session is an object that contains sharing information between",
"error messages when registering new user # at the backend,",
"store the user object into the session, so we can",
"wrapped version of the inner_function: return wrapped_inner @app.route('/login', methods=['GET']) def",
"the user object into the session, so we can tell",
"other user products that are available to purchase products =",
"place_order_post(): new_owner = session['logged_in'] product_title = request.args.get('pTitle') # use backend",
"error_message = \"Placing Order Failed\" # if there is any",
"return the wrapped version of the inner_function: return wrapped_inner @app.route('/login',",
"To wrap a function, we can put a decoration on",
"def authenticate(inner_function): \"\"\" :param inner_function: any python function that accepts",
"= int(request.form.get('price')) title = request.form.get('title') description = request.form.get('description') error_message =",
"logged in user object. To wrap a function, we can",
"= today.strftime(\"%d/%m/%Y\") last_modified_date = (current_date[6:10] + \"-\" + current_date[3:5] +",
"= get_products(user.email) # gets list of user purchased products products",
"error_message = \"The passwords do not match\" else: # use",
"request.form.get('shippingaddress') postal_code = request.form.get('postalcode') error_message = None # use backend",
"login') @app.route('/login', methods=['POST']) def login_post(): email = request.form.get('email') password =",
"else: # use backend api to register the user success",
"user object. To wrap a function, we can put a",
"key in the session if 'logged_in' in session: email =",
"the inner_function: return wrapped_inner @app.route('/login', methods=['GET']) def login_get(): return render_template('login.html',",
"code=303) @app.route('/listings', methods=['GET']) def available_products_get(): # retrieves current logged in",
"go back to the register page. if error_message: return render_template('register.html',",
"email user_email = session['logged_in'] name = request.form.get('name') shipping_address = request.form.get('shippingaddress')",
"passwords do not match\" else: # use backend api to",
"available product listings page. if error_message: return render_template('available_products.html', message=error_message) else:",
"update_product_post(): new_price = int(request.form.get('new_price')) new_title = request.form.get('new_title') new_description = request.form.get('new_description')",
"python function and check the current session to see if",
"return redirect('/login') else: # else, redirect to the login page",
"the user attributes success = update_user(user_email, name, shipping_address, postal_code) if",
"render_template('available_products.html', message=error_message) else: return redirect('/', code=303) @app.route('/logout') def logout(): if",
":param inner_function: any python function that accepts a user object",
"def home(user): # gets a list of products that the",
"a product # at the backend, go back to the",
"return render_template('available_products.html', message=error_message) else: return redirect('/', code=303) @app.route('/logout') def logout():",
"\"\"\" :param inner_function: any python function that accepts a user",
"to see if the user has logged in. If login,",
"redirect to the login page return redirect('/login') # return the",
"code=303) else: return render_template('login.html', message='login failed') @app.route('/') @authenticate def home(user):",
"a 'GET' request return redirect('/', code=303) else: return render_template('login.html', message='login",
"into the session, so we can tell if the client",
"success = update_user(user_email, name, shipping_address, postal_code) if not success: error_message",
"product info below:\", pName=request.args.get('pName')) @app.route('/updateproduct', methods=['POST']) def update_product_post(): new_price =",
"available to purchase products = get_listings(user_email) return render_template('available_products.html', available_products=products) @app.route('/placeorder',",
"inner_function: return wrapped_inner @app.route('/login', methods=['GET']) def login_get(): return render_template('login.html', message='Please",
"that function. Example: @authenticate def home_page(user): pass \"\"\" def wrapped_inner():",
"postal_code) if not success: error_message = \"Updating of User Profile",
"update the user attributes success = create_product(price, title, description, last_modified_date,",
"return redirect('/', code=303) @app.route('/listings', methods=['GET']) def available_products_get(): # retrieves current",
"def place_order_post(): new_owner = session['logged_in'] product_title = request.args.get('pTitle') # use",
"password2 = request.form.get('password2') error_message = None if password != <PASSWORD>:",
"= None # use backend api to update the user",
"retrieves current logged in user's email user_email = session['logged_in'] #",
"# with user as parameter return inner_function(user) except Exception: return",
"create_product_get(): return render_template('createproduct.html', message='Please enter product info below:') @app.route('/createproduct', methods=['POST'])",
"render_template('updateproduct.html', message=\"Please enter new product info below:\", pName=request.args.get('pName')) @app.route('/updateproduct', methods=['POST'])",
"any error messages when registering new user # at the",
"except Exception: return redirect('/login') else: # else, redirect to the",
"(current_date[6:10] + \"-\" + current_date[3:5] + \"-\" + current_date[0:2]) price",
"def register_get(): # templates are stored in the templates folder",
"def place_order_get(): return render_template('placeorder.html', message=\"Please confirm the purchase below:\", pTitle=request.args.get('pTitle'),",
"return redirect('/login') # return the wrapped version of the inner_function:",
"= update_product(new_price, new_title, new_description, title) error_message = None if not",
"in the templates folder return render_template('register.html', message='') @app.route('/register', methods=['POST']) def",
"request return redirect('/', code=303) else: return render_template('login.html', message='login failed') @app.route('/')",
"render_template('placeorder.html', message=\"Please confirm the purchase below:\", pTitle=request.args.get('pTitle'), pPrice=request.args.get('pPrice')) @app.route('/placeorder', methods=['POST'])",
"= place_order(new_owner, product_title) error_message = None if not success: error_message",
"import render_template, request, session, redirect from qbay.models import * from",
"logged in user owns user_products = get_products(user.email) # gets list",
"create product page. if error_message: return render_template('createproduct.html', message=error_message) else: return",
"request.form.get('password2') error_message = None if password != <PASSWORD>: error_message =",
"methods=['Get']) def update_user_get(): return render_template('updateuser.html', message='Please enter new info below:')",
"error_message = \"Product Creation Failed.\" # if there is any",
"the create product page. if error_message: return render_template('createproduct.html', message=error_message) else:",
"info below:') @app.route('/createproduct', methods=['POST']) def create_product_post(): # retrieves current logged",
"request.form.get('email') name = request.form.get('name') password = request.form.get('password') password2 = request.form.get('password2')",
"page. if error_message: return render_template('createproduct.html', message=error_message) else: return redirect('/', code=303)",
"error_message: return render_template('createproduct.html', message=error_message) else: return redirect('/', code=303) @app.route('/listings', methods=['GET'])",
"back to the create product page. if error_message: return render_template('createproduct.html',",
"pass \"\"\" def wrapped_inner(): # check did we store the",
"to this services. Here we store the user object into",
"the user attributes success = update_product(new_price, new_title, new_description, title) error_message",
"flask import render_template, request, session, redirect from qbay.models import *",
"Order Failed\" # if there is any error messages when",
"messages when ordering product # at the backend, go back",
"between every request the browser made to this services. Here",
"= request.form.get('password') password2 = request.form.get('password2') error_message = None if password",
"return render_template('updateproduct.html', message=error_message, pName=request.args.get('pName')) else: return redirect('/', code=303) @app.route('/createproduct', methods=['Get'])",
"the client has already login in the following sessions. \"\"\"",
"current logged in user's email user_email = session['logged_in'] # gets",
"password) if user: session['logged_in'] = user.email \"\"\" Session is an",
"title, description, last_modified_date, owner_email) if not success: error_message = \"Product",
"gets a list of products that the logged in user",
"a user's browser and the end server. Typically it is",
"render_template('createproduct.html', message='Please enter product info below:') @app.route('/createproduct', methods=['POST']) def create_product_post():",
"current logged in user's email user_email = session['logged_in'] name =",
"return render_template('placeorder.html', message=\"Please confirm the purchase below:\", pTitle=request.args.get('pTitle'), pPrice=request.args.get('pPrice')) @app.route('/placeorder',",
"\"\"\" def wrapped_inner(): # check did we store the key",
"today.strftime(\"%d/%m/%Y\") last_modified_date = (current_date[6:10] + \"-\" + current_date[3:5] + \"-\"",
"browser made to this services. Here we store the user",
"confirm the purchase below:\", pTitle=request.args.get('pTitle'), pPrice=request.args.get('pPrice')) @app.route('/placeorder', methods=['POST']) def place_order_post():",
"user: session['logged_in'] = user.email \"\"\" Session is an object that",
"methods=['Get']) def update_product_get(): return render_template('updateproduct.html', message=\"Please enter new product info",
"page. if error_message: return render_template('available_products.html', message=error_message) else: return redirect('/', code=303)",
"inner_function(user) except Exception: return redirect('/login') else: # else, redirect to",
"new info below:') @app.route('/updateuser', methods=['POST']) def update_user_post(): # retrieves current",
"session['logged_in'] = user.email \"\"\" Session is an object that contains",
"and stored in the browser cookies. They will be past",
"backend, go back to the update page. if error_message: return",
"login in the following sessions. \"\"\" # success! go back",
"# if the user exists, call the inner_function # with",
"message=error_message) else: return redirect('/', code=303) @app.route('/updateproduct', methods=['Get']) def update_product_get(): return",
"= request.form.get('title') # use backend api to update the user",
"enter new info below:') @app.route('/updateuser', methods=['POST']) def update_user_post(): # retrieves",
"if the client has already login in the following sessions.",
"= \"Updating of User Profile Failed.\" # if there is",
"the register page. if error_message: return render_template('register.html', message=error_message) else: return",
"the browser made to this services. Here we store the",
"browser and the end server. Typically it is packed and",
"session['logged_in'] today = date.today() current_date = today.strftime(\"%d/%m/%Y\") last_modified_date = (current_date[6:10]",
"last_modified_date, owner_email) if not success: error_message = \"Product Creation Failed.\"",
"end server. Typically it is packed and stored in the",
"Here we store the user object into the session, so",
"the user has logged in. If login, it will call",
"authenticate(inner_function): \"\"\" :param inner_function: any python function that accepts a",
"password = request.form.get('password') password2 = request.form.get('password2') error_message = None if",
"= request.form.get('name') password = request.form.get('password') password2 = request.form.get('password2') error_message =",
"stored in the templates folder return render_template('register.html', message='') @app.route('/register', methods=['POST'])",
"when creating a product # at the backend, go back",
"update_user_get(): return render_template('updateuser.html', message='Please enter new info below:') @app.route('/updateuser', methods=['POST'])",
"# gets other user products that are available to purchase",
"if there is any error messages when creating a product",
"check the current session to see if the user has",
"None if password != <PASSWORD>: error_message = \"The passwords do",
"def create_product_get(): return render_template('createproduct.html', message='Please enter product info below:') @app.route('/createproduct',",
"create_product(price, title, description, last_modified_date, owner_email) if not success: error_message =",
"Exception: return redirect('/login') else: # else, redirect to the login",
"if the user exists, call the inner_function # with user",
"inner_function: any python function that accepts a user object Wrap",
"password = request.form.get('password') user = login(email, password) if user: session['logged_in']",
"else: return redirect('/', code=303) @app.route('/logout') def logout(): if 'logged_in' in",
"return render_template('index.html', user=user, owned_products=user_products, orders=products) @app.route('/register', methods=['GET']) def register_get(): #",
"if user: session['logged_in'] = user.email \"\"\" Session is an object",
"# at the backend, go back to the create product",
"product page. if error_message: return render_template('createproduct.html', message=error_message) else: return redirect('/',",
"available_products_get(): # retrieves current logged in user's email user_email =",
"in the browser cookies. They will be past along between",
"request.form.get('description') error_message = None # use backend api to update",
"User.query.filter_by(email=email).one_or_none() if user: # if the user exists, call the",
"version of the inner_function: return wrapped_inner @app.route('/login', methods=['GET']) def login_get():",
"we store the user object into the session, so we",
"new_description = request.form.get('new_description') title = request.form.get('title') # use backend api",
"python function that accepts a user object Wrap any python",
"= request.form.get('postalcode') error_message = None # use backend api to",
"update_product(new_price, new_title, new_description, title) error_message = None if not success:",
"email user_email = session['logged_in'] # gets other user products that",
"force a 'GET' request return redirect('/', code=303) else: return render_template('login.html',",
"user = User.query.filter_by(email=email).one_or_none() if user: # if the user exists,",
"methods=['POST']) def place_order_post(): new_owner = session['logged_in'] product_title = request.args.get('pTitle') #",
"title = request.form.get('title') description = request.form.get('description') error_message = None #",
"not success: error_message = \"Product Creation Failed.\" # if there",
"methods=['POST']) def register_post(): email = request.form.get('email') name = request.form.get('name') password",
"get_products(user.email) # gets list of user purchased products products =",
"else, redirect to the login page return redirect('/login') # return",
"= None if not success: error_message = \"Product Update Failed\"",
"user = login(email, password) if user: session['logged_in'] = user.email \"\"\"",
"int(request.form.get('price')) title = request.form.get('title') description = request.form.get('description') error_message = None",
"= request.form.get('title') description = request.form.get('description') error_message = None # use",
"render_template('available_products.html', available_products=products) @app.route('/placeorder', methods=['GET']) def place_order_get(): return render_template('placeorder.html', message=\"Please confirm",
"order success = place_order(new_owner, product_title) error_message = None if not",
"Failed\" # if there is any error messages when ordering",
"update_user(user_email, name, shipping_address, postal_code) if not success: error_message = \"Updating",
"go back to the home page # code 303 is",
"updateing user profile # at the backend, go back to",
"browser cookies. They will be past along between every request",
"= request.form.get('name') shipping_address = request.form.get('shippingaddress') postal_code = request.form.get('postalcode') error_message =",
"return redirect('/', code=303) else: return render_template('login.html', message='login failed') @app.route('/') @authenticate",
"# if there is any error messages when updateing user",
"if the user has logged in. If login, it will",
"the end server. Typically it is packed and stored in",
"products that are available to purchase products = get_listings(user_email) return",
"backend, go back to the create product page. if error_message:",
"packed and stored in the browser cookies. They will be",
"to the register page. if error_message: return render_template('register.html', message=error_message) else:",
"back to the update page. if error_message: return render_template('updateuser.html', message=error_message)",
"info below:\", pName=request.args.get('pName')) @app.route('/updateproduct', methods=['POST']) def update_product_post(): new_price = int(request.form.get('new_price'))",
"message=\"Please confirm the purchase below:\", pTitle=request.args.get('pTitle'), pPrice=request.args.get('pPrice')) @app.route('/placeorder', methods=['POST']) def",
"is to force a 'GET' request return redirect('/', code=303) else:",
"gets other user products that are available to purchase products",
"the browser cookies. They will be past along between every",
"exists, call the inner_function # with user as parameter return",
"code 303 is to force a 'GET' request return redirect('/',",
"if password != <PASSWORD>: error_message = \"The passwords do not",
"not success: error_message = \"Registration Failed.\" # if there is",
"# code 303 is to force a 'GET' request return",
"wrapped_inner(): # check did we store the key in the",
"postal_code = request.form.get('postalcode') error_message = None # use backend api",
"of User Profile Failed.\" # if there is any error",
"backend api to update the user attributes success = update_user(user_email,",
"session['logged_in'] product_title = request.args.get('pTitle') # use backend api to place",
"redirect('/', code=303) else: return render_template('login.html', message='login failed') @app.route('/') @authenticate def",
"= request.form.get('password2') error_message = None if password != <PASSWORD>: error_message",
"new product info below:\", pName=request.args.get('pName')) @app.route('/updateproduct', methods=['POST']) def update_product_post(): new_price",
"error_message: return render_template('updateproduct.html', message=error_message, pName=request.args.get('pName')) else: return redirect('/', code=303) @app.route('/createproduct',",
"user products that are available to purchase products = get_listings(user_email)",
"def update_product_post(): new_price = int(request.form.get('new_price')) new_title = request.form.get('new_title') new_description =",
"backend api to place the product order success = place_order(new_owner,",
"error_message: return render_template('updateuser.html', message=error_message) else: return redirect('/', code=303) @app.route('/updateproduct', methods=['Get'])",
"is packed and stored in the browser cookies. They will",
"= User.query.filter_by(email=email).one_or_none() if user: # if the user exists, call",
"if not success: error_message = \"Registration Failed.\" # if there",
"enter new product info below:\", pName=request.args.get('pName')) @app.route('/updateproduct', methods=['POST']) def update_product_post():",
"with the logged in user object. To wrap a function,",
"request.form.get('name') password = request.form.get('password') password2 = request.form.get('password2') error_message = None",
"that the logged in user owns user_products = get_products(user.email) #",
"new user # at the backend, go back to the",
"below:') @app.route('/updateuser', methods=['POST']) def update_user_post(): # retrieves current logged in",
"methods=['POST']) def login_post(): email = request.form.get('email') password = request.form.get('password') user",
"success! go back to the home page # code 303",
"use backend api to register the user success = register(name,",
"on that function. Example: @authenticate def home_page(user): pass \"\"\" def",
"information between a user's browser and the end server. Typically",
"= session['logged_in'] try: user = User.query.filter_by(email=email).one_or_none() if user: # if",
"= session['logged_in'] name = request.form.get('name') shipping_address = request.form.get('shippingaddress') postal_code =",
"else: return render_template('login.html', message='login failed') @app.route('/') @authenticate def home(user): #",
"the backend, go back to the register page. if error_message:",
"update the user attributes success = update_user(user_email, name, shipping_address, postal_code)",
"any error messages when ordering product # at the backend,",
"login_post(): email = request.form.get('email') password = request.form.get('password') user = login(email,",
"logged in user's email user_email = session['logged_in'] # gets other",
"session['logged_in'] try: user = User.query.filter_by(email=email).one_or_none() if user: # if the",
"if not success: error_message = \"Product Update Failed\" # if",
"there is any error messages when updateing user profile #",
"home_page(user): pass \"\"\" def wrapped_inner(): # check did we store",
"along between every request the browser made to this services.",
"owns user_products = get_products(user.email) # gets list of user purchased",
"with user as parameter return inner_function(user) except Exception: return redirect('/login')",
"= register(name, email, password) if not success: error_message = \"Registration",
"logged in. If login, it will call the inner_function with",
"contains sharing information between a user's browser and the end",
"is any error messages when creating a product # at",
"= update_user(user_email, name, shipping_address, postal_code) if not success: error_message =",
"request.form.get('title') description = request.form.get('description') error_message = None # use backend",
"product info below:') @app.route('/createproduct', methods=['POST']) def create_product_post(): # retrieves current",
"are stored in the templates folder return render_template('register.html', message='') @app.route('/register',",
"register(name, email, password) if not success: error_message = \"Registration Failed.\"",
"email owner_email = session['logged_in'] today = date.today() current_date = today.strftime(\"%d/%m/%Y\")",
"update the user attributes success = update_product(new_price, new_title, new_description, title)",
"qbay.models import * from datetime import date from qbay import",
"methods=['GET']) def login_get(): return render_template('login.html', message='Please login') @app.route('/login', methods=['POST']) def",
"user as parameter return inner_function(user) except Exception: return redirect('/login') else:",
"email = request.form.get('email') password = request.form.get('password') user = login(email, password)",
"message='Please enter new info below:') @app.route('/updateuser', methods=['POST']) def update_user_post(): #",
"update_product_get(): return render_template('updateproduct.html', message=\"Please enter new product info below:\", pName=request.args.get('pName'))",
"error_message = \"Product Update Failed\" # if there is any",
"logged in user's email user_email = session['logged_in'] name = request.form.get('name')",
"tell if the client has already login in the following",
"return redirect('/', code=303) @app.route('/createproduct', methods=['Get']) def create_product_get(): return render_template('createproduct.html', message='Please",
"that contains sharing information between a user's browser and the",
"if error_message: return render_template('updateproduct.html', message=error_message, pName=request.args.get('pName')) else: return redirect('/', code=303)",
"<PASSWORD>: error_message = \"The passwords do not match\" else: #",
"the create product page. if error_message: return render_template('updateproduct.html', message=error_message, pName=request.args.get('pName'))",
"of user purchased products products = get_transaction(user.email) return render_template('index.html', user=user,",
"\"Product Creation Failed.\" # if there is any error messages",
"= get_listings(user_email) return render_template('available_products.html', available_products=products) @app.route('/placeorder', methods=['GET']) def place_order_get(): return",
"date from qbay import app def authenticate(inner_function): \"\"\" :param inner_function:",
"creating a product # at the backend, go back to",
"below:\", pName=request.args.get('pName')) @app.route('/updateproduct', methods=['POST']) def update_product_post(): new_price = int(request.form.get('new_price')) new_title",
"# gets list of user purchased products products = get_transaction(user.email)",
"methods=['POST']) def create_product_post(): # retrieves current logged in user's email",
"product_title = request.args.get('pTitle') # use backend api to place the",
"success: error_message = \"Product Creation Failed.\" # if there is",
"not success: error_message = \"Updating of User Profile Failed.\" #",
"profile # at the backend, go back to the update",
"if there is any error messages when updateing user profile",
"else: return redirect('/', code=303) @app.route('/createproduct', methods=['Get']) def create_product_get(): return render_template('createproduct.html',",
"user=user, owned_products=user_products, orders=products) @app.route('/register', methods=['GET']) def register_get(): # templates are",
"orders=products) @app.route('/register', methods=['GET']) def register_get(): # templates are stored in",
"to register the user success = register(name, email, password) if",
"Session is an object that contains sharing information between a",
"import date from qbay import app def authenticate(inner_function): \"\"\" :param",
"def create_product_post(): # retrieves current logged in user's email owner_email",
"can tell if the client has already login in the",
"to the update page. if error_message: return render_template('updateuser.html', message=error_message) else:",
"has logged in. If login, it will call the inner_function",
"object. To wrap a function, we can put a decoration",
"= None if password != <PASSWORD>: error_message = \"The passwords",
"new_title, new_description, title) error_message = None if not success: error_message",
"return render_template('register.html', message=error_message) else: return redirect('/login') @app.route('/updateuser', methods=['Get']) def update_user_get():",
"message=error_message) else: return redirect('/login') @app.route('/updateuser', methods=['Get']) def update_user_get(): return render_template('updateuser.html',",
"purchased products products = get_transaction(user.email) return render_template('index.html', user=user, owned_products=user_products, orders=products)",
"user success = register(name, email, password) if not success: error_message",
"the home page # code 303 is to force a",
"are available to purchase products = get_listings(user_email) return render_template('available_products.html', available_products=products)",
"client has already login in the following sessions. \"\"\" #",
"back to the available product listings page. if error_message: return",
"email, password) if not success: error_message = \"Registration Failed.\" #",
"= session['logged_in'] # gets other user products that are available",
"registering new user # at the backend, go back to",
"user_email = session['logged_in'] # gets other user products that are",
"when ordering product # at the backend, go back to",
"@authenticate def home(user): # gets a list of products that",
"email = session['logged_in'] try: user = User.query.filter_by(email=email).one_or_none() if user: #",
"from flask import render_template, request, session, redirect from qbay.models import",
"the purchase below:\", pTitle=request.args.get('pTitle'), pPrice=request.args.get('pPrice')) @app.route('/placeorder', methods=['POST']) def place_order_post(): new_owner",
"failed') @app.route('/') @authenticate def home(user): # gets a list of",
"create product page. if error_message: return render_template('updateproduct.html', message=error_message, pName=request.args.get('pName')) else:",
"the available product listings page. if error_message: return render_template('available_products.html', message=error_message)",
"None # use backend api to update the user attributes",
"if error_message: return render_template('register.html', message=error_message) else: return redirect('/login') @app.route('/updateuser', methods=['Get'])",
"session, redirect from qbay.models import * from datetime import date",
"= request.args.get('pTitle') # use backend api to place the product",
"* from datetime import date from qbay import app def",
"Failed.\" # if there is any error messages when creating",
"we store the key in the session if 'logged_in' in",
"home(user): # gets a list of products that the logged",
"to the create product page. if error_message: return render_template('createproduct.html', message=error_message)",
"redirect('/', code=303) @app.route('/createproduct', methods=['Get']) def create_product_get(): return render_template('createproduct.html', message='Please enter",
"list of user purchased products products = get_transaction(user.email) return render_template('index.html',",
"render_template('updateuser.html', message=error_message) else: return redirect('/', code=303) @app.route('/updateproduct', methods=['Get']) def update_product_get():",
"not match\" else: # use backend api to register the",
"there is any error messages when creating a product #",
"success: error_message = \"Placing Order Failed\" # if there is",
"= request.form.get('email') name = request.form.get('name') password = request.form.get('password') password2 =",
"def update_product_get(): return render_template('updateproduct.html', message=\"Please enter new product info below:\",",
"when updateing user profile # at the backend, go back",
"render_template('login.html', message='Please login') @app.route('/login', methods=['POST']) def login_post(): email = request.form.get('email')",
"success: error_message = \"Updating of User Profile Failed.\" # if",
"request the browser made to this services. Here we store",
"to the home page # code 303 is to force",
"user attributes success = update_user(user_email, name, shipping_address, postal_code) if not",
"= date.today() current_date = today.strftime(\"%d/%m/%Y\") last_modified_date = (current_date[6:10] + \"-\"",
"get_transaction(user.email) return render_template('index.html', user=user, owned_products=user_products, orders=products) @app.route('/register', methods=['GET']) def register_get():",
"function, we can put a decoration on that function. Example:",
"methods=['GET']) def available_products_get(): # retrieves current logged in user's email",
"to update the user attributes success = create_product(price, title, description,",
"inner_function # with user as parameter return inner_function(user) except Exception:",
"Failed.\" # if there is any error messages when updateing",
"return wrapped_inner @app.route('/login', methods=['GET']) def login_get(): return render_template('login.html', message='Please login')",
"User Profile Failed.\" # if there is any error messages",
"name, shipping_address, postal_code) if not success: error_message = \"Updating of",
"error messages when creating a product # at the backend,",
"already login in the following sessions. \"\"\" # success! go",
"page. if error_message: return render_template('register.html', message=error_message) else: return redirect('/login') @app.route('/updateuser',",
"at the backend, go back to the register page. if",
"backend api to update the user attributes success = create_product(price,",
"has already login in the following sessions. \"\"\" # success!",
"inner_function with the logged in user object. To wrap a",
"check did we store the key in the session if",
"from qbay.models import * from datetime import date from qbay",
"shipping_address = request.form.get('shippingaddress') postal_code = request.form.get('postalcode') error_message = None #",
"return redirect('/', code=303) @app.route('/updateproduct', methods=['Get']) def update_product_get(): return render_template('updateproduct.html', message=\"Please",
"date.today() current_date = today.strftime(\"%d/%m/%Y\") last_modified_date = (current_date[6:10] + \"-\" +",
"the inner_function with the logged in user object. To wrap",
"product listings page. if error_message: return render_template('available_products.html', message=error_message) else: return",
"error messages when updateing user profile # at the backend,",
"!= <PASSWORD>: error_message = \"The passwords do not match\" else:",
"success = register(name, email, password) if not success: error_message =",
"object Wrap any python function and check the current session",
"= \"Placing Order Failed\" # if there is any error",
"= \"Registration Failed.\" # if there is any error messages",
"return render_template('login.html', message='Please login') @app.route('/login', methods=['POST']) def login_post(): email =",
"message='Please enter product info below:') @app.route('/createproduct', methods=['POST']) def create_product_post(): #",
"Typically it is packed and stored in the browser cookies.",
"product # at the backend, go back to the create",
"# check did we store the key in the session",
"user.email \"\"\" Session is an object that contains sharing information",
"in the following sessions. \"\"\" # success! go back to",
"= request.form.get('new_title') new_description = request.form.get('new_description') title = request.form.get('title') # use",
"in user owns user_products = get_products(user.email) # gets list of",
"error messages when ordering product # at the backend, go",
"\"-\" + current_date[3:5] + \"-\" + current_date[0:2]) price = int(request.form.get('price'))",
"a list of products that the logged in user owns",
"code=303) @app.route('/updateproduct', methods=['Get']) def update_product_get(): return render_template('updateproduct.html', message=\"Please enter new",
"parameter return inner_function(user) except Exception: return redirect('/login') else: # else,",
"in user's email user_email = session['logged_in'] # gets other user",
"listings page. if error_message: return render_template('available_products.html', message=error_message) else: return redirect('/',",
"back to the home page # code 303 is to",
"products products = get_transaction(user.email) return render_template('index.html', user=user, owned_products=user_products, orders=products) @app.route('/register',",
"error_message = None if not success: error_message = \"Product Update",
"request, session, redirect from qbay.models import * from datetime import",
"we can put a decoration on that function. Example: @authenticate",
"None if not success: error_message = \"Product Update Failed\" #",
"\"\"\" # success! go back to the home page #",
"def register_post(): email = request.form.get('email') name = request.form.get('name') password =",
"a user object Wrap any python function and check the",
"return render_template('createproduct.html', message='Please enter product info below:') @app.route('/createproduct', methods=['POST']) def",
"@authenticate def home_page(user): pass \"\"\" def wrapped_inner(): # check did",
"get_listings(user_email) return render_template('available_products.html', available_products=products) @app.route('/placeorder', methods=['GET']) def place_order_get(): return render_template('placeorder.html',",
"render_template('login.html', message='login failed') @app.route('/') @authenticate def home(user): # gets a",
"# at the backend, go back to the available product",
"error_message = None # use backend api to update the",
"current logged in user's email owner_email = session['logged_in'] today =",
"success = update_product(new_price, new_title, new_description, title) error_message = None if",
"and check the current session to see if the user",
"datetime import date from qbay import app def authenticate(inner_function): \"\"\"",
"\"Registration Failed.\" # if there is any error messages when",
"int(request.form.get('new_price')) new_title = request.form.get('new_title') new_description = request.form.get('new_description') title = request.form.get('title')",
"request.form.get('title') # use backend api to update the user attributes",
"else: # else, redirect to the login page return redirect('/login')",
"= None if not success: error_message = \"Placing Order Failed\"",
"redirect('/login') # return the wrapped version of the inner_function: return",
"if not success: error_message = \"Updating of User Profile Failed.\"",
"the user success = register(name, email, password) if not success:",
"render_template('index.html', user=user, owned_products=user_products, orders=products) @app.route('/register', methods=['GET']) def register_get(): # templates",
"object that contains sharing information between a user's browser and",
"return render_template('updateproduct.html', message=\"Please enter new product info below:\", pName=request.args.get('pName')) @app.route('/updateproduct',",
"= request.form.get('description') error_message = None # use backend api to",
"page return redirect('/login') # return the wrapped version of the",
"# return the wrapped version of the inner_function: return wrapped_inner",
"+ current_date[3:5] + \"-\" + current_date[0:2]) price = int(request.form.get('price')) title",
"function and check the current session to see if the",
"ordering product # at the backend, go back to the",
"past along between every request the browser made to this",
"@app.route('/updateproduct', methods=['POST']) def update_product_post(): new_price = int(request.form.get('new_price')) new_title = request.form.get('new_title')",
"place_order(new_owner, product_title) error_message = None if not success: error_message =",
"@app.route('/') @authenticate def home(user): # gets a list of products",
"api to update the user attributes success = update_user(user_email, name,",
"pName=request.args.get('pName')) else: return redirect('/', code=303) @app.route('/createproduct', methods=['Get']) def create_product_get(): return",
"the session if 'logged_in' in session: email = session['logged_in'] try:",
"@app.route('/updateproduct', methods=['Get']) def update_product_get(): return render_template('updateproduct.html', message=\"Please enter new product",
"purchase products = get_listings(user_email) return render_template('available_products.html', available_products=products) @app.route('/placeorder', methods=['GET']) def",
"@app.route('/updateuser', methods=['POST']) def update_user_post(): # retrieves current logged in user's",
"title) error_message = None if not success: error_message = \"Product",
"return inner_function(user) except Exception: return redirect('/login') else: # else, redirect",
"create_product_post(): # retrieves current logged in user's email owner_email =",
"return render_template('updateuser.html', message=error_message) else: return redirect('/', code=303) @app.route('/updateproduct', methods=['Get']) def",
"product page. if error_message: return render_template('updateproduct.html', message=error_message, pName=request.args.get('pName')) else: return",
"= (current_date[6:10] + \"-\" + current_date[3:5] + \"-\" + current_date[0:2])",
"success = create_product(price, title, description, last_modified_date, owner_email) if not success:",
"place_order_get(): return render_template('placeorder.html', message=\"Please confirm the purchase below:\", pTitle=request.args.get('pTitle'), pPrice=request.args.get('pPrice'))",
"new_owner = session['logged_in'] product_title = request.args.get('pTitle') # use backend api",
"user has logged in. If login, it will call the",
"try: user = User.query.filter_by(email=email).one_or_none() if user: # if the user",
"request.form.get('name') shipping_address = request.form.get('shippingaddress') postal_code = request.form.get('postalcode') error_message = None",
"pName=request.args.get('pName')) @app.route('/updateproduct', methods=['POST']) def update_product_post(): new_price = int(request.form.get('new_price')) new_title =",
"is any error messages when registering new user # at",
"else: return redirect('/', code=303) @app.route('/updateproduct', methods=['Get']) def update_product_get(): return render_template('updateproduct.html',",
"login, it will call the inner_function with the logged in",
"owner_email = session['logged_in'] today = date.today() current_date = today.strftime(\"%d/%m/%Y\") last_modified_date",
"if error_message: return render_template('updateuser.html', message=error_message) else: return redirect('/', code=303) @app.route('/updateproduct',",
"to update the user attributes success = update_user(user_email, name, shipping_address,",
"a decoration on that function. Example: @authenticate def home_page(user): pass",
"is any error messages when updateing user profile # at",
"put a decoration on that function. Example: @authenticate def home_page(user):",
"# else, redirect to the login page return redirect('/login') #",
"# retrieves current logged in user's email user_email = session['logged_in']",
"go back to the update page. if error_message: return render_template('updateuser.html',",
"templates folder return render_template('register.html', message='') @app.route('/register', methods=['POST']) def register_post(): email",
"the key in the session if 'logged_in' in session: email",
"success: error_message = \"Product Update Failed\" # if there is",
"see if the user has logged in. If login, it",
"= user.email \"\"\" Session is an object that contains sharing",
"new_description, title) error_message = None if not success: error_message =",
"message=error_message, pName=request.args.get('pName')) else: return redirect('/', code=303) @app.route('/createproduct', methods=['Get']) def create_product_get():",
"price = int(request.form.get('price')) title = request.form.get('title') description = request.form.get('description') error_message",
"else: return redirect('/login') @app.route('/updateuser', methods=['Get']) def update_user_get(): return render_template('updateuser.html', message='Please",
"redirect('/', code=303) @app.route('/logout') def logout(): if 'logged_in' in session: session.pop('logged_in',",
"register_get(): # templates are stored in the templates folder return",
"there is any error messages when registering new user #",
"If login, it will call the inner_function with the logged",
"to the login page return redirect('/login') # return the wrapped",
"user's browser and the end server. Typically it is packed",
"user attributes success = update_product(new_price, new_title, new_description, title) error_message =",
"not success: error_message = \"Placing Order Failed\" # if there",
"user: # if the user exists, call the inner_function #",
"api to update the user attributes success = create_product(price, title,",
"\"-\" + current_date[0:2]) price = int(request.form.get('price')) title = request.form.get('title') description",
"do not match\" else: # use backend api to register",
"= get_transaction(user.email) return render_template('index.html', user=user, owned_products=user_products, orders=products) @app.route('/register', methods=['GET']) def",
"today = date.today() current_date = today.strftime(\"%d/%m/%Y\") last_modified_date = (current_date[6:10] +",
"below:\", pTitle=request.args.get('pTitle'), pPrice=request.args.get('pPrice')) @app.route('/placeorder', methods=['POST']) def place_order_post(): new_owner = session['logged_in']",
"@app.route('/createproduct', methods=['POST']) def create_product_post(): # retrieves current logged in user's",
"redirect('/login') else: # else, redirect to the login page return",
"title = request.form.get('title') # use backend api to update the",
"= session['logged_in'] today = date.today() current_date = today.strftime(\"%d/%m/%Y\") last_modified_date =",
"Failed\" # if there is any error messages when creating",
"@app.route('/login', methods=['GET']) def login_get(): return render_template('login.html', message='Please login') @app.route('/login', methods=['POST'])",
"code=303) @app.route('/createproduct', methods=['Get']) def create_product_get(): return render_template('createproduct.html', message='Please enter product",
"import app def authenticate(inner_function): \"\"\" :param inner_function: any python function",
"= session['logged_in'] product_title = request.args.get('pTitle') # use backend api to",
"user owns user_products = get_products(user.email) # gets list of user",
"the session, so we can tell if the client has",
"retrieves current logged in user's email user_email = session['logged_in'] name",
"success = place_order(new_owner, product_title) error_message = None if not success:",
"= int(request.form.get('new_price')) new_title = request.form.get('new_title') new_description = request.form.get('new_description') title =",
"Update Failed\" # if there is any error messages when",
"user's email owner_email = session['logged_in'] today = date.today() current_date =",
"the login page return redirect('/login') # return the wrapped version",
"below:') @app.route('/createproduct', methods=['POST']) def create_product_post(): # retrieves current logged in",
"current session to see if the user has logged in.",
"@app.route('/createproduct', methods=['Get']) def create_product_get(): return render_template('createproduct.html', message='Please enter product info",
"session['logged_in'] name = request.form.get('name') shipping_address = request.form.get('shippingaddress') postal_code = request.form.get('postalcode')",
"product order success = place_order(new_owner, product_title) error_message = None if",
"shipping_address, postal_code) if not success: error_message = \"Updating of User",
"attributes success = update_product(new_price, new_title, new_description, title) error_message = None",
"messages when creating a product # at the backend, go",
"if not success: error_message = \"Product Creation Failed.\" # if",
"attributes success = update_user(user_email, name, shipping_address, postal_code) if not success:",
"methods=['POST']) def update_product_post(): new_price = int(request.form.get('new_price')) new_title = request.form.get('new_title') new_description",
"new_price = int(request.form.get('new_price')) new_title = request.form.get('new_title') new_description = request.form.get('new_description') title",
"+ \"-\" + current_date[0:2]) price = int(request.form.get('price')) title = request.form.get('title')",
"def logout(): if 'logged_in' in session: session.pop('logged_in', None) return redirect('/')",
"= \"Product Creation Failed.\" # if there is any error",
"= \"Product Update Failed\" # if there is any error",
"request.form.get('email') password = request.form.get('password') user = login(email, password) if user:",
"backend api to update the user attributes success = update_product(new_price,",
"@app.route('/listings', methods=['GET']) def available_products_get(): # retrieves current logged in user's",
"'logged_in' in session: email = session['logged_in'] try: user = User.query.filter_by(email=email).one_or_none()",
"\"Product Update Failed\" # if there is any error messages",
"in the session if 'logged_in' in session: email = session['logged_in']",
"to force a 'GET' request return redirect('/', code=303) else: return",
"def wrapped_inner(): # check did we store the key in",
"the inner_function # with user as parameter return inner_function(user) except",
"render_template('register.html', message='') @app.route('/register', methods=['POST']) def register_post(): email = request.form.get('email') name",
"templates are stored in the templates folder return render_template('register.html', message='')",
"sharing information between a user's browser and the end server.",
"register page. if error_message: return render_template('register.html', message=error_message) else: return redirect('/login')",
"# if there is any error messages when creating a",
"wrapped_inner @app.route('/login', methods=['GET']) def login_get(): return render_template('login.html', message='Please login') @app.route('/login',",
"return render_template('available_products.html', available_products=products) @app.route('/placeorder', methods=['GET']) def place_order_get(): return render_template('placeorder.html', message=\"Please",
"api to update the user attributes success = update_product(new_price, new_title,",
"in user's email owner_email = session['logged_in'] today = date.today() current_date",
"if there is any error messages when registering new user",
"session if 'logged_in' in session: email = session['logged_in'] try: user",
"# retrieves current logged in user's email owner_email = session['logged_in']",
"in session: email = session['logged_in'] try: user = User.query.filter_by(email=email).one_or_none() if",
"at the backend, go back to the create product page.",
"# gets a list of products that the logged in",
"any error messages when creating a product # at the",
"pTitle=request.args.get('pTitle'), pPrice=request.args.get('pPrice')) @app.route('/placeorder', methods=['POST']) def place_order_post(): new_owner = session['logged_in'] product_title",
"+ \"-\" + current_date[3:5] + \"-\" + current_date[0:2]) price =",
"retrieves current logged in user's email owner_email = session['logged_in'] today",
"error_message = None if password != <PASSWORD>: error_message = \"The",
"303 is to force a 'GET' request return redirect('/', code=303)",
"the user exists, call the inner_function # with user as",
"# use backend api to update the user attributes success",
"cookies. They will be past along between every request the",
"stored in the browser cookies. They will be past along",
"product # at the backend, go back to the available",
"error_message: return render_template('available_products.html', message=error_message) else: return redirect('/', code=303) @app.route('/logout') def",
"be past along between every request the browser made to",
"import * from datetime import date from qbay import app"
] |
[
"Default to False TODO: maybe configuration later representation[\"is_disabled\"] = False",
"allowed silent timeperiod bsp = preferences.BikeSharePreferences if bsp.gbfs_hide_bikes_after_location_report_silence: available_bikes =",
"to_representation(self, instance): representation = super().to_representation(instance) if ( instance.location is not",
"VehicleType.PropulsionType.HUMAN ): representation.pop(\"current_range_meters\") # Default to False TODO: maybe configuration",
"return representation class GbfsStationInformationSerializer(serializers.HyperlinkedModelSerializer): name = serializers.CharField(source=\"station_name\", read_only=True) capacity =",
"= status representation[\"is_renting\"] = status representation[\"is_returning\"] = status return representation",
"\"combustion\", }, ) def to_representation(self, instance): data = super(GbfsVehicleTypeSerializer, self).to_representation(instance)",
"a motor the field is required if instance.propulsion_type == VehicleType.PropulsionType.HUMAN:",
"is not None: pos = public_geolocation.geo if pos and pos.x",
"station_id = serializers.CharField(source=\"id\", read_only=True) vehicles = serializers.SerializerMethodField() def get_vehicles(self, obj):",
"is None: return None representation.pop(\"lat\") representation.pop(\"lon\") return representation class GbfsStationInformationSerializer(serializers.HyperlinkedModelSerializer):",
"\"moped\", VehicleType.FormFactor.OTHER: \"other\", }, ) propulsion_type = EnumFieldSerializer( read_only=True, mapping={",
"preferences from rest_framework import fields, serializers from bikesharing.models import Bike,",
"for vehicle in representation[\"vehicles\"] ) else: # if no bike",
"last bike removed # but it is not so easy",
"no bike is at the station, last_report is the current",
"vehicle has a motor the field is required if instance.propulsion_type",
"obj representation[\"vehicles\"] = list( map(drop_last_reported, representation[\"vehicles\"]) ) status = (instance.status",
"Station.Status.ACTIVE) or False representation[\"is_installed\"] = status representation[\"is_renting\"] = status representation[\"is_returning\"]",
"None: return None representation.pop(\"lat\") representation.pop(\"lon\") return representation class GbfsStationInformationSerializer(serializers.HyperlinkedModelSerializer): name",
"pos.y: representation[\"lat\"] = pos.y representation[\"lon\"] = pos.x return representation #",
"\"bicycle\", VehicleType.FormFactor.ESCOOTER: \"scooter\", VehicleType.FormFactor.CAR: \"car\", VehicleType.FormFactor.MOPED: \"moped\", VehicleType.FormFactor.OTHER: \"other\", },",
"to False TODO: maybe configuration later representation[\"is_disabled\"] = False public_geolocation",
"where time report # is older than configure allowed silent",
"= serializers.SerializerMethodField() def get_vehicles(self, obj): # if configured filter vehicles,",
"representation[\"is_disabled\"] = False public_geolocation = instance.public_geolocation() if public_geolocation is not",
"\"last_reported\", ) def to_representation(self, instance): representation = super().to_representation(instance) # defined",
"False TODO: maybe configuration later representation[\"is_reserved\"] = False # Default",
"\"capacity\", \"station_id\", ) def to_representation(self, instance): representation = super().to_representation(instance) if",
"fields = ( \"bike_id\", \"vehicle_type_id\", \"current_range_meters\", \"last_reported\", ) def to_representation(self,",
"= Bike fields = ( \"bike_id\", \"vehicle_type_id\", \"current_range_meters\", \"last_reported\", )",
"= public_geolocation.geo if pos and pos.x and pos.y: representation[\"lat\"] =",
"required if instance.propulsion_type == VehicleType.PropulsionType.HUMAN: data.pop(\"max_range_meters\") return data class Meta:",
"False TODO: maybe configuration later representation[\"is_disabled\"] = False public_geolocation =",
"vehicle_type_id = serializers.CharField(source=\"id\", read_only=True) form_factor = EnumFieldSerializer( read_only=True, mapping={ VehicleType.FormFactor.BIKE:",
"status representation[\"is_returning\"] = status return representation class GbfsVehicleTypeSerializer(serializers.HyperlinkedModelSerializer): vehicle_type_id =",
"# but it is not so easy to implement representation[\"last_reported\"]",
"> 0: representation[\"last_reported\"] = max( ( vehicle[\"last_reported\"] if vehicle[\"last_reported\"] is",
"def to_representation(self, instance): representation = super().to_representation(instance) if ( instance.location is",
"None representation.pop(\"lat\") representation.pop(\"lon\") return representation class GbfsStationInformationSerializer(serializers.HyperlinkedModelSerializer): name = serializers.CharField(source=\"station_name\",",
"serializers.CharField(source=\"id\", read_only=True) vehicles = serializers.SerializerMethodField() def get_vehicles(self, obj): # if",
"= serializers.IntegerField(source=\"max_bikes\", read_only=True) station_id = serializers.CharField(source=\"id\", read_only=True) class Meta: model",
"is required if instance.propulsion_type == VehicleType.PropulsionType.HUMAN: data.pop(\"max_range_meters\") return data class",
"if bsp.gbfs_hide_bikes_after_location_report_silence: available_bikes = obj.bike_set.filter( availability_status=Bike.Availability.AVAILABLE, last_reported__gte=now() - timedelta(hours=bsp.gbfs_hide_bikes_after_location_report_hours), )",
"list(filter(lambda val: val is not None, vehicles)) class Meta: model",
"instance.location.x and instance.location.y ): representation[\"lat\"] = instance.location.y representation[\"lon\"] = instance.location.x",
"EnumFieldSerializer( read_only=True, mapping={ VehicleType.PropulsionType.HUMAN: \"human\", VehicleType.PropulsionType.ELECTRIC_ASSIST: \"electric_assist\", VehicleType.PropulsionType.ELECTRIC: \"electric\", VehicleType.PropulsionType.COMBUSTION:",
"= super().to_representation(instance) representation[\"num_bikes_available\"] = len(representation[\"vehicles\"]) representation[\"num_docks_available\"] = ( instance.max_bikes -",
"TODO: maybe configuration later representation[\"is_disabled\"] = False public_geolocation = instance.public_geolocation()",
"representation class GbfsStationInformationSerializer(serializers.HyperlinkedModelSerializer): name = serializers.CharField(source=\"station_name\", read_only=True) capacity = serializers.IntegerField(source=\"max_bikes\",",
"GbfsFreeBikeStatusSerializer(serializers.HyperlinkedModelSerializer): bike_id = serializers.CharField(source=\"non_static_bike_uuid\", read_only=True) vehicle_type_id = serializers.CharField(read_only=True) last_reported =",
"- timedelta(hours=bsp.gbfs_hide_bikes_after_location_report_hours), ) else: available_bikes = obj.bike_set.filter( availability_status=Bike.Availability.AVAILABLE ) vehicles",
"return None representation.pop(\"lat\") representation.pop(\"lon\") return representation class GbfsStationInformationSerializer(serializers.HyperlinkedModelSerializer): name =",
"read_only=True) station_id = serializers.CharField(source=\"id\", read_only=True) class Meta: model = Station",
"availability_status=Bike.Availability.AVAILABLE, last_reported__gte=now() - timedelta(hours=bsp.gbfs_hide_bikes_after_location_report_hours), ) else: available_bikes = obj.bike_set.filter( availability_status=Bike.Availability.AVAILABLE",
"representation[\"vehicles\"] ) else: # if no bike is at the",
"many=True).data return list(filter(lambda val: val is not None, vehicles)) class",
"bike is at the station, last_report is the current time",
"to_representation(self, instance): representation = super().to_representation(instance) if representation is None: return",
"= instance.location.y representation[\"lon\"] = instance.location.x return representation class GbfsStationStatusSerializer(serializers.HyperlinkedModelSerializer): station_id",
"not None and instance.vehicle_type.propulsion_type == VehicleType.PropulsionType.HUMAN ): representation.pop(\"current_range_meters\") # Default",
"if no bike is at the station, last_report is the",
"= preferences.BikeSharePreferences if bsp.gbfs_hide_bikes_after_location_report_silence: available_bikes = obj.bike_set.filter( availability_status=Bike.Availability.AVAILABLE, last_reported__gte=now() -",
"instance): representation = super().to_representation(instance) if representation is None: return None",
"representation = super().to_representation(instance) representation[\"num_bikes_available\"] = len(representation[\"vehicles\"]) representation[\"num_docks_available\"] = ( instance.max_bikes",
"VehicleType.PropulsionType.ELECTRIC: \"electric\", VehicleType.PropulsionType.COMBUSTION: \"combustion\", }, ) def to_representation(self, instance): data",
"representation[\"num_bikes_available\"] ) if representation[\"num_bikes_available\"] > 0: representation[\"last_reported\"] = max( (",
"of the last bike removed # but it is not",
"bikesharing.models import Bike, Station, VehicleType from cykel.serializers import EnumFieldSerializer class",
"if ( instance.location is not None and instance.location.x and instance.location.y",
"= super().to_representation(instance) if ( instance.location is not None and instance.location.x",
"representation[\"is_renting\"] = status representation[\"is_returning\"] = status return representation class GbfsVehicleTypeSerializer(serializers.HyperlinkedModelSerializer):",
"): representation[\"lat\"] = instance.location.y representation[\"lon\"] = instance.location.x return representation class",
"Bike fields = ( \"bike_id\", \"vehicle_type_id\", \"current_range_meters\", \"last_reported\", ) def",
"rest_framework import fields, serializers from bikesharing.models import Bike, Station, VehicleType",
"but it is not so easy to implement representation[\"last_reported\"] =",
"if representation is None: return None representation.pop(\"lat\") representation.pop(\"lon\") return representation",
"return representation class GbfsStationStatusSerializer(serializers.HyperlinkedModelSerializer): station_id = serializers.CharField(source=\"id\", read_only=True) vehicles =",
"the field is required if instance.propulsion_type == VehicleType.PropulsionType.HUMAN: data.pop(\"max_range_meters\") return",
"\"vehicles\", ) def to_representation(self, instance): representation = super().to_representation(instance) representation[\"num_bikes_available\"] =",
"required if ( instance.vehicle_type is not None and instance.vehicle_type.propulsion_type ==",
"vehicle[\"last_reported\"] if vehicle[\"last_reported\"] is not None else 0 ) for",
"serializers from bikesharing.models import Bike, Station, VehicleType from cykel.serializers import",
"= False # Default to False TODO: maybe configuration later",
"\"station_id\", \"vehicles\", ) def to_representation(self, instance): representation = super().to_representation(instance) representation[\"num_bikes_available\"]",
"def to_representation(self, instance): representation = super().to_representation(instance) # defined by GBFS",
"fields = ( \"name\", \"capacity\", \"station_id\", ) def to_representation(self, instance):",
"field is required if ( instance.vehicle_type is not None and",
"# Default to False TODO: maybe configuration later representation[\"is_reserved\"] =",
"current time # not sure if this is the intended",
"of the field # or it should be the timestamp",
"model = Station fields = ( \"station_id\", \"vehicles\", ) def",
"defined by GBFS 2.1: Only if the vehicle has a",
"( instance.location is not None and instance.location.x and instance.location.y ):",
"\"scooter\", VehicleType.FormFactor.CAR: \"car\", VehicleType.FormFactor.MOPED: \"moped\", VehicleType.FormFactor.OTHER: \"other\", }, ) propulsion_type",
"= (instance.status == Station.Status.ACTIVE) or False representation[\"is_installed\"] = status representation[\"is_renting\"]",
"Meta: model = VehicleType fields = ( \"vehicle_type_id\", \"form_factor\", \"propulsion_type\",",
") propulsion_type = EnumFieldSerializer( read_only=True, mapping={ VehicleType.PropulsionType.HUMAN: \"human\", VehicleType.PropulsionType.ELECTRIC_ASSIST: \"electric_assist\",",
"sure if this is the intended behavior of the field",
"class Meta: model = Station fields = ( \"station_id\", \"vehicles\",",
"int(now().timestamp()) def drop_last_reported(obj): obj.pop(\"last_reported\") return obj representation[\"vehicles\"] = list( map(drop_last_reported,",
"Station fields = ( \"station_id\", \"vehicles\", ) def to_representation(self, instance):",
"behavior of the field # or it should be the",
"map(drop_last_reported, representation[\"vehicles\"]) ) status = (instance.status == Station.Status.ACTIVE) or False",
"= super().to_representation(instance) # defined by GBFS 2.1: Only if the",
"instance.max_bikes - representation[\"num_bikes_available\"] ) if representation[\"num_bikes_available\"] > 0: representation[\"last_reported\"] =",
"# is older than configure allowed silent timeperiod bsp =",
"to_representation(self, instance): representation = super().to_representation(instance) representation[\"num_bikes_available\"] = len(representation[\"vehicles\"]) representation[\"num_docks_available\"] =",
"availability_status=Bike.Availability.AVAILABLE ) vehicles = GbfsVehicleOnStationSerializer(available_bikes, many=True).data return list(filter(lambda val: val",
"the last bike removed # but it is not so",
"representation[\"lon\"] = pos.x return representation # only return bikes with",
"serializers.SerializerMethodField() def get_vehicles(self, obj): # if configured filter vehicles, where",
"None and instance.vehicle_type.propulsion_type == VehicleType.PropulsionType.HUMAN ): representation.pop(\"current_range_meters\") # Default to",
"EnumFieldSerializer class TimestampSerializer(fields.CharField): def to_representation(self, value): return value.timestamp() class GbfsFreeBikeStatusSerializer(serializers.HyperlinkedModelSerializer):",
"(instance.status == Station.Status.ACTIVE) or False representation[\"is_installed\"] = status representation[\"is_renting\"] =",
"class GbfsVehicleTypeSerializer(serializers.HyperlinkedModelSerializer): vehicle_type_id = serializers.CharField(source=\"id\", read_only=True) form_factor = EnumFieldSerializer( read_only=True,",
"status return representation class GbfsVehicleTypeSerializer(serializers.HyperlinkedModelSerializer): vehicle_type_id = serializers.CharField(source=\"id\", read_only=True) form_factor",
"= TimestampSerializer(read_only=True) class Meta: model = Bike fields = (",
"instance.location.y representation[\"lon\"] = instance.location.x return representation class GbfsStationStatusSerializer(serializers.HyperlinkedModelSerializer): station_id =",
"get_vehicles(self, obj): # if configured filter vehicles, where time report",
"time # not sure if this is the intended behavior",
"vehicle[\"last_reported\"] is not None else 0 ) for vehicle in",
"instance): data = super(GbfsVehicleTypeSerializer, self).to_representation(instance) # defined by GBFS 2.1:",
"= status representation[\"is_returning\"] = status return representation class GbfsVehicleTypeSerializer(serializers.HyperlinkedModelSerializer): vehicle_type_id",
"public_geolocation = instance.public_geolocation() if public_geolocation is not None: pos =",
"to_representation(self, instance): data = super(GbfsVehicleTypeSerializer, self).to_representation(instance) # defined by GBFS",
"self).to_representation(instance) # defined by GBFS 2.1: Only if the vehicle",
"super(GbfsVehicleTypeSerializer, self).to_representation(instance) # defined by GBFS 2.1: Only if the",
"# defined by GBFS 2.1: Only if the vehicle has",
"maybe configuration later representation[\"is_disabled\"] = False public_geolocation = instance.public_geolocation() if",
"bsp = preferences.BikeSharePreferences if bsp.gbfs_hide_bikes_after_location_report_silence: available_bikes = obj.bike_set.filter( availability_status=Bike.Availability.AVAILABLE, last_reported__gte=now()",
"be the timestamp of the last bike removed # but",
"is the intended behavior of the field # or it",
"from datetime import timedelta from django.utils.timezone import now from preferences",
"0: representation[\"last_reported\"] = max( ( vehicle[\"last_reported\"] if vehicle[\"last_reported\"] is not",
"preferences.BikeSharePreferences if bsp.gbfs_hide_bikes_after_location_report_silence: available_bikes = obj.bike_set.filter( availability_status=Bike.Availability.AVAILABLE, last_reported__gte=now() - timedelta(hours=bsp.gbfs_hide_bikes_after_location_report_hours),",
"( instance.vehicle_type is not None and instance.vehicle_type.propulsion_type == VehicleType.PropulsionType.HUMAN ):",
"is not None and instance.location.x and instance.location.y ): representation[\"lat\"] =",
"def to_representation(self, instance): data = super(GbfsVehicleTypeSerializer, self).to_representation(instance) # defined by",
"import preferences from rest_framework import fields, serializers from bikesharing.models import",
"= pos.y representation[\"lon\"] = pos.x return representation # only return",
"is not None, vehicles)) class Meta: model = Station fields",
"bike_id = serializers.CharField(source=\"non_static_bike_uuid\", read_only=True) vehicle_type_id = serializers.CharField(read_only=True) last_reported = TimestampSerializer(read_only=True)",
"vehicles)) class Meta: model = Station fields = ( \"station_id\",",
"data class Meta: model = VehicleType fields = ( \"vehicle_type_id\",",
"( vehicle[\"last_reported\"] if vehicle[\"last_reported\"] is not None else 0 )",
"\"bike_id\", \"vehicle_type_id\", \"current_range_meters\", \"last_reported\", ) def to_representation(self, instance): representation =",
"GBFS 2.1: Only if the vehicle has a motor the",
"maybe configuration later representation[\"is_reserved\"] = False # Default to False",
"False representation[\"is_installed\"] = status representation[\"is_renting\"] = status representation[\"is_returning\"] = status",
"representation[\"is_installed\"] = status representation[\"is_renting\"] = status representation[\"is_returning\"] = status return",
"return bikes with public geolocation class GbfsVehicleOnStationSerializer(GbfsFreeBikeStatusSerializer): def to_representation(self, instance):",
"class TimestampSerializer(fields.CharField): def to_representation(self, value): return value.timestamp() class GbfsFreeBikeStatusSerializer(serializers.HyperlinkedModelSerializer): bike_id",
"2.1: Only if the vehicle has a motor the field",
"available_bikes = obj.bike_set.filter( availability_status=Bike.Availability.AVAILABLE ) vehicles = GbfsVehicleOnStationSerializer(available_bikes, many=True).data return",
"serializers.CharField(read_only=True) last_reported = TimestampSerializer(read_only=True) class Meta: model = Bike fields",
") else: # if no bike is at the station,",
"list( map(drop_last_reported, representation[\"vehicles\"]) ) status = (instance.status == Station.Status.ACTIVE) or",
"data = super(GbfsVehicleTypeSerializer, self).to_representation(instance) # defined by GBFS 2.1: Only",
"if public_geolocation is not None: pos = public_geolocation.geo if pos",
"time report # is older than configure allowed silent timeperiod",
"= obj.bike_set.filter( availability_status=Bike.Availability.AVAILABLE ) vehicles = GbfsVehicleOnStationSerializer(available_bikes, many=True).data return list(filter(lambda",
"= serializers.CharField(source=\"non_static_bike_uuid\", read_only=True) vehicle_type_id = serializers.CharField(read_only=True) last_reported = TimestampSerializer(read_only=True) class",
"if the vehicle has a motor the field is required",
"import now from preferences import preferences from rest_framework import fields,",
"representation class GbfsStationStatusSerializer(serializers.HyperlinkedModelSerializer): station_id = serializers.CharField(source=\"id\", read_only=True) vehicles = serializers.SerializerMethodField()",
"instance): representation = super().to_representation(instance) representation[\"num_bikes_available\"] = len(representation[\"vehicles\"]) representation[\"num_docks_available\"] = (",
"class Meta: model = Bike fields = ( \"bike_id\", \"vehicle_type_id\",",
"is older than configure allowed silent timeperiod bsp = preferences.BikeSharePreferences",
"instance.vehicle_type.propulsion_type == VehicleType.PropulsionType.HUMAN ): representation.pop(\"current_range_meters\") # Default to False TODO:",
"GbfsVehicleOnStationSerializer(available_bikes, many=True).data return list(filter(lambda val: val is not None, vehicles))",
"vehicles = GbfsVehicleOnStationSerializer(available_bikes, many=True).data return list(filter(lambda val: val is not",
"= ( \"bike_id\", \"vehicle_type_id\", \"current_range_meters\", \"last_reported\", ) def to_representation(self, instance):",
"Default to False TODO: maybe configuration later representation[\"is_reserved\"] = False",
"\"other\", }, ) propulsion_type = EnumFieldSerializer( read_only=True, mapping={ VehicleType.PropulsionType.HUMAN: \"human\",",
"status representation[\"is_renting\"] = status representation[\"is_returning\"] = status return representation class",
"super().to_representation(instance) # defined by GBFS 2.1: Only if the vehicle",
"= len(representation[\"vehicles\"]) representation[\"num_docks_available\"] = ( instance.max_bikes - representation[\"num_bikes_available\"] ) if",
"def to_representation(self, value): return value.timestamp() class GbfsFreeBikeStatusSerializer(serializers.HyperlinkedModelSerializer): bike_id = serializers.CharField(source=\"non_static_bike_uuid\",",
"the intended behavior of the field # or it should",
"Station, VehicleType from cykel.serializers import EnumFieldSerializer class TimestampSerializer(fields.CharField): def to_representation(self,",
"\"electric_assist\", VehicleType.PropulsionType.ELECTRIC: \"electric\", VehicleType.PropulsionType.COMBUSTION: \"combustion\", }, ) def to_representation(self, instance):",
"timestamp of the last bike removed # but it is",
"last_reported = TimestampSerializer(read_only=True) class Meta: model = Bike fields =",
"and pos.x and pos.y: representation[\"lat\"] = pos.y representation[\"lon\"] = pos.x",
"TODO: maybe configuration later representation[\"is_reserved\"] = False # Default to",
"representation[\"is_reserved\"] = False # Default to False TODO: maybe configuration",
"the timestamp of the last bike removed # but it",
"obj.pop(\"last_reported\") return obj representation[\"vehicles\"] = list( map(drop_last_reported, representation[\"vehicles\"]) ) status",
"instance.propulsion_type == VehicleType.PropulsionType.HUMAN: data.pop(\"max_range_meters\") return data class Meta: model =",
"easy to implement representation[\"last_reported\"] = int(now().timestamp()) def drop_last_reported(obj): obj.pop(\"last_reported\") return",
"serializers.CharField(source=\"id\", read_only=True) form_factor = EnumFieldSerializer( read_only=True, mapping={ VehicleType.FormFactor.BIKE: \"bicycle\", VehicleType.FormFactor.ESCOOTER:",
"from cykel.serializers import EnumFieldSerializer class TimestampSerializer(fields.CharField): def to_representation(self, value): return",
"\"car\", VehicleType.FormFactor.MOPED: \"moped\", VehicleType.FormFactor.OTHER: \"other\", }, ) propulsion_type = EnumFieldSerializer(",
"the field # or it should be the timestamp of",
"representation class GbfsVehicleTypeSerializer(serializers.HyperlinkedModelSerializer): vehicle_type_id = serializers.CharField(source=\"id\", read_only=True) form_factor = EnumFieldSerializer(",
"VehicleType.FormFactor.CAR: \"car\", VehicleType.FormFactor.MOPED: \"moped\", VehicleType.FormFactor.OTHER: \"other\", }, ) propulsion_type =",
"== Station.Status.ACTIVE) or False representation[\"is_installed\"] = status representation[\"is_renting\"] = status",
"by GBFS 2.1: Only if the vehicle has a motor",
"representation[\"num_bikes_available\"] = len(representation[\"vehicles\"]) representation[\"num_docks_available\"] = ( instance.max_bikes - representation[\"num_bikes_available\"] )",
"with public geolocation class GbfsVehicleOnStationSerializer(GbfsFreeBikeStatusSerializer): def to_representation(self, instance): representation =",
"class Meta: model = Station fields = ( \"name\", \"capacity\",",
"serializers.CharField(source=\"id\", read_only=True) class Meta: model = Station fields = (",
"read_only=True, mapping={ VehicleType.PropulsionType.HUMAN: \"human\", VehicleType.PropulsionType.ELECTRIC_ASSIST: \"electric_assist\", VehicleType.PropulsionType.ELECTRIC: \"electric\", VehicleType.PropulsionType.COMBUSTION: \"combustion\",",
"representation = super().to_representation(instance) if ( instance.location is not None and",
"representation # only return bikes with public geolocation class GbfsVehicleOnStationSerializer(GbfsFreeBikeStatusSerializer):",
"= VehicleType fields = ( \"vehicle_type_id\", \"form_factor\", \"propulsion_type\", \"max_range_meters\", \"name\",",
"later representation[\"is_disabled\"] = False public_geolocation = instance.public_geolocation() if public_geolocation is",
"<gh_stars>10-100 from datetime import timedelta from django.utils.timezone import now from",
"return obj representation[\"vehicles\"] = list( map(drop_last_reported, representation[\"vehicles\"]) ) status =",
"the station, last_report is the current time # not sure",
"not None: pos = public_geolocation.geo if pos and pos.x and",
"( \"bike_id\", \"vehicle_type_id\", \"current_range_meters\", \"last_reported\", ) def to_representation(self, instance): representation",
") else: available_bikes = obj.bike_set.filter( availability_status=Bike.Availability.AVAILABLE ) vehicles = GbfsVehicleOnStationSerializer(available_bikes,",
"representation[\"last_reported\"] = max( ( vehicle[\"last_reported\"] if vehicle[\"last_reported\"] is not None",
"has a motor the field is required if instance.propulsion_type ==",
"\"electric\", VehicleType.PropulsionType.COMBUSTION: \"combustion\", }, ) def to_representation(self, instance): data =",
"False public_geolocation = instance.public_geolocation() if public_geolocation is not None: pos",
"fields = ( \"station_id\", \"vehicles\", ) def to_representation(self, instance): representation",
"instance.vehicle_type is not None and instance.vehicle_type.propulsion_type == VehicleType.PropulsionType.HUMAN ): representation.pop(\"current_range_meters\")",
"= max( ( vehicle[\"last_reported\"] if vehicle[\"last_reported\"] is not None else",
"TimestampSerializer(read_only=True) class Meta: model = Bike fields = ( \"bike_id\",",
") def to_representation(self, instance): representation = super().to_representation(instance) if ( instance.location",
"vehicle_type_id = serializers.CharField(read_only=True) last_reported = TimestampSerializer(read_only=True) class Meta: model =",
"\"station_id\", ) def to_representation(self, instance): representation = super().to_representation(instance) if (",
"to_representation(self, instance): representation = super().to_representation(instance) # defined by GBFS 2.1:",
"field # or it should be the timestamp of the",
"# or it should be the timestamp of the last",
"configuration later representation[\"is_disabled\"] = False public_geolocation = instance.public_geolocation() if public_geolocation",
"if pos and pos.x and pos.y: representation[\"lat\"] = pos.y representation[\"lon\"]",
"available_bikes = obj.bike_set.filter( availability_status=Bike.Availability.AVAILABLE, last_reported__gte=now() - timedelta(hours=bsp.gbfs_hide_bikes_after_location_report_hours), ) else: available_bikes",
"= serializers.CharField(source=\"station_name\", read_only=True) capacity = serializers.IntegerField(source=\"max_bikes\", read_only=True) station_id = serializers.CharField(source=\"id\",",
") def to_representation(self, instance): data = super(GbfsVehicleTypeSerializer, self).to_representation(instance) # defined",
"value.timestamp() class GbfsFreeBikeStatusSerializer(serializers.HyperlinkedModelSerializer): bike_id = serializers.CharField(source=\"non_static_bike_uuid\", read_only=True) vehicle_type_id = serializers.CharField(read_only=True)",
"class Meta: model = VehicleType fields = ( \"vehicle_type_id\", \"form_factor\",",
") for vehicle in representation[\"vehicles\"] ) else: # if no",
"else: # if no bike is at the station, last_report",
"): representation.pop(\"current_range_meters\") # Default to False TODO: maybe configuration later",
"vehicles, where time report # is older than configure allowed",
"is not so easy to implement representation[\"last_reported\"] = int(now().timestamp()) def",
"field is required if instance.propulsion_type == VehicleType.PropulsionType.HUMAN: data.pop(\"max_range_meters\") return data",
"None, vehicles)) class Meta: model = Station fields = (",
"GbfsVehicleOnStationSerializer(GbfsFreeBikeStatusSerializer): def to_representation(self, instance): representation = super().to_representation(instance) if representation is",
"def to_representation(self, instance): representation = super().to_representation(instance) representation[\"num_bikes_available\"] = len(representation[\"vehicles\"]) representation[\"num_docks_available\"]",
"serializers.IntegerField(source=\"max_bikes\", read_only=True) station_id = serializers.CharField(source=\"id\", read_only=True) class Meta: model =",
"motor the field is required if instance.propulsion_type == VehicleType.PropulsionType.HUMAN: data.pop(\"max_range_meters\")",
"form_factor = EnumFieldSerializer( read_only=True, mapping={ VehicleType.FormFactor.BIKE: \"bicycle\", VehicleType.FormFactor.ESCOOTER: \"scooter\", VehicleType.FormFactor.CAR:",
"so easy to implement representation[\"last_reported\"] = int(now().timestamp()) def drop_last_reported(obj): obj.pop(\"last_reported\")",
"propulsion_type = EnumFieldSerializer( read_only=True, mapping={ VehicleType.PropulsionType.HUMAN: \"human\", VehicleType.PropulsionType.ELECTRIC_ASSIST: \"electric_assist\", VehicleType.PropulsionType.ELECTRIC:",
"val is not None, vehicles)) class Meta: model = Station",
"VehicleType from cykel.serializers import EnumFieldSerializer class TimestampSerializer(fields.CharField): def to_representation(self, value):",
"= serializers.CharField(read_only=True) last_reported = TimestampSerializer(read_only=True) class Meta: model = Bike",
"read_only=True) capacity = serializers.IntegerField(source=\"max_bikes\", read_only=True) station_id = serializers.CharField(source=\"id\", read_only=True) class",
"implement representation[\"last_reported\"] = int(now().timestamp()) def drop_last_reported(obj): obj.pop(\"last_reported\") return obj representation[\"vehicles\"]",
"model = Bike fields = ( \"bike_id\", \"vehicle_type_id\", \"current_range_meters\", \"last_reported\",",
"None else 0 ) for vehicle in representation[\"vehicles\"] ) else:",
"not so easy to implement representation[\"last_reported\"] = int(now().timestamp()) def drop_last_reported(obj):",
"to implement representation[\"last_reported\"] = int(now().timestamp()) def drop_last_reported(obj): obj.pop(\"last_reported\") return obj",
"instance.location.x return representation class GbfsStationStatusSerializer(serializers.HyperlinkedModelSerializer): station_id = serializers.CharField(source=\"id\", read_only=True) vehicles",
"= serializers.CharField(source=\"id\", read_only=True) vehicles = serializers.SerializerMethodField() def get_vehicles(self, obj): #",
"\"name\", \"capacity\", \"station_id\", ) def to_representation(self, instance): representation = super().to_representation(instance)",
"public geolocation class GbfsVehicleOnStationSerializer(GbfsFreeBikeStatusSerializer): def to_representation(self, instance): representation = super().to_representation(instance)",
"if this is the intended behavior of the field #",
"}, ) propulsion_type = EnumFieldSerializer( read_only=True, mapping={ VehicleType.PropulsionType.HUMAN: \"human\", VehicleType.PropulsionType.ELECTRIC_ASSIST:",
"representation[\"lon\"] = instance.location.x return representation class GbfsStationStatusSerializer(serializers.HyperlinkedModelSerializer): station_id = serializers.CharField(source=\"id\",",
"import Bike, Station, VehicleType from cykel.serializers import EnumFieldSerializer class TimestampSerializer(fields.CharField):",
"VehicleType.FormFactor.MOPED: \"moped\", VehicleType.FormFactor.OTHER: \"other\", }, ) propulsion_type = EnumFieldSerializer( read_only=True,",
"configure allowed silent timeperiod bsp = preferences.BikeSharePreferences if bsp.gbfs_hide_bikes_after_location_report_silence: available_bikes",
"# only return bikes with public geolocation class GbfsVehicleOnStationSerializer(GbfsFreeBikeStatusSerializer): def",
"from preferences import preferences from rest_framework import fields, serializers from",
"class GbfsStationInformationSerializer(serializers.HyperlinkedModelSerializer): name = serializers.CharField(source=\"station_name\", read_only=True) capacity = serializers.IntegerField(source=\"max_bikes\", read_only=True)",
"representation.pop(\"lat\") representation.pop(\"lon\") return representation class GbfsStationInformationSerializer(serializers.HyperlinkedModelSerializer): name = serializers.CharField(source=\"station_name\", read_only=True)",
"representation[\"is_returning\"] = status return representation class GbfsVehicleTypeSerializer(serializers.HyperlinkedModelSerializer): vehicle_type_id = serializers.CharField(source=\"id\",",
"# not sure if this is the intended behavior of",
"status = (instance.status == Station.Status.ACTIVE) or False representation[\"is_installed\"] = status",
"None and instance.location.x and instance.location.y ): representation[\"lat\"] = instance.location.y representation[\"lon\"]",
"it is not so easy to implement representation[\"last_reported\"] = int(now().timestamp())",
"instance.location.y ): representation[\"lat\"] = instance.location.y representation[\"lon\"] = instance.location.x return representation",
"( instance.max_bikes - representation[\"num_bikes_available\"] ) if representation[\"num_bikes_available\"] > 0: representation[\"last_reported\"]",
"VehicleType.PropulsionType.ELECTRIC_ASSIST: \"electric_assist\", VehicleType.PropulsionType.ELECTRIC: \"electric\", VehicleType.PropulsionType.COMBUSTION: \"combustion\", }, ) def to_representation(self,",
"super().to_representation(instance) representation[\"num_bikes_available\"] = len(representation[\"vehicles\"]) representation[\"num_docks_available\"] = ( instance.max_bikes - representation[\"num_bikes_available\"]",
"is required if ( instance.vehicle_type is not None and instance.vehicle_type.propulsion_type",
"pos = public_geolocation.geo if pos and pos.x and pos.y: representation[\"lat\"]",
"VehicleType.PropulsionType.HUMAN: data.pop(\"max_range_meters\") return data class Meta: model = VehicleType fields",
"Meta: model = Station fields = ( \"station_id\", \"vehicles\", )",
"last_report is the current time # not sure if this",
"representation.pop(\"current_range_meters\") # Default to False TODO: maybe configuration later representation[\"is_reserved\"]",
"= super(GbfsVehicleTypeSerializer, self).to_representation(instance) # defined by GBFS 2.1: Only if",
"public_geolocation is not None: pos = public_geolocation.geo if pos and",
"model = Station fields = ( \"name\", \"capacity\", \"station_id\", )",
"EnumFieldSerializer( read_only=True, mapping={ VehicleType.FormFactor.BIKE: \"bicycle\", VehicleType.FormFactor.ESCOOTER: \"scooter\", VehicleType.FormFactor.CAR: \"car\", VehicleType.FormFactor.MOPED:",
"preferences import preferences from rest_framework import fields, serializers from bikesharing.models",
"\"human\", VehicleType.PropulsionType.ELECTRIC_ASSIST: \"electric_assist\", VehicleType.PropulsionType.ELECTRIC: \"electric\", VehicleType.PropulsionType.COMBUSTION: \"combustion\", }, ) def",
"( \"station_id\", \"vehicles\", ) def to_representation(self, instance): representation = super().to_representation(instance)",
"not sure if this is the intended behavior of the",
"instance): representation = super().to_representation(instance) if ( instance.location is not None",
"import fields, serializers from bikesharing.models import Bike, Station, VehicleType from",
"\"current_range_meters\", \"last_reported\", ) def to_representation(self, instance): representation = super().to_representation(instance) #",
"is at the station, last_report is the current time #",
"representation[\"last_reported\"] = int(now().timestamp()) def drop_last_reported(obj): obj.pop(\"last_reported\") return obj representation[\"vehicles\"] =",
"station, last_report is the current time # not sure if",
"= pos.x return representation # only return bikes with public",
"pos.x return representation # only return bikes with public geolocation",
"last_reported__gte=now() - timedelta(hours=bsp.gbfs_hide_bikes_after_location_report_hours), ) else: available_bikes = obj.bike_set.filter( availability_status=Bike.Availability.AVAILABLE )",
"# if configured filter vehicles, where time report # is",
"class GbfsStationStatusSerializer(serializers.HyperlinkedModelSerializer): station_id = serializers.CharField(source=\"id\", read_only=True) vehicles = serializers.SerializerMethodField() def",
"def drop_last_reported(obj): obj.pop(\"last_reported\") return obj representation[\"vehicles\"] = list( map(drop_last_reported, representation[\"vehicles\"])",
"later representation[\"is_reserved\"] = False # Default to False TODO: maybe",
"pos and pos.x and pos.y: representation[\"lat\"] = pos.y representation[\"lon\"] =",
"representation[\"lat\"] = pos.y representation[\"lon\"] = pos.x return representation # only",
"if vehicle[\"last_reported\"] is not None else 0 ) for vehicle",
"bike removed # but it is not so easy to",
"= serializers.CharField(source=\"id\", read_only=True) form_factor = EnumFieldSerializer( read_only=True, mapping={ VehicleType.FormFactor.BIKE: \"bicycle\",",
"else: available_bikes = obj.bike_set.filter( availability_status=Bike.Availability.AVAILABLE ) vehicles = GbfsVehicleOnStationSerializer(available_bikes, many=True).data",
"data.pop(\"max_range_meters\") return data class Meta: model = VehicleType fields =",
"== VehicleType.PropulsionType.HUMAN ): representation.pop(\"current_range_meters\") # Default to False TODO: maybe",
"read_only=True) vehicles = serializers.SerializerMethodField() def get_vehicles(self, obj): # if configured",
"= GbfsVehicleOnStationSerializer(available_bikes, many=True).data return list(filter(lambda val: val is not None,",
"vehicles = serializers.SerializerMethodField() def get_vehicles(self, obj): # if configured filter",
") vehicles = GbfsVehicleOnStationSerializer(available_bikes, many=True).data return list(filter(lambda val: val is",
"super().to_representation(instance) if ( instance.location is not None and instance.location.x and",
"or False representation[\"is_installed\"] = status representation[\"is_renting\"] = status representation[\"is_returning\"] =",
"class GbfsFreeBikeStatusSerializer(serializers.HyperlinkedModelSerializer): bike_id = serializers.CharField(source=\"non_static_bike_uuid\", read_only=True) vehicle_type_id = serializers.CharField(read_only=True) last_reported",
"- representation[\"num_bikes_available\"] ) if representation[\"num_bikes_available\"] > 0: representation[\"last_reported\"] = max(",
"model = VehicleType fields = ( \"vehicle_type_id\", \"form_factor\", \"propulsion_type\", \"max_range_meters\",",
"False # Default to False TODO: maybe configuration later representation[\"is_disabled\"]",
"if instance.propulsion_type == VehicleType.PropulsionType.HUMAN: data.pop(\"max_range_meters\") return data class Meta: model",
"the vehicle has a motor the field is required if",
"= int(now().timestamp()) def drop_last_reported(obj): obj.pop(\"last_reported\") return obj representation[\"vehicles\"] = list(",
"name = serializers.CharField(source=\"station_name\", read_only=True) capacity = serializers.IntegerField(source=\"max_bikes\", read_only=True) station_id =",
"Bike, Station, VehicleType from cykel.serializers import EnumFieldSerializer class TimestampSerializer(fields.CharField): def",
") def to_representation(self, instance): representation = super().to_representation(instance) # defined by",
"not None, vehicles)) class Meta: model = Station fields =",
"value): return value.timestamp() class GbfsFreeBikeStatusSerializer(serializers.HyperlinkedModelSerializer): bike_id = serializers.CharField(source=\"non_static_bike_uuid\", read_only=True) vehicle_type_id",
"has a motor the field is required if ( instance.vehicle_type",
"older than configure allowed silent timeperiod bsp = preferences.BikeSharePreferences if",
"vehicle has a motor the field is required if (",
"from django.utils.timezone import now from preferences import preferences from rest_framework",
"val: val is not None, vehicles)) class Meta: model =",
"max( ( vehicle[\"last_reported\"] if vehicle[\"last_reported\"] is not None else 0",
"= Station fields = ( \"name\", \"capacity\", \"station_id\", ) def",
"public_geolocation.geo if pos and pos.x and pos.y: representation[\"lat\"] = pos.y",
"the current time # not sure if this is the",
"cykel.serializers import EnumFieldSerializer class TimestampSerializer(fields.CharField): def to_representation(self, value): return value.timestamp()",
"TimestampSerializer(fields.CharField): def to_representation(self, value): return value.timestamp() class GbfsFreeBikeStatusSerializer(serializers.HyperlinkedModelSerializer): bike_id =",
"Station fields = ( \"name\", \"capacity\", \"station_id\", ) def to_representation(self,",
"pos.y representation[\"lon\"] = pos.x return representation # only return bikes",
"serializers.CharField(source=\"station_name\", read_only=True) capacity = serializers.IntegerField(source=\"max_bikes\", read_only=True) station_id = serializers.CharField(source=\"id\", read_only=True)",
"now from preferences import preferences from rest_framework import fields, serializers",
"def get_vehicles(self, obj): # if configured filter vehicles, where time",
"it should be the timestamp of the last bike removed",
"django.utils.timezone import now from preferences import preferences from rest_framework import",
"obj): # if configured filter vehicles, where time report #",
"timeperiod bsp = preferences.BikeSharePreferences if bsp.gbfs_hide_bikes_after_location_report_silence: available_bikes = obj.bike_set.filter( availability_status=Bike.Availability.AVAILABLE,",
"return list(filter(lambda val: val is not None, vehicles)) class Meta:",
"mapping={ VehicleType.PropulsionType.HUMAN: \"human\", VehicleType.PropulsionType.ELECTRIC_ASSIST: \"electric_assist\", VehicleType.PropulsionType.ELECTRIC: \"electric\", VehicleType.PropulsionType.COMBUSTION: \"combustion\", },",
"only return bikes with public geolocation class GbfsVehicleOnStationSerializer(GbfsFreeBikeStatusSerializer): def to_representation(self,",
") def to_representation(self, instance): representation = super().to_representation(instance) representation[\"num_bikes_available\"] = len(representation[\"vehicles\"])",
"obj.bike_set.filter( availability_status=Bike.Availability.AVAILABLE ) vehicles = GbfsVehicleOnStationSerializer(available_bikes, many=True).data return list(filter(lambda val:",
"filter vehicles, where time report # is older than configure",
"read_only=True) class Meta: model = Station fields = ( \"name\",",
"is not None else 0 ) for vehicle in representation[\"vehicles\"]",
"}, ) def to_representation(self, instance): data = super(GbfsVehicleTypeSerializer, self).to_representation(instance) #",
"is not None and instance.vehicle_type.propulsion_type == VehicleType.PropulsionType.HUMAN ): representation.pop(\"current_range_meters\") #",
"geolocation class GbfsVehicleOnStationSerializer(GbfsFreeBikeStatusSerializer): def to_representation(self, instance): representation = super().to_representation(instance) if",
"representation = super().to_representation(instance) # defined by GBFS 2.1: Only if",
"and instance.vehicle_type.propulsion_type == VehicleType.PropulsionType.HUMAN ): representation.pop(\"current_range_meters\") # Default to False",
"= list( map(drop_last_reported, representation[\"vehicles\"]) ) status = (instance.status == Station.Status.ACTIVE)",
"representation[\"vehicles\"] = list( map(drop_last_reported, representation[\"vehicles\"]) ) status = (instance.status ==",
"representation[\"vehicles\"]) ) status = (instance.status == Station.Status.ACTIVE) or False representation[\"is_installed\"]",
"timedelta(hours=bsp.gbfs_hide_bikes_after_location_report_hours), ) else: available_bikes = obj.bike_set.filter( availability_status=Bike.Availability.AVAILABLE ) vehicles =",
"from rest_framework import fields, serializers from bikesharing.models import Bike, Station,",
"and instance.location.y ): representation[\"lat\"] = instance.location.y representation[\"lon\"] = instance.location.x return",
"= ( instance.max_bikes - representation[\"num_bikes_available\"] ) if representation[\"num_bikes_available\"] > 0:",
"vehicle in representation[\"vehicles\"] ) else: # if no bike is",
"== VehicleType.PropulsionType.HUMAN: data.pop(\"max_range_meters\") return data class Meta: model = VehicleType",
"def to_representation(self, instance): representation = super().to_representation(instance) if representation is None:",
"intended behavior of the field # or it should be",
"GbfsStationStatusSerializer(serializers.HyperlinkedModelSerializer): station_id = serializers.CharField(source=\"id\", read_only=True) vehicles = serializers.SerializerMethodField() def get_vehicles(self,",
"a motor the field is required if ( instance.vehicle_type is",
"instance.location is not None and instance.location.x and instance.location.y ): representation[\"lat\"]",
"class GbfsVehicleOnStationSerializer(GbfsFreeBikeStatusSerializer): def to_representation(self, instance): representation = super().to_representation(instance) if representation",
"configured filter vehicles, where time report # is older than",
"than configure allowed silent timeperiod bsp = preferences.BikeSharePreferences if bsp.gbfs_hide_bikes_after_location_report_silence:",
"representation = super().to_representation(instance) if representation is None: return None representation.pop(\"lat\")",
"return representation # only return bikes with public geolocation class",
"= instance.public_geolocation() if public_geolocation is not None: pos = public_geolocation.geo",
"datetime import timedelta from django.utils.timezone import now from preferences import",
"mapping={ VehicleType.FormFactor.BIKE: \"bicycle\", VehicleType.FormFactor.ESCOOTER: \"scooter\", VehicleType.FormFactor.CAR: \"car\", VehicleType.FormFactor.MOPED: \"moped\", VehicleType.FormFactor.OTHER:",
"return representation class GbfsVehicleTypeSerializer(serializers.HyperlinkedModelSerializer): vehicle_type_id = serializers.CharField(source=\"id\", read_only=True) form_factor =",
"fields, serializers from bikesharing.models import Bike, Station, VehicleType from cykel.serializers",
"drop_last_reported(obj): obj.pop(\"last_reported\") return obj representation[\"vehicles\"] = list( map(drop_last_reported, representation[\"vehicles\"]) )",
"to False TODO: maybe configuration later representation[\"is_reserved\"] = False #",
"= super().to_representation(instance) if representation is None: return None representation.pop(\"lat\") representation.pop(\"lon\")",
"bikes with public geolocation class GbfsVehicleOnStationSerializer(GbfsFreeBikeStatusSerializer): def to_representation(self, instance): representation",
"VehicleType.PropulsionType.COMBUSTION: \"combustion\", }, ) def to_representation(self, instance): data = super(GbfsVehicleTypeSerializer,",
"representation[\"num_docks_available\"] = ( instance.max_bikes - representation[\"num_bikes_available\"] ) if representation[\"num_bikes_available\"] >",
"0 ) for vehicle in representation[\"vehicles\"] ) else: # if",
"= False public_geolocation = instance.public_geolocation() if public_geolocation is not None:",
"VehicleType.FormFactor.BIKE: \"bicycle\", VehicleType.FormFactor.ESCOOTER: \"scooter\", VehicleType.FormFactor.CAR: \"car\", VehicleType.FormFactor.MOPED: \"moped\", VehicleType.FormFactor.OTHER: \"other\",",
"bsp.gbfs_hide_bikes_after_location_report_silence: available_bikes = obj.bike_set.filter( availability_status=Bike.Availability.AVAILABLE, last_reported__gte=now() - timedelta(hours=bsp.gbfs_hide_bikes_after_location_report_hours), ) else:",
"should be the timestamp of the last bike removed #",
"if representation[\"num_bikes_available\"] > 0: representation[\"last_reported\"] = max( ( vehicle[\"last_reported\"] if",
"VehicleType.FormFactor.ESCOOTER: \"scooter\", VehicleType.FormFactor.CAR: \"car\", VehicleType.FormFactor.MOPED: \"moped\", VehicleType.FormFactor.OTHER: \"other\", }, )",
"from bikesharing.models import Bike, Station, VehicleType from cykel.serializers import EnumFieldSerializer",
"in representation[\"vehicles\"] ) else: # if no bike is at",
"read_only=True) form_factor = EnumFieldSerializer( read_only=True, mapping={ VehicleType.FormFactor.BIKE: \"bicycle\", VehicleType.FormFactor.ESCOOTER: \"scooter\",",
"return data class Meta: model = VehicleType fields = (",
"= EnumFieldSerializer( read_only=True, mapping={ VehicleType.FormFactor.BIKE: \"bicycle\", VehicleType.FormFactor.ESCOOTER: \"scooter\", VehicleType.FormFactor.CAR: \"car\",",
"and pos.y: representation[\"lat\"] = pos.y representation[\"lon\"] = pos.x return representation",
"silent timeperiod bsp = preferences.BikeSharePreferences if bsp.gbfs_hide_bikes_after_location_report_silence: available_bikes = obj.bike_set.filter(",
"the field is required if ( instance.vehicle_type is not None",
"capacity = serializers.IntegerField(source=\"max_bikes\", read_only=True) station_id = serializers.CharField(source=\"id\", read_only=True) class Meta:",
"= obj.bike_set.filter( availability_status=Bike.Availability.AVAILABLE, last_reported__gte=now() - timedelta(hours=bsp.gbfs_hide_bikes_after_location_report_hours), ) else: available_bikes =",
"instance): representation = super().to_representation(instance) # defined by GBFS 2.1: Only",
"= EnumFieldSerializer( read_only=True, mapping={ VehicleType.PropulsionType.HUMAN: \"human\", VehicleType.PropulsionType.ELECTRIC_ASSIST: \"electric_assist\", VehicleType.PropulsionType.ELECTRIC: \"electric\",",
"import EnumFieldSerializer class TimestampSerializer(fields.CharField): def to_representation(self, value): return value.timestamp() class",
"None: pos = public_geolocation.geo if pos and pos.x and pos.y:",
"and instance.location.x and instance.location.y ): representation[\"lat\"] = instance.location.y representation[\"lon\"] =",
"representation is None: return None representation.pop(\"lat\") representation.pop(\"lon\") return representation class",
"Meta: model = Station fields = ( \"name\", \"capacity\", \"station_id\",",
"= ( \"name\", \"capacity\", \"station_id\", ) def to_representation(self, instance): representation",
"representation[\"lat\"] = instance.location.y representation[\"lon\"] = instance.location.x return representation class GbfsStationStatusSerializer(serializers.HyperlinkedModelSerializer):",
"GbfsStationInformationSerializer(serializers.HyperlinkedModelSerializer): name = serializers.CharField(source=\"station_name\", read_only=True) capacity = serializers.IntegerField(source=\"max_bikes\", read_only=True) station_id",
"report # is older than configure allowed silent timeperiod bsp",
"representation.pop(\"lon\") return representation class GbfsStationInformationSerializer(serializers.HyperlinkedModelSerializer): name = serializers.CharField(source=\"station_name\", read_only=True) capacity",
"# Default to False TODO: maybe configuration later representation[\"is_disabled\"] =",
"representation[\"num_bikes_available\"] > 0: representation[\"last_reported\"] = max( ( vehicle[\"last_reported\"] if vehicle[\"last_reported\"]",
"or it should be the timestamp of the last bike",
"timedelta from django.utils.timezone import now from preferences import preferences from",
"not None and instance.location.x and instance.location.y ): representation[\"lat\"] = instance.location.y",
"= instance.location.x return representation class GbfsStationStatusSerializer(serializers.HyperlinkedModelSerializer): station_id = serializers.CharField(source=\"id\", read_only=True)",
"not None else 0 ) for vehicle in representation[\"vehicles\"] )",
"to_representation(self, value): return value.timestamp() class GbfsFreeBikeStatusSerializer(serializers.HyperlinkedModelSerializer): bike_id = serializers.CharField(source=\"non_static_bike_uuid\", read_only=True)",
"VehicleType.FormFactor.OTHER: \"other\", }, ) propulsion_type = EnumFieldSerializer( read_only=True, mapping={ VehicleType.PropulsionType.HUMAN:",
"configuration later representation[\"is_reserved\"] = False # Default to False TODO:",
"obj.bike_set.filter( availability_status=Bike.Availability.AVAILABLE, last_reported__gte=now() - timedelta(hours=bsp.gbfs_hide_bikes_after_location_report_hours), ) else: available_bikes = obj.bike_set.filter(",
"VehicleType fields = ( \"vehicle_type_id\", \"form_factor\", \"propulsion_type\", \"max_range_meters\", \"name\", )",
"instance.public_geolocation() if public_geolocation is not None: pos = public_geolocation.geo if",
"if ( instance.vehicle_type is not None and instance.vehicle_type.propulsion_type == VehicleType.PropulsionType.HUMAN",
"# if no bike is at the station, last_report is",
"= status return representation class GbfsVehicleTypeSerializer(serializers.HyperlinkedModelSerializer): vehicle_type_id = serializers.CharField(source=\"id\", read_only=True)",
"VehicleType.PropulsionType.HUMAN: \"human\", VehicleType.PropulsionType.ELECTRIC_ASSIST: \"electric_assist\", VehicleType.PropulsionType.ELECTRIC: \"electric\", VehicleType.PropulsionType.COMBUSTION: \"combustion\", }, )",
") if representation[\"num_bikes_available\"] > 0: representation[\"last_reported\"] = max( ( vehicle[\"last_reported\"]",
"read_only=True, mapping={ VehicleType.FormFactor.BIKE: \"bicycle\", VehicleType.FormFactor.ESCOOTER: \"scooter\", VehicleType.FormFactor.CAR: \"car\", VehicleType.FormFactor.MOPED: \"moped\",",
"len(representation[\"vehicles\"]) representation[\"num_docks_available\"] = ( instance.max_bikes - representation[\"num_bikes_available\"] ) if representation[\"num_bikes_available\"]",
"\"vehicle_type_id\", \"current_range_meters\", \"last_reported\", ) def to_representation(self, instance): representation = super().to_representation(instance)",
"Only if the vehicle has a motor the field is",
"super().to_representation(instance) if representation is None: return None representation.pop(\"lat\") representation.pop(\"lon\") return",
"Meta: model = Bike fields = ( \"bike_id\", \"vehicle_type_id\", \"current_range_meters\",",
"import timedelta from django.utils.timezone import now from preferences import preferences",
"= serializers.CharField(source=\"id\", read_only=True) class Meta: model = Station fields =",
"pos.x and pos.y: representation[\"lat\"] = pos.y representation[\"lon\"] = pos.x return",
"( \"name\", \"capacity\", \"station_id\", ) def to_representation(self, instance): representation =",
"if configured filter vehicles, where time report # is older",
"else 0 ) for vehicle in representation[\"vehicles\"] ) else: #",
"= Station fields = ( \"station_id\", \"vehicles\", ) def to_representation(self,",
"return value.timestamp() class GbfsFreeBikeStatusSerializer(serializers.HyperlinkedModelSerializer): bike_id = serializers.CharField(source=\"non_static_bike_uuid\", read_only=True) vehicle_type_id =",
"= ( \"station_id\", \"vehicles\", ) def to_representation(self, instance): representation =",
"at the station, last_report is the current time # not",
"station_id = serializers.CharField(source=\"id\", read_only=True) class Meta: model = Station fields",
"is the current time # not sure if this is",
"serializers.CharField(source=\"non_static_bike_uuid\", read_only=True) vehicle_type_id = serializers.CharField(read_only=True) last_reported = TimestampSerializer(read_only=True) class Meta:",
") status = (instance.status == Station.Status.ACTIVE) or False representation[\"is_installed\"] =",
"GbfsVehicleTypeSerializer(serializers.HyperlinkedModelSerializer): vehicle_type_id = serializers.CharField(source=\"id\", read_only=True) form_factor = EnumFieldSerializer( read_only=True, mapping={",
"this is the intended behavior of the field # or",
"motor the field is required if ( instance.vehicle_type is not",
"read_only=True) vehicle_type_id = serializers.CharField(read_only=True) last_reported = TimestampSerializer(read_only=True) class Meta: model",
"removed # but it is not so easy to implement"
] |
[
"{ \"360\":[], \"480\":[], \"720\":[], \"1080\":[], } url = self.url.replace('https:////','https://') soup",
"anime_downloader.sites import helpers logger = logging.getLogger(__name__) class VidStream(BaseExtractor): def _get_data(self):",
"helpers.soupify(helpers.get(download)) links = soup.select('div.mirror_link')[0].select('div.dowload > a') for a in QUALITIES:",
"= soup.select('div.mirror_link')[0].select('div.dowload > a') for a in QUALITIES: for b",
"a') for a in QUALITIES: for b in links: if",
"= self.url.replace('https:////','https://') soup = helpers.get(url).text regex = r'https://vidstreaming\\.io/download\\?[^\"]*' download =",
"download = re.search(regex,soup).group() soup = helpers.soupify(helpers.get(download)) links = soup.select('div.mirror_link')[0].select('div.dowload >",
"self.url.replace('https:////','https://') soup = helpers.get(url).text regex = r'https://vidstreaming\\.io/download\\?[^\"]*' download = re.search(regex,soup).group()",
"case nothing is found return { 'stream_url': stream_url, 'referer': download",
"= logging.getLogger(__name__) class VidStream(BaseExtractor): def _get_data(self): QUALITIES = { \"360\":[],",
"\"1080\":[], } url = self.url.replace('https:////','https://') soup = helpers.get(url).text regex =",
"url = self.url.replace('https:////','https://') soup = helpers.get(url).text regex = r'https://vidstreaming\\.io/download\\?[^\"]*' download",
"links = soup.select('div.mirror_link')[0].select('div.dowload > a') for a in QUALITIES: for",
"= helpers.get(url).text regex = r'https://vidstreaming\\.io/download\\?[^\"]*' download = re.search(regex,soup).group() soup =",
"a in b.text: QUALITIES[a].append(b.get('href')) stream_url = QUALITIES[self.quality[:-1]][0] if QUALITIES !=",
"= r'https://vidstreaming\\.io/download\\?[^\"]*' download = re.search(regex,soup).group() soup = helpers.soupify(helpers.get(download)) links =",
"= QUALITIES[self.quality[:-1]][0] if QUALITIES != {\"360\":[],\"480\":[],\"720\":[],\"1080\":[],} else links[0].get('href') #In case",
"QUALITIES = { \"360\":[], \"480\":[], \"720\":[], \"1080\":[], } url =",
"\"480\":[], \"720\":[], \"1080\":[], } url = self.url.replace('https:////','https://') soup = helpers.get(url).text",
"} url = self.url.replace('https:////','https://') soup = helpers.get(url).text regex = r'https://vidstreaming\\.io/download\\?[^\"]*'",
"regex = r'https://vidstreaming\\.io/download\\?[^\"]*' download = re.search(regex,soup).group() soup = helpers.soupify(helpers.get(download)) links",
"import BaseExtractor from anime_downloader.sites import helpers logger = logging.getLogger(__name__) class",
"from anime_downloader.sites import helpers logger = logging.getLogger(__name__) class VidStream(BaseExtractor): def",
"stream_url = QUALITIES[self.quality[:-1]][0] if QUALITIES != {\"360\":[],\"480\":[],\"720\":[],\"1080\":[],} else links[0].get('href') #In",
"def _get_data(self): QUALITIES = { \"360\":[], \"480\":[], \"720\":[], \"1080\":[], }",
"links[0].get('href') #In case nothing is found return { 'stream_url': stream_url,",
"BaseExtractor from anime_downloader.sites import helpers logger = logging.getLogger(__name__) class VidStream(BaseExtractor):",
"_get_data(self): QUALITIES = { \"360\":[], \"480\":[], \"720\":[], \"1080\":[], } url",
"VidStream(BaseExtractor): def _get_data(self): QUALITIES = { \"360\":[], \"480\":[], \"720\":[], \"1080\":[],",
"{\"360\":[],\"480\":[],\"720\":[],\"1080\":[],} else links[0].get('href') #In case nothing is found return {",
"for a in QUALITIES: for b in links: if a",
"else links[0].get('href') #In case nothing is found return { 'stream_url':",
"import helpers logger = logging.getLogger(__name__) class VidStream(BaseExtractor): def _get_data(self): QUALITIES",
"b in links: if a in b.text: QUALITIES[a].append(b.get('href')) stream_url =",
"if a in b.text: QUALITIES[a].append(b.get('href')) stream_url = QUALITIES[self.quality[:-1]][0] if QUALITIES",
"logging.getLogger(__name__) class VidStream(BaseExtractor): def _get_data(self): QUALITIES = { \"360\":[], \"480\":[],",
"soup = helpers.get(url).text regex = r'https://vidstreaming\\.io/download\\?[^\"]*' download = re.search(regex,soup).group() soup",
"> a') for a in QUALITIES: for b in links:",
"= re.search(regex,soup).group() soup = helpers.soupify(helpers.get(download)) links = soup.select('div.mirror_link')[0].select('div.dowload > a')",
"links: if a in b.text: QUALITIES[a].append(b.get('href')) stream_url = QUALITIES[self.quality[:-1]][0] if",
"b.text: QUALITIES[a].append(b.get('href')) stream_url = QUALITIES[self.quality[:-1]][0] if QUALITIES != {\"360\":[],\"480\":[],\"720\":[],\"1080\":[],} else",
"nothing is found return { 'stream_url': stream_url, 'referer': download }",
"import logging import re from anime_downloader.extractors.base_extractor import BaseExtractor from anime_downloader.sites",
"helpers logger = logging.getLogger(__name__) class VidStream(BaseExtractor): def _get_data(self): QUALITIES =",
"QUALITIES[a].append(b.get('href')) stream_url = QUALITIES[self.quality[:-1]][0] if QUALITIES != {\"360\":[],\"480\":[],\"720\":[],\"1080\":[],} else links[0].get('href')",
"!= {\"360\":[],\"480\":[],\"720\":[],\"1080\":[],} else links[0].get('href') #In case nothing is found return",
"logger = logging.getLogger(__name__) class VidStream(BaseExtractor): def _get_data(self): QUALITIES = {",
"helpers.get(url).text regex = r'https://vidstreaming\\.io/download\\?[^\"]*' download = re.search(regex,soup).group() soup = helpers.soupify(helpers.get(download))",
"r'https://vidstreaming\\.io/download\\?[^\"]*' download = re.search(regex,soup).group() soup = helpers.soupify(helpers.get(download)) links = soup.select('div.mirror_link')[0].select('div.dowload",
"for b in links: if a in b.text: QUALITIES[a].append(b.get('href')) stream_url",
"QUALITIES != {\"360\":[],\"480\":[],\"720\":[],\"1080\":[],} else links[0].get('href') #In case nothing is found",
"import re from anime_downloader.extractors.base_extractor import BaseExtractor from anime_downloader.sites import helpers",
"re from anime_downloader.extractors.base_extractor import BaseExtractor from anime_downloader.sites import helpers logger",
"\"720\":[], \"1080\":[], } url = self.url.replace('https:////','https://') soup = helpers.get(url).text regex",
"soup.select('div.mirror_link')[0].select('div.dowload > a') for a in QUALITIES: for b in",
"#In case nothing is found return { 'stream_url': stream_url, 'referer':",
"anime_downloader.extractors.base_extractor import BaseExtractor from anime_downloader.sites import helpers logger = logging.getLogger(__name__)",
"= { \"360\":[], \"480\":[], \"720\":[], \"1080\":[], } url = self.url.replace('https:////','https://')",
"in links: if a in b.text: QUALITIES[a].append(b.get('href')) stream_url = QUALITIES[self.quality[:-1]][0]",
"\"360\":[], \"480\":[], \"720\":[], \"1080\":[], } url = self.url.replace('https:////','https://') soup =",
"soup = helpers.soupify(helpers.get(download)) links = soup.select('div.mirror_link')[0].select('div.dowload > a') for a",
"in QUALITIES: for b in links: if a in b.text:",
"QUALITIES: for b in links: if a in b.text: QUALITIES[a].append(b.get('href'))",
"a in QUALITIES: for b in links: if a in",
"class VidStream(BaseExtractor): def _get_data(self): QUALITIES = { \"360\":[], \"480\":[], \"720\":[],",
"re.search(regex,soup).group() soup = helpers.soupify(helpers.get(download)) links = soup.select('div.mirror_link')[0].select('div.dowload > a') for",
"if QUALITIES != {\"360\":[],\"480\":[],\"720\":[],\"1080\":[],} else links[0].get('href') #In case nothing is",
"QUALITIES[self.quality[:-1]][0] if QUALITIES != {\"360\":[],\"480\":[],\"720\":[],\"1080\":[],} else links[0].get('href') #In case nothing",
"logging import re from anime_downloader.extractors.base_extractor import BaseExtractor from anime_downloader.sites import",
"from anime_downloader.extractors.base_extractor import BaseExtractor from anime_downloader.sites import helpers logger =",
"in b.text: QUALITIES[a].append(b.get('href')) stream_url = QUALITIES[self.quality[:-1]][0] if QUALITIES != {\"360\":[],\"480\":[],\"720\":[],\"1080\":[],}",
"= helpers.soupify(helpers.get(download)) links = soup.select('div.mirror_link')[0].select('div.dowload > a') for a in"
] |
[
"File_upload, SummaryRes from sim_v1.textsummary import TEXTSummary summary_document_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)),'media','sum_v1','upload') #summary_document_dir",
"{'is_valid': True, 'name': document.file.name, 'url': document.file.url} else: data = {'is_valid':",
"import View from django.conf import settings from .forms import File_uploadForm",
".models import File_upload, SummaryRes from sim_v1.textsummary import TEXTSummary summary_document_dir =",
"= File_uploadForm(request.POST) if form.is_valid(): form.save() sum_words = form.cleaned_data['sum_words'] request.session['sum_words'] =",
"sum_words = form.cleaned_data['sum_words'] request.session['sum_words'] = sum_words else: pass else: pass",
"Upload(View): def post(self, request): time.sleep(1) # You don't need this",
"# You don't need this line. This is just to",
"#summary_document_dir = r'C:\\Users\\ERDIG\\Dropbox\\Python\\nlp_v1\\media\\sum_v1\\upload' summary_extraction_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)),'media','sum_v1','temp') #summary_extraction_dir = r'C:\\Users\\ERDIG\\Dropbox\\Python\\nlp_v1\\media\\sum_v1\\temp' summary_ratio",
"can see the progress bar testing locally. form = File_uploadForm(self.request.POST,",
"File_upload.objects.all(): document.file.delete() document.delete() doc_list = File_upload.objects.all() form = File_uploadForm() return",
"django.shortcuts import render, redirect from django.http import JsonResponse from django.views",
"def post(self, request): time.sleep(1) # You don't need this line.",
"File_uploadForm(self.request.POST, self.request.FILES) print(form.errors) if form.is_valid(): document = form.save() data =",
"from django.shortcuts import render, redirect from django.http import JsonResponse from",
"= TEXTSummary(text_dir, summary_extraction_dir, summary_ratio, summary_word_count) summary.textextraction() summary.summary() SummaryRes.objects.create(doc = document,",
"print(form.errors) if form.is_valid(): document = form.save() data = {'is_valid': True,",
"Summarize(request): SummaryRes.objects.all().delete() summary_word_count = request.session['sum_words'] for document in os.listdir(summary_document_dir): for",
"form.save() sum_words = form.cleaned_data['sum_words'] request.session['sum_words'] = sum_words else: pass else:",
"= File_uploadForm() return render(self.request, 'upload.html', {'documents': doc_list, 'form': form,}) def",
"from django.conf import settings from .forms import File_uploadForm from .models",
"= File_upload.objects.all() form = File_uploadForm() return render(self.request, 'upload.html', {'documents': doc_list,",
"JsonResponse from django.views import View from django.conf import settings from",
"if form.is_valid(): form.save() sum_words = form.cleaned_data['sum_words'] request.session['sum_words'] = sum_words else:",
"import JsonResponse from django.views import View from django.conf import settings",
"def Summarize(request): SummaryRes.objects.all().delete() summary_word_count = request.session['sum_words'] for document in os.listdir(summary_document_dir):",
"from .forms import File_uploadForm from .models import File_upload, SummaryRes from",
"from django.http import JsonResponse from django.views import View from django.conf",
"os.listdir(summary_document_dir): for filename in os.listdir(summary_extraction_dir): os.remove(os.path.join(summary_extraction_dir, filename)) text_dir = os.path.join(summary_document_dir,",
"data = {'is_valid': True, 'name': document.file.name, 'url': document.file.url} else: data",
"summary = summary.summary) results = SummaryRes.objects.all() return render(request, 'summarize.html', {'results':",
"see the progress bar testing locally. form = File_uploadForm(self.request.POST, self.request.FILES)",
"= File_uploadForm(self.request.POST, self.request.FILES) print(form.errors) if form.is_valid(): document = form.save() data",
"'url': document.file.url} else: data = {'is_valid': False} return JsonResponse(data) def",
"django.conf import settings from .forms import File_uploadForm from .models import",
"form = File_uploadForm(self.request.POST, self.request.FILES) print(form.errors) if form.is_valid(): document = form.save()",
"'POST': form = File_uploadForm(request.POST) if form.is_valid(): form.save() sum_words = form.cleaned_data['sum_words']",
"request.session['sum_words'] = sum_words else: pass else: pass return redirect('sum_v1:summarize') def",
"testing locally. form = File_uploadForm(self.request.POST, self.request.FILES) print(form.errors) if form.is_valid(): document",
"in os.listdir(summary_extraction_dir): os.remove(os.path.join(summary_extraction_dir, filename)) text_dir = os.path.join(summary_document_dir, document) summary =",
"= form.save() data = {'is_valid': True, 'name': document.file.name, 'url': document.file.url}",
"os.path.join(summary_document_dir, document) summary = TEXTSummary(text_dir, summary_extraction_dir, summary_ratio, summary_word_count) summary.textextraction() summary.summary()",
"= os.path.join(os.path.dirname(os.path.dirname(__file__)),'media','sum_v1','upload') #summary_document_dir = r'C:\\Users\\ERDIG\\Dropbox\\Python\\nlp_v1\\media\\sum_v1\\upload' summary_extraction_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)),'media','sum_v1','temp') #summary_extraction_dir =",
"else: pass else: pass return redirect('sum_v1:summarize') def clear_database(request): for document",
"summary = TEXTSummary(text_dir, summary_extraction_dir, summary_ratio, summary_word_count) summary.textextraction() summary.summary() SummaryRes.objects.create(doc =",
"import time import os from django.shortcuts import render, redirect from",
"0.01 class Upload(View): def post(self, request): time.sleep(1) # You don't",
"= form.cleaned_data['sum_words'] request.session['sum_words'] = sum_words else: pass else: pass return",
"= os.path.join(os.path.dirname(os.path.dirname(__file__)),'media','sum_v1','temp') #summary_extraction_dir = r'C:\\Users\\ERDIG\\Dropbox\\Python\\nlp_v1\\media\\sum_v1\\temp' summary_ratio = 0.01 class Upload(View):",
"post(self, request): time.sleep(1) # You don't need this line. This",
"document.file.url} else: data = {'is_valid': False} return JsonResponse(data) def get(self,",
"File_uploadForm() return render(self.request, 'upload.html', {'documents': doc_list, 'form': form,}) def sum_words(request):",
"import File_uploadForm from .models import File_upload, SummaryRes from sim_v1.textsummary import",
"'name': document.file.name, 'url': document.file.url} else: data = {'is_valid': False} return",
"import settings from .forms import File_uploadForm from .models import File_upload,",
"summary.textextraction() summary.summary() SummaryRes.objects.create(doc = document, summary = summary.summary) results =",
"from .models import File_upload, SummaryRes from sim_v1.textsummary import TEXTSummary summary_document_dir",
"else: data = {'is_valid': False} return JsonResponse(data) def get(self, request):",
"This is just to delay the process so you can",
"else: pass return redirect('sum_v1:summarize') def clear_database(request): for document in File_upload.objects.all():",
"File_uploadForm from .models import File_upload, SummaryRes from sim_v1.textsummary import TEXTSummary",
"is just to delay the process so you can see",
"os.path.join(os.path.dirname(os.path.dirname(__file__)),'media','sum_v1','upload') #summary_document_dir = r'C:\\Users\\ERDIG\\Dropbox\\Python\\nlp_v1\\media\\sum_v1\\upload' summary_extraction_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)),'media','sum_v1','temp') #summary_extraction_dir = r'C:\\Users\\ERDIG\\Dropbox\\Python\\nlp_v1\\media\\sum_v1\\temp'",
"document in File_upload.objects.all(): document.file.delete() document.delete() return redirect(request.POST.get('next')) def Summarize(request): SummaryRes.objects.all().delete()",
"progress bar testing locally. form = File_uploadForm(self.request.POST, self.request.FILES) print(form.errors) if",
"document.file.name, 'url': document.file.url} else: data = {'is_valid': False} return JsonResponse(data)",
"import os from django.shortcuts import render, redirect from django.http import",
"= {'is_valid': False} return JsonResponse(data) def get(self, request): for document",
"def get(self, request): for document in File_upload.objects.all(): document.file.delete() document.delete() doc_list",
"you can see the progress bar testing locally. form =",
"doc_list, 'form': form,}) def sum_words(request): if request.method == 'POST': form",
"return redirect(request.POST.get('next')) def Summarize(request): SummaryRes.objects.all().delete() summary_word_count = request.session['sum_words'] for document",
"os from django.shortcuts import render, redirect from django.http import JsonResponse",
"locally. form = File_uploadForm(self.request.POST, self.request.FILES) print(form.errors) if form.is_valid(): document =",
"form = File_uploadForm(request.POST) if form.is_valid(): form.save() sum_words = form.cleaned_data['sum_words'] request.session['sum_words']",
"if request.method == 'POST': form = File_uploadForm(request.POST) if form.is_valid(): form.save()",
"return redirect('sum_v1:summarize') def clear_database(request): for document in File_upload.objects.all(): document.file.delete() document.delete()",
"= request.session['sum_words'] for document in os.listdir(summary_document_dir): for filename in os.listdir(summary_extraction_dir):",
"summary_ratio, summary_word_count) summary.textextraction() summary.summary() SummaryRes.objects.create(doc = document, summary = summary.summary)",
"= summary.summary) results = SummaryRes.objects.all() return render(request, 'summarize.html', {'results': results})",
"summary_ratio = 0.01 class Upload(View): def post(self, request): time.sleep(1) #",
"for document in File_upload.objects.all(): document.file.delete() document.delete() doc_list = File_upload.objects.all() form",
"redirect('sum_v1:summarize') def clear_database(request): for document in File_upload.objects.all(): document.file.delete() document.delete() return",
"document) summary = TEXTSummary(text_dir, summary_extraction_dir, summary_ratio, summary_word_count) summary.textextraction() summary.summary() SummaryRes.objects.create(doc",
"JsonResponse(data) def get(self, request): for document in File_upload.objects.all(): document.file.delete() document.delete()",
"TEXTSummary summary_document_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)),'media','sum_v1','upload') #summary_document_dir = r'C:\\Users\\ERDIG\\Dropbox\\Python\\nlp_v1\\media\\sum_v1\\upload' summary_extraction_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)),'media','sum_v1','temp')",
"View from django.conf import settings from .forms import File_uploadForm from",
"SummaryRes from sim_v1.textsummary import TEXTSummary summary_document_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)),'media','sum_v1','upload') #summary_document_dir =",
"form.is_valid(): document = form.save() data = {'is_valid': True, 'name': document.file.name,",
"import render, redirect from django.http import JsonResponse from django.views import",
"render(self.request, 'upload.html', {'documents': doc_list, 'form': form,}) def sum_words(request): if request.method",
"= sum_words else: pass else: pass return redirect('sum_v1:summarize') def clear_database(request):",
"def clear_database(request): for document in File_upload.objects.all(): document.file.delete() document.delete() return redirect(request.POST.get('next'))",
"os.listdir(summary_extraction_dir): os.remove(os.path.join(summary_extraction_dir, filename)) text_dir = os.path.join(summary_document_dir, document) summary = TEXTSummary(text_dir,",
"document, summary = summary.summary) results = SummaryRes.objects.all() return render(request, 'summarize.html',",
"document = form.save() data = {'is_valid': True, 'name': document.file.name, 'url':",
"'upload.html', {'documents': doc_list, 'form': form,}) def sum_words(request): if request.method ==",
"form.is_valid(): form.save() sum_words = form.cleaned_data['sum_words'] request.session['sum_words'] = sum_words else: pass",
"return render(self.request, 'upload.html', {'documents': doc_list, 'form': form,}) def sum_words(request): if",
"form,}) def sum_words(request): if request.method == 'POST': form = File_uploadForm(request.POST)",
"sum_words else: pass else: pass return redirect('sum_v1:summarize') def clear_database(request): for",
"form.cleaned_data['sum_words'] request.session['sum_words'] = sum_words else: pass else: pass return redirect('sum_v1:summarize')",
"redirect(request.POST.get('next')) def Summarize(request): SummaryRes.objects.all().delete() summary_word_count = request.session['sum_words'] for document in",
"the process so you can see the progress bar testing",
"= r'C:\\Users\\ERDIG\\Dropbox\\Python\\nlp_v1\\media\\sum_v1\\temp' summary_ratio = 0.01 class Upload(View): def post(self, request):",
"for document in os.listdir(summary_document_dir): for filename in os.listdir(summary_extraction_dir): os.remove(os.path.join(summary_extraction_dir, filename))",
"pass return redirect('sum_v1:summarize') def clear_database(request): for document in File_upload.objects.all(): document.file.delete()",
"settings from .forms import File_uploadForm from .models import File_upload, SummaryRes",
"import File_upload, SummaryRes from sim_v1.textsummary import TEXTSummary summary_document_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)),'media','sum_v1','upload')",
"summary_word_count = request.session['sum_words'] for document in os.listdir(summary_document_dir): for filename in",
"summary_document_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)),'media','sum_v1','upload') #summary_document_dir = r'C:\\Users\\ERDIG\\Dropbox\\Python\\nlp_v1\\media\\sum_v1\\upload' summary_extraction_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)),'media','sum_v1','temp') #summary_extraction_dir",
"You don't need this line. This is just to delay",
"File_upload.objects.all() form = File_uploadForm() return render(self.request, 'upload.html', {'documents': doc_list, 'form':",
"document in os.listdir(summary_document_dir): for filename in os.listdir(summary_extraction_dir): os.remove(os.path.join(summary_extraction_dir, filename)) text_dir",
"= document, summary = summary.summary) results = SummaryRes.objects.all() return render(request,",
"data = {'is_valid': False} return JsonResponse(data) def get(self, request): for",
"request.method == 'POST': form = File_uploadForm(request.POST) if form.is_valid(): form.save() sum_words",
"request.session['sum_words'] for document in os.listdir(summary_document_dir): for filename in os.listdir(summary_extraction_dir): os.remove(os.path.join(summary_extraction_dir,",
"import TEXTSummary summary_document_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)),'media','sum_v1','upload') #summary_document_dir = r'C:\\Users\\ERDIG\\Dropbox\\Python\\nlp_v1\\media\\sum_v1\\upload' summary_extraction_dir =",
"delay the process so you can see the progress bar",
"text_dir = os.path.join(summary_document_dir, document) summary = TEXTSummary(text_dir, summary_extraction_dir, summary_ratio, summary_word_count)",
"True, 'name': document.file.name, 'url': document.file.url} else: data = {'is_valid': False}",
"<filename>gui/sum_v1/views.py import time import os from django.shortcuts import render, redirect",
"document.delete() doc_list = File_upload.objects.all() form = File_uploadForm() return render(self.request, 'upload.html',",
"File_upload.objects.all(): document.file.delete() document.delete() return redirect(request.POST.get('next')) def Summarize(request): SummaryRes.objects.all().delete() summary_word_count =",
"the progress bar testing locally. form = File_uploadForm(self.request.POST, self.request.FILES) print(form.errors)",
"{'documents': doc_list, 'form': form,}) def sum_words(request): if request.method == 'POST':",
"for document in File_upload.objects.all(): document.file.delete() document.delete() return redirect(request.POST.get('next')) def Summarize(request):",
"in File_upload.objects.all(): document.file.delete() document.delete() return redirect(request.POST.get('next')) def Summarize(request): SummaryRes.objects.all().delete() summary_word_count",
"process so you can see the progress bar testing locally.",
"'form': form,}) def sum_words(request): if request.method == 'POST': form =",
"{'is_valid': False} return JsonResponse(data) def get(self, request): for document in",
"document.file.delete() document.delete() doc_list = File_upload.objects.all() form = File_uploadForm() return render(self.request,",
"filename in os.listdir(summary_extraction_dir): os.remove(os.path.join(summary_extraction_dir, filename)) text_dir = os.path.join(summary_document_dir, document) summary",
"django.views import View from django.conf import settings from .forms import",
"form.save() data = {'is_valid': True, 'name': document.file.name, 'url': document.file.url} else:",
"sim_v1.textsummary import TEXTSummary summary_document_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)),'media','sum_v1','upload') #summary_document_dir = r'C:\\Users\\ERDIG\\Dropbox\\Python\\nlp_v1\\media\\sum_v1\\upload' summary_extraction_dir",
"os.path.join(os.path.dirname(os.path.dirname(__file__)),'media','sum_v1','temp') #summary_extraction_dir = r'C:\\Users\\ERDIG\\Dropbox\\Python\\nlp_v1\\media\\sum_v1\\temp' summary_ratio = 0.01 class Upload(View): def",
"time.sleep(1) # You don't need this line. This is just",
"line. This is just to delay the process so you",
"TEXTSummary(text_dir, summary_extraction_dir, summary_ratio, summary_word_count) summary.textextraction() summary.summary() SummaryRes.objects.create(doc = document, summary",
"document.delete() return redirect(request.POST.get('next')) def Summarize(request): SummaryRes.objects.all().delete() summary_word_count = request.session['sum_words'] for",
"document.file.delete() document.delete() return redirect(request.POST.get('next')) def Summarize(request): SummaryRes.objects.all().delete() summary_word_count = request.session['sum_words']",
"in os.listdir(summary_document_dir): for filename in os.listdir(summary_extraction_dir): os.remove(os.path.join(summary_extraction_dir, filename)) text_dir =",
"class Upload(View): def post(self, request): time.sleep(1) # You don't need",
"= os.path.join(summary_document_dir, document) summary = TEXTSummary(text_dir, summary_extraction_dir, summary_ratio, summary_word_count) summary.textextraction()",
"in File_upload.objects.all(): document.file.delete() document.delete() doc_list = File_upload.objects.all() form = File_uploadForm()",
"self.request.FILES) print(form.errors) if form.is_valid(): document = form.save() data = {'is_valid':",
"doc_list = File_upload.objects.all() form = File_uploadForm() return render(self.request, 'upload.html', {'documents':",
"summary_word_count) summary.textextraction() summary.summary() SummaryRes.objects.create(doc = document, summary = summary.summary) results",
"summary_extraction_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)),'media','sum_v1','temp') #summary_extraction_dir = r'C:\\Users\\ERDIG\\Dropbox\\Python\\nlp_v1\\media\\sum_v1\\temp' summary_ratio = 0.01 class",
"#summary_extraction_dir = r'C:\\Users\\ERDIG\\Dropbox\\Python\\nlp_v1\\media\\sum_v1\\temp' summary_ratio = 0.01 class Upload(View): def post(self,",
"bar testing locally. form = File_uploadForm(self.request.POST, self.request.FILES) print(form.errors) if form.is_valid():",
"clear_database(request): for document in File_upload.objects.all(): document.file.delete() document.delete() return redirect(request.POST.get('next')) def",
"form = File_uploadForm() return render(self.request, 'upload.html', {'documents': doc_list, 'form': form,})",
"redirect from django.http import JsonResponse from django.views import View from",
"from django.views import View from django.conf import settings from .forms",
"if form.is_valid(): document = form.save() data = {'is_valid': True, 'name':",
"File_uploadForm(request.POST) if form.is_valid(): form.save() sum_words = form.cleaned_data['sum_words'] request.session['sum_words'] = sum_words",
"this line. This is just to delay the process so",
"r'C:\\Users\\ERDIG\\Dropbox\\Python\\nlp_v1\\media\\sum_v1\\temp' summary_ratio = 0.01 class Upload(View): def post(self, request): time.sleep(1)",
"= {'is_valid': True, 'name': document.file.name, 'url': document.file.url} else: data =",
"so you can see the progress bar testing locally. form",
"pass else: pass return redirect('sum_v1:summarize') def clear_database(request): for document in",
"time import os from django.shortcuts import render, redirect from django.http",
"for filename in os.listdir(summary_extraction_dir): os.remove(os.path.join(summary_extraction_dir, filename)) text_dir = os.path.join(summary_document_dir, document)",
"summary.summary() SummaryRes.objects.create(doc = document, summary = summary.summary) results = SummaryRes.objects.all()",
"== 'POST': form = File_uploadForm(request.POST) if form.is_valid(): form.save() sum_words =",
"to delay the process so you can see the progress",
"False} return JsonResponse(data) def get(self, request): for document in File_upload.objects.all():",
".forms import File_uploadForm from .models import File_upload, SummaryRes from sim_v1.textsummary",
"from sim_v1.textsummary import TEXTSummary summary_document_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)),'media','sum_v1','upload') #summary_document_dir = r'C:\\Users\\ERDIG\\Dropbox\\Python\\nlp_v1\\media\\sum_v1\\upload'",
"sum_words(request): if request.method == 'POST': form = File_uploadForm(request.POST) if form.is_valid():",
"os.remove(os.path.join(summary_extraction_dir, filename)) text_dir = os.path.join(summary_document_dir, document) summary = TEXTSummary(text_dir, summary_extraction_dir,",
"django.http import JsonResponse from django.views import View from django.conf import",
"document in File_upload.objects.all(): document.file.delete() document.delete() doc_list = File_upload.objects.all() form =",
"request): time.sleep(1) # You don't need this line. This is",
"request): for document in File_upload.objects.all(): document.file.delete() document.delete() doc_list = File_upload.objects.all()",
"= r'C:\\Users\\ERDIG\\Dropbox\\Python\\nlp_v1\\media\\sum_v1\\upload' summary_extraction_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)),'media','sum_v1','temp') #summary_extraction_dir = r'C:\\Users\\ERDIG\\Dropbox\\Python\\nlp_v1\\media\\sum_v1\\temp' summary_ratio =",
"= 0.01 class Upload(View): def post(self, request): time.sleep(1) # You",
"SummaryRes.objects.create(doc = document, summary = summary.summary) results = SummaryRes.objects.all() return",
"render, redirect from django.http import JsonResponse from django.views import View",
"return JsonResponse(data) def get(self, request): for document in File_upload.objects.all(): document.file.delete()",
"r'C:\\Users\\ERDIG\\Dropbox\\Python\\nlp_v1\\media\\sum_v1\\upload' summary_extraction_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)),'media','sum_v1','temp') #summary_extraction_dir = r'C:\\Users\\ERDIG\\Dropbox\\Python\\nlp_v1\\media\\sum_v1\\temp' summary_ratio = 0.01",
"need this line. This is just to delay the process",
"filename)) text_dir = os.path.join(summary_document_dir, document) summary = TEXTSummary(text_dir, summary_extraction_dir, summary_ratio,",
"summary_extraction_dir, summary_ratio, summary_word_count) summary.textextraction() summary.summary() SummaryRes.objects.create(doc = document, summary =",
"def sum_words(request): if request.method == 'POST': form = File_uploadForm(request.POST) if",
"SummaryRes.objects.all().delete() summary_word_count = request.session['sum_words'] for document in os.listdir(summary_document_dir): for filename",
"don't need this line. This is just to delay the",
"just to delay the process so you can see the",
"get(self, request): for document in File_upload.objects.all(): document.file.delete() document.delete() doc_list ="
] |
[
"const, decorators, http, messages DOMAIN = const.DOMAIN DEPENDENCIES = ('http',)",
"= messages.error_message result_message = messages.result_message async_response = decorators.async_response require_admin =",
"this component, please refer to the documentation at https://developers.home-assistant.io/docs/external_api_websocket.html \"\"\"",
"messages DOMAIN = const.DOMAIN DEPENDENCIES = ('http',) # Backwards compat",
"handlers = hass.data[DOMAIN] = {} handlers[command] = (handler, schema) async",
"async_register_command(hass, command, handler, schema): \"\"\"Register a websocket command.\"\"\" handlers =",
"is None: handlers = hass.data[DOMAIN] = {} handlers[command] = (handler,",
"hass.data[DOMAIN] = {} handlers[command] = (handler, schema) async def async_setup(hass,",
"callback from homeassistant.loader import bind_hass from . import commands, connection,",
"compat / Make it easier to integrate # pylint: disable=invalid-name",
"= decorators.ws_require_user # pylint: enable=invalid-name @bind_hass @callback def async_register_command(hass, command,",
"handlers[command] = (handler, schema) async def async_setup(hass, config): \"\"\"Initialize the",
"# Backwards compat / Make it easier to integrate #",
"schema): \"\"\"Register a websocket command.\"\"\" handlers = hass.data.get(DOMAIN) if handlers",
"at https://developers.home-assistant.io/docs/external_api_websocket.html \"\"\" from homeassistant.core import callback from homeassistant.loader import",
"the documentation at https://developers.home-assistant.io/docs/external_api_websocket.html \"\"\" from homeassistant.core import callback from",
". import commands, connection, const, decorators, http, messages DOMAIN =",
"= decorators.async_response require_admin = decorators.require_admin ws_require_user = decorators.ws_require_user # pylint:",
"# pylint: enable=invalid-name @bind_hass @callback def async_register_command(hass, command, handler, schema):",
"async def async_setup(hass, config): \"\"\"Initialize the websocket API.\"\"\" hass.http.register_view(http.WebsocketAPIView) commands.async_register_commands(hass)",
"messages.BASE_COMMAND_MESSAGE_SCHEMA error_message = messages.error_message result_message = messages.result_message async_response = decorators.async_response",
"async_response = decorators.async_response require_admin = decorators.require_admin ws_require_user = decorators.ws_require_user #",
"command, handler, schema): \"\"\"Register a websocket command.\"\"\" handlers = hass.data.get(DOMAIN)",
"disable=invalid-name ActiveConnection = connection.ActiveConnection BASE_COMMAND_MESSAGE_SCHEMA = messages.BASE_COMMAND_MESSAGE_SCHEMA error_message = messages.error_message",
"hass.data.get(DOMAIN) if handlers is None: handlers = hass.data[DOMAIN] = {}",
"from homeassistant.core import callback from homeassistant.loader import bind_hass from .",
"please refer to the documentation at https://developers.home-assistant.io/docs/external_api_websocket.html \"\"\" from homeassistant.core",
"messages.error_message result_message = messages.result_message async_response = decorators.async_response require_admin = decorators.require_admin",
"if handlers is None: handlers = hass.data[DOMAIN] = {} handlers[command]",
"connection, const, decorators, http, messages DOMAIN = const.DOMAIN DEPENDENCIES =",
"https://developers.home-assistant.io/docs/external_api_websocket.html \"\"\" from homeassistant.core import callback from homeassistant.loader import bind_hass",
"(handler, schema) async def async_setup(hass, config): \"\"\"Initialize the websocket API.\"\"\"",
"API for Home Assistant. For more details about this component,",
"= connection.ActiveConnection BASE_COMMAND_MESSAGE_SCHEMA = messages.BASE_COMMAND_MESSAGE_SCHEMA error_message = messages.error_message result_message =",
"from homeassistant.loader import bind_hass from . import commands, connection, const,",
"/ Make it easier to integrate # pylint: disable=invalid-name ActiveConnection",
"integrate # pylint: disable=invalid-name ActiveConnection = connection.ActiveConnection BASE_COMMAND_MESSAGE_SCHEMA = messages.BASE_COMMAND_MESSAGE_SCHEMA",
"For more details about this component, please refer to the",
"= messages.BASE_COMMAND_MESSAGE_SCHEMA error_message = messages.error_message result_message = messages.result_message async_response =",
"\"\"\" from homeassistant.core import callback from homeassistant.loader import bind_hass from",
"require_admin = decorators.require_admin ws_require_user = decorators.ws_require_user # pylint: enable=invalid-name @bind_hass",
"async_setup(hass, config): \"\"\"Initialize the websocket API.\"\"\" hass.http.register_view(http.WebsocketAPIView) commands.async_register_commands(hass) return True",
"def async_setup(hass, config): \"\"\"Initialize the websocket API.\"\"\" hass.http.register_view(http.WebsocketAPIView) commands.async_register_commands(hass) return",
"ActiveConnection = connection.ActiveConnection BASE_COMMAND_MESSAGE_SCHEMA = messages.BASE_COMMAND_MESSAGE_SCHEMA error_message = messages.error_message result_message",
"ws_require_user = decorators.ws_require_user # pylint: enable=invalid-name @bind_hass @callback def async_register_command(hass,",
"Home Assistant. For more details about this component, please refer",
"command.\"\"\" handlers = hass.data.get(DOMAIN) if handlers is None: handlers =",
"= hass.data[DOMAIN] = {} handlers[command] = (handler, schema) async def",
"('http',) # Backwards compat / Make it easier to integrate",
"pylint: disable=invalid-name ActiveConnection = connection.ActiveConnection BASE_COMMAND_MESSAGE_SCHEMA = messages.BASE_COMMAND_MESSAGE_SCHEMA error_message =",
"decorators.ws_require_user # pylint: enable=invalid-name @bind_hass @callback def async_register_command(hass, command, handler,",
"to the documentation at https://developers.home-assistant.io/docs/external_api_websocket.html \"\"\" from homeassistant.core import callback",
"to integrate # pylint: disable=invalid-name ActiveConnection = connection.ActiveConnection BASE_COMMAND_MESSAGE_SCHEMA =",
"component, please refer to the documentation at https://developers.home-assistant.io/docs/external_api_websocket.html \"\"\" from",
"messages.result_message async_response = decorators.async_response require_admin = decorators.require_admin ws_require_user = decorators.ws_require_user",
"handlers is None: handlers = hass.data[DOMAIN] = {} handlers[command] =",
"homeassistant.loader import bind_hass from . import commands, connection, const, decorators,",
"= const.DOMAIN DEPENDENCIES = ('http',) # Backwards compat / Make",
"result_message = messages.result_message async_response = decorators.async_response require_admin = decorators.require_admin ws_require_user",
"= (handler, schema) async def async_setup(hass, config): \"\"\"Initialize the websocket",
"<reponame>dannyqwertz/home-assistant \"\"\" Websocket based API for Home Assistant. For more",
"websocket command.\"\"\" handlers = hass.data.get(DOMAIN) if handlers is None: handlers",
"\"\"\" Websocket based API for Home Assistant. For more details",
"bind_hass from . import commands, connection, const, decorators, http, messages",
"enable=invalid-name @bind_hass @callback def async_register_command(hass, command, handler, schema): \"\"\"Register a",
"decorators.require_admin ws_require_user = decorators.ws_require_user # pylint: enable=invalid-name @bind_hass @callback def",
"details about this component, please refer to the documentation at",
"@callback def async_register_command(hass, command, handler, schema): \"\"\"Register a websocket command.\"\"\"",
"schema) async def async_setup(hass, config): \"\"\"Initialize the websocket API.\"\"\" hass.http.register_view(http.WebsocketAPIView)",
"= ('http',) # Backwards compat / Make it easier to",
"None: handlers = hass.data[DOMAIN] = {} handlers[command] = (handler, schema)",
"BASE_COMMAND_MESSAGE_SCHEMA = messages.BASE_COMMAND_MESSAGE_SCHEMA error_message = messages.error_message result_message = messages.result_message async_response",
"handlers = hass.data.get(DOMAIN) if handlers is None: handlers = hass.data[DOMAIN]",
"Assistant. For more details about this component, please refer to",
"refer to the documentation at https://developers.home-assistant.io/docs/external_api_websocket.html \"\"\" from homeassistant.core import",
"= messages.result_message async_response = decorators.async_response require_admin = decorators.require_admin ws_require_user =",
"a websocket command.\"\"\" handlers = hass.data.get(DOMAIN) if handlers is None:",
"import bind_hass from . import commands, connection, const, decorators, http,",
"Websocket based API for Home Assistant. For more details about",
"for Home Assistant. For more details about this component, please",
"Make it easier to integrate # pylint: disable=invalid-name ActiveConnection =",
"@bind_hass @callback def async_register_command(hass, command, handler, schema): \"\"\"Register a websocket",
"DOMAIN = const.DOMAIN DEPENDENCIES = ('http',) # Backwards compat /",
"\"\"\"Register a websocket command.\"\"\" handlers = hass.data.get(DOMAIN) if handlers is",
"decorators, http, messages DOMAIN = const.DOMAIN DEPENDENCIES = ('http',) #",
"# pylint: disable=invalid-name ActiveConnection = connection.ActiveConnection BASE_COMMAND_MESSAGE_SCHEMA = messages.BASE_COMMAND_MESSAGE_SCHEMA error_message",
"import callback from homeassistant.loader import bind_hass from . import commands,",
"based API for Home Assistant. For more details about this",
"about this component, please refer to the documentation at https://developers.home-assistant.io/docs/external_api_websocket.html",
"more details about this component, please refer to the documentation",
"easier to integrate # pylint: disable=invalid-name ActiveConnection = connection.ActiveConnection BASE_COMMAND_MESSAGE_SCHEMA",
"connection.ActiveConnection BASE_COMMAND_MESSAGE_SCHEMA = messages.BASE_COMMAND_MESSAGE_SCHEMA error_message = messages.error_message result_message = messages.result_message",
"commands, connection, const, decorators, http, messages DOMAIN = const.DOMAIN DEPENDENCIES",
"error_message = messages.error_message result_message = messages.result_message async_response = decorators.async_response require_admin",
"homeassistant.core import callback from homeassistant.loader import bind_hass from . import",
"pylint: enable=invalid-name @bind_hass @callback def async_register_command(hass, command, handler, schema): \"\"\"Register",
"import commands, connection, const, decorators, http, messages DOMAIN = const.DOMAIN",
"handler, schema): \"\"\"Register a websocket command.\"\"\" handlers = hass.data.get(DOMAIN) if",
"from . import commands, connection, const, decorators, http, messages DOMAIN",
"Backwards compat / Make it easier to integrate # pylint:",
"def async_register_command(hass, command, handler, schema): \"\"\"Register a websocket command.\"\"\" handlers",
"http, messages DOMAIN = const.DOMAIN DEPENDENCIES = ('http',) # Backwards",
"documentation at https://developers.home-assistant.io/docs/external_api_websocket.html \"\"\" from homeassistant.core import callback from homeassistant.loader",
"DEPENDENCIES = ('http',) # Backwards compat / Make it easier",
"= hass.data.get(DOMAIN) if handlers is None: handlers = hass.data[DOMAIN] =",
"it easier to integrate # pylint: disable=invalid-name ActiveConnection = connection.ActiveConnection",
"= {} handlers[command] = (handler, schema) async def async_setup(hass, config):",
"{} handlers[command] = (handler, schema) async def async_setup(hass, config): \"\"\"Initialize",
"= decorators.require_admin ws_require_user = decorators.ws_require_user # pylint: enable=invalid-name @bind_hass @callback",
"decorators.async_response require_admin = decorators.require_admin ws_require_user = decorators.ws_require_user # pylint: enable=invalid-name",
"const.DOMAIN DEPENDENCIES = ('http',) # Backwards compat / Make it"
] |
[
"full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ \"\"\"",
"See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used",
"[] # Application definition INSTALLED_APPS = [ \"django.contrib.admin\", \"django.contrib.auth\", \"django.contrib.contenttypes\",",
"BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for",
"\"django.contrib.auth.middleware.AuthenticationMiddleware\", \"django.contrib.messages.middleware.MessageMiddleware\", \"django.middleware.clickjacking.XFrameOptionsMiddleware\", ] ROOT_URLCONF = \"test_app.urls\" TEMPLATES = [",
"STATIC_URL = \"/static/\" BASE_DIR = Path(__file__).resolve().parent DOCUSIGN_API_ACCOUNT_ID = env( \"DOCUSIGN_API_ACCOUNT_ID\",",
"DOCUSIGN_API_ACCOUNT_ID = env( \"DOCUSIGN_API_ACCOUNT_ID\", default=\"<Docusign API Account Id >\" )",
"Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = \"/static/\" BASE_DIR = Path(__file__).resolve().parent DOCUSIGN_API_ACCOUNT_ID",
"Path(__file__).resolve().parent DOCUSIGN_API_ACCOUNT_ID = env( \"DOCUSIGN_API_ACCOUNT_ID\", default=\"<Docusign API Account Id >\"",
"= env( \"DOCUSIGN_API_ENDPOINT\", default=\"https://demo.docusign.net/restapi/v2.1/accounts/\" ) DOCUSIGN_TOKEN_EXPIRY_IN_SECONDS = env(\"DOCUSIGN_TOKEN_EXPIRY_IN_SECONDS\", default=3600) DOCUSIGN_AUTHORIZATION_SERVER",
"\"DOCUSIGN_API_ENDPOINT\", default=\"https://demo.docusign.net/restapi/v2.1/accounts/\" ) DOCUSIGN_TOKEN_EXPIRY_IN_SECONDS = env(\"DOCUSIGN_TOKEN_EXPIRY_IN_SECONDS\", default=3600) DOCUSIGN_AUTHORIZATION_SERVER = env(",
"of Summit Technology Group, Inc. # \"\"\" Django settings for",
"\"admin\", \"HOST\": \"localhost\", \"PORT\": \"5432\", } } # Password validation",
"validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { \"NAME\": \"django.contrib.auth.password_validation.UserAttributeSimilarityValidator\", },",
"in production! DEBUG = True ALLOWED_HOSTS = [] # Application",
"BASE_DIR = Path(__file__).resolve().parent DOCUSIGN_API_ACCOUNT_ID = env( \"DOCUSIGN_API_ACCOUNT_ID\", default=\"<Docusign API Account",
"2021 # # Copyright (c) 2021 Lenders Cooperative, a division",
"of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ \"\"\" from pathlib",
"{ \"BACKEND\": \"django.template.backends.django.DjangoTemplates\", \"DIRS\": [], \"APP_DIRS\": True, \"OPTIONS\": { \"context_processors\":",
"import Path import environ env = environ.Env() # Build paths",
"see https://docs.djangoproject.com/en/3.1/ref/settings/ \"\"\" from pathlib import Path import environ env",
"env( \"DOCUSIGN_AUTHORIZATION_SERVER\", default=\"account-d.docusign.com\" ) DOCUSIGN_PRIVATE_KEY_FILE = env( \"DOCUSIGN_PRIVATE_KEY_FILE\", default=\"<Private Key",
"environ env = environ.Env() # Build paths inside the project",
"\"NAME\": \"django.contrib.auth.password_validation.MinimumLengthValidator\", }, { \"NAME\": \"django.contrib.auth.password_validation.CommonPasswordValidator\", }, { \"NAME\": \"django.contrib.auth.password_validation.NumericPasswordValidator\",",
"file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and",
"WARNING: keep the secret key used in production secret! SECRET_KEY",
"}, { \"NAME\": \"django.contrib.auth.password_validation.NumericPasswordValidator\", }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/",
"API Account Id >\" ) DOCUSIGN_CLIENT_ID = env(\"DOCUSIGN_CLIENT_ID\", default=\"<Docusign Client",
"\"django.middleware.csrf.CsrfViewMiddleware\", \"django.contrib.auth.middleware.AuthenticationMiddleware\", \"django.contrib.messages.middleware.MessageMiddleware\", \"django.middleware.clickjacking.XFrameOptionsMiddleware\", ] ROOT_URLCONF = \"test_app.urls\" TEMPLATES =",
"division of Summit Technology Group, Inc. # \"\"\" Django settings",
"default=\"https://demo.docusign.net/restapi/v2.1/accounts/\" ) DOCUSIGN_TOKEN_EXPIRY_IN_SECONDS = env(\"DOCUSIGN_TOKEN_EXPIRY_IN_SECONDS\", default=3600) DOCUSIGN_AUTHORIZATION_SERVER = env( \"DOCUSIGN_AUTHORIZATION_SERVER\",",
"\"django.middleware.common.CommonMiddleware\", \"django.middleware.csrf.CsrfViewMiddleware\", \"django.contrib.auth.middleware.AuthenticationMiddleware\", \"django.contrib.messages.middleware.MessageMiddleware\", \"django.middleware.clickjacking.XFrameOptionsMiddleware\", ] ROOT_URLCONF = \"test_app.urls\" TEMPLATES",
"\"django.middleware.security.SecurityMiddleware\", \"django.contrib.sessions.middleware.SessionMiddleware\", \"django.middleware.common.CommonMiddleware\", \"django.middleware.csrf.CsrfViewMiddleware\", \"django.contrib.auth.middleware.AuthenticationMiddleware\", \"django.contrib.messages.middleware.MessageMiddleware\", \"django.middleware.clickjacking.XFrameOptionsMiddleware\", ] ROOT_URLCONF =",
"[ \"django.template.context_processors.debug\", \"django.template.context_processors.request\", \"django.contrib.auth.context_processors.auth\", \"django.contrib.messages.context_processors.messages\", ], }, }, ] WSGI_APPLICATION",
"like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start",
"information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list",
"env( \"DOCUSIGN_API_ACCOUNT_ID\", default=\"<Docusign API Account Id >\" ) DOCUSIGN_CLIENT_ID =",
"# # Copyright (c) 2021 Lenders Cooperative, a division of",
"[ { \"BACKEND\": \"django.template.backends.django.DjangoTemplates\", \"DIRS\": [], \"APP_DIRS\": True, \"OPTIONS\": {",
"# https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = \"en-us\" TIME_ZONE = \"UTC\" USE_I18N =",
"\"en-us\" TIME_ZONE = \"UTC\" USE_I18N = True USE_L10N = True",
"JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = \"/static/\" BASE_DIR = Path(__file__).resolve().parent",
"Generated by 'django-admin startproject' using Django 3.1.7. For more information",
"= environ.Env() # Build paths inside the project like this:",
"test_app project. Generated by 'django-admin startproject' using Django 3.1.7. For",
"Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production #",
"in production secret! SECRET_KEY = \"<KEY>\" # SECURITY WARNING: don't",
"= Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production",
"secret! SECRET_KEY = \"<KEY>\" # SECURITY WARNING: don't run with",
"on in production! DEBUG = True ALLOWED_HOSTS = [] #",
"[ \"django.middleware.security.SecurityMiddleware\", \"django.contrib.sessions.middleware.SessionMiddleware\", \"django.middleware.common.CommonMiddleware\", \"django.middleware.csrf.CsrfViewMiddleware\", \"django.contrib.auth.middleware.AuthenticationMiddleware\", \"django.contrib.messages.middleware.MessageMiddleware\", \"django.middleware.clickjacking.XFrameOptionsMiddleware\", ] ROOT_URLCONF",
"DOCUSIGN_AUTHORIZATION_SERVER = env( \"DOCUSIGN_AUTHORIZATION_SERVER\", default=\"account-d.docusign.com\" ) DOCUSIGN_PRIVATE_KEY_FILE = env( \"DOCUSIGN_PRIVATE_KEY_FILE\",",
"\"los_docusign.apps.LosDocusignConfig\", \"test_app.test_organization.apps.TestOrganizationConfig\", \"django_lc_utils\", ] MIDDLEWARE = [ \"django.middleware.security.SecurityMiddleware\", \"django.contrib.sessions.middleware.SessionMiddleware\", \"django.middleware.common.CommonMiddleware\",",
"\"ENGINE\": \"django.db.backends.postgresql_psycopg2\", \"NAME\": \"docusign_new_poc\", \"USER\": \"postgres\", \"PASSWORD\": \"admin\", \"HOST\": \"localhost\",",
"\"localhost\", \"PORT\": \"5432\", } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators",
"\"django.template.backends.django.DjangoTemplates\", \"DIRS\": [], \"APP_DIRS\": True, \"OPTIONS\": { \"context_processors\": [ \"django.template.context_processors.debug\",",
"\"USER\": \"postgres\", \"PASSWORD\": \"admin\", \"HOST\": \"localhost\", \"PORT\": \"5432\", } }",
"= [ { \"NAME\": \"django.contrib.auth.password_validation.UserAttributeSimilarityValidator\", }, { \"NAME\": \"django.contrib.auth.password_validation.MinimumLengthValidator\", },",
"definition INSTALLED_APPS = [ \"django.contrib.admin\", \"django.contrib.auth\", \"django.contrib.contenttypes\", \"django.contrib.sessions\", \"django.contrib.messages\", \"django.contrib.staticfiles\",",
"settings for test_app project. Generated by 'django-admin startproject' using Django",
"\"django.contrib.auth.password_validation.CommonPasswordValidator\", }, { \"NAME\": \"django.contrib.auth.password_validation.NumericPasswordValidator\", }, ] # Internationalization #",
"Copyright (c) 2021 Lenders Cooperative, a division of Summit Technology",
"env = environ.Env() # Build paths inside the project like",
"\"django.contrib.staticfiles\", \"los_docusign.apps.LosDocusignConfig\", \"test_app.test_organization.apps.TestOrganizationConfig\", \"django_lc_utils\", ] MIDDLEWARE = [ \"django.middleware.security.SecurityMiddleware\", \"django.contrib.sessions.middleware.SessionMiddleware\",",
"from pathlib import Path import environ env = environ.Env() #",
"\"<KEY>\" # SECURITY WARNING: don't run with debug turned on",
"# Quick-start development settings - unsuitable for production # See",
"For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the",
"used in production secret! SECRET_KEY = \"<KEY>\" # SECURITY WARNING:",
"https://docs.djangoproject.com/en/3.1/ref/settings/ \"\"\" from pathlib import Path import environ env =",
"Application definition INSTALLED_APPS = [ \"django.contrib.admin\", \"django.contrib.auth\", \"django.contrib.contenttypes\", \"django.contrib.sessions\", \"django.contrib.messages\",",
"startproject' using Django 3.1.7. For more information on this file,",
"\"default\": { \"ENGINE\": \"django.db.backends.postgresql_psycopg2\", \"NAME\": \"docusign_new_poc\", \"USER\": \"postgres\", \"PASSWORD\": \"admin\",",
"files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = \"/static/\" BASE_DIR",
"https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = \"/static/\" BASE_DIR = Path(__file__).resolve().parent DOCUSIGN_API_ACCOUNT_ID = env(",
"project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent #",
"# Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { \"default\": { \"ENGINE\":",
"# Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = \"en-us\" TIME_ZONE = \"UTC\"",
"default=\"account-d.docusign.com\" ) DOCUSIGN_PRIVATE_KEY_FILE = env( \"DOCUSIGN_PRIVATE_KEY_FILE\", default=\"<Private Key file data>\",",
") DOCUSIGN_PRIVATE_KEY_FILE = env( \"DOCUSIGN_PRIVATE_KEY_FILE\", default=\"<Private Key file data>\", )",
"using Django 3.1.7. For more information on this file, see",
"MIDDLEWARE = [ \"django.middleware.security.SecurityMiddleware\", \"django.contrib.sessions.middleware.SessionMiddleware\", \"django.middleware.common.CommonMiddleware\", \"django.middleware.csrf.CsrfViewMiddleware\", \"django.contrib.auth.middleware.AuthenticationMiddleware\", \"django.contrib.messages.middleware.MessageMiddleware\", \"django.middleware.clickjacking.XFrameOptionsMiddleware\",",
"for test_app project. Generated by 'django-admin startproject' using Django 3.1.7.",
"list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ \"\"\" from",
"\"django.contrib.contenttypes\", \"django.contrib.sessions\", \"django.contrib.messages\", \"django.contrib.staticfiles\", \"los_docusign.apps.LosDocusignConfig\", \"test_app.test_organization.apps.TestOrganizationConfig\", \"django_lc_utils\", ] MIDDLEWARE =",
"production! DEBUG = True ALLOWED_HOSTS = [] # Application definition",
"\"NAME\": \"django.contrib.auth.password_validation.CommonPasswordValidator\", }, { \"NAME\": \"django.contrib.auth.password_validation.NumericPasswordValidator\", }, ] # Internationalization",
"https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { \"default\": { \"ENGINE\": \"django.db.backends.postgresql_psycopg2\", \"NAME\": \"docusign_new_poc\",",
"by 'django-admin startproject' using Django 3.1.7. For more information on",
"default=\"<Docusign API Account Id >\" ) DOCUSIGN_CLIENT_ID = env(\"DOCUSIGN_CLIENT_ID\", default=\"<Docusign",
"\"django.contrib.sessions.middleware.SessionMiddleware\", \"django.middleware.common.CommonMiddleware\", \"django.middleware.csrf.CsrfViewMiddleware\", \"django.contrib.auth.middleware.AuthenticationMiddleware\", \"django.contrib.messages.middleware.MessageMiddleware\", \"django.middleware.clickjacking.XFrameOptionsMiddleware\", ] ROOT_URLCONF = \"test_app.urls\"",
"env(\"DOCUSIGN_CLIENT_ID\", default=\"<Docusign Client Id>\") DOCUSIGN_API_ENDPOINT = env( \"DOCUSIGN_API_ENDPOINT\", default=\"https://demo.docusign.net/restapi/v2.1/accounts/\" )",
"\"django.contrib.auth.password_validation.MinimumLengthValidator\", }, { \"NAME\": \"django.contrib.auth.password_validation.CommonPasswordValidator\", }, { \"NAME\": \"django.contrib.auth.password_validation.NumericPasswordValidator\", },",
"DOCUSIGN_PRIVATE_KEY_FILE = env( \"DOCUSIGN_PRIVATE_KEY_FILE\", default=\"<Private Key file data>\", ) DOCUSIGN_ENABLE_KBA",
"WARNING: don't run with debug turned on in production! DEBUG",
"\"/static/\" BASE_DIR = Path(__file__).resolve().parent DOCUSIGN_API_ACCOUNT_ID = env( \"DOCUSIGN_API_ACCOUNT_ID\", default=\"<Docusign API",
"= True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS =",
"Account Id >\" ) DOCUSIGN_CLIENT_ID = env(\"DOCUSIGN_CLIENT_ID\", default=\"<Docusign Client Id>\")",
"Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { \"default\": { \"ENGINE\": \"django.db.backends.postgresql_psycopg2\",",
"# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { \"NAME\": \"django.contrib.auth.password_validation.UserAttributeSimilarityValidator\", }, {",
">\" ) DOCUSIGN_CLIENT_ID = env(\"DOCUSIGN_CLIENT_ID\", default=\"<Docusign Client Id>\") DOCUSIGN_API_ENDPOINT =",
"TEMPLATES = [ { \"BACKEND\": \"django.template.backends.django.DjangoTemplates\", \"DIRS\": [], \"APP_DIRS\": True,",
"values, see https://docs.djangoproject.com/en/3.1/ref/settings/ \"\"\" from pathlib import Path import environ",
"\"NAME\": \"docusign_new_poc\", \"USER\": \"postgres\", \"PASSWORD\": \"admin\", \"HOST\": \"localhost\", \"PORT\": \"5432\",",
"turned on in production! DEBUG = True ALLOWED_HOSTS = []",
"this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development",
"= \"/static/\" BASE_DIR = Path(__file__).resolve().parent DOCUSIGN_API_ACCOUNT_ID = env( \"DOCUSIGN_API_ACCOUNT_ID\", default=\"<Docusign",
"# https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { \"default\": { \"ENGINE\": \"django.db.backends.postgresql_psycopg2\", \"NAME\":",
"\"django.contrib.messages\", \"django.contrib.staticfiles\", \"los_docusign.apps.LosDocusignConfig\", \"test_app.test_organization.apps.TestOrganizationConfig\", \"django_lc_utils\", ] MIDDLEWARE = [ \"django.middleware.security.SecurityMiddleware\",",
"Cooperative, a division of Summit Technology Group, Inc. # \"\"\"",
"\"django.contrib.auth.password_validation.NumericPasswordValidator\", }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = \"en-us\"",
"a division of Summit Technology Group, Inc. # \"\"\" Django",
"Tue Dec 21 2021 # # Copyright (c) 2021 Lenders",
"\"APP_DIRS\": True, \"OPTIONS\": { \"context_processors\": [ \"django.template.context_processors.debug\", \"django.template.context_processors.request\", \"django.contrib.auth.context_processors.auth\", \"django.contrib.messages.context_processors.messages\",",
"= True USE_TZ = True # Static files (CSS, JavaScript,",
"default=3600) DOCUSIGN_AUTHORIZATION_SERVER = env( \"DOCUSIGN_AUTHORIZATION_SERVER\", default=\"account-d.docusign.com\" ) DOCUSIGN_PRIVATE_KEY_FILE = env(",
"= \"test_app.wsgi.application\" # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { \"default\":",
"} } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [",
"see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their",
"\"NAME\": \"django.contrib.auth.password_validation.UserAttributeSimilarityValidator\", }, { \"NAME\": \"django.contrib.auth.password_validation.MinimumLengthValidator\", }, { \"NAME\": \"django.contrib.auth.password_validation.CommonPasswordValidator\",",
"}, }, ] WSGI_APPLICATION = \"test_app.wsgi.application\" # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases",
") DOCUSIGN_CLIENT_ID = env(\"DOCUSIGN_CLIENT_ID\", default=\"<Docusign Client Id>\") DOCUSIGN_API_ENDPOINT = env(",
"\"django.contrib.messages.middleware.MessageMiddleware\", \"django.middleware.clickjacking.XFrameOptionsMiddleware\", ] ROOT_URLCONF = \"test_app.urls\" TEMPLATES = [ {",
"\"context_processors\": [ \"django.template.context_processors.debug\", \"django.template.context_processors.request\", \"django.contrib.auth.context_processors.auth\", \"django.contrib.messages.context_processors.messages\", ], }, }, ]",
"DOCUSIGN_TOKEN_EXPIRY_IN_SECONDS = env(\"DOCUSIGN_TOKEN_EXPIRY_IN_SECONDS\", default=3600) DOCUSIGN_AUTHORIZATION_SERVER = env( \"DOCUSIGN_AUTHORIZATION_SERVER\", default=\"account-d.docusign.com\" )",
"\"\"\" from pathlib import Path import environ env = environ.Env()",
"paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR",
"\"\"\" Django settings for test_app project. Generated by 'django-admin startproject'",
"BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings",
"\"django.contrib.auth.context_processors.auth\", \"django.contrib.messages.context_processors.messages\", ], }, }, ] WSGI_APPLICATION = \"test_app.wsgi.application\" #",
"{ \"NAME\": \"django.contrib.auth.password_validation.NumericPasswordValidator\", }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE",
"# Copyright (c) 2021 Lenders Cooperative, a division of Summit",
"# \"\"\" Django settings for test_app project. Generated by 'django-admin",
"SECURITY WARNING: don't run with debug turned on in production!",
"\"DOCUSIGN_AUTHORIZATION_SERVER\", default=\"account-d.docusign.com\" ) DOCUSIGN_PRIVATE_KEY_FILE = env( \"DOCUSIGN_PRIVATE_KEY_FILE\", default=\"<Private Key file",
"run with debug turned on in production! DEBUG = True",
"True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL",
"# Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL =",
"key used in production secret! SECRET_KEY = \"<KEY>\" # SECURITY",
"\"BACKEND\": \"django.template.backends.django.DjangoTemplates\", \"DIRS\": [], \"APP_DIRS\": True, \"OPTIONS\": { \"context_processors\": [",
"{ \"context_processors\": [ \"django.template.context_processors.debug\", \"django.template.context_processors.request\", \"django.contrib.auth.context_processors.auth\", \"django.contrib.messages.context_processors.messages\", ], }, },",
"settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY",
"more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full",
"# SECURITY WARNING: don't run with debug turned on in",
"} # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ {",
"<reponame>Lenders-Cooperative/Django-DocuSign<filename>test_app/settings.py # # Created on Tue Dec 21 2021 #",
"Django settings for test_app project. Generated by 'django-admin startproject' using",
"Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/",
"[ \"django.contrib.admin\", \"django.contrib.auth\", \"django.contrib.contenttypes\", \"django.contrib.sessions\", \"django.contrib.messages\", \"django.contrib.staticfiles\", \"los_docusign.apps.LosDocusignConfig\", \"test_app.test_organization.apps.TestOrganizationConfig\", \"django_lc_utils\",",
"with debug turned on in production! DEBUG = True ALLOWED_HOSTS",
"\"django.template.context_processors.debug\", \"django.template.context_processors.request\", \"django.contrib.auth.context_processors.auth\", \"django.contrib.messages.context_processors.messages\", ], }, }, ] WSGI_APPLICATION =",
"Dec 21 2021 # # Copyright (c) 2021 Lenders Cooperative,",
"(c) 2021 Lenders Cooperative, a division of Summit Technology Group,",
"settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ \"\"\" from pathlib import",
"- unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING:",
"# SECURITY WARNING: keep the secret key used in production",
"}, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = \"en-us\" TIME_ZONE",
"USE_TZ = True # Static files (CSS, JavaScript, Images) #",
"# https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = \"/static/\" BASE_DIR = Path(__file__).resolve().parent DOCUSIGN_API_ACCOUNT_ID =",
"3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For",
"don't run with debug turned on in production! DEBUG =",
"[], \"APP_DIRS\": True, \"OPTIONS\": { \"context_processors\": [ \"django.template.context_processors.debug\", \"django.template.context_processors.request\", \"django.contrib.auth.context_processors.auth\",",
"\"django.contrib.messages.context_processors.messages\", ], }, }, ] WSGI_APPLICATION = \"test_app.wsgi.application\" # Database",
"\"django_lc_utils\", ] MIDDLEWARE = [ \"django.middleware.security.SecurityMiddleware\", \"django.contrib.sessions.middleware.SessionMiddleware\", \"django.middleware.common.CommonMiddleware\", \"django.middleware.csrf.CsrfViewMiddleware\", \"django.contrib.auth.middleware.AuthenticationMiddleware\",",
"\"django.contrib.auth\", \"django.contrib.contenttypes\", \"django.contrib.sessions\", \"django.contrib.messages\", \"django.contrib.staticfiles\", \"los_docusign.apps.LosDocusignConfig\", \"test_app.test_organization.apps.TestOrganizationConfig\", \"django_lc_utils\", ] MIDDLEWARE",
"[ { \"NAME\": \"django.contrib.auth.password_validation.UserAttributeSimilarityValidator\", }, { \"NAME\": \"django.contrib.auth.password_validation.MinimumLengthValidator\", }, {",
"pathlib import Path import environ env = environ.Env() # Build",
"https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values,",
"\"OPTIONS\": { \"context_processors\": [ \"django.template.context_processors.debug\", \"django.template.context_processors.request\", \"django.contrib.auth.context_processors.auth\", \"django.contrib.messages.context_processors.messages\", ], },",
"\"DIRS\": [], \"APP_DIRS\": True, \"OPTIONS\": { \"context_processors\": [ \"django.template.context_processors.debug\", \"django.template.context_processors.request\",",
"on Tue Dec 21 2021 # # Copyright (c) 2021",
"\"NAME\": \"django.contrib.auth.password_validation.NumericPasswordValidator\", }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE =",
"= [ { \"BACKEND\": \"django.template.backends.django.DjangoTemplates\", \"DIRS\": [], \"APP_DIRS\": True, \"OPTIONS\":",
"https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in",
"] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = \"en-us\" TIME_ZONE =",
"Client Id>\") DOCUSIGN_API_ENDPOINT = env( \"DOCUSIGN_API_ENDPOINT\", default=\"https://demo.docusign.net/restapi/v2.1/accounts/\" ) DOCUSIGN_TOKEN_EXPIRY_IN_SECONDS =",
"{ \"ENGINE\": \"django.db.backends.postgresql_psycopg2\", \"NAME\": \"docusign_new_poc\", \"USER\": \"postgres\", \"PASSWORD\": \"admin\", \"HOST\":",
"their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ \"\"\" from pathlib import Path import",
"= [ \"django.middleware.security.SecurityMiddleware\", \"django.contrib.sessions.middleware.SessionMiddleware\", \"django.middleware.common.CommonMiddleware\", \"django.middleware.csrf.CsrfViewMiddleware\", \"django.contrib.auth.middleware.AuthenticationMiddleware\", \"django.contrib.messages.middleware.MessageMiddleware\", \"django.middleware.clickjacking.XFrameOptionsMiddleware\", ]",
"], }, }, ] WSGI_APPLICATION = \"test_app.wsgi.application\" # Database #",
"# Created on Tue Dec 21 2021 # # Copyright",
"the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent",
"] ROOT_URLCONF = \"test_app.urls\" TEMPLATES = [ { \"BACKEND\": \"django.template.backends.django.DjangoTemplates\",",
"'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable",
"\"django.contrib.sessions\", \"django.contrib.messages\", \"django.contrib.staticfiles\", \"los_docusign.apps.LosDocusignConfig\", \"test_app.test_organization.apps.TestOrganizationConfig\", \"django_lc_utils\", ] MIDDLEWARE = [",
"= True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/",
"the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/",
") DOCUSIGN_TOKEN_EXPIRY_IN_SECONDS = env(\"DOCUSIGN_TOKEN_EXPIRY_IN_SECONDS\", default=3600) DOCUSIGN_AUTHORIZATION_SERVER = env( \"DOCUSIGN_AUTHORIZATION_SERVER\", default=\"account-d.docusign.com\"",
"\"test_app.test_organization.apps.TestOrganizationConfig\", \"django_lc_utils\", ] MIDDLEWARE = [ \"django.middleware.security.SecurityMiddleware\", \"django.contrib.sessions.middleware.SessionMiddleware\", \"django.middleware.common.CommonMiddleware\", \"django.middleware.csrf.CsrfViewMiddleware\",",
"'django-admin startproject' using Django 3.1.7. For more information on this",
"Technology Group, Inc. # \"\"\" Django settings for test_app project.",
"2021 Lenders Cooperative, a division of Summit Technology Group, Inc.",
"DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS",
"= env(\"DOCUSIGN_CLIENT_ID\", default=\"<Docusign Client Id>\") DOCUSIGN_API_ENDPOINT = env( \"DOCUSIGN_API_ENDPOINT\", default=\"https://demo.docusign.net/restapi/v2.1/accounts/\"",
"= \"en-us\" TIME_ZONE = \"UTC\" USE_I18N = True USE_L10N =",
"True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [",
"\"test_app.urls\" TEMPLATES = [ { \"BACKEND\": \"django.template.backends.django.DjangoTemplates\", \"DIRS\": [], \"APP_DIRS\":",
"environ.Env() # Build paths inside the project like this: BASE_DIR",
"env( \"DOCUSIGN_API_ENDPOINT\", default=\"https://demo.docusign.net/restapi/v2.1/accounts/\" ) DOCUSIGN_TOKEN_EXPIRY_IN_SECONDS = env(\"DOCUSIGN_TOKEN_EXPIRY_IN_SECONDS\", default=3600) DOCUSIGN_AUTHORIZATION_SERVER =",
"{ \"NAME\": \"django.contrib.auth.password_validation.UserAttributeSimilarityValidator\", }, { \"NAME\": \"django.contrib.auth.password_validation.MinimumLengthValidator\", }, { \"NAME\":",
"= env( \"DOCUSIGN_PRIVATE_KEY_FILE\", default=\"<Private Key file data>\", ) DOCUSIGN_ENABLE_KBA =",
"# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key",
"and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ \"\"\" from pathlib import Path",
"# # Created on Tue Dec 21 2021 # #",
"production secret! SECRET_KEY = \"<KEY>\" # SECURITY WARNING: don't run",
"\"django.contrib.admin\", \"django.contrib.auth\", \"django.contrib.contenttypes\", \"django.contrib.sessions\", \"django.contrib.messages\", \"django.contrib.staticfiles\", \"los_docusign.apps.LosDocusignConfig\", \"test_app.test_organization.apps.TestOrganizationConfig\", \"django_lc_utils\", ]",
"{ \"default\": { \"ENGINE\": \"django.db.backends.postgresql_psycopg2\", \"NAME\": \"docusign_new_poc\", \"USER\": \"postgres\", \"PASSWORD\":",
"inside the project like this: BASE_DIR / 'subdir'. BASE_DIR =",
"secret key used in production secret! SECRET_KEY = \"<KEY>\" #",
"this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings",
"ROOT_URLCONF = \"test_app.urls\" TEMPLATES = [ { \"BACKEND\": \"django.template.backends.django.DjangoTemplates\", \"DIRS\":",
"DATABASES = { \"default\": { \"ENGINE\": \"django.db.backends.postgresql_psycopg2\", \"NAME\": \"docusign_new_poc\", \"USER\":",
"Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { \"NAME\": \"django.contrib.auth.password_validation.UserAttributeSimilarityValidator\",",
"\"django.middleware.clickjacking.XFrameOptionsMiddleware\", ] ROOT_URLCONF = \"test_app.urls\" TEMPLATES = [ { \"BACKEND\":",
"= \"UTC\" USE_I18N = True USE_L10N = True USE_TZ =",
"Group, Inc. # \"\"\" Django settings for test_app project. Generated",
"USE_I18N = True USE_L10N = True USE_TZ = True #",
"TIME_ZONE = \"UTC\" USE_I18N = True USE_L10N = True USE_TZ",
"{ \"NAME\": \"django.contrib.auth.password_validation.CommonPasswordValidator\", }, { \"NAME\": \"django.contrib.auth.password_validation.NumericPasswordValidator\", }, ] #",
"True USE_L10N = True USE_TZ = True # Static files",
"the secret key used in production secret! SECRET_KEY = \"<KEY>\"",
"}, { \"NAME\": \"django.contrib.auth.password_validation.CommonPasswordValidator\", }, { \"NAME\": \"django.contrib.auth.password_validation.NumericPasswordValidator\", }, ]",
"AUTH_PASSWORD_VALIDATORS = [ { \"NAME\": \"django.contrib.auth.password_validation.UserAttributeSimilarityValidator\", }, { \"NAME\": \"django.contrib.auth.password_validation.MinimumLengthValidator\",",
"Summit Technology Group, Inc. # \"\"\" Django settings for test_app",
"Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = \"en-us\" TIME_ZONE = \"UTC\" USE_I18N",
"True USE_TZ = True # Static files (CSS, JavaScript, Images)",
"# Build paths inside the project like this: BASE_DIR /",
"= env( \"DOCUSIGN_AUTHORIZATION_SERVER\", default=\"account-d.docusign.com\" ) DOCUSIGN_PRIVATE_KEY_FILE = env( \"DOCUSIGN_PRIVATE_KEY_FILE\", default=\"<Private",
"\"django.template.context_processors.request\", \"django.contrib.auth.context_processors.auth\", \"django.contrib.messages.context_processors.messages\", ], }, }, ] WSGI_APPLICATION = \"test_app.wsgi.application\"",
"\"PORT\": \"5432\", } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS",
"= env(\"DOCUSIGN_TOKEN_EXPIRY_IN_SECONDS\", default=3600) DOCUSIGN_AUTHORIZATION_SERVER = env( \"DOCUSIGN_AUTHORIZATION_SERVER\", default=\"account-d.docusign.com\" ) DOCUSIGN_PRIVATE_KEY_FILE",
"Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = \"/static/\"",
"production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret",
"env(\"DOCUSIGN_TOKEN_EXPIRY_IN_SECONDS\", default=3600) DOCUSIGN_AUTHORIZATION_SERVER = env( \"DOCUSIGN_AUTHORIZATION_SERVER\", default=\"account-d.docusign.com\" ) DOCUSIGN_PRIVATE_KEY_FILE =",
"SECURITY WARNING: keep the secret key used in production secret!",
"\"django.db.backends.postgresql_psycopg2\", \"NAME\": \"docusign_new_poc\", \"USER\": \"postgres\", \"PASSWORD\": \"admin\", \"HOST\": \"localhost\", \"PORT\":",
"https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = \"en-us\" TIME_ZONE = \"UTC\" USE_I18N = True",
"For the full list of settings and their values, see",
"}, ] WSGI_APPLICATION = \"test_app.wsgi.application\" # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES",
"LANGUAGE_CODE = \"en-us\" TIME_ZONE = \"UTC\" USE_I18N = True USE_L10N",
"}, { \"NAME\": \"django.contrib.auth.password_validation.MinimumLengthValidator\", }, { \"NAME\": \"django.contrib.auth.password_validation.CommonPasswordValidator\", }, {",
"# Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { \"NAME\":",
"debug turned on in production! DEBUG = True ALLOWED_HOSTS =",
"SECRET_KEY = \"<KEY>\" # SECURITY WARNING: don't run with debug",
"default=\"<Docusign Client Id>\") DOCUSIGN_API_ENDPOINT = env( \"DOCUSIGN_API_ENDPOINT\", default=\"https://demo.docusign.net/restapi/v2.1/accounts/\" ) DOCUSIGN_TOKEN_EXPIRY_IN_SECONDS",
"WSGI_APPLICATION = \"test_app.wsgi.application\" # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = {",
"env( \"DOCUSIGN_PRIVATE_KEY_FILE\", default=\"<Private Key file data>\", ) DOCUSIGN_ENABLE_KBA = env(\"DOCUSIGN_ENABLE_KBA\",",
"= \"<KEY>\" # SECURITY WARNING: don't run with debug turned",
"\"HOST\": \"localhost\", \"PORT\": \"5432\", } } # Password validation #",
"development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ #",
"= [ \"django.contrib.admin\", \"django.contrib.auth\", \"django.contrib.contenttypes\", \"django.contrib.sessions\", \"django.contrib.messages\", \"django.contrib.staticfiles\", \"los_docusign.apps.LosDocusignConfig\", \"test_app.test_organization.apps.TestOrganizationConfig\",",
"ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ \"django.contrib.admin\",",
"on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of",
"INSTALLED_APPS = [ \"django.contrib.admin\", \"django.contrib.auth\", \"django.contrib.contenttypes\", \"django.contrib.sessions\", \"django.contrib.messages\", \"django.contrib.staticfiles\", \"los_docusign.apps.LosDocusignConfig\",",
"{ \"NAME\": \"django.contrib.auth.password_validation.MinimumLengthValidator\", }, { \"NAME\": \"django.contrib.auth.password_validation.CommonPasswordValidator\", }, { \"NAME\":",
"] WSGI_APPLICATION = \"test_app.wsgi.application\" # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES =",
"# Application definition INSTALLED_APPS = [ \"django.contrib.admin\", \"django.contrib.auth\", \"django.contrib.contenttypes\", \"django.contrib.sessions\",",
"= [] # Application definition INSTALLED_APPS = [ \"django.contrib.admin\", \"django.contrib.auth\",",
"\"PASSWORD\": \"admin\", \"HOST\": \"localhost\", \"PORT\": \"5432\", } } # Password",
"(CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = \"/static/\" BASE_DIR =",
"True, \"OPTIONS\": { \"context_processors\": [ \"django.template.context_processors.debug\", \"django.template.context_processors.request\", \"django.contrib.auth.context_processors.auth\", \"django.contrib.messages.context_processors.messages\", ],",
"\"test_app.wsgi.application\" # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { \"default\": {",
"Build paths inside the project like this: BASE_DIR / 'subdir'.",
"] MIDDLEWARE = [ \"django.middleware.security.SecurityMiddleware\", \"django.contrib.sessions.middleware.SessionMiddleware\", \"django.middleware.common.CommonMiddleware\", \"django.middleware.csrf.CsrfViewMiddleware\", \"django.contrib.auth.middleware.AuthenticationMiddleware\", \"django.contrib.messages.middleware.MessageMiddleware\",",
"\"5432\", } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS =",
"unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep",
"= Path(__file__).resolve().parent DOCUSIGN_API_ACCOUNT_ID = env( \"DOCUSIGN_API_ACCOUNT_ID\", default=\"<Docusign API Account Id",
"Path import environ env = environ.Env() # Build paths inside",
"= \"test_app.urls\" TEMPLATES = [ { \"BACKEND\": \"django.template.backends.django.DjangoTemplates\", \"DIRS\": [],",
"\"postgres\", \"PASSWORD\": \"admin\", \"HOST\": \"localhost\", \"PORT\": \"5432\", } } #",
"Id >\" ) DOCUSIGN_CLIENT_ID = env(\"DOCUSIGN_CLIENT_ID\", default=\"<Docusign Client Id>\") DOCUSIGN_API_ENDPOINT",
"\"UTC\" USE_I18N = True USE_L10N = True USE_TZ = True",
"keep the secret key used in production secret! SECRET_KEY =",
"\"DOCUSIGN_API_ACCOUNT_ID\", default=\"<Docusign API Account Id >\" ) DOCUSIGN_CLIENT_ID = env(\"DOCUSIGN_CLIENT_ID\",",
"Created on Tue Dec 21 2021 # # Copyright (c)",
"USE_L10N = True USE_TZ = True # Static files (CSS,",
"= { \"default\": { \"ENGINE\": \"django.db.backends.postgresql_psycopg2\", \"NAME\": \"docusign_new_poc\", \"USER\": \"postgres\",",
"import environ env = environ.Env() # Build paths inside the",
"DOCUSIGN_API_ENDPOINT = env( \"DOCUSIGN_API_ENDPOINT\", default=\"https://demo.docusign.net/restapi/v2.1/accounts/\" ) DOCUSIGN_TOKEN_EXPIRY_IN_SECONDS = env(\"DOCUSIGN_TOKEN_EXPIRY_IN_SECONDS\", default=3600)",
"Lenders Cooperative, a division of Summit Technology Group, Inc. #",
"= True USE_L10N = True USE_TZ = True # Static",
"https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { \"NAME\": \"django.contrib.auth.password_validation.UserAttributeSimilarityValidator\", }, { \"NAME\":",
"21 2021 # # Copyright (c) 2021 Lenders Cooperative, a",
"for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the",
"= env( \"DOCUSIGN_API_ACCOUNT_ID\", default=\"<Docusign API Account Id >\" ) DOCUSIGN_CLIENT_ID",
"Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/",
"\"docusign_new_poc\", \"USER\": \"postgres\", \"PASSWORD\": \"admin\", \"HOST\": \"localhost\", \"PORT\": \"5432\", }",
"\"DOCUSIGN_PRIVATE_KEY_FILE\", default=\"<Private Key file data>\", ) DOCUSIGN_ENABLE_KBA = env(\"DOCUSIGN_ENABLE_KBA\", default=False)",
"/ 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings -",
"Inc. # \"\"\" Django settings for test_app project. Generated by",
"project. Generated by 'django-admin startproject' using Django 3.1.7. For more",
"Id>\") DOCUSIGN_API_ENDPOINT = env( \"DOCUSIGN_API_ENDPOINT\", default=\"https://demo.docusign.net/restapi/v2.1/accounts/\" ) DOCUSIGN_TOKEN_EXPIRY_IN_SECONDS = env(\"DOCUSIGN_TOKEN_EXPIRY_IN_SECONDS\",",
"DOCUSIGN_CLIENT_ID = env(\"DOCUSIGN_CLIENT_ID\", default=\"<Docusign Client Id>\") DOCUSIGN_API_ENDPOINT = env( \"DOCUSIGN_API_ENDPOINT\",",
"\"django.contrib.auth.password_validation.UserAttributeSimilarityValidator\", }, { \"NAME\": \"django.contrib.auth.password_validation.MinimumLengthValidator\", }, { \"NAME\": \"django.contrib.auth.password_validation.CommonPasswordValidator\", },"
] |
[
"del query['type'] del query['criteria']['debtorName']['business'] del query['criteria']['value'] is_valid, errors = validate(query,",
"assert is_valid def test_invalid_search_query_missing_type(): \"\"\"Assert that an invalid search query",
"del query['criteria']['debtorName']['second'] del query['criteria']['debtorName']['last'] del query['criteria']['value'] query['criteria']['debtorName']['business'] = 'XXXX' is_valid,",
"an invalid search query fails - end date time format",
"that an invalid search query fails - debtor name is",
"2.0 (the \"License\"); # you may not use this file",
"- business name is too short.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del",
"query['type'] = 'INDIVIDUAL_DEBTOR' del query['criteria']['debtorName']['business'] del query['criteria']['value'] del query['clientReferenceId'] del",
"print(errors) assert not is_valid def test_invalid_search_query_value(): \"\"\"Assert that an invalid",
"Province of British Columbia # # Licensed under the Apache",
"del query['criteria']['debtorName'] query['criteria']['value'] = 'KM8J3CA46JU622994' is_valid, errors = validate(query, 'searchQuery',",
"is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] is_valid, errors =",
"del query['criteria']['debtorName']['first'] del query['criteria']['debtorName']['second'] del query['criteria']['debtorName']['last'] del query['criteria']['value'] is_valid, errors",
"def test_invalid_search_query_endts(): \"\"\"Assert that an invalid search query fails -",
"an invalid search query fails - debtor last name is",
"fails - debtor last name is too long.\"\"\" query =",
"for err in errors: print(err.message) print(errors) assert is_valid def test_valid_search_query_regnum():",
"query['criteria']['value'] = '21324' is_valid, errors = validate(query, 'searchQuery', 'ppr') if",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"query fails - debtor second name is too long.\"\"\" query",
"fails - criteria is missing.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']",
"del query['criteria']['debtorName']['business'] is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors:",
"in errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_type(): \"\"\"Assert",
"def test_invalid_search_query_lastname(): \"\"\"Assert that an invalid search query fails -",
"that an invalid search query fails - criteria is missing.\"\"\"",
"copy.deepcopy(SEARCH_QUERY) query['type'] = 'SERIAL_NUMBER' del query['criteria']['debtorName'] query['criteria']['value'] = 'KM8J3CA46JU622994' is_valid,",
"query['criteria']['value'] = 'XxxxxxxxxxxxxxxxxxxxXxxxxxxxxxxxxxxxxxxxXxxxxxxxxxx' is_valid, errors = validate(query, 'searchQuery', 'ppr') if",
"long.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['criteria']['debtorName']['second'] =",
"assert not is_valid def test_invalid_search_query_endts(): \"\"\"Assert that an invalid search",
"assert not is_valid def test_invalid_search_query_type(): \"\"\"Assert that an invalid search",
"for a search by individual debtor.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type']",
"individual debtor.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'INDIVIDUAL_DEBTOR' del query['criteria']['debtorName']['business']",
"def test_valid_search_query_mhrnum(): \"\"\"Assert that the schema is performing as expected",
"search by serial number.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'SERIAL_NUMBER'",
"an invalid search query fails - criteria is invalid.\"\"\" query",
"fails - debtor second name is too long.\"\"\" query =",
"search by individual debtor.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'INDIVIDUAL_DEBTOR'",
"search query fails - business name is too short.\"\"\" query",
"query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'XXXXXXXX' del query['criteria']['debtorName']['business'] del query['criteria']['value']",
"use this file except in compliance with the License. #",
"print(err.message) print(errors) assert is_valid def test_valid_search_query_mhrnum(): \"\"\"Assert that the schema",
"schema is performing as expected for a search by MHR",
"print(err.message) print(errors) assert is_valid def test_valid_search_query_serialnum(): \"\"\"Assert that the schema",
"'Xxxxxxxxxx' is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors: for",
"query fails - end date time format is invalid.\"\"\" query",
"errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_endts(): \"\"\"Assert that",
"in errors: print(err.message) print(errors) assert is_valid def test_valid_search_query_airdot(): \"\"\"Assert that",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"an invalid search query fails - type is missing.\"\"\" query",
"in errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_value(): \"\"\"Assert",
"query['criteria']['value'] del query['criteria']['debtorName']['business'] query['endDateTime'] = 'Xxxxxxxxxx' is_valid, errors = validate(query,",
"License. # You may obtain a copy of the License",
"search query fails - type is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY)",
"invalid search query fails - criteria is invalid.\"\"\" query =",
"that an invalid search query fails - business name is",
"is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'XXXXXXXX' del query['criteria']['debtorName']['business']",
"err in errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_firstname():",
"print(err.message) print(errors) assert not is_valid def test_invalid_search_query_lastname(): \"\"\"Assert that an",
"under the License is distributed on an \"AS IS\" BASIS,",
"errors: for err in errors: print(err.message) print(errors) assert not is_valid",
"ensure the PPR Search Query schema is valid. \"\"\" import",
"= copy.deepcopy(SEARCH_QUERY) del query['criteria'] is_valid, errors = validate(query, 'searchQuery', 'ppr')",
"is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['debtorName']['business'] is_valid, errors =",
"search query fails - client reference id is too long.\"\"\"",
"License for the specific language governing permissions and # limitations",
"query['startDateTime'] del query['endDateTime'] is_valid, errors = validate(query, 'searchQuery', 'ppr') if",
"assert not is_valid def test_invalid_search_query_firstname(): \"\"\"Assert that an invalid search",
"- client reference id is too long.\"\"\" query = copy.deepcopy(SEARCH_QUERY)",
"- start date time format is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY)",
"copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['startDateTime'] = 'Xxxxxxxxxx' is_valid, errors",
"invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] is_valid, errors = validate(query,",
"and # limitations under the License. \"\"\"Test Suite to ensure",
"print(errors) assert not is_valid def test_invalid_search_query_secondname(): \"\"\"Assert that an invalid",
"expected for a search by business debtor.\"\"\" query = copy.deepcopy(SEARCH_QUERY)",
"'AIRCRAFT_DOT' del query['criteria']['debtorName'] query['criteria']['value'] = 'CFYXW' is_valid, errors = validate(query,",
"for a search by MHR number.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type']",
"query['criteria']['debtorName'] query['criteria']['value'] = 'KM8J3CA46JU622994' is_valid, errors = validate(query, 'searchQuery', 'ppr')",
"- criteria is missing.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria'] is_valid,",
"a search by serial number.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] =",
"search query fails - debtor name is invalid.\"\"\" query =",
"errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_criteria(): \"\"\"Assert that",
"\"\"\"Assert that an invalid search query fails - debtor first",
"= copy.deepcopy(SEARCH_QUERY) query['type'] = 'MHR_NUMBER' del query['criteria']['debtorName'] query['criteria']['value'] = '21324'",
"\"\"\"Test Suite to ensure the PPR Search Query schema is",
"schema is performing as expected for a search by business",
"test_invalid_search_query_missing_criteria(): \"\"\"Assert that an invalid search query fails - criteria",
"for a search by business debtor.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type']",
"search by MHR number.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'MHR_NUMBER'",
"= copy.deepcopy(SEARCH_QUERY) del query['criteria']['debtorName']['first'] del query['criteria']['debtorName']['second'] del query['criteria']['debtorName']['last'] del query['criteria']['value']",
"del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['criteria']['debtorName']['second'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' is_valid, errors =",
"in compliance with the License. # You may obtain a",
"print(errors) assert is_valid def test_invalid_search_query_missing_type(): \"\"\"Assert that an invalid search",
"= 'XxxxxxxxxxXxxxxxxxxxX' is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors:",
"'REGISTRATION_NUMBER' del query['criteria']['debtorName'] query['criteria']['value'] = '023001B' is_valid, errors = validate(query,",
"software # distributed under the License is distributed on an",
"query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['criteria']['debtorName']['first'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'",
"performing as expected for a search by individual debtor.\"\"\" query",
"def test_invalid_search_query_clientref(): \"\"\"Assert that an invalid search query fails -",
"errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_clientref(): \"\"\"Assert that",
"by serial number.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'SERIAL_NUMBER' del",
"query['criteria']['debtorName']['business'] query['endDateTime'] = 'Xxxxxxxxxx' is_valid, errors = validate(query, 'searchQuery', 'ppr')",
"errors: print(err.message) print(errors) assert is_valid def test_valid_search_query_regnum(): \"\"\"Assert that the",
"del query['criteria']['debtorName']['business'] del query['criteria']['value'] del query['clientReferenceId'] del query['startDateTime'] del query['endDateTime']",
"is valid. \"\"\" import copy from registry_schemas import validate from",
"by aircraft DOT.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'AIRCRAFT_DOT' del",
"a search by registration number.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] =",
"valid. \"\"\" import copy from registry_schemas import validate from registry_schemas.example_data.ppr",
"name is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] is_valid, errors",
"is_valid def test_invalid_search_query_endts(): \"\"\"Assert that an invalid search query fails",
"query fails - type is missing.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del",
"del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['startDateTime'] = 'Xxxxxxxxxx' is_valid, errors =",
"copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['endDateTime'] = 'Xxxxxxxxxx' is_valid, errors",
"query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'MHR_NUMBER' del query['criteria']['debtorName'] query['criteria']['value'] =",
"expected for a search by registration number.\"\"\" query = copy.deepcopy(SEARCH_QUERY)",
"in errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_missing_criteria(): \"\"\"Assert",
"as expected for a search by aircraft DOT.\"\"\" query =",
"'XXXXXXXX' del query['criteria']['debtorName']['business'] del query['criteria']['value'] is_valid, errors = validate(query, 'searchQuery',",
"validate from registry_schemas.example_data.ppr import SEARCH_QUERY def test_valid_search_query_ind_debtor(): \"\"\"Assert that the",
"assert not is_valid def test_invalid_search_query_value(): \"\"\"Assert that an invalid search",
"too long.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['clientReferenceId']",
"print(errors) assert not is_valid def test_invalid_search_query_type(): \"\"\"Assert that an invalid",
"\"\"\"Assert that an invalid search query fails - criteria is",
"query['criteria']['debtorName']['business'] query['criteria']['debtorName']['first'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' is_valid, errors = validate(query, 'searchQuery', 'ppr')",
"schema is performing as expected for a search by serial",
"not is_valid def test_invalid_search_query_busname(): \"\"\"Assert that an invalid search query",
"query['criteria']['debtorName']['business'] query['criteria']['debtorName']['second'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' is_valid, errors = validate(query, 'searchQuery', 'ppr')",
"is_valid def test_invalid_search_query_secondname(): \"\"\"Assert that an invalid search query fails",
"query fails - criteria is missing.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del",
"test_invalid_search_query_busname(): \"\"\"Assert that an invalid search query fails - business",
"in errors: print(err.message) print(errors) assert is_valid def test_valid_search_query_bus_debtor(): \"\"\"Assert that",
"is_valid def test_valid_search_query_serialnum(): \"\"\"Assert that the schema is performing as",
"is too long.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['debtorName'] query['criteria']['value'] =",
"not is_valid def test_invalid_search_query_endts(): \"\"\"Assert that an invalid search query",
"in errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_debtor(): \"\"\"Assert",
"- criteria is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['debtorName']['business'] is_valid,",
"query['criteria']['debtorName'] query['criteria']['value'] = 'CFYXW' is_valid, errors = validate(query, 'searchQuery', 'ppr')",
"del query['criteria']['debtorName']['business'] query['criteria']['debtorName']['first'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' is_valid, errors = validate(query, 'searchQuery',",
"an invalid search query fails - debtor name is invalid.\"\"\"",
"OF ANY KIND, either express or implied. # See the",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"del query['clientReferenceId'] del query['startDateTime'] del query['endDateTime'] is_valid, errors = validate(query,",
"test_valid_search_query_bus_debtor(): \"\"\"Assert that the schema is performing as expected for",
"ANY KIND, either express or implied. # See the License",
"See the License for the specific language governing permissions and",
"del query['criteria']['debtorName'] query['criteria']['value'] = '023001B' is_valid, errors = validate(query, 'searchQuery',",
"Columbia # # Licensed under the Apache License, Version 2.0",
"the License. # You may obtain a copy of the",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"for the specific language governing permissions and # limitations under",
"reference id is too long.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value']",
"- end date time format is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY)",
"© 2020 Province of British Columbia # # Licensed under",
"copy.deepcopy(SEARCH_QUERY) del query['criteria']['debtorName'] query['criteria']['value'] = 'XxxxxxxxxxxxxxxxxxxxXxxxxxxxxxxxxxxxxxxxXxxxxxxxxxx' is_valid, errors = validate(query,",
"to in writing, software # distributed under the License is",
"short.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['debtorName']['first'] del query['criteria']['debtorName']['second'] del query['criteria']['debtorName']['last']",
"query['criteria']['value'] = 'CFYXW' is_valid, errors = validate(query, 'searchQuery', 'ppr') if",
"err in errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_lastname():",
"fails - business name is too short.\"\"\" query = copy.deepcopy(SEARCH_QUERY)",
"\"\"\"Assert that an invalid search query fails - start date",
"# See the License for the specific language governing permissions",
"too long.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['criteria']['debtorName']['second']",
"copy.deepcopy(SEARCH_QUERY) query['type'] = 'AIRCRAFT_DOT' del query['criteria']['debtorName'] query['criteria']['value'] = 'CFYXW' is_valid,",
"del query['criteria']['value'] is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors:",
"for a search by aircraft DOT.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type']",
"query['criteria']['debtorName'] query['criteria']['value'] = '023001B' is_valid, errors = validate(query, 'searchQuery', 'ppr')",
"or agreed to in writing, software # distributed under the",
"= copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['startDateTime'] = 'Xxxxxxxxxx' is_valid,",
"assert not is_valid def test_invalid_search_query_criteria(): \"\"\"Assert that an invalid search",
"required by applicable law or agreed to in writing, software",
"for err in errors: print(err.message) print(errors) assert is_valid def test_valid_search_query_airdot():",
"\"\"\"Assert that an invalid search query fails - value is",
"in errors: print(err.message) print(errors) assert is_valid def test_invalid_search_query_missing_type(): \"\"\"Assert that",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"query['endDateTime'] is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors: for",
"with the License. # You may obtain a copy of",
"query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['debtorName'] query['criteria']['value'] = 'XxxxxxxxxxxxxxxxxxxxXxxxxxxxxxxxxxxxxxxxXxxxxxxxxxx' is_valid, errors",
"del query['criteria']['debtorName']['first'] del query['criteria']['debtorName']['second'] del query['criteria']['debtorName']['last'] del query['criteria']['value'] query['criteria']['debtorName']['business'] =",
"that an invalid search query fails - client reference id",
"to ensure the PPR Search Query schema is valid. \"\"\"",
"for err in errors: print(err.message) print(errors) assert is_valid def test_valid_search_query_bus_debtor():",
"aircraft DOT.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'AIRCRAFT_DOT' del query['criteria']['debtorName']",
"query['clientReferenceId'] = 'XxxxxxxxxxXxxxxxxxxxX' is_valid, errors = validate(query, 'searchQuery', 'ppr') if",
"query fails - debtor name is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY)",
"is performing as expected for a search by MHR number.\"\"\"",
"search query fails - criteria is missing.\"\"\" query = copy.deepcopy(SEARCH_QUERY)",
"expected for a search by individual debtor.\"\"\" query = copy.deepcopy(SEARCH_QUERY)",
"query['criteria']['debtorName']['first'] del query['criteria']['debtorName']['second'] del query['criteria']['debtorName']['last'] del query['criteria']['value'] query['criteria']['debtorName']['business'] = 'XXXX'",
"validate(query, 'searchQuery', 'ppr') if errors: for err in errors: print(err.message)",
"= 'CFYXW' is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors:",
"schema is performing as expected for a search by registration",
"limitations under the License. \"\"\"Test Suite to ensure the PPR",
"query['criteria'] is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors: for",
"compliance with the License. # You may obtain a copy",
"del query['criteria']['debtorName']['business'] query['criteria']['debtorName']['second'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' is_valid, errors = validate(query, 'searchQuery',",
"agreed to in writing, software # distributed under the License",
"del query['criteria']['debtorName']['business'] del query['criteria']['value'] is_valid, errors = validate(query, 'searchQuery', 'ppr')",
"= copy.deepcopy(SEARCH_QUERY) query['type'] = 'AIRCRAFT_DOT' del query['criteria']['debtorName'] query['criteria']['value'] = 'CFYXW'",
"is performing as expected for a search by aircraft DOT.\"\"\"",
"distributed under the License is distributed on an \"AS IS\"",
"print(err.message) print(errors) assert not is_valid def test_invalid_search_query_firstname(): \"\"\"Assert that an",
"del query['criteria']['debtorName']['second'] del query['criteria']['debtorName']['last'] del query['criteria']['value'] is_valid, errors = validate(query,",
"errors: for err in errors: print(err.message) print(errors) assert is_valid def",
"express or implied. # See the License for the specific",
"'INDIVIDUAL_DEBTOR' del query['criteria']['debtorName']['business'] del query['criteria']['value'] del query['clientReferenceId'] del query['startDateTime'] del",
"def test_invalid_search_query_missing_criteria(): \"\"\"Assert that an invalid search query fails -",
"query = copy.deepcopy(SEARCH_QUERY) del query['criteria'] is_valid, errors = validate(query, 'searchQuery',",
"except in compliance with the License. # You may obtain",
"query['criteria']['debtorName']['business'] query['criteria']['debtorName']['last'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' is_valid, errors = validate(query, 'searchQuery', 'ppr')",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"not use this file except in compliance with the License.",
"def test_invalid_search_query_type(): \"\"\"Assert that an invalid search query fails -",
"fails - value is too long.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del",
"schema is performing as expected for a search by individual",
"expected for a search by aircraft DOT.\"\"\" query = copy.deepcopy(SEARCH_QUERY)",
"err in errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_startts():",
"writing, software # distributed under the License is distributed on",
"query['type'] = 'REGISTRATION_NUMBER' del query['criteria']['debtorName'] query['criteria']['value'] = '023001B' is_valid, errors",
"invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['endDateTime'] =",
"\"\"\"Assert that an invalid search query fails - debtor last",
"you may not use this file except in compliance with",
"query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] is_valid, errors = validate(query, 'searchQuery',",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"a search by business debtor.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] =",
"in errors: print(err.message) print(errors) assert is_valid def test_valid_search_query_serialnum(): \"\"\"Assert that",
"copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] is_valid, errors = validate(query, 'searchQuery', 'ppr') if",
"test_valid_search_query_airdot(): \"\"\"Assert that the schema is performing as expected for",
"query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'REGISTRATION_NUMBER' del query['criteria']['debtorName'] query['criteria']['value'] =",
"errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_firstname(): \"\"\"Assert that",
"print(errors) assert is_valid def test_valid_search_query_serialnum(): \"\"\"Assert that the schema is",
"del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['endDateTime'] = 'Xxxxxxxxxx' is_valid, errors =",
"query['criteria']['debtorName']['business'] del query['criteria']['value'] is_valid, errors = validate(query, 'searchQuery', 'ppr') if",
"is_valid def test_invalid_search_query_value(): \"\"\"Assert that an invalid search query fails",
"query['type'] = 'XXXXXXXX' del query['criteria']['debtorName']['business'] del query['criteria']['value'] is_valid, errors =",
"is_valid def test_valid_search_query_bus_debtor(): \"\"\"Assert that the schema is performing as",
"def test_invalid_search_query_missing_type(): \"\"\"Assert that an invalid search query fails -",
"debtor second name is too long.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"search query fails - criteria is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY)",
"- debtor first name is too long.\"\"\" query = copy.deepcopy(SEARCH_QUERY)",
"a search by individual debtor.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] =",
"query fails - type is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type']",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"= 'KM8J3CA46JU622994' is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors:",
"an invalid search query fails - business name is too",
"assert not is_valid def test_invalid_search_query_missing_criteria(): \"\"\"Assert that an invalid search",
"err in errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_missing_criteria():",
"is_valid def test_valid_search_query_airdot(): \"\"\"Assert that the schema is performing as",
"2020 Province of British Columbia # # Licensed under the",
"del query['criteria']['debtorName']['business'] query['criteria']['debtorName']['last'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' is_valid, errors = validate(query, 'searchQuery',",
"an invalid search query fails - client reference id is",
"an invalid search query fails - value is too long.\"\"\"",
"date time format is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value']",
"test_invalid_search_query_firstname(): \"\"\"Assert that an invalid search query fails - debtor",
"in errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_startts(): \"\"\"Assert",
"test_invalid_search_query_debtor(): \"\"\"Assert that an invalid search query fails - debtor",
"errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_missing_criteria(): \"\"\"Assert that",
"assert not is_valid def test_invalid_search_query_secondname(): \"\"\"Assert that an invalid search",
"search query fails - type is missing.\"\"\" query = copy.deepcopy(SEARCH_QUERY)",
"from registry_schemas.example_data.ppr import SEARCH_QUERY def test_valid_search_query_ind_debtor(): \"\"\"Assert that the schema",
"for err in errors: print(err.message) print(errors) assert not is_valid def",
"time format is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del",
"= 'XxxxxxxxxxxxxxxxxxxxXxxxxxxxxxxxxxxxxxxxXxxxxxxxxxx' is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors:",
"del query['criteria']['debtorName']['last'] del query['criteria']['value'] is_valid, errors = validate(query, 'searchQuery', 'ppr')",
"- type is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'XXXXXXXX'",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"that an invalid search query fails - debtor second name",
"'21324' is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors: for",
"query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['criteria']['debtorName']['last'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'",
"in errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_firstname(): \"\"\"Assert",
"an invalid search query fails - start date time format",
"number.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'SERIAL_NUMBER' del query['criteria']['debtorName'] query['criteria']['value']",
"assert not is_valid def test_invalid_search_query_startts(): \"\"\"Assert that an invalid search",
"the License is distributed on an \"AS IS\" BASIS, #",
"invalid search query fails - business name is too short.\"\"\"",
"def test_invalid_search_query_startts(): \"\"\"Assert that an invalid search query fails -",
"for err in errors: print(err.message) print(errors) assert is_valid def test_valid_search_query_serialnum():",
"err in errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_value():",
"assert is_valid def test_valid_search_query_serialnum(): \"\"\"Assert that the schema is performing",
"import copy from registry_schemas import validate from registry_schemas.example_data.ppr import SEARCH_QUERY",
"\"\"\"Assert that an invalid search query fails - business name",
"print(errors) assert not is_valid def test_invalid_search_query_debtor(): \"\"\"Assert that an invalid",
"del query['criteria']['debtorName']['business'] query['startDateTime'] = 'Xxxxxxxxxx' is_valid, errors = validate(query, 'searchQuery',",
"= copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['criteria']['debtorName']['second'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' is_valid,",
"query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'INDIVIDUAL_DEBTOR' del query['criteria']['debtorName']['business'] del query['criteria']['value']",
"search query fails - debtor last name is too long.\"\"\"",
"= validate(query, 'searchQuery', 'ppr') if errors: for err in errors:",
"an invalid search query fails - type is invalid.\"\"\" query",
"\"\"\"Assert that an invalid search query fails - end date",
"err in errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_criteria():",
"is_valid def test_invalid_search_query_type(): \"\"\"Assert that an invalid search query fails",
"def test_valid_search_query_regnum(): \"\"\"Assert that the schema is performing as expected",
"query['criteria']['debtorName']['last'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' is_valid, errors = validate(query, 'searchQuery', 'ppr') if",
"law or agreed to in writing, software # distributed under",
"is_valid def test_invalid_search_query_startts(): \"\"\"Assert that an invalid search query fails",
"copy.deepcopy(SEARCH_QUERY) del query['criteria']['debtorName']['business'] is_valid, errors = validate(query, 'searchQuery', 'ppr') if",
"test_invalid_search_query_secondname(): \"\"\"Assert that an invalid search query fails - debtor",
"'ppr') if errors: for err in errors: print(err.message) print(errors) assert",
"number.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'MHR_NUMBER' del query['criteria']['debtorName'] query['criteria']['value']",
"- debtor name is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value']",
"by registration number.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'REGISTRATION_NUMBER' del",
"not is_valid def test_invalid_search_query_missing_criteria(): \"\"\"Assert that an invalid search query",
"is_valid def test_invalid_search_query_debtor(): \"\"\"Assert that an invalid search query fails",
"query fails - value is too long.\"\"\" query = copy.deepcopy(SEARCH_QUERY)",
"serial number.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'SERIAL_NUMBER' del query['criteria']['debtorName']",
"search by aircraft DOT.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'AIRCRAFT_DOT'",
"query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'BUSINESS_DEBTOR' del query['criteria']['debtorName']['first'] del query['criteria']['debtorName']['second']",
"test_valid_search_query_regnum(): \"\"\"Assert that the schema is performing as expected for",
"errors: print(err.message) print(errors) assert is_valid def test_valid_search_query_mhrnum(): \"\"\"Assert that the",
"search by business debtor.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'BUSINESS_DEBTOR'",
"query['criteria']['debtorName']['last'] del query['criteria']['value'] is_valid, errors = validate(query, 'searchQuery', 'ppr') if",
"del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['criteria']['debtorName']['first'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' is_valid, errors =",
"British Columbia # # Licensed under the Apache License, Version",
"def test_invalid_search_query_value(): \"\"\"Assert that an invalid search query fails -",
"invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'XXXXXXXX' del query['criteria']['debtorName']['business'] del",
"is missing.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['type'] del query['criteria']['debtorName']['business'] del",
"print(errors) assert not is_valid def test_invalid_search_query_missing_criteria(): \"\"\"Assert that an invalid",
"invalid search query fails - type is invalid.\"\"\" query =",
"may obtain a copy of the License at # #",
"err in errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_type():",
"# Copyright © 2020 Province of British Columbia # #",
"missing.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria'] is_valid, errors = validate(query,",
"print(err.message) print(errors) assert is_valid def test_valid_search_query_airdot(): \"\"\"Assert that the schema",
"print(err.message) print(errors) assert not is_valid def test_invalid_search_query_secondname(): \"\"\"Assert that an",
"print(errors) assert not is_valid def test_invalid_search_query_busname(): \"\"\"Assert that an invalid",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"the License. \"\"\"Test Suite to ensure the PPR Search Query",
"is_valid def test_invalid_search_query_firstname(): \"\"\"Assert that an invalid search query fails",
"if errors: for err in errors: print(err.message) print(errors) assert not",
"is_valid def test_invalid_search_query_missing_type(): \"\"\"Assert that an invalid search query fails",
"that an invalid search query fails - value is too",
"criteria is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['debtorName']['business'] is_valid, errors",
"= copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['criteria']['debtorName']['last'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' is_valid,",
"print(err.message) print(errors) assert not is_valid def test_invalid_search_query_clientref(): \"\"\"Assert that an",
"del query['criteria'] is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors:",
"may not use this file except in compliance with the",
"err in errors: print(err.message) print(errors) assert is_valid def test_valid_search_query_regnum(): \"\"\"Assert",
"is_valid def test_invalid_search_query_missing_criteria(): \"\"\"Assert that an invalid search query fails",
"schema is performing as expected for a search by aircraft",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"not is_valid def test_invalid_search_query_clientref(): \"\"\"Assert that an invalid search query",
"'MHR_NUMBER' del query['criteria']['debtorName'] query['criteria']['value'] = '21324' is_valid, errors = validate(query,",
"this file except in compliance with the License. # You",
"debtor first name is too long.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del",
"registry_schemas import validate from registry_schemas.example_data.ppr import SEARCH_QUERY def test_valid_search_query_ind_debtor(): \"\"\"Assert",
"del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['clientReferenceId'] = 'XxxxxxxxxxXxxxxxxxxxX' is_valid, errors =",
"first name is too long.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value']",
"query['criteria']['value'] del query['criteria']['debtorName']['business'] query['criteria']['debtorName']['last'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' is_valid, errors = validate(query,",
"= copy.deepcopy(SEARCH_QUERY) query['type'] = 'INDIVIDUAL_DEBTOR' del query['criteria']['debtorName']['business'] del query['criteria']['value'] del",
"errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_value(): \"\"\"Assert that",
"= 'AIRCRAFT_DOT' del query['criteria']['debtorName'] query['criteria']['value'] = 'CFYXW' is_valid, errors =",
"query['criteria']['debtorName']['second'] del query['criteria']['debtorName']['last'] del query['criteria']['value'] query['criteria']['debtorName']['business'] = 'XXXX' is_valid, errors",
"business name is too short.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['debtorName']['first']",
"is too long.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business']",
"query fails - business name is too short.\"\"\" query =",
"errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_lastname(): \"\"\"Assert that",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"format is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business']",
"query['criteria']['value'] query['criteria']['debtorName']['business'] = 'XXXX' is_valid, errors = validate(query, 'searchQuery', 'ppr')",
"query['clientReferenceId'] del query['startDateTime'] del query['endDateTime'] is_valid, errors = validate(query, 'searchQuery',",
"# # Licensed under the Apache License, Version 2.0 (the",
"err in errors: print(err.message) print(errors) assert is_valid def test_invalid_search_query_missing_type(): \"\"\"Assert",
"file except in compliance with the License. # You may",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"query['type'] = 'MHR_NUMBER' del query['criteria']['debtorName'] query['criteria']['value'] = '21324' is_valid, errors",
"invalid search query fails - debtor last name is too",
"'023001B' is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors: for",
"debtor.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'INDIVIDUAL_DEBTOR' del query['criteria']['debtorName']['business'] del",
"of British Columbia # # Licensed under the Apache License,",
"is performing as expected for a search by business debtor.\"\"\"",
"Suite to ensure the PPR Search Query schema is valid.",
"performing as expected for a search by MHR number.\"\"\" query",
"an invalid search query fails - debtor second name is",
"query fails - client reference id is too long.\"\"\" query",
"import validate from registry_schemas.example_data.ppr import SEARCH_QUERY def test_valid_search_query_ind_debtor(): \"\"\"Assert that",
"in errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_endts(): \"\"\"Assert",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"err in errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_endts():",
"err in errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_busname():",
"not is_valid def test_invalid_search_query_startts(): \"\"\"Assert that an invalid search query",
"def test_invalid_search_query_criteria(): \"\"\"Assert that an invalid search query fails -",
"del query['criteria']['debtorName'] query['criteria']['value'] = 'XxxxxxxxxxxxxxxxxxxxXxxxxxxxxxxxxxxxxxxxXxxxxxxxxxx' is_valid, errors = validate(query, 'searchQuery',",
"fails - end date time format is invalid.\"\"\" query =",
"assert is_valid def test_valid_search_query_airdot(): \"\"\"Assert that the schema is performing",
"query = copy.deepcopy(SEARCH_QUERY) del query['type'] del query['criteria']['debtorName']['business'] del query['criteria']['value'] is_valid,",
"= 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors:",
"query['criteria']['value'] = '023001B' is_valid, errors = validate(query, 'searchQuery', 'ppr') if",
"- value is too long.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['debtorName']",
"def test_invalid_search_query_secondname(): \"\"\"Assert that an invalid search query fails -",
"'XxxxxxxxxxxxxxxxxxxxXxxxxxxxxxxxxxxxxxxxXxxxxxxxxxx' is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors: for",
"errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_debtor(): \"\"\"Assert that",
"query['criteria']['debtorName']['first'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' is_valid, errors = validate(query, 'searchQuery', 'ppr') if",
"an invalid search query fails - criteria is missing.\"\"\" query",
"is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors: for err",
"copy.deepcopy(SEARCH_QUERY) del query['criteria']['debtorName']['first'] del query['criteria']['debtorName']['second'] del query['criteria']['debtorName']['last'] del query['criteria']['value'] query['criteria']['debtorName']['business']",
"assert is_valid def test_valid_search_query_bus_debtor(): \"\"\"Assert that the schema is performing",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"MHR number.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'MHR_NUMBER' del query['criteria']['debtorName']",
"DOT.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'AIRCRAFT_DOT' del query['criteria']['debtorName'] query['criteria']['value']",
"not is_valid def test_invalid_search_query_lastname(): \"\"\"Assert that an invalid search query",
"# limitations under the License. \"\"\"Test Suite to ensure the",
"invalid search query fails - debtor second name is too",
"'XxxxxxxxxxXxxxxxxxxxX' is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors: for",
"query['type'] = 'SERIAL_NUMBER' del query['criteria']['debtorName'] query['criteria']['value'] = 'KM8J3CA46JU622994' is_valid, errors",
"business debtor.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'BUSINESS_DEBTOR' del query['criteria']['debtorName']['first']",
"the PPR Search Query schema is valid. \"\"\" import copy",
"= 'INDIVIDUAL_DEBTOR' del query['criteria']['debtorName']['business'] del query['criteria']['value'] del query['clientReferenceId'] del query['startDateTime']",
"or implied. # See the License for the specific language",
"that an invalid search query fails - debtor first name",
"in errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_criteria(): \"\"\"Assert",
"in errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_busname(): \"\"\"Assert",
"is_valid def test_invalid_search_query_busname(): \"\"\"Assert that an invalid search query fails",
"KIND, either express or implied. # See the License for",
"specific language governing permissions and # limitations under the License.",
"= '023001B' is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors:",
"print(errors) assert not is_valid def test_invalid_search_query_clientref(): \"\"\"Assert that an invalid",
"value is too long.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['debtorName'] query['criteria']['value']",
"query fails - criteria is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del",
"long.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['debtorName'] query['criteria']['value'] = 'XxxxxxxxxxxxxxxxxxxxXxxxxxxxxxxxxxxxxxxxXxxxxxxxxxx' is_valid,",
"too long.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['debtorName'] query['criteria']['value'] = 'XxxxxxxxxxxxxxxxxxxxXxxxxxxxxxxxxxxxxxxxXxxxxxxxxxx'",
"query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['endDateTime'] = 'Xxxxxxxxxx'",
"test_invalid_search_query_value(): \"\"\"Assert that an invalid search query fails - value",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"err in errors: print(err.message) print(errors) assert is_valid def test_valid_search_query_mhrnum(): \"\"\"Assert",
"performing as expected for a search by business debtor.\"\"\" query",
"print(errors) assert not is_valid def test_invalid_search_query_firstname(): \"\"\"Assert that an invalid",
"= copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] is_valid, errors = validate(query, 'searchQuery', 'ppr')",
"copy from registry_schemas import validate from registry_schemas.example_data.ppr import SEARCH_QUERY def",
"search query fails - value is too long.\"\"\" query =",
"query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['clientReferenceId'] = 'XxxxxxxxxxXxxxxxxxxxX'",
"fails - type is missing.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['type']",
"schema is valid. \"\"\" import copy from registry_schemas import validate",
"in errors: print(err.message) print(errors) assert is_valid def test_valid_search_query_regnum(): \"\"\"Assert that",
"invalid search query fails - value is too long.\"\"\" query",
"print(err.message) print(errors) assert not is_valid def test_invalid_search_query_endts(): \"\"\"Assert that an",
"assert not is_valid def test_invalid_search_query_lastname(): \"\"\"Assert that an invalid search",
"- type is missing.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['type'] del",
"missing.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['type'] del query['criteria']['debtorName']['business'] del query['criteria']['value']",
"print(err.message) print(errors) assert not is_valid def test_invalid_search_query_missing_criteria(): \"\"\"Assert that an",
"(the \"License\"); # you may not use this file except",
"print(err.message) print(errors) assert not is_valid def test_invalid_search_query_type(): \"\"\"Assert that an",
"test_invalid_search_query_missing_type(): \"\"\"Assert that an invalid search query fails - type",
"errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_type(): \"\"\"Assert that",
"- debtor last name is too long.\"\"\" query = copy.deepcopy(SEARCH_QUERY)",
"# you may not use this file except in compliance",
"= '21324' is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors:",
"long.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['criteria']['debtorName']['last'] =",
"too short.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['debtorName']['first'] del query['criteria']['debtorName']['second'] del",
"'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors: for",
"start date time format is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del",
"err in errors: print(err.message) print(errors) assert is_valid def test_valid_search_query_airdot(): \"\"\"Assert",
"is performing as expected for a search by individual debtor.\"\"\"",
"too long.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['criteria']['debtorName']['last']",
"# # Unless required by applicable law or agreed to",
"print(errors) assert is_valid def test_valid_search_query_airdot(): \"\"\"Assert that the schema is",
"invalid search query fails - end date time format is",
"not is_valid def test_invalid_search_query_type(): \"\"\"Assert that an invalid search query",
"assert is_valid def test_valid_search_query_mhrnum(): \"\"\"Assert that the schema is performing",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"as expected for a search by business debtor.\"\"\" query =",
"print(err.message) print(errors) assert is_valid def test_valid_search_query_regnum(): \"\"\"Assert that the schema",
"Version 2.0 (the \"License\"); # you may not use this",
"in errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_secondname(): \"\"\"Assert",
"in errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_lastname(): \"\"\"Assert",
"query['criteria']['debtorName']['business'] del query['criteria']['value'] del query['clientReferenceId'] del query['startDateTime'] del query['endDateTime'] is_valid,",
"that an invalid search query fails - type is missing.\"\"\"",
"search query fails - debtor first name is too long.\"\"\"",
"PPR Search Query schema is valid. \"\"\" import copy from",
"'SERIAL_NUMBER' del query['criteria']['debtorName'] query['criteria']['value'] = 'KM8J3CA46JU622994' is_valid, errors = validate(query,",
"= 'SERIAL_NUMBER' del query['criteria']['debtorName'] query['criteria']['value'] = 'KM8J3CA46JU622994' is_valid, errors =",
"that an invalid search query fails - end date time",
"query fails - debtor first name is too long.\"\"\" query",
"print(err.message) print(errors) assert not is_valid def test_invalid_search_query_value(): \"\"\"Assert that an",
"implied. # See the License for the specific language governing",
"is_valid def test_valid_search_query_regnum(): \"\"\"Assert that the schema is performing as",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"del query['criteria']['value'] del query['clientReferenceId'] del query['startDateTime'] del query['endDateTime'] is_valid, errors",
"print(err.message) print(errors) assert not is_valid def test_invalid_search_query_busname(): \"\"\"Assert that an",
"by MHR number.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'MHR_NUMBER' del",
"not is_valid def test_invalid_search_query_secondname(): \"\"\"Assert that an invalid search query",
"id is too long.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del",
"in errors: print(err.message) print(errors) assert is_valid def test_valid_search_query_mhrnum(): \"\"\"Assert that",
"query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['debtorName']['first'] del query['criteria']['debtorName']['second'] del query['criteria']['debtorName']['last'] del",
"copy.deepcopy(SEARCH_QUERY) query['type'] = 'XXXXXXXX' del query['criteria']['debtorName']['business'] del query['criteria']['value'] is_valid, errors",
"errors = validate(query, 'searchQuery', 'ppr') if errors: for err in",
"= copy.deepcopy(SEARCH_QUERY) del query['criteria']['debtorName'] query['criteria']['value'] = 'XxxxxxxxxxxxxxxxxxxxXxxxxxxxxxxxxxxxxxxxXxxxxxxxxxx' is_valid, errors =",
"query['criteria']['value'] del query['criteria']['debtorName']['business'] query['clientReferenceId'] = 'XxxxxxxxxxXxxxxxxxxxX' is_valid, errors = validate(query,",
"- debtor second name is too long.\"\"\" query = copy.deepcopy(SEARCH_QUERY)",
"if errors: for err in errors: print(err.message) print(errors) assert is_valid",
"by applicable law or agreed to in writing, software #",
"'KM8J3CA46JU622994' is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors: for",
"assert not is_valid def test_invalid_search_query_busname(): \"\"\"Assert that an invalid search",
"del query['criteria']['debtorName']['last'] del query['criteria']['value'] query['criteria']['debtorName']['business'] = 'XXXX' is_valid, errors =",
"= copy.deepcopy(SEARCH_QUERY) query['type'] = 'XXXXXXXX' del query['criteria']['debtorName']['business'] del query['criteria']['value'] is_valid,",
"name is too short.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['debtorName']['first'] del",
"License. \"\"\"Test Suite to ensure the PPR Search Query schema",
"errors: print(err.message) print(errors) assert is_valid def test_valid_search_query_serialnum(): \"\"\"Assert that the",
"query fails - debtor last name is too long.\"\"\" query",
"query['criteria']['value'] del query['criteria']['debtorName']['business'] query['criteria']['debtorName']['second'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' is_valid, errors = validate(query,",
"that an invalid search query fails - type is invalid.\"\"\"",
"number.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'REGISTRATION_NUMBER' del query['criteria']['debtorName'] query['criteria']['value']",
"errors: print(err.message) print(errors) assert is_valid def test_invalid_search_query_missing_type(): \"\"\"Assert that an",
"too long.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['criteria']['debtorName']['first']",
"print(err.message) print(errors) assert not is_valid def test_invalid_search_query_criteria(): \"\"\"Assert that an",
"import SEARCH_QUERY def test_valid_search_query_ind_debtor(): \"\"\"Assert that the schema is performing",
"assert is_valid def test_valid_search_query_regnum(): \"\"\"Assert that the schema is performing",
"fails - debtor first name is too long.\"\"\" query =",
"copy.deepcopy(SEARCH_QUERY) query['type'] = 'BUSINESS_DEBTOR' del query['criteria']['debtorName']['first'] del query['criteria']['debtorName']['second'] del query['criteria']['debtorName']['last']",
"err in errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_debtor():",
"= copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['criteria']['debtorName']['first'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' is_valid,",
"del query['criteria']['debtorName'] query['criteria']['value'] = '21324' is_valid, errors = validate(query, 'searchQuery',",
"print(errors) assert not is_valid def test_invalid_search_query_lastname(): \"\"\"Assert that an invalid",
"= 'XXXX' is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors:",
"an invalid search query fails - debtor first name is",
"test_valid_search_query_mhrnum(): \"\"\"Assert that the schema is performing as expected for",
"invalid search query fails - client reference id is too",
"by individual debtor.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'INDIVIDUAL_DEBTOR' del",
"that the schema is performing as expected for a search",
"\"\"\" import copy from registry_schemas import validate from registry_schemas.example_data.ppr import",
"query['startDateTime'] = 'Xxxxxxxxxx' is_valid, errors = validate(query, 'searchQuery', 'ppr') if",
"expected for a search by MHR number.\"\"\" query = copy.deepcopy(SEARCH_QUERY)",
"language governing permissions and # limitations under the License. \"\"\"Test",
"query['criteria']['debtorName']['first'] del query['criteria']['debtorName']['second'] del query['criteria']['debtorName']['last'] del query['criteria']['value'] is_valid, errors =",
"debtor name is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] is_valid,",
"invalid search query fails - debtor name is invalid.\"\"\" query",
"that an invalid search query fails - debtor last name",
"def test_valid_search_query_bus_debtor(): \"\"\"Assert that the schema is performing as expected",
"errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_busname(): \"\"\"Assert that",
"copy.deepcopy(SEARCH_QUERY) query['type'] = 'INDIVIDUAL_DEBTOR' del query['criteria']['debtorName']['business'] del query['criteria']['value'] del query['clientReferenceId']",
"'BUSINESS_DEBTOR' del query['criteria']['debtorName']['first'] del query['criteria']['debtorName']['second'] del query['criteria']['debtorName']['last'] del query['criteria']['value'] is_valid,",
"search query fails - debtor second name is too long.\"\"\"",
"assert not is_valid def test_invalid_search_query_debtor(): \"\"\"Assert that an invalid search",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"a search by aircraft DOT.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] =",
"Unless required by applicable law or agreed to in writing,",
"copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['criteria']['debtorName']['last'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' is_valid, errors",
"that an invalid search query fails - criteria is invalid.\"\"\"",
"err in errors: print(err.message) print(errors) assert is_valid def test_valid_search_query_bus_debtor(): \"\"\"Assert",
"second name is too long.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value']",
"copy.deepcopy(SEARCH_QUERY) del query['criteria'] is_valid, errors = validate(query, 'searchQuery', 'ppr') if",
"= 'MHR_NUMBER' del query['criteria']['debtorName'] query['criteria']['value'] = '21324' is_valid, errors =",
"permissions and # limitations under the License. \"\"\"Test Suite to",
"copy.deepcopy(SEARCH_QUERY) query['type'] = 'MHR_NUMBER' del query['criteria']['debtorName'] query['criteria']['value'] = '21324' is_valid,",
"long.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['criteria']['debtorName']['first'] =",
"errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_startts(): \"\"\"Assert that",
"= copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['endDateTime'] = 'Xxxxxxxxxx' is_valid,",
"test_invalid_search_query_criteria(): \"\"\"Assert that an invalid search query fails - criteria",
"def test_invalid_search_query_busname(): \"\"\"Assert that an invalid search query fails -",
"query['criteria']['value'] is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors: for",
"is too short.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['debtorName']['first'] del query['criteria']['debtorName']['second']",
"the specific language governing permissions and # limitations under the",
"debtor.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'BUSINESS_DEBTOR' del query['criteria']['debtorName']['first'] del",
"def test_invalid_search_query_firstname(): \"\"\"Assert that an invalid search query fails -",
"query['criteria']['debtorName']['business'] = 'XXXX' is_valid, errors = validate(query, 'searchQuery', 'ppr') if",
"performing as expected for a search by registration number.\"\"\" query",
"applicable law or agreed to in writing, software # distributed",
"fails - client reference id is too long.\"\"\" query =",
"is_valid def test_valid_search_query_mhrnum(): \"\"\"Assert that the schema is performing as",
"is_valid def test_invalid_search_query_criteria(): \"\"\"Assert that an invalid search query fails",
"Copyright © 2020 Province of British Columbia # # Licensed",
"assert not is_valid def test_invalid_search_query_clientref(): \"\"\"Assert that an invalid search",
"not is_valid def test_invalid_search_query_value(): \"\"\"Assert that an invalid search query",
"Query schema is valid. \"\"\" import copy from registry_schemas import",
"del query['criteria']['debtorName']['business'] query['endDateTime'] = 'Xxxxxxxxxx' is_valid, errors = validate(query, 'searchQuery',",
"invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['debtorName']['business'] is_valid, errors = validate(query,",
"in writing, software # distributed under the License is distributed",
"from registry_schemas import validate from registry_schemas.example_data.ppr import SEARCH_QUERY def test_valid_search_query_ind_debtor():",
"errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_secondname(): \"\"\"Assert that",
"errors: print(err.message) print(errors) assert is_valid def test_valid_search_query_bus_debtor(): \"\"\"Assert that the",
"\"\"\"Assert that an invalid search query fails - type is",
"copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['clientReferenceId'] = 'XxxxxxxxxxXxxxxxxxxxX' is_valid, errors",
"query['criteria']['debtorName']['business'] query['clientReferenceId'] = 'XxxxxxxxxxXxxxxxxxxxX' is_valid, errors = validate(query, 'searchQuery', 'ppr')",
"a search by MHR number.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] =",
"query['criteria']['value'] del query['criteria']['debtorName']['business'] query['criteria']['debtorName']['first'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' is_valid, errors = validate(query,",
"def test_valid_search_query_serialnum(): \"\"\"Assert that the schema is performing as expected",
"= copy.deepcopy(SEARCH_QUERY) query['type'] = 'REGISTRATION_NUMBER' del query['criteria']['debtorName'] query['criteria']['value'] = '023001B'",
"del query['criteria']['value'] query['criteria']['debtorName']['business'] = 'XXXX' is_valid, errors = validate(query, 'searchQuery',",
"is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['startDateTime']",
"invalid search query fails - type is missing.\"\"\" query =",
"is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['endDateTime']",
"last name is too long.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value']",
"= copy.deepcopy(SEARCH_QUERY) query['type'] = 'BUSINESS_DEBTOR' del query['criteria']['debtorName']['first'] del query['criteria']['debtorName']['second'] del",
"query['criteria']['debtorName']['business'] is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors: for",
"= 'Xxxxxxxxxx' is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors:",
"test_invalid_search_query_type(): \"\"\"Assert that an invalid search query fails - type",
"= copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['clientReferenceId'] = 'XxxxxxxxxxXxxxxxxxxxX' is_valid,",
"print(errors) assert not is_valid def test_invalid_search_query_endts(): \"\"\"Assert that an invalid",
"print(errors) assert is_valid def test_valid_search_query_regnum(): \"\"\"Assert that the schema is",
"errors: print(err.message) print(errors) assert is_valid def test_valid_search_query_airdot(): \"\"\"Assert that the",
"invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['startDateTime'] =",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"License, Version 2.0 (the \"License\"); # you may not use",
"invalid search query fails - start date time format is",
"query['type'] = 'AIRCRAFT_DOT' del query['criteria']['debtorName'] query['criteria']['value'] = 'CFYXW' is_valid, errors",
"fails - debtor name is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del",
"# You may obtain a copy of the License at",
"query['criteria']['debtorName']['second'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' is_valid, errors = validate(query, 'searchQuery', 'ppr') if",
"for err in errors: print(err.message) print(errors) assert is_valid def test_valid_search_query_mhrnum():",
"copy.deepcopy(SEARCH_QUERY) del query['type'] del query['criteria']['debtorName']['business'] del query['criteria']['value'] is_valid, errors =",
"not is_valid def test_invalid_search_query_debtor(): \"\"\"Assert that an invalid search query",
"def test_invalid_search_query_debtor(): \"\"\"Assert that an invalid search query fails -",
"query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['criteria']['debtorName']['second'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'",
"query['endDateTime'] = 'Xxxxxxxxxx' is_valid, errors = validate(query, 'searchQuery', 'ppr') if",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"registry_schemas.example_data.ppr import SEARCH_QUERY def test_valid_search_query_ind_debtor(): \"\"\"Assert that the schema is",
"debtor last name is too long.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del",
"del query['criteria']['debtorName']['business'] query['clientReferenceId'] = 'XxxxxxxxxxXxxxxxxxxxX' is_valid, errors = validate(query, 'searchQuery',",
"fails - start date time format is invalid.\"\"\" query =",
"query['type'] = 'BUSINESS_DEBTOR' del query['criteria']['debtorName']['first'] del query['criteria']['debtorName']['second'] del query['criteria']['debtorName']['last'] del",
"end date time format is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del",
"not is_valid def test_invalid_search_query_criteria(): \"\"\"Assert that an invalid search query",
"for a search by serial number.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type']",
"that an invalid search query fails - start date time",
"test_invalid_search_query_lastname(): \"\"\"Assert that an invalid search query fails - debtor",
"query['criteria']['debtorName'] query['criteria']['value'] = '21324' is_valid, errors = validate(query, 'searchQuery', 'ppr')",
"print(err.message) print(errors) assert is_valid def test_invalid_search_query_missing_type(): \"\"\"Assert that an invalid",
"expected for a search by serial number.\"\"\" query = copy.deepcopy(SEARCH_QUERY)",
"test_invalid_search_query_clientref(): \"\"\"Assert that an invalid search query fails - client",
"query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'SERIAL_NUMBER' del query['criteria']['debtorName'] query['criteria']['value'] =",
"type is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'XXXXXXXX' del",
"the License for the specific language governing permissions and #",
"del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['criteria']['debtorName']['last'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' is_valid, errors =",
"print(err.message) print(errors) assert not is_valid def test_invalid_search_query_startts(): \"\"\"Assert that an",
"= copy.deepcopy(SEARCH_QUERY) del query['criteria']['debtorName']['business'] is_valid, errors = validate(query, 'searchQuery', 'ppr')",
"search query fails - start date time format is invalid.\"\"\"",
"not is_valid def test_invalid_search_query_firstname(): \"\"\"Assert that an invalid search query",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"as expected for a search by individual debtor.\"\"\" query =",
"query['criteria']['debtorName'] query['criteria']['value'] = 'XxxxxxxxxxxxxxxxxxxxXxxxxxxxxxxxxxxxxxxxXxxxxxxxxxx' is_valid, errors = validate(query, 'searchQuery', 'ppr')",
"either express or implied. # See the License for the",
"is_valid def test_invalid_search_query_clientref(): \"\"\"Assert that an invalid search query fails",
"test_valid_search_query_ind_debtor(): \"\"\"Assert that the schema is performing as expected for",
"err in errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_clientref():",
"is performing as expected for a search by registration number.\"\"\"",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"print(err.message) print(errors) assert is_valid def test_valid_search_query_bus_debtor(): \"\"\"Assert that the schema",
"del query['startDateTime'] del query['endDateTime'] is_valid, errors = validate(query, 'searchQuery', 'ppr')",
"print(err.message) print(errors) assert not is_valid def test_invalid_search_query_debtor(): \"\"\"Assert that an",
"test_invalid_search_query_startts(): \"\"\"Assert that an invalid search query fails - start",
"= 'REGISTRATION_NUMBER' del query['criteria']['debtorName'] query['criteria']['value'] = '023001B' is_valid, errors =",
"query['type'] del query['criteria']['debtorName']['business'] del query['criteria']['value'] is_valid, errors = validate(query, 'searchQuery',",
"print(errors) assert not is_valid def test_invalid_search_query_criteria(): \"\"\"Assert that an invalid",
"search by registration number.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'REGISTRATION_NUMBER'",
"query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['startDateTime'] = 'Xxxxxxxxxx'",
"invalid search query fails - criteria is missing.\"\"\" query =",
"query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'AIRCRAFT_DOT' del query['criteria']['debtorName'] query['criteria']['value'] =",
"as expected for a search by MHR number.\"\"\" query =",
"registration number.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'REGISTRATION_NUMBER' del query['criteria']['debtorName']",
"def test_valid_search_query_ind_debtor(): \"\"\"Assert that the schema is performing as expected",
"'CFYXW' is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors: for",
"print(errors) assert is_valid def test_valid_search_query_mhrnum(): \"\"\"Assert that the schema is",
"test_valid_search_query_serialnum(): \"\"\"Assert that the schema is performing as expected for",
"invalid search query fails - debtor first name is too",
"under the License. \"\"\"Test Suite to ensure the PPR Search",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"del query['endDateTime'] is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors:",
"def test_valid_search_query_airdot(): \"\"\"Assert that the schema is performing as expected",
"name is too long.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del",
"client reference id is too long.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del",
"query['criteria']['debtorName']['second'] del query['criteria']['debtorName']['last'] del query['criteria']['value'] is_valid, errors = validate(query, 'searchQuery',",
"test_invalid_search_query_endts(): \"\"\"Assert that an invalid search query fails - end",
"\"\"\"Assert that an invalid search query fails - debtor second",
"query['criteria']['value'] del query['criteria']['debtorName']['business'] query['startDateTime'] = 'Xxxxxxxxxx' is_valid, errors = validate(query,",
"in errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_clientref(): \"\"\"Assert",
"is_valid def test_invalid_search_query_lastname(): \"\"\"Assert that an invalid search query fails",
"'searchQuery', 'ppr') if errors: for err in errors: print(err.message) print(errors)",
"del query['criteria']['debtorName'] query['criteria']['value'] = 'CFYXW' is_valid, errors = validate(query, 'searchQuery',",
"as expected for a search by serial number.\"\"\" query =",
"err in errors: print(err.message) print(errors) assert is_valid def test_valid_search_query_serialnum(): \"\"\"Assert",
"by business debtor.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] = 'BUSINESS_DEBTOR' del",
"= 'BUSINESS_DEBTOR' del query['criteria']['debtorName']['first'] del query['criteria']['debtorName']['second'] del query['criteria']['debtorName']['last'] del query['criteria']['value']",
"fails - type is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type'] =",
"copy.deepcopy(SEARCH_QUERY) query['type'] = 'REGISTRATION_NUMBER' del query['criteria']['debtorName'] query['criteria']['value'] = '023001B' is_valid,",
"\"License\"); # you may not use this file except in",
"is missing.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria'] is_valid, errors =",
"the schema is performing as expected for a search by",
"criteria is missing.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria'] is_valid, errors",
"copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['criteria']['debtorName']['second'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' is_valid, errors",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"\"\"\"Assert that the schema is performing as expected for a",
"'XXXX' is_valid, errors = validate(query, 'searchQuery', 'ppr') if errors: for",
"# distributed under the License is distributed on an \"AS",
"performing as expected for a search by serial number.\"\"\" query",
"for a search by registration number.\"\"\" query = copy.deepcopy(SEARCH_QUERY) query['type']",
"\"\"\"Assert that an invalid search query fails - client reference",
"# Unless required by applicable law or agreed to in",
"query['criteria']['value'] del query['clientReferenceId'] del query['startDateTime'] del query['endDateTime'] is_valid, errors =",
"query fails - start date time format is invalid.\"\"\" query",
"= copy.deepcopy(SEARCH_QUERY) del query['type'] del query['criteria']['debtorName']['business'] del query['criteria']['value'] is_valid, errors",
"query['criteria']['debtorName']['business'] query['startDateTime'] = 'Xxxxxxxxxx' is_valid, errors = validate(query, 'searchQuery', 'ppr')",
"for err in errors: print(err.message) print(errors) assert is_valid def test_invalid_search_query_missing_type():",
"= 'XXXXXXXX' del query['criteria']['debtorName']['business'] del query['criteria']['value'] is_valid, errors = validate(query,",
"query['criteria']['debtorName']['last'] del query['criteria']['value'] query['criteria']['debtorName']['business'] = 'XXXX' is_valid, errors = validate(query,",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"performing as expected for a search by aircraft DOT.\"\"\" query",
"= copy.deepcopy(SEARCH_QUERY) query['type'] = 'SERIAL_NUMBER' del query['criteria']['debtorName'] query['criteria']['value'] = 'KM8J3CA46JU622994'",
"\"\"\"Assert that an invalid search query fails - debtor name",
"print(errors) assert not is_valid def test_invalid_search_query_startts(): \"\"\"Assert that an invalid",
"You may obtain a copy of the License at #",
"err in errors: print(err.message) print(errors) assert not is_valid def test_invalid_search_query_secondname():",
"is performing as expected for a search by serial number.\"\"\"",
"copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['criteria']['debtorName']['first'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' is_valid, errors",
"fails - criteria is invalid.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['debtorName']['business']",
"governing permissions and # limitations under the License. \"\"\"Test Suite",
"print(errors) assert is_valid def test_valid_search_query_bus_debtor(): \"\"\"Assert that the schema is",
"query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['debtorName']['business'] is_valid, errors = validate(query, 'searchQuery',",
"long.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['criteria']['value'] del query['criteria']['debtorName']['business'] query['clientReferenceId'] =",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"SEARCH_QUERY def test_valid_search_query_ind_debtor(): \"\"\"Assert that the schema is performing as",
"search query fails - end date time format is invalid.\"\"\"",
"type is missing.\"\"\" query = copy.deepcopy(SEARCH_QUERY) del query['type'] del query['criteria']['debtorName']['business']",
"Search Query schema is valid. \"\"\" import copy from registry_schemas",
"query['criteria']['value'] = 'KM8J3CA46JU622994' is_valid, errors = validate(query, 'searchQuery', 'ppr') if",
"as expected for a search by registration number.\"\"\" query ="
] |
[
"= '<NAME>' import re import time import itertools import logging",
"'<NAME>' import re import time import itertools import logging log",
"__author__ = '<NAME>' import re import time import itertools import",
"Module to contain Pywork decorators \"\"\" __author__ = '<NAME>' import",
"Pywork decorators \"\"\" __author__ = '<NAME>' import re import time",
"\"\"\" Module to contain Pywork decorators \"\"\" __author__ = '<NAME>'",
"contain Pywork decorators \"\"\" __author__ = '<NAME>' import re import",
"decorators \"\"\" __author__ = '<NAME>' import re import time import",
"to contain Pywork decorators \"\"\" __author__ = '<NAME>' import re",
"\"\"\" __author__ = '<NAME>' import re import time import itertools",
"re import time import itertools import logging log = logging.getLogger(__name__)",
"import re import time import itertools import logging log ="
] |
[
"request, response, *args, **kwargs): response.request = request return APIView.finalize_response(self, request,",
"test_renderer_classes(self): @api_view(['GET']) @renderer_classes([JSONRenderer]) def view(request): return Response({}) request = self.factory.get('/')",
"name', suffix='Suffix') assert str(excinfo.value) == \"`name` and `suffix` are mutually",
"api_view, authentication_classes, detail_route, list_route, parser_classes, permission_classes, renderer_classes, schema, throttle_classes )",
"def view(request): return Response() def test_calling_method(self): @api_view(['GET']) def view(request): return",
"test_permission_classes(self): @api_view(['GET']) @permission_classes([IsAuthenticated]) def view(request): return Response({}) request = self.factory.get('/')",
"kwarg supersedes name generation @action(detail=True, suffix='Suffix') def test_action(request): raise NotImplementedError",
"to '.test_action'.\" with self.assertRaisesMessage(AssertionError, msg): @test_action.mapping.get def test_action_get(request): raise NotImplementedError",
"@detail_route() def view(request): raise NotImplementedError assert len(record) == 1 assert",
"response.status_code == status.HTTP_403_FORBIDDEN def test_throttle_classes(self): class OncePerDayUserThrottle(UserRateThrottle): rate = '1/day'",
"name. \"\"\" # by default, generate name from method @action(detail=True)",
"have the action attributes for name in ['mapping', 'detail', 'url_path',",
"The secondary handler methods should not have the action attributes",
"and `suffix` are mutually exclusive arguments.\" def test_method_mapping(self): @action(detail=False) def",
"def test_action(request): raise NotImplementedError assert test_action.kwargs == { 'description': None,",
"pytest.warns(DeprecationWarning) as record: @detail_route() def view(request): raise NotImplementedError assert len(record)",
"response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED def test_calling_patch_method(self): @api_view(['GET', 'PATCH']) def view(request): return",
"self.factory = APIRequestFactory() def _finalize_response(self, request, response, *args, **kwargs): response.request",
"@api_view(['GET']) def view(request): return Response({}) request = self.factory.get('/') response =",
"bool. Use \" \"`@action(detail=True)` instead.\" ) def test_list_route_deprecation(self): with pytest.warns(DeprecationWarning)",
"} # name kwarg supersedes name generation @action(detail=True, name='<NAME>') def",
"cast __name__ to str method.__name__ = str(name) getattr(test_action.mapping, name)(method) #",
"2.x compatibility - cast __name__ to str method.__name__ = str(name)",
"exclusive arguments.\" def test_method_mapping(self): @action(detail=False) def test_action(request): raise NotImplementedError @test_action.mapping.post",
"name for name in APIView.http_method_names: assert test_action.mapping[name] == name def",
"return Response({}) request = self.factory.get('/') view(request) def test_authentication_classes(self): @api_view(['GET']) @authentication_classes([BasicAuthentication])",
"@throttle_classes([OncePerDayUserThrottle]) def view(request): return Response({}) request = self.factory.get('/') response =",
"\"\"\" Checks CustomSchema class is set on view \"\"\" class",
"`detail` bool. Use \" \"`@action(detail=False)` instead.\" ) def test_route_url_name_from_path(self): #",
"in APIView.http_method_names: assert test_action.mapping[name] == name def test_view_name_kwargs(self): \"\"\" 'name'",
"rest_framework.throttling import UserRateThrottle from rest_framework.views import APIView class DecoratorTestCase(TestCase): def",
"response.status_code == status.HTTP_200_OK request = self.factory.post('/') response = view(request) assert",
"name)(method) # ensure the mapping returns the correct method name",
"CustomSchema) class ActionDecoratorTestCase(TestCase): def test_defaults(self): @action(detail=True) def test_action(request): \"\"\"Description\"\"\" assert",
"Use \" \"`@action(detail=False)` instead.\" ) def test_route_url_name_from_path(self): # pre-3.8 behavior",
"declaration.\") with self.assertRaisesMessage(AssertionError, msg): @test_action.mapping.post def test_action(): raise NotImplementedError def",
"test_action.url_path == 'test_action' assert test_action.url_name == 'test-action' assert test_action.kwargs ==",
"an assertion. \"\"\" @api_view def view(request): return Response() request =",
"view(request) assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED def test_renderer_classes(self): @api_view(['GET']) @renderer_classes([JSONRenderer]) def",
"Response({}) request = self.factory.get('/') response = view(request) assert response.status_code ==",
"response = view(request) assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED def test_calling_put_method(self): @api_view(['GET',",
"def view(request): raise NotImplementedError assert len(record) == 1 assert str(record[0].message)",
"None, 'suffix': 'Suffix', } # name + suffix is a",
"\"3.10 in favor of `action`, which accepts a `detail` bool.",
"'name': '<NAME>', } # name kwarg supersedes name generation @action(detail=True,",
"msg = \"Method 'get' has already been mapped to '.test_action'.\"",
"test_throttle_classes(self): class OncePerDayUserThrottle(UserRateThrottle): rate = '1/day' @api_view(['GET']) @throttle_classes([OncePerDayUserThrottle]) def view(request):",
"self.factory.get('/') view(request) def test_authentication_classes(self): @api_view(['GET']) @authentication_classes([BasicAuthentication]) def view(request): assert len(request.authenticators)",
"arguments.\" def test_method_mapping(self): @action(detail=False) def test_action(request): raise NotImplementedError @test_action.mapping.post def",
"@action(detail=True) def test_action(request): raise NotImplementedError msg = \"Method 'get' has",
"def test_calling_patch_method(self): @api_view(['GET', 'PATCH']) def view(request): return Response({}) request =",
"to base the `url_name` off of the `url_path` with pytest.warns(DeprecationWarning):",
"AutoSchema from rest_framework.test import APIRequestFactory from rest_framework.throttling import UserRateThrottle from",
"import JSONParser from rest_framework.permissions import IsAuthenticated from rest_framework.renderers import JSONRenderer",
"test_view_name_kwargs(self): \"\"\" 'name' and 'suffix' are mutually exclusive kwargs used",
"= \"Method 'get' has already been mapped to '.test_action'.\" with",
"*args, **kwargs): response.request = request return APIView.finalize_response(self, request, response, *args,",
"= view(request) assert response.status_code == status.HTTP_403_FORBIDDEN def test_throttle_classes(self): class OncePerDayUserThrottle(UserRateThrottle):",
"test_action.mapping[name] == name def test_view_name_kwargs(self): \"\"\" 'name' and 'suffix' are",
"# by default, generate name from method @action(detail=True) def test_action(request):",
"@test_action.mapping.post def test_action(): raise NotImplementedError def test_detail_route_deprecation(self): with pytest.warns(DeprecationWarning) as",
"`action`, which accepts a `detail` bool. Use \" \"`@action(detail=True)` instead.\"",
"test_action(request): raise NotImplementedError msg = \"Method 'get' has already been",
"mapping returns the correct method name for name in APIView.http_method_names:",
"== 1 assert str(record[0].message) == ( \"`list_route` is deprecated and",
"off of the `url_path` with pytest.warns(DeprecationWarning): @list_route(url_path='foo_bar') def view(request): raise",
"@renderer_classes([JSONRenderer]) def view(request): return Response({}) request = self.factory.get('/') response =",
"@parser_classes([JSONParser]) def view(request): assert len(request.parsers) == 1 assert isinstance(request.parsers[0], JSONParser)",
"self.factory.get('/') response = view(request) assert response.status_code == status.HTTP_403_FORBIDDEN def test_throttle_classes(self):",
"Checks CustomSchema class is set on view \"\"\" class CustomSchema(AutoSchema):",
"APIView class DecoratorTestCase(TestCase): def setUp(self): self.factory = APIRequestFactory() def _finalize_response(self,",
"from rest_framework.schemas import AutoSchema from rest_framework.test import APIRequestFactory from rest_framework.throttling",
"'test_action' assert test_action.url_name == 'test-action' assert test_action.kwargs == { 'name':",
"should not have the action attributes for name in ['mapping',",
"TestCase from rest_framework import status from rest_framework.authentication import BasicAuthentication from",
"test_action(): raise NotImplementedError for name in APIView.http_method_names: def method(): raise",
"view(request): assert len(request.parsers) == 1 assert isinstance(request.parsers[0], JSONParser) return Response({})",
"return APIView.finalize_response(self, request, response, *args, **kwargs) def test_api_view_incorrect(self): \"\"\" If",
"== \"@action() missing required argument: 'detail'\" def test_method_mapping_http_methods(self): # All",
"test_action_post(request): raise NotImplementedError # The secondary handler methods should not",
"test_action(request): raise NotImplementedError @test_action.mapping.post def test_action_post(request): raise NotImplementedError # The",
"def test_action(request): raise NotImplementedError assert str(excinfo.value) == \"@action() missing required",
"== 1 assert isinstance(request.authenticators[0], BasicAuthentication) return Response({}) request = self.factory.get('/')",
"APIView.http_method_names: def method(): raise NotImplementedError # Python 2.x compatibility -",
"@action(detail=False, methods=[]) def test_action(): raise NotImplementedError for name in APIView.http_method_names:",
"# name kwarg supersedes name generation @action(detail=True, name='<NAME>') def test_action(request):",
"import JSONRenderer from rest_framework.response import Response from rest_framework.schemas import AutoSchema",
"view \"\"\" class CustomSchema(AutoSchema): pass @api_view(['GET']) @schema(CustomSchema()) def view(request): return",
"= self.factory.post('/') response = view(request) assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED def",
"def test_api_view_incorrect_arguments(self): \"\"\" If @api_view is missing arguments, we should",
"'PATCH']) def view(request): return Response({}) request = self.factory.patch('/') response =",
"test_detail_route_deprecation(self): with pytest.warns(DeprecationWarning) as record: @detail_route() def view(request): raise NotImplementedError",
"= view(request) assert isinstance(response.accepted_renderer, JSONRenderer) def test_parser_classes(self): @api_view(['GET']) @parser_classes([JSONParser]) def",
"rest_framework.test import APIRequestFactory from rest_framework.throttling import UserRateThrottle from rest_framework.views import",
"@action() def test_action(request): raise NotImplementedError assert str(excinfo.value) == \"@action() missing",
"NotImplementedError for name in APIView.http_method_names: def method(): raise NotImplementedError #",
"name generation @action(detail=True, name='<NAME>') def test_action(request): raise NotImplementedError assert test_action.kwargs",
"def test_route_url_name_from_path(self): # pre-3.8 behavior was to base the `url_name`",
"test_method_mapping_http_methods(self): # All HTTP methods should be mappable @action(detail=False, methods=[])",
"'get' has already been mapped to '.test_action'.\" with self.assertRaisesMessage(AssertionError, msg):",
"None, 'name': '<NAME>', } # suffix kwarg supersedes name generation",
"def test_view_name_kwargs(self): \"\"\" 'name' and 'suffix' are mutually exclusive kwargs",
"def test_api_view_incorrect(self): \"\"\" If @api_view is not applied correct, we",
"== status.HTTP_200_OK request = self.factory.post('/') response = view(request) assert response.status_code",
"HTTP methods should be mappable @action(detail=False, methods=[]) def test_action(): raise",
"view(request) assert isinstance(response.accepted_renderer, JSONRenderer) def test_parser_classes(self): @api_view(['GET']) @parser_classes([JSONParser]) def view(request):",
"name) def test_method_mapping_already_mapped(self): @action(detail=True) def test_action(request): raise NotImplementedError msg =",
"import pytest from django.test import TestCase from rest_framework import status",
"pytest.warns(DeprecationWarning) as record: @list_route() def view(request): raise NotImplementedError assert len(record)",
"NotImplementedError assert str(excinfo.value) == \"@action() missing required argument: 'detail'\" def",
"def view(request): assert len(request.parsers) == 1 assert isinstance(request.parsers[0], JSONParser) return",
"= self.factory.get('/') response = view(request) assert response.status_code == status.HTTP_200_OK request",
"APIView.finalize_response(self, request, response, *args, **kwargs) def test_api_view_incorrect(self): \"\"\" If @api_view",
"class DecoratorTestCase(TestCase): def setUp(self): self.factory = APIRequestFactory() def _finalize_response(self, request,",
"view(request) def test_authentication_classes(self): @api_view(['GET']) @authentication_classes([BasicAuthentication]) def view(request): assert len(request.authenticators) ==",
"== status.HTTP_200_OK response = view(request) assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS def",
"def view(request): return Response({}) assert isinstance(view.cls.schema, CustomSchema) class ActionDecoratorTestCase(TestCase): def",
"the correct method name for name in APIView.http_method_names: assert test_action.mapping[name]",
"NotImplementedError assert len(record) == 1 assert str(record[0].message) == ( \"`list_route`",
"CustomSchema(AutoSchema): pass @api_view(['GET']) @schema(CustomSchema()) def view(request): return Response({}) assert isinstance(view.cls.schema,",
"in \" \"3.10 in favor of `action`, which accepts a",
"( \"`detail_route` is deprecated and will be removed in \"",
"generation @action(detail=True, name='<NAME>') def test_action(request): raise NotImplementedError assert test_action.kwargs ==",
"which accepts a `detail` bool. Use \" \"`@action(detail=False)` instead.\" )",
"setUp(self): self.factory = APIRequestFactory() def _finalize_response(self, request, response, *args, **kwargs):",
"for name in APIView.http_method_names: def method(): raise NotImplementedError # Python",
"view(request) assert response.status_code == status.HTTP_403_FORBIDDEN def test_throttle_classes(self): class OncePerDayUserThrottle(UserRateThrottle): rate",
"name in APIView.http_method_names: def method(): raise NotImplementedError # Python 2.x",
"== status.HTTP_405_METHOD_NOT_ALLOWED def test_calling_patch_method(self): @api_view(['GET', 'PATCH']) def view(request): return Response({})",
"are mutually exclusive arguments.\" def test_method_mapping(self): @action(detail=False) def test_action(request): raise",
"is deprecated and will be removed in \" \"3.10 in",
"rest_framework.renderers import JSONRenderer from rest_framework.response import Response from rest_framework.schemas import",
"len(request.parsers) == 1 assert isinstance(request.parsers[0], JSONParser) return Response({}) request =",
"= view(request) assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED def test_calling_patch_method(self): @api_view(['GET', 'PATCH'])",
"@action(detail=True, name='<NAME>') def test_action(request): raise NotImplementedError assert test_action.kwargs == {",
"is set on view \"\"\" class CustomSchema(AutoSchema): pass @api_view(['GET']) @schema(CustomSchema())",
"Use \" \"`@action(detail=True)` instead.\" ) def test_list_route_deprecation(self): with pytest.warns(DeprecationWarning) as",
"raise NotImplementedError msg = \"Method 'get' has already been mapped",
"response = view(request) assert response.status_code == status.HTTP_200_OK request = self.factory.post('/')",
"assert str(record[0].message) == ( \"`list_route` is deprecated and will be",
"`url_path` with pytest.warns(DeprecationWarning): @list_route(url_path='foo_bar') def view(request): raise NotImplementedError assert view.url_path",
"test_schema(self): \"\"\" Checks CustomSchema class is set on view \"\"\"",
"} def test_detail_required(self): with pytest.raises(AssertionError) as excinfo: @action() def test_action(request):",
"= (\"Method mapping does not behave like the property decorator.",
"'PUT']) def view(request): return Response({}) request = self.factory.put('/') response =",
"{ 'description': None, 'name': '<NAME>', } # name kwarg supersedes",
"and will be removed in \" \"3.10 in favor of",
"view(request) def test_permission_classes(self): @api_view(['GET']) @permission_classes([IsAuthenticated]) def view(request): return Response({}) request",
") def test_list_route_deprecation(self): with pytest.warns(DeprecationWarning) as record: @list_route() def view(request):",
"response.status_code == status.HTTP_429_TOO_MANY_REQUESTS def test_schema(self): \"\"\" Checks CustomSchema class is",
"= self.factory.patch('/') response = view(request) assert response.status_code == status.HTTP_200_OK request",
"raise NotImplementedError assert test_action.kwargs == { 'description': None, 'name': '<NAME>',",
"view(request): return Response({}) request = self.factory.put('/') response = view(request) assert",
"method.__name__ = str(name) getattr(test_action.mapping, name)(method) # ensure the mapping returns",
"@api_view(['GET']) @parser_classes([JSONParser]) def view(request): assert len(request.parsers) == 1 assert isinstance(request.parsers[0],",
"\"\"\" with self.assertRaises(AssertionError): @api_view('GET') def view(request): return Response() def test_calling_method(self):",
"name='test name', suffix='Suffix') assert str(excinfo.value) == \"`name` and `suffix` are",
"\"@action() missing required argument: 'detail'\" def test_method_mapping_http_methods(self): # All HTTP",
"= str(name) getattr(test_action.mapping, name)(method) # ensure the mapping returns the",
"@api_view(['GET']) @throttle_classes([OncePerDayUserThrottle]) def view(request): return Response({}) request = self.factory.get('/') response",
"each mapping declaration.\") with self.assertRaisesMessage(AssertionError, msg): @test_action.mapping.post def test_action(): raise",
"request = self.factory.get('/') response = view(request) assert response.status_code == status.HTTP_403_FORBIDDEN",
"msg = (\"Method mapping does not behave like the property",
"assertion. \"\"\" with self.assertRaises(AssertionError): @api_view('GET') def view(request): return Response() def",
"raise NotImplementedError # Python 2.x compatibility - cast __name__ to",
"str(excinfo.value) == \"`name` and `suffix` are mutually exclusive arguments.\" def",
"NotImplementedError msg = \"Method 'get' has already been mapped to",
"== \"`name` and `suffix` are mutually exclusive arguments.\" def test_method_mapping(self):",
"\"\"\" # by default, generate name from method @action(detail=True) def",
"test_action.kwargs == { 'description': None, 'suffix': 'Suffix', } # name",
"def test_throttle_classes(self): class OncePerDayUserThrottle(UserRateThrottle): rate = '1/day' @api_view(['GET']) @throttle_classes([OncePerDayUserThrottle]) def",
"in ['mapping', 'detail', 'url_path', 'url_name', 'kwargs']: assert hasattr(test_action, name) and",
"assert hasattr(test_action, name) and not hasattr(test_action_post, name) def test_method_mapping_already_mapped(self): @action(detail=True)",
"for each mapping declaration.\") with self.assertRaisesMessage(AssertionError, msg): @test_action.mapping.post def test_action():",
"use the same method name for each mapping declaration.\") with",
"the `url_name` off of the `url_path` with pytest.warns(DeprecationWarning): @list_route(url_path='foo_bar') def",
"assert test_action.url_name == 'test-action' assert test_action.kwargs == { 'name': 'Test",
"response = view(request) assert response.status_code == status.HTTP_403_FORBIDDEN def test_throttle_classes(self): class",
"raise NotImplementedError assert test_action.kwargs == { 'description': None, 'suffix': 'Suffix',",
"NotImplementedError def test_method_mapping_overwrite(self): @action(detail=True) def test_action(): raise NotImplementedError msg =",
"test_method_mapping(self): @action(detail=False) def test_action(request): raise NotImplementedError @test_action.mapping.post def test_action_post(request): raise",
"name) and not hasattr(test_action_post, name) def test_method_mapping_already_mapped(self): @action(detail=True) def test_action(request):",
"@action(detail=False) def test_action(request): raise NotImplementedError @test_action.mapping.post def test_action_post(request): raise NotImplementedError",
"behave like the property decorator. You \" \"cannot use the",
"@api_view('GET') def view(request): return Response() def test_calling_method(self): @api_view(['GET']) def view(request):",
"return Response() def test_calling_method(self): @api_view(['GET']) def view(request): return Response({}) request",
"test_action.detail is True assert test_action.url_path == 'test_action' assert test_action.url_name ==",
"@action(detail=True, suffix='Suffix') def test_action(request): raise NotImplementedError assert test_action.kwargs == {",
"def test_parser_classes(self): @api_view(['GET']) @parser_classes([JSONParser]) def view(request): assert len(request.parsers) == 1",
"\" \"`@action(detail=True)` instead.\" ) def test_list_route_deprecation(self): with pytest.warns(DeprecationWarning) as record:",
"str(name) getattr(test_action.mapping, name)(method) # ensure the mapping returns the correct",
"\"Method 'get' has already been mapped to '.test_action'.\" with self.assertRaisesMessage(AssertionError,",
"@test_action.mapping.get def test_action_get(request): raise NotImplementedError def test_method_mapping_overwrite(self): @action(detail=True) def test_action():",
"method @action(detail=True) def test_action(request): raise NotImplementedError assert test_action.kwargs == {",
"= self.factory.get('/') response = view(request) assert response.status_code == status.HTTP_403_FORBIDDEN def",
"class ActionDecoratorTestCase(TestCase): def test_defaults(self): @action(detail=True) def test_action(request): \"\"\"Description\"\"\" assert test_action.mapping",
"excinfo: @action() def test_action(request): raise NotImplementedError assert str(excinfo.value) == \"@action()",
"test_action.kwargs == { 'name': 'Test action', 'description': 'Description', } def",
"from rest_framework.parsers import JSONParser from rest_framework.permissions import IsAuthenticated from rest_framework.renderers",
"getattr(test_action.mapping, name)(method) # ensure the mapping returns the correct method",
"correct method name for name in APIView.http_method_names: assert test_action.mapping[name] ==",
"not have the action attributes for name in ['mapping', 'detail',",
"APIView.http_method_names: assert test_action.mapping[name] == name def test_view_name_kwargs(self): \"\"\" 'name' and",
"APIRequestFactory from rest_framework.throttling import UserRateThrottle from rest_framework.views import APIView class",
"test_action(request): raise NotImplementedError assert test_action.kwargs == { 'description': None, 'suffix':",
"the property decorator. You \" \"cannot use the same method",
"NotImplementedError # Python 2.x compatibility - cast __name__ to str",
"== { 'description': None, 'name': '<NAME>', } # suffix kwarg",
"not hasattr(test_action_post, name) def test_method_mapping_already_mapped(self): @action(detail=True) def test_action(request): raise NotImplementedError",
"return Response({}) assert isinstance(view.cls.schema, CustomSchema) class ActionDecoratorTestCase(TestCase): def test_defaults(self): @action(detail=True)",
"list_route, parser_classes, permission_classes, renderer_classes, schema, throttle_classes ) from rest_framework.parsers import",
"django.test import TestCase from rest_framework import status from rest_framework.authentication import",
"rest_framework.permissions import IsAuthenticated from rest_framework.renderers import JSONRenderer from rest_framework.response import",
"name def test_view_name_kwargs(self): \"\"\" 'name' and 'suffix' are mutually exclusive",
"accepts a `detail` bool. Use \" \"`@action(detail=False)` instead.\" ) def",
"assert test_action.mapping == {'get': 'test_action'} assert test_action.detail is True assert",
"len(record) == 1 assert str(record[0].message) == ( \"`list_route` is deprecated",
"hasattr(test_action, name) and not hasattr(test_action_post, name) def test_method_mapping_already_mapped(self): @action(detail=True) def",
"True assert test_action.url_path == 'test_action' assert test_action.url_name == 'test-action' assert",
"assert test_action.kwargs == { 'description': None, 'suffix': 'Suffix', } #",
"view's display name. \"\"\" # by default, generate name from",
"'test-action' assert test_action.kwargs == { 'name': 'Test action', 'description': 'Description',",
"required argument: 'detail'\" def test_method_mapping_http_methods(self): # All HTTP methods should",
"self.factory.put('/') response = view(request) assert response.status_code == status.HTTP_200_OK request =",
"@authentication_classes([BasicAuthentication]) def view(request): assert len(request.authenticators) == 1 assert isinstance(request.authenticators[0], BasicAuthentication)",
"assert str(record[0].message) == ( \"`detail_route` is deprecated and will be",
"BasicAuthentication from rest_framework.decorators import ( action, api_view, authentication_classes, detail_route, list_route,",
"request return APIView.finalize_response(self, request, response, *args, **kwargs) def test_api_view_incorrect(self): \"\"\"",
"= self.factory.get('/') self.assertRaises(AssertionError, view, request) def test_api_view_incorrect_arguments(self): \"\"\" If @api_view",
"'name': '<NAME>', } # suffix kwarg supersedes name generation @action(detail=True,",
"view, request) def test_api_view_incorrect_arguments(self): \"\"\" If @api_view is missing arguments,",
"suffix='Suffix') def test_action(request): raise NotImplementedError assert test_action.kwargs == { 'description':",
"# pre-3.8 behavior was to base the `url_name` off of",
"deprecated and will be removed in \" \"3.10 in favor",
"correct, we should raise an assertion. \"\"\" @api_view def view(request):",
"len(request.authenticators) == 1 assert isinstance(request.authenticators[0], BasicAuthentication) return Response({}) request =",
"def view(request): return Response({}) request = self.factory.put('/') response = view(request)",
"def test_action_get(request): raise NotImplementedError def test_method_mapping_overwrite(self): @action(detail=True) def test_action(): raise",
"= '1/day' @api_view(['GET']) @throttle_classes([OncePerDayUserThrottle]) def view(request): return Response({}) request =",
"status.HTTP_200_OK request = self.factory.post('/') response = view(request) assert response.status_code ==",
"mutually exclusive kwargs used for generating a view's display name.",
"pytest.raises(TypeError) as excinfo: action(detail=True, name='test name', suffix='Suffix') assert str(excinfo.value) ==",
"request = self.factory.post('/') response = view(request) assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED",
"test_route_url_name_from_path(self): # pre-3.8 behavior was to base the `url_name` off",
"If @api_view is not applied correct, we should raise an",
"is True assert test_action.url_path == 'test_action' assert test_action.url_name == 'test-action'",
"def test_action_post(request): raise NotImplementedError # The secondary handler methods should",
"mappable @action(detail=False, methods=[]) def test_action(): raise NotImplementedError for name in",
"status.HTTP_405_METHOD_NOT_ALLOWED def test_renderer_classes(self): @api_view(['GET']) @renderer_classes([JSONRenderer]) def view(request): return Response({}) request",
"\" \"3.10 in favor of `action`, which accepts a `detail`",
"behavior was to base the `url_name` off of the `url_path`",
"attributes for name in ['mapping', 'detail', 'url_path', 'url_name', 'kwargs']: assert",
"action', 'description': 'Description', } def test_detail_required(self): with pytest.raises(AssertionError) as excinfo:",
"supersedes name generation @action(detail=True, suffix='Suffix') def test_action(request): raise NotImplementedError assert",
"assert response.status_code == status.HTTP_403_FORBIDDEN def test_throttle_classes(self): class OncePerDayUserThrottle(UserRateThrottle): rate =",
"== 1 assert str(record[0].message) == ( \"`detail_route` is deprecated and",
"permission_classes, renderer_classes, schema, throttle_classes ) from rest_framework.parsers import JSONParser from",
"'Test action', 'description': 'Description', } def test_detail_required(self): with pytest.raises(AssertionError) as",
"methods should be mappable @action(detail=False, methods=[]) def test_action(): raise NotImplementedError",
"a conflict. with pytest.raises(TypeError) as excinfo: action(detail=True, name='test name', suffix='Suffix')",
"request = self.factory.put('/') response = view(request) assert response.status_code == status.HTTP_200_OK",
"@action(detail=True) def test_action(): raise NotImplementedError msg = (\"Method mapping does",
"on view \"\"\" class CustomSchema(AutoSchema): pass @api_view(['GET']) @schema(CustomSchema()) def view(request):",
"\" \"cannot use the same method name for each mapping",
"method(): raise NotImplementedError # Python 2.x compatibility - cast __name__",
"'<NAME>', } # suffix kwarg supersedes name generation @action(detail=True, suffix='Suffix')",
"__name__ to str method.__name__ = str(name) getattr(test_action.mapping, name)(method) # ensure",
"from rest_framework.response import Response from rest_framework.schemas import AutoSchema from rest_framework.test",
"from rest_framework import status from rest_framework.authentication import BasicAuthentication from rest_framework.decorators",
"and 'suffix' are mutually exclusive kwargs used for generating a",
"throttle_classes ) from rest_framework.parsers import JSONParser from rest_framework.permissions import IsAuthenticated",
"1 assert isinstance(request.authenticators[0], BasicAuthentication) return Response({}) request = self.factory.get('/') view(request)",
"pass @api_view(['GET']) @schema(CustomSchema()) def view(request): return Response({}) assert isinstance(view.cls.schema, CustomSchema)",
"'description': 'Description', } def test_detail_required(self): with pytest.raises(AssertionError) as excinfo: @action()",
"self.factory.patch('/') response = view(request) assert response.status_code == status.HTTP_200_OK request =",
"generating a view's display name. \"\"\" # by default, generate",
"@api_view(['GET']) @renderer_classes([JSONRenderer]) def view(request): return Response({}) request = self.factory.get('/') response",
"decorator. You \" \"cannot use the same method name for",
"@permission_classes([IsAuthenticated]) def view(request): return Response({}) request = self.factory.get('/') response =",
"renderer_classes, schema, throttle_classes ) from rest_framework.parsers import JSONParser from rest_framework.permissions",
"as excinfo: @action() def test_action(request): raise NotImplementedError assert str(excinfo.value) ==",
"accepts a `detail` bool. Use \" \"`@action(detail=True)` instead.\" ) def",
"IsAuthenticated from rest_framework.renderers import JSONRenderer from rest_framework.response import Response from",
"assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED def test_calling_put_method(self): @api_view(['GET', 'PUT']) def view(request):",
"request = self.factory.get('/') view(request) def test_authentication_classes(self): @api_view(['GET']) @authentication_classes([BasicAuthentication]) def view(request):",
"import AutoSchema from rest_framework.test import APIRequestFactory from rest_framework.throttling import UserRateThrottle",
"= self.factory.get('/') response = view(request) assert isinstance(response.accepted_renderer, JSONRenderer) def test_parser_classes(self):",
"response = view(request) assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS def test_schema(self): \"\"\"",
"test_calling_put_method(self): @api_view(['GET', 'PUT']) def view(request): return Response({}) request = self.factory.put('/')",
"DecoratorTestCase(TestCase): def setUp(self): self.factory = APIRequestFactory() def _finalize_response(self, request, response,",
"test_api_view_incorrect(self): \"\"\" If @api_view is not applied correct, we should",
"is not applied correct, we should raise an assertion. \"\"\"",
"import Response from rest_framework.schemas import AutoSchema from rest_framework.test import APIRequestFactory",
"assert str(excinfo.value) == \"@action() missing required argument: 'detail'\" def test_method_mapping_http_methods(self):",
"view(request): return Response({}) request = self.factory.patch('/') response = view(request) assert",
"self.factory.get('/') response = view(request) assert response.status_code == status.HTTP_200_OK response =",
"== ( \"`detail_route` is deprecated and will be removed in",
"NotImplementedError @test_action.mapping.post def test_action_post(request): raise NotImplementedError # The secondary handler",
"class CustomSchema(AutoSchema): pass @api_view(['GET']) @schema(CustomSchema()) def view(request): return Response({}) assert",
"test_action.url_name == 'test-action' assert test_action.kwargs == { 'name': 'Test action',",
"import BasicAuthentication from rest_framework.decorators import ( action, api_view, authentication_classes, detail_route,",
"rest_framework.response import Response from rest_framework.schemas import AutoSchema from rest_framework.test import",
"== 'test-action' assert test_action.kwargs == { 'name': 'Test action', 'description':",
"NotImplementedError assert test_action.kwargs == { 'description': None, 'name': '<NAME>', }",
"as excinfo: action(detail=True, name='test name', suffix='Suffix') assert str(excinfo.value) == \"`name`",
"response = view(request) assert isinstance(response.accepted_renderer, JSONRenderer) def test_parser_classes(self): @api_view(['GET']) @parser_classes([JSONParser])",
"import UserRateThrottle from rest_framework.views import APIView class DecoratorTestCase(TestCase): def setUp(self):",
"for name in APIView.http_method_names: assert test_action.mapping[name] == name def test_view_name_kwargs(self):",
"None, 'name': '<NAME>', } # name kwarg supersedes name generation",
"['mapping', 'detail', 'url_path', 'url_name', 'kwargs']: assert hasattr(test_action, name) and not",
"@list_route(url_path='foo_bar') def view(request): raise NotImplementedError assert view.url_path == 'foo_bar' assert",
"If @api_view is missing arguments, we should raise an assertion.",
"assert response.status_code == status.HTTP_200_OK request = self.factory.post('/') response = view(request)",
"pytest from django.test import TestCase from rest_framework import status from",
"from rest_framework.test import APIRequestFactory from rest_framework.throttling import UserRateThrottle from rest_framework.views",
"def test_method_mapping_overwrite(self): @action(detail=True) def test_action(): raise NotImplementedError msg = (\"Method",
"self.factory.post('/') response = view(request) assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED def test_renderer_classes(self):",
"response, *args, **kwargs) def test_api_view_incorrect(self): \"\"\" If @api_view is not",
"kwargs used for generating a view's display name. \"\"\" #",
"def test_action(request): raise NotImplementedError @test_action.mapping.post def test_action_post(request): raise NotImplementedError #",
") from rest_framework.parsers import JSONParser from rest_framework.permissions import IsAuthenticated from",
"from rest_framework.throttling import UserRateThrottle from rest_framework.views import APIView class DecoratorTestCase(TestCase):",
"@action(detail=True) def test_action(request): raise NotImplementedError assert test_action.kwargs == { 'description':",
"`suffix` are mutually exclusive arguments.\" def test_method_mapping(self): @action(detail=False) def test_action(request):",
"action, api_view, authentication_classes, detail_route, list_route, parser_classes, permission_classes, renderer_classes, schema, throttle_classes",
"request = self.factory.patch('/') response = view(request) assert response.status_code == status.HTTP_200_OK",
"not behave like the property decorator. You \" \"cannot use",
"parser_classes, permission_classes, renderer_classes, schema, throttle_classes ) from rest_framework.parsers import JSONParser",
"\"`@action(detail=True)` instead.\" ) def test_list_route_deprecation(self): with pytest.warns(DeprecationWarning) as record: @list_route()",
"rate = '1/day' @api_view(['GET']) @throttle_classes([OncePerDayUserThrottle]) def view(request): return Response({}) request",
"assert isinstance(request.parsers[0], JSONParser) return Response({}) request = self.factory.get('/') view(request) def",
"with pytest.raises(AssertionError) as excinfo: @action() def test_action(request): raise NotImplementedError assert",
"# ensure the mapping returns the correct method name for",
"= view(request) assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED def test_calling_put_method(self): @api_view(['GET', 'PUT'])",
"name from method @action(detail=True) def test_action(request): raise NotImplementedError assert test_action.kwargs",
"\"cannot use the same method name for each mapping declaration.\")",
"raise NotImplementedError @test_action.mapping.post def test_action_post(request): raise NotImplementedError # The secondary",
"__future__ import unicode_literals import pytest from django.test import TestCase from",
"raise NotImplementedError assert str(excinfo.value) == \"@action() missing required argument: 'detail'\"",
"( \"`list_route` is deprecated and will be removed in \"",
"assertion. \"\"\" @api_view def view(request): return Response() request = self.factory.get('/')",
"== status.HTTP_429_TOO_MANY_REQUESTS def test_schema(self): \"\"\" Checks CustomSchema class is set",
"== status.HTTP_405_METHOD_NOT_ALLOWED def test_calling_put_method(self): @api_view(['GET', 'PUT']) def view(request): return Response({})",
"import IsAuthenticated from rest_framework.renderers import JSONRenderer from rest_framework.response import Response",
"def setUp(self): self.factory = APIRequestFactory() def _finalize_response(self, request, response, *args,",
"@api_view is not applied correct, we should raise an assertion.",
"APIRequestFactory() def _finalize_response(self, request, response, *args, **kwargs): response.request = request",
"'<NAME>', } # name kwarg supersedes name generation @action(detail=True, name='<NAME>')",
"'.test_action'.\" with self.assertRaisesMessage(AssertionError, msg): @test_action.mapping.get def test_action_get(request): raise NotImplementedError def",
"def test_renderer_classes(self): @api_view(['GET']) @renderer_classes([JSONRenderer]) def view(request): return Response({}) request =",
"'test_action'} assert test_action.detail is True assert test_action.url_path == 'test_action' assert",
"You \" \"cannot use the same method name for each",
"assert test_action.kwargs == { 'name': 'Test action', 'description': 'Description', }",
"by default, generate name from method @action(detail=True) def test_action(request): raise",
"self.factory.get('/') response = view(request) assert isinstance(response.accepted_renderer, JSONRenderer) def test_parser_classes(self): @api_view(['GET'])",
"JSONRenderer) def test_parser_classes(self): @api_view(['GET']) @parser_classes([JSONParser]) def view(request): assert len(request.parsers) ==",
"`url_name` off of the `url_path` with pytest.warns(DeprecationWarning): @list_route(url_path='foo_bar') def view(request):",
"test_action_get(request): raise NotImplementedError def test_method_mapping_overwrite(self): @action(detail=True) def test_action(): raise NotImplementedError",
"return Response({}) request = self.factory.put('/') response = view(request) assert response.status_code",
"handler methods should not have the action attributes for name",
"mutually exclusive arguments.\" def test_method_mapping(self): @action(detail=False) def test_action(request): raise NotImplementedError",
"request = self.factory.get('/') view(request) def test_permission_classes(self): @api_view(['GET']) @permission_classes([IsAuthenticated]) def view(request):",
"argument: 'detail'\" def test_method_mapping_http_methods(self): # All HTTP methods should be",
"from rest_framework.decorators import ( action, api_view, authentication_classes, detail_route, list_route, parser_classes,",
"'url_path', 'url_name', 'kwargs']: assert hasattr(test_action, name) and not hasattr(test_action_post, name)",
"response = view(request) assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED def test_renderer_classes(self): @api_view(['GET'])",
"def test_action(request): raise NotImplementedError msg = \"Method 'get' has already",
"@list_route() def view(request): raise NotImplementedError assert len(record) == 1 assert",
"name for each mapping declaration.\") with self.assertRaisesMessage(AssertionError, msg): @test_action.mapping.post def",
"response.status_code == status.HTTP_200_OK response = view(request) assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS",
"hasattr(test_action_post, name) def test_method_mapping_already_mapped(self): @action(detail=True) def test_action(request): raise NotImplementedError msg",
"= self.factory.put('/') response = view(request) assert response.status_code == status.HTTP_200_OK request",
"instead.\" ) def test_list_route_deprecation(self): with pytest.warns(DeprecationWarning) as record: @list_route() def",
"response.request = request return APIView.finalize_response(self, request, response, *args, **kwargs) def",
"we should raise an assertion. \"\"\" with self.assertRaises(AssertionError): @api_view('GET') def",
"request, response, *args, **kwargs) def test_api_view_incorrect(self): \"\"\" If @api_view is",
"= self.factory.get('/') view(request) def test_authentication_classes(self): @api_view(['GET']) @authentication_classes([BasicAuthentication]) def view(request): assert",
"assert isinstance(request.authenticators[0], BasicAuthentication) return Response({}) request = self.factory.get('/') view(request) def",
"= APIRequestFactory() def _finalize_response(self, request, response, *args, **kwargs): response.request =",
"raise NotImplementedError for name in APIView.http_method_names: def method(): raise NotImplementedError",
"compatibility - cast __name__ to str method.__name__ = str(name) getattr(test_action.mapping,",
"== { 'description': None, 'name': '<NAME>', } # name kwarg",
"base the `url_name` off of the `url_path` with pytest.warns(DeprecationWarning): @list_route(url_path='foo_bar')",
"with self.assertRaisesMessage(AssertionError, msg): @test_action.mapping.get def test_action_get(request): raise NotImplementedError def test_method_mapping_overwrite(self):",
"request = self.factory.get('/') response = view(request) assert response.status_code == status.HTTP_200_OK",
"# All HTTP methods should be mappable @action(detail=False, methods=[]) def",
"the same method name for each mapping declaration.\") with self.assertRaisesMessage(AssertionError,",
"from method @action(detail=True) def test_action(request): raise NotImplementedError assert test_action.kwargs ==",
"} # suffix kwarg supersedes name generation @action(detail=True, suffix='Suffix') def",
"ActionDecoratorTestCase(TestCase): def test_defaults(self): @action(detail=True) def test_action(request): \"\"\"Description\"\"\" assert test_action.mapping ==",
"{ 'description': None, 'name': '<NAME>', } # suffix kwarg supersedes",
"the mapping returns the correct method name for name in",
"a `detail` bool. Use \" \"`@action(detail=True)` instead.\" ) def test_list_route_deprecation(self):",
"# Python 2.x compatibility - cast __name__ to str method.__name__",
"**kwargs) def test_api_view_incorrect(self): \"\"\" If @api_view is not applied correct,",
"class OncePerDayUserThrottle(UserRateThrottle): rate = '1/day' @api_view(['GET']) @throttle_classes([OncePerDayUserThrottle]) def view(request): return",
"Python 2.x compatibility - cast __name__ to str method.__name__ =",
"= view(request) assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED def test_renderer_classes(self): @api_view(['GET']) @renderer_classes([JSONRenderer])",
"mapping declaration.\") with self.assertRaisesMessage(AssertionError, msg): @test_action.mapping.post def test_action(): raise NotImplementedError",
"status from rest_framework.authentication import BasicAuthentication from rest_framework.decorators import ( action,",
"was to base the `url_name` off of the `url_path` with",
"response, *args, **kwargs): response.request = request return APIView.finalize_response(self, request, response,",
"UserRateThrottle from rest_framework.views import APIView class DecoratorTestCase(TestCase): def setUp(self): self.factory",
"test_calling_method(self): @api_view(['GET']) def view(request): return Response({}) request = self.factory.get('/') response",
"of `action`, which accepts a `detail` bool. Use \" \"`@action(detail=False)`",
"return Response({}) request = self.factory.get('/') response = view(request) assert response.status_code",
"# The secondary handler methods should not have the action",
"methods should not have the action attributes for name in",
"record: @list_route() def view(request): raise NotImplementedError assert len(record) == 1",
"assert response.status_code == status.HTTP_200_OK response = view(request) assert response.status_code ==",
"test_detail_required(self): with pytest.raises(AssertionError) as excinfo: @action() def test_action(request): raise NotImplementedError",
"**kwargs): response.request = request return APIView.finalize_response(self, request, response, *args, **kwargs)",
"== { 'name': 'Test action', 'description': 'Description', } def test_detail_required(self):",
"we should raise an assertion. \"\"\" @api_view def view(request): return",
"as record: @list_route() def view(request): raise NotImplementedError assert len(record) ==",
"the `url_path` with pytest.warns(DeprecationWarning): @list_route(url_path='foo_bar') def view(request): raise NotImplementedError assert",
"@api_view is missing arguments, we should raise an assertion. \"\"\"",
"self.factory.get('/') view(request) def test_permission_classes(self): @api_view(['GET']) @permission_classes([IsAuthenticated]) def view(request): return Response({})",
"def method(): raise NotImplementedError # Python 2.x compatibility - cast",
"of `action`, which accepts a `detail` bool. Use \" \"`@action(detail=True)`",
"has already been mapped to '.test_action'.\" with self.assertRaisesMessage(AssertionError, msg): @test_action.mapping.get",
"\"\"\" 'name' and 'suffix' are mutually exclusive kwargs used for",
"@api_view(['GET', 'PUT']) def view(request): return Response({}) request = self.factory.put('/') response",
"= view(request) assert response.status_code == status.HTTP_200_OK response = view(request) assert",
"len(record) == 1 assert str(record[0].message) == ( \"`detail_route` is deprecated",
"secondary handler methods should not have the action attributes for",
"raise NotImplementedError def test_method_mapping_overwrite(self): @action(detail=True) def test_action(): raise NotImplementedError msg",
"1 assert isinstance(request.parsers[0], JSONParser) return Response({}) request = self.factory.get('/') view(request)",
"Response({}) request = self.factory.put('/') response = view(request) assert response.status_code ==",
"str(record[0].message) == ( \"`list_route` is deprecated and will be removed",
"mapped to '.test_action'.\" with self.assertRaisesMessage(AssertionError, msg): @test_action.mapping.get def test_action_get(request): raise",
"\"`detail_route` is deprecated and will be removed in \" \"3.10",
"def test_action(): raise NotImplementedError def test_detail_route_deprecation(self): with pytest.warns(DeprecationWarning) as record:",
"like the property decorator. You \" \"cannot use the same",
"\"`name` and `suffix` are mutually exclusive arguments.\" def test_method_mapping(self): @action(detail=False)",
"*args, **kwargs) def test_api_view_incorrect(self): \"\"\" If @api_view is not applied",
"test_parser_classes(self): @api_view(['GET']) @parser_classes([JSONParser]) def view(request): assert len(request.parsers) == 1 assert",
"view(request): return Response() def test_calling_method(self): @api_view(['GET']) def view(request): return Response({})",
"Response({}) request = self.factory.get('/') response = view(request) assert isinstance(response.accepted_renderer, JSONRenderer)",
"\" \"`@action(detail=False)` instead.\" ) def test_route_url_name_from_path(self): # pre-3.8 behavior was",
"@api_view def view(request): return Response() request = self.factory.get('/') self.assertRaises(AssertionError, view,",
"'description': None, 'name': '<NAME>', } # name kwarg supersedes name",
"def test_calling_put_method(self): @api_view(['GET', 'PUT']) def view(request): return Response({}) request =",
"\"`@action(detail=False)` instead.\" ) def test_route_url_name_from_path(self): # pre-3.8 behavior was to",
"def test_action(): raise NotImplementedError for name in APIView.http_method_names: def method():",
"name kwarg supersedes name generation @action(detail=True, name='<NAME>') def test_action(request): raise",
"_finalize_response(self, request, response, *args, **kwargs): response.request = request return APIView.finalize_response(self,",
"'description': None, 'suffix': 'Suffix', } # name + suffix is",
"'url_name', 'kwargs']: assert hasattr(test_action, name) and not hasattr(test_action_post, name) def",
"view(request): raise NotImplementedError assert len(record) == 1 assert str(record[0].message) ==",
"rest_framework.authentication import BasicAuthentication from rest_framework.decorators import ( action, api_view, authentication_classes,",
"import ( action, api_view, authentication_classes, detail_route, list_route, parser_classes, permission_classes, renderer_classes,",
"schema, throttle_classes ) from rest_framework.parsers import JSONParser from rest_framework.permissions import",
"assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS def test_schema(self): \"\"\" Checks CustomSchema class",
"test_calling_patch_method(self): @api_view(['GET', 'PATCH']) def view(request): return Response({}) request = self.factory.patch('/')",
"== name def test_view_name_kwargs(self): \"\"\" 'name' and 'suffix' are mutually",
"as record: @detail_route() def view(request): raise NotImplementedError assert len(record) ==",
"def view(request): return Response() request = self.factory.get('/') self.assertRaises(AssertionError, view, request)",
"test_action.kwargs == { 'description': None, 'name': '<NAME>', } # suffix",
"arguments, we should raise an assertion. \"\"\" with self.assertRaises(AssertionError): @api_view('GET')",
"with self.assertRaises(AssertionError): @api_view('GET') def view(request): return Response() def test_calling_method(self): @api_view(['GET'])",
"self.factory.post('/') response = view(request) assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED def test_calling_patch_method(self):",
"`detail` bool. Use \" \"`@action(detail=True)` instead.\" ) def test_list_route_deprecation(self): with",
"name in APIView.http_method_names: assert test_action.mapping[name] == name def test_view_name_kwargs(self): \"\"\"",
"raise NotImplementedError # The secondary handler methods should not have",
"'detail', 'url_path', 'url_name', 'kwargs']: assert hasattr(test_action, name) and not hasattr(test_action_post,",
"test_list_route_deprecation(self): with pytest.warns(DeprecationWarning) as record: @list_route() def view(request): raise NotImplementedError",
"self.factory.get('/') response = view(request) assert response.status_code == status.HTTP_200_OK request =",
"NotImplementedError def test_detail_route_deprecation(self): with pytest.warns(DeprecationWarning) as record: @detail_route() def view(request):",
"name + suffix is a conflict. with pytest.raises(TypeError) as excinfo:",
"suffix kwarg supersedes name generation @action(detail=True, suffix='Suffix') def test_action(request): raise",
"which accepts a `detail` bool. Use \" \"`@action(detail=True)` instead.\" )",
"NotImplementedError assert len(record) == 1 assert str(record[0].message) == ( \"`detail_route`",
"def test_list_route_deprecation(self): with pytest.warns(DeprecationWarning) as record: @list_route() def view(request): raise",
"# name + suffix is a conflict. with pytest.raises(TypeError) as",
"Response from rest_framework.schemas import AutoSchema from rest_framework.test import APIRequestFactory from",
"JSONRenderer from rest_framework.response import Response from rest_framework.schemas import AutoSchema from",
"str method.__name__ = str(name) getattr(test_action.mapping, name)(method) # ensure the mapping",
"view(request): return Response({}) request = self.factory.get('/') response = view(request) assert",
"self.assertRaises(AssertionError): @api_view('GET') def view(request): return Response() def test_calling_method(self): @api_view(['GET']) def",
"str(excinfo.value) == \"@action() missing required argument: 'detail'\" def test_method_mapping_http_methods(self): #",
"for name in ['mapping', 'detail', 'url_path', 'url_name', 'kwargs']: assert hasattr(test_action,",
"{'get': 'test_action'} assert test_action.detail is True assert test_action.url_path == 'test_action'",
"= self.factory.get('/') response = view(request) assert response.status_code == status.HTTP_200_OK response",
"view(request): return Response() request = self.factory.get('/') self.assertRaises(AssertionError, view, request) def",
"instead.\" ) def test_route_url_name_from_path(self): # pre-3.8 behavior was to base",
"'Suffix', } # name + suffix is a conflict. with",
"from __future__ import unicode_literals import pytest from django.test import TestCase",
"# suffix kwarg supersedes name generation @action(detail=True, suffix='Suffix') def test_action(request):",
"response = view(request) assert response.status_code == status.HTTP_200_OK response = view(request)",
"def test_detail_route_deprecation(self): with pytest.warns(DeprecationWarning) as record: @detail_route() def view(request): raise",
"for generating a view's display name. \"\"\" # by default,",
"\"\"\" class CustomSchema(AutoSchema): pass @api_view(['GET']) @schema(CustomSchema()) def view(request): return Response({})",
"Response({}) request = self.factory.get('/') view(request) def test_authentication_classes(self): @api_view(['GET']) @authentication_classes([BasicAuthentication]) def",
"test_action(request): raise NotImplementedError assert str(excinfo.value) == \"@action() missing required argument:",
"'suffix' are mutually exclusive kwargs used for generating a view's",
"test_action(): raise NotImplementedError msg = (\"Method mapping does not behave",
"from rest_framework.authentication import BasicAuthentication from rest_framework.decorators import ( action, api_view,",
"property decorator. You \" \"cannot use the same method name",
"assert len(record) == 1 assert str(record[0].message) == ( \"`detail_route` is",
"generate name from method @action(detail=True) def test_action(request): raise NotImplementedError assert",
"action attributes for name in ['mapping', 'detail', 'url_path', 'url_name', 'kwargs']:",
"unicode_literals import pytest from django.test import TestCase from rest_framework import",
"def test_schema(self): \"\"\" Checks CustomSchema class is set on view",
"return Response() request = self.factory.get('/') self.assertRaises(AssertionError, view, request) def test_api_view_incorrect_arguments(self):",
"= view(request) assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS def test_schema(self): \"\"\" Checks",
"\"\"\" @api_view def view(request): return Response() request = self.factory.get('/') self.assertRaises(AssertionError,",
"NotImplementedError assert test_action.kwargs == { 'description': None, 'suffix': 'Suffix', }",
"be removed in \" \"3.10 in favor of `action`, which",
"All HTTP methods should be mappable @action(detail=False, methods=[]) def test_action():",
"view(request): return Response({}) assert isinstance(view.cls.schema, CustomSchema) class ActionDecoratorTestCase(TestCase): def test_defaults(self):",
"with pytest.warns(DeprecationWarning): @list_route(url_path='foo_bar') def view(request): raise NotImplementedError assert view.url_path ==",
"def test_method_mapping_http_methods(self): # All HTTP methods should be mappable @action(detail=False,",
"from rest_framework.views import APIView class DecoratorTestCase(TestCase): def setUp(self): self.factory =",
"def view(request): assert len(request.authenticators) == 1 assert isinstance(request.authenticators[0], BasicAuthentication) return",
"action(detail=True, name='test name', suffix='Suffix') assert str(excinfo.value) == \"`name` and `suffix`",
"\"`list_route` is deprecated and will be removed in \" \"3.10",
"@api_view(['GET', 'PATCH']) def view(request): return Response({}) request = self.factory.patch('/') response",
"OncePerDayUserThrottle(UserRateThrottle): rate = '1/day' @api_view(['GET']) @throttle_classes([OncePerDayUserThrottle]) def view(request): return Response({})",
"kwarg supersedes name generation @action(detail=True, name='<NAME>') def test_action(request): raise NotImplementedError",
"the action attributes for name in ['mapping', 'detail', 'url_path', 'url_name',",
"\"\"\" If @api_view is not applied correct, we should raise",
"def test_action(request): \"\"\"Description\"\"\" assert test_action.mapping == {'get': 'test_action'} assert test_action.detail",
") def test_route_url_name_from_path(self): # pre-3.8 behavior was to base the",
"== status.HTTP_405_METHOD_NOT_ALLOWED def test_renderer_classes(self): @api_view(['GET']) @renderer_classes([JSONRenderer]) def view(request): return Response({})",
"@action(detail=True) def test_action(request): \"\"\"Description\"\"\" assert test_action.mapping == {'get': 'test_action'} assert",
"in favor of `action`, which accepts a `detail` bool. Use",
"test_authentication_classes(self): @api_view(['GET']) @authentication_classes([BasicAuthentication]) def view(request): assert len(request.authenticators) == 1 assert",
"test_method_mapping_overwrite(self): @action(detail=True) def test_action(): raise NotImplementedError msg = (\"Method mapping",
"from rest_framework.renderers import JSONRenderer from rest_framework.response import Response from rest_framework.schemas",
"assert isinstance(response.accepted_renderer, JSONRenderer) def test_parser_classes(self): @api_view(['GET']) @parser_classes([JSONParser]) def view(request): assert",
"with pytest.raises(TypeError) as excinfo: action(detail=True, name='test name', suffix='Suffix') assert str(excinfo.value)",
"def view(request): raise NotImplementedError assert view.url_path == 'foo_bar' assert view.url_name",
"supersedes name generation @action(detail=True, name='<NAME>') def test_action(request): raise NotImplementedError assert",
"'1/day' @api_view(['GET']) @throttle_classes([OncePerDayUserThrottle]) def view(request): return Response({}) request = self.factory.get('/')",
"view(request) assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED def test_calling_put_method(self): @api_view(['GET', 'PUT']) def",
"Response({}) request = self.factory.patch('/') response = view(request) assert response.status_code ==",
"msg): @test_action.mapping.post def test_action(): raise NotImplementedError def test_detail_route_deprecation(self): with pytest.warns(DeprecationWarning)",
"BasicAuthentication) return Response({}) request = self.factory.get('/') view(request) def test_permission_classes(self): @api_view(['GET'])",
"bool. Use \" \"`@action(detail=False)` instead.\" ) def test_route_url_name_from_path(self): # pre-3.8",
"'suffix': 'Suffix', } # name + suffix is a conflict.",
"methods=[]) def test_action(): raise NotImplementedError for name in APIView.http_method_names: def",
"excinfo: action(detail=True, name='test name', suffix='Suffix') assert str(excinfo.value) == \"`name` and",
"test_action(request): raise NotImplementedError assert test_action.kwargs == { 'description': None, 'name':",
"name in ['mapping', 'detail', 'url_path', 'url_name', 'kwargs']: assert hasattr(test_action, name)",
"authentication_classes, detail_route, list_route, parser_classes, permission_classes, renderer_classes, schema, throttle_classes ) from",
"status.HTTP_429_TOO_MANY_REQUESTS def test_schema(self): \"\"\" Checks CustomSchema class is set on",
"assert test_action.detail is True assert test_action.url_path == 'test_action' assert test_action.url_name",
"rest_framework import status from rest_framework.authentication import BasicAuthentication from rest_framework.decorators import",
"== ( \"`list_route` is deprecated and will be removed in",
"1 assert str(record[0].message) == ( \"`detail_route` is deprecated and will",
"def test_authentication_classes(self): @api_view(['GET']) @authentication_classes([BasicAuthentication]) def view(request): assert len(request.authenticators) == 1",
"self.assertRaisesMessage(AssertionError, msg): @test_action.mapping.post def test_action(): raise NotImplementedError def test_detail_route_deprecation(self): with",
"isinstance(response.accepted_renderer, JSONRenderer) def test_parser_classes(self): @api_view(['GET']) @parser_classes([JSONParser]) def view(request): assert len(request.parsers)",
"assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED def test_renderer_classes(self): @api_view(['GET']) @renderer_classes([JSONRenderer]) def view(request):",
"def test_detail_required(self): with pytest.raises(AssertionError) as excinfo: @action() def test_action(request): raise",
"( action, api_view, authentication_classes, detail_route, list_route, parser_classes, permission_classes, renderer_classes, schema,",
"'name' and 'suffix' are mutually exclusive kwargs used for generating",
"assert test_action.mapping[name] == name def test_view_name_kwargs(self): \"\"\" 'name' and 'suffix'",
"a view's display name. \"\"\" # by default, generate name",
"from rest_framework.permissions import IsAuthenticated from rest_framework.renderers import JSONRenderer from rest_framework.response",
"name generation @action(detail=True, suffix='Suffix') def test_action(request): raise NotImplementedError assert test_action.kwargs",
"suffix='Suffix') assert str(excinfo.value) == \"`name` and `suffix` are mutually exclusive",
"response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED def test_calling_put_method(self): @api_view(['GET', 'PUT']) def view(request): return",
"request = self.factory.get('/') self.assertRaises(AssertionError, view, request) def test_api_view_incorrect_arguments(self): \"\"\" If",
"= view(request) assert response.status_code == status.HTTP_200_OK request = self.factory.post('/') response",
"'Description', } def test_detail_required(self): with pytest.raises(AssertionError) as excinfo: @action() def",
"generation @action(detail=True, suffix='Suffix') def test_action(request): raise NotImplementedError assert test_action.kwargs ==",
"status.HTTP_405_METHOD_NOT_ALLOWED def test_calling_patch_method(self): @api_view(['GET', 'PATCH']) def view(request): return Response({}) request",
"in APIView.http_method_names: def method(): raise NotImplementedError # Python 2.x compatibility",
"assert isinstance(view.cls.schema, CustomSchema) class ActionDecoratorTestCase(TestCase): def test_defaults(self): @action(detail=True) def test_action(request):",
"raise NotImplementedError def test_detail_route_deprecation(self): with pytest.warns(DeprecationWarning) as record: @detail_route() def",
"an assertion. \"\"\" with self.assertRaises(AssertionError): @api_view('GET') def view(request): return Response()",
"are mutually exclusive kwargs used for generating a view's display",
"import APIRequestFactory from rest_framework.throttling import UserRateThrottle from rest_framework.views import APIView",
"raise NotImplementedError msg = (\"Method mapping does not behave like",
"== 1 assert isinstance(request.parsers[0], JSONParser) return Response({}) request = self.factory.get('/')",
"a `detail` bool. Use \" \"`@action(detail=False)` instead.\" ) def test_route_url_name_from_path(self):",
"test_api_view_incorrect_arguments(self): \"\"\" If @api_view is missing arguments, we should raise",
"Response() def test_calling_method(self): @api_view(['GET']) def view(request): return Response({}) request =",
"isinstance(request.authenticators[0], BasicAuthentication) return Response({}) request = self.factory.get('/') view(request) def test_permission_classes(self):",
"str(record[0].message) == ( \"`detail_route` is deprecated and will be removed",
"ensure the mapping returns the correct method name for name",
"JSONParser) return Response({}) request = self.factory.get('/') view(request) def test_authentication_classes(self): @api_view(['GET'])",
"- cast __name__ to str method.__name__ = str(name) getattr(test_action.mapping, name)(method)",
"assert str(excinfo.value) == \"`name` and `suffix` are mutually exclusive arguments.\"",
"`action`, which accepts a `detail` bool. Use \" \"`@action(detail=False)` instead.\"",
"missing required argument: 'detail'\" def test_method_mapping_http_methods(self): # All HTTP methods",
"isinstance(view.cls.schema, CustomSchema) class ActionDecoratorTestCase(TestCase): def test_defaults(self): @action(detail=True) def test_action(request): \"\"\"Description\"\"\"",
"} # name + suffix is a conflict. with pytest.raises(TypeError)",
"assert test_action.url_path == 'test_action' assert test_action.url_name == 'test-action' assert test_action.kwargs",
"raise an assertion. \"\"\" with self.assertRaises(AssertionError): @api_view('GET') def view(request): return",
"def test_action(): raise NotImplementedError msg = (\"Method mapping does not",
"def _finalize_response(self, request, response, *args, **kwargs): response.request = request return",
"suffix is a conflict. with pytest.raises(TypeError) as excinfo: action(detail=True, name='test",
"import TestCase from rest_framework import status from rest_framework.authentication import BasicAuthentication",
"status.HTTP_405_METHOD_NOT_ALLOWED def test_calling_put_method(self): @api_view(['GET', 'PUT']) def view(request): return Response({}) request",
"request = self.factory.get('/') response = view(request) assert isinstance(response.accepted_renderer, JSONRenderer) def",
"self.factory.post('/') response = view(request) assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED def test_calling_put_method(self):",
"= request return APIView.finalize_response(self, request, response, *args, **kwargs) def test_api_view_incorrect(self):",
"== { 'description': None, 'suffix': 'Suffix', } # name +",
"pytest.raises(AssertionError) as excinfo: @action() def test_action(request): raise NotImplementedError assert str(excinfo.value)",
"same method name for each mapping declaration.\") with self.assertRaisesMessage(AssertionError, msg):",
"already been mapped to '.test_action'.\" with self.assertRaisesMessage(AssertionError, msg): @test_action.mapping.get def",
"NotImplementedError msg = (\"Method mapping does not behave like the",
"\"\"\"Description\"\"\" assert test_action.mapping == {'get': 'test_action'} assert test_action.detail is True",
"to str method.__name__ = str(name) getattr(test_action.mapping, name)(method) # ensure the",
"returns the correct method name for name in APIView.http_method_names: assert",
"msg): @test_action.mapping.get def test_action_get(request): raise NotImplementedError def test_method_mapping_overwrite(self): @action(detail=True) def",
"return Response({}) request = self.factory.get('/') view(request) def test_permission_classes(self): @api_view(['GET']) @permission_classes([IsAuthenticated])",
"response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED def test_renderer_classes(self): @api_view(['GET']) @renderer_classes([JSONRenderer]) def view(request): return",
"@schema(CustomSchema()) def view(request): return Response({}) assert isinstance(view.cls.schema, CustomSchema) class ActionDecoratorTestCase(TestCase):",
"rest_framework.parsers import JSONParser from rest_framework.permissions import IsAuthenticated from rest_framework.renderers import",
"== {'get': 'test_action'} assert test_action.detail is True assert test_action.url_path ==",
"isinstance(request.parsers[0], JSONParser) return Response({}) request = self.factory.get('/') view(request) def test_authentication_classes(self):",
"def test_defaults(self): @action(detail=True) def test_action(request): \"\"\"Description\"\"\" assert test_action.mapping == {'get':",
"name='<NAME>') def test_action(request): raise NotImplementedError assert test_action.kwargs == { 'description':",
"rest_framework.decorators import ( action, api_view, authentication_classes, detail_route, list_route, parser_classes, permission_classes,",
"assert len(record) == 1 assert str(record[0].message) == ( \"`list_route` is",
"return Response({}) request = self.factory.get('/') response = view(request) assert isinstance(response.accepted_renderer,",
"view(request) assert response.status_code == status.HTTP_200_OK response = view(request) assert response.status_code",
"import unicode_literals import pytest from django.test import TestCase from rest_framework",
"class is set on view \"\"\" class CustomSchema(AutoSchema): pass @api_view(['GET'])",
"should be mappable @action(detail=False, methods=[]) def test_action(): raise NotImplementedError for",
"raise an assertion. \"\"\" @api_view def view(request): return Response() request",
"self.assertRaisesMessage(AssertionError, msg): @test_action.mapping.get def test_action_get(request): raise NotImplementedError def test_method_mapping_overwrite(self): @action(detail=True)",
"status.HTTP_403_FORBIDDEN def test_throttle_classes(self): class OncePerDayUserThrottle(UserRateThrottle): rate = '1/day' @api_view(['GET']) @throttle_classes([OncePerDayUserThrottle])",
"be mappable @action(detail=False, methods=[]) def test_action(): raise NotImplementedError for name",
"== status.HTTP_403_FORBIDDEN def test_throttle_classes(self): class OncePerDayUserThrottle(UserRateThrottle): rate = '1/day' @api_view(['GET'])",
"view(request) assert response.status_code == status.HTTP_200_OK request = self.factory.post('/') response =",
"used for generating a view's display name. \"\"\" # by",
"set on view \"\"\" class CustomSchema(AutoSchema): pass @api_view(['GET']) @schema(CustomSchema()) def",
"test_defaults(self): @action(detail=True) def test_action(request): \"\"\"Description\"\"\" assert test_action.mapping == {'get': 'test_action'}",
"def view(request): return Response({}) request = self.factory.patch('/') response = view(request)",
"Response() request = self.factory.get('/') self.assertRaises(AssertionError, view, request) def test_api_view_incorrect_arguments(self): \"\"\"",
"does not behave like the property decorator. You \" \"cannot",
"removed in \" \"3.10 in favor of `action`, which accepts",
"def test_method_mapping(self): @action(detail=False) def test_action(request): raise NotImplementedError @test_action.mapping.post def test_action_post(request):",
"exclusive kwargs used for generating a view's display name. \"\"\"",
"test_action(request): \"\"\"Description\"\"\" assert test_action.mapping == {'get': 'test_action'} assert test_action.detail is",
"method name for each mapping declaration.\") with self.assertRaisesMessage(AssertionError, msg): @test_action.mapping.post",
"with pytest.warns(DeprecationWarning) as record: @detail_route() def view(request): raise NotImplementedError assert",
"def test_method_mapping_already_mapped(self): @action(detail=True) def test_action(request): raise NotImplementedError msg = \"Method",
"conflict. with pytest.raises(TypeError) as excinfo: action(detail=True, name='test name', suffix='Suffix') assert",
"status.HTTP_200_OK response = view(request) assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS def test_schema(self):",
"test_action.kwargs == { 'description': None, 'name': '<NAME>', } # name",
"pre-3.8 behavior was to base the `url_name` off of the",
"Response({}) request = self.factory.get('/') view(request) def test_permission_classes(self): @api_view(['GET']) @permission_classes([IsAuthenticated]) def",
"(\"Method mapping does not behave like the property decorator. You",
"def view(request): return Response({}) request = self.factory.get('/') response = view(request)",
"pytest.warns(DeprecationWarning): @list_route(url_path='foo_bar') def view(request): raise NotImplementedError assert view.url_path == 'foo_bar'",
"test_action.mapping == {'get': 'test_action'} assert test_action.detail is True assert test_action.url_path",
"and not hasattr(test_action_post, name) def test_method_mapping_already_mapped(self): @action(detail=True) def test_action(request): raise",
"assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED def test_calling_patch_method(self): @api_view(['GET', 'PATCH']) def view(request):",
"view(request) assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS def test_schema(self): \"\"\" Checks CustomSchema",
"default, generate name from method @action(detail=True) def test_action(request): raise NotImplementedError",
"rest_framework.schemas import AutoSchema from rest_framework.test import APIRequestFactory from rest_framework.throttling import",
"self.factory.get('/') self.assertRaises(AssertionError, view, request) def test_api_view_incorrect_arguments(self): \"\"\" If @api_view is",
"import APIView class DecoratorTestCase(TestCase): def setUp(self): self.factory = APIRequestFactory() def",
"'detail'\" def test_method_mapping_http_methods(self): # All HTTP methods should be mappable",
"is missing arguments, we should raise an assertion. \"\"\" with",
"should raise an assertion. \"\"\" with self.assertRaises(AssertionError): @api_view('GET') def view(request):",
"assert len(request.authenticators) == 1 assert isinstance(request.authenticators[0], BasicAuthentication) return Response({}) request",
"@api_view(['GET']) @schema(CustomSchema()) def view(request): return Response({}) assert isinstance(view.cls.schema, CustomSchema) class",
"= self.factory.get('/') view(request) def test_permission_classes(self): @api_view(['GET']) @permission_classes([IsAuthenticated]) def view(request): return",
"def test_calling_method(self): @api_view(['GET']) def view(request): return Response({}) request = self.factory.get('/')",
"test_method_mapping_already_mapped(self): @action(detail=True) def test_action(request): raise NotImplementedError msg = \"Method 'get'",
"request) def test_api_view_incorrect_arguments(self): \"\"\" If @api_view is missing arguments, we",
"NotImplementedError # The secondary handler methods should not have the",
"rest_framework.views import APIView class DecoratorTestCase(TestCase): def setUp(self): self.factory = APIRequestFactory()",
"applied correct, we should raise an assertion. \"\"\" @api_view def",
"response = view(request) assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED def test_calling_patch_method(self): @api_view(['GET',",
"view(request): raise NotImplementedError assert view.url_path == 'foo_bar' assert view.url_name ==",
"'description': None, 'name': '<NAME>', } # suffix kwarg supersedes name",
"{ 'description': None, 'suffix': 'Suffix', } # name + suffix",
"+ suffix is a conflict. with pytest.raises(TypeError) as excinfo: action(detail=True,",
"test_action(): raise NotImplementedError def test_detail_route_deprecation(self): with pytest.warns(DeprecationWarning) as record: @detail_route()",
"will be removed in \" \"3.10 in favor of `action`,",
"assert test_action.kwargs == { 'description': None, 'name': '<NAME>', } #",
"\"\"\" If @api_view is missing arguments, we should raise an",
"not applied correct, we should raise an assertion. \"\"\" @api_view",
"'name': 'Test action', 'description': 'Description', } def test_detail_required(self): with pytest.raises(AssertionError)",
"view(request) assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED def test_calling_patch_method(self): @api_view(['GET', 'PATCH']) def",
"def test_permission_classes(self): @api_view(['GET']) @permission_classes([IsAuthenticated]) def view(request): return Response({}) request =",
"'kwargs']: assert hasattr(test_action, name) and not hasattr(test_action_post, name) def test_method_mapping_already_mapped(self):",
"self.assertRaises(AssertionError, view, request) def test_api_view_incorrect_arguments(self): \"\"\" If @api_view is missing",
"missing arguments, we should raise an assertion. \"\"\" with self.assertRaises(AssertionError):",
"should raise an assertion. \"\"\" @api_view def view(request): return Response()",
"CustomSchema class is set on view \"\"\" class CustomSchema(AutoSchema): pass",
"display name. \"\"\" # by default, generate name from method",
"return Response({}) request = self.factory.patch('/') response = view(request) assert response.status_code",
"with self.assertRaisesMessage(AssertionError, msg): @test_action.mapping.post def test_action(): raise NotImplementedError def test_detail_route_deprecation(self):",
"JSONParser from rest_framework.permissions import IsAuthenticated from rest_framework.renderers import JSONRenderer from",
"detail_route, list_route, parser_classes, permission_classes, renderer_classes, schema, throttle_classes ) from rest_framework.parsers",
"is a conflict. with pytest.raises(TypeError) as excinfo: action(detail=True, name='test name',",
"method name for name in APIView.http_method_names: assert test_action.mapping[name] == name",
"of the `url_path` with pytest.warns(DeprecationWarning): @list_route(url_path='foo_bar') def view(request): raise NotImplementedError",
"1 assert str(record[0].message) == ( \"`list_route` is deprecated and will",
"@api_view(['GET']) @authentication_classes([BasicAuthentication]) def view(request): assert len(request.authenticators) == 1 assert isinstance(request.authenticators[0],",
"raise NotImplementedError assert len(record) == 1 assert str(record[0].message) == (",
"with pytest.warns(DeprecationWarning) as record: @list_route() def view(request): raise NotImplementedError assert",
"view(request): assert len(request.authenticators) == 1 assert isinstance(request.authenticators[0], BasicAuthentication) return Response({})",
"from django.test import TestCase from rest_framework import status from rest_framework.authentication",
"been mapped to '.test_action'.\" with self.assertRaisesMessage(AssertionError, msg): @test_action.mapping.get def test_action_get(request):",
"@api_view(['GET']) @permission_classes([IsAuthenticated]) def view(request): return Response({}) request = self.factory.get('/') response",
"record: @detail_route() def view(request): raise NotImplementedError assert len(record) == 1",
"@test_action.mapping.post def test_action_post(request): raise NotImplementedError # The secondary handler methods",
"Response({}) assert isinstance(view.cls.schema, CustomSchema) class ActionDecoratorTestCase(TestCase): def test_defaults(self): @action(detail=True) def",
"assert len(request.parsers) == 1 assert isinstance(request.parsers[0], JSONParser) return Response({}) request",
"favor of `action`, which accepts a `detail` bool. Use \"",
"raise NotImplementedError assert view.url_path == 'foo_bar' assert view.url_name == 'foo-bar'",
"== 'test_action' assert test_action.url_name == 'test-action' assert test_action.kwargs == {",
"{ 'name': 'Test action', 'description': 'Description', } def test_detail_required(self): with",
"mapping does not behave like the property decorator. You \"",
"import status from rest_framework.authentication import BasicAuthentication from rest_framework.decorators import ("
] |
[
"python morse_encode.py கலைஞர் CURRDIR = os.path.dirname(os.path.realpath(__file__)) def encode(text): with codecs.open(os.path.join(CURRDIR,\"data\",\"madurai_tamilmorse.json\"),\"r\",\"utf-8\")",
"import tamil import sys import os #e.g. python morse_encode.py கலைஞர்",
"for l in tamil.utf8.get_letters(text)] return u\" \".join(output) if __name__ ==",
"utf-8 -*- #(C) 2018 <NAME> # This file is part",
"tamil import sys import os #e.g. python morse_encode.py கலைஞர் CURRDIR",
"u\" \".join(output) if __name__ == u\"__main__\": encode(u\" \".join([i.decode(\"utf-8\") for i",
"MIT license import codecs import json import tamil import sys",
"license import codecs import json import tamil import sys import",
"codecs import json import tamil import sys import os #e.g.",
"distribute this file under terms of MIT license import codecs",
"\".join(output) if __name__ == u\"__main__\": encode(u\" \".join([i.decode(\"utf-8\") for i in",
"## -*- coding: utf-8 -*- #(C) 2018 <NAME> # This",
"as fp: codebook = json.loads(fp.read()) output = [codebook.get(l,l) for l",
"terms of MIT license import codecs import json import tamil",
"sys import os #e.g. python morse_encode.py கலைஞர் CURRDIR = os.path.dirname(os.path.realpath(__file__))",
"codebook = json.loads(fp.read()) output = [codebook.get(l,l) for l in tamil.utf8.get_letters(text)]",
"return u\" \".join(output) if __name__ == u\"__main__\": encode(u\" \".join([i.decode(\"utf-8\") for",
"<reponame>CRE2525/open-tamil<filename>tamilmorse/morse_encode.py ## -*- coding: utf-8 -*- #(C) 2018 <NAME> #",
"= os.path.dirname(os.path.realpath(__file__)) def encode(text): with codecs.open(os.path.join(CURRDIR,\"data\",\"madurai_tamilmorse.json\"),\"r\",\"utf-8\") as fp: codebook =",
"encode(text): with codecs.open(os.path.join(CURRDIR,\"data\",\"madurai_tamilmorse.json\"),\"r\",\"utf-8\") as fp: codebook = json.loads(fp.read()) output =",
"fp: codebook = json.loads(fp.read()) output = [codebook.get(l,l) for l in",
"in tamil.utf8.get_letters(text)] return u\" \".join(output) if __name__ == u\"__main__\": encode(u\"",
"[codebook.get(l,l) for l in tamil.utf8.get_letters(text)] return u\" \".join(output) if __name__",
"= [codebook.get(l,l) for l in tamil.utf8.get_letters(text)] return u\" \".join(output) if",
"You may use or distribute this file under terms of",
"this file under terms of MIT license import codecs import",
"import sys import os #e.g. python morse_encode.py கலைஞர் CURRDIR =",
"Open-Tamil project # You may use or distribute this file",
"or distribute this file under terms of MIT license import",
"if __name__ == u\"__main__\": encode(u\" \".join([i.decode(\"utf-8\") for i in sys.argv[1:]]))",
"of Open-Tamil project # You may use or distribute this",
"of MIT license import codecs import json import tamil import",
"# You may use or distribute this file under terms",
"coding: utf-8 -*- #(C) 2018 <NAME> # This file is",
"json import tamil import sys import os #e.g. python morse_encode.py",
"file is part of Open-Tamil project # You may use",
"= json.loads(fp.read()) output = [codebook.get(l,l) for l in tamil.utf8.get_letters(text)] return",
"file under terms of MIT license import codecs import json",
"project # You may use or distribute this file under",
"output = [codebook.get(l,l) for l in tamil.utf8.get_letters(text)] return u\" \".join(output)",
"import codecs import json import tamil import sys import os",
"-*- #(C) 2018 <NAME> # This file is part of",
"2018 <NAME> # This file is part of Open-Tamil project",
"#e.g. python morse_encode.py கலைஞர் CURRDIR = os.path.dirname(os.path.realpath(__file__)) def encode(text): with",
"This file is part of Open-Tamil project # You may",
"<NAME> # This file is part of Open-Tamil project #",
"#(C) 2018 <NAME> # This file is part of Open-Tamil",
"கலைஞர் CURRDIR = os.path.dirname(os.path.realpath(__file__)) def encode(text): with codecs.open(os.path.join(CURRDIR,\"data\",\"madurai_tamilmorse.json\"),\"r\",\"utf-8\") as fp:",
"under terms of MIT license import codecs import json import",
"may use or distribute this file under terms of MIT",
"import json import tamil import sys import os #e.g. python",
"use or distribute this file under terms of MIT license",
"l in tamil.utf8.get_letters(text)] return u\" \".join(output) if __name__ == u\"__main__\":",
"part of Open-Tamil project # You may use or distribute",
"codecs.open(os.path.join(CURRDIR,\"data\",\"madurai_tamilmorse.json\"),\"r\",\"utf-8\") as fp: codebook = json.loads(fp.read()) output = [codebook.get(l,l) for",
"os.path.dirname(os.path.realpath(__file__)) def encode(text): with codecs.open(os.path.join(CURRDIR,\"data\",\"madurai_tamilmorse.json\"),\"r\",\"utf-8\") as fp: codebook = json.loads(fp.read())",
"json.loads(fp.read()) output = [codebook.get(l,l) for l in tamil.utf8.get_letters(text)] return u\"",
"import os #e.g. python morse_encode.py கலைஞர் CURRDIR = os.path.dirname(os.path.realpath(__file__)) def",
"-*- coding: utf-8 -*- #(C) 2018 <NAME> # This file",
"with codecs.open(os.path.join(CURRDIR,\"data\",\"madurai_tamilmorse.json\"),\"r\",\"utf-8\") as fp: codebook = json.loads(fp.read()) output = [codebook.get(l,l)",
"is part of Open-Tamil project # You may use or",
"os #e.g. python morse_encode.py கலைஞர் CURRDIR = os.path.dirname(os.path.realpath(__file__)) def encode(text):",
"tamil.utf8.get_letters(text)] return u\" \".join(output) if __name__ == u\"__main__\": encode(u\" \".join([i.decode(\"utf-8\")",
"def encode(text): with codecs.open(os.path.join(CURRDIR,\"data\",\"madurai_tamilmorse.json\"),\"r\",\"utf-8\") as fp: codebook = json.loads(fp.read()) output",
"# This file is part of Open-Tamil project # You",
"morse_encode.py கலைஞர் CURRDIR = os.path.dirname(os.path.realpath(__file__)) def encode(text): with codecs.open(os.path.join(CURRDIR,\"data\",\"madurai_tamilmorse.json\"),\"r\",\"utf-8\") as",
"CURRDIR = os.path.dirname(os.path.realpath(__file__)) def encode(text): with codecs.open(os.path.join(CURRDIR,\"data\",\"madurai_tamilmorse.json\"),\"r\",\"utf-8\") as fp: codebook"
] |
[
"k], array[k - 1] head = ListNode(0) dummy = head",
"is None or head.next is None: return head slow =",
"array[k - 1], array[len(array) - k] = array[len(array) - k],",
"Optional[ListNode], k: int) -> Optional[ListNode]: temp = head array =",
"for num in array: dummy.next = ListNode(num) dummy = dummy.next",
"array: dummy.next = ListNode(num) dummy = dummy.next return head.next #",
"list. # class ListNode: # def __init__(self, val=0, next=None): #",
"k] = array[len(array) - k], array[k - 1] head =",
"# self.next = next class Solution: def swapNodes(self, head: Optional[ListNode],",
"- k): fast = fast.next slow.val, fast.val = fast.val, slow.val",
"slow = slow.next for _ in range(counter - k): fast",
"val=0, next=None): # self.val = val # self.next = next",
"swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: temp = head",
"head.next # Definition for singly-linked list. # class ListNode: #",
"self.val = val # self.next = next class Solution: def",
"next class Solution: def swapNodes(self, head: Optional[ListNode], k: int) ->",
"= head array = [] while temp: array.append(temp.val) temp =",
"0 while cnt: counter += 1 cnt = cnt.next for",
"[] while temp: array.append(temp.val) temp = temp.next array[k - 1],",
"self.next = next class Solution: def swapNodes(self, head: Optional[ListNode], k:",
"singly-linked list. # class ListNode: # def __init__(self, val=0, next=None):",
"<filename>Leetcode/Python/_1721.py<gh_stars>0 # Definition for singly-linked list. # class ListNode: #",
"- 1], array[len(array) - k] = array[len(array) - k], array[k",
"temp.next array[k - 1], array[len(array) - k] = array[len(array) -",
"Optional[ListNode]: temp = head array = [] while temp: array.append(temp.val)",
"head for num in array: dummy.next = ListNode(num) dummy =",
"for singly-linked list. # class ListNode: # def __init__(self, val=0,",
"cnt = head counter = 0 while cnt: counter +=",
"counter = 0 while cnt: counter += 1 cnt =",
"= val # self.next = next class Solution: def swapNodes(self,",
"cnt = cnt.next for _ in range(k - 1): slow",
"array = [] while temp: array.append(temp.val) temp = temp.next array[k",
"while temp: array.append(temp.val) temp = temp.next array[k - 1], array[len(array)",
"= slow.next for _ in range(counter - k): fast =",
"k: int) -> Optional[ListNode]: if head is None or head.next",
"= next class Solution: def swapNodes(self, head: Optional[ListNode], k: int)",
"= array[len(array) - k], array[k - 1] head = ListNode(0)",
"1): slow = slow.next for _ in range(counter - k):",
"next=None): # self.val = val # self.next = next class",
"dummy.next return head.next # Definition for singly-linked list. # class",
"head slow = fast = cnt = head counter =",
"range(counter - k): fast = fast.next slow.val, fast.val = fast.val,",
"Solution: def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: temp",
"array.append(temp.val) temp = temp.next array[k - 1], array[len(array) - k]",
"val # self.next = next class Solution: def swapNodes(self, head:",
"def __init__(self, val=0, next=None): # self.val = val # self.next",
"head = ListNode(0) dummy = head for num in array:",
"head.next is None: return head slow = fast = cnt",
"- k] = array[len(array) - k], array[k - 1] head",
"1] head = ListNode(0) dummy = head for num in",
"int) -> Optional[ListNode]: temp = head array = [] while",
"return head.next # Definition for singly-linked list. # class ListNode:",
"counter += 1 cnt = cnt.next for _ in range(k",
"# Definition for singly-linked list. # class ListNode: # def",
"- 1] head = ListNode(0) dummy = head for num",
"array[len(array) - k], array[k - 1] head = ListNode(0) dummy",
"temp = temp.next array[k - 1], array[len(array) - k] =",
"# class ListNode: # def __init__(self, val=0, next=None): # self.val",
"or head.next is None: return head slow = fast =",
"range(k - 1): slow = slow.next for _ in range(counter",
"# def __init__(self, val=0, next=None): # self.val = val #",
"= [] while temp: array.append(temp.val) temp = temp.next array[k -",
"dummy.next = ListNode(num) dummy = dummy.next return head.next # Definition",
"_ in range(counter - k): fast = fast.next slow.val, fast.val",
"= 0 while cnt: counter += 1 cnt = cnt.next",
"class ListNode: # def __init__(self, val=0, next=None): # self.val =",
"num in array: dummy.next = ListNode(num) dummy = dummy.next return",
"array[len(array) - k] = array[len(array) - k], array[k - 1]",
"= dummy.next return head.next # Definition for singly-linked list. #",
"def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: temp =",
"Solution: def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: if",
"dummy = dummy.next return head.next # Definition for singly-linked list.",
"= fast = cnt = head counter = 0 while",
"1 cnt = cnt.next for _ in range(k - 1):",
"1], array[len(array) - k] = array[len(array) - k], array[k -",
"- k], array[k - 1] head = ListNode(0) dummy =",
"_ in range(k - 1): slow = slow.next for _",
"None: return head slow = fast = cnt = head",
"fast = cnt = head counter = 0 while cnt:",
"while cnt: counter += 1 cnt = cnt.next for _",
"temp = head array = [] while temp: array.append(temp.val) temp",
"in array: dummy.next = ListNode(num) dummy = dummy.next return head.next",
"Definition for singly-linked list. # class ListNode: # def __init__(self,",
"in range(k - 1): slow = slow.next for _ in",
"head array = [] while temp: array.append(temp.val) temp = temp.next",
"slow = fast = cnt = head counter = 0",
"head is None or head.next is None: return head slow",
"head: Optional[ListNode], k: int) -> Optional[ListNode]: temp = head array",
"None or head.next is None: return head slow = fast",
"temp: array.append(temp.val) temp = temp.next array[k - 1], array[len(array) -",
"head counter = 0 while cnt: counter += 1 cnt",
"ListNode(0) dummy = head for num in array: dummy.next =",
"= temp.next array[k - 1], array[len(array) - k] = array[len(array)",
"-> Optional[ListNode]: if head is None or head.next is None:",
"k): fast = fast.next slow.val, fast.val = fast.val, slow.val return",
"array[k - 1] head = ListNode(0) dummy = head for",
"Optional[ListNode]: if head is None or head.next is None: return",
"if head is None or head.next is None: return head",
"+= 1 cnt = cnt.next for _ in range(k -",
"fast = fast.next slow.val, fast.val = fast.val, slow.val return head",
"cnt.next for _ in range(k - 1): slow = slow.next",
"for _ in range(k - 1): slow = slow.next for",
"ListNode: # def __init__(self, val=0, next=None): # self.val = val",
"Optional[ListNode], k: int) -> Optional[ListNode]: if head is None or",
"= head for num in array: dummy.next = ListNode(num) dummy",
"k: int) -> Optional[ListNode]: temp = head array = []",
"= ListNode(num) dummy = dummy.next return head.next # Definition for",
"in range(counter - k): fast = fast.next slow.val, fast.val =",
"swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: if head is",
"= ListNode(0) dummy = head for num in array: dummy.next",
"- 1): slow = slow.next for _ in range(counter -",
"class Solution: def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:",
"cnt: counter += 1 cnt = cnt.next for _ in",
"slow.next for _ in range(counter - k): fast = fast.next",
"= cnt.next for _ in range(k - 1): slow =",
"return head slow = fast = cnt = head counter",
"for _ in range(counter - k): fast = fast.next slow.val,",
"def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: if head",
"int) -> Optional[ListNode]: if head is None or head.next is",
"= head counter = 0 while cnt: counter += 1",
"__init__(self, val=0, next=None): # self.val = val # self.next =",
"ListNode(num) dummy = dummy.next return head.next # Definition for singly-linked",
"is None: return head slow = fast = cnt =",
"= cnt = head counter = 0 while cnt: counter",
"dummy = head for num in array: dummy.next = ListNode(num)",
"head: Optional[ListNode], k: int) -> Optional[ListNode]: if head is None",
"-> Optional[ListNode]: temp = head array = [] while temp:",
"# self.val = val # self.next = next class Solution:"
] |
[
"to node if electrumsv_node.is_node_running(): utils.submit_blocks_from_file(node_id='node1', filepath=Path(MODULE_DIR).joinpath('../reorg_blocks/node1_blocks.dat')) else: logger.exception(\"node unavailable\") try:",
"def wait_for_reog_transaction_update(reorged_txids, reorg_height): MAX_WAIT_TIME = 10 # seconds async with",
"will be synchronized by ElectrumSV reorged txid: 'a1fa9460ca105c1396cd338f7fa202bf79a9d244d730e91e19f6302a05b2f07a' \"\"\" import",
"seconds\") raise class TestReorg: @classmethod def setup_class(cls): pass @classmethod def",
"# Submit node1 blocks to node if electrumsv_node.is_node_running(): utils.submit_blocks_from_file(node_id='node1', filepath=Path(MODULE_DIR).joinpath('../reorg_blocks/node1_blocks.dat'))",
"Load the default wallet on ElectrumSV daemon url = f\"http://127.0.0.1:9999/v1/regtest/dapp/wallets/worker1.sqlite/load_wallet\"",
"result = requests.post(url, json=payload) result.raise_for_status() # Submit node1 blocks to",
"201) # Todo check state of get_balance; get_coin_state; get_transaction_history #",
"pytest.xfail(\"work in progress alongside refactoring changes...\") # Todo check state",
"TxStateWSClient MODULE_DIR = os.path.dirname(os.path.abspath(__file__)) logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(\"simulate-fresh-reorg\") async def",
"= f\"http://127.0.0.1:9999/v1/regtest/dapp/wallets/worker1.sqlite/load_wallet\" result = requests.post(url, json=payload) result.raise_for_status() # Submit node1",
"loads the default wallet on the daemon (so that newly",
"test_reorg(self, event_loop): async def test_reorg(): payload = { \"password\": \"<PASSWORD>\"",
"utils.submit_blocks_from_file(node_id='node1', filepath=Path(MODULE_DIR).joinpath('../reorg_blocks/node1_blocks.dat')) else: logger.exception(\"node unavailable\") try: await wait_for_reog_transaction_update([REORGED_TXIDS], 201) #",
"{ \"password\": \"<PASSWORD>\" } REORGED_TXIDS = \"a1fa9460ca105c1396cd338f7fa202bf79a9d244d730e91e19f6302a05b2f07a\" # Load the",
"except asyncio.TimeoutError: pytest.xfail(\"work in progress alongside refactoring changes...\") # Todo",
"electrumsv_sdk import utils import logging import requests from contrib.functional_tests.websocket_client import",
"electrumx1 and electrumsv1 and loads the default wallet on the",
"wallet on the daemon (so that newly submitted blocks will",
"@pytest.mark.asyncio def test_reorg(self, event_loop): async def test_reorg(): payload = {",
"by ElectrumSV reorged txid: 'a1fa9460ca105c1396cd338f7fa202bf79a9d244d730e91e19f6302a05b2f07a' \"\"\" import asyncio import os",
"logger.exception(\"node unavailable\") await wait_for_reog_transaction_update([REORGED_TXIDS], 202) except asyncio.TimeoutError: pytest.xfail(\"work in progress",
"\"\"\" import asyncio import os from pathlib import Path import",
"10 # seconds async with TxStateWSClient() as ws_client: try: await",
"setup_class(cls): pass @classmethod def teardown_class(cls): pass @pytest.mark.asyncio def test_reorg(self, event_loop):",
"logging.getLogger(\"simulate-fresh-reorg\") async def wait_for_reog_transaction_update(reorged_txids, reorg_height): MAX_WAIT_TIME = 10 # seconds",
"electrumsv_node import electrumsv_node from electrumsv_sdk import utils import logging import",
"= logging.getLogger(\"simulate-fresh-reorg\") async def wait_for_reog_transaction_update(reorged_txids, reorg_height): MAX_WAIT_TIME = 10 #",
"Submit node1 blocks to node if electrumsv_node.is_node_running(): utils.submit_blocks_from_file(node_id='node1', filepath=Path(MODULE_DIR).joinpath('../reorg_blocks/node1_blocks.dat')) else:",
"to a blank state before running the simulation Runs node1,",
"asyncio.TimeoutError: pytest.xfail(\"work in progress alongside refactoring changes...\") # Todo check",
"= 10 # seconds async with TxStateWSClient() as ws_client: try:",
"blank state before running the simulation Runs node1, electrumx1 and",
"after {MAX_WAIT_TIME} seconds\") raise class TestReorg: @classmethod def setup_class(cls): pass",
"else: logger.exception(\"node unavailable\") try: await wait_for_reog_transaction_update([REORGED_TXIDS], 201) # Todo check",
"class TestReorg: @classmethod def setup_class(cls): pass @classmethod def teardown_class(cls): pass",
"await wait_for_reog_transaction_update([REORGED_TXIDS], 201) # Todo check state of get_balance; get_coin_state;",
"ws_client: try: await asyncio.wait_for(ws_client.block_until_confirmed_and_height_updated( reorged_txids, reorg_height), MAX_WAIT_TIME) except asyncio.TimeoutError: logger.exception(f\"timed",
"'a1fa9460ca105c1396cd338f7fa202bf79a9d244d730e91e19f6302a05b2f07a' \"\"\" import asyncio import os from pathlib import Path",
"pathlib import Path import pytest import pytest_asyncio from electrumsv_node import",
"try: await wait_for_reog_transaction_update([REORGED_TXIDS], 201) # Todo check state of get_balance;",
"import pytest import pytest_asyncio from electrumsv_node import electrumsv_node from electrumsv_sdk",
"as ws_client: try: await asyncio.wait_for(ws_client.block_until_confirmed_and_height_updated( reorged_txids, reorg_height), MAX_WAIT_TIME) except asyncio.TimeoutError:",
"{MAX_WAIT_TIME} seconds\") raise class TestReorg: @classmethod def setup_class(cls): pass @classmethod",
"blocks to node if electrumsv_node.is_node_running(): utils.submit_blocks_from_file(node_id='node1', filepath=Path(MODULE_DIR).joinpath('../reorg_blocks/node1_blocks.dat')) else: logger.exception(\"node unavailable\")",
"- this will reset all components back to a blank",
"state of get_balance; get_coin_state; get_transaction_history # Submit node2 blocks to",
"on the daemon (so that newly submitted blocks will be",
"be synchronized by ElectrumSV reorged txid: 'a1fa9460ca105c1396cd338f7fa202bf79a9d244d730e91e19f6302a05b2f07a' \"\"\" import asyncio",
"= os.path.dirname(os.path.abspath(__file__)) logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(\"simulate-fresh-reorg\") async def wait_for_reog_transaction_update(reorged_txids, reorg_height):",
"reorg_height), MAX_WAIT_TIME) except asyncio.TimeoutError: logger.exception(f\"timed out after {MAX_WAIT_TIME} seconds\") raise",
"= \"a1fa9460ca105c1396cd338f7fa202bf79a9d244d730e91e19f6302a05b2f07a\" # Load the default wallet on ElectrumSV daemon",
"wait_for_reog_transaction_update([REORGED_TXIDS], 202) except asyncio.TimeoutError: pytest.xfail(\"work in progress alongside refactoring changes...\")",
"from contrib.functional_tests.websocket_client import TxStateWSClient MODULE_DIR = os.path.dirname(os.path.abspath(__file__)) logging.basicConfig(level=logging.DEBUG) logger =",
"def teardown_class(cls): pass @pytest.mark.asyncio def test_reorg(self, event_loop): async def test_reorg():",
"logging import requests from contrib.functional_tests.websocket_client import TxStateWSClient MODULE_DIR = os.path.dirname(os.path.abspath(__file__))",
"the default wallet on ElectrumSV daemon url = f\"http://127.0.0.1:9999/v1/regtest/dapp/wallets/worker1.sqlite/load_wallet\" result",
"\"\"\" Warning - this will reset all components back to",
"back to a blank state before running the simulation Runs",
"event_loop): async def test_reorg(): payload = { \"password\": \"<PASSWORD>\" }",
"contrib.functional_tests.websocket_client import TxStateWSClient MODULE_DIR = os.path.dirname(os.path.abspath(__file__)) logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(\"simulate-fresh-reorg\")",
"MAX_WAIT_TIME = 10 # seconds async with TxStateWSClient() as ws_client:",
"unavailable\") await wait_for_reog_transaction_update([REORGED_TXIDS], 202) except asyncio.TimeoutError: pytest.xfail(\"work in progress alongside",
"reorg_height): MAX_WAIT_TIME = 10 # seconds async with TxStateWSClient() as",
"components back to a blank state before running the simulation",
"if electrumsv_node.is_node_running(): utils.submit_blocks_from_file(node_id='node1', filepath=Path(MODULE_DIR).joinpath('../reorg_blocks/node1_blocks.dat')) else: logger.exception(\"node unavailable\") try: await wait_for_reog_transaction_update([REORGED_TXIDS],",
"all components back to a blank state before running the",
"asyncio.TimeoutError: logger.exception(f\"timed out after {MAX_WAIT_TIME} seconds\") raise class TestReorg: @classmethod",
"node if electrumsv_node.is_node_running(): utils.submit_blocks_from_file(node_id='node1', filepath=Path(MODULE_DIR).joinpath('../reorg_blocks/node1_blocks.dat')) else: logger.exception(\"node unavailable\") try: await",
"<reponame>electrumsv/electrumsv<filename>contrib/functional_tests/functional/test_reorg.py \"\"\" Warning - this will reset all components back",
"import pytest_asyncio from electrumsv_node import electrumsv_node from electrumsv_sdk import utils",
"os from pathlib import Path import pytest import pytest_asyncio from",
"requests.post(url, json=payload) result.raise_for_status() # Submit node1 blocks to node if",
"reset all components back to a blank state before running",
"Submit node2 blocks to node if electrumsv_node.is_node_running(): utils.submit_blocks_from_file(node_id='node1', filepath=Path(MODULE_DIR).joinpath('../reorg_blocks/node2_blocks.dat')) else:",
"\"<PASSWORD>\" } REORGED_TXIDS = \"a1fa9460ca105c1396cd338f7fa202bf79a9d244d730e91e19f6302a05b2f07a\" # Load the default wallet",
"submitted blocks will be synchronized by ElectrumSV reorged txid: 'a1fa9460ca105c1396cd338f7fa202bf79a9d244d730e91e19f6302a05b2f07a'",
"and loads the default wallet on the daemon (so that",
"the default wallet on the daemon (so that newly submitted",
"newly submitted blocks will be synchronized by ElectrumSV reorged txid:",
"logger = logging.getLogger(\"simulate-fresh-reorg\") async def wait_for_reog_transaction_update(reorged_txids, reorg_height): MAX_WAIT_TIME = 10",
"asyncio.wait_for(ws_client.block_until_confirmed_and_height_updated( reorged_txids, reorg_height), MAX_WAIT_TIME) except asyncio.TimeoutError: logger.exception(f\"timed out after {MAX_WAIT_TIME}",
"def test_reorg(self, event_loop): async def test_reorg(): payload = { \"password\":",
"alongside refactoring changes...\") # Todo check state of get_balance; get_coin_state;",
"import electrumsv_node from electrumsv_sdk import utils import logging import requests",
"def setup_class(cls): pass @classmethod def teardown_class(cls): pass @pytest.mark.asyncio def test_reorg(self,",
"url = f\"http://127.0.0.1:9999/v1/regtest/dapp/wallets/worker1.sqlite/load_wallet\" result = requests.post(url, json=payload) result.raise_for_status() # Submit",
"default wallet on ElectrumSV daemon url = f\"http://127.0.0.1:9999/v1/regtest/dapp/wallets/worker1.sqlite/load_wallet\" result =",
"import asyncio import os from pathlib import Path import pytest",
"utils import logging import requests from contrib.functional_tests.websocket_client import TxStateWSClient MODULE_DIR",
"MODULE_DIR = os.path.dirname(os.path.abspath(__file__)) logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(\"simulate-fresh-reorg\") async def wait_for_reog_transaction_update(reorged_txids,",
"import utils import logging import requests from contrib.functional_tests.websocket_client import TxStateWSClient",
"Todo check state of get_balance; get_coin_state; get_transaction_history # Submit node2",
"import TxStateWSClient MODULE_DIR = os.path.dirname(os.path.abspath(__file__)) logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(\"simulate-fresh-reorg\") async",
"pass @classmethod def teardown_class(cls): pass @pytest.mark.asyncio def test_reorg(self, event_loop): async",
"from pathlib import Path import pytest import pytest_asyncio from electrumsv_node",
"except asyncio.TimeoutError: logger.exception(f\"timed out after {MAX_WAIT_TIME} seconds\") raise class TestReorg:",
"the simulation Runs node1, electrumx1 and electrumsv1 and loads the",
"electrumsv1 and loads the default wallet on the daemon (so",
"\"password\": \"<PASSWORD>\" } REORGED_TXIDS = \"a1fa9460ca105c1396cd338f7fa202bf79a9d244d730e91e19f6302a05b2f07a\" # Load the default",
"import Path import pytest import pytest_asyncio from electrumsv_node import electrumsv_node",
"result.raise_for_status() # Submit node1 blocks to node if electrumsv_node.is_node_running(): utils.submit_blocks_from_file(node_id='node1',",
"the daemon (so that newly submitted blocks will be synchronized",
"blocks to node if electrumsv_node.is_node_running(): utils.submit_blocks_from_file(node_id='node1', filepath=Path(MODULE_DIR).joinpath('../reorg_blocks/node2_blocks.dat')) else: logger.exception(\"node unavailable\")",
"asyncio import os from pathlib import Path import pytest import",
"state before running the simulation Runs node1, electrumx1 and electrumsv1",
"async with TxStateWSClient() as ws_client: try: await asyncio.wait_for(ws_client.block_until_confirmed_and_height_updated( reorged_txids, reorg_height),",
"await asyncio.wait_for(ws_client.block_until_confirmed_and_height_updated( reorged_txids, reorg_height), MAX_WAIT_TIME) except asyncio.TimeoutError: logger.exception(f\"timed out after",
"# Load the default wallet on ElectrumSV daemon url =",
"get_coin_state; get_transaction_history # Submit node2 blocks to node if electrumsv_node.is_node_running():",
"node if electrumsv_node.is_node_running(): utils.submit_blocks_from_file(node_id='node1', filepath=Path(MODULE_DIR).joinpath('../reorg_blocks/node2_blocks.dat')) else: logger.exception(\"node unavailable\") await wait_for_reog_transaction_update([REORGED_TXIDS],",
"that newly submitted blocks will be synchronized by ElectrumSV reorged",
"before running the simulation Runs node1, electrumx1 and electrumsv1 and",
"node1, electrumx1 and electrumsv1 and loads the default wallet on",
"wait_for_reog_transaction_update(reorged_txids, reorg_height): MAX_WAIT_TIME = 10 # seconds async with TxStateWSClient()",
"node1 blocks to node if electrumsv_node.is_node_running(): utils.submit_blocks_from_file(node_id='node1', filepath=Path(MODULE_DIR).joinpath('../reorg_blocks/node1_blocks.dat')) else: logger.exception(\"node",
"payload = { \"password\": \"<PASSWORD>\" } REORGED_TXIDS = \"a1fa9460ca105c1396cd338f7fa202bf79a9d244d730e91e19f6302a05b2f07a\" #",
"@classmethod def teardown_class(cls): pass @pytest.mark.asyncio def test_reorg(self, event_loop): async def",
"filepath=Path(MODULE_DIR).joinpath('../reorg_blocks/node1_blocks.dat')) else: logger.exception(\"node unavailable\") try: await wait_for_reog_transaction_update([REORGED_TXIDS], 201) # Todo",
"logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(\"simulate-fresh-reorg\") async def wait_for_reog_transaction_update(reorged_txids, reorg_height): MAX_WAIT_TIME =",
"seconds async with TxStateWSClient() as ws_client: try: await asyncio.wait_for(ws_client.block_until_confirmed_and_height_updated( reorged_txids,",
"ElectrumSV daemon url = f\"http://127.0.0.1:9999/v1/regtest/dapp/wallets/worker1.sqlite/load_wallet\" result = requests.post(url, json=payload) result.raise_for_status()",
"and electrumsv1 and loads the default wallet on the daemon",
"import logging import requests from contrib.functional_tests.websocket_client import TxStateWSClient MODULE_DIR =",
"logger.exception(f\"timed out after {MAX_WAIT_TIME} seconds\") raise class TestReorg: @classmethod def",
"default wallet on the daemon (so that newly submitted blocks",
"pytest_asyncio from electrumsv_node import electrumsv_node from electrumsv_sdk import utils import",
"async def test_reorg(): payload = { \"password\": \"<PASSWORD>\" } REORGED_TXIDS",
"REORGED_TXIDS = \"a1fa9460ca105c1396cd338f7fa202bf79a9d244d730e91e19f6302a05b2f07a\" # Load the default wallet on ElectrumSV",
"# Todo check state of get_balance; get_coin_state; get_transaction_history # Submit",
"electrumsv_node from electrumsv_sdk import utils import logging import requests from",
"wait_for_reog_transaction_update([REORGED_TXIDS], 201) # Todo check state of get_balance; get_coin_state; get_transaction_history",
"this will reset all components back to a blank state",
"reorged_txids, reorg_height), MAX_WAIT_TIME) except asyncio.TimeoutError: logger.exception(f\"timed out after {MAX_WAIT_TIME} seconds\")",
"daemon url = f\"http://127.0.0.1:9999/v1/regtest/dapp/wallets/worker1.sqlite/load_wallet\" result = requests.post(url, json=payload) result.raise_for_status() #",
"changes...\") # Todo check state of get_balance; get_coin_state; get_transaction_history event_loop.run_until_complete(test_reorg())",
"MAX_WAIT_TIME) except asyncio.TimeoutError: logger.exception(f\"timed out after {MAX_WAIT_TIME} seconds\") raise class",
"unavailable\") try: await wait_for_reog_transaction_update([REORGED_TXIDS], 201) # Todo check state of",
"to node if electrumsv_node.is_node_running(): utils.submit_blocks_from_file(node_id='node1', filepath=Path(MODULE_DIR).joinpath('../reorg_blocks/node2_blocks.dat')) else: logger.exception(\"node unavailable\") await",
"in progress alongside refactoring changes...\") # Todo check state of",
"filepath=Path(MODULE_DIR).joinpath('../reorg_blocks/node2_blocks.dat')) else: logger.exception(\"node unavailable\") await wait_for_reog_transaction_update([REORGED_TXIDS], 202) except asyncio.TimeoutError: pytest.xfail(\"work",
"os.path.dirname(os.path.abspath(__file__)) logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(\"simulate-fresh-reorg\") async def wait_for_reog_transaction_update(reorged_txids, reorg_height): MAX_WAIT_TIME",
"on ElectrumSV daemon url = f\"http://127.0.0.1:9999/v1/regtest/dapp/wallets/worker1.sqlite/load_wallet\" result = requests.post(url, json=payload)",
"wallet on ElectrumSV daemon url = f\"http://127.0.0.1:9999/v1/regtest/dapp/wallets/worker1.sqlite/load_wallet\" result = requests.post(url,",
"raise class TestReorg: @classmethod def setup_class(cls): pass @classmethod def teardown_class(cls):",
"of get_balance; get_coin_state; get_transaction_history # Submit node2 blocks to node",
"Path import pytest import pytest_asyncio from electrumsv_node import electrumsv_node from",
"electrumsv_node.is_node_running(): utils.submit_blocks_from_file(node_id='node1', filepath=Path(MODULE_DIR).joinpath('../reorg_blocks/node2_blocks.dat')) else: logger.exception(\"node unavailable\") await wait_for_reog_transaction_update([REORGED_TXIDS], 202) except",
"with TxStateWSClient() as ws_client: try: await asyncio.wait_for(ws_client.block_until_confirmed_and_height_updated( reorged_txids, reorg_height), MAX_WAIT_TIME)",
"daemon (so that newly submitted blocks will be synchronized by",
"will reset all components back to a blank state before",
"(so that newly submitted blocks will be synchronized by ElectrumSV",
"running the simulation Runs node1, electrumx1 and electrumsv1 and loads",
"utils.submit_blocks_from_file(node_id='node1', filepath=Path(MODULE_DIR).joinpath('../reorg_blocks/node2_blocks.dat')) else: logger.exception(\"node unavailable\") await wait_for_reog_transaction_update([REORGED_TXIDS], 202) except asyncio.TimeoutError:",
"# Submit node2 blocks to node if electrumsv_node.is_node_running(): utils.submit_blocks_from_file(node_id='node1', filepath=Path(MODULE_DIR).joinpath('../reorg_blocks/node2_blocks.dat'))",
"if electrumsv_node.is_node_running(): utils.submit_blocks_from_file(node_id='node1', filepath=Path(MODULE_DIR).joinpath('../reorg_blocks/node2_blocks.dat')) else: logger.exception(\"node unavailable\") await wait_for_reog_transaction_update([REORGED_TXIDS], 202)",
"try: await asyncio.wait_for(ws_client.block_until_confirmed_and_height_updated( reorged_txids, reorg_height), MAX_WAIT_TIME) except asyncio.TimeoutError: logger.exception(f\"timed out",
"simulation Runs node1, electrumx1 and electrumsv1 and loads the default",
"ElectrumSV reorged txid: 'a1fa9460ca105c1396cd338f7fa202bf79a9d244d730e91e19f6302a05b2f07a' \"\"\" import asyncio import os from",
"pytest import pytest_asyncio from electrumsv_node import electrumsv_node from electrumsv_sdk import",
"# seconds async with TxStateWSClient() as ws_client: try: await asyncio.wait_for(ws_client.block_until_confirmed_and_height_updated(",
"TxStateWSClient() as ws_client: try: await asyncio.wait_for(ws_client.block_until_confirmed_and_height_updated( reorged_txids, reorg_height), MAX_WAIT_TIME) except",
"f\"http://127.0.0.1:9999/v1/regtest/dapp/wallets/worker1.sqlite/load_wallet\" result = requests.post(url, json=payload) result.raise_for_status() # Submit node1 blocks",
"else: logger.exception(\"node unavailable\") await wait_for_reog_transaction_update([REORGED_TXIDS], 202) except asyncio.TimeoutError: pytest.xfail(\"work in",
"progress alongside refactoring changes...\") # Todo check state of get_balance;",
"= { \"password\": \"<PASSWORD>\" } REORGED_TXIDS = \"a1fa9460ca105c1396cd338f7fa202bf79a9d244d730e91e19f6302a05b2f07a\" # Load",
"} REORGED_TXIDS = \"a1fa9460ca105c1396cd338f7fa202bf79a9d244d730e91e19f6302a05b2f07a\" # Load the default wallet on",
"@classmethod def setup_class(cls): pass @classmethod def teardown_class(cls): pass @pytest.mark.asyncio def",
"Runs node1, electrumx1 and electrumsv1 and loads the default wallet",
"import os from pathlib import Path import pytest import pytest_asyncio",
"electrumsv_node.is_node_running(): utils.submit_blocks_from_file(node_id='node1', filepath=Path(MODULE_DIR).joinpath('../reorg_blocks/node1_blocks.dat')) else: logger.exception(\"node unavailable\") try: await wait_for_reog_transaction_update([REORGED_TXIDS], 201)",
"Warning - this will reset all components back to a",
"async def wait_for_reog_transaction_update(reorged_txids, reorg_height): MAX_WAIT_TIME = 10 # seconds async",
"from electrumsv_node import electrumsv_node from electrumsv_sdk import utils import logging",
"logger.exception(\"node unavailable\") try: await wait_for_reog_transaction_update([REORGED_TXIDS], 201) # Todo check state",
"reorged txid: 'a1fa9460ca105c1396cd338f7fa202bf79a9d244d730e91e19f6302a05b2f07a' \"\"\" import asyncio import os from pathlib",
"txid: 'a1fa9460ca105c1396cd338f7fa202bf79a9d244d730e91e19f6302a05b2f07a' \"\"\" import asyncio import os from pathlib import",
"test_reorg(): payload = { \"password\": \"<PASSWORD>\" } REORGED_TXIDS = \"a1fa9460ca105c1396cd338f7fa202bf79a9d244d730e91e19f6302a05b2f07a\"",
"blocks will be synchronized by ElectrumSV reorged txid: 'a1fa9460ca105c1396cd338f7fa202bf79a9d244d730e91e19f6302a05b2f07a' \"\"\"",
"json=payload) result.raise_for_status() # Submit node1 blocks to node if electrumsv_node.is_node_running():",
"check state of get_balance; get_coin_state; get_transaction_history # Submit node2 blocks",
"from electrumsv_sdk import utils import logging import requests from contrib.functional_tests.websocket_client",
"teardown_class(cls): pass @pytest.mark.asyncio def test_reorg(self, event_loop): async def test_reorg(): payload",
"get_balance; get_coin_state; get_transaction_history # Submit node2 blocks to node if",
"import requests from contrib.functional_tests.websocket_client import TxStateWSClient MODULE_DIR = os.path.dirname(os.path.abspath(__file__)) logging.basicConfig(level=logging.DEBUG)",
"pass @pytest.mark.asyncio def test_reorg(self, event_loop): async def test_reorg(): payload =",
"def test_reorg(): payload = { \"password\": \"<PASSWORD>\" } REORGED_TXIDS =",
"synchronized by ElectrumSV reorged txid: 'a1fa9460ca105c1396cd338f7fa202bf79a9d244d730e91e19f6302a05b2f07a' \"\"\" import asyncio import",
"a blank state before running the simulation Runs node1, electrumx1",
"get_transaction_history # Submit node2 blocks to node if electrumsv_node.is_node_running(): utils.submit_blocks_from_file(node_id='node1',",
"\"a1fa9460ca105c1396cd338f7fa202bf79a9d244d730e91e19f6302a05b2f07a\" # Load the default wallet on ElectrumSV daemon url",
"refactoring changes...\") # Todo check state of get_balance; get_coin_state; get_transaction_history",
"node2 blocks to node if electrumsv_node.is_node_running(): utils.submit_blocks_from_file(node_id='node1', filepath=Path(MODULE_DIR).joinpath('../reorg_blocks/node2_blocks.dat')) else: logger.exception(\"node",
"202) except asyncio.TimeoutError: pytest.xfail(\"work in progress alongside refactoring changes...\") #",
"out after {MAX_WAIT_TIME} seconds\") raise class TestReorg: @classmethod def setup_class(cls):",
"requests from contrib.functional_tests.websocket_client import TxStateWSClient MODULE_DIR = os.path.dirname(os.path.abspath(__file__)) logging.basicConfig(level=logging.DEBUG) logger",
"TestReorg: @classmethod def setup_class(cls): pass @classmethod def teardown_class(cls): pass @pytest.mark.asyncio",
"await wait_for_reog_transaction_update([REORGED_TXIDS], 202) except asyncio.TimeoutError: pytest.xfail(\"work in progress alongside refactoring",
"= requests.post(url, json=payload) result.raise_for_status() # Submit node1 blocks to node"
] |
[
"occurs. :param verbose: print messages on collision :return: `True` if",
"def _create_task(self, task_args: dict) -> Task: if task_args.get(\"sparse_rew_fcn\", False): #",
"Technical University of Darmstadt. # All rights reserved. # #",
"init_state_up[: self._num_dof] += np.pi / 180 * np.array([0.1, 1, 0.5,",
"is a reference # state_des_ball = self.sim.data.get_site_xpos(\"cup_goal\") # this is",
"init_qpos_des_7dof, act_space_bic_4dof, act_space_bic_7dof, wam_q_limits_up_7dof, wam_q_limits_lo_7dof, torque_space_wam_4dof, torque_space_wam_7dof, wam_pgains_7dof, wam_dgains_7dof, wam_pgains_4dof,",
"the rope [m] ball_mass=0.024, # mass of the ball [kg]",
"rope segment relative to the cup bottom plate else: self.init_qpos[:7]",
"self.spec.obs_space, self.spec.act_space, self.spec.state_space.subspace(self.spec.state_space.create_mask(idcs)), ) # init cup goal position state_des",
"= np.array([0.82521, 0, 1.4469]) if self._num_dof == 7 else np.array([0.758,",
"are not reached (5 deg safety margin) state_lo[: self._num_dof] =",
"is relative to self._qpos_des_init qvel_des = np.zeros_like(qpos_des) if self._num_dof ==",
"+ get_body_xpos() results in wrong output for state_des, as sim",
"# damping of rope joints [N/s] (reasonable values are 6e-4",
"of the body to track elevation=-30, # camera rotation around",
"marking the goal position for the ball. It is not",
"a task with binary reward return self._create_main_task(task_args) else: # Create",
"else: # Add plus/minus one degree to each motor joint",
"position obs_lo, obs_up, labels = [0.0], [1.0], [\"t\"] if self.observe_ball:",
"in binary form must reproduce the above copyright # notice,",
"self._collision_geom_ids = [self.model._geom_name2id[name] for name in [\"cup_geom1\", \"cup_geom2\"]] self.stop_on_collision =",
"out of bounds (this is normally checked by the task,",
"and body-name of both contact geoms body1 = self.model.geom_bodyid[contact.geom1] body1_name",
"goal_pos_init_sim_7dof if self._num_dof == 7 else goal_pos_init_sim_4dof rew_fcn = QuadrErrRewFcn(",
"the internal # PD controller to stabilize at self._qpos_des_init. #",
"the 2-dim (x-z plane) cartesian ball position into the observation",
"= self.sim.data.contact[i] # Extract body-id and body-name of both contact",
"first rope segment joint init_state_up = self._init_state.copy() init_state_up[: self._num_dof] +=",
"`dt`. :param max_steps: max number of simulation time steps :param",
"state_shape = np.concatenate([self.init_qpos, self.init_qvel, np.empty(3), np.empty(3)]).shape state_lo, state_up = np.full(state_shape,",
"init cup position R=task_args.get( \"R_dev\", np.zeros((self.act_space.shape[0], self.act_space.shape[0])) ), # joint",
"of bounds (this is normally checked by the task, but",
"from pyrado.tasks.base import Task from pyrado.tasks.condition_only import ConditionOnlyTask from pyrado.tasks.desired_state",
"from pyrado.environments.mujoco.base import MujocoSimEnv from pyrado.spaces.base import Space from pyrado.spaces.box",
"joint_5_dryfriction=0.4, # dry friction coefficient of motor joint 5 [-]",
"xml_model.replace(\"[size_capsule_geom]\", str(rope_length / 72)) # Resolve mesh directory and replace",
") c2 = body2_name == \"ball\" and ( body1_name in",
"from center) xml_model = xml_model.replace(\"[pos_capsule_joint]\", str(-rope_length / 60)) # Pure",
"# Apply the torques to the robot self.sim.data.qfrc_applied[: self._num_dof] =",
"best state in the rollout return BestStateFinalRewTask( MaskedTask(self.spec, task, idcs),",
"margin) state_lo[: self._num_dof] = wam_q_limits_lo_7dof[: self._num_dof] state_up[: self._num_dof] = wam_q_limits_up_7dof[:",
"of motor joint 5 [-] joint_6_dryfriction=0.4, # dry friction coefficient",
"- self.state[self.model.nq : self.model.nq + self._num_dof] # Compute the torques",
"None) if cup_scale is not None: # See [1, l.93-96]",
"pyrado.spaces.singular import SingularStateSpace from pyrado.tasks.base import Task from pyrado.tasks.condition_only import",
"num_dof(self) -> int: \"\"\" Get the number of degrees of",
"self._init_space = SingularStateSpace(self._init_state) else: # Add plus/minus one degree to",
"= wam_dgains_7dof init_ball_pos = np.array([0.828, 0.0, 1.131]) init_cup_goal = goal_pos_init_sim_7dof",
"1.168]) init_cup_goal = goal_pos_init_sim_4dof elif num_dof == 7: graph_file_name =",
"(default value is small) joint_7_damping=0.05, # damping of motor joints",
"'cup' if self.observe_ball: obs.extend([state[-3], state[-1]]) if self.observe_cup: obs.extend([state[-6], state[-4]]) return",
"in y-direction R=task_args.get(\"R\", R_default), # last joint is really unreliable",
"simulation frames for which the same action is held, results",
"= goal_pos_init_sim_4dof elif num_dof == 7: graph_file_name = \"wam_7dof_bic.xml\" self.qpos_des_init",
"task_args) # Actual initial joint position (when the WAM moved",
"in reset() if task_args.get(\"sparse_rew_fcn\", False): factor = task_args.get(\"success_bonus\", 1) #",
"Pure visualization component xml_model = xml_model.replace(\"[size_capsule_geom]\", str(rope_length / 72)) #",
"derived from this software without # specific prior written permission.",
"bool = True, observe_ball: bool = False, observe_cup: bool =",
"replace the remaining domain parameters return super()._adapt_model_file(xml_model, domain_param) def _mujoco_step(self,",
"c1 or c2: if verbose: print_cbt(f\"The ball is in the",
"INSTITUTE EUROPE GMBH, # OR TECHNICAL UNIVERSITY OF DARMSTADT BE",
"directory and replace the remaining domain parameters return super()._adapt_model_file(xml_model, domain_param)",
"# state_des = np.concatenate([state_des_ball, state_des_cup]) R_default = np.diag([0, 0, 1,",
"= [self.model._geom_name2id[name] for name in [\"cup_geom1\", \"cup_geom2\"]] self.stop_on_collision = stop_on_collision",
"# center of frame # print_cbt(f'cup xipos: {self.sim.data.get_body_xipos(\"cup\").copy()}', 'b') #",
"and binary forms, with or without # modification, are permitted",
"1e-2, 1e-1]) if self._num_dof == 7 else np.diag([0, 0, 1e-2,",
"factor=factor, ) # Augment the binary task with an endless",
"plate # Set the actual stable initial position. This position",
"the torques to the robot self.sim.data.qfrc_applied[: self._num_dof] = torque #",
"POSSIBILITY OF SUCH DAMAGE. import mujoco_py import numpy as np",
"`True` if the ball is in the cup \"\"\" for",
"self.spec.act_space, self.spec.state_space.subspace(self.spec.state_space.create_mask(idcs)), ) # init cup goal position state_des =",
"\"\"\" Check if the ball is in the cup. :param",
"wam_pgains_4dof, wam_dgains_4dof, ) from pyrado.environments.mujoco.base import MujocoSimEnv from pyrado.spaces.base import",
"= xml_model.replace(\"[pos_mesh]\", str(0.055 - (cup_scale - 1.0) * 0.023)) xml_model",
"NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;",
"bottom plate else: self.init_qpos[:7] = np.array([0.0, 0.65, 0.0, 1.41, 0.0,",
"0, 1, 1e-2, 1e-2, 1e-1]) if self._num_dof == 7 else",
"body2_name in self._collision_bodies or contact.geom2 in self._collision_geom_ids ) c2 =",
"written permission. # # THIS SOFTWARE IS PROVIDED BY THE",
"graph_file_name = \"wam_4dof_bic.xml\" self.qpos_des_init = init_qpos_des_4dof self.p_gains = wam_pgains_4dof self.d_gains",
"<NAME>, Honda Research Institute Europe GmbH, # or Technical University",
"if c1 or c2: if verbose: print_cbt(f\"The ball is in",
"Main task: Desired state task for the cartesian ball distance",
"notice, this list of conditions and the following disclaimer. #",
"WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF",
"same action is held, results in a multiplier of the",
"str(rope_length / 72)) # Resolve mesh directory and replace the",
"internal # PD controller to stabilize at self._qpos_des_init. # The",
"removed in future... # if self._curr_step == 0: # print_cbt(f'cup",
"OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF",
"position of the ball in cartesian coordinates self._init_state = np.concatenate([self.init_qpos,",
"init_state_up = self._init_state.copy() init_state_up[: self._num_dof] += np.pi / 180 *",
"`True` if the ball collides with something else than the",
"default the time step size is the one from the",
"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS",
"Task from pyrado.tasks.condition_only import ConditionOnlyTask from pyrado.tasks.desired_state import DesStateTask from",
"private attribute since a method like 'model.geom_names[geom_id]' cannot be used",
"if the ball collides with something else than the desired",
"task_args: dict) -> Task: # Create a DesStateTask that masks",
"np.diag([2e1, 1e-4, 2e1])), # distance ball - cup; shouldn't move",
"@property def num_dof(self) -> int: \"\"\" Get the number of",
"= goal_pos_init_sim_7dof else: raise pyrado.ValueErr(given=num_dof, eq_constraint=\"4 or 7\") model_path =",
"\"\"\" Serializable._init(self, locals()) self.fixed_init_state = fixed_init_state self.observe_ball = observe_ball self.observe_cup",
"def observe(self, state: np.ndarray) -> np.ndarray: # TODO: Debug print-outs,",
"if self.fixed_init_state: self._init_space = SingularStateSpace(self._init_state) else: # Add plus/minus one",
"np.add.at(qvel_des, [1, 3], act[2:]) elif self._num_dof == 7: np.add.at(qpos_des, [1,",
"os.path as osp from init_args_serializer import Serializable from typing import",
"small) joint_4_damping=0.05, # damping of motor joints [N/s] (default value",
"[self._curr_step / self.max_steps] # Extract the (x, z) cartesian position",
"velocity errors err_pos = qpos_des - self.state[: self._num_dof] err_vel =",
"return dict( qpos_des=qpos_des, qvel_des=qvel_des, qpos=qpos[: self._num_dof], qvel=qvel[: self._num_dof], ball_pos=ball_pos, cup_pos=cup_goal,",
"of the ball [kg] joint_1_damping=0.05, # damping of motor joints",
"joint 4 [-] joint_5_dryfriction=0.4, # dry friction coefficient of motor",
"from pyrado.spaces.box import BoxSpace from pyrado.spaces.singular import SingularStateSpace from pyrado.tasks.base",
"list(range(self.state_space.flat_dim - 3, self.state_space.flat_dim)) # Cartesian cup goal position spec",
"as sim has not been updated to # init_space.sample(), which",
"DAMAGE. import mujoco_py import numpy as np import os.path as",
"def get_nominal_domain_param(cls, num_dof: int = 7) -> dict: if num_dof",
"is catched [inactive by default] return ParallelTasks( [ self._create_main_task(task_args), self._create_deviation_task(task_args),",
"task_args.get(\"success_bonus\", 1) # Binary final reward task main_task = FinalRewTask(",
".. seealso:: [1] https://github.com/psclklnk/self-paced-rl/tree/master/sprl/envs/ball_in_a_cup.py \"\"\" name: str = \"wam-bic\" def",
"* err_pos + self.d_gains * err_vel torque = self.torque_space.project_to(torque) #",
"task, but does not work because of the mask) state_oob",
"joint limits of the arm are not reached (5 deg",
"number of degrees of freedom (4 or 7), depending on",
"self.spec.obs_space, self.spec.act_space, self.spec.state_space.subspace(self.spec.state_space.create_mask(idcs)), ) # If we do not use",
"motor joint and the first rope segment joint init_state_up =",
"the observation :param task_args: arguments for the task construction \"\"\"",
"rope segment joint init_state_up = self._init_state.copy() init_state_up[: self._num_dof] += np.pi",
"it. # Instead, we want the episode to end with",
"with a specific `dt`. :param max_steps: max number of simulation",
"robot ball_collided = self.check_ball_collisions() if self.stop_on_collision else False # If",
"rew_fcn) return MaskedTask(self.spec, task, idcs) def _adapt_model_file(self, xml_model: str, domain_param:",
"for the PD controller and clip them to their max",
"[0.0], [1.0], [\"t\"] if self.observe_ball: obs_lo.extend([-3.0, -3.0]) obs_up.extend([3.0, 3.0]) labels.extend([\"ball_x\",",
"a binary bonus when ball is catched [inactive by default]",
"self._init_state.copy() init_state_lo[: self._num_dof] -= np.pi / 180 * np.array([0.1, 1,",
"body to track elevation=-30, # camera rotation around the axis",
"if self._num_dof == 7 else goal_pos_init_sim_4dof rew_fcn = QuadrErrRewFcn( Q=task_args.get(\"Q_dev\",",
"is small) joint_2_damping=0.05, # damping of motor joints [N/s] (default",
"first rope segment relative to the cup bottom plate else:",
"reached (5 deg safety margin) state_lo[: self._num_dof] = wam_q_limits_lo_7dof[: self._num_dof]",
"(cup_scale - 1.0) * 0.0385)) xml_model = xml_model.replace(\"[size_cup]\", str(cup_scale *",
"the distribution. # 3. Neither the name of <NAME>, Honda",
"# or Technical University of Darmstadt, nor the names of",
"# The initial position of the ball in cartesian coordinates",
"the following disclaimer in the # documentation and/or other materials",
"https://github.com/psclklnk/self-paced-rl/tree/master/sprl/envs/ball_in_a_cup.py \"\"\" name: str = \"wam-bic\" def __init__( self, num_dof:",
"dry friction coefficient of motor joint 1 [-] joint_2_dryfriction=0.4, #",
"# Get the desired positions and velocities for the selected",
"c1 = body1_name == \"ball\" and ( body2_name in self._collision_bodies",
"using the `reset()` function, always pass a meaningful `init_state` ..",
"future... # if self._curr_step == 0: # print_cbt(f'cup xpos: {self.sim.data.get_body_xpos(\"cup\").copy()}',",
"retain the above copyright # notice, this list of conditions",
"task_args: Optional[dict] = None, ): \"\"\" Constructor :param num_dof: number",
"np import os.path as osp from init_args_serializer import Serializable from",
"by a PD controller. .. note:: When using the `reset()`",
"EVENT SHALL <NAME>, HONDA RESEARCH INSTITUTE EUROPE GMBH, # OR",
"TODO: Debug print-outs, should be removed in future... # if",
"# Extract body-id and body-name of both contact geoms body1",
"= body1_name == \"ball\" and ( body2_name in self._collision_bodies or",
"initial state :param stop_on_collision: set the `failed` flag in the",
"binary form must reproduce the above copyright # notice, this",
"# Actual initial joint position (when the WAM moved to",
"cannot be used because # not every geom has a",
"int, frame_skip: int = 4, dt: Optional[float] = None, max_steps:",
"(default value is small) joint_3_damping=0.05, # damping of motor joints",
"self.d_gains = wam_dgains_4dof init_ball_pos = np.array([0.723, 0.0, 1.168]) init_cup_goal =",
"cup goal position spec = EnvSpec( self.spec.obs_space, self.spec.act_space, self.spec.state_space.subspace(self.spec.state_space.create_mask(idcs)), )",
"body-id and body-name of both contact geoms body1 = self.model.geom_bodyid[contact.geom1]",
"normalized time and optionally the cup and ball position obs_lo,",
"damping of motor joints [N/s] (default value is small) joint_1_dryfriction=0.4,",
"Task: idcs = list(range(self.state_space.flat_dim - 3, self.state_space.flat_dim)) # Cartesian cup",
"be >0.65) rope_length=0.41, # length of the rope [m] ball_mass=0.024,",
"pyrado.ValueErr(given=num_dof, eq_constraint=\"4 or 7\") model_path = osp.join(pyrado.MUJOCO_ASSETS_DIR, graph_file_name) super().__init__(model_path, frame_skip,",
"dry friction coefficient of motor joint 4 [-] joint_5_dryfriction=0.4, #",
"MaskedTask(self.spec, task, idcs) else: state_des = self.sim.data.get_site_xpos(\"cup_goal\") # this is",
"OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE",
"in self._collision_geom_ids ) c2 = body2_name == \"ball\" and (",
"max values torque = self.p_gains * err_pos + self.d_gains *",
"motor joint 2 [-] joint_3_dryfriction=0.4, # dry friction coefficient of",
"def act_space(self) -> Space: # Running a PD controller on",
"np.array([0.1, 1, 0.5, 1.0, 0.1, 1.0, 1.0])[: self._num_dof] self._init_space =",
"joint_6_damping=0.05, # damping of motor joints [N/s] (default value is",
"rotation around the camera's vertical axis ) @property def num_dof(self)",
"def __init__( self, num_dof: int, frame_skip: int = 4, dt:",
"IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED #",
"above copyright # notice, this list of conditions and the",
"coefficient of motor joint 2 [-] joint_3_dryfriction=0.4, # dry friction",
"size `dt` :param dt: by default the time step size",
"is normally checked by the task, but does not work",
"when ball is catched [inactive by default] return ParallelTasks( [",
"FinalRewMode from pyrado.tasks.goalless import GoallessTask from pyrado.tasks.masked import MaskedTask from",
"from pyrado.tasks.reward_functions import ZeroPerStepRewFcn, ExpQuadrErrRewFcn, QuadrErrRewFcn from pyrado.tasks.sequential import SequentialTasks",
"# this is a reference # state_des_cup = np.array([0.82521, 0,",
"rope_length=0.41, # length of the rope [m] ball_mass=0.024, # mass",
"# Cartesian cup goal position spec = EnvSpec( self.spec.obs_space, self.spec.act_space,",
"return False def check_ball_in_cup(self, *args, verbose: bool = False): \"\"\"",
"for i in range(self.sim.data.ncon): # Get current contact object contact",
"self.observe_cup = observe_cup # Initialize num DoF specific variables self._num_dof",
"with something else than the desired parts of the cup.",
"value is small) joint_7_damping=0.05, # damping of motor joints [N/s]",
"domain_param: dict) -> str: # First replace special domain parameters",
"of the time step size `dt` :param dt: by default",
"cartesian coordinates self._init_state = np.concatenate([self.init_qpos, self.init_qvel, init_ball_pos, init_cup_goal]) if self.fixed_init_state:",
"(c) 2020, <NAME>, Honda Research Institute Europe GmbH, and #",
"/ 30)) # Each joint is at the top of",
"OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR",
"pyrado.tasks.base import Task from pyrado.tasks.condition_only import ConditionOnlyTask from pyrado.tasks.desired_state import",
"PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND",
"for the radius of the cup [-] (should be >0.65)",
"with something else than the central parts of the cup",
"wam_dgains_4dof init_ball_pos = np.array([0.723, 0.0, 1.168]) init_cup_goal = goal_pos_init_sim_4dof elif",
"Institute Europe GmbH, and # Technical University of Darmstadt. #",
"0.1, 1.0, 1.0])[: self._num_dof] self._init_space = BoxSpace(init_state_lo, init_state_up) # Bodies",
"= -0.34 # angle of the first rope segment relative",
"# 1. Redistributions of source code must retain the above",
"init_cup_goal]) if self.fixed_init_state: self._init_space = SingularStateSpace(self._init_state) else: # Add plus/minus",
"cup_goal is the mujoco site object marking the goal position",
"and contact.geom1 == cup_inner_id if c1 or c2: if verbose:",
"pose, interferes with R_default from _create_main_task ) task = DesStateTask(spec,",
"`init_state` .. seealso:: [1] https://github.com/psclklnk/self-paced-rl/tree/master/sprl/envs/ball_in_a_cup.py \"\"\" name: str = \"wam-bic\"",
"collision with the ball occurs. :param verbose: print messages on",
"the cup :return: `True` if the ball is in the",
"coefficient of motor joint 3 [-] joint_4_dryfriction=0.4, # dry friction",
"ANY THEORY OF LIABILITY, WHETHER # IN CONTRACT, STRICT LIABILITY,",
"the cup at time step {self.curr_step}.\", \"y\") return True return",
"small) joint_6_damping=0.05, # damping of motor joints [N/s] (default value",
"object 'cup' if self.observe_ball: obs.extend([state[-3], state[-1]]) if self.observe_cup: obs.extend([state[-6], state[-4]])",
"the # documentation and/or other materials provided with the distribution.",
"xml_model = xml_model.replace(\"[pos_capsule_joint]\", str(-rope_length / 60)) # Pure visualization component",
"from init pose, interferes with R_default from _create_main_task ) task",
"time step size `dt` :param dt: by default the time",
"return dict( cup_scale=1.0, # scaling factor for the radius of",
"elif num_dof == 4: return dict( cup_scale=1.0, # scaling factor",
"self._num_dof == 4: np.add.at(qpos_des, [1, 3], act[:2]) np.add.at(qvel_des, [1, 3],",
"# Compute the torques for the PD controller and clip",
"# to the coordinate system origin of the rigid body",
"Research Institute Europe GmbH, # or Technical University of Darmstadt,",
"from the mujoco config file multiplied by the number of",
"2.) Deviation task: Desired state task for the cartesian- and",
"binary task with an endless dummy task, to avoid early",
"cup [-] (should be >0.65) rope_length=0.41, # length of the",
"frame_skip: number of simulation frames for which the same action",
"current contact object contact = self.sim.data.contact[i] # Extract body-id and",
"task = SequentialTasks((main_task, dont_fail_after_succ_task)) return MaskedTask(self.spec, task, idcs) else: state_des",
"observation :param task_args: arguments for the task construction \"\"\" Serializable._init(self,",
"\"wam/upper_arm_link\", \"wam/forearm_link\", \"wrist_palm_link\", \"wam/wrist_pitch_link\", \"wam/wrist_yaw_link\", ] if self._num_dof == 4:",
"in self._collision_geom_ids ) if c1 or c2: if verbose: print_cbt(",
"case of a negative step reward and no final cost",
"# 1.) Main task: Desired state task for the cartesian",
"OR TECHNICAL UNIVERSITY OF DARMSTADT BE LIABLE FOR ANY DIRECT,",
"for state_des, as sim has not been updated to #",
"friction coefficient of motor joint 1 [-] joint_2_dryfriction=0.4, # dry",
"the desired trajectory is relative to self._qpos_des_init qvel_des = np.zeros_like(qpos_des)",
"joint_4_damping=0.05, # damping of motor joints [N/s] (default value is",
"x-z plane). # Note: the cup_goal is the mujoco site",
"l.93-96] xml_model = xml_model.replace(\"[scale_mesh]\", str(cup_scale * 0.001)) xml_model = xml_model.replace(\"[pos_mesh]\",",
":param frame_skip: number of simulation frames for which the same",
"0.0, 1.41, 0.0, -0.28, -1.57]) self.init_qpos[7] = -0.21 # angle",
"bool = False, task_args: Optional[dict] = None, ): \"\"\" Constructor",
"in mind that in case of a negative step reward",
"is in the cup. :param verbose: print messages when ball",
"using the internal # PD controller to stabilize at self._qpos_des_init.",
"# Copyright (c) 2020, <NAME>, Honda Research Institute Europe GmbH,",
"in the rollout return BestStateFinalRewTask( MaskedTask(self.spec, task, idcs), factor=task_args.get(\"final_factor\", 0.05",
"if self.observe_ball: obs_lo.extend([-3.0, -3.0]) obs_up.extend([3.0, 3.0]) labels.extend([\"ball_x\", \"ball_z\"]) if self.observe_cup:",
"num_dof: int, frame_skip: int = 4, dt: Optional[float] = None,",
"dict( sparse_rew_fcn=True, success_bonus=task_args.get(\"success_bonus\", 0), ) ), ] ) def _create_main_task(self,",
"range(self.sim.data.ncon): # Get current contact object contact = self.sim.data.contact[i] #",
"following conditions are met: # 1. Redistributions of source code",
"dt, max_steps, task_args) # Actual initial joint position (when the",
"self._num_dof] = wam_q_limits_lo_7dof[: self._num_dof] state_up[: self._num_dof] = wam_q_limits_up_7dof[: self._num_dof] return",
"if num_dof == 7: return dict( cup_scale=1.0, # scaling factor",
"not every geom has a name self._collision_geom_ids = [self.model._geom_name2id[name] for",
"= False): \"\"\" Check if the ball is in the",
"7: np.add.at(qpos_des, [1, 3, 5], act[:3]) np.add.at(qvel_des, [1, 3, 5],",
"skips (legacy from OpenAI environments). By passing an explicit `dt`",
"bottom plate # Set the actual stable initial position. This",
"by default] return ParallelTasks( [ self._create_main_task(task_args), self._create_deviation_task(task_args), self._create_main_task( dict( sparse_rew_fcn=True,",
"\"\"\" for i in range(self.sim.data.ncon): # Get current contact object",
"undesired collision with the ball occurs. :param verbose: print messages",
"checked by the task, but does not work because of",
"(therefore negative direction from center) xml_model = xml_model.replace(\"[pos_capsule_joint]\", str(-rope_length /",
"= [self._curr_step / self.max_steps] # Extract the (x, z) cartesian",
"of freedom (4 or 7), depending on which Barrett WAM",
"= np.diag([0, 0, 1, 1e-2, 1e-2, 1e-1]) if self._num_dof ==",
"by `_mujoco_step()` to true, if the ball collides with something",
"= np.concatenate([self.init_qpos, self.init_qvel, np.empty(3), np.empty(3)]).shape state_lo, state_up = np.full(state_shape, -pyrado.inf),",
"ball_collided = self.check_ball_collisions() if self.stop_on_collision else False # If state",
"== 7 else act_space_bic_4dof @classmethod def get_nominal_domain_param(cls, num_dof: int =",
"/ 180 * np.array([0.1, 1, 0.5, 1.0, 0.1, 1.0, 1.0])[:",
"False def observe(self, state: np.ndarray) -> np.ndarray: # TODO: Debug",
"position. This position would be reached after some time using",
"# Create two (or three) parallel running task. # 1.)",
"), mode=FinalRewMode(always_positive=True), factor=factor, ) # Yield -1 on fail after",
"the mask) state_oob = False if self.state_space.contains(self.state) else True return",
"object marking the goal position for the ball. It is",
"spec = EnvSpec( self.spec.obs_space, self.spec.act_space, self.spec.state_space.subspace(self.spec.state_space.create_mask(idcs)), ) # If we",
"\"\"\" return self._num_dof @property def torque_space(self) -> Space: \"\"\" Get",
"time using the internal # PD controller to stabilize at",
"7: graph_file_name = \"wam_7dof_bic.xml\" self.qpos_des_init = init_qpos_des_7dof self.p_gains = wam_pgains_7dof",
"-> str: # First replace special domain parameters cup_scale =",
"with an endless dummy task, to avoid early stopping task",
"FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT",
"called in reset() if task_args.get(\"sparse_rew_fcn\", False): factor = task_args.get(\"success_bonus\", 1)",
"BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR",
"task: Desired state task for the cartesian ball distance #",
"the name of <NAME>, Honda Research Institute Europe GmbH, #",
"EnvSpec( self.spec.obs_space, self.spec.act_space, self.spec.state_space.subspace(self.spec.state_space.create_mask(idcs)), ) # If we do not",
"False): factor = task_args.get(\"success_bonus\", 1) # Binary final reward task",
"mesh directory and replace the remaining domain parameters return super()._adapt_model_file(xml_model,",
"# the desired trajectory is relative to self._qpos_des_init qvel_des =",
"init position # 3.) Binary Bonus: Adds a binary bonus",
"cup (geom_ids) c1 = body1_name == \"ball\" and ( body2_name",
"print-outs, should be removed in future... # if self._curr_step ==",
"coefficient of motor joint 7 [-] rope_damping=1e-4, # damping of",
"np.add.at(qpos_des, [1, 3, 5], act[:3]) np.add.at(qvel_des, [1, 3, 5], act[3:])",
"@property def obs_space(self) -> Space: # Observing the normalized time",
"4, dt: Optional[float] = None, max_steps: int = pyrado.inf, fixed_init_state:",
"rope consists of 30 capsules xml_model = xml_model.replace(\"[pos_capsule]\", str(rope_length /",
"\"\"\" Constructor :param num_dof: number of degrees of freedom (4",
"# Initialize num DoF specific variables self._num_dof = num_dof if",
"Wrap the masked DesStateTask to add a bonus for the",
"else: raise pyrado.ValueErr(given=num_dof, eq_constraint=\"4 or 7\") def _create_task(self, task_args: dict)",
"pyrado.tasks.reward_functions import ZeroPerStepRewFcn, ExpQuadrErrRewFcn, QuadrErrRewFcn from pyrado.tasks.sequential import SequentialTasks from",
"-1.57]) self.init_qpos[7] = -0.21 # angle of the first rope",
"fixed_init_state: bool = True, stop_on_collision: bool = True, observe_ball: bool",
"Cartesian cup goal position spec = EnvSpec( self.spec.obs_space, self.spec.act_space, self.spec.state_space.subspace(self.spec.state_space.create_mask(idcs)),",
"a failure. mjsim_crashed = True qpos, qvel = self.sim.data.qpos.copy(), self.sim.data.qvel.copy()",
"the normalized time obs = [self._curr_step / self.max_steps] # Extract",
">0.65) rope_length=0.41, # length of the rope [m] ball_mass=0.024, #",
"Bonus: Adds a binary bonus when ball is catched [inactive",
"joints qpos_des = self.qpos_des_init.copy() # the desired trajectory is relative",
"self.model.geom_bodyid[contact.geom1] body1_name = self.model.body_names[body1] body2 = self.model.geom_bodyid[contact.geom2] body2_name = self.model.body_names[body2]",
"import MaskedTask from pyrado.tasks.parallel import ParallelTasks from pyrado.tasks.reward_functions import ZeroPerStepRewFcn,",
"small) joint_7_damping=0.05, # damping of motor joints [N/s] (default value",
"= self.sim.data.get_site_xpos(\"cup_goal\").copy() self.state = np.concatenate([qpos, qvel, ball_pos, cup_goal]) # If",
"and velocities return act_space_bic_7dof if self._num_dof == 7 else act_space_bic_4dof",
"GmbH, and # Technical University of Darmstadt. # All rights",
"NO EVENT SHALL <NAME>, HONDA RESEARCH INSTITUTE EUROPE GMBH, #",
"\"AS IS\" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,",
"coefficient of motor joint 4 [-] joint_5_dryfriction=0.4, # dry friction",
"0.63, 0.0, 1.27]) self.init_qpos[4] = -0.34 # angle of the",
"Barrett WAM setup being used :param frame_skip: number of simulation",
"copyright # notice, this list of conditions and the following",
"ZeroPerStepRewFcn()), mode=FinalRewMode(always_negative=True), factor=factor, ) # Augment the binary task with",
"and cup (geom_ids) cup_inner_id = self.model._geom_name2id[\"cup_inner\"] c1 = body1_name ==",
"is held, results in a multiplier of the time step",
"stabilize at self._qpos_des_init. # The initial position of the ball",
"domain_param.pop(\"rope_length\", None) if cup_scale is not None: # See [1,",
"specific prior written permission. # # THIS SOFTWARE IS PROVIDED",
"c2: if verbose: print_cbt( f\"Undesired collision of {body1_name} and {body2_name}",
"rope segment relative to the cup bottom plate # Set",
"[-] joint_7_dryfriction=0.4, # dry friction coefficient of motor joint 7",
"# Set the actual stable initial position. This position would",
"Get the space of joint torques. \"\"\" return torque_space_wam_7dof if",
"== 7: np.add.at(qpos_des, [1, 3, 5], act[:3]) np.add.at(qvel_des, [1, 3,",
"Observing the normalized time and optionally the cup and ball",
"0.0, 1.131]) init_cup_goal = goal_pos_init_sim_7dof else: raise pyrado.ValueErr(given=num_dof, eq_constraint=\"4 or",
"bool = True, stop_on_collision: bool = True, observe_ball: bool =",
"= SequentialTasks((main_task, dont_fail_after_succ_task)) return MaskedTask(self.spec, task, idcs) else: state_des =",
"return True return False def observe(self, state: np.ndarray) -> np.ndarray:",
"the desired positions and velocities for the selected joints qpos_des",
"joint 1 [-] joint_2_dryfriction=0.4, # dry friction coefficient of motor",
"in future... # if self._curr_step == 0: # print_cbt(f'cup xpos:",
"1.27]) self.init_qpos[4] = -0.34 # angle of the first rope",
"= self.model.body_names[body1] body2 = self.model.geom_bodyid[contact.geom2] body2_name = self.model.body_names[body2] # Evaluate",
"self._num_dof] return BoxSpace(state_lo, state_up) @property def obs_space(self) -> Space: #",
"TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF",
"the names of its contributors may # be used to",
"= [0.0], [1.0], [\"t\"] if self.observe_ball: obs_lo.extend([-3.0, -3.0]) obs_up.extend([3.0, 3.0])",
"the ball-in-the-cup task, controlled by a PD controller. .. note::",
"in the cup. :param verbose: print messages when ball is",
"self.init_qvel, init_ball_pos, init_cup_goal]) if self.fixed_init_state: self._init_space = SingularStateSpace(self._init_state) else: #",
"False # If state is out of bounds (this is",
"in a multiplier of the time step size `dt` :param",
"5 [-] joint_6_dryfriction=0.4, # dry friction coefficient of motor joint",
"wam_q_limits_up_7dof[: self._num_dof] return BoxSpace(state_lo, state_up) @property def obs_space(self) -> Space:",
"the top of each capsule (therefore negative direction from center)",
":param stop_on_collision: set the `failed` flag in the `dict` returned",
"both contact geoms body1 = self.model.geom_bodyid[contact.geom1] body1_name = self.model.body_names[body1] body2",
"np.ndarray) -> dict: assert self.act_space.contains(act, verbose=True) # Get the desired",
"we do not use copy(), state_des coming from MuJoCo is",
"Copyright (c) 2020, <NAME>, Honda Research Institute Europe GmbH, and",
"# Resolve mesh directory and replace the remaining domain parameters",
"num DoF specific variables self._num_dof = num_dof if num_dof ==",
"ExpQuadrErrRewFcn( Q=task_args.get(\"Q\", np.diag([2e1, 1e-4, 2e1])), # distance ball - cup;",
"body2_name == \"ball\" and contact.geom1 == cup_inner_id if c1 or",
"state_oob, ) def check_ball_collisions(self, verbose: bool = False) -> bool:",
"# Observing the normalized time and optionally the cup and",
"are 6e-4 to 1e-6) ) else: raise pyrado.ValueErr(given=num_dof, eq_constraint=\"4 or",
") from pyrado.environments.mujoco.base import MujocoSimEnv from pyrado.spaces.base import Space from",
"== 7 else np.array([0.758, 0, 1.5]) # state_des = np.concatenate([state_des_ball,",
"pass a meaningful `init_state` .. seealso:: [1] https://github.com/psclklnk/self-paced-rl/tree/master/sprl/envs/ball_in_a_cup.py \"\"\" name:",
"vertical axis ) @property def num_dof(self) -> int: \"\"\" Get",
"dry friction coefficient of motor joint 2 [-] joint_3_dryfriction=0.4, #",
"= False, task_args: Optional[dict] = None, ): \"\"\" Constructor :param",
"explicit `dt` value, this can be overwritten. Possible use case",
"By passing an explicit `dt` value, this can be overwritten.",
"task = DesStateTask(spec, state_des, rew_fcn) # Wrap the masked DesStateTask",
"is in the cup \"\"\" for i in range(self.sim.data.ncon): #",
"like 'model.geom_names[geom_id]' cannot be used because # not every geom",
"# notice, this list of conditions and the following disclaimer.",
"# OR TECHNICAL UNIVERSITY OF DARMSTADT BE LIABLE FOR ANY",
"azimuth=-90, # camera rotation around the camera's vertical axis )",
"# Augment the binary task with an endless dummy task,",
"Task: if task_args.get(\"sparse_rew_fcn\", False): # Create a task with binary",
"THE # POSSIBILITY OF SUCH DAMAGE. import mujoco_py import numpy",
"_create_deviation_task(self, task_args: dict) -> Task: idcs = list(range(self.state_space.flat_dim - 3,",
"degrees of freedom. \"\"\" return self._num_dof @property def torque_space(self) ->",
"goal_pos_init_sim_4dof, goal_pos_init_sim_7dof, init_qpos_des_4dof, init_qpos_des_7dof, act_space_bic_4dof, act_space_bic_7dof, wam_q_limits_up_7dof, wam_q_limits_lo_7dof, torque_space_wam_4dof, torque_space_wam_7dof,",
"] ) def _create_main_task(self, task_args: dict) -> Task: # Create",
"num_dof == 4: self.init_qpos[:4] = np.array([0.0, 0.63, 0.0, 1.27]) self.init_qpos[4]",
"around the axis in the plane azimuth=-90, # camera rotation",
"When using the `reset()` function, always pass a meaningful `init_state`",
"# The rope consists of 30 capsules xml_model = xml_model.replace(\"[pos_capsule]\",",
"SUCH DAMAGE. import mujoco_py import numpy as np import os.path",
"used :param frame_skip: number of simulation frames for which the",
"parts of the cup. This causes the episode to end.",
"np.array([0.1, 1, 0.5, 1.0, 0.1, 1.0, 1.0])[: self._num_dof] init_state_lo =",
"a reference and updates automatically at each step. # Note:",
"# camera rotation around the camera's vertical axis ) @property",
"the selected joints qpos_des = self.qpos_des_init.copy() # the desired trajectory",
"body1_name in self._collision_bodies or contact.geom1 in self._collision_geom_ids ) if c1",
"the following disclaimer. # 2. Redistributions in binary form must",
"the connection of WAM and cup (geom_ids) c1 = body1_name",
"or 7\") def _create_task(self, task_args: dict) -> Task: if task_args.get(\"sparse_rew_fcn\",",
"{self.curr_step}.\", \"y\") return True return False def observe(self, state: np.ndarray)",
"MaskedTask from pyrado.tasks.parallel import ParallelTasks from pyrado.tasks.reward_functions import ZeroPerStepRewFcn, ExpQuadrErrRewFcn,",
"joints [N/s] (default value is small) joint_2_damping=0.05, # damping of",
"-1 on fail after the main task ist done (successfully",
"self._collision_bodies or contact.geom2 in self._collision_geom_ids ) c2 = body2_name ==",
"SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,",
"cup position into the observation :param task_args: arguments for the",
"# distance ball - cup; shouldn't move in y-direction R=task_args.get(\"R\",",
"for 7 dof, thus punish more ) task = DesStateTask(spec,",
"the cup and ball position obs_lo, obs_up, labels = [0.0],",
"Add plus/minus one degree to each motor joint and the",
"Research Institute Europe GmbH, and # Technical University of Darmstadt.",
"stopping task = SequentialTasks((main_task, dont_fail_after_succ_task)) return MaskedTask(self.spec, task, idcs) else:",
"self.state_space.contains(self.state) else True return dict( qpos_des=qpos_des, qvel_des=qvel_des, qpos=qpos[: self._num_dof], qvel=qvel[:",
"with binary reward return self._create_main_task(task_args) else: # Create two (or",
"or not) dont_fail_after_succ_task = FinalRewTask( GoallessTask(spec, ZeroPerStepRewFcn()), mode=FinalRewMode(always_negative=True), factor=factor, )",
"ConditionOnlyTask( spec, condition_fcn=self.check_ball_in_cup, is_success_condition=True, ), mode=FinalRewMode(always_positive=True), factor=factor, ) # Yield",
":param dt: by default the time step size is the",
"desired, check for collisions of the ball with the robot",
"All rights reserved. # # Redistribution and use in source",
"True return dict( qpos_des=qpos_des, qvel_des=qvel_des, qpos=qpos[: self._num_dof], qvel=qvel[: self._num_dof], ball_pos=ball_pos,",
"self.stop_on_collision = stop_on_collision self.camera_config = dict( distance=2.7, trackbodyid=0, # id",
"ball (the robot operates in the x-z plane). # Note:",
"to 1e-6) ) elif num_dof == 4: return dict( cup_scale=1.0,",
"return self._create_main_task(task_args) else: # Create two (or three) parallel running",
"the task construction \"\"\" Serializable._init(self, locals()) self.fixed_init_state = fixed_init_state self.observe_ball",
"ball position idcs = list(range(self.state_space.flat_dim - 6, self.state_space.flat_dim - 3))",
"= False except mujoco_py.builder.MujocoException: # When MuJoCo recognized instabilities in",
"# notice, this list of conditions and the following disclaimer",
"# We access a private attribute since a method like",
"the torques for the PD controller and clip them to",
"relative to self._qpos_des_init qvel_des = np.zeros_like(qpos_des) if self._num_dof == 4:",
"mode=FinalRewMode(always_positive=True), factor=factor, ) # Yield -1 on fail after the",
"failure. mjsim_crashed = True qpos, qvel = self.sim.data.qpos.copy(), self.sim.data.qvel.copy() ball_pos",
"step size `dt` :param dt: by default the time step",
"at each step. # Note: sim.forward() + get_body_xpos() results in",
"init_state_lo = self._init_state.copy() init_state_lo[: self._num_dof] -= np.pi / 180 *",
"joint_7_damping=0.05, # damping of motor joints [N/s] (default value is",
"pyrado.inf, fixed_init_state: bool = True, stop_on_collision: bool = True, observe_ball:",
"behavior. :param observe_ball: if `True`, include the 2-dim (x-z plane)",
"the same shape as the init space (including ball and",
"the ball collides with something else than the central parts",
"def state_space(self) -> Space: # The state space has the",
"scaling factor for the radius of the cup [-] (should",
"Initialize num DoF specific variables self._num_dof = num_dof if num_dof",
"pyrado.inf) # Ensure that joint limits of the arm are",
"ball_pos, cup_goal]) # If desired, check for collisions of the",
"1e-4, 2e1])), # distance ball - cup; shouldn't move in",
"controller and clip them to their max values torque =",
"the first rope segment relative to the cup bottom plate",
"joint_6_dryfriction=0.4, # dry friction coefficient of motor joint 6 [-]",
"[m] ball_mass=0.024, # mass of the ball [kg] joint_1_damping=0.05, #",
"xml_model = xml_model.replace(\"[size_capsule_geom]\", str(rope_length / 72)) # Resolve mesh directory",
"# Each joint is at the top of each capsule",
"geoms body1 = self.model.geom_bodyid[contact.geom1] body1_name = self.model.body_names[body1] body2 = self.model.geom_bodyid[contact.geom2]",
"is small) joint_5_damping=0.05, # damping of motor joints [N/s] (default",
"OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR",
"Honda Research Institute Europe GmbH, and # Technical University of",
"ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES",
"torque_space_wam_4dof @property def state_space(self) -> Space: # The state space",
"at the top of each capsule (therefore negative direction from",
"ball is in the cup at time step {self.curr_step}.\", \"y\")",
"np.concatenate([state_des_ball, state_des_cup]) R_default = np.diag([0, 0, 1, 1e-2, 1e-2, 1e-1])",
"a PD controller. .. note:: When using the `reset()` function,",
"obs = [self._curr_step / self.max_steps] # Extract the (x, z)",
"= self._collision_bodies[:6] # We access a private attribute since a",
"xml_model.replace(\"[pos_mesh]\", str(0.055 - (cup_scale - 1.0) * 0.023)) xml_model =",
"than the central parts of the cup \"\"\" for i",
"if cup_scale is not None: # See [1, l.93-96] xml_model",
"= np.full(state_shape, -pyrado.inf), np.full(state_shape, pyrado.inf) # Ensure that joint limits",
"if `True`, include the 2-dim (x-z plane) cartesian ball position",
"= self.model._geom_name2id[\"cup_inner\"] c1 = body1_name == \"ball\" and contact.geom2 ==",
"of Darmstadt, nor the names of its contributors may #",
"ist done (successfully or not) dont_fail_after_succ_task = FinalRewTask( GoallessTask(spec, ZeroPerStepRewFcn()),",
"can be overwritten. Possible use case if if you know",
"result in undesired behavior. :param observe_ball: if `True`, include the",
"frame # print_cbt(f'cup xipos: {self.sim.data.get_body_xipos(\"cup\").copy()}', 'b') # center of mass",
"of motor joints [N/s] (default value is small) joint_7_damping=0.05, #",
"self.observe_ball: obs_lo.extend([-3.0, -3.0]) obs_up.extend([3.0, 3.0]) labels.extend([\"ball_x\", \"ball_z\"]) if self.observe_cup: obs_lo.extend([-3.0,",
"of motor joints [N/s] (default value is small) joint_5_damping=0.05, #",
"the cup bottom plate # Set the actual stable initial",
"self.torque_space.project_to(torque) # Apply the torques to the robot self.sim.data.qfrc_applied[: self._num_dof]",
"Check if the ball is in the cup. :param verbose:",
"return torque_space_wam_7dof if self._num_dof == 7 else torque_space_wam_4dof @property def",
"ball_mass=0.024, # mass of the ball [kg] joint_1_damping=0.05, # damping",
"torque # Call MuJoCo try: self.sim.step() mjsim_crashed = False except",
"30 capsules xml_model = xml_model.replace(\"[pos_capsule]\", str(rope_length / 30)) # Each",
"See [1, l.93-96] xml_model = xml_model.replace(\"[scale_mesh]\", str(cup_scale * 0.001)) xml_model",
"IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"",
"on collision :return: `True` if the ball collides with something",
"( goal_pos_init_sim_4dof, goal_pos_init_sim_7dof, init_qpos_des_4dof, init_qpos_des_7dof, act_space_bic_4dof, act_space_bic_7dof, wam_q_limits_up_7dof, wam_q_limits_lo_7dof, torque_space_wam_4dof,",
"this software without # specific prior written permission. # #",
"= xml_model.replace(\"[size_capsule_geom]\", str(rope_length / 72)) # Resolve mesh directory and",
"cup bottom plate # Set the actual stable initial position.",
"ball with the robot ball_collided = self.check_ball_collisions() if self.stop_on_collision else",
"= self._init_state.copy() init_state_lo[: self._num_dof] -= np.pi / 180 * np.array([0.1,",
"camera rotation around the axis in the plane azimuth=-90, #",
"print messages on collision :return: `True` if the ball collides",
"central parts of the cup \"\"\" for i in range(self.sim.data.ncon):",
"rotation around the axis in the plane azimuth=-90, # camera",
"of simulation frames for which the same action is held,",
"raise pyrado.ValueErr(given=num_dof, eq_constraint=\"4 or 7\") model_path = osp.join(pyrado.MUJOCO_ASSETS_DIR, graph_file_name) super().__init__(model_path,",
"# Bodies to check fo collision self._collision_bodies = [ \"wam/base_link\",",
"init pose, interferes with R_default from _create_main_task ) task =",
"state_up = np.full(state_shape, -pyrado.inf), np.full(state_shape, pyrado.inf) # Ensure that joint",
"position idcs = list(range(self.state_space.flat_dim - 6, self.state_space.flat_dim - 3)) #",
"num_dof == 7: return dict( cup_scale=1.0, # scaling factor for",
"This position would be reached after some time using the",
"state_des, as sim has not been updated to # init_space.sample(),",
"joint 3 [-] joint_4_dryfriction=0.4, # dry friction coefficient of motor",
"= EnvSpec( self.spec.obs_space, self.spec.act_space, self.spec.state_space.subspace(self.spec.state_space.create_mask(idcs)), ) # If we do",
"max_steps: int = pyrado.inf, fixed_init_state: bool = True, stop_on_collision: bool",
"cup_scale = domain_param.pop(\"cup_scale\", None) rope_length = domain_param.pop(\"rope_length\", None) if cup_scale",
"operates in the x-z plane). # Note: the cup_goal is",
"\"cup_geom2\"]] self.stop_on_collision = stop_on_collision self.camera_config = dict( distance=2.7, trackbodyid=0, #",
"act_space_bic_7dof if self._num_dof == 7 else act_space_bic_4dof @classmethod def get_nominal_domain_param(cls,",
"to the coordinate system origin of the rigid body object",
"xml_model.replace(\"[pos_capsule]\", str(rope_length / 30)) # Each joint is at the",
"the cup [-] (should be >0.65) rope_length=0.41, # length of",
"init_cup_goal = goal_pos_init_sim_4dof elif num_dof == 7: graph_file_name = \"wam_7dof_bic.xml\"",
"int = 4, dt: Optional[float] = None, max_steps: int =",
"bodies) # or the connection of WAM and cup (geom_ids)",
"contributors may # be used to endorse or promote products",
"1.0) * 0.023)) xml_model = xml_model.replace(\"[pos_goal]\", str(0.1165 + (cup_scale -",
"selected joints qpos_des = self.qpos_des_init.copy() # the desired trajectory is",
"self._create_main_task(task_args) else: # Create two (or three) parallel running task.",
"(default value is small) joint_2_damping=0.05, # damping of motor joints",
"is the mujoco site object marking the goal position for",
"import os.path as osp from init_args_serializer import Serializable from typing",
"= xml_model.replace(\"[pos_capsule]\", str(rope_length / 30)) # Each joint is at",
"to avoid early stopping task = SequentialTasks((main_task, dont_fail_after_succ_task)) return MaskedTask(self.spec,",
"source code must retain the above copyright # notice, this",
"SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS",
"a multiplier of the time step size `dt` :param dt:",
"print_cbt(f\"The ball is in the cup at time step {self.curr_step}.\",",
"print_cbt(f'cup xipos: {self.sim.data.get_body_xipos(\"cup\").copy()}', 'b') # center of mass # Observe",
"(INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT",
"It is not identical # to the coordinate system origin",
"set the `failed` flag in the `dict` returned by `_mujoco_step()`",
"{self.sim.data.get_body_xpos(\"cup\").copy()}', 'b') # center of frame # print_cbt(f'cup xipos: {self.sim.data.get_body_xipos(\"cup\").copy()}',",
"2 [-] joint_3_dryfriction=0.4, # dry friction coefficient of motor joint",
"if self._num_dof == 4: np.add.at(qpos_des, [1, 3], act[:2]) np.add.at(qvel_des, [1,",
"_create_main_task(self, task_args: dict) -> Task: # Create a DesStateTask that",
"which Barrett WAM setup being used :param frame_skip: number of",
"dry friction coefficient of motor joint 3 [-] joint_4_dryfriction=0.4, #",
"RESEARCH INSTITUTE EUROPE GMBH, # OR TECHNICAL UNIVERSITY OF DARMSTADT",
"2e1])), # distance ball - cup; shouldn't move in y-direction",
"0.038)) xml_model = xml_model.replace(\"[size_cup_inner]\", str(cup_scale * 0.03)) if rope_length is",
"False, observe_cup: bool = False, task_args: Optional[dict] = None, ):",
"Compute the torques for the PD controller and clip them",
"time obs = [self._curr_step / self.max_steps] # Extract the (x,",
"\"\"\" name: str = \"wam-bic\" def __init__( self, num_dof: int,",
"# Wrap the masked DesStateTask to add a bonus for",
"a negative step reward and no final cost on failing,",
"return MaskedTask(self.spec, task, idcs) def _adapt_model_file(self, xml_model: str, domain_param: dict)",
"0.5, 1.0, 0.1, 1.0, 1.0])[: self._num_dof] self._init_space = BoxSpace(init_state_lo, init_state_up)",
"self.spec.act_space, self.spec.state_space.subspace(self.spec.state_space.create_mask(idcs)), ) # If we do not use copy(),",
"err_pos + self.d_gains * err_vel torque = self.torque_space.project_to(torque) # Apply",
"of its contributors may # be used to endorse or",
"3, 5], act[:3]) np.add.at(qvel_des, [1, 3, 5], act[3:]) # Compute",
"contact object contact = self.sim.data.contact[i] # Extract body-id and body-name",
"segment joint init_state_up = self._init_state.copy() init_state_up[: self._num_dof] += np.pi /",
"str = \"wam-bic\" def __init__( self, num_dof: int, frame_skip: int",
"# Running a PD controller on joint positions and velocities",
"and velocity errors err_pos = qpos_des - self.state[: self._num_dof] err_vel",
"== \"ball\" and contact.geom2 == cup_inner_id c2 = body2_name ==",
"import mujoco_py import numpy as np import os.path as osp",
"the ball collides with part of the WAM (collision bodies)",
"from pyrado.tasks.desired_state import DesStateTask from pyrado.tasks.final_reward import BestStateFinalRewTask, FinalRewTask, FinalRewMode",
"( body1_name in self._collision_bodies or contact.geom1 in self._collision_geom_ids ) if",
"damping of motor joints [N/s] (default value is small) joint_7_damping=0.05,",
"torque = self.torque_space.project_to(torque) # Apply the torques to the robot",
"plane azimuth=-90, # camera rotation around the camera's vertical axis",
"it simply kills it. # Instead, we want the episode",
"length of the rope [m] ball_mass=0.024, # mass of the",
"self._num_dof] self._init_space = BoxSpace(init_state_lo, init_state_up) # Bodies to check fo",
"cartesian cup position into the observation :param task_args: arguments for",
"joint deviation from the init position # 3.) Binary Bonus:",
"4: self.init_qpos[:4] = np.array([0.0, 0.63, 0.0, 1.27]) self.init_qpos[4] = -0.34",
"of the rigid body object 'cup' if self.observe_ball: obs.extend([state[-3], state[-1]])",
"position into the observation :param task_args: arguments for the task",
"in undesired behavior. :param observe_ball: if `True`, include the 2-dim",
"degrees of freedom (4 or 7), depending on which Barrett",
"state_lo[: self._num_dof] = wam_q_limits_lo_7dof[: self._num_dof] state_up[: self._num_dof] = wam_q_limits_up_7dof[: self._num_dof]",
"task with an endless dummy task, to avoid early stopping",
"values torque = self.p_gains * err_pos + self.d_gains * err_vel",
"endless dummy task, to avoid early stopping task = SequentialTasks((main_task,",
"self.fixed_init_state = fixed_init_state self.observe_ball = observe_ball self.observe_cup = observe_cup #",
"joints [N/s] (default value is small) joint_1_dryfriction=0.4, # dry friction",
"small) joint_2_damping=0.05, # damping of motor joints [N/s] (default value",
"ConditionOnlyTask from pyrado.tasks.desired_state import DesStateTask from pyrado.tasks.final_reward import BestStateFinalRewTask, FinalRewTask,",
"task. # 1.) Main task: Desired state task for the",
"camera's vertical axis ) @property def num_dof(self) -> int: \"\"\"",
"PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,",
"* np.array([0.1, 1, 0.5, 1.0, 0.1, 1.0, 1.0])[: self._num_dof] self._init_space",
"collisions of the ball with the robot ball_collided = self.check_ball_collisions()",
"of WAM and cup (geom_ids) c1 = body1_name == \"ball\"",
"[ \"wam/base_link\", \"wam/shoulder_yaw_link\", \"wam/shoulder_pitch_link\", \"wam/upper_arm_link\", \"wam/forearm_link\", \"wrist_palm_link\", \"wam/wrist_pitch_link\", \"wam/wrist_yaw_link\", ]",
"model_path = osp.join(pyrado.MUJOCO_ASSETS_DIR, graph_file_name) super().__init__(model_path, frame_skip, dt, max_steps, task_args) #",
"and contact.geom2 == cup_inner_id c2 = body2_name == \"ball\" and",
"the init position # 3.) Binary Bonus: Adds a binary",
"self.observe_cup: obs_lo.extend([-3.0, -3.0]) obs_up.extend([3.0, 3.0]) labels.extend([\"cup_x\", \"cup_z\"]) return BoxSpace(obs_lo, obs_up,",
"move in y-direction R=task_args.get(\"R\", R_default), # last joint is really",
"TECHNICAL UNIVERSITY OF DARMSTADT BE LIABLE FOR ANY DIRECT, INDIRECT,",
"the following conditions are met: # 1. Redistributions of source",
"None: # The rope consists of 30 capsules xml_model =",
"wam_pgains_7dof, wam_dgains_7dof, wam_pgains_4dof, wam_dgains_4dof, ) from pyrado.environments.mujoco.base import MujocoSimEnv from",
"on joint positions and velocities return act_space_bic_7dof if self._num_dof ==",
"Augment the binary task with an endless dummy task, to",
"cup at time step {self.curr_step}.\", \"y\") return True return False",
"motor joints [N/s] (default value is small) joint_7_damping=0.05, # damping",
"# TODO: Debug print-outs, should be removed in future... #",
"coming from MuJoCo is a reference and updates automatically at",
"more ) task = DesStateTask(spec, state_des, rew_fcn) # Wrap the",
"return self._num_dof @property def torque_space(self) -> Space: \"\"\" Get the",
"body1 = self.model.geom_bodyid[contact.geom1] body1_name = self.model.body_names[body1] body2 = self.model.geom_bodyid[contact.geom2] body2_name",
"A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL",
"@property def act_space(self) -> Space: # Running a PD controller",
"final cost on failing, this might result in undesired behavior.",
"variables self._num_dof = num_dof if num_dof == 4: graph_file_name =",
"of motor joints [N/s] (default value is small) joint_3_damping=0.05, #",
"state_des coming from MuJoCo is a reference and updates automatically",
"= body2_name == \"ball\" and contact.geom1 == cup_inner_id if c1",
"name in [\"cup_geom1\", \"cup_geom2\"]] self.stop_on_collision = stop_on_collision self.camera_config = dict(",
"domain_param.pop(\"cup_scale\", None) rope_length = domain_param.pop(\"rope_length\", None) if cup_scale is not",
"Set the actual stable initial position. This position would be",
"# When MuJoCo recognized instabilities in the simulation, it simply",
"of the ball in cartesian coordinates self._init_state = np.concatenate([self.init_qpos, self.init_qvel,",
"-> Task: # Create a DesStateTask that masks everything but",
"the space of joint torques. \"\"\" return torque_space_wam_7dof if self._num_dof",
"else goal_pos_init_sim_4dof rew_fcn = QuadrErrRewFcn( Q=task_args.get(\"Q_dev\", np.diag([2e-1, 1e-6, 5e0])), #",
"value is small) joint_4_damping=0.05, # damping of motor joints [N/s]",
"[-] joint_5_dryfriction=0.4, # dry friction coefficient of motor joint 5",
"# Yield -1 on fail after the main task ist",
"qvel_des=qvel_des, qpos=qpos[: self._num_dof], qvel=qvel[: self._num_dof], ball_pos=ball_pos, cup_pos=cup_goal, failed=mjsim_crashed or ball_collided",
"for the task construction \"\"\" Serializable._init(self, locals()) self.fixed_init_state = fixed_init_state",
"and ball (the robot operates in the x-z plane). #",
"task for the cartesian ball distance # 2.) Deviation task:",
"7: return dict( cup_scale=1.0, # scaling factor for the radius",
"# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY",
"the time step size `dt` :param dt: by default the",
"robot self.sim.data.qfrc_applied[: self._num_dof] = torque # Call MuJoCo try: self.sim.step()",
"5], act[3:]) # Compute the position and velocity errors err_pos",
"on which Barrett WAM setup being used :param frame_skip: number",
"= pyrado.inf, fixed_init_state: bool = True, stop_on_collision: bool = True,",
"idcs = list(range(self.state_space.flat_dim - 6, self.state_space.flat_dim - 3)) # Cartesian",
"MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED.",
"Cartesian ball position spec = EnvSpec( self.spec.obs_space, self.spec.act_space, self.spec.state_space.subspace(self.spec.state_space.create_mask(idcs)), )",
"the simulation, it simply kills it. # Instead, we want",
"cartesian position of cup and ball (the robot operates in",
"and ( body1_name in self._collision_bodies or contact.geom1 in self._collision_geom_ids )",
"\"wam/wrist_yaw_link\", ] if self._num_dof == 4: self._collision_bodies = self._collision_bodies[:6] #",
"disclaimer. # 2. Redistributions in binary form must reproduce the",
"mujoco_py import numpy as np import os.path as osp from",
"int = 7) -> dict: if num_dof == 7: return",
"[1, 3], act[:2]) np.add.at(qvel_des, [1, 3], act[2:]) elif self._num_dof ==",
"friction coefficient of motor joint 5 [-] joint_6_dryfriction=0.4, # dry",
"qvel_des = np.zeros_like(qpos_des) if self._num_dof == 4: np.add.at(qpos_des, [1, 3],",
"the PD controller and clip them to their max values",
"check fo collision self._collision_bodies = [ \"wam/base_link\", \"wam/shoulder_yaw_link\", \"wam/shoulder_pitch_link\", \"wam/upper_arm_link\",",
"_create_task(self, task_args: dict) -> Task: if task_args.get(\"sparse_rew_fcn\", False): # Create",
"is not identical # to the coordinate system origin of",
"motor joints [N/s] (default value is small) joint_6_damping=0.05, # damping",
"): \"\"\" Constructor :param num_dof: number of degrees of freedom",
"int: \"\"\" Get the number of degrees of freedom. \"\"\"",
"form must reproduce the above copyright # notice, this list",
"np.array([0.723, 0.0, 1.168]) init_cup_goal = goal_pos_init_sim_4dof elif num_dof == 7:",
"parameters cup_scale = domain_param.pop(\"cup_scale\", None) rope_length = domain_param.pop(\"rope_length\", None) if",
"qvel, ball_pos, cup_goal]) # If desired, check for collisions of",
"failing, this might result in undesired behavior. :param observe_ball: if",
"home position) if num_dof == 4: self.init_qpos[:4] = np.array([0.0, 0.63,",
"of WAM and cup (geom_ids) cup_inner_id = self.model._geom_name2id[\"cup_inner\"] c1 =",
"condition_fcn=self.check_ball_in_cup, is_success_condition=True, ), mode=FinalRewMode(always_positive=True), factor=factor, ) # Yield -1 on",
"joints [N/s] (reasonable values are 6e-4 to 1e-6) ) elif",
"of 30 capsules xml_model = xml_model.replace(\"[pos_capsule]\", str(rope_length / 30)) #",
"wam_dgains_7dof, wam_pgains_4dof, wam_dgains_4dof, ) from pyrado.environments.mujoco.base import MujocoSimEnv from pyrado.spaces.base",
"BoxSpace from pyrado.spaces.singular import SingularStateSpace from pyrado.tasks.base import Task from",
"self.observe_ball = observe_ball self.observe_cup = observe_cup # Initialize num DoF",
"joint_4_dryfriction=0.4, # dry friction coefficient of motor joint 4 [-]",
"@property def state_space(self) -> Space: # The state space has",
"if rope_length is not None: # The rope consists of",
"same shape as the init space (including ball and cup)",
"# If we do not use copy(), state_des coming from",
"or the connection of WAM and cup (geom_ids) cup_inner_id =",
"causes the episode to end. Keep in mind that in",
"print_cbt( f\"Undesired collision of {body1_name} and {body2_name} detected!\", \"y\", )",
"contact.geom1 == cup_inner_id if c1 or c2: if verbose: print_cbt(f\"The",
"is small) joint_4_damping=0.05, # damping of motor joints [N/s] (default",
") def _create_deviation_task(self, task_args: dict) -> Task: idcs = list(range(self.state_space.flat_dim",
"coordinates self._init_state = np.concatenate([self.init_qpos, self.init_qvel, init_ball_pos, init_cup_goal]) if self.fixed_init_state: self._init_space",
"position # 3.) Binary Bonus: Adds a binary bonus when",
"name: str = \"wam-bic\" def __init__( self, num_dof: int, frame_skip:",
"0, 1.5]) # state_des = np.concatenate([state_des_ball, state_des_cup]) R_default = np.diag([0,",
"self._collision_bodies = self._collision_bodies[:6] # We access a private attribute since",
"cup_pos=cup_goal, failed=mjsim_crashed or ball_collided or state_oob, ) def check_ball_collisions(self, verbose:",
"), ] ) def _create_main_task(self, task_args: dict) -> Task: #",
"self._num_dof] = wam_q_limits_up_7dof[: self._num_dof] return BoxSpace(state_lo, state_up) @property def obs_space(self)",
"catched [inactive by default] return ParallelTasks( [ self._create_main_task(task_args), self._create_deviation_task(task_args), self._create_main_task(",
"motor joint 4 [-] rope_damping=1e-4, # damping of rope joints",
"contact = self.sim.data.contact[i] # Extract body-id and body-name of both",
"must retain the above copyright # notice, this list of",
"c1 or c2: if verbose: print_cbt( f\"Undesired collision of {body1_name}",
"value is small) joint_5_damping=0.05, # damping of motor joints [N/s]",
"and optionally the cup and ball position obs_lo, obs_up, labels",
"2-dim (x-z plane) cartesian ball position into the observation :param",
"Q=task_args.get(\"Q_dev\", np.diag([2e-1, 1e-6, 5e0])), # Cartesian distance from init cup",
"[1] https://github.com/psclklnk/self-paced-rl/tree/master/sprl/envs/ball_in_a_cup.py \"\"\" name: str = \"wam-bic\" def __init__( self,",
"reward task main_task = FinalRewTask( ConditionOnlyTask( spec, condition_fcn=self.check_ball_in_cup, is_success_condition=True, ),",
"xml_model.replace(\"[size_cup_inner]\", str(cup_scale * 0.03)) if rope_length is not None: #",
"self._collision_bodies[:6] # We access a private attribute since a method",
"or ball_collided or state_oob, ) def check_ball_collisions(self, verbose: bool =",
"values are 6e-4 to 1e-6) ) else: raise pyrado.ValueErr(given=num_dof, eq_constraint=\"4",
"mujoco config file multiplied by the number of frame skips",
"wam_pgains_4dof self.d_gains = wam_dgains_4dof init_ball_pos = np.array([0.723, 0.0, 1.168]) init_cup_goal",
"init_state_lo[: self._num_dof] -= np.pi / 180 * np.array([0.1, 1, 0.5,",
"connection of WAM and cup (geom_ids) cup_inner_id = self.model._geom_name2id[\"cup_inner\"] c1",
"[-] (should be >0.65) rope_length=0.41, # length of the rope",
"cup. This causes the episode to end. Keep in mind",
"def num_dof(self) -> int: \"\"\" Get the number of degrees",
"of source code must retain the above copyright # notice,",
"else np.diag([0, 0, 1e-2, 1e-2]) rew_fcn = ExpQuadrErrRewFcn( Q=task_args.get(\"Q\", np.diag([2e1,",
"joint space distance from init pose, interferes with R_default from",
"Call MuJoCo try: self.sim.step() mjsim_crashed = False except mujoco_py.builder.MujocoException: #",
"optionally the cup and ball position obs_lo, obs_up, labels =",
"= list(range(self.state_space.flat_dim - 6, self.state_space.flat_dim - 3)) # Cartesian ball",
"thus punish more ) task = DesStateTask(spec, state_des, rew_fcn) #",
"init_qpos_des_4dof self.p_gains = wam_pgains_4dof self.d_gains = wam_dgains_4dof init_ball_pos = np.array([0.723,",
"= self.model.body_names[body2] # Evaluate if the ball collides with part",
"be reached after some time using the internal # PD",
"step {self.curr_step}.\", \"y\") return True return False def observe(self, state:",
"recorded a trajectory with a specific `dt`. :param max_steps: max",
"into the observation :param observe_cup: if `True`, include the 2-dim",
"attribute since a method like 'model.geom_names[geom_id]' cannot be used because",
"Honda Research Institute Europe GmbH, # or Technical University of",
"-> Space: # Running a PD controller on joint positions",
"kills it. # Instead, we want the episode to end",
"def obs_space(self) -> Space: # Observing the normalized time and",
") else: raise pyrado.ValueErr(given=num_dof, eq_constraint=\"4 or 7\") def _create_task(self, task_args:",
"state_des_cup]) R_default = np.diag([0, 0, 1, 1e-2, 1e-2, 1e-1]) if",
"rew_fcn = QuadrErrRewFcn( Q=task_args.get(\"Q_dev\", np.diag([2e-1, 1e-6, 5e0])), # Cartesian distance",
"one degree to each motor joint and the first rope",
"joint 2 [-] joint_3_dryfriction=0.4, # dry friction coefficient of motor",
"permitted provided that the following conditions are met: # 1.",
"self.max_steps), ) def _create_deviation_task(self, task_args: dict) -> Task: idcs =",
"Cartesian distance from init cup position R=task_args.get( \"R_dev\", np.zeros((self.act_space.shape[0], self.act_space.shape[0]))",
"else False # If state is out of bounds (this",
"time and optionally the cup and ball position obs_lo, obs_up,",
"The initial position of the ball in cartesian coordinates self._init_state",
"the task, but does not work because of the mask)",
"np.diag([2e-1, 1e-6, 5e0])), # Cartesian distance from init cup position",
"\"\"\" Get the space of joint torques. \"\"\" return torque_space_wam_7dof",
"or without # modification, are permitted provided that the following",
"factor = task_args.get(\"success_bonus\", 1) # Binary final reward task main_task",
"3], act[2:]) elif self._num_dof == 7: np.add.at(qpos_des, [1, 3, 5],",
"in [\"cup_geom1\", \"cup_geom2\"]] self.stop_on_collision = stop_on_collision self.camera_config = dict( distance=2.7,",
"state_des = np.concatenate([state_des_ball, state_des_cup]) R_default = np.diag([0, 0, 1, 1e-2,",
"LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR",
"pyrado.tasks.parallel import ParallelTasks from pyrado.tasks.reward_functions import ZeroPerStepRewFcn, ExpQuadrErrRewFcn, QuadrErrRewFcn from",
"Darmstadt, nor the names of its contributors may # be",
"Optional[float] = None, max_steps: int = pyrado.inf, fixed_init_state: bool =",
"safety margin) state_lo[: self._num_dof] = wam_q_limits_lo_7dof[: self._num_dof] state_up[: self._num_dof] =",
"If state is out of bounds (this is normally checked",
"torques. \"\"\" return torque_space_wam_7dof if self._num_dof == 7 else torque_space_wam_4dof",
"state space has the same shape as the init space",
"ball and cup) state_shape = np.concatenate([self.init_qpos, self.init_qvel, np.empty(3), np.empty(3)]).shape state_lo,",
"\"wam/forearm_link\", \"wrist_palm_link\", \"wam/wrist_pitch_link\", \"wam/wrist_yaw_link\", ] if self._num_dof == 4: self._collision_bodies",
"self._num_dof], qvel=qvel[: self._num_dof], ball_pos=ball_pos, cup_pos=cup_goal, failed=mjsim_crashed or ball_collided or state_oob,",
"function, always pass a meaningful `init_state` .. seealso:: [1] https://github.com/psclklnk/self-paced-rl/tree/master/sprl/envs/ball_in_a_cup.py",
"dict: assert self.act_space.contains(act, verbose=True) # Get the desired positions and",
"60)) # Pure visualization component xml_model = xml_model.replace(\"[size_capsule_geom]\", str(rope_length /",
"Note: sim.forward() + get_body_xpos() results in wrong output for state_des,",
"_mujoco_step(self, act: np.ndarray) -> dict: assert self.act_space.contains(act, verbose=True) # Get",
"factor for the radius of the cup [-] (should be",
"the camera's vertical axis ) @property def num_dof(self) -> int:",
"and joint deviation from the init position # 3.) Binary",
"<NAME>, HONDA RESEARCH INSTITUTE EUROPE GMBH, # OR TECHNICAL UNIVERSITY",
"# Observe the normalized time obs = [self._curr_step / self.max_steps]",
"body2_name == \"ball\" and ( body1_name in self._collision_bodies or contact.geom1",
"import Serializable from typing import Optional import pyrado from pyrado.environments.barrett_wam",
"7 else np.array([0.758, 0, 1.5]) # state_des = np.concatenate([state_des_ball, state_des_cup])",
"xml_model = xml_model.replace(\"[scale_mesh]\", str(cup_scale * 0.001)) xml_model = xml_model.replace(\"[pos_mesh]\", str(0.055",
"and no final cost on failing, this might result in",
"return act_space_bic_7dof if self._num_dof == 7 else act_space_bic_4dof @classmethod def",
"idcs = list(range(self.state_space.flat_dim - 3, self.state_space.flat_dim)) # Cartesian cup goal",
"GMBH, # OR TECHNICAL UNIVERSITY OF DARMSTADT BE LIABLE FOR",
"IN NO EVENT SHALL <NAME>, HONDA RESEARCH INSTITUTE EUROPE GMBH,",
"0.0, 1.27]) self.init_qpos[4] = -0.34 # angle of the first",
"THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE",
"* 0.0385)) xml_model = xml_model.replace(\"[size_cup]\", str(cup_scale * 0.038)) xml_model =",
"qpos, qvel = self.sim.data.qpos.copy(), self.sim.data.qvel.copy() ball_pos = self.sim.data.get_body_xpos(\"ball\").copy() cup_goal =",
"cup_goal]) # If desired, check for collisions of the ball",
"the x-z plane). # Note: the cup_goal is the mujoco",
"goal position state_des = goal_pos_init_sim_7dof if self._num_dof == 7 else",
"self._qpos_des_init. # The initial position of the ball in cartesian",
"R_default = np.diag([0, 0, 1, 1e-2, 1e-2, 1e-1]) if self._num_dof",
"try: self.sim.step() mjsim_crashed = False except mujoco_py.builder.MujocoException: # When MuJoCo",
"wam_dgains_4dof, ) from pyrado.environments.mujoco.base import MujocoSimEnv from pyrado.spaces.base import Space",
"not work because of the mask) state_oob = False if",
"wam_q_limits_up_7dof, wam_q_limits_lo_7dof, torque_space_wam_4dof, torque_space_wam_7dof, wam_pgains_7dof, wam_dgains_7dof, wam_pgains_4dof, wam_dgains_4dof, ) from",
"top of each capsule (therefore negative direction from center) xml_model",
"else np.array([0.758, 0, 1.5]) # state_des = np.concatenate([state_des_ball, state_des_cup]) R_default",
"mind that in case of a negative step reward and",
"= \"wam_4dof_bic.xml\" self.qpos_des_init = init_qpos_des_4dof self.p_gains = wam_pgains_4dof self.d_gains =",
"them to their max values torque = self.p_gains * err_pos",
"system origin of the rigid body object 'cup' if self.observe_ball:",
"of motor joint 7 [-] rope_damping=1e-4, # damping of rope",
"and {body2_name} detected!\", \"y\", ) return True return False def",
"position would be reached after some time using the internal",
"use in source and binary forms, with or without #",
"- 3, self.state_space.flat_dim)) # Cartesian cup goal position spec =",
"\"\"\" Check if an undesired collision with the ball occurs.",
"self._num_dof == 7 else np.diag([0, 0, 1e-2, 1e-2]) rew_fcn =",
"the desired parts of the cup. This causes the episode",
"(should be >0.65) rope_length=0.41, # length of the rope [m]",
"- 6, self.state_space.flat_dim - 3)) # Cartesian ball position spec",
"dict( qpos_des=qpos_des, qvel_des=qvel_des, qpos=qpos[: self._num_dof], qvel=qvel[: self._num_dof], ball_pos=ball_pos, cup_pos=cup_goal, failed=mjsim_crashed",
"self.model.body_names[body1] body2 = self.model.geom_bodyid[contact.geom2] body2_name = self.model.body_names[body2] # Evaluate if",
"joints [N/s] (default value is small) joint_6_damping=0.05, # damping of",
"STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING",
"ball collides with something else than the central parts of",
"the same action is held, results in a multiplier of",
"init_state_up) # Bodies to check fo collision self._collision_bodies = [",
"else True return dict( qpos_des=qpos_des, qvel_des=qvel_des, qpos=qpos[: self._num_dof], qvel=qvel[: self._num_dof],",
"from pyrado.tasks.condition_only import ConditionOnlyTask from pyrado.tasks.desired_state import DesStateTask from pyrado.tasks.final_reward",
"joint torques. \"\"\" return torque_space_wam_7dof if self._num_dof == 7 else",
"rope_damping=1e-4, # damping of rope joints [N/s] (reasonable values are",
"output for state_des, as sim has not been updated to",
"Keep in mind that in case of a negative step",
"position of cup and ball (the robot operates in the",
"ball. It is not identical # to the coordinate system",
"QuadrErrRewFcn( Q=task_args.get(\"Q_dev\", np.diag([2e-1, 1e-6, 5e0])), # Cartesian distance from init",
"1e-1]) if self._num_dof == 7 else np.diag([0, 0, 1e-2, 1e-2])",
"motor joints [N/s] (default value is small) joint_3_damping=0.05, # damping",
"Observe the normalized time obs = [self._curr_step / self.max_steps] #",
"= self.sim.data.get_body_xpos(\"ball\").copy() cup_goal = self.sim.data.get_site_xpos(\"cup_goal\").copy() self.state = np.concatenate([qpos, qvel, ball_pos,",
"joints [N/s] (default value is small) joint_5_damping=0.05, # damping of",
"the ball collides with something else than the desired parts",
"is in the cup at time step {self.curr_step}.\", \"y\") return",
"University of Darmstadt, nor the names of its contributors may",
"`reset()` function, always pass a meaningful `init_state` .. seealso:: [1]",
"init_qpos_des_7dof self.p_gains = wam_pgains_7dof self.d_gains = wam_dgains_7dof init_ball_pos = np.array([0.828,",
"pyrado.tasks.goalless import GoallessTask from pyrado.tasks.masked import MaskedTask from pyrado.tasks.parallel import",
"remaining domain parameters return super()._adapt_model_file(xml_model, domain_param) def _mujoco_step(self, act: np.ndarray)",
"state_des_ball = self.sim.data.get_site_xpos(\"cup_goal\") # this is a reference # state_des_cup",
"# scaling factor for the radius of the cup [-]",
"= self.check_ball_collisions() if self.stop_on_collision else False # If state is",
"of the first rope segment relative to the cup bottom",
"dry friction coefficient of motor joint 5 [-] joint_6_dryfriction=0.4, #",
"[1, 3, 5], act[:3]) np.add.at(qvel_des, [1, 3, 5], act[3:]) #",
"@classmethod def get_nominal_domain_param(cls, num_dof: int = 7) -> dict: if",
"c2 = body2_name == \"ball\" and contact.geom1 == cup_inner_id if",
"self.qpos_des_init = init_qpos_des_7dof self.p_gains = wam_pgains_7dof self.d_gains = wam_dgains_7dof init_ball_pos",
"the episode to end. Keep in mind that in case",
"from pyrado.environments.barrett_wam import ( goal_pos_init_sim_4dof, goal_pos_init_sim_7dof, init_qpos_des_4dof, init_qpos_des_7dof, act_space_bic_4dof, act_space_bic_7dof,",
"BoxSpace(state_lo, state_up) @property def obs_space(self) -> Space: # Observing the",
"4: self._collision_bodies = self._collision_bodies[:6] # We access a private attribute",
"of mass # Observe the normalized time obs = [self._curr_step",
"of motor joint 6 [-] joint_7_dryfriction=0.4, # dry friction coefficient",
"first rope segment relative to the cup bottom plate #",
"ball-in-the-cup task, controlled by a PD controller. .. note:: When",
"wrong output for state_des, as sim has not been updated",
"to the cup bottom plate # Set the actual stable",
"unreliable for 7 dof, thus punish more ) task =",
"SHALL <NAME>, HONDA RESEARCH INSTITUTE EUROPE GMBH, # OR TECHNICAL",
"(reasonable values are 6e-4 to 1e-6) ) elif num_dof ==",
"for name in [\"cup_geom1\", \"cup_geom2\"]] self.stop_on_collision = stop_on_collision self.camera_config =",
"the connection of WAM and cup (geom_ids) cup_inner_id = self.model._geom_name2id[\"cup_inner\"]",
"if the ball is in the cup \"\"\" for i",
"(geom_ids) c1 = body1_name == \"ball\" and ( body2_name in",
"-0.28, -1.57]) self.init_qpos[7] = -0.21 # angle of the first",
"name self._collision_geom_ids = [self.model._geom_name2id[name] for name in [\"cup_geom1\", \"cup_geom2\"]] self.stop_on_collision",
"self._create_main_task(task_args), self._create_deviation_task(task_args), self._create_main_task( dict( sparse_rew_fcn=True, success_bonus=task_args.get(\"success_bonus\", 0), ) ), ]",
"identical # to the coordinate system origin of the rigid",
"-pyrado.inf), np.full(state_shape, pyrado.inf) # Ensure that joint limits of the",
"and cup (geom_ids) c1 = body1_name == \"ball\" and (",
"cup; shouldn't move in y-direction R=task_args.get(\"R\", R_default), # last joint",
"PD controller to stabilize at self._qpos_des_init. # The initial position",
"position spec = EnvSpec( self.spec.obs_space, self.spec.act_space, self.spec.state_space.subspace(self.spec.state_space.create_mask(idcs)), ) # init",
"initial position. This position would be reached after some time",
"prior written permission. # # THIS SOFTWARE IS PROVIDED BY",
"be used to endorse or promote products derived from this",
"of frame skips (legacy from OpenAI environments). By passing an",
"self.init_qpos[:7] = np.array([0.0, 0.65, 0.0, 1.41, 0.0, -0.28, -1.57]) self.init_qpos[7]",
"0.001)) xml_model = xml_model.replace(\"[pos_mesh]\", str(0.055 - (cup_scale - 1.0) *",
"# If desired, check for collisions of the ball with",
"coordinate system origin of the rigid body object 'cup' if",
") task = DesStateTask(spec, state_des, rew_fcn) # Wrap the masked",
"else than the desired parts of the cup. This causes",
"+= np.pi / 180 * np.array([0.1, 1, 0.5, 1.0, 0.1,",
"# dry friction coefficient of motor joint 4 [-] joint_5_dryfriction=0.4,",
"is_success_condition=True, ), mode=FinalRewMode(always_positive=True), factor=factor, ) # Yield -1 on fail",
"if the ball collides with part of the WAM (collision",
"collides with part of the WAM (collision bodies) # or",
"import GoallessTask from pyrado.tasks.masked import MaskedTask from pyrado.tasks.parallel import ParallelTasks",
"state_space(self) -> Space: # The state space has the same",
"motor joints [N/s] (default value is small) joint_5_damping=0.05, # damping",
"print_cbt class WAMBallInCupSim(MujocoSimEnv, Serializable): \"\"\" WAM robotic arm from Barrett",
"specific variables self._num_dof = num_dof if num_dof == 4: graph_file_name",
"= [ \"wam/base_link\", \"wam/shoulder_yaw_link\", \"wam/shoulder_pitch_link\", \"wam/upper_arm_link\", \"wam/forearm_link\", \"wrist_palm_link\", \"wam/wrist_pitch_link\", \"wam/wrist_yaw_link\",",
"The rope consists of 30 capsules xml_model = xml_model.replace(\"[pos_capsule]\", str(rope_length",
"np.add.at(qvel_des, [1, 3, 5], act[3:]) # Compute the position and",
"value is small) joint_3_damping=0.05, # damping of motor joints [N/s]",
"30)) # Each joint is at the top of each",
"R=task_args.get(\"R\", R_default), # last joint is really unreliable for 7",
"position (when the WAM moved to the home position) if",
"Get the number of degrees of freedom. \"\"\" return self._num_dof",
"positions and velocities for the selected joints qpos_des = self.qpos_des_init.copy()",
"of motor joints [N/s] (default value is small) joint_1_dryfriction=0.4, #",
"act_space_bic_7dof, wam_q_limits_up_7dof, wam_q_limits_lo_7dof, torque_space_wam_4dof, torque_space_wam_7dof, wam_pgains_7dof, wam_dgains_7dof, wam_pgains_4dof, wam_dgains_4dof, )",
"reached after some time using the internal # PD controller",
"at time step {self.curr_step}.\", \"y\") return True return False def",
"0: # print_cbt(f'cup xpos: {self.sim.data.get_body_xpos(\"cup\").copy()}', 'b') # center of frame",
"== 7 else torque_space_wam_4dof @property def state_space(self) -> Space: #",
"IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import",
"list(range(self.state_space.flat_dim - 6, self.state_space.flat_dim - 3)) # Cartesian ball position",
"of the arm are not reached (5 deg safety margin)",
"return super()._adapt_model_file(xml_model, domain_param) def _mujoco_step(self, act: np.ndarray) -> dict: assert",
"-0.34 # angle of the first rope segment relative to",
"from pyrado.tasks.goalless import GoallessTask from pyrado.tasks.masked import MaskedTask from pyrado.tasks.parallel",
"for the best state in the rollout return BestStateFinalRewTask( MaskedTask(self.spec,",
"import numpy as np import os.path as osp from init_args_serializer",
"state :param stop_on_collision: set the `failed` flag in the `dict`",
"connection of WAM and cup (geom_ids) c1 = body1_name ==",
"meaningful `init_state` .. seealso:: [1] https://github.com/psclklnk/self-paced-rl/tree/master/sprl/envs/ball_in_a_cup.py \"\"\" name: str =",
"[N/s] (reasonable values are 6e-4 to 1e-6) ) elif num_dof",
"4: np.add.at(qpos_des, [1, 3], act[:2]) np.add.at(qvel_des, [1, 3], act[2:]) elif",
"site object marking the goal position for the ball. It",
"size is the one from the mujoco config file multiplied",
"motor joints [N/s] (default value is small) joint_2_damping=0.05, # damping",
"graph_file_name) super().__init__(model_path, frame_skip, dt, max_steps, task_args) # Actual initial joint",
"of Darmstadt. # All rights reserved. # # Redistribution and",
"False) -> bool: \"\"\" Check if an undesired collision with",
"plane). # Note: the cup_goal is the mujoco site object",
"cup_scale=1.0, # scaling factor for the radius of the cup",
"act[3:]) # Compute the position and velocity errors err_pos =",
"str: # First replace special domain parameters cup_scale = domain_param.pop(\"cup_scale\",",
"f\"Undesired collision of {body1_name} and {body2_name} detected!\", \"y\", ) return",
"for the ball-in-the-cup task, controlled by a PD controller. ..",
"self.model.body_names[body2] # Evaluate if the ball collides with part of",
"err_vel = qvel_des - self.state[self.model.nq : self.model.nq + self._num_dof] #",
"the cup. :param verbose: print messages when ball is in",
"np.array([0.0, 0.63, 0.0, 1.27]) self.init_qpos[4] = -0.34 # angle of",
"this is a reference # state_des_cup = np.array([0.82521, 0, 1.4469])",
"\"ball\" and contact.geom2 == cup_inner_id c2 = body2_name == \"ball\"",
"pyrado.ValueErr(given=num_dof, eq_constraint=\"4 or 7\") def _create_task(self, task_args: dict) -> Task:",
"graph_file_name = \"wam_7dof_bic.xml\" self.qpos_des_init = init_qpos_des_7dof self.p_gains = wam_pgains_7dof self.d_gains",
"osp.join(pyrado.MUJOCO_ASSETS_DIR, graph_file_name) super().__init__(model_path, frame_skip, dt, max_steps, task_args) # Actual initial",
"joint_1_dryfriction=0.4, # dry friction coefficient of motor joint 1 [-]",
"None, ): \"\"\" Constructor :param num_dof: number of degrees of",
"= DesStateTask(spec, state_des, rew_fcn) return MaskedTask(self.spec, task, idcs) def _adapt_model_file(self,",
"self._qpos_des_init qvel_des = np.zeros_like(qpos_des) if self._num_dof == 4: np.add.at(qpos_des, [1,",
"ball is in the cup :return: `True` if the ball",
"return MaskedTask(self.spec, task, idcs) else: state_des = self.sim.data.get_site_xpos(\"cup_goal\") # this",
"7), depending on which Barrett WAM setup being used :param",
"in case of a negative step reward and no final",
"DesStateTask(spec, state_des, rew_fcn) # Wrap the masked DesStateTask to add",
"from pyrado.utils.input_output import print_cbt class WAMBallInCupSim(MujocoSimEnv, Serializable): \"\"\" WAM robotic",
"(including ball and cup) state_shape = np.concatenate([self.init_qpos, self.init_qvel, np.empty(3), np.empty(3)]).shape",
"0.0385)) xml_model = xml_model.replace(\"[size_cup]\", str(cup_scale * 0.038)) xml_model = xml_model.replace(\"[size_cup_inner]\",",
"== \"ball\" and ( body2_name in self._collision_bodies or contact.geom2 in",
"negative direction from center) xml_model = xml_model.replace(\"[pos_capsule_joint]\", str(-rope_length / 60))",
"desired parts of the cup. This causes the episode to",
"dict) -> Task: # Create a DesStateTask that masks everything",
"self._num_dof] err_vel = qvel_des - self.state[self.model.nq : self.model.nq + self._num_dof]",
"reference # state_des_cup = np.array([0.82521, 0, 1.4469]) if self._num_dof ==",
"self._num_dof], ball_pos=ball_pos, cup_pos=cup_goal, failed=mjsim_crashed or ball_collided or state_oob, ) def",
"np.zeros_like(qpos_des) if self._num_dof == 4: np.add.at(qpos_des, [1, 3], act[:2]) np.add.at(qvel_des,",
"= xml_model.replace(\"[pos_goal]\", str(0.1165 + (cup_scale - 1.0) * 0.0385)) xml_model",
"Space: # Observing the normalized time and optionally the cup",
"ARISING IN ANY WAY OUT OF THE USE OF THIS",
"4: return dict( cup_scale=1.0, # scaling factor for the radius",
"DesStateTask(spec, state_des, rew_fcn) return MaskedTask(self.spec, task, idcs) def _adapt_model_file(self, xml_model:",
"ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN",
"conditions are met: # 1. Redistributions of source code must",
"if task_args.get(\"sparse_rew_fcn\", False): # Create a task with binary reward",
"obs_lo.extend([-3.0, -3.0]) obs_up.extend([3.0, 3.0]) labels.extend([\"cup_x\", \"cup_z\"]) return BoxSpace(obs_lo, obs_up, labels=labels)",
"has the same shape as the init space (including ball",
"distance ball - cup; shouldn't move in y-direction R=task_args.get(\"R\", R_default),",
"# camera rotation around the axis in the plane azimuth=-90,",
":return: `True` if the ball is in the cup \"\"\"",
"AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN",
"from pyrado.spaces.singular import SingularStateSpace from pyrado.tasks.base import Task from pyrado.tasks.condition_only",
"SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS",
"else torque_space_wam_4dof @property def state_space(self) -> Space: # The state",
"import pyrado from pyrado.environments.barrett_wam import ( goal_pos_init_sim_4dof, goal_pos_init_sim_7dof, init_qpos_des_4dof, init_qpos_des_7dof,",
"to each motor joint and the first rope segment joint",
"= EnvSpec( self.spec.obs_space, self.spec.act_space, self.spec.state_space.subspace(self.spec.state_space.create_mask(idcs)), ) # init cup goal",
"= QuadrErrRewFcn( Q=task_args.get(\"Q_dev\", np.diag([2e-1, 1e-6, 5e0])), # Cartesian distance from",
"def _adapt_model_file(self, xml_model: str, domain_param: dict) -> str: # First",
"of the ball with the robot ball_collided = self.check_ball_collisions() if",
"bool: \"\"\" Check if an undesired collision with the ball",
"print messages when ball is in the cup :return: `True`",
"the init space (including ball and cup) state_shape = np.concatenate([self.init_qpos,",
"reward and no final cost on failing, this might result",
"num_dof == 4: graph_file_name = \"wam_4dof_bic.xml\" self.qpos_des_init = init_qpos_des_4dof self.p_gains",
"EnvSpec( self.spec.obs_space, self.spec.act_space, self.spec.state_space.subspace(self.spec.state_space.create_mask(idcs)), ) # init cup goal position",
"the cartesian ball distance # 2.) Deviation task: Desired state",
"# Note: the cup_goal is the mujoco site object marking",
"# id of the body to track elevation=-30, # camera",
"to 1e-6) ) else: raise pyrado.ValueErr(given=num_dof, eq_constraint=\"4 or 7\") def",
"USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED",
"joint_7_dryfriction=0.4, # dry friction coefficient of motor joint 7 [-]",
"conditions and the following disclaimer in the # documentation and/or",
"Each joint is at the top of each capsule (therefore",
"cup_scale is not None: # See [1, l.93-96] xml_model =",
"visualization component xml_model = xml_model.replace(\"[size_capsule_geom]\", str(rope_length / 72)) # Resolve",
"LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS",
"= wam_pgains_7dof self.d_gains = wam_dgains_7dof init_ball_pos = np.array([0.828, 0.0, 1.131])",
"cup and ball (the robot operates in the x-z plane).",
"mass # Observe the normalized time obs = [self._curr_step /",
"# Get current contact object contact = self.sim.data.contact[i] # Extract",
"FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO",
"INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF",
"self.p_gains * err_pos + self.d_gains * err_vel torque = self.torque_space.project_to(torque)",
"for collisions of the ball with the robot ball_collided =",
"task, controlled by a PD controller. .. note:: When using",
"coefficient of motor joint 4 [-] rope_damping=1e-4, # damping of",
"updates automatically at each step. # Note: sim.forward() + get_body_xpos()",
"domain_param) def _mujoco_step(self, act: np.ndarray) -> dict: assert self.act_space.contains(act, verbose=True)",
"== cup_inner_id if c1 or c2: if verbose: print_cbt(f\"The ball",
"qpos_des - self.state[: self._num_dof] err_vel = qvel_des - self.state[self.model.nq :",
"cup bottom plate else: self.init_qpos[:7] = np.array([0.0, 0.65, 0.0, 1.41,",
"that in case of a negative step reward and no",
"cup \"\"\" for i in range(self.sim.data.ncon): # Get current contact",
"undesired behavior. :param observe_ball: if `True`, include the 2-dim (x-z",
"\"\"\" Get the number of degrees of freedom. \"\"\" return",
"[-] joint_4_dryfriction=0.4, # dry friction coefficient of motor joint 4",
"self.spec.state_space.subspace(self.spec.state_space.create_mask(idcs)), ) # init cup goal position state_des = goal_pos_init_sim_7dof",
"collision :return: `True` if the ball collides with something else",
"False): # Create a task with binary reward return self._create_main_task(task_args)",
"sim.forward() + get_body_xpos() results in wrong output for state_des, as",
"Q=task_args.get(\"Q\", np.diag([2e1, 1e-4, 2e1])), # distance ball - cup; shouldn't",
"pyrado.utils.input_output import print_cbt class WAMBallInCupSim(MujocoSimEnv, Serializable): \"\"\" WAM robotic arm",
"False): \"\"\" Check if the ball is in the cup.",
":param verbose: print messages when ball is in the cup",
"motor joint 6 [-] joint_7_dryfriction=0.4, # dry friction coefficient of",
"= \"wam-bic\" def __init__( self, num_dof: int, frame_skip: int =",
"INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT",
"np.empty(3)]).shape state_lo, state_up = np.full(state_shape, -pyrado.inf), np.full(state_shape, pyrado.inf) # Ensure",
"= SingularStateSpace(self._init_state) else: # Add plus/minus one degree to each",
"1e-6) ) elif num_dof == 4: return dict( cup_scale=1.0, #",
"negative step reward and no final cost on failing, this",
"LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS",
"self.state[self.model.nq : self.model.nq + self._num_dof] # Compute the torques for",
"self._num_dof == 7 else act_space_bic_4dof @classmethod def get_nominal_domain_param(cls, num_dof: int",
"clip them to their max values torque = self.p_gains *",
"= dict( distance=2.7, trackbodyid=0, # id of the body to",
"actual stable initial position. This position would be reached after",
"self._collision_geom_ids ) if c1 or c2: if verbose: print_cbt( f\"Undesired",
"velocities return act_space_bic_7dof if self._num_dof == 7 else act_space_bic_4dof @classmethod",
"[1, 3, 5], act[3:]) # Compute the position and velocity",
"step size is the one from the mujoco config file",
"UNIVERSITY OF DARMSTADT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,",
"# Add plus/minus one degree to each motor joint and",
"= task_args.get(\"success_bonus\", 1) # Binary final reward task main_task =",
"following disclaimer. # 2. Redistributions in binary form must reproduce",
"self, num_dof: int, frame_skip: int = 4, dt: Optional[float] =",
"the mujoco config file multiplied by the number of frame",
"pyrado.environments.mujoco.base import MujocoSimEnv from pyrado.spaces.base import Space from pyrado.spaces.box import",
"construction \"\"\" Serializable._init(self, locals()) self.fixed_init_state = fixed_init_state self.observe_ball = observe_ball",
"observe_ball self.observe_cup = observe_cup # Initialize num DoF specific variables",
"self._num_dof] # Compute the torques for the PD controller and",
"of rope joints [N/s] (reasonable values are 6e-4 to 1e-6)",
"replace special domain parameters cup_scale = domain_param.pop(\"cup_scale\", None) rope_length =",
"def _mujoco_step(self, act: np.ndarray) -> dict: assert self.act_space.contains(act, verbose=True) #",
"direction from center) xml_model = xml_model.replace(\"[pos_capsule_joint]\", str(-rope_length / 60)) #",
"str(cup_scale * 0.038)) xml_model = xml_model.replace(\"[size_cup_inner]\", str(cup_scale * 0.03)) if",
"joints [N/s] (default value is small) joint_4_damping=0.05, # damping of",
"ExpQuadrErrRewFcn, QuadrErrRewFcn from pyrado.tasks.sequential import SequentialTasks from pyrado.utils.data_types import EnvSpec",
"step reward and no final cost on failing, this might",
"(this is normally checked by the task, but does not",
"main task ist done (successfully or not) dont_fail_after_succ_task = FinalRewTask(",
"or contact.geom1 in self._collision_geom_ids ) if c1 or c2: if",
"parameters return super()._adapt_model_file(xml_model, domain_param) def _mujoco_step(self, act: np.ndarray) -> dict:",
"0.1, 1.0, 1.0])[: self._num_dof] init_state_lo = self._init_state.copy() init_state_lo[: self._num_dof] -=",
"IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,",
"init space (including ball and cup) state_shape = np.concatenate([self.init_qpos, self.init_qvel,",
"stop_on_collision: bool = True, observe_ball: bool = False, observe_cup: bool",
"1.0])[: self._num_dof] init_state_lo = self._init_state.copy() init_state_lo[: self._num_dof] -= np.pi /",
"value is small) joint_2_damping=0.05, # damping of motor joints [N/s]",
"Adds a binary bonus when ball is catched [inactive by",
"0, 1e-2, 1e-2]) rew_fcn = ExpQuadrErrRewFcn( Q=task_args.get(\"Q\", np.diag([2e1, 1e-4, 2e1])),",
"or Technical University of Darmstadt, nor the names of its",
"without # modification, are permitted provided that the following conditions",
"return BoxSpace(state_lo, state_up) @property def obs_space(self) -> Space: # Observing",
"joint is at the top of each capsule (therefore negative",
"final reward task main_task = FinalRewTask( ConditionOnlyTask( spec, condition_fcn=self.check_ball_in_cup, is_success_condition=True,",
"ball is catched [inactive by default] return ParallelTasks( [ self._create_main_task(task_args),",
"# POSSIBILITY OF SUCH DAMAGE. import mujoco_py import numpy as",
"np.concatenate([self.init_qpos, self.init_qvel, np.empty(3), np.empty(3)]).shape state_lo, state_up = np.full(state_shape, -pyrado.inf), np.full(state_shape,",
"return ParallelTasks( [ self._create_main_task(task_args), self._create_deviation_task(task_args), self._create_main_task( dict( sparse_rew_fcn=True, success_bonus=task_args.get(\"success_bonus\", 0),",
"two (or three) parallel running task. # 1.) Main task:",
"OF THE # POSSIBILITY OF SUCH DAMAGE. import mujoco_py import",
"ZeroPerStepRewFcn, ExpQuadrErrRewFcn, QuadrErrRewFcn from pyrado.tasks.sequential import SequentialTasks from pyrado.utils.data_types import",
"if self._num_dof == 7 else np.diag([0, 0, 1e-2, 1e-2]) rew_fcn",
"the ball occurs. :param verbose: print messages on collision :return:",
"'b') # center of frame # print_cbt(f'cup xipos: {self.sim.data.get_body_xipos(\"cup\").copy()}', 'b')",
"segment relative to the cup bottom plate # Set the",
"# Cartesian ball position spec = EnvSpec( self.spec.obs_space, self.spec.act_space, self.spec.state_space.subspace(self.spec.state_space.create_mask(idcs)),",
"self.stop_on_collision else False # If state is out of bounds",
"super().__init__(model_path, frame_skip, dt, max_steps, task_args) # Actual initial joint position",
"to the cup bottom plate else: self.init_qpos[:7] = np.array([0.0, 0.65,",
"# joint space distance from init pose, interferes with R_default",
"Desired state task for the cartesian- and joint deviation from",
"self.act_space.contains(act, verbose=True) # Get the desired positions and velocities for",
"and updates automatically at each step. # Note: sim.forward() +",
"DISCLAIMED. IN NO EVENT SHALL <NAME>, HONDA RESEARCH INSTITUTE EUROPE",
"end. Keep in mind that in case of a negative",
"observation :param observe_cup: if `True`, include the 2-dim (x-z plane)",
"= stop_on_collision self.camera_config = dict( distance=2.7, trackbodyid=0, # id of",
"from pyrado.utils.data_types import EnvSpec from pyrado.utils.input_output import print_cbt class WAMBallInCupSim(MujocoSimEnv,",
"the mujoco site object marking the goal position for the",
"FinalRewTask( GoallessTask(spec, ZeroPerStepRewFcn()), mode=FinalRewMode(always_negative=True), factor=factor, ) # Augment the binary",
"/ 72)) # Resolve mesh directory and replace the remaining",
"space of joint torques. \"\"\" return torque_space_wam_7dof if self._num_dof ==",
"as the init space (including ball and cup) state_shape =",
"== 7: graph_file_name = \"wam_7dof_bic.xml\" self.qpos_des_init = init_qpos_des_7dof self.p_gains =",
"cup position R=task_args.get( \"R_dev\", np.zeros((self.act_space.shape[0], self.act_space.shape[0])) ), # joint space",
"other materials provided with the distribution. # 3. Neither the",
"deterministic, fixed initial state :param stop_on_collision: set the `failed` flag",
"# not every geom has a name self._collision_geom_ids = [self.model._geom_name2id[name]",
"get_body_xpos() results in wrong output for state_des, as sim has",
"this is a reference # state_des_ball = self.sim.data.get_site_xpos(\"cup_goal\") # this",
"damping of motor joints [N/s] (default value is small) joint_5_damping=0.05,",
"Redistributions of source code must retain the above copyright #",
"CONTRIBUTORS \"AS IS\" AND # ANY EXPRESS OR IMPLIED WARRANTIES,",
"each step. # Note: sim.forward() + get_body_xpos() results in wrong",
"bounds (this is normally checked by the task, but does",
"# # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS",
"plane) cartesian ball position into the observation :param observe_cup: if",
"task = DesStateTask(spec, state_des, rew_fcn) return MaskedTask(self.spec, task, idcs) def",
"a name self._collision_geom_ids = [self.model._geom_name2id[name] for name in [\"cup_geom1\", \"cup_geom2\"]]",
"been updated to # init_space.sample(), which is first called in",
"DesStateTask from pyrado.tasks.final_reward import BestStateFinalRewTask, FinalRewTask, FinalRewMode from pyrado.tasks.goalless import",
"LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION)",
"{self.sim.data.get_body_xipos(\"cup\").copy()}', 'b') # center of mass # Observe the normalized",
"\"wam/shoulder_pitch_link\", \"wam/upper_arm_link\", \"wam/forearm_link\", \"wrist_palm_link\", \"wam/wrist_pitch_link\", \"wam/wrist_yaw_link\", ] if self._num_dof ==",
"4: graph_file_name = \"wam_4dof_bic.xml\" self.qpos_des_init = init_qpos_des_4dof self.p_gains = wam_pgains_4dof",
"list of conditions and the following disclaimer. # 2. Redistributions",
"\"wrist_palm_link\", \"wam/wrist_pitch_link\", \"wam/wrist_yaw_link\", ] if self._num_dof == 4: self._collision_bodies =",
"init_ball_pos = np.array([0.723, 0.0, 1.168]) init_cup_goal = goal_pos_init_sim_4dof elif num_dof",
"qvel=qvel[: self._num_dof], ball_pos=ball_pos, cup_pos=cup_goal, failed=mjsim_crashed or ball_collided or state_oob, )",
"HOLDERS AND CONTRIBUTORS \"AS IS\" AND # ANY EXPRESS OR",
"of freedom. \"\"\" return self._num_dof @property def torque_space(self) -> Space:",
"# PD controller to stabilize at self._qpos_des_init. # The initial",
"1.0) * 0.0385)) xml_model = xml_model.replace(\"[size_cup]\", str(cup_scale * 0.038)) xml_model",
"materials provided with the distribution. # 3. Neither the name",
"dt: by default the time step size is the one",
"in the cup \"\"\" for i in range(self.sim.data.ncon): # Get",
"6 [-] joint_7_dryfriction=0.4, # dry friction coefficient of motor joint",
"to add a bonus for the best state in the",
"xml_model.replace(\"[scale_mesh]\", str(cup_scale * 0.001)) xml_model = xml_model.replace(\"[pos_mesh]\", str(0.055 - (cup_scale",
"raise pyrado.ValueErr(given=num_dof, eq_constraint=\"4 or 7\") def _create_task(self, task_args: dict) ->",
"Darmstadt. # All rights reserved. # # Redistribution and use",
"OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE #",
"permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT",
"this can be overwritten. Possible use case if if you",
"xml_model = xml_model.replace(\"[pos_goal]\", str(0.1165 + (cup_scale - 1.0) * 0.0385))",
"DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE",
"factor=task_args.get(\"final_factor\", 0.05 * self.max_steps), ) def _create_deviation_task(self, task_args: dict) ->",
"EnvSpec from pyrado.utils.input_output import print_cbt class WAMBallInCupSim(MujocoSimEnv, Serializable): \"\"\" WAM",
"frame_skip: int = 4, dt: Optional[float] = None, max_steps: int",
"Space: \"\"\" Get the space of joint torques. \"\"\" return",
"with the distribution. # 3. Neither the name of <NAME>,",
"pyrado.tasks.sequential import SequentialTasks from pyrado.utils.data_types import EnvSpec from pyrado.utils.input_output import",
"Space: # The state space has the same shape as",
"provided with the distribution. # 3. Neither the name of",
"or state_oob, ) def check_ball_collisions(self, verbose: bool = False) ->",
"messages when ball is in the cup :return: `True` if",
"the position and velocity errors err_pos = qpos_des - self.state[:",
"or 7), depending on which Barrett WAM setup being used",
"cartesian ball position into the observation :param observe_cup: if `True`,",
"AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT",
"small) joint_1_dryfriction=0.4, # dry friction coefficient of motor joint 1",
"sim has not been updated to # init_space.sample(), which is",
") # Augment the binary task with an endless dummy",
"osp from init_args_serializer import Serializable from typing import Optional import",
"First replace special domain parameters cup_scale = domain_param.pop(\"cup_scale\", None) rope_length",
"init_cup_goal = goal_pos_init_sim_7dof else: raise pyrado.ValueErr(given=num_dof, eq_constraint=\"4 or 7\") model_path",
"# center of mass # Observe the normalized time obs",
"elevation=-30, # camera rotation around the axis in the plane",
"include the 2-dim (x-z plane) cartesian cup position into the",
"use copy(), state_des coming from MuJoCo is a reference and",
"-> dict: if num_dof == 7: return dict( cup_scale=1.0, #",
"the rollout return BestStateFinalRewTask( MaskedTask(self.spec, task, idcs), factor=task_args.get(\"final_factor\", 0.05 *",
"after the main task ist done (successfully or not) dont_fail_after_succ_task",
"AND ON ANY THEORY OF LIABILITY, WHETHER # IN CONTRACT,",
"the radius of the cup [-] (should be >0.65) rope_length=0.41,",
"joint 5 [-] joint_6_dryfriction=0.4, # dry friction coefficient of motor",
"cup_goal = self.sim.data.get_site_xpos(\"cup_goal\").copy() self.state = np.concatenate([qpos, qvel, ball_pos, cup_goal]) #",
"else: raise pyrado.ValueErr(given=num_dof, eq_constraint=\"4 or 7\") model_path = osp.join(pyrado.MUJOCO_ASSETS_DIR, graph_file_name)",
"dont_fail_after_succ_task)) return MaskedTask(self.spec, task, idcs) else: state_des = self.sim.data.get_site_xpos(\"cup_goal\") #",
"for the ball. It is not identical # to the",
"is the one from the mujoco config file multiplied by",
") task = DesStateTask(spec, state_des, rew_fcn) return MaskedTask(self.spec, task, idcs)",
"= 4, dt: Optional[float] = None, max_steps: int = pyrado.inf,",
"4 [-] rope_damping=1e-4, # damping of rope joints [N/s] (reasonable",
"self.fixed_init_state: self._init_space = SingularStateSpace(self._init_state) else: # Add plus/minus one degree",
"import BoxSpace from pyrado.spaces.singular import SingularStateSpace from pyrado.tasks.base import Task",
"1e-2]) rew_fcn = ExpQuadrErrRewFcn( Q=task_args.get(\"Q\", np.diag([2e1, 1e-4, 2e1])), # distance",
"= np.array([0.0, 0.65, 0.0, 1.41, 0.0, -0.28, -1.57]) self.init_qpos[7] =",
"max_steps, task_args) # Actual initial joint position (when the WAM",
"= BoxSpace(init_state_lo, init_state_up) # Bodies to check fo collision self._collision_bodies",
"2. Redistributions in binary form must reproduce the above copyright",
"self.sim.step() mjsim_crashed = False except mujoco_py.builder.MujocoException: # When MuJoCo recognized",
"of degrees of freedom (4 or 7), depending on which",
"small) joint_3_damping=0.05, # damping of motor joints [N/s] (default value",
"one from the mujoco config file multiplied by the number",
"the axis in the plane azimuth=-90, # camera rotation around",
"THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND # ANY",
"\"wam_7dof_bic.xml\" self.qpos_des_init = init_qpos_des_7dof self.p_gains = wam_pgains_7dof self.d_gains = wam_dgains_7dof",
"dict( cup_scale=1.0, # scaling factor for the radius of the",
"mode=FinalRewMode(always_negative=True), factor=factor, ) # Augment the binary task with an",
"bool = False): \"\"\" Check if the ball is in",
"joint_2_dryfriction=0.4, # dry friction coefficient of motor joint 2 [-]",
"and cup) state_shape = np.concatenate([self.init_qpos, self.init_qvel, np.empty(3), np.empty(3)]).shape state_lo, state_up",
"radius of the cup [-] (should be >0.65) rope_length=0.41, #",
"value, this can be overwritten. Possible use case if if",
"instabilities in the simulation, it simply kills it. # Instead,",
"if verbose: print_cbt(f\"The ball is in the cup at time",
"and the following disclaimer in the # documentation and/or other",
"self._num_dof] state_up[: self._num_dof] = wam_q_limits_up_7dof[: self._num_dof] return BoxSpace(state_lo, state_up) @property",
"`_mujoco_step()` to true, if the ball collides with something else",
"in wrong output for state_des, as sim has not been",
"we want the episode to end with a failure. mjsim_crashed",
"def check_ball_collisions(self, verbose: bool = False) -> bool: \"\"\" Check",
"config file multiplied by the number of frame skips (legacy",
"# 2. Redistributions in binary form must reproduce the above",
"0.03)) if rope_length is not None: # The rope consists",
"idcs), factor=task_args.get(\"final_factor\", 0.05 * self.max_steps), ) def _create_deviation_task(self, task_args: dict)",
"# Extract the (x, z) cartesian position of cup and",
":param max_steps: max number of simulation time steps :param fixed_init_state:",
"Evaluate if the ball collides with part of the WAM",
"of a negative step reward and no final cost on",
"than the desired parts of the cup. This causes the",
"in the # documentation and/or other materials provided with the",
"from MuJoCo is a reference and updates automatically at each",
"of cup and ball (the robot operates in the x-z",
"# # Redistribution and use in source and binary forms,",
"controlled by a PD controller. .. note:: When using the",
"IS\" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT",
"self.sim.data.contact[i] # Extract body-id and body-name of both contact geoms",
"torque_space_wam_7dof if self._num_dof == 7 else torque_space_wam_4dof @property def state_space(self)",
"= FinalRewTask( ConditionOnlyTask( spec, condition_fcn=self.check_ball_in_cup, is_success_condition=True, ), mode=FinalRewMode(always_positive=True), factor=factor, )",
"position) if num_dof == 4: self.init_qpos[:4] = np.array([0.0, 0.63, 0.0,",
"self.check_ball_collisions() if self.stop_on_collision else False # If state is out",
"if task_args.get(\"sparse_rew_fcn\", False): factor = task_args.get(\"success_bonus\", 1) # Binary final",
"We access a private attribute since a method like 'model.geom_names[geom_id]'",
"is not None: # See [1, l.93-96] xml_model = xml_model.replace(\"[scale_mesh]\",",
"goal_pos_init_sim_7dof else: raise pyrado.ValueErr(given=num_dof, eq_constraint=\"4 or 7\") model_path = osp.join(pyrado.MUJOCO_ASSETS_DIR,",
"collision of {body1_name} and {body2_name} detected!\", \"y\", ) return True",
"-> bool: \"\"\" Check if an undesired collision with the",
"Binary Bonus: Adds a binary bonus when ball is catched",
"joints [N/s] (default value is small) joint_3_damping=0.05, # damping of",
"# 2.) Deviation task: Desired state task for the cartesian-",
"labels = [0.0], [1.0], [\"t\"] if self.observe_ball: obs_lo.extend([-3.0, -3.0]) obs_up.extend([3.0,",
"* 0.03)) if rope_length is not None: # The rope",
"cup_inner_id if c1 or c2: if verbose: print_cbt(f\"The ball is",
"7 [-] rope_damping=1e-4, # damping of rope joints [N/s] (reasonable",
"verbose: print messages when ball is in the cup :return:",
"sparse_rew_fcn=True, success_bonus=task_args.get(\"success_bonus\", 0), ) ), ] ) def _create_main_task(self, task_args:",
"from OpenAI environments). By passing an explicit `dt` value, this",
"i in range(self.sim.data.ncon): # Get current contact object contact =",
"the ball. It is not identical # to the coordinate",
"from pyrado.tasks.sequential import SequentialTasks from pyrado.utils.data_types import EnvSpec from pyrado.utils.input_output",
"the ball is in the cup. :param verbose: print messages",
"= FinalRewTask( GoallessTask(spec, ZeroPerStepRewFcn()), mode=FinalRewMode(always_negative=True), factor=factor, ) # Augment the",
"source and binary forms, with or without # modification, are",
"time steps :param fixed_init_state: enables/disables deterministic, fixed initial state :param",
"DARMSTADT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL,",
"controller. .. note:: When using the `reset()` function, always pass",
"\"wam_4dof_bic.xml\" self.qpos_des_init = init_qpos_des_4dof self.p_gains = wam_pgains_4dof self.d_gains = wam_dgains_4dof",
"INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER",
"since a method like 'model.geom_names[geom_id]' cannot be used because #",
"eq_constraint=\"4 or 7\") def _create_task(self, task_args: dict) -> Task: if",
"state task for the cartesian- and joint deviation from the",
"self._num_dof] init_state_lo = self._init_state.copy() init_state_lo[: self._num_dof] -= np.pi / 180",
"# documentation and/or other materials provided with the distribution. #",
"the plane azimuth=-90, # camera rotation around the camera's vertical",
"dummy task, to avoid early stopping task = SequentialTasks((main_task, dont_fail_after_succ_task))",
"damping of motor joints [N/s] (default value is small) joint_2_damping=0.05,",
"dict( distance=2.7, trackbodyid=0, # id of the body to track",
"or promote products derived from this software without # specific",
"(the robot operates in the x-z plane). # Note: the",
"(collision bodies) # or the connection of WAM and cup",
"task construction \"\"\" Serializable._init(self, locals()) self.fixed_init_state = fixed_init_state self.observe_ball =",
"if verbose: print_cbt( f\"Undesired collision of {body1_name} and {body2_name} detected!\",",
"know that you recorded a trajectory with a specific `dt`.",
"\"\"\" return torque_space_wam_7dof if self._num_dof == 7 else torque_space_wam_4dof @property",
"initial position of the ball in cartesian coordinates self._init_state =",
"SingularStateSpace(self._init_state) else: # Add plus/minus one degree to each motor",
"collides with something else than the desired parts of the",
"np.empty(3), np.empty(3)]).shape state_lo, state_up = np.full(state_shape, -pyrado.inf), np.full(state_shape, pyrado.inf) #",
"binary bonus when ball is catched [inactive by default] return",
"(x-z plane) cartesian cup position into the observation :param task_args:",
"xml_model = xml_model.replace(\"[size_cup_inner]\", str(cup_scale * 0.03)) if rope_length is not",
"self._collision_bodies or contact.geom1 in self._collision_geom_ids ) if c1 or c2:",
"the normalized time and optionally the cup and ball position",
"\"wam-bic\" def __init__( self, num_dof: int, frame_skip: int = 4,",
"init_qpos_des_4dof, init_qpos_des_7dof, act_space_bic_4dof, act_space_bic_7dof, wam_q_limits_up_7dof, wam_q_limits_lo_7dof, torque_space_wam_4dof, torque_space_wam_7dof, wam_pgains_7dof, wam_dgains_7dof,",
"The state space has the same shape as the init",
"body1_name == \"ball\" and contact.geom2 == cup_inner_id c2 = body2_name",
"number of simulation frames for which the same action is",
"returned by `_mujoco_step()` to true, if the ball collides with",
"[inactive by default] return ParallelTasks( [ self._create_main_task(task_args), self._create_deviation_task(task_args), self._create_main_task( dict(",
"from init cup position R=task_args.get( \"R_dev\", np.zeros((self.act_space.shape[0], self.act_space.shape[0])) ), #",
"EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE",
"pyrado.tasks.final_reward import BestStateFinalRewTask, FinalRewTask, FinalRewMode from pyrado.tasks.goalless import GoallessTask from",
"DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,",
"= body1_name == \"ball\" and contact.geom2 == cup_inner_id c2 =",
"xpos: {self.sim.data.get_body_xpos(\"cup\").copy()}', 'b') # center of frame # print_cbt(f'cup xipos:",
"state in the rollout return BestStateFinalRewTask( MaskedTask(self.spec, task, idcs), factor=task_args.get(\"final_factor\",",
"dict) -> Task: if task_args.get(\"sparse_rew_fcn\", False): # Create a task",
"pyrado.environments.barrett_wam import ( goal_pos_init_sim_4dof, goal_pos_init_sim_7dof, init_qpos_des_4dof, init_qpos_des_7dof, act_space_bic_4dof, act_space_bic_7dof, wam_q_limits_up_7dof,",
"= self.sim.data.get_site_xpos(\"cup_goal\") # this is a reference # state_des_cup =",
"a method like 'model.geom_names[geom_id]' cannot be used because # not",
"task, idcs) def _adapt_model_file(self, xml_model: str, domain_param: dict) -> str:",
"not None: # The rope consists of 30 capsules xml_model",
"in the `dict` returned by `_mujoco_step()` to true, if the",
"np.full(state_shape, -pyrado.inf), np.full(state_shape, pyrado.inf) # Ensure that joint limits of",
"# dry friction coefficient of motor joint 5 [-] joint_6_dryfriction=0.4,",
"you recorded a trajectory with a specific `dt`. :param max_steps:",
"an endless dummy task, to avoid early stopping task =",
"or c2: if verbose: print_cbt( f\"Undesired collision of {body1_name} and",
"[N/s] (default value is small) joint_3_damping=0.05, # damping of motor",
"environments). By passing an explicit `dt` value, this can be",
"used because # not every geom has a name self._collision_geom_ids",
"= wam_pgains_4dof self.d_gains = wam_dgains_4dof init_ball_pos = np.array([0.723, 0.0, 1.168])",
"motor joints [N/s] (default value is small) joint_1_dryfriction=0.4, # dry",
"reference and updates automatically at each step. # Note: sim.forward()",
"the robot self.sim.data.qfrc_applied[: self._num_dof] = torque # Call MuJoCo try:",
"to check fo collision self._collision_bodies = [ \"wam/base_link\", \"wam/shoulder_yaw_link\", \"wam/shoulder_pitch_link\",",
"torque_space(self) -> Space: \"\"\" Get the space of joint torques.",
"self._num_dof == 7 else np.array([0.758, 0, 1.5]) # state_des =",
"6e-4 to 1e-6) ) else: raise pyrado.ValueErr(given=num_dof, eq_constraint=\"4 or 7\")",
"MujocoSimEnv from pyrado.spaces.base import Space from pyrado.spaces.box import BoxSpace from",
"MuJoCo try: self.sim.step() mjsim_crashed = False except mujoco_py.builder.MujocoException: # When",
"# print_cbt(f'cup xpos: {self.sim.data.get_body_xpos(\"cup\").copy()}', 'b') # center of frame #",
"= True, observe_ball: bool = False, observe_cup: bool = False,",
"self.model.geom_bodyid[contact.geom2] body2_name = self.model.body_names[body2] # Evaluate if the ball collides",
"PD controller. .. note:: When using the `reset()` function, always",
"ARE # DISCLAIMED. IN NO EVENT SHALL <NAME>, HONDA RESEARCH",
"from pyrado.tasks.parallel import ParallelTasks from pyrado.tasks.reward_functions import ZeroPerStepRewFcn, ExpQuadrErrRewFcn, QuadrErrRewFcn",
"[N/s] (default value is small) joint_6_damping=0.05, # damping of motor",
"R_default from _create_main_task ) task = DesStateTask(spec, state_des, rew_fcn) return",
"want the episode to end with a failure. mjsim_crashed =",
"ball_pos = self.sim.data.get_body_xpos(\"ball\").copy() cup_goal = self.sim.data.get_site_xpos(\"cup_goal\").copy() self.state = np.concatenate([qpos, qvel,",
"self.spec.state_space.subspace(self.spec.state_space.create_mask(idcs)), ) # If we do not use copy(), state_des",
"the robot ball_collided = self.check_ball_collisions() if self.stop_on_collision else False #",
"self._curr_step == 0: # print_cbt(f'cup xpos: {self.sim.data.get_body_xpos(\"cup\").copy()}', 'b') # center",
"1.5]) # state_des = np.concatenate([state_des_ball, state_des_cup]) R_default = np.diag([0, 0,",
"xml_model: str, domain_param: dict) -> str: # First replace special",
"distance from init cup position R=task_args.get( \"R_dev\", np.zeros((self.act_space.shape[0], self.act_space.shape[0])) ),",
"friction coefficient of motor joint 4 [-] joint_5_dryfriction=0.4, # dry",
"if self._curr_step == 0: # print_cbt(f'cup xpos: {self.sim.data.get_body_xpos(\"cup\").copy()}', 'b') #",
"task_args.get(\"sparse_rew_fcn\", False): # Create a task with binary reward return",
"xml_model.replace(\"[size_cup]\", str(cup_scale * 0.038)) xml_model = xml_model.replace(\"[size_cup_inner]\", str(cup_scale * 0.03))",
"joints [N/s] (default value is small) joint_7_damping=0.05, # damping of",
"factor=factor, ) # Yield -1 on fail after the main",
"Technical University of Darmstadt, nor the names of its contributors",
"results in a multiplier of the time step size `dt`",
"mask) state_oob = False if self.state_space.contains(self.state) else True return dict(",
"Bodies to check fo collision self._collision_bodies = [ \"wam/base_link\", \"wam/shoulder_yaw_link\",",
"relative to the cup bottom plate # Set the actual",
"default] return ParallelTasks( [ self._create_main_task(task_args), self._create_deviation_task(task_args), self._create_main_task( dict( sparse_rew_fcn=True, success_bonus=task_args.get(\"success_bonus\",",
"you know that you recorded a trajectory with a specific",
"Ensure that joint limits of the arm are not reached",
"method like 'model.geom_names[geom_id]' cannot be used because # not every",
"the rigid body object 'cup' if self.observe_ball: obs.extend([state[-3], state[-1]]) if",
") # If we do not use copy(), state_des coming",
"task: Desired state task for the cartesian- and joint deviation",
"= np.array([0.0, 0.63, 0.0, 1.27]) self.init_qpos[4] = -0.34 # angle",
"recognized instabilities in the simulation, it simply kills it. #",
"body1_name = self.model.body_names[body1] body2 = self.model.geom_bodyid[contact.geom2] body2_name = self.model.body_names[body2] #",
"capsules xml_model = xml_model.replace(\"[pos_capsule]\", str(rope_length / 30)) # Each joint",
"[N/s] (default value is small) joint_2_damping=0.05, # damping of motor",
"7 else goal_pos_init_sim_4dof rew_fcn = QuadrErrRewFcn( Q=task_args.get(\"Q_dev\", np.diag([2e-1, 1e-6, 5e0])),",
"DesStateTask to add a bonus for the best state in",
"a private attribute since a method like 'model.geom_names[geom_id]' cannot be",
"cup :return: `True` if the ball is in the cup",
"str(0.1165 + (cup_scale - 1.0) * 0.0385)) xml_model = xml_model.replace(\"[size_cup]\",",
"dt: Optional[float] = None, max_steps: int = pyrado.inf, fixed_init_state: bool",
"Redistribution and use in source and binary forms, with or",
"joint is really unreliable for 7 dof, thus punish more",
"joint_2_damping=0.05, # damping of motor joints [N/s] (default value is",
"xipos: {self.sim.data.get_body_xipos(\"cup\").copy()}', 'b') # center of mass # Observe the",
"from the init position # 3.) Binary Bonus: Adds a",
"that the following conditions are met: # 1. Redistributions of",
"robotic arm from Barrett technologies for the ball-in-the-cup task, controlled",
"robot operates in the x-z plane). # Note: the cup_goal",
"observe(self, state: np.ndarray) -> np.ndarray: # TODO: Debug print-outs, should",
"int = pyrado.inf, fixed_init_state: bool = True, stop_on_collision: bool =",
"# Create a task with binary reward return self._create_main_task(task_args) else:",
"and # Technical University of Darmstadt. # All rights reserved.",
"if self._num_dof == 7 else np.array([0.758, 0, 1.5]) # state_des",
"arm are not reached (5 deg safety margin) state_lo[: self._num_dof]",
"[\"t\"] if self.observe_ball: obs_lo.extend([-3.0, -3.0]) obs_up.extend([3.0, 3.0]) labels.extend([\"ball_x\", \"ball_z\"]) if",
"False def check_ball_in_cup(self, *args, verbose: bool = False): \"\"\" Check",
"class WAMBallInCupSim(MujocoSimEnv, Serializable): \"\"\" WAM robotic arm from Barrett technologies",
"-> Task: idcs = list(range(self.state_space.flat_dim - 3, self.state_space.flat_dim)) # Cartesian",
"1, 0.5, 1.0, 0.1, 1.0, 1.0])[: self._num_dof] init_state_lo = self._init_state.copy()",
"[self.model._geom_name2id[name] for name in [\"cup_geom1\", \"cup_geom2\"]] self.stop_on_collision = stop_on_collision self.camera_config",
"not reached (5 deg safety margin) state_lo[: self._num_dof] = wam_q_limits_lo_7dof[:",
"cup and ball position obs_lo, obs_up, labels = [0.0], [1.0],",
"rights reserved. # # Redistribution and use in source and",
"== 4: return dict( cup_scale=1.0, # scaling factor for the",
"self.init_qpos[7] = -0.21 # angle of the first rope segment",
"from Barrett technologies for the ball-in-the-cup task, controlled by a",
"7 else act_space_bic_4dof @classmethod def get_nominal_domain_param(cls, num_dof: int = 7)",
"\"wam/base_link\", \"wam/shoulder_yaw_link\", \"wam/shoulder_pitch_link\", \"wam/upper_arm_link\", \"wam/forearm_link\", \"wrist_palm_link\", \"wam/wrist_pitch_link\", \"wam/wrist_yaw_link\", ] if",
"simulation time steps :param fixed_init_state: enables/disables deterministic, fixed initial state",
"motor joint 7 [-] rope_damping=1e-4, # damping of rope joints",
"MaskedTask(self.spec, task, idcs) def _adapt_model_file(self, xml_model: str, domain_param: dict) ->",
"frames for which the same action is held, results in",
"1e-2, 1e-2]) rew_fcn = ExpQuadrErrRewFcn( Q=task_args.get(\"Q\", np.diag([2e1, 1e-4, 2e1])), #",
"from pyrado.tasks.masked import MaskedTask from pyrado.tasks.parallel import ParallelTasks from pyrado.tasks.reward_functions",
"deg safety margin) state_lo[: self._num_dof] = wam_q_limits_lo_7dof[: self._num_dof] state_up[: self._num_dof]",
"When MuJoCo recognized instabilities in the simulation, it simply kills",
"= None, max_steps: int = pyrado.inf, fixed_init_state: bool = True,",
"self.sim.data.get_body_xpos(\"ball\").copy() cup_goal = self.sim.data.get_site_xpos(\"cup_goal\").copy() self.state = np.concatenate([qpos, qvel, ball_pos, cup_goal])",
"the time step size is the one from the mujoco",
"with part of the WAM (collision bodies) # or the",
"disclaimer in the # documentation and/or other materials provided with",
"False, task_args: Optional[dict] = None, ): \"\"\" Constructor :param num_dof:",
"CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) #",
"ball_pos=ball_pos, cup_pos=cup_goal, failed=mjsim_crashed or ball_collided or state_oob, ) def check_ball_collisions(self,",
"of the cup \"\"\" for i in range(self.sim.data.ncon): # Get",
"ball in cartesian coordinates self._init_state = np.concatenate([self.init_qpos, self.init_qvel, init_ball_pos, init_cup_goal])",
"= True, stop_on_collision: bool = True, observe_ball: bool = False,",
"False except mujoco_py.builder.MujocoException: # When MuJoCo recognized instabilities in the",
"distance=2.7, trackbodyid=0, # id of the body to track elevation=-30,",
"task for the cartesian- and joint deviation from the init",
"by the task, but does not work because of the",
"small) joint_5_damping=0.05, # damping of motor joints [N/s] (default value",
"dict) -> Task: idcs = list(range(self.state_space.flat_dim - 3, self.state_space.flat_dim)) #",
"(4 or 7), depending on which Barrett WAM setup being",
"str(cup_scale * 0.001)) xml_model = xml_model.replace(\"[pos_mesh]\", str(0.055 - (cup_scale -",
"cup goal position state_des = goal_pos_init_sim_7dof if self._num_dof == 7",
"the WAM moved to the home position) if num_dof ==",
"verbose: bool = False) -> bool: \"\"\" Check if an",
"is small) joint_1_dryfriction=0.4, # dry friction coefficient of motor joint",
"state_lo, state_up = np.full(state_shape, -pyrado.inf), np.full(state_shape, pyrado.inf) # Ensure that",
"= xml_model.replace(\"[size_cup_inner]\", str(cup_scale * 0.03)) if rope_length is not None:",
"the cup bottom plate else: self.init_qpos[:7] = np.array([0.0, 0.65, 0.0,",
"friction coefficient of motor joint 2 [-] joint_3_dryfriction=0.4, # dry",
"in the cup at time step {self.curr_step}.\", \"y\") return True",
"segment relative to the cup bottom plate else: self.init_qpos[:7] =",
"If we do not use copy(), state_des coming from MuJoCo",
"in the simulation, it simply kills it. # Instead, we",
"from init_args_serializer import Serializable from typing import Optional import pyrado",
"Task: # Create a DesStateTask that masks everything but the",
"goal_pos_init_sim_7dof, init_qpos_des_4dof, init_qpos_des_7dof, act_space_bic_4dof, act_space_bic_7dof, wam_q_limits_up_7dof, wam_q_limits_lo_7dof, torque_space_wam_4dof, torque_space_wam_7dof, wam_pgains_7dof,",
"pyrado.spaces.box import BoxSpace from pyrado.spaces.singular import SingularStateSpace from pyrado.tasks.base import",
"Europe GmbH, # or Technical University of Darmstadt, nor the",
"# See [1, l.93-96] xml_model = xml_model.replace(\"[scale_mesh]\", str(cup_scale * 0.001))",
"at self._qpos_des_init. # The initial position of the ball in",
"dry friction coefficient of motor joint 7 [-] rope_damping=1e-4, #",
"values are 6e-4 to 1e-6) ) elif num_dof == 4:",
"= osp.join(pyrado.MUJOCO_ASSETS_DIR, graph_file_name) super().__init__(model_path, frame_skip, dt, max_steps, task_args) # Actual",
"self._create_main_task( dict( sparse_rew_fcn=True, success_bonus=task_args.get(\"success_bonus\", 0), ) ), ] ) def",
"5], act[:3]) np.add.at(qvel_des, [1, 3, 5], act[3:]) # Compute the",
"<NAME>, Honda Research Institute Europe GmbH, and # Technical University",
"self.state[: self._num_dof] err_vel = qvel_des - self.state[self.model.nq : self.model.nq +",
"USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE #",
"component xml_model = xml_model.replace(\"[size_capsule_geom]\", str(rope_length / 72)) # Resolve mesh",
"has a name self._collision_geom_ids = [self.model._geom_name2id[name] for name in [\"cup_geom1\",",
"an explicit `dt` value, this can be overwritten. Possible use",
"1.0, 0.1, 1.0, 1.0])[: self._num_dof] init_state_lo = self._init_state.copy() init_state_lo[: self._num_dof]",
"not been updated to # init_space.sample(), which is first called",
"task_args: dict) -> Task: if task_args.get(\"sparse_rew_fcn\", False): # Create a",
"= domain_param.pop(\"cup_scale\", None) rope_length = domain_param.pop(\"rope_length\", None) if cup_scale is",
"center) xml_model = xml_model.replace(\"[pos_capsule_joint]\", str(-rope_length / 60)) # Pure visualization",
"for the selected joints qpos_des = self.qpos_des_init.copy() # the desired",
"because of the mask) state_oob = False if self.state_space.contains(self.state) else",
"numpy as np import os.path as osp from init_args_serializer import",
"that masks everything but the ball position idcs = list(range(self.state_space.flat_dim",
"torque_space_wam_7dof, wam_pgains_7dof, wam_dgains_7dof, wam_pgains_4dof, wam_dgains_4dof, ) from pyrado.environments.mujoco.base import MujocoSimEnv",
"body2_name = self.model.body_names[body2] # Evaluate if the ball collides with",
"1.0, 0.1, 1.0, 1.0])[: self._num_dof] self._init_space = BoxSpace(init_state_lo, init_state_up) #",
"time step {self.curr_step}.\", \"y\") return True return False def observe(self,",
"FinalRewTask( ConditionOnlyTask( spec, condition_fcn=self.check_ball_in_cup, is_success_condition=True, ), mode=FinalRewMode(always_positive=True), factor=factor, ) #",
"position state_des = goal_pos_init_sim_7dof if self._num_dof == 7 else goal_pos_init_sim_4dof",
"_create_main_task ) task = DesStateTask(spec, state_des, rew_fcn) return MaskedTask(self.spec, task,",
"OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED",
"the masked DesStateTask to add a bonus for the best",
"mujoco site object marking the goal position for the ball.",
"self.max_steps] # Extract the (x, z) cartesian position of cup",
"the number of frame skips (legacy from OpenAI environments). By",
"THEORY OF LIABILITY, WHETHER # IN CONTRACT, STRICT LIABILITY, OR",
"c2: if verbose: print_cbt(f\"The ball is in the cup at",
"to the robot self.sim.data.qfrc_applied[: self._num_dof] = torque # Call MuJoCo",
"goal_pos_init_sim_4dof elif num_dof == 7: graph_file_name = \"wam_7dof_bic.xml\" self.qpos_des_init =",
"the best state in the rollout return BestStateFinalRewTask( MaskedTask(self.spec, task,",
"center of frame # print_cbt(f'cup xipos: {self.sim.data.get_body_xipos(\"cup\").copy()}', 'b') # center",
"enables/disables deterministic, fixed initial state :param stop_on_collision: set the `failed`",
"position R=task_args.get( \"R_dev\", np.zeros((self.act_space.shape[0], self.act_space.shape[0])) ), # joint space distance",
"0, 1.4469]) if self._num_dof == 7 else np.array([0.758, 0, 1.5])",
"num_dof if num_dof == 4: graph_file_name = \"wam_4dof_bic.xml\" self.qpos_des_init =",
"BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,",
"into the observation :param task_args: arguments for the task construction",
"observe_ball: if `True`, include the 2-dim (x-z plane) cartesian ball",
"-= np.pi / 180 * np.array([0.1, 1, 0.5, 1.0, 0.1,",
"self._init_state.copy() init_state_up[: self._num_dof] += np.pi / 180 * np.array([0.1, 1,",
"a DesStateTask that masks everything but the ball position idcs",
"reset() if task_args.get(\"sparse_rew_fcn\", False): factor = task_args.get(\"success_bonus\", 1) # Binary",
"Institute Europe GmbH, # or Technical University of Darmstadt, nor",
"= init_qpos_des_7dof self.p_gains = wam_pgains_7dof self.d_gains = wam_dgains_7dof init_ball_pos =",
"self._num_dof == 7 else goal_pos_init_sim_4dof rew_fcn = QuadrErrRewFcn( Q=task_args.get(\"Q_dev\", np.diag([2e-1,",
"-> Space: \"\"\" Get the space of joint torques. \"\"\"",
"nor the names of its contributors may # be used",
"/ 60)) # Pure visualization component xml_model = xml_model.replace(\"[size_capsule_geom]\", str(rope_length",
"obs_lo, obs_up, labels = [0.0], [1.0], [\"t\"] if self.observe_ball: obs_lo.extend([-3.0,",
"geom has a name self._collision_geom_ids = [self.model._geom_name2id[name] for name in",
"ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import mujoco_py",
"[1, l.93-96] xml_model = xml_model.replace(\"[scale_mesh]\", str(cup_scale * 0.001)) xml_model =",
"c2 = body2_name == \"ball\" and ( body1_name in self._collision_bodies",
"assert self.act_space.contains(act, verbose=True) # Get the desired positions and velocities",
"return BestStateFinalRewTask( MaskedTask(self.spec, task, idcs), factor=task_args.get(\"final_factor\", 0.05 * self.max_steps), )",
"[1, 3], act[2:]) elif self._num_dof == 7: np.add.at(qpos_des, [1, 3,",
"`dt` value, this can be overwritten. Possible use case if",
"OF LIABILITY, WHETHER # IN CONTRACT, STRICT LIABILITY, OR TORT",
"def check_ball_in_cup(self, *args, verbose: bool = False): \"\"\" Check if",
"deviation from the init position # 3.) Binary Bonus: Adds",
"the cup_goal is the mujoco site object marking the goal",
"reference # state_des_ball = self.sim.data.get_site_xpos(\"cup_goal\") # this is a reference",
"pyrado.tasks.masked import MaskedTask from pyrado.tasks.parallel import ParallelTasks from pyrado.tasks.reward_functions import",
"and use in source and binary forms, with or without",
"ball_collided or state_oob, ) def check_ball_collisions(self, verbose: bool = False)",
"action is held, results in a multiplier of the time",
"self.sim.data.qpos.copy(), self.sim.data.qvel.copy() ball_pos = self.sim.data.get_body_xpos(\"ball\").copy() cup_goal = self.sim.data.get_site_xpos(\"cup_goal\").copy() self.state =",
"= DesStateTask(spec, state_des, rew_fcn) # Wrap the masked DesStateTask to",
"str(0.055 - (cup_scale - 1.0) * 0.023)) xml_model = xml_model.replace(\"[pos_goal]\",",
"be removed in future... # if self._curr_step == 0: #",
"7) -> dict: if num_dof == 7: return dict( cup_scale=1.0,",
"angle of the first rope segment relative to the cup",
":param observe_cup: if `True`, include the 2-dim (x-z plane) cartesian",
"a bonus for the best state in the rollout return",
"and the first rope segment joint init_state_up = self._init_state.copy() init_state_up[:",
"def torque_space(self) -> Space: \"\"\" Get the space of joint",
"= list(range(self.state_space.flat_dim - 3, self.state_space.flat_dim)) # Cartesian cup goal position",
"damping of motor joints [N/s] (default value is small) joint_4_damping=0.05,",
"WAM setup being used :param frame_skip: number of simulation frames",
"# be used to endorse or promote products derived from",
"IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR",
"PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL <NAME>,",
"Desired state task for the cartesian ball distance # 2.)",
"- 1.0) * 0.023)) xml_model = xml_model.replace(\"[pos_goal]\", str(0.1165 + (cup_scale",
") def check_ball_collisions(self, verbose: bool = False) -> bool: \"\"\"",
"file multiplied by the number of frame skips (legacy from",
"plane) cartesian cup position into the observation :param task_args: arguments",
"the first rope segment joint init_state_up = self._init_state.copy() init_state_up[: self._num_dof]",
"in self._collision_bodies or contact.geom2 in self._collision_geom_ids ) c2 = body2_name",
"coefficient of motor joint 5 [-] joint_6_dryfriction=0.4, # dry friction",
"arguments for the task construction \"\"\" Serializable._init(self, locals()) self.fixed_init_state =",
"0.023)) xml_model = xml_model.replace(\"[pos_goal]\", str(0.1165 + (cup_scale - 1.0) *",
"body object 'cup' if self.observe_ball: obs.extend([state[-3], state[-1]]) if self.observe_cup: obs.extend([state[-6],",
"str, domain_param: dict) -> str: # First replace special domain",
"dict) -> str: # First replace special domain parameters cup_scale",
"forms, with or without # modification, are permitted provided that",
"rew_fcn) # Wrap the masked DesStateTask to add a bonus",
"WAM and cup (geom_ids) cup_inner_id = self.model._geom_name2id[\"cup_inner\"] c1 = body1_name",
"has not been updated to # init_space.sample(), which is first",
"velocities for the selected joints qpos_des = self.qpos_des_init.copy() # the",
"self.d_gains = wam_dgains_7dof init_ball_pos = np.array([0.828, 0.0, 1.131]) init_cup_goal =",
"True qpos, qvel = self.sim.data.qpos.copy(), self.sim.data.qvel.copy() ball_pos = self.sim.data.get_body_xpos(\"ball\").copy() cup_goal",
"joint 7 [-] rope_damping=1e-4, # damping of rope joints [N/s]",
"\"ball\" and contact.geom1 == cup_inner_id if c1 or c2: if",
"5e0])), # Cartesian distance from init cup position R=task_args.get( \"R_dev\",",
"if self.state_space.contains(self.state) else True return dict( qpos_des=qpos_des, qvel_des=qvel_des, qpos=qpos[: self._num_dof],",
"(when the WAM moved to the home position) if num_dof",
"joints [N/s] (reasonable values are 6e-4 to 1e-6) ) else:",
"= num_dof if num_dof == 4: graph_file_name = \"wam_4dof_bic.xml\" self.qpos_des_init",
"to # init_space.sample(), which is first called in reset() if",
"of both contact geoms body1 = self.model.geom_bodyid[contact.geom1] body1_name = self.model.body_names[body1]",
"Neither the name of <NAME>, Honda Research Institute Europe GmbH,",
"steps :param fixed_init_state: enables/disables deterministic, fixed initial state :param stop_on_collision:",
"True return False def check_ball_in_cup(self, *args, verbose: bool = False):",
"labels=labels) @property def act_space(self) -> Space: # Running a PD",
"overwritten. Possible use case if if you know that you",
"self.act_space.shape[0])) ), # joint space distance from init pose, interferes",
"Binary final reward task main_task = FinalRewTask( ConditionOnlyTask( spec, condition_fcn=self.check_ball_in_cup,",
"to endorse or promote products derived from this software without",
"# 3.) Binary Bonus: Adds a binary bonus when ball",
"DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND",
"case if if you know that you recorded a trajectory",
"PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY",
"task main_task = FinalRewTask( ConditionOnlyTask( spec, condition_fcn=self.check_ball_in_cup, is_success_condition=True, ), mode=FinalRewMode(always_positive=True),",
"torques to the robot self.sim.data.qfrc_applied[: self._num_dof] = torque # Call",
"* 0.001)) xml_model = xml_model.replace(\"[pos_mesh]\", str(0.055 - (cup_scale - 1.0)",
"goal_pos_init_sim_4dof rew_fcn = QuadrErrRewFcn( Q=task_args.get(\"Q_dev\", np.diag([2e-1, 1e-6, 5e0])), # Cartesian",
"the above copyright # notice, this list of conditions and",
"- cup; shouldn't move in y-direction R=task_args.get(\"R\", R_default), # last",
"joint_5_damping=0.05, # damping of motor joints [N/s] (default value is",
"are permitted provided that the following conditions are met: #",
"import SequentialTasks from pyrado.utils.data_types import EnvSpec from pyrado.utils.input_output import print_cbt",
"parts of the cup \"\"\" for i in range(self.sim.data.ncon): #",
"Note: the cup_goal is the mujoco site object marking the",
"in the x-z plane). # Note: the cup_goal is the",
"avoid early stopping task = SequentialTasks((main_task, dont_fail_after_succ_task)) return MaskedTask(self.spec, task,",
"if the ball collides with something else than the central",
"= np.array([0.723, 0.0, 1.168]) init_cup_goal = goal_pos_init_sim_4dof elif num_dof ==",
"limits of the arm are not reached (5 deg safety",
"BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY,",
"OF DARMSTADT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, #",
"3)) # Cartesian ball position spec = EnvSpec( self.spec.obs_space, self.spec.act_space,",
"# Redistribution and use in source and binary forms, with",
"import ConditionOnlyTask from pyrado.tasks.desired_state import DesStateTask from pyrado.tasks.final_reward import BestStateFinalRewTask,",
"of motor joint 2 [-] joint_3_dryfriction=0.4, # dry friction coefficient",
"idcs) else: state_des = self.sim.data.get_site_xpos(\"cup_goal\") # this is a reference",
"- 1.0) * 0.0385)) xml_model = xml_model.replace(\"[size_cup]\", str(cup_scale * 0.038))",
"and ( body2_name in self._collision_bodies or contact.geom2 in self._collision_geom_ids )",
"== \"ball\" and ( body1_name in self._collision_bodies or contact.geom1 in",
"True, observe_ball: bool = False, observe_cup: bool = False, task_args:",
"== 4: self.init_qpos[:4] = np.array([0.0, 0.63, 0.0, 1.27]) self.init_qpos[4] =",
"import ( goal_pos_init_sim_4dof, goal_pos_init_sim_7dof, init_qpos_des_4dof, init_qpos_des_7dof, act_space_bic_4dof, act_space_bic_7dof, wam_q_limits_up_7dof, wam_q_limits_lo_7dof,",
"code must retain the above copyright # notice, this list",
"[ self._create_main_task(task_args), self._create_deviation_task(task_args), self._create_main_task( dict( sparse_rew_fcn=True, success_bonus=task_args.get(\"success_bonus\", 0), ) ),",
"np.array([0.828, 0.0, 1.131]) init_cup_goal = goal_pos_init_sim_7dof else: raise pyrado.ValueErr(given=num_dof, eq_constraint=\"4",
"-> Space: # Observing the normalized time and optionally the",
"freedom. \"\"\" return self._num_dof @property def torque_space(self) -> Space: \"\"\"",
"{body1_name} and {body2_name} detected!\", \"y\", ) return True return False",
"idcs) def _adapt_model_file(self, xml_model: str, domain_param: dict) -> str: #",
"act[2:]) elif self._num_dof == 7: np.add.at(qpos_des, [1, 3, 5], act[:3])",
"LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN",
"copy(), state_des coming from MuJoCo is a reference and updates",
"axis in the plane azimuth=-90, # camera rotation around the",
") # init cup goal position state_des = goal_pos_init_sim_7dof if",
"OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT",
"spec = EnvSpec( self.spec.obs_space, self.spec.act_space, self.spec.state_space.subspace(self.spec.state_space.create_mask(idcs)), ) # init cup",
"use case if if you know that you recorded a",
"friction coefficient of motor joint 3 [-] joint_4_dryfriction=0.4, # dry",
"of the cup [-] (should be >0.65) rope_length=0.41, # length",
"Space: # Running a PD controller on joint positions and",
"= self.sim.data.qpos.copy(), self.sim.data.qvel.copy() ball_pos = self.sim.data.get_body_xpos(\"ball\").copy() cup_goal = self.sim.data.get_site_xpos(\"cup_goal\").copy() self.state",
"= False if self.state_space.contains(self.state) else True return dict( qpos_des=qpos_des, qvel_des=qvel_des,",
"would be reached after some time using the internal #",
"desired trajectory is relative to self._qpos_des_init qvel_des = np.zeros_like(qpos_des) if",
"state_up) @property def obs_space(self) -> Space: # Observing the normalized",
"fixed_init_state: enables/disables deterministic, fixed initial state :param stop_on_collision: set the",
"joint init_state_up = self._init_state.copy() init_state_up[: self._num_dof] += np.pi / 180",
"multiplied by the number of frame skips (legacy from OpenAI",
"with the robot ball_collided = self.check_ball_collisions() if self.stop_on_collision else False",
"super()._adapt_model_file(xml_model, domain_param) def _mujoco_step(self, act: np.ndarray) -> dict: assert self.act_space.contains(act,",
"state_des, rew_fcn) # Wrap the masked DesStateTask to add a",
"[-] joint_6_dryfriction=0.4, # dry friction coefficient of motor joint 6",
"if `True`, include the 2-dim (x-z plane) cartesian cup position",
"import Space from pyrado.spaces.box import BoxSpace from pyrado.spaces.singular import SingularStateSpace",
"of degrees of freedom. \"\"\" return self._num_dof @property def torque_space(self)",
"if if you know that you recorded a trajectory with",
"self._num_dof == 4: self._collision_bodies = self._collision_bodies[:6] # We access a",
"on fail after the main task ist done (successfully or",
"the (x, z) cartesian position of cup and ball (the",
"# last joint is really unreliable for 7 dof, thus",
"the goal position for the ball. It is not identical",
":return: `True` if the ball collides with something else than",
"should be removed in future... # if self._curr_step == 0:",
"Yield -1 on fail after the main task ist done",
"* 0.023)) xml_model = xml_model.replace(\"[pos_goal]\", str(0.1165 + (cup_scale - 1.0)",
"reward return self._create_main_task(task_args) else: # Create two (or three) parallel",
"INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT",
"max_steps: max number of simulation time steps :param fixed_init_state: enables/disables",
"SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH",
"check_ball_in_cup(self, *args, verbose: bool = False): \"\"\" Check if the",
"be overwritten. Possible use case if if you know that",
"for which the same action is held, results in a",
"conditions and the following disclaimer. # 2. Redistributions in binary",
"rope_length is not None: # The rope consists of 30",
"print_cbt(f'cup xpos: {self.sim.data.get_body_xpos(\"cup\").copy()}', 'b') # center of frame # print_cbt(f'cup",
"and the following disclaimer. # 2. Redistributions in binary form",
"moved to the home position) if num_dof == 4: self.init_qpos[:4]",
"trajectory with a specific `dt`. :param max_steps: max number of",
"# dry friction coefficient of motor joint 4 [-] rope_damping=1e-4,",
"# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND",
"to the home position) if num_dof == 4: self.init_qpos[:4] =",
"= self.model.geom_bodyid[contact.geom1] body1_name = self.model.body_names[body1] body2 = self.model.geom_bodyid[contact.geom2] body2_name =",
"to end. Keep in mind that in case of a",
"EUROPE GMBH, # OR TECHNICAL UNIVERSITY OF DARMSTADT BE LIABLE",
"1, 0.5, 1.0, 0.1, 1.0, 1.0])[: self._num_dof] self._init_space = BoxSpace(init_state_lo,",
"[1.0], [\"t\"] if self.observe_ball: obs_lo.extend([-3.0, -3.0]) obs_up.extend([3.0, 3.0]) labels.extend([\"ball_x\", \"ball_z\"])",
"the ball in cartesian coordinates self._init_state = np.concatenate([self.init_qpos, self.init_qvel, init_ball_pos,",
"[\"cup_geom1\", \"cup_geom2\"]] self.stop_on_collision = stop_on_collision self.camera_config = dict( distance=2.7, trackbodyid=0,",
"check_ball_collisions(self, verbose: bool = False) -> bool: \"\"\" Check if",
"body2 = self.model.geom_bodyid[contact.geom2] body2_name = self.model.body_names[body2] # Evaluate if the",
"dont_fail_after_succ_task = FinalRewTask( GoallessTask(spec, ZeroPerStepRewFcn()), mode=FinalRewMode(always_negative=True), factor=factor, ) # Augment",
"72)) # Resolve mesh directory and replace the remaining domain",
"None, max_steps: int = pyrado.inf, fixed_init_state: bool = True, stop_on_collision:",
"num_dof == 7: graph_file_name = \"wam_7dof_bic.xml\" self.qpos_des_init = init_qpos_des_7dof self.p_gains",
"= xml_model.replace(\"[scale_mesh]\", str(cup_scale * 0.001)) xml_model = xml_model.replace(\"[pos_mesh]\", str(0.055 -",
"3.0]) labels.extend([\"ball_x\", \"ball_z\"]) if self.observe_cup: obs_lo.extend([-3.0, -3.0]) obs_up.extend([3.0, 3.0]) labels.extend([\"cup_x\",",
"notice, this list of conditions and the following disclaimer in",
"obs_space(self) -> Space: # Observing the normalized time and optionally",
"shape as the init space (including ball and cup) state_shape",
"This causes the episode to end. Keep in mind that",
"= goal_pos_init_sim_7dof if self._num_dof == 7 else goal_pos_init_sim_4dof rew_fcn =",
"\"wam/wrist_pitch_link\", \"wam/wrist_yaw_link\", ] if self._num_dof == 4: self._collision_bodies = self._collision_bodies[:6]",
"self.sim.data.qvel.copy() ball_pos = self.sim.data.get_body_xpos(\"ball\").copy() cup_goal = self.sim.data.get_site_xpos(\"cup_goal\").copy() self.state = np.concatenate([qpos,",
"np.full(state_shape, pyrado.inf) # Ensure that joint limits of the arm",
"from pyrado.tasks.final_reward import BestStateFinalRewTask, FinalRewTask, FinalRewMode from pyrado.tasks.goalless import GoallessTask",
"-0.21 # angle of the first rope segment relative to",
"OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY",
"( body2_name in self._collision_bodies or contact.geom2 in self._collision_geom_ids ) c2",
"180 * np.array([0.1, 1, 0.5, 1.0, 0.1, 1.0, 1.0])[: self._num_dof]",
"# damping of motor joints [N/s] (default value is small)",
"[N/s] (default value is small) joint_7_damping=0.05, # damping of motor",
"Barrett technologies for the ball-in-the-cup task, controlled by a PD",
"friction coefficient of motor joint 6 [-] joint_7_dryfriction=0.4, # dry",
"`dict` returned by `_mujoco_step()` to true, if the ball collides",
"modification, are permitted provided that the following conditions are met:",
"== 7 else np.diag([0, 0, 1e-2, 1e-2]) rew_fcn = ExpQuadrErrRewFcn(",
"3.) Binary Bonus: Adds a binary bonus when ball is",
"body-name of both contact geoms body1 = self.model.geom_bodyid[contact.geom1] body1_name =",
"depending on which Barrett WAM setup being used :param frame_skip:",
"z) cartesian position of cup and ball (the robot operates",
"BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND #",
"[N/s] (default value is small) joint_1_dryfriction=0.4, # dry friction coefficient",
"of frame # print_cbt(f'cup xipos: {self.sim.data.get_body_xipos(\"cup\").copy()}', 'b') # center of",
"# print_cbt(f'cup xipos: {self.sim.data.get_body_xipos(\"cup\").copy()}', 'b') # center of mass #",
"= np.array([0.828, 0.0, 1.131]) init_cup_goal = goal_pos_init_sim_7dof else: raise pyrado.ValueErr(given=num_dof,",
"# ARISING IN ANY WAY OUT OF THE USE OF",
"[kg] joint_1_damping=0.05, # damping of motor joints [N/s] (default value",
":param fixed_init_state: enables/disables deterministic, fixed initial state :param stop_on_collision: set",
"the episode to end with a failure. mjsim_crashed = True",
"joint_1_damping=0.05, # damping of motor joints [N/s] (default value is",
"== 4: np.add.at(qpos_des, [1, 3], act[:2]) np.add.at(qvel_des, [1, 3], act[2:])",
"# Ensure that joint limits of the arm are not",
"stable initial position. This position would be reached after some",
"__init__( self, num_dof: int, frame_skip: int = 4, dt: Optional[float]",
"= domain_param.pop(\"rope_length\", None) if cup_scale is not None: # See",
"consists of 30 capsules xml_model = xml_model.replace(\"[pos_capsule]\", str(rope_length / 30))",
"reserved. # # Redistribution and use in source and binary",
"def _create_deviation_task(self, task_args: dict) -> Task: idcs = list(range(self.state_space.flat_dim -",
"cup. :param verbose: print messages when ball is in the",
") elif num_dof == 4: return dict( cup_scale=1.0, # scaling",
"the number of degrees of freedom. \"\"\" return self._num_dof @property",
"# specific prior written permission. # # THIS SOFTWARE IS",
"may # be used to endorse or promote products derived",
"ball collides with part of the WAM (collision bodies) #",
"= np.concatenate([self.init_qpos, self.init_qvel, init_ball_pos, init_cup_goal]) if self.fixed_init_state: self._init_space = SingularStateSpace(self._init_state)",
"state_des_cup = np.array([0.82521, 0, 1.4469]) if self._num_dof == 7 else",
"around the camera's vertical axis ) @property def num_dof(self) ->",
"init_ball_pos, init_cup_goal]) if self.fixed_init_state: self._init_space = SingularStateSpace(self._init_state) else: # Add",
"str(cup_scale * 0.03)) if rope_length is not None: # The",
"TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR",
"of {body1_name} and {body2_name} detected!\", \"y\", ) return True return",
"motor joint 5 [-] joint_6_dryfriction=0.4, # dry friction coefficient of",
"rew_fcn = ExpQuadrErrRewFcn( Q=task_args.get(\"Q\", np.diag([2e1, 1e-4, 2e1])), # distance ball",
"qpos_des=qpos_des, qvel_des=qvel_des, qpos=qpos[: self._num_dof], qvel=qvel[: self._num_dof], ball_pos=ball_pos, cup_pos=cup_goal, failed=mjsim_crashed or",
"collision self._collision_bodies = [ \"wam/base_link\", \"wam/shoulder_yaw_link\", \"wam/shoulder_pitch_link\", \"wam/upper_arm_link\", \"wam/forearm_link\", \"wrist_palm_link\",",
"the home position) if num_dof == 4: self.init_qpos[:4] = np.array([0.0,",
"the 2-dim (x-z plane) cartesian cup position into the observation",
"-> np.ndarray: # TODO: Debug print-outs, should be removed in",
"are 6e-4 to 1e-6) ) elif num_dof == 4: return",
"(or three) parallel running task. # 1.) Main task: Desired",
"after some time using the internal # PD controller to",
"name of <NAME>, Honda Research Institute Europe GmbH, # or",
"multiplier of the time step size `dt` :param dt: by",
"that you recorded a trajectory with a specific `dt`. :param",
"self.qpos_des_init.copy() # the desired trajectory is relative to self._qpos_des_init qvel_des",
"qpos_des = self.qpos_des_init.copy() # the desired trajectory is relative to",
"met: # 1. Redistributions of source code must retain the",
"7\") model_path = osp.join(pyrado.MUJOCO_ASSETS_DIR, graph_file_name) super().__init__(model_path, frame_skip, dt, max_steps, task_args)",
"= self._init_state.copy() init_state_up[: self._num_dof] += np.pi / 180 * np.array([0.1,",
"ball - cup; shouldn't move in y-direction R=task_args.get(\"R\", R_default), #",
"Serializable._init(self, locals()) self.fixed_init_state = fixed_init_state self.observe_ball = observe_ball self.observe_cup =",
"THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A",
"Create a task with binary reward return self._create_main_task(task_args) else: #",
"bonus for the best state in the rollout return BestStateFinalRewTask(",
"qpos=qpos[: self._num_dof], qvel=qvel[: self._num_dof], ball_pos=ball_pos, cup_pos=cup_goal, failed=mjsim_crashed or ball_collided or",
"if num_dof == 4: graph_file_name = \"wam_4dof_bic.xml\" self.qpos_des_init = init_qpos_des_4dof",
"np.ndarray) -> np.ndarray: # TODO: Debug print-outs, should be removed",
"of the WAM (collision bodies) # or the connection of",
"SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;",
"\"y\", ) return True return False def check_ball_in_cup(self, *args, verbose:",
"from _create_main_task ) task = DesStateTask(spec, state_des, rew_fcn) return MaskedTask(self.spec,",
"7 else np.diag([0, 0, 1e-2, 1e-2]) rew_fcn = ExpQuadrErrRewFcn( Q=task_args.get(\"Q\",",
"of motor joints [N/s] (default value is small) joint_6_damping=0.05, #",
"ball position obs_lo, obs_up, labels = [0.0], [1.0], [\"t\"] if",
") # Yield -1 on fail after the main task",
"done (successfully or not) dont_fail_after_succ_task = FinalRewTask( GoallessTask(spec, ZeroPerStepRewFcn()), mode=FinalRewMode(always_negative=True),",
"OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON",
"GmbH, # or Technical University of Darmstadt, nor the names",
"the cup \"\"\" for i in range(self.sim.data.ncon): # Get current",
"joint 6 [-] joint_7_dryfriction=0.4, # dry friction coefficient of motor",
"== cup_inner_id c2 = body2_name == \"ball\" and contact.geom1 ==",
"or c2: if verbose: print_cbt(f\"The ball is in the cup",
"OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY",
"torque = self.p_gains * err_pos + self.d_gains * err_vel torque",
"from typing import Optional import pyrado from pyrado.environments.barrett_wam import (",
"check for collisions of the ball with the robot ball_collided",
"contact.geom1 in self._collision_geom_ids ) if c1 or c2: if verbose:",
"1.41, 0.0, -0.28, -1.57]) self.init_qpos[7] = -0.21 # angle of",
"obs_lo.extend([-3.0, -3.0]) obs_up.extend([3.0, 3.0]) labels.extend([\"ball_x\", \"ball_z\"]) if self.observe_cup: obs_lo.extend([-3.0, -3.0])",
"the central parts of the cup \"\"\" for i in",
"following disclaimer in the # documentation and/or other materials provided",
"self.qpos_des_init = init_qpos_des_4dof self.p_gains = wam_pgains_4dof self.d_gains = wam_dgains_4dof init_ball_pos",
"trackbodyid=0, # id of the body to track elevation=-30, #",
"Optional import pyrado from pyrado.environments.barrett_wam import ( goal_pos_init_sim_4dof, goal_pos_init_sim_7dof, init_qpos_des_4dof,",
"on failing, this might result in undesired behavior. :param observe_ball:",
"1.) Main task: Desired state task for the cartesian ball",
"self._init_space = BoxSpace(init_state_lo, init_state_up) # Bodies to check fo collision",
"xml_model.replace(\"[pos_goal]\", str(0.1165 + (cup_scale - 1.0) * 0.0385)) xml_model =",
"the observation :param observe_cup: if `True`, include the 2-dim (x-z",
"str(-rope_length / 60)) # Pure visualization component xml_model = xml_model.replace(\"[size_capsule_geom]\",",
"== 0: # print_cbt(f'cup xpos: {self.sim.data.get_body_xpos(\"cup\").copy()}', 'b') # center of",
"something else than the desired parts of the cup. This",
"PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL <NAME>, HONDA",
"FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL",
"(x, z) cartesian position of cup and ball (the robot",
"init_space.sample(), which is first called in reset() if task_args.get(\"sparse_rew_fcn\", False):",
"\"ball\" and ( body1_name in self._collision_bodies or contact.geom1 in self._collision_geom_ids",
"np.diag([0, 0, 1e-2, 1e-2]) rew_fcn = ExpQuadrErrRewFcn( Q=task_args.get(\"Q\", np.diag([2e1, 1e-4,",
"`dt` :param dt: by default the time step size is",
"really unreliable for 7 dof, thus punish more ) task",
"mujoco_py.builder.MujocoException: # When MuJoCo recognized instabilities in the simulation, it",
"names of its contributors may # be used to endorse",
"and replace the remaining domain parameters return super()._adapt_model_file(xml_model, domain_param) def",
"is at the top of each capsule (therefore negative direction",
"not identical # to the coordinate system origin of the",
"-> int: \"\"\" Get the number of degrees of freedom.",
"verbose: bool = False): \"\"\" Check if the ball is",
"rigid body object 'cup' if self.observe_ball: obs.extend([state[-3], state[-1]]) if self.observe_cup:",
"1.131]) init_cup_goal = goal_pos_init_sim_7dof else: raise pyrado.ValueErr(given=num_dof, eq_constraint=\"4 or 7\")",
"Compute the position and velocity errors err_pos = qpos_des -",
"distance # 2.) Deviation task: Desired state task for the",
"not None: # See [1, l.93-96] xml_model = xml_model.replace(\"[scale_mesh]\", str(cup_scale",
"DesStateTask that masks everything but the ball position idcs =",
"verbose: print messages on collision :return: `True` if the ball",
"= np.concatenate([state_des_ball, state_des_cup]) R_default = np.diag([0, 0, 1, 1e-2, 1e-2,",
"errors err_pos = qpos_des - self.state[: self._num_dof] err_vel = qvel_des",
"AND CONTRIBUTORS \"AS IS\" AND # ANY EXPRESS OR IMPLIED",
"early stopping task = SequentialTasks((main_task, dont_fail_after_succ_task)) return MaskedTask(self.spec, task, idcs)",
"joint position (when the WAM moved to the home position)",
"# init cup goal position state_des = goal_pos_init_sim_7dof if self._num_dof",
"of motor joint 3 [-] joint_4_dryfriction=0.4, # dry friction coefficient",
"when ball is in the cup :return: `True` if the",
"= False, observe_cup: bool = False, task_args: Optional[dict] = None,",
"BoxSpace(obs_lo, obs_up, labels=labels) @property def act_space(self) -> Space: # Running",
"None) rope_length = domain_param.pop(\"rope_length\", None) if cup_scale is not None:",
"ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,",
"\"cup_z\"]) return BoxSpace(obs_lo, obs_up, labels=labels) @property def act_space(self) -> Space:",
"flag in the `dict` returned by `_mujoco_step()` to true, if",
"xml_model.replace(\"[pos_capsule_joint]\", str(-rope_length / 60)) # Pure visualization component xml_model =",
"self.state_space.flat_dim - 3)) # Cartesian ball position spec = EnvSpec(",
"Europe GmbH, and # Technical University of Darmstadt. # All",
"object contact = self.sim.data.contact[i] # Extract body-id and body-name of",
"1) # Binary final reward task main_task = FinalRewTask( ConditionOnlyTask(",
"the cup. This causes the episode to end. Keep in",
"0.65, 0.0, 1.41, 0.0, -0.28, -1.57]) self.init_qpos[7] = -0.21 #",
"If desired, check for collisions of the ball with the",
"\"ball\" and ( body2_name in self._collision_bodies or contact.geom2 in self._collision_geom_ids",
"c1 = body1_name == \"ball\" and contact.geom2 == cup_inner_id c2",
"body1_name == \"ball\" and ( body2_name in self._collision_bodies or contact.geom2",
"cost on failing, this might result in undesired behavior. :param",
"1 [-] joint_2_dryfriction=0.4, # dry friction coefficient of motor joint",
"GoallessTask(spec, ZeroPerStepRewFcn()), mode=FinalRewMode(always_negative=True), factor=factor, ) # Augment the binary task",
"# mass of the ball [kg] joint_1_damping=0.05, # damping of",
"(x-z plane) cartesian ball position into the observation :param observe_cup:",
"their max values torque = self.p_gains * err_pos + self.d_gains",
"with the ball occurs. :param verbose: print messages on collision",
"(reasonable values are 6e-4 to 1e-6) ) else: raise pyrado.ValueErr(given=num_dof,",
"in range(self.sim.data.ncon): # Get current contact object contact = self.sim.data.contact[i]",
"-> dict: assert self.act_space.contains(act, verbose=True) # Get the desired positions",
"of motor joints [N/s] (default value is small) joint_2_damping=0.05, #",
"to stabilize at self._qpos_des_init. # The initial position of the",
"Get the desired positions and velocities for the selected joints",
"OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER",
":param num_dof: number of degrees of freedom (4 or 7),",
"number of simulation time steps :param fixed_init_state: enables/disables deterministic, fixed",
"main_task = FinalRewTask( ConditionOnlyTask( spec, condition_fcn=self.check_ball_in_cup, is_success_condition=True, ), mode=FinalRewMode(always_positive=True), factor=factor,",
"and velocities for the selected joints qpos_des = self.qpos_des_init.copy() #",
"to their max values torque = self.p_gains * err_pos +",
"list of conditions and the following disclaimer in the #",
"NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF",
"if an undesired collision with the ball occurs. :param verbose:",
"R=task_args.get( \"R_dev\", np.zeros((self.act_space.shape[0], self.act_space.shape[0])) ), # joint space distance from",
"of joint torques. \"\"\" return torque_space_wam_7dof if self._num_dof == 7",
"Instead, we want the episode to end with a failure.",
"True return False def observe(self, state: np.ndarray) -> np.ndarray: #",
"a meaningful `init_state` .. seealso:: [1] https://github.com/psclklnk/self-paced-rl/tree/master/sprl/envs/ball_in_a_cup.py \"\"\" name: str",
"* self.max_steps), ) def _create_deviation_task(self, task_args: dict) -> Task: idcs",
"products derived from this software without # specific prior written",
"HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER #",
"positions and velocities return act_space_bic_7dof if self._num_dof == 7 else",
"labels.extend([\"cup_x\", \"cup_z\"]) return BoxSpace(obs_lo, obs_up, labels=labels) @property def act_space(self) ->",
"space has the same shape as the init space (including",
"friction coefficient of motor joint 4 [-] rope_damping=1e-4, # damping",
"updated to # init_space.sample(), which is first called in reset()",
"MuJoCo recognized instabilities in the simulation, it simply kills it.",
"np.array([0.82521, 0, 1.4469]) if self._num_dof == 7 else np.array([0.758, 0,",
"Check if an undesired collision with the ball occurs. :param",
"act_space_bic_4dof, act_space_bic_7dof, wam_q_limits_up_7dof, wam_q_limits_lo_7dof, torque_space_wam_4dof, torque_space_wam_7dof, wam_pgains_7dof, wam_dgains_7dof, wam_pgains_4dof, wam_dgains_4dof,",
"number of degrees of freedom. \"\"\" return self._num_dof @property def",
"Running a PD controller on joint positions and velocities return",
"observe_cup: bool = False, task_args: Optional[dict] = None, ): \"\"\"",
"observe_cup: if `True`, include the 2-dim (x-z plane) cartesian cup",
"-3.0]) obs_up.extend([3.0, 3.0]) labels.extend([\"cup_x\", \"cup_z\"]) return BoxSpace(obs_lo, obs_up, labels=labels) @property",
"(5 deg safety margin) state_lo[: self._num_dof] = wam_q_limits_lo_7dof[: self._num_dof] state_up[:",
"else: self.init_qpos[:7] = np.array([0.0, 0.65, 0.0, 1.41, 0.0, -0.28, -1.57])",
"# Note: sim.forward() + get_body_xpos() results in wrong output for",
"-> Space: # The state space has the same shape",
"import BestStateFinalRewTask, FinalRewTask, FinalRewMode from pyrado.tasks.goalless import GoallessTask from pyrado.tasks.masked",
"CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF",
"# length of the rope [m] ball_mass=0.024, # mass of",
"`failed` flag in the `dict` returned by `_mujoco_step()` to true,",
"(default value is small) joint_4_damping=0.05, # damping of motor joints",
"of <NAME>, Honda Research Institute Europe GmbH, # or Technical",
"initial joint position (when the WAM moved to the home",
"7\") def _create_task(self, task_args: dict) -> Task: if task_args.get(\"sparse_rew_fcn\", False):",
"# angle of the first rope segment relative to the",
"running task. # 1.) Main task: Desired state task for",
"true, if the ball collides with something else than the",
"err_pos = qpos_des - self.state[: self._num_dof] err_vel = qvel_des -",
"if self._num_dof == 7 else torque_space_wam_4dof @property def state_space(self) ->",
"observe_cup # Initialize num DoF specific variables self._num_dof = num_dof",
"motor joint 1 [-] joint_2_dryfriction=0.4, # dry friction coefficient of",
"everything but the ball position idcs = list(range(self.state_space.flat_dim - 6,",
"simply kills it. # Instead, we want the episode to",
"== \"ball\" and contact.geom1 == cup_inner_id if c1 or c2:",
"\"y\") return True return False def observe(self, state: np.ndarray) ->",
"joint positions and velocities return act_space_bic_7dof if self._num_dof == 7",
"the WAM (collision bodies) # or the connection of WAM",
"provided that the following conditions are met: # 1. Redistributions",
"a reference # state_des_cup = np.array([0.82521, 0, 1.4469]) if self._num_dof",
"endorse or promote products derived from this software without #",
"[-] joint_2_dryfriction=0.4, # dry friction coefficient of motor joint 2",
"0), ) ), ] ) def _create_main_task(self, task_args: dict) ->",
"# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED",
"automatically at each step. # Note: sim.forward() + get_body_xpos() results",
"= \"wam_7dof_bic.xml\" self.qpos_des_init = init_qpos_des_7dof self.p_gains = wam_pgains_7dof self.d_gains =",
"= -0.21 # angle of the first rope segment relative",
"pyrado.tasks.condition_only import ConditionOnlyTask from pyrado.tasks.desired_state import DesStateTask from pyrado.tasks.final_reward import",
"BestStateFinalRewTask, FinalRewTask, FinalRewMode from pyrado.tasks.goalless import GoallessTask from pyrado.tasks.masked import",
"WAM moved to the home position) if num_dof == 4:",
"), # joint space distance from init pose, interferes with",
"0.5, 1.0, 0.1, 1.0, 1.0])[: self._num_dof] init_state_lo = self._init_state.copy() init_state_lo[:",
"* err_vel torque = self.torque_space.project_to(torque) # Apply the torques to",
"the coordinate system origin of the rigid body object 'cup'",
"True, stop_on_collision: bool = True, observe_ball: bool = False, observe_cup:",
"self.model._geom_name2id[\"cup_inner\"] c1 = body1_name == \"ball\" and contact.geom2 == cup_inner_id",
"WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE",
"as osp from init_args_serializer import Serializable from typing import Optional",
"Constructor :param num_dof: number of degrees of freedom (4 or",
"y-direction R=task_args.get(\"R\", R_default), # last joint is really unreliable for",
"a PD controller on joint positions and velocities return act_space_bic_7dof",
"typing import Optional import pyrado from pyrado.environments.barrett_wam import ( goal_pos_init_sim_4dof,",
"import DesStateTask from pyrado.tasks.final_reward import BestStateFinalRewTask, FinalRewTask, FinalRewMode from pyrado.tasks.goalless",
"self._init_state = np.concatenate([self.init_qpos, self.init_qvel, init_ball_pos, init_cup_goal]) if self.fixed_init_state: self._init_space =",
"- self.state[: self._num_dof] err_vel = qvel_des - self.state[self.model.nq : self.model.nq",
"BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY",
"+ (cup_scale - 1.0) * 0.0385)) xml_model = xml_model.replace(\"[size_cup]\", str(cup_scale",
"= observe_cup # Initialize num DoF specific variables self._num_dof =",
"Debug print-outs, should be removed in future... # if self._curr_step",
"reproduce the above copyright # notice, this list of conditions",
"(legacy from OpenAI environments). By passing an explicit `dt` value,",
"domain parameters return super()._adapt_model_file(xml_model, domain_param) def _mujoco_step(self, act: np.ndarray) ->",
"# or the connection of WAM and cup (geom_ids) cup_inner_id",
"passing an explicit `dt` value, this can be overwritten. Possible",
"obs_up.extend([3.0, 3.0]) labels.extend([\"cup_x\", \"cup_z\"]) return BoxSpace(obs_lo, obs_up, labels=labels) @property def",
"= 7) -> dict: if num_dof == 7: return dict(",
"damping of rope joints [N/s] (reasonable values are 6e-4 to",
"self.init_qpos[4] = -0.34 # angle of the first rope segment",
"degree to each motor joint and the first rope segment",
"WHETHER # IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE",
"the `dict` returned by `_mujoco_step()` to true, if the ball",
"task_args.get(\"sparse_rew_fcn\", False): factor = task_args.get(\"success_bonus\", 1) # Binary final reward",
"return BoxSpace(obs_lo, obs_up, labels=labels) @property def act_space(self) -> Space: #",
"is small) joint_3_damping=0.05, # damping of motor joints [N/s] (default",
"WAMBallInCupSim(MujocoSimEnv, Serializable): \"\"\" WAM robotic arm from Barrett technologies for",
"self.sim.data.get_site_xpos(\"cup_goal\") # this is a reference # state_des_cup = np.array([0.82521,",
"of simulation time steps :param fixed_init_state: enables/disables deterministic, fixed initial",
"of motor joint 4 [-] rope_damping=1e-4, # damping of rope",
"np.concatenate([self.init_qpos, self.init_qvel, init_ball_pos, init_cup_goal]) if self.fixed_init_state: self._init_space = SingularStateSpace(self._init_state) else:",
"SingularStateSpace from pyrado.tasks.base import Task from pyrado.tasks.condition_only import ConditionOnlyTask from",
"each capsule (therefore negative direction from center) xml_model = xml_model.replace(\"[pos_capsule_joint]\",",
"for the cartesian- and joint deviation from the init position",
"PD controller and clip them to their max values torque",
"rope_length = domain_param.pop(\"rope_length\", None) if cup_scale is not None: #",
"else than the central parts of the cup \"\"\" for",
"ball occurs. :param verbose: print messages on collision :return: `True`",
"normally checked by the task, but does not work because",
"LIABILITY, WHETHER # IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING",
"desired positions and velocities for the selected joints qpos_des =",
"ball is in the cup \"\"\" for i in range(self.sim.data.ncon):",
"3.0]) labels.extend([\"cup_x\", \"cup_z\"]) return BoxSpace(obs_lo, obs_up, labels=labels) @property def act_space(self)",
"# dry friction coefficient of motor joint 6 [-] joint_7_dryfriction=0.4,",
"EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, #",
"axis ) @property def num_dof(self) -> int: \"\"\" Get the",
"# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE",
"motor joint 4 [-] joint_5_dryfriction=0.4, # dry friction coefficient of",
"of each capsule (therefore negative direction from center) xml_model =",
"state_des = goal_pos_init_sim_7dof if self._num_dof == 7 else goal_pos_init_sim_4dof rew_fcn",
"SequentialTasks((main_task, dont_fail_after_succ_task)) return MaskedTask(self.spec, task, idcs) else: state_des = self.sim.data.get_site_xpos(\"cup_goal\")",
"dof, thus punish more ) task = DesStateTask(spec, state_des, rew_fcn)",
"import ZeroPerStepRewFcn, ExpQuadrErrRewFcn, QuadrErrRewFcn from pyrado.tasks.sequential import SequentialTasks from pyrado.utils.data_types",
"by the number of frame skips (legacy from OpenAI environments).",
"self.init_qpos[:4] = np.array([0.0, 0.63, 0.0, 1.27]) self.init_qpos[4] = -0.34 #",
"motor joints [N/s] (default value is small) joint_4_damping=0.05, # damping",
"= init_qpos_des_4dof self.p_gains = wam_pgains_4dof self.d_gains = wam_dgains_4dof init_ball_pos =",
"is a reference # state_des_cup = np.array([0.82521, 0, 1.4469]) if",
"Serializable from typing import Optional import pyrado from pyrado.environments.barrett_wam import",
"shouldn't move in y-direction R=task_args.get(\"R\", R_default), # last joint is",
"with a failure. mjsim_crashed = True qpos, qvel = self.sim.data.qpos.copy(),",
"3, self.state_space.flat_dim)) # Cartesian cup goal position spec = EnvSpec(",
"from pyrado.spaces.base import Space from pyrado.spaces.box import BoxSpace from pyrado.spaces.singular",
"of conditions and the following disclaimer. # 2. Redistributions in",
"return False def observe(self, state: np.ndarray) -> np.ndarray: # TODO:",
"ball position spec = EnvSpec( self.spec.obs_space, self.spec.act_space, self.spec.state_space.subspace(self.spec.state_space.create_mask(idcs)), ) #",
"camera rotation around the camera's vertical axis ) @property def",
"# The state space has the same shape as the",
"GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; #",
"SequentialTasks from pyrado.utils.data_types import EnvSpec from pyrado.utils.input_output import print_cbt class",
"is out of bounds (this is normally checked by the",
"a reference # state_des_ball = self.sim.data.get_site_xpos(\"cup_goal\") # this is a",
"# Cartesian distance from init cup position R=task_args.get( \"R_dev\", np.zeros((self.act_space.shape[0],",
"== 7 else goal_pos_init_sim_4dof rew_fcn = QuadrErrRewFcn( Q=task_args.get(\"Q_dev\", np.diag([2e-1, 1e-6,",
"DoF specific variables self._num_dof = num_dof if num_dof == 4:",
"# First replace special domain parameters cup_scale = domain_param.pop(\"cup_scale\", None)",
"= self.qpos_des_init.copy() # the desired trajectory is relative to self._qpos_des_init",
"# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,",
"used to endorse or promote products derived from this software",
"observe_ball: bool = False, observe_cup: bool = False, task_args: Optional[dict]",
"wam_dgains_7dof init_ball_pos = np.array([0.828, 0.0, 1.131]) init_cup_goal = goal_pos_init_sim_7dof else:",
"stop_on_collision: set the `failed` flag in the `dict` returned by",
"mjsim_crashed = False except mujoco_py.builder.MujocoException: # When MuJoCo recognized instabilities",
"WAM robotic arm from Barrett technologies for the ball-in-the-cup task,",
"coefficient of motor joint 6 [-] joint_7_dryfriction=0.4, # dry friction",
"motor joint 3 [-] joint_4_dryfriction=0.4, # dry friction coefficient of",
"= wam_q_limits_lo_7dof[: self._num_dof] state_up[: self._num_dof] = wam_q_limits_up_7dof[: self._num_dof] return BoxSpace(state_lo,",
"a specific `dt`. :param max_steps: max number of simulation time",
"trajectory is relative to self._qpos_des_init qvel_des = np.zeros_like(qpos_des) if self._num_dof",
"Resolve mesh directory and replace the remaining domain parameters return",
"and ball position obs_lo, obs_up, labels = [0.0], [1.0], [\"t\"]",
"if num_dof == 4: self.init_qpos[:4] = np.array([0.0, 0.63, 0.0, 1.27])",
"np.array([0.0, 0.65, 0.0, 1.41, 0.0, -0.28, -1.57]) self.init_qpos[7] = -0.21",
"np.diag([0, 0, 1, 1e-2, 1e-2, 1e-1]) if self._num_dof == 7",
"self.d_gains * err_vel torque = self.torque_space.project_to(torque) # Apply the torques",
"EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE.",
"last joint is really unreliable for 7 dof, thus punish",
"ball is in the cup. :param verbose: print messages when",
"parallel running task. # 1.) Main task: Desired state task",
"\"wam/shoulder_yaw_link\", \"wam/shoulder_pitch_link\", \"wam/upper_arm_link\", \"wam/forearm_link\", \"wrist_palm_link\", \"wam/wrist_pitch_link\", \"wam/wrist_yaw_link\", ] if self._num_dof",
"add a bonus for the best state in the rollout",
"6e-4 to 1e-6) ) elif num_dof == 4: return dict(",
"with R_default from _create_main_task ) task = DesStateTask(spec, state_des, rew_fcn)",
"cartesian ball distance # 2.) Deviation task: Desired state task",
"number of frame skips (legacy from OpenAI environments). By passing",
"self.p_gains = wam_pgains_7dof self.d_gains = wam_dgains_7dof init_ball_pos = np.array([0.828, 0.0,",
"get_nominal_domain_param(cls, num_dof: int = 7) -> dict: if num_dof ==",
"masked DesStateTask to add a bonus for the best state",
"technologies for the ball-in-the-cup task, controlled by a PD controller.",
".. note:: When using the `reset()` function, always pass a",
"in the plane azimuth=-90, # camera rotation around the camera's",
"id of the body to track elevation=-30, # camera rotation",
"TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY",
"import Optional import pyrado from pyrado.environments.barrett_wam import ( goal_pos_init_sim_4dof, goal_pos_init_sim_7dof,",
"0.0, 1.168]) init_cup_goal = goal_pos_init_sim_4dof elif num_dof == 7: graph_file_name",
"= qvel_des - self.state[self.model.nq : self.model.nq + self._num_dof] # Compute",
"state: np.ndarray) -> np.ndarray: # TODO: Debug print-outs, should be",
"of the cup. This causes the episode to end. Keep",
"the cartesian- and joint deviation from the init position #",
"BoxSpace(init_state_lo, init_state_up) # Bodies to check fo collision self._collision_bodies =",
"masks everything but the ball position idcs = list(range(self.state_space.flat_dim -",
":param verbose: print messages on collision :return: `True` if the",
"[-] rope_damping=1e-4, # damping of rope joints [N/s] (reasonable values",
"in source and binary forms, with or without # modification,",
"QuadrErrRewFcn from pyrado.tasks.sequential import SequentialTasks from pyrado.utils.data_types import EnvSpec from",
"controller to stabilize at self._qpos_des_init. # The initial position of",
"= self.sim.data.get_site_xpos(\"cup_goal\") # this is a reference # state_des_ball =",
"bonus when ball is catched [inactive by default] return ParallelTasks(",
"0.05 * self.max_steps), ) def _create_deviation_task(self, task_args: dict) -> Task:",
"import MujocoSimEnv from pyrado.spaces.base import Space from pyrado.spaces.box import BoxSpace",
"Get current contact object contact = self.sim.data.contact[i] # Extract body-id",
"7 else torque_space_wam_4dof @property def state_space(self) -> Space: # The",
"= ExpQuadrErrRewFcn( Q=task_args.get(\"Q\", np.diag([2e1, 1e-4, 2e1])), # distance ball -",
"rope [m] ball_mass=0.024, # mass of the ball [kg] joint_1_damping=0.05,",
"stop_on_collision self.camera_config = dict( distance=2.7, trackbodyid=0, # id of the",
"arm from Barrett technologies for the ball-in-the-cup task, controlled by",
"no final cost on failing, this might result in undesired",
"[N/s] (default value is small) joint_4_damping=0.05, # damping of motor",
"must reproduce the above copyright # notice, this list of",
"might result in undesired behavior. :param observe_ball: if `True`, include",
"verbose=True) # Get the desired positions and velocities for the",
"setup being used :param frame_skip: number of simulation frames for",
"are met: # 1. Redistributions of source code must retain",
"contact.geom2 == cup_inner_id c2 = body2_name == \"ball\" and contact.geom1",
"self.init_qvel, np.empty(3), np.empty(3)]).shape state_lo, state_up = np.full(state_shape, -pyrado.inf), np.full(state_shape, pyrado.inf)",
"state_oob = False if self.state_space.contains(self.state) else True return dict( qpos_des=qpos_des,",
"this list of conditions and the following disclaimer. # 2.",
"# dry friction coefficient of motor joint 3 [-] joint_4_dryfriction=0.4,",
"note:: When using the `reset()` function, always pass a meaningful",
"== 7: return dict( cup_scale=1.0, # scaling factor for the",
"# or the connection of WAM and cup (geom_ids) c1",
"if self._num_dof == 4: self._collision_bodies = self._collision_bodies[:6] # We access",
"center of mass # Observe the normalized time obs =",
"this might result in undesired behavior. :param observe_ball: if `True`,",
"\"\"\" WAM robotic arm from Barrett technologies for the ball-in-the-cup",
"because # not every geom has a name self._collision_geom_ids =",
"cup_inner_id = self.model._geom_name2id[\"cup_inner\"] c1 = body1_name == \"ball\" and contact.geom2",
"task, to avoid early stopping task = SequentialTasks((main_task, dont_fail_after_succ_task)) return",
"to track elevation=-30, # camera rotation around the axis in",
"R_default), # last joint is really unreliable for 7 dof,",
"# DISCLAIMED. IN NO EVENT SHALL <NAME>, HONDA RESEARCH INSTITUTE",
"task with binary reward return self._create_main_task(task_args) else: # Create two",
"np.zeros((self.act_space.shape[0], self.act_space.shape[0])) ), # joint space distance from init pose,",
"elif self._num_dof == 7: np.add.at(qpos_des, [1, 3, 5], act[:3]) np.add.at(qvel_des,",
"self._num_dof] = torque # Call MuJoCo try: self.sim.step() mjsim_crashed =",
"in the cup :return: `True` if the ball is in",
"the actual stable initial position. This position would be reached",
"three) parallel running task. # 1.) Main task: Desired state",
"goal position for the ball. It is not identical #",
"self._num_dof = num_dof if num_dof == 4: graph_file_name = \"wam_4dof_bic.xml\"",
"is not None: # The rope consists of 30 capsules",
"4 [-] joint_5_dryfriction=0.4, # dry friction coefficient of motor joint",
"THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF",
") ), ] ) def _create_main_task(self, task_args: dict) -> Task:",
"False if self.state_space.contains(self.state) else True return dict( qpos_des=qpos_des, qvel_des=qvel_des, qpos=qpos[:",
"Optional[dict] = None, ): \"\"\" Constructor :param num_dof: number of",
"the ball position idcs = list(range(self.state_space.flat_dim - 6, self.state_space.flat_dim -",
"the ball is in the cup \"\"\" for i in",
"episode to end. Keep in mind that in case of",
"return True return False def check_ball_in_cup(self, *args, verbose: bool =",
"# init_space.sample(), which is first called in reset() if task_args.get(\"sparse_rew_fcn\",",
"OF SUCH DAMAGE. import mujoco_py import numpy as np import",
"frame_skip, dt, max_steps, task_args) # Actual initial joint position (when",
"promote products derived from this software without # specific prior",
"with or without # modification, are permitted provided that the",
"self.sim.data.get_site_xpos(\"cup_goal\").copy() self.state = np.concatenate([qpos, qvel, ball_pos, cup_goal]) # If desired,",
"position into the observation :param observe_cup: if `True`, include the",
"to end with a failure. mjsim_crashed = True qpos, qvel",
"is really unreliable for 7 dof, thus punish more )",
"dict: if num_dof == 7: return dict( cup_scale=1.0, # scaling",
"position for the ball. It is not identical # to",
"value is small) joint_1_dryfriction=0.4, # dry friction coefficient of motor",
"FinalRewTask, FinalRewMode from pyrado.tasks.goalless import GoallessTask from pyrado.tasks.masked import MaskedTask",
"of motor joints [N/s] (default value is small) joint_4_damping=0.05, #",
"# Instead, we want the episode to end with a",
"bool = False, observe_cup: bool = False, task_args: Optional[dict] =",
"specific `dt`. :param max_steps: max number of simulation time steps",
"act[:3]) np.add.at(qvel_des, [1, 3, 5], act[3:]) # Compute the position",
"err_vel torque = self.torque_space.project_to(torque) # Apply the torques to the",
"contact geoms body1 = self.model.geom_bodyid[contact.geom1] body1_name = self.model.body_names[body1] body2 =",
"# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED",
"include the 2-dim (x-z plane) cartesian ball position into the",
"labels.extend([\"ball_x\", \"ball_z\"]) if self.observe_cup: obs_lo.extend([-3.0, -3.0]) obs_up.extend([3.0, 3.0]) labels.extend([\"cup_x\", \"cup_z\"])",
"is a reference and updates automatically at each step. #",
"IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)",
"2-dim (x-z plane) cartesian cup position into the observation :param",
"# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR",
"the body to track elevation=-30, # camera rotation around the",
"= np.zeros_like(qpos_des) if self._num_dof == 4: np.add.at(qpos_des, [1, 3], act[:2])",
"friction coefficient of motor joint 7 [-] rope_damping=1e-4, # damping",
"-3.0]) obs_up.extend([3.0, 3.0]) labels.extend([\"ball_x\", \"ball_z\"]) if self.observe_cup: obs_lo.extend([-3.0, -3.0]) obs_up.extend([3.0,",
"University of Darmstadt. # All rights reserved. # # Redistribution",
") @property def num_dof(self) -> int: \"\"\" Get the number",
"= True qpos, qvel = self.sim.data.qpos.copy(), self.sim.data.qvel.copy() ball_pos = self.sim.data.get_body_xpos(\"ball\").copy()",
"= np.concatenate([qpos, qvel, ball_pos, cup_goal]) # If desired, check for",
"# state_des_cup = np.array([0.82521, 0, 1.4469]) if self._num_dof == 7",
"cup_inner_id c2 = body2_name == \"ball\" and contact.geom1 == cup_inner_id",
"special domain parameters cup_scale = domain_param.pop(\"cup_scale\", None) rope_length = domain_param.pop(\"rope_length\",",
"[-] joint_3_dryfriction=0.4, # dry friction coefficient of motor joint 3",
"or the connection of WAM and cup (geom_ids) c1 =",
"self._create_deviation_task(task_args), self._create_main_task( dict( sparse_rew_fcn=True, success_bonus=task_args.get(\"success_bonus\", 0), ) ), ] )",
"documentation and/or other materials provided with the distribution. # 3.",
"= body2_name == \"ball\" and ( body1_name in self._collision_bodies or",
"interferes with R_default from _create_main_task ) task = DesStateTask(spec, state_des,",
"task_args: arguments for the task construction \"\"\" Serializable._init(self, locals()) self.fixed_init_state",
"the binary task with an endless dummy task, to avoid",
"space distance from init pose, interferes with R_default from _create_main_task",
"= observe_ball self.observe_cup = observe_cup # Initialize num DoF specific",
"freedom (4 or 7), depending on which Barrett WAM setup",
"failed=mjsim_crashed or ball_collided or state_oob, ) def check_ball_collisions(self, verbose: bool",
"rollout return BestStateFinalRewTask( MaskedTask(self.spec, task, idcs), factor=task_args.get(\"final_factor\", 0.05 * self.max_steps),",
"the remaining domain parameters return super()._adapt_model_file(xml_model, domain_param) def _mujoco_step(self, act:",
"WAM and cup (geom_ids) c1 = body1_name == \"ball\" and",
"if the ball is in the cup. :param verbose: print",
"OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE",
"verbose: print_cbt( f\"Undesired collision of {body1_name} and {body2_name} detected!\", \"y\",",
"distance from init pose, interferes with R_default from _create_main_task )",
"self._num_dof] -= np.pi / 180 * np.array([0.1, 1, 0.5, 1.0,",
"BestStateFinalRewTask( MaskedTask(self.spec, task, idcs), factor=task_args.get(\"final_factor\", 0.05 * self.max_steps), ) def",
"self.state_space.flat_dim)) # Cartesian cup goal position spec = EnvSpec( self.spec.obs_space,",
"self.sim.data.qfrc_applied[: self._num_dof] = torque # Call MuJoCo try: self.sim.step() mjsim_crashed",
"(default value is small) joint_5_damping=0.05, # damping of motor joints",
"3], act[:2]) np.add.at(qvel_des, [1, 3], act[2:]) elif self._num_dof == 7:",
"the ball [kg] joint_1_damping=0.05, # damping of motor joints [N/s]",
"for the cartesian ball distance # 2.) Deviation task: Desired",
"* np.array([0.1, 1, 0.5, 1.0, 0.1, 1.0, 1.0])[: self._num_dof] init_state_lo",
"do not use copy(), state_des coming from MuJoCo is a",
"\"R_dev\", np.zeros((self.act_space.shape[0], self.act_space.shape[0])) ), # joint space distance from init",
"OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF",
"WAM (collision bodies) # or the connection of WAM and",
"/ self.max_steps] # Extract the (x, z) cartesian position of",
"which is first called in reset() if task_args.get(\"sparse_rew_fcn\", False): factor",
"its contributors may # be used to endorse or promote",
"Create two (or three) parallel running task. # 1.) Main",
"fixed_init_state self.observe_ball = observe_ball self.observe_cup = observe_cup # Initialize num",
"self._num_dof @property def torque_space(self) -> Space: \"\"\" Get the space",
"does not work because of the mask) state_oob = False",
"`True`, include the 2-dim (x-z plane) cartesian cup position into",
"pyrado.tasks.desired_state import DesStateTask from pyrado.tasks.final_reward import BestStateFinalRewTask, FinalRewTask, FinalRewMode from",
"plate else: self.init_qpos[:7] = np.array([0.0, 0.65, 0.0, 1.41, 0.0, -0.28,",
"else: # Create two (or three) parallel running task. #",
"1.4469]) if self._num_dof == 7 else np.array([0.758, 0, 1.5]) #",
"task ist done (successfully or not) dont_fail_after_succ_task = FinalRewTask( GoallessTask(spec,",
"binary forms, with or without # modification, are permitted provided",
"1e-2, 1e-2, 1e-1]) if self._num_dof == 7 else np.diag([0, 0,",
"cup) state_shape = np.concatenate([self.init_qpos, self.init_qvel, np.empty(3), np.empty(3)]).shape state_lo, state_up =",
"task_args: dict) -> Task: idcs = list(range(self.state_space.flat_dim - 3, self.state_space.flat_dim))",
"import EnvSpec from pyrado.utils.input_output import print_cbt class WAMBallInCupSim(MujocoSimEnv, Serializable): \"\"\"",
"1e-6, 5e0])), # Cartesian distance from init cup position R=task_args.get(",
"qvel_des - self.state[self.model.nq : self.model.nq + self._num_dof] # Compute the",
"dry friction coefficient of motor joint 4 [-] rope_damping=1e-4, #",
"ball collides with something else than the desired parts of",
"not use copy(), state_des coming from MuJoCo is a reference",
"'b') # center of mass # Observe the normalized time",
"Deviation task: Desired state task for the cartesian- and joint",
"by default the time step size is the one from",
"distribution. # 3. Neither the name of <NAME>, Honda Research",
"the `reset()` function, always pass a meaningful `init_state` .. seealso::",
"torque_space_wam_4dof, torque_space_wam_7dof, wam_pgains_7dof, wam_dgains_7dof, wam_pgains_4dof, wam_dgains_4dof, ) from pyrado.environments.mujoco.base import",
"if self.observe_ball: obs.extend([state[-3], state[-1]]) if self.observe_cup: obs.extend([state[-6], state[-4]]) return np.array(obs)",
"collides with something else than the central parts of the",
"messages on collision :return: `True` if the ball collides with",
"some time using the internal # PD controller to stabilize",
"always pass a meaningful `init_state` .. seealso:: [1] https://github.com/psclklnk/self-paced-rl/tree/master/sprl/envs/ball_in_a_cup.py \"\"\"",
"spec, condition_fcn=self.check_ball_in_cup, is_success_condition=True, ), mode=FinalRewMode(always_positive=True), factor=factor, ) # Yield -1",
"the arm are not reached (5 deg safety margin) state_lo[:",
"act_space(self) -> Space: # Running a PD controller on joint",
"being used :param frame_skip: number of simulation frames for which",
"# this is a reference # state_des_ball = self.sim.data.get_site_xpos(\"cup_goal\") #",
"is in the cup :return: `True` if the ball is",
"cup (geom_ids) cup_inner_id = self.model._geom_name2id[\"cup_inner\"] c1 = body1_name == \"ball\"",
"import print_cbt class WAMBallInCupSim(MujocoSimEnv, Serializable): \"\"\" WAM robotic arm from",
"time step size is the one from the mujoco config",
"# All rights reserved. # # Redistribution and use in",
"# Evaluate if the ball collides with part of the",
"= wam_q_limits_up_7dof[: self._num_dof] return BoxSpace(state_lo, state_up) @property def obs_space(self) ->",
"np.pi / 180 * np.array([0.1, 1, 0.5, 1.0, 0.1, 1.0,",
"of motor joint 4 [-] joint_5_dryfriction=0.4, # dry friction coefficient",
"MuJoCo is a reference and updates automatically at each step.",
":param task_args: arguments for the task construction \"\"\" Serializable._init(self, locals())",
"num_dof: number of degrees of freedom (4 or 7), depending",
"not) dont_fail_after_succ_task = FinalRewTask( GoallessTask(spec, ZeroPerStepRewFcn()), mode=FinalRewMode(always_negative=True), factor=factor, ) #",
"ball position into the observation :param observe_cup: if `True`, include",
"torques for the PD controller and clip them to their",
"act[:2]) np.add.at(qvel_des, [1, 3], act[2:]) elif self._num_dof == 7: np.add.at(qpos_des,",
"the `failed` flag in the `dict` returned by `_mujoco_step()` to",
"# dry friction coefficient of motor joint 2 [-] joint_3_dryfriction=0.4,",
"# dry friction coefficient of motor joint 1 [-] joint_2_dryfriction=0.4,",
"ball distance # 2.) Deviation task: Desired state task for",
") def _create_main_task(self, task_args: dict) -> Task: # Create a",
"1.0])[: self._num_dof] self._init_space = BoxSpace(init_state_lo, init_state_up) # Bodies to check",
"step. # Note: sim.forward() + get_body_xpos() results in wrong output",
"act: np.ndarray) -> dict: assert self.act_space.contains(act, verbose=True) # Get the",
"+ self.d_gains * err_vel torque = self.torque_space.project_to(torque) # Apply the",
"\"ball_z\"]) if self.observe_cup: obs_lo.extend([-3.0, -3.0]) obs_up.extend([3.0, 3.0]) labels.extend([\"cup_x\", \"cup_z\"]) return",
"(geom_ids) cup_inner_id = self.model._geom_name2id[\"cup_inner\"] c1 = body1_name == \"ball\" and",
"pyrado from pyrado.environments.barrett_wam import ( goal_pos_init_sim_4dof, goal_pos_init_sim_7dof, init_qpos_des_4dof, init_qpos_des_7dof, act_space_bic_4dof,",
"results in wrong output for state_des, as sim has not",
"7 dof, thus punish more ) task = DesStateTask(spec, state_des,",
"self._num_dof == 7: np.add.at(qpos_des, [1, 3, 5], act[:3]) np.add.at(qvel_des, [1,",
"self.p_gains = wam_pgains_4dof self.d_gains = wam_dgains_4dof init_ball_pos = np.array([0.723, 0.0,",
"simulation, it simply kills it. # Instead, we want the",
"in cartesian coordinates self._init_state = np.concatenate([self.init_qpos, self.init_qvel, init_ball_pos, init_cup_goal]) if",
"# modification, are permitted provided that the following conditions are",
"a trajectory with a specific `dt`. :param max_steps: max number",
"*args, verbose: bool = False): \"\"\" Check if the ball",
"COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND # ANY EXPRESS",
"coefficient of motor joint 1 [-] joint_2_dryfriction=0.4, # dry friction",
"3 [-] joint_4_dryfriction=0.4, # dry friction coefficient of motor joint",
"position and velocity errors err_pos = qpos_des - self.state[: self._num_dof]",
"0.0, -0.28, -1.57]) self.init_qpos[7] = -0.21 # angle of the",
"success_bonus=task_args.get(\"success_bonus\", 0), ) ), ] ) def _create_main_task(self, task_args: dict)",
"and clip them to their max values torque = self.p_gains",
"track elevation=-30, # camera rotation around the axis in the",
"wam_q_limits_lo_7dof[: self._num_dof] state_up[: self._num_dof] = wam_q_limits_up_7dof[: self._num_dof] return BoxSpace(state_lo, state_up)",
"# if self._curr_step == 0: # print_cbt(f'cup xpos: {self.sim.data.get_body_xpos(\"cup\").copy()}', 'b')",
"Serializable): \"\"\" WAM robotic arm from Barrett technologies for the",
"] if self._num_dof == 4: self._collision_bodies = self._collision_bodies[:6] # We",
"the ball with the robot ball_collided = self.check_ball_collisions() if self.stop_on_collision",
"every geom has a name self._collision_geom_ids = [self.model._geom_name2id[name] for name",
"1.0, 1.0])[: self._num_dof] init_state_lo = self._init_state.copy() init_state_lo[: self._num_dof] -= np.pi",
"1e-6) ) else: raise pyrado.ValueErr(given=num_dof, eq_constraint=\"4 or 7\") def _create_task(self,",
"punish more ) task = DesStateTask(spec, state_des, rew_fcn) # Wrap",
"position spec = EnvSpec( self.spec.obs_space, self.spec.act_space, self.spec.state_space.subspace(self.spec.state_space.create_mask(idcs)), ) # If",
"state is out of bounds (this is normally checked by",
") if c1 or c2: if verbose: print_cbt( f\"Undesired collision",
"# If state is out of bounds (this is normally",
"of motor joint 1 [-] joint_2_dryfriction=0.4, # dry friction coefficient",
"None: # See [1, l.93-96] xml_model = xml_model.replace(\"[scale_mesh]\", str(cup_scale *",
"# 3. Neither the name of <NAME>, Honda Research Institute",
"== 4: self._collision_bodies = self._collision_bodies[:6] # We access a private",
"NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND",
"of conditions and the following disclaimer in the # documentation",
"is small) joint_7_damping=0.05, # damping of motor joints [N/s] (default",
"if c1 or c2: if verbose: print_cbt( f\"Undesired collision of",
"the one from the mujoco config file multiplied by the",
"Apply the torques to the robot self.sim.data.qfrc_applied[: self._num_dof] = torque",
"Extract the (x, z) cartesian position of cup and ball",
"(cup_scale - 1.0) * 0.023)) xml_model = xml_model.replace(\"[pos_goal]\", str(0.1165 +",
"6, self.state_space.flat_dim - 3)) # Cartesian ball position spec =",
"seealso:: [1] https://github.com/psclklnk/self-paced-rl/tree/master/sprl/envs/ball_in_a_cup.py \"\"\" name: str = \"wam-bic\" def __init__(",
"is small) joint_6_damping=0.05, # damping of motor joints [N/s] (default",
"ParallelTasks( [ self._create_main_task(task_args), self._create_deviation_task(task_args), self._create_main_task( dict( sparse_rew_fcn=True, success_bonus=task_args.get(\"success_bonus\", 0), )",
"in self._collision_bodies or contact.geom1 in self._collision_geom_ids ) if c1 or",
"self.camera_config = dict( distance=2.7, trackbodyid=0, # id of the body",
"= xml_model.replace(\"[pos_capsule_joint]\", str(-rope_length / 60)) # Pure visualization component xml_model",
"ON ANY THEORY OF LIABILITY, WHETHER # IN CONTRACT, STRICT",
"HONDA RESEARCH INSTITUTE EUROPE GMBH, # OR TECHNICAL UNIVERSITY OF",
"software without # specific prior written permission. # # THIS",
"xml_model = xml_model.replace(\"[pos_mesh]\", str(0.055 - (cup_scale - 1.0) * 0.023))",
"Actual initial joint position (when the WAM moved to the",
"ParallelTasks from pyrado.tasks.reward_functions import ZeroPerStepRewFcn, ExpQuadrErrRewFcn, QuadrErrRewFcn from pyrado.tasks.sequential import",
"self._num_dof] += np.pi / 180 * np.array([0.1, 1, 0.5, 1.0,",
"# dry friction coefficient of motor joint 7 [-] rope_damping=1e-4,",
"state task for the cartesian ball distance # 2.) Deviation",
"frame skips (legacy from OpenAI environments). By passing an explicit",
"1.0, 1.0])[: self._num_dof] self._init_space = BoxSpace(init_state_lo, init_state_up) # Bodies to",
"without # specific prior written permission. # # THIS SOFTWARE",
"that joint limits of the arm are not reached (5",
"binary reward return self._create_main_task(task_args) else: # Create two (or three)",
"+ self._num_dof] # Compute the torques for the PD controller",
"part of the WAM (collision bodies) # or the connection",
"WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES",
"state_up[: self._num_dof] = wam_q_limits_up_7dof[: self._num_dof] return BoxSpace(state_lo, state_up) @property def",
"normalized time obs = [self._curr_step / self.max_steps] # Extract the",
"obs_up.extend([3.0, 3.0]) labels.extend([\"ball_x\", \"ball_z\"]) if self.observe_cup: obs_lo.extend([-3.0, -3.0]) obs_up.extend([3.0, 3.0])",
"MaskedTask(self.spec, task, idcs), factor=task_args.get(\"final_factor\", 0.05 * self.max_steps), ) def _create_deviation_task(self,",
"end with a failure. mjsim_crashed = True qpos, qvel =",
"'model.geom_names[geom_id]' cannot be used because # not every geom has",
"1, 1e-2, 1e-2, 1e-1]) if self._num_dof == 7 else np.diag([0,",
"joint 4 [-] rope_damping=1e-4, # damping of rope joints [N/s]",
"import ParallelTasks from pyrado.tasks.reward_functions import ZeroPerStepRewFcn, ExpQuadrErrRewFcn, QuadrErrRewFcn from pyrado.tasks.sequential",
"num_dof == 4: return dict( cup_scale=1.0, # scaling factor for",
"self._collision_geom_ids ) c2 = body2_name == \"ball\" and ( body1_name",
"and/or other materials provided with the distribution. # 3. Neither",
"if self.stop_on_collision else False # If state is out of",
"obs_up, labels = [0.0], [1.0], [\"t\"] if self.observe_ball: obs_lo.extend([-3.0, -3.0])",
"state_des = self.sim.data.get_site_xpos(\"cup_goal\") # this is a reference # state_des_ball",
"mjsim_crashed = True qpos, qvel = self.sim.data.qpos.copy(), self.sim.data.qvel.copy() ball_pos =",
"= fixed_init_state self.observe_ball = observe_ball self.observe_cup = observe_cup # Initialize",
"# Binary final reward task main_task = FinalRewTask( ConditionOnlyTask( spec,",
"an undesired collision with the ball occurs. :param verbose: print",
"eq_constraint=\"4 or 7\") model_path = osp.join(pyrado.MUJOCO_ASSETS_DIR, graph_file_name) super().__init__(model_path, frame_skip, dt,",
"task, idcs) else: state_des = self.sim.data.get_site_xpos(\"cup_goal\") # this is a",
"Create a DesStateTask that masks everything but the ball position",
"= self.torque_space.project_to(torque) # Apply the torques to the robot self.sim.data.qfrc_applied[:",
"plus/minus one degree to each motor joint and the first",
"Extract body-id and body-name of both contact geoms body1 =",
": self.model.nq + self._num_dof] # Compute the torques for the",
"except mujoco_py.builder.MujocoException: # When MuJoCo recognized instabilities in the simulation,",
"Possible use case if if you know that you recorded",
"this list of conditions and the following disclaimer in the",
"{body2_name} detected!\", \"y\", ) return True return False def check_ball_in_cup(self,",
"CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER # IN",
"GoallessTask from pyrado.tasks.masked import MaskedTask from pyrado.tasks.parallel import ParallelTasks from",
"cartesian- and joint deviation from the init position # 3.)",
"of the mask) state_oob = False if self.state_space.contains(self.state) else True",
"= None, ): \"\"\" Constructor :param num_dof: number of degrees",
"relative to the cup bottom plate else: self.init_qpos[:7] = np.array([0.0,",
"verbose: print_cbt(f\"The ball is in the cup at time step",
"OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED",
"# Technical University of Darmstadt. # All rights reserved. #",
"the main task ist done (successfully or not) dont_fail_after_succ_task =",
"to true, if the ball collides with something else than",
"# state_des_ball = self.sim.data.get_site_xpos(\"cup_goal\") # this is a reference #",
"locals()) self.fixed_init_state = fixed_init_state self.observe_ball = observe_ball self.observe_cup = observe_cup",
"(default value is small) joint_6_damping=0.05, # damping of motor joints",
"task, idcs), factor=task_args.get(\"final_factor\", 0.05 * self.max_steps), ) def _create_deviation_task(self, task_args:",
"or 7\") model_path = osp.join(pyrado.MUJOCO_ASSETS_DIR, graph_file_name) super().__init__(model_path, frame_skip, dt, max_steps,",
"but the ball position idcs = list(range(self.state_space.flat_dim - 6, self.state_space.flat_dim",
"from this software without # specific prior written permission. #",
"fail after the main task ist done (successfully or not)",
"as np import os.path as osp from init_args_serializer import Serializable",
"held, results in a multiplier of the time step size",
"- (cup_scale - 1.0) * 0.023)) xml_model = xml_model.replace(\"[pos_goal]\", str(0.1165",
"= False) -> bool: \"\"\" Check if an undesired collision",
"np.array([0.758, 0, 1.5]) # state_des = np.concatenate([state_des_ball, state_des_cup]) R_default =",
"act_space_bic_4dof @classmethod def get_nominal_domain_param(cls, num_dof: int = 7) -> dict:",
"state_des, rew_fcn) return MaskedTask(self.spec, task, idcs) def _adapt_model_file(self, xml_model: str,",
"joint_3_dryfriction=0.4, # dry friction coefficient of motor joint 3 [-]",
"work because of the mask) state_oob = False if self.state_space.contains(self.state)",
"wam_q_limits_lo_7dof, torque_space_wam_4dof, torque_space_wam_7dof, wam_pgains_7dof, wam_dgains_7dof, wam_pgains_4dof, wam_dgains_4dof, ) from pyrado.environments.mujoco.base",
"self.model.nq + self._num_dof] # Compute the torques for the PD",
"self._collision_bodies = [ \"wam/base_link\", \"wam/shoulder_yaw_link\", \"wam/shoulder_pitch_link\", \"wam/upper_arm_link\", \"wam/forearm_link\", \"wrist_palm_link\", \"wam/wrist_pitch_link\",",
"= wam_dgains_4dof init_ball_pos = np.array([0.723, 0.0, 1.168]) init_cup_goal = goal_pos_init_sim_4dof",
"if self.observe_cup: obs_lo.extend([-3.0, -3.0]) obs_up.extend([3.0, 3.0]) labels.extend([\"cup_x\", \"cup_z\"]) return BoxSpace(obs_lo,",
"- 3)) # Cartesian ball position spec = EnvSpec( self.spec.obs_space,",
"which the same action is held, results in a multiplier",
"else: state_des = self.sim.data.get_site_xpos(\"cup_goal\") # this is a reference #",
"mass of the ball [kg] joint_1_damping=0.05, # damping of motor",
"import SingularStateSpace from pyrado.tasks.base import Task from pyrado.tasks.condition_only import ConditionOnlyTask",
"something else than the central parts of the cup \"\"\"",
"of the rope [m] ball_mass=0.024, # mass of the ball",
"= torque # Call MuJoCo try: self.sim.step() mjsim_crashed = False",
"(successfully or not) dont_fail_after_succ_task = FinalRewTask( GoallessTask(spec, ZeroPerStepRewFcn()), mode=FinalRewMode(always_negative=True), factor=factor,",
"# Create a DesStateTask that masks everything but the ball",
"or contact.geom2 in self._collision_geom_ids ) c2 = body2_name == \"ball\"",
"(default value is small) joint_1_dryfriction=0.4, # dry friction coefficient of",
"num_dof: int = 7) -> dict: if num_dof == 7:",
"np.ndarray: # TODO: Debug print-outs, should be removed in future...",
"def _create_main_task(self, task_args: dict) -> Task: # Create a DesStateTask",
"# Call MuJoCo try: self.sim.step() mjsim_crashed = False except mujoco_py.builder.MujocoException:",
"init_ball_pos = np.array([0.828, 0.0, 1.131]) init_cup_goal = goal_pos_init_sim_7dof else: raise",
"if self._num_dof == 7 else act_space_bic_4dof @classmethod def get_nominal_domain_param(cls, num_dof:",
"[N/s] (reasonable values are 6e-4 to 1e-6) ) else: raise",
"OpenAI environments). By passing an explicit `dt` value, this can",
"xml_model = xml_model.replace(\"[size_cup]\", str(cup_scale * 0.038)) xml_model = xml_model.replace(\"[size_cup_inner]\", str(cup_scale",
"to self._qpos_des_init qvel_des = np.zeros_like(qpos_des) if self._num_dof == 4: np.add.at(qpos_des,",
"# Compute the position and velocity errors err_pos = qpos_des",
"space (including ball and cup) state_shape = np.concatenate([self.init_qpos, self.init_qvel, np.empty(3),",
"goal position spec = EnvSpec( self.spec.obs_space, self.spec.act_space, self.spec.state_space.subspace(self.spec.state_space.create_mask(idcs)), ) #",
"access a private attribute since a method like 'model.geom_names[geom_id]' cannot",
"_adapt_model_file(self, xml_model: str, domain_param: dict) -> str: # First replace",
"import Task from pyrado.tasks.condition_only import ConditionOnlyTask from pyrado.tasks.desired_state import DesStateTask",
"bool = False) -> bool: \"\"\" Check if an undesired",
"3, 5], act[3:]) # Compute the position and velocity errors",
"xml_model = xml_model.replace(\"[pos_capsule]\", str(rope_length / 30)) # Each joint is",
"each motor joint and the first rope segment joint init_state_up",
"qvel = self.sim.data.qpos.copy(), self.sim.data.qvel.copy() ball_pos = self.sim.data.get_body_xpos(\"ball\").copy() cup_goal = self.sim.data.get_site_xpos(\"cup_goal\").copy()",
"Redistributions in binary form must reproduce the above copyright #",
"damping of motor joints [N/s] (default value is small) joint_3_damping=0.05,",
"damping of motor joints [N/s] (default value is small) joint_6_damping=0.05,",
"self.sim.data.get_site_xpos(\"cup_goal\") # this is a reference # state_des_ball = self.sim.data.get_site_xpos(\"cup_goal\")",
"np.add.at(qpos_des, [1, 3], act[:2]) np.add.at(qvel_des, [1, 3], act[2:]) elif self._num_dof",
"2020, <NAME>, Honda Research Institute Europe GmbH, and # Technical",
"-> Task: if task_args.get(\"sparse_rew_fcn\", False): # Create a task with",
"`True`, include the 2-dim (x-z plane) cartesian ball position into",
"3. Neither the name of <NAME>, Honda Research Institute Europe",
"self._num_dof == 7 else torque_space_wam_4dof @property def state_space(self) -> Space:",
"be used because # not every geom has a name",
"rope joints [N/s] (reasonable values are 6e-4 to 1e-6) )",
"ball [kg] joint_1_damping=0.05, # damping of motor joints [N/s] (default",
"1. Redistributions of source code must retain the above copyright",
"if you know that you recorded a trajectory with a",
"str(rope_length / 30)) # Each joint is at the top",
"fo collision self._collision_bodies = [ \"wam/base_link\", \"wam/shoulder_yaw_link\", \"wam/shoulder_pitch_link\", \"wam/upper_arm_link\", \"wam/forearm_link\",",
":param observe_ball: if `True`, include the 2-dim (x-z plane) cartesian",
"dry friction coefficient of motor joint 6 [-] joint_7_dryfriction=0.4, #",
"init cup goal position state_des = goal_pos_init_sim_7dof if self._num_dof ==",
"episode to end with a failure. mjsim_crashed = True qpos,",
"first called in reset() if task_args.get(\"sparse_rew_fcn\", False): factor = task_args.get(\"success_bonus\",",
"== 4: graph_file_name = \"wam_4dof_bic.xml\" self.qpos_des_init = init_qpos_des_4dof self.p_gains =",
"joint_3_damping=0.05, # damping of motor joints [N/s] (default value is",
"= qpos_des - self.state[: self._num_dof] err_vel = qvel_des - self.state[self.model.nq",
"wam_pgains_7dof self.d_gains = wam_dgains_7dof init_ball_pos = np.array([0.828, 0.0, 1.131]) init_cup_goal",
"= xml_model.replace(\"[size_cup]\", str(cup_scale * 0.038)) xml_model = xml_model.replace(\"[size_cup_inner]\", str(cup_scale *",
"* 0.038)) xml_model = xml_model.replace(\"[size_cup_inner]\", str(cup_scale * 0.03)) if rope_length",
"joint and the first rope segment joint init_state_up = self._init_state.copy()",
"controller on joint positions and velocities return act_space_bic_7dof if self._num_dof",
"capsule (therefore negative direction from center) xml_model = xml_model.replace(\"[pos_capsule_joint]\", str(-rope_length",
"init_args_serializer import Serializable from typing import Optional import pyrado from",
"max number of simulation time steps :param fixed_init_state: enables/disables deterministic,",
"fixed initial state :param stop_on_collision: set the `failed` flag in",
"else act_space_bic_4dof @classmethod def get_nominal_domain_param(cls, num_dof: int = 7) ->",
"domain parameters cup_scale = domain_param.pop(\"cup_scale\", None) rope_length = domain_param.pop(\"rope_length\", None)",
"self.state = np.concatenate([qpos, qvel, ball_pos, cup_goal]) # If desired, check",
"obs_up, labels=labels) @property def act_space(self) -> Space: # Running a",
") return True return False def check_ball_in_cup(self, *args, verbose: bool",
"elif num_dof == 7: graph_file_name = \"wam_7dof_bic.xml\" self.qpos_des_init = init_qpos_des_7dof",
"value is small) joint_6_damping=0.05, # damping of motor joints [N/s]",
"detected!\", \"y\", ) return True return False def check_ball_in_cup(self, *args,",
"= self.p_gains * err_pos + self.d_gains * err_vel torque =",
"[N/s] (default value is small) joint_5_damping=0.05, # damping of motor",
"np.concatenate([qpos, qvel, ball_pos, cup_goal]) # If desired, check for collisions",
"(INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS",
"Space from pyrado.spaces.box import BoxSpace from pyrado.spaces.singular import SingularStateSpace from",
"= self.model.geom_bodyid[contact.geom2] body2_name = self.model.body_names[body2] # Evaluate if the ball",
"PD controller on joint positions and velocities return act_space_bic_7dof if",
"contact.geom2 in self._collision_geom_ids ) c2 = body2_name == \"ball\" and",
"# Pure visualization component xml_model = xml_model.replace(\"[size_capsule_geom]\", str(rope_length / 72))",
"but does not work because of the mask) state_oob =",
"origin of the rigid body object 'cup' if self.observe_ball: obs.extend([state[-3],",
"pyrado.utils.data_types import EnvSpec from pyrado.utils.input_output import print_cbt class WAMBallInCupSim(MujocoSimEnv, Serializable):",
"@property def torque_space(self) -> Space: \"\"\" Get the space of",
"is first called in reset() if task_args.get(\"sparse_rew_fcn\", False): factor =",
"pyrado.spaces.base import Space from pyrado.spaces.box import BoxSpace from pyrado.spaces.singular import"
] |
[
"pyRasp # Copyright (c) <NAME> 2020. Licensed under MIT. #",
"requirement : # Python 3 # pip install pyyaml #",
"from prepare_wrf import prepare_wrf from real import real from wrf",
"pip install f90nml from downloadGFSA import downloadGFSA from prepare_wps import",
"downloadGFSA from prepare_wps import prepare_wps from ungrib import ungrib from",
"from ungrib import ungrib from metgrid import metgrid from prepare_wrf",
"import prepare_wrf from real import real from wrf import wrf",
"2020. Licensed under MIT. # requirement : # Python 3",
"under MIT. # requirement : # Python 3 # pip",
"import metgrid from prepare_wrf import prepare_wrf from real import real",
"ungrib from metgrid import metgrid from prepare_wrf import prepare_wrf from",
"# pip install request # pip install f90nml from downloadGFSA",
"pyyaml # pip install request # pip install f90nml from",
"metgrid from prepare_wrf import prepare_wrf from real import real from",
"# pip install pyyaml # pip install request # pip",
": # Python 3 # pip install pyyaml # pip",
"install pyyaml # pip install request # pip install f90nml",
"pip install request # pip install f90nml from downloadGFSA import",
"wrf import wrf result = downloadGFSA(True) prepare_wps(result) ungrib() metgrid() prepare_wrf(result)",
"MIT. # requirement : # Python 3 # pip install",
"Licensed under MIT. # requirement : # Python 3 #",
"# Python 3 # pip install pyyaml # pip install",
"real from wrf import wrf result = downloadGFSA(True) prepare_wps(result) ungrib()",
"import wrf result = downloadGFSA(True) prepare_wps(result) ungrib() metgrid() prepare_wrf(result) real()",
"# Copyright (c) <NAME> 2020. Licensed under MIT. # requirement",
"3 # pip install pyyaml # pip install request #",
"ungrib import ungrib from metgrid import metgrid from prepare_wrf import",
"import prepare_wps from ungrib import ungrib from metgrid import metgrid",
"downloadGFSA import downloadGFSA from prepare_wps import prepare_wps from ungrib import",
"# pip install f90nml from downloadGFSA import downloadGFSA from prepare_wps",
"from prepare_wps import prepare_wps from ungrib import ungrib from metgrid",
"from metgrid import metgrid from prepare_wrf import prepare_wrf from real",
"import ungrib from metgrid import metgrid from prepare_wrf import prepare_wrf",
"metgrid import metgrid from prepare_wrf import prepare_wrf from real import",
"install f90nml from downloadGFSA import downloadGFSA from prepare_wps import prepare_wps",
"prepare_wps import prepare_wps from ungrib import ungrib from metgrid import",
"(c) <NAME> 2020. Licensed under MIT. # requirement : #",
"real import real from wrf import wrf result = downloadGFSA(True)",
"wrf result = downloadGFSA(True) prepare_wps(result) ungrib() metgrid() prepare_wrf(result) real() wrf()",
"request # pip install f90nml from downloadGFSA import downloadGFSA from",
"# requirement : # Python 3 # pip install pyyaml",
"install request # pip install f90nml from downloadGFSA import downloadGFSA",
"f90nml from downloadGFSA import downloadGFSA from prepare_wps import prepare_wps from",
"import real from wrf import wrf result = downloadGFSA(True) prepare_wps(result)",
"prepare_wrf from real import real from wrf import wrf result",
"Python 3 # pip install pyyaml # pip install request",
"prepare_wps from ungrib import ungrib from metgrid import metgrid from",
"Copyright (c) <NAME> 2020. Licensed under MIT. # requirement :",
"from real import real from wrf import wrf result =",
"import downloadGFSA from prepare_wps import prepare_wps from ungrib import ungrib",
"pip install pyyaml # pip install request # pip install",
"<NAME> 2020. Licensed under MIT. # requirement : # Python",
"from wrf import wrf result = downloadGFSA(True) prepare_wps(result) ungrib() metgrid()",
"prepare_wrf import prepare_wrf from real import real from wrf import",
"from downloadGFSA import downloadGFSA from prepare_wps import prepare_wps from ungrib",
"# pyRasp # Copyright (c) <NAME> 2020. Licensed under MIT."
] |
[
"] def can_buy(self, df): prev_candle = self.candle(df) last_ema = prev_candle[\"close_3_ema\"]",
"BaseStrategy pd.set_option(\"display.max_columns\", None) pd.set_option(\"display.width\", None) class EMABBAlligatorStrategy(BaseStrategy): BUY_SIGNAL = \"buy_signal\"",
"ao.ao() return df def can_sell(self, df): prev_candle = self.candle(df) last_ema",
"prev_candle = self.candle(df) last_ema = prev_candle[\"close_3_ema\"] last_bb = prev_candle[\"boll\"] return",
"as pd import ta from app.common import reshape_data from app.strategies.base_strategy",
"= df[\"close_3_ema\"] _ = df[\"boll\"] ao = ta.momentum.AwesomeOscillatorIndicator(high=df[\"high\"], low=df[\"low\"]) df[\"AO\"]",
"app.strategies.base_strategy import BaseStrategy pd.set_option(\"display.max_columns\", None) pd.set_option(\"display.width\", None) class EMABBAlligatorStrategy(BaseStrategy): BUY_SIGNAL",
"import BaseStrategy pd.set_option(\"display.max_columns\", None) pd.set_option(\"display.width\", None) class EMABBAlligatorStrategy(BaseStrategy): BUY_SIGNAL =",
"= self.candle(df) last_ema = prev_candle[\"close_3_ema\"] last_bb = prev_candle[\"boll\"] return [",
"pandas as pd import ta from app.common import reshape_data from",
"self.load_df(limit=1000) _ = df[\"close_3_ema\"] _ = df[\"boll\"] ao = ta.momentum.AwesomeOscillatorIndicator(high=df[\"high\"],",
"low=df[\"low\"]) df[\"AO\"] = ao.ao() return df def can_sell(self, df): prev_candle",
"0) & (self.candle(df, rewind=-1)[\"AO\"] < 0), prev_candle[\"volume\"] > 0, ]",
"prev_candle[\"volume\"] > 0, ] def alert_message(self, df): prev_candle = self.candle(df)",
"self.candle(df) last_close = prev_candle[\"close\"] last_ao = prev_candle[\"AO\"] return ( \"Close:",
"df[\"close_3_ema\"] _ = df[\"boll\"] ao = ta.momentum.AwesomeOscillatorIndicator(high=df[\"high\"], low=df[\"low\"]) df[\"AO\"] =",
"def alert_message(self, df): prev_candle = self.candle(df) last_close = prev_candle[\"close\"] last_ao",
"EMABBAlligatorStrategy(BaseStrategy): BUY_SIGNAL = \"buy_signal\" SELL_SIGNAL = \"sell_signal\" def calculate_indicators(self): df",
"df[\"boll\"] ao = ta.momentum.AwesomeOscillatorIndicator(high=df[\"high\"], low=df[\"low\"]) df[\"AO\"] = ao.ao() return df",
"import pandas as pd import ta from app.common import reshape_data",
"& (self.candle(df, rewind=-1)[\"AO\"] > 0), prev_candle[\"volume\"] > 0, ] def",
"df = self.load_df(limit=1000) _ = df[\"close_3_ema\"] _ = df[\"boll\"] ao",
"= prev_candle[\"close\"] last_ao = prev_candle[\"AO\"] return ( \"Close: {:.2f}, Awesome",
"_ = df[\"boll\"] ao = ta.momentum.AwesomeOscillatorIndicator(high=df[\"high\"], low=df[\"low\"]) df[\"AO\"] = ao.ao()",
"last_close = prev_candle[\"close\"] last_ao = prev_candle[\"AO\"] return ( \"Close: {:.2f},",
"0, ] def can_buy(self, df): prev_candle = self.candle(df) last_ema =",
"( \"Close: {:.2f}, Awesome Oscillator value: {:.2f}\".format( last_close, last_ao ),",
"prev_candle[\"AO\"] return ( \"Close: {:.2f}, Awesome Oscillator value: {:.2f}\".format( last_close,",
"from app.common import reshape_data from app.strategies.base_strategy import BaseStrategy pd.set_option(\"display.max_columns\", None)",
"from app.strategies.base_strategy import BaseStrategy pd.set_option(\"display.max_columns\", None) pd.set_option(\"display.width\", None) class EMABBAlligatorStrategy(BaseStrategy):",
"reshape_data from app.strategies.base_strategy import BaseStrategy pd.set_option(\"display.max_columns\", None) pd.set_option(\"display.width\", None) class",
"> 0, ] def can_buy(self, df): prev_candle = self.candle(df) last_ema",
"can_buy(self, df): prev_candle = self.candle(df) last_ema = prev_candle[\"close_3_ema\"] last_bb =",
"df[\"AO\"] = ao.ao() return df def can_sell(self, df): prev_candle =",
"None) class EMABBAlligatorStrategy(BaseStrategy): BUY_SIGNAL = \"buy_signal\" SELL_SIGNAL = \"sell_signal\" def",
"= self.load_df(limit=1000) _ = df[\"close_3_ema\"] _ = df[\"boll\"] ao =",
"> 0) & (self.candle(df, rewind=-1)[\"AO\"] < 0), prev_candle[\"volume\"] > 0,",
"rewind=-1)[\"AO\"] > 0), prev_candle[\"volume\"] > 0, ] def alert_message(self, df):",
"df): prev_candle = self.candle(df) last_ema = prev_candle[\"close_3_ema\"] last_bb = prev_candle[\"boll\"]",
"(self.candle(df, rewind=-1)[\"AO\"] < 0), prev_candle[\"volume\"] > 0, ] def can_buy(self,",
"rewind=-2)[\"AO\"] < 0) & (self.candle(df, rewind=-1)[\"AO\"] > 0), prev_candle[\"volume\"] >",
"_ = df[\"close_3_ema\"] _ = df[\"boll\"] ao = ta.momentum.AwesomeOscillatorIndicator(high=df[\"high\"], low=df[\"low\"])",
"can_sell(self, df): prev_candle = self.candle(df) last_ema = prev_candle[\"close_3_ema\"] last_bb =",
"\"Close: {:.2f}, Awesome Oscillator value: {:.2f}\".format( last_close, last_ao ), )",
"pd.set_option(\"display.max_columns\", None) pd.set_option(\"display.width\", None) class EMABBAlligatorStrategy(BaseStrategy): BUY_SIGNAL = \"buy_signal\" SELL_SIGNAL",
"calculate_indicators(self): df = self.load_df(limit=1000) _ = df[\"close_3_ema\"] _ = df[\"boll\"]",
"> last_bb, (self.candle(df, rewind=-2)[\"AO\"] < 0) & (self.candle(df, rewind=-1)[\"AO\"] >",
"] def alert_message(self, df): prev_candle = self.candle(df) last_close = prev_candle[\"close\"]",
"return ( \"Close: {:.2f}, Awesome Oscillator value: {:.2f}\".format( last_close, last_ao",
"0) & (self.candle(df, rewind=-1)[\"AO\"] > 0), prev_candle[\"volume\"] > 0, ]",
"pd.set_option(\"display.width\", None) class EMABBAlligatorStrategy(BaseStrategy): BUY_SIGNAL = \"buy_signal\" SELL_SIGNAL = \"sell_signal\"",
"prev_candle[\"close\"] last_ao = prev_candle[\"AO\"] return ( \"Close: {:.2f}, Awesome Oscillator",
"return [ last_ema > last_bb, (self.candle(df, rewind=-2)[\"AO\"] < 0) &",
"prev_candle[\"close_3_ema\"] last_bb = prev_candle[\"boll\"] return [ last_ema > last_bb, (self.candle(df,",
"last_ao = prev_candle[\"AO\"] return ( \"Close: {:.2f}, Awesome Oscillator value:",
"alert_message(self, df): prev_candle = self.candle(df) last_close = prev_candle[\"close\"] last_ao =",
"= prev_candle[\"close_3_ema\"] last_bb = prev_candle[\"boll\"] return [ last_ema > last_bb,",
"last_bb = prev_candle[\"boll\"] return [ last_ema > last_bb, (self.candle(df, rewind=-2)[\"AO\"]",
"SELL_SIGNAL = \"sell_signal\" def calculate_indicators(self): df = self.load_df(limit=1000) _ =",
"last_ema < last_bb, (self.candle(df, rewind=-2)[\"AO\"] > 0) & (self.candle(df, rewind=-1)[\"AO\"]",
"prev_candle = self.candle(df) last_close = prev_candle[\"close\"] last_ao = prev_candle[\"AO\"] return",
"< last_bb, (self.candle(df, rewind=-2)[\"AO\"] > 0) & (self.candle(df, rewind=-1)[\"AO\"] <",
"def can_buy(self, df): prev_candle = self.candle(df) last_ema = prev_candle[\"close_3_ema\"] last_bb",
"\"buy_signal\" SELL_SIGNAL = \"sell_signal\" def calculate_indicators(self): df = self.load_df(limit=1000) _",
"> 0, ] def alert_message(self, df): prev_candle = self.candle(df) last_close",
"rewind=-1)[\"AO\"] < 0), prev_candle[\"volume\"] > 0, ] def can_buy(self, df):",
"= prev_candle[\"close_3_ema\"] last_bb = prev_candle[\"boll\"] return [ last_ema < last_bb,",
"= prev_candle[\"boll\"] return [ last_ema > last_bb, (self.candle(df, rewind=-2)[\"AO\"] <",
"< 0) & (self.candle(df, rewind=-1)[\"AO\"] > 0), prev_candle[\"volume\"] > 0,",
"BUY_SIGNAL = \"buy_signal\" SELL_SIGNAL = \"sell_signal\" def calculate_indicators(self): df =",
"0), prev_candle[\"volume\"] > 0, ] def alert_message(self, df): prev_candle =",
"0), prev_candle[\"volume\"] > 0, ] def can_buy(self, df): prev_candle =",
"(self.candle(df, rewind=-1)[\"AO\"] > 0), prev_candle[\"volume\"] > 0, ] def alert_message(self,",
"last_ema = prev_candle[\"close_3_ema\"] last_bb = prev_candle[\"boll\"] return [ last_ema <",
"last_bb, (self.candle(df, rewind=-2)[\"AO\"] > 0) & (self.candle(df, rewind=-1)[\"AO\"] < 0),",
"> 0), prev_candle[\"volume\"] > 0, ] def alert_message(self, df): prev_candle",
"= \"buy_signal\" SELL_SIGNAL = \"sell_signal\" def calculate_indicators(self): df = self.load_df(limit=1000)",
"= \"sell_signal\" def calculate_indicators(self): df = self.load_df(limit=1000) _ = df[\"close_3_ema\"]",
"prev_candle[\"volume\"] > 0, ] def can_buy(self, df): prev_candle = self.candle(df)",
"(self.candle(df, rewind=-2)[\"AO\"] > 0) & (self.candle(df, rewind=-1)[\"AO\"] < 0), prev_candle[\"volume\"]",
"return df def can_sell(self, df): prev_candle = self.candle(df) last_ema =",
"prev_candle[\"close_3_ema\"] last_bb = prev_candle[\"boll\"] return [ last_ema < last_bb, (self.candle(df,",
"None) pd.set_option(\"display.width\", None) class EMABBAlligatorStrategy(BaseStrategy): BUY_SIGNAL = \"buy_signal\" SELL_SIGNAL =",
"= df[\"boll\"] ao = ta.momentum.AwesomeOscillatorIndicator(high=df[\"high\"], low=df[\"low\"]) df[\"AO\"] = ao.ao() return",
"return [ last_ema < last_bb, (self.candle(df, rewind=-2)[\"AO\"] > 0) &",
"prev_candle[\"boll\"] return [ last_ema < last_bb, (self.candle(df, rewind=-2)[\"AO\"] > 0)",
"import ta from app.common import reshape_data from app.strategies.base_strategy import BaseStrategy",
"ao = ta.momentum.AwesomeOscillatorIndicator(high=df[\"high\"], low=df[\"low\"]) df[\"AO\"] = ao.ao() return df def",
"[ last_ema < last_bb, (self.candle(df, rewind=-2)[\"AO\"] > 0) & (self.candle(df,",
"pd import ta from app.common import reshape_data from app.strategies.base_strategy import",
"[ last_ema > last_bb, (self.candle(df, rewind=-2)[\"AO\"] < 0) & (self.candle(df,",
"ta.momentum.AwesomeOscillatorIndicator(high=df[\"high\"], low=df[\"low\"]) df[\"AO\"] = ao.ao() return df def can_sell(self, df):",
"rewind=-2)[\"AO\"] > 0) & (self.candle(df, rewind=-1)[\"AO\"] < 0), prev_candle[\"volume\"] >",
"def can_sell(self, df): prev_candle = self.candle(df) last_ema = prev_candle[\"close_3_ema\"] last_bb",
"class EMABBAlligatorStrategy(BaseStrategy): BUY_SIGNAL = \"buy_signal\" SELL_SIGNAL = \"sell_signal\" def calculate_indicators(self):",
"= ao.ao() return df def can_sell(self, df): prev_candle = self.candle(df)",
"self.candle(df) last_ema = prev_candle[\"close_3_ema\"] last_bb = prev_candle[\"boll\"] return [ last_ema",
"= self.candle(df) last_close = prev_candle[\"close\"] last_ao = prev_candle[\"AO\"] return (",
"\"sell_signal\" def calculate_indicators(self): df = self.load_df(limit=1000) _ = df[\"close_3_ema\"] _",
"df def can_sell(self, df): prev_candle = self.candle(df) last_ema = prev_candle[\"close_3_ema\"]",
"(self.candle(df, rewind=-2)[\"AO\"] < 0) & (self.candle(df, rewind=-1)[\"AO\"] > 0), prev_candle[\"volume\"]",
"ta from app.common import reshape_data from app.strategies.base_strategy import BaseStrategy pd.set_option(\"display.max_columns\",",
"def calculate_indicators(self): df = self.load_df(limit=1000) _ = df[\"close_3_ema\"] _ =",
"last_bb = prev_candle[\"boll\"] return [ last_ema < last_bb, (self.candle(df, rewind=-2)[\"AO\"]",
"last_ema = prev_candle[\"close_3_ema\"] last_bb = prev_candle[\"boll\"] return [ last_ema >",
"& (self.candle(df, rewind=-1)[\"AO\"] < 0), prev_candle[\"volume\"] > 0, ] def",
"import reshape_data from app.strategies.base_strategy import BaseStrategy pd.set_option(\"display.max_columns\", None) pd.set_option(\"display.width\", None)",
"df): prev_candle = self.candle(df) last_close = prev_candle[\"close\"] last_ao = prev_candle[\"AO\"]",
"last_bb, (self.candle(df, rewind=-2)[\"AO\"] < 0) & (self.candle(df, rewind=-1)[\"AO\"] > 0),",
"= ta.momentum.AwesomeOscillatorIndicator(high=df[\"high\"], low=df[\"low\"]) df[\"AO\"] = ao.ao() return df def can_sell(self,",
"prev_candle[\"boll\"] return [ last_ema > last_bb, (self.candle(df, rewind=-2)[\"AO\"] < 0)",
"< 0), prev_candle[\"volume\"] > 0, ] def can_buy(self, df): prev_candle",
"= prev_candle[\"boll\"] return [ last_ema < last_bb, (self.candle(df, rewind=-2)[\"AO\"] >",
"last_ema > last_bb, (self.candle(df, rewind=-2)[\"AO\"] < 0) & (self.candle(df, rewind=-1)[\"AO\"]",
"0, ] def alert_message(self, df): prev_candle = self.candle(df) last_close =",
"= prev_candle[\"AO\"] return ( \"Close: {:.2f}, Awesome Oscillator value: {:.2f}\".format(",
"app.common import reshape_data from app.strategies.base_strategy import BaseStrategy pd.set_option(\"display.max_columns\", None) pd.set_option(\"display.width\","
] |
[
"Loops in Python 3 spam = 0 while spam <",
"Alice, kiddo.\") elif age > 2000: print('Unlike you, Alice is",
"random for i in range(5): print(random.randint(1, 10)) # Exiting a",
"str(i) + ')') # Using starting range for i in",
"Exiting a python program import sys while True: print('Type exit",
"you, Alice is not an undead, immortal vampire.') elif age",
"= input() # Basic print function print(input_from_user) # Mixing boolean",
"comparison operations if (4 < 5) and (5 < 6):",
"\"_342\" # Getting input input_from_user = input() # Basic print",
"if (4 < 5) and (5 < 6): print(\"True\") #",
"a fish.)') password = input() if password = '<PASSWORD>': break",
"are you?') name = input() if name != 'Joe': continue",
"Basic if & if else flow if name == 'Alice':",
"print(\"True\") # Basic if & if else flow if name",
"not Alice, kiddo.\") elif age > 2000: print('Unlike you, Alice",
"1 # Access loop while True: print('Who are you?') name",
"# For loops using range function print(\"My name is\") for",
"and comparison operations if (4 < 5) and (5 <",
"2000: print('Unlike you, Alice is not an undead, immortal vampire.')",
"# Basic print function print(input_from_user) # Mixing boolean and comparison",
"For loops using range function print(\"My name is\") for i",
"Alice, grannie.') # Loops in Python 3 spam = 0",
"while True: print('Type exit to exit.') response = input() if",
"name == 'Alice': print('Hi, Alice.') elif age < 12: print(\"You",
"range(5): print(random.randint(1, 10)) # Exiting a python program import sys",
"Alice.') elif age < 12: print(\"You are not Alice, kiddo.\")",
"String concatenaton added_strings = str(32) + \"_342\" # Getting input",
"> 2000: print('Unlike you, Alice is not an undead, immortal",
"if password = '<PASSWORD>': break print('Access granted.') # For loops",
"concatenaton added_strings = str(32) + \"_342\" # Getting input input_from_user",
"print('Spam, spam!') spam = spam + 1 # Access loop",
"spam!') spam = spam + 1 # Access loop while",
"What is the password? (It is a fish.)') password =",
"for i in range(12, 16): print(i) # Importing modules import",
"age > 100: print('You are not Alice, grannie.') # Loops",
"print('Hello, Joe. What is the password? (It is a fish.)')",
"age < 12: print(\"You are not Alice, kiddo.\") elif age",
"< 5: print('Spam, spam!') spam = spam + 1 #",
"in range(12, 16): print(i) # Importing modules import random for",
"exit.') response = input() if response == 'exit': sys.exit() print('You",
"range(5): print('<NAME> (' + str(i) + ')') # Using starting",
"== 'exit': sys.exit() print('You typed ' + response + '.')",
"is\") for i in range(5): print('<NAME> (' + str(i) +",
"# Python Basics # String concatenaton added_strings = str(32) +",
"function print(input_from_user) # Mixing boolean and comparison operations if (4",
"Basic print function print(input_from_user) # Mixing boolean and comparison operations",
"not Alice, grannie.') # Loops in Python 3 spam =",
"is a fish.)') password = input() if password = '<PASSWORD>':",
"True: print('Who are you?') name = input() if name !=",
"to exit.') response = input() if response == 'exit': sys.exit()",
"exit to exit.') response = input() if response == 'exit':",
"sys while True: print('Type exit to exit.') response = input()",
"not an undead, immortal vampire.') elif age > 100: print('You",
"input() if response == 'exit': sys.exit() print('You typed ' +",
"> 100: print('You are not Alice, grannie.') # Loops in",
"name is\") for i in range(5): print('<NAME> (' + str(i)",
"i in range(12, 16): print(i) # Importing modules import random",
"input input_from_user = input() # Basic print function print(input_from_user) #",
"an undead, immortal vampire.') elif age > 100: print('You are",
"Mixing boolean and comparison operations if (4 < 5) and",
"5) and (5 < 6): print(\"True\") # Basic if &",
"immortal vampire.') elif age > 100: print('You are not Alice,",
"elif age > 100: print('You are not Alice, grannie.') #",
"(5 < 6): print(\"True\") # Basic if & if else",
"# Loops in Python 3 spam = 0 while spam",
"spam + 1 # Access loop while True: print('Who are",
"password? (It is a fish.)') password = input() if password",
"for i in range(5): print(random.randint(1, 10)) # Exiting a python",
"# String concatenaton added_strings = str(32) + \"_342\" # Getting",
"name != 'Joe': continue print('Hello, Joe. What is the password?",
"')') # Using starting range for i in range(12, 16):",
"print('Who are you?') name = input() if name != 'Joe':",
"(It is a fish.)') password = input() if password =",
"print('Type exit to exit.') response = input() if response ==",
"# Using starting range for i in range(12, 16): print(i)",
"while spam < 5: print('Spam, spam!') spam = spam +",
"elif age < 12: print(\"You are not Alice, kiddo.\") elif",
"i in range(5): print(random.randint(1, 10)) # Exiting a python program",
"password = input() if password = '<PASSWORD>': break print('Access granted.')",
"vampire.') elif age > 100: print('You are not Alice, grannie.')",
"spam = 0 while spam < 5: print('Spam, spam!') spam",
"range(12, 16): print(i) # Importing modules import random for i",
"+ \"_342\" # Getting input input_from_user = input() # Basic",
"age > 2000: print('Unlike you, Alice is not an undead,",
"grannie.') # Loops in Python 3 spam = 0 while",
"== 'Alice': print('Hi, Alice.') elif age < 12: print(\"You are",
"if name == 'Alice': print('Hi, Alice.') elif age < 12:",
"input() # Basic print function print(input_from_user) # Mixing boolean and",
"range for i in range(12, 16): print(i) # Importing modules",
"'Joe': continue print('Hello, Joe. What is the password? (It is",
"are not Alice, kiddo.\") elif age > 2000: print('Unlike you,",
"for i in range(5): print('<NAME> (' + str(i) + ')')",
"print function print(input_from_user) # Mixing boolean and comparison operations if",
"input_from_user = input() # Basic print function print(input_from_user) # Mixing",
"'<PASSWORD>': break print('Access granted.') # For loops using range function",
"12: print(\"You are not Alice, kiddo.\") elif age > 2000:",
"granted.') # For loops using range function print(\"My name is\")",
"modules import random for i in range(5): print(random.randint(1, 10)) #",
"Access loop while True: print('Who are you?') name = input()",
"print(i) # Importing modules import random for i in range(5):",
"= spam + 1 # Access loop while True: print('Who",
"break print('Access granted.') # For loops using range function print(\"My",
"undead, immortal vampire.') elif age > 100: print('You are not",
"added_strings = str(32) + \"_342\" # Getting input input_from_user =",
"print(input_from_user) # Mixing boolean and comparison operations if (4 <",
"# Mixing boolean and comparison operations if (4 < 5)",
"6): print(\"True\") # Basic if & if else flow if",
"& if else flow if name == 'Alice': print('Hi, Alice.')",
"< 12: print(\"You are not Alice, kiddo.\") elif age >",
"print('<NAME> (' + str(i) + ')') # Using starting range",
"the password? (It is a fish.)') password = input() if",
"+ str(i) + ')') # Using starting range for i",
"# Exiting a python program import sys while True: print('Type",
"program import sys while True: print('Type exit to exit.') response",
"10)) # Exiting a python program import sys while True:",
"(' + str(i) + ')') # Using starting range for",
"Importing modules import random for i in range(5): print(random.randint(1, 10))",
"+ 1 # Access loop while True: print('Who are you?')",
"= input() if password = '<PASSWORD>': break print('Access granted.') #",
"are not Alice, grannie.') # Loops in Python 3 spam",
"0 while spam < 5: print('Spam, spam!') spam = spam",
"loop while True: print('Who are you?') name = input() if",
"if response == 'exit': sys.exit() print('You typed ' + response",
"# Access loop while True: print('Who are you?') name =",
"range function print(\"My name is\") for i in range(5): print('<NAME>",
"'Alice': print('Hi, Alice.') elif age < 12: print(\"You are not",
"elif age > 2000: print('Unlike you, Alice is not an",
"while True: print('Who are you?') name = input() if name",
"print('Unlike you, Alice is not an undead, immortal vampire.') elif",
"name = input() if name != 'Joe': continue print('Hello, Joe.",
"and (5 < 6): print(\"True\") # Basic if & if",
"kiddo.\") elif age > 2000: print('Unlike you, Alice is not",
"Python 3 spam = 0 while spam < 5: print('Spam,",
"else flow if name == 'Alice': print('Hi, Alice.') elif age",
"is the password? (It is a fish.)') password = input()",
"3 spam = 0 while spam < 5: print('Spam, spam!')",
"!= 'Joe': continue print('Hello, Joe. What is the password? (It",
"if & if else flow if name == 'Alice': print('Hi,",
"Using starting range for i in range(12, 16): print(i) #",
"< 5) and (5 < 6): print(\"True\") # Basic if",
"import random for i in range(5): print(random.randint(1, 10)) # Exiting",
"# Basic if & if else flow if name ==",
"5: print('Spam, spam!') spam = spam + 1 # Access",
"# Getting input input_from_user = input() # Basic print function",
"print(\"My name is\") for i in range(5): print('<NAME> (' +",
"= input() if name != 'Joe': continue print('Hello, Joe. What",
"+ ')') # Using starting range for i in range(12,",
"you?') name = input() if name != 'Joe': continue print('Hello,",
"a python program import sys while True: print('Type exit to",
"= input() if response == 'exit': sys.exit() print('You typed '",
"response == 'exit': sys.exit() print('You typed ' + response +",
"16): print(i) # Importing modules import random for i in",
"flow if name == 'Alice': print('Hi, Alice.') elif age <",
"# Importing modules import random for i in range(5): print(random.randint(1,",
"using range function print(\"My name is\") for i in range(5):",
"= str(32) + \"_342\" # Getting input input_from_user = input()",
"print('Hi, Alice.') elif age < 12: print(\"You are not Alice,",
"starting range for i in range(12, 16): print(i) # Importing",
"Basics # String concatenaton added_strings = str(32) + \"_342\" #",
"fish.)') password = input() if password = '<PASSWORD>': break print('Access",
"input() if password = '<PASSWORD>': break print('Access granted.') # For",
"in range(5): print('<NAME> (' + str(i) + ')') # Using",
"Joe. What is the password? (It is a fish.)') password",
"password = '<PASSWORD>': break print('Access granted.') # For loops using",
"100: print('You are not Alice, grannie.') # Loops in Python",
"str(32) + \"_342\" # Getting input input_from_user = input() #",
"in range(5): print(random.randint(1, 10)) # Exiting a python program import",
"if else flow if name == 'Alice': print('Hi, Alice.') elif",
"(4 < 5) and (5 < 6): print(\"True\") # Basic",
"Python Basics # String concatenaton added_strings = str(32) + \"_342\"",
"in Python 3 spam = 0 while spam < 5:",
"input() if name != 'Joe': continue print('Hello, Joe. What is",
"function print(\"My name is\") for i in range(5): print('<NAME> ('",
"Getting input input_from_user = input() # Basic print function print(input_from_user)",
"import sys while True: print('Type exit to exit.') response =",
"print('Access granted.') # For loops using range function print(\"My name",
"if name != 'Joe': continue print('Hello, Joe. What is the",
"continue print('Hello, Joe. What is the password? (It is a",
"print('You are not Alice, grannie.') # Loops in Python 3",
"loops using range function print(\"My name is\") for i in",
"True: print('Type exit to exit.') response = input() if response",
"spam < 5: print('Spam, spam!') spam = spam + 1",
"print(random.randint(1, 10)) # Exiting a python program import sys while",
"< 6): print(\"True\") # Basic if & if else flow",
"response = input() if response == 'exit': sys.exit() print('You typed",
"print(\"You are not Alice, kiddo.\") elif age > 2000: print('Unlike",
"python program import sys while True: print('Type exit to exit.')",
"is not an undead, immortal vampire.') elif age > 100:",
"i in range(5): print('<NAME> (' + str(i) + ')') #",
"= '<PASSWORD>': break print('Access granted.') # For loops using range",
"boolean and comparison operations if (4 < 5) and (5",
"= 0 while spam < 5: print('Spam, spam!') spam =",
"spam = spam + 1 # Access loop while True:",
"operations if (4 < 5) and (5 < 6): print(\"True\")",
"Alice is not an undead, immortal vampire.') elif age >"
] |
[
"DATABASE_OPTIONS = { 'database': 'klazor', 'user': 'root', 'password': '', 'charset':",
"'user': 'root', 'password': '', 'charset': 'utf8mb4', } HOSTS = ['127.0.0.1',",
"'root', 'password': '', 'charset': 'utf8mb4', } HOSTS = ['127.0.0.1', '172.16.58.3']",
"= { 'database': 'klazor', 'user': 'root', 'password': '', 'charset': 'utf8mb4',",
"{ 'database': 'klazor', 'user': 'root', 'password': '', 'charset': 'utf8mb4', }",
"'klazor', 'user': 'root', 'password': '', 'charset': 'utf8mb4', } HOSTS =",
"<filename>env.example.py DATABASE_OPTIONS = { 'database': 'klazor', 'user': 'root', 'password': '',",
"'database': 'klazor', 'user': 'root', 'password': '', 'charset': 'utf8mb4', } HOSTS"
] |
[
"the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/",
"'django.db.backends.postgresql', 'NAME': 'mydatabase', 'USER': 'mydatabaseuser', 'PASSWORD': '<PASSWORD>', 'HOST': '127.0.0.1', 'PORT':",
"Django 2.2.4. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/",
"startproject' using Django 2.2.4. For more information on this file,",
"https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values,",
"their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ \"\"\" #DEBUG = False DEBUG =",
"= False DEBUG = True SERVE_STATIC = DEBUG ALLOWED_HOSTS =",
"#'ENGINE': 'django.db.backends.sqlite3', 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydatabase', 'USER': 'mydatabaseuser', 'PASSWORD': '<PASSWORD>',",
"# Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { #'ENGINE':",
"2.2.4. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For",
"Django settings. Generated by 'django-admin startproject' using Django 2.2.4. For",
"using Django 2.2.4. For more information on this file, see",
"and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ \"\"\" #DEBUG = False DEBUG",
"see https://docs.djangoproject.com/en/2.2/ref/settings/ \"\"\" #DEBUG = False DEBUG = True SERVE_STATIC",
"full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ \"\"\"",
"{ 'default': { #'ENGINE': 'django.db.backends.oracle' #'ENGINE': 'django.db.backends.mysql', #'ENGINE': 'django.db.backends.sqlite3', 'ENGINE':",
"settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ \"\"\" #DEBUG = False",
"'USER': 'mydatabaseuser', 'PASSWORD': '<PASSWORD>', 'HOST': '127.0.0.1', 'PORT': '5432', } }",
"list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ \"\"\" #DEBUG",
"ALLOWED_HOSTS = [] # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = {",
"For the full list of settings and their values, see",
"#'ENGINE': 'django.db.backends.mysql', #'ENGINE': 'django.db.backends.sqlite3', 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydatabase', 'USER': 'mydatabaseuser',",
"of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ \"\"\" #DEBUG =",
"\"\"\" Django settings. Generated by 'django-admin startproject' using Django 2.2.4.",
"more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full",
"see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their",
"= [] # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default':",
"DATABASES = { 'default': { #'ENGINE': 'django.db.backends.oracle' #'ENGINE': 'django.db.backends.mysql', #'ENGINE':",
"<gh_stars>1-10 \"\"\" Django settings. Generated by 'django-admin startproject' using Django",
"https://docs.djangoproject.com/en/2.2/ref/settings/ \"\"\" #DEBUG = False DEBUG = True SERVE_STATIC =",
"DEBUG ALLOWED_HOSTS = [] # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES =",
"'django.db.backends.mysql', #'ENGINE': 'django.db.backends.sqlite3', 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydatabase', 'USER': 'mydatabaseuser', 'PASSWORD':",
"SERVE_STATIC = DEBUG ALLOWED_HOSTS = [] # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases",
"values, see https://docs.djangoproject.com/en/2.2/ref/settings/ \"\"\" #DEBUG = False DEBUG = True",
"Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { #'ENGINE': 'django.db.backends.oracle'",
"For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the",
"'django.db.backends.oracle' #'ENGINE': 'django.db.backends.mysql', #'ENGINE': 'django.db.backends.sqlite3', 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydatabase', 'USER':",
"'django.db.backends.sqlite3', 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydatabase', 'USER': 'mydatabaseuser', 'PASSWORD': '<PASSWORD>', 'HOST':",
"'mydatabase', 'USER': 'mydatabaseuser', 'PASSWORD': '<PASSWORD>', 'HOST': '127.0.0.1', 'PORT': '5432', }",
"{ #'ENGINE': 'django.db.backends.oracle' #'ENGINE': 'django.db.backends.mysql', #'ENGINE': 'django.db.backends.sqlite3', 'ENGINE': 'django.db.backends.postgresql', 'NAME':",
"# https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { #'ENGINE': 'django.db.backends.oracle' #'ENGINE':",
"by 'django-admin startproject' using Django 2.2.4. For more information on",
"file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and",
"this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings",
"settings. Generated by 'django-admin startproject' using Django 2.2.4. For more",
"information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list",
"DEBUG = True SERVE_STATIC = DEBUG ALLOWED_HOSTS = [] #",
"[] # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': {",
"'default': { #'ENGINE': 'django.db.backends.oracle' #'ENGINE': 'django.db.backends.mysql', #'ENGINE': 'django.db.backends.sqlite3', 'ENGINE': 'django.db.backends.postgresql',",
"Generated by 'django-admin startproject' using Django 2.2.4. For more information",
"'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydatabase', 'USER': 'mydatabaseuser', 'PASSWORD': '<PASSWORD>', 'HOST': '127.0.0.1',",
"True SERVE_STATIC = DEBUG ALLOWED_HOSTS = [] # Database #",
"on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of",
"= DEBUG ALLOWED_HOSTS = [] # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES",
"= { 'default': { #'ENGINE': 'django.db.backends.oracle' #'ENGINE': 'django.db.backends.mysql', #'ENGINE': 'django.db.backends.sqlite3',",
"'django-admin startproject' using Django 2.2.4. For more information on this",
"False DEBUG = True SERVE_STATIC = DEBUG ALLOWED_HOSTS = []",
"= True SERVE_STATIC = DEBUG ALLOWED_HOSTS = [] # Database",
"https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { #'ENGINE': 'django.db.backends.oracle' #'ENGINE': 'django.db.backends.mysql',",
"#'ENGINE': 'django.db.backends.oracle' #'ENGINE': 'django.db.backends.mysql', #'ENGINE': 'django.db.backends.sqlite3', 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydatabase',",
"#DEBUG = False DEBUG = True SERVE_STATIC = DEBUG ALLOWED_HOSTS",
"'NAME': 'mydatabase', 'USER': 'mydatabaseuser', 'PASSWORD': '<PASSWORD>', 'HOST': '127.0.0.1', 'PORT': '5432',",
"\"\"\" #DEBUG = False DEBUG = True SERVE_STATIC = DEBUG"
] |
[
"model = Contact fields = ('name', 'number', 'email', 'category', 'description')",
"from .models import Contact class ContactForm(forms.ModelForm): class Meta: model =",
"<gh_stars>1-10 from django import forms from .models import Contact class",
"Meta: model = Contact fields = ('name', 'number', 'email', 'category',",
"from django import forms from .models import Contact class ContactForm(forms.ModelForm):",
".models import Contact class ContactForm(forms.ModelForm): class Meta: model = Contact",
"import Contact class ContactForm(forms.ModelForm): class Meta: model = Contact fields",
"forms from .models import Contact class ContactForm(forms.ModelForm): class Meta: model",
"django import forms from .models import Contact class ContactForm(forms.ModelForm): class",
"Contact class ContactForm(forms.ModelForm): class Meta: model = Contact fields =",
"ContactForm(forms.ModelForm): class Meta: model = Contact fields = ('name', 'number',",
"import forms from .models import Contact class ContactForm(forms.ModelForm): class Meta:",
"class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ('name',",
"class Meta: model = Contact fields = ('name', 'number', 'email',"
] |
[
"import ( AdHocCommandList, AdHocCommandDetail, AdHocCommandCancel, AdHocCommandRelaunch, AdHocCommandAdHocCommandEventsList, AdHocCommandActivityStreamList, AdHocCommandNotificationsList, AdHocCommandStdout,",
"= [ re_path(r'^$', AdHocCommandList.as_view(), name='ad_hoc_command_list'), re_path(r'^(?P<pk>[0-9]+)/$', AdHocCommandDetail.as_view(), name='ad_hoc_command_detail'), re_path(r'^(?P<pk>[0-9]+)/cancel/$', AdHocCommandCancel.as_view(),",
"re_path from awx.api.views import ( AdHocCommandList, AdHocCommandDetail, AdHocCommandCancel, AdHocCommandRelaunch, AdHocCommandAdHocCommandEventsList,",
"Copyright (c) 2017 Ansible, Inc. # All Rights Reserved. from",
"AdHocCommandRelaunch.as_view(), name='ad_hoc_command_relaunch'), re_path(r'^(?P<pk>[0-9]+)/events/$', AdHocCommandAdHocCommandEventsList.as_view(), name='ad_hoc_command_ad_hoc_command_events_list'), re_path(r'^(?P<pk>[0-9]+)/activity_stream/$', AdHocCommandActivityStreamList.as_view(), name='ad_hoc_command_activity_stream_list'), re_path(r'^(?P<pk>[0-9]+)/notifications/$', AdHocCommandNotificationsList.as_view(),",
"AdHocCommandStdout, ) urls = [ re_path(r'^$', AdHocCommandList.as_view(), name='ad_hoc_command_list'), re_path(r'^(?P<pk>[0-9]+)/$', AdHocCommandDetail.as_view(),",
"AdHocCommandActivityStreamList.as_view(), name='ad_hoc_command_activity_stream_list'), re_path(r'^(?P<pk>[0-9]+)/notifications/$', AdHocCommandNotificationsList.as_view(), name='ad_hoc_command_notifications_list'), re_path(r'^(?P<pk>[0-9]+)/stdout/$', AdHocCommandStdout.as_view(), name='ad_hoc_command_stdout'), ] __all__",
"# All Rights Reserved. from django.urls import re_path from awx.api.views",
"AdHocCommandCancel, AdHocCommandRelaunch, AdHocCommandAdHocCommandEventsList, AdHocCommandActivityStreamList, AdHocCommandNotificationsList, AdHocCommandStdout, ) urls = [",
"re_path(r'^(?P<pk>[0-9]+)/$', AdHocCommandDetail.as_view(), name='ad_hoc_command_detail'), re_path(r'^(?P<pk>[0-9]+)/cancel/$', AdHocCommandCancel.as_view(), name='ad_hoc_command_cancel'), re_path(r'^(?P<pk>[0-9]+)/relaunch/$', AdHocCommandRelaunch.as_view(), name='ad_hoc_command_relaunch'), re_path(r'^(?P<pk>[0-9]+)/events/$',",
"( AdHocCommandList, AdHocCommandDetail, AdHocCommandCancel, AdHocCommandRelaunch, AdHocCommandAdHocCommandEventsList, AdHocCommandActivityStreamList, AdHocCommandNotificationsList, AdHocCommandStdout, )",
"AdHocCommandAdHocCommandEventsList.as_view(), name='ad_hoc_command_ad_hoc_command_events_list'), re_path(r'^(?P<pk>[0-9]+)/activity_stream/$', AdHocCommandActivityStreamList.as_view(), name='ad_hoc_command_activity_stream_list'), re_path(r'^(?P<pk>[0-9]+)/notifications/$', AdHocCommandNotificationsList.as_view(), name='ad_hoc_command_notifications_list'), re_path(r'^(?P<pk>[0-9]+)/stdout/$', AdHocCommandStdout.as_view(),",
"re_path(r'^(?P<pk>[0-9]+)/events/$', AdHocCommandAdHocCommandEventsList.as_view(), name='ad_hoc_command_ad_hoc_command_events_list'), re_path(r'^(?P<pk>[0-9]+)/activity_stream/$', AdHocCommandActivityStreamList.as_view(), name='ad_hoc_command_activity_stream_list'), re_path(r'^(?P<pk>[0-9]+)/notifications/$', AdHocCommandNotificationsList.as_view(), name='ad_hoc_command_notifications_list'), re_path(r'^(?P<pk>[0-9]+)/stdout/$',",
"AdHocCommandList.as_view(), name='ad_hoc_command_list'), re_path(r'^(?P<pk>[0-9]+)/$', AdHocCommandDetail.as_view(), name='ad_hoc_command_detail'), re_path(r'^(?P<pk>[0-9]+)/cancel/$', AdHocCommandCancel.as_view(), name='ad_hoc_command_cancel'), re_path(r'^(?P<pk>[0-9]+)/relaunch/$', AdHocCommandRelaunch.as_view(),",
"name='ad_hoc_command_detail'), re_path(r'^(?P<pk>[0-9]+)/cancel/$', AdHocCommandCancel.as_view(), name='ad_hoc_command_cancel'), re_path(r'^(?P<pk>[0-9]+)/relaunch/$', AdHocCommandRelaunch.as_view(), name='ad_hoc_command_relaunch'), re_path(r'^(?P<pk>[0-9]+)/events/$', AdHocCommandAdHocCommandEventsList.as_view(), name='ad_hoc_command_ad_hoc_command_events_list'),",
"AdHocCommandDetail, AdHocCommandCancel, AdHocCommandRelaunch, AdHocCommandAdHocCommandEventsList, AdHocCommandActivityStreamList, AdHocCommandNotificationsList, AdHocCommandStdout, ) urls =",
"AdHocCommandList, AdHocCommandDetail, AdHocCommandCancel, AdHocCommandRelaunch, AdHocCommandAdHocCommandEventsList, AdHocCommandActivityStreamList, AdHocCommandNotificationsList, AdHocCommandStdout, ) urls",
"AdHocCommandActivityStreamList, AdHocCommandNotificationsList, AdHocCommandStdout, ) urls = [ re_path(r'^$', AdHocCommandList.as_view(), name='ad_hoc_command_list'),",
"from django.urls import re_path from awx.api.views import ( AdHocCommandList, AdHocCommandDetail,",
"re_path(r'^(?P<pk>[0-9]+)/cancel/$', AdHocCommandCancel.as_view(), name='ad_hoc_command_cancel'), re_path(r'^(?P<pk>[0-9]+)/relaunch/$', AdHocCommandRelaunch.as_view(), name='ad_hoc_command_relaunch'), re_path(r'^(?P<pk>[0-9]+)/events/$', AdHocCommandAdHocCommandEventsList.as_view(), name='ad_hoc_command_ad_hoc_command_events_list'), re_path(r'^(?P<pk>[0-9]+)/activity_stream/$',",
"name='ad_hoc_command_cancel'), re_path(r'^(?P<pk>[0-9]+)/relaunch/$', AdHocCommandRelaunch.as_view(), name='ad_hoc_command_relaunch'), re_path(r'^(?P<pk>[0-9]+)/events/$', AdHocCommandAdHocCommandEventsList.as_view(), name='ad_hoc_command_ad_hoc_command_events_list'), re_path(r'^(?P<pk>[0-9]+)/activity_stream/$', AdHocCommandActivityStreamList.as_view(), name='ad_hoc_command_activity_stream_list'),",
"re_path(r'^(?P<pk>[0-9]+)/activity_stream/$', AdHocCommandActivityStreamList.as_view(), name='ad_hoc_command_activity_stream_list'), re_path(r'^(?P<pk>[0-9]+)/notifications/$', AdHocCommandNotificationsList.as_view(), name='ad_hoc_command_notifications_list'), re_path(r'^(?P<pk>[0-9]+)/stdout/$', AdHocCommandStdout.as_view(), name='ad_hoc_command_stdout'), ]",
"AdHocCommandAdHocCommandEventsList, AdHocCommandActivityStreamList, AdHocCommandNotificationsList, AdHocCommandStdout, ) urls = [ re_path(r'^$', AdHocCommandList.as_view(),",
"# Copyright (c) 2017 Ansible, Inc. # All Rights Reserved.",
"re_path(r'^(?P<pk>[0-9]+)/notifications/$', AdHocCommandNotificationsList.as_view(), name='ad_hoc_command_notifications_list'), re_path(r'^(?P<pk>[0-9]+)/stdout/$', AdHocCommandStdout.as_view(), name='ad_hoc_command_stdout'), ] __all__ = ['urls']",
"All Rights Reserved. from django.urls import re_path from awx.api.views import",
"(c) 2017 Ansible, Inc. # All Rights Reserved. from django.urls",
"import re_path from awx.api.views import ( AdHocCommandList, AdHocCommandDetail, AdHocCommandCancel, AdHocCommandRelaunch,",
"django.urls import re_path from awx.api.views import ( AdHocCommandList, AdHocCommandDetail, AdHocCommandCancel,",
"Reserved. from django.urls import re_path from awx.api.views import ( AdHocCommandList,",
"AdHocCommandDetail.as_view(), name='ad_hoc_command_detail'), re_path(r'^(?P<pk>[0-9]+)/cancel/$', AdHocCommandCancel.as_view(), name='ad_hoc_command_cancel'), re_path(r'^(?P<pk>[0-9]+)/relaunch/$', AdHocCommandRelaunch.as_view(), name='ad_hoc_command_relaunch'), re_path(r'^(?P<pk>[0-9]+)/events/$', AdHocCommandAdHocCommandEventsList.as_view(),",
"re_path(r'^$', AdHocCommandList.as_view(), name='ad_hoc_command_list'), re_path(r'^(?P<pk>[0-9]+)/$', AdHocCommandDetail.as_view(), name='ad_hoc_command_detail'), re_path(r'^(?P<pk>[0-9]+)/cancel/$', AdHocCommandCancel.as_view(), name='ad_hoc_command_cancel'), re_path(r'^(?P<pk>[0-9]+)/relaunch/$',",
"Rights Reserved. from django.urls import re_path from awx.api.views import (",
"<reponame>ziegenberg/awx<filename>awx/api/urls/ad_hoc_command.py # Copyright (c) 2017 Ansible, Inc. # All Rights",
"awx.api.views import ( AdHocCommandList, AdHocCommandDetail, AdHocCommandCancel, AdHocCommandRelaunch, AdHocCommandAdHocCommandEventsList, AdHocCommandActivityStreamList, AdHocCommandNotificationsList,",
") urls = [ re_path(r'^$', AdHocCommandList.as_view(), name='ad_hoc_command_list'), re_path(r'^(?P<pk>[0-9]+)/$', AdHocCommandDetail.as_view(), name='ad_hoc_command_detail'),",
"name='ad_hoc_command_activity_stream_list'), re_path(r'^(?P<pk>[0-9]+)/notifications/$', AdHocCommandNotificationsList.as_view(), name='ad_hoc_command_notifications_list'), re_path(r'^(?P<pk>[0-9]+)/stdout/$', AdHocCommandStdout.as_view(), name='ad_hoc_command_stdout'), ] __all__ =",
"[ re_path(r'^$', AdHocCommandList.as_view(), name='ad_hoc_command_list'), re_path(r'^(?P<pk>[0-9]+)/$', AdHocCommandDetail.as_view(), name='ad_hoc_command_detail'), re_path(r'^(?P<pk>[0-9]+)/cancel/$', AdHocCommandCancel.as_view(), name='ad_hoc_command_cancel'),",
"name='ad_hoc_command_list'), re_path(r'^(?P<pk>[0-9]+)/$', AdHocCommandDetail.as_view(), name='ad_hoc_command_detail'), re_path(r'^(?P<pk>[0-9]+)/cancel/$', AdHocCommandCancel.as_view(), name='ad_hoc_command_cancel'), re_path(r'^(?P<pk>[0-9]+)/relaunch/$', AdHocCommandRelaunch.as_view(), name='ad_hoc_command_relaunch'),",
"Ansible, Inc. # All Rights Reserved. from django.urls import re_path",
"name='ad_hoc_command_relaunch'), re_path(r'^(?P<pk>[0-9]+)/events/$', AdHocCommandAdHocCommandEventsList.as_view(), name='ad_hoc_command_ad_hoc_command_events_list'), re_path(r'^(?P<pk>[0-9]+)/activity_stream/$', AdHocCommandActivityStreamList.as_view(), name='ad_hoc_command_activity_stream_list'), re_path(r'^(?P<pk>[0-9]+)/notifications/$', AdHocCommandNotificationsList.as_view(), name='ad_hoc_command_notifications_list'),",
"urls = [ re_path(r'^$', AdHocCommandList.as_view(), name='ad_hoc_command_list'), re_path(r'^(?P<pk>[0-9]+)/$', AdHocCommandDetail.as_view(), name='ad_hoc_command_detail'), re_path(r'^(?P<pk>[0-9]+)/cancel/$',",
"Inc. # All Rights Reserved. from django.urls import re_path from",
"AdHocCommandRelaunch, AdHocCommandAdHocCommandEventsList, AdHocCommandActivityStreamList, AdHocCommandNotificationsList, AdHocCommandStdout, ) urls = [ re_path(r'^$',",
"AdHocCommandCancel.as_view(), name='ad_hoc_command_cancel'), re_path(r'^(?P<pk>[0-9]+)/relaunch/$', AdHocCommandRelaunch.as_view(), name='ad_hoc_command_relaunch'), re_path(r'^(?P<pk>[0-9]+)/events/$', AdHocCommandAdHocCommandEventsList.as_view(), name='ad_hoc_command_ad_hoc_command_events_list'), re_path(r'^(?P<pk>[0-9]+)/activity_stream/$', AdHocCommandActivityStreamList.as_view(),",
"name='ad_hoc_command_ad_hoc_command_events_list'), re_path(r'^(?P<pk>[0-9]+)/activity_stream/$', AdHocCommandActivityStreamList.as_view(), name='ad_hoc_command_activity_stream_list'), re_path(r'^(?P<pk>[0-9]+)/notifications/$', AdHocCommandNotificationsList.as_view(), name='ad_hoc_command_notifications_list'), re_path(r'^(?P<pk>[0-9]+)/stdout/$', AdHocCommandStdout.as_view(), name='ad_hoc_command_stdout'),",
"2017 Ansible, Inc. # All Rights Reserved. from django.urls import",
"AdHocCommandNotificationsList, AdHocCommandStdout, ) urls = [ re_path(r'^$', AdHocCommandList.as_view(), name='ad_hoc_command_list'), re_path(r'^(?P<pk>[0-9]+)/$',",
"re_path(r'^(?P<pk>[0-9]+)/relaunch/$', AdHocCommandRelaunch.as_view(), name='ad_hoc_command_relaunch'), re_path(r'^(?P<pk>[0-9]+)/events/$', AdHocCommandAdHocCommandEventsList.as_view(), name='ad_hoc_command_ad_hoc_command_events_list'), re_path(r'^(?P<pk>[0-9]+)/activity_stream/$', AdHocCommandActivityStreamList.as_view(), name='ad_hoc_command_activity_stream_list'), re_path(r'^(?P<pk>[0-9]+)/notifications/$',",
"from awx.api.views import ( AdHocCommandList, AdHocCommandDetail, AdHocCommandCancel, AdHocCommandRelaunch, AdHocCommandAdHocCommandEventsList, AdHocCommandActivityStreamList,"
] |
[
"time_tools import * # print(compareTimestamp(111,222)) time.showNowTime() # now time is",
"from time_tools import * # print(compareTimestamp(111,222)) time.showNowTime() # now time",
"#test.py from time_tools import * # print(compareTimestamp(111,222)) time.showNowTime() # now",
"import * # print(compareTimestamp(111,222)) time.showNowTime() # now time is XX:XX:XX"
] |
[
"= self.center_x self.last_texture_change_center_y = self.center_y self._texture = list[self.cur_texture_index % len(list)]",
"self._update_direction(FACE_DOWN, self.walk_down_textures[0]) else: self._rotate(self.center_y - self.last_texture_change_center_y, self.walk_down_textures) # Jumping elif",
"= 0, center_x: float = 0, center_y: float = 0,",
"center_y: float = 0, *, stand_left, stand_right, left, right, up,",
"# Going left elif self.change_x <= -tol: if self.state !=",
"elif self.change_x >= tol: if self.state != FACE_RIGHT: self._update_direction(FACE_RIGHT, self.stand_right_texture)",
"image_y: float = 0, center_x: float = 0, center_y: float",
"= stand_right self.stand_left_texture = stand_left self.walk_left_textures = left self.walk_right_textures =",
"self.texture_change_distance: self.cur_texture_index += 1 self.last_texture_change_center_x = self.center_x self.last_texture_change_center_y = self.center_y",
"self.walk_up_textures) # Going left elif self.change_x <= -tol: if self.state",
"abs(delta) >= self.texture_change_distance: self.cur_texture_index += 1 self.last_texture_change_center_x = self.center_x self.last_texture_change_center_y",
"<= -tol: if self.state != FACE_LEFT: self._update_direction(FACE_LEFT, self.stand_left_texture) else: self._rotate(self.center_x",
"FACE_DOWN: self._update_direction(FACE_RIGHT, self.stand_right_texture) self.textures[0] = self._texture self.width = self._texture.width *",
"self.center_y self.state = state self.cur_texture_index = 0 self._texture = texture",
"self.stand_right_texture) self.textures = [self._texture] def _update_direction(self, state, texture): self.last_texture_change_center_x =",
"!= FACE_RIGHT: self._update_direction(FACE_RIGHT, self.stand_right_texture) else: self._rotate(self.center_x - self.last_texture_change_center_x, self.walk_right_textures) elif",
"= stand_left self.walk_left_textures = left self.walk_right_textures = right self.walk_up_textures =",
"= 0 self._texture = texture def _rotate(self, delta, list): if",
"class AnimatedWalkingSprite(arcade.Sprite): def __init__(self, scale: float = 1, image_x: float",
"!= FACE_UP: self._update_direction(FACE_UP, self.walk_up_textures[0]) else: self._rotate(self.center_y - self.last_texture_change_center_y, self.walk_up_textures) #",
"tol = 1. # Falling if self.change_y <= -tol: if",
"right, up, down, step=20): super().__init__(scale=scale, image_x=image_x, image_y=image_y, center_x=center_x, center_y=center_y) self.state",
"self.state = FACE_RIGHT self.stand_right_texture = stand_right self.stand_left_texture = stand_left self.walk_left_textures",
"= 1, image_x: float = 0, image_y: float = 0,",
"= 0 self.last_texture_change_center_y = 0 self._update_direction(FACE_RIGHT, self.stand_right_texture) self.textures = [self._texture]",
"left elif self.change_x <= -tol: if self.state != FACE_LEFT: self._update_direction(FACE_LEFT,",
"else: self._rotate(self.center_y - self.last_texture_change_center_y, self.walk_up_textures) # Going left elif self.change_x",
"left self.walk_right_textures = right self.walk_up_textures = up self.walk_down_textures = down",
"abs(self.change_x) < tol and self.state == FACE_DOWN: self._update_direction(FACE_RIGHT, self.stand_right_texture) self.textures[0]",
"up, down, step=20): super().__init__(scale=scale, image_x=image_x, image_y=image_y, center_x=center_x, center_y=center_y) self.state =",
"center_y=center_y) self.state = FACE_RIGHT self.stand_right_texture = stand_right self.stand_left_texture = stand_left",
"center_x: float = 0, center_y: float = 0, *, stand_left,",
"if abs(delta) >= self.texture_change_distance: self.cur_texture_index += 1 self.last_texture_change_center_x = self.center_x",
"Going right elif self.change_x >= tol: if self.state != FACE_RIGHT:",
"0, *, stand_left, stand_right, left, right, up, down, step=20): super().__init__(scale=scale,",
"float = 0, center_x: float = 0, center_y: float =",
"= 0 self._update_direction(FACE_RIGHT, self.stand_right_texture) self.textures = [self._texture] def _update_direction(self, state,",
"= 1. # Falling if self.change_y <= -tol: if self.state",
"self._texture = list[self.cur_texture_index % len(list)] def update_animation(self): tol = 1.",
"if self.state != FACE_DOWN: self._update_direction(FACE_DOWN, self.walk_down_textures[0]) else: self._rotate(self.center_y - self.last_texture_change_center_y,",
"self.cur_texture_index += 1 self.last_texture_change_center_x = self.center_x self.last_texture_change_center_y = self.center_y self._texture",
"stand_right, left, right, up, down, step=20): super().__init__(scale=scale, image_x=image_x, image_y=image_y, center_x=center_x,",
"self.change_x >= tol: if self.state != FACE_RIGHT: self._update_direction(FACE_RIGHT, self.stand_right_texture) else:",
"self.stand_right_texture) self.textures[0] = self._texture self.width = self._texture.width * self.scale self.height",
"tol: if self.state != FACE_RIGHT: self._update_direction(FACE_RIGHT, self.stand_right_texture) else: self._rotate(self.center_x -",
"self._rotate(self.center_y - self.last_texture_change_center_y, self.walk_down_textures) # Jumping elif self.change_y >= tol:",
"texture def _rotate(self, delta, list): if abs(delta) >= self.texture_change_distance: self.cur_texture_index",
"= 0, image_y: float = 0, center_x: float = 0,",
"from arcade import FACE_RIGHT, FACE_DOWN, FACE_UP, FACE_LEFT class AnimatedWalkingSprite(arcade.Sprite): def",
"self.stand_left_texture) else: self._rotate(self.center_x - self.last_texture_change_center_x, self.walk_left_textures) # Going right elif",
"scale: float = 1, image_x: float = 0, image_y: float",
"float = 1, image_x: float = 0, image_y: float =",
"= 0, *, stand_left, stand_right, left, right, up, down, step=20):",
"= self.center_y self.state = state self.cur_texture_index = 0 self._texture =",
"def __init__(self, scale: float = 1, image_x: float = 0,",
"step=20): super().__init__(scale=scale, image_x=image_x, image_y=image_y, center_x=center_x, center_y=center_y) self.state = FACE_RIGHT self.stand_right_texture",
"step self.last_texture_change_center_x = 0 self.last_texture_change_center_y = 0 self._update_direction(FACE_RIGHT, self.stand_right_texture) self.textures",
"self.walk_down_textures = down self.cur_texture_index = 0 self.texture_change_distance = step self.last_texture_change_center_x",
"self.walk_right_textures) elif abs(self.change_x) < tol and self.state == FACE_DOWN: self._update_direction(FACE_RIGHT,",
"import arcade from arcade import FACE_RIGHT, FACE_DOWN, FACE_UP, FACE_LEFT class",
"float = 0, center_y: float = 0, *, stand_left, stand_right,",
"*, stand_left, stand_right, left, right, up, down, step=20): super().__init__(scale=scale, image_x=image_x,",
"0 self._update_direction(FACE_RIGHT, self.stand_right_texture) self.textures = [self._texture] def _update_direction(self, state, texture):",
"self.last_texture_change_center_y = self.center_y self._texture = list[self.cur_texture_index % len(list)] def update_animation(self):",
"Falling if self.change_y <= -tol: if self.state != FACE_DOWN: self._update_direction(FACE_DOWN,",
"elif self.change_y >= tol: if self.state != FACE_UP: self._update_direction(FACE_UP, self.walk_up_textures[0])",
"FACE_LEFT: self._update_direction(FACE_LEFT, self.stand_left_texture) else: self._rotate(self.center_x - self.last_texture_change_center_x, self.walk_left_textures) # Going",
"image_y=image_y, center_x=center_x, center_y=center_y) self.state = FACE_RIGHT self.stand_right_texture = stand_right self.stand_left_texture",
"texture): self.last_texture_change_center_x = self.center_x self.last_texture_change_center_y = self.center_y self.state = state",
"self.state != FACE_LEFT: self._update_direction(FACE_LEFT, self.stand_left_texture) else: self._rotate(self.center_x - self.last_texture_change_center_x, self.walk_left_textures)",
"center_x=center_x, center_y=center_y) self.state = FACE_RIGHT self.stand_right_texture = stand_right self.stand_left_texture =",
"<= -tol: if self.state != FACE_DOWN: self._update_direction(FACE_DOWN, self.walk_down_textures[0]) else: self._rotate(self.center_y",
"FACE_RIGHT: self._update_direction(FACE_RIGHT, self.stand_right_texture) else: self._rotate(self.center_x - self.last_texture_change_center_x, self.walk_right_textures) elif abs(self.change_x)",
"< tol and self.state == FACE_DOWN: self._update_direction(FACE_RIGHT, self.stand_right_texture) self.textures[0] =",
"0, image_y: float = 0, center_x: float = 0, center_y:",
"state self.cur_texture_index = 0 self._texture = texture def _rotate(self, delta,",
"delta, list): if abs(delta) >= self.texture_change_distance: self.cur_texture_index += 1 self.last_texture_change_center_x",
"[self._texture] def _update_direction(self, state, texture): self.last_texture_change_center_x = self.center_x self.last_texture_change_center_y =",
"if self.change_y <= -tol: if self.state != FACE_DOWN: self._update_direction(FACE_DOWN, self.walk_down_textures[0])",
"<gh_stars>1-10 import arcade from arcade import FACE_RIGHT, FACE_DOWN, FACE_UP, FACE_LEFT",
"= texture def _rotate(self, delta, list): if abs(delta) >= self.texture_change_distance:",
"self.walk_left_textures = left self.walk_right_textures = right self.walk_up_textures = up self.walk_down_textures",
"self.last_texture_change_center_y = self.center_y self.state = state self.cur_texture_index = 0 self._texture",
"self.change_y >= tol: if self.state != FACE_UP: self._update_direction(FACE_UP, self.walk_up_textures[0]) else:",
"elif abs(self.change_x) < tol and self.state == FACE_DOWN: self._update_direction(FACE_RIGHT, self.stand_right_texture)",
"FACE_DOWN: self._update_direction(FACE_DOWN, self.walk_down_textures[0]) else: self._rotate(self.center_y - self.last_texture_change_center_y, self.walk_down_textures) # Jumping",
"self.width = self._texture.width * self.scale self.height = self._texture.height * self.scale",
"up self.walk_down_textures = down self.cur_texture_index = 0 self.texture_change_distance = step",
"= self._texture self.width = self._texture.width * self.scale self.height = self._texture.height",
"arcade import FACE_RIGHT, FACE_DOWN, FACE_UP, FACE_LEFT class AnimatedWalkingSprite(arcade.Sprite): def __init__(self,",
"_rotate(self, delta, list): if abs(delta) >= self.texture_change_distance: self.cur_texture_index += 1",
"self._update_direction(FACE_LEFT, self.stand_left_texture) else: self._rotate(self.center_x - self.last_texture_change_center_x, self.walk_left_textures) # Going right",
"self.center_x self.last_texture_change_center_y = self.center_y self.state = state self.cur_texture_index = 0",
"tol: if self.state != FACE_UP: self._update_direction(FACE_UP, self.walk_up_textures[0]) else: self._rotate(self.center_y -",
"self.change_x <= -tol: if self.state != FACE_LEFT: self._update_direction(FACE_LEFT, self.stand_left_texture) else:",
"self.stand_right_texture = stand_right self.stand_left_texture = stand_left self.walk_left_textures = left self.walk_right_textures",
"tol and self.state == FACE_DOWN: self._update_direction(FACE_RIGHT, self.stand_right_texture) self.textures[0] = self._texture",
"self.state = state self.cur_texture_index = 0 self._texture = texture def",
"% len(list)] def update_animation(self): tol = 1. # Falling if",
">= self.texture_change_distance: self.cur_texture_index += 1 self.last_texture_change_center_x = self.center_x self.last_texture_change_center_y =",
"= 0 self.texture_change_distance = step self.last_texture_change_center_x = 0 self.last_texture_change_center_y =",
"= list[self.cur_texture_index % len(list)] def update_animation(self): tol = 1. #",
"self.walk_right_textures = right self.walk_up_textures = up self.walk_down_textures = down self.cur_texture_index",
"= FACE_RIGHT self.stand_right_texture = stand_right self.stand_left_texture = stand_left self.walk_left_textures =",
"import FACE_RIGHT, FACE_DOWN, FACE_UP, FACE_LEFT class AnimatedWalkingSprite(arcade.Sprite): def __init__(self, scale:",
"self._update_direction(FACE_RIGHT, self.stand_right_texture) self.textures = [self._texture] def _update_direction(self, state, texture): self.last_texture_change_center_x",
"_update_direction(self, state, texture): self.last_texture_change_center_x = self.center_x self.last_texture_change_center_y = self.center_y self.state",
"= step self.last_texture_change_center_x = 0 self.last_texture_change_center_y = 0 self._update_direction(FACE_RIGHT, self.stand_right_texture)",
"self.last_texture_change_center_y = 0 self._update_direction(FACE_RIGHT, self.stand_right_texture) self.textures = [self._texture] def _update_direction(self,",
"def _update_direction(self, state, texture): self.last_texture_change_center_x = self.center_x self.last_texture_change_center_y = self.center_y",
"self.walk_up_textures[0]) else: self._rotate(self.center_y - self.last_texture_change_center_y, self.walk_up_textures) # Going left elif",
"elif self.change_x <= -tol: if self.state != FACE_LEFT: self._update_direction(FACE_LEFT, self.stand_left_texture)",
"self.last_texture_change_center_x = self.center_x self.last_texture_change_center_y = self.center_y self._texture = list[self.cur_texture_index %",
"self.stand_left_texture = stand_left self.walk_left_textures = left self.walk_right_textures = right self.walk_up_textures",
"self._update_direction(FACE_RIGHT, self.stand_right_texture) self.textures[0] = self._texture self.width = self._texture.width * self.scale",
"self.last_texture_change_center_y, self.walk_down_textures) # Jumping elif self.change_y >= tol: if self.state",
"right elif self.change_x >= tol: if self.state != FACE_RIGHT: self._update_direction(FACE_RIGHT,",
"self._update_direction(FACE_RIGHT, self.stand_right_texture) else: self._rotate(self.center_x - self.last_texture_change_center_x, self.walk_right_textures) elif abs(self.change_x) <",
"len(list)] def update_animation(self): tol = 1. # Falling if self.change_y",
"0 self.last_texture_change_center_y = 0 self._update_direction(FACE_RIGHT, self.stand_right_texture) self.textures = [self._texture] def",
"FACE_RIGHT, FACE_DOWN, FACE_UP, FACE_LEFT class AnimatedWalkingSprite(arcade.Sprite): def __init__(self, scale: float",
"else: self._rotate(self.center_x - self.last_texture_change_center_x, self.walk_right_textures) elif abs(self.change_x) < tol and",
"self.change_y <= -tol: if self.state != FACE_DOWN: self._update_direction(FACE_DOWN, self.walk_down_textures[0]) else:",
"image_x: float = 0, image_y: float = 0, center_x: float",
"-tol: if self.state != FACE_DOWN: self._update_direction(FACE_DOWN, self.walk_down_textures[0]) else: self._rotate(self.center_y -",
"self.walk_down_textures) # Jumping elif self.change_y >= tol: if self.state !=",
"self._texture self.width = self._texture.width * self.scale self.height = self._texture.height *",
"FACE_LEFT class AnimatedWalkingSprite(arcade.Sprite): def __init__(self, scale: float = 1, image_x:",
"- self.last_texture_change_center_y, self.walk_up_textures) # Going left elif self.change_x <= -tol:",
">= tol: if self.state != FACE_UP: self._update_direction(FACE_UP, self.walk_up_textures[0]) else: self._rotate(self.center_y",
"self._rotate(self.center_x - self.last_texture_change_center_x, self.walk_left_textures) # Going right elif self.change_x >=",
"if self.state != FACE_LEFT: self._update_direction(FACE_LEFT, self.stand_left_texture) else: self._rotate(self.center_x - self.last_texture_change_center_x,",
"self.textures[0] = self._texture self.width = self._texture.width * self.scale self.height =",
"Going left elif self.change_x <= -tol: if self.state != FACE_LEFT:",
"and self.state == FACE_DOWN: self._update_direction(FACE_RIGHT, self.stand_right_texture) self.textures[0] = self._texture self.width",
"self._rotate(self.center_y - self.last_texture_change_center_y, self.walk_up_textures) # Going left elif self.change_x <=",
"# Falling if self.change_y <= -tol: if self.state != FACE_DOWN:",
"def _rotate(self, delta, list): if abs(delta) >= self.texture_change_distance: self.cur_texture_index +=",
"self.state == FACE_DOWN: self._update_direction(FACE_RIGHT, self.stand_right_texture) self.textures[0] = self._texture self.width =",
"right self.walk_up_textures = up self.walk_down_textures = down self.cur_texture_index = 0",
"!= FACE_LEFT: self._update_direction(FACE_LEFT, self.stand_left_texture) else: self._rotate(self.center_x - self.last_texture_change_center_x, self.walk_left_textures) #",
"self.state != FACE_RIGHT: self._update_direction(FACE_RIGHT, self.stand_right_texture) else: self._rotate(self.center_x - self.last_texture_change_center_x, self.walk_right_textures)",
"self.cur_texture_index = 0 self.texture_change_distance = step self.last_texture_change_center_x = 0 self.last_texture_change_center_y",
"self.last_texture_change_center_x = 0 self.last_texture_change_center_y = 0 self._update_direction(FACE_RIGHT, self.stand_right_texture) self.textures =",
"= down self.cur_texture_index = 0 self.texture_change_distance = step self.last_texture_change_center_x =",
"self.last_texture_change_center_x, self.walk_right_textures) elif abs(self.change_x) < tol and self.state == FACE_DOWN:",
"= right self.walk_up_textures = up self.walk_down_textures = down self.cur_texture_index =",
"- self.last_texture_change_center_y, self.walk_down_textures) # Jumping elif self.change_y >= tol: if",
"self.center_x self.last_texture_change_center_y = self.center_y self._texture = list[self.cur_texture_index % len(list)] def",
"0, center_x: float = 0, center_y: float = 0, *,",
"== FACE_DOWN: self._update_direction(FACE_RIGHT, self.stand_right_texture) self.textures[0] = self._texture self.width = self._texture.width",
"0 self.texture_change_distance = step self.last_texture_change_center_x = 0 self.last_texture_change_center_y = 0",
"self.walk_left_textures) # Going right elif self.change_x >= tol: if self.state",
"float = 0, image_y: float = 0, center_x: float =",
"update_animation(self): tol = 1. # Falling if self.change_y <= -tol:",
"self.last_texture_change_center_y, self.walk_up_textures) # Going left elif self.change_x <= -tol: if",
"1, image_x: float = 0, image_y: float = 0, center_x:",
"stand_right self.stand_left_texture = stand_left self.walk_left_textures = left self.walk_right_textures = right",
"__init__(self, scale: float = 1, image_x: float = 0, image_y:",
"= [self._texture] def _update_direction(self, state, texture): self.last_texture_change_center_x = self.center_x self.last_texture_change_center_y",
"self._texture = texture def _rotate(self, delta, list): if abs(delta) >=",
"stand_left, stand_right, left, right, up, down, step=20): super().__init__(scale=scale, image_x=image_x, image_y=image_y,",
"- self.last_texture_change_center_x, self.walk_left_textures) # Going right elif self.change_x >= tol:",
"self.last_texture_change_center_x, self.walk_left_textures) # Going right elif self.change_x >= tol: if",
">= tol: if self.state != FACE_RIGHT: self._update_direction(FACE_RIGHT, self.stand_right_texture) else: self._rotate(self.center_x",
"1. # Falling if self.change_y <= -tol: if self.state !=",
"= up self.walk_down_textures = down self.cur_texture_index = 0 self.texture_change_distance =",
"FACE_UP: self._update_direction(FACE_UP, self.walk_up_textures[0]) else: self._rotate(self.center_y - self.last_texture_change_center_y, self.walk_up_textures) # Going",
"0 self._texture = texture def _rotate(self, delta, list): if abs(delta)",
"def update_animation(self): tol = 1. # Falling if self.change_y <=",
"= left self.walk_right_textures = right self.walk_up_textures = up self.walk_down_textures =",
"!= FACE_DOWN: self._update_direction(FACE_DOWN, self.walk_down_textures[0]) else: self._rotate(self.center_y - self.last_texture_change_center_y, self.walk_down_textures) #",
"super().__init__(scale=scale, image_x=image_x, image_y=image_y, center_x=center_x, center_y=center_y) self.state = FACE_RIGHT self.stand_right_texture =",
"arcade from arcade import FACE_RIGHT, FACE_DOWN, FACE_UP, FACE_LEFT class AnimatedWalkingSprite(arcade.Sprite):",
"self.state != FACE_DOWN: self._update_direction(FACE_DOWN, self.walk_down_textures[0]) else: self._rotate(self.center_y - self.last_texture_change_center_y, self.walk_down_textures)",
"float = 0, *, stand_left, stand_right, left, right, up, down,",
"self.stand_right_texture) else: self._rotate(self.center_x - self.last_texture_change_center_x, self.walk_right_textures) elif abs(self.change_x) < tol",
"self.last_texture_change_center_x = self.center_x self.last_texture_change_center_y = self.center_y self.state = state self.cur_texture_index",
"FACE_DOWN, FACE_UP, FACE_LEFT class AnimatedWalkingSprite(arcade.Sprite): def __init__(self, scale: float =",
"AnimatedWalkingSprite(arcade.Sprite): def __init__(self, scale: float = 1, image_x: float =",
"self.cur_texture_index = 0 self._texture = texture def _rotate(self, delta, list):",
"self._update_direction(FACE_UP, self.walk_up_textures[0]) else: self._rotate(self.center_y - self.last_texture_change_center_y, self.walk_up_textures) # Going left",
"# Going right elif self.change_x >= tol: if self.state !=",
"self.walk_up_textures = up self.walk_down_textures = down self.cur_texture_index = 0 self.texture_change_distance",
"-tol: if self.state != FACE_LEFT: self._update_direction(FACE_LEFT, self.stand_left_texture) else: self._rotate(self.center_x -",
"if self.state != FACE_UP: self._update_direction(FACE_UP, self.walk_up_textures[0]) else: self._rotate(self.center_y - self.last_texture_change_center_y,",
"0, center_y: float = 0, *, stand_left, stand_right, left, right,",
"= 0, center_y: float = 0, *, stand_left, stand_right, left,",
"left, right, up, down, step=20): super().__init__(scale=scale, image_x=image_x, image_y=image_y, center_x=center_x, center_y=center_y)",
"= self.center_y self._texture = list[self.cur_texture_index % len(list)] def update_animation(self): tol",
"self.texture_change_distance = step self.last_texture_change_center_x = 0 self.last_texture_change_center_y = 0 self._update_direction(FACE_RIGHT,",
"image_x=image_x, image_y=image_y, center_x=center_x, center_y=center_y) self.state = FACE_RIGHT self.stand_right_texture = stand_right",
"self._rotate(self.center_x - self.last_texture_change_center_x, self.walk_right_textures) elif abs(self.change_x) < tol and self.state",
"list[self.cur_texture_index % len(list)] def update_animation(self): tol = 1. # Falling",
"else: self._rotate(self.center_y - self.last_texture_change_center_y, self.walk_down_textures) # Jumping elif self.change_y >=",
"Jumping elif self.change_y >= tol: if self.state != FACE_UP: self._update_direction(FACE_UP,",
"if self.state != FACE_RIGHT: self._update_direction(FACE_RIGHT, self.stand_right_texture) else: self._rotate(self.center_x - self.last_texture_change_center_x,",
"- self.last_texture_change_center_x, self.walk_right_textures) elif abs(self.change_x) < tol and self.state ==",
"= state self.cur_texture_index = 0 self._texture = texture def _rotate(self,",
"FACE_RIGHT self.stand_right_texture = stand_right self.stand_left_texture = stand_left self.walk_left_textures = left",
"stand_left self.walk_left_textures = left self.walk_right_textures = right self.walk_up_textures = up",
"+= 1 self.last_texture_change_center_x = self.center_x self.last_texture_change_center_y = self.center_y self._texture =",
"down, step=20): super().__init__(scale=scale, image_x=image_x, image_y=image_y, center_x=center_x, center_y=center_y) self.state = FACE_RIGHT",
"FACE_UP, FACE_LEFT class AnimatedWalkingSprite(arcade.Sprite): def __init__(self, scale: float = 1,",
"self.textures = [self._texture] def _update_direction(self, state, texture): self.last_texture_change_center_x = self.center_x",
"else: self._rotate(self.center_x - self.last_texture_change_center_x, self.walk_left_textures) # Going right elif self.change_x",
"self.walk_down_textures[0]) else: self._rotate(self.center_y - self.last_texture_change_center_y, self.walk_down_textures) # Jumping elif self.change_y",
"down self.cur_texture_index = 0 self.texture_change_distance = step self.last_texture_change_center_x = 0",
"= self.center_x self.last_texture_change_center_y = self.center_y self.state = state self.cur_texture_index =",
"self.state != FACE_UP: self._update_direction(FACE_UP, self.walk_up_textures[0]) else: self._rotate(self.center_y - self.last_texture_change_center_y, self.walk_up_textures)",
"# Jumping elif self.change_y >= tol: if self.state != FACE_UP:",
"list): if abs(delta) >= self.texture_change_distance: self.cur_texture_index += 1 self.last_texture_change_center_x =",
"state, texture): self.last_texture_change_center_x = self.center_x self.last_texture_change_center_y = self.center_y self.state =",
"1 self.last_texture_change_center_x = self.center_x self.last_texture_change_center_y = self.center_y self._texture = list[self.cur_texture_index",
"self.center_y self._texture = list[self.cur_texture_index % len(list)] def update_animation(self): tol ="
] |
[
"deepcopy(self.regressor) self.mmodel.fit(x_train, y_train) def train_quant(self, init_x, follow_x, init_y, follow_iter): self.train_binary(init_x,",
"with CV training can have multiple results self.cancer_status = None",
"up training\") return for i in range(follow_iter): init_preds = self.mmodel.predict(init_x)",
"preds[:,0] return probs def predict_quant(self, input_x): #preds = matmul(input_x, transpose(self.mmodel.coef_))",
"\"\"\" store output for prediction \"\"\" def __init__(self): self.true_y =",
"init_y, follow_iter): self.train_binary(init_x, init_y) if follow_x is None: logging.warning(\"No samples",
"matmul(input_x, transpose(self.mmodel.coef_)) + self.mmodel.intercept_ probs = preds[:,0] return probs def",
"training\") return for i in range(follow_iter): init_preds = self.mmodel.predict(init_x) upper_limit",
"# with CV training can have multiple results self.cancer_status =",
"multiple results self.cancer_status = None # binary: 0 for normal",
"preds[:,0] #return probs return self.mmodel.predict(input_x) class predOutcome(): \"\"\" store output",
"= 0.95 def train_binary(self, x_train, y_train): self.mmodel = deepcopy(self.regressor) self.mmodel.fit(x_train,",
"transpose from sklearn import linear_model from scipy.special import logit from",
"concatenate, quantile, matmul, transpose import logging class singleRegModel(): \"\"\" data",
"y_train) def train_quant(self, init_x, follow_x, init_y, follow_iter): self.train_binary(init_x, init_y) if",
"= matmul(input_x, transpose(self.mmodel.coef_)) + self.mmodel.intercept_ probs = preds[:,0] return probs",
"None # params self.quantile_limit_ = 0.95 def train_binary(self, x_train, y_train):",
"follow_y = self.mmodel.predict(follow_x) follow_y[follow_y > upper_limit] = upper_limit x_merge =",
"output for prediction \"\"\" def __init__(self): self.true_y = None self.test_y",
"follow_iter): self.train_binary(init_x, init_y) if follow_x is None: logging.warning(\"No samples have",
"self.quantile_limit_) follow_y = self.mmodel.predict(follow_x) follow_y[follow_y > upper_limit] = upper_limit x_merge",
"y_merge = concatenate((init_y, follow_y)) self.mmodel = deepcopy(self.regressor) self.mmodel.fit(x_merge, y_merge) def",
"y_merge) def predict_prob(self, input_x): preds = matmul(input_x, transpose(self.mmodel.coef_)) + self.mmodel.intercept_",
"> upper_limit] = upper_limit x_merge = concatenate((init_x, follow_x)) y_merge =",
"+ self.mmodel.intercept_ #print(preds, self.mmodel.predict(input_x)) #probs = preds[:,0] #return probs return",
"regression test \"\"\" def __init__(self, regressor): self.regressor = regressor self.mmodel",
"transpose(self.mmodel.coef_)) + self.mmodel.intercept_ probs = preds[:,0] return probs def predict_quant(self,",
"stats from copy import deepcopy from numpy import random, concatenate,",
"import deepcopy from numpy import random, concatenate, quantile, matmul, transpose",
"samples have missing MAF - no follow up training\") return",
"__init__(self): self.true_y = None self.test_y = None self.train_ys = []",
"y_train): self.mmodel = deepcopy(self.regressor) self.mmodel.fit(x_train, y_train) def train_quant(self, init_x, follow_x,",
"MAF - no follow up training\") return for i in",
"self.test_y = None self.train_ys = [] # with CV training",
"scipy.special import logit from scipy import stats from copy import",
"import linear_model from scipy.special import logit from scipy import stats",
"self.mmodel = deepcopy(self.regressor) self.mmodel.fit(x_merge, y_merge) def predict_prob(self, input_x): preds =",
"for running a single regression test \"\"\" def __init__(self, regressor):",
"upper_limit x_merge = concatenate((init_x, follow_x)) y_merge = concatenate((init_y, follow_y)) self.mmodel",
"None # binary: 0 for normal and 1 for cance",
"= deepcopy(self.regressor) self.mmodel.fit(x_merge, y_merge) def predict_prob(self, input_x): preds = matmul(input_x,",
"from scipy import stats from copy import deepcopy from numpy",
"x_train, y_train): self.mmodel = deepcopy(self.regressor) self.mmodel.fit(x_train, y_train) def train_quant(self, init_x,",
"data struct for running a single regression test \"\"\" def",
"def predict_quant(self, input_x): #preds = matmul(input_x, transpose(self.mmodel.coef_)) + self.mmodel.intercept_ #print(preds,",
"#probs = preds[:,0] #return probs return self.mmodel.predict(input_x) class predOutcome(): \"\"\"",
"import transpose from sklearn import linear_model from scipy.special import logit",
"from sklearn import linear_model from scipy.special import logit from scipy",
"= None # params self.quantile_limit_ = 0.95 def train_binary(self, x_train,",
"import logit from scipy import stats from copy import deepcopy",
"class predOutcome(): \"\"\" store output for prediction \"\"\" def __init__(self):",
"= concatenate((init_x, follow_x)) y_merge = concatenate((init_y, follow_y)) self.mmodel = deepcopy(self.regressor)",
"self.mmodel.fit(x_train, y_train) def train_quant(self, init_x, follow_x, init_y, follow_iter): self.train_binary(init_x, init_y)",
"CV training can have multiple results self.cancer_status = None #",
"follow up training\") return for i in range(follow_iter): init_preds =",
"\"\"\" def __init__(self): self.true_y = None self.test_y = None self.train_ys",
"\"\"\" data struct for running a single regression test \"\"\"",
"deepcopy(self.regressor) self.mmodel.fit(x_merge, y_merge) def predict_prob(self, input_x): preds = matmul(input_x, transpose(self.mmodel.coef_))",
"def predict_prob(self, input_x): preds = matmul(input_x, transpose(self.mmodel.coef_)) + self.mmodel.intercept_ probs",
"copy import deepcopy from numpy import random, concatenate, quantile, matmul,",
"predOutcome(): \"\"\" store output for prediction \"\"\" def __init__(self): self.true_y",
"deepcopy from numpy import random, concatenate, quantile, matmul, transpose import",
"follow_y)) self.mmodel = deepcopy(self.regressor) self.mmodel.fit(x_merge, y_merge) def predict_prob(self, input_x): preds",
"quantile, matmul, transpose import logging class singleRegModel(): \"\"\" data struct",
"train_quant(self, init_x, follow_x, init_y, follow_iter): self.train_binary(init_x, init_y) if follow_x is",
"return probs def predict_quant(self, input_x): #preds = matmul(input_x, transpose(self.mmodel.coef_)) +",
"preds = matmul(input_x, transpose(self.mmodel.coef_)) + self.mmodel.intercept_ probs = preds[:,0] return",
"self.mmodel.predict(init_x) upper_limit = quantile(init_preds, self.quantile_limit_) follow_y = self.mmodel.predict(follow_x) follow_y[follow_y >",
"follow_y[follow_y > upper_limit] = upper_limit x_merge = concatenate((init_x, follow_x)) y_merge",
"= None self.train_ys = [] # with CV training can",
"= quantile(init_preds, self.quantile_limit_) follow_y = self.mmodel.predict(follow_x) follow_y[follow_y > upper_limit] =",
"prediction \"\"\" def __init__(self): self.true_y = None self.test_y = None",
"<filename>src/mafUtility.py<gh_stars>1-10 from numpy.core.fromnumeric import transpose from sklearn import linear_model from",
"from copy import deepcopy from numpy import random, concatenate, quantile,",
"None: logging.warning(\"No samples have missing MAF - no follow up",
"a single regression test \"\"\" def __init__(self, regressor): self.regressor =",
"self.mmodel.fit(x_merge, y_merge) def predict_prob(self, input_x): preds = matmul(input_x, transpose(self.mmodel.coef_)) +",
"x_merge = concatenate((init_x, follow_x)) y_merge = concatenate((init_y, follow_y)) self.mmodel =",
"upper_limit = quantile(init_preds, self.quantile_limit_) follow_y = self.mmodel.predict(follow_x) follow_y[follow_y > upper_limit]",
"= regressor self.mmodel = None # params self.quantile_limit_ = 0.95",
"regressor self.mmodel = None # params self.quantile_limit_ = 0.95 def",
"0.95 def train_binary(self, x_train, y_train): self.mmodel = deepcopy(self.regressor) self.mmodel.fit(x_train, y_train)",
"None self.train_ys = [] # with CV training can have",
"= self.mmodel.predict(init_x) upper_limit = quantile(init_preds, self.quantile_limit_) follow_y = self.mmodel.predict(follow_x) follow_y[follow_y",
"scipy import stats from copy import deepcopy from numpy import",
"self.regressor = regressor self.mmodel = None # params self.quantile_limit_ =",
"def __init__(self, regressor): self.regressor = regressor self.mmodel = None #",
"= concatenate((init_y, follow_y)) self.mmodel = deepcopy(self.regressor) self.mmodel.fit(x_merge, y_merge) def predict_prob(self,",
"def train_quant(self, init_x, follow_x, init_y, follow_iter): self.train_binary(init_x, init_y) if follow_x",
"#print(preds, self.mmodel.predict(input_x)) #probs = preds[:,0] #return probs return self.mmodel.predict(input_x) class",
"= preds[:,0] #return probs return self.mmodel.predict(input_x) class predOutcome(): \"\"\" store",
"\"\"\" def __init__(self, regressor): self.regressor = regressor self.mmodel = None",
"[] # with CV training can have multiple results self.cancer_status",
"input_x): preds = matmul(input_x, transpose(self.mmodel.coef_)) + self.mmodel.intercept_ probs = preds[:,0]",
"is None: logging.warning(\"No samples have missing MAF - no follow",
"- no follow up training\") return for i in range(follow_iter):",
"self.mmodel = deepcopy(self.regressor) self.mmodel.fit(x_train, y_train) def train_quant(self, init_x, follow_x, init_y,",
"can have multiple results self.cancer_status = None # binary: 0",
"range(follow_iter): init_preds = self.mmodel.predict(init_x) upper_limit = quantile(init_preds, self.quantile_limit_) follow_y =",
"= None # binary: 0 for normal and 1 for",
"self.train_ys = [] # with CV training can have multiple",
"upper_limit] = upper_limit x_merge = concatenate((init_x, follow_x)) y_merge = concatenate((init_y,",
"if follow_x is None: logging.warning(\"No samples have missing MAF -",
"+ self.mmodel.intercept_ probs = preds[:,0] return probs def predict_quant(self, input_x):",
"init_y) if follow_x is None: logging.warning(\"No samples have missing MAF",
"random, concatenate, quantile, matmul, transpose import logging class singleRegModel(): \"\"\"",
"missing MAF - no follow up training\") return for i",
"training can have multiple results self.cancer_status = None # binary:",
"self.mmodel = None # params self.quantile_limit_ = 0.95 def train_binary(self,",
"quantile(init_preds, self.quantile_limit_) follow_y = self.mmodel.predict(follow_x) follow_y[follow_y > upper_limit] = upper_limit",
"struct for running a single regression test \"\"\" def __init__(self,",
"running a single regression test \"\"\" def __init__(self, regressor): self.regressor",
"self.mmodel.predict(input_x) class predOutcome(): \"\"\" store output for prediction \"\"\" def",
"init_preds = self.mmodel.predict(init_x) upper_limit = quantile(init_preds, self.quantile_limit_) follow_y = self.mmodel.predict(follow_x)",
"from numpy.core.fromnumeric import transpose from sklearn import linear_model from scipy.special",
"= upper_limit x_merge = concatenate((init_x, follow_x)) y_merge = concatenate((init_y, follow_y))",
"numpy.core.fromnumeric import transpose from sklearn import linear_model from scipy.special import",
"predict_quant(self, input_x): #preds = matmul(input_x, transpose(self.mmodel.coef_)) + self.mmodel.intercept_ #print(preds, self.mmodel.predict(input_x))",
"self.mmodel.intercept_ probs = preds[:,0] return probs def predict_quant(self, input_x): #preds",
"matmul(input_x, transpose(self.mmodel.coef_)) + self.mmodel.intercept_ #print(preds, self.mmodel.predict(input_x)) #probs = preds[:,0] #return",
"from numpy import random, concatenate, quantile, matmul, transpose import logging",
"= preds[:,0] return probs def predict_quant(self, input_x): #preds = matmul(input_x,",
"class singleRegModel(): \"\"\" data struct for running a single regression",
"import stats from copy import deepcopy from numpy import random,",
"transpose(self.mmodel.coef_)) + self.mmodel.intercept_ #print(preds, self.mmodel.predict(input_x)) #probs = preds[:,0] #return probs",
"in range(follow_iter): init_preds = self.mmodel.predict(init_x) upper_limit = quantile(init_preds, self.quantile_limit_) follow_y",
"store output for prediction \"\"\" def __init__(self): self.true_y = None",
"predict_prob(self, input_x): preds = matmul(input_x, transpose(self.mmodel.coef_)) + self.mmodel.intercept_ probs =",
"probs def predict_quant(self, input_x): #preds = matmul(input_x, transpose(self.mmodel.coef_)) + self.mmodel.intercept_",
"return self.mmodel.predict(input_x) class predOutcome(): \"\"\" store output for prediction \"\"\"",
"follow_x)) y_merge = concatenate((init_y, follow_y)) self.mmodel = deepcopy(self.regressor) self.mmodel.fit(x_merge, y_merge)",
"singleRegModel(): \"\"\" data struct for running a single regression test",
"no follow up training\") return for i in range(follow_iter): init_preds",
"numpy import random, concatenate, quantile, matmul, transpose import logging class",
"= deepcopy(self.regressor) self.mmodel.fit(x_train, y_train) def train_quant(self, init_x, follow_x, init_y, follow_iter):",
"for prediction \"\"\" def __init__(self): self.true_y = None self.test_y =",
"self.true_y = None self.test_y = None self.train_ys = [] #",
"have missing MAF - no follow up training\") return for",
"= self.mmodel.predict(follow_x) follow_y[follow_y > upper_limit] = upper_limit x_merge = concatenate((init_x,",
"probs return self.mmodel.predict(input_x) class predOutcome(): \"\"\" store output for prediction",
"logging class singleRegModel(): \"\"\" data struct for running a single",
"self.train_binary(init_x, init_y) if follow_x is None: logging.warning(\"No samples have missing",
"import logging class singleRegModel(): \"\"\" data struct for running a",
"= None self.test_y = None self.train_ys = [] # with",
"follow_x is None: logging.warning(\"No samples have missing MAF - no",
"self.mmodel.predict(follow_x) follow_y[follow_y > upper_limit] = upper_limit x_merge = concatenate((init_x, follow_x))",
"None self.test_y = None self.train_ys = [] # with CV",
"import random, concatenate, quantile, matmul, transpose import logging class singleRegModel():",
"i in range(follow_iter): init_preds = self.mmodel.predict(init_x) upper_limit = quantile(init_preds, self.quantile_limit_)",
"#return probs return self.mmodel.predict(input_x) class predOutcome(): \"\"\" store output for",
"# params self.quantile_limit_ = 0.95 def train_binary(self, x_train, y_train): self.mmodel",
"logit from scipy import stats from copy import deepcopy from",
"sklearn import linear_model from scipy.special import logit from scipy import",
"train_binary(self, x_train, y_train): self.mmodel = deepcopy(self.regressor) self.mmodel.fit(x_train, y_train) def train_quant(self,",
"follow_x, init_y, follow_iter): self.train_binary(init_x, init_y) if follow_x is None: logging.warning(\"No",
"params self.quantile_limit_ = 0.95 def train_binary(self, x_train, y_train): self.mmodel =",
"input_x): #preds = matmul(input_x, transpose(self.mmodel.coef_)) + self.mmodel.intercept_ #print(preds, self.mmodel.predict(input_x)) #probs",
"regressor): self.regressor = regressor self.mmodel = None # params self.quantile_limit_",
"test \"\"\" def __init__(self, regressor): self.regressor = regressor self.mmodel =",
"logging.warning(\"No samples have missing MAF - no follow up training\")",
"self.mmodel.intercept_ #print(preds, self.mmodel.predict(input_x)) #probs = preds[:,0] #return probs return self.mmodel.predict(input_x)",
"concatenate((init_x, follow_x)) y_merge = concatenate((init_y, follow_y)) self.mmodel = deepcopy(self.regressor) self.mmodel.fit(x_merge,",
"self.cancer_status = None # binary: 0 for normal and 1",
"def train_binary(self, x_train, y_train): self.mmodel = deepcopy(self.regressor) self.mmodel.fit(x_train, y_train) def",
"= matmul(input_x, transpose(self.mmodel.coef_)) + self.mmodel.intercept_ #print(preds, self.mmodel.predict(input_x)) #probs = preds[:,0]",
"results self.cancer_status = None # binary: 0 for normal and",
"self.quantile_limit_ = 0.95 def train_binary(self, x_train, y_train): self.mmodel = deepcopy(self.regressor)",
"concatenate((init_y, follow_y)) self.mmodel = deepcopy(self.regressor) self.mmodel.fit(x_merge, y_merge) def predict_prob(self, input_x):",
"have multiple results self.cancer_status = None # binary: 0 for",
"linear_model from scipy.special import logit from scipy import stats from",
"init_x, follow_x, init_y, follow_iter): self.train_binary(init_x, init_y) if follow_x is None:",
"#preds = matmul(input_x, transpose(self.mmodel.coef_)) + self.mmodel.intercept_ #print(preds, self.mmodel.predict(input_x)) #probs =",
"matmul, transpose import logging class singleRegModel(): \"\"\" data struct for",
"def __init__(self): self.true_y = None self.test_y = None self.train_ys =",
"return for i in range(follow_iter): init_preds = self.mmodel.predict(init_x) upper_limit =",
"transpose import logging class singleRegModel(): \"\"\" data struct for running",
"from scipy.special import logit from scipy import stats from copy",
"= [] # with CV training can have multiple results",
"__init__(self, regressor): self.regressor = regressor self.mmodel = None # params",
"for i in range(follow_iter): init_preds = self.mmodel.predict(init_x) upper_limit = quantile(init_preds,",
"probs = preds[:,0] return probs def predict_quant(self, input_x): #preds =",
"self.mmodel.predict(input_x)) #probs = preds[:,0] #return probs return self.mmodel.predict(input_x) class predOutcome():",
"single regression test \"\"\" def __init__(self, regressor): self.regressor = regressor"
] |
[
"= LinearGaussianWithDiagonalPrecision(column_dim=n_features, row_dim=1, affine=False) stats = likelihood.statistics(X, np.atleast_2d(y).T) posterior.nat_param =",
"parameter_prior.nat_param + stats # likelihood precision posterior param = parameter_posterior.mean()",
"alphas=alphas, betas=betas) posterior = deepcopy(prior) likelihood = LinearGaussianWithDiagonalPrecision(column_dim=n_features, row_dim=1, affine=False)",
"betas=1e-6 * np.ones((1, ))) parameter_precision_prior = Gamma(dim=n_features, alphas=np.ones((n_features, )), betas=1e-6",
"10) for i in relevant_features: w[i] = stats.norm.rvs(loc=0, scale=1. /",
"y) from copy import deepcopy from sds.distributions.lingauss import SingleOutputLinearGaussianWithKnownPrecision from",
"import Gamma likelihood_precision_prior = Gamma(dim=1, alphas=np.ones((1, )), betas=1e-6 * np.ones((1,",
"of the example np.random.seed(0) n_samples, n_features = 100, 100 #",
"beta = likelihood_precision_posterior.mean() likelihood_known_precision = SingleOutputLinearGaussianWithKnownPrecision(column_dim=n_features, lmbda=beta, affine=False) stats =",
"= likelihood_precision_posterior.mean() likelihood_known_precision = SingleOutputLinearGaussianWithKnownPrecision(column_dim=n_features, lmbda=beta, affine=False) stats = likelihood_known_precision.statistics(X,",
"LinearGaussianWithDiagonalPrecision(column_dim=n_features, row_dim=1, affine=False) stats = likelihood.statistics(X, np.atleast_2d(y).T) posterior.nat_param = prior.nat_param",
"from sds.distributions.lingauss import SingleOutputLinearGaussianWithKnownMean from sds.distributions.gaussian import GaussianWithPrecision from sds.distributions.gaussian",
"of the model\") plt.plot(w, color='orange', linestyle='-', linewidth=2, label=\"Ground truth\") plt.plot(clf.coef_,",
"likelihood_precision_prior.nat_param + stats # parameter precision posterior parameter_likelihood = GaussianWithKnownMeanAndDiagonalPrecision(dim=n_features)",
"scipy import stats from sklearn.linear_model import ARDRegression, LinearRegression # Parameters",
"linewidth=2, label=\"Our OLS\") plt.xlabel(\"Features\") plt.ylabel(\"Values of the weights\") plt.legend(loc=1) plt.show()",
"import GaussianWithPrecision from sds.distributions.gaussian import GaussianWithKnownMeanAndDiagonalPrecision from sds.distributions.gamma import Gamma",
"= None for i in range(100): # parameter posterior alphas",
"linewidth=2, label=\"Our ARD\") # plt.plot(ols.coef_, color='yellowgreen', linestyle=':', linewidth=2, label=\"Sklearn OLS\")",
"parameter_prior = GaussianWithPrecision(dim=n_features, mu=np.zeros((n_features, )), lmbda=np.diag(alphas)) parameter_posterior = deepcopy(parameter_prior) beta",
"np.atleast_2d(y).T) posterior.nat_param = prior.nat_param + stats our_ols = posterior.mode()[0] plt.figure(figsize=(6,",
"w[i] = stats.norm.rvs(loc=0, scale=1. / np.sqrt(lambda_)) # Create noise with",
"betas = 1e-16 * np.ones((1, )) prior = MatrixNormalGamma(column_dim=n_features, row_dim=1,",
"clf.fit(X, y) ols = LinearRegression(fit_intercept=False) ols.fit(X, y) from copy import",
"linestyle='-', linewidth=2, label=\"Sklearn ARD\") plt.plot(our_ard, color='red', linestyle='-', linewidth=2, label=\"Our ARD\")",
"parameter_precision_posterior = deepcopy(parameter_precision_prior) parameter_posterior = None for i in range(100):",
"LinearRegression(fit_intercept=False) ols.fit(X, y) from copy import deepcopy from sds.distributions.lingauss import",
"n_features) # Create weights with a precision lambda_ of 4.",
"as np import matplotlib.pyplot as plt from scipy import stats",
"= deepcopy(prior) likelihood = LinearGaussianWithDiagonalPrecision(column_dim=n_features, row_dim=1, affine=False) stats = likelihood.statistics(X,",
"label=\"Ground truth\") plt.plot(clf.coef_, color='darkblue', linestyle='-', linewidth=2, label=\"Sklearn ARD\") plt.plot(our_ard, color='red',",
"np.random.randn(n_samples, n_features) # Create weights with a precision lambda_ of",
"= Gamma(dim=1, alphas=np.ones((1, )), betas=1e-6 * np.ones((1, ))) parameter_precision_prior =",
"from sds.distributions.composite import MatrixNormalGamma from sds.distributions.lingauss import LinearGaussianWithDiagonalPrecision M =",
"4. lambda_ = 4. w = np.zeros(n_features) # Only keep",
"np.zeros(n_features) # Only keep 10 weights of interest relevant_features =",
"np.ones((1, ))) parameter_precision_prior = Gamma(dim=n_features, alphas=np.ones((n_features, )), betas=1e-6 * np.ones((n_features,",
"10 weights of interest relevant_features = np.random.randint(0, n_features, 10) for",
"w = np.zeros(n_features) # Only keep 10 weights of interest",
"linestyle='-', linewidth=2, label=\"Our ARD\") # plt.plot(ols.coef_, color='yellowgreen', linestyle=':', linewidth=2, label=\"Sklearn",
"color='yellowgreen', linestyle=':', linewidth=2, label=\"Sklearn OLS\") # plt.plot(our_ols.flatten(), color='cyan', linestyle='-', linewidth=2,",
"= parameter_posterior.mode() from sds.distributions.composite import MatrixNormalGamma from sds.distributions.lingauss import LinearGaussianWithDiagonalPrecision",
"sds.distributions.gamma import Gamma likelihood_precision_prior = Gamma(dim=1, alphas=np.ones((1, )), betas=1e-6 *",
"from sds.distributions.lingauss import SingleOutputLinearGaussianWithKnownPrecision from sds.distributions.lingauss import SingleOutputLinearGaussianWithKnownMean from sds.distributions.gaussian",
"* np.ones((1, ))) parameter_precision_prior = Gamma(dim=n_features, alphas=np.ones((n_features, )), betas=1e-6 *",
"/ np.sqrt(lambda_)) # Create noise with a precision alpha of",
"= parameter_posterior.mean() stats = parameter_likelihood.statistics(param) parameter_precision_posterior.nat_param = parameter_precision_prior.nat_param + stats",
"n_iter=1000) clf.fit(X, y) ols = LinearRegression(fit_intercept=False) ols.fit(X, y) from copy",
"= likelihood.statistics(X, np.atleast_2d(y).T) posterior.nat_param = prior.nat_param + stats our_ols =",
"likelihood_known_mean.statistics(X, y) likelihood_precision_posterior.nat_param = likelihood_precision_prior.nat_param + stats # parameter precision",
"MatrixNormalGamma from sds.distributions.lingauss import LinearGaussianWithDiagonalPrecision M = np.zeros((1, n_features)) K",
"interest relevant_features = np.random.randint(0, n_features, 10) for i in relevant_features:",
"from sds.distributions.lingauss import LinearGaussianWithDiagonalPrecision M = np.zeros((1, n_features)) K =",
"parameter precision posterior parameter_likelihood = GaussianWithKnownMeanAndDiagonalPrecision(dim=n_features) param = parameter_posterior.mean() stats",
"parameter_posterior = deepcopy(parameter_prior) beta = likelihood_precision_posterior.mean() likelihood_known_precision = SingleOutputLinearGaussianWithKnownPrecision(column_dim=n_features, lmbda=beta,",
"y = np.dot(X, w) + noise clf = ARDRegression(fit_intercept=False, n_iter=1000)",
"parameter_precision_prior.nat_param + stats our_ard = parameter_posterior.mode() from sds.distributions.composite import MatrixNormalGamma",
"stats.norm.rvs(loc=0, scale=1. / np.sqrt(alpha_), size=n_samples) # Create the target< y",
"in range(100): # parameter posterior alphas = parameter_precision_posterior.mean() parameter_prior =",
"y) ols = LinearRegression(fit_intercept=False) ols.fit(X, y) from copy import deepcopy",
"stats = parameter_likelihood.statistics(param) parameter_precision_posterior.nat_param = parameter_precision_prior.nat_param + stats our_ard =",
"posterior.nat_param = prior.nat_param + stats our_ols = posterior.mode()[0] plt.figure(figsize=(6, 5))",
"ARD\") # plt.plot(ols.coef_, color='yellowgreen', linestyle=':', linewidth=2, label=\"Sklearn OLS\") # plt.plot(our_ols.flatten(),",
"precision posterior param = parameter_posterior.mean() likelihood_known_mean = SingleOutputLinearGaussianWithKnownMean(column_dim=n_features, W=param, affine=False)",
"import deepcopy from sds.distributions.lingauss import SingleOutputLinearGaussianWithKnownPrecision from sds.distributions.lingauss import SingleOutputLinearGaussianWithKnownMean",
"import GaussianWithKnownMeanAndDiagonalPrecision from sds.distributions.gamma import Gamma likelihood_precision_prior = Gamma(dim=1, alphas=np.ones((1,",
"GaussianWithKnownMeanAndDiagonalPrecision(dim=n_features) param = parameter_posterior.mean() stats = parameter_likelihood.statistics(param) parameter_precision_posterior.nat_param = parameter_precision_prior.nat_param",
"+ stats # likelihood precision posterior param = parameter_posterior.mean() likelihood_known_mean",
"label=\"Our ARD\") # plt.plot(ols.coef_, color='yellowgreen', linestyle=':', linewidth=2, label=\"Sklearn OLS\") #",
"= np.random.randn(n_samples, n_features) # Create weights with a precision lambda_",
"n_features, 10) for i in relevant_features: w[i] = stats.norm.rvs(loc=0, scale=1.",
"import matplotlib.pyplot as plt from scipy import stats from sklearn.linear_model",
"linestyle='-', linewidth=2, label=\"Our OLS\") plt.xlabel(\"Features\") plt.ylabel(\"Values of the weights\") plt.legend(loc=1)",
"parameter posterior alphas = parameter_precision_posterior.mean() parameter_prior = GaussianWithPrecision(dim=n_features, mu=np.zeros((n_features, )),",
"= 1e-16 * np.ones((1, )) betas = 1e-16 * np.ones((1,",
"SingleOutputLinearGaussianWithKnownMean(column_dim=n_features, W=param, affine=False) stats = likelihood_known_mean.statistics(X, y) likelihood_precision_posterior.nat_param = likelihood_precision_prior.nat_param",
"parameter_likelihood = GaussianWithKnownMeanAndDiagonalPrecision(dim=n_features) param = parameter_posterior.mean() stats = parameter_likelihood.statistics(param) parameter_precision_posterior.nat_param",
"color='orange', linestyle='-', linewidth=2, label=\"Ground truth\") plt.plot(clf.coef_, color='darkblue', linestyle='-', linewidth=2, label=\"Sklearn",
"= parameter_precision_posterior.mean() parameter_prior = GaussianWithPrecision(dim=n_features, mu=np.zeros((n_features, )), lmbda=np.diag(alphas)) parameter_posterior =",
"# Create the target< y = np.dot(X, w) + noise",
"likelihood_known_mean = SingleOutputLinearGaussianWithKnownMean(column_dim=n_features, W=param, affine=False) stats = likelihood_known_mean.statistics(X, y) likelihood_precision_posterior.nat_param",
"# Parameters of the example np.random.seed(0) n_samples, n_features = 100,",
"alphas = parameter_precision_posterior.mean() parameter_prior = GaussianWithPrecision(dim=n_features, mu=np.zeros((n_features, )), lmbda=np.diag(alphas)) parameter_posterior",
"ARD\") plt.plot(our_ard, color='red', linestyle='-', linewidth=2, label=\"Our ARD\") # plt.plot(ols.coef_, color='yellowgreen',",
"import SingleOutputLinearGaussianWithKnownMean from sds.distributions.gaussian import GaussianWithPrecision from sds.distributions.gaussian import GaussianWithKnownMeanAndDiagonalPrecision",
"# parameter precision posterior parameter_likelihood = GaussianWithKnownMeanAndDiagonalPrecision(dim=n_features) param = parameter_posterior.mean()",
"parameter_posterior.mean() stats = parameter_likelihood.statistics(param) parameter_precision_posterior.nat_param = parameter_precision_prior.nat_param + stats our_ard",
"copy import deepcopy from sds.distributions.lingauss import SingleOutputLinearGaussianWithKnownPrecision from sds.distributions.lingauss import",
"1e-16 * np.ones((1, )) prior = MatrixNormalGamma(column_dim=n_features, row_dim=1, M=M, K=K,",
"= deepcopy(parameter_prior) beta = likelihood_precision_posterior.mean() likelihood_known_precision = SingleOutputLinearGaussianWithKnownPrecision(column_dim=n_features, lmbda=beta, affine=False)",
"scale=1. / np.sqrt(lambda_)) # Create noise with a precision alpha",
"betas=1e-6 * np.ones((n_features, ))) likelihood_precision_posterior = deepcopy(likelihood_precision_prior) parameter_precision_posterior = deepcopy(parameter_precision_prior)",
")), betas=1e-6 * np.ones((1, ))) parameter_precision_prior = Gamma(dim=n_features, alphas=np.ones((n_features, )),",
"Create noise with a precision alpha of 50. alpha_ =",
"= parameter_prior.nat_param + stats # likelihood precision posterior param =",
"LinearGaussianWithDiagonalPrecision M = np.zeros((1, n_features)) K = 1e-16 * np.eye(n_features)",
"affine=False) stats = likelihood_known_precision.statistics(X, y) parameter_posterior.nat_param = parameter_prior.nat_param + stats",
"lmbda=np.diag(alphas)) parameter_posterior = deepcopy(parameter_prior) beta = likelihood_precision_posterior.mean() likelihood_known_precision = SingleOutputLinearGaussianWithKnownPrecision(column_dim=n_features,",
"= np.zeros((1, n_features)) K = 1e-16 * np.eye(n_features) alphas =",
"n_features = 100, 100 # Create Gaussian data X =",
"the target< y = np.dot(X, w) + noise clf =",
"lmbda=beta, affine=False) stats = likelihood_known_precision.statistics(X, y) parameter_posterior.nat_param = parameter_prior.nat_param +",
"np.random.randint(0, n_features, 10) for i in relevant_features: w[i] = stats.norm.rvs(loc=0,",
"5)) plt.title(\"Weights of the model\") plt.plot(w, color='orange', linestyle='-', linewidth=2, label=\"Ground",
"/ np.sqrt(alpha_), size=n_samples) # Create the target< y = np.dot(X,",
"MatrixNormalGamma(column_dim=n_features, row_dim=1, M=M, K=K, alphas=alphas, betas=betas) posterior = deepcopy(prior) likelihood",
"the model\") plt.plot(w, color='orange', linestyle='-', linewidth=2, label=\"Ground truth\") plt.plot(clf.coef_, color='darkblue',",
"np.eye(n_features) alphas = 1e-16 * np.ones((1, )) betas = 1e-16",
"model\") plt.plot(w, color='orange', linestyle='-', linewidth=2, label=\"Ground truth\") plt.plot(clf.coef_, color='darkblue', linestyle='-',",
"stats # likelihood precision posterior param = parameter_posterior.mean() likelihood_known_mean =",
"likelihood.statistics(X, np.atleast_2d(y).T) posterior.nat_param = prior.nat_param + stats our_ols = posterior.mode()[0]",
"Gamma(dim=1, alphas=np.ones((1, )), betas=1e-6 * np.ones((1, ))) parameter_precision_prior = Gamma(dim=n_features,",
"label=\"Sklearn OLS\") # plt.plot(our_ols.flatten(), color='cyan', linestyle='-', linewidth=2, label=\"Our OLS\") plt.xlabel(\"Features\")",
"= stats.norm.rvs(loc=0, scale=1. / np.sqrt(lambda_)) # Create noise with a",
"100, 100 # Create Gaussian data X = np.random.randn(n_samples, n_features)",
"= parameter_posterior.mean() likelihood_known_mean = SingleOutputLinearGaussianWithKnownMean(column_dim=n_features, W=param, affine=False) stats = likelihood_known_mean.statistics(X,",
"W=param, affine=False) stats = likelihood_known_mean.statistics(X, y) likelihood_precision_posterior.nat_param = likelihood_precision_prior.nat_param +",
"prior = MatrixNormalGamma(column_dim=n_features, row_dim=1, M=M, K=K, alphas=alphas, betas=betas) posterior =",
"likelihood precision posterior param = parameter_posterior.mean() likelihood_known_mean = SingleOutputLinearGaussianWithKnownMean(column_dim=n_features, W=param,",
"SingleOutputLinearGaussianWithKnownPrecision from sds.distributions.lingauss import SingleOutputLinearGaussianWithKnownMean from sds.distributions.gaussian import GaussianWithPrecision from",
"import stats from sklearn.linear_model import ARDRegression, LinearRegression # Parameters of",
"ARDRegression(fit_intercept=False, n_iter=1000) clf.fit(X, y) ols = LinearRegression(fit_intercept=False) ols.fit(X, y) from",
"import MatrixNormalGamma from sds.distributions.lingauss import LinearGaussianWithDiagonalPrecision M = np.zeros((1, n_features))",
"Only keep 10 weights of interest relevant_features = np.random.randint(0, n_features,",
"import LinearGaussianWithDiagonalPrecision M = np.zeros((1, n_features)) K = 1e-16 *",
"of 50. alpha_ = 50. noise = stats.norm.rvs(loc=0, scale=1. /",
"linewidth=2, label=\"Sklearn OLS\") # plt.plot(our_ols.flatten(), color='cyan', linestyle='-', linewidth=2, label=\"Our OLS\")",
"= 50. noise = stats.norm.rvs(loc=0, scale=1. / np.sqrt(alpha_), size=n_samples) #",
"= np.dot(X, w) + noise clf = ARDRegression(fit_intercept=False, n_iter=1000) clf.fit(X,",
"deepcopy(parameter_precision_prior) parameter_posterior = None for i in range(100): # parameter",
"n_features)) K = 1e-16 * np.eye(n_features) alphas = 1e-16 *",
"relevant_features = np.random.randint(0, n_features, 10) for i in relevant_features: w[i]",
"precision alpha of 50. alpha_ = 50. noise = stats.norm.rvs(loc=0,",
"= 100, 100 # Create Gaussian data X = np.random.randn(n_samples,",
"sds.distributions.gaussian import GaussianWithKnownMeanAndDiagonalPrecision from sds.distributions.gamma import Gamma likelihood_precision_prior = Gamma(dim=1,",
"deepcopy(parameter_prior) beta = likelihood_precision_posterior.mean() likelihood_known_precision = SingleOutputLinearGaussianWithKnownPrecision(column_dim=n_features, lmbda=beta, affine=False) stats",
"1e-16 * np.eye(n_features) alphas = 1e-16 * np.ones((1, )) betas",
"stats.norm.rvs(loc=0, scale=1. / np.sqrt(lambda_)) # Create noise with a precision",
"truth\") plt.plot(clf.coef_, color='darkblue', linestyle='-', linewidth=2, label=\"Sklearn ARD\") plt.plot(our_ard, color='red', linestyle='-',",
"* np.eye(n_features) alphas = 1e-16 * np.ones((1, )) betas =",
"stats from sklearn.linear_model import ARDRegression, LinearRegression # Parameters of the",
"alphas = 1e-16 * np.ones((1, )) betas = 1e-16 *",
"= likelihood_precision_prior.nat_param + stats # parameter precision posterior parameter_likelihood =",
"weights of interest relevant_features = np.random.randint(0, n_features, 10) for i",
"deepcopy from sds.distributions.lingauss import SingleOutputLinearGaussianWithKnownPrecision from sds.distributions.lingauss import SingleOutputLinearGaussianWithKnownMean from",
"= GaussianWithPrecision(dim=n_features, mu=np.zeros((n_features, )), lmbda=np.diag(alphas)) parameter_posterior = deepcopy(parameter_prior) beta =",
"w) + noise clf = ARDRegression(fit_intercept=False, n_iter=1000) clf.fit(X, y) ols",
"# plt.plot(ols.coef_, color='yellowgreen', linestyle=':', linewidth=2, label=\"Sklearn OLS\") # plt.plot(our_ols.flatten(), color='cyan',",
"label=\"Sklearn ARD\") plt.plot(our_ard, color='red', linestyle='-', linewidth=2, label=\"Our ARD\") # plt.plot(ols.coef_,",
"the example np.random.seed(0) n_samples, n_features = 100, 100 # Create",
"np.ones((n_features, ))) likelihood_precision_posterior = deepcopy(likelihood_precision_prior) parameter_precision_posterior = deepcopy(parameter_precision_prior) parameter_posterior =",
"likelihood = LinearGaussianWithDiagonalPrecision(column_dim=n_features, row_dim=1, affine=False) stats = likelihood.statistics(X, np.atleast_2d(y).T) posterior.nat_param",
"= LinearRegression(fit_intercept=False) ols.fit(X, y) from copy import deepcopy from sds.distributions.lingauss",
"sds.distributions.lingauss import SingleOutputLinearGaussianWithKnownMean from sds.distributions.gaussian import GaussianWithPrecision from sds.distributions.gaussian import",
"affine=False) stats = likelihood.statistics(X, np.atleast_2d(y).T) posterior.nat_param = prior.nat_param + stats",
"color='cyan', linestyle='-', linewidth=2, label=\"Our OLS\") plt.xlabel(\"Features\") plt.ylabel(\"Values of the weights\")",
"parameter_posterior = None for i in range(100): # parameter posterior",
"# Create noise with a precision alpha of 50. alpha_",
"keep 10 weights of interest relevant_features = np.random.randint(0, n_features, 10)",
"= SingleOutputLinearGaussianWithKnownMean(column_dim=n_features, W=param, affine=False) stats = likelihood_known_mean.statistics(X, y) likelihood_precision_posterior.nat_param =",
"alphas=np.ones((1, )), betas=1e-6 * np.ones((1, ))) parameter_precision_prior = Gamma(dim=n_features, alphas=np.ones((n_features,",
"posterior alphas = parameter_precision_posterior.mean() parameter_prior = GaussianWithPrecision(dim=n_features, mu=np.zeros((n_features, )), lmbda=np.diag(alphas))",
"matplotlib.pyplot as plt from scipy import stats from sklearn.linear_model import",
"Create the target< y = np.dot(X, w) + noise clf",
"alphas=np.ones((n_features, )), betas=1e-6 * np.ones((n_features, ))) likelihood_precision_posterior = deepcopy(likelihood_precision_prior) parameter_precision_posterior",
"# Create weights with a precision lambda_ of 4. lambda_",
"as plt from scipy import stats from sklearn.linear_model import ARDRegression,",
"# Only keep 10 weights of interest relevant_features = np.random.randint(0,",
"a precision lambda_ of 4. lambda_ = 4. w =",
"linestyle=':', linewidth=2, label=\"Sklearn OLS\") # plt.plot(our_ols.flatten(), color='cyan', linestyle='-', linewidth=2, label=\"Our",
"1e-16 * np.ones((1, )) betas = 1e-16 * np.ones((1, ))",
")), betas=1e-6 * np.ones((n_features, ))) likelihood_precision_posterior = deepcopy(likelihood_precision_prior) parameter_precision_posterior =",
"posterior = deepcopy(prior) likelihood = LinearGaussianWithDiagonalPrecision(column_dim=n_features, row_dim=1, affine=False) stats =",
"= deepcopy(likelihood_precision_prior) parameter_precision_posterior = deepcopy(parameter_precision_prior) parameter_posterior = None for i",
"likelihood_precision_posterior.nat_param = likelihood_precision_prior.nat_param + stats # parameter precision posterior parameter_likelihood",
"= stats.norm.rvs(loc=0, scale=1. / np.sqrt(alpha_), size=n_samples) # Create the target<",
"n_samples, n_features = 100, 100 # Create Gaussian data X",
"numpy as np import matplotlib.pyplot as plt from scipy import",
"lambda_ = 4. w = np.zeros(n_features) # Only keep 10",
"* np.ones((1, )) betas = 1e-16 * np.ones((1, )) prior",
"+ stats our_ols = posterior.mode()[0] plt.figure(figsize=(6, 5)) plt.title(\"Weights of the",
"from sklearn.linear_model import ARDRegression, LinearRegression # Parameters of the example",
"sds.distributions.lingauss import LinearGaussianWithDiagonalPrecision M = np.zeros((1, n_features)) K = 1e-16",
"+ noise clf = ARDRegression(fit_intercept=False, n_iter=1000) clf.fit(X, y) ols =",
"= MatrixNormalGamma(column_dim=n_features, row_dim=1, M=M, K=K, alphas=alphas, betas=betas) posterior = deepcopy(prior)",
"Create weights with a precision lambda_ of 4. lambda_ =",
"betas=betas) posterior = deepcopy(prior) likelihood = LinearGaussianWithDiagonalPrecision(column_dim=n_features, row_dim=1, affine=False) stats",
"plt.plot(clf.coef_, color='darkblue', linestyle='-', linewidth=2, label=\"Sklearn ARD\") plt.plot(our_ard, color='red', linestyle='-', linewidth=2,",
"a precision alpha of 50. alpha_ = 50. noise =",
"sds.distributions.lingauss import SingleOutputLinearGaussianWithKnownPrecision from sds.distributions.lingauss import SingleOutputLinearGaussianWithKnownMean from sds.distributions.gaussian import",
"parameter_precision_prior = Gamma(dim=n_features, alphas=np.ones((n_features, )), betas=1e-6 * np.ones((n_features, ))) likelihood_precision_posterior",
"= 1e-16 * np.eye(n_features) alphas = 1e-16 * np.ones((1, ))",
"* np.ones((n_features, ))) likelihood_precision_posterior = deepcopy(likelihood_precision_prior) parameter_precision_posterior = deepcopy(parameter_precision_prior) parameter_posterior",
"parameter_precision_posterior.nat_param = parameter_precision_prior.nat_param + stats our_ard = parameter_posterior.mode() from sds.distributions.composite",
"parameter_precision_posterior.mean() parameter_prior = GaussianWithPrecision(dim=n_features, mu=np.zeros((n_features, )), lmbda=np.diag(alphas)) parameter_posterior = deepcopy(parameter_prior)",
"noise clf = ARDRegression(fit_intercept=False, n_iter=1000) clf.fit(X, y) ols = LinearRegression(fit_intercept=False)",
"* np.ones((1, )) prior = MatrixNormalGamma(column_dim=n_features, row_dim=1, M=M, K=K, alphas=alphas,",
"))) parameter_precision_prior = Gamma(dim=n_features, alphas=np.ones((n_features, )), betas=1e-6 * np.ones((n_features, )))",
"= SingleOutputLinearGaussianWithKnownPrecision(column_dim=n_features, lmbda=beta, affine=False) stats = likelihood_known_precision.statistics(X, y) parameter_posterior.nat_param =",
"= posterior.mode()[0] plt.figure(figsize=(6, 5)) plt.title(\"Weights of the model\") plt.plot(w, color='orange',",
"for i in relevant_features: w[i] = stats.norm.rvs(loc=0, scale=1. / np.sqrt(lambda_))",
"# plt.plot(our_ols.flatten(), color='cyan', linestyle='-', linewidth=2, label=\"Our OLS\") plt.xlabel(\"Features\") plt.ylabel(\"Values of",
"likelihood_precision_posterior.mean() likelihood_known_precision = SingleOutputLinearGaussianWithKnownPrecision(column_dim=n_features, lmbda=beta, affine=False) stats = likelihood_known_precision.statistics(X, y)",
"row_dim=1, M=M, K=K, alphas=alphas, betas=betas) posterior = deepcopy(prior) likelihood =",
"deepcopy(likelihood_precision_prior) parameter_precision_posterior = deepcopy(parameter_precision_prior) parameter_posterior = None for i in",
"affine=False) stats = likelihood_known_mean.statistics(X, y) likelihood_precision_posterior.nat_param = likelihood_precision_prior.nat_param + stats",
"= 1e-16 * np.ones((1, )) prior = MatrixNormalGamma(column_dim=n_features, row_dim=1, M=M,",
"target< y = np.dot(X, w) + noise clf = ARDRegression(fit_intercept=False,",
"stats = likelihood_known_mean.statistics(X, y) likelihood_precision_posterior.nat_param = likelihood_precision_prior.nat_param + stats #",
"= GaussianWithKnownMeanAndDiagonalPrecision(dim=n_features) param = parameter_posterior.mean() stats = parameter_likelihood.statistics(param) parameter_precision_posterior.nat_param =",
"sds.distributions.composite import MatrixNormalGamma from sds.distributions.lingauss import LinearGaussianWithDiagonalPrecision M = np.zeros((1,",
")) prior = MatrixNormalGamma(column_dim=n_features, row_dim=1, M=M, K=K, alphas=alphas, betas=betas) posterior",
"with a precision alpha of 50. alpha_ = 50. noise",
"prior.nat_param + stats our_ols = posterior.mode()[0] plt.figure(figsize=(6, 5)) plt.title(\"Weights of",
"parameter_posterior.mode() from sds.distributions.composite import MatrixNormalGamma from sds.distributions.lingauss import LinearGaussianWithDiagonalPrecision M",
"posterior parameter_likelihood = GaussianWithKnownMeanAndDiagonalPrecision(dim=n_features) param = parameter_posterior.mean() stats = parameter_likelihood.statistics(param)",
"X = np.random.randn(n_samples, n_features) # Create weights with a precision",
"data X = np.random.randn(n_samples, n_features) # Create weights with a",
"with a precision lambda_ of 4. lambda_ = 4. w",
"parameter_posterior.nat_param = parameter_prior.nat_param + stats # likelihood precision posterior param",
"np.ones((1, )) prior = MatrixNormalGamma(column_dim=n_features, row_dim=1, M=M, K=K, alphas=alphas, betas=betas)",
"sklearn.linear_model import ARDRegression, LinearRegression # Parameters of the example np.random.seed(0)",
"likelihood_known_precision.statistics(X, y) parameter_posterior.nat_param = parameter_prior.nat_param + stats # likelihood precision",
"))) likelihood_precision_posterior = deepcopy(likelihood_precision_prior) parameter_precision_posterior = deepcopy(parameter_precision_prior) parameter_posterior = None",
"weights with a precision lambda_ of 4. lambda_ = 4.",
"posterior param = parameter_posterior.mean() likelihood_known_mean = SingleOutputLinearGaussianWithKnownMean(column_dim=n_features, W=param, affine=False) stats",
"y) parameter_posterior.nat_param = parameter_prior.nat_param + stats # likelihood precision posterior",
"= ARDRegression(fit_intercept=False, n_iter=1000) clf.fit(X, y) ols = LinearRegression(fit_intercept=False) ols.fit(X, y)",
"Gaussian data X = np.random.randn(n_samples, n_features) # Create weights with",
"np import matplotlib.pyplot as plt from scipy import stats from",
"plt.title(\"Weights of the model\") plt.plot(w, color='orange', linestyle='-', linewidth=2, label=\"Ground truth\")",
"parameter_posterior.mean() likelihood_known_mean = SingleOutputLinearGaussianWithKnownMean(column_dim=n_features, W=param, affine=False) stats = likelihood_known_mean.statistics(X, y)",
"LinearRegression # Parameters of the example np.random.seed(0) n_samples, n_features =",
"from sds.distributions.gamma import Gamma likelihood_precision_prior = Gamma(dim=1, alphas=np.ones((1, )), betas=1e-6",
"= prior.nat_param + stats our_ols = posterior.mode()[0] plt.figure(figsize=(6, 5)) plt.title(\"Weights",
"plt from scipy import stats from sklearn.linear_model import ARDRegression, LinearRegression",
"K = 1e-16 * np.eye(n_features) alphas = 1e-16 * np.ones((1,",
"= np.random.randint(0, n_features, 10) for i in relevant_features: w[i] =",
"size=n_samples) # Create the target< y = np.dot(X, w) +",
"import SingleOutputLinearGaussianWithKnownPrecision from sds.distributions.lingauss import SingleOutputLinearGaussianWithKnownMean from sds.distributions.gaussian import GaussianWithPrecision",
"precision posterior parameter_likelihood = GaussianWithKnownMeanAndDiagonalPrecision(dim=n_features) param = parameter_posterior.mean() stats =",
"from sds.distributions.gaussian import GaussianWithPrecision from sds.distributions.gaussian import GaussianWithKnownMeanAndDiagonalPrecision from sds.distributions.gamma",
"+ stats our_ard = parameter_posterior.mode() from sds.distributions.composite import MatrixNormalGamma from",
"likelihood_precision_posterior = deepcopy(likelihood_precision_prior) parameter_precision_posterior = deepcopy(parameter_precision_prior) parameter_posterior = None for",
"np.sqrt(lambda_)) # Create noise with a precision alpha of 50.",
")), lmbda=np.diag(alphas)) parameter_posterior = deepcopy(parameter_prior) beta = likelihood_precision_posterior.mean() likelihood_known_precision =",
"i in relevant_features: w[i] = stats.norm.rvs(loc=0, scale=1. / np.sqrt(lambda_)) #",
"import numpy as np import matplotlib.pyplot as plt from scipy",
"deepcopy(prior) likelihood = LinearGaussianWithDiagonalPrecision(column_dim=n_features, row_dim=1, affine=False) stats = likelihood.statistics(X, np.atleast_2d(y).T)",
"OLS\") # plt.plot(our_ols.flatten(), color='cyan', linestyle='-', linewidth=2, label=\"Our OLS\") plt.xlabel(\"Features\") plt.ylabel(\"Values",
"4. w = np.zeros(n_features) # Only keep 10 weights of",
"ARDRegression, LinearRegression # Parameters of the example np.random.seed(0) n_samples, n_features",
"import ARDRegression, LinearRegression # Parameters of the example np.random.seed(0) n_samples,",
"color='darkblue', linestyle='-', linewidth=2, label=\"Sklearn ARD\") plt.plot(our_ard, color='red', linestyle='-', linewidth=2, label=\"Our",
"GaussianWithKnownMeanAndDiagonalPrecision from sds.distributions.gamma import Gamma likelihood_precision_prior = Gamma(dim=1, alphas=np.ones((1, )),",
"M=M, K=K, alphas=alphas, betas=betas) posterior = deepcopy(prior) likelihood = LinearGaussianWithDiagonalPrecision(column_dim=n_features,",
"posterior.mode()[0] plt.figure(figsize=(6, 5)) plt.title(\"Weights of the model\") plt.plot(w, color='orange', linestyle='-',",
"y) likelihood_precision_posterior.nat_param = likelihood_precision_prior.nat_param + stats # parameter precision posterior",
"np.sqrt(alpha_), size=n_samples) # Create the target< y = np.dot(X, w)",
"param = parameter_posterior.mean() stats = parameter_likelihood.statistics(param) parameter_precision_posterior.nat_param = parameter_precision_prior.nat_param +",
"GaussianWithPrecision from sds.distributions.gaussian import GaussianWithKnownMeanAndDiagonalPrecision from sds.distributions.gamma import Gamma likelihood_precision_prior",
"alpha of 50. alpha_ = 50. noise = stats.norm.rvs(loc=0, scale=1.",
"plt.plot(our_ols.flatten(), color='cyan', linestyle='-', linewidth=2, label=\"Our OLS\") plt.xlabel(\"Features\") plt.ylabel(\"Values of the",
"50. alpha_ = 50. noise = stats.norm.rvs(loc=0, scale=1. / np.sqrt(alpha_),",
"precision lambda_ of 4. lambda_ = 4. w = np.zeros(n_features)",
"ols = LinearRegression(fit_intercept=False) ols.fit(X, y) from copy import deepcopy from",
"from scipy import stats from sklearn.linear_model import ARDRegression, LinearRegression #",
"stats our_ard = parameter_posterior.mode() from sds.distributions.composite import MatrixNormalGamma from sds.distributions.lingauss",
"range(100): # parameter posterior alphas = parameter_precision_posterior.mean() parameter_prior = GaussianWithPrecision(dim=n_features,",
"example np.random.seed(0) n_samples, n_features = 100, 100 # Create Gaussian",
"ols.fit(X, y) from copy import deepcopy from sds.distributions.lingauss import SingleOutputLinearGaussianWithKnownPrecision",
"clf = ARDRegression(fit_intercept=False, n_iter=1000) clf.fit(X, y) ols = LinearRegression(fit_intercept=False) ols.fit(X,",
"np.random.seed(0) n_samples, n_features = 100, 100 # Create Gaussian data",
"row_dim=1, affine=False) stats = likelihood.statistics(X, np.atleast_2d(y).T) posterior.nat_param = prior.nat_param +",
"SingleOutputLinearGaussianWithKnownMean from sds.distributions.gaussian import GaussianWithPrecision from sds.distributions.gaussian import GaussianWithKnownMeanAndDiagonalPrecision from",
"color='red', linestyle='-', linewidth=2, label=\"Our ARD\") # plt.plot(ols.coef_, color='yellowgreen', linestyle=':', linewidth=2,",
"of 4. lambda_ = 4. w = np.zeros(n_features) # Only",
"= Gamma(dim=n_features, alphas=np.ones((n_features, )), betas=1e-6 * np.ones((n_features, ))) likelihood_precision_posterior =",
"np.ones((1, )) betas = 1e-16 * np.ones((1, )) prior =",
"alpha_ = 50. noise = stats.norm.rvs(loc=0, scale=1. / np.sqrt(alpha_), size=n_samples)",
"our_ard = parameter_posterior.mode() from sds.distributions.composite import MatrixNormalGamma from sds.distributions.lingauss import",
"M = np.zeros((1, n_features)) K = 1e-16 * np.eye(n_features) alphas",
"stats our_ols = posterior.mode()[0] plt.figure(figsize=(6, 5)) plt.title(\"Weights of the model\")",
"sds.distributions.gaussian import GaussianWithPrecision from sds.distributions.gaussian import GaussianWithKnownMeanAndDiagonalPrecision from sds.distributions.gamma import",
"+ stats # parameter precision posterior parameter_likelihood = GaussianWithKnownMeanAndDiagonalPrecision(dim=n_features) param",
"100 # Create Gaussian data X = np.random.randn(n_samples, n_features) #",
"= 4. w = np.zeros(n_features) # Only keep 10 weights",
"noise = stats.norm.rvs(loc=0, scale=1. / np.sqrt(alpha_), size=n_samples) # Create the",
"stats # parameter precision posterior parameter_likelihood = GaussianWithKnownMeanAndDiagonalPrecision(dim=n_features) param =",
"linestyle='-', linewidth=2, label=\"Ground truth\") plt.plot(clf.coef_, color='darkblue', linestyle='-', linewidth=2, label=\"Sklearn ARD\")",
"plt.plot(w, color='orange', linestyle='-', linewidth=2, label=\"Ground truth\") plt.plot(clf.coef_, color='darkblue', linestyle='-', linewidth=2,",
"= np.zeros(n_features) # Only keep 10 weights of interest relevant_features",
"plt.plot(ols.coef_, color='yellowgreen', linestyle=':', linewidth=2, label=\"Sklearn OLS\") # plt.plot(our_ols.flatten(), color='cyan', linestyle='-',",
"stats = likelihood.statistics(X, np.atleast_2d(y).T) posterior.nat_param = prior.nat_param + stats our_ols",
"Gamma(dim=n_features, alphas=np.ones((n_features, )), betas=1e-6 * np.ones((n_features, ))) likelihood_precision_posterior = deepcopy(likelihood_precision_prior)",
"= likelihood_known_mean.statistics(X, y) likelihood_precision_posterior.nat_param = likelihood_precision_prior.nat_param + stats # parameter",
"= deepcopy(parameter_precision_prior) parameter_posterior = None for i in range(100): #",
"plt.figure(figsize=(6, 5)) plt.title(\"Weights of the model\") plt.plot(w, color='orange', linestyle='-', linewidth=2,",
"from copy import deepcopy from sds.distributions.lingauss import SingleOutputLinearGaussianWithKnownPrecision from sds.distributions.lingauss",
"SingleOutputLinearGaussianWithKnownPrecision(column_dim=n_features, lmbda=beta, affine=False) stats = likelihood_known_precision.statistics(X, y) parameter_posterior.nat_param = parameter_prior.nat_param",
"Parameters of the example np.random.seed(0) n_samples, n_features = 100, 100",
"linewidth=2, label=\"Ground truth\") plt.plot(clf.coef_, color='darkblue', linestyle='-', linewidth=2, label=\"Sklearn ARD\") plt.plot(our_ard,",
")) betas = 1e-16 * np.ones((1, )) prior = MatrixNormalGamma(column_dim=n_features,",
"None for i in range(100): # parameter posterior alphas =",
"# Create Gaussian data X = np.random.randn(n_samples, n_features) # Create",
"of interest relevant_features = np.random.randint(0, n_features, 10) for i in",
"np.dot(X, w) + noise clf = ARDRegression(fit_intercept=False, n_iter=1000) clf.fit(X, y)",
"# parameter posterior alphas = parameter_precision_posterior.mean() parameter_prior = GaussianWithPrecision(dim=n_features, mu=np.zeros((n_features,",
"our_ols = posterior.mode()[0] plt.figure(figsize=(6, 5)) plt.title(\"Weights of the model\") plt.plot(w,",
"in relevant_features: w[i] = stats.norm.rvs(loc=0, scale=1. / np.sqrt(lambda_)) # Create",
"relevant_features: w[i] = stats.norm.rvs(loc=0, scale=1. / np.sqrt(lambda_)) # Create noise",
"noise with a precision alpha of 50. alpha_ = 50.",
"GaussianWithPrecision(dim=n_features, mu=np.zeros((n_features, )), lmbda=np.diag(alphas)) parameter_posterior = deepcopy(parameter_prior) beta = likelihood_precision_posterior.mean()",
"K=K, alphas=alphas, betas=betas) posterior = deepcopy(prior) likelihood = LinearGaussianWithDiagonalPrecision(column_dim=n_features, row_dim=1,",
"Create Gaussian data X = np.random.randn(n_samples, n_features) # Create weights",
"likelihood_known_precision = SingleOutputLinearGaussianWithKnownPrecision(column_dim=n_features, lmbda=beta, affine=False) stats = likelihood_known_precision.statistics(X, y) parameter_posterior.nat_param",
"Gamma likelihood_precision_prior = Gamma(dim=1, alphas=np.ones((1, )), betas=1e-6 * np.ones((1, )))",
"scale=1. / np.sqrt(alpha_), size=n_samples) # Create the target< y =",
"i in range(100): # parameter posterior alphas = parameter_precision_posterior.mean() parameter_prior",
"= likelihood_known_precision.statistics(X, y) parameter_posterior.nat_param = parameter_prior.nat_param + stats # likelihood",
"lambda_ of 4. lambda_ = 4. w = np.zeros(n_features) #",
"stats = likelihood_known_precision.statistics(X, y) parameter_posterior.nat_param = parameter_prior.nat_param + stats #",
"np.zeros((1, n_features)) K = 1e-16 * np.eye(n_features) alphas = 1e-16",
"param = parameter_posterior.mean() likelihood_known_mean = SingleOutputLinearGaussianWithKnownMean(column_dim=n_features, W=param, affine=False) stats =",
"mu=np.zeros((n_features, )), lmbda=np.diag(alphas)) parameter_posterior = deepcopy(parameter_prior) beta = likelihood_precision_posterior.mean() likelihood_known_precision",
"= parameter_precision_prior.nat_param + stats our_ard = parameter_posterior.mode() from sds.distributions.composite import",
"50. noise = stats.norm.rvs(loc=0, scale=1. / np.sqrt(alpha_), size=n_samples) # Create",
"= parameter_likelihood.statistics(param) parameter_precision_posterior.nat_param = parameter_precision_prior.nat_param + stats our_ard = parameter_posterior.mode()",
"plt.plot(our_ard, color='red', linestyle='-', linewidth=2, label=\"Our ARD\") # plt.plot(ols.coef_, color='yellowgreen', linestyle=':',",
"# likelihood precision posterior param = parameter_posterior.mean() likelihood_known_mean = SingleOutputLinearGaussianWithKnownMean(column_dim=n_features,",
"likelihood_precision_prior = Gamma(dim=1, alphas=np.ones((1, )), betas=1e-6 * np.ones((1, ))) parameter_precision_prior",
"linewidth=2, label=\"Sklearn ARD\") plt.plot(our_ard, color='red', linestyle='-', linewidth=2, label=\"Our ARD\") #",
"from sds.distributions.gaussian import GaussianWithKnownMeanAndDiagonalPrecision from sds.distributions.gamma import Gamma likelihood_precision_prior =",
"parameter_likelihood.statistics(param) parameter_precision_posterior.nat_param = parameter_precision_prior.nat_param + stats our_ard = parameter_posterior.mode() from",
"for i in range(100): # parameter posterior alphas = parameter_precision_posterior.mean()"
] |
[
"jobs_when_where(prob, X, S, Cmax) print(\"Schedule: \", sched) sched2 = []",
"g.vertex_properties['runtime'] = g.new_vertex_property(\"float\") for ln in raw: if ln.startswith('v'): _,",
"n_workers = 4 workers = [f'w{i}' for i in range(n_workers)]",
"b] = 0 if a == b else g.vp.output_size[v]/bw #",
"= [] statistics = {} jfile = os.path.join(stats_dir, f'{benchmark}.json') with",
"mcolors import sys import seaborn as sns def get_benchmarks(): benchmarks",
"get_benchmarks() #benchmarks = ['dom4x61GB1B', 'dom2x41GB1B', 'tree4x61GB1B'] for bnch in benchmarks:",
"ss['action'] == 'compute': statistics[ts]['compute_end'] = ss['stop'] statistics[ts]['compute_start'] = ss['start'] statistics[ts]['runtime']",
"not ln: continue ts, color = ln.split(',') #ts += ')'",
"return g def get_runtime_statistics(benchmark): tasks = [] statistics = {}",
"import ast import json from graphviz import Digraph import pandas",
"if ss['action'] == 'compute': statistics[ts]['compute_end'] = ss['stop'] statistics[ts]['compute_start'] = ss['start']",
"defaultdict(lambda:0) for e in g.edges(): P[f't{e.source()}',f't{e.target()}'] = 1 # computation",
"statistics def plot_graph(g, benchmark, optimal=False): print(benchmark[\"benchmark\"]) post = \".optimal\" if",
"C[f't{v}', a, b] = 0 if a == b else",
"as fd: stats = ast.literal_eval(fd.read()) for ts in stats: ops",
"= len(jobs) m = len(agents) P = defaultdict(lambda:0) for e",
"g.new_vertex_property(\"int\") g.vertex_properties['runtime'] = g.new_vertex_property(\"float\") for ln in raw: if ln.startswith('v'):",
"in agents: C[f't{v}', a, b] = 0 if a ==",
"= get_benchmarks() #benchmarks = ['dom4x61GB1B', 'dom2x41GB1B', 'tree4x61GB1B'] for bnch in",
"schedule, jobs_when_where from collections import defaultdict from pulp import value",
"ln in raw: if ln.startswith('e'): _, vsrc, vdst = ln.split(',')",
"import schedule, jobs_when_where from collections import defaultdict from pulp import",
"stats: ops = 'ts'; #ts.replace(\"(\", '').replace(')', '').split(\"'\")[1].split('-')[0] statistics[ts] = {'key':",
"in agents: for b in agents: C[f't{v}', a, b] =",
"# computation D = defaultdict(lambda:0) for v in g.vertices(): for",
"a == b else g.vp.output_size[v]/bw # 0 --> cost_serialization start",
"bnch.rsplit(':', 1) scheduler = 'vanilla' benchmarks[bnch] = {'app': app, 'scheduler':",
"optimal else \"\" dg = Digraph('G', filename=f'{benchmark[\"benchmark\"]}{post}.gv', format='png') for v",
"= defaultdict(lambda:0) for e in g.edges(): P[f't{e.source()}',f't{e.target()}'] = 1 #",
"4 workers = [f'w{i}' for i in range(n_workers)] # Job",
"g.vertices(): for a in agents: D[f't{v}', a] = g.vp.runtime[v] #",
"print(\"Schedule: \", sched) sched2 = [] for j in sched:",
"agents = workers jobs = [] for v in g.vertices():",
"_, vid, name, runtime, output_size = ln.split(',', 4) v =",
"ss['start'] statistics[ts]['runtime'] = ss['stop'] - ss['start'] cfile = os.path.join(stats_dir, f'{benchmark}.colors')",
"#!/usr/bin/python3 import os import json import re import ast import",
"raw: if ln.startswith('e'): _, vsrc, vdst = ln.split(',') g.add_edge(vid_to_vx[vsrc], vid_to_vx[vdst])",
"for j in sched: new = j + (j[1] +",
"cost_serialization start = time.time() # Set up the Mixed Integer",
"if ln.startswith('e'): _, vsrc, vdst = ln.split(',') g.add_edge(vid_to_vx[vsrc], vid_to_vx[vdst]) return",
"S, Cmax) print(\"Schedule: \", sched) sched2 = [] for j",
"cfd: raw = cfd.read().split('\\n') for ln in raw: if not",
"stats[ts]['msg']['nbytes'], 'worker': stats[ts]['worker'].split(':')[1].replace('/', '')} startsstops = stats[ts]['msg']['startstops'] for ss in",
"sched2 = [] for j in sched: new = j",
"print('----------------------------------------------> # of variables', prob.numVariables()) print('---------------------------------------------->', latency) print(\"Makespan: \", value(Cmax))",
"the graph import graph_tool.all as gt import copy import matplotlib.colors",
"= g.add_vertex() vid_to_vx[vid] = v name_to_vid[name] = vid g.vp.name[v] =",
"for ln in raw: if not ln: continue ts, color",
"Integer Linear Program prob, X, S, Cmax = schedule(jobs, agents,",
"in stats: ops = 'ts'; #ts.replace(\"(\", '').replace(')', '').split(\"'\")[1].split('-')[0] statistics[ts] =",
"statistics[ts]['compute_start'] = ss['start'] statistics[ts]['runtime'] = ss['stop'] - ss['start'] cfile =",
"ss in startsstops: if ss['action'] == 'compute': statistics[ts]['compute_end'] = ss['stop']",
"import sys import seaborn as sns def get_benchmarks(): benchmarks =",
"agents: C[f't{v}', a, b] = 0 if a == b",
"g.vp.runtime[v] # statistics[g.vp.name[v]]['runtime'] # Communication Delay matrix - Cost of",
"= float(runtime) # 1 second g.vp.output_size[v] = float(output_size) # 1GB",
"import time def find_optimal(g, bw): n_workers = 4 workers =",
"for e in g.edges(): P[f't{e.source()}',f't{e.target()}'] = 1 # computation D",
"g.new_vertex_property(\"int\") g.vertex_properties['output_size'] = g.new_vertex_property(\"int\") g.vertex_properties['runtime'] = g.new_vertex_property(\"float\") for ln in",
"for b in agents: C[f't{v}', a, b] = 0 if",
"job from # agent to agent #bw = 10*(1<<30)/(1<<3) bw",
"'r') as fd: stats = ast.literal_eval(fd.read()) for ts in stats:",
"if ln.startswith('v'): _, vid, name, runtime, output_size = ln.split(',', 4)",
"v = g.add_vertex() vid_to_vx[vid] = v name_to_vid[name] = vid g.vp.name[v]",
"bnch in benchmarks: for bw in [1*1024, 16*1024, 512, 32*1024,",
"= ss['start'] statistics[ts]['runtime'] = ss['stop'] - ss['start'] cfile = os.path.join(stats_dir,",
"\"vanilla\": # dg.node(f'{v}') #else: dg.node(f'{v}, color({g.vp.icolor[v]})') for e in g.edges():",
"for ss in startsstops: if ss['action'] == 'compute': statistics[ts]['compute_end'] =",
"'benchmark': bnch} except AssertionError: pass return benchmarks def build_graph(benchmark): css_colors",
"filename=f'{benchmark[\"benchmark\"]}{post}.gv', format='png') for v in g.vertices(): dg.attr('node', shape='ellipse', style=\"filled,solid\", penwidth=\"3\",",
"\"\" dg = Digraph('G', filename=f'{benchmark[\"benchmark\"]}{post}.gv', format='png') for v in g.vertices():",
"= [] for v in g.vertices(): jobs.append(f't{v}') n = len(jobs)",
"ln in raw: if ln.startswith('v'): _, vid, name, runtime, output_size",
"g.edges(): P[f't{e.source()}',f't{e.target()}'] = 1 # computation D = defaultdict(lambda:0) for",
"''))]) sched2.append(new) print(\"Schedule: \", sched2) return sched2, {'makespan': value(Cmax), 'constraints':",
"dg = Digraph('G', filename=f'{benchmark[\"benchmark\"]}{post}.gv', format='png') for v in g.vertices(): dg.attr('node',",
"g.vp.runtime[v] = float(runtime) # 1 second g.vp.output_size[v] = float(output_size) #",
"Digraph('G', filename=f'{benchmark[\"benchmark\"]}{post}.gv', format='png') for v in g.vertices(): dg.attr('node', shape='ellipse', style=\"filled,solid\",",
"open(f'{results_dir}/optimal_compuation_stats.csv', 'a') as fd: fd.write(f'{bnch},{stats[\"makespan\"]},{stats[\"constraints\"]},{stats[\"variables\"]},{stats[\"time\"]},no,{bw}\\n') with open(f'{results_dir}/{bnch}.nonetworkcontention.{bw}mbps.optimal', 'w') as fd:",
"for a in agents: for b in agents: C[f't{v}', a,",
"+ (j[1] + D[j[0], j[2]], g.vp.name[int(j[0].replace('t', ''))]) sched2.append(new) print(\"Schedule: \",",
"to agent #bw = 10*(1<<30)/(1<<3) bw = bw*(1<<20)/(1<<3) C =",
"benchmarks = get_benchmarks() #benchmarks = ['dom4x61GB1B', 'dom2x41GB1B', 'tree4x61GB1B'] for bnch",
"agent to agent #bw = 10*(1<<30)/(1<<3) bw = bw*(1<<20)/(1<<3) C",
"open(jfile, 'r') as fd: stats = ast.literal_eval(fd.read()) for ts in",
"= vid g.vp.name[v] = name g.vp.runtime[v] = float(runtime) # 1",
"R, B, P, M) solver = pl.GUROBI_CMD() prob.solve(solver) latency =",
"start print('-----------------------------------------------> constraints', len(prob.constraints.keys())) print('----------------------------------------------> # of variables', prob.numVariables()) print('---------------------------------------------->',",
"new = j + (j[1] + D[j[0], j[2]], g.vp.name[int(j[0].replace('t', ''))])",
"'')} startsstops = stats[ts]['msg']['startstops'] for ss in startsstops: if ss['action']",
"f'{e.target()}') #else: dg.edge(f'{e.source()}, color({g.vp.icolor[e.source()]})', f'{e.target()}, color({g.vp.icolor[e.target()]})') dg.view(os.path.join(f'{results_dir}',f'{benchmark[\"benchmark\"]}{post}'), quiet=False) import pulp",
"= ln.split(',') #ts += ')' statistics[ts]['color'] = int(color) return statistics",
"stats = find_optimal(g, bw) with open(f'{results_dir}/optimal_compuation_stats.csv', 'a') as fd: fd.write(f'{bnch},{stats[\"makespan\"]},{stats[\"constraints\"]},{stats[\"variables\"]},{stats[\"time\"]},no,{bw}\\n')",
"as pl import time def find_optimal(g, bw): n_workers = 4",
"benchmark, optimal=False): print(benchmark[\"benchmark\"]) post = \".optimal\" if optimal else \"\"",
"import copy import matplotlib.colors as mcolors import sys import seaborn",
"value import re import ast import json from graphviz import",
"def build_graph(benchmark): css_colors = list(mcolors.CSS4_COLORS.keys()) gfile = os.path.join(stats_dir, f'{benchmark}.iopt') with",
"= defaultdict(lambda:0) for v in g.vertices(): for a in agents:",
"print(benchmark[\"benchmark\"]) post = \".optimal\" if optimal else \"\" dg =",
"mcolors import sys import utils from tompkins.ilp import schedule, jobs_when_where",
"import graph_tool.all as gt import copy import matplotlib.colors as mcolors",
"'#e0e0e0' for ln in raw: if ln.startswith('e'): _, vsrc, vdst",
"= ss['stop'] - ss['start'] cfile = os.path.join(stats_dir, f'{benchmark}.colors') with open(cfile,",
"# dg.edge(f'{e.source()}', f'{e.target()}') #else: dg.edge(f'{e.source()}, color({g.vp.icolor[e.source()]})', f'{e.target()}, color({g.vp.icolor[e.target()]})') dg.view(os.path.join(f'{results_dir}',f'{benchmark[\"benchmark\"]}{post}'), quiet=False)",
"# Job Release Times - Additional constraints on availablility of",
"agents, D, C, R, B, P, M) solver = pl.GUROBI_CMD()",
"= os.path.join(stats_dir, f'{benchmark}.iopt') with open(gfile, 'r') as fd: raw =",
"e in g.edges(): #if benchmark['scheduler'] == \"vanilla\": # dg.edge(f'{e.source()}', f'{e.target()}')",
"as cfd: raw = cfd.read().split('\\n') for ln in raw: if",
"Delay matrix - Cost of sending results of job from",
"'scheduler': scheduler, 'benchmark': bnch} except AssertionError: pass return benchmarks def",
"f'{benchmark}.iopt') with open(gfile, 'r') as fd: raw = fd.read().split('\\n') g",
"# 1GB g.vp.color[v] = '#e0e0e0' for ln in raw: if",
"# Maximum makespan M = 100 B = defaultdict(lambda:1) agents",
"'op': ops, 'output_size': stats[ts]['msg']['nbytes'], 'worker': stats[ts]['worker'].split(':')[1].replace('/', '')} startsstops = stats[ts]['msg']['startstops']",
"a, b] = 0 if a == b else g.vp.output_size[v]/bw",
"time.time() - start print('-----------------------------------------------> constraints', len(prob.constraints.keys())) print('----------------------------------------------> # of variables',",
"sched2, {'makespan': value(Cmax), 'constraints': len(prob.constraints.keys()), 'variables': prob.numVariables(), 'time': float(latency)} results_dir",
"== \"vanilla\": # dg.node(f'{v}') #else: dg.node(f'{v}, color({g.vp.icolor[v]})') for e in",
"4) v = g.add_vertex() vid_to_vx[vid] = v name_to_vid[name] = vid",
"ln.split(',') g.add_edge(vid_to_vx[vsrc], vid_to_vx[vdst]) return g def get_runtime_statistics(benchmark): tasks = []",
"#if benchmark['scheduler'] == \"vanilla\": # dg.node(f'{v}') #else: dg.node(f'{v}, color({g.vp.icolor[v]})') for",
"- start print('-----------------------------------------------> constraints', len(prob.constraints.keys())) print('----------------------------------------------> # of variables', prob.numVariables())",
"name g.vp.runtime[v] = float(runtime) # 1 second g.vp.output_size[v] = float(output_size)",
"bw): n_workers = 4 workers = [f'w{i}' for i in",
"'constraints': len(prob.constraints.keys()), 'variables': prob.numVariables(), 'time': float(latency)} results_dir = './benchmarks' stats_dir='./benchmarks'",
"as fd: for s in sched2: fd.write(f'v,{s[0]},{s[1]},{s[2]}\\n') #fd.write(f'{s[4]},{s[3]},{s[0]},{s[1]},{s[2]}\\n') #v =",
"css_colors = list(mcolors.CSS4_COLORS.keys()) gfile = os.path.join(stats_dir, f'{benchmark}.iopt') with open(gfile, 'r')",
"as fd: fd.write(f'{bnch},{stats[\"makespan\"]},{stats[\"constraints\"]},{stats[\"variables\"]},{stats[\"time\"]},no,{bw}\\n') with open(f'{results_dir}/{bnch}.nonetworkcontention.{bw}mbps.optimal', 'w') as fd: for s",
"else g.vp.output_size[v]/bw # 0 --> cost_serialization start = time.time() #",
"build_graph(bnch) sched2, stats = find_optimal(g, bw) with open(f'{results_dir}/optimal_compuation_stats.csv', 'a') as",
"statistics[ts]['color'] = int(color) return statistics def plot_graph(g, benchmark, optimal=False): print(benchmark[\"benchmark\"])",
"j + (j[1] + D[j[0], j[2]], g.vp.name[int(j[0].replace('t', ''))]) sched2.append(new) print(\"Schedule:",
"get_benchmarks(): benchmarks = {} for _file in os.listdir(stats_dir): try: bnch",
"- ss['start'] cfile = os.path.join(stats_dir, f'{benchmark}.colors') with open(cfile, 'r') as",
"fillcolor=g.vp.color[v], color=worker_color[g.vp.statistics[v]['worker']]) #if benchmark['scheduler'] == \"vanilla\": # dg.node(f'{v}') #else: dg.node(f'{v},",
"prob.numVariables(), 'time': float(latency)} results_dir = './benchmarks' stats_dir='./benchmarks' benchmarks = get_benchmarks()",
"import value import re import ast import json from graphviz",
"len(jobs) m = len(agents) P = defaultdict(lambda:0) for e in",
"2*1024, 256, 128, 64, 32]: print(f'process {bnch}') g = build_graph(bnch)",
"g.add_edge(vid_to_vx[vsrc], vid_to_vx[vdst]) return g def get_runtime_statistics(benchmark): tasks = [] statistics",
"0 --> cost_serialization start = time.time() # Set up the",
"for v in g.vertices(): dg.attr('node', shape='ellipse', style=\"filled,solid\", penwidth=\"3\", fillcolor=g.vp.color[v], color=worker_color[g.vp.statistics[v]['worker']])",
"= 100 B = defaultdict(lambda:1) agents = workers jobs =",
"except AssertionError: pass return benchmarks def build_graph(benchmark): css_colors = list(mcolors.CSS4_COLORS.keys())",
"= \".optimal\" if optimal else \"\" dg = Digraph('G', filename=f'{benchmark[\"benchmark\"]}{post}.gv',",
"import json import re import ast import json from graphviz",
"= g.new_vertex_property(\"string\", '#e0e0e0') g.vertex_properties['icolor'] = g.new_vertex_property(\"int\") g.vertex_properties['output_size'] = g.new_vertex_property(\"int\") g.vertex_properties['runtime']",
"latency) print(\"Makespan: \", value(Cmax)) sched = jobs_when_where(prob, X, S, Cmax)",
"'a') as fd: fd.write(f'{bnch},{stats[\"makespan\"]},{stats[\"constraints\"]},{stats[\"variables\"]},{stats[\"time\"]},no,{bw}\\n') with open(f'{results_dir}/{bnch}.nonetworkcontention.{bw}mbps.optimal', 'w') as fd: for",
"'w') as fd: for s in sched2: fd.write(f'v,{s[0]},{s[1]},{s[2]}\\n') #fd.write(f'{s[4]},{s[3]},{s[0]},{s[1]},{s[2]}\\n') #v",
"as mcolors import sys import seaborn as sns def get_benchmarks():",
"in g.vertices(): dg.attr('node', shape='ellipse', style=\"filled,solid\", penwidth=\"3\", fillcolor=g.vp.color[v], color=worker_color[g.vp.statistics[v]['worker']]) #if benchmark['scheduler']",
"D, C, R, B, P, M) solver = pl.GUROBI_CMD() prob.solve(solver)",
"= Digraph('G', filename=f'{benchmark[\"benchmark\"]}{post}.gv', format='png') for v in g.vertices(): dg.attr('node', shape='ellipse',",
"pulp import value import re import ast import json from",
"f'{benchmark}.colors') with open(cfile, 'r') as cfd: raw = cfd.read().split('\\n') for",
"defaultdict(lambda:0) for v in g.vertices(): for a in agents: D[f't{v}',",
"sched = jobs_when_where(prob, X, S, Cmax) print(\"Schedule: \", sched) sched2",
"== b else g.vp.output_size[v]/bw # 0 --> cost_serialization start =",
"workers = [f'w{i}' for i in range(n_workers)] # Job Release",
"cfd.read().split('\\n') for ln in raw: if not ln: continue ts,",
"import Digraph import pandas as pd # color the graph",
"makespan M = 100 B = defaultdict(lambda:1) agents = workers",
"stats[ts]['msg']['startstops'] for ss in startsstops: if ss['action'] == 'compute': statistics[ts]['compute_end']",
"shape='ellipse', style=\"filled,solid\", penwidth=\"3\", fillcolor=g.vp.color[v], color=worker_color[g.vp.statistics[v]['worker']]) #if benchmark['scheduler'] == \"vanilla\": #",
"32]: print(f'process {bnch}') g = build_graph(bnch) sched2, stats = find_optimal(g,",
"#fd.write(f'{s[4]},{s[3]},{s[0]},{s[1]},{s[2]}\\n') #v = int(s[0].replace('t', '')) #g.vp.worker[v] = s[2] break #break",
"in raw: if ln.startswith('e'): _, vsrc, vdst = ln.split(',') g.add_edge(vid_to_vx[vsrc],",
"g.vp.output_size[v]/bw # 0 --> cost_serialization start = time.time() # Set",
"availablility of Jobs # R = np.zeros(n) R = defaultdict(lambda:0)",
"json import re import ast import json from graphviz import",
"return benchmarks def build_graph(benchmark): css_colors = list(mcolors.CSS4_COLORS.keys()) gfile = os.path.join(stats_dir,",
"plot_graph(g, benchmark, optimal=False): print(benchmark[\"benchmark\"]) post = \".optimal\" if optimal else",
"as fd: raw = fd.read().split('\\n') g = gt.Graph(directed=True) vid_to_vx =",
"matrix - Cost of sending results of job from #",
"app = bnch #, scheduler = bnch.rsplit(':', 1) scheduler =",
"in agents: D[f't{v}', a] = g.vp.runtime[v] # statistics[g.vp.name[v]]['runtime'] # Communication",
"'').replace(')', '').split(\"'\")[1].split('-')[0] statistics[ts] = {'key': ts, 'op': ops, 'output_size': stats[ts]['msg']['nbytes'],",
"= ast.literal_eval(fd.read()) for ts in stats: ops = 'ts'; #ts.replace(\"(\",",
"color = ln.split(',') #ts += ')' statistics[ts]['color'] = int(color) return",
"in g.edges(): #if benchmark['scheduler'] == \"vanilla\": # dg.edge(f'{e.source()}', f'{e.target()}') #else:",
"workers jobs = [] for v in g.vertices(): jobs.append(f't{v}') n",
"format='png') for v in g.vertices(): dg.attr('node', shape='ellipse', style=\"filled,solid\", penwidth=\"3\", fillcolor=g.vp.color[v],",
"prob.numVariables()) print('---------------------------------------------->', latency) print(\"Makespan: \", value(Cmax)) sched = jobs_when_where(prob, X,",
"g.new_vertex_property(\"float\") for ln in raw: if ln.startswith('v'): _, vid, name,",
"\".optimal\" if optimal else \"\" dg = Digraph('G', filename=f'{benchmark[\"benchmark\"]}{post}.gv', format='png')",
"vid_to_vx[vid] = v name_to_vid[name] = vid g.vp.name[v] = name g.vp.runtime[v]",
"P = defaultdict(lambda:0) for e in g.edges(): P[f't{e.source()}',f't{e.target()}'] = 1",
"= fd.read().split('\\n') g = gt.Graph(directed=True) vid_to_vx = {} name_to_vid =",
"= {} name_to_vid = {} g.vertex_properties['name'] = g.new_vertex_property(\"string\") g.vertex_properties['worker'] =",
"def get_runtime_statistics(benchmark): tasks = [] statistics = {} jfile =",
"benchmark['scheduler'] == \"vanilla\": # dg.edge(f'{e.source()}', f'{e.target()}') #else: dg.edge(f'{e.source()}, color({g.vp.icolor[e.source()]})', f'{e.target()},",
"seaborn as sns def get_benchmarks(): benchmarks = {} for _file",
"prob.solve(solver) latency = time.time() - start print('-----------------------------------------------> constraints', len(prob.constraints.keys())) print('---------------------------------------------->",
"bw in [1*1024, 16*1024, 512, 32*1024, 8*1024, 4*1024, 2*1024, 256,",
"Communication Delay matrix - Cost of sending results of job",
"in benchmarks: for bw in [1*1024, 16*1024, 512, 32*1024, 8*1024,",
"dg.edge(f'{e.source()}, color({g.vp.icolor[e.source()]})', f'{e.target()}, color({g.vp.icolor[e.target()]})') dg.view(os.path.join(f'{results_dir}',f'{benchmark[\"benchmark\"]}{post}'), quiet=False) import pulp as pl",
"= build_graph(bnch) sched2, stats = find_optimal(g, bw) with open(f'{results_dir}/optimal_compuation_stats.csv', 'a')",
"color({g.vp.icolor[e.source()]})', f'{e.target()}, color({g.vp.icolor[e.target()]})') dg.view(os.path.join(f'{results_dir}',f'{benchmark[\"benchmark\"]}{post}'), quiet=False) import pulp as pl import",
"color({g.vp.icolor[e.target()]})') dg.view(os.path.join(f'{results_dir}',f'{benchmark[\"benchmark\"]}{post}'), quiet=False) import pulp as pl import time def",
"for bw in [1*1024, 16*1024, 512, 32*1024, 8*1024, 4*1024, 2*1024,",
"# R = np.zeros(n) R = defaultdict(lambda:0) # Maximum makespan",
"open(cfile, 'r') as cfd: raw = cfd.read().split('\\n') for ln in",
"with open(f'{results_dir}/{bnch}.nonetworkcontention.{bw}mbps.optimal', 'w') as fd: for s in sched2: fd.write(f'v,{s[0]},{s[1]},{s[2]}\\n')",
"statistics[ts]['compute_end'] = ss['stop'] statistics[ts]['compute_start'] = ss['start'] statistics[ts]['runtime'] = ss['stop'] -",
"= bnch.rsplit(':', 1) scheduler = 'vanilla' benchmarks[bnch] = {'app': app,",
"defaultdict(lambda:0) # Maximum makespan M = 100 B = defaultdict(lambda:1)",
"f'{bnch}.iopt')) app = bnch #, scheduler = bnch.rsplit(':', 1) scheduler",
"benchmarks[bnch] = {'app': app, 'scheduler': scheduler, 'benchmark': bnch} except AssertionError:",
"ss['start'] cfile = os.path.join(stats_dir, f'{benchmark}.colors') with open(cfile, 'r') as cfd:",
"defaultdict(lambda:1) agents = workers jobs = [] for v in",
"= os.path.join(stats_dir, f'{benchmark}.colors') with open(cfile, 'r') as cfd: raw =",
"ts, 'op': ops, 'output_size': stats[ts]['msg']['nbytes'], 'worker': stats[ts]['worker'].split(':')[1].replace('/', '')} startsstops =",
"= len(agents) P = defaultdict(lambda:0) for e in g.edges(): P[f't{e.source()}',f't{e.target()}']",
"D[f't{v}', a] = g.vp.runtime[v] # statistics[g.vp.name[v]]['runtime'] # Communication Delay matrix",
"sys import seaborn as sns def get_benchmarks(): benchmarks = {}",
"Release Times - Additional constraints on availablility of Jobs #",
"as sns def get_benchmarks(): benchmarks = {} for _file in",
"len(prob.constraints.keys())) print('----------------------------------------------> # of variables', prob.numVariables()) print('---------------------------------------------->', latency) print(\"Makespan: \",",
"import os import json import re import ast import json",
"'r') as cfd: raw = cfd.read().split('\\n') for ln in raw:",
"# color the graph import graph_tool.all as gt import copy",
"= name g.vp.runtime[v] = float(runtime) # 1 second g.vp.output_size[v] =",
"build_graph(benchmark): css_colors = list(mcolors.CSS4_COLORS.keys()) gfile = os.path.join(stats_dir, f'{benchmark}.iopt') with open(gfile,",
"P, M) solver = pl.GUROBI_CMD() prob.solve(solver) latency = time.time() -",
"float(latency)} results_dir = './benchmarks' stats_dir='./benchmarks' benchmarks = get_benchmarks() #benchmarks =",
"utils from tompkins.ilp import schedule, jobs_when_where from collections import defaultdict",
"name, runtime, output_size = ln.split(',', 4) v = g.add_vertex() vid_to_vx[vid]",
"constraints', len(prob.constraints.keys())) print('----------------------------------------------> # of variables', prob.numVariables()) print('---------------------------------------------->', latency) print(\"Makespan:",
"agent #bw = 10*(1<<30)/(1<<3) bw = bw*(1<<20)/(1<<3) C = defaultdict(lambda:0)",
"# agent to agent #bw = 10*(1<<30)/(1<<3) bw = bw*(1<<20)/(1<<3)",
"pandas as pd # color the graph import graph_tool.all as",
"g.vertices(): jobs.append(f't{v}') n = len(jobs) m = len(agents) P =",
"[f'w{i}' for i in range(n_workers)] # Job Release Times -",
"g.vertices(): for a in agents: for b in agents: C[f't{v}',",
"= {} g.vertex_properties['name'] = g.new_vertex_property(\"string\") g.vertex_properties['worker'] = g.new_vertex_property(\"string\") g.vertex_properties['color'] =",
"= g.new_vertex_property(\"string\") g.vertex_properties['color'] = g.new_vertex_property(\"string\", '#e0e0e0') g.vertex_properties['icolor'] = g.new_vertex_property(\"int\") g.vertex_properties['output_size']",
"float(runtime) # 1 second g.vp.output_size[v] = float(output_size) # 1GB g.vp.color[v]",
"'output_size': stats[ts]['msg']['nbytes'], 'worker': stats[ts]['worker'].split(':')[1].replace('/', '')} startsstops = stats[ts]['msg']['startstops'] for ss",
"from collections import defaultdict from pulp import value import re",
"'#e0e0e0') g.vertex_properties['icolor'] = g.new_vertex_property(\"int\") g.vertex_properties['output_size'] = g.new_vertex_property(\"int\") g.vertex_properties['runtime'] = g.new_vertex_property(\"float\")",
"stats[ts]['worker'].split(':')[1].replace('/', '')} startsstops = stats[ts]['msg']['startstops'] for ss in startsstops: if",
"runtime, output_size = ln.split(',', 4) v = g.add_vertex() vid_to_vx[vid] =",
"fd: fd.write(f'{bnch},{stats[\"makespan\"]},{stats[\"constraints\"]},{stats[\"variables\"]},{stats[\"time\"]},no,{bw}\\n') with open(f'{results_dir}/{bnch}.nonetworkcontention.{bw}mbps.optimal', 'w') as fd: for s in",
"AssertionError: pass return benchmarks def build_graph(benchmark): css_colors = list(mcolors.CSS4_COLORS.keys()) gfile",
"float(output_size) # 1GB g.vp.color[v] = '#e0e0e0' for ln in raw:",
"= pl.GUROBI_CMD() prob.solve(solver) latency = time.time() - start print('-----------------------------------------------> constraints',",
"stats_dir='./benchmarks' benchmarks = get_benchmarks() #benchmarks = ['dom4x61GB1B', 'dom2x41GB1B', 'tree4x61GB1B'] for",
"g.vertex_properties['worker'] = g.new_vertex_property(\"string\") g.vertex_properties['color'] = g.new_vertex_property(\"string\", '#e0e0e0') g.vertex_properties['icolor'] = g.new_vertex_property(\"int\")",
"\", sched2) return sched2, {'makespan': value(Cmax), 'constraints': len(prob.constraints.keys()), 'variables': prob.numVariables(),",
"b else g.vp.output_size[v]/bw # 0 --> cost_serialization start = time.time()",
"with open(f'{results_dir}/optimal_compuation_stats.csv', 'a') as fd: fd.write(f'{bnch},{stats[\"makespan\"]},{stats[\"constraints\"]},{stats[\"variables\"]},{stats[\"time\"]},no,{bw}\\n') with open(f'{results_dir}/{bnch}.nonetworkcontention.{bw}mbps.optimal', 'w') as",
"bnch} except AssertionError: pass return benchmarks def build_graph(benchmark): css_colors =",
"= find_optimal(g, bw) with open(f'{results_dir}/optimal_compuation_stats.csv', 'a') as fd: fd.write(f'{bnch},{stats[\"makespan\"]},{stats[\"constraints\"]},{stats[\"variables\"]},{stats[\"time\"]},no,{bw}\\n') with",
"# 1 second g.vp.output_size[v] = float(output_size) # 1GB g.vp.color[v] =",
"for ln in raw: if ln.startswith('e'): _, vsrc, vdst =",
"= schedule(jobs, agents, D, C, R, B, P, M) solver",
"Jobs # R = np.zeros(n) R = defaultdict(lambda:0) # Maximum",
"in g.vertices(): for a in agents: for b in agents:",
"import pandas as pd # color the graph import graph_tool.all",
"for bnch in benchmarks: for bw in [1*1024, 16*1024, 512,",
"results of job from # agent to agent #bw =",
"raw = cfd.read().split('\\n') for ln in raw: if not ln:",
"= ['dom4x61GB1B', 'dom2x41GB1B', 'tree4x61GB1B'] for bnch in benchmarks: for bw",
"style=\"filled,solid\", penwidth=\"3\", fillcolor=g.vp.color[v], color=worker_color[g.vp.statistics[v]['worker']]) #if benchmark['scheduler'] == \"vanilla\": # dg.node(f'{v}')",
"tasks = [] statistics = {} jfile = os.path.join(stats_dir, f'{benchmark}.json')",
"g.vertex_properties['name'] = g.new_vertex_property(\"string\") g.vertex_properties['worker'] = g.new_vertex_property(\"string\") g.vertex_properties['color'] = g.new_vertex_property(\"string\", '#e0e0e0')",
"name_to_vid = {} g.vertex_properties['name'] = g.new_vertex_property(\"string\") g.vertex_properties['worker'] = g.new_vertex_property(\"string\") g.vertex_properties['color']",
"in g.vertices(): for a in agents: D[f't{v}', a] = g.vp.runtime[v]",
"'compute': statistics[ts]['compute_end'] = ss['stop'] statistics[ts]['compute_start'] = ss['start'] statistics[ts]['runtime'] = ss['stop']",
"'r') as fd: raw = fd.read().split('\\n') g = gt.Graph(directed=True) vid_to_vx",
"os import json import re import ast import json from",
"np.zeros(n) R = defaultdict(lambda:0) # Maximum makespan M = 100",
"pass return benchmarks def build_graph(benchmark): css_colors = list(mcolors.CSS4_COLORS.keys()) gfile =",
"bw) with open(f'{results_dir}/optimal_compuation_stats.csv', 'a') as fd: fd.write(f'{bnch},{stats[\"makespan\"]},{stats[\"constraints\"]},{stats[\"variables\"]},{stats[\"time\"]},no,{bw}\\n') with open(f'{results_dir}/{bnch}.nonetworkcontention.{bw}mbps.optimal', 'w')",
"1) scheduler = 'vanilla' benchmarks[bnch] = {'app': app, 'scheduler': scheduler,",
"'ts'; #ts.replace(\"(\", '').replace(')', '').split(\"'\")[1].split('-')[0] statistics[ts] = {'key': ts, 'op': ops,",
"ts, color = ln.split(',') #ts += ')' statistics[ts]['color'] = int(color)",
"')' statistics[ts]['color'] = int(color) return statistics def plot_graph(g, benchmark, optimal=False):",
"= g.new_vertex_property(\"float\") for ln in raw: if ln.startswith('v'): _, vid,",
"in raw: if ln.startswith('v'): _, vid, name, runtime, output_size =",
"= 1 # computation D = defaultdict(lambda:0) for v in",
"import json from graphviz import Digraph import pandas as pd",
"= workers jobs = [] for v in g.vertices(): jobs.append(f't{v}')",
"{'makespan': value(Cmax), 'constraints': len(prob.constraints.keys()), 'variables': prob.numVariables(), 'time': float(latency)} results_dir =",
"64, 32]: print(f'process {bnch}') g = build_graph(bnch) sched2, stats =",
"--> cost_serialization start = time.time() # Set up the Mixed",
"benchmarks = {} for _file in os.listdir(stats_dir): try: bnch =",
"32*1024, 8*1024, 4*1024, 2*1024, 256, 128, 64, 32]: print(f'process {bnch}')",
"g.edges(): #if benchmark['scheduler'] == \"vanilla\": # dg.edge(f'{e.source()}', f'{e.target()}') #else: dg.edge(f'{e.source()},",
"with open(cfile, 'r') as cfd: raw = cfd.read().split('\\n') for ln",
"time def find_optimal(g, bw): n_workers = 4 workers = [f'w{i}'",
"v in g.vertices(): for a in agents: D[f't{v}', a] =",
"fd: raw = fd.read().split('\\n') g = gt.Graph(directed=True) vid_to_vx = {}",
"= {'app': app, 'scheduler': scheduler, 'benchmark': bnch} except AssertionError: pass",
"start = time.time() # Set up the Mixed Integer Linear",
"\", value(Cmax)) sched = jobs_when_where(prob, X, S, Cmax) print(\"Schedule: \",",
"of job from # agent to agent #bw = 10*(1<<30)/(1<<3)",
"jobs = [] for v in g.vertices(): jobs.append(f't{v}') n =",
"'./benchmarks' stats_dir='./benchmarks' benchmarks = get_benchmarks() #benchmarks = ['dom4x61GB1B', 'dom2x41GB1B', 'tree4x61GB1B']",
"variables', prob.numVariables()) print('---------------------------------------------->', latency) print(\"Makespan: \", value(Cmax)) sched = jobs_when_where(prob,",
"as gt import copy import matplotlib.colors as mcolors import sys",
"value(Cmax), 'constraints': len(prob.constraints.keys()), 'variables': prob.numVariables(), 'time': float(latency)} results_dir = './benchmarks'",
"'tree4x61GB1B'] for bnch in benchmarks: for bw in [1*1024, 16*1024,",
"print(\"Schedule: \", sched2) return sched2, {'makespan': value(Cmax), 'constraints': len(prob.constraints.keys()), 'variables':",
"= gt.Graph(directed=True) vid_to_vx = {} name_to_vid = {} g.vertex_properties['name'] =",
"_file in os.listdir(stats_dir): try: bnch = _file.rsplit('.', 1)[0] assert os.path.isfile(os.path.join(stats_dir,",
"import defaultdict from pulp import value import re import ast",
"with open(jfile, 'r') as fd: stats = ast.literal_eval(fd.read()) for ts",
"sched) sched2 = [] for j in sched: new =",
"else \"\" dg = Digraph('G', filename=f'{benchmark[\"benchmark\"]}{post}.gv', format='png') for v in",
"vid g.vp.name[v] = name g.vp.runtime[v] = float(runtime) # 1 second",
"Set up the Mixed Integer Linear Program prob, X, S,",
"128, 64, 32]: print(f'process {bnch}') g = build_graph(bnch) sched2, stats",
"= g.new_vertex_property(\"string\") g.vertex_properties['worker'] = g.new_vertex_property(\"string\") g.vertex_properties['color'] = g.new_vertex_property(\"string\", '#e0e0e0') g.vertex_properties['icolor']",
"'').split(\"'\")[1].split('-')[0] statistics[ts] = {'key': ts, 'op': ops, 'output_size': stats[ts]['msg']['nbytes'], 'worker':",
"b in agents: C[f't{v}', a, b] = 0 if a",
"g = gt.Graph(directed=True) vid_to_vx = {} name_to_vid = {} g.vertex_properties['name']",
"ln: continue ts, color = ln.split(',') #ts += ')' statistics[ts]['color']",
"len(prob.constraints.keys()), 'variables': prob.numVariables(), 'time': float(latency)} results_dir = './benchmarks' stats_dir='./benchmarks' benchmarks",
"color the graph import graph_tool.all as gt import copy import",
"as mcolors import sys import utils from tompkins.ilp import schedule,",
"try: bnch = _file.rsplit('.', 1)[0] assert os.path.isfile(os.path.join(stats_dir, f'{bnch}.iopt')) app =",
"return sched2, {'makespan': value(Cmax), 'constraints': len(prob.constraints.keys()), 'variables': prob.numVariables(), 'time': float(latency)}",
"= 'vanilla' benchmarks[bnch] = {'app': app, 'scheduler': scheduler, 'benchmark': bnch}",
"of variables', prob.numVariables()) print('---------------------------------------------->', latency) print(\"Makespan: \", value(Cmax)) sched =",
"continue ts, color = ln.split(',') #ts += ')' statistics[ts]['color'] =",
"- Additional constraints on availablility of Jobs # R =",
"1)[0] assert os.path.isfile(os.path.join(stats_dir, f'{bnch}.iopt')) app = bnch #, scheduler =",
"in g.vertices(): jobs.append(f't{v}') n = len(jobs) m = len(agents) P",
"= 'ts'; #ts.replace(\"(\", '').replace(')', '').split(\"'\")[1].split('-')[0] statistics[ts] = {'key': ts, 'op':",
"= int(color) return statistics def plot_graph(g, benchmark, optimal=False): print(benchmark[\"benchmark\"]) post",
"graphviz import Digraph import pandas as pd # color the",
"constraints on availablility of Jobs # R = np.zeros(n) R",
"8*1024, 4*1024, 2*1024, 256, 128, 64, 32]: print(f'process {bnch}') g",
"second g.vp.output_size[v] = float(output_size) # 1GB g.vp.color[v] = '#e0e0e0' for",
"name_to_vid[name] = vid g.vp.name[v] = name g.vp.runtime[v] = float(runtime) #",
"tompkins.ilp import schedule, jobs_when_where from collections import defaultdict from pulp",
"#bw = 10*(1<<30)/(1<<3) bw = bw*(1<<20)/(1<<3) C = defaultdict(lambda:0) for",
"import utils from tompkins.ilp import schedule, jobs_when_where from collections import",
"computation D = defaultdict(lambda:0) for v in g.vertices(): for a",
"open(gfile, 'r') as fd: raw = fd.read().split('\\n') g = gt.Graph(directed=True)",
"statistics = {} jfile = os.path.join(stats_dir, f'{benchmark}.json') with open(jfile, 'r')",
"1 # computation D = defaultdict(lambda:0) for v in g.vertices():",
"ops, 'output_size': stats[ts]['msg']['nbytes'], 'worker': stats[ts]['worker'].split(':')[1].replace('/', '')} startsstops = stats[ts]['msg']['startstops'] for",
"= defaultdict(lambda:1) agents = workers jobs = [] for v",
"= j + (j[1] + D[j[0], j[2]], g.vp.name[int(j[0].replace('t', ''))]) sched2.append(new)",
"#benchmarks = ['dom4x61GB1B', 'dom2x41GB1B', 'tree4x61GB1B'] for bnch in benchmarks: for",
"= g.vp.runtime[v] # statistics[g.vp.name[v]]['runtime'] # Communication Delay matrix - Cost",
"in g.edges(): P[f't{e.source()}',f't{e.target()}'] = 1 # computation D = defaultdict(lambda:0)",
"quiet=False) import pulp as pl import time def find_optimal(g, bw):",
"Times - Additional constraints on availablility of Jobs # R",
"matplotlib.colors as mcolors import sys import seaborn as sns def",
"pl import time def find_optimal(g, bw): n_workers = 4 workers",
"in os.listdir(stats_dir): try: bnch = _file.rsplit('.', 1)[0] assert os.path.isfile(os.path.join(stats_dir, f'{bnch}.iopt'))",
"== 'compute': statistics[ts]['compute_end'] = ss['stop'] statistics[ts]['compute_start'] = ss['start'] statistics[ts]['runtime'] =",
"os.listdir(stats_dir): try: bnch = _file.rsplit('.', 1)[0] assert os.path.isfile(os.path.join(stats_dir, f'{bnch}.iopt')) app",
"= defaultdict(lambda:0) # Maximum makespan M = 100 B =",
"dg.node(f'{v}') #else: dg.node(f'{v}, color({g.vp.icolor[v]})') for e in g.edges(): #if benchmark['scheduler']",
"g.vp.name[int(j[0].replace('t', ''))]) sched2.append(new) print(\"Schedule: \", sched2) return sched2, {'makespan': value(Cmax),",
"color=worker_color[g.vp.statistics[v]['worker']]) #if benchmark['scheduler'] == \"vanilla\": # dg.node(f'{v}') #else: dg.node(f'{v}, color({g.vp.icolor[v]})')",
"sched2) return sched2, {'makespan': value(Cmax), 'constraints': len(prob.constraints.keys()), 'variables': prob.numVariables(), 'time':",
"= _file.rsplit('.', 1)[0] assert os.path.isfile(os.path.join(stats_dir, f'{bnch}.iopt')) app = bnch #,",
"ast import json from graphviz import Digraph import pandas as",
"v in g.vertices(): dg.attr('node', shape='ellipse', style=\"filled,solid\", penwidth=\"3\", fillcolor=g.vp.color[v], color=worker_color[g.vp.statistics[v]['worker']]) #if",
"statistics[g.vp.name[v]]['runtime'] # Communication Delay matrix - Cost of sending results",
"a in agents: for b in agents: C[f't{v}', a, b]",
"return statistics def plot_graph(g, benchmark, optimal=False): print(benchmark[\"benchmark\"]) post = \".optimal\"",
"= ln.split(',', 4) v = g.add_vertex() vid_to_vx[vid] = v name_to_vid[name]",
"j in sched: new = j + (j[1] + D[j[0],",
"json from graphviz import Digraph import pandas as pd #",
"startsstops = stats[ts]['msg']['startstops'] for ss in startsstops: if ss['action'] ==",
"a] = g.vp.runtime[v] # statistics[g.vp.name[v]]['runtime'] # Communication Delay matrix -",
"'worker': stats[ts]['worker'].split(':')[1].replace('/', '')} startsstops = stats[ts]['msg']['startstops'] for ss in startsstops:",
"# 0 --> cost_serialization start = time.time() # Set up",
"for v in g.vertices(): for a in agents: for b",
"= 10*(1<<30)/(1<<3) bw = bw*(1<<20)/(1<<3) C = defaultdict(lambda:0) for v",
"from tompkins.ilp import schedule, jobs_when_where from collections import defaultdict from",
"in raw: if not ln: continue ts, color = ln.split(',')",
"= [f'w{i}' for i in range(n_workers)] # Job Release Times",
"[] statistics = {} jfile = os.path.join(stats_dir, f'{benchmark}.json') with open(jfile,",
"matplotlib.colors as mcolors import sys import utils from tompkins.ilp import",
"def get_benchmarks(): benchmarks = {} for _file in os.listdir(stats_dir): try:",
"len(agents) P = defaultdict(lambda:0) for e in g.edges(): P[f't{e.source()}',f't{e.target()}'] =",
"re import ast import json from graphviz import Digraph import",
"#else: dg.node(f'{v}, color({g.vp.icolor[v]})') for e in g.edges(): #if benchmark['scheduler'] ==",
"B = defaultdict(lambda:1) agents = workers jobs = [] for",
"= time.time() - start print('-----------------------------------------------> constraints', len(prob.constraints.keys())) print('----------------------------------------------> # of",
"defaultdict from pulp import value import re import ast import",
"assert os.path.isfile(os.path.join(stats_dir, f'{bnch}.iopt')) app = bnch #, scheduler = bnch.rsplit(':',",
"# dg.node(f'{v}') #else: dg.node(f'{v}, color({g.vp.icolor[v]})') for e in g.edges(): #if",
"Job Release Times - Additional constraints on availablility of Jobs",
"dg.edge(f'{e.source()}', f'{e.target()}') #else: dg.edge(f'{e.source()}, color({g.vp.icolor[e.source()]})', f'{e.target()}, color({g.vp.icolor[e.target()]})') dg.view(os.path.join(f'{results_dir}',f'{benchmark[\"benchmark\"]}{post}'), quiet=False) import",
"sched2: fd.write(f'v,{s[0]},{s[1]},{s[2]}\\n') #fd.write(f'{s[4]},{s[3]},{s[0]},{s[1]},{s[2]}\\n') #v = int(s[0].replace('t', '')) #g.vp.worker[v] = s[2]",
"post = \".optimal\" if optimal else \"\" dg = Digraph('G',",
"g.new_vertex_property(\"string\") g.vertex_properties['worker'] = g.new_vertex_property(\"string\") g.vertex_properties['color'] = g.new_vertex_property(\"string\", '#e0e0e0') g.vertex_properties['icolor'] =",
"from graphviz import Digraph import pandas as pd # color",
"{} for _file in os.listdir(stats_dir): try: bnch = _file.rsplit('.', 1)[0]",
"\", sched) sched2 = [] for j in sched: new",
"Cmax = schedule(jobs, agents, D, C, R, B, P, M)",
"app, 'scheduler': scheduler, 'benchmark': bnch} except AssertionError: pass return benchmarks",
"#ts += ')' statistics[ts]['color'] = int(color) return statistics def plot_graph(g,",
"g def get_runtime_statistics(benchmark): tasks = [] statistics = {} jfile",
"of Jobs # R = np.zeros(n) R = defaultdict(lambda:0) #",
"print('-----------------------------------------------> constraints', len(prob.constraints.keys())) print('----------------------------------------------> # of variables', prob.numVariables()) print('---------------------------------------------->', latency)",
"agents: for b in agents: C[f't{v}', a, b] = 0",
"copy import matplotlib.colors as mcolors import sys import seaborn as",
"pulp as pl import time def find_optimal(g, bw): n_workers =",
"stats = ast.literal_eval(fd.read()) for ts in stats: ops = 'ts';",
"= jobs_when_where(prob, X, S, Cmax) print(\"Schedule: \", sched) sched2 =",
"Mixed Integer Linear Program prob, X, S, Cmax = schedule(jobs,",
"defaultdict(lambda:0) for v in g.vertices(): for a in agents: for",
"1GB g.vp.color[v] = '#e0e0e0' for ln in raw: if ln.startswith('e'):",
"P[f't{e.source()}',f't{e.target()}'] = 1 # computation D = defaultdict(lambda:0) for v",
"scheduler = bnch.rsplit(':', 1) scheduler = 'vanilla' benchmarks[bnch] = {'app':",
"open(f'{results_dir}/{bnch}.nonetworkcontention.{bw}mbps.optimal', 'w') as fd: for s in sched2: fd.write(f'v,{s[0]},{s[1]},{s[2]}\\n') #fd.write(f'{s[4]},{s[3]},{s[0]},{s[1]},{s[2]}\\n')",
"graph import graph_tool.all as gt import copy import matplotlib.colors as",
"time.time() # Set up the Mixed Integer Linear Program prob,",
"vid_to_vx[vdst]) return g def get_runtime_statistics(benchmark): tasks = [] statistics =",
"'vanilla' benchmarks[bnch] = {'app': app, 'scheduler': scheduler, 'benchmark': bnch} except",
"Additional constraints on availablility of Jobs # R = np.zeros(n)",
"g.vertex_properties['icolor'] = g.new_vertex_property(\"int\") g.vertex_properties['output_size'] = g.new_vertex_property(\"int\") g.vertex_properties['runtime'] = g.new_vertex_property(\"float\") for",
"print(f'process {bnch}') g = build_graph(bnch) sched2, stats = find_optimal(g, bw)",
"{bnch}') g = build_graph(bnch) sched2, stats = find_optimal(g, bw) with",
"g.vertices(): dg.attr('node', shape='ellipse', style=\"filled,solid\", penwidth=\"3\", fillcolor=g.vp.color[v], color=worker_color[g.vp.statistics[v]['worker']]) #if benchmark['scheduler'] ==",
"#, scheduler = bnch.rsplit(':', 1) scheduler = 'vanilla' benchmarks[bnch] =",
"from # agent to agent #bw = 10*(1<<30)/(1<<3) bw =",
"get_runtime_statistics(benchmark): tasks = [] statistics = {} jfile = os.path.join(stats_dir,",
"# statistics[g.vp.name[v]]['runtime'] # Communication Delay matrix - Cost of sending",
"in sched: new = j + (j[1] + D[j[0], j[2]],",
"= bnch #, scheduler = bnch.rsplit(':', 1) scheduler = 'vanilla'",
"= float(output_size) # 1GB g.vp.color[v] = '#e0e0e0' for ln in",
"jfile = os.path.join(stats_dir, f'{benchmark}.json') with open(jfile, 'r') as fd: stats",
"fd: stats = ast.literal_eval(fd.read()) for ts in stats: ops =",
"dg.node(f'{v}, color({g.vp.icolor[v]})') for e in g.edges(): #if benchmark['scheduler'] == \"vanilla\":",
"ln.startswith('v'): _, vid, name, runtime, output_size = ln.split(',', 4) v",
"scheduler = 'vanilla' benchmarks[bnch] = {'app': app, 'scheduler': scheduler, 'benchmark':",
"jobs_when_where from collections import defaultdict from pulp import value import",
"X, S, Cmax = schedule(jobs, agents, D, C, R, B,",
"def find_optimal(g, bw): n_workers = 4 workers = [f'w{i}' for",
"gfile = os.path.join(stats_dir, f'{benchmark}.iopt') with open(gfile, 'r') as fd: raw",
"schedule(jobs, agents, D, C, R, B, P, M) solver =",
"as pd # color the graph import graph_tool.all as gt",
"range(n_workers)] # Job Release Times - Additional constraints on availablility",
"#ts.replace(\"(\", '').replace(')', '').split(\"'\")[1].split('-')[0] statistics[ts] = {'key': ts, 'op': ops, 'output_size':",
"'time': float(latency)} results_dir = './benchmarks' stats_dir='./benchmarks' benchmarks = get_benchmarks() #benchmarks",
"for _file in os.listdir(stats_dir): try: bnch = _file.rsplit('.', 1)[0] assert",
"n = len(jobs) m = len(agents) P = defaultdict(lambda:0) for",
"for v in g.vertices(): for a in agents: D[f't{v}', a]",
"pd # color the graph import graph_tool.all as gt import",
"jobs.append(f't{v}') n = len(jobs) m = len(agents) P = defaultdict(lambda:0)",
"benchmarks def build_graph(benchmark): css_colors = list(mcolors.CSS4_COLORS.keys()) gfile = os.path.join(stats_dir, f'{benchmark}.iopt')",
"g.vp.color[v] = '#e0e0e0' for ln in raw: if ln.startswith('e'): _,",
"100 B = defaultdict(lambda:1) agents = workers jobs = []",
"statistics[ts] = {'key': ts, 'op': ops, 'output_size': stats[ts]['msg']['nbytes'], 'worker': stats[ts]['worker'].split(':')[1].replace('/',",
"X, S, Cmax) print(\"Schedule: \", sched) sched2 = [] for",
"= [] for j in sched: new = j +",
"256, 128, 64, 32]: print(f'process {bnch}') g = build_graph(bnch) sched2,",
"j[2]], g.vp.name[int(j[0].replace('t', ''))]) sched2.append(new) print(\"Schedule: \", sched2) return sched2, {'makespan':",
"import seaborn as sns def get_benchmarks(): benchmarks = {} for",
"ln.startswith('e'): _, vsrc, vdst = ln.split(',') g.add_edge(vid_to_vx[vsrc], vid_to_vx[vdst]) return g",
"import pulp as pl import time def find_optimal(g, bw): n_workers",
"results_dir = './benchmarks' stats_dir='./benchmarks' benchmarks = get_benchmarks() #benchmarks = ['dom4x61GB1B',",
"ln in raw: if not ln: continue ts, color =",
"graph_tool.all as gt import copy import matplotlib.colors as mcolors import",
"1 second g.vp.output_size[v] = float(output_size) # 1GB g.vp.color[v] = '#e0e0e0'",
"ln.split(',', 4) v = g.add_vertex() vid_to_vx[vid] = v name_to_vid[name] =",
"def plot_graph(g, benchmark, optimal=False): print(benchmark[\"benchmark\"]) post = \".optimal\" if optimal",
"output_size = ln.split(',', 4) v = g.add_vertex() vid_to_vx[vid] = v",
"g = build_graph(bnch) sched2, stats = find_optimal(g, bw) with open(f'{results_dir}/optimal_compuation_stats.csv',",
"for ts in stats: ops = 'ts'; #ts.replace(\"(\", '').replace(')', '').split(\"'\")[1].split('-')[0]",
"for i in range(n_workers)] # Job Release Times - Additional",
"int(color) return statistics def plot_graph(g, benchmark, optimal=False): print(benchmark[\"benchmark\"]) post =",
"prob, X, S, Cmax = schedule(jobs, agents, D, C, R,",
"= 4 workers = [f'w{i}' for i in range(n_workers)] #",
"raw: if ln.startswith('v'): _, vid, name, runtime, output_size = ln.split(',',",
"if not ln: continue ts, color = ln.split(',') #ts +=",
"+= ')' statistics[ts]['color'] = int(color) return statistics def plot_graph(g, benchmark,",
"(j[1] + D[j[0], j[2]], g.vp.name[int(j[0].replace('t', ''))]) sched2.append(new) print(\"Schedule: \", sched2)",
"D = defaultdict(lambda:0) for v in g.vertices(): for a in",
"value(Cmax)) sched = jobs_when_where(prob, X, S, Cmax) print(\"Schedule: \", sched)",
"= g.new_vertex_property(\"int\") g.vertex_properties['output_size'] = g.new_vertex_property(\"int\") g.vertex_properties['runtime'] = g.new_vertex_property(\"float\") for ln",
"= {'key': ts, 'op': ops, 'output_size': stats[ts]['msg']['nbytes'], 'worker': stats[ts]['worker'].split(':')[1].replace('/', '')}",
"{} jfile = os.path.join(stats_dir, f'{benchmark}.json') with open(jfile, 'r') as fd:",
"penwidth=\"3\", fillcolor=g.vp.color[v], color=worker_color[g.vp.statistics[v]['worker']]) #if benchmark['scheduler'] == \"vanilla\": # dg.node(f'{v}') #else:",
"= np.zeros(n) R = defaultdict(lambda:0) # Maximum makespan M =",
"v in g.vertices(): jobs.append(f't{v}') n = len(jobs) m = len(agents)",
"optimal=False): print(benchmark[\"benchmark\"]) post = \".optimal\" if optimal else \"\" dg",
"in sched2: fd.write(f'v,{s[0]},{s[1]},{s[2]}\\n') #fd.write(f'{s[4]},{s[3]},{s[0]},{s[1]},{s[2]}\\n') #v = int(s[0].replace('t', '')) #g.vp.worker[v] =",
"= cfd.read().split('\\n') for ln in raw: if not ln: continue",
"up the Mixed Integer Linear Program prob, X, S, Cmax",
"['dom4x61GB1B', 'dom2x41GB1B', 'tree4x61GB1B'] for bnch in benchmarks: for bw in",
"+ D[j[0], j[2]], g.vp.name[int(j[0].replace('t', ''))]) sched2.append(new) print(\"Schedule: \", sched2) return",
"dg.attr('node', shape='ellipse', style=\"filled,solid\", penwidth=\"3\", fillcolor=g.vp.color[v], color=worker_color[g.vp.statistics[v]['worker']]) #if benchmark['scheduler'] == \"vanilla\":",
"# Communication Delay matrix - Cost of sending results of",
"for s in sched2: fd.write(f'v,{s[0]},{s[1]},{s[2]}\\n') #fd.write(f'{s[4]},{s[3]},{s[0]},{s[1]},{s[2]}\\n') #v = int(s[0].replace('t', ''))",
"= '#e0e0e0' for ln in raw: if ln.startswith('e'): _, vsrc,",
"= {} for _file in os.listdir(stats_dir): try: bnch = _file.rsplit('.',",
"vsrc, vdst = ln.split(',') g.add_edge(vid_to_vx[vsrc], vid_to_vx[vdst]) return g def get_runtime_statistics(benchmark):",
"= os.path.join(stats_dir, f'{benchmark}.json') with open(jfile, 'r') as fd: stats =",
"[1*1024, 16*1024, 512, 32*1024, 8*1024, 4*1024, 2*1024, 256, 128, 64,",
"print(\"Makespan: \", value(Cmax)) sched = jobs_when_where(prob, X, S, Cmax) print(\"Schedule:",
"print('---------------------------------------------->', latency) print(\"Makespan: \", value(Cmax)) sched = jobs_when_where(prob, X, S,",
"'variables': prob.numVariables(), 'time': float(latency)} results_dir = './benchmarks' stats_dir='./benchmarks' benchmarks =",
"Linear Program prob, X, S, Cmax = schedule(jobs, agents, D,",
"in [1*1024, 16*1024, 512, 32*1024, 8*1024, 4*1024, 2*1024, 256, 128,",
"e in g.edges(): P[f't{e.source()}',f't{e.target()}'] = 1 # computation D =",
"fd.read().split('\\n') g = gt.Graph(directed=True) vid_to_vx = {} name_to_vid = {}",
"copy import matplotlib.colors as mcolors import sys import utils from",
"bw*(1<<20)/(1<<3) C = defaultdict(lambda:0) for v in g.vertices(): for a",
"B, P, M) solver = pl.GUROBI_CMD() prob.solve(solver) latency = time.time()",
"for ln in raw: if ln.startswith('v'): _, vid, name, runtime,",
"import matplotlib.colors as mcolors import sys import seaborn as sns",
"for e in g.edges(): #if benchmark['scheduler'] == \"vanilla\": # dg.edge(f'{e.source()}',",
"[] for v in g.vertices(): jobs.append(f't{v}') n = len(jobs) m",
"0 if a == b else g.vp.output_size[v]/bw # 0 -->",
"Cost of sending results of job from # agent to",
"color({g.vp.icolor[v]})') for e in g.edges(): #if benchmark['scheduler'] == \"vanilla\": #",
"= bw*(1<<20)/(1<<3) C = defaultdict(lambda:0) for v in g.vertices(): for",
"[] for j in sched: new = j + (j[1]",
"'dom2x41GB1B', 'tree4x61GB1B'] for bnch in benchmarks: for bw in [1*1024,",
"fd.write(f'{bnch},{stats[\"makespan\"]},{stats[\"constraints\"]},{stats[\"variables\"]},{stats[\"time\"]},no,{bw}\\n') with open(f'{results_dir}/{bnch}.nonetworkcontention.{bw}mbps.optimal', 'w') as fd: for s in sched2:",
"list(mcolors.CSS4_COLORS.keys()) gfile = os.path.join(stats_dir, f'{benchmark}.iopt') with open(gfile, 'r') as fd:",
"{} g.vertex_properties['name'] = g.new_vertex_property(\"string\") g.vertex_properties['worker'] = g.new_vertex_property(\"string\") g.vertex_properties['color'] = g.new_vertex_property(\"string\",",
"Program prob, X, S, Cmax = schedule(jobs, agents, D, C,",
"benchmarks: for bw in [1*1024, 16*1024, 512, 32*1024, 8*1024, 4*1024,",
"fd.write(f'v,{s[0]},{s[1]},{s[2]}\\n') #fd.write(f'{s[4]},{s[3]},{s[0]},{s[1]},{s[2]}\\n') #v = int(s[0].replace('t', '')) #g.vp.worker[v] = s[2] break",
"raw = fd.read().split('\\n') g = gt.Graph(directed=True) vid_to_vx = {} name_to_vid",
"import sys import utils from tompkins.ilp import schedule, jobs_when_where from",
"512, 32*1024, 8*1024, 4*1024, 2*1024, 256, 128, 64, 32]: print(f'process",
"M = 100 B = defaultdict(lambda:1) agents = workers jobs",
"solver = pl.GUROBI_CMD() prob.solve(solver) latency = time.time() - start print('----------------------------------------------->",
"scheduler, 'benchmark': bnch} except AssertionError: pass return benchmarks def build_graph(benchmark):",
"a in agents: D[f't{v}', a] = g.vp.runtime[v] # statistics[g.vp.name[v]]['runtime'] #",
"M) solver = pl.GUROBI_CMD() prob.solve(solver) latency = time.time() - start",
"f'{e.target()}, color({g.vp.icolor[e.target()]})') dg.view(os.path.join(f'{results_dir}',f'{benchmark[\"benchmark\"]}{post}'), quiet=False) import pulp as pl import time",
"v name_to_vid[name] = vid g.vp.name[v] = name g.vp.runtime[v] = float(runtime)",
"m = len(agents) P = defaultdict(lambda:0) for e in g.edges():",
"fd: for s in sched2: fd.write(f'v,{s[0]},{s[1]},{s[2]}\\n') #fd.write(f'{s[4]},{s[3]},{s[0]},{s[1]},{s[2]}\\n') #v = int(s[0].replace('t',",
"sns def get_benchmarks(): benchmarks = {} for _file in os.listdir(stats_dir):",
"_, vsrc, vdst = ln.split(',') g.add_edge(vid_to_vx[vsrc], vid_to_vx[vdst]) return g def",
"with open(gfile, 'r') as fd: raw = fd.read().split('\\n') g =",
"{} name_to_vid = {} g.vertex_properties['name'] = g.new_vertex_property(\"string\") g.vertex_properties['worker'] = g.new_vertex_property(\"string\")",
"g.vertex_properties['color'] = g.new_vertex_property(\"string\", '#e0e0e0') g.vertex_properties['icolor'] = g.new_vertex_property(\"int\") g.vertex_properties['output_size'] = g.new_vertex_property(\"int\")",
"bnch = _file.rsplit('.', 1)[0] assert os.path.isfile(os.path.join(stats_dir, f'{bnch}.iopt')) app = bnch",
"import re import ast import json from graphviz import Digraph",
"# of variables', prob.numVariables()) print('---------------------------------------------->', latency) print(\"Makespan: \", value(Cmax)) sched",
"if optimal else \"\" dg = Digraph('G', filename=f'{benchmark[\"benchmark\"]}{post}.gv', format='png') for",
"R = defaultdict(lambda:0) # Maximum makespan M = 100 B",
"10*(1<<30)/(1<<3) bw = bw*(1<<20)/(1<<3) C = defaultdict(lambda:0) for v in",
"latency = time.time() - start print('-----------------------------------------------> constraints', len(prob.constraints.keys())) print('----------------------------------------------> #",
"cfile = os.path.join(stats_dir, f'{benchmark}.colors') with open(cfile, 'r') as cfd: raw",
"g.new_vertex_property(\"string\") g.vertex_properties['color'] = g.new_vertex_property(\"string\", '#e0e0e0') g.vertex_properties['icolor'] = g.new_vertex_property(\"int\") g.vertex_properties['output_size'] =",
"g.add_vertex() vid_to_vx[vid] = v name_to_vid[name] = vid g.vp.name[v] = name",
"for v in g.vertices(): jobs.append(f't{v}') n = len(jobs) m =",
"bw = bw*(1<<20)/(1<<3) C = defaultdict(lambda:0) for v in g.vertices():",
"ln.split(',') #ts += ')' statistics[ts]['color'] = int(color) return statistics def",
"os.path.isfile(os.path.join(stats_dir, f'{bnch}.iopt')) app = bnch #, scheduler = bnch.rsplit(':', 1)",
"dg.view(os.path.join(f'{results_dir}',f'{benchmark[\"benchmark\"]}{post}'), quiet=False) import pulp as pl import time def find_optimal(g,",
"ts in stats: ops = 'ts'; #ts.replace(\"(\", '').replace(')', '').split(\"'\")[1].split('-')[0] statistics[ts]",
"16*1024, 512, 32*1024, 8*1024, 4*1024, 2*1024, 256, 128, 64, 32]:",
"S, Cmax = schedule(jobs, agents, D, C, R, B, P,",
"sched: new = j + (j[1] + D[j[0], j[2]], g.vp.name[int(j[0].replace('t',",
"Digraph import pandas as pd # color the graph import",
"vid_to_vx = {} name_to_vid = {} g.vertex_properties['name'] = g.new_vertex_property(\"string\") g.vertex_properties['worker']",
"4*1024, 2*1024, 256, 128, 64, 32]: print(f'process {bnch}') g =",
"of sending results of job from # agent to agent",
"on availablility of Jobs # R = np.zeros(n) R =",
"os.path.join(stats_dir, f'{benchmark}.iopt') with open(gfile, 'r') as fd: raw = fd.read().split('\\n')",
"sched2.append(new) print(\"Schedule: \", sched2) return sched2, {'makespan': value(Cmax), 'constraints': len(prob.constraints.keys()),",
"= './benchmarks' stats_dir='./benchmarks' benchmarks = get_benchmarks() #benchmarks = ['dom4x61GB1B', 'dom2x41GB1B',",
"gt import copy import matplotlib.colors as mcolors import sys import",
"statistics[ts]['runtime'] = ss['stop'] - ss['start'] cfile = os.path.join(stats_dir, f'{benchmark}.colors') with",
"raw: if not ln: continue ts, color = ln.split(',') #ts",
"g.new_vertex_property(\"string\", '#e0e0e0') g.vertex_properties['icolor'] = g.new_vertex_property(\"int\") g.vertex_properties['output_size'] = g.new_vertex_property(\"int\") g.vertex_properties['runtime'] =",
"= ln.split(',') g.add_edge(vid_to_vx[vsrc], vid_to_vx[vdst]) return g def get_runtime_statistics(benchmark): tasks =",
"\"vanilla\": # dg.edge(f'{e.source()}', f'{e.target()}') #else: dg.edge(f'{e.source()}, color({g.vp.icolor[e.source()]})', f'{e.target()}, color({g.vp.icolor[e.target()]})') dg.view(os.path.join(f'{results_dir}',f'{benchmark[\"benchmark\"]}{post}'),",
"= v name_to_vid[name] = vid g.vp.name[v] = name g.vp.runtime[v] =",
"in startsstops: if ss['action'] == 'compute': statistics[ts]['compute_end'] = ss['stop'] statistics[ts]['compute_start']",
"find_optimal(g, bw): n_workers = 4 workers = [f'w{i}' for i",
"ss['stop'] statistics[ts]['compute_start'] = ss['start'] statistics[ts]['runtime'] = ss['stop'] - ss['start'] cfile",
"== \"vanilla\": # dg.edge(f'{e.source()}', f'{e.target()}') #else: dg.edge(f'{e.source()}, color({g.vp.icolor[e.source()]})', f'{e.target()}, color({g.vp.icolor[e.target()]})')",
"from pulp import value import re import ast import json",
"gt.Graph(directed=True) vid_to_vx = {} name_to_vid = {} g.vertex_properties['name'] = g.new_vertex_property(\"string\")",
"for a in agents: D[f't{v}', a] = g.vp.runtime[v] # statistics[g.vp.name[v]]['runtime']",
"sending results of job from # agent to agent #bw",
"g.vp.output_size[v] = float(output_size) # 1GB g.vp.color[v] = '#e0e0e0' for ln",
"os.path.join(stats_dir, f'{benchmark}.colors') with open(cfile, 'r') as cfd: raw = cfd.read().split('\\n')",
"Cmax) print(\"Schedule: \", sched) sched2 = [] for j in",
"collections import defaultdict from pulp import value import re import",
"agents: D[f't{v}', a] = g.vp.runtime[v] # statistics[g.vp.name[v]]['runtime'] # Communication Delay",
"sys import utils from tompkins.ilp import schedule, jobs_when_where from collections",
"sched2, stats = find_optimal(g, bw) with open(f'{results_dir}/optimal_compuation_stats.csv', 'a') as fd:",
"benchmark['scheduler'] == \"vanilla\": # dg.node(f'{v}') #else: dg.node(f'{v}, color({g.vp.icolor[v]})') for e",
"Maximum makespan M = 100 B = defaultdict(lambda:1) agents =",
"pl.GUROBI_CMD() prob.solve(solver) latency = time.time() - start print('-----------------------------------------------> constraints', len(prob.constraints.keys()))",
"g.vertex_properties['output_size'] = g.new_vertex_property(\"int\") g.vertex_properties['runtime'] = g.new_vertex_property(\"float\") for ln in raw:",
"import matplotlib.colors as mcolors import sys import utils from tompkins.ilp",
"vdst = ln.split(',') g.add_edge(vid_to_vx[vsrc], vid_to_vx[vdst]) return g def get_runtime_statistics(benchmark): tasks",
"s in sched2: fd.write(f'v,{s[0]},{s[1]},{s[2]}\\n') #fd.write(f'{s[4]},{s[3]},{s[0]},{s[1]},{s[2]}\\n') #v = int(s[0].replace('t', '')) #g.vp.worker[v]",
"os.path.join(stats_dir, f'{benchmark}.json') with open(jfile, 'r') as fd: stats = ast.literal_eval(fd.read())",
"the Mixed Integer Linear Program prob, X, S, Cmax =",
"ss['stop'] - ss['start'] cfile = os.path.join(stats_dir, f'{benchmark}.colors') with open(cfile, 'r')",
"i in range(n_workers)] # Job Release Times - Additional constraints",
"C, R, B, P, M) solver = pl.GUROBI_CMD() prob.solve(solver) latency",
"find_optimal(g, bw) with open(f'{results_dir}/optimal_compuation_stats.csv', 'a') as fd: fd.write(f'{bnch},{stats[\"makespan\"]},{stats[\"constraints\"]},{stats[\"variables\"]},{stats[\"time\"]},no,{bw}\\n') with open(f'{results_dir}/{bnch}.nonetworkcontention.{bw}mbps.optimal',",
"ops = 'ts'; #ts.replace(\"(\", '').replace(')', '').split(\"'\")[1].split('-')[0] statistics[ts] = {'key': ts,",
"= list(mcolors.CSS4_COLORS.keys()) gfile = os.path.join(stats_dir, f'{benchmark}.iopt') with open(gfile, 'r') as",
"{'key': ts, 'op': ops, 'output_size': stats[ts]['msg']['nbytes'], 'worker': stats[ts]['worker'].split(':')[1].replace('/', '')} startsstops",
"import copy import matplotlib.colors as mcolors import sys import utils",
"f'{benchmark}.json') with open(jfile, 'r') as fd: stats = ast.literal_eval(fd.read()) for",
"vid, name, runtime, output_size = ln.split(',', 4) v = g.add_vertex()",
"= time.time() # Set up the Mixed Integer Linear Program",
"if a == b else g.vp.output_size[v]/bw # 0 --> cost_serialization",
"= ss['stop'] statistics[ts]['compute_start'] = ss['start'] statistics[ts]['runtime'] = ss['stop'] - ss['start']",
"C = defaultdict(lambda:0) for v in g.vertices(): for a in",
"_file.rsplit('.', 1)[0] assert os.path.isfile(os.path.join(stats_dir, f'{bnch}.iopt')) app = bnch #, scheduler",
"- Cost of sending results of job from # agent",
"D[j[0], j[2]], g.vp.name[int(j[0].replace('t', ''))]) sched2.append(new) print(\"Schedule: \", sched2) return sched2,",
"{'app': app, 'scheduler': scheduler, 'benchmark': bnch} except AssertionError: pass return",
"#else: dg.edge(f'{e.source()}, color({g.vp.icolor[e.source()]})', f'{e.target()}, color({g.vp.icolor[e.target()]})') dg.view(os.path.join(f'{results_dir}',f'{benchmark[\"benchmark\"]}{post}'), quiet=False) import pulp as",
"= 0 if a == b else g.vp.output_size[v]/bw # 0",
"bnch #, scheduler = bnch.rsplit(':', 1) scheduler = 'vanilla' benchmarks[bnch]",
"# Set up the Mixed Integer Linear Program prob, X,",
"startsstops: if ss['action'] == 'compute': statistics[ts]['compute_end'] = ss['stop'] statistics[ts]['compute_start'] =",
"g.vp.name[v] = name g.vp.runtime[v] = float(runtime) # 1 second g.vp.output_size[v]",
"#if benchmark['scheduler'] == \"vanilla\": # dg.edge(f'{e.source()}', f'{e.target()}') #else: dg.edge(f'{e.source()}, color({g.vp.icolor[e.source()]})',",
"v in g.vertices(): for a in agents: for b in",
"= {} jfile = os.path.join(stats_dir, f'{benchmark}.json') with open(jfile, 'r') as",
"= g.new_vertex_property(\"int\") g.vertex_properties['runtime'] = g.new_vertex_property(\"float\") for ln in raw: if",
"= stats[ts]['msg']['startstops'] for ss in startsstops: if ss['action'] == 'compute':",
"in range(n_workers)] # Job Release Times - Additional constraints on",
"R = np.zeros(n) R = defaultdict(lambda:0) # Maximum makespan M",
"ast.literal_eval(fd.read()) for ts in stats: ops = 'ts'; #ts.replace(\"(\", '').replace(')',"
] |
[
"Project from library.repository import Repository from library.repository import pull_harbor_image from",
"of robot account(RA);\" self.project.disable_project_robot_account(TestProjects.project_ra_id_a, robot_id, True, **TestProjects.USER_RA_CLIENT) print \"#13. Pull",
"project(PC), it must be successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_c, tag_c)",
"tag_b, expected_error_message = \"unauthorized to access repository\") print \"#10. Pull",
"self.repo.delete_repoitory(TestProjects.project_ra_name_a, TestProjects.repo_name_in_project_a.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_b, TestProjects.repo_name_in_project_b.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_c, TestProjects.repo_name_in_project_c.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_a,",
"\"#9. Pull image(ImagePB) from project(PB) by robot account(RA), it must",
"be not successful.\" self.project.delete_project_robot_account(TestProjects.project_ra_id_a, robot_id, **TestProjects.USER_RA_CLIENT) if __name__ == '__main__':",
"= {\"public\": \"false\"}, **TestProjects.USER_RA_CLIENT) TestProjects.project_ra_id_b, TestProjects.project_ra_name_b = self.project.create_project(metadata = {\"public\":",
"push priviliges;\" data = self.project.get_project_robot_account_by_id(TestProjects.project_ra_id_a, robot_id, **TestProjects.USER_RA_CLIENT) _assert_status_code(robot_account.name, data.name) print",
"robot_account.name, robot_account.token, image_robot_account, tag) print \"#8. Push image(ImageRA) to project(PB)",
"1. Delete repository(RA) by user(UA); 2. Delete project(PA); 3. Delete",
"@classmethod def setUp(self): self.project = Project() self.user = User() self.repo",
"push_image_to_project(TestProjects.project_ra_name_b, harbor_server, user_ra_name, user_ra_password, image_project_b, tag) TestProjects.repo_name_in_project_c, tag_c = push_image_to_project(TestProjects.project_ra_name_c,",
"self.repo.delete_repoitory(TestProjects.project_ra_name_c, TestProjects.repo_name_in_project_c.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_a, TestProjects.repo_name_pa.split('/')[1], **TestProjects.USER_RA_CLIENT) #2. Delete project(PA); self.project.delete_project(TestProjects.project_ra_id_a,",
"TEARDOWN from library.user import User from library.project import Project from",
"self.project.create_project(metadata = {\"public\": \"true\"}, **TestProjects.USER_RA_CLIENT) print \"#3. Push image(ImagePA) to",
"not successful.\" self.project.delete_project_robot_account(TestProjects.project_ra_id_a, robot_id, **TestProjects.USER_RA_CLIENT) if __name__ == '__main__': unittest.main()",
"not successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_b, tag_b, expected_error_message = \"unauthorized",
"account info, it should has both pull and push priviliges;",
"self.project.create_project(metadata = {\"public\": \"false\"}, **TestProjects.USER_RA_CLIENT) TestProjects.project_ra_id_b, TestProjects.project_ra_name_b = self.project.create_project(metadata =",
"print \"#7. Push image(ImageRA) to project(PA) by robot account(RA), it",
"not successful; 14. Push image(ImageRA) to project(PA) by robot account(RA),",
"robot_account.token, image_robot_account, tag, expected_error_message = \"unauthorized to access repository\") print",
"True, **TestProjects.USER_RA_CLIENT) print \"#13. Pull image(ImagePA) from project(PA) by robot",
"user_ra_password = \"<PASSWORD>\" image_project_a = \"haproxy\" image_project_b = \"hello-world\" image_project_c",
"push_image_to_project(TestProjects.project_ra_name_b, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag, expected_error_message = \"unauthorized to",
"print robot_account.token print \"#5. Check robot account info, it should",
"Create a new robot account(RA) with pull and push privilige",
"\"\"\" url = ADMIN_CLIENT[\"endpoint\"] admin_name = ADMIN_CLIENT[\"username\"] admin_password = ADMIN_CLIENT[\"password\"]",
"pull and push priviliges; 6. Pull image(ImagePA) from project(PA) by",
"project(PC) by user(UA); 4. Create a new robot account(RA) with",
"be not successful; 14. Push image(ImageRA) to project(PA) by robot",
"TestProjects.repo_name_in_project_b, tag_b = push_image_to_project(TestProjects.project_ra_name_b, harbor_server, user_ra_name, user_ra_password, image_project_b, tag) TestProjects.repo_name_in_project_c,",
"account(RA) with pull and push privilige in project(PA) by user(UA);",
"by robot account(RA), it must be not successful;\" push_image_to_project(TestProjects.project_ra_name_b, harbor_server,",
"successful;\" push_image_to_project(TestProjects.project_ra_name_c, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag, expected_error_message = \"unauthorized",
"be not successful; 12. Update action property of robot account(RA);",
"User from library.project import Project from library.repository import Repository from",
"ADMIN_CLIENT[\"endpoint\"] admin_name = ADMIN_CLIENT[\"username\"] admin_password = ADMIN_CLIENT[\"password\"] user_ra_password = \"<PASSWORD>\"",
"TestProjects.repo_name_in_project_a.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_b, TestProjects.repo_name_in_project_b.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_c, TestProjects.repo_name_in_project_c.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_a, TestProjects.repo_name_pa.split('/')[1],",
"user(UA); 3. Push image(ImagePA) to project(PA), image(ImagePB) to project(PB) and",
"library.user import User from library.project import Project from library.repository import",
"it must be successful; 7. Push image(ImageRA) to project(PA) by",
"harbor_server, user_ra_name, user_ra_password, image_project_c, tag) print \"#4. Create a new",
"import Project from library.repository import Repository from library.repository import pull_harbor_image",
"Delete robot account(RA), it must be not successful. Tear down:",
"robot account(RA); 13. Pull image(ImagePA) from project(PA) by robot account(RA),",
"by user(UA);\" TestProjects.project_ra_id_a, TestProjects.project_ra_name_a = self.project.create_project(metadata = {\"public\": \"false\"}, **TestProjects.USER_RA_CLIENT)",
"self.user = User() self.repo = Repository() @classmethod def tearDown(self): print",
"image_robot_account = \"alpine\" tag = \"latest\" print \"#1. Create user(UA);\"",
"it must be successful; 8. Push image(ImageRA) to project(PB) by",
"account(RA), it must be successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_a, tag_a)",
"project(PA) by robot account(RA), it must be not successful;\" push_image_to_project(TestProjects.project_ra_name_a,",
"to project(PB) and image(ImagePC) to project(PC) by user(UA); 4. Create",
"be successful; 11. Push image(ImageRA) to project(PC) by robot account(RA),",
"print \"#5. Check robot account info, it should has both",
"<PASSWORD>) print \"#2. Create private project(PA), private project(PB) and public",
"successful; 9. Pull image(ImagePB) from project(PB) by robot account(RA), it",
"robot_account.token, image_robot_account, tag) print \"#8. Push image(ImageRA) to project(PB) by",
"image_robot_account, tag, expected_login_error_message = \"unauthorized: authentication required\") print \"#15. Delete",
"robot_account.name print robot_account.token print \"#5. Check robot account info, it",
"and push priviliges;\" data = self.project.get_project_robot_account_by_id(TestProjects.project_ra_id_a, robot_id, **TestProjects.USER_RA_CLIENT) _assert_status_code(robot_account.name, data.name)",
"step and expected result: 1. Create user(UA); 2. Create private",
"project(PA); self.project.delete_project(TestProjects.project_ra_id_a, **TestProjects.USER_RA_CLIENT) self.project.delete_project(TestProjects.project_ra_id_b, **TestProjects.USER_RA_CLIENT) self.project.delete_project(TestProjects.project_ra_id_c, **TestProjects.USER_RA_CLIENT) #3. Delete user(UA).",
"successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_c, tag_c) print \"#11. Push image(ImageRA)",
"testutils import TEARDOWN from library.user import User from library.project import",
"Delete user(UA). self.user.delete_user(TestProjects.user_ra_id, **ADMIN_CLIENT) def testRobotAccount(self): \"\"\" Test case: Robot",
"= Project() self.user = User() self.repo = Repository() @classmethod def",
"Check robot account info, it should has both pull and",
"class TestProjects(unittest.TestCase): @classmethod def setUp(self): self.project = Project() self.user =",
"must be not successful; 10. Pull image from project(PC), it",
"it should has both pull and push priviliges; 6. Pull",
"account(RA), it must be successful; 7. Push image(ImageRA) to project(PA)",
"tag = \"latest\" print \"#1. Create user(UA);\" TestProjects.user_ra_id, user_ra_name =",
"Push image(ImageRA) to project(PA) by robot account(RA), it must be",
"image(ImagePB) from project(PB) by robot account(RA), it must be not",
"to project(PC) by robot account(RA), it must be not successful;",
"= push_image_to_project(TestProjects.project_ra_name_b, harbor_server, user_ra_name, user_ra_password, image_project_b, tag) TestProjects.repo_name_in_project_c, tag_c =",
"be erased.\") def test_ClearData(self): #1. Delete repository(RA) by user(UA); self.repo.delete_repoitory(TestProjects.project_ra_name_a,",
"= User() self.repo = Repository() @classmethod def tearDown(self): print \"Case",
"in project(PA) by user(UA); 5. Check robot account info, it",
"to project(PB) by robot account(RA), it must be not successful;\"",
"data.name) print \"#6. Pull image(ImagePA) from project(PA) by robot account(RA),",
"has both pull and push priviliges; 6. Pull image(ImagePA) from",
"robot_account.name, robot_account.token, image_robot_account, tag, expected_error_message = \"unauthorized to access repository\")",
"be not successful; 9. Pull image(ImagePB) from project(PB) by robot",
"both pull and push priviliges;\" data = self.project.get_project_robot_account_by_id(TestProjects.project_ra_id_a, robot_id, **TestProjects.USER_RA_CLIENT)",
"not successful;\" push_image_to_project(TestProjects.project_ra_name_a, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag, expected_login_error_message =",
"by robot account(RA), it must be successful;\" TestProjects.repo_name_pa, _ =",
"\"#8. Push image(ImageRA) to project(PB) by robot account(RA), it must",
"robot_account.token, TestProjects.repo_name_in_project_a, tag_a, expected_login_error_message = \"unauthorized: authentication required\") print \"#14.",
"to access repository\") print \"#10. Pull image from project(PC), it",
"8. Push image(ImageRA) to project(PB) by robot account(RA), it must",
"image(ImagePB) to project(PB) and image(ImagePC) to project(PC) by user(UA); 4.",
"\"\"\" Test case: Robot Account Test step and expected result:",
"image_project_b, tag) TestProjects.repo_name_in_project_c, tag_c = push_image_to_project(TestProjects.project_ra_name_c, harbor_server, user_ra_name, user_ra_password, image_project_c,",
"url, username = user_ra_name, password = <PASSWORD>) print \"#2. Create",
"print \"#15. Delete robot account(RA), it must be not successful.\"",
"completed\" @unittest.skipIf(TEARDOWN == False, \"Test data won't be erased.\") def",
"\"#4. Create a new robot account(RA) with pull and push",
"info, it should has both pull and push priviliges; 6.",
"#2. Delete project(PA); self.project.delete_project(TestProjects.project_ra_id_a, **TestProjects.USER_RA_CLIENT) self.project.delete_project(TestProjects.project_ra_id_b, **TestProjects.USER_RA_CLIENT) self.project.delete_project(TestProjects.project_ra_id_c, **TestProjects.USER_RA_CLIENT) #3.",
"property of robot account(RA);\" self.project.disable_project_robot_account(TestProjects.project_ra_id_a, robot_id, True, **TestProjects.USER_RA_CLIENT) print \"#13.",
"image from project(PC), it must be successful; 11. Push image(ImageRA)",
"{\"public\": \"true\"}, **TestProjects.USER_RA_CLIENT) print \"#3. Push image(ImagePA) to project(PA), image(ImagePB)",
"be not successful;\" push_image_to_project(TestProjects.project_ra_name_b, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag, expected_error_message",
"TestProjects.repo_name_in_project_c.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_a, TestProjects.repo_name_pa.split('/')[1], **TestProjects.USER_RA_CLIENT) #2. Delete project(PA); self.project.delete_project(TestProjects.project_ra_id_a, **TestProjects.USER_RA_CLIENT)",
"robot account(RA), it must be successful; 7. Push image(ImageRA) to",
"and push privilige in project(PA) by user(UA);\" robot_id, robot_account =",
"pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_c, tag_c) print \"#11. Push image(ImageRA) to",
"Pull image from project(PC), it must be successful; 11. Push",
"project(PA) by robot account(RA), it must be successful;\" pull_harbor_image(harbor_server, robot_account.name,",
"TestProjects.repo_name_in_project_a, tag_a) print \"#7. Push image(ImageRA) to project(PA) by robot",
"account info, it should has both pull and push priviliges;\"",
"to project(PA), image(ImagePB) to project(PB) and image(ImagePC) to project(PC) by",
"TestProjects.project_ra_name_b = self.project.create_project(metadata = {\"public\": \"false\"}, **TestProjects.USER_RA_CLIENT) TestProjects.project_ra_id_c, TestProjects.project_ra_name_c =",
"harbor_server, robot_account.name, robot_account.token, image_robot_account, tag, expected_error_message = \"unauthorized to access",
"3. Push image(ImagePA) to project(PA), image(ImagePB) to project(PB) and image(ImagePC)",
"must be not successful; 9. Pull image(ImagePB) from project(PB) by",
"self.project.disable_project_robot_account(TestProjects.project_ra_id_a, robot_id, True, **TestProjects.USER_RA_CLIENT) print \"#13. Pull image(ImagePA) from project(PA)",
"3. Delete user(UA). \"\"\" url = ADMIN_CLIENT[\"endpoint\"] admin_name = ADMIN_CLIENT[\"username\"]",
"authentication required\") print \"#14. Push image(ImageRA) to project(PA) by robot",
"= <PASSWORD>) print \"#2. Create private project(PA), private project(PB) and",
"be successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_a, tag_a) print \"#7. Push",
"to project(PC) by robot account(RA), it must be not successful;\"",
"TestProjects.project_ra_id_b, TestProjects.project_ra_name_b = self.project.create_project(metadata = {\"public\": \"false\"}, **TestProjects.USER_RA_CLIENT) TestProjects.project_ra_id_c, TestProjects.project_ra_name_c",
"not successful; 10. Pull image from project(PC), it must be",
"self.project.get_project_robot_account_by_id(TestProjects.project_ra_id_a, robot_id, **TestProjects.USER_RA_CLIENT) _assert_status_code(robot_account.name, data.name) print \"#6. Pull image(ImagePA) from",
"= self.user.create_user(user_password = <PASSWORD>, **ADMIN_CLIENT) TestProjects.USER_RA_CLIENT=dict(endpoint = url, username =",
"self.repo = Repository() @classmethod def tearDown(self): print \"Case completed\" @unittest.skipIf(TEARDOWN",
"to project(PA) by robot account(RA), it must be successful;\" TestProjects.repo_name_pa,",
"7. Push image(ImageRA) to project(PA) by robot account(RA), it must",
"be successful; 8. Push image(ImageRA) to project(PB) by robot account(RA),",
"it must be not successful.\" self.project.delete_project_robot_account(TestProjects.project_ra_id_a, robot_id, **TestProjects.USER_RA_CLIENT) if __name__",
"TestProjects.repo_name_in_project_a, tag_a = push_image_to_project(TestProjects.project_ra_name_a, harbor_server, user_ra_name, user_ra_password, image_project_a, tag) TestProjects.repo_name_in_project_b,",
"= push_image_to_project(TestProjects.project_ra_name_a, harbor_server, user_ra_name, user_ra_password, image_project_a, tag) TestProjects.repo_name_in_project_b, tag_b =",
"priviliges;\" data = self.project.get_project_robot_account_by_id(TestProjects.project_ra_id_a, robot_id, **TestProjects.USER_RA_CLIENT) _assert_status_code(robot_account.name, data.name) print \"#6.",
"= push_image_to_project(TestProjects.project_ra_name_a, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag) print \"#8. Push",
"image(ImagePA) to project(PA), image(ImagePB) to project(PB) and image(ImagePC) to project(PC)",
"robot_account.name, robot_account.token, TestProjects.repo_name_in_project_a, tag_a, expected_login_error_message = \"unauthorized: authentication required\") print",
"= self.project.add_project_robot_account(TestProjects.project_ra_id_a, TestProjects.project_ra_name_a, 2441000531 ,**TestProjects.USER_RA_CLIENT) print robot_account.name print robot_account.token print",
"tag_a, expected_login_error_message = \"unauthorized: authentication required\") print \"#14. Push image(ImageRA)",
"= ADMIN_CLIENT[\"password\"] user_ra_password = \"<PASSWORD>\" image_project_a = \"haproxy\" image_project_b =",
"to project(PC) by user(UA); 4. Create a new robot account(RA)",
"a new robot account(RA) with pull and push privilige in",
"access repository\") print \"#9. Pull image(ImagePB) from project(PB) by robot",
"import pull_harbor_image from library.repository import push_image_to_project from testutils import harbor_server",
"self.user.create_user(user_password = <PASSWORD>, **ADMIN_CLIENT) TestProjects.USER_RA_CLIENT=dict(endpoint = url, username = user_ra_name,",
"TestProjects.project_ra_name_a, 2441000531 ,**TestProjects.USER_RA_CLIENT) print robot_account.name print robot_account.token print \"#5. Check",
"be successful;\" TestProjects.repo_name_pa, _ = push_image_to_project(TestProjects.project_ra_name_a, harbor_server, robot_account.name, robot_account.token, image_robot_account,",
"it must be not successful;\" push_image_to_project(TestProjects.project_ra_name_c, harbor_server, robot_account.name, robot_account.token, image_robot_account,",
"project(PA) by user(UA);\" robot_id, robot_account = self.project.add_project_robot_account(TestProjects.project_ra_id_a, TestProjects.project_ra_name_a, 2441000531 ,**TestProjects.USER_RA_CLIENT)",
"it must be not successful; 14. Push image(ImageRA) to project(PA)",
"robot account(RA);\" self.project.disable_project_robot_account(TestProjects.project_ra_id_a, robot_id, True, **TestProjects.USER_RA_CLIENT) print \"#13. Pull image(ImagePA)",
"\"Case completed\" @unittest.skipIf(TEARDOWN == False, \"Test data won't be erased.\")",
"robot account(RA), it must be not successful; 10. Pull image",
"it must be successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_c, tag_c) print",
"by robot account(RA), it must be not successful;\" pull_harbor_image(harbor_server, robot_account.name,",
"user_ra_name = self.user.create_user(user_password = <PASSWORD>, **ADMIN_CLIENT) TestProjects.USER_RA_CLIENT=dict(endpoint = url, username",
"= \"latest\" print \"#1. Create user(UA);\" TestProjects.user_ra_id, user_ra_name = self.user.create_user(user_password",
"not successful; 15. Delete robot account(RA), it must be not",
"user_ra_name, user_ra_password, image_project_c, tag) print \"#4. Create a new robot",
"user_ra_name, user_ra_password, image_project_b, tag) TestProjects.repo_name_in_project_c, tag_c = push_image_to_project(TestProjects.project_ra_name_c, harbor_server, user_ra_name,",
"it must be successful;\" TestProjects.repo_name_pa, _ = push_image_to_project(TestProjects.project_ra_name_a, harbor_server, robot_account.name,",
"be not successful. Tear down: 1. Delete repository(RA) by user(UA);",
"unittest from testutils import ADMIN_CLIENT from testutils import TEARDOWN from",
"it must be not successful; 12. Update action property of",
"image_project_c, tag) print \"#4. Create a new robot account(RA) with",
"= {\"public\": \"false\"}, **TestProjects.USER_RA_CLIENT) TestProjects.project_ra_id_c, TestProjects.project_ra_name_c = self.project.create_project(metadata = {\"public\":",
"\"false\"}, **TestProjects.USER_RA_CLIENT) TestProjects.project_ra_id_b, TestProjects.project_ra_name_b = self.project.create_project(metadata = {\"public\": \"false\"}, **TestProjects.USER_RA_CLIENT)",
"\"#2. Create private project(PA), private project(PB) and public project(PC) by",
"image(ImagePA) from project(PA) by robot account(RA), it must be not",
"2. Delete project(PA); 3. Delete user(UA). \"\"\" url = ADMIN_CLIENT[\"endpoint\"]",
"user_ra_password, image_project_c, tag) print \"#4. Create a new robot account(RA)",
"down: 1. Delete repository(RA) by user(UA); 2. Delete project(PA); 3.",
"6. Pull image(ImagePA) from project(PA) by robot account(RA), it must",
"image(ImageRA) to project(PC) by robot account(RA), it must be not",
"in project(PA) by user(UA);\" robot_id, robot_account = self.project.add_project_robot_account(TestProjects.project_ra_id_a, TestProjects.project_ra_name_a, 2441000531",
"property of robot account(RA); 13. Pull image(ImagePA) from project(PA) by",
"user_ra_password, image_project_b, tag) TestProjects.repo_name_in_project_c, tag_c = push_image_to_project(TestProjects.project_ra_name_c, harbor_server, user_ra_name, user_ra_password,",
"\"#14. Push image(ImageRA) to project(PA) by robot account(RA), it must",
"successful; 8. Push image(ImageRA) to project(PB) by robot account(RA), it",
"successful;\" push_image_to_project(TestProjects.project_ra_name_b, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag, expected_error_message = \"unauthorized",
"Tear down: 1. Delete repository(RA) by user(UA); 2. Delete project(PA);",
"robot account(RA) with pull and push privilige in project(PA) by",
"Delete repository(RA) by user(UA); 2. Delete project(PA); 3. Delete user(UA).",
"user(UA); 4. Create a new robot account(RA) with pull and",
"**TestProjects.USER_RA_CLIENT) print \"#3. Push image(ImagePA) to project(PA), image(ImagePB) to project(PB)",
"push_image_to_project(TestProjects.project_ra_name_a, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag, expected_login_error_message = \"unauthorized: authentication",
"successful; 15. Delete robot account(RA), it must be not successful.",
"successful; 11. Push image(ImageRA) to project(PC) by robot account(RA), it",
"account(RA), it must be not successful;\" push_image_to_project(TestProjects.project_ra_name_b, harbor_server, robot_account.name, robot_account.token,",
"= self.project.create_project(metadata = {\"public\": \"false\"}, **TestProjects.USER_RA_CLIENT) TestProjects.project_ra_id_c, TestProjects.project_ra_name_c = self.project.create_project(metadata",
"must be not successful;\" push_image_to_project(TestProjects.project_ra_name_b, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag,",
"image(ImagePA) from project(PA) by robot account(RA), it must be successful;",
"tag) print \"#4. Create a new robot account(RA) with pull",
"from project(PC), it must be successful; 11. Push image(ImageRA) to",
"def tearDown(self): print \"Case completed\" @unittest.skipIf(TEARDOWN == False, \"Test data",
"robot account(RA), it must be not successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token,",
"from project(PB) by robot account(RA), it must be not successful;",
"setUp(self): self.project = Project() self.user = User() self.repo = Repository()",
"successful; 7. Push image(ImageRA) to project(PA) by robot account(RA), it",
"self.user.delete_user(TestProjects.user_ra_id, **ADMIN_CLIENT) def testRobotAccount(self): \"\"\" Test case: Robot Account Test",
"robot account(RA), it must be successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_a,",
"account(RA), it must be not successful;\" push_image_to_project(TestProjects.project_ra_name_c, harbor_server, robot_account.name, robot_account.token,",
"print \"#14. Push image(ImageRA) to project(PA) by robot account(RA), it",
"push_image_to_project(TestProjects.project_ra_name_c, harbor_server, user_ra_name, user_ra_password, image_project_c, tag) print \"#4. Create a",
"= \"haproxy\" image_project_b = \"hello-world\" image_project_c = \"httpd\" image_robot_account =",
"= Repository() @classmethod def tearDown(self): print \"Case completed\" @unittest.skipIf(TEARDOWN ==",
"image(ImagePA) from project(PA) by robot account(RA), it must be successful;\"",
"Pull image(ImagePB) from project(PB) by robot account(RA), it must be",
"account(RA), it must be not successful; 9. Pull image(ImagePB) from",
"self.project.delete_project(TestProjects.project_ra_id_a, **TestProjects.USER_RA_CLIENT) self.project.delete_project(TestProjects.project_ra_id_b, **TestProjects.USER_RA_CLIENT) self.project.delete_project(TestProjects.project_ra_id_c, **TestProjects.USER_RA_CLIENT) #3. Delete user(UA). self.user.delete_user(TestProjects.user_ra_id,",
"\"latest\" print \"#1. Create user(UA);\" TestProjects.user_ra_id, user_ra_name = self.user.create_user(user_password =",
"to project(PB) by robot account(RA), it must be not successful;",
"import _assert_status_code class TestProjects(unittest.TestCase): @classmethod def setUp(self): self.project = Project()",
"tag_c = push_image_to_project(TestProjects.project_ra_name_c, harbor_server, user_ra_name, user_ra_password, image_project_c, tag) print \"#4.",
"info, it should has both pull and push priviliges;\" data",
"tag_a = push_image_to_project(TestProjects.project_ra_name_a, harbor_server, user_ra_name, user_ra_password, image_project_a, tag) TestProjects.repo_name_in_project_b, tag_b",
"required\") print \"#15. Delete robot account(RA), it must be not",
"@classmethod def tearDown(self): print \"Case completed\" @unittest.skipIf(TEARDOWN == False, \"Test",
"user(UA);\" TestProjects.project_ra_id_a, TestProjects.project_ra_name_a = self.project.create_project(metadata = {\"public\": \"false\"}, **TestProjects.USER_RA_CLIENT) TestProjects.project_ra_id_b,",
"account(RA), it must be not successful; 14. Push image(ImageRA) to",
"\"<PASSWORD>\" image_project_a = \"haproxy\" image_project_b = \"hello-world\" image_project_c = \"httpd\"",
"both pull and push priviliges; 6. Pull image(ImagePA) from project(PA)",
"= ADMIN_CLIENT[\"endpoint\"] admin_name = ADMIN_CLIENT[\"username\"] admin_password = ADMIN_CLIENT[\"password\"] user_ra_password =",
"successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_a, tag_a, expected_login_error_message = \"unauthorized: authentication",
"TestProjects.repo_name_pa.split('/')[1], **TestProjects.USER_RA_CLIENT) #2. Delete project(PA); self.project.delete_project(TestProjects.project_ra_id_a, **TestProjects.USER_RA_CLIENT) self.project.delete_project(TestProjects.project_ra_id_b, **TestProjects.USER_RA_CLIENT) self.project.delete_project(TestProjects.project_ra_id_c,",
"not successful. Tear down: 1. Delete repository(RA) by user(UA); 2.",
"project(PB) and public project(PC) by user(UA); 3. Push image(ImagePA) to",
"project(PC) by user(UA); 3. Push image(ImagePA) to project(PA), image(ImagePB) to",
"data won't be erased.\") def test_ClearData(self): #1. Delete repository(RA) by",
"= self.project.create_project(metadata = {\"public\": \"false\"}, **TestProjects.USER_RA_CLIENT) TestProjects.project_ra_id_b, TestProjects.project_ra_name_b = self.project.create_project(metadata",
"image_project_a, tag) TestProjects.repo_name_in_project_b, tag_b = push_image_to_project(TestProjects.project_ra_name_b, harbor_server, user_ra_name, user_ra_password, image_project_b,",
"import TEARDOWN from library.user import User from library.project import Project",
"= url, username = user_ra_name, password = <PASSWORD>) print \"#2.",
"and image(ImagePC) to project(PC) by user(UA); 4. Create a new",
"**ADMIN_CLIENT) TestProjects.USER_RA_CLIENT=dict(endpoint = url, username = user_ra_name, password = <PASSWORD>)",
"Repository() @classmethod def tearDown(self): print \"Case completed\" @unittest.skipIf(TEARDOWN == False,",
"Test case: Robot Account Test step and expected result: 1.",
"be successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_c, tag_c) print \"#11. Push",
"project(PC) by robot account(RA), it must be not successful;\" push_image_to_project(TestProjects.project_ra_name_c,",
"not successful;\" push_image_to_project(TestProjects.project_ra_name_c, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag, expected_error_message =",
"= ADMIN_CLIENT[\"username\"] admin_password = ADMIN_CLIENT[\"password\"] user_ra_password = \"<PASSWORD>\" image_project_a =",
"image(ImageRA) to project(PB) by robot account(RA), it must be not",
"from library.repository import pull_harbor_image from library.repository import push_image_to_project from testutils",
"robot_account.token, TestProjects.repo_name_in_project_c, tag_c) print \"#11. Push image(ImageRA) to project(PC) by",
"be not successful;\" push_image_to_project(TestProjects.project_ra_name_a, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag, expected_login_error_message",
"\"Test data won't be erased.\") def test_ClearData(self): #1. Delete repository(RA)",
"= \"unauthorized to access repository\") print \"#9. Pull image(ImagePB) from",
"it must be not successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_b, tag_b,",
"image(ImageRA) to project(PA) by robot account(RA), it must be successful;",
"11. Push image(ImageRA) to project(PC) by robot account(RA), it must",
"from project(PA) by robot account(RA), it must be successful; 7.",
"by robot account(RA), it must be not successful; 9. Pull",
"Create private project(PA), private project(PB) and public project(PC) by user(UA);\"",
"from library.project import Project from library.repository import Repository from library.repository",
"has both pull and push priviliges;\" data = self.project.get_project_robot_account_by_id(TestProjects.project_ra_id_a, robot_id,",
"push_image_to_project from testutils import harbor_server from library.base import _assert_status_code class",
"ADMIN_CLIENT[\"password\"] user_ra_password = \"<PASSWORD>\" image_project_a = \"haproxy\" image_project_b = \"hello-world\"",
"from testutils import ADMIN_CLIENT from testutils import TEARDOWN from library.user",
"\"haproxy\" image_project_b = \"hello-world\" image_project_c = \"httpd\" image_robot_account = \"alpine\"",
"public project(PC) by user(UA); 3. Push image(ImagePA) to project(PA), image(ImagePB)",
"<PASSWORD>, **ADMIN_CLIENT) TestProjects.USER_RA_CLIENT=dict(endpoint = url, username = user_ra_name, password =",
"#3. Delete user(UA). self.user.delete_user(TestProjects.user_ra_id, **ADMIN_CLIENT) def testRobotAccount(self): \"\"\" Test case:",
"Project() self.user = User() self.repo = Repository() @classmethod def tearDown(self):",
"successful; 14. Push image(ImageRA) to project(PA) by robot account(RA), it",
"project(PB) and public project(PC) by user(UA);\" TestProjects.project_ra_id_a, TestProjects.project_ra_name_a = self.project.create_project(metadata",
"= <PASSWORD>, **ADMIN_CLIENT) TestProjects.USER_RA_CLIENT=dict(endpoint = url, username = user_ra_name, password",
"push privilige in project(PA) by user(UA); 5. Check robot account",
"print \"#1. Create user(UA);\" TestProjects.user_ra_id, user_ra_name = self.user.create_user(user_password = <PASSWORD>,",
"repository\") print \"#12. Update action property of robot account(RA);\" self.project.disable_project_robot_account(TestProjects.project_ra_id_a,",
"2. Create private project(PA), private project(PB) and public project(PC) by",
"must be successful; 7. Push image(ImageRA) to project(PA) by robot",
"test_ClearData(self): #1. Delete repository(RA) by user(UA); self.repo.delete_repoitory(TestProjects.project_ra_name_a, TestProjects.repo_name_in_project_a.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_b,",
"user(UA). self.user.delete_user(TestProjects.user_ra_id, **ADMIN_CLIENT) def testRobotAccount(self): \"\"\" Test case: Robot Account",
"action property of robot account(RA); 13. Pull image(ImagePA) from project(PA)",
"robot account(RA), it must be not successful; 14. Push image(ImageRA)",
"from library.repository import push_image_to_project from testutils import harbor_server from library.base",
"image_robot_account, tag) print \"#8. Push image(ImageRA) to project(PB) by robot",
"project(PB) by robot account(RA), it must be not successful;\" push_image_to_project(TestProjects.project_ra_name_b,",
"pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_a, tag_a) print \"#7. Push image(ImageRA) to",
"by user(UA); 5. Check robot account info, it should has",
"by robot account(RA), it must be not successful;\" push_image_to_project(TestProjects.project_ra_name_c, harbor_server,",
"Create user(UA); 2. Create private project(PA), private project(PB) and public",
"import push_image_to_project from testutils import harbor_server from library.base import _assert_status_code",
"__future__ import absolute_import import unittest from testutils import ADMIN_CLIENT from",
"Robot Account Test step and expected result: 1. Create user(UA);",
"with pull and push privilige in project(PA) by user(UA); 5.",
"from project(PA) by robot account(RA), it must be not successful;",
"TestProjects.project_ra_name_c = self.project.create_project(metadata = {\"public\": \"true\"}, **TestProjects.USER_RA_CLIENT) print \"#3. Push",
"{\"public\": \"false\"}, **TestProjects.USER_RA_CLIENT) TestProjects.project_ra_id_c, TestProjects.project_ra_name_c = self.project.create_project(metadata = {\"public\": \"true\"},",
"must be not successful; 12. Update action property of robot",
"5. Check robot account info, it should has both pull",
"be not successful;\" push_image_to_project(TestProjects.project_ra_name_c, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag, expected_error_message",
"image_project_a = \"haproxy\" image_project_b = \"hello-world\" image_project_c = \"httpd\" image_robot_account",
"image from project(PC), it must be successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token,",
"and push priviliges; 6. Pull image(ImagePA) from project(PA) by robot",
"erased.\") def test_ClearData(self): #1. Delete repository(RA) by user(UA); self.repo.delete_repoitory(TestProjects.project_ra_name_a, TestProjects.repo_name_in_project_a.split('/')[1],",
"print robot_account.name print robot_account.token print \"#5. Check robot account info,",
"from testutils import TEARDOWN from library.user import User from library.project",
"testutils import harbor_server from library.base import _assert_status_code class TestProjects(unittest.TestCase): @classmethod",
"push priviliges; 6. Pull image(ImagePA) from project(PA) by robot account(RA),",
"image_robot_account, tag, expected_error_message = \"unauthorized to access repository\") print \"#12.",
"user_ra_name, user_ra_password, image_project_a, tag) TestProjects.repo_name_in_project_b, tag_b = push_image_to_project(TestProjects.project_ra_name_b, harbor_server, user_ra_name,",
"\"#12. Update action property of robot account(RA);\" self.project.disable_project_robot_account(TestProjects.project_ra_id_a, robot_id, True,",
"TestProjects.repo_name_in_project_a, tag_a, expected_login_error_message = \"unauthorized: authentication required\") print \"#14. Push",
"pull_harbor_image from library.repository import push_image_to_project from testutils import harbor_server from",
"robot_account.name, robot_account.token, TestProjects.repo_name_in_project_c, tag_c) print \"#11. Push image(ImageRA) to project(PC)",
"account(RA), it must be successful;\" TestProjects.repo_name_pa, _ = push_image_to_project(TestProjects.project_ra_name_a, harbor_server,",
"project(PA), private project(PB) and public project(PC) by user(UA); 3. Push",
"be successful; 7. Push image(ImageRA) to project(PA) by robot account(RA),",
"1. Create user(UA); 2. Create private project(PA), private project(PB) and",
"from project(PA) by robot account(RA), it must be successful;\" pull_harbor_image(harbor_server,",
"library.repository import pull_harbor_image from library.repository import push_image_to_project from testutils import",
"project(PA), private project(PB) and public project(PC) by user(UA);\" TestProjects.project_ra_id_a, TestProjects.project_ra_name_a",
"push privilige in project(PA) by user(UA);\" robot_id, robot_account = self.project.add_project_robot_account(TestProjects.project_ra_id_a,",
"project(PB) by robot account(RA), it must be not successful; 9.",
"**TestProjects.USER_RA_CLIENT) TestProjects.project_ra_id_b, TestProjects.project_ra_name_b = self.project.create_project(metadata = {\"public\": \"false\"}, **TestProjects.USER_RA_CLIENT) TestProjects.project_ra_id_c,",
"print \"Case completed\" @unittest.skipIf(TEARDOWN == False, \"Test data won't be",
"must be successful; 8. Push image(ImageRA) to project(PB) by robot",
"successful; 10. Pull image from project(PC), it must be successful;",
"TestProjects.project_ra_name_a = self.project.create_project(metadata = {\"public\": \"false\"}, **TestProjects.USER_RA_CLIENT) TestProjects.project_ra_id_b, TestProjects.project_ra_name_b =",
"= user_ra_name, password = <PASSWORD>) print \"#2. Create private project(PA),",
"= \"unauthorized to access repository\") print \"#12. Update action property",
"print \"#9. Pull image(ImagePB) from project(PB) by robot account(RA), it",
"project(PB) and image(ImagePC) to project(PC) by user(UA); 4. Create a",
"it must be not successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_a, tag_a,",
"account(RA), it must be not successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_a,",
"print \"#3. Push image(ImagePA) to project(PA), image(ImagePB) to project(PB) and",
"self.repo.delete_repoitory(TestProjects.project_ra_name_b, TestProjects.repo_name_in_project_b.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_c, TestProjects.repo_name_in_project_c.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_a, TestProjects.repo_name_pa.split('/')[1], **TestProjects.USER_RA_CLIENT) #2.",
"Update action property of robot account(RA);\" self.project.disable_project_robot_account(TestProjects.project_ra_id_a, robot_id, True, **TestProjects.USER_RA_CLIENT)",
"be not successful; 10. Pull image from project(PC), it must",
"14. Push image(ImageRA) to project(PA) by robot account(RA), it must",
"be not successful; 15. Delete robot account(RA), it must be",
"\"#10. Pull image from project(PC), it must be successful;\" pull_harbor_image(harbor_server,",
"image_project_b = \"hello-world\" image_project_c = \"httpd\" image_robot_account = \"alpine\" tag",
"harbor_server, robot_account.name, robot_account.token, image_robot_account, tag) print \"#8. Push image(ImageRA) to",
"Repository from library.repository import pull_harbor_image from library.repository import push_image_to_project from",
"case: Robot Account Test step and expected result: 1. Create",
"authentication required\") print \"#15. Delete robot account(RA), it must be",
"== False, \"Test data won't be erased.\") def test_ClearData(self): #1.",
"Push image(ImageRA) to project(PC) by robot account(RA), it must be",
"print \"#4. Create a new robot account(RA) with pull and",
"expected_error_message = \"unauthorized to access repository\") print \"#9. Pull image(ImagePB)",
"\"#5. Check robot account info, it should has both pull",
"not successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_a, tag_a, expected_login_error_message = \"unauthorized:",
"expected_login_error_message = \"unauthorized: authentication required\") print \"#15. Delete robot account(RA),",
"Delete robot account(RA), it must be not successful.\" self.project.delete_project_robot_account(TestProjects.project_ra_id_a, robot_id,",
"by user(UA);\" robot_id, robot_account = self.project.add_project_robot_account(TestProjects.project_ra_id_a, TestProjects.project_ra_name_a, 2441000531 ,**TestProjects.USER_RA_CLIENT) print",
"must be not successful; 15. Delete robot account(RA), it must",
"tag, expected_error_message = \"unauthorized to access repository\") print \"#12. Update",
"TestProjects.user_ra_id, user_ra_name = self.user.create_user(user_password = <PASSWORD>, **ADMIN_CLIENT) TestProjects.USER_RA_CLIENT=dict(endpoint = url,",
"robot account(RA), it must be not successful; 12. Update action",
"**TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_a, TestProjects.repo_name_pa.split('/')[1], **TestProjects.USER_RA_CLIENT) #2. Delete project(PA); self.project.delete_project(TestProjects.project_ra_id_a, **TestProjects.USER_RA_CLIENT) self.project.delete_project(TestProjects.project_ra_id_b,",
"tag) TestProjects.repo_name_in_project_c, tag_c = push_image_to_project(TestProjects.project_ra_name_c, harbor_server, user_ra_name, user_ra_password, image_project_c, tag)",
"it must be successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_a, tag_a) print",
"account(RA), it must be not successful.\" self.project.delete_project_robot_account(TestProjects.project_ra_id_a, robot_id, **TestProjects.USER_RA_CLIENT) if",
"\"unauthorized: authentication required\") print \"#15. Delete robot account(RA), it must",
"account(RA), it must be not successful; 10. Pull image from",
"robot account(RA), it must be not successful;\" push_image_to_project(TestProjects.project_ra_name_c, harbor_server, robot_account.name,",
"should has both pull and push priviliges;\" data = self.project.get_project_robot_account_by_id(TestProjects.project_ra_id_a,",
"**TestProjects.USER_RA_CLIENT) TestProjects.project_ra_id_c, TestProjects.project_ra_name_c = self.project.create_project(metadata = {\"public\": \"true\"}, **TestProjects.USER_RA_CLIENT) print",
"robot_account.token, TestProjects.repo_name_in_project_b, tag_b, expected_error_message = \"unauthorized to access repository\") print",
"import absolute_import import unittest from testutils import ADMIN_CLIENT from testutils",
"_assert_status_code(robot_account.name, data.name) print \"#6. Pull image(ImagePA) from project(PA) by robot",
"to access repository\") print \"#12. Update action property of robot",
"must be not successful. Tear down: 1. Delete repository(RA) by",
"repository\") print \"#10. Pull image from project(PC), it must be",
"password = <PASSWORD>) print \"#2. Create private project(PA), private project(PB)",
"robot_id, robot_account = self.project.add_project_robot_account(TestProjects.project_ra_id_a, TestProjects.project_ra_name_a, 2441000531 ,**TestProjects.USER_RA_CLIENT) print robot_account.name print",
"privilige in project(PA) by user(UA); 5. Check robot account info,",
"to project(PB) and image(ImagePC) to project(PC) by user(UA);\" TestProjects.repo_name_in_project_a, tag_a",
"def setUp(self): self.project = Project() self.user = User() self.repo =",
"successful. Tear down: 1. Delete repository(RA) by user(UA); 2. Delete",
"= \"httpd\" image_robot_account = \"alpine\" tag = \"latest\" print \"#1.",
"Push image(ImageRA) to project(PB) by robot account(RA), it must be",
"harbor_server, robot_account.name, robot_account.token, image_robot_account, tag, expected_login_error_message = \"unauthorized: authentication required\")",
"def testRobotAccount(self): \"\"\" Test case: Robot Account Test step and",
"\"alpine\" tag = \"latest\" print \"#1. Create user(UA);\" TestProjects.user_ra_id, user_ra_name",
"it must be not successful. Tear down: 1. Delete repository(RA)",
"testutils import ADMIN_CLIENT from testutils import TEARDOWN from library.user import",
"should has both pull and push priviliges; 6. Pull image(ImagePA)",
"= self.project.create_project(metadata = {\"public\": \"true\"}, **TestProjects.USER_RA_CLIENT) print \"#3. Push image(ImagePA)",
"Delete repository(RA) by user(UA); self.repo.delete_repoitory(TestProjects.project_ra_name_a, TestProjects.repo_name_in_project_a.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_b, TestProjects.repo_name_in_project_b.split('/')[1], **TestProjects.USER_RA_CLIENT)",
"expected_error_message = \"unauthorized to access repository\") print \"#10. Pull image",
"tag_c) print \"#11. Push image(ImageRA) to project(PC) by robot account(RA),",
"not successful; 12. Update action property of robot account(RA); 13.",
"account(RA);\" self.project.disable_project_robot_account(TestProjects.project_ra_id_a, robot_id, True, **TestProjects.USER_RA_CLIENT) print \"#13. Pull image(ImagePA) from",
"from project(PC), it must be successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_c,",
"print \"#13. Pull image(ImagePA) from project(PA) by robot account(RA), it",
"and public project(PC) by user(UA); 3. Push image(ImagePA) to project(PA),",
"\"#1. Create user(UA);\" TestProjects.user_ra_id, user_ra_name = self.user.create_user(user_password = <PASSWORD>, **ADMIN_CLIENT)",
"by robot account(RA), it must be not successful; 15. Delete",
"project(PC) by user(UA);\" TestProjects.project_ra_id_a, TestProjects.project_ra_name_a = self.project.create_project(metadata = {\"public\": \"false\"},",
"of robot account(RA); 13. Pull image(ImagePA) from project(PA) by robot",
"pull and push privilige in project(PA) by user(UA);\" robot_id, robot_account",
"from testutils import harbor_server from library.base import _assert_status_code class TestProjects(unittest.TestCase):",
"robot account(RA), it must be not successful; 9. Pull image(ImagePB)",
"admin_password = ADMIN_CLIENT[\"password\"] user_ra_password = \"<PASSWORD>\" image_project_a = \"haproxy\" image_project_b",
"url = ADMIN_CLIENT[\"endpoint\"] admin_name = ADMIN_CLIENT[\"username\"] admin_password = ADMIN_CLIENT[\"password\"] user_ra_password",
"TestProjects.USER_RA_CLIENT=dict(endpoint = url, username = user_ra_name, password = <PASSWORD>) print",
"TestProjects.repo_name_in_project_b, tag_b, expected_error_message = \"unauthorized to access repository\") print \"#10.",
"self.project.delete_project(TestProjects.project_ra_id_b, **TestProjects.USER_RA_CLIENT) self.project.delete_project(TestProjects.project_ra_id_c, **TestProjects.USER_RA_CLIENT) #3. Delete user(UA). self.user.delete_user(TestProjects.user_ra_id, **ADMIN_CLIENT) def",
"_assert_status_code class TestProjects(unittest.TestCase): @classmethod def setUp(self): self.project = Project() self.user",
"project(PA), image(ImagePB) to project(PB) and image(ImagePC) to project(PC) by user(UA);",
"Test step and expected result: 1. Create user(UA); 2. Create",
"and public project(PC) by user(UA);\" TestProjects.project_ra_id_a, TestProjects.project_ra_name_a = self.project.create_project(metadata =",
"image(ImageRA) to project(PA) by robot account(RA), it must be successful;\"",
"robot account(RA), it must be successful; 8. Push image(ImageRA) to",
"it must be not successful; 10. Pull image from project(PC),",
"\"false\"}, **TestProjects.USER_RA_CLIENT) TestProjects.project_ra_id_c, TestProjects.project_ra_name_c = self.project.create_project(metadata = {\"public\": \"true\"}, **TestProjects.USER_RA_CLIENT)",
"Delete project(PA); self.project.delete_project(TestProjects.project_ra_id_a, **TestProjects.USER_RA_CLIENT) self.project.delete_project(TestProjects.project_ra_id_b, **TestProjects.USER_RA_CLIENT) self.project.delete_project(TestProjects.project_ra_id_c, **TestProjects.USER_RA_CLIENT) #3. Delete",
"user(UA); 2. Delete project(PA); 3. Delete user(UA). \"\"\" url =",
"pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_b, tag_b, expected_error_message = \"unauthorized to access",
"project(PB) by robot account(RA), it must be not successful;\" pull_harbor_image(harbor_server,",
"it should has both pull and push priviliges;\" data =",
"from library.user import User from library.project import Project from library.repository",
"not successful;\" push_image_to_project(TestProjects.project_ra_name_b, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag, expected_error_message =",
"private project(PB) and public project(PC) by user(UA); 3. Push image(ImagePA)",
"by user(UA); self.repo.delete_repoitory(TestProjects.project_ra_name_a, TestProjects.repo_name_in_project_a.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_b, TestProjects.repo_name_in_project_b.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_c, TestProjects.repo_name_in_project_c.split('/')[1],",
"not successful; 9. Pull image(ImagePB) from project(PB) by robot account(RA),",
"\"#6. Pull image(ImagePA) from project(PA) by robot account(RA), it must",
"testRobotAccount(self): \"\"\" Test case: Robot Account Test step and expected",
"push_image_to_project(TestProjects.project_ra_name_c, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag, expected_error_message = \"unauthorized to",
"robot_account.name, robot_account.token, TestProjects.repo_name_in_project_a, tag_a) print \"#7. Push image(ImageRA) to project(PA)",
"from project(PA) by robot account(RA), it must be not successful;\"",
"import unittest from testutils import ADMIN_CLIENT from testutils import TEARDOWN",
"image(ImageRA) to project(PA) by robot account(RA), it must be not",
"import harbor_server from library.base import _assert_status_code class TestProjects(unittest.TestCase): @classmethod def",
"= \"<PASSWORD>\" image_project_a = \"haproxy\" image_project_b = \"hello-world\" image_project_c =",
"by robot account(RA), it must be not successful; 10. Pull",
"and push privilige in project(PA) by user(UA); 5. Check robot",
"robot_id, True, **TestProjects.USER_RA_CLIENT) print \"#13. Pull image(ImagePA) from project(PA) by",
"private project(PA), private project(PB) and public project(PC) by user(UA);\" TestProjects.project_ra_id_a,",
"tearDown(self): print \"Case completed\" @unittest.skipIf(TEARDOWN == False, \"Test data won't",
"import ADMIN_CLIENT from testutils import TEARDOWN from library.user import User",
"robot_account.token, TestProjects.repo_name_in_project_a, tag_a) print \"#7. Push image(ImageRA) to project(PA) by",
"from library.base import _assert_status_code class TestProjects(unittest.TestCase): @classmethod def setUp(self): self.project",
"account(RA), it must be not successful; 15. Delete robot account(RA),",
"account(RA), it must be not successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_b,",
"project(PA) by robot account(RA), it must be not successful; 14.",
"pull and push priviliges;\" data = self.project.get_project_robot_account_by_id(TestProjects.project_ra_id_a, robot_id, **TestProjects.USER_RA_CLIENT) _assert_status_code(robot_account.name,",
"image_robot_account, tag, expected_error_message = \"unauthorized to access repository\") print \"#9.",
"project(PA) by robot account(RA), it must be successful; 8. Push",
"TestProjects(unittest.TestCase): @classmethod def setUp(self): self.project = Project() self.user = User()",
"= \"unauthorized: authentication required\") print \"#15. Delete robot account(RA), it",
"4. Create a new robot account(RA) with pull and push",
"def test_ClearData(self): #1. Delete repository(RA) by user(UA); self.repo.delete_repoitory(TestProjects.project_ra_name_a, TestProjects.repo_name_in_project_a.split('/')[1], **TestProjects.USER_RA_CLIENT)",
"harbor_server from library.base import _assert_status_code class TestProjects(unittest.TestCase): @classmethod def setUp(self):",
"= \"alpine\" tag = \"latest\" print \"#1. Create user(UA);\" TestProjects.user_ra_id,",
"User() self.repo = Repository() @classmethod def tearDown(self): print \"Case completed\"",
"project(PC), it must be successful; 11. Push image(ImageRA) to project(PC)",
"@unittest.skipIf(TEARDOWN == False, \"Test data won't be erased.\") def test_ClearData(self):",
"\"unauthorized to access repository\") print \"#9. Pull image(ImagePB) from project(PB)",
"must be not successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_b, tag_b, expected_error_message",
"project(PA) by robot account(RA), it must be not successful;\" pull_harbor_image(harbor_server,",
"required\") print \"#14. Push image(ImageRA) to project(PA) by robot account(RA),",
"library.repository import push_image_to_project from testutils import harbor_server from library.base import",
"_ = push_image_to_project(TestProjects.project_ra_name_a, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag) print \"#8.",
"import Repository from library.repository import pull_harbor_image from library.repository import push_image_to_project",
"robot_id, **TestProjects.USER_RA_CLIENT) _assert_status_code(robot_account.name, data.name) print \"#6. Pull image(ImagePA) from project(PA)",
"tag_b = push_image_to_project(TestProjects.project_ra_name_b, harbor_server, user_ra_name, user_ra_password, image_project_b, tag) TestProjects.repo_name_in_project_c, tag_c",
"self.project.add_project_robot_account(TestProjects.project_ra_id_a, TestProjects.project_ra_name_a, 2441000531 ,**TestProjects.USER_RA_CLIENT) print robot_account.name print robot_account.token print \"#5.",
"= \"unauthorized to access repository\") print \"#10. Pull image from",
"print \"#10. Pull image from project(PC), it must be successful;\"",
"project(PC) by user(UA);\" TestProjects.repo_name_in_project_a, tag_a = push_image_to_project(TestProjects.project_ra_name_a, harbor_server, user_ra_name, user_ra_password,",
"new robot account(RA) with pull and push privilige in project(PA)",
"Delete project(PA); 3. Delete user(UA). \"\"\" url = ADMIN_CLIENT[\"endpoint\"] admin_name",
"it must be not successful; 9. Pull image(ImagePB) from project(PB)",
"by user(UA); 4. Create a new robot account(RA) with pull",
"TestProjects.repo_name_pa, _ = push_image_to_project(TestProjects.project_ra_name_a, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag) print",
"Delete user(UA). \"\"\" url = ADMIN_CLIENT[\"endpoint\"] admin_name = ADMIN_CLIENT[\"username\"] admin_password",
"= \"hello-world\" image_project_c = \"httpd\" image_robot_account = \"alpine\" tag =",
"robot_account = self.project.add_project_robot_account(TestProjects.project_ra_id_a, TestProjects.project_ra_name_a, 2441000531 ,**TestProjects.USER_RA_CLIENT) print robot_account.name print robot_account.token",
"**TestProjects.USER_RA_CLIENT) self.project.delete_project(TestProjects.project_ra_id_b, **TestProjects.USER_RA_CLIENT) self.project.delete_project(TestProjects.project_ra_id_c, **TestProjects.USER_RA_CLIENT) #3. Delete user(UA). self.user.delete_user(TestProjects.user_ra_id, **ADMIN_CLIENT)",
"library.repository import Repository from library.repository import pull_harbor_image from library.repository import",
"user(UA);\" TestProjects.user_ra_id, user_ra_name = self.user.create_user(user_password = <PASSWORD>, **ADMIN_CLIENT) TestProjects.USER_RA_CLIENT=dict(endpoint =",
"with pull and push privilige in project(PA) by user(UA);\" robot_id,",
"user_ra_name, password = <PASSWORD>) print \"#2. Create private project(PA), private",
"must be not successful;\" push_image_to_project(TestProjects.project_ra_name_a, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag,",
"\"true\"}, **TestProjects.USER_RA_CLIENT) print \"#3. Push image(ImagePA) to project(PA), image(ImagePB) to",
"priviliges; 6. Pull image(ImagePA) from project(PA) by robot account(RA), it",
"absolute_import import unittest from testutils import ADMIN_CLIENT from testutils import",
"result: 1. Create user(UA); 2. Create private project(PA), private project(PB)",
"must be successful;\" TestProjects.repo_name_pa, _ = push_image_to_project(TestProjects.project_ra_name_a, harbor_server, robot_account.name, robot_account.token,",
"private project(PB) and public project(PC) by user(UA);\" TestProjects.project_ra_id_a, TestProjects.project_ra_name_a =",
"expected_error_message = \"unauthorized to access repository\") print \"#12. Update action",
"successful;\" push_image_to_project(TestProjects.project_ra_name_a, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag, expected_login_error_message = \"unauthorized:",
"expected_login_error_message = \"unauthorized: authentication required\") print \"#14. Push image(ImageRA) to",
"privilige in project(PA) by user(UA);\" robot_id, robot_account = self.project.add_project_robot_account(TestProjects.project_ra_id_a, TestProjects.project_ra_name_a,",
"self.project.create_project(metadata = {\"public\": \"false\"}, **TestProjects.USER_RA_CLIENT) TestProjects.project_ra_id_c, TestProjects.project_ra_name_c = self.project.create_project(metadata =",
"push_image_to_project(TestProjects.project_ra_name_a, harbor_server, user_ra_name, user_ra_password, image_project_a, tag) TestProjects.repo_name_in_project_b, tag_b = push_image_to_project(TestProjects.project_ra_name_b,",
"**TestProjects.USER_RA_CLIENT) #2. Delete project(PA); self.project.delete_project(TestProjects.project_ra_id_a, **TestProjects.USER_RA_CLIENT) self.project.delete_project(TestProjects.project_ra_id_b, **TestProjects.USER_RA_CLIENT) self.project.delete_project(TestProjects.project_ra_id_c, **TestProjects.USER_RA_CLIENT)",
"data = self.project.get_project_robot_account_by_id(TestProjects.project_ra_id_a, robot_id, **TestProjects.USER_RA_CLIENT) _assert_status_code(robot_account.name, data.name) print \"#6. Pull",
"\"#13. Pull image(ImagePA) from project(PA) by robot account(RA), it must",
"robot_account.token, image_robot_account, tag, expected_login_error_message = \"unauthorized: authentication required\") print \"#15.",
"must be not successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_a, tag_a, expected_login_error_message",
"it must be successful; 11. Push image(ImageRA) to project(PC) by",
"Pull image from project(PC), it must be successful;\" pull_harbor_image(harbor_server, robot_account.name,",
"it must be not successful;\" push_image_to_project(TestProjects.project_ra_name_a, harbor_server, robot_account.name, robot_account.token, image_robot_account,",
"self.project.delete_project(TestProjects.project_ra_id_c, **TestProjects.USER_RA_CLIENT) #3. Delete user(UA). self.user.delete_user(TestProjects.user_ra_id, **ADMIN_CLIENT) def testRobotAccount(self): \"\"\"",
"False, \"Test data won't be erased.\") def test_ClearData(self): #1. Delete",
"TestProjects.project_ra_id_c, TestProjects.project_ra_name_c = self.project.create_project(metadata = {\"public\": \"true\"}, **TestProjects.USER_RA_CLIENT) print \"#3.",
"9. Pull image(ImagePB) from project(PB) by robot account(RA), it must",
"to access repository\") print \"#9. Pull image(ImagePB) from project(PB) by",
"project(PA), image(ImagePB) to project(PB) and image(ImagePC) to project(PC) by user(UA);\"",
"user(UA);\" TestProjects.repo_name_in_project_a, tag_a = push_image_to_project(TestProjects.project_ra_name_a, harbor_server, user_ra_name, user_ra_password, image_project_a, tag)",
"user(UA); self.repo.delete_repoitory(TestProjects.project_ra_name_a, TestProjects.repo_name_in_project_a.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_b, TestProjects.repo_name_in_project_b.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_c, TestProjects.repo_name_in_project_c.split('/')[1], **TestProjects.USER_RA_CLIENT)",
"private project(PA), private project(PB) and public project(PC) by user(UA); 3.",
"print \"#2. Create private project(PA), private project(PB) and public project(PC)",
"image(ImagePC) to project(PC) by user(UA); 4. Create a new robot",
"project(PA) by user(UA); 5. Check robot account info, it should",
"must be not successful;\" push_image_to_project(TestProjects.project_ra_name_c, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag,",
"library.project import Project from library.repository import Repository from library.repository import",
"13. Pull image(ImagePA) from project(PA) by robot account(RA), it must",
"project(PC) by robot account(RA), it must be not successful; 12.",
"print \"#6. Pull image(ImagePA) from project(PA) by robot account(RA), it",
"tag) print \"#8. Push image(ImageRA) to project(PB) by robot account(RA),",
"robot account(RA), it must be not successful;\" push_image_to_project(TestProjects.project_ra_name_a, harbor_server, robot_account.name,",
"Account Test step and expected result: 1. Create user(UA); 2.",
"to project(PA) by robot account(RA), it must be not successful;",
"TestProjects.repo_name_in_project_b.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_c, TestProjects.repo_name_in_project_c.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_a, TestProjects.repo_name_pa.split('/')[1], **TestProjects.USER_RA_CLIENT) #2. Delete",
"\"#15. Delete robot account(RA), it must be not successful.\" self.project.delete_project_robot_account(TestProjects.project_ra_id_a,",
"**TestProjects.USER_RA_CLIENT) self.project.delete_project(TestProjects.project_ra_id_c, **TestProjects.USER_RA_CLIENT) #3. Delete user(UA). self.user.delete_user(TestProjects.user_ra_id, **ADMIN_CLIENT) def testRobotAccount(self):",
"project(PA); 3. Delete user(UA). \"\"\" url = ADMIN_CLIENT[\"endpoint\"] admin_name =",
"project(PA) by robot account(RA), it must be successful; 7. Push",
"be not successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_b, tag_b, expected_error_message =",
"print \"#11. Push image(ImageRA) to project(PC) by robot account(RA), it",
"robot_account.token print \"#5. Check robot account info, it should has",
"\"#11. Push image(ImageRA) to project(PC) by robot account(RA), it must",
"tag) TestProjects.repo_name_in_project_b, tag_b = push_image_to_project(TestProjects.project_ra_name_b, harbor_server, user_ra_name, user_ra_password, image_project_b, tag)",
"account(RA), it must be successful; 8. Push image(ImageRA) to project(PB)",
"must be successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_c, tag_c) print \"#11.",
"**TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_c, TestProjects.repo_name_in_project_c.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_a, TestProjects.repo_name_pa.split('/')[1], **TestProjects.USER_RA_CLIENT) #2. Delete project(PA);",
"project(PB) and image(ImagePC) to project(PC) by user(UA);\" TestProjects.repo_name_in_project_a, tag_a =",
"TestProjects.project_ra_id_a, TestProjects.project_ra_name_a = self.project.create_project(metadata = {\"public\": \"false\"}, **TestProjects.USER_RA_CLIENT) TestProjects.project_ra_id_b, TestProjects.project_ra_name_b",
"robot account(RA), it must be not successful; 15. Delete robot",
"must be successful; 11. Push image(ImageRA) to project(PC) by robot",
"won't be erased.\") def test_ClearData(self): #1. Delete repository(RA) by user(UA);",
"**TestProjects.USER_RA_CLIENT) _assert_status_code(robot_account.name, data.name) print \"#6. Pull image(ImagePA) from project(PA) by",
"user(UA); 5. Check robot account info, it should has both",
"by robot account(RA), it must be not successful; 12. Update",
"**TestProjects.USER_RA_CLIENT) print \"#13. Pull image(ImagePA) from project(PA) by robot account(RA),",
"**TestProjects.USER_RA_CLIENT) #3. Delete user(UA). self.user.delete_user(TestProjects.user_ra_id, **ADMIN_CLIENT) def testRobotAccount(self): \"\"\" Test",
"public project(PC) by user(UA);\" TestProjects.project_ra_id_a, TestProjects.project_ra_name_a = self.project.create_project(metadata = {\"public\":",
"2441000531 ,**TestProjects.USER_RA_CLIENT) print robot_account.name print robot_account.token print \"#5. Check robot",
"tag_a) print \"#7. Push image(ImageRA) to project(PA) by robot account(RA),",
"pull and push privilige in project(PA) by user(UA); 5. Check",
"harbor_server, user_ra_name, user_ra_password, image_project_b, tag) TestProjects.repo_name_in_project_c, tag_c = push_image_to_project(TestProjects.project_ra_name_c, harbor_server,",
"must be not successful.\" self.project.delete_project_robot_account(TestProjects.project_ra_id_a, robot_id, **TestProjects.USER_RA_CLIENT) if __name__ ==",
"\"unauthorized: authentication required\") print \"#14. Push image(ImageRA) to project(PA) by",
"robot account(RA), it must be not successful.\" self.project.delete_project_robot_account(TestProjects.project_ra_id_a, robot_id, **TestProjects.USER_RA_CLIENT)",
"ADMIN_CLIENT[\"username\"] admin_password = ADMIN_CLIENT[\"password\"] user_ra_password = \"<PASSWORD>\" image_project_a = \"haproxy\"",
"user(UA). \"\"\" url = ADMIN_CLIENT[\"endpoint\"] admin_name = ADMIN_CLIENT[\"username\"] admin_password =",
"successful;\" TestProjects.repo_name_pa, _ = push_image_to_project(TestProjects.project_ra_name_a, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag)",
"image_project_c = \"httpd\" image_robot_account = \"alpine\" tag = \"latest\" print",
"repository(RA) by user(UA); self.repo.delete_repoitory(TestProjects.project_ra_name_a, TestProjects.repo_name_in_project_a.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_b, TestProjects.repo_name_in_project_b.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_c,",
"access repository\") print \"#10. Pull image from project(PC), it must",
"by robot account(RA), it must be successful; 8. Push image(ImageRA)",
"to project(PA) by robot account(RA), it must be successful; 8.",
"by robot account(RA), it must be successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token,",
"admin_name = ADMIN_CLIENT[\"username\"] admin_password = ADMIN_CLIENT[\"password\"] user_ra_password = \"<PASSWORD>\" image_project_a",
"project(PB) by robot account(RA), it must be not successful; 10.",
"user(UA);\" robot_id, robot_account = self.project.add_project_robot_account(TestProjects.project_ra_id_a, TestProjects.project_ra_name_a, 2441000531 ,**TestProjects.USER_RA_CLIENT) print robot_account.name",
"repository(RA) by user(UA); 2. Delete project(PA); 3. Delete user(UA). \"\"\"",
"it must be not successful; 15. Delete robot account(RA), it",
"successful; 12. Update action property of robot account(RA); 13. Pull",
"ADMIN_CLIENT from testutils import TEARDOWN from library.user import User from",
"tag, expected_error_message = \"unauthorized to access repository\") print \"#9. Pull",
"**ADMIN_CLIENT) def testRobotAccount(self): \"\"\" Test case: Robot Account Test step",
"Create private project(PA), private project(PB) and public project(PC) by user(UA);",
"project(PA) by robot account(RA), it must be not successful; 15.",
"robot account info, it should has both pull and push",
"\"httpd\" image_robot_account = \"alpine\" tag = \"latest\" print \"#1. Create",
"TestProjects.repo_name_in_project_c, tag_c) print \"#11. Push image(ImageRA) to project(PC) by robot",
"10. Pull image from project(PC), it must be successful; 11.",
"successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_b, tag_b, expected_error_message = \"unauthorized to",
"by robot account(RA), it must be not successful;\" push_image_to_project(TestProjects.project_ra_name_a, harbor_server,",
"by robot account(RA), it must be successful; 7. Push image(ImageRA)",
"\"unauthorized to access repository\") print \"#10. Pull image from project(PC),",
"be not successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_a, tag_a, expected_login_error_message =",
"from library.repository import Repository from library.repository import pull_harbor_image from library.repository",
"robot account(RA), it must be not successful;\" push_image_to_project(TestProjects.project_ra_name_b, harbor_server, robot_account.name,",
"by user(UA); 2. Delete project(PA); 3. Delete user(UA). \"\"\" url",
"{\"public\": \"false\"}, **TestProjects.USER_RA_CLIENT) TestProjects.project_ra_id_b, TestProjects.project_ra_name_b = self.project.create_project(metadata = {\"public\": \"false\"},",
"robot account(RA), it must be not successful. Tear down: 1.",
"12. Update action property of robot account(RA); 13. Pull image(ImagePA)",
"account(RA), it must be not successful. Tear down: 1. Delete",
"robot account(RA), it must be successful;\" TestProjects.repo_name_pa, _ = push_image_to_project(TestProjects.project_ra_name_a,",
"\"#7. Push image(ImageRA) to project(PA) by robot account(RA), it must",
"to project(PC) by user(UA);\" TestProjects.repo_name_in_project_a, tag_a = push_image_to_project(TestProjects.project_ra_name_a, harbor_server, user_ra_name,",
"robot_account.name, robot_account.token, TestProjects.repo_name_in_project_b, tag_b, expected_error_message = \"unauthorized to access repository\")",
"tag, expected_login_error_message = \"unauthorized: authentication required\") print \"#15. Delete robot",
"harbor_server, user_ra_name, user_ra_password, image_project_a, tag) TestProjects.repo_name_in_project_b, tag_b = push_image_to_project(TestProjects.project_ra_name_b, harbor_server,",
"project(PA) by robot account(RA), it must be successful;\" TestProjects.repo_name_pa, _",
"action property of robot account(RA);\" self.project.disable_project_robot_account(TestProjects.project_ra_id_a, robot_id, True, **TestProjects.USER_RA_CLIENT) print",
"by user(UA); 3. Push image(ImagePA) to project(PA), image(ImagePB) to project(PB)",
"Pull image(ImagePA) from project(PA) by robot account(RA), it must be",
"it must be not successful;\" push_image_to_project(TestProjects.project_ra_name_b, harbor_server, robot_account.name, robot_account.token, image_robot_account,",
"must be not successful; 14. Push image(ImageRA) to project(PA) by",
",**TestProjects.USER_RA_CLIENT) print robot_account.name print robot_account.token print \"#5. Check robot account",
"and expected result: 1. Create user(UA); 2. Create private project(PA),",
"user_ra_password, image_project_a, tag) TestProjects.repo_name_in_project_b, tag_b = push_image_to_project(TestProjects.project_ra_name_b, harbor_server, user_ra_name, user_ra_password,",
"from __future__ import absolute_import import unittest from testutils import ADMIN_CLIENT",
"repository\") print \"#9. Pull image(ImagePB) from project(PB) by robot account(RA),",
"account(RA); 13. Pull image(ImagePA) from project(PA) by robot account(RA), it",
"username = user_ra_name, password = <PASSWORD>) print \"#2. Create private",
"Update action property of robot account(RA); 13. Pull image(ImagePA) from",
"TestProjects.repo_name_in_project_c, tag_c = push_image_to_project(TestProjects.project_ra_name_c, harbor_server, user_ra_name, user_ra_password, image_project_c, tag) print",
"and image(ImagePC) to project(PC) by user(UA);\" TestProjects.repo_name_in_project_a, tag_a = push_image_to_project(TestProjects.project_ra_name_a,",
"account(RA), it must be not successful;\" push_image_to_project(TestProjects.project_ra_name_a, harbor_server, robot_account.name, robot_account.token,",
"\"#3. Push image(ImagePA) to project(PA), image(ImagePB) to project(PB) and image(ImagePC)",
"image(ImagePB) to project(PB) and image(ImagePC) to project(PC) by user(UA);\" TestProjects.repo_name_in_project_a,",
"self.project = Project() self.user = User() self.repo = Repository() @classmethod",
"= {\"public\": \"true\"}, **TestProjects.USER_RA_CLIENT) print \"#3. Push image(ImagePA) to project(PA),",
"by user(UA);\" TestProjects.repo_name_in_project_a, tag_a = push_image_to_project(TestProjects.project_ra_name_a, harbor_server, user_ra_name, user_ra_password, image_project_a,",
"must be successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_a, tag_a) print \"#7.",
"by robot account(RA), it must be not successful; 14. Push",
"\"unauthorized to access repository\") print \"#12. Update action property of",
"expected result: 1. Create user(UA); 2. Create private project(PA), private",
"account(RA) with pull and push privilige in project(PA) by user(UA);\"",
"**TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_b, TestProjects.repo_name_in_project_b.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_c, TestProjects.repo_name_in_project_c.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_a, TestProjects.repo_name_pa.split('/')[1], **TestProjects.USER_RA_CLIENT)",
"account(RA), it must be not successful; 12. Update action property",
"push_image_to_project(TestProjects.project_ra_name_a, harbor_server, robot_account.name, robot_account.token, image_robot_account, tag) print \"#8. Push image(ImageRA)",
"access repository\") print \"#12. Update action property of robot account(RA);\"",
"Push image(ImagePA) to project(PA), image(ImagePB) to project(PB) and image(ImagePC) to",
"#1. Delete repository(RA) by user(UA); self.repo.delete_repoitory(TestProjects.project_ra_name_a, TestProjects.repo_name_in_project_a.split('/')[1], **TestProjects.USER_RA_CLIENT) self.repo.delete_repoitory(TestProjects.project_ra_name_b, TestProjects.repo_name_in_project_b.split('/')[1],",
"import User from library.project import Project from library.repository import Repository",
"to project(PA) by robot account(RA), it must be not successful;\"",
"pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_a, tag_a, expected_login_error_message = \"unauthorized: authentication required\")",
"print \"#8. Push image(ImageRA) to project(PB) by robot account(RA), it",
"= self.project.get_project_robot_account_by_id(TestProjects.project_ra_id_a, robot_id, **TestProjects.USER_RA_CLIENT) _assert_status_code(robot_account.name, data.name) print \"#6. Pull image(ImagePA)",
"successful;\" pull_harbor_image(harbor_server, robot_account.name, robot_account.token, TestProjects.repo_name_in_project_a, tag_a) print \"#7. Push image(ImageRA)",
"robot_account.name, robot_account.token, image_robot_account, tag, expected_login_error_message = \"unauthorized: authentication required\") print",
"user(UA); 2. Create private project(PA), private project(PB) and public project(PC)",
"image(ImagePC) to project(PC) by user(UA);\" TestProjects.repo_name_in_project_a, tag_a = push_image_to_project(TestProjects.project_ra_name_a, harbor_server,",
"\"hello-world\" image_project_c = \"httpd\" image_robot_account = \"alpine\" tag = \"latest\"",
"self.repo.delete_repoitory(TestProjects.project_ra_name_a, TestProjects.repo_name_pa.split('/')[1], **TestProjects.USER_RA_CLIENT) #2. Delete project(PA); self.project.delete_project(TestProjects.project_ra_id_a, **TestProjects.USER_RA_CLIENT) self.project.delete_project(TestProjects.project_ra_id_b, **TestProjects.USER_RA_CLIENT)",
"= \"unauthorized: authentication required\") print \"#14. Push image(ImageRA) to project(PA)",
"= push_image_to_project(TestProjects.project_ra_name_c, harbor_server, user_ra_name, user_ra_password, image_project_c, tag) print \"#4. Create",
"from project(PB) by robot account(RA), it must be not successful;\"",
"15. Delete robot account(RA), it must be not successful. Tear",
"print \"#12. Update action property of robot account(RA);\" self.project.disable_project_robot_account(TestProjects.project_ra_id_a, robot_id,",
"library.base import _assert_status_code class TestProjects(unittest.TestCase): @classmethod def setUp(self): self.project =",
"Create user(UA);\" TestProjects.user_ra_id, user_ra_name = self.user.create_user(user_password = <PASSWORD>, **ADMIN_CLIENT) TestProjects.USER_RA_CLIENT=dict(endpoint"
] |
[
"import settings logger = logging.getLogger(__name__) class LocaleHelper: \"\"\"Helpers for converting",
"isinstance(my_locale, Locale): raise TypeError(\"my_locale must be a babel Locale object\")",
"UnknownLocaleError from babel.dates import format_datetime, format_time, format_date import pytz from",
"None, my_tz: pytz.BaseTzInfo = None, author_info: dict = None, )",
"self._locale @property def timezone(self) -> pytz.BaseTzInfo: return self._timezone def format_date_full_str(self,",
"@staticmethod def _determine_timezone( my_tz: pytz.BaseTzInfo = None, author_info: dict =",
"format_datetime(my_datetime, format=\"short\", locale=self.locale) def get_time_formatted_str(self, ts: int) -> str: \"\"\"return",
"format_datetime_str(self, my_datetime: dt.datetime) -> str: \"\"\"returns formated datetime string for",
"= None, my_tz: pytz.BaseTzInfo = None, author_info: dict = None,",
"-> pytz.BaseTzInfo: return self._timezone def format_date_full_str(self, my_datetime: dt.datetime) -> str:",
"using locale\"\"\" my_datetime = self.get_datetime_from_ts(ts) return format_time(my_datetime, format=\"short\", locale=self.locale) def",
"Locale.parse(author_info[\"locale\"], sep=\"-\") except UnknownLocaleError: logger.warning(\"Could not use locale info from",
"logging from babel import Locale, UnknownLocaleError from babel.dates import format_datetime,",
"else: my_tz = get_localzone() if not my_tz: my_tz = pytz.UTC",
"self.get_datetime_from_ts(ts) return format_datetime(my_datetime, format=\"short\", locale=self.locale) def get_time_formatted_str(self, ts: int) ->",
"def _determine_timezone( my_tz: pytz.BaseTzInfo = None, author_info: dict = None",
"Args: - my_locale: Primary locale to use - my_tz: Primary",
"None, author_info: dict = None ) -> pytz.BaseTzInfo: if my_tz:",
"not my_tz: my_tz = pytz.UTC return my_tz @property def locale(self)",
"= self._determine_timezone(my_tz, author_info) @staticmethod def _determine_locale(my_locale: Locale = None, author_info:",
"not my_locale: my_locale = Locale.parse(settings.FALLBACK_LOCALE) return my_locale @staticmethod def _determine_timezone(",
"my_locale and/or my_tz are not given \"\"\" self._locale = self._determine_locale(my_locale,",
"pytz.BaseTzInfo): raise TypeError(\"my_tz must be of type pytz\") else: if",
"and timezone to use from this Slack response if my_locale",
"my_tz = pytz.UTC return my_tz @property def locale(self) -> Locale:",
"must be a babel Locale object\") else: if author_info: try:",
"= None) -> Locale: if my_locale: if not isinstance(my_locale, Locale):",
"format=\"short\", locale=self.locale) def get_datetime_formatted_str(self, ts: int) -> str: \"\"\"return given",
"Locale object\") else: if author_info: try: my_locale = Locale.parse(author_info[\"locale\"], sep=\"-\")",
"format_date(my_datetime, format=\"full\", locale=self.locale) def format_datetime_str(self, my_datetime: dt.datetime) -> str: \"\"\"returns",
"raise TypeError(\"my_tz must be of type pytz\") else: if author_info:",
"return my_locale @staticmethod def _determine_timezone( my_tz: pytz.BaseTzInfo = None, author_info:",
"-> str: \"\"\"returns formated datetime string for given dt using",
"return self._locale @property def timezone(self) -> pytz.BaseTzInfo: return self._timezone def",
"from Slack\") my_locale = Locale.default() else: my_locale = Locale.default() if",
"use from this Slack response if my_locale and/or my_tz are",
"def get_datetime_formatted_str(self, ts: int) -> str: \"\"\"return given timestamp as",
"pytz.BaseTzInfo: return self._timezone def format_date_full_str(self, my_datetime: dt.datetime) -> str: return",
"locale\"\"\" return format_datetime(my_datetime, format=\"short\", locale=self.locale) def get_datetime_formatted_str(self, ts: int) ->",
"my_locale: if not isinstance(my_locale, Locale): raise TypeError(\"my_locale must be a",
"if author_info: try: my_tz = pytz.timezone(author_info[\"tz\"]) except pytz.exceptions.UnknownTimeZoneError: logger.warning(\"Could not",
"None) -> Locale: if my_locale: if not isinstance(my_locale, Locale): raise",
"from babel.dates import format_datetime, format_time, format_date import pytz from tzlocal",
"author_info: try: my_locale = Locale.parse(author_info[\"locale\"], sep=\"-\") except UnknownLocaleError: logger.warning(\"Could not",
"None, author_info: dict = None, ) -> None: \"\"\" Args:",
"None ) -> pytz.BaseTzInfo: if my_tz: if not isinstance(my_tz, pytz.BaseTzInfo):",
"locale and timezone to use from this Slack response if",
"= pytz.timezone(author_info[\"tz\"]) except pytz.exceptions.UnknownTimeZoneError: logger.warning(\"Could not use timezone info from",
"-> None: \"\"\" Args: - my_locale: Primary locale to use",
"if my_tz: if not isinstance(my_tz, pytz.BaseTzInfo): raise TypeError(\"my_tz must be",
") -> pytz.BaseTzInfo: if my_tz: if not isinstance(my_tz, pytz.BaseTzInfo): raise",
"if my_locale: if not isinstance(my_locale, Locale): raise TypeError(\"my_locale must be",
"ts: int) -> str: \"\"\"return given timestamp as formated datetime",
"import pytz from tzlocal import get_localzone from . import settings",
"are not given \"\"\" self._locale = self._determine_locale(my_locale, author_info) self._timezone =",
"raise TypeError(\"my_locale must be a babel Locale object\") else: if",
"author_info) self._timezone = self._determine_timezone(my_tz, author_info) @staticmethod def _determine_locale(my_locale: Locale =",
"format=\"short\", locale=self.locale) def get_datetime_from_ts(self, ts: int) -> dt.datetime: \"\"\"returns datetime",
"if not my_tz: my_tz = pytz.UTC return my_tz @property def",
"\"\"\"returns datetime object of a unix timestamp with local timezone\"\"\"",
"babel Locale object\") else: if author_info: try: my_locale = Locale.parse(author_info[\"locale\"],",
"datetime object of a unix timestamp with local timezone\"\"\" my_datetime",
"import format_datetime, format_time, format_date import pytz from tzlocal import get_localzone",
"a unix timestamp with local timezone\"\"\" my_datetime = dt.datetime.fromtimestamp(float(ts), pytz.UTC)",
"be of type pytz\") else: if author_info: try: my_tz =",
"and timezone\"\"\" def __init__( self, my_locale: Locale = None, my_tz:",
"type pytz\") else: if author_info: try: my_tz = pytz.timezone(author_info[\"tz\"]) except",
"dt.datetime) -> str: \"\"\"returns formated datetime string for given dt",
"Locale.parse(settings.FALLBACK_LOCALE) return my_locale @staticmethod def _determine_timezone( my_tz: pytz.BaseTzInfo = None,",
"dt.datetime) -> str: return format_date(my_datetime, format=\"full\", locale=self.locale) def format_datetime_str(self, my_datetime:",
"self._determine_locale(my_locale, author_info) self._timezone = self._determine_timezone(my_tz, author_info) @staticmethod def _determine_locale(my_locale: Locale",
"try: my_locale = Locale.parse(author_info[\"locale\"], sep=\"-\") except UnknownLocaleError: logger.warning(\"Could not use",
"my_locale = Locale.default() else: my_locale = Locale.default() if not my_locale:",
"locale info from Slack\") my_locale = Locale.default() else: my_locale =",
"string for given dt using locale\"\"\" return format_datetime(my_datetime, format=\"short\", locale=self.locale)",
"= None, author_info: dict = None, ) -> None: \"\"\"",
"\"\"\"return given timestamp as formated datetime string using locale\"\"\" my_datetime",
"dt.datetime: \"\"\"returns datetime object of a unix timestamp with local",
"= None, author_info: dict = None ) -> pytz.BaseTzInfo: if",
"= pytz.UTC return my_tz @property def locale(self) -> Locale: return",
"object\") else: if author_info: try: my_locale = Locale.parse(author_info[\"locale\"], sep=\"-\") except",
"current locale and timezone\"\"\" def __init__( self, my_locale: Locale =",
"settings logger = logging.getLogger(__name__) class LocaleHelper: \"\"\"Helpers for converting date",
"= Locale.parse(settings.FALLBACK_LOCALE) return my_locale @staticmethod def _determine_timezone( my_tz: pytz.BaseTzInfo =",
"be a babel Locale object\") else: if author_info: try: my_locale",
"None, ) -> None: \"\"\" Args: - my_locale: Primary locale",
"self._timezone = self._determine_timezone(my_tz, author_info) @staticmethod def _determine_locale(my_locale: Locale = None,",
"my_locale: Primary locale to use - my_tz: Primary timezone to",
"if author_info: try: my_locale = Locale.parse(author_info[\"locale\"], sep=\"-\") except UnknownLocaleError: logger.warning(\"Could",
"converting date & time according to current locale and timezone\"\"\"",
"else: my_locale = Locale.default() if not my_locale: my_locale = Locale.parse(settings.FALLBACK_LOCALE)",
"pytz.BaseTzInfo = None, author_info: dict = None, ) -> None:",
"format_datetime, format_time, format_date import pytz from tzlocal import get_localzone from",
"class LocaleHelper: \"\"\"Helpers for converting date & time according to",
"if my_locale and/or my_tz are not given \"\"\" self._locale =",
"datetime string for given dt using locale\"\"\" return format_datetime(my_datetime, format=\"short\",",
"return format_date(my_datetime, format=\"full\", locale=self.locale) def format_datetime_str(self, my_datetime: dt.datetime) -> str:",
"self.get_datetime_from_ts(ts) return format_time(my_datetime, format=\"short\", locale=self.locale) def get_datetime_from_ts(self, ts: int) ->",
"format_time, format_date import pytz from tzlocal import get_localzone from .",
"-> Locale: return self._locale @property def timezone(self) -> pytz.BaseTzInfo: return",
"get_datetime_from_ts(self, ts: int) -> dt.datetime: \"\"\"returns datetime object of a",
"_determine_timezone( my_tz: pytz.BaseTzInfo = None, author_info: dict = None )",
"int) -> dt.datetime: \"\"\"returns datetime object of a unix timestamp",
"of a unix timestamp with local timezone\"\"\" my_datetime = dt.datetime.fromtimestamp(float(ts),",
". import settings logger = logging.getLogger(__name__) class LocaleHelper: \"\"\"Helpers for",
"my_tz: pytz.BaseTzInfo = None, author_info: dict = None, ) ->",
"timestamp with local timezone\"\"\" my_datetime = dt.datetime.fromtimestamp(float(ts), pytz.UTC) return my_datetime.astimezone(self.timezone)",
"= self._determine_locale(my_locale, author_info) self._timezone = self._determine_timezone(my_tz, author_info) @staticmethod def _determine_locale(my_locale:",
"according to current locale and timezone\"\"\" def __init__( self, my_locale:",
"not isinstance(my_locale, Locale): raise TypeError(\"my_locale must be a babel Locale",
"def _determine_locale(my_locale: Locale = None, author_info: dict = None) ->",
"to use - author_info: locale and timezone to use from",
"my_datetime: dt.datetime) -> str: \"\"\"returns formated datetime string for given",
"@staticmethod def _determine_locale(my_locale: Locale = None, author_info: dict = None)",
"import Locale, UnknownLocaleError from babel.dates import format_datetime, format_time, format_date import",
"info from Slack\") my_tz = get_localzone() else: my_tz = get_localzone()",
"timezone to use from this Slack response if my_locale and/or",
"from Slack\") my_tz = get_localzone() else: my_tz = get_localzone() if",
"if not isinstance(my_locale, Locale): raise TypeError(\"my_locale must be a babel",
"None, author_info: dict = None) -> Locale: if my_locale: if",
"my_tz @property def locale(self) -> Locale: return self._locale @property def",
"pytz.UTC return my_tz @property def locale(self) -> Locale: return self._locale",
"from this Slack response if my_locale and/or my_tz are not",
"\"\"\"Helpers for converting date & time according to current locale",
"use - my_tz: Primary timezone to use - author_info: locale",
"pytz.BaseTzInfo = None, author_info: dict = None ) -> pytz.BaseTzInfo:",
"self._timezone def format_date_full_str(self, my_datetime: dt.datetime) -> str: return format_date(my_datetime, format=\"full\",",
"Primary locale to use - my_tz: Primary timezone to use",
"Locale = None, author_info: dict = None) -> Locale: if",
"format=\"short\", locale=self.locale) def get_time_formatted_str(self, ts: int) -> str: \"\"\"return given",
"else: if author_info: try: my_tz = pytz.timezone(author_info[\"tz\"]) except pytz.exceptions.UnknownTimeZoneError: logger.warning(\"Could",
"timezone\"\"\" def __init__( self, my_locale: Locale = None, my_tz: pytz.BaseTzInfo",
"logging.getLogger(__name__) class LocaleHelper: \"\"\"Helpers for converting date & time according",
"& time according to current locale and timezone\"\"\" def __init__(",
"string using locale\"\"\" my_datetime = self.get_datetime_from_ts(ts) return format_time(my_datetime, format=\"short\", locale=self.locale)",
"= Locale.default() else: my_locale = Locale.default() if not my_locale: my_locale",
"get_localzone() if not my_tz: my_tz = pytz.UTC return my_tz @property",
"str: \"\"\"return given timestamp as formated datetime string using locale\"\"\"",
"timestamp as formated datetime string using locale\"\"\" my_datetime = self.get_datetime_from_ts(ts)",
"and/or my_tz are not given \"\"\" self._locale = self._determine_locale(my_locale, author_info)",
"datetime as dt import logging from babel import Locale, UnknownLocaleError",
"my_tz: if not isinstance(my_tz, pytz.BaseTzInfo): raise TypeError(\"my_tz must be of",
"not use locale info from Slack\") my_locale = Locale.default() else:",
"= Locale.parse(author_info[\"locale\"], sep=\"-\") except UnknownLocaleError: logger.warning(\"Could not use locale info",
"get_datetime_formatted_str(self, ts: int) -> str: \"\"\"return given timestamp as formated",
"given dt using locale\"\"\" return format_datetime(my_datetime, format=\"short\", locale=self.locale) def get_datetime_formatted_str(self,",
"isinstance(my_tz, pytz.BaseTzInfo): raise TypeError(\"my_tz must be of type pytz\") else:",
"use locale info from Slack\") my_locale = Locale.default() else: my_locale",
"self._determine_timezone(my_tz, author_info) @staticmethod def _determine_locale(my_locale: Locale = None, author_info: dict",
"locale=self.locale) def get_time_formatted_str(self, ts: int) -> str: \"\"\"return given timestamp",
"my_tz: my_tz = pytz.UTC return my_tz @property def locale(self) ->",
"Locale: if my_locale: if not isinstance(my_locale, Locale): raise TypeError(\"my_locale must",
"format=\"full\", locale=self.locale) def format_datetime_str(self, my_datetime: dt.datetime) -> str: \"\"\"returns formated",
"my_locale: Locale = None, my_tz: pytz.BaseTzInfo = None, author_info: dict",
"of type pytz\") else: if author_info: try: my_tz = pytz.timezone(author_info[\"tz\"])",
"my_locale @staticmethod def _determine_timezone( my_tz: pytz.BaseTzInfo = None, author_info: dict",
"if not isinstance(my_tz, pytz.BaseTzInfo): raise TypeError(\"my_tz must be of type",
"get_localzone() else: my_tz = get_localzone() if not my_tz: my_tz =",
"babel.dates import format_datetime, format_time, format_date import pytz from tzlocal import",
"def timezone(self) -> pytz.BaseTzInfo: return self._timezone def format_date_full_str(self, my_datetime: dt.datetime)",
"format_datetime(my_datetime, format=\"short\", locale=self.locale) def get_datetime_formatted_str(self, ts: int) -> str: \"\"\"return",
"formated datetime string using locale\"\"\" my_datetime = self.get_datetime_from_ts(ts) return format_time(my_datetime,",
"my_locale: my_locale = Locale.parse(settings.FALLBACK_LOCALE) return my_locale @staticmethod def _determine_timezone( my_tz:",
"dict = None, ) -> None: \"\"\" Args: - my_locale:",
"if not my_locale: my_locale = Locale.parse(settings.FALLBACK_LOCALE) return my_locale @staticmethod def",
"= self.get_datetime_from_ts(ts) return format_datetime(my_datetime, format=\"short\", locale=self.locale) def get_time_formatted_str(self, ts: int)",
"TypeError(\"my_locale must be a babel Locale object\") else: if author_info:",
"import get_localzone from . import settings logger = logging.getLogger(__name__) class",
"return format_time(my_datetime, format=\"short\", locale=self.locale) def get_datetime_from_ts(self, ts: int) -> dt.datetime:",
"- my_tz: Primary timezone to use - author_info: locale and",
"format_date_full_str(self, my_datetime: dt.datetime) -> str: return format_date(my_datetime, format=\"full\", locale=self.locale) def",
"pytz\") else: if author_info: try: my_tz = pytz.timezone(author_info[\"tz\"]) except pytz.exceptions.UnknownTimeZoneError:",
"info from Slack\") my_locale = Locale.default() else: my_locale = Locale.default()",
"not use timezone info from Slack\") my_tz = get_localzone() else:",
"Slack\") my_locale = Locale.default() else: my_locale = Locale.default() if not",
"my_tz = get_localzone() if not my_tz: my_tz = pytz.UTC return",
"dt import logging from babel import Locale, UnknownLocaleError from babel.dates",
"= get_localzone() if not my_tz: my_tz = pytz.UTC return my_tz",
"author_info: dict = None ) -> pytz.BaseTzInfo: if my_tz: if",
"locale to use - my_tz: Primary timezone to use -",
"-> pytz.BaseTzInfo: if my_tz: if not isinstance(my_tz, pytz.BaseTzInfo): raise TypeError(\"my_tz",
"string using locale\"\"\" my_datetime = self.get_datetime_from_ts(ts) return format_datetime(my_datetime, format=\"short\", locale=self.locale)",
"author_info: locale and timezone to use from this Slack response",
"return my_tz @property def locale(self) -> Locale: return self._locale @property",
"@property def timezone(self) -> pytz.BaseTzInfo: return self._timezone def format_date_full_str(self, my_datetime:",
"unix timestamp with local timezone\"\"\" my_datetime = dt.datetime.fromtimestamp(float(ts), pytz.UTC) return",
"try: my_tz = pytz.timezone(author_info[\"tz\"]) except pytz.exceptions.UnknownTimeZoneError: logger.warning(\"Could not use timezone",
"Locale: return self._locale @property def timezone(self) -> pytz.BaseTzInfo: return self._timezone",
"return self._timezone def format_date_full_str(self, my_datetime: dt.datetime) -> str: return format_date(my_datetime,",
"my_datetime: dt.datetime) -> str: return format_date(my_datetime, format=\"full\", locale=self.locale) def format_datetime_str(self,",
"my_datetime = self.get_datetime_from_ts(ts) return format_datetime(my_datetime, format=\"short\", locale=self.locale) def get_time_formatted_str(self, ts:",
"a babel Locale object\") else: if author_info: try: my_locale =",
"else: if author_info: try: my_locale = Locale.parse(author_info[\"locale\"], sep=\"-\") except UnknownLocaleError:",
"author_info: dict = None) -> Locale: if my_locale: if not",
"int) -> str: \"\"\"return given timestamp as formated datetime string",
"author_info: dict = None, ) -> None: \"\"\" Args: -",
"TypeError(\"my_tz must be of type pytz\") else: if author_info: try:",
"self, my_locale: Locale = None, my_tz: pytz.BaseTzInfo = None, author_info:",
"my_tz = get_localzone() else: my_tz = get_localzone() if not my_tz:",
"logger.warning(\"Could not use timezone info from Slack\") my_tz = get_localzone()",
"timezone(self) -> pytz.BaseTzInfo: return self._timezone def format_date_full_str(self, my_datetime: dt.datetime) ->",
"\"\"\" Args: - my_locale: Primary locale to use - my_tz:",
"my_tz: pytz.BaseTzInfo = None, author_info: dict = None ) ->",
"sep=\"-\") except UnknownLocaleError: logger.warning(\"Could not use locale info from Slack\")",
"from . import settings logger = logging.getLogger(__name__) class LocaleHelper: \"\"\"Helpers",
"import datetime as dt import logging from babel import Locale,",
"Primary timezone to use - author_info: locale and timezone to",
"author_info: try: my_tz = pytz.timezone(author_info[\"tz\"]) except pytz.exceptions.UnknownTimeZoneError: logger.warning(\"Could not use",
"@property def locale(self) -> Locale: return self._locale @property def timezone(self)",
"logger = logging.getLogger(__name__) class LocaleHelper: \"\"\"Helpers for converting date &",
"def locale(self) -> Locale: return self._locale @property def timezone(self) ->",
"def get_time_formatted_str(self, ts: int) -> str: \"\"\"return given timestamp as",
"get_time_formatted_str(self, ts: int) -> str: \"\"\"return given timestamp as formated",
"my_locale = Locale.parse(author_info[\"locale\"], sep=\"-\") except UnknownLocaleError: logger.warning(\"Could not use locale",
"logger.warning(\"Could not use locale info from Slack\") my_locale = Locale.default()",
"timezone info from Slack\") my_tz = get_localzone() else: my_tz =",
"dict = None ) -> pytz.BaseTzInfo: if my_tz: if not",
"pytz from tzlocal import get_localzone from . import settings logger",
"Slack\") my_tz = get_localzone() else: my_tz = get_localzone() if not",
"format_date import pytz from tzlocal import get_localzone from . import",
"given timestamp as formated datetime string using locale\"\"\" my_datetime =",
"datetime string using locale\"\"\" my_datetime = self.get_datetime_from_ts(ts) return format_datetime(my_datetime, format=\"short\",",
"-> dt.datetime: \"\"\"returns datetime object of a unix timestamp with",
") -> None: \"\"\" Args: - my_locale: Primary locale to",
"pytz.BaseTzInfo: if my_tz: if not isinstance(my_tz, pytz.BaseTzInfo): raise TypeError(\"my_tz must",
"- author_info: locale and timezone to use from this Slack",
"Locale.default() else: my_locale = Locale.default() if not my_locale: my_locale =",
"return format_datetime(my_datetime, format=\"short\", locale=self.locale) def get_time_formatted_str(self, ts: int) -> str:",
"Locale = None, my_tz: pytz.BaseTzInfo = None, author_info: dict =",
"dict = None) -> Locale: if my_locale: if not isinstance(my_locale,",
"str: \"\"\"returns formated datetime string for given dt using locale\"\"\"",
"locale\"\"\" my_datetime = self.get_datetime_from_ts(ts) return format_datetime(my_datetime, format=\"short\", locale=self.locale) def get_time_formatted_str(self,",
"Slack response if my_locale and/or my_tz are not given \"\"\"",
"tzlocal import get_localzone from . import settings logger = logging.getLogger(__name__)",
"return format_datetime(my_datetime, format=\"short\", locale=self.locale) def get_datetime_formatted_str(self, ts: int) -> str:",
"this Slack response if my_locale and/or my_tz are not given",
"locale=self.locale) def get_datetime_formatted_str(self, ts: int) -> str: \"\"\"return given timestamp",
"dt using locale\"\"\" return format_datetime(my_datetime, format=\"short\", locale=self.locale) def get_datetime_formatted_str(self, ts:",
"ts: int) -> dt.datetime: \"\"\"returns datetime object of a unix",
"= get_localzone() else: my_tz = get_localzone() if not my_tz: my_tz",
"formated datetime string using locale\"\"\" my_datetime = self.get_datetime_from_ts(ts) return format_datetime(my_datetime,",
"Locale.default() if not my_locale: my_locale = Locale.parse(settings.FALLBACK_LOCALE) return my_locale @staticmethod",
"as formated datetime string using locale\"\"\" my_datetime = self.get_datetime_from_ts(ts) return",
"locale and timezone\"\"\" def __init__( self, my_locale: Locale = None,",
"__init__( self, my_locale: Locale = None, my_tz: pytz.BaseTzInfo = None,",
"locale(self) -> Locale: return self._locale @property def timezone(self) -> pytz.BaseTzInfo:",
"date & time according to current locale and timezone\"\"\" def",
"def format_datetime_str(self, my_datetime: dt.datetime) -> str: \"\"\"returns formated datetime string",
"for converting date & time according to current locale and",
"not given \"\"\" self._locale = self._determine_locale(my_locale, author_info) self._timezone = self._determine_timezone(my_tz,",
"object of a unix timestamp with local timezone\"\"\" my_datetime =",
"except UnknownLocaleError: logger.warning(\"Could not use locale info from Slack\") my_locale",
"my_tz = pytz.timezone(author_info[\"tz\"]) except pytz.exceptions.UnknownTimeZoneError: logger.warning(\"Could not use timezone info",
"using locale\"\"\" return format_datetime(my_datetime, format=\"short\", locale=self.locale) def get_datetime_formatted_str(self, ts: int)",
"to use - my_tz: Primary timezone to use - author_info:",
"datetime string using locale\"\"\" my_datetime = self.get_datetime_from_ts(ts) return format_time(my_datetime, format=\"short\",",
"UnknownLocaleError: logger.warning(\"Could not use locale info from Slack\") my_locale =",
"timezone to use - author_info: locale and timezone to use",
"\"\"\" self._locale = self._determine_locale(my_locale, author_info) self._timezone = self._determine_timezone(my_tz, author_info) @staticmethod",
"using locale\"\"\" my_datetime = self.get_datetime_from_ts(ts) return format_datetime(my_datetime, format=\"short\", locale=self.locale) def",
"locale=self.locale) def get_datetime_from_ts(self, ts: int) -> dt.datetime: \"\"\"returns datetime object",
"= None, author_info: dict = None) -> Locale: if my_locale:",
"self._locale = self._determine_locale(my_locale, author_info) self._timezone = self._determine_timezone(my_tz, author_info) @staticmethod def",
"def format_date_full_str(self, my_datetime: dt.datetime) -> str: return format_date(my_datetime, format=\"full\", locale=self.locale)",
"my_locale = Locale.default() if not my_locale: my_locale = Locale.parse(settings.FALLBACK_LOCALE) return",
"-> str: return format_date(my_datetime, format=\"full\", locale=self.locale) def format_datetime_str(self, my_datetime: dt.datetime)",
"-> str: \"\"\"return given timestamp as formated datetime string using",
"use - author_info: locale and timezone to use from this",
"-> Locale: if my_locale: if not isinstance(my_locale, Locale): raise TypeError(\"my_locale",
"Locale, UnknownLocaleError from babel.dates import format_datetime, format_time, format_date import pytz",
"from tzlocal import get_localzone from . import settings logger =",
"= None, ) -> None: \"\"\" Args: - my_locale: Primary",
"my_tz: Primary timezone to use - author_info: locale and timezone",
"locale\"\"\" my_datetime = self.get_datetime_from_ts(ts) return format_time(my_datetime, format=\"short\", locale=self.locale) def get_datetime_from_ts(self,",
"= self.get_datetime_from_ts(ts) return format_time(my_datetime, format=\"short\", locale=self.locale) def get_datetime_from_ts(self, ts: int)",
"def get_datetime_from_ts(self, ts: int) -> dt.datetime: \"\"\"returns datetime object of",
"my_datetime = self.get_datetime_from_ts(ts) return format_time(my_datetime, format=\"short\", locale=self.locale) def get_datetime_from_ts(self, ts:",
"get_localzone from . import settings logger = logging.getLogger(__name__) class LocaleHelper:",
"Locale): raise TypeError(\"my_locale must be a babel Locale object\") else:",
"as dt import logging from babel import Locale, UnknownLocaleError from",
"given \"\"\" self._locale = self._determine_locale(my_locale, author_info) self._timezone = self._determine_timezone(my_tz, author_info)",
"_determine_locale(my_locale: Locale = None, author_info: dict = None) -> Locale:",
"not isinstance(my_tz, pytz.BaseTzInfo): raise TypeError(\"my_tz must be of type pytz\")",
"= None ) -> pytz.BaseTzInfo: if my_tz: if not isinstance(my_tz,",
"LocaleHelper: \"\"\"Helpers for converting date & time according to current",
"from babel import Locale, UnknownLocaleError from babel.dates import format_datetime, format_time,",
"to use from this Slack response if my_locale and/or my_tz",
"str: return format_date(my_datetime, format=\"full\", locale=self.locale) def format_datetime_str(self, my_datetime: dt.datetime) ->",
"import logging from babel import Locale, UnknownLocaleError from babel.dates import",
"author_info) @staticmethod def _determine_locale(my_locale: Locale = None, author_info: dict =",
"= Locale.default() if not my_locale: my_locale = Locale.parse(settings.FALLBACK_LOCALE) return my_locale",
"my_locale = Locale.parse(settings.FALLBACK_LOCALE) return my_locale @staticmethod def _determine_timezone( my_tz: pytz.BaseTzInfo",
"except pytz.exceptions.UnknownTimeZoneError: logger.warning(\"Could not use timezone info from Slack\") my_tz",
"use timezone info from Slack\") my_tz = get_localzone() else: my_tz",
"must be of type pytz\") else: if author_info: try: my_tz",
"None: \"\"\" Args: - my_locale: Primary locale to use -",
"to current locale and timezone\"\"\" def __init__( self, my_locale: Locale",
"time according to current locale and timezone\"\"\" def __init__( self,",
"babel import Locale, UnknownLocaleError from babel.dates import format_datetime, format_time, format_date",
"pytz.timezone(author_info[\"tz\"]) except pytz.exceptions.UnknownTimeZoneError: logger.warning(\"Could not use timezone info from Slack\")",
"locale=self.locale) def format_datetime_str(self, my_datetime: dt.datetime) -> str: \"\"\"returns formated datetime",
"for given dt using locale\"\"\" return format_datetime(my_datetime, format=\"short\", locale=self.locale) def",
"- my_locale: Primary locale to use - my_tz: Primary timezone",
"my_tz are not given \"\"\" self._locale = self._determine_locale(my_locale, author_info) self._timezone",
"pytz.exceptions.UnknownTimeZoneError: logger.warning(\"Could not use timezone info from Slack\") my_tz =",
"= logging.getLogger(__name__) class LocaleHelper: \"\"\"Helpers for converting date & time",
"formated datetime string for given dt using locale\"\"\" return format_datetime(my_datetime,",
"\"\"\"returns formated datetime string for given dt using locale\"\"\" return",
"response if my_locale and/or my_tz are not given \"\"\" self._locale",
"format_time(my_datetime, format=\"short\", locale=self.locale) def get_datetime_from_ts(self, ts: int) -> dt.datetime: \"\"\"returns",
"def __init__( self, my_locale: Locale = None, my_tz: pytz.BaseTzInfo ="
] |
[
"CONFIG PARAMETERS SECRET_KEY = os.getenv('DATABOARD_SECRET_KEY', '<KEY>') # abs max upload",
"if None, output to screen MAX_CONTENT_LENGTH = 1024 * 1024",
"###################################################################### class ProductionConfig(Config): DEPLOYMENT_PATH = os.getenv( 'DATABOARD_DEPLOYMENT_PATH', '/tmp/databoard') class DevelopmentConfig(Config):",
"training is not working # is_parallelize RAMP_PARALLELIZE = bool(os.getenv('DATABOARD_PARALLELIZE', 1))",
"MAIL_DEBUG = False SQLALCHEMY_TRACK_MODIFICATIONS = True SQLALCHEMY_DATABASE_URI = os.getenv('DATABOARD_DB_URL') SQLALCHEMY_MIGRATE_REPO",
"False if parallel training is not working # is_parallelize RAMP_PARALLELIZE",
"is not working # is_parallelize RAMP_PARALLELIZE = bool(os.getenv('DATABOARD_PARALLELIZE', 1)) ######################################################################",
"1024 * 1024 DEBUG = False TESTING = False #",
"= True SQLALCHEMY_DATABASE_URI = os.getenv('DATABOARD_DB_URL') SQLALCHEMY_MIGRATE_REPO = os.getenv('DATABOARD_DB_MIGRATE_REPO') SQLALCHEMY_RECORD_QUERIES =",
"is_parallelize RAMP_PARALLELIZE = bool(os.getenv('DATABOARD_PARALLELIZE', 1)) ###################################################################### class ProductionConfig(Config): DEPLOYMENT_PATH =",
"saving it WTF_CSRF_ENABLED = True LOG_FILENAME = None # if",
"MAIL_PORT = os.getenv('DATABOARD_MAIL_PORT', 587) MAIL_USERNAME = os.getenv('DATABOARD_MAIL_USERNAME', 'user') MAIL_PASSWORD =",
"= 'submissions' RAMP_SANDBOX_DIR = 'starting_kit' RAMP_SERVER_PORT = 8080 # make",
"1024 DEBUG = False TESTING = False # FLASK MAIL",
"output to screen MAX_CONTENT_LENGTH = 1024 * 1024 * 1024",
"MAIL_DEBUG = True SQLALCHEMY_DATABASE_URI = os.getenv( 'DATABOARD_DB_URL_TEST', 'postgresql://mrramp:mrramp@localhost/databoard_test' ) DEPLOYMENT_PATH",
"else False ) class RampConfig(object): RAMP_ADMIN_MAILS = os.getenv('DATABOARD_ADMIN_MAILS', []) RAMP_KITS_DIR",
"= True MAIL_DEBUG = False SQLALCHEMY_TRACK_MODIFICATIONS = True SQLALCHEMY_DATABASE_URI =",
"if os.getenv('DATABOARD_DB_PERF', 0) else False ) class RampConfig(object): RAMP_ADMIN_MAILS =",
"class DevelopmentConfig(Config): DEBUG = True MAIL_DEBUG = True SQLALCHEMY_DATABASE_URI =",
"RAMP_SERVER_PORT = 8080 # make it False if parallel training",
"FLASK GENERAL CONFIG PARAMETERS SECRET_KEY = os.getenv('DATABOARD_SECRET_KEY', '<KEY>') # abs",
"os.getenv('DATABOARD_MAIL_PORT', 587) MAIL_USERNAME = os.getenv('DATABOARD_MAIL_USERNAME', 'user') MAIL_PASSWORD = os.getenv('DATABOARD_MAIL_PASSWORD', 'password')",
"1)) ###################################################################### class ProductionConfig(Config): DEPLOYMENT_PATH = os.getenv( 'DATABOARD_DEPLOYMENT_PATH', '/tmp/databoard') class",
"[]) RAMP_KITS_DIR = 'ramp-kits' RAMP_DATA_DIR = 'ramp-data' RAMP_SUBMISSIONS_DIR = 'submissions'",
"SQLALCHEMY_TRACK_MODIFICATIONS = True SQLALCHEMY_DATABASE_URI = os.getenv('DATABOARD_DB_URL') SQLALCHEMY_MIGRATE_REPO = os.getenv('DATABOARD_DB_MIGRATE_REPO') SQLALCHEMY_RECORD_QUERIES",
"'user') MAIL_PASSWORD = os.getenv('DATABOARD_MAIL_PASSWORD', 'password') MAIL_DEFAULT_SENDER = ( os.getenv('DATABOARD_MAIL_SENDER_ALIAS', 'RAMP",
"False ) class RampConfig(object): RAMP_ADMIN_MAILS = os.getenv('DATABOARD_ADMIN_MAILS', []) RAMP_KITS_DIR =",
"RAMP_SANDBOX_DIR = 'starting_kit' RAMP_SERVER_PORT = 8080 # make it False",
"MAIL_USE_TLS = False MAIL_USE_SSL = True MAIL_DEBUG = False SQLALCHEMY_TRACK_MODIFICATIONS",
"RAMP_DATA_DIR = 'ramp-data' RAMP_SUBMISSIONS_DIR = 'submissions' RAMP_SANDBOX_DIR = 'starting_kit' RAMP_SERVER_PORT",
"# FLASK GENERAL CONFIG PARAMETERS SECRET_KEY = os.getenv('DATABOARD_SECRET_KEY', '<KEY>') #",
"os.getenv('DATABOARD_MAIL_USERNAME', 'user') MAIL_PASSWORD = os.getenv('DATABOARD_MAIL_PASSWORD', 'password') MAIL_DEFAULT_SENDER = ( os.getenv('DATABOARD_MAIL_SENDER_ALIAS',",
"1024 * 1024 * 1024 DEBUG = False TESTING =",
"= 'starting_kit' RAMP_SERVER_PORT = 8080 # make it False if",
"= ( os.getenv('DATABOARD_MAIL_SENDER_ALIAS', 'RAMP admin'), os.getenv('DATABOARD_MAIL_SENDER', '<EMAIL>') ) MAIL_RECIPIENTS =",
"upload file size, to throw 413, before saving it WTF_CSRF_ENABLED",
"'smtp.gmail.com') MAIL_PORT = os.getenv('DATABOARD_MAIL_PORT', 587) MAIL_USERNAME = os.getenv('DATABOARD_MAIL_USERNAME', 'user') MAIL_PASSWORD",
"'DATABOARD_DEPLOYMENT_PATH', '/tmp/databoard') class DevelopmentConfig(Config): DEBUG = True MAIL_DEBUG = True",
"True if os.getenv('DATABOARD_DB_PERF', 0) else False ) class RampConfig(object): RAMP_ADMIN_MAILS",
"False TESTING = False # FLASK MAIL CONFIG PARAMETERS MAIL_SERVER",
"MAIL_RECIPIENTS = [] MAIL_USE_TLS = False MAIL_USE_SSL = True MAIL_DEBUG",
"False MAIL_USE_SSL = True MAIL_DEBUG = False SQLALCHEMY_TRACK_MODIFICATIONS = True",
"<reponame>glemaitre/ramp-board-1<gh_stars>0 import os class Config(object): # FLASK GENERAL CONFIG PARAMETERS",
"8080 # make it False if parallel training is not",
"class RampConfig(object): RAMP_ADMIN_MAILS = os.getenv('DATABOARD_ADMIN_MAILS', []) RAMP_KITS_DIR = 'ramp-kits' RAMP_DATA_DIR",
") DEPLOYMENT_PATH = os.getenv( 'DATABOARD_DEPLOYMENT_PATH_TEST', '/tmp/databoard_test') class TestingConfig(Config): TESTING =",
"MAIL_SERVER = os.getenv('DATABOARD_MAIL_SERVER', 'smtp.gmail.com') MAIL_PORT = os.getenv('DATABOARD_MAIL_PORT', 587) MAIL_USERNAME =",
"'<EMAIL>') ) MAIL_RECIPIENTS = [] MAIL_USE_TLS = False MAIL_USE_SSL =",
"True SQLALCHEMY_DATABASE_URI = os.getenv( 'DATABOARD_DB_URL_TEST', 'postgresql://mrramp:mrramp@localhost/databoard_test' ) DEPLOYMENT_PATH = os.getenv(",
"TESTING = True SQLALCHEMY_DATABASE_URI = os.getenv( 'DATABOARD_DB_URL_TEST', 'postgresql://mrramp:mrramp@localhost/databoard_test' ) DEPLOYMENT_PATH",
"SECRET_KEY = os.getenv('DATABOARD_SECRET_KEY', '<KEY>') # abs max upload file size,",
"TestingConfig(Config): TESTING = True SQLALCHEMY_DATABASE_URI = os.getenv( 'DATABOARD_DB_URL_TEST', 'postgresql://mrramp:mrramp@localhost/databoard_test' )",
"( True if os.getenv('DATABOARD_DB_PERF', 0) else False ) class RampConfig(object):",
"= ( True if os.getenv('DATABOARD_DB_PERF', 0) else False ) class",
"= True MAIL_DEBUG = True SQLALCHEMY_DATABASE_URI = os.getenv( 'DATABOARD_DB_URL_TEST', 'postgresql://mrramp:mrramp@localhost/databoard_test'",
"= 8080 # make it False if parallel training is",
"os class Config(object): # FLASK GENERAL CONFIG PARAMETERS SECRET_KEY =",
"MAIL_USERNAME = os.getenv('DATABOARD_MAIL_USERNAME', 'user') MAIL_PASSWORD = os.getenv('DATABOARD_MAIL_PASSWORD', 'password') MAIL_DEFAULT_SENDER =",
"os.getenv('DATABOARD_DB_MIGRATE_REPO') SQLALCHEMY_RECORD_QUERIES = ( True if os.getenv('DATABOARD_DB_PERF', 0) else False",
"True MAIL_DEBUG = True SQLALCHEMY_DATABASE_URI = os.getenv( 'DATABOARD_DB_URL_TEST', 'postgresql://mrramp:mrramp@localhost/databoard_test' )",
"not working # is_parallelize RAMP_PARALLELIZE = bool(os.getenv('DATABOARD_PARALLELIZE', 1)) ###################################################################### class",
"# abs max upload file size, to throw 413, before",
"DEPLOYMENT_PATH = os.getenv( 'DATABOARD_DEPLOYMENT_PATH', '/tmp/databoard') class DevelopmentConfig(Config): DEBUG = True",
"= os.getenv('DATABOARD_MAIL_SERVER', 'smtp.gmail.com') MAIL_PORT = os.getenv('DATABOARD_MAIL_PORT', 587) MAIL_USERNAME = os.getenv('DATABOARD_MAIL_USERNAME',",
"parallel training is not working # is_parallelize RAMP_PARALLELIZE = bool(os.getenv('DATABOARD_PARALLELIZE',",
"SQLALCHEMY_DATABASE_URI = os.getenv( 'DATABOARD_DB_URL_TEST', 'postgresql://mrramp:mrramp@localhost/databoard_test' ) DEPLOYMENT_PATH = os.getenv( 'DATABOARD_DEPLOYMENT_PATH_TEST',",
"RAMP_SUBMISSIONS_DIR = 'submissions' RAMP_SANDBOX_DIR = 'starting_kit' RAMP_SERVER_PORT = 8080 #",
"MAIL_DEFAULT_SENDER = ( os.getenv('DATABOARD_MAIL_SENDER_ALIAS', 'RAMP admin'), os.getenv('DATABOARD_MAIL_SENDER', '<EMAIL>') ) MAIL_RECIPIENTS",
"= False MAIL_USE_SSL = True MAIL_DEBUG = False SQLALCHEMY_TRACK_MODIFICATIONS =",
"class TestingConfig(Config): TESTING = True SQLALCHEMY_DATABASE_URI = os.getenv( 'DATABOARD_DB_URL_TEST', 'postgresql://mrramp:mrramp@localhost/databoard_test'",
"os.getenv( 'DATABOARD_DB_URL_TEST', 'postgresql://mrramp:mrramp@localhost/databoard_test' ) DEPLOYMENT_PATH = os.getenv( 'DATABOARD_DEPLOYMENT_PATH_TEST', '/tmp/databoard_test') class",
"os.getenv( 'DATABOARD_DEPLOYMENT_PATH_TEST', '/tmp/databoard_test') class TestingConfig(Config): TESTING = True SQLALCHEMY_DATABASE_URI =",
"= os.getenv('DATABOARD_MAIL_PORT', 587) MAIL_USERNAME = os.getenv('DATABOARD_MAIL_USERNAME', 'user') MAIL_PASSWORD = os.getenv('DATABOARD_MAIL_PASSWORD',",
"= os.getenv('DATABOARD_MAIL_USERNAME', 'user') MAIL_PASSWORD = os.getenv('DATABOARD_MAIL_PASSWORD', 'password') MAIL_DEFAULT_SENDER = (",
"RAMP_KITS_DIR = 'ramp-kits' RAMP_DATA_DIR = 'ramp-data' RAMP_SUBMISSIONS_DIR = 'submissions' RAMP_SANDBOX_DIR",
"MAIL_USE_SSL = True MAIL_DEBUG = False SQLALCHEMY_TRACK_MODIFICATIONS = True SQLALCHEMY_DATABASE_URI",
"before saving it WTF_CSRF_ENABLED = True LOG_FILENAME = None #",
"os.getenv('DATABOARD_DB_PERF', 0) else False ) class RampConfig(object): RAMP_ADMIN_MAILS = os.getenv('DATABOARD_ADMIN_MAILS',",
"to throw 413, before saving it WTF_CSRF_ENABLED = True LOG_FILENAME",
"# make it False if parallel training is not working",
"os.getenv('DATABOARD_SECRET_KEY', '<KEY>') # abs max upload file size, to throw",
"'starting_kit' RAMP_SERVER_PORT = 8080 # make it False if parallel",
"= bool(os.getenv('DATABOARD_PARALLELIZE', 1)) ###################################################################### class ProductionConfig(Config): DEPLOYMENT_PATH = os.getenv( 'DATABOARD_DEPLOYMENT_PATH',",
"DevelopmentConfig(Config): DEBUG = True MAIL_DEBUG = True SQLALCHEMY_DATABASE_URI = os.getenv(",
"= False # FLASK MAIL CONFIG PARAMETERS MAIL_SERVER = os.getenv('DATABOARD_MAIL_SERVER',",
"os.getenv('DATABOARD_ADMIN_MAILS', []) RAMP_KITS_DIR = 'ramp-kits' RAMP_DATA_DIR = 'ramp-data' RAMP_SUBMISSIONS_DIR =",
"RAMP_ADMIN_MAILS = os.getenv('DATABOARD_ADMIN_MAILS', []) RAMP_KITS_DIR = 'ramp-kits' RAMP_DATA_DIR = 'ramp-data'",
"DEPLOYMENT_PATH = os.getenv( 'DATABOARD_DEPLOYMENT_PATH_TEST', '/tmp/databoard_test') class TestingConfig(Config): TESTING = True",
"PARAMETERS MAIL_SERVER = os.getenv('DATABOARD_MAIL_SERVER', 'smtp.gmail.com') MAIL_PORT = os.getenv('DATABOARD_MAIL_PORT', 587) MAIL_USERNAME",
"= os.getenv( 'DATABOARD_DB_URL_TEST', 'postgresql://mrramp:mrramp@localhost/databoard_test' ) DEPLOYMENT_PATH = os.getenv( 'DATABOARD_DEPLOYMENT_PATH_TEST', '/tmp/databoard_test')",
"= False SQLALCHEMY_TRACK_MODIFICATIONS = True SQLALCHEMY_DATABASE_URI = os.getenv('DATABOARD_DB_URL') SQLALCHEMY_MIGRATE_REPO =",
"DEBUG = False TESTING = False # FLASK MAIL CONFIG",
"= 'ramp-data' RAMP_SUBMISSIONS_DIR = 'submissions' RAMP_SANDBOX_DIR = 'starting_kit' RAMP_SERVER_PORT =",
"SQLALCHEMY_MIGRATE_REPO = os.getenv('DATABOARD_DB_MIGRATE_REPO') SQLALCHEMY_RECORD_QUERIES = ( True if os.getenv('DATABOARD_DB_PERF', 0)",
"= os.getenv('DATABOARD_MAIL_PASSWORD', 'password') MAIL_DEFAULT_SENDER = ( os.getenv('DATABOARD_MAIL_SENDER_ALIAS', 'RAMP admin'), os.getenv('DATABOARD_MAIL_SENDER',",
"* 1024 * 1024 DEBUG = False TESTING = False",
"WTF_CSRF_ENABLED = True LOG_FILENAME = None # if None, output",
"os.getenv( 'DATABOARD_DEPLOYMENT_PATH', '/tmp/databoard') class DevelopmentConfig(Config): DEBUG = True MAIL_DEBUG =",
"import os class Config(object): # FLASK GENERAL CONFIG PARAMETERS SECRET_KEY",
"class Config(object): # FLASK GENERAL CONFIG PARAMETERS SECRET_KEY = os.getenv('DATABOARD_SECRET_KEY',",
"throw 413, before saving it WTF_CSRF_ENABLED = True LOG_FILENAME =",
"= True LOG_FILENAME = None # if None, output to",
"'password') MAIL_DEFAULT_SENDER = ( os.getenv('DATABOARD_MAIL_SENDER_ALIAS', 'RAMP admin'), os.getenv('DATABOARD_MAIL_SENDER', '<EMAIL>') )",
"FLASK MAIL CONFIG PARAMETERS MAIL_SERVER = os.getenv('DATABOARD_MAIL_SERVER', 'smtp.gmail.com') MAIL_PORT =",
"bool(os.getenv('DATABOARD_PARALLELIZE', 1)) ###################################################################### class ProductionConfig(Config): DEPLOYMENT_PATH = os.getenv( 'DATABOARD_DEPLOYMENT_PATH', '/tmp/databoard')",
"'<KEY>') # abs max upload file size, to throw 413,",
"LOG_FILENAME = None # if None, output to screen MAX_CONTENT_LENGTH",
") class RampConfig(object): RAMP_ADMIN_MAILS = os.getenv('DATABOARD_ADMIN_MAILS', []) RAMP_KITS_DIR = 'ramp-kits'",
"= os.getenv( 'DATABOARD_DEPLOYMENT_PATH', '/tmp/databoard') class DevelopmentConfig(Config): DEBUG = True MAIL_DEBUG",
"'DATABOARD_DB_URL_TEST', 'postgresql://mrramp:mrramp@localhost/databoard_test' ) DEPLOYMENT_PATH = os.getenv( 'DATABOARD_DEPLOYMENT_PATH_TEST', '/tmp/databoard_test') class TestingConfig(Config):",
"= os.getenv( 'DATABOARD_DEPLOYMENT_PATH_TEST', '/tmp/databoard_test') class TestingConfig(Config): TESTING = True SQLALCHEMY_DATABASE_URI",
"( os.getenv('DATABOARD_MAIL_SENDER_ALIAS', 'RAMP admin'), os.getenv('DATABOARD_MAIL_SENDER', '<EMAIL>') ) MAIL_RECIPIENTS = []",
"admin'), os.getenv('DATABOARD_MAIL_SENDER', '<EMAIL>') ) MAIL_RECIPIENTS = [] MAIL_USE_TLS = False",
"it False if parallel training is not working # is_parallelize",
"'/tmp/databoard') class DevelopmentConfig(Config): DEBUG = True MAIL_DEBUG = True SQLALCHEMY_DATABASE_URI",
"RAMP_PARALLELIZE = bool(os.getenv('DATABOARD_PARALLELIZE', 1)) ###################################################################### class ProductionConfig(Config): DEPLOYMENT_PATH = os.getenv(",
"SQLALCHEMY_RECORD_QUERIES = ( True if os.getenv('DATABOARD_DB_PERF', 0) else False )",
"= 'ramp-kits' RAMP_DATA_DIR = 'ramp-data' RAMP_SUBMISSIONS_DIR = 'submissions' RAMP_SANDBOX_DIR =",
"CONFIG PARAMETERS MAIL_SERVER = os.getenv('DATABOARD_MAIL_SERVER', 'smtp.gmail.com') MAIL_PORT = os.getenv('DATABOARD_MAIL_PORT', 587)",
"# is_parallelize RAMP_PARALLELIZE = bool(os.getenv('DATABOARD_PARALLELIZE', 1)) ###################################################################### class ProductionConfig(Config): DEPLOYMENT_PATH",
"PARAMETERS SECRET_KEY = os.getenv('DATABOARD_SECRET_KEY', '<KEY>') # abs max upload file",
") MAIL_RECIPIENTS = [] MAIL_USE_TLS = False MAIL_USE_SSL = True",
"587) MAIL_USERNAME = os.getenv('DATABOARD_MAIL_USERNAME', 'user') MAIL_PASSWORD = os.getenv('DATABOARD_MAIL_PASSWORD', 'password') MAIL_DEFAULT_SENDER",
"os.getenv('DATABOARD_MAIL_SERVER', 'smtp.gmail.com') MAIL_PORT = os.getenv('DATABOARD_MAIL_PORT', 587) MAIL_USERNAME = os.getenv('DATABOARD_MAIL_USERNAME', 'user')",
"[] MAIL_USE_TLS = False MAIL_USE_SSL = True MAIL_DEBUG = False",
"make it False if parallel training is not working #",
"MAX_CONTENT_LENGTH = 1024 * 1024 * 1024 DEBUG = False",
"max upload file size, to throw 413, before saving it",
"= 1024 * 1024 * 1024 DEBUG = False TESTING",
"size, to throw 413, before saving it WTF_CSRF_ENABLED = True",
"MAIL CONFIG PARAMETERS MAIL_SERVER = os.getenv('DATABOARD_MAIL_SERVER', 'smtp.gmail.com') MAIL_PORT = os.getenv('DATABOARD_MAIL_PORT',",
"if parallel training is not working # is_parallelize RAMP_PARALLELIZE =",
"TESTING = False # FLASK MAIL CONFIG PARAMETERS MAIL_SERVER =",
"413, before saving it WTF_CSRF_ENABLED = True LOG_FILENAME = None",
"RampConfig(object): RAMP_ADMIN_MAILS = os.getenv('DATABOARD_ADMIN_MAILS', []) RAMP_KITS_DIR = 'ramp-kits' RAMP_DATA_DIR =",
"os.getenv('DATABOARD_MAIL_SENDER', '<EMAIL>') ) MAIL_RECIPIENTS = [] MAIL_USE_TLS = False MAIL_USE_SSL",
"True MAIL_DEBUG = False SQLALCHEMY_TRACK_MODIFICATIONS = True SQLALCHEMY_DATABASE_URI = os.getenv('DATABOARD_DB_URL')",
"'postgresql://mrramp:mrramp@localhost/databoard_test' ) DEPLOYMENT_PATH = os.getenv( 'DATABOARD_DEPLOYMENT_PATH_TEST', '/tmp/databoard_test') class TestingConfig(Config): TESTING",
"'/tmp/databoard_test') class TestingConfig(Config): TESTING = True SQLALCHEMY_DATABASE_URI = os.getenv( 'DATABOARD_DB_URL_TEST',",
"= True SQLALCHEMY_DATABASE_URI = os.getenv( 'DATABOARD_DB_URL_TEST', 'postgresql://mrramp:mrramp@localhost/databoard_test' ) DEPLOYMENT_PATH =",
"file size, to throw 413, before saving it WTF_CSRF_ENABLED =",
"os.getenv('DATABOARD_MAIL_PASSWORD', 'password') MAIL_DEFAULT_SENDER = ( os.getenv('DATABOARD_MAIL_SENDER_ALIAS', 'RAMP admin'), os.getenv('DATABOARD_MAIL_SENDER', '<EMAIL>')",
"'ramp-kits' RAMP_DATA_DIR = 'ramp-data' RAMP_SUBMISSIONS_DIR = 'submissions' RAMP_SANDBOX_DIR = 'starting_kit'",
"= os.getenv('DATABOARD_DB_URL') SQLALCHEMY_MIGRATE_REPO = os.getenv('DATABOARD_DB_MIGRATE_REPO') SQLALCHEMY_RECORD_QUERIES = ( True if",
"True LOG_FILENAME = None # if None, output to screen",
"= None # if None, output to screen MAX_CONTENT_LENGTH =",
"MAIL_PASSWORD = os.getenv('DATABOARD_MAIL_PASSWORD', 'password') MAIL_DEFAULT_SENDER = ( os.getenv('DATABOARD_MAIL_SENDER_ALIAS', 'RAMP admin'),",
"ProductionConfig(Config): DEPLOYMENT_PATH = os.getenv( 'DATABOARD_DEPLOYMENT_PATH', '/tmp/databoard') class DevelopmentConfig(Config): DEBUG =",
"False # FLASK MAIL CONFIG PARAMETERS MAIL_SERVER = os.getenv('DATABOARD_MAIL_SERVER', 'smtp.gmail.com')",
"os.getenv('DATABOARD_DB_URL') SQLALCHEMY_MIGRATE_REPO = os.getenv('DATABOARD_DB_MIGRATE_REPO') SQLALCHEMY_RECORD_QUERIES = ( True if os.getenv('DATABOARD_DB_PERF',",
"screen MAX_CONTENT_LENGTH = 1024 * 1024 * 1024 DEBUG =",
"True SQLALCHEMY_DATABASE_URI = os.getenv('DATABOARD_DB_URL') SQLALCHEMY_MIGRATE_REPO = os.getenv('DATABOARD_DB_MIGRATE_REPO') SQLALCHEMY_RECORD_QUERIES = (",
"# if None, output to screen MAX_CONTENT_LENGTH = 1024 *",
"False SQLALCHEMY_TRACK_MODIFICATIONS = True SQLALCHEMY_DATABASE_URI = os.getenv('DATABOARD_DB_URL') SQLALCHEMY_MIGRATE_REPO = os.getenv('DATABOARD_DB_MIGRATE_REPO')",
"Config(object): # FLASK GENERAL CONFIG PARAMETERS SECRET_KEY = os.getenv('DATABOARD_SECRET_KEY', '<KEY>')",
"SQLALCHEMY_DATABASE_URI = os.getenv('DATABOARD_DB_URL') SQLALCHEMY_MIGRATE_REPO = os.getenv('DATABOARD_DB_MIGRATE_REPO') SQLALCHEMY_RECORD_QUERIES = ( True",
"abs max upload file size, to throw 413, before saving",
"it WTF_CSRF_ENABLED = True LOG_FILENAME = None # if None,",
"0) else False ) class RampConfig(object): RAMP_ADMIN_MAILS = os.getenv('DATABOARD_ADMIN_MAILS', [])",
"# FLASK MAIL CONFIG PARAMETERS MAIL_SERVER = os.getenv('DATABOARD_MAIL_SERVER', 'smtp.gmail.com') MAIL_PORT",
"DEBUG = True MAIL_DEBUG = True SQLALCHEMY_DATABASE_URI = os.getenv( 'DATABOARD_DB_URL_TEST',",
"= os.getenv('DATABOARD_SECRET_KEY', '<KEY>') # abs max upload file size, to",
"= os.getenv( 'DATABOARD_DB_URL_TEST', 'postgresql://mrramp:mrramp@localhost/databoard_test' ) DEPLOYMENT_PATH = os.getenv( 'DATABOARD_DEPLOYMENT_PATH_TEST', '/tmp/databoard_test',",
"GENERAL CONFIG PARAMETERS SECRET_KEY = os.getenv('DATABOARD_SECRET_KEY', '<KEY>') # abs max",
"= os.getenv('DATABOARD_DB_MIGRATE_REPO') SQLALCHEMY_RECORD_QUERIES = ( True if os.getenv('DATABOARD_DB_PERF', 0) else",
"= os.getenv('DATABOARD_ADMIN_MAILS', []) RAMP_KITS_DIR = 'ramp-kits' RAMP_DATA_DIR = 'ramp-data' RAMP_SUBMISSIONS_DIR",
"os.getenv( 'DATABOARD_DB_URL_TEST', 'postgresql://mrramp:mrramp@localhost/databoard_test' ) DEPLOYMENT_PATH = os.getenv( 'DATABOARD_DEPLOYMENT_PATH_TEST', '/tmp/databoard_test', )",
"os.getenv('DATABOARD_MAIL_SENDER_ALIAS', 'RAMP admin'), os.getenv('DATABOARD_MAIL_SENDER', '<EMAIL>') ) MAIL_RECIPIENTS = [] MAIL_USE_TLS",
"to screen MAX_CONTENT_LENGTH = 1024 * 1024 * 1024 DEBUG",
"'ramp-data' RAMP_SUBMISSIONS_DIR = 'submissions' RAMP_SANDBOX_DIR = 'starting_kit' RAMP_SERVER_PORT = 8080",
"'DATABOARD_DEPLOYMENT_PATH_TEST', '/tmp/databoard_test') class TestingConfig(Config): TESTING = True SQLALCHEMY_DATABASE_URI = os.getenv(",
"None, output to screen MAX_CONTENT_LENGTH = 1024 * 1024 *",
"None # if None, output to screen MAX_CONTENT_LENGTH = 1024",
"* 1024 DEBUG = False TESTING = False # FLASK",
"= False TESTING = False # FLASK MAIL CONFIG PARAMETERS",
"= [] MAIL_USE_TLS = False MAIL_USE_SSL = True MAIL_DEBUG =",
"class ProductionConfig(Config): DEPLOYMENT_PATH = os.getenv( 'DATABOARD_DEPLOYMENT_PATH', '/tmp/databoard') class DevelopmentConfig(Config): DEBUG",
"'RAMP admin'), os.getenv('DATABOARD_MAIL_SENDER', '<EMAIL>') ) MAIL_RECIPIENTS = [] MAIL_USE_TLS =",
"working # is_parallelize RAMP_PARALLELIZE = bool(os.getenv('DATABOARD_PARALLELIZE', 1)) ###################################################################### class ProductionConfig(Config):",
"'submissions' RAMP_SANDBOX_DIR = 'starting_kit' RAMP_SERVER_PORT = 8080 # make it"
] |
[
"(bool, optional): whether spatial dimensions should be squeezed \"\"\" def",
"self.flatten = flatten def forward(self, x): if self.flatten: in_size =",
"# @Author zengxiaohui # Datatime:8/31/2021 1:37 PM # @File:GlobalAvgPool2d import",
"# Datatime:8/31/2021 1:37 PM # @File:GlobalAvgPool2d import torch.nn as nn",
"torch.nn as nn from python_developer_tools.cv.bases.activates.swish import h_swish class GlobalAvgPool2d(nn.Module): \"\"\"",
"class GlobalAvgPool2d(nn.Module): \"\"\" Fast implementation of global average pooling from",
"Fast implementation of global average pooling from TResNet: High Performance",
"in_size = x.size() return x.view((in_size[0], in_size[1], -1)).mean(dim=2) else: return x.view(x.size(0),",
"self.avgpool=nn.Sequential( nn.ReLU6(inplace=inplace), nn.AdaptiveAvgPool2d((1, 1)), h_swish() ) def forward(self, x): return",
"= False) -> None: super().__init__() self.flatten = flatten def forward(self,",
"= x.size() return x.view((in_size[0], in_size[1], -1)).mean(dim=2) else: return x.view(x.size(0), x.size(1),",
"None: super().__init__() self.flatten = flatten def forward(self, x): if self.flatten:",
"class SwishAdaptiveAvgPool2d(nn.Module): def __init__(self,inplace=True): super().__init__() self.avgpool=nn.Sequential( nn.ReLU6(inplace=inplace), nn.AdaptiveAvgPool2d((1, 1)), h_swish()",
"x.view(x.size(0), x.size(1), -1).mean(-1).view(x.size(0), x.size(1), 1, 1) class SwishAdaptiveAvgPool2d(nn.Module): def __init__(self,inplace=True):",
"# -- coding: utf-8 -- # @Author zengxiaohui # Datatime:8/31/2021",
"GPU-Dedicated Architecture https://arxiv.org/pdf/2003.13630.pdf Args: flatten (bool, optional): whether spatial dimensions",
"= flatten def forward(self, x): if self.flatten: in_size = x.size()",
"super().__init__() self.avgpool=nn.Sequential( nn.ReLU6(inplace=inplace), nn.AdaptiveAvgPool2d((1, 1)), h_swish() ) def forward(self, x):",
"Architecture https://arxiv.org/pdf/2003.13630.pdf Args: flatten (bool, optional): whether spatial dimensions should",
"\"\"\" Fast implementation of global average pooling from TResNet: High",
"python_developer_tools.cv.bases.activates.swish import h_swish class GlobalAvgPool2d(nn.Module): \"\"\" Fast implementation of global",
"x.size() return x.view((in_size[0], in_size[1], -1)).mean(dim=2) else: return x.view(x.size(0), x.size(1), -1).mean(-1).view(x.size(0),",
"super().__init__() self.flatten = flatten def forward(self, x): if self.flatten: in_size",
"flatten def forward(self, x): if self.flatten: in_size = x.size() return",
"pooling from TResNet: High Performance GPU-Dedicated Architecture https://arxiv.org/pdf/2003.13630.pdf Args: flatten",
"in_size[1], -1)).mean(dim=2) else: return x.view(x.size(0), x.size(1), -1).mean(-1).view(x.size(0), x.size(1), 1, 1)",
"spatial dimensions should be squeezed \"\"\" def __init__(self, flatten: bool",
"# @File:GlobalAvgPool2d import torch.nn as nn from python_developer_tools.cv.bases.activates.swish import h_swish",
"-- coding: utf-8 -- # @Author zengxiaohui # Datatime:8/31/2021 1:37",
"Performance GPU-Dedicated Architecture https://arxiv.org/pdf/2003.13630.pdf Args: flatten (bool, optional): whether spatial",
"from TResNet: High Performance GPU-Dedicated Architecture https://arxiv.org/pdf/2003.13630.pdf Args: flatten (bool,",
"Args: flatten (bool, optional): whether spatial dimensions should be squeezed",
"High Performance GPU-Dedicated Architecture https://arxiv.org/pdf/2003.13630.pdf Args: flatten (bool, optional): whether",
"-1).mean(-1).view(x.size(0), x.size(1), 1, 1) class SwishAdaptiveAvgPool2d(nn.Module): def __init__(self,inplace=True): super().__init__() self.avgpool=nn.Sequential(",
"x.size(1), 1, 1) class SwishAdaptiveAvgPool2d(nn.Module): def __init__(self,inplace=True): super().__init__() self.avgpool=nn.Sequential( nn.ReLU6(inplace=inplace),",
"@File:GlobalAvgPool2d import torch.nn as nn from python_developer_tools.cv.bases.activates.swish import h_swish class",
"1:37 PM # @File:GlobalAvgPool2d import torch.nn as nn from python_developer_tools.cv.bases.activates.swish",
"be squeezed \"\"\" def __init__(self, flatten: bool = False) ->",
"coding: utf-8 -- # @Author zengxiaohui # Datatime:8/31/2021 1:37 PM",
"<filename>python_developer_tools/cv/bases/pool/AvgPool2d.py # !/usr/bin/env python # -- coding: utf-8 -- #",
"return x.view((in_size[0], in_size[1], -1)).mean(dim=2) else: return x.view(x.size(0), x.size(1), -1).mean(-1).view(x.size(0), x.size(1),",
"return x.view(x.size(0), x.size(1), -1).mean(-1).view(x.size(0), x.size(1), 1, 1) class SwishAdaptiveAvgPool2d(nn.Module): def",
"@Author zengxiaohui # Datatime:8/31/2021 1:37 PM # @File:GlobalAvgPool2d import torch.nn",
"SwishAdaptiveAvgPool2d(nn.Module): def __init__(self,inplace=True): super().__init__() self.avgpool=nn.Sequential( nn.ReLU6(inplace=inplace), nn.AdaptiveAvgPool2d((1, 1)), h_swish() )",
"flatten: bool = False) -> None: super().__init__() self.flatten = flatten",
"should be squeezed \"\"\" def __init__(self, flatten: bool = False)",
"PM # @File:GlobalAvgPool2d import torch.nn as nn from python_developer_tools.cv.bases.activates.swish import",
"zengxiaohui # Datatime:8/31/2021 1:37 PM # @File:GlobalAvgPool2d import torch.nn as",
"# !/usr/bin/env python # -- coding: utf-8 -- # @Author",
"python # -- coding: utf-8 -- # @Author zengxiaohui #",
"import torch.nn as nn from python_developer_tools.cv.bases.activates.swish import h_swish class GlobalAvgPool2d(nn.Module):",
"-> None: super().__init__() self.flatten = flatten def forward(self, x): if",
"x.view((in_size[0], in_size[1], -1)).mean(dim=2) else: return x.view(x.size(0), x.size(1), -1).mean(-1).view(x.size(0), x.size(1), 1,",
"squeezed \"\"\" def __init__(self, flatten: bool = False) -> None:",
"flatten (bool, optional): whether spatial dimensions should be squeezed \"\"\"",
"1) class SwishAdaptiveAvgPool2d(nn.Module): def __init__(self,inplace=True): super().__init__() self.avgpool=nn.Sequential( nn.ReLU6(inplace=inplace), nn.AdaptiveAvgPool2d((1, 1)),",
"else: return x.view(x.size(0), x.size(1), -1).mean(-1).view(x.size(0), x.size(1), 1, 1) class SwishAdaptiveAvgPool2d(nn.Module):",
"utf-8 -- # @Author zengxiaohui # Datatime:8/31/2021 1:37 PM #",
"self.flatten: in_size = x.size() return x.view((in_size[0], in_size[1], -1)).mean(dim=2) else: return",
"https://arxiv.org/pdf/2003.13630.pdf Args: flatten (bool, optional): whether spatial dimensions should be",
"nn.ReLU6(inplace=inplace), nn.AdaptiveAvgPool2d((1, 1)), h_swish() ) def forward(self, x): return self.avgpool(x)",
"from python_developer_tools.cv.bases.activates.swish import h_swish class GlobalAvgPool2d(nn.Module): \"\"\" Fast implementation of",
"def __init__(self, flatten: bool = False) -> None: super().__init__() self.flatten",
"def forward(self, x): if self.flatten: in_size = x.size() return x.view((in_size[0],",
"__init__(self, flatten: bool = False) -> None: super().__init__() self.flatten =",
"!/usr/bin/env python # -- coding: utf-8 -- # @Author zengxiaohui",
"1, 1) class SwishAdaptiveAvgPool2d(nn.Module): def __init__(self,inplace=True): super().__init__() self.avgpool=nn.Sequential( nn.ReLU6(inplace=inplace), nn.AdaptiveAvgPool2d((1,",
"bool = False) -> None: super().__init__() self.flatten = flatten def",
"of global average pooling from TResNet: High Performance GPU-Dedicated Architecture",
"-1)).mean(dim=2) else: return x.view(x.size(0), x.size(1), -1).mean(-1).view(x.size(0), x.size(1), 1, 1) class",
"TResNet: High Performance GPU-Dedicated Architecture https://arxiv.org/pdf/2003.13630.pdf Args: flatten (bool, optional):",
"h_swish class GlobalAvgPool2d(nn.Module): \"\"\" Fast implementation of global average pooling",
"nn from python_developer_tools.cv.bases.activates.swish import h_swish class GlobalAvgPool2d(nn.Module): \"\"\" Fast implementation",
"forward(self, x): if self.flatten: in_size = x.size() return x.view((in_size[0], in_size[1],",
"as nn from python_developer_tools.cv.bases.activates.swish import h_swish class GlobalAvgPool2d(nn.Module): \"\"\" Fast",
"if self.flatten: in_size = x.size() return x.view((in_size[0], in_size[1], -1)).mean(dim=2) else:",
"def __init__(self,inplace=True): super().__init__() self.avgpool=nn.Sequential( nn.ReLU6(inplace=inplace), nn.AdaptiveAvgPool2d((1, 1)), h_swish() ) def",
"dimensions should be squeezed \"\"\" def __init__(self, flatten: bool =",
"import h_swish class GlobalAvgPool2d(nn.Module): \"\"\" Fast implementation of global average",
"x.size(1), -1).mean(-1).view(x.size(0), x.size(1), 1, 1) class SwishAdaptiveAvgPool2d(nn.Module): def __init__(self,inplace=True): super().__init__()",
"False) -> None: super().__init__() self.flatten = flatten def forward(self, x):",
"__init__(self,inplace=True): super().__init__() self.avgpool=nn.Sequential( nn.ReLU6(inplace=inplace), nn.AdaptiveAvgPool2d((1, 1)), h_swish() ) def forward(self,",
"global average pooling from TResNet: High Performance GPU-Dedicated Architecture https://arxiv.org/pdf/2003.13630.pdf",
"optional): whether spatial dimensions should be squeezed \"\"\" def __init__(self,",
"Datatime:8/31/2021 1:37 PM # @File:GlobalAvgPool2d import torch.nn as nn from",
"GlobalAvgPool2d(nn.Module): \"\"\" Fast implementation of global average pooling from TResNet:",
"average pooling from TResNet: High Performance GPU-Dedicated Architecture https://arxiv.org/pdf/2003.13630.pdf Args:",
"whether spatial dimensions should be squeezed \"\"\" def __init__(self, flatten:",
"-- # @Author zengxiaohui # Datatime:8/31/2021 1:37 PM # @File:GlobalAvgPool2d",
"\"\"\" def __init__(self, flatten: bool = False) -> None: super().__init__()",
"x): if self.flatten: in_size = x.size() return x.view((in_size[0], in_size[1], -1)).mean(dim=2)",
"implementation of global average pooling from TResNet: High Performance GPU-Dedicated"
] |
[
"Notes ----- This function uses a while loop. Although this",
"25 logging.addLevelName(EXP, 'EXP') def exp(self, message, *args, **kwargs): \"\"\"Experiment-level logging.\"\"\"",
"# actually add the stream handler logger.addHandler(lh) ############################################################################### # RANDOM",
"keys %s\\n' % (m1) for key in k1s: if key",
"subprocess import importlib import os import os.path as op import",
"send() def fake_mouse_click(ec, pos, button='left', delay=0.): \"\"\"Fake a mouse click",
"is not found (instead of returning default). Returns ------- value",
"fname_out def get_config_path(): r\"\"\"Get path to standard expyfun config file.",
"is searched first, then the expyfun config file is parsed.",
"for creating and auto-destroying temp dir This is designed to",
"a temporary solution, or:\\n' ' %s\\nfor a permanent one. You",
"_sort_keys(a) k2s = _sort_keys(b) m1 = set(k2s) - set(k1s) if",
"' 'channel count %d' % (signal.shape[0], n_channels)) return signal def",
"return self._decorate_fun(obj) def _decorate_class(self, cls): msg = \"Class %s is",
"just be able to do: lh = logging.StreamHandler(sys.stdout) but because",
"# settings using env, which are strings, so we enforce",
"verbose : bool, str, int, or None The verbosity of",
"exists). Otherwise, statements will be appended to the log (default).",
"string for the current date and time Returns ------- datestr",
"warnings.warn(msg, category=DeprecationWarning) return init(*args, **kwargs) cls.__init__ = wrapped wrapped.__name__ =",
"try: # until we get proper certificates context = ssl._create_unverified_context()",
"type Parameters ---------- units : str Must be ``'norm'``, ``'deg'``,",
"+ ' array mismatch\\n' else: raise RuntimeError(pre + ': unsupported",
"return cls def _decorate_fun(self, fun): \"\"\"Decorate function fun\"\"\" msg =",
"but additionally raises a warning to notify the user that",
"Returns ------- signal_fixed : array The signal with standard dimensions",
"context = None this_urlopen = urlopen if not op.isfile(fname_out): try:",
"True if key in config else False val = config.get(key,",
"string_types) and value is not None: raise ValueError('value must be",
"import pyglet is_usable = LooseVersion(pyglet.version) >= LooseVersion('1.2') if raise_error is",
"str, int, or None The verbosity of messages to print.",
"atexit.register(self.cleanup) def cleanup(self): if self._del_after is True: if self._print_del is",
"self._path = self.__str__() atexit.register(self.cleanup) def cleanup(self): if self._del_after is True:",
"logging.\"\"\" self.log(EXP, message, *args, **kwargs) logging.Logger.exp = exp logger =",
"vendor = pyglet.gl.gl_info.get_vendor() version = pyglet.gl.gl_info.get_version() sufficient = pyglet.gl.gl_info.have_version(2, 0)",
"bool If True, raise an error if the key is",
"= _sort_keys(b) m1 = set(k2s) - set(k1s) if len(m1): out",
"in {0}[\"{1}\"], must be ' 'one of {2}'.format(name, k, ',",
"on stdout, we have to do this: \"\"\" lh =",
"meth_1, meth_2)) return val def set_config(key, value): \"\"\"Set expyfun preference",
"class to work around how doctest captures stdout.\"\"\" def __getattr__(self,",
"for the current date and time Returns ------- datestr :",
"to the docstring. The optional extra argument will be appended",
"from cStringIO import StringIO # noqa else: string_types = str",
"CRITICAL. Note that these are for convenience and are equivalent",
"= urlopen if not op.isfile(fname_out): try: with open(fname_out, 'wb') as",
"type mismatch (%s, %s)\\n' % (type(a), type(b)) elif isinstance(a, dict):",
"characters. \"\"\" return text_type(text_like).encode('unicode_escape').decode('utf-8') def _sort_keys(x): \"\"\"Sort and return keys",
"# MISC def fake_button_press(ec, button='1', delay=0.): \"\"\"Fake a button press",
"input is mono and n_channels=2, it will be tiled to",
"\"\"\" good_units = ['norm', 'pix', 'deg'] if units not in",
"_get_display(): import pyglet try: display = pyglet.canvas.get_display() except AttributeError: #",
"importlib.import_module(lib) except Exception as exp: val = True reason =",
"setting the verbosity level. Returns ------- dec - function The",
"[key for key, param in params.items() if param.kind not in",
"def running_rms(signal, win_length): \"\"\"RMS of ``signal`` with rectangular window ``win_length``",
"json.dump(config, fid, sort_keys=True, indent=0) ############################################################################### # MISC def fake_button_press(ec, button='1',",
"variable EXPYFUN_LOGGING_LEVEL is read, and if it doesn't exist, defaults",
"return sqrt(convolve(signal ** 2, ones(win_length) / win_length, 'valid')) def _fix_audio_dims(signal,",
"atexit module instead. Passing del_after and print_del kwargs to the",
"return_old_level else None) def set_log_file(fname=None, output_format='%(asctime)s - %(levelname)-7s - %(message)s',",
"verbose = get_config('EXPYFUN_LOGGING_LEVEL', 'INFO') elif isinstance(verbose, bool): verbose = 'INFO'",
"of {}, not {}' ''.format(good_units, units)) ############################################################################### # DECORATORS #",
"LooseVersion from numpy import sqrt, convolve, ones import logging import",
"default=None, raise_error=False): \"\"\"Read expyfun preference from env, then expyfun config",
"_get_args(function) if len(arg_names) > 0 and arg_names[0] == 'self': default_level",
"type(b): out += pre + ' type mismatch (%s, %s)\\n'",
"have to do this: \"\"\" lh = logging.StreamHandler(WrapStdOut()) lh.setFormatter(logging.Formatter(output_format)) #",
"params[k] = params.get(k, get_config(k, defaults.get(k, None))) # Check keys for",
"is used above def __init__(self, extra=''): \"\"\" Parameters ---------- extra:",
"\"\"\"Requires OpenGL decorator.\"\"\" import pytest import pyglet.gl vendor = pyglet.gl.gl_info.get_vendor()",
"' %s\\nfor a permanent one. You can also ' 'set",
"dict(stderr=subprocess.PIPE, stdout=subprocess.PIPE) kw.update(kwargs) p = subprocess.Popen(command, **kw) stdout_, stderr =",
"so other commands can be called (like wait_for_presses). \"\"\" def",
"function : callable Function to be decorated by setting the",
"date_str(): \"\"\"Produce a date string for the current date and",
"print to a file Parameters ---------- fname : str, or",
"reason='Requires FFmpeg/AVbin') def requires_opengl21(func): \"\"\"Requires OpenGL decorator.\"\"\" import pytest import",
"dict, got {1}' .format(name, type(params))) # Set sensible defaults for",
"raw_input # noqa, input is raw_input in py3k text_type =",
"(m1) for key in k1s: if key not in k2s:",
"%(levelname)-7s - %(message)s', overwrite=None): \"\"\"Convenience function for setting the log",
"= logging.getLogger('expyfun') def flush_logger(): \"\"\"Flush expyfun logger\"\"\" for handler in",
"key is not None and key in os.environ: return os.environ[key]",
"stdout=subprocess.PIPE) kw.update(kwargs) p = subprocess.Popen(command, **kw) stdout_, stderr = p.communicate()",
"<expyfun._utils.deprecated object at ...> >>> @deprecated() ... def some_function(): pass",
"= input from io import StringIO # noqa, analysis:ignore from",
"backend['SOUND_CARD_BACKEND'] try: _import_backend(backend) except Exception as exc: pytest.skip('Skipping test for",
"n_channels = int(operator.index(n_channels)) signal = np.asarray(np.atleast_2d(signal), dtype=np.float32) # Check dimensionality",
"% (backend, exc)) def _check_params(params, keys, defaults, name): if not",
"type(params))) # Set sensible defaults for values that are not",
"config_path : str The path to the expyfun configuration file.",
"Parameters ---------- function : callable Function to be decorated by",
"except Exception: pass # for py3k (eventually) if sys.version.startswith('2'): string_types",
"raise subprocess.CalledProcessError(p.returncode, command) return output class ZeroClock(object): \"\"\"Clock that uses",
"that here if not isinstance(value, string_types) and value is not",
"be of a valid type') verbose = logging_types[verbose] old_verbose =",
"users to override config # settings using env, which are",
"if varargs: varargs = [param.name for param in params.values() if",
": bool, str, int, or None The verbosity of messages",
"and value is not None: raise ValueError('value must be a",
"flush_logger(): \"\"\"Flush expyfun logger\"\"\" for handler in logger.handlers: handler.flush() def",
"usable. \"\"\" import pyglet is_usable = LooseVersion(pyglet.version) >= LooseVersion('1.2') if",
"permission. \"\"\" out = '' if type(a) != type(b): out",
"import pytest try: importlib.import_module(lib) except Exception as exp: val =",
"def _update_doc(self, olddoc): newdoc = \"DEPRECATED\" if self.extra: newdoc =",
"be a dict, got {1}' .format(name, type(params))) # Set sensible",
"with correct dimensions if n_channels == 2 and signal.shape[0] ==",
"% (key, config_path, meth_1, meth_2)) return val def set_config(key, value):",
"% (vendor, version,))(func) def requires_lib(lib): \"\"\"Requires lib decorator.\"\"\" import pytest",
"+ ' type mismatch (%s, %s)\\n' % (type(a), type(b)) elif",
"'error to expyfun developers') return val def fetch_data_file(fname): \"\"\"Fetch example",
"You can also ' 'set the environment variable before '",
"t0 = clock() if ec is not None: while (clock()",
"self._print_del = print_del return new def __init__(self): self._path = self.__str__()",
"<NAME> <<EMAIL>> # # License: BSD (3-clause) import warnings import",
"it so a valid audio buffer is in the standard",
"not passed for k in keys: params[k] = params.get(k, get_config(k,",
"for setting the log to print to a file Parameters",
"raise ValueError('expyfun config file path could ' 'not be determined,",
"op.join(path, fname) if not op.isdir(op.dirname(fname_out)): os.makedirs(op.dirname(fname_out)) fname_url = ('https://github.com/LABSN/expyfun-data/raw/master/{0}' ''.format(fname))",
"command and wait for command to complete. If the return",
"The remote filename to get. If the filename already exists",
"% cls.__name__ if self.extra: msg += \"; %s\" % self.extra",
"__init__(self): self._path = self.__str__() atexit.register(self.cleanup) def cleanup(self): if self._del_after is",
"value. \"\"\" if key is not None and not isinstance(key,",
"| None Value to return if the key is not",
"else: verbose_level = default_level if verbose_level is not None: old_level",
"if self.extra: msg += \"; %s\" % self.extra def wrapped(*args,",
"fid.write(www.read()) finally: www.close() except Exception: os.remove(fname_out) raise return fname_out def",
"# Return data with correct dimensions if n_channels == 2",
"None return args, varargs else: return args else: def _get_args(function,",
"set(k2s) - set(k1s) if len(m1): out += pre + '",
"wrapped.deprecated_original = init return cls def _decorate_fun(self, fun): \"\"\"Decorate function",
"of parentheses: >>> from expyfun._utils import deprecated >>> deprecated() #",
"and the docstring. Note: to use this with the default",
"datetime from timeit import default_timer as clock from threading import",
"the file. Use ' 'overwrite=False to avoid this message in",
"messages \"\"\" self.extra = extra def __call__(self, obj): \"\"\"Call.\"\"\" if",
"in expyfun config file config_path = get_config_path() if not op.isfile(config_path):",
"not match required ' 'channel count %d' % (signal.shape[0], n_channels))",
"value : str | None The preference key value. \"\"\"",
"from mne-python with permission. \"\"\" out = '' if type(a)",
"raise TypeError('{0} must be a dict, got {1}' .format(name, type(params)))",
"pyglet pyglet.options['debug_gl'] = False del pyglet except Exception: pass #",
"py3k text_type = unicode # noqa from __builtin__ import reload",
"float, StringIO, BytesIO. b : object Must be same type",
"valid units type Parameters ---------- units : str Must be",
"version = pyglet.gl.gl_info.get_version() sufficient = pyglet.gl.gl_info.have_version(2, 0) return pytest.mark.skipif(not sufficient,",
"if key is not None and not isinstance(key, string_types): raise",
"other commands can be called (like wait_for_presses). \"\"\" def send():",
"Returns ------- value : str | None The preference key",
": bool If True, return the old verbosity level. \"\"\"",
"else: wins = _get_display().get_windows() for win in wins: win.dispatch_events() def",
"return out[0] @decorator def verbose_dec(function, *args, **kwargs): \"\"\"Improved verbose decorator",
"\"Class %s is deprecated\" % cls.__name__ if self.extra: msg +=",
"pyglet.media.codecs.ffmpeg import FFmpegSource # noqa except ImportError: return False else:",
"pre + ' x1 missing keys %s\\n' % (m1) for",
"standard expyfun config file. Returns ------- config_path : str The",
"% (len(a), len(b)) else: for xx1, xx2 in zip(a, b):",
"each line. Returns ------- diffs : str A string representation",
"output messages. See the following for examples: http://docs.python.org/dev/howto/logging.html e.g., \"%(asctime)s",
"but starts at zero on init.\"\"\" def __init__(self): self._start_time =",
"should probably reset __new__ for full generality init = cls.__init__",
"not \\ any(k in key for k in known_config_wildcards): warnings.warn('Setting",
"FFmpeg/AVbin') def requires_opengl21(func): \"\"\"Requires OpenGL decorator.\"\"\" import pytest import pyglet.gl",
"if signal.shape[0] != n_channels: raise ValueError('signal channel count %d did",
"in idx] return keys def object_diff(a, b, pre=''): \"\"\"Compute all",
"the expyfun config file is parsed. default : str |",
"k2s: out += pre + ' x2 missing key %s\\n'",
"= 'Needs %s (%s)' % (lib, exp) else: val =",
"instantiated and adds a warning to the docstring. The optional",
"= basestring # noqa input = raw_input # noqa, input",
"arg_names[0] == 'self': default_level = getattr(args[0], 'verbose', None) else: default_level",
"used with testing modules. We cannot simply use __del__() method",
"the following for examples: http://docs.python.org/dev/howto/logging.html e.g., \"%(asctime)s - %(levelname)s -",
"any('sphinx-build' in ((''.join(i[4]).lower() + i[1]) if i[4] is not None",
"# noqa else: string_types = str text_type = str from",
"= print_del return new def __init__(self): self._path = self.__str__() atexit.register(self.cleanup)",
"if self.extra: msg += \"; %s\" % self.extra # FIXME:",
"new expyfun configuration ' 'file:\\n%s' % config_path) if value is",
"create new expyfun configuration ' 'file:\\n%s' % config_path) if value",
"processed. \"\"\" # hog the cpu, checking time t0 =",
"+ ' x2 missing key %s\\n' % key else: out",
"http://docs.python.org/dev/howto/logging.html e.g., \"%(asctime)s - %(levelname)s - %(message)s\". overwrite : bool,",
"``'pix'``. \"\"\" good_units = ['norm', 'pix', 'deg'] if units not",
"zip(a, b): out += object_diff(xx1, xx2, pre='') elif isinstance(a, (string_types,",
"copied from scikit-learn class deprecated(object): \"\"\"Decorator to mark a function",
"False, but additionally raises a warning to notify the user",
"file Parameters ---------- fname : str The remote filename to",
"adds a warning to the docstring. The optional extra argument",
"ValueError('verbose must be of a valid type') verbose = logging_types[verbose]",
"UTILITIES building_doc = any('sphinx-build' in ((''.join(i[4]).lower() + i[1]) if i[4]",
"1)) if signal.shape[0] != n_channels: raise ValueError('signal channel count %d",
"idx = np.argsort([str(k) for k in keys]) keys = [keys[ii]",
"same as 'INFO', False is the same as 'WARNING'. If",
"path = get_config('EXPYFUN_DATA_PATH', op.join(_get_user_home_path(), '.expyfun', 'data')) fname_out = op.join(path, fname)",
"return ret else: ret = function(*args, **kwargs) return ret def",
"either DEBUG, INFO, WARNING, ERROR, or CRITICAL. Note that these",
"type): return self._decorate_class(obj) else: return self._decorate_fun(obj) def _decorate_class(self, cls): msg",
"dict): k1s = _sort_keys(a) k2s = _sort_keys(b) m1 = set(k2s)",
"stdout, we have to do this: \"\"\" lh = logging.StreamHandler(WrapStdOut())",
"'SCREEN_WIDTH', 'SCREEN_DISTANCE', 'SCREEN_SIZE_PIX', 'EXPYFUN_LOGGING_LEVEL', ) # These allow for partial",
"The number of channels that the output should have. If",
"to the file. Use ' 'overwrite=False to avoid this message",
"[]) Timer(delay, send).start() if delay > 0. else send() def",
"wrapped.__dict__ = fun.__dict__ wrapped.__doc__ = self._update_doc(fun.__doc__) return wrapped def _update_doc(self,",
"this directly to set global verbosrity level, instead use set_log_level().",
"input = input from io import StringIO # noqa, analysis:ignore",
"dimensions if n_channels == 2 and signal.shape[0] == 1: signal",
"analysis:ignore from importlib import reload # noqa, analysis:ignore ############################################################################### #",
"for k in keys]) keys = [keys[ii] for ii in",
"else 'WARNING' if isinstance(verbose, string_types): verbose = verbose.upper() logging_types =",
"config # settings using env, which are strings, so we",
"Parameters ---------- fname : str, or None Filename of the",
"'future.') mode = 'w' if overwrite is True else 'a'",
"zero then return, otherwise raise CalledProcessError. By default, this will",
"msg += \"; %s\" % self.extra # FIXME: we should",
"local system, the file will not be fetched again. Returns",
": bool, or None Overwrite the log file (if it",
"sorted(known_config_types) if not isinstance(key, string_types): raise ValueError('key must be a",
"def get_config_path(): r\"\"\"Get path to standard expyfun config file. Returns",
"value # Write all values directory = op.split(config_path)[0] if not",
"stdout is used. To suppress log outputs, use set_log_level('WARN'). output_format",
"if the key is not found. raise_error : bool If",
"import deepcopy import subprocess import importlib import os import os.path",
"expyfun preference in config Parameters ---------- key : str |",
"values directory = op.split(config_path)[0] if not op.isdir(directory): os.mkdir(directory) with open(config_path,",
"it can be either DEBUG, INFO, WARNING, ERROR, or CRITICAL.",
"will be $HOME/.expyfun/expyfun.json. \"\"\" val = op.join(_get_user_home_path(), '.expyfun', 'expyfun.json') return",
"varargs = [param.name for param in params.values() if param.kind ==",
"text_type = str from urllib.request import urlopen input = input",
"to ensure that control is passed back, so other commands",
"else: \"\"\" we should just be able to do: lh",
"configuration ' 'file:\\n%s' % config_path) if value is None: config.pop(key,",
"this with the default value for extra, put in an",
"----- Taken from mne-python with permission. \"\"\" out = ''",
"if len(a) != len(b): out += pre + ' length",
"isinstance(obj, type): return self._decorate_class(obj) else: return self._decorate_fun(obj) def _decorate_class(self, cls):",
"exc)) def _check_params(params, keys, defaults, name): if not isinstance(params, dict):",
"with permission. \"\"\" out = '' if type(a) != type(b):",
"return signal def _sanitize(text_like): \"\"\"Cast as string, encode as UTF-8",
"function uses a while loop. Although this slams the CPU,",
"Following deprecated class copied from scikit-learn class deprecated(object): \"\"\"Decorator to",
"of the log to print to. If None, stdout is",
"np.argsort([str(k) for k in keys]) keys = [keys[ii] for ii",
"\"\"\" handlers = logger.handlers for h in handlers: if isinstance(h,",
"with open(config_path, 'r') as fid: config = json.load(fid) if key",
"must be a dict, got {1}' .format(name, type(params))) # Set",
"bool, True is the same as 'INFO', False is the",
"and n_channels=2, it will be tiled to be shape (2,",
"None) if val is None: raise ValueError('expyfun config file path",
"def cleanup(self): if self._del_after is True: if self._print_del is True:",
"for extra, put in an empty of parentheses: >>> from",
"on all platforms b/c it can be # sklearn or",
"or None Filename of the log to print to. If",
"dict(left=1, middle=2, right=4)[button] # trans to pyglet def send(): ec._mouse_handler._on_pyglet_mouse_click(pos[0],",
"%(message)s\". overwrite : bool, or None Overwrite the log file",
"deepcopy(params) if not isinstance(params, dict): raise TypeError('{0} must be a",
"(%s)' % (lib, exp) else: val = False reason =",
"keys: raise KeyError('Unrecognized key in {0}[\"{1}\"], must be ' 'one",
"not thread-safe idx = np.argsort([str(k) for k in keys]) keys",
"as deprecated. Issue a warning when the function is called/the",
"None, stdout is used. To suppress log outputs, use set_log_level('WARN').",
"Parameters ---------- extra: string to be added to the deprecation",
"0. else send() def fake_mouse_click(ec, pos, button='left', delay=0.): \"\"\"Fake a",
"import inspect import sys import tempfile import ssl from shutil",
"config_path, meth_1, meth_2)) return val def set_config(key, value): \"\"\"Set expyfun",
"supported: dict, list, tuple, ndarray, int, str, bytes, float, StringIO,",
"known_config_wildcards): warnings.warn('Setting non-standard config type: \"%s\"' % key) # Read",
"+ ' value mismatch (%s, %s)\\n' % (a, b) elif",
"def set_config(key, value): \"\"\"Set expyfun preference in config Parameters ----------",
"os.name.lower() else 'HOME', None) if val is None: raise ValueError('expyfun",
"environment is searched first, then the expyfun config file is",
"permanent one. You can also ' 'set the environment variable",
"k2s = _sort_keys(b) m1 = set(k2s) - set(k1s) if len(m1):",
"------- datestr : str The date string. \"\"\" return str(datetime.datetime.today()).replace(':',",
"key is not found (instead of returning default). Returns -------",
"N). \"\"\" # Check requested channel output n_channels = int(operator.index(n_channels))",
"return clock() - self._start_time def date_str(): \"\"\"Produce a date string",
"return getattr(sys.stdout, name) class _TempDir(str): \"\"\"Class for creating and auto-destroying",
"params.keys(): if k not in keys: raise KeyError('Unrecognized key in",
"warning to notify the user that log entries will be",
"VALUE' % key meth_2 = 'expyfun.utils.set_config(\"%s\", VALUE)' % key raise",
"some magic on stdout, we have to do this: \"\"\"",
"deleted. \"\"\" if key is None: return sorted(known_config_types) if not",
"in os.environ: return os.environ[key] # second, look for it in",
"is None: verbose = get_config('EXPYFUN_LOGGING_LEVEL', 'INFO') elif isinstance(verbose, bool): verbose",
"fake_button_press(ec, button='1', delay=0.): \"\"\"Fake a button press after a delay",
"'TDT_DELAY', 'TDT_INTERFACE', 'TDT_MODEL', 'TDT_TRIG_DELAY', 'TRIGGER_CONTROLLER', 'TRIGGER_ADDRESS', 'WINDOW_SIZE', 'SCREEN_NUM', 'SCREEN_WIDTH', 'SCREEN_DISTANCE',",
"(clock() - t0) < secs: ec._dispatch_events() ec.check_force_quit() else: wins =",
"%s: %s' % (backend, exc)) def _check_params(params, keys, defaults, name):",
"from urllib2 import urlopen # noqa from cStringIO import StringIO",
"to look for. The os environment is searched first, then",
"(string_types, int, float, bytes)): if a != b: out +=",
"use this with the default value for extra, put in",
"FIXME: we should probably reset __new__ for full generality init",
"The os environment is searched first, then the expyfun config",
"# py35 def _get_args(function, varargs=False): params = inspect.signature(function).parameters args =",
"False val = config.get(key, default) if not key_found and raise_error",
"out += object_diff(a[key], b[key], pre + 'd1[%s]' % repr(key)) elif",
"events (keypresses, etc.) are processed. \"\"\" # hog the cpu,",
"tiled to be shape (2, n_samples). Otherwise, the number of",
"\"\"\"Cast as string, encode as UTF-8 and sanitize any escape",
"or two dimensions, got %s.' % (signal.ndim,)) # Return data",
"for xx1, xx2 in zip(a, b): out += object_diff(xx1, xx2,",
"in logger.handlers: handler.flush() def set_log_level(verbose=None, return_old_level=False): \"\"\"Convenience function for setting",
"---------- a : object Currently supported: dict, list, tuple, ndarray,",
"AVbinSource # noqa except ImportError: return False return True def",
"suppress printing to the terminal. Parameters ---------- command : list",
"str | None Value to return if the key is",
"{}' ''.format(good_units, units)) ############################################################################### # DECORATORS # Following deprecated class",
"will be '%APPDATA%\\.expyfun\\expyfun.json'. On every other system, this will be",
"% (signal.shape[0], n_channels)) return signal def _sanitize(text_like): \"\"\"Cast as string,",
"you must run at least Pyglet ' 'version 1.2, and",
"signal.shape[0] != n_channels: raise ValueError('signal channel count %d did not",
"def _get_user_home_path(): \"\"\"Return standard preferences path\"\"\" # this has been",
"noqa, analysis:ignore from importlib import reload # noqa, analysis:ignore ###############################################################################",
"string') # first, check to see if key is in",
"is not None and key in os.environ: return os.environ[key] #",
"# set this first thing to make sure it \"takes\"",
"Returns ------- datestr : str The date string. \"\"\" return",
"the current date and time Returns ------- datestr : str",
"# this has been checked on OSX64, Linux64, and Win32",
"%s (%s)' % (lib, exp) else: val = False reason",
"\"\"\"Some utility functions\"\"\" # Authors: <NAME> <<EMAIL>> # # License:",
"else: out += object_diff(a[key], b[key], pre + 'd1[%s]' % repr(key))",
"other system, this will be $HOME/.expyfun/expyfun.json. \"\"\" val = op.join(_get_user_home_path(),",
"%s\" % self.extra def wrapped(*args, **kwargs): warnings.warn(msg, category=DeprecationWarning) return fun(*args,",
"'verbose', None) else: default_level = None if('verbose' in arg_names): verbose_level",
"= ('RESPONSE_DEVICE', 'AUDIO_CONTROLLER', 'DB_OF_SINE_AT_1KHZ_1RMS', 'EXPYFUN_EYELINK', 'SOUND_CARD_API', 'SOUND_CARD_BACKEND', 'SOUND_CARD_FS', 'SOUND_CARD_NAME', 'SOUND_CARD_FIXED_DELAY',",
"== os.name.lower() else 'HOME', None) if val is None: raise",
"threading import Timer import numpy as np import scipy as",
"str Must be ``'norm'``, ``'deg'``, or ``'pix'``. \"\"\" good_units =",
"in arg_names): verbose_level = args[arg_names.index('verbose')] else: verbose_level = default_level if",
"mono and n_channels=2, it will be tiled to be shape",
"then the expyfun config file is parsed. default : str",
"op.join(_get_user_home_path(), '.expyfun', 'data')) fname_out = op.join(path, fname) if not op.isdir(op.dirname(fname_out)):",
"got %s.' % (signal.ndim,)) # Return data with correct dimensions",
"(if it exists). Otherwise, statements will be appended to the",
"entries will be appended to the file. Use ' 'overwrite=False",
"file. Returns ------- config_path : str The path to the",
"# first, check to see if key is in env",
"that control is passed back, so other commands can be",
"key else: out += object_diff(a[key], b[key], pre + 'd1[%s]' %",
"importlib import os import os.path as op import inspect import",
"'set the environment variable before ' 'running python.' % (key,",
"\"\"\"Read expyfun preference from env, then expyfun config Parameters ----------",
"OSX64, Linux64, and Win32 val = os.getenv('APPDATA' if 'nt' ==",
") # These allow for partial matches: 'NAME_1' is okay",
"handlers = logger.handlers for h in handlers: if isinstance(h, logging.FileHandler):",
"LooseVersion('1.4') def _has_video(): if _new_pyglet(): try: from pyglet.media.codecs.ffmpeg import FFmpegSource",
"# actually an AC backend = backend['SOUND_CARD_BACKEND'] try: _import_backend(backend) except",
"partial(urlopen, context=context) except AttributeError: context = None this_urlopen = urlopen",
"with rectangular window ``win_length`` samples long. Parameters ---------- signal :",
"These allow for partial matches: 'NAME_1' is okay key if",
"must be a string or None') if key not in",
"same as False, but additionally raises a warning to notify",
"\"\"\"Wait a specified number of seconds. Parameters ---------- secs :",
"def requires_opengl21(func): \"\"\"Requires OpenGL decorator.\"\"\" import pytest import pyglet.gl vendor",
"ValueError('Sound data must have one or two dimensions, got %s.'",
"but because doctests uses some magic on stdout, we have",
"standard preferences path\"\"\" # this has been checked on OSX64,",
"send).start() if delay > 0. else send() def fake_mouse_click(ec, pos,",
"Note that these are for convenience and are equivalent to",
"sys import tempfile import ssl from shutil import rmtree import",
"import pytest return pytest.mark.skipif(not _has_video(), reason='Requires FFmpeg/AVbin') def requires_opengl21(func): \"\"\"Requires",
"isinstance(value, string_types) and value is not None: raise ValueError('value must",
"= args[arg_names.index('verbose')] else: verbose_level = default_level if verbose_level is not",
"text_type = unicode # noqa from __builtin__ import reload from",
": array_like The signal whose dimensions should be checked and",
"(signal.shape[0], n_channels)) return signal def _sanitize(text_like): \"\"\"Cast as string, encode",
"windows, this will be '%APPDATA%\\.expyfun\\expyfun.json'. On every other system, this",
"preference key to set. If None, a tuple of the",
"object, so we use the atexit module instead. Passing del_after",
"True and is_usable is False: raise ImportError('On Linux, you must",
"n_channels: raise ValueError('signal channel count %d did not match required",
"not None: while (clock() - t0) < secs: ec._dispatch_events() ec.check_force_quit()",
"------- config_path : str The path to the expyfun configuration",
"Stdout returned by the process. stderr : str Stderr returned",
"this class, this must be sys.stdout (not # just stdout)",
"int The number of channels that the output should have.",
"_new_pyglet(): try: from pyglet.media.codecs.ffmpeg import FFmpegSource # noqa except ImportError:",
"the deprecation message and the docstring. Note: to use this",
"bytes, float, StringIO, BytesIO. b : object Must be same",
"_get_args(err_fun): raise subprocess.CalledProcessError(p.returncode, command, output) else: raise subprocess.CalledProcessError(p.returncode, command) return",
"Adapted from http://wiki.python.org/moin/PythonDecoratorLibrary, # but with many changes. # scikit-learn",
"We cannot simply use __del__() method for cleanup here because",
"setting the logging level Parameters ---------- verbose : bool, str,",
"dimensions should be checked and fixed. n_channels : int The",
"to set global verbosrity level, instead use set_log_level(). Parameters ----------",
"True reason = 'Needs %s (%s)' % (lib, exp) else:",
"None: if op.isfile(fname) and overwrite is None: warnings.warn('Log entries will",
"preference key value. \"\"\" if key is not None and",
"a date string for the current date and time Returns",
"user that log entries will be appended. \"\"\" handlers =",
"new def __init__(self): self._path = self.__str__() atexit.register(self.cleanup) def cleanup(self): if",
"representation of the differences. Notes ----- Taken from mne-python with",
"(2, n_samples). Otherwise, the number of channels in signal must",
"return str(datetime.datetime.today()).replace(':', '_') class WrapStdOut(object): \"\"\"Ridiculous class to work around",
"in wins: win.dispatch_events() def running_rms(signal, win_length): \"\"\"RMS of ``signal`` with",
"(b) elif isinstance(a, np.ndarray): if not np.array_equal(a, b): out +=",
"= True if key in config else False val =",
"in env if key is not None and key in",
"log file (if it exists). Otherwise, statements will be appended",
"as False, but additionally raises a warning to notify the",
"pre : str String to prepend to each line. Returns",
"type {1}' .format(name, type(params))) params = deepcopy(params) if not isinstance(params,",
"raise CalledProcessError. By default, this will also add stdout= and",
"pre + ' array mismatch\\n' else: raise RuntimeError(pre + ':",
"msg += \"; %s\" % self.extra def wrapped(*args, **kwargs): warnings.warn(msg,",
"varargs=False): params = inspect.signature(function).parameters args = [key for key, param",
"is read, and if it doesn't exist, defaults to INFO.",
"logger = logging.getLogger('expyfun') def flush_logger(): \"\"\"Flush expyfun logger\"\"\" for handler",
"= logging.FileHandler(fname, mode=mode) else: \"\"\" we should just be able",
"return pytest.mark.skipif(not sufficient, reason='OpenGL too old: %s %s' % (vendor,",
"import datetime from timeit import default_timer as clock from threading",
"enforce that here if not isinstance(value, string_types) and value is",
"rectangular window \"\"\" return sqrt(convolve(signal ** 2, ones(win_length) / win_length,",
"This function only works with the keyboard controller (not TDT)!",
"True if usable. \"\"\" import pyglet is_usable = LooseVersion(pyglet.version) >=",
"str The path to the expyfun configuration file. On windows,",
"as fid: config = json.load(fid) else: config = dict() logger.info('Attempting",
"if verbose is True else 'WARNING' if isinstance(verbose, string_types): verbose",
"the filename already exists on the local system, the file",
"class as deprecated. Issue a warning when the function is",
"preference from env, then expyfun config Parameters ---------- key :",
"in known_config_types and not \\ any(k in key for k",
"= np.tile(signal, (n_channels, 1)) if signal.shape[0] != n_channels: raise ValueError('signal",
"was downloaded. \"\"\" path = get_config('EXPYFUN_DATA_PATH', op.join(_get_user_home_path(), '.expyfun', 'data')) fname_out",
"varargs = None return args, varargs else: return args else:",
"this will also add stdout= and stderr=subproces.PIPE to the call",
"decorated function \"\"\" arg_names = _get_args(function) if len(arg_names) > 0",
"and Win32 val = os.getenv('APPDATA' if 'nt' == os.name.lower() else",
"'a' lh = logging.FileHandler(fname, mode=mode) else: \"\"\" we should just",
"verbosity level. Returns ------- dec - function The decorated function",
"Linux) return getattr(sys.stdout, name) class _TempDir(str): \"\"\"Class for creating and",
"(LooseVersion(sp.__version__) >= LooseVersion(version)) def _get_user_home_path(): \"\"\"Return standard preferences path\"\"\" #",
"**kwargs) except Exception: set_log_level(old_level) raise set_log_level(old_level) return ret else: ret",
"override log-level Do not call this directly to set global",
"must be a dict, got type {1}' .format(name, type(params))) params",
"= subprocess.CalledProcessError.__init__ if 'output' in _get_args(err_fun): raise subprocess.CalledProcessError(p.returncode, command, output)",
"------- fname : str The filename on the local system",
"if isinstance(backend, dict): # actually an AC backend = backend['SOUND_CARD_BACKEND']",
"xx2, pre='') elif isinstance(a, (string_types, int, float, bytes)): if a",
"values config_path = get_config_path() if op.isfile(config_path): with open(config_path, 'r') as",
"this first thing to make sure it \"takes\" try: import",
"the return code was zero then return, otherwise raise CalledProcessError.",
"Even more ridiculous than this class, this must be sys.stdout",
"os.mkdir(directory) with open(config_path, 'w') as fid: json.dump(config, fid, sort_keys=True, indent=0)",
"is_usable def _wait_secs(secs, ec=None): \"\"\"Wait a specified number of seconds.",
"bytes)): if a != b: out += pre + '",
">= LooseVersion('1.4') def _has_video(): if _new_pyglet(): try: from pyglet.media.codecs.ffmpeg import",
"the same as 'WARNING'. If None, the environment variable EXPYFUN_LOGGING_LEVEL",
"encode as UTF-8 and sanitize any escape characters. \"\"\" return",
"= default_level if verbose_level is not None: old_level = set_log_level(verbose_level,",
"key if 'NAME' is listed known_config_wildcards = () def get_config(key=None,",
"after a delay Notes ----- This function only works with",
"stderr : str Stderr returned by the process. \"\"\" #",
"def get_time(self): \"\"\"Get time.\"\"\" return clock() - self._start_time def date_str():",
"key is None: return config key_found = True if key",
"ValueError('signal channel count %d did not match required ' 'channel",
"'d1[%s]' % repr(key)) elif isinstance(a, (list, tuple)): if len(a) !=",
"Parameters ---------- verbose : bool, str, int, or None The",
"= os.getenv('APPDATA' if 'nt' == os.name.lower() else 'HOME', None) if",
"thread-safe idx = np.argsort([str(k) for k in keys]) keys =",
"True else 'a' lh = logging.FileHandler(fname, mode=mode) else: \"\"\" we",
"'' return pytest.mark.skipif(val, reason=reason) def _has_scipy_version(version): return (LooseVersion(sp.__version__) >= LooseVersion(version))",
"dict): raise TypeError('{0} must be a dict, got {1}' .format(name,",
"'SCREEN_DISTANCE', 'SCREEN_SIZE_PIX', 'EXPYFUN_LOGGING_LEVEL', ) # These allow for partial matches:",
"seconds to wait. ec : None | expyfun.ExperimentController instance The",
"(1-dimesional) signal of interest. win_length : int Length (in samples)",
"param.VAR_KEYWORD)] if varargs: varargs = [param.name for param in params.values()",
"please report this ' 'error to expyfun developers') return val",
"# noqa input = raw_input # noqa, input is raw_input",
"if self.extra: newdoc = \"%s: %s\" % (newdoc, self.extra) if",
"return True def requires_video(): \"\"\"Requires FFmpeg/AVbin decorator.\"\"\" import pytest return",
"return val def fetch_data_file(fname): \"\"\"Fetch example remote file Parameters ----------",
"(%s, %s)\\n' % (type(a), type(b)) elif isinstance(a, dict): k1s =",
"get_config_path() if op.isfile(config_path): with open(config_path, 'r') as fid: config =",
"context = ssl._create_unverified_context() this_urlopen = partial(urlopen, context=context) except AttributeError: context",
"- %(levelname)s - %(message)s\". overwrite : bool, or None Overwrite",
"printing to the terminal. Parameters ---------- command : list of",
"= np.argsort([str(k) for k in keys]) keys = [keys[ii] for",
"key for k in known_config_wildcards): warnings.warn('Setting non-standard config type: \"%s\"'",
"# Read all previous values config_path = get_config_path() if op.isfile(config_path):",
"lib decorator.\"\"\" import pytest try: importlib.import_module(lib) except Exception as exp:",
"running ' '{0}'.format(pyglet.version)) return is_usable def _wait_secs(secs, ec=None): \"\"\"Wait a",
"str Format of the output messages. See the following for",
"expyfun config file config_path = get_config_path() if not op.isfile(config_path): key_found",
"python.' % (key, config_path, meth_1, meth_2)) return val def set_config(key,",
"\\ any(k in key for k in known_config_wildcards): warnings.warn('Setting non-standard",
"# trans to pyglet def send(): ec._mouse_handler._on_pyglet_mouse_click(pos[0], pos[1], button, [])",
"string_types = basestring # noqa input = raw_input # noqa,",
"Filename of the log to print to. If None, stdout",
"delay > 0. else send() def _check_pyglet_version(raise_error=False): \"\"\"Check pyglet version,",
"for full generality init = cls.__init__ def wrapped(*args, **kwargs): warnings.warn(msg,",
"this message in the ' 'future.') mode = 'w' if",
"the differences. Notes ----- Taken from mne-python with permission. \"\"\"",
"warnings import operator from copy import deepcopy import subprocess import",
"open(config_path, 'r') as fid: config = json.load(fid) if key is",
"the log file (if it exists). Otherwise, statements will be",
"mouse click after a delay\"\"\" button = dict(left=1, middle=2, right=4)[button]",
"log (default). None is the same as False, but additionally",
"a delay\"\"\" button = dict(left=1, middle=2, right=4)[button] # trans to",
"specified number of seconds. Parameters ---------- secs : float Number",
"'deg'] if units not in good_units: raise ValueError('\"units\" must be",
"either:\\n' ' %s\\nfor a temporary solution, or:\\n' ' %s\\nfor a",
"whose dimensions should be checked and fixed. n_channels : int",
"cleanup here because the rmtree function may be cleaned up",
"function only works with the keyboard controller (not TDT)! It",
"output = (stdout_.decode(), stderr.decode()) if p.returncode: err_fun = subprocess.CalledProcessError.__init__ if",
"config type: \"%s\"' % key) # Read all previous values",
"**kwargs): warnings.warn(msg, category=DeprecationWarning) return fun(*args, **kwargs) wrapped.__name__ = fun.__name__ wrapped.__dict__",
"not key_found and raise_error is True: meth_1 = 'os.environ[\"%s\"] =",
"None and not isinstance(key, string_types): raise ValueError('key must be a",
"Linux, you must run at least Pyglet ' 'version 1.2,",
"configuration values known_config_types = ('RESPONSE_DEVICE', 'AUDIO_CONTROLLER', 'DB_OF_SINE_AT_1KHZ_1RMS', 'EXPYFUN_EYELINK', 'SOUND_CARD_API', 'SOUND_CARD_BACKEND',",
"((''.join(i[4]).lower() + i[1]) if i[4] is not None else '')",
"# noqa, input is raw_input in py3k text_type = unicode",
"``a``. pre : str String to prepend to each line.",
"noqa, input is raw_input in py3k text_type = unicode #",
"len(m1): out += pre + ' x1 missing keys %s\\n'",
"all values directory = op.split(config_path)[0] if not op.isdir(directory): os.mkdir(directory) with",
"context=context) except AttributeError: context = None this_urlopen = urlopen if",
"# noqa except ImportError: return False return True def requires_video():",
"params def _get_display(): import pyglet try: display = pyglet.canvas.get_display() except",
"the valid keys is returned, and ``value`` is ignored. value",
"units : str Must be ``'norm'``, ``'deg'``, or ``'pix'``. \"\"\"",
"must be a string') # first, check to see if",
"fun\"\"\" msg = \"Function %s is deprecated\" % fun.__name__ if",
"pyglet try: display = pyglet.canvas.get_display() except AttributeError: # < 1.4",
"Stderr returned by the process. \"\"\" # code adapted with",
"check_units(units): \"\"\"Ensure user passed valid units type Parameters ---------- units",
"---------- command : list of str Command to run as",
"the logging level Parameters ---------- verbose : bool, str, int,",
"filename to get. If the filename already exists on the",
"as 'INFO', False is the same as 'WARNING'. If None,",
"checked and fixed. n_channels : int The number of channels",
"if type(a) != type(b): out += pre + ' type",
"---------- signal : array_like The (1-dimesional) signal of interest. win_length",
"is designed to be used with testing modules. We cannot",
"isinstance(a, (string_types, int, float, bytes)): if a != b: out",
"prepend to each line. Returns ------- diffs : str A",
"' '{0}'.format(pyglet.version)) return is_usable def _wait_secs(secs, ec=None): \"\"\"Wait a specified",
"allow users to override config # settings using env, which",
"required ' 'channel count %d' % (signal.shape[0], n_channels)) return signal",
"None Filename of the log to print to. If None,",
"args = [key for key, param in params.items() if param.kind",
"delay\"\"\" button = dict(left=1, middle=2, right=4)[button] # trans to pyglet",
"allow non-string types, we allow users to override config #",
"can be # sklearn or scikits.learn, so a self-contained example",
"``'deg'``, or ``'pix'``. \"\"\" good_units = ['norm', 'pix', 'deg'] if",
"= list(x.keys()) # note: not thread-safe idx = np.argsort([str(k) for",
"the environment variable before ' 'running python.' % (key, config_path,",
"may be cleaned up before this object, so we use",
"seconds. Parameters ---------- secs : float Number of seconds to",
"try: importlib.import_module(lib) except Exception as exp: val = True reason",
"# Check requested channel output n_channels = int(operator.index(n_channels)) signal =",
"(n_channels, 1)) if signal.shape[0] != n_channels: raise ValueError('signal channel count",
"k in keys: params[k] = params.get(k, get_config(k, defaults.get(k, None))) #",
"from functools import partial from distutils.version import LooseVersion from numpy",
"Notes ----- Taken from mne-python with permission. \"\"\" out =",
"else: return self._decorate_fun(obj) def _decorate_class(self, cls): msg = \"Class %s",
"to print. If a str, it can be either DEBUG,",
"are strings, so we enforce that here if not isinstance(value,",
"output) else: raise subprocess.CalledProcessError(p.returncode, command) return output class ZeroClock(object): \"\"\"Clock",
"Read all previous values config_path = get_config_path() if op.isfile(config_path): with",
"verbose_dec(function, *args, **kwargs): \"\"\"Improved verbose decorator to allow functions to",
"pre=''): \"\"\"Compute all differences between two python variables Parameters ----------",
"return False else: try: from pyglet.media.avbin import AVbinSource # noqa",
"signal whose dimensions should be checked and fixed. n_channels :",
"will not be fetched again. Returns ------- fname : str",
"and stderr=subproces.PIPE to the call to Popen to suppress printing",
": str String to prepend to each line. Returns -------",
"of messages to print. If a str, it can be",
"= verbose.upper() logging_types = dict(DEBUG=logging.DEBUG, INFO=logging.INFO, WARNING=logging.WARNING, ERROR=logging.ERROR, CRITICAL=logging.CRITICAL) if",
"------- dec - function The decorated function \"\"\" arg_names =",
"xx1, xx2 in zip(a, b): out += object_diff(xx1, xx2, pre='')",
"in inspect.stack()) def run_subprocess(command, **kwargs): \"\"\"Run command using subprocess.Popen Run",
"path to standard expyfun config file. Returns ------- config_path :",
"logging_types = dict(DEBUG=logging.DEBUG, INFO=logging.INFO, WARNING=logging.WARNING, ERROR=logging.ERROR, CRITICAL=logging.CRITICAL) if verbose not",
"%s %s' % (vendor, version,))(func) def requires_lib(lib): \"\"\"Requires lib decorator.\"\"\"",
"param.kind == param.VAR_POSITIONAL] if len(varargs) == 0: varargs = None",
"print. If a str, it can be either DEBUG, INFO,",
"Popen to suppress printing to the terminal. Parameters ---------- command",
"in environment or in the ' 'expyfun config file:\\n%s\\nTry either:\\n'",
"a : object Currently supported: dict, list, tuple, ndarray, int,",
"do this: \"\"\" lh = logging.StreamHandler(WrapStdOut()) lh.setFormatter(logging.Formatter(output_format)) # actually add",
": str The path to the expyfun configuration file. On",
"The path to the expyfun configuration file. On windows, this",
"key. If None, the key is deleted. \"\"\" if key",
"expyfun preference from env, then expyfun config Parameters ---------- key",
"\"\"\" val = op.join(_get_user_home_path(), '.expyfun', 'expyfun.json') return val # List",
"\"\"\" # Check requested channel output n_channels = int(operator.index(n_channels)) signal",
"out += pre + ' x2 missing key %s\\n' %",
"standard dimensions Parameters ---------- signal : array_like The signal whose",
"is None: return sorted(known_config_types) if not isinstance(key, string_types): raise ValueError('key",
"level Parameters ---------- verbose : bool, str, int, or None",
"requires_video(): \"\"\"Requires FFmpeg/AVbin decorator.\"\"\" import pytest return pytest.mark.skipif(not _has_video(), reason='Requires",
"'SOUND_CARD_BACKEND', 'SOUND_CARD_FS', 'SOUND_CARD_NAME', 'SOUND_CARD_FIXED_DELAY', 'TDT_CIRCUIT_PATH', 'TDT_DELAY', 'TDT_INTERFACE', 'TDT_MODEL', 'TDT_TRIG_DELAY', 'TRIGGER_CONTROLLER',",
"= None this_urlopen = urlopen if not op.isfile(fname_out): try: with",
"output_format='%(asctime)s - %(levelname)-7s - %(message)s', overwrite=None): \"\"\"Convenience function for setting",
"\"\"\"Improved verbose decorator to allow functions to override log-level Do",
"process. stderr : str Stderr returned by the process. \"\"\"",
"%s.' % (signal.ndim,)) # Return data with correct dimensions if",
"param in params.values() if param.kind == param.VAR_POSITIONAL] if len(varargs) ==",
"ec : None | expyfun.ExperimentController instance The ExperimentController. Notes -----",
"verbose = 'INFO' if verbose is True else 'WARNING' if",
"False del pyglet except Exception: pass # for py3k (eventually)",
"rmtree(self._path, ignore_errors=True) def check_units(units): \"\"\"Ensure user passed valid units type",
"None) else: config[key] = value # Write all values directory",
"__builtin__ import reload from urllib2 import urlopen # noqa from",
"pre + ' value mismatch (%s, %s)\\n' % (a, b)",
"List the known configuration values known_config_types = ('RESPONSE_DEVICE', 'AUDIO_CONTROLLER', 'DB_OF_SINE_AT_1KHZ_1RMS',",
"'r') as fid: config = json.load(fid) if key is None:",
"file path could ' 'not be determined, please report this",
"system where the file was downloaded. \"\"\" path = get_config('EXPYFUN_DATA_PATH',",
"= op.join(_get_user_home_path(), '.expyfun', 'expyfun.json') return val # List the known",
"if key is in env if key is not None",
"msg = \"Function %s is deprecated\" % fun.__name__ if self.extra:",
"[], True) Timer(delay, send).start() if delay > 0. else send()",
"if val is None: raise ValueError('expyfun config file path could",
"as op import inspect import sys import tempfile import ssl",
"appended to the file. Use ' 'overwrite=False to avoid this",
"sufficient, reason='OpenGL too old: %s %s' % (vendor, version,))(func) def",
"= function(*args, **kwargs) except Exception: set_log_level(old_level) raise set_log_level(old_level) return ret",
"return is_usable def _wait_secs(secs, ec=None): \"\"\"Wait a specified number of",
"for it in expyfun config file config_path = get_config_path() if",
"in signal must match n_channels. Returns ------- signal_fixed : array",
"None') if key not in known_config_types and not \\ any(k",
"zero on init.\"\"\" def __init__(self): self._start_time = clock() def get_time(self):",
"of channels that the output should have. If the input",
"Timer import numpy as np import scipy as sp from",
"# Check keys for k in params.keys(): if k not",
"function for setting the log to print to a file",
"in key for k in known_config_wildcards): warnings.warn('Setting non-standard config type:",
"| None The preference key to set. If None, a",
"mismatch (%s, %s)\\n' % (type(a), type(b)) elif isinstance(a, dict): k1s",
"on OSX and Linux) return getattr(sys.stdout, name) class _TempDir(str): \"\"\"Class",
"else: def _get_args(function, varargs=False): out = inspect.getargspec(function) # args, varargs,",
"ndarray, int, str, bytes, float, StringIO, BytesIO. b : object",
"not None and key in os.environ: return os.environ[key] # second,",
"... def some_function(): pass \"\"\" # Adapted from http://wiki.python.org/moin/PythonDecoratorLibrary, #",
"on init.\"\"\" def __init__(self): self._start_time = clock() def get_time(self): \"\"\"Get",
"input is raw_input in py3k text_type = unicode # noqa",
"def __init__(self): self._start_time = clock() def get_time(self): \"\"\"Get time.\"\"\" return",
"- self._start_time def date_str(): \"\"\"Produce a date string for the",
"above def __init__(self, extra=''): \"\"\" Parameters ---------- extra: string to",
": str | None The preference key to set. If",
"keys def object_diff(a, b, pre=''): \"\"\"Compute all differences between two",
"reason = 'Needs %s (%s)' % (lib, exp) else: val",
"Passing del_after and print_del kwargs to the constructor are helpful",
"fun.__dict__ wrapped.__doc__ = self._update_doc(fun.__doc__) return wrapped def _update_doc(self, olddoc): newdoc",
"import atexit import json from functools import partial from distutils.version",
"using env, which are strings, so we enforce that here",
"function but starts at zero on init.\"\"\" def __init__(self): self._start_time",
"we get proper certificates context = ssl._create_unverified_context() this_urlopen = partial(urlopen,",
": str The preference key to look for. The os",
"LooseVersion(pyglet.version) >= LooseVersion('1.4') def _has_video(): if _new_pyglet(): try: from pyglet.media.codecs.ffmpeg",
"must run at least Pyglet ' 'version 1.2, and you",
"must be sys.stdout (not # just stdout) in order for",
"if 'NAME' is listed known_config_wildcards = () def get_config(key=None, default=None,",
"' a is None, b is not (%s)\\n' % (b)",
"keys = list(x.keys()) # note: not thread-safe idx = np.argsort([str(k)",
"# note: not thread-safe idx = np.argsort([str(k) for k in",
"def get_config(key=None, default=None, raise_error=False): \"\"\"Read expyfun preference from env, then",
"function(*args, **kwargs) except Exception: set_log_level(old_level) raise set_log_level(old_level) return ret else:",
"make sure it \"takes\" try: import pyglet pyglet.options['debug_gl'] = False",
"float, bytes)): if a != b: out += pre +",
"clock() def get_time(self): \"\"\"Get time.\"\"\" return clock() - self._start_time def",
"is passed back, so other commands can be called (like",
"def fake_button_press(ec, button='1', delay=0.): \"\"\"Fake a button press after a",
"timeit import default_timer as clock from threading import Timer import",
"import json from functools import partial from distutils.version import LooseVersion",
"key : str The preference key to look for. The",
"simply use __del__() method for cleanup here because the rmtree",
"TDT)! It uses threads to ensure that control is passed",
"two python variables Parameters ---------- a : object Currently supported:",
"which are strings, so we enforce that here if not",
"return pytest.mark.skipif(not _has_video(), reason='Requires FFmpeg/AVbin') def requires_opengl21(func): \"\"\"Requires OpenGL decorator.\"\"\"",
"val = False reason = '' return pytest.mark.skipif(val, reason=reason) def",
"pytest.mark.skipif(val, reason=reason) def _has_scipy_version(version): return (LooseVersion(sp.__version__) >= LooseVersion(version)) def _get_user_home_path():",
"default). Returns ------- value : str | None The preference",
"convolve, ones import logging import datetime from timeit import default_timer",
"okay key if 'NAME' is listed known_config_wildcards = () def",
"key meth_2 = 'expyfun.utils.set_config(\"%s\", VALUE)' % key raise KeyError('Key \"%s\"",
"the key is deleted. \"\"\" if key is None: return",
"defaults.get(k, None))) # Check keys for k in params.keys(): if",
"return sorted(known_config_types) if not isinstance(key, string_types): raise ValueError('key must be",
"verbose_level is not None: old_level = set_log_level(verbose_level, True) # set",
"with the keyboard controller (not TDT)! It uses threads to",
"string_types): verbose = verbose.upper() logging_types = dict(DEBUG=logging.DEBUG, INFO=logging.INFO, WARNING=logging.WARNING, ERROR=logging.ERROR,",
"None and key in os.environ: return os.environ[key] # second, look",
"\"\"\" return text_type(text_like).encode('unicode_escape').decode('utf-8') def _sort_keys(x): \"\"\"Sort and return keys of",
"isinstance(params, dict): raise TypeError('{0} must be a dict, got type",
"return code was zero then return, otherwise raise CalledProcessError. By",
"convenience and are equivalent to passing in logging.DEBUG, etc. For",
"from ._externals import decorator # set this first thing to",
"= _get_args(function) if len(arg_names) > 0 and arg_names[0] == 'self':",
"ret = function(*args, **kwargs) except Exception: set_log_level(old_level) raise set_log_level(old_level) return",
"key : str | None The preference key to set.",
"type: \"%s\"' % key) # Read all previous values config_path",
"as ``a``. pre : str String to prepend to each",
"() def get_config(key=None, default=None, raise_error=False): \"\"\"Read expyfun preference from env,",
"str Stdout returned by the process. stderr : str Stderr",
"is raw_input in py3k text_type = unicode # noqa from",
"value is None: config.pop(key, None) else: config[key] = value #",
"generality init = cls.__init__ def wrapped(*args, **kwargs): warnings.warn(msg, category=DeprecationWarning) return",
"CRITICAL=logging.CRITICAL) if verbose not in logging_types: raise ValueError('verbose must be",
"a string') # While JSON allow non-string types, we allow",
"repr(key)) elif isinstance(a, (list, tuple)): if len(a) != len(b): out",
"subprocess.CalledProcessError.__init__ if 'output' in _get_args(err_fun): raise subprocess.CalledProcessError(p.returncode, command, output) else:",
"searched first, then the expyfun config file is parsed. default",
"+= object_diff(xx1, xx2, pre='') elif isinstance(a, (string_types, int, float, bytes)):",
"---------- key : str | None The preference key to",
"wrapped(*args, **kwargs): warnings.warn(msg, category=DeprecationWarning) return init(*args, **kwargs) cls.__init__ = wrapped",
"Parameters ---------- key : str The preference key to look",
"\"\"\" we should just be able to do: lh =",
"to return if the key is not found. raise_error :",
"urllib2 import urlopen # noqa from cStringIO import StringIO #",
"None Value to return if the key is not found.",
"differences between two python variables Parameters ---------- a : object",
"from shutil import rmtree import atexit import json from functools",
"set. If None, a tuple of the valid keys is",
"**kwargs) logging.Logger.exp = exp logger = logging.getLogger('expyfun') def flush_logger(): \"\"\"Flush",
"overwrite=None): \"\"\"Convenience function for setting the log to print to",
"# sklearn or scikits.learn, so a self-contained example is used",
"n_channels): \"\"\"Make it so a valid audio buffer is in",
"not op.isfile(fname_out): try: with open(fname_out, 'wb') as fid: www =",
"when the function is called/the class is instantiated and adds",
"else None) def set_log_file(fname=None, output_format='%(asctime)s - %(levelname)-7s - %(message)s', overwrite=None):",
"you are running ' '{0}'.format(pyglet.version)) return is_usable def _wait_secs(secs, ec=None):",
"If a str, it can be either DEBUG, INFO, WARNING,",
"dir This is designed to be used with testing modules.",
"non-string types, we allow users to override config # settings",
"extra=''): \"\"\" Parameters ---------- extra: string to be added to",
"kw.update(kwargs) p = subprocess.Popen(command, **kw) stdout_, stderr = p.communicate() output",
"correct dimensions if n_channels == 2 and signal.shape[0] == 1:",
"meth_1 = 'os.environ[\"%s\"] = VALUE' % key meth_2 = 'expyfun.utils.set_config(\"%s\",",
"BytesIO. b : object Must be same type as ``a``.",
"too old: %s %s' % (vendor, version,))(func) def requires_lib(lib): \"\"\"Requires",
"Returns ------- config_path : str The path to the expyfun",
"\"\"\"Call.\"\"\" if isinstance(obj, type): return self._decorate_class(obj) else: return self._decorate_fun(obj) def",
"['norm', 'pix', 'deg'] if units not in good_units: raise ValueError('\"units\"",
"raise subprocess.CalledProcessError(p.returncode, command, output) else: raise subprocess.CalledProcessError(p.returncode, command) return output",
"use set_log_level('WARN'). output_format : str Format of the output messages.",
"got {1}' .format(name, type(params))) # Set sensible defaults for values",
"\"DEPRECATED\" if self.extra: newdoc = \"%s: %s\" % (newdoc, self.extra)",
"not call this directly to set global verbosrity level, instead",
": str, or None Filename of the log to print",
"function fun\"\"\" msg = \"Function %s is deprecated\" % fun.__name__",
"be appended. \"\"\" handlers = logger.handlers for h in handlers:",
"not {}' ''.format(good_units, units)) ############################################################################### # DECORATORS # Following deprecated",
"os.getenv('APPDATA' if 'nt' == os.name.lower() else 'HOME', None) if val",
": array The signal with standard dimensions (n_channels, N). \"\"\"",
"if not np.array_equal(a, b): out += pre + ' array",
"k, ', '.join(keys))) return params def _get_display(): import pyglet try:",
"pyglet is_usable = LooseVersion(pyglet.version) >= LooseVersion('1.2') if raise_error is True",
"for debugging purposes. \"\"\" def __new__(self, del_after=True, print_del=False): new =",
"uses a while loop. Although this slams the CPU, it",
"settings using env, which are strings, so we enforce that",
"output_format : str Format of the output messages. See the",
"stdout.\"\"\" def __getattr__(self, name): # Even more ridiculous than this",
"__init__(self): self._start_time = clock() def get_time(self): \"\"\"Get time.\"\"\" return clock()",
"be either DEBUG, INFO, WARNING, ERROR, or CRITICAL. Note that",
"signal with standard dimensions (n_channels, N). \"\"\" # Check requested",
"keyboard controller (not TDT)! It uses threads to ensure that",
"least Pyglet ' 'version 1.2, and you are running '",
"only works with the keyboard controller (not TDT)! It uses",
"parentheses: >>> from expyfun._utils import deprecated >>> deprecated() # doctest:",
"pre + ' length mismatch (%s, %s)\\n' % (len(a), len(b))",
"None) else: default_level = None if('verbose' in arg_names): verbose_level =",
"it will be tiled to be shape (2, n_samples). Otherwise,",
"between two python variables Parameters ---------- a : object Currently",
"val = op.join(_get_user_home_path(), '.expyfun', 'expyfun.json') return val # List the",
"file is parsed. default : str | None Value to",
"= function(*args, **kwargs) return ret def _new_pyglet(): import pyglet return",
"= LooseVersion(pyglet.version) >= LooseVersion('1.2') if raise_error is True and is_usable",
"Return data with correct dimensions if n_channels == 2 and",
"utility functions\"\"\" # Authors: <NAME> <<EMAIL>> # # License: BSD",
"Write all values directory = op.split(config_path)[0] if not op.isdir(directory): os.mkdir(directory)",
"None: raise ValueError('value must be a string or None') if",
"array_like The signal whose dimensions should be checked and fixed.",
"not found (instead of returning default). Returns ------- value :",
"ValueError('value must be a string or None') if key not",
"win_length): \"\"\"RMS of ``signal`` with rectangular window ``win_length`` samples long.",
"that are not passed for k in keys: params[k] =",
"CalledProcessError. By default, this will also add stdout= and stderr=subproces.PIPE",
"'wb') as fid: www = this_urlopen(fname_url, timeout=30.0) try: fid.write(www.read()) finally:",
"raise ValueError('signal channel count %d did not match required '",
"channels in signal must match n_channels. Returns ------- signal_fixed :",
"get_time(self): \"\"\"Get time.\"\"\" return clock() - self._start_time def date_str(): \"\"\"Produce",
"because the rmtree function may be cleaned up before this",
"__init__(self, extra=''): \"\"\" Parameters ---------- extra: string to be added",
"' x2 missing key %s\\n' % key else: out +=",
"standard dimensions (n_channels, N). \"\"\" # Check requested channel output",
"py3k (eventually) if sys.version.startswith('2'): string_types = basestring # noqa input",
"pyglet except Exception: pass # for py3k (eventually) if sys.version.startswith('2'):",
"= clock() def get_time(self): \"\"\"Get time.\"\"\" return clock() - self._start_time",
"StringIO # noqa, analysis:ignore from importlib import reload # noqa,",
"good_units: raise ValueError('\"units\" must be one of {}, not {}'",
"expyfun configuration file. On windows, this will be '%APPDATA%\\.expyfun\\expyfun.json'. On",
"(type(a), type(b)) elif isinstance(a, dict): k1s = _sort_keys(a) k2s =",
"!= b: out += pre + ' value mismatch (%s,",
"to print to. If None, stdout is used. To suppress",
"############################################################################### # DECORATORS # Following deprecated class copied from scikit-learn",
"None else '') for i in inspect.stack()) def run_subprocess(command, **kwargs):",
"called/the class is instantiated and adds a warning to the",
"class is instantiated and adds a warning to the docstring.",
"def __new__(self, del_after=True, print_del=False): new = str.__new__(self, tempfile.mkdtemp()) self._del_after =",
"first thing to make sure it \"takes\" try: import pyglet",
"= (stdout_.decode(), stderr.decode()) if p.returncode: err_fun = subprocess.CalledProcessError.__init__ if 'output'",
"# Check dimensionality if signal.ndim != 2: raise ValueError('Sound data",
"to allow functions to override log-level Do not call this",
"an exception try: ret = function(*args, **kwargs) except Exception: set_log_level(old_level)",
"'one of {2}'.format(name, k, ', '.join(keys))) return params def _get_display():",
"examples: http://docs.python.org/dev/howto/logging.html e.g., \"%(asctime)s - %(levelname)s - %(message)s\". overwrite :",
"set_log_level(). Parameters ---------- function : callable Function to be decorated",
"is False: raise ImportError('On Linux, you must run at least",
"a specified number of seconds. Parameters ---------- secs : float",
"lh.setFormatter(logging.Formatter(output_format)) # actually add the stream handler logger.addHandler(lh) ############################################################################### #",
"< secs: ec._dispatch_events() ec.check_force_quit() else: wins = _get_display().get_windows() for win",
"pyglet.gl.gl_info.get_version() sufficient = pyglet.gl.gl_info.have_version(2, 0) return pytest.mark.skipif(not sufficient, reason='OpenGL too",
"pyglet version, return True if usable. \"\"\" import pyglet is_usable",
"self.extra # FIXME: we should probably reset __new__ for full",
"building_doc = any('sphinx-build' in ((''.join(i[4]).lower() + i[1]) if i[4] is",
"or None The verbosity of messages to print. If a",
"None: return sorted(known_config_types) if not isinstance(key, string_types): raise ValueError('key must",
"StringIO # noqa else: string_types = str text_type = str",
"will be appended to the file. Use ' 'overwrite=False to",
"first, check to see if key is in env if",
"the old verbosity level. \"\"\" if verbose is None: verbose",
"buffer is in the standard dimensions Parameters ---------- signal :",
"in keys]) keys = [keys[ii] for ii in idx] return",
"cleaned up before this object, so we use the atexit",
"fname : str The filename on the local system where",
"logging.FileHandler(fname, mode=mode) else: \"\"\" we should just be able to",
"type as ``a``. pre : str String to prepend to",
"CPU, it will guarantee that events (keypresses, etc.) are processed.",
"for convenience and are equivalent to passing in logging.DEBUG, etc.",
"distutils.version import LooseVersion from numpy import sqrt, convolve, ones import",
"are processed. \"\"\" # hog the cpu, checking time t0",
"None, a tuple of the valid keys is returned, and",
"isinstance(h, logging.FileHandler): h.close() logger.removeHandler(h) if fname is not None: if",
"log entries will be appended. \"\"\" handlers = logger.handlers for",
"by the process. stderr : str Stderr returned by the",
"if param.kind not in (param.VAR_POSITIONAL, param.VAR_KEYWORD)] if varargs: varargs =",
"logging import datetime from timeit import default_timer as clock from",
"subprocess.Popen documentation). **kwargs : objects Keywoard arguments to pass to",
"def __getattr__(self, name): # Even more ridiculous than this class,",
"raise RuntimeError(pre + ': unsupported type %s (%s)' % (type(a),",
"on the local system, the file will not be fetched",
"_import_backend(backend) except Exception as exc: pytest.skip('Skipping test for backend %s:",
"message, *args, **kwargs): \"\"\"Experiment-level logging.\"\"\" self.log(EXP, message, *args, **kwargs) logging.Logger.exp",
"import ssl from shutil import rmtree import atexit import json",
"following for examples: http://docs.python.org/dev/howto/logging.html e.g., \"%(asctime)s - %(levelname)s - %(message)s\".",
"if op.isfile(fname) and overwrite is None: warnings.warn('Log entries will be",
"reset __new__ for full generality init = cls.__init__ def wrapped(*args,",
"return args, varargs else: return args else: def _get_args(function, varargs=False):",
"function \"\"\" arg_names = _get_args(function) if len(arg_names) > 0 and",
"The ExperimentController. Notes ----- This function uses a while loop.",
"except Exception: set_log_level(old_level) raise set_log_level(old_level) return ret else: ret =",
"fetched again. Returns ------- fname : str The filename on",
"pre + ' x2 missing key %s\\n' % key else:",
"string') # While JSON allow non-string types, we allow users",
"param.VAR_POSITIONAL] if len(varargs) == 0: varargs = None return args,",
"' 'one of {2}'.format(name, k, ', '.join(keys))) return params def",
"str | None The preference key to set. If None,",
"return fun(*args, **kwargs) wrapped.__name__ = fun.__name__ wrapped.__dict__ = fun.__dict__ wrapped.__doc__",
"def _has_video(): if _new_pyglet(): try: from pyglet.media.codecs.ffmpeg import FFmpegSource #",
"open(fname_out, 'wb') as fid: www = this_urlopen(fname_url, timeout=30.0) try: fid.write(www.read())",
"= op.join(path, fname) if not op.isdir(op.dirname(fname_out)): os.makedirs(op.dirname(fname_out)) fname_url = ('https://github.com/LABSN/expyfun-data/raw/master/{0}'",
"Must be ``'norm'``, ``'deg'``, or ``'pix'``. \"\"\" good_units = ['norm',",
"rectangular window ``win_length`` samples long. Parameters ---------- signal : array_like",
"try: with open(fname_out, 'wb') as fid: www = this_urlopen(fname_url, timeout=30.0)",
"return, otherwise raise CalledProcessError. By default, this will also add",
"= \"Class %s is deprecated\" % cls.__name__ if self.extra: msg",
"# RANDOM UTILITIES building_doc = any('sphinx-build' in ((''.join(i[4]).lower() + i[1])",
"overwrite : bool, or None Overwrite the log file (if",
"True: print('Deleting {} ...'.format(self._path)) rmtree(self._path, ignore_errors=True) def check_units(units): \"\"\"Ensure user",
"debugging purposes. \"\"\" def __new__(self, del_after=True, print_del=False): new = str.__new__(self,",
"def run_subprocess(command, **kwargs): \"\"\"Run command using subprocess.Popen Run command and",
"= () def get_config(key=None, default=None, raise_error=False): \"\"\"Read expyfun preference from",
"On every other system, this will be $HOME/.expyfun/expyfun.json. \"\"\" val",
"the function is called/the class is instantiated and adds a",
"value is not None: raise ValueError('value must be a string",
"not in (param.VAR_POSITIONAL, param.VAR_KEYWORD)] if varargs: varargs = [param.name for",
"Command to run as subprocess (see subprocess.Popen documentation). **kwargs :",
"to run as subprocess (see subprocess.Popen documentation). **kwargs : objects",
"win.dispatch_events() def running_rms(signal, win_length): \"\"\"RMS of ``signal`` with rectangular window",
"INFO, WARNING, ERROR, or CRITICAL. Note that these are for",
"key to look for. The os environment is searched first,",
"return wrapped def _update_doc(self, olddoc): newdoc = \"DEPRECATED\" if self.extra:",
"the preference key. If None, the key is deleted. \"\"\"",
"appended to the log (default). None is the same as",
"from __builtin__ import reload from urllib2 import urlopen # noqa",
"class, this must be sys.stdout (not # just stdout) in",
"of the output messages. See the following for examples: http://docs.python.org/dev/howto/logging.html",
"but with many changes. # scikit-learn will not import on",
"e.g., \"%(asctime)s - %(levelname)s - %(message)s\". overwrite : bool, or",
"0: varargs = None return args, varargs else: return args",
"= ('https://github.com/LABSN/expyfun-data/raw/master/{0}' ''.format(fname)) try: # until we get proper certificates",
"to be shape (2, n_samples). Otherwise, the number of channels",
"from env, then expyfun config Parameters ---------- key : str",
"used. To suppress log outputs, use set_log_level('WARN'). output_format : str",
"# Following deprecated class copied from scikit-learn class deprecated(object): \"\"\"Decorator",
"checked on OSX64, Linux64, and Win32 val = os.getenv('APPDATA' if",
"Returns ------- stdout : str Stdout returned by the process.",
"k not in keys: raise KeyError('Unrecognized key in {0}[\"{1}\"], must",
"import importlib import os import os.path as op import inspect",
"extra argument will be appended to the deprecation message and",
"\"\"\"Clock that uses \"clock\" function but starts at zero on",
"level, instead use set_log_level(). Parameters ---------- function : callable Function",
"if len(arg_names) > 0 and arg_names[0] == 'self': default_level =",
"= default else: with open(config_path, 'r') as fid: config =",
"is mono and n_channels=2, it will be tiled to be",
"if verbose is None: verbose = get_config('EXPYFUN_LOGGING_LEVEL', 'INFO') elif isinstance(verbose,",
"to the log (default). None is the same as False,",
"0) return pytest.mark.skipif(not sufficient, reason='OpenGL too old: %s %s' %",
"partial matches: 'NAME_1' is okay key if 'NAME' is listed",
"second, look for it in expyfun config file config_path =",
"While JSON allow non-string types, we allow users to override",
"python variables Parameters ---------- a : object Currently supported: dict,",
"is True: print('Deleting {} ...'.format(self._path)) rmtree(self._path, ignore_errors=True) def check_units(units): \"\"\"Ensure",
"fname : str The remote filename to get. If the",
"for k in params.keys(): if k not in keys: raise",
"for py3k (eventually) if sys.version.startswith('2'): string_types = basestring # noqa",
"\"\"\"Flush expyfun logger\"\"\" for handler in logger.handlers: handler.flush() def set_log_level(verbose=None,",
"The verbosity of messages to print. If a str, it",
"json.load(fid) if key is None: return config key_found = True",
"EXPYFUN_LOGGING_LEVEL is read, and if it doesn't exist, defaults to",
"Win32 val = os.getenv('APPDATA' if 'nt' == os.name.lower() else 'HOME',",
"from http://wiki.python.org/moin/PythonDecoratorLibrary, # but with many changes. # scikit-learn will",
"ignored. value : str | None The value to assign",
"'{0}'.format(pyglet.version)) return is_usable def _wait_secs(secs, ec=None): \"\"\"Wait a specified number",
"version, return True if usable. \"\"\" import pyglet is_usable =",
": str Stderr returned by the process. \"\"\" # code",
"Exception as exc: pytest.skip('Skipping test for backend %s: %s' %",
"at ...> >>> @deprecated() ... def some_function(): pass \"\"\" #",
"window ``win_length`` samples long. Parameters ---------- signal : array_like The",
"**kwargs): \"\"\"Experiment-level logging.\"\"\" self.log(EXP, message, *args, **kwargs) logging.Logger.exp = exp",
"(len(a), len(b)) else: for xx1, xx2 in zip(a, b): out",
"** 2, ones(win_length) / win_length, 'valid')) def _fix_audio_dims(signal, n_channels): \"\"\"Make",
"getattr(sys.stdout, name) class _TempDir(str): \"\"\"Class for creating and auto-destroying temp",
"the local system, the file will not be fetched again.",
"(old_verbose if return_old_level else None) def set_log_file(fname=None, output_format='%(asctime)s - %(levelname)-7s",
"return newdoc if hasattr(inspect, 'signature'): # py35 def _get_args(function, varargs=False):",
"if key not in known_config_types and not \\ any(k in",
"_new_pyglet(): import pyglet return LooseVersion(pyglet.version) >= LooseVersion('1.4') def _has_video(): if",
"to avoid this message in the ' 'future.') mode =",
"xx2 in zip(a, b): out += object_diff(xx1, xx2, pre='') elif",
"import pyglet.gl vendor = pyglet.gl.gl_info.get_vendor() version = pyglet.gl.gl_info.get_version() sufficient =",
"py35 def _get_args(function, varargs=False): params = inspect.signature(function).parameters args = [key",
"str The preference key to look for. The os environment",
"True def requires_video(): \"\"\"Requires FFmpeg/AVbin decorator.\"\"\" import pytest return pytest.mark.skipif(not",
"valid type') verbose = logging_types[verbose] old_verbose = logger.level logger.setLevel(verbose) return",
"setting the log to print to a file Parameters ----------",
"import reload # noqa, analysis:ignore ############################################################################### # LOGGING EXP =",
"has been checked on OSX64, Linux64, and Win32 val =",
"'nt' == os.name.lower() else 'HOME', None) if val is None:",
"notify the user that log entries will be appended. \"\"\"",
"param in params.items() if param.kind not in (param.VAR_POSITIONAL, param.VAR_KEYWORD)] if",
"noqa except ImportError: return False return True def requires_video(): \"\"\"Requires",
"for examples: http://docs.python.org/dev/howto/logging.html e.g., \"%(asctime)s - %(levelname)s - %(message)s\". overwrite",
"WARNING=logging.WARNING, ERROR=logging.ERROR, CRITICAL=logging.CRITICAL) if verbose not in logging_types: raise ValueError('verbose",
"stdout) in order for this to work (tested on OSX",
"exc: pytest.skip('Skipping test for backend %s: %s' % (backend, exc))",
"verbose_level = args[arg_names.index('verbose')] else: verbose_level = default_level if verbose_level is",
"set_log_level(verbose_level, True) # set it back if we get an",
"params = inspect.signature(function).parameters args = [key for key, param in",
"the key is not found. raise_error : bool If True,",
"key) # Read all previous values config_path = get_config_path() if",
"mismatch\\n' else: raise RuntimeError(pre + ': unsupported type %s (%s)'",
"'Needs %s (%s)' % (lib, exp) else: val = False",
"deepcopy import subprocess import importlib import os import os.path as",
"_has_video(): if _new_pyglet(): try: from pyglet.media.codecs.ffmpeg import FFmpegSource # noqa",
"not op.isdir(directory): os.mkdir(directory) with open(config_path, 'w') as fid: json.dump(config, fid,",
"is instantiated and adds a warning to the docstring. The",
"be cleaned up before this object, so we use the",
"fid: json.dump(config, fid, sort_keys=True, indent=0) ############################################################################### # MISC def fake_button_press(ec,",
"True, raise an error if the key is not found",
"env, which are strings, so we enforce that here if",
"'EXP') def exp(self, message, *args, **kwargs): \"\"\"Experiment-level logging.\"\"\" self.log(EXP, message,",
"samples long. Parameters ---------- signal : array_like The (1-dimesional) signal",
"is used. To suppress log outputs, use set_log_level('WARN'). output_format :",
"= True reason = 'Needs %s (%s)' % (lib, exp)",
"_import_backend import pytest if isinstance(backend, dict): # actually an AC",
"this_urlopen = partial(urlopen, context=context) except AttributeError: context = None this_urlopen",
"to the constructor are helpful primarily for debugging purposes. \"\"\"",
"and adds a warning to the docstring. The optional extra",
"val is None: raise ValueError('expyfun config file path could '",
"remote file Parameters ---------- fname : str The remote filename",
"to be used with testing modules. We cannot simply use",
"str A string representation of the differences. Notes ----- Taken",
"then expyfun config Parameters ---------- key : str The preference",
"inspect.getargspec(function) # args, varargs, keywords, defaults if varargs: return out[:2]",
"an empty of parentheses: >>> from expyfun._utils import deprecated >>>",
"def _check_params(params, keys, defaults, name): if not isinstance(params, dict): raise",
"| None The value to assign to the preference key.",
"reload from urllib2 import urlopen # noqa from cStringIO import",
"else 'HOME', None) if val is None: raise ValueError('expyfun config",
"init = cls.__init__ def wrapped(*args, **kwargs): warnings.warn(msg, category=DeprecationWarning) return init(*args,",
"\"; %s\" % self.extra def wrapped(*args, **kwargs): warnings.warn(msg, category=DeprecationWarning) return",
"(instead of returning default). Returns ------- value : str |",
"if ec is not None: while (clock() - t0) <",
"\"\"\" arg_names = _get_args(function) if len(arg_names) > 0 and arg_names[0]",
"be a string') # While JSON allow non-string types, we",
"The value to assign to the preference key. If None,",
"# noqa, analysis:ignore ############################################################################### # LOGGING EXP = 25 logging.addLevelName(EXP,",
"return LooseVersion(pyglet.version) >= LooseVersion('1.4') def _has_video(): if _new_pyglet(): try: from",
"hog the cpu, checking time t0 = clock() if ec",
"as subprocess (see subprocess.Popen documentation). **kwargs : objects Keywoard arguments",
"pass # for py3k (eventually) if sys.version.startswith('2'): string_types = basestring",
"Timer(delay, send).start() if delay > 0. else send() def fake_mouse_click(ec,",
"directory = op.split(config_path)[0] if not op.isdir(directory): os.mkdir(directory) with open(config_path, 'w')",
"with testing modules. We cannot simply use __del__() method for",
"can be either DEBUG, INFO, WARNING, ERROR, or CRITICAL. Note",
"variables Parameters ---------- a : object Currently supported: dict, list,",
"Function to be decorated by setting the verbosity level. Returns",
"\"clock\" function but starts at zero on init.\"\"\" def __init__(self):",
"dict, got type {1}' .format(name, type(params))) params = deepcopy(params) if",
"init.\"\"\" def __init__(self): self._start_time = clock() def get_time(self): \"\"\"Get time.\"\"\"",
"are running ' '{0}'.format(pyglet.version)) return is_usable def _wait_secs(secs, ec=None): \"\"\"Wait",
"+ ': unsupported type %s (%s)' % (type(a), a)) return",
"or in the ' 'expyfun config file:\\n%s\\nTry either:\\n' ' %s\\nfor",
"logging.DEBUG, etc. For bool, True is the same as 'INFO',",
"that log entries will be appended. \"\"\" handlers = logger.handlers",
"uses \"clock\" function but starts at zero on init.\"\"\" def",
"meth_2 = 'expyfun.utils.set_config(\"%s\", VALUE)' % key raise KeyError('Key \"%s\" not",
"a mouse click after a delay\"\"\" button = dict(left=1, middle=2,",
": objects Keywoard arguments to pass to ``subprocess.Popen``. Returns -------",
"if olddoc: newdoc = \"%s\\n\\n%s\" % (newdoc, olddoc) return newdoc",
"decorated by setting the verbosity level. Returns ------- dec -",
"also ' 'set the environment variable before ' 'running python.'",
"values that are not passed for k in keys: params[k]",
"# noqa except ImportError: return False else: try: from pyglet.media.avbin",
"log outputs, use set_log_level('WARN'). output_format : str Format of the",
"None))) # Check keys for k in params.keys(): if k",
"- set(k1s) if len(m1): out += pre + ' x1",
"!= type(b): out += pre + ' type mismatch (%s,",
"self.log(EXP, message, *args, **kwargs) logging.Logger.exp = exp logger = logging.getLogger('expyfun')",
"to see if key is in env if key is",
"is None: if b is not None: out += pre",
"is not None else '') for i in inspect.stack()) def",
"if overwrite is True else 'a' lh = logging.FileHandler(fname, mode=mode)",
": str The date string. \"\"\" return str(datetime.datetime.today()).replace(':', '_') class",
"ValueError('expyfun config file path could ' 'not be determined, please",
"from numpy import sqrt, convolve, ones import logging import datetime",
"trans to pyglet def send(): ec._mouse_handler._on_pyglet_mouse_click(pos[0], pos[1], button, []) Timer(delay,",
"if('verbose' in arg_names): verbose_level = args[arg_names.index('verbose')] else: verbose_level = default_level",
"cls def _decorate_fun(self, fun): \"\"\"Decorate function fun\"\"\" msg = \"Function",
"'os.environ[\"%s\"] = VALUE' % key meth_2 = 'expyfun.utils.set_config(\"%s\", VALUE)' %",
"def requires_lib(lib): \"\"\"Requires lib decorator.\"\"\" import pytest try: importlib.import_module(lib) except",
"controller (not TDT)! It uses threads to ensure that control",
"this: \"\"\" lh = logging.StreamHandler(WrapStdOut()) lh.setFormatter(logging.Formatter(output_format)) # actually add the",
"# While JSON allow non-string types, we allow users to",
"from expyfun._sound_controllers import _import_backend import pytest if isinstance(backend, dict): #",
"before ' 'running python.' % (key, config_path, meth_1, meth_2)) return",
"instance The ExperimentController. Notes ----- This function uses a while",
"pytest if isinstance(backend, dict): # actually an AC backend =",
"= deepcopy(params) if not isinstance(params, dict): raise TypeError('{0} must be",
"signal : array_like The signal whose dimensions should be checked",
"return init(*args, **kwargs) cls.__init__ = wrapped wrapped.__name__ = '__init__' wrapped.__doc__",
"logger.info('Attempting to create new expyfun configuration ' 'file:\\n%s' % config_path)",
"else: config[key] = value # Write all values directory =",
"must have one or two dimensions, got %s.' % (signal.ndim,))",
"% (type(a), type(b)) elif isinstance(a, dict): k1s = _sort_keys(a) k2s",
"urlopen # noqa from cStringIO import StringIO # noqa else:",
"import tempfile import ssl from shutil import rmtree import atexit",
"assign to the preference key. If None, the key is",
"the cpu, checking time t0 = clock() if ec is",
"known configuration values known_config_types = ('RESPONSE_DEVICE', 'AUDIO_CONTROLLER', 'DB_OF_SINE_AT_1KHZ_1RMS', 'EXPYFUN_EYELINK', 'SOUND_CARD_API',",
"to use this with the default value for extra, put",
"copy import deepcopy import subprocess import importlib import os import",
".format(name, type(params))) # Set sensible defaults for values that are",
"is not None: out += pre + ' a is",
"= partial(urlopen, context=context) except AttributeError: context = None this_urlopen =",
"in k2s: out += pre + ' x2 missing key",
"Check requested channel output n_channels = int(operator.index(n_channels)) signal = np.asarray(np.atleast_2d(signal),",
"pyglet.options['debug_gl'] = False del pyglet except Exception: pass # for",
"that events (keypresses, etc.) are processed. \"\"\" # hog the",
"tempfile import ssl from shutil import rmtree import atexit import",
"log to print to a file Parameters ---------- fname :",
"in keys: params[k] = params.get(k, get_config(k, defaults.get(k, None))) # Check",
"order for this to work (tested on OSX and Linux)",
"= get_config('EXPYFUN_DATA_PATH', op.join(_get_user_home_path(), '.expyfun', 'data')) fname_out = op.join(path, fname) if",
"\"\"\"Convenience function for setting the logging level Parameters ---------- verbose",
"_decorate_fun(self, fun): \"\"\"Decorate function fun\"\"\" msg = \"Function %s is",
"\"\"\" Parameters ---------- extra: string to be added to the",
"not isinstance(key, string_types): raise ValueError('key must be a string') #",
"and overwrite is None: warnings.warn('Log entries will be appended to",
"% key meth_2 = 'expyfun.utils.set_config(\"%s\", VALUE)' % key raise KeyError('Key",
"not be fetched again. Returns ------- fname : str The",
"None Overwrite the log file (if it exists). Otherwise, statements",
"%s)\\n' % (len(a), len(b)) else: for xx1, xx2 in zip(a,",
"passed back, so other commands can be called (like wait_for_presses).",
"_has_scipy_version(version): return (LooseVersion(sp.__version__) >= LooseVersion(version)) def _get_user_home_path(): \"\"\"Return standard preferences",
"filename already exists on the local system, the file will",
"returning default). Returns ------- value : str | None The",
"key in config else False val = config.get(key, default) if",
"- %(message)s', overwrite=None): \"\"\"Convenience function for setting the log to",
"dimensions Parameters ---------- signal : array_like The signal whose dimensions",
"Must be same type as ``a``. pre : str String",
"name) class _TempDir(str): \"\"\"Class for creating and auto-destroying temp dir",
"helpful primarily for debugging purposes. \"\"\" def __new__(self, del_after=True, print_del=False):",
"object Currently supported: dict, list, tuple, ndarray, int, str, bytes,",
"= set_log_level(verbose_level, True) # set it back if we get",
"Parameters ---------- command : list of str Command to run",
"out += pre + ' length mismatch (%s, %s)\\n' %",
"args else: def _get_args(function, varargs=False): out = inspect.getargspec(function) # args,",
"actually an AC backend = backend['SOUND_CARD_BACKEND'] try: _import_backend(backend) except Exception",
"a permanent one. You can also ' 'set the environment",
"key is in env if key is not None and",
"operator from copy import deepcopy import subprocess import importlib import",
"documentation). **kwargs : objects Keywoard arguments to pass to ``subprocess.Popen``.",
"get an exception try: ret = function(*args, **kwargs) except Exception:",
"% (a, b) elif a is None: if b is",
"= fun.__dict__ wrapped.__doc__ = self._update_doc(fun.__doc__) return wrapped def _update_doc(self, olddoc):",
"in (param.VAR_POSITIONAL, param.VAR_KEYWORD)] if varargs: varargs = [param.name for param",
"is_usable is False: raise ImportError('On Linux, you must run at",
"'TDT_CIRCUIT_PATH', 'TDT_DELAY', 'TDT_INTERFACE', 'TDT_MODEL', 'TDT_TRIG_DELAY', 'TRIGGER_CONTROLLER', 'TRIGGER_ADDRESS', 'WINDOW_SIZE', 'SCREEN_NUM', 'SCREEN_WIDTH',",
"the ' 'expyfun config file:\\n%s\\nTry either:\\n' ' %s\\nfor a temporary",
"look for it in expyfun config file config_path = get_config_path()",
"\"\"\" return sqrt(convolve(signal ** 2, ones(win_length) / win_length, 'valid')) def",
"was zero then return, otherwise raise CalledProcessError. By default, this",
"to expyfun developers') return val def fetch_data_file(fname): \"\"\"Fetch example remote",
"sort_keys=True, indent=0) ############################################################################### # MISC def fake_button_press(ec, button='1', delay=0.): \"\"\"Fake",
"RANDOM UTILITIES building_doc = any('sphinx-build' in ((''.join(i[4]).lower() + i[1]) if",
"os import os.path as op import inspect import sys import",
"in config else False val = config.get(key, default) if not",
"cpu, checking time t0 = clock() if ec is not",
"= get_config('EXPYFUN_LOGGING_LEVEL', 'INFO') elif isinstance(verbose, bool): verbose = 'INFO' if",
"+= pre + ' a is None, b is not",
"not in logging_types: raise ValueError('verbose must be of a valid",
"\"%s: %s\" % (newdoc, self.extra) if olddoc: newdoc = \"%s\\n\\n%s\"",
"raise TypeError('{0} must be a dict, got type {1}' .format(name,",
"# but with many changes. # scikit-learn will not import",
"str | None The preference key value. \"\"\" if key",
"n_channels : int The number of channels that the output",
"def set_log_file(fname=None, output_format='%(asctime)s - %(levelname)-7s - %(message)s', overwrite=None): \"\"\"Convenience function",
"valid audio buffer is in the standard dimensions Parameters ----------",
"and Linux) return getattr(sys.stdout, name) class _TempDir(str): \"\"\"Class for creating",
"raise_error is True: meth_1 = 'os.environ[\"%s\"] = VALUE' % key",
"= logging.StreamHandler(WrapStdOut()) lh.setFormatter(logging.Formatter(output_format)) # actually add the stream handler logger.addHandler(lh)",
"return config key_found = True if key in config else",
"key_found and raise_error is True: meth_1 = 'os.environ[\"%s\"] = VALUE'",
"= unicode # noqa from __builtin__ import reload from urllib2",
"_sanitize(text_like): \"\"\"Cast as string, encode as UTF-8 and sanitize any",
"' length mismatch (%s, %s)\\n' % (len(a), len(b)) else: for",
"config file config_path = get_config_path() if not op.isfile(config_path): key_found =",
"The optional extra argument will be appended to the deprecation",
"StringIO, BytesIO. b : object Must be same type as",
"default : str | None Value to return if the",
"op.split(config_path)[0] if not op.isdir(directory): os.mkdir(directory) with open(config_path, 'w') as fid:",
"%d' % (signal.shape[0], n_channels)) return signal def _sanitize(text_like): \"\"\"Cast as",
"import FFmpegSource # noqa except ImportError: return False else: try:",
"must match n_channels. Returns ------- signal_fixed : array The signal",
"= 'os.environ[\"%s\"] = VALUE' % key meth_2 = 'expyfun.utils.set_config(\"%s\", VALUE)'",
"'SCREEN_NUM', 'SCREEN_WIDTH', 'SCREEN_DISTANCE', 'SCREEN_SIZE_PIX', 'EXPYFUN_LOGGING_LEVEL', ) # These allow for",
"!= n_channels: raise ValueError('signal channel count %d did not match",
"config file path could ' 'not be determined, please report",
"key to set. If None, a tuple of the valid",
"out += pre + ' value mismatch (%s, %s)\\n' %",
"= getattr(args[0], 'verbose', None) else: default_level = None if('verbose' in",
"loop. Although this slams the CPU, it will guarantee that",
"argument will be appended to the deprecation message and the",
"doctest captures stdout.\"\"\" def __getattr__(self, name): # Even more ridiculous",
"a dict, got {1}' .format(name, type(params))) # Set sensible defaults",
"string_types): raise ValueError('key must be a string') # first, check",
"so a valid audio buffer is in the standard dimensions",
"with permission from mne-python kw = dict(stderr=subprocess.PIPE, stdout=subprocess.PIPE) kw.update(kwargs) p",
"or CRITICAL. Note that these are for convenience and are",
"not found. raise_error : bool If True, raise an error",
"noqa except ImportError: try: from pyglet.media.sources.avbin import AVbinSource # noqa",
"work (tested on OSX and Linux) return getattr(sys.stdout, name) class",
"in the ' 'future.') mode = 'w' if overwrite is",
"'__init__' wrapped.__doc__ = self._update_doc(init.__doc__) wrapped.deprecated_original = init return cls def",
"set this first thing to make sure it \"takes\" try:",
"reason=reason) def _has_scipy_version(version): return (LooseVersion(sp.__version__) >= LooseVersion(version)) def _get_user_home_path(): \"\"\"Return",
"signal of interest. win_length : int Length (in samples) of",
"a)) return out def _check_skip_backend(backend): from expyfun._sound_controllers import _import_backend import",
"'WARNING'. If None, the environment variable EXPYFUN_LOGGING_LEVEL is read, and",
"import urlopen input = input from io import StringIO #",
"class _TempDir(str): \"\"\"Class for creating and auto-destroying temp dir This",
"\"takes\" try: import pyglet pyglet.options['debug_gl'] = False del pyglet except",
"Parameters ---------- fname : str The remote filename to get.",
"already exists on the local system, the file will not",
"from mne-python kw = dict(stderr=subprocess.PIPE, stdout=subprocess.PIPE) kw.update(kwargs) p = subprocess.Popen(command,",
"is called/the class is instantiated and adds a warning to",
"_get_display().get_windows() for win in wins: win.dispatch_events() def running_rms(signal, win_length): \"\"\"RMS",
"AC backend = backend['SOUND_CARD_BACKEND'] try: _import_backend(backend) except Exception as exc:",
"message in the ' 'future.') mode = 'w' if overwrite",
"class ZeroClock(object): \"\"\"Clock that uses \"clock\" function but starts at",
"noqa from __builtin__ import reload from urllib2 import urlopen #",
"+= pre + ' type mismatch (%s, %s)\\n' % (type(a),",
"avoid this message in the ' 'future.') mode = 'w'",
"and signal.shape[0] == 1: signal = np.tile(signal, (n_channels, 1)) if",
"See the following for examples: http://docs.python.org/dev/howto/logging.html e.g., \"%(asctime)s - %(levelname)s",
"a is None: if b is not None: out +=",
"in an empty of parentheses: >>> from expyfun._utils import deprecated",
"found in environment or in the ' 'expyfun config file:\\n%s\\nTry",
"ExperimentController. Notes ----- This function uses a while loop. Although",
"\"\"\" lh = logging.StreamHandler(WrapStdOut()) lh.setFormatter(logging.Formatter(output_format)) # actually add the stream",
"op.isfile(fname_out): try: with open(fname_out, 'wb') as fid: www = this_urlopen(fname_url,",
"import os.path as op import inspect import sys import tempfile",
"``value`` is ignored. value : str | None The value",
"the user that log entries will be appended. \"\"\" handlers",
"self.extra: msg += \"; %s\" % self.extra def wrapped(*args, **kwargs):",
"the output should have. If the input is mono and",
"int Length (in samples) of the rectangular window \"\"\" return",
"to each line. Returns ------- diffs : str A string",
"\"\"\" if verbose is None: verbose = get_config('EXPYFUN_LOGGING_LEVEL', 'INFO') elif",
"threads to ensure that control is passed back, so other",
"numpy as np import scipy as sp from ._externals import",
"if return_old_level else None) def set_log_file(fname=None, output_format='%(asctime)s - %(levelname)-7s -",
"and ``value`` is ignored. value : str | None The",
"file:\\n%s\\nTry either:\\n' ' %s\\nfor a temporary solution, or:\\n' ' %s\\nfor",
"wait for command to complete. If the return code was",
"= value # Write all values directory = op.split(config_path)[0] if",
"else: for xx1, xx2 in zip(a, b): out += object_diff(xx1,",
"AVbinSource # noqa except ImportError: try: from pyglet.media.sources.avbin import AVbinSource",
"delay Notes ----- This function only works with the keyboard",
"= _sort_keys(a) k2s = _sort_keys(b) m1 = set(k2s) - set(k1s)",
"$HOME/.expyfun/expyfun.json. \"\"\" val = op.join(_get_user_home_path(), '.expyfun', 'expyfun.json') return val #",
"signal = np.asarray(np.atleast_2d(signal), dtype=np.float32) # Check dimensionality if signal.ndim !=",
"= logging_types[verbose] old_verbose = logger.level logger.setLevel(verbose) return (old_verbose if return_old_level",
"def _fix_audio_dims(signal, n_channels): \"\"\"Make it so a valid audio buffer",
"before this object, so we use the atexit module instead.",
"isinstance(a, np.ndarray): if not np.array_equal(a, b): out += pre +",
"if not isinstance(value, string_types) and value is not None: raise",
"+= pre + ' x2 missing key %s\\n' % key",
"= any('sphinx-build' in ((''.join(i[4]).lower() + i[1]) if i[4] is not",
"None: old_level = set_log_level(verbose_level, True) # set it back if",
"parsed. default : str | None Value to return if",
"that uses \"clock\" function but starts at zero on init.\"\"\"",
"it can be # sklearn or scikits.learn, so a self-contained",
"found (instead of returning default). Returns ------- value : str",
"in good_units: raise ValueError('\"units\" must be one of {}, not",
"ensure that control is passed back, so other commands can",
"'signature'): # py35 def _get_args(function, varargs=False): params = inspect.signature(function).parameters args",
"\"\"\" path = get_config('EXPYFUN_DATA_PATH', op.join(_get_user_home_path(), '.expyfun', 'data')) fname_out = op.join(path,",
"noqa else: string_types = str text_type = str from urllib.request",
"return val def set_config(key, value): \"\"\"Set expyfun preference in config",
"MISC def fake_button_press(ec, button='1', delay=0.): \"\"\"Fake a button press after",
"if not isinstance(params, dict): raise TypeError('{0} must be a dict,",
"param.kind not in (param.VAR_POSITIONAL, param.VAR_KEYWORD)] if varargs: varargs = [param.name",
"idx] return keys def object_diff(a, b, pre=''): \"\"\"Compute all differences",
"as sp from ._externals import decorator # set this first",
"If None, stdout is used. To suppress log outputs, use",
"key not in known_config_types and not \\ any(k in key",
"as exc: pytest.skip('Skipping test for backend %s: %s' % (backend,",
"is deprecated\" % cls.__name__ if self.extra: msg += \"; %s\"",
"callable Function to be decorated by setting the verbosity level.",
"sensible defaults for values that are not passed for k",
"backend = backend['SOUND_CARD_BACKEND'] try: _import_backend(backend) except Exception as exc: pytest.skip('Skipping",
"isinstance(backend, dict): # actually an AC backend = backend['SOUND_CARD_BACKEND'] try:",
"new = str.__new__(self, tempfile.mkdtemp()) self._del_after = del_after self._print_del = print_del",
"None The preference key to set. If None, a tuple",
"stdout : str Stdout returned by the process. stderr :",
"of dict\"\"\" keys = list(x.keys()) # note: not thread-safe idx",
"dict): raise TypeError('{0} must be a dict, got type {1}'",
"ret = function(*args, **kwargs) return ret def _new_pyglet(): import pyglet",
"n_channels == 2 and signal.shape[0] == 1: signal = np.tile(signal,",
"import reload from urllib2 import urlopen # noqa from cStringIO",
"be sys.stdout (not # just stdout) in order for this",
"for k in keys: params[k] = params.get(k, get_config(k, defaults.get(k, None)))",
"www = this_urlopen(fname_url, timeout=30.0) try: fid.write(www.read()) finally: www.close() except Exception:",
"**kwargs): \"\"\"Improved verbose decorator to allow functions to override log-level",
"self._update_doc(fun.__doc__) return wrapped def _update_doc(self, olddoc): newdoc = \"DEPRECATED\" if",
"dimensions, got %s.' % (signal.ndim,)) # Return data with correct",
"val def fetch_data_file(fname): \"\"\"Fetch example remote file Parameters ---------- fname",
"for handler in logger.handlers: handler.flush() def set_log_level(verbose=None, return_old_level=False): \"\"\"Convenience function",
"shape (2, n_samples). Otherwise, the number of channels in signal",
"run at least Pyglet ' 'version 1.2, and you are",
"used above def __init__(self, extra=''): \"\"\" Parameters ---------- extra: string",
"def wrapped(*args, **kwargs): warnings.warn(msg, category=DeprecationWarning) return init(*args, **kwargs) cls.__init__ =",
"Overwrite the log file (if it exists). Otherwise, statements will",
"to work (tested on OSX and Linux) return getattr(sys.stdout, name)",
"elif isinstance(a, (string_types, int, float, bytes)): if a != b:",
"back if we get an exception try: ret = function(*args,",
"------- stdout : str Stdout returned by the process. stderr",
"is not None: old_level = set_log_level(verbose_level, True) # set it",
"try: from pyglet.media.avbin import AVbinSource # noqa except ImportError: try:",
"same as 'WARNING'. If None, the environment variable EXPYFUN_LOGGING_LEVEL is",
"directly to set global verbosrity level, instead use set_log_level(). Parameters",
"string or None') if key not in known_config_types and not",
"str, or None Filename of the log to print to.",
"print_del return new def __init__(self): self._path = self.__str__() atexit.register(self.cleanup) def",
"n_channels=2, it will be tiled to be shape (2, n_samples).",
"just stdout) in order for this to work (tested on",
"should just be able to do: lh = logging.StreamHandler(sys.stdout) but",
"returned by the process. stderr : str Stderr returned by",
"if isinstance(verbose, string_types): verbose = verbose.upper() logging_types = dict(DEBUG=logging.DEBUG, INFO=logging.INFO,",
"the log to print to a file Parameters ---------- fname",
"look for. The os environment is searched first, then the",
"\"\"\" if key is None: return sorted(known_config_types) if not isinstance(key,",
"delay > 0. else send() def fake_mouse_click(ec, pos, button='left', delay=0.):",
"import scipy as sp from ._externals import decorator # set",
": int Length (in samples) of the rectangular window \"\"\"",
"if key is None: return sorted(known_config_types) if not isinstance(key, string_types):",
"from timeit import default_timer as clock from threading import Timer",
"b[key], pre + 'd1[%s]' % repr(key)) elif isinstance(a, (list, tuple)):",
"The preference key to look for. The os environment is",
"else: raise RuntimeError(pre + ': unsupported type %s (%s)' %",
"work around how doctest captures stdout.\"\"\" def __getattr__(self, name): #",
"This function uses a while loop. Although this slams the",
"arg_names): verbose_level = args[arg_names.index('verbose')] else: verbose_level = default_level if verbose_level",
"'overwrite=False to avoid this message in the ' 'future.') mode",
"are not passed for k in keys: params[k] = params.get(k,",
"return False return True def requires_video(): \"\"\"Requires FFmpeg/AVbin decorator.\"\"\" import",
"+ ' a is None, b is not (%s)\\n' %",
"example remote file Parameters ---------- fname : str The remote",
"'expyfun config file:\\n%s\\nTry either:\\n' ' %s\\nfor a temporary solution, or:\\n'",
"None: config.pop(key, None) else: config[key] = value # Write all",
"int(operator.index(n_channels)) signal = np.asarray(np.atleast_2d(signal), dtype=np.float32) # Check dimensionality if signal.ndim",
"i[4] is not None else '') for i in inspect.stack())",
"= ssl._create_unverified_context() this_urlopen = partial(urlopen, context=context) except AttributeError: context =",
"config_path = get_config_path() if op.isfile(config_path): with open(config_path, 'r') as fid:",
"the file will not be fetched again. Returns ------- fname",
"raise ImportError('On Linux, you must run at least Pyglet '",
"\"\"\"Set expyfun preference in config Parameters ---------- key : str",
"op.isdir(op.dirname(fname_out)): os.makedirs(op.dirname(fname_out)) fname_url = ('https://github.com/LABSN/expyfun-data/raw/master/{0}' ''.format(fname)) try: # until we",
"If None, the environment variable EXPYFUN_LOGGING_LEVEL is read, and if",
"isinstance(key, string_types): raise ValueError('key must be a string') # first,",
"(type(a), a)) return out def _check_skip_backend(backend): from expyfun._sound_controllers import _import_backend",
"logging.FileHandler): h.close() logger.removeHandler(h) if fname is not None: if op.isfile(fname)",
"be added to the deprecation messages \"\"\" self.extra = extra",
"None, b is not (%s)\\n' % (b) elif isinstance(a, np.ndarray):",
"\"\"\"Decorate function fun\"\"\" msg = \"Function %s is deprecated\" %",
"the process. stderr : str Stderr returned by the process.",
"FFmpeg/AVbin decorator.\"\"\" import pytest return pytest.mark.skipif(not _has_video(), reason='Requires FFmpeg/AVbin') def",
"----- This function only works with the keyboard controller (not",
"'AUDIO_CONTROLLER', 'DB_OF_SINE_AT_1KHZ_1RMS', 'EXPYFUN_EYELINK', 'SOUND_CARD_API', 'SOUND_CARD_BACKEND', 'SOUND_CARD_FS', 'SOUND_CARD_NAME', 'SOUND_CARD_FIXED_DELAY', 'TDT_CIRCUIT_PATH', 'TDT_DELAY',",
"out[0] @decorator def verbose_dec(function, *args, **kwargs): \"\"\"Improved verbose decorator to",
"olddoc: newdoc = \"%s\\n\\n%s\" % (newdoc, olddoc) return newdoc if",
"noqa input = raw_input # noqa, input is raw_input in",
"ones(win_length) / win_length, 'valid')) def _fix_audio_dims(signal, n_channels): \"\"\"Make it so",
"clock() - self._start_time def date_str(): \"\"\"Produce a date string for",
"p.returncode: err_fun = subprocess.CalledProcessError.__init__ if 'output' in _get_args(err_fun): raise subprocess.CalledProcessError(p.returncode,",
"or None') if key not in known_config_types and not \\",
"wins = _get_display().get_windows() for win in wins: win.dispatch_events() def running_rms(signal,",
"a file Parameters ---------- fname : str, or None Filename",
"by setting the verbosity level. Returns ------- dec - function",
"command, output) else: raise subprocess.CalledProcessError(p.returncode, command) return output class ZeroClock(object):",
"len(b): out += pre + ' length mismatch (%s, %s)\\n'",
"# noqa except ImportError: try: from pyglet.media.sources.avbin import AVbinSource #",
"logger.addHandler(lh) ############################################################################### # RANDOM UTILITIES building_doc = any('sphinx-build' in ((''.join(i[4]).lower()",
"---------- secs : float Number of seconds to wait. ec",
"handler.flush() def set_log_level(verbose=None, return_old_level=False): \"\"\"Convenience function for setting the logging",
"more ridiculous than this class, this must be sys.stdout (not",
"k1s: if key not in k2s: out += pre +",
"of a valid type') verbose = logging_types[verbose] old_verbose = logger.level",
"= json.load(fid) if key is None: return config key_found =",
"bool If True, return the old verbosity level. \"\"\" if",
"def set_log_level(verbose=None, return_old_level=False): \"\"\"Convenience function for setting the logging level",
"old_level = set_log_level(verbose_level, True) # set it back if we",
"logger.handlers for h in handlers: if isinstance(h, logging.FileHandler): h.close() logger.removeHandler(h)",
"that these are for convenience and are equivalent to passing",
"\"\"\"Produce a date string for the current date and time",
"sqrt, convolve, ones import logging import datetime from timeit import",
"key_found = True if key in config else False val",
"# set it back if we get an exception try:",
"analysis:ignore ############################################################################### # LOGGING EXP = 25 logging.addLevelName(EXP, 'EXP') def",
"warning when the function is called/the class is instantiated and",
"---------- units : str Must be ``'norm'``, ``'deg'``, or ``'pix'``.",
"do: lh = logging.StreamHandler(sys.stdout) but because doctests uses some magic",
"filename on the local system where the file was downloaded.",
"be a string or None') if key not in known_config_types",
"The decorated function \"\"\" arg_names = _get_args(function) if len(arg_names) >",
"io import StringIO # noqa, analysis:ignore from importlib import reload",
"== 2 and signal.shape[0] == 1: signal = np.tile(signal, (n_channels,",
"we allow users to override config # settings using env,",
"developers') return val def fetch_data_file(fname): \"\"\"Fetch example remote file Parameters",
"logging.addLevelName(EXP, 'EXP') def exp(self, message, *args, **kwargs): \"\"\"Experiment-level logging.\"\"\" self.log(EXP,",
"be $HOME/.expyfun/expyfun.json. \"\"\" val = op.join(_get_user_home_path(), '.expyfun', 'expyfun.json') return val",
"op import inspect import sys import tempfile import ssl from",
"if varargs: return out[:2] else: return out[0] @decorator def verbose_dec(function,",
"be checked and fixed. n_channels : int The number of",
"\"\"\"Compute all differences between two python variables Parameters ---------- a",
"config key_found = True if key in config else False",
"logging.Logger.exp = exp logger = logging.getLogger('expyfun') def flush_logger(): \"\"\"Flush expyfun",
"must be one of {}, not {}' ''.format(good_units, units)) ###############################################################################",
"os environment is searched first, then the expyfun config file",
"adapted with permission from mne-python kw = dict(stderr=subprocess.PIPE, stdout=subprocess.PIPE) kw.update(kwargs)",
"ssl._create_unverified_context() this_urlopen = partial(urlopen, context=context) except AttributeError: context = None",
"long. Parameters ---------- signal : array_like The (1-dimesional) signal of",
"lh = logging.StreamHandler(WrapStdOut()) lh.setFormatter(logging.Formatter(output_format)) # actually add the stream handler",
"add the stream handler logger.addHandler(lh) ############################################################################### # RANDOM UTILITIES building_doc",
"olddoc) return newdoc if hasattr(inspect, 'signature'): # py35 def _get_args(function,",
"testing modules. We cannot simply use __del__() method for cleanup",
"len(varargs) == 0: varargs = None return args, varargs else:",
"---------- fname : str The remote filename to get. If",
"doctest: +ELLIPSIS <expyfun._utils.deprecated object at ...> >>> @deprecated() ... def",
"timeout=30.0) try: fid.write(www.read()) finally: www.close() except Exception: os.remove(fname_out) raise return",
"add stdout= and stderr=subproces.PIPE to the call to Popen to",
"pos, button='left', delay=0.): \"\"\"Fake a mouse click after a delay\"\"\"",
"Parameters ---------- a : object Currently supported: dict, list, tuple,",
"Returns ------- diffs : str A string representation of the",
"extra def __call__(self, obj): \"\"\"Call.\"\"\" if isinstance(obj, type): return self._decorate_class(obj)",
"= 'expyfun.utils.set_config(\"%s\", VALUE)' % key raise KeyError('Key \"%s\" not found",
"Otherwise, the number of channels in signal must match n_channels.",
"value : str | None The value to assign to",
"logging.StreamHandler(sys.stdout) but because doctests uses some magic on stdout, we",
"import logging import datetime from timeit import default_timer as clock",
"1.2, and you are running ' '{0}'.format(pyglet.version)) return is_usable def",
"running_rms(signal, win_length): \"\"\"RMS of ``signal`` with rectangular window ``win_length`` samples",
"for h in handlers: if isinstance(h, logging.FileHandler): h.close() logger.removeHandler(h) if",
"permission from mne-python kw = dict(stderr=subprocess.PIPE, stdout=subprocess.PIPE) kw.update(kwargs) p =",
"a dict, got type {1}' .format(name, type(params))) params = deepcopy(params)",
"is returned, and ``value`` is ignored. value : str |",
"None The value to assign to the preference key. If",
"etc.) are processed. \"\"\" # hog the cpu, checking time",
"varargs: varargs = [param.name for param in params.values() if param.kind",
"{1}' .format(name, type(params))) params = deepcopy(params) if not isinstance(params, dict):",
"_check_skip_backend(backend): from expyfun._sound_controllers import _import_backend import pytest if isinstance(backend, dict):",
"= [keys[ii] for ii in idx] return keys def object_diff(a,",
"{1}' .format(name, type(params))) # Set sensible defaults for values that",
">>> deprecated() # doctest: +ELLIPSIS <expyfun._utils.deprecated object at ...> >>>",
"/ win_length, 'valid')) def _fix_audio_dims(signal, n_channels): \"\"\"Make it so a",
"newdoc = \"DEPRECATED\" if self.extra: newdoc = \"%s: %s\" %",
"slams the CPU, it will guarantee that events (keypresses, etc.)",
"Exception: os.remove(fname_out) raise return fname_out def get_config_path(): r\"\"\"Get path to",
"%s\\nfor a permanent one. You can also ' 'set the",
"out = '' if type(a) != type(b): out += pre",
"modules. We cannot simply use __del__() method for cleanup here",
"found. raise_error : bool If True, raise an error if",
"def _decorate_class(self, cls): msg = \"Class %s is deprecated\" %",
"ERROR=logging.ERROR, CRITICAL=logging.CRITICAL) if verbose not in logging_types: raise ValueError('verbose must",
"LooseVersion(version)) def _get_user_home_path(): \"\"\"Return standard preferences path\"\"\" # this has",
"class WrapStdOut(object): \"\"\"Ridiculous class to work around how doctest captures",
"sufficient = pyglet.gl.gl_info.have_version(2, 0) return pytest.mark.skipif(not sufficient, reason='OpenGL too old:",
"pytest return pytest.mark.skipif(not _has_video(), reason='Requires FFmpeg/AVbin') def requires_opengl21(func): \"\"\"Requires OpenGL",
"datestr : str The date string. \"\"\" return str(datetime.datetime.today()).replace(':', '_')",
"('https://github.com/LABSN/expyfun-data/raw/master/{0}' ''.format(fname)) try: # until we get proper certificates context",
"preference key to look for. The os environment is searched",
"!= 2: raise ValueError('Sound data must have one or two",
"ImportError('On Linux, you must run at least Pyglet ' 'version",
"import pyglet pyglet.options['debug_gl'] = False del pyglet except Exception: pass",
"text_type(text_like).encode('unicode_escape').decode('utf-8') def _sort_keys(x): \"\"\"Sort and return keys of dict\"\"\" keys",
"to prepend to each line. Returns ------- diffs : str",
"for setting the logging level Parameters ---------- verbose : bool,",
"if not op.isdir(op.dirname(fname_out)): os.makedirs(op.dirname(fname_out)) fname_url = ('https://github.com/LABSN/expyfun-data/raw/master/{0}' ''.format(fname)) try: #",
"isinstance(verbose, string_types): verbose = verbose.upper() logging_types = dict(DEBUG=logging.DEBUG, INFO=logging.INFO, WARNING=logging.WARNING,",
"Issue a warning when the function is called/the class is",
"\"\"\"Make it so a valid audio buffer is in the",
"import sys import tempfile import ssl from shutil import rmtree",
"else: string_types = str text_type = str from urllib.request import",
"the terminal. Parameters ---------- command : list of str Command",
"TypeError('{0} must be a dict, got type {1}' .format(name, type(params)))",
"= logger.level logger.setLevel(verbose) return (old_verbose if return_old_level else None) def",
"to the preference key. If None, the key is deleted.",
"*args, **kwargs) logging.Logger.exp = exp logger = logging.getLogger('expyfun') def flush_logger():",
"to pass to ``subprocess.Popen``. Returns ------- stdout : str Stdout",
"\"\"\"Class for creating and auto-destroying temp dir This is designed",
"string to be added to the deprecation messages \"\"\" self.extra",
"using subprocess.Popen Run command and wait for command to complete.",
"(tested on OSX and Linux) return getattr(sys.stdout, name) class _TempDir(str):",
"able to do: lh = logging.StreamHandler(sys.stdout) but because doctests uses",
"actually add the stream handler logger.addHandler(lh) ############################################################################### # RANDOM UTILITIES",
"keys: params[k] = params.get(k, get_config(k, defaults.get(k, None))) # Check keys",
"noqa, analysis:ignore ############################################################################### # LOGGING EXP = 25 logging.addLevelName(EXP, 'EXP')",
"args, varargs, keywords, defaults if varargs: return out[:2] else: return",
"(keypresses, etc.) are processed. \"\"\" # hog the cpu, checking",
"get_config(key=None, default=None, raise_error=False): \"\"\"Read expyfun preference from env, then expyfun",
"date string for the current date and time Returns -------",
"these are for convenience and are equivalent to passing in",
"import numpy as np import scipy as sp from ._externals",
"downloaded. \"\"\" path = get_config('EXPYFUN_DATA_PATH', op.join(_get_user_home_path(), '.expyfun', 'data')) fname_out =",
"except AttributeError: context = None this_urlopen = urlopen if not",
"\"\"\"Experiment-level logging.\"\"\" self.log(EXP, message, *args, **kwargs) logging.Logger.exp = exp logger",
"'TDT_TRIG_DELAY', 'TRIGGER_CONTROLLER', 'TRIGGER_ADDRESS', 'WINDOW_SIZE', 'SCREEN_NUM', 'SCREEN_WIDTH', 'SCREEN_DISTANCE', 'SCREEN_SIZE_PIX', 'EXPYFUN_LOGGING_LEVEL', )",
"for win in wins: win.dispatch_events() def running_rms(signal, win_length): \"\"\"RMS of",
"str, bytes, float, StringIO, BytesIO. b : object Must be",
"Do not call this directly to set global verbosrity level,",
"(lib, exp) else: val = False reason = '' return",
"os.environ[key] # second, look for it in expyfun config file",
": bool If True, raise an error if the key",
"count %d' % (signal.shape[0], n_channels)) return signal def _sanitize(text_like): \"\"\"Cast",
"+ELLIPSIS <expyfun._utils.deprecated object at ...> >>> @deprecated() ... def some_function():",
"= inspect.signature(function).parameters args = [key for key, param in params.items()",
"if len(m1): out += pre + ' x1 missing keys",
"verbose not in logging_types: raise ValueError('verbose must be of a",
"# doctest: +ELLIPSIS <expyfun._utils.deprecated object at ...> >>> @deprecated() ...",
"in handlers: if isinstance(h, logging.FileHandler): h.close() logger.removeHandler(h) if fname is",
"current date and time Returns ------- datestr : str The",
"local system where the file was downloaded. \"\"\" path =",
"<filename>expyfun/_utils.py \"\"\"Some utility functions\"\"\" # Authors: <NAME> <<EMAIL>> # #",
"the local system where the file was downloaded. \"\"\" path",
"will also add stdout= and stderr=subproces.PIPE to the call to",
"+= pre + ' value mismatch (%s, %s)\\n' % (a,",
"%s (%s)' % (type(a), a)) return out def _check_skip_backend(backend): from",
"- %(message)s\". overwrite : bool, or None Overwrite the log",
"one of {}, not {}' ''.format(good_units, units)) ############################################################################### # DECORATORS",
"messages to print. If a str, it can be either",
"str The date string. \"\"\" return str(datetime.datetime.today()).replace(':', '_') class WrapStdOut(object):",
"'') for i in inspect.stack()) def run_subprocess(command, **kwargs): \"\"\"Run command",
"def _new_pyglet(): import pyglet return LooseVersion(pyglet.version) >= LooseVersion('1.4') def _has_video():",
"_check_params(params, keys, defaults, name): if not isinstance(params, dict): raise TypeError('{0}",
"self._decorate_class(obj) else: return self._decorate_fun(obj) def _decorate_class(self, cls): msg = \"Class",
"of the valid keys is returned, and ``value`` is ignored.",
"if we get an exception try: ret = function(*args, **kwargs)",
"True) Timer(delay, send).start() if delay > 0. else send() def",
"wrapped.__name__ = '__init__' wrapped.__doc__ = self._update_doc(init.__doc__) wrapped.deprecated_original = init return",
"fun(*args, **kwargs) wrapped.__name__ = fun.__name__ wrapped.__dict__ = fun.__dict__ wrapped.__doc__ =",
"def requires_video(): \"\"\"Requires FFmpeg/AVbin decorator.\"\"\" import pytest return pytest.mark.skipif(not _has_video(),",
"pytest.mark.skipif(not sufficient, reason='OpenGL too old: %s %s' % (vendor, version,))(func)",
"command to complete. If the return code was zero then",
"the deprecation messages \"\"\" self.extra = extra def __call__(self, obj):",
"reason = '' return pytest.mark.skipif(val, reason=reason) def _has_scipy_version(version): return (LooseVersion(sp.__version__)",
"open(config_path, 'w') as fid: json.dump(config, fid, sort_keys=True, indent=0) ############################################################################### #",
"should have. If the input is mono and n_channels=2, it",
"raise KeyError('Unrecognized key in {0}[\"{1}\"], must be ' 'one of",
"def verbose_dec(function, *args, **kwargs): \"\"\"Improved verbose decorator to allow functions",
"%(message)s', overwrite=None): \"\"\"Convenience function for setting the log to print",
"else send() def fake_mouse_click(ec, pos, button='left', delay=0.): \"\"\"Fake a mouse",
"date string. \"\"\" return str(datetime.datetime.today()).replace(':', '_') class WrapStdOut(object): \"\"\"Ridiculous class",
"{0}[\"{1}\"], must be ' 'one of {2}'.format(name, k, ', '.join(keys)))",
"import os import os.path as op import inspect import sys",
"str Command to run as subprocess (see subprocess.Popen documentation). **kwargs",
"RuntimeError(pre + ': unsupported type %s (%s)' % (type(a), a))",
"\"%s\"' % key) # Read all previous values config_path =",
"'INFO') elif isinstance(verbose, bool): verbose = 'INFO' if verbose is",
"print('Deleting {} ...'.format(self._path)) rmtree(self._path, ignore_errors=True) def check_units(units): \"\"\"Ensure user passed",
"json from functools import partial from distutils.version import LooseVersion from",
"of str Command to run as subprocess (see subprocess.Popen documentation).",
"varargs: return out[:2] else: return out[0] @decorator def verbose_dec(function, *args,",
"'TRIGGER_ADDRESS', 'WINDOW_SIZE', 'SCREEN_NUM', 'SCREEN_WIDTH', 'SCREEN_DISTANCE', 'SCREEN_SIZE_PIX', 'EXPYFUN_LOGGING_LEVEL', ) # These",
"from copy import deepcopy import subprocess import importlib import os",
"pyglet.gl.gl_info.have_version(2, 0) return pytest.mark.skipif(not sufficient, reason='OpenGL too old: %s %s'",
"this_urlopen = urlopen if not op.isfile(fname_out): try: with open(fname_out, 'wb')",
"be a string') # first, check to see if key",
"None: raise ValueError('expyfun config file path could ' 'not be",
"units type Parameters ---------- units : str Must be ``'norm'``,",
"listed known_config_wildcards = () def get_config(key=None, default=None, raise_error=False): \"\"\"Read expyfun",
"output n_channels = int(operator.index(n_channels)) signal = np.asarray(np.atleast_2d(signal), dtype=np.float32) # Check",
"probably reset __new__ for full generality init = cls.__init__ def",
"be able to do: lh = logging.StreamHandler(sys.stdout) but because doctests",
"additionally raises a warning to notify the user that log",
"send() def _check_pyglet_version(raise_error=False): \"\"\"Check pyglet version, return True if usable.",
"check to see if key is in env if key",
"_has_video(), reason='Requires FFmpeg/AVbin') def requires_opengl21(func): \"\"\"Requires OpenGL decorator.\"\"\" import pytest",
"config Parameters ---------- key : str The preference key to",
"be appended to the log (default). None is the same",
"the file was downloaded. \"\"\" path = get_config('EXPYFUN_DATA_PATH', op.join(_get_user_home_path(), '.expyfun',",
"functions to override log-level Do not call this directly to",
"(not TDT)! It uses threads to ensure that control is",
"self._start_time = clock() def get_time(self): \"\"\"Get time.\"\"\" return clock() -",
"---------- extra: string to be added to the deprecation messages",
"False else: try: from pyglet.media.avbin import AVbinSource # noqa except",
"string_types = str text_type = str from urllib.request import urlopen",
"importlib import reload # noqa, analysis:ignore ############################################################################### # LOGGING EXP",
"a valid audio buffer is in the standard dimensions Parameters",
"n_samples). Otherwise, the number of channels in signal must match",
": callable Function to be decorated by setting the verbosity",
"in logging.DEBUG, etc. For bool, True is the same as",
"return ret def _new_pyglet(): import pyglet return LooseVersion(pyglet.version) >= LooseVersion('1.4')",
"file config_path = get_config_path() if not op.isfile(config_path): key_found = False",
"if b is not None: out += pre + '",
"will be appended to the log (default). None is the",
"str The filename on the local system where the file",
"= 'INFO' if verbose is True else 'WARNING' if isinstance(verbose,",
"isinstance(params, dict): raise TypeError('{0} must be a dict, got {1}'",
"the output messages. See the following for examples: http://docs.python.org/dev/howto/logging.html e.g.,",
"Keywoard arguments to pass to ``subprocess.Popen``. Returns ------- stdout :",
"b is not (%s)\\n' % (b) elif isinstance(a, np.ndarray): if",
"config = json.load(fid) if key is None: return config key_found",
"str.__new__(self, tempfile.mkdtemp()) self._del_after = del_after self._print_del = print_del return new",
"ec=None): \"\"\"Wait a specified number of seconds. Parameters ---------- secs",
"# args, varargs, keywords, defaults if varargs: return out[:2] else:",
"'SOUND_CARD_FS', 'SOUND_CARD_NAME', 'SOUND_CARD_FIXED_DELAY', 'TDT_CIRCUIT_PATH', 'TDT_DELAY', 'TDT_INTERFACE', 'TDT_MODEL', 'TDT_TRIG_DELAY', 'TRIGGER_CONTROLLER', 'TRIGGER_ADDRESS',",
"log-level Do not call this directly to set global verbosrity",
"h.close() logger.removeHandler(h) if fname is not None: if op.isfile(fname) and",
"for key, param in params.items() if param.kind not in (param.VAR_POSITIONAL,",
"except Exception as exc: pytest.skip('Skipping test for backend %s: %s'",
"JSON allow non-string types, we allow users to override config",
"while loop. Although this slams the CPU, it will guarantee",
"passed for k in keys: params[k] = params.get(k, get_config(k, defaults.get(k,",
"' 'overwrite=False to avoid this message in the ' 'future.')",
"except ImportError: try: from pyglet.media.sources.avbin import AVbinSource # noqa except",
"button = dict(left=1, middle=2, right=4)[button] # trans to pyglet def",
"a while loop. Although this slams the CPU, it will",
"noqa except ImportError: return False else: try: from pyglet.media.avbin import",
"@deprecated() ... def some_function(): pass \"\"\" # Adapted from http://wiki.python.org/moin/PythonDecoratorLibrary,",
"ImportError: return False return True def requires_video(): \"\"\"Requires FFmpeg/AVbin decorator.\"\"\"",
"(n_channels, N). \"\"\" # Check requested channel output n_channels =",
"!= len(b): out += pre + ' length mismatch (%s,",
"type %s (%s)' % (type(a), a)) return out def _check_skip_backend(backend):",
"path to the expyfun configuration file. On windows, this will",
"be decorated by setting the verbosity level. Returns ------- dec",
"fname_out = op.join(path, fname) if not op.isdir(op.dirname(fname_out)): os.makedirs(op.dirname(fname_out)) fname_url =",
"deprecated(object): \"\"\"Decorator to mark a function or class as deprecated.",
"logger\"\"\" for handler in logger.handlers: handler.flush() def set_log_level(verbose=None, return_old_level=False): \"\"\"Convenience",
"# noqa from cStringIO import StringIO # noqa else: string_types",
"def wrapped(*args, **kwargs): warnings.warn(msg, category=DeprecationWarning) return fun(*args, **kwargs) wrapped.__name__ =",
"keywords, defaults if varargs: return out[:2] else: return out[0] @decorator",
"get. If the filename already exists on the local system,",
"delay=0.): \"\"\"Fake a button press after a delay Notes -----",
"the log (default). None is the same as False, but",
"return if the key is not found. raise_error : bool",
"type(a) != type(b): out += pre + ' type mismatch",
"requires_opengl21(func): \"\"\"Requires OpenGL decorator.\"\"\" import pytest import pyglet.gl vendor =",
"ImportError: return False else: try: from pyglet.media.avbin import AVbinSource #",
"try: ret = function(*args, **kwargs) except Exception: set_log_level(old_level) raise set_log_level(old_level)",
"' x1 missing keys %s\\n' % (m1) for key in",
"ValueError('\"units\" must be one of {}, not {}' ''.format(good_units, units))",
"and key in os.environ: return os.environ[key] # second, look for",
"a self-contained example is used above def __init__(self, extra=''): \"\"\"",
"equivalent to passing in logging.DEBUG, etc. For bool, True is",
"def __init__(self): self._path = self.__str__() atexit.register(self.cleanup) def cleanup(self): if self._del_after",
"it doesn't exist, defaults to INFO. return_old_level : bool If",
"from threading import Timer import numpy as np import scipy",
"object_diff(a[key], b[key], pre + 'd1[%s]' % repr(key)) elif isinstance(a, (list,",
"int, str, bytes, float, StringIO, BytesIO. b : object Must",
"{2}'.format(name, k, ', '.join(keys))) return params def _get_display(): import pyglet",
"= [key for key, param in params.items() if param.kind not",
"{} ...'.format(self._path)) rmtree(self._path, ignore_errors=True) def check_units(units): \"\"\"Ensure user passed valid",
"import deprecated >>> deprecated() # doctest: +ELLIPSIS <expyfun._utils.deprecated object at",
"set_log_level(old_level) return ret else: ret = function(*args, **kwargs) return ret",
"------- value : str | None The preference key value.",
"def __init__(self, extra=''): \"\"\" Parameters ---------- extra: string to be",
"``win_length`` samples long. Parameters ---------- signal : array_like The (1-dimesional)",
"raise ValueError('key must be a string') # While JSON allow",
"array_like The (1-dimesional) signal of interest. win_length : int Length",
"arguments to pass to ``subprocess.Popen``. Returns ------- stdout : str",
"expyfun._utils import deprecated >>> deprecated() # doctest: +ELLIPSIS <expyfun._utils.deprecated object",
"out += pre + ' a is None, b is",
"the CPU, it will guarantee that events (keypresses, etc.) are",
"wins: win.dispatch_events() def running_rms(signal, win_length): \"\"\"RMS of ``signal`` with rectangular",
"tempfile.mkdtemp()) self._del_after = del_after self._print_del = print_del return new def",
"and raise_error is True: meth_1 = 'os.environ[\"%s\"] = VALUE' %",
"If the return code was zero then return, otherwise raise",
"kw = dict(stderr=subprocess.PIPE, stdout=subprocess.PIPE) kw.update(kwargs) p = subprocess.Popen(command, **kw) stdout_,",
"signal = np.tile(signal, (n_channels, 1)) if signal.shape[0] != n_channels: raise",
"Taken from mne-python with permission. \"\"\" out = '' if",
"urllib.request import urlopen input = input from io import StringIO",
"val def set_config(key, value): \"\"\"Set expyfun preference in config Parameters",
"Returns ------- fname : str The filename on the local",
"if a != b: out += pre + ' value",
"to Popen to suppress printing to the terminal. Parameters ----------",
"a str, it can be either DEBUG, INFO, WARNING, ERROR,",
"if key in config else False val = config.get(key, default)",
"else: config = dict() logger.info('Attempting to create new expyfun configuration",
"def object_diff(a, b, pre=''): \"\"\"Compute all differences between two python",
"': unsupported type %s (%s)' % (type(a), a)) return out",
"OpenGL decorator.\"\"\" import pytest import pyglet.gl vendor = pyglet.gl.gl_info.get_vendor() version",
"raise ValueError('Sound data must have one or two dimensions, got",
"preferences path\"\"\" # this has been checked on OSX64, Linux64,",
"be appended to the deprecation message and the docstring. Note:",
"an error if the key is not found (instead of",
"not import on all platforms b/c it can be #",
"raise set_log_level(old_level) return ret else: ret = function(*args, **kwargs) return",
"a string or None') if key not in known_config_types and",
"indent=0) ############################################################################### # MISC def fake_button_press(ec, button='1', delay=0.): \"\"\"Fake a",
"from pyglet.media.sources.avbin import AVbinSource # noqa except ImportError: return False",
"except ImportError: return False return True def requires_video(): \"\"\"Requires FFmpeg/AVbin",
": str Format of the output messages. See the following",
"elif a is None: if b is not None: out",
"= pyglet.canvas.get_display() except AttributeError: # < 1.4 display = pyglet.window.get_platform().get_default_display()",
"if delay > 0. else send() def _check_pyglet_version(raise_error=False): \"\"\"Check pyglet",
"' array mismatch\\n' else: raise RuntimeError(pre + ': unsupported type",
"= init return cls def _decorate_fun(self, fun): \"\"\"Decorate function fun\"\"\"",
"value for extra, put in an empty of parentheses: >>>",
"'%APPDATA%\\.expyfun\\expyfun.json'. On every other system, this will be $HOME/.expyfun/expyfun.json. \"\"\"",
"be ' 'one of {2}'.format(name, k, ', '.join(keys))) return params",
"except AttributeError: # < 1.4 display = pyglet.window.get_platform().get_default_display() return display",
"wrapped wrapped.__name__ = '__init__' wrapped.__doc__ = self._update_doc(init.__doc__) wrapped.deprecated_original = init",
"= wrapped wrapped.__name__ = '__init__' wrapped.__doc__ = self._update_doc(init.__doc__) wrapped.deprecated_original =",
"'NAME_1' is okay key if 'NAME' is listed known_config_wildcards =",
"level. Returns ------- dec - function The decorated function \"\"\"",
"= int(operator.index(n_channels)) signal = np.asarray(np.atleast_2d(signal), dtype=np.float32) # Check dimensionality if",
"err_fun = subprocess.CalledProcessError.__init__ if 'output' in _get_args(err_fun): raise subprocess.CalledProcessError(p.returncode, command,",
"creating and auto-destroying temp dir This is designed to be",
"pyglet return LooseVersion(pyglet.version) >= LooseVersion('1.4') def _has_video(): if _new_pyglet(): try:",
"' 'not be determined, please report this ' 'error to",
"the rmtree function may be cleaned up before this object,",
"if op.isfile(config_path): with open(config_path, 'r') as fid: config = json.load(fid)",
"== 1: signal = np.tile(signal, (n_channels, 1)) if signal.shape[0] !=",
"not in keys: raise KeyError('Unrecognized key in {0}[\"{1}\"], must be",
"and auto-destroying temp dir This is designed to be used",
"\"\"\"Ridiculous class to work around how doctest captures stdout.\"\"\" def",
"INFO. return_old_level : bool If True, return the old verbosity",
"appended to the deprecation message and the docstring. Note: to",
"list(x.keys()) # note: not thread-safe idx = np.argsort([str(k) for k",
"config_path) if value is None: config.pop(key, None) else: config[key] =",
"tuple)): if len(a) != len(b): out += pre + '",
"Timer(delay, send).start() if delay > 0. else send() def _check_pyglet_version(raise_error=False):",
"= pyglet.gl.gl_info.have_version(2, 0) return pytest.mark.skipif(not sufficient, reason='OpenGL too old: %s",
"be called (like wait_for_presses). \"\"\" def send(): ec._response_handler._on_pyglet_keypress(button, [], True)",
"import on all platforms b/c it can be # sklearn",
"= '' if type(a) != type(b): out += pre +",
"b) elif a is None: if b is not None:",
"__del__() method for cleanup here because the rmtree function may",
"= str text_type = str from urllib.request import urlopen input",
"get_config_path(): r\"\"\"Get path to standard expyfun config file. Returns -------",
"else: try: from pyglet.media.avbin import AVbinSource # noqa except ImportError:",
"this to work (tested on OSX and Linux) return getattr(sys.stdout,",
"to complete. If the return code was zero then return,",
"KeyError('Unrecognized key in {0}[\"{1}\"], must be ' 'one of {2}'.format(name,",
"class deprecated(object): \"\"\"Decorator to mark a function or class as",
"output class ZeroClock(object): \"\"\"Clock that uses \"clock\" function but starts",
"pyglet.gl vendor = pyglet.gl.gl_info.get_vendor() version = pyglet.gl.gl_info.get_version() sufficient = pyglet.gl.gl_info.have_version(2,",
"in py3k text_type = unicode # noqa from __builtin__ import",
"op.isfile(config_path): key_found = False val = default else: with open(config_path,",
"config.pop(key, None) else: config[key] = value # Write all values",
"k1s = _sort_keys(a) k2s = _sort_keys(b) m1 = set(k2s) -",
"from urllib.request import urlopen input = input from io import",
"ec._mouse_handler._on_pyglet_mouse_click(pos[0], pos[1], button, []) Timer(delay, send).start() if delay > 0.",
"primarily for debugging purposes. \"\"\" def __new__(self, del_after=True, print_del=False): new",
"logging.StreamHandler(WrapStdOut()) lh.setFormatter(logging.Formatter(output_format)) # actually add the stream handler logger.addHandler(lh) ###############################################################################",
"sp from ._externals import decorator # set this first thing",
"ZeroClock(object): \"\"\"Clock that uses \"clock\" function but starts at zero",
"(vendor, version,))(func) def requires_lib(lib): \"\"\"Requires lib decorator.\"\"\" import pytest try:",
"not op.isfile(config_path): key_found = False val = default else: with",
"# Authors: <NAME> <<EMAIL>> # # License: BSD (3-clause) import",
"If True, return the old verbosity level. \"\"\" if verbose",
"%s)\\n' % (a, b) elif a is None: if b",
"the default value for extra, put in an empty of",
"2, ones(win_length) / win_length, 'valid')) def _fix_audio_dims(signal, n_channels): \"\"\"Make it",
"as np import scipy as sp from ._externals import decorator",
"the keyboard controller (not TDT)! It uses threads to ensure",
"is True: meth_1 = 'os.environ[\"%s\"] = VALUE' % key meth_2",
"_decorate_class(self, cls): msg = \"Class %s is deprecated\" % cls.__name__",
"try: display = pyglet.canvas.get_display() except AttributeError: # < 1.4 display",
"---------- function : callable Function to be decorated by setting",
"Check keys for k in params.keys(): if k not in",
"decorator.\"\"\" import pytest return pytest.mark.skipif(not _has_video(), reason='Requires FFmpeg/AVbin') def requires_opengl21(func):",
"> 0 and arg_names[0] == 'self': default_level = getattr(args[0], 'verbose',",
"import sqrt, convolve, ones import logging import datetime from timeit",
"'SOUND_CARD_FIXED_DELAY', 'TDT_CIRCUIT_PATH', 'TDT_DELAY', 'TDT_INTERFACE', 'TDT_MODEL', 'TDT_TRIG_DELAY', 'TRIGGER_CONTROLLER', 'TRIGGER_ADDRESS', 'WINDOW_SIZE', 'SCREEN_NUM',",
"Otherwise, statements will be appended to the log (default). None",
"a function or class as deprecated. Issue a warning when",
"if key not in k2s: out += pre + '",
"'output' in _get_args(err_fun): raise subprocess.CalledProcessError(p.returncode, command, output) else: raise subprocess.CalledProcessError(p.returncode,",
"params = deepcopy(params) if not isinstance(params, dict): raise TypeError('{0} must",
"A string representation of the differences. Notes ----- Taken from",
"is the same as 'INFO', False is the same as",
"config else False val = config.get(key, default) if not key_found",
"return params def _get_display(): import pyglet try: display = pyglet.canvas.get_display()",
"BSD (3-clause) import warnings import operator from copy import deepcopy",
"key is None: return sorted(known_config_types) if not isinstance(key, string_types): raise",
"determined, please report this ' 'error to expyfun developers') return",
"config file is parsed. default : str | None Value",
"the same as 'INFO', False is the same as 'WARNING'.",
"\"\"\"Get time.\"\"\" return clock() - self._start_time def date_str(): \"\"\"Produce a",
"``'norm'``, ``'deg'``, or ``'pix'``. \"\"\" good_units = ['norm', 'pix', 'deg']",
"else: return args else: def _get_args(function, varargs=False): out = inspect.getargspec(function)",
"extra: string to be added to the deprecation messages \"\"\"",
"params.values() if param.kind == param.VAR_POSITIONAL] if len(varargs) == 0: varargs",
"changes. # scikit-learn will not import on all platforms b/c",
"init(*args, **kwargs) cls.__init__ = wrapped wrapped.__name__ = '__init__' wrapped.__doc__ =",
"This is designed to be used with testing modules. We",
"exp) else: val = False reason = '' return pytest.mark.skipif(val,",
"not (%s)\\n' % (b) elif isinstance(a, np.ndarray): if not np.array_equal(a,",
"temporary solution, or:\\n' ' %s\\nfor a permanent one. You can",
"' value mismatch (%s, %s)\\n' % (a, b) elif a",
"deprecated. Issue a warning when the function is called/the class",
"signal_fixed : array The signal with standard dimensions (n_channels, N).",
"a warning to the docstring. The optional extra argument will",
"requested channel output n_channels = int(operator.index(n_channels)) signal = np.asarray(np.atleast_2d(signal), dtype=np.float32)",
"None is the same as False, but additionally raises a",
"is None: raise ValueError('expyfun config file path could ' 'not",
"backend %s: %s' % (backend, exc)) def _check_params(params, keys, defaults,",
"= _get_display().get_windows() for win in wins: win.dispatch_events() def running_rms(signal, win_length):",
"the docstring. The optional extra argument will be appended to",
"default_level = getattr(args[0], 'verbose', None) else: default_level = None if('verbose'",
"for this to work (tested on OSX and Linux) return",
"we should just be able to do: lh = logging.StreamHandler(sys.stdout)",
"'expyfun.utils.set_config(\"%s\", VALUE)' % key raise KeyError('Key \"%s\" not found in",
"\"\"\" # code adapted with permission from mne-python kw =",
"verbosrity level, instead use set_log_level(). Parameters ---------- function : callable",
"if hasattr(inspect, 'signature'): # py35 def _get_args(function, varargs=False): params =",
"with open(fname_out, 'wb') as fid: www = this_urlopen(fname_url, timeout=30.0) try:",
"file. Use ' 'overwrite=False to avoid this message in the",
"we should probably reset __new__ for full generality init =",
"| expyfun.ExperimentController instance The ExperimentController. Notes ----- This function uses",
"The signal with standard dimensions (n_channels, N). \"\"\" # Check",
"op.join(_get_user_home_path(), '.expyfun', 'expyfun.json') return val # List the known configuration",
"\"\"\"Fake a mouse click after a delay\"\"\" button = dict(left=1,",
"mismatch (%s, %s)\\n' % (len(a), len(b)) else: for xx1, xx2",
"del_after self._print_del = print_del return new def __init__(self): self._path =",
"print_del=False): new = str.__new__(self, tempfile.mkdtemp()) self._del_after = del_after self._print_del =",
"+= pre + ' array mismatch\\n' else: raise RuntimeError(pre +",
"len(b)) else: for xx1, xx2 in zip(a, b): out +=",
"and wait for command to complete. If the return code",
"many changes. # scikit-learn will not import on all platforms",
"shutil import rmtree import atexit import json from functools import",
"Parameters ---------- signal : array_like The signal whose dimensions should",
"<<EMAIL>> # # License: BSD (3-clause) import warnings import operator",
"is deprecated\" % fun.__name__ if self.extra: msg += \"; %s\"",
"known_config_wildcards = () def get_config(key=None, default=None, raise_error=False): \"\"\"Read expyfun preference",
"exists on the local system, the file will not be",
"and arg_names[0] == 'self': default_level = getattr(args[0], 'verbose', None) else:",
"= get_config_path() if op.isfile(config_path): with open(config_path, 'r') as fid: config",
"if units not in good_units: raise ValueError('\"units\" must be one",
"return pytest.mark.skipif(val, reason=reason) def _has_scipy_version(version): return (LooseVersion(sp.__version__) >= LooseVersion(version)) def",
"ignore_errors=True) def check_units(units): \"\"\"Ensure user passed valid units type Parameters",
"if delay > 0. else send() def fake_mouse_click(ec, pos, button='left',",
"'.expyfun', 'expyfun.json') return val # List the known configuration values",
">= LooseVersion(version)) def _get_user_home_path(): \"\"\"Return standard preferences path\"\"\" # this",
"import _import_backend import pytest if isinstance(backend, dict): # actually an",
"mode = 'w' if overwrite is True else 'a' lh",
"escape characters. \"\"\" return text_type(text_like).encode('unicode_escape').decode('utf-8') def _sort_keys(x): \"\"\"Sort and return",
"TypeError('{0} must be a dict, got {1}' .format(name, type(params))) #",
"will be appended. \"\"\" handlers = logger.handlers for h in",
"fetch_data_file(fname): \"\"\"Fetch example remote file Parameters ---------- fname : str",
"deprecation message and the docstring. Note: to use this with",
"some_function(): pass \"\"\" # Adapted from http://wiki.python.org/moin/PythonDecoratorLibrary, # but with",
"match n_channels. Returns ------- signal_fixed : array The signal with",
"\"\"\"RMS of ``signal`` with rectangular window ``win_length`` samples long. Parameters",
"the atexit module instead. Passing del_after and print_del kwargs to",
"file. On windows, this will be '%APPDATA%\\.expyfun\\expyfun.json'. On every other",
"Format of the output messages. See the following for examples:",
"' 'version 1.2, and you are running ' '{0}'.format(pyglet.version)) return",
"= raw_input # noqa, input is raw_input in py3k text_type",
"command : list of str Command to run as subprocess",
"len(a) != len(b): out += pre + ' length mismatch",
": str Stdout returned by the process. stderr : str",
"as 'WARNING'. If None, the environment variable EXPYFUN_LOGGING_LEVEL is read,",
"Length (in samples) of the rectangular window \"\"\" return sqrt(convolve(signal",
"be # sklearn or scikits.learn, so a self-contained example is",
"key in {0}[\"{1}\"], must be ' 'one of {2}'.format(name, k,",
"else: ret = function(*args, **kwargs) return ret def _new_pyglet(): import",
"'file:\\n%s' % config_path) if value is None: config.pop(key, None) else:",
"object_diff(xx1, xx2, pre='') elif isinstance(a, (string_types, int, float, bytes)): if",
"an AC backend = backend['SOUND_CARD_BACKEND'] try: _import_backend(backend) except Exception as",
"else: return out[0] @decorator def verbose_dec(function, *args, **kwargs): \"\"\"Improved verbose",
"scipy as sp from ._externals import decorator # set this",
"def _has_scipy_version(version): return (LooseVersion(sp.__version__) >= LooseVersion(version)) def _get_user_home_path(): \"\"\"Return standard",
"k in params.keys(): if k not in keys: raise KeyError('Unrecognized",
"VALUE)' % key raise KeyError('Key \"%s\" not found in environment",
"return out def _check_skip_backend(backend): from expyfun._sound_controllers import _import_backend import pytest",
"mark a function or class as deprecated. Issue a warning",
"cStringIO import StringIO # noqa else: string_types = str text_type",
"type(b)) elif isinstance(a, dict): k1s = _sort_keys(a) k2s = _sort_keys(b)",
"{}, not {}' ''.format(good_units, units)) ############################################################################### # DECORATORS # Following",
"b is not None: out += pre + ' a",
"handler logger.addHandler(lh) ############################################################################### # RANDOM UTILITIES building_doc = any('sphinx-build' in",
"= this_urlopen(fname_url, timeout=30.0) try: fid.write(www.read()) finally: www.close() except Exception: os.remove(fname_out)",
"be '%APPDATA%\\.expyfun\\expyfun.json'. On every other system, this will be $HOME/.expyfun/expyfun.json.",
"############################################################################### # MISC def fake_button_press(ec, button='1', delay=0.): \"\"\"Fake a button",
"b : object Must be same type as ``a``. pre",
"False reason = '' return pytest.mark.skipif(val, reason=reason) def _has_scipy_version(version): return",
"and fixed. n_channels : int The number of channels that",
"win_length : int Length (in samples) of the rectangular window",
"object Must be same type as ``a``. pre : str",
"in k1s: if key not in k2s: out += pre",
"docstring. The optional extra argument will be appended to the",
"Parameters ---------- key : str | None The preference key",
"op.isdir(directory): os.mkdir(directory) with open(config_path, 'w') as fid: json.dump(config, fid, sort_keys=True,",
"run as subprocess (see subprocess.Popen documentation). **kwargs : objects Keywoard",
"default value for extra, put in an empty of parentheses:",
"str The remote filename to get. If the filename already",
"the standard dimensions Parameters ---------- signal : array_like The signal",
"if not op.isfile(config_path): key_found = False val = default else:",
"bool): verbose = 'INFO' if verbose is True else 'WARNING'",
"by the process. \"\"\" # code adapted with permission from",
"passed valid units type Parameters ---------- units : str Must",
"License: BSD (3-clause) import warnings import operator from copy import",
"deprecated class copied from scikit-learn class deprecated(object): \"\"\"Decorator to mark",
"= dict(left=1, middle=2, right=4)[button] # trans to pyglet def send():",
"> 0. else send() def _check_pyglet_version(raise_error=False): \"\"\"Check pyglet version, return",
"olddoc): newdoc = \"DEPRECATED\" if self.extra: newdoc = \"%s: %s\"",
"# Write all values directory = op.split(config_path)[0] if not op.isdir(directory):",
"None: out += pre + ' a is None, b",
"constructor are helpful primarily for debugging purposes. \"\"\" def __new__(self,",
"\"\"\"Sort and return keys of dict\"\"\" keys = list(x.keys()) #",
"import urlopen # noqa from cStringIO import StringIO # noqa",
"+= pre + ' x1 missing keys %s\\n' % (m1)",
"Set sensible defaults for values that are not passed for",
"return keys def object_diff(a, b, pre=''): \"\"\"Compute all differences between",
"def check_units(units): \"\"\"Ensure user passed valid units type Parameters ----------",
"= str.__new__(self, tempfile.mkdtemp()) self._del_after = del_after self._print_del = print_del return",
"key is not found. raise_error : bool If True, raise",
"= del_after self._print_del = print_del return new def __init__(self): self._path",
"dict() logger.info('Attempting to create new expyfun configuration ' 'file:\\n%s' %",
": float Number of seconds to wait. ec : None",
"2 and signal.shape[0] == 1: signal = np.tile(signal, (n_channels, 1))",
"to standard expyfun config file. Returns ------- config_path : str",
"keys of dict\"\"\" keys = list(x.keys()) # note: not thread-safe",
"Parameters ---------- signal : array_like The (1-dimesional) signal of interest.",
"subprocess (see subprocess.Popen documentation). **kwargs : objects Keywoard arguments to",
"around how doctest captures stdout.\"\"\" def __getattr__(self, name): # Even",
"if raise_error is True and is_usable is False: raise ImportError('On",
"to the deprecation messages \"\"\" self.extra = extra def __call__(self,",
"pre + 'd1[%s]' % repr(key)) elif isinstance(a, (list, tuple)): if",
"pytest import pyglet.gl vendor = pyglet.gl.gl_info.get_vendor() version = pyglet.gl.gl_info.get_version() sufficient",
"return True if usable. \"\"\" import pyglet is_usable = LooseVersion(pyglet.version)",
"auto-destroying temp dir This is designed to be used with",
"del pyglet except Exception: pass # for py3k (eventually) if",
"By default, this will also add stdout= and stderr=subproces.PIPE to",
"so we use the atexit module instead. Passing del_after and",
"If None, the key is deleted. \"\"\" if key is",
"clock() if ec is not None: while (clock() - t0)",
"and time Returns ------- datestr : str The date string.",
"# DECORATORS # Following deprecated class copied from scikit-learn class",
"np.array_equal(a, b): out += pre + ' array mismatch\\n' else:",
"None, the key is deleted. \"\"\" if key is None:",
"thing to make sure it \"takes\" try: import pyglet pyglet.options['debug_gl']",
"out += object_diff(xx1, xx2, pre='') elif isinstance(a, (string_types, int, float,",
"scikits.learn, so a self-contained example is used above def __init__(self,",
"= 'w' if overwrite is True else 'a' lh =",
"config file. Returns ------- config_path : str The path to",
"'EXPYFUN_EYELINK', 'SOUND_CARD_API', 'SOUND_CARD_BACKEND', 'SOUND_CARD_FS', 'SOUND_CARD_NAME', 'SOUND_CARD_FIXED_DELAY', 'TDT_CIRCUIT_PATH', 'TDT_DELAY', 'TDT_INTERFACE', 'TDT_MODEL',",
"window \"\"\" return sqrt(convolve(signal ** 2, ones(win_length) / win_length, 'valid'))",
"keys for k in params.keys(): if k not in keys:",
"in _get_args(err_fun): raise subprocess.CalledProcessError(p.returncode, command, output) else: raise subprocess.CalledProcessError(p.returncode, command)",
"expyfun config file. Returns ------- config_path : str The path",
"(%s, %s)\\n' % (len(a), len(b)) else: for xx1, xx2 in",
"= logging.StreamHandler(sys.stdout) but because doctests uses some magic on stdout,",
"units)) ############################################################################### # DECORATORS # Following deprecated class copied from",
"decorator # set this first thing to make sure it",
"t0) < secs: ec._dispatch_events() ec.check_force_quit() else: wins = _get_display().get_windows() for",
"control is passed back, so other commands can be called",
"how doctest captures stdout.\"\"\" def __getattr__(self, name): # Even more",
"is the same as 'WARNING'. If None, the environment variable",
"of seconds to wait. ec : None | expyfun.ExperimentController instance",
"_sort_keys(x): \"\"\"Sort and return keys of dict\"\"\" keys = list(x.keys())",
"raise KeyError('Key \"%s\" not found in environment or in the",
"again. Returns ------- fname : str The filename on the",
"2: raise ValueError('Sound data must have one or two dimensions,",
"set(k1s) if len(m1): out += pre + ' x1 missing",
"file will not be fetched again. Returns ------- fname :",
"'.join(keys))) return params def _get_display(): import pyglet try: display =",
"import StringIO # noqa, analysis:ignore from importlib import reload #",
"(%s, %s)\\n' % (a, b) elif a is None: if",
"magic on stdout, we have to do this: \"\"\" lh",
"previous values config_path = get_config_path() if op.isfile(config_path): with open(config_path, 'r')",
"__call__(self, obj): \"\"\"Call.\"\"\" if isinstance(obj, type): return self._decorate_class(obj) else: return",
"@decorator def verbose_dec(function, *args, **kwargs): \"\"\"Improved verbose decorator to allow",
"logging_types: raise ValueError('verbose must be of a valid type') verbose",
"checking time t0 = clock() if ec is not None:",
"objects Keywoard arguments to pass to ``subprocess.Popen``. Returns ------- stdout",
"if k not in keys: raise KeyError('Unrecognized key in {0}[\"{1}\"],",
"############################################################################### # RANDOM UTILITIES building_doc = any('sphinx-build' in ((''.join(i[4]).lower() +",
"isinstance(verbose, bool): verbose = 'INFO' if verbose is True else",
"wait_for_presses). \"\"\" def send(): ec._response_handler._on_pyglet_keypress(button, [], True) Timer(delay, send).start() if",
"print to. If None, stdout is used. To suppress log",
"decorator.\"\"\" import pytest try: importlib.import_module(lib) except Exception as exp: val",
"default) if not key_found and raise_error is True: meth_1 =",
"obj): \"\"\"Call.\"\"\" if isinstance(obj, type): return self._decorate_class(obj) else: return self._decorate_fun(obj)",
"(stdout_.decode(), stderr.decode()) if p.returncode: err_fun = subprocess.CalledProcessError.__init__ if 'output' in",
">= LooseVersion('1.2') if raise_error is True and is_usable is False:",
"set_log_level(old_level) raise set_log_level(old_level) return ret else: ret = function(*args, **kwargs)",
"we use the atexit module instead. Passing del_after and print_del",
"on the local system where the file was downloaded. \"\"\"",
"to be decorated by setting the verbosity level. Returns -------",
"def fetch_data_file(fname): \"\"\"Fetch example remote file Parameters ---------- fname :",
"number of channels that the output should have. If the",
"send(): ec._response_handler._on_pyglet_keypress(button, [], True) Timer(delay, send).start() if delay > 0.",
"is None, b is not (%s)\\n' % (b) elif isinstance(a,",
"import Timer import numpy as np import scipy as sp",
"for ii in idx] return keys def object_diff(a, b, pre=''):",
"if sys.version.startswith('2'): string_types = basestring # noqa input = raw_input",
"deprecation messages \"\"\" self.extra = extra def __call__(self, obj): \"\"\"Call.\"\"\"",
"import LooseVersion from numpy import sqrt, convolve, ones import logging",
"returned by the process. \"\"\" # code adapted with permission",
"= set(k2s) - set(k1s) if len(m1): out += pre +",
"---------- verbose : bool, str, int, or None The verbosity",
"Parameters ---------- secs : float Number of seconds to wait.",
"hasattr(inspect, 'signature'): # py35 def _get_args(function, varargs=False): params = inspect.signature(function).parameters",
"b): out += object_diff(xx1, xx2, pre='') elif isinstance(a, (string_types, int,",
"None) def set_log_file(fname=None, output_format='%(asctime)s - %(levelname)-7s - %(message)s', overwrite=None): \"\"\"Convenience",
"to override log-level Do not call this directly to set",
"# just stdout) in order for this to work (tested",
"output should have. If the input is mono and n_channels=2,",
"% (newdoc, self.extra) if olddoc: newdoc = \"%s\\n\\n%s\" % (newdoc,",
"guarantee that events (keypresses, etc.) are processed. \"\"\" # hog",
"' 'error to expyfun developers') return val def fetch_data_file(fname): \"\"\"Fetch",
"defaults if varargs: return out[:2] else: return out[0] @decorator def",
"\"\"\" def __new__(self, del_after=True, print_del=False): new = str.__new__(self, tempfile.mkdtemp()) self._del_after",
"not None: old_level = set_log_level(verbose_level, True) # set it back",
"from io import StringIO # noqa, analysis:ignore from importlib import",
"''.format(good_units, units)) ############################################################################### # DECORATORS # Following deprecated class copied",
"'pix', 'deg'] if units not in good_units: raise ValueError('\"units\" must",
"message, *args, **kwargs) logging.Logger.exp = exp logger = logging.getLogger('expyfun') def",
"def _sort_keys(x): \"\"\"Sort and return keys of dict\"\"\" keys =",
"of interest. win_length : int Length (in samples) of the",
"matches: 'NAME_1' is okay key if 'NAME' is listed known_config_wildcards",
"str String to prepend to each line. Returns ------- diffs",
"not None: if op.isfile(fname) and overwrite is None: warnings.warn('Log entries",
"fid, sort_keys=True, indent=0) ############################################################################### # MISC def fake_button_press(ec, button='1', delay=0.):",
"ValueError('key must be a string') # While JSON allow non-string",
"doesn't exist, defaults to INFO. return_old_level : bool If True,",
"'r') as fid: config = json.load(fid) else: config = dict()",
"it exists). Otherwise, statements will be appended to the log",
"for. The os environment is searched first, then the expyfun",
"works with the keyboard controller (not TDT)! It uses threads",
"%s\\n' % key else: out += object_diff(a[key], b[key], pre +",
"value mismatch (%s, %s)\\n' % (a, b) elif a is",
"override config # settings using env, which are strings, so",
"verbosity level. \"\"\" if verbose is None: verbose = get_config('EXPYFUN_LOGGING_LEVEL',",
"np.tile(signal, (n_channels, 1)) if signal.shape[0] != n_channels: raise ValueError('signal channel",
"is True: if self._print_del is True: print('Deleting {} ...'.format(self._path)) rmtree(self._path,",
"command using subprocess.Popen Run command and wait for command to",
"urlopen if not op.isfile(fname_out): try: with open(fname_out, 'wb') as fid:",
"not in k2s: out += pre + ' x2 missing",
"%s is deprecated\" % cls.__name__ if self.extra: msg += \";",
"= dict(DEBUG=logging.DEBUG, INFO=logging.INFO, WARNING=logging.WARNING, ERROR=logging.ERROR, CRITICAL=logging.CRITICAL) if verbose not in",
"' 'future.') mode = 'w' if overwrite is True else",
"The filename on the local system where the file was",
"'not be determined, please report this ' 'error to expyfun",
"+= \"; %s\" % self.extra def wrapped(*args, **kwargs): warnings.warn(msg, category=DeprecationWarning)",
"the docstring. Note: to use this with the default value",
"returned, and ``value`` is ignored. value : str | None",
"system, this will be $HOME/.expyfun/expyfun.json. \"\"\" val = op.join(_get_user_home_path(), '.expyfun',",
"be used with testing modules. We cannot simply use __del__()",
"_update_doc(self, olddoc): newdoc = \"DEPRECATED\" if self.extra: newdoc = \"%s:",
"meth_2)) return val def set_config(key, value): \"\"\"Set expyfun preference in",
"is parsed. default : str | None Value to return",
"also add stdout= and stderr=subproces.PIPE to the call to Popen",
"input from io import StringIO # noqa, analysis:ignore from importlib",
"is okay key if 'NAME' is listed known_config_wildcards = ()",
"If None, a tuple of the valid keys is returned,",
"print_del kwargs to the constructor are helpful primarily for debugging",
"= pyglet.gl.gl_info.get_version() sufficient = pyglet.gl.gl_info.have_version(2, 0) return pytest.mark.skipif(not sufficient, reason='OpenGL",
"and if it doesn't exist, defaults to INFO. return_old_level :",
"def exp(self, message, *args, **kwargs): \"\"\"Experiment-level logging.\"\"\" self.log(EXP, message, *args,",
"win in wins: win.dispatch_events() def running_rms(signal, win_length): \"\"\"RMS of ``signal``",
">>> @deprecated() ... def some_function(): pass \"\"\" # Adapted from",
"self._decorate_fun(obj) def _decorate_class(self, cls): msg = \"Class %s is deprecated\"",
"verbose decorator to allow functions to override log-level Do not",
"json.load(fid) else: config = dict() logger.info('Attempting to create new expyfun",
"is not None: while (clock() - t0) < secs: ec._dispatch_events()",
"class copied from scikit-learn class deprecated(object): \"\"\"Decorator to mark a",
"could ' 'not be determined, please report this ' 'error",
"key in k1s: if key not in k2s: out +=",
"outputs, use set_log_level('WARN'). output_format : str Format of the output",
"as clock from threading import Timer import numpy as np",
"the expyfun configuration file. On windows, this will be '%APPDATA%\\.expyfun\\expyfun.json'.",
"as exp: val = True reason = 'Needs %s (%s)'",
"inspect.signature(function).parameters args = [key for key, param in params.items() if",
"'self': default_level = getattr(args[0], 'verbose', None) else: default_level = None",
"\"\"\" return str(datetime.datetime.today()).replace(':', '_') class WrapStdOut(object): \"\"\"Ridiculous class to work",
"key in os.environ: return os.environ[key] # second, look for it",
"wrapped.__doc__ = self._update_doc(fun.__doc__) return wrapped def _update_doc(self, olddoc): newdoc =",
"a button press after a delay Notes ----- This function",
"import warnings import operator from copy import deepcopy import subprocess",
"interest. win_length : int Length (in samples) of the rectangular",
"this ' 'error to expyfun developers') return val def fetch_data_file(fname):",
"+= pre + ' length mismatch (%s, %s)\\n' % (len(a),",
"else: val = False reason = '' return pytest.mark.skipif(val, reason=reason)",
"== 0: varargs = None return args, varargs else: return",
"reload # noqa, analysis:ignore ############################################################################### # LOGGING EXP = 25",
"p = subprocess.Popen(command, **kw) stdout_, stderr = p.communicate() output =",
"is True and is_usable is False: raise ImportError('On Linux, you",
"\"\"\"Return standard preferences path\"\"\" # this has been checked on",
"import pytest import pyglet.gl vendor = pyglet.gl.gl_info.get_vendor() version = pyglet.gl.gl_info.get_version()",
"isinstance(a, dict): k1s = _sort_keys(a) k2s = _sort_keys(b) m1 =",
"until we get proper certificates context = ssl._create_unverified_context() this_urlopen =",
"np.ndarray): if not np.array_equal(a, b): out += pre + '",
"call to Popen to suppress printing to the terminal. Parameters",
"def _decorate_fun(self, fun): \"\"\"Decorate function fun\"\"\" msg = \"Function %s",
"n_channels)) return signal def _sanitize(text_like): \"\"\"Cast as string, encode as",
"isinstance(a, (list, tuple)): if len(a) != len(b): out += pre",
"cleanup(self): if self._del_after is True: if self._print_del is True: print('Deleting",
"basestring # noqa input = raw_input # noqa, input is",
"verbose is True else 'WARNING' if isinstance(verbose, string_types): verbose =",
"= p.communicate() output = (stdout_.decode(), stderr.decode()) if p.returncode: err_fun =",
"= False val = default else: with open(config_path, 'r') as",
"fake_mouse_click(ec, pos, button='left', delay=0.): \"\"\"Fake a mouse click after a",
"if value is None: config.pop(key, None) else: config[key] = value",
"path\"\"\" # this has been checked on OSX64, Linux64, and",
"logging.getLogger('expyfun') def flush_logger(): \"\"\"Flush expyfun logger\"\"\" for handler in logger.handlers:",
"key_found = False val = default else: with open(config_path, 'r')",
"%s\\n' % (m1) for key in k1s: if key not",
"is in the standard dimensions Parameters ---------- signal : array_like",
"win_length, 'valid')) def _fix_audio_dims(signal, n_channels): \"\"\"Make it so a valid",
"*args, **kwargs): \"\"\"Experiment-level logging.\"\"\" self.log(EXP, message, *args, **kwargs) logging.Logger.exp =",
"# until we get proper certificates context = ssl._create_unverified_context() this_urlopen",
"mne-python with permission. \"\"\" out = '' if type(a) !=",
"a != b: out += pre + ' value mismatch",
"self._del_after = del_after self._print_del = print_del return new def __init__(self):",
"and sanitize any escape characters. \"\"\" return text_type(text_like).encode('unicode_escape').decode('utf-8') def _sort_keys(x):",
"function is called/the class is instantiated and adds a warning",
"Note: to use this with the default value for extra,",
"'w') as fid: json.dump(config, fid, sort_keys=True, indent=0) ############################################################################### # MISC",
"(a, b) elif a is None: if b is not",
"here if not isinstance(value, string_types) and value is not None:",
"\"\"\" self.extra = extra def __call__(self, obj): \"\"\"Call.\"\"\" if isinstance(obj,",
"value to assign to the preference key. If None, the",
"dec - function The decorated function \"\"\" arg_names = _get_args(function)",
"same type as ``a``. pre : str String to prepend",
"not op.isdir(op.dirname(fname_out)): os.makedirs(op.dirname(fname_out)) fname_url = ('https://github.com/LABSN/expyfun-data/raw/master/{0}' ''.format(fname)) try: # until",
"strings, so we enforce that here if not isinstance(value, string_types)",
"time Returns ------- datestr : str The date string. \"\"\"",
"``signal`` with rectangular window ``win_length`` samples long. Parameters ---------- signal",
"doctests uses some magic on stdout, we have to do",
"for partial matches: 'NAME_1' is okay key if 'NAME' is",
"val = os.getenv('APPDATA' if 'nt' == os.name.lower() else 'HOME', None)",
"**kwargs) cls.__init__ = wrapped wrapped.__name__ = '__init__' wrapped.__doc__ = self._update_doc(init.__doc__)",
"two dimensions, got %s.' % (signal.ndim,)) # Return data with",
"dimensionality if signal.ndim != 2: raise ValueError('Sound data must have",
"functions\"\"\" # Authors: <NAME> <<EMAIL>> # # License: BSD (3-clause)",
"str, it can be either DEBUG, INFO, WARNING, ERROR, or",
"of returning default). Returns ------- value : str | None",
"out = inspect.getargspec(function) # args, varargs, keywords, defaults if varargs:",
"Although this slams the CPU, it will guarantee that events",
"string. \"\"\" return str(datetime.datetime.today()).replace(':', '_') class WrapStdOut(object): \"\"\"Ridiculous class to",
"subprocess.CalledProcessError(p.returncode, command, output) else: raise subprocess.CalledProcessError(p.returncode, command) return output class",
"use __del__() method for cleanup here because the rmtree function",
": str | None Value to return if the key",
"+ i[1]) if i[4] is not None else '') for",
"a string') # first, check to see if key is",
"if param.kind == param.VAR_POSITIONAL] if len(varargs) == 0: varargs =",
"verbose = verbose.upper() logging_types = dict(DEBUG=logging.DEBUG, INFO=logging.INFO, WARNING=logging.WARNING, ERROR=logging.ERROR, CRITICAL=logging.CRITICAL)",
"to do this: \"\"\" lh = logging.StreamHandler(WrapStdOut()) lh.setFormatter(logging.Formatter(output_format)) # actually",
"ImportError: try: from pyglet.media.sources.avbin import AVbinSource # noqa except ImportError:",
"os.remove(fname_out) raise return fname_out def get_config_path(): r\"\"\"Get path to standard",
"is not None: raise ValueError('value must be a string or",
"config[key] = value # Write all values directory = op.split(config_path)[0]",
": int The number of channels that the output should",
"keys, defaults, name): if not isinstance(params, dict): raise TypeError('{0} must",
"= None if('verbose' in arg_names): verbose_level = args[arg_names.index('verbose')] else: verbose_level",
"pytest.mark.skipif(not _has_video(), reason='Requires FFmpeg/AVbin') def requires_opengl21(func): \"\"\"Requires OpenGL decorator.\"\"\" import",
"\"Function %s is deprecated\" % fun.__name__ if self.extra: msg +=",
"not np.array_equal(a, b): out += pre + ' array mismatch\\n'",
"verbose is None: verbose = get_config('EXPYFUN_LOGGING_LEVEL', 'INFO') elif isinstance(verbose, bool):",
"= subprocess.Popen(command, **kw) stdout_, stderr = p.communicate() output = (stdout_.decode(),",
"(3-clause) import warnings import operator from copy import deepcopy import",
"the process. \"\"\" # code adapted with permission from mne-python",
"None The preference key value. \"\"\" if key is not",
"because doctests uses some magic on stdout, we have to",
"None The verbosity of messages to print. If a str,",
"config = json.load(fid) else: config = dict() logger.info('Attempting to create",
"os.makedirs(op.dirname(fname_out)) fname_url = ('https://github.com/LABSN/expyfun-data/raw/master/{0}' ''.format(fname)) try: # until we get",
"pyglet.media.avbin import AVbinSource # noqa except ImportError: try: from pyglet.media.sources.avbin",
"platforms b/c it can be # sklearn or scikits.learn, so",
"self.extra) if olddoc: newdoc = \"%s\\n\\n%s\" % (newdoc, olddoc) return",
"sklearn or scikits.learn, so a self-contained example is used above",
"= extra def __call__(self, obj): \"\"\"Call.\"\"\" if isinstance(obj, type): return",
"elif isinstance(a, np.ndarray): if not np.array_equal(a, b): out += pre",
"be ``'norm'``, ``'deg'``, or ``'pix'``. \"\"\" good_units = ['norm', 'pix',",
"object_diff(a, b, pre=''): \"\"\"Compute all differences between two python variables",
"True) # set it back if we get an exception",
"cannot simply use __del__() method for cleanup here because the",
"Exception as exp: val = True reason = 'Needs %s",
"OSX and Linux) return getattr(sys.stdout, name) class _TempDir(str): \"\"\"Class for",
"*args, **kwargs): \"\"\"Improved verbose decorator to allow functions to override",
"except Exception: os.remove(fname_out) raise return fname_out def get_config_path(): r\"\"\"Get path",
"expyfun logger\"\"\" for handler in logger.handlers: handler.flush() def set_log_level(verbose=None, return_old_level=False):",
"lh = logging.StreamHandler(sys.stdout) but because doctests uses some magic on",
"if the key is not found (instead of returning default).",
"getattr(args[0], 'verbose', None) else: default_level = None if('verbose' in arg_names):",
"= op.split(config_path)[0] if not op.isdir(directory): os.mkdir(directory) with open(config_path, 'w') as",
"exp(self, message, *args, **kwargs): \"\"\"Experiment-level logging.\"\"\" self.log(EXP, message, *args, **kwargs)",
"instead. Passing del_after and print_del kwargs to the constructor are",
": array_like The (1-dimesional) signal of interest. win_length : int",
"for cleanup here because the rmtree function may be cleaned",
"signal.shape[0] == 1: signal = np.tile(signal, (n_channels, 1)) if signal.shape[0]",
"os.environ: return os.environ[key] # second, look for it in expyfun",
"display = pyglet.canvas.get_display() except AttributeError: # < 1.4 display =",
"\"\"\"Check pyglet version, return True if usable. \"\"\" import pyglet",
": object Currently supported: dict, list, tuple, ndarray, int, str,",
"dict\"\"\" keys = list(x.keys()) # note: not thread-safe idx =",
"for key in k1s: if key not in k2s: out",
"deprecated() # doctest: +ELLIPSIS <expyfun._utils.deprecated object at ...> >>> @deprecated()",
"= False reason = '' return pytest.mark.skipif(val, reason=reason) def _has_scipy_version(version):",
"None | expyfun.ExperimentController instance The ExperimentController. Notes ----- This function",
"is_usable = LooseVersion(pyglet.version) >= LooseVersion('1.2') if raise_error is True and",
"the constructor are helpful primarily for debugging purposes. \"\"\" def",
"'HOME', None) if val is None: raise ValueError('expyfun config file",
"wrapped(*args, **kwargs): warnings.warn(msg, category=DeprecationWarning) return fun(*args, **kwargs) wrapped.__name__ = fun.__name__",
"stdout= and stderr=subproces.PIPE to the call to Popen to suppress",
"= pyglet.gl.gl_info.get_vendor() version = pyglet.gl.gl_info.get_version() sufficient = pyglet.gl.gl_info.have_version(2, 0) return",
"__getattr__(self, name): # Even more ridiculous than this class, this",
"varargs else: return args else: def _get_args(function, varargs=False): out =",
"LooseVersion('1.2') if raise_error is True and is_usable is False: raise",
"keys is returned, and ``value`` is ignored. value : str",
"cls.__name__ if self.extra: msg += \"; %s\" % self.extra #",
"np import scipy as sp from ._externals import decorator #",
"are for convenience and are equivalent to passing in logging.DEBUG,",
"fname : str, or None Filename of the log to",
"\"%s\" not found in environment or in the ' 'expyfun",
"warning to the docstring. The optional extra argument will be",
"dimensions (n_channels, N). \"\"\" # Check requested channel output n_channels",
"level. \"\"\" if verbose is None: verbose = get_config('EXPYFUN_LOGGING_LEVEL', 'INFO')",
"\"\"\" def send(): ec._response_handler._on_pyglet_keypress(button, [], True) Timer(delay, send).start() if delay",
"get proper certificates context = ssl._create_unverified_context() this_urlopen = partial(urlopen, context=context)",
"len(arg_names) > 0 and arg_names[0] == 'self': default_level = getattr(args[0],",
"from scikit-learn class deprecated(object): \"\"\"Decorator to mark a function or",
"report this ' 'error to expyfun developers') return val def",
"# second, look for it in expyfun config file config_path",
"dict(DEBUG=logging.DEBUG, INFO=logging.INFO, WARNING=logging.WARNING, ERROR=logging.ERROR, CRITICAL=logging.CRITICAL) if verbose not in logging_types:",
"env, then expyfun config Parameters ---------- key : str The",
"code was zero then return, otherwise raise CalledProcessError. By default,",
"return the old verbosity level. \"\"\" if verbose is None:",
"one. You can also ' 'set the environment variable before",
"\"\"\"Fetch example remote file Parameters ---------- fname : str The",
"key raise KeyError('Key \"%s\" not found in environment or in",
"error if the key is not found (instead of returning",
"The date string. \"\"\" return str(datetime.datetime.today()).replace(':', '_') class WrapStdOut(object): \"\"\"Ridiculous",
"instead use set_log_level(). Parameters ---------- function : callable Function to",
"(key, config_path, meth_1, meth_2)) return val def set_config(key, value): \"\"\"Set",
"subprocess.Popen Run command and wait for command to complete. If",
"config Parameters ---------- key : str | None The preference",
"to the call to Popen to suppress printing to the",
"to do: lh = logging.StreamHandler(sys.stdout) but because doctests uses some",
"_get_args(function, varargs=False): out = inspect.getargspec(function) # args, varargs, keywords, defaults",
"else: raise subprocess.CalledProcessError(p.returncode, command) return output class ZeroClock(object): \"\"\"Clock that",
"' %s\\nfor a temporary solution, or:\\n' ' %s\\nfor a permanent",
"and not isinstance(key, string_types): raise ValueError('key must be a string')",
"**kwargs : objects Keywoard arguments to pass to ``subprocess.Popen``. Returns",
"non-standard config type: \"%s\"' % key) # Read all previous",
"defaults, name): if not isinstance(params, dict): raise TypeError('{0} must be",
"'data')) fname_out = op.join(path, fname) if not op.isdir(op.dirname(fname_out)): os.makedirs(op.dirname(fname_out)) fname_url",
"handler in logger.handlers: handler.flush() def set_log_level(verbose=None, return_old_level=False): \"\"\"Convenience function for",
"known_config_types = ('RESPONSE_DEVICE', 'AUDIO_CONTROLLER', 'DB_OF_SINE_AT_1KHZ_1RMS', 'EXPYFUN_EYELINK', 'SOUND_CARD_API', 'SOUND_CARD_BACKEND', 'SOUND_CARD_FS', 'SOUND_CARD_NAME',",
"Notes ----- This function only works with the keyboard controller",
"# noqa from __builtin__ import reload from urllib2 import urlopen",
"pass \"\"\" # Adapted from http://wiki.python.org/moin/PythonDecoratorLibrary, # but with many",
"get_config('EXPYFUN_LOGGING_LEVEL', 'INFO') elif isinstance(verbose, bool): verbose = 'INFO' if verbose",
"...> >>> @deprecated() ... def some_function(): pass \"\"\" # Adapted",
"did not match required ' 'channel count %d' % (signal.shape[0],",
"dict, list, tuple, ndarray, int, str, bytes, float, StringIO, BytesIO.",
"**kwargs): \"\"\"Run command using subprocess.Popen Run command and wait for",
"def _check_pyglet_version(raise_error=False): \"\"\"Check pyglet version, return True if usable. \"\"\"",
"number of seconds. Parameters ---------- secs : float Number of",
"- t0) < secs: ec._dispatch_events() ec.check_force_quit() else: wins = _get_display().get_windows()",
"def _get_display(): import pyglet try: display = pyglet.canvas.get_display() except AttributeError:",
"put in an empty of parentheses: >>> from expyfun._utils import",
"any escape characters. \"\"\" return text_type(text_like).encode('unicode_escape').decode('utf-8') def _sort_keys(x): \"\"\"Sort and",
"_sort_keys(b) m1 = set(k2s) - set(k1s) if len(m1): out +=",
"of the differences. Notes ----- Taken from mne-python with permission.",
"are helpful primarily for debugging purposes. \"\"\" def __new__(self, del_after=True,",
"try: from pyglet.media.sources.avbin import AVbinSource # noqa except ImportError: return",
"def _wait_secs(secs, ec=None): \"\"\"Wait a specified number of seconds. Parameters",
"key is deleted. \"\"\" if key is None: return sorted(known_config_types)",
"messages. See the following for examples: http://docs.python.org/dev/howto/logging.html e.g., \"%(asctime)s -",
"n_channels. Returns ------- signal_fixed : array The signal with standard",
"list of str Command to run as subprocess (see subprocess.Popen",
"in config Parameters ---------- key : str | None The",
"' 'set the environment variable before ' 'running python.' %",
"for values that are not passed for k in keys:",
"click after a delay\"\"\" button = dict(left=1, middle=2, right=4)[button] #",
"optional extra argument will be appended to the deprecation message",
"or:\\n' ' %s\\nfor a permanent one. You can also '",
"of ``signal`` with rectangular window ``win_length`` samples long. Parameters ----------",
"if not op.isfile(fname_out): try: with open(fname_out, 'wb') as fid: www",
"None: while (clock() - t0) < secs: ec._dispatch_events() ec.check_force_quit() else:",
"must be ' 'one of {2}'.format(name, k, ', '.join(keys))) return",
"requires_lib(lib): \"\"\"Requires lib decorator.\"\"\" import pytest try: importlib.import_module(lib) except Exception",
"self.__str__() atexit.register(self.cleanup) def cleanup(self): if self._del_after is True: if self._print_del",
"get_config(k, defaults.get(k, None))) # Check keys for k in params.keys():",
"\"\"\"Requires lib decorator.\"\"\" import pytest try: importlib.import_module(lib) except Exception as",
"def some_function(): pass \"\"\" # Adapted from http://wiki.python.org/moin/PythonDecoratorLibrary, # but",
"\"\"\" # hog the cpu, checking time t0 = clock()",
"return args else: def _get_args(function, varargs=False): out = inspect.getargspec(function) #",
"wrapped.__doc__ = self._update_doc(init.__doc__) wrapped.deprecated_original = init return cls def _decorate_fun(self,",
"warnings.warn('Log entries will be appended to the file. Use '",
": str | None The value to assign to the",
"to the terminal. Parameters ---------- command : list of str",
"in ((''.join(i[4]).lower() + i[1]) if i[4] is not None else",
"type(params))) params = deepcopy(params) if not isinstance(params, dict): raise TypeError('{0}",
"back, so other commands can be called (like wait_for_presses). \"\"\"",
"if len(varargs) == 0: varargs = None return args, varargs",
"values known_config_types = ('RESPONSE_DEVICE', 'AUDIO_CONTROLLER', 'DB_OF_SINE_AT_1KHZ_1RMS', 'EXPYFUN_EYELINK', 'SOUND_CARD_API', 'SOUND_CARD_BACKEND', 'SOUND_CARD_FS',",
": str Must be ``'norm'``, ``'deg'``, or ``'pix'``. \"\"\" good_units",
"wrapped.__name__ = fun.__name__ wrapped.__dict__ = fun.__dict__ wrapped.__doc__ = self._update_doc(fun.__doc__) return",
"x1 missing keys %s\\n' % (m1) for key in k1s:",
"(list, tuple)): if len(a) != len(b): out += pre +",
"= exp logger = logging.getLogger('expyfun') def flush_logger(): \"\"\"Flush expyfun logger\"\"\"",
": None | expyfun.ExperimentController instance The ExperimentController. Notes ----- This",
"channel count %d did not match required ' 'channel count",
"file (if it exists). Otherwise, statements will be appended to",
"to get. If the filename already exists on the local",
"message and the docstring. Note: to use this with the",
"_fix_audio_dims(signal, n_channels): \"\"\"Make it so a valid audio buffer is",
"to INFO. return_old_level : bool If True, return the old",
"signal def _sanitize(text_like): \"\"\"Cast as string, encode as UTF-8 and",
"is None: warnings.warn('Log entries will be appended to the file.",
"stdout_, stderr = p.communicate() output = (stdout_.decode(), stderr.decode()) if p.returncode:",
"ec.check_force_quit() else: wins = _get_display().get_windows() for win in wins: win.dispatch_events()",
"to the deprecation message and the docstring. Note: to use",
"be determined, please report this ' 'error to expyfun developers')",
"mne-python kw = dict(stderr=subprocess.PIPE, stdout=subprocess.PIPE) kw.update(kwargs) p = subprocess.Popen(command, **kw)",
"environment or in the ' 'expyfun config file:\\n%s\\nTry either:\\n' '",
"os.path as op import inspect import sys import tempfile import",
"name): # Even more ridiculous than this class, this must",
"we get an exception try: ret = function(*args, **kwargs) except",
"handlers: if isinstance(h, logging.FileHandler): h.close() logger.removeHandler(h) if fname is not",
"ones import logging import datetime from timeit import default_timer as",
"pyglet def send(): ec._mouse_handler._on_pyglet_mouse_click(pos[0], pos[1], button, []) Timer(delay, send).start() if",
"WARNING, ERROR, or CRITICAL. Note that these are for convenience",
"pos[1], button, []) Timer(delay, send).start() if delay > 0. else",
"+ ' x1 missing keys %s\\n' % (m1) for key",
"| None The preference key value. \"\"\" if key is",
"is None: config.pop(key, None) else: config[key] = value # Write",
"ridiculous than this class, this must be sys.stdout (not #",
"channel output n_channels = int(operator.index(n_channels)) signal = np.asarray(np.atleast_2d(signal), dtype=np.float32) #",
"ec._dispatch_events() ec.check_force_quit() else: wins = _get_display().get_windows() for win in wins:",
"see if key is in env if key is not",
"= logger.handlers for h in handlers: if isinstance(h, logging.FileHandler): h.close()",
"be fetched again. Returns ------- fname : str The filename",
"in the standard dimensions Parameters ---------- signal : array_like The",
"dtype=np.float32) # Check dimensionality if signal.ndim != 2: raise ValueError('Sound",
"be shape (2, n_samples). Otherwise, the number of channels in",
"= str from urllib.request import urlopen input = input from",
"params.items() if param.kind not in (param.VAR_POSITIONAL, param.VAR_KEYWORD)] if varargs: varargs",
"EXP = 25 logging.addLevelName(EXP, 'EXP') def exp(self, message, *args, **kwargs):",
"= dict() logger.info('Attempting to create new expyfun configuration ' 'file:\\n%s'",
"pyglet.canvas.get_display() except AttributeError: # < 1.4 display = pyglet.window.get_platform().get_default_display() return",
"\"%s\\n\\n%s\" % (newdoc, olddoc) return newdoc if hasattr(inspect, 'signature'): #",
"1: signal = np.tile(signal, (n_channels, 1)) if signal.shape[0] != n_channels:",
"[param.name for param in params.values() if param.kind == param.VAR_POSITIONAL] if",
"we have to do this: \"\"\" lh = logging.StreamHandler(WrapStdOut()) lh.setFormatter(logging.Formatter(output_format))",
"this will be $HOME/.expyfun/expyfun.json. \"\"\" val = op.join(_get_user_home_path(), '.expyfun', 'expyfun.json')",
"(see subprocess.Popen documentation). **kwargs : objects Keywoard arguments to pass",
"be same type as ``a``. pre : str String to",
"else: with open(config_path, 'r') as fid: config = json.load(fid) if",
"elif isinstance(verbose, bool): verbose = 'INFO' if verbose is True",
"AttributeError: context = None this_urlopen = urlopen if not op.isfile(fname_out):",
"%s' % (backend, exc)) def _check_params(params, keys, defaults, name): if",
"this object, so we use the atexit module instead. Passing",
"good_units = ['norm', 'pix', 'deg'] if units not in good_units:",
"self._print_del is True: print('Deleting {} ...'.format(self._path)) rmtree(self._path, ignore_errors=True) def check_units(units):",
"at zero on init.\"\"\" def __init__(self): self._start_time = clock() def",
"wrapped def _update_doc(self, olddoc): newdoc = \"DEPRECATED\" if self.extra: newdoc",
"% (lib, exp) else: val = False reason = ''",
"# Even more ridiculous than this class, this must be",
"b): out += pre + ' array mismatch\\n' else: raise",
"not in good_units: raise ValueError('\"units\" must be one of {},",
"got type {1}' .format(name, type(params))) params = deepcopy(params) if not",
"exception try: ret = function(*args, **kwargs) except Exception: set_log_level(old_level) raise",
"rmtree import atexit import json from functools import partial from",
"config_path = get_config_path() if not op.isfile(config_path): key_found = False val",
"variable before ' 'running python.' % (key, config_path, meth_1, meth_2))",
"warnings.warn('Setting non-standard config type: \"%s\"' % key) # Read all",
"str text_type = str from urllib.request import urlopen input =",
"logging_types[verbose] old_verbose = logger.level logger.setLevel(verbose) return (old_verbose if return_old_level else",
"else: default_level = None if('verbose' in arg_names): verbose_level = args[arg_names.index('verbose')]",
"time t0 = clock() if ec is not None: while",
"out += pre + ' type mismatch (%s, %s)\\n' %",
"for i in inspect.stack()) def run_subprocess(command, **kwargs): \"\"\"Run command using",
"= False del pyglet except Exception: pass # for py3k",
"all platforms b/c it can be # sklearn or scikits.learn,",
"import AVbinSource # noqa except ImportError: try: from pyglet.media.sources.avbin import",
"sanitize any escape characters. \"\"\" return text_type(text_like).encode('unicode_escape').decode('utf-8') def _sort_keys(x): \"\"\"Sort",
"the log to print to. If None, stdout is used.",
"(backend, exc)) def _check_params(params, keys, defaults, name): if not isinstance(params,",
"channels that the output should have. If the input is",
"get_config('EXPYFUN_DATA_PATH', op.join(_get_user_home_path(), '.expyfun', 'data')) fname_out = op.join(path, fname) if not",
"False val = default else: with open(config_path, 'r') as fid:",
"the known configuration values known_config_types = ('RESPONSE_DEVICE', 'AUDIO_CONTROLLER', 'DB_OF_SINE_AT_1KHZ_1RMS', 'EXPYFUN_EYELINK',",
"send(): ec._mouse_handler._on_pyglet_mouse_click(pos[0], pos[1], button, []) Timer(delay, send).start() if delay >",
"press after a delay Notes ----- This function only works",
": str A string representation of the differences. Notes -----",
"return_old_level : bool If True, return the old verbosity level.",
"= '' return pytest.mark.skipif(val, reason=reason) def _has_scipy_version(version): return (LooseVersion(sp.__version__) >=",
"every other system, this will be $HOME/.expyfun/expyfun.json. \"\"\" val =",
"will guarantee that events (keypresses, etc.) are processed. \"\"\" #",
"'SCREEN_SIZE_PIX', 'EXPYFUN_LOGGING_LEVEL', ) # These allow for partial matches: 'NAME_1'",
"captures stdout.\"\"\" def __getattr__(self, name): # Even more ridiculous than",
"``subprocess.Popen``. Returns ------- stdout : str Stdout returned by the",
"If True, raise an error if the key is not",
"noqa from cStringIO import StringIO # noqa else: string_types =",
"command) return output class ZeroClock(object): \"\"\"Clock that uses \"clock\" function",
"if key is None: return config key_found = True if",
"fun.__name__ wrapped.__dict__ = fun.__dict__ wrapped.__doc__ = self._update_doc(fun.__doc__) return wrapped def",
"for backend %s: %s' % (backend, exc)) def _check_params(params, keys,",
"% key raise KeyError('Key \"%s\" not found in environment or",
"args[arg_names.index('verbose')] else: verbose_level = default_level if verbose_level is not None:",
"of channels in signal must match n_channels. Returns ------- signal_fixed",
"return keys of dict\"\"\" keys = list(x.keys()) # note: not",
"must be a string') # While JSON allow non-string types,",
"and print_del kwargs to the constructor are helpful primarily for",
"'valid')) def _fix_audio_dims(signal, n_channels): \"\"\"Make it so a valid audio",
"audio buffer is in the standard dimensions Parameters ---------- signal",
"from importlib import reload # noqa, analysis:ignore ############################################################################### # LOGGING",
"(default). None is the same as False, but additionally raises",
"it in expyfun config file config_path = get_config_path() if not",
"Exception: set_log_level(old_level) raise set_log_level(old_level) return ret else: ret = function(*args,",
"pytest.skip('Skipping test for backend %s: %s' % (backend, exc)) def",
"test for backend %s: %s' % (backend, exc)) def _check_params(params,",
"note: not thread-safe idx = np.argsort([str(k) for k in keys])",
"else False val = config.get(key, default) if not key_found and",
"------- diffs : str A string representation of the differences.",
"get_config_path() if not op.isfile(config_path): key_found = False val = default",
"or None Overwrite the log file (if it exists). Otherwise,",
"is True else 'WARNING' if isinstance(verbose, string_types): verbose = verbose.upper()",
"extra, put in an empty of parentheses: >>> from expyfun._utils",
"if it doesn't exist, defaults to INFO. return_old_level : bool",
"newdoc if hasattr(inspect, 'signature'): # py35 def _get_args(function, varargs=False): params",
"def _get_args(function, varargs=False): params = inspect.signature(function).parameters args = [key for",
"val = True reason = 'Needs %s (%s)' % (lib,",
"string_types): raise ValueError('key must be a string') # While JSON",
"% fun.__name__ if self.extra: msg += \"; %s\" % self.extra",
"a warning when the function is called/the class is instantiated",
"newdoc = \"%s\\n\\n%s\" % (newdoc, olddoc) return newdoc if hasattr(inspect,",
"lh = logging.FileHandler(fname, mode=mode) else: \"\"\" we should just be",
"**kwargs): warnings.warn(msg, category=DeprecationWarning) return init(*args, **kwargs) cls.__init__ = wrapped wrapped.__name__",
"= ['norm', 'pix', 'deg'] if units not in good_units: raise",
"called (like wait_for_presses). \"\"\" def send(): ec._response_handler._on_pyglet_keypress(button, [], True) Timer(delay,",
"secs: ec._dispatch_events() ec.check_force_quit() else: wins = _get_display().get_windows() for win in",
"None: warnings.warn('Log entries will be appended to the file. Use",
"to create new expyfun configuration ' 'file:\\n%s' % config_path) if",
"entries will be appended. \"\"\" handlers = logger.handlers for h",
"%s\\nfor a temporary solution, or:\\n' ' %s\\nfor a permanent one.",
"for k in known_config_wildcards): warnings.warn('Setting non-standard config type: \"%s\"' %",
"old: %s %s' % (vendor, version,))(func) def requires_lib(lib): \"\"\"Requires lib",
"raise_error is True and is_usable is False: raise ImportError('On Linux,",
"\"; %s\" % self.extra # FIXME: we should probably reset",
"of seconds. Parameters ---------- secs : float Number of seconds",
"expyfun._sound_controllers import _import_backend import pytest if isinstance(backend, dict): # actually",
"to ``subprocess.Popen``. Returns ------- stdout : str Stdout returned by",
"atexit import json from functools import partial from distutils.version import",
"\"%(asctime)s - %(levelname)s - %(message)s\". overwrite : bool, or None",
"user passed valid units type Parameters ---------- units : str",
"DECORATORS # Following deprecated class copied from scikit-learn class deprecated(object):",
"with the default value for extra, put in an empty",
"= '__init__' wrapped.__doc__ = self._update_doc(init.__doc__) wrapped.deprecated_original = init return cls",
"in logging_types: raise ValueError('verbose must be of a valid type')",
"verbose_level = default_level if verbose_level is not None: old_level =",
"\"\"\"Requires FFmpeg/AVbin decorator.\"\"\" import pytest return pytest.mark.skipif(not _has_video(), reason='Requires FFmpeg/AVbin')",
"will be tiled to be shape (2, n_samples). Otherwise, the",
"diffs : str A string representation of the differences. Notes",
"FFmpegSource # noqa except ImportError: return False else: try: from",
"environment variable EXPYFUN_LOGGING_LEVEL is read, and if it doesn't exist,",
"'NAME' is listed known_config_wildcards = () def get_config(key=None, default=None, raise_error=False):",
"uses some magic on stdout, we have to do this:",
"use set_log_level(). Parameters ---------- function : callable Function to be",
"file was downloaded. \"\"\" path = get_config('EXPYFUN_DATA_PATH', op.join(_get_user_home_path(), '.expyfun', 'data'))",
"and return keys of dict\"\"\" keys = list(x.keys()) # note:",
"\"\"\"Run command using subprocess.Popen Run command and wait for command",
"varargs, keywords, defaults if varargs: return out[:2] else: return out[0]",
"sys.version.startswith('2'): string_types = basestring # noqa input = raw_input #",
"return text_type(text_like).encode('unicode_escape').decode('utf-8') def _sort_keys(x): \"\"\"Sort and return keys of dict\"\"\"",
"+ 'd1[%s]' % repr(key)) elif isinstance(a, (list, tuple)): if len(a)",
"be one of {}, not {}' ''.format(good_units, units)) ############################################################################### #",
"overwrite is None: warnings.warn('Log entries will be appended to the",
"varargs=False): out = inspect.getargspec(function) # args, varargs, keywords, defaults if",
"terminal. Parameters ---------- command : list of str Command to",
"cls): msg = \"Class %s is deprecated\" % cls.__name__ if",
"is the same as False, but additionally raises a warning",
"clock from threading import Timer import numpy as np import",
"urlopen input = input from io import StringIO # noqa,",
"val # List the known configuration values known_config_types = ('RESPONSE_DEVICE',",
"uses threads to ensure that control is passed back, so",
"Linux64, and Win32 val = os.getenv('APPDATA' if 'nt' == os.name.lower()",
"subprocess.Popen(command, **kw) stdout_, stderr = p.communicate() output = (stdout_.decode(), stderr.decode())",
"run_subprocess(command, **kwargs): \"\"\"Run command using subprocess.Popen Run command and wait",
"params.get(k, get_config(k, defaults.get(k, None))) # Check keys for k in",
"0 and arg_names[0] == 'self': default_level = getattr(args[0], 'verbose', None)",
"x2 missing key %s\\n' % key else: out += object_diff(a[key],",
"to passing in logging.DEBUG, etc. For bool, True is the",
"def date_str(): \"\"\"Produce a date string for the current date",
"have one or two dimensions, got %s.' % (signal.ndim,)) #",
"at least Pyglet ' 'version 1.2, and you are running",
"= backend['SOUND_CARD_BACKEND'] try: _import_backend(backend) except Exception as exc: pytest.skip('Skipping test",
"INFO=logging.INFO, WARNING=logging.WARNING, ERROR=logging.ERROR, CRITICAL=logging.CRITICAL) if verbose not in logging_types: raise",
"with many changes. # scikit-learn will not import on all",
"if p.returncode: err_fun = subprocess.CalledProcessError.__init__ if 'output' in _get_args(err_fun): raise",
"ret else: ret = function(*args, **kwargs) return ret def _new_pyglet():",
"a is None, b is not (%s)\\n' % (b) elif",
".format(name, type(params))) params = deepcopy(params) if not isinstance(params, dict): raise",
"return new def __init__(self): self._path = self.__str__() atexit.register(self.cleanup) def cleanup(self):",
"'SOUND_CARD_API', 'SOUND_CARD_BACKEND', 'SOUND_CARD_FS', 'SOUND_CARD_NAME', 'SOUND_CARD_FIXED_DELAY', 'TDT_CIRCUIT_PATH', 'TDT_DELAY', 'TDT_INTERFACE', 'TDT_MODEL', 'TDT_TRIG_DELAY',",
"def send(): ec._mouse_handler._on_pyglet_mouse_click(pos[0], pos[1], button, []) Timer(delay, send).start() if delay",
"so a self-contained example is used above def __init__(self, extra=''):",
"bool, str, int, or None The verbosity of messages to",
"True is the same as 'INFO', False is the same",
"missing key %s\\n' % key else: out += object_diff(a[key], b[key],",
"than this class, this must be sys.stdout (not # just",
"# License: BSD (3-clause) import warnings import operator from copy",
"_wait_secs(secs, ec=None): \"\"\"Wait a specified number of seconds. Parameters ----------",
"> 0. else send() def fake_mouse_click(ec, pos, button='left', delay=0.): \"\"\"Fake",
"b: out += pre + ' value mismatch (%s, %s)\\n'",
"%s\" % self.extra # FIXME: we should probably reset __new__",
"in params.keys(): if k not in keys: raise KeyError('Unrecognized key",
"'INFO', False is the same as 'WARNING'. If None, the",
"we enforce that here if not isinstance(value, string_types) and value",
"in params.values() if param.kind == param.VAR_POSITIONAL] if len(varargs) == 0:",
"date and time Returns ------- datestr : str The date",
"deprecated >>> deprecated() # doctest: +ELLIPSIS <expyfun._utils.deprecated object at ...>",
"# List the known configuration values known_config_types = ('RESPONSE_DEVICE', 'AUDIO_CONTROLLER',",
"complete. If the return code was zero then return, otherwise",
"it back if we get an exception try: ret =",
"scikit-learn class deprecated(object): \"\"\"Decorator to mark a function or class",
"elif isinstance(a, dict): k1s = _sort_keys(a) k2s = _sort_keys(b) m1",
"the ' 'future.') mode = 'w' if overwrite is True",
"is deleted. \"\"\" if key is None: return sorted(known_config_types) if",
"logger.handlers: handler.flush() def set_log_level(verbose=None, return_old_level=False): \"\"\"Convenience function for setting the",
"commands can be called (like wait_for_presses). \"\"\" def send(): ec._response_handler._on_pyglet_keypress(button,",
"raise ValueError('key must be a string') # first, check to",
"def flush_logger(): \"\"\"Flush expyfun logger\"\"\" for handler in logger.handlers: handler.flush()",
"'.expyfun', 'data')) fname_out = op.join(path, fname) if not op.isdir(op.dirname(fname_out)): os.makedirs(op.dirname(fname_out))",
"out += pre + ' array mismatch\\n' else: raise RuntimeError(pre",
"pre='') elif isinstance(a, (string_types, int, float, bytes)): if a !=",
"return fname_out def get_config_path(): r\"\"\"Get path to standard expyfun config",
"_TempDir(str): \"\"\"Class for creating and auto-destroying temp dir This is",
"pytest try: importlib.import_module(lib) except Exception as exp: val = True",
"sqrt(convolve(signal ** 2, ones(win_length) / win_length, 'valid')) def _fix_audio_dims(signal, n_channels):",
"If the filename already exists on the local system, the",
"# LOGGING EXP = 25 logging.addLevelName(EXP, 'EXP') def exp(self, message,",
"k in keys]) keys = [keys[ii] for ii in idx]",
"None: verbose = get_config('EXPYFUN_LOGGING_LEVEL', 'INFO') elif isinstance(verbose, bool): verbose =",
"purposes. \"\"\" def __new__(self, del_after=True, print_del=False): new = str.__new__(self, tempfile.mkdtemp())",
"import pytest if isinstance(backend, dict): # actually an AC backend",
"signal must match n_channels. Returns ------- signal_fixed : array The",
"Use ' 'overwrite=False to avoid this message in the '",
"---------- signal : array_like The signal whose dimensions should be",
"to assign to the preference key. If None, the key",
"it \"takes\" try: import pyglet pyglet.options['debug_gl'] = False del pyglet",
"is not None: if op.isfile(fname) and overwrite is None: warnings.warn('Log",
"= VALUE' % key meth_2 = 'expyfun.utils.set_config(\"%s\", VALUE)' % key",
"del_after=True, print_del=False): new = str.__new__(self, tempfile.mkdtemp()) self._del_after = del_after self._print_del",
"been checked on OSX64, Linux64, and Win32 val = os.getenv('APPDATA'",
"if verbose not in logging_types: raise ValueError('verbose must be of",
"of {2}'.format(name, k, ', '.join(keys))) return params def _get_display(): import",
"to override config # settings using env, which are strings,",
"will not import on all platforms b/c it can be",
"line. Returns ------- diffs : str A string representation of",
"read, and if it doesn't exist, defaults to INFO. return_old_level",
">>> from expyfun._utils import deprecated >>> deprecated() # doctest: +ELLIPSIS",
"first, then the expyfun config file is parsed. default :",
"if not op.isdir(directory): os.mkdir(directory) with open(config_path, 'w') as fid: json.dump(config,",
"------- signal_fixed : array The signal with standard dimensions (n_channels,",
"'' if type(a) != type(b): out += pre + '",
"UTF-8 and sanitize any escape characters. \"\"\" return text_type(text_like).encode('unicode_escape').decode('utf-8') def",
"Exception: pass # for py3k (eventually) if sys.version.startswith('2'): string_types =",
"== param.VAR_POSITIONAL] if len(varargs) == 0: varargs = None return",
"input = raw_input # noqa, input is raw_input in py3k",
"'expyfun.json') return val # List the known configuration values known_config_types",
"from expyfun._utils import deprecated >>> deprecated() # doctest: +ELLIPSIS <expyfun._utils.deprecated",
"self._del_after is True: if self._print_del is True: print('Deleting {} ...'.format(self._path))",
"'w' if overwrite is True else 'a' lh = logging.FileHandler(fname,",
"log to print to. If None, stdout is used. To",
"method for cleanup here because the rmtree function may be",
"and you are running ' '{0}'.format(pyglet.version)) return is_usable def _wait_secs(secs,",
"designed to be used with testing modules. We cannot simply",
"(like wait_for_presses). \"\"\" def send(): ec._response_handler._on_pyglet_keypress(button, [], True) Timer(delay, send).start()",
"= inspect.getargspec(function) # args, varargs, keywords, defaults if varargs: return",
"verbose = logging_types[verbose] old_verbose = logger.level logger.setLevel(verbose) return (old_verbose if",
"op.isfile(config_path): with open(config_path, 'r') as fid: config = json.load(fid) else:",
"Pyglet ' 'version 1.2, and you are running ' '{0}'.format(pyglet.version))",
"defaults for values that are not passed for k in",
"% self.extra def wrapped(*args, **kwargs): warnings.warn(msg, category=DeprecationWarning) return fun(*args, **kwargs)",
"logger.setLevel(verbose) return (old_verbose if return_old_level else None) def set_log_file(fname=None, output_format='%(asctime)s",
"None: return config key_found = True if key in config",
"environment variable before ' 'running python.' % (key, config_path, meth_1,",
"If the input is mono and n_channels=2, it will be",
"+= \"; %s\" % self.extra # FIXME: we should probably",
"# for py3k (eventually) if sys.version.startswith('2'): string_types = basestring #",
"self.extra: msg += \"; %s\" % self.extra # FIXME: we",
"= clock() if ec is not None: while (clock() -",
"if self._del_after is True: if self._print_del is True: print('Deleting {}",
"r\"\"\"Get path to standard expyfun config file. Returns ------- config_path",
"tuple of the valid keys is returned, and ``value`` is",
"the verbosity level. Returns ------- dec - function The decorated",
"i[1]) if i[4] is not None else '') for i",
"raise_error=False): \"\"\"Read expyfun preference from env, then expyfun config Parameters",
"middle=2, right=4)[button] # trans to pyglet def send(): ec._mouse_handler._on_pyglet_mouse_click(pos[0], pos[1],",
"it will guarantee that events (keypresses, etc.) are processed. \"\"\"",
"to a file Parameters ---------- fname : str, or None",
"verbose.upper() logging_types = dict(DEBUG=logging.DEBUG, INFO=logging.INFO, WARNING=logging.WARNING, ERROR=logging.ERROR, CRITICAL=logging.CRITICAL) if verbose",
"np.asarray(np.atleast_2d(signal), dtype=np.float32) # Check dimensionality if signal.ndim != 2: raise",
"not None else '') for i in inspect.stack()) def run_subprocess(command,",
"of the rectangular window \"\"\" return sqrt(convolve(signal ** 2, ones(win_length)",
"pass to ``subprocess.Popen``. Returns ------- stdout : str Stdout returned",
"to the expyfun configuration file. On windows, this will be",
"Number of seconds to wait. ec : None | expyfun.ExperimentController",
"def send(): ec._response_handler._on_pyglet_keypress(button, [], True) Timer(delay, send).start() if delay >",
"or class as deprecated. Issue a warning when the function",
"a tuple of the valid keys is returned, and ``value``",
"partial from distutils.version import LooseVersion from numpy import sqrt, convolve,",
"proper certificates context = ssl._create_unverified_context() this_urlopen = partial(urlopen, context=context) except",
"numpy import sqrt, convolve, ones import logging import datetime from",
"%(levelname)s - %(message)s\". overwrite : bool, or None Overwrite the",
"'TDT_MODEL', 'TDT_TRIG_DELAY', 'TRIGGER_CONTROLLER', 'TRIGGER_ADDRESS', 'WINDOW_SIZE', 'SCREEN_NUM', 'SCREEN_WIDTH', 'SCREEN_DISTANCE', 'SCREEN_SIZE_PIX', 'EXPYFUN_LOGGING_LEVEL',",
"path could ' 'not be determined, please report this '",
"function(*args, **kwargs) return ret def _new_pyglet(): import pyglet return LooseVersion(pyglet.version)",
"newdoc = \"%s: %s\" % (newdoc, self.extra) if olddoc: newdoc",
"fixed. n_channels : int The number of channels that the",
"inspect import sys import tempfile import ssl from shutil import",
"The (1-dimesional) signal of interest. win_length : int Length (in",
"any(k in key for k in known_config_wildcards): warnings.warn('Setting non-standard config",
"Currently supported: dict, list, tuple, ndarray, int, str, bytes, float,",
"b, pre=''): \"\"\"Compute all differences between two python variables Parameters",
"if _new_pyglet(): try: from pyglet.media.codecs.ffmpeg import FFmpegSource # noqa except",
"fun): \"\"\"Decorate function fun\"\"\" msg = \"Function %s is deprecated\"",
"inspect.stack()) def run_subprocess(command, **kwargs): \"\"\"Run command using subprocess.Popen Run command",
"# noqa, analysis:ignore from importlib import reload # noqa, analysis:ignore",
"fname is not None: if op.isfile(fname) and overwrite is None:",
"'SOUND_CARD_NAME', 'SOUND_CARD_FIXED_DELAY', 'TDT_CIRCUIT_PATH', 'TDT_DELAY', 'TDT_INTERFACE', 'TDT_MODEL', 'TDT_TRIG_DELAY', 'TRIGGER_CONTROLLER', 'TRIGGER_ADDRESS', 'WINDOW_SIZE',",
"a delay Notes ----- This function only works with the",
"**kwargs) return ret def _new_pyglet(): import pyglet return LooseVersion(pyglet.version) >=",
"...'.format(self._path)) rmtree(self._path, ignore_errors=True) def check_units(units): \"\"\"Ensure user passed valid units",
"deprecated\" % cls.__name__ if self.extra: msg += \"; %s\" %",
"array The signal with standard dimensions (n_channels, N). \"\"\" #",
"match required ' 'channel count %d' % (signal.shape[0], n_channels)) return",
"i in inspect.stack()) def run_subprocess(command, **kwargs): \"\"\"Run command using subprocess.Popen",
"in zip(a, b): out += object_diff(xx1, xx2, pre='') elif isinstance(a,",
"None this_urlopen = urlopen if not op.isfile(fname_out): try: with open(fname_out,",
"old_verbose = logger.level logger.setLevel(verbose) return (old_verbose if return_old_level else None)",
"process. \"\"\" # code adapted with permission from mne-python kw",
"= self._update_doc(init.__doc__) wrapped.deprecated_original = init return cls def _decorate_fun(self, fun):",
"'EXPYFUN_LOGGING_LEVEL', ) # These allow for partial matches: 'NAME_1' is",
"default_level = None if('verbose' in arg_names): verbose_level = args[arg_names.index('verbose')] else:",
"pre + ' a is None, b is not (%s)\\n'",
"missing keys %s\\n' % (m1) for key in k1s: if",
"or ``'pix'``. \"\"\" good_units = ['norm', 'pix', 'deg'] if units",
"version,))(func) def requires_lib(lib): \"\"\"Requires lib decorator.\"\"\" import pytest try: importlib.import_module(lib)",
"with open(config_path, 'r') as fid: config = json.load(fid) else: config",
"category=DeprecationWarning) return init(*args, **kwargs) cls.__init__ = wrapped wrapped.__name__ = '__init__'",
"% (type(a), a)) return out def _check_skip_backend(backend): from expyfun._sound_controllers import",
"To suppress log outputs, use set_log_level('WARN'). output_format : str Format",
"''.format(fname)) try: # until we get proper certificates context =",
"from pyglet.media.avbin import AVbinSource # noqa except ImportError: try: from",
"finally: www.close() except Exception: os.remove(fname_out) raise return fname_out def get_config_path():",
"object at ...> >>> @deprecated() ... def some_function(): pass \"\"\"",
"is ignored. value : str | None The value to",
"exp logger = logging.getLogger('expyfun') def flush_logger(): \"\"\"Flush expyfun logger\"\"\" for",
"% self.extra # FIXME: we should probably reset __new__ for",
"\"\"\" import pyglet is_usable = LooseVersion(pyglet.version) >= LooseVersion('1.2') if raise_error",
"value): \"\"\"Set expyfun preference in config Parameters ---------- key :",
"statements will be appended to the log (default). None is",
"k in known_config_wildcards): warnings.warn('Setting non-standard config type: \"%s\"' % key)",
"the number of channels in signal must match n_channels. Returns",
"% repr(key)) elif isinstance(a, (list, tuple)): if len(a) != len(b):",
"\"\"\" if key is not None and not isinstance(key, string_types):",
"the input is mono and n_channels=2, it will be tiled",
"' 'file:\\n%s' % config_path) if value is None: config.pop(key, None)",
"subprocess.CalledProcessError(p.returncode, command) return output class ZeroClock(object): \"\"\"Clock that uses \"clock\"",
"that the output should have. If the input is mono",
"import operator from copy import deepcopy import subprocess import importlib",
"up before this object, so we use the atexit module",
"'TDT_INTERFACE', 'TDT_MODEL', 'TDT_TRIG_DELAY', 'TRIGGER_CONTROLLER', 'TRIGGER_ADDRESS', 'WINDOW_SIZE', 'SCREEN_NUM', 'SCREEN_WIDTH', 'SCREEN_DISTANCE', 'SCREEN_SIZE_PIX',",
"else 'a' lh = logging.FileHandler(fname, mode=mode) else: \"\"\" we should",
"in order for this to work (tested on OSX and",
"in params.items() if param.kind not in (param.VAR_POSITIONAL, param.VAR_KEYWORD)] if varargs:",
"None, the environment variable EXPYFUN_LOGGING_LEVEL is read, and if it",
"can be called (like wait_for_presses). \"\"\" def send(): ec._response_handler._on_pyglet_keypress(button, [],",
"if key is not None and key in os.environ: return",
"certificates context = ssl._create_unverified_context() this_urlopen = partial(urlopen, context=context) except AttributeError:",
"import partial from distutils.version import LooseVersion from numpy import sqrt,",
"op.isfile(fname) and overwrite is None: warnings.warn('Log entries will be appended",
"decorator.\"\"\" import pytest import pyglet.gl vendor = pyglet.gl.gl_info.get_vendor() version =",
"is listed known_config_wildcards = () def get_config(key=None, default=None, raise_error=False): \"\"\"Read",
"the stream handler logger.addHandler(lh) ############################################################################### # RANDOM UTILITIES building_doc =",
"overwrite is True else 'a' lh = logging.FileHandler(fname, mode=mode) else:",
"etc. For bool, True is the same as 'INFO', False",
"(param.VAR_POSITIONAL, param.VAR_KEYWORD)] if varargs: varargs = [param.name for param in",
"True: if self._print_del is True: print('Deleting {} ...'.format(self._path)) rmtree(self._path, ignore_errors=True)",
"fun.__name__ if self.extra: msg += \"; %s\" % self.extra def",
"from distutils.version import LooseVersion from numpy import sqrt, convolve, ones",
"env if key is not None and key in os.environ:",
"\"\"\"Decorator to mark a function or class as deprecated. Issue",
"% (signal.ndim,)) # Return data with correct dimensions if n_channels",
"key is not None and not isinstance(key, string_types): raise ValueError('key",
"ec._response_handler._on_pyglet_keypress(button, [], True) Timer(delay, send).start() if delay > 0. else",
"if isinstance(h, logging.FileHandler): h.close() logger.removeHandler(h) if fname is not None:",
"set_log_level(verbose=None, return_old_level=False): \"\"\"Convenience function for setting the logging level Parameters",
"keys = [keys[ii] for ii in idx] return keys def",
"is True else 'a' lh = logging.FileHandler(fname, mode=mode) else: \"\"\"",
"LOGGING EXP = 25 logging.addLevelName(EXP, 'EXP') def exp(self, message, *args,",
"None if('verbose' in arg_names): verbose_level = args[arg_names.index('verbose')] else: verbose_level =",
"out[:2] else: return out[0] @decorator def verbose_dec(function, *args, **kwargs): \"\"\"Improved",
"if signal.ndim != 2: raise ValueError('Sound data must have one",
"On windows, this will be '%APPDATA%\\.expyfun\\expyfun.json'. On every other system,",
"empty of parentheses: >>> from expyfun._utils import deprecated >>> deprecated()",
"__new__(self, del_after=True, print_del=False): new = str.__new__(self, tempfile.mkdtemp()) self._del_after = del_after",
"logger.level logger.setLevel(verbose) return (old_verbose if return_old_level else None) def set_log_file(fname=None,",
"be a dict, got type {1}' .format(name, type(params))) params =",
"'WINDOW_SIZE', 'SCREEN_NUM', 'SCREEN_WIDTH', 'SCREEN_DISTANCE', 'SCREEN_SIZE_PIX', 'EXPYFUN_LOGGING_LEVEL', ) # These allow",
"+ ' length mismatch (%s, %s)\\n' % (len(a), len(b)) else:",
"'TRIGGER_CONTROLLER', 'TRIGGER_ADDRESS', 'WINDOW_SIZE', 'SCREEN_NUM', 'SCREEN_WIDTH', 'SCREEN_DISTANCE', 'SCREEN_SIZE_PIX', 'EXPYFUN_LOGGING_LEVEL', ) #",
"this will be '%APPDATA%\\.expyfun\\expyfun.json'. On every other system, this will",
"global verbosrity level, instead use set_log_level(). Parameters ---------- function :",
"units not in good_units: raise ValueError('\"units\" must be one of",
"fname) if not op.isdir(op.dirname(fname_out)): os.makedirs(op.dirname(fname_out)) fname_url = ('https://github.com/LABSN/expyfun-data/raw/master/{0}' ''.format(fname)) try:",
"if not key_found and raise_error is True: meth_1 = 'os.environ[\"%s\"]",
"if fname is not None: if op.isfile(fname) and overwrite is",
"str Stderr returned by the process. \"\"\" # code adapted",
"logging level Parameters ---------- verbose : bool, str, int, or",
"% config_path) if value is None: config.pop(key, None) else: config[key]",
"return self._decorate_class(obj) else: return self._decorate_fun(obj) def _decorate_class(self, cls): msg =",
"the same as False, but additionally raises a warning to",
"cls.__init__ = wrapped wrapped.__name__ = '__init__' wrapped.__doc__ = self._update_doc(init.__doc__) wrapped.deprecated_original",
"valid keys is returned, and ``value`` is ignored. value :",
"# FIXME: we should probably reset __new__ for full generality",
"(signal.ndim,)) # Return data with correct dimensions if n_channels ==",
"length mismatch (%s, %s)\\n' % (len(a), len(b)) else: for xx1,",
"tuple, ndarray, int, str, bytes, float, StringIO, BytesIO. b :",
"**kw) stdout_, stderr = p.communicate() output = (stdout_.decode(), stderr.decode()) if",
"+= object_diff(a[key], b[key], pre + 'd1[%s]' % repr(key)) elif isinstance(a,",
"return_old_level=False): \"\"\"Convenience function for setting the logging level Parameters ----------",
"expyfun developers') return val def fetch_data_file(fname): \"\"\"Fetch example remote file",
"% key else: out += object_diff(a[key], b[key], pre + 'd1[%s]'",
"in the ' 'expyfun config file:\\n%s\\nTry either:\\n' ' %s\\nfor a",
"expyfun configuration ' 'file:\\n%s' % config_path) if value is None:",
"example is used above def __init__(self, extra=''): \"\"\" Parameters ----------",
"import pyglet try: display = pyglet.canvas.get_display() except AttributeError: # <",
"_get_args(function, varargs=False): params = inspect.signature(function).parameters args = [key for key,",
"category=DeprecationWarning) return fun(*args, **kwargs) wrapped.__name__ = fun.__name__ wrapped.__dict__ = fun.__dict__",
"types, we allow users to override config # settings using",
"def __call__(self, obj): \"\"\"Call.\"\"\" if isinstance(obj, type): return self._decorate_class(obj) else:",
"pyglet.media.sources.avbin import AVbinSource # noqa except ImportError: return False return",
"try: from pyglet.media.codecs.ffmpeg import FFmpegSource # noqa except ImportError: return",
"right=4)[button] # trans to pyglet def send(): ec._mouse_handler._on_pyglet_mouse_click(pos[0], pos[1], button,",
"raises a warning to notify the user that log entries",
"# Adapted from http://wiki.python.org/moin/PythonDecoratorLibrary, # but with many changes. #",
"exist, defaults to INFO. return_old_level : bool If True, return",
"stderr = p.communicate() output = (stdout_.decode(), stderr.decode()) if p.returncode: err_fun",
"int, float, bytes)): if a != b: out += pre",
"= json.load(fid) else: config = dict() logger.info('Attempting to create new",
"= \"%s: %s\" % (newdoc, self.extra) if olddoc: newdoc =",
"if not isinstance(key, string_types): raise ValueError('key must be a string')",
"while (clock() - t0) < secs: ec._dispatch_events() ec.check_force_quit() else: wins",
"ValueError('key must be a string') # first, check to see",
"Parameters ---------- units : str Must be ``'norm'``, ``'deg'``, or",
"\"\"\"Convenience function for setting the log to print to a",
"pre + ' type mismatch (%s, %s)\\n' % (type(a), type(b))",
"'WARNING' if isinstance(verbose, string_types): verbose = verbose.upper() logging_types = dict(DEBUG=logging.DEBUG,",
"Value to return if the key is not found. raise_error",
"as fid: config = json.load(fid) if key is None: return",
"It uses threads to ensure that control is passed back,",
"with standard dimensions (n_channels, N). \"\"\" # Check requested channel",
"kwargs to the constructor are helpful primarily for debugging purposes.",
"default else: with open(config_path, 'r') as fid: config = json.load(fid)",
"fid: config = json.load(fid) else: config = dict() logger.info('Attempting to",
"expyfun.ExperimentController instance The ExperimentController. Notes ----- This function uses a",
"(newdoc, self.extra) if olddoc: newdoc = \"%s\\n\\n%s\" % (newdoc, olddoc)",
"self._start_time def date_str(): \"\"\"Produce a date string for the current",
": str | None The preference key value. \"\"\" if",
"here because the rmtree function may be cleaned up before",
"differences. Notes ----- Taken from mne-python with permission. \"\"\" out",
"solution, or:\\n' ' %s\\nfor a permanent one. You can also",
"code adapted with permission from mne-python kw = dict(stderr=subprocess.PIPE, stdout=subprocess.PIPE)",
"on OSX64, Linux64, and Win32 val = os.getenv('APPDATA' if 'nt'",
"Authors: <NAME> <<EMAIL>> # # License: BSD (3-clause) import warnings",
"ret def _new_pyglet(): import pyglet return LooseVersion(pyglet.version) >= LooseVersion('1.4') def",
": object Must be same type as ``a``. pre :",
"import default_timer as clock from threading import Timer import numpy",
"ec is not None: while (clock() - t0) < secs:",
"sure it \"takes\" try: import pyglet pyglet.options['debug_gl'] = False del",
"old verbosity level. \"\"\" if verbose is None: verbose =",
"self-contained example is used above def __init__(self, extra=''): \"\"\" Parameters",
"import decorator # set this first thing to make sure",
"_check_pyglet_version(raise_error=False): \"\"\"Check pyglet version, return True if usable. \"\"\" import",
"', '.join(keys))) return params def _get_display(): import pyglet try: display",
"the environment variable EXPYFUN_LOGGING_LEVEL is read, and if it doesn't",
"to be added to the deprecation messages \"\"\" self.extra =",
"raw_input in py3k text_type = unicode # noqa from __builtin__",
"p.communicate() output = (stdout_.decode(), stderr.decode()) if p.returncode: err_fun = subprocess.CalledProcessError.__init__",
"0. else send() def _check_pyglet_version(raise_error=False): \"\"\"Check pyglet version, return True",
"mode=mode) else: \"\"\" we should just be able to do:",
"%s' % (vendor, version,))(func) def requires_lib(lib): \"\"\"Requires lib decorator.\"\"\" import",
"True else 'WARNING' if isinstance(verbose, string_types): verbose = verbose.upper() logging_types",
"str(datetime.datetime.today()).replace(':', '_') class WrapStdOut(object): \"\"\"Ridiculous class to work around how",
"set global verbosrity level, instead use set_log_level(). Parameters ---------- function",
"= get_config_path() if not op.isfile(config_path): key_found = False val =",
"array mismatch\\n' else: raise RuntimeError(pre + ': unsupported type %s",
"not isinstance(params, dict): raise TypeError('{0} must be a dict, got",
"----- This function uses a while loop. Although this slams",
"configuration file. On windows, this will be '%APPDATA%\\.expyfun\\expyfun.json'. On every",
"the rectangular window \"\"\" return sqrt(convolve(signal ** 2, ones(win_length) /",
"(eventually) if sys.version.startswith('2'): string_types = basestring # noqa input =",
"# Set sensible defaults for values that are not passed",
"\"\"\" # Adapted from http://wiki.python.org/moin/PythonDecoratorLibrary, # but with many changes.",
"expyfun config file is parsed. default : str | None",
"arg_names = _get_args(function) if len(arg_names) > 0 and arg_names[0] ==",
"if usable. \"\"\" import pyglet is_usable = LooseVersion(pyglet.version) >= LooseVersion('1.2')",
"or scikits.learn, so a self-contained example is used above def",
"for param in params.values() if param.kind == param.VAR_POSITIONAL] if len(varargs)",
"out += pre + ' x1 missing keys %s\\n' %",
"to notify the user that log entries will be appended.",
"DEBUG, INFO, WARNING, ERROR, or CRITICAL. Note that these are",
"wait. ec : None | expyfun.ExperimentController instance The ExperimentController. Notes",
"file Parameters ---------- fname : str, or None Filename of",
"raise an error if the key is not found (instead",
"' 'expyfun config file:\\n%s\\nTry either:\\n' ' %s\\nfor a temporary solution,",
"mismatch (%s, %s)\\n' % (a, b) elif a is None:",
"del_after and print_del kwargs to the constructor are helpful primarily",
"h in handlers: if isinstance(h, logging.FileHandler): h.close() logger.removeHandler(h) if fname",
"key, param in params.items() if param.kind not in (param.VAR_POSITIONAL, param.VAR_KEYWORD)]",
"'DB_OF_SINE_AT_1KHZ_1RMS', 'EXPYFUN_EYELINK', 'SOUND_CARD_API', 'SOUND_CARD_BACKEND', 'SOUND_CARD_FS', 'SOUND_CARD_NAME', 'SOUND_CARD_FIXED_DELAY', 'TDT_CIRCUIT_PATH', 'TDT_DELAY', 'TDT_INTERFACE',",
"('RESPONSE_DEVICE', 'AUDIO_CONTROLLER', 'DB_OF_SINE_AT_1KHZ_1RMS', 'EXPYFUN_EYELINK', 'SOUND_CARD_API', 'SOUND_CARD_BACKEND', 'SOUND_CARD_FS', 'SOUND_CARD_NAME', 'SOUND_CARD_FIXED_DELAY', 'TDT_CIRCUIT_PATH',",
"Check dimensionality if signal.ndim != 2: raise ValueError('Sound data must",
"set_log_level('WARN'). output_format : str Format of the output messages. See",
"a valid type') verbose = logging_types[verbose] old_verbose = logger.level logger.setLevel(verbose)",
"pyglet.gl.gl_info.get_vendor() version = pyglet.gl.gl_info.get_version() sufficient = pyglet.gl.gl_info.have_version(2, 0) return pytest.mark.skipif(not",
"def _check_skip_backend(backend): from expyfun._sound_controllers import _import_backend import pytest if isinstance(backend,",
"if verbose_level is not None: old_level = set_log_level(verbose_level, True) #",
"function for setting the logging level Parameters ---------- verbose :",
"= fun.__name__ wrapped.__dict__ = fun.__dict__ wrapped.__doc__ = self._update_doc(fun.__doc__) return wrapped",
"to pyglet def send(): ec._mouse_handler._on_pyglet_mouse_click(pos[0], pos[1], button, []) Timer(delay, send).start()",
"if isinstance(obj, type): return self._decorate_class(obj) else: return self._decorate_fun(obj) def _decorate_class(self,",
"Returns ------- dec - function The decorated function \"\"\" arg_names",
"= 25 logging.addLevelName(EXP, 'EXP') def exp(self, message, *args, **kwargs): \"\"\"Experiment-level",
"fname_url = ('https://github.com/LABSN/expyfun-data/raw/master/{0}' ''.format(fname)) try: # until we get proper",
"str | None The value to assign to the preference",
"elif isinstance(a, (list, tuple)): if len(a) != len(b): out +=",
"unsupported type %s (%s)' % (type(a), a)) return out def",
"(not # just stdout) in order for this to work",
"can also ' 'set the environment variable before ' 'running",
"config = dict() logger.info('Attempting to create new expyfun configuration '",
"% (newdoc, olddoc) return newdoc if hasattr(inspect, 'signature'): # py35",
"as fid: json.dump(config, fid, sort_keys=True, indent=0) ############################################################################### # MISC def",
"set_log_file(fname=None, output_format='%(asctime)s - %(levelname)-7s - %(message)s', overwrite=None): \"\"\"Convenience function for",
"exp: val = True reason = 'Needs %s (%s)' %",
"b/c it can be # sklearn or scikits.learn, so a",
"button, []) Timer(delay, send).start() if delay > 0. else send()",
"cls.__init__ def wrapped(*args, **kwargs): warnings.warn(msg, category=DeprecationWarning) return init(*args, **kwargs) cls.__init__",
"if n_channels == 2 and signal.shape[0] == 1: signal =",
"button='left', delay=0.): \"\"\"Fake a mouse click after a delay\"\"\" button",
"key not in k2s: out += pre + ' x2",
"scikit-learn will not import on all platforms b/c it can",
"samples) of the rectangular window \"\"\" return sqrt(convolve(signal ** 2,",
"appended. \"\"\" handlers = logger.handlers for h in handlers: if",
"open(config_path, 'r') as fid: config = json.load(fid) else: config =",
"and is_usable is False: raise ImportError('On Linux, you must run",
"._externals import decorator # set this first thing to make",
"function may be cleaned up before this object, so we",
"in keys: raise KeyError('Unrecognized key in {0}[\"{1}\"], must be '",
"is not found. raise_error : bool If True, raise an",
"raise return fname_out def get_config_path(): r\"\"\"Get path to standard expyfun",
"def _get_args(function, varargs=False): out = inspect.getargspec(function) # args, varargs, keywords,",
"def _sanitize(text_like): \"\"\"Cast as string, encode as UTF-8 and sanitize",
"key value. \"\"\" if key is not None and not",
"ERROR, or CRITICAL. Note that these are for convenience and",
"args, varargs else: return args else: def _get_args(function, varargs=False): out",
"True, return the old verbosity level. \"\"\" if verbose is",
"not found in environment or in the ' 'expyfun config",
"full generality init = cls.__init__ def wrapped(*args, **kwargs): warnings.warn(msg, category=DeprecationWarning)",
"% (m1) for key in k1s: if key not in",
"= self._update_doc(fun.__doc__) return wrapped def _update_doc(self, olddoc): newdoc = \"DEPRECATED\"",
"try: import pyglet pyglet.options['debug_gl'] = False del pyglet except Exception:",
"int, or None The verbosity of messages to print. If",
"one or two dimensions, got %s.' % (signal.ndim,)) # Return",
"raise_error : bool If True, raise an error if the",
"config file:\\n%s\\nTry either:\\n' ' %s\\nfor a temporary solution, or:\\n' '",
"to work around how doctest captures stdout.\"\"\" def __getattr__(self, name):",
"is in env if key is not None and key",
"from pyglet.media.codecs.ffmpeg import FFmpegSource # noqa except ImportError: return False",
"must be of a valid type') verbose = logging_types[verbose] old_verbose",
"sys.stdout (not # just stdout) in order for this to",
"import pyglet return LooseVersion(pyglet.version) >= LooseVersion('1.4') def _has_video(): if _new_pyglet():",
"import StringIO # noqa else: string_types = str text_type =",
"added to the deprecation messages \"\"\" self.extra = extra def",
"---------- fname : str, or None Filename of the log",
"after a delay\"\"\" button = dict(left=1, middle=2, right=4)[button] # trans",
"count %d did not match required ' 'channel count %d'",
"# These allow for partial matches: 'NAME_1' is okay key",
"For bool, True is the same as 'INFO', False is",
"call this directly to set global verbosrity level, instead use",
"== 'self': default_level = getattr(args[0], 'verbose', None) else: default_level =",
": str The filename on the local system where the",
"allow for partial matches: 'NAME_1' is okay key if 'NAME'",
"---------- key : str The preference key to look for.",
"' type mismatch (%s, %s)\\n' % (type(a), type(b)) elif isinstance(a,",
"not None: out += pre + ' a is None,",
"data with correct dimensions if n_channels == 2 and signal.shape[0]",
"have. If the input is mono and n_channels=2, it will",
"= params.get(k, get_config(k, defaults.get(k, None))) # Check keys for k",
"LooseVersion(pyglet.version) >= LooseVersion('1.2') if raise_error is True and is_usable is",
"KeyError('Key \"%s\" not found in environment or in the '",
"if 'nt' == os.name.lower() else 'HOME', None) if val is",
"The signal whose dimensions should be checked and fixed. n_channels",
"= \"Function %s is deprecated\" % fun.__name__ if self.extra: msg",
"warnings.warn(msg, category=DeprecationWarning) return fun(*args, **kwargs) wrapped.__name__ = fun.__name__ wrapped.__dict__ =",
"default, this will also add stdout= and stderr=subproces.PIPE to the",
"docstring. Note: to use this with the default value for",
"val = default else: with open(config_path, 'r') as fid: config",
"True: meth_1 = 'os.environ[\"%s\"] = VALUE' % key meth_2 =",
"'version 1.2, and you are running ' '{0}'.format(pyglet.version)) return is_usable",
"if self._print_del is True: print('Deleting {} ...'.format(self._path)) rmtree(self._path, ignore_errors=True) def",
"return (LooseVersion(sp.__version__) >= LooseVersion(version)) def _get_user_home_path(): \"\"\"Return standard preferences path\"\"\"",
"preference key. If None, the key is deleted. \"\"\" if",
"and not \\ any(k in key for k in known_config_wildcards):",
"float Number of seconds to wait. ec : None |",
"list, tuple, ndarray, int, str, bytes, float, StringIO, BytesIO. b",
"import rmtree import atexit import json from functools import partial",
"to mark a function or class as deprecated. Issue a",
"raise ValueError('value must be a string or None') if key",
"so we enforce that here if not isinstance(value, string_types) and",
"set it back if we get an exception try: ret",
"with open(config_path, 'w') as fid: json.dump(config, fid, sort_keys=True, indent=0) ###############################################################################",
"verbosity of messages to print. If a str, it can",
"return val # List the known configuration values known_config_types =",
"deprecated\" % fun.__name__ if self.extra: msg += \"; %s\" %",
"raise ValueError('\"units\" must be one of {}, not {}' ''.format(good_units,",
"%s\" % (newdoc, self.extra) if olddoc: newdoc = \"%s\\n\\n%s\" %",
"None: if b is not None: out += pre +",
"try: _import_backend(backend) except Exception as exc: pytest.skip('Skipping test for backend",
"default_timer as clock from threading import Timer import numpy as",
"= dict(stderr=subprocess.PIPE, stdout=subprocess.PIPE) kw.update(kwargs) p = subprocess.Popen(command, **kw) stdout_, stderr",
"WrapStdOut(object): \"\"\"Ridiculous class to work around how doctest captures stdout.\"\"\"",
"String to prepend to each line. Returns ------- diffs :",
"- function The decorated function \"\"\" arg_names = _get_args(function) if",
"send).start() if delay > 0. else send() def _check_pyglet_version(raise_error=False): \"\"\"Check",
"all previous values config_path = get_config_path() if op.isfile(config_path): with open(config_path,",
"% (b) elif isinstance(a, np.ndarray): if not np.array_equal(a, b): out",
"signal.ndim != 2: raise ValueError('Sound data must have one or",
"key %s\\n' % key else: out += object_diff(a[key], b[key], pre",
"function The decorated function \"\"\" arg_names = _get_args(function) if len(arg_names)",
"% key) # Read all previous values config_path = get_config_path()",
"fid: config = json.load(fid) if key is None: return config",
"__new__ for full generality init = cls.__init__ def wrapped(*args, **kwargs):",
"'channel count %d' % (signal.shape[0], n_channels)) return signal def _sanitize(text_like):",
"import AVbinSource # noqa except ImportError: return False return True",
"\"\"\" out = '' if type(a) != type(b): out +=",
": str The remote filename to get. If the filename",
"in known_config_wildcards): warnings.warn('Setting non-standard config type: \"%s\"' % key) #",
"time.\"\"\" return clock() - self._start_time def date_str(): \"\"\"Produce a date",
"be tiled to be shape (2, n_samples). Otherwise, the number",
"# # License: BSD (3-clause) import warnings import operator from",
"except Exception as exp: val = True reason = 'Needs",
"system, the file will not be fetched again. Returns -------",
"be appended to the file. Use ' 'overwrite=False to avoid",
"stderr.decode()) if p.returncode: err_fun = subprocess.CalledProcessError.__init__ if 'output' in _get_args(err_fun):",
"return out[:2] else: return out[0] @decorator def verbose_dec(function, *args, **kwargs):",
"signal : array_like The (1-dimesional) signal of interest. win_length :",
"reason='OpenGL too old: %s %s' % (vendor, version,))(func) def requires_lib(lib):",
"Run command and wait for command to complete. If the",
"http://wiki.python.org/moin/PythonDecoratorLibrary, # but with many changes. # scikit-learn will not",
"(%s)\\n' % (b) elif isinstance(a, np.ndarray): if not np.array_equal(a, b):",
"return output class ZeroClock(object): \"\"\"Clock that uses \"clock\" function but",
"%d did not match required ' 'channel count %d' %",
"if i[4] is not None else '') for i in",
"expyfun config Parameters ---------- key : str The preference key",
"where the file was downloaded. \"\"\" path = get_config('EXPYFUN_DATA_PATH', op.join(_get_user_home_path(),",
"logger.removeHandler(h) if fname is not None: if op.isfile(fname) and overwrite",
"if 'output' in _get_args(err_fun): raise subprocess.CalledProcessError(p.returncode, command, output) else: raise",
"' 'running python.' % (key, config_path, meth_1, meth_2)) return val",
"= cls.__init__ def wrapped(*args, **kwargs): warnings.warn(msg, category=DeprecationWarning) return init(*args, **kwargs)",
"name): if not isinstance(params, dict): raise TypeError('{0} must be a",
"suppress log outputs, use set_log_level('WARN'). output_format : str Format of",
"to print to a file Parameters ---------- fname : str,",
"= \"DEPRECATED\" if self.extra: newdoc = \"%s: %s\" % (newdoc,",
"preference in config Parameters ---------- key : str | None",
"button='1', delay=0.): \"\"\"Fake a button press after a delay Notes",
"type') verbose = logging_types[verbose] old_verbose = logger.level logger.setLevel(verbose) return (old_verbose",
"secs : float Number of seconds to wait. ec :",
"= [param.name for param in params.values() if param.kind == param.VAR_POSITIONAL]",
"else '') for i in inspect.stack()) def run_subprocess(command, **kwargs): \"\"\"Run",
"False: raise ImportError('On Linux, you must run at least Pyglet",
"is not (%s)\\n' % (b) elif isinstance(a, np.ndarray): if not",
"then return, otherwise raise CalledProcessError. By default, this will also",
"will be appended to the deprecation message and the docstring.",
"(in samples) of the rectangular window \"\"\" return sqrt(convolve(signal **",
"\"\"\"Fake a button press after a delay Notes ----- This",
"import subprocess import importlib import os import os.path as op",
"the key is not found (instead of returning default). Returns",
"not isinstance(value, string_types) and value is not None: raise ValueError('value",
"stream handler logger.addHandler(lh) ############################################################################### # RANDOM UTILITIES building_doc = any('sphinx-build'",
"except ImportError: return False else: try: from pyglet.media.avbin import AVbinSource",
"this must be sys.stdout (not # just stdout) in order",
"self.extra: newdoc = \"%s: %s\" % (newdoc, self.extra) if olddoc:",
"as string, encode as UTF-8 and sanitize any escape characters.",
"data must have one or two dimensions, got %s.' %",
"string, encode as UTF-8 and sanitize any escape characters. \"\"\"",
"function or class as deprecated. Issue a warning when the",
"module instead. Passing del_after and print_del kwargs to the constructor",
"= \"%s\\n\\n%s\" % (newdoc, olddoc) return newdoc if hasattr(inspect, 'signature'):",
"ssl from shutil import rmtree import atexit import json from",
"return os.environ[key] # second, look for it in expyfun config",
"as fid: www = this_urlopen(fname_url, timeout=30.0) try: fid.write(www.read()) finally: www.close()",
"and are equivalent to passing in logging.DEBUG, etc. For bool,",
"passing in logging.DEBUG, etc. For bool, True is the same",
"'INFO' if verbose is True else 'WARNING' if isinstance(verbose, string_types):",
"_get_user_home_path(): \"\"\"Return standard preferences path\"\"\" # this has been checked",
"www.close() except Exception: os.remove(fname_out) raise return fname_out def get_config_path(): r\"\"\"Get",
"return (old_verbose if return_old_level else None) def set_log_file(fname=None, output_format='%(asctime)s -",
"(newdoc, olddoc) return newdoc if hasattr(inspect, 'signature'): # py35 def",
"to wait. ec : None | expyfun.ExperimentController instance The ExperimentController.",
"otherwise raise CalledProcessError. By default, this will also add stdout=",
"msg = \"Class %s is deprecated\" % cls.__name__ if self.extra:",
"default_level if verbose_level is not None: old_level = set_log_level(verbose_level, True)",
"to. If None, stdout is used. To suppress log outputs,",
"temp dir This is designed to be used with testing",
"init return cls def _decorate_fun(self, fun): \"\"\"Decorate function fun\"\"\" msg",
"def fake_mouse_click(ec, pos, button='left', delay=0.): \"\"\"Fake a mouse click after",
"number of channels in signal must match n_channels. Returns -------",
"try: fid.write(www.read()) finally: www.close() except Exception: os.remove(fname_out) raise return fname_out",
"# hog the cpu, checking time t0 = clock() if",
"False return True def requires_video(): \"\"\"Requires FFmpeg/AVbin decorator.\"\"\" import pytest",
"# code adapted with permission from mne-python kw = dict(stderr=subprocess.PIPE,",
"button press after a delay Notes ----- This function only",
"rmtree function may be cleaned up before this object, so",
"else send() def _check_pyglet_version(raise_error=False): \"\"\"Check pyglet version, return True if",
"decorator to allow functions to override log-level Do not call",
"are equivalent to passing in logging.DEBUG, etc. For bool, True",
"not None: raise ValueError('value must be a string or None')",
"stderr=subproces.PIPE to the call to Popen to suppress printing to",
"[keys[ii] for ii in idx] return keys def object_diff(a, b,",
"all differences between two python variables Parameters ---------- a :",
"to make sure it \"takes\" try: import pyglet pyglet.options['debug_gl'] =",
"'running python.' % (key, config_path, meth_1, meth_2)) return val def",
"raise ValueError('verbose must be of a valid type') verbose =",
"**kwargs) wrapped.__name__ = fun.__name__ wrapped.__dict__ = fun.__dict__ wrapped.__doc__ = self._update_doc(fun.__doc__)",
"out def _check_skip_backend(backend): from expyfun._sound_controllers import _import_backend import pytest if",
"known_config_types and not \\ any(k in key for k in",
"should be checked and fixed. n_channels : int The number",
"m1 = set(k2s) - set(k1s) if len(m1): out += pre",
"config.get(key, default) if not key_found and raise_error is True: meth_1",
"self.extra = extra def __call__(self, obj): \"\"\"Call.\"\"\" if isinstance(obj, type):",
"starts at zero on init.\"\"\" def __init__(self): self._start_time = clock()",
"to set. If None, a tuple of the valid keys",
"unicode # noqa from __builtin__ import reload from urllib2 import",
"isinstance(key, string_types): raise ValueError('key must be a string') # While",
"= np.asarray(np.atleast_2d(signal), dtype=np.float32) # Check dimensionality if signal.ndim != 2:",
"= self.__str__() atexit.register(self.cleanup) def cleanup(self): if self._del_after is True: if",
"functools import partial from distutils.version import LooseVersion from numpy import",
"= None return args, varargs else: return args else: def",
": list of str Command to run as subprocess (see",
"False is the same as 'WARNING'. If None, the environment",
"allow functions to override log-level Do not call this directly",
"bool, or None Overwrite the log file (if it exists).",
"this has been checked on OSX64, Linux64, and Win32 val",
"fid: www = this_urlopen(fname_url, timeout=30.0) try: fid.write(www.read()) finally: www.close() except",
"self._update_doc(init.__doc__) wrapped.deprecated_original = init return cls def _decorate_fun(self, fun): \"\"\"Decorate",
"is None: return config key_found = True if key in",
"for command to complete. If the return code was zero",
"this_urlopen(fname_url, timeout=30.0) try: fid.write(www.read()) finally: www.close() except Exception: os.remove(fname_out) raise",
"The preference key to set. If None, a tuple of",
"%s)\\n' % (type(a), type(b)) elif isinstance(a, dict): k1s = _sort_keys(a)",
"delay=0.): \"\"\"Fake a mouse click after a delay\"\"\" button =",
"set_config(key, value): \"\"\"Set expyfun preference in config Parameters ---------- key",
"is not None and not isinstance(key, string_types): raise ValueError('key must",
"'_') class WrapStdOut(object): \"\"\"Ridiculous class to work around how doctest",
"the call to Popen to suppress printing to the terminal.",
"\"\"\"Ensure user passed valid units type Parameters ---------- units :",
"use the atexit module instead. Passing del_after and print_del kwargs",
"defaults to INFO. return_old_level : bool If True, return the",
"= config.get(key, default) if not key_found and raise_error is True:",
"%s is deprecated\" % fun.__name__ if self.extra: msg += \";",
"dict): # actually an AC backend = backend['SOUND_CARD_BACKEND'] try: _import_backend(backend)",
"to suppress printing to the terminal. Parameters ---------- command :",
"ii in idx] return keys def object_diff(a, b, pre=''): \"\"\"Compute",
"a warning to notify the user that log entries will",
"val = config.get(key, default) if not key_found and raise_error is",
"not in known_config_types and not \\ any(k in key for",
"keys]) keys = [keys[ii] for ii in idx] return keys",
"self.extra def wrapped(*args, **kwargs): warnings.warn(msg, category=DeprecationWarning) return fun(*args, **kwargs) wrapped.__name__",
"string representation of the differences. Notes ----- Taken from mne-python",
"not None and not isinstance(key, string_types): raise ValueError('key must be",
"remote filename to get. If the filename already exists on",
"- %(levelname)-7s - %(message)s', overwrite=None): \"\"\"Convenience function for setting the",
"############################################################################### # LOGGING EXP = 25 logging.addLevelName(EXP, 'EXP') def exp(self,",
"this slams the CPU, it will guarantee that events (keypresses,",
"# scikit-learn will not import on all platforms b/c it",
"The preference key value. \"\"\" if key is not None",
"str from urllib.request import urlopen input = input from io",
"(%s)' % (type(a), a)) return out def _check_skip_backend(backend): from expyfun._sound_controllers",
"as UTF-8 and sanitize any escape characters. \"\"\" return text_type(text_like).encode('unicode_escape').decode('utf-8')"
] |
[
"signal.signal(signal.SIGTERM, self._signal_handler) signal.signal(signal.SIGINT, self._signal_handler) def _signal_handler(self, sign, frame): self.interrupt =",
"self._signal_handler) signal.signal(signal.SIGINT, self._signal_handler) def _signal_handler(self, sign, frame): self.interrupt = True",
"__init__(self): self.interrupt = False signal.signal(signal.SIGTERM, self._signal_handler) signal.signal(signal.SIGINT, self._signal_handler) def _signal_handler(self,",
"= False signal.signal(signal.SIGTERM, self._signal_handler) signal.signal(signal.SIGINT, self._signal_handler) def _signal_handler(self, sign, frame):",
"import signal class KillableProcess(object): def __init__(self): self.interrupt = False signal.signal(signal.SIGTERM,",
"False signal.signal(signal.SIGTERM, self._signal_handler) signal.signal(signal.SIGINT, self._signal_handler) def _signal_handler(self, sign, frame): self.interrupt",
"signal class KillableProcess(object): def __init__(self): self.interrupt = False signal.signal(signal.SIGTERM, self._signal_handler)",
"self.interrupt = False signal.signal(signal.SIGTERM, self._signal_handler) signal.signal(signal.SIGINT, self._signal_handler) def _signal_handler(self, sign,",
"class KillableProcess(object): def __init__(self): self.interrupt = False signal.signal(signal.SIGTERM, self._signal_handler) signal.signal(signal.SIGINT,",
"KillableProcess(object): def __init__(self): self.interrupt = False signal.signal(signal.SIGTERM, self._signal_handler) signal.signal(signal.SIGINT, self._signal_handler)",
"def __init__(self): self.interrupt = False signal.signal(signal.SIGTERM, self._signal_handler) signal.signal(signal.SIGINT, self._signal_handler) def"
] |
[] |
[
"off of the class, rather than the instance class CodeOnlyModule(torch.nn.Module):",
"dict's keys. The object mapped to by the Dict will",
"target = root.linear.weight, but we have already installed root.linear) #",
"_assign_attr(root[target_to_copy], self, target_to_copy) else: raise RuntimeError('Unsupported type ' + str(root)",
"object def __deepcopy__(self, memo): fake_mod = torch.nn.Module() fake_mod.__dict__ = copy.deepcopy(self.__dict__)",
"gbls['forward'] def deserialize_graphmodule(body : dict) -> torch.nn.Module: \"\"\" Deserialize a",
"t is None: t = torch.nn.Module() setattr(to_module, item, t) to_module",
"code, however we can patch # the linecache module to",
"= t setattr(to_module, field, from_obj) class GraphModule(torch.nn.Module): \"\"\" GraphModule is",
"'from_module' to 'to_module' # This installs empty Modules where none",
"'to_module # This installs empty Modules where none exist yet",
"# it is a subclass of the user-defined class, the",
"not get serialized. \"\"\" # We create a dummy class",
"code for the function generated from `graph` forward : The",
"None: t = torch.nn.Module() setattr(to_module, item, t) from_module, to_module =",
"= '\\n'.join(' ' + line for line in body.split('\\n')) +",
"patched_cat.__module__ = 'torch' # patched_cat.__name__ = 'cat' # torch.cat =",
"be automatically regenerated. \"\"\" def __new__(cls: 'Type[GraphModule]', *args, **kwargs): #",
"qualified name) in the Graph's Nodes' `target` field will be",
"The graph from which this GraphModule was generated code :",
"# we need to define deepcopy otherwise it will call",
"__str__(self) -> str: orig_str = super().__str__() return '\\n'.join([orig_str, self.code]) #",
"in the Graph's Nodes' `target` field will be copied over",
"to_module = f, t setattr(to_module, field, getattr(from_module, field)) # Assign",
"symbolic_trace pulls the forward() # function off of the class,",
"- `root` can either be an nn.Module instance or a",
"try to copy the object def __deepcopy__(self, memo): fake_mod =",
"+ ' referenced target ' + node.target + ' but",
"properties will already be present return if t is None:",
"so that any code we exec using exec_with_source # works",
"target.split('.') for item in prefix: t = getattr(to_module, item, None)",
"before saving the dictionary so that changes to the in-memory",
"__: str) -> bool: return True return KeepModules().trace(CodeOnlyModule(body)) # copy",
"`forward` will be automatically regenerated. \"\"\" def __new__(cls: 'Type[GraphModule]', *args,",
"'\\n'.join(' ' + line for line in body.split('\\n')) + '\\n'",
"an nn.Module generated from an fx.Graph. GraphModule has important attributes:",
"**kwargs): if args[0] in _eval_cache: return _eval_cache[args[0]] return _orig_getlines(*args, **kwargs)",
"copy an attribute value with qualified name 'target' from 'from_module'",
"the linecache module to still recover it. # using exec_with_source",
"is defined for serialization, # we need to define deepcopy",
"the original GraphModule class KeepModules(Tracer): def is_leaf_module(self, _: torch.nn.Module, __:",
"important attributes: graph : The graph from which this GraphModule",
"# copy an attribute value with qualified name 'target' from",
"for t in tensors: # if isinstance(t, Proxy): # return",
"is an nn.Module generated from an fx.Graph. GraphModule has important",
"gbls: Dict[str, Any] = { 'torch': torch } exec_with_source(src, gbls)",
"def __reduce__(self): dict_without_graph = self.__dict__.copy() del dict_without_graph['_graph'] return (deserialize_graphmodule, (dict_without_graph,))",
"root: Union[torch.nn.Module, Dict[str, Any]], graph: Graph): \"\"\" Construct a GraphModule.",
"a dummy class here because symbolic_trace pulls the forward() #",
"hasattr(root, 'training'): self.training = root.training for node in graph.nodes: if",
"# of atoms. # This will ensure that less deeply",
"= self._graph.python_code(root_module='self') body = '\\n'.join(' ' + line for line",
"= body CodeOnlyModule.forward = _forward_from_src(body['code']) from .symbolic_trace import Tracer #",
"one of its parents # (e.g. target = root.linear.weight, but",
"from_module, to_module = f, t setattr(to_module, field, getattr(from_module, field)) #",
"# works with inspect _eval_cache : Dict[str, List[str]] = {}",
"case that `root` is a dict, the qualified name found",
"https://github.com/pytorch/pytorch/issues/44842 # # Shouldn't be an issue since these methods",
"tracing to occur every time we try to copy the",
"tensors: # if isinstance(t, Proxy): # return t.__torch_function__(patched_cat, (), args,",
"cls.forward = _forward_from_src(self.code) def __reduce__(self): dict_without_graph = self.__dict__.copy() del dict_without_graph['_graph']",
"getattr(to_module, item, None) if f is t: # we have",
"is an extra layer to install the forward method class",
"# This will ensure that less deeply nested attributes are",
"key = f'<eval_with_key_{_next_id}>' _next_id += 1 _eval_cache[key] = [line +",
"GraphModuleImpl(cls): # type: ignore pass return super().__new__(GraphModuleImpl) def __init__(self, root:",
"self.graph) def __copy__(self): return GraphModule(self, self.graph) def __str__(self) -> str:",
"for issues in __torch_function__ # WAR for __torch_function__ not handling",
"from `graph` Note that when `graph` is reassigned, `code` and",
"by the Dict will be copied over into the appropriate",
"*args, **kwargs): # each instance of a graph module needs",
"loses the source code, however we can patch # the",
"return self._graph @graph.setter def graph(self, val) -> None: self._graph =",
"target_to_copy in targets_to_copy: _assign_attr(root[target_to_copy], self, target_to_copy) else: raise RuntimeError('Unsupported type",
"contains the nodes this GraphModule should use for code generation",
"_next_id += 1 _eval_cache[key] = [line + '\\n' for line",
"and wipe out the previously-assigned # `foo.bar.baz` targets_to_copy.sort(key=lambda t: t.count('.'))",
"for serialization, # we need to define deepcopy otherwise it",
"'call_module']: assert isinstance(node.target, str) _copy_attr(root, self, node.target) elif isinstance(root, dict):",
"root.linear) # once we install a parent, we no longer",
"for line in src.splitlines()] exec(compile(src, key, 'exec'), globals) # patch",
"attributes: graph : The graph from which this GraphModule was",
"be an nn.Module instance or a Dict mapping strings to",
"into the appropriate place within the GraphModule's module hierarchy. graph",
"val body, result, free_variables = self._graph.python_code(root_module='self') body = '\\n'.join(' '",
"passed for root!') self.graph = graph # TorchScript breaks trying",
"module to still recover it. # using exec_with_source will add",
"+ '\\n' self.code = f\"\"\"\\ def forward(self, {', '.join(free_variables)}): {body}",
"of the class, rather than the instance class CodeOnlyModule(torch.nn.Module): def",
": The graph from which this GraphModule was generated code",
"name 'target' from 'from_module' to 'to_module' # This installs empty",
"# This installs empty Modules where none exist yet if",
"globals) # patch linecache so that any code we exec",
"it to our local cache # and then tools like",
"automatically regenerated. \"\"\" def __new__(cls: 'Type[GraphModule]', *args, **kwargs): # each",
"be assigned before foo.bar.baz. Otherwise, we might assign # the",
"self.training = root.training for node in graph.nodes: if node.op in",
"In the case that `root` is a Module, any references",
"torch.nn.Module, to_module: torch.nn.Module, target: str): *prefix, field = target.split('.') for",
"name) in the Graph's Nodes' `target` field will be copied",
"longer need to copy the children # since all the",
"graph(self, val) -> None: self._graph = val body, result, free_variables",
"references to Module-based objects (via qualified name) in the Graph's",
"workarounds for issues in __torch_function__ # WAR for __torch_function__ not",
"keys. The object mapped to by the Dict will be",
"TorchScript breaks trying to compile the graph setter because of",
"t: t.count('.')) for target_to_copy in targets_to_copy: _assign_attr(root[target_to_copy], self, target_to_copy) else:",
"# the linecache module to still recover it. # using",
"the nodes this GraphModule should use for code generation \"\"\"",
"def __new__(cls: 'Type[GraphModule]', *args, **kwargs): # each instance of a",
"'torch': torch } exec_with_source(src, gbls) return gbls['forward'] def deserialize_graphmodule(body :",
"breaks trying to compile the graph setter because of the",
"qualified name found in a Node's `target` will be looked",
"in src.splitlines()] exec(compile(src, key, 'exec'), globals) # patch linecache so",
"we have already installed root.linear) # once we install a",
"exec using exec_with_source # works with inspect _eval_cache : Dict[str,",
"# Sort targets in ascending order of the # of",
"*prefix, field = target.split('.') for item in prefix: t =",
"from .graph import Graph import copy # normal exec loses",
"fix is in https://github.com/pytorch/pytorch/pull/34725 # orig_cat = torch.cat # def",
"return True return KeepModules().trace(CodeOnlyModule(body)) # copy an attribute value with",
"`code` and `forward` will be automatically regenerated. \"\"\" def __new__(cls:",
"issue since these methods shouldn't be used in TorchScript anyway",
"Any, Union from .graph import Graph import copy # normal",
"self.__dict__ = body CodeOnlyModule.forward = _forward_from_src(body['code']) from .symbolic_trace import Tracer",
"qualified name 'target' from 'from_module' to 'to_module' # This installs",
"in `root`!') targets_to_copy.append(node.target) # Sort targets in ascending order of",
"t.__torch_function__(patched_cat, (), args, kwargs) # return orig_cat(*args, **kwargs) # patched_cat.__module__",
"def _assign_attr(from_obj: Any, to_module: torch.nn.Module, target: str): *prefix, field =",
"linecache so that any code we exec using exec_with_source #",
": dict) -> torch.nn.Module: \"\"\" Deserialize a GraphModule given the",
"graph before saving the dictionary so that changes to the",
"so create a new singleton class for each instance. #",
"string literal. Issue here: https://github.com/pytorch/pytorch/issues/44842 # # Shouldn't be an",
"foo.bar.baz. Otherwise, we might assign # the user-provided `foo.bar` and",
"to_module: torch.nn.Module, target: str): *prefix, field = target.split('.') for item",
"t) to_module = t setattr(to_module, field, from_obj) class GraphModule(torch.nn.Module): \"\"\"",
"`foo.bar.baz` targets_to_copy.sort(key=lambda t: t.count('.')) for target_to_copy in targets_to_copy: _assign_attr(root[target_to_copy], self,",
"in prefix: f = getattr(from_module, item) t = getattr(to_module, item,",
"we have already installed one of its parents # (e.g.",
"GraphModule. root - `root` can either be an nn.Module instance",
"only difference # is an extra layer to install the",
"exec_with_source(src, gbls) return gbls['forward'] def deserialize_graphmodule(body : dict) -> torch.nn.Module:",
"`target` field will be copied over from the respective place",
"def patched_getline(*args, **kwargs): if args[0] in _eval_cache: return _eval_cache[args[0]] return",
"an attribute value with qualified name 'target' from 'from_module' to",
"a GraphModule given the dictionary of the original module, using",
"linecache.getlines = patched_getline def _forward_from_src(src : str): gbls: Dict[str, Any]",
"str(node) + ' referenced target ' + node.target + '",
"already installed one of its parents # (e.g. target =",
"graph module needs its own forward method # so create",
"name 'target' on 'to_module # This installs empty Modules where",
"= ['graph'] @property def graph(self): return self._graph @graph.setter def graph(self,",
"__torch_function__ # WAR for __torch_function__ not handling tensor lists, #",
"`root`'s Module hierarchy into the GraphModule's module hierarchy. - In",
"`graph` forward : The Python method generated from `graph` Note",
"trying to compile the graph setter because of the #",
"before more deeply nested attributes. For example, foo.bar # will",
"the respective place within `root`'s Module hierarchy into the GraphModule's",
"nn.Module instance or a Dict mapping strings to any attribute",
"module hierarchy. graph - `graph` contains the nodes this GraphModule",
"self.graph) def __str__(self) -> str: orig_str = super().__str__() return '\\n'.join([orig_str,",
"root.linear.weight, but we have already installed root.linear) # once we",
"of the original module, using the code to reconstruct the",
"the qualified name 'target' on 'to_module # This installs empty",
"over into the appropriate place within the GraphModule's module hierarchy.",
"will ensure that less deeply nested attributes are assigned #",
"attributes are assigned # before more deeply nested attributes. For",
"out the previously-assigned # `foo.bar.baz` targets_to_copy.sort(key=lambda t: t.count('.')) for target_to_copy",
"attribute type. - In the case that `root` is a",
"GraphModule was generated code : The Python source code for",
"over from the respective place within `root`'s Module hierarchy into",
"' passed for root!') self.graph = graph # TorchScript breaks",
"str(root) + ' passed for root!') self.graph = graph #",
"return (deserialize_graphmodule, (dict_without_graph,)) # because __reduce__ is defined for serialization,",
"of atoms. # This will ensure that less deeply nested",
"targets_to_copy: _assign_attr(root[target_to_copy], self, target_to_copy) else: raise RuntimeError('Unsupported type ' +",
"patched_cat(*args, **kwargs): # tensors = args[0] # for t in",
"function generated from `graph` forward : The Python method generated",
"RuntimeError('Unsupported type ' + str(root) + ' passed for root!')",
"t = torch.nn.Module() setattr(to_module, item, t) from_module, to_module = f,",
"+ '\\n' for line in src.splitlines()] exec(compile(src, key, 'exec'), globals)",
"code to reconstruct the graph. We delete the actual graph",
"if isinstance(root, torch.nn.Module): if hasattr(root, 'training'): self.training = root.training for",
"class here because symbolic_trace pulls the forward() # function off",
"any of the submodules, they were not # because they",
"the user-defined class, the only difference # is an extra",
"Node's `target` will be looked up directly in the dict's",
"setattr(to_module, field, from_obj) class GraphModule(torch.nn.Module): \"\"\" GraphModule is an nn.Module",
"issues in __torch_function__ # WAR for __torch_function__ not handling tensor",
"user-provided `foo.bar` and wipe out the previously-assigned # `foo.bar.baz` targets_to_copy.sort(key=lambda",
"t setattr(to_module, field, getattr(from_module, field)) # Assign attribute 'from_obj' to",
"body): super().__init__() self.__dict__ = body CodeOnlyModule.forward = _forward_from_src(body['code']) from .symbolic_trace",
"Module, any references to Module-based objects (via qualified name) in",
"if node.op in ['get_attr', 'call_module']: assert isinstance(node.target, str) _copy_attr(root, self,",
"val) -> None: self._graph = val body, result, free_variables =",
"tensors = args[0] # for t in tensors: # if",
"of the user-defined class, the only difference # is an",
"to copy the object def __deepcopy__(self, memo): fake_mod = torch.nn.Module()",
"literal. Issue here: https://github.com/pytorch/pytorch/issues/44842 # # Shouldn't be an issue",
"is None: t = torch.nn.Module() setattr(to_module, item, t) from_module, to_module",
"mapped to by the Dict will be copied over into",
"# will be assigned before foo.bar.baz. Otherwise, we might assign",
"assert isinstance(node.target, str) _copy_attr(root, self, node.target) elif isinstance(root, dict): targets_to_copy",
"is None: t = torch.nn.Module() setattr(to_module, item, t) to_module =",
"Any]], graph: Graph): \"\"\" Construct a GraphModule. root - `root`",
"GraphModule's module hierarchy. - In the case that `root` is",
"object mapped to by the Dict will be copied over",
"parent, we no longer need to copy the children #",
"a GraphModule. root - `root` can either be an nn.Module",
"might assign # the user-provided `foo.bar` and wipe out the",
"Python method generated from `graph` Note that when `graph` is",
"del dict_without_graph['_graph'] return (deserialize_graphmodule, (dict_without_graph,)) # because __reduce__ is defined",
"in https://github.com/pytorch/pytorch/pull/34725 # orig_cat = torch.cat # def patched_cat(*args, **kwargs):",
"For example, foo.bar # will be assigned before foo.bar.baz. Otherwise,",
"def patched_cat(*args, **kwargs): # tensors = args[0] # for t",
"(), args, kwargs) # return orig_cat(*args, **kwargs) # patched_cat.__module__ =",
"[line + '\\n' for line in src.splitlines()] exec(compile(src, key, 'exec'),",
"install a parent, we no longer need to copy the",
"import Graph import copy # normal exec loses the source",
"field, from_obj) class GraphModule(torch.nn.Module): \"\"\" GraphModule is an nn.Module generated",
"within `root`'s Module hierarchy into the GraphModule's module hierarchy. -",
"Deserialize a GraphModule given the dictionary of the original module,",
"item, None) if t is None: t = torch.nn.Module() setattr(to_module,",
"_orig_getlines(*args, **kwargs) linecache.getlines = patched_getline def _forward_from_src(src : str): gbls:",
"local cache # and then tools like TorchScript will be",
"torch.overrides import linecache from typing import Type, Dict, List, Any,",
"self, target_to_copy) else: raise RuntimeError('Unsupported type ' + str(root) +",
"getattr(from_module, field)) # Assign attribute 'from_obj' to the qualified name",
"installed one of its parents # (e.g. target = root.linear.weight,",
"from typing import Type, Dict, List, Any, Union from .graph",
"super().__init__() self.__dict__ = body CodeOnlyModule.forward = _forward_from_src(body['code']) from .symbolic_trace import",
"dummy class here because symbolic_trace pulls the forward() # function",
"to any attribute type. - In the case that `root`",
"the Graph's Nodes' `target` field will be copied over from",
"root - `root` can either be an nn.Module instance or",
"generated from `graph` forward : The Python method generated from",
"objects (via qualified name) in the Graph's Nodes' `target` field",
"of target def _assign_attr(from_obj: Any, to_module: torch.nn.Module, target: str): *prefix,",
"patched_getline(*args, **kwargs): if args[0] in _eval_cache: return _eval_cache[args[0]] return _orig_getlines(*args,",
"a parent, we no longer need to copy the children",
"torch.nn.Module() fake_mod.__dict__ = copy.deepcopy(self.__dict__) return GraphModule(fake_mod, self.graph) def __copy__(self): return",
"https://github.com/pytorch/pytorch/pull/34725 # orig_cat = torch.cat # def patched_cat(*args, **kwargs): #",
"This installs empty Modules where none exist yet if they",
"copy # normal exec loses the source code, however we",
"none exist yet if they are subpaths of target def",
"= linecache.getlines def patched_getline(*args, **kwargs): if args[0] in _eval_cache: return",
"on 'to_module # This installs empty Modules where none exist",
"the forward method class GraphModuleImpl(cls): # type: ignore pass return",
"will be looked up directly in the dict's keys. The",
"isinstance(root, dict): targets_to_copy = [] for node in graph.nodes: if",
"`root`!') targets_to_copy.append(node.target) # Sort targets in ascending order of the",
"body.split('\\n')) + '\\n' self.code = f\"\"\"\\ def forward(self, {', '.join(free_variables)}):",
"target def _copy_attr(from_module: torch.nn.Module, to_module: torch.nn.Module, target: str): *prefix, field",
"str, globals: Dict[str, Any]): global _next_id key = f'<eval_with_key_{_next_id}>' _next_id",
"in the dict's keys. The object mapped to by the",
"# the user-provided `foo.bar` and wipe out the previously-assigned #",
"= f'<eval_with_key_{_next_id}>' _next_id += 1 _eval_cache[key] = [line + '\\n'",
"item in prefix: f = getattr(from_module, item) t = getattr(to_module,",
"empty Modules where none exist yet if they are subpaths",
"{body} return {result} \"\"\" cls = type(self) cls.forward = _forward_from_src(self.code)",
"the class, rather than the instance class CodeOnlyModule(torch.nn.Module): def __init__(self,",
"fake_mod.__dict__ = copy.deepcopy(self.__dict__) return GraphModule(fake_mod, self.graph) def __copy__(self): return GraphModule(self,",
"torch } exec_with_source(src, gbls) return gbls['forward'] def deserialize_graphmodule(body : dict)",
"linecache from typing import Type, Dict, List, Any, Union from",
"def __str__(self) -> str: orig_str = super().__str__() return '\\n'.join([orig_str, self.code])",
"are subpaths of target def _assign_attr(from_obj: Any, to_module: torch.nn.Module, target:",
"graph: Graph): \"\"\" Construct a GraphModule. root - `root` can",
"reassigned, `code` and `forward` will be automatically regenerated. \"\"\" def",
"__deepcopy__(self, memo): fake_mod = torch.nn.Module() fake_mod.__dict__ = copy.deepcopy(self.__dict__) return GraphModule(fake_mod,",
"this GraphModule was generated code : The Python source code",
"setter because of the # continued string literal. Issue here:",
"str): *prefix, field = target.split('.') for item in prefix: f",
"assign # the user-provided `foo.bar` and wipe out the previously-assigned",
"be an issue since these methods shouldn't be used in",
"# and then tools like TorchScript will be able to",
"{', '.join(free_variables)}): {body} return {result} \"\"\" cls = type(self) cls.forward",
"the appropriate place within the GraphModule's module hierarchy. graph -",
"None: t = torch.nn.Module() setattr(to_module, item, t) to_module = t",
"the previously-assigned # `foo.bar.baz` targets_to_copy.sort(key=lambda t: t.count('.')) for target_to_copy in",
"return GraphModule(self, self.graph) def __str__(self) -> str: orig_str = super().__str__()",
"were not traced in the original GraphModule class KeepModules(Tracer): def",
"the user-provided `foo.bar` and wipe out the previously-assigned # `foo.bar.baz`",
"because of the # continued string literal. Issue here: https://github.com/pytorch/pytorch/issues/44842",
"- In the case that `root` is a dict, the",
"to the qualified name 'target' on 'to_module # This installs",
"of target def _copy_attr(from_module: torch.nn.Module, to_module: torch.nn.Module, target: str): *prefix,",
"type. - In the case that `root` is a Module,",
"attribute value with qualified name 'target' from 'from_module' to 'to_module'",
"if node.target not in root: raise RuntimeError('Node ' + str(node)",
"original module, using the code to reconstruct the graph. We",
"for root!') self.graph = graph # TorchScript breaks trying to",
"Tracer # we shouldn't trace into any of the submodules,",
"'.join(free_variables)}): {body} return {result} \"\"\" cls = type(self) cls.forward =",
"# Assign attribute 'from_obj' to the qualified name 'target' on",
"method generated from `graph` Note that when `graph` is reassigned,",
"found in a Node's `target` will be looked up directly",
"that less deeply nested attributes are assigned # before more",
"exist yet if they are subpaths of target def _assign_attr(from_obj:",
"= graph # TorchScript breaks trying to compile the graph",
"they were not traced in the original GraphModule class KeepModules(Tracer):",
"a Node's `target` will be looked up directly in the",
"using exec_with_source # works with inspect _eval_cache : Dict[str, List[str]]",
"Assign attribute 'from_obj' to the qualified name 'target' on 'to_module",
"be looked up directly in the dict's keys. The object",
"ignore pass return super().__new__(GraphModuleImpl) def __init__(self, root: Union[torch.nn.Module, Dict[str, Any]],",
"the # continued string literal. Issue here: https://github.com/pytorch/pytorch/issues/44842 # #",
"if isinstance(t, Proxy): # return t.__torch_function__(patched_cat, (), args, kwargs) #",
"be able to get source info. _next_id = 0 def",
"orig_str = super().__str__() return '\\n'.join([orig_str, self.code]) # workarounds for issues",
"to the in-memory graph format do not get serialized. \"\"\"",
"shouldn't trace into any of the submodules, they were not",
"In the case that `root` is a dict, the qualified",
"dict) -> torch.nn.Module: \"\"\" Deserialize a GraphModule given the dictionary",
"a Dict mapping strings to any attribute type. - In",
"each instance of a graph module needs its own forward",
"+ node.target + ' but that target was not provided",
"to reconstruct the graph. We delete the actual graph before",
"we exec using exec_with_source # works with inspect _eval_cache :",
"installs empty Modules where none exist yet if they are",
"we try to copy the object def __deepcopy__(self, memo): fake_mod",
"line in src.splitlines()] exec(compile(src, key, 'exec'), globals) # patch linecache",
"return KeepModules().trace(CodeOnlyModule(body)) # copy an attribute value with qualified name",
"t setattr(to_module, field, from_obj) class GraphModule(torch.nn.Module): \"\"\" GraphModule is an",
"graph(self): return self._graph @graph.setter def graph(self, val) -> None: self._graph",
"' + str(root) + ' passed for root!') self.graph =",
"strings to any attribute type. - In the case that",
"targets in ascending order of the # of atoms. #",
"in __torch_function__ # WAR for __torch_function__ not handling tensor lists,",
"globals: Dict[str, Any]): global _next_id key = f'<eval_with_key_{_next_id}>' _next_id +=",
"result, free_variables = self._graph.python_code(root_module='self') body = '\\n'.join(' ' + line",
"generated from `graph` Note that when `graph` is reassigned, `code`",
"which this GraphModule was generated code : The Python source",
"\"\"\" Construct a GraphModule. root - `root` can either be",
"the only difference # is an extra layer to install",
"methods shouldn't be used in TorchScript anyway __jit_unused_properties__ = ['graph']",
"the GraphModule's module hierarchy. graph - `graph` contains the nodes",
"`root` is a dict, the qualified name found in a",
": str): gbls: Dict[str, Any] = { 'torch': torch }",
"copy the children # since all the needed properties will",
"<gh_stars>100-1000 import torch import torch.overrides import linecache from typing import",
"qualified name 'target' on 'to_module # This installs empty Modules",
"forward(self, {', '.join(free_variables)}): {body} return {result} \"\"\" cls = type(self)",
"to compile the graph setter because of the # continued",
"isinstance(root, torch.nn.Module): if hasattr(root, 'training'): self.training = root.training for node",
"{} _orig_getlines = linecache.getlines def patched_getline(*args, **kwargs): if args[0] in",
"source code for the function generated from `graph` forward :",
"in root: raise RuntimeError('Node ' + str(node) + ' referenced",
"# WAR for __torch_function__ not handling tensor lists, # fix",
"to copy the children # since all the needed properties",
"forward() # function off of the class, rather than the",
"present return if t is None: t = torch.nn.Module() setattr(to_module,",
"_next_id = 0 def exec_with_source(src: str, globals: Dict[str, Any]): global",
"delete the actual graph before saving the dictionary so that",
"\"\"\" # We create a dummy class here because symbolic_trace",
"return super().__new__(GraphModuleImpl) def __init__(self, root: Union[torch.nn.Module, Dict[str, Any]], graph: Graph):",
"in ['get_attr', 'call_module']: assert isinstance(node.target, str) if node.target not in",
"deeply nested attributes. For example, foo.bar # will be assigned",
"lists, # fix is in https://github.com/pytorch/pytorch/pull/34725 # orig_cat = torch.cat",
"patch linecache so that any code we exec using exec_with_source",
"we need to define deepcopy otherwise it will call __reduce__",
"exec loses the source code, however we can patch #",
"isinstance(t, Proxy): # return t.__torch_function__(patched_cat, (), args, kwargs) # return",
"the dict's keys. The object mapped to by the Dict",
"are assigned # before more deeply nested attributes. For example,",
"attributes. For example, foo.bar # will be assigned before foo.bar.baz.",
"from_obj) class GraphModule(torch.nn.Module): \"\"\" GraphModule is an nn.Module generated from",
"fx.Graph. GraphModule has important attributes: graph : The graph from",
"its own forward method # so create a new singleton",
"create a new singleton class for each instance. # it",
"dict_without_graph['_graph'] return (deserialize_graphmodule, (dict_without_graph,)) # because __reduce__ is defined for",
"the graph. We delete the actual graph before saving the",
"= type(self) cls.forward = _forward_from_src(self.code) def __reduce__(self): dict_without_graph = self.__dict__.copy()",
"GraphModule is an nn.Module generated from an fx.Graph. GraphModule has",
"from .symbolic_trace import Tracer # we shouldn't trace into any",
"_forward_from_src(body['code']) from .symbolic_trace import Tracer # we shouldn't trace into",
"= f\"\"\"\\ def forward(self, {', '.join(free_variables)}): {body} return {result} \"\"\"",
"'target' from 'from_module' to 'to_module' # This installs empty Modules",
"nn.Module generated from an fx.Graph. GraphModule has important attributes: graph",
"in a Node's `target` will be looked up directly in",
"forward method # so create a new singleton class for",
"= 'torch' # patched_cat.__name__ = 'cat' # torch.cat = patched_cat",
"_forward_from_src(src : str): gbls: Dict[str, Any] = { 'torch': torch",
"f'<eval_with_key_{_next_id}>' _next_id += 1 _eval_cache[key] = [line + '\\n' for",
"setattr(to_module, field, getattr(from_module, field)) # Assign attribute 'from_obj' to the",
"linecache module to still recover it. # using exec_with_source will",
"TorchScript will be able to get source info. _next_id =",
"to still recover it. # using exec_with_source will add it",
"# before more deeply nested attributes. For example, foo.bar #",
"for item in prefix: f = getattr(from_module, item) t =",
"= torch.nn.Module() fake_mod.__dict__ = copy.deepcopy(self.__dict__) return GraphModule(fake_mod, self.graph) def __copy__(self):",
"target.split('.') for item in prefix: f = getattr(from_module, item) t",
"node.op in ['get_attr', 'call_module']: assert isinstance(node.target, str) if node.target not",
"and cause symbolic tracing to occur every time we try",
"class, rather than the instance class CodeOnlyModule(torch.nn.Module): def __init__(self, body):",
"' referenced target ' + node.target + ' but that",
"to get source info. _next_id = 0 def exec_with_source(src: str,",
"# is an extra layer to install the forward method",
"def graph(self, val) -> None: self._graph = val body, result,",
"using the code to reconstruct the graph. We delete the",
"target_to_copy) else: raise RuntimeError('Unsupported type ' + str(root) + '",
"to our local cache # and then tools like TorchScript",
"because they were not traced in the original GraphModule class",
"an extra layer to install the forward method class GraphModuleImpl(cls):",
"reconstruct the graph. We delete the actual graph before saving",
"str): gbls: Dict[str, Any] = { 'torch': torch } exec_with_source(src,",
"actual graph before saving the dictionary so that changes to",
"will call __reduce__ # and cause symbolic tracing to occur",
"super().__str__() return '\\n'.join([orig_str, self.code]) # workarounds for issues in __torch_function__",
"prefix: f = getattr(from_module, item) t = getattr(to_module, item, None)",
"def is_leaf_module(self, _: torch.nn.Module, __: str) -> bool: return True",
"_next_id key = f'<eval_with_key_{_next_id}>' _next_id += 1 _eval_cache[key] = [line",
"key, 'exec'), globals) # patch linecache so that any code",
"List[str]] = {} _orig_getlines = linecache.getlines def patched_getline(*args, **kwargs): if",
"KeepModules().trace(CodeOnlyModule(body)) # copy an attribute value with qualified name 'target'",
"`root` is a Module, any references to Module-based objects (via",
"super().__init__() if isinstance(root, torch.nn.Module): if hasattr(root, 'training'): self.training = root.training",
"graph # TorchScript breaks trying to compile the graph setter",
"f is t: # we have already installed one of",
"for code generation \"\"\" super().__init__() if isinstance(root, torch.nn.Module): if hasattr(root,",
"of its parents # (e.g. target = root.linear.weight, but we",
"are subpaths of target def _copy_attr(from_module: torch.nn.Module, to_module: torch.nn.Module, target:",
"was generated code : The Python source code for the",
"this GraphModule should use for code generation \"\"\" super().__init__() if",
"+ ' passed for root!') self.graph = graph # TorchScript",
"tensor lists, # fix is in https://github.com/pytorch/pytorch/pull/34725 # orig_cat =",
"needed properties will already be present return if t is",
"node in graph.nodes: if node.op in ['get_attr', 'call_module']: assert isinstance(node.target,",
"all the needed properties will already be present return if",
"type ' + str(root) + ' passed for root!') self.graph",
"subpaths of target def _copy_attr(from_module: torch.nn.Module, to_module: torch.nn.Module, target: str):",
"nested attributes are assigned # before more deeply nested attributes.",
"dictionary of the original module, using the code to reconstruct",
"instance. # it is a subclass of the user-defined class,",
"self.code = f\"\"\"\\ def forward(self, {', '.join(free_variables)}): {body} return {result}",
"and then tools like TorchScript will be able to get",
"linecache.getlines def patched_getline(*args, **kwargs): if args[0] in _eval_cache: return _eval_cache[args[0]]",
"- `graph` contains the nodes this GraphModule should use for",
"the source code, however we can patch # the linecache",
"f\"\"\"\\ def forward(self, {', '.join(free_variables)}): {body} return {result} \"\"\" cls",
"'\\n' for line in src.splitlines()] exec(compile(src, key, 'exec'), globals) #",
"f, t setattr(to_module, field, getattr(from_module, field)) # Assign attribute 'from_obj'",
"graph setter because of the # continued string literal. Issue",
"Proxy): # return t.__torch_function__(patched_cat, (), args, kwargs) # return orig_cat(*args,",
"We delete the actual graph before saving the dictionary so",
"works with inspect _eval_cache : Dict[str, List[str]] = {} _orig_getlines",
"field)) # Assign attribute 'from_obj' to the qualified name 'target'",
"an issue since these methods shouldn't be used in TorchScript",
"used in TorchScript anyway __jit_unused_properties__ = ['graph'] @property def graph(self):",
"that changes to the in-memory graph format do not get",
"each instance. # it is a subclass of the user-defined",
"from 'from_module' to 'to_module' # This installs empty Modules where",
"of the # of atoms. # This will ensure that",
"or a Dict mapping strings to any attribute type. -",
"source info. _next_id = 0 def exec_with_source(src: str, globals: Dict[str,",
"that when `graph` is reassigned, `code` and `forward` will be",
"body CodeOnlyModule.forward = _forward_from_src(body['code']) from .symbolic_trace import Tracer # we",
"instance of a graph module needs its own forward method",
"with inspect _eval_cache : Dict[str, List[str]] = {} _orig_getlines =",
"were not # because they were not traced in the",
"import torch import torch.overrides import linecache from typing import Type,",
"will be automatically regenerated. \"\"\" def __new__(cls: 'Type[GraphModule]', *args, **kwargs):",
"Sort targets in ascending order of the # of atoms.",
"_copy_attr(root, self, node.target) elif isinstance(root, dict): targets_to_copy = [] for",
"# continued string literal. Issue here: https://github.com/pytorch/pytorch/issues/44842 # # Shouldn't",
"return '\\n'.join([orig_str, self.code]) # workarounds for issues in __torch_function__ #",
"place within the GraphModule's module hierarchy. graph - `graph` contains",
"every time we try to copy the object def __deepcopy__(self,",
"args[0] # for t in tensors: # if isinstance(t, Proxy):",
"like TorchScript will be able to get source info. _next_id",
"getattr(to_module, item, None) if t is None: t = torch.nn.Module()",
"# TorchScript breaks trying to compile the graph setter because",
"def __init__(self, body): super().__init__() self.__dict__ = body CodeOnlyModule.forward = _forward_from_src(body['code'])",
"' + str(node) + ' referenced target ' + node.target",
": Dict[str, List[str]] = {} _orig_getlines = linecache.getlines def patched_getline(*args,",
"Dict, List, Any, Union from .graph import Graph import copy",
"_eval_cache[args[0]] return _orig_getlines(*args, **kwargs) linecache.getlines = patched_getline def _forward_from_src(src :",
"import torch.overrides import linecache from typing import Type, Dict, List,",
"forward method class GraphModuleImpl(cls): # type: ignore pass return super().__new__(GraphModuleImpl)",
"['graph'] @property def graph(self): return self._graph @graph.setter def graph(self, val)",
"cause symbolic tracing to occur every time we try to",
"# patched_cat.__module__ = 'torch' # patched_cat.__name__ = 'cat' # torch.cat",
"bool: return True return KeepModules().trace(CodeOnlyModule(body)) # copy an attribute value",
"dict): targets_to_copy = [] for node in graph.nodes: if node.op",
"Dict[str, List[str]] = {} _orig_getlines = linecache.getlines def patched_getline(*args, **kwargs):",
"module, using the code to reconstruct the graph. We delete",
": The Python source code for the function generated from",
"any attribute type. - In the case that `root` is",
"is a subclass of the user-defined class, the only difference",
"+ str(node) + ' referenced target ' + node.target +",
"Graph import copy # normal exec loses the source code,",
"_assign_attr(from_obj: Any, to_module: torch.nn.Module, target: str): *prefix, field = target.split('.')",
"type(self) cls.forward = _forward_from_src(self.code) def __reduce__(self): dict_without_graph = self.__dict__.copy() del",
"changes to the in-memory graph format do not get serialized.",
"with qualified name 'target' from 'from_module' to 'to_module' # This",
"Dict mapping strings to any attribute type. - In the",
"= 0 def exec_with_source(src: str, globals: Dict[str, Any]): global _next_id",
"be used in TorchScript anyway __jit_unused_properties__ = ['graph'] @property def",
"not handling tensor lists, # fix is in https://github.com/pytorch/pytorch/pull/34725 #",
"# since all the needed properties will already be present",
"t = getattr(to_module, item, None) if f is t: #",
"orig_cat(*args, **kwargs) # patched_cat.__module__ = 'torch' # patched_cat.__name__ = 'cat'",
"code we exec using exec_with_source # works with inspect _eval_cache",
"CodeOnlyModule.forward = _forward_from_src(body['code']) from .symbolic_trace import Tracer # we shouldn't",
"a graph module needs its own forward method # so",
"Module-based objects (via qualified name) in the Graph's Nodes' `target`",
".graph import Graph import copy # normal exec loses the",
"time we try to copy the object def __deepcopy__(self, memo):",
"of the # continued string literal. Issue here: https://github.com/pytorch/pytorch/issues/44842 #",
"name found in a Node's `target` will be looked up",
"will add it to our local cache # and then",
"the in-memory graph format do not get serialized. \"\"\" #",
"= getattr(to_module, item, None) if f is t: # we",
"__init__(self, body): super().__init__() self.__dict__ = body CodeOnlyModule.forward = _forward_from_src(body['code']) from",
"_eval_cache : Dict[str, List[str]] = {} _orig_getlines = linecache.getlines def",
"`target` will be looked up directly in the dict's keys.",
"GraphModule's module hierarchy. graph - `graph` contains the nodes this",
"t = torch.nn.Module() setattr(to_module, item, t) to_module = t setattr(to_module,",
"in TorchScript anyway __jit_unused_properties__ = ['graph'] @property def graph(self): return",
"# if isinstance(t, Proxy): # return t.__torch_function__(patched_cat, (), args, kwargs)",
"torch.nn.Module, __: str) -> bool: return True return KeepModules().trace(CodeOnlyModule(body)) #",
"the submodules, they were not # because they were not",
"kwargs) # return orig_cat(*args, **kwargs) # patched_cat.__module__ = 'torch' #",
"getattr(from_module, item) t = getattr(to_module, item, None) if f is",
"self, node.target) elif isinstance(root, dict): targets_to_copy = [] for node",
"# return orig_cat(*args, **kwargs) # patched_cat.__module__ = 'torch' # patched_cat.__name__",
"subpaths of target def _assign_attr(from_obj: Any, to_module: torch.nn.Module, target: str):",
"target def _assign_attr(from_obj: Any, to_module: torch.nn.Module, target: str): *prefix, field",
"`graph` is reassigned, `code` and `forward` will be automatically regenerated.",
"an nn.Module instance or a Dict mapping strings to any",
"+ ' but that target was not provided in `root`!')",
"can either be an nn.Module instance or a Dict mapping",
"ascending order of the # of atoms. # This will",
"layer to install the forward method class GraphModuleImpl(cls): # type:",
"Type, Dict, List, Any, Union from .graph import Graph import",
"node.target) elif isinstance(root, dict): targets_to_copy = [] for node in",
"defined for serialization, # we need to define deepcopy otherwise",
"List, Any, Union from .graph import Graph import copy #",
"return _orig_getlines(*args, **kwargs) linecache.getlines = patched_getline def _forward_from_src(src : str):",
"looked up directly in the dict's keys. The object mapped",
"info. _next_id = 0 def exec_with_source(src: str, globals: Dict[str, Any]):",
"'Type[GraphModule]', *args, **kwargs): # each instance of a graph module",
"Python source code for the function generated from `graph` forward",
"the dictionary of the original module, using the code to",
"nested attributes. For example, foo.bar # will be assigned before",
"KeepModules(Tracer): def is_leaf_module(self, _: torch.nn.Module, __: str) -> bool: return",
"class for each instance. # it is a subclass of",
"typing import Type, Dict, List, Any, Union from .graph import",
"we might assign # the user-provided `foo.bar` and wipe out",
"when `graph` is reassigned, `code` and `forward` will be automatically",
"either be an nn.Module instance or a Dict mapping strings",
"The object mapped to by the Dict will be copied",
"__copy__(self): return GraphModule(self, self.graph) def __str__(self) -> str: orig_str =",
"def __copy__(self): return GraphModule(self, self.graph) def __str__(self) -> str: orig_str",
"# and cause symbolic tracing to occur every time we",
"= args[0] # for t in tensors: # if isinstance(t,",
"self.__dict__.copy() del dict_without_graph['_graph'] return (deserialize_graphmodule, (dict_without_graph,)) # because __reduce__ is",
"`foo.bar` and wipe out the previously-assigned # `foo.bar.baz` targets_to_copy.sort(key=lambda t:",
"deserialize_graphmodule(body : dict) -> torch.nn.Module: \"\"\" Deserialize a GraphModule given",
"(e.g. target = root.linear.weight, but we have already installed root.linear)",
"\"\"\" super().__init__() if isinstance(root, torch.nn.Module): if hasattr(root, 'training'): self.training =",
"get serialized. \"\"\" # We create a dummy class here",
"of the submodules, they were not # because they were",
"def _copy_attr(from_module: torch.nn.Module, to_module: torch.nn.Module, target: str): *prefix, field =",
"pass return super().__new__(GraphModuleImpl) def __init__(self, root: Union[torch.nn.Module, Dict[str, Any]], graph:",
"so that changes to the in-memory graph format do not",
"to Module-based objects (via qualified name) in the Graph's Nodes'",
"an fx.Graph. GraphModule has important attributes: graph : The graph",
"the # of atoms. # This will ensure that less",
"# because __reduce__ is defined for serialization, # we need",
"__reduce__ is defined for serialization, # we need to define",
"into the GraphModule's module hierarchy. - In the case that",
"t) from_module, to_module = f, t setattr(to_module, field, getattr(from_module, field))",
"item) t = getattr(to_module, item, None) if f is t:",
"but we have already installed root.linear) # once we install",
"regenerated. \"\"\" def __new__(cls: 'Type[GraphModule]', *args, **kwargs): # each instance",
"node.op in ['get_attr', 'call_module']: assert isinstance(node.target, str) _copy_attr(root, self, node.target)",
"Dict[str, Any]): global _next_id key = f'<eval_with_key_{_next_id}>' _next_id += 1",
"we install a parent, we no longer need to copy",
"the instance class CodeOnlyModule(torch.nn.Module): def __init__(self, body): super().__init__() self.__dict__ =",
"will be copied over into the appropriate place within the",
"these methods shouldn't be used in TorchScript anyway __jit_unused_properties__ =",
"if args[0] in _eval_cache: return _eval_cache[args[0]] return _orig_getlines(*args, **kwargs) linecache.getlines",
"= torch.cat # def patched_cat(*args, **kwargs): # tensors = args[0]",
"# so create a new singleton class for each instance.",
"place within `root`'s Module hierarchy into the GraphModule's module hierarchy.",
"copy.deepcopy(self.__dict__) return GraphModule(fake_mod, self.graph) def __copy__(self): return GraphModule(self, self.graph) def",
"exec_with_source will add it to our local cache # and",
"cls = type(self) cls.forward = _forward_from_src(self.code) def __reduce__(self): dict_without_graph =",
"torch.nn.Module, target: str): *prefix, field = target.split('.') for item in",
"= getattr(to_module, item, None) if t is None: t =",
"here: https://github.com/pytorch/pytorch/issues/44842 # # Shouldn't be an issue since these",
"+ line for line in body.split('\\n')) + '\\n' self.code =",
"# fix is in https://github.com/pytorch/pytorch/pull/34725 # orig_cat = torch.cat #",
"graph. We delete the actual graph before saving the dictionary",
"'to_module' # This installs empty Modules where none exist yet",
"def __deepcopy__(self, memo): fake_mod = torch.nn.Module() fake_mod.__dict__ = copy.deepcopy(self.__dict__) return",
"root: raise RuntimeError('Node ' + str(node) + ' referenced target",
"@property def graph(self): return self._graph @graph.setter def graph(self, val) ->",
"they are subpaths of target def _copy_attr(from_module: torch.nn.Module, to_module: torch.nn.Module,",
"= target.split('.') for item in prefix: f = getattr(from_module, item)",
"the Dict will be copied over into the appropriate place",
"# using exec_with_source will add it to our local cache",
"we shouldn't trace into any of the submodules, they were",
"need to copy the children # since all the needed",
"example, foo.bar # will be assigned before foo.bar.baz. Otherwise, we",
"Any, to_module: torch.nn.Module, target: str): *prefix, field = target.split('.') for",
"GraphModule should use for code generation \"\"\" super().__init__() if isinstance(root,",
"the forward() # function off of the class, rather than",
"if f is t: # we have already installed one",
"str): *prefix, field = target.split('.') for item in prefix: t",
"torch.nn.Module() setattr(to_module, item, t) to_module = t setattr(to_module, field, from_obj)",
"targets_to_copy = [] for node in graph.nodes: if node.op in",
"the GraphModule's module hierarchy. - In the case that `root`",
"the original module, using the code to reconstruct the graph.",
"should use for code generation \"\"\" super().__init__() if isinstance(root, torch.nn.Module):",
"node.target + ' but that target was not provided in",
"_eval_cache: return _eval_cache[args[0]] return _orig_getlines(*args, **kwargs) linecache.getlines = patched_getline def",
"children # since all the needed properties will already be",
"Module hierarchy into the GraphModule's module hierarchy. - In the",
"**kwargs) linecache.getlines = patched_getline def _forward_from_src(src : str): gbls: Dict[str,",
"gbls) return gbls['forward'] def deserialize_graphmodule(body : dict) -> torch.nn.Module: \"\"\"",
"'target' on 'to_module # This installs empty Modules where none",
"raise RuntimeError('Node ' + str(node) + ' referenced target '",
"body = '\\n'.join(' ' + line for line in body.split('\\n'))",
"`graph` contains the nodes this GraphModule should use for code",
"to occur every time we try to copy the object",
"target: str): *prefix, field = target.split('.') for item in prefix:",
"code generation \"\"\" super().__init__() if isinstance(root, torch.nn.Module): if hasattr(root, 'training'):",
"def forward(self, {', '.join(free_variables)}): {body} return {result} \"\"\" cls =",
"[] for node in graph.nodes: if node.op in ['get_attr', 'call_module']:",
"-> torch.nn.Module: \"\"\" Deserialize a GraphModule given the dictionary of",
"atoms. # This will ensure that less deeply nested attributes",
"def graph(self): return self._graph @graph.setter def graph(self, val) -> None:",
"since all the needed properties will already be present return",
"Union[torch.nn.Module, Dict[str, Any]], graph: Graph): \"\"\" Construct a GraphModule. root",
"generated from an fx.Graph. GraphModule has important attributes: graph :",
"Dict[str, Any]], graph: Graph): \"\"\" Construct a GraphModule. root -",
"Any] = { 'torch': torch } exec_with_source(src, gbls) return gbls['forward']",
"graph.nodes: if node.op in ['get_attr', 'call_module']: assert isinstance(node.target, str) _copy_attr(root,",
"hierarchy. - In the case that `root` is a dict,",
"here because symbolic_trace pulls the forward() # function off of",
"is_leaf_module(self, _: torch.nn.Module, __: str) -> bool: return True return",
"`root` can either be an nn.Module instance or a Dict",
"self._graph = val body, result, free_variables = self._graph.python_code(root_module='self') body =",
"order of the # of atoms. # This will ensure",
"copy the object def __deepcopy__(self, memo): fake_mod = torch.nn.Module() fake_mod.__dict__",
"tools like TorchScript will be able to get source info.",
"exist yet if they are subpaths of target def _copy_attr(from_module:",
"saving the dictionary so that changes to the in-memory graph",
"*prefix, field = target.split('.') for item in prefix: f =",
"be copied over from the respective place within `root`'s Module",
"True return KeepModules().trace(CodeOnlyModule(body)) # copy an attribute value with qualified",
"the children # since all the needed properties will already",
"'exec'), globals) # patch linecache so that any code we",
"field = target.split('.') for item in prefix: t = getattr(to_module,",
"WAR for __torch_function__ not handling tensor lists, # fix is",
"import Type, Dict, List, Any, Union from .graph import Graph",
"class GraphModule(torch.nn.Module): \"\"\" GraphModule is an nn.Module generated from an",
"for node in graph.nodes: if node.op in ['get_attr', 'call_module']: assert",
"is a dict, the qualified name found in a Node's",
"method # so create a new singleton class for each",
"= [] for node in graph.nodes: if node.op in ['get_attr',",
"if node.op in ['get_attr', 'call_module']: assert isinstance(node.target, str) if node.target",
"\"\"\" def __new__(cls: 'Type[GraphModule]', *args, **kwargs): # each instance of",
"anyway __jit_unused_properties__ = ['graph'] @property def graph(self): return self._graph @graph.setter",
"generation \"\"\" super().__init__() if isinstance(root, torch.nn.Module): if hasattr(root, 'training'): self.training",
"line in body.split('\\n')) + '\\n' self.code = f\"\"\"\\ def forward(self,",
"user-defined class, the only difference # is an extra layer",
"Issue here: https://github.com/pytorch/pytorch/issues/44842 # # Shouldn't be an issue since",
"singleton class for each instance. # it is a subclass",
"# patch linecache so that any code we exec using",
"because symbolic_trace pulls the forward() # function off of the",
"more deeply nested attributes. For example, foo.bar # will be",
"in targets_to_copy: _assign_attr(root[target_to_copy], self, target_to_copy) else: raise RuntimeError('Unsupported type '",
"patched_getline def _forward_from_src(src : str): gbls: Dict[str, Any] = {",
"class CodeOnlyModule(torch.nn.Module): def __init__(self, body): super().__init__() self.__dict__ = body CodeOnlyModule.forward",
"# orig_cat = torch.cat # def patched_cat(*args, **kwargs): # tensors",
"however we can patch # the linecache module to still",
"add it to our local cache # and then tools",
"CodeOnlyModule(torch.nn.Module): def __init__(self, body): super().__init__() self.__dict__ = body CodeOnlyModule.forward =",
"\"\"\" GraphModule is an nn.Module generated from an fx.Graph. GraphModule",
"once we install a parent, we no longer need to",
"super().__new__(GraphModuleImpl) def __init__(self, root: Union[torch.nn.Module, Dict[str, Any]], graph: Graph): \"\"\"",
"t.count('.')) for target_to_copy in targets_to_copy: _assign_attr(root[target_to_copy], self, target_to_copy) else: raise",
"return {result} \"\"\" cls = type(self) cls.forward = _forward_from_src(self.code) def",
"already installed root.linear) # once we install a parent, we",
"self._graph.python_code(root_module='self') body = '\\n'.join(' ' + line for line in",
"in the original GraphModule class KeepModules(Tracer): def is_leaf_module(self, _: torch.nn.Module,",
"that `root` is a dict, the qualified name found in",
"= super().__str__() return '\\n'.join([orig_str, self.code]) # workarounds for issues in",
"# normal exec loses the source code, however we can",
"is in https://github.com/pytorch/pytorch/pull/34725 # orig_cat = torch.cat # def patched_cat(*args,",
"= root.training for node in graph.nodes: if node.op in ['get_attr',",
"isinstance(node.target, str) _copy_attr(root, self, node.target) elif isinstance(root, dict): targets_to_copy =",
"exec_with_source(src: str, globals: Dict[str, Any]): global _next_id key = f'<eval_with_key_{_next_id}>'",
"able to get source info. _next_id = 0 def exec_with_source(src:",
"(deserialize_graphmodule, (dict_without_graph,)) # because __reduce__ is defined for serialization, #",
"__new__(cls: 'Type[GraphModule]', *args, **kwargs): # each instance of a graph",
"# (e.g. target = root.linear.weight, but we have already installed",
"assert isinstance(node.target, str) if node.target not in root: raise RuntimeError('Node",
"\"\"\" cls = type(self) cls.forward = _forward_from_src(self.code) def __reduce__(self): dict_without_graph",
"no longer need to copy the children # since all",
"dict_without_graph = self.__dict__.copy() del dict_without_graph['_graph'] return (deserialize_graphmodule, (dict_without_graph,)) # because",
"This will ensure that less deeply nested attributes are assigned",
"parents # (e.g. target = root.linear.weight, but we have already",
"in ascending order of the # of atoms. # This",
"that any code we exec using exec_with_source # works with",
"in-memory graph format do not get serialized. \"\"\" # We",
"compile the graph setter because of the # continued string",
"= [line + '\\n' for line in src.splitlines()] exec(compile(src, key,",
"provided in `root`!') targets_to_copy.append(node.target) # Sort targets in ascending order",
"was not provided in `root`!') targets_to_copy.append(node.target) # Sort targets in",
"occur every time we try to copy the object def",
"otherwise it will call __reduce__ # and cause symbolic tracing",
"has important attributes: graph : The graph from which this",
"to define deepcopy otherwise it will call __reduce__ # and",
"'\\n'.join([orig_str, self.code]) # workarounds for issues in __torch_function__ # WAR",
": The Python method generated from `graph` Note that when",
"`graph` Note that when `graph` is reassigned, `code` and `forward`",
"# `foo.bar.baz` targets_to_copy.sort(key=lambda t: t.count('.')) for target_to_copy in targets_to_copy: _assign_attr(root[target_to_copy],",
"torch.cat # def patched_cat(*args, **kwargs): # tensors = args[0] #",
"_orig_getlines = linecache.getlines def patched_getline(*args, **kwargs): if args[0] in _eval_cache:",
"__reduce__(self): dict_without_graph = self.__dict__.copy() del dict_without_graph['_graph'] return (deserialize_graphmodule, (dict_without_graph,)) #",
"_forward_from_src(self.code) def __reduce__(self): dict_without_graph = self.__dict__.copy() del dict_without_graph['_graph'] return (deserialize_graphmodule,",
"# type: ignore pass return super().__new__(GraphModuleImpl) def __init__(self, root: Union[torch.nn.Module,",
"'training'): self.training = root.training for node in graph.nodes: if node.op",
"raise RuntimeError('Unsupported type ' + str(root) + ' passed for",
"will be able to get source info. _next_id = 0",
"+= 1 _eval_cache[key] = [line + '\\n' for line in",
"isinstance(node.target, str) if node.target not in root: raise RuntimeError('Node '",
"= patched_getline def _forward_from_src(src : str): gbls: Dict[str, Any] =",
"import Tracer # we shouldn't trace into any of the",
"and `forward` will be automatically regenerated. \"\"\" def __new__(cls: 'Type[GraphModule]',",
"ensure that less deeply nested attributes are assigned # before",
"GraphModule(self, self.graph) def __str__(self) -> str: orig_str = super().__str__() return",
"already be present return if t is None: t =",
"__torch_function__ not handling tensor lists, # fix is in https://github.com/pytorch/pytorch/pull/34725",
"0 def exec_with_source(src: str, globals: Dict[str, Any]): global _next_id key",
"return GraphModule(fake_mod, self.graph) def __copy__(self): return GraphModule(self, self.graph) def __str__(self)",
"respective place within `root`'s Module hierarchy into the GraphModule's module",
"GraphModule class KeepModules(Tracer): def is_leaf_module(self, _: torch.nn.Module, __: str) ->",
"field = target.split('.') for item in prefix: f = getattr(from_module,",
"a subclass of the user-defined class, the only difference #",
"less deeply nested attributes are assigned # before more deeply",
"deepcopy otherwise it will call __reduce__ # and cause symbolic",
"if they are subpaths of target def _copy_attr(from_module: torch.nn.Module, to_module:",
"# because they were not traced in the original GraphModule",
"then tools like TorchScript will be able to get source",
"the actual graph before saving the dictionary so that changes",
"to 'to_module' # This installs empty Modules where none exist",
"# once we install a parent, we no longer need",
"that `root` is a Module, any references to Module-based objects",
"graph : The graph from which this GraphModule was generated",
"Nodes' `target` field will be copied over from the respective",
"root!') self.graph = graph # TorchScript breaks trying to compile",
"__jit_unused_properties__ = ['graph'] @property def graph(self): return self._graph @graph.setter def",
"serialization, # we need to define deepcopy otherwise it will",
"field will be copied over from the respective place within",
".symbolic_trace import Tracer # we shouldn't trace into any of",
"not traced in the original GraphModule class KeepModules(Tracer): def is_leaf_module(self,",
"' + node.target + ' but that target was not",
"# for t in tensors: # if isinstance(t, Proxy): #",
"appropriate place within the GraphModule's module hierarchy. graph - `graph`",
"deeply nested attributes are assigned # before more deeply nested",
"yet if they are subpaths of target def _copy_attr(from_module: torch.nn.Module,",
"_copy_attr(from_module: torch.nn.Module, to_module: torch.nn.Module, target: str): *prefix, field = target.split('.')",
"-> bool: return True return KeepModules().trace(CodeOnlyModule(body)) # copy an attribute",
"prefix: t = getattr(to_module, item, None) if t is None:",
"return if t is None: t = torch.nn.Module() setattr(to_module, item,",
"in ['get_attr', 'call_module']: assert isinstance(node.target, str) _copy_attr(root, self, node.target) elif",
"if hasattr(root, 'training'): self.training = root.training for node in graph.nodes:",
"' + line for line in body.split('\\n')) + '\\n' self.code",
"{result} \"\"\" cls = type(self) cls.forward = _forward_from_src(self.code) def __reduce__(self):",
"' but that target was not provided in `root`!') targets_to_copy.append(node.target)",
"given the dictionary of the original module, using the code",
"not in root: raise RuntimeError('Node ' + str(node) + '",
"it. # using exec_with_source will add it to our local",
"'call_module']: assert isinstance(node.target, str) if node.target not in root: raise",
"its parents # (e.g. target = root.linear.weight, but we have",
"the needed properties will already be present return if t",
"elif isinstance(root, dict): targets_to_copy = [] for node in graph.nodes:",
"['get_attr', 'call_module']: assert isinstance(node.target, str) if node.target not in root:",
"from the respective place within `root`'s Module hierarchy into the",
"return t.__torch_function__(patched_cat, (), args, kwargs) # return orig_cat(*args, **kwargs) #",
"case that `root` is a Module, any references to Module-based",
"the qualified name found in a Node's `target` will be",
"that target was not provided in `root`!') targets_to_copy.append(node.target) # Sort",
"{ 'torch': torch } exec_with_source(src, gbls) return gbls['forward'] def deserialize_graphmodule(body",
"= torch.nn.Module() setattr(to_module, item, t) from_module, to_module = f, t",
"target was not provided in `root`!') targets_to_copy.append(node.target) # Sort targets",
"hierarchy. graph - `graph` contains the nodes this GraphModule should",
"not provided in `root`!') targets_to_copy.append(node.target) # Sort targets in ascending",
"targets_to_copy.sort(key=lambda t: t.count('.')) for target_to_copy in targets_to_copy: _assign_attr(root[target_to_copy], self, target_to_copy)",
"pulls the forward() # function off of the class, rather",
"(dict_without_graph,)) # because __reduce__ is defined for serialization, # we",
"setattr(to_module, item, t) from_module, to_module = f, t setattr(to_module, field,",
"the case that `root` is a dict, the qualified name",
"cache # and then tools like TorchScript will be able",
"installed root.linear) # once we install a parent, we no",
"'\\n' self.code = f\"\"\"\\ def forward(self, {', '.join(free_variables)}): {body} return",
"inspect _eval_cache : Dict[str, List[str]] = {} _orig_getlines = linecache.getlines",
"mapping strings to any attribute type. - In the case",
"str) -> bool: return True return KeepModules().trace(CodeOnlyModule(body)) # copy an",
"t = getattr(to_module, item, None) if t is None: t",
"type: ignore pass return super().__new__(GraphModuleImpl) def __init__(self, root: Union[torch.nn.Module, Dict[str,",
"handling tensor lists, # fix is in https://github.com/pytorch/pytorch/pull/34725 # orig_cat",
"rather than the instance class CodeOnlyModule(torch.nn.Module): def __init__(self, body): super().__init__()",
"into any of the submodules, they were not # because",
"field, getattr(from_module, field)) # Assign attribute 'from_obj' to the qualified",
"code : The Python source code for the function generated",
"format do not get serialized. \"\"\" # We create a",
"submodules, they were not # because they were not traced",
"self.graph = graph # TorchScript breaks trying to compile the",
"Graph): \"\"\" Construct a GraphModule. root - `root` can either",
"The Python method generated from `graph` Note that when `graph`",
"# each instance of a graph module needs its own",
"new singleton class for each instance. # it is a",
"any code we exec using exec_with_source # works with inspect",
"subclass of the user-defined class, the only difference # is",
"\"\"\" Deserialize a GraphModule given the dictionary of the original",
"Dict will be copied over into the appropriate place within",
"import linecache from typing import Type, Dict, List, Any, Union",
"be present return if t is None: t = torch.nn.Module()",
"__reduce__ # and cause symbolic tracing to occur every time",
"from which this GraphModule was generated code : The Python",
"self.code]) # workarounds for issues in __torch_function__ # WAR for",
"item, t) from_module, to_module = f, t setattr(to_module, field, getattr(from_module,",
"str) if node.target not in root: raise RuntimeError('Node ' +",
"**kwargs): # tensors = args[0] # for t in tensors:",
"is a Module, any references to Module-based objects (via qualified",
"for __torch_function__ not handling tensor lists, # fix is in",
"item, t) to_module = t setattr(to_module, field, from_obj) class GraphModule(torch.nn.Module):",
"original GraphModule class KeepModules(Tracer): def is_leaf_module(self, _: torch.nn.Module, __: str)",
"because __reduce__ is defined for serialization, # we need to",
"# def patched_cat(*args, **kwargs): # tensors = args[0] # for",
"- In the case that `root` is a Module, any",
"use for code generation \"\"\" super().__init__() if isinstance(root, torch.nn.Module): if",
"instance class CodeOnlyModule(torch.nn.Module): def __init__(self, body): super().__init__() self.__dict__ = body",
"= _forward_from_src(body['code']) from .symbolic_trace import Tracer # we shouldn't trace",
"None) if t is None: t = torch.nn.Module() setattr(to_module, item,",
"body, result, free_variables = self._graph.python_code(root_module='self') body = '\\n'.join(' ' +",
"-> str: orig_str = super().__str__() return '\\n'.join([orig_str, self.code]) # workarounds",
"hierarchy into the GraphModule's module hierarchy. - In the case",
"serialized. \"\"\" # We create a dummy class here because",
"node.target not in root: raise RuntimeError('Node ' + str(node) +",
"Any]): global _next_id key = f'<eval_with_key_{_next_id}>' _next_id += 1 _eval_cache[key]",
"create a dummy class here because symbolic_trace pulls the forward()",
"attribute 'from_obj' to the qualified name 'target' on 'to_module #",
"= getattr(from_module, item) t = getattr(to_module, item, None) if f",
"__init__(self, root: Union[torch.nn.Module, Dict[str, Any]], graph: Graph): \"\"\" Construct a",
"class KeepModules(Tracer): def is_leaf_module(self, _: torch.nn.Module, __: str) -> bool:",
"install the forward method class GraphModuleImpl(cls): # type: ignore pass",
"assigned before foo.bar.baz. Otherwise, we might assign # the user-provided",
"have already installed one of its parents # (e.g. target",
"TorchScript anyway __jit_unused_properties__ = ['graph'] @property def graph(self): return self._graph",
"# we have already installed one of its parents #",
"dictionary so that changes to the in-memory graph format do",
"directly in the dict's keys. The object mapped to by",
"they are subpaths of target def _assign_attr(from_obj: Any, to_module: torch.nn.Module,",
"a Module, any references to Module-based objects (via qualified name)",
"str) _copy_attr(root, self, node.target) elif isinstance(root, dict): targets_to_copy = []",
"torch import torch.overrides import linecache from typing import Type, Dict,",
"need to define deepcopy otherwise it will call __reduce__ #",
"# # Shouldn't be an issue since these methods shouldn't",
"a new singleton class for each instance. # it is",
"nodes this GraphModule should use for code generation \"\"\" super().__init__()",
"Modules where none exist yet if they are subpaths of",
"the code to reconstruct the graph. We delete the actual",
"Shouldn't be an issue since these methods shouldn't be used",
"We create a dummy class here because symbolic_trace pulls the",
"t: # we have already installed one of its parents",
"**kwargs): # each instance of a graph module needs its",
"the object def __deepcopy__(self, memo): fake_mod = torch.nn.Module() fake_mod.__dict__ =",
"_eval_cache[key] = [line + '\\n' for line in src.splitlines()] exec(compile(src,",
"our local cache # and then tools like TorchScript will",
"= {} _orig_getlines = linecache.getlines def patched_getline(*args, **kwargs): if args[0]",
"src.splitlines()] exec(compile(src, key, 'exec'), globals) # patch linecache so that",
"where none exist yet if they are subpaths of target",
"we no longer need to copy the children # since",
"GraphModule has important attributes: graph : The graph from which",
"for each instance. # it is a subclass of the",
"before foo.bar.baz. Otherwise, we might assign # the user-provided `foo.bar`",
"continued string literal. Issue here: https://github.com/pytorch/pytorch/issues/44842 # # Shouldn't be",
"= self.__dict__.copy() del dict_without_graph['_graph'] return (deserialize_graphmodule, (dict_without_graph,)) # because __reduce__",
"args, kwargs) # return orig_cat(*args, **kwargs) # patched_cat.__module__ = 'torch'",
"+ str(root) + ' passed for root!') self.graph = graph",
"Union from .graph import Graph import copy # normal exec",
"patch # the linecache module to still recover it. #",
"else: raise RuntimeError('Unsupported type ' + str(root) + ' passed",
"exec(compile(src, key, 'exec'), globals) # patch linecache so that any",
"do not get serialized. \"\"\" # We create a dummy",
"torch.nn.Module() setattr(to_module, item, t) from_module, to_module = f, t setattr(to_module,",
"they were not # because they were not traced in",
"RuntimeError('Node ' + str(node) + ' referenced target ' +",
"call __reduce__ # and cause symbolic tracing to occur every",
"class GraphModuleImpl(cls): # type: ignore pass return super().__new__(GraphModuleImpl) def __init__(self,",
"def exec_with_source(src: str, globals: Dict[str, Any]): global _next_id key =",
"# We create a dummy class here because symbolic_trace pulls",
"def __init__(self, root: Union[torch.nn.Module, Dict[str, Any]], graph: Graph): \"\"\" Construct",
"generated code : The Python source code for the function",
"# function off of the class, rather than the instance",
"} exec_with_source(src, gbls) return gbls['forward'] def deserialize_graphmodule(body : dict) ->",
"graph format do not get serialized. \"\"\" # We create",
"method class GraphModuleImpl(cls): # type: ignore pass return super().__new__(GraphModuleImpl) def",
"assigned # before more deeply nested attributes. For example, foo.bar",
"it is a subclass of the user-defined class, the only",
"torch.nn.Module): if hasattr(root, 'training'): self.training = root.training for node in",
"can patch # the linecache module to still recover it.",
"module needs its own forward method # so create a",
"but that target was not provided in `root`!') targets_to_copy.append(node.target) #",
"= f, t setattr(to_module, field, getattr(from_module, field)) # Assign attribute",
"t is None: t = torch.nn.Module() setattr(to_module, item, t) from_module,",
"-> None: self._graph = val body, result, free_variables = self._graph.python_code(root_module='self')",
"for line in body.split('\\n')) + '\\n' self.code = f\"\"\"\\ def",
"define deepcopy otherwise it will call __reduce__ # and cause",
"to_module = t setattr(to_module, field, from_obj) class GraphModule(torch.nn.Module): \"\"\" GraphModule",
"copied over into the appropriate place within the GraphModule's module",
"the graph setter because of the # continued string literal.",
"line for line in body.split('\\n')) + '\\n' self.code = f\"\"\"\\",
"in _eval_cache: return _eval_cache[args[0]] return _orig_getlines(*args, **kwargs) linecache.getlines = patched_getline",
"= { 'torch': torch } exec_with_source(src, gbls) return gbls['forward'] def",
"trace into any of the submodules, they were not #",
"in prefix: t = getattr(to_module, item, None) if t is",
"have already installed root.linear) # once we install a parent,",
"function off of the class, rather than the instance class",
"1 _eval_cache[key] = [line + '\\n' for line in src.splitlines()]",
"still recover it. # using exec_with_source will add it to",
"the dictionary so that changes to the in-memory graph format",
"# we shouldn't trace into any of the submodules, they",
"target ' + node.target + ' but that target was",
"from `graph` forward : The Python method generated from `graph`",
"The Python source code for the function generated from `graph`",
"targets_to_copy.append(node.target) # Sort targets in ascending order of the #",
"will be assigned before foo.bar.baz. Otherwise, we might assign #",
"using exec_with_source will add it to our local cache #",
"source code, however we can patch # the linecache module",
"it will call __reduce__ # and cause symbolic tracing to",
"fake_mod = torch.nn.Module() fake_mod.__dict__ = copy.deepcopy(self.__dict__) return GraphModule(fake_mod, self.graph) def",
"args[0] in _eval_cache: return _eval_cache[args[0]] return _orig_getlines(*args, **kwargs) linecache.getlines =",
"return _eval_cache[args[0]] return _orig_getlines(*args, **kwargs) linecache.getlines = patched_getline def _forward_from_src(src",
"in tensors: # if isinstance(t, Proxy): # return t.__torch_function__(patched_cat, (),",
"Construct a GraphModule. root - `root` can either be an",
"to by the Dict will be copied over into the",
"traced in the original GraphModule class KeepModules(Tracer): def is_leaf_module(self, _:",
"Note that when `graph` is reassigned, `code` and `forward` will",
"for the function generated from `graph` forward : The Python",
"graph.nodes: if node.op in ['get_attr', 'call_module']: assert isinstance(node.target, str) if",
"to install the forward method class GraphModuleImpl(cls): # type: ignore",
"return gbls['forward'] def deserialize_graphmodule(body : dict) -> torch.nn.Module: \"\"\" Deserialize",
"= torch.nn.Module() setattr(to_module, item, t) to_module = t setattr(to_module, field,",
"be copied over into the appropriate place within the GraphModule's",
"graph - `graph` contains the nodes this GraphModule should use",
"exec_with_source # works with inspect _eval_cache : Dict[str, List[str]] =",
"is reassigned, `code` and `forward` will be automatically regenerated. \"\"\"",
"in graph.nodes: if node.op in ['get_attr', 'call_module']: assert isinstance(node.target, str)",
"None: self._graph = val body, result, free_variables = self._graph.python_code(root_module='self') body",
"if t is None: t = torch.nn.Module() setattr(to_module, item, t)",
"= copy.deepcopy(self.__dict__) return GraphModule(fake_mod, self.graph) def __copy__(self): return GraphModule(self, self.graph)",
"normal exec loses the source code, however we can patch",
"yet if they are subpaths of target def _assign_attr(from_obj: Any,",
"than the instance class CodeOnlyModule(torch.nn.Module): def __init__(self, body): super().__init__() self.__dict__",
"GraphModule given the dictionary of the original module, using the",
"def deserialize_graphmodule(body : dict) -> torch.nn.Module: \"\"\" Deserialize a GraphModule",
"is t: # we have already installed one of its",
"forward : The Python method generated from `graph` Note that",
"@graph.setter def graph(self, val) -> None: self._graph = val body,",
"Dict[str, Any] = { 'torch': torch } exec_with_source(src, gbls) return",
"item, None) if f is t: # we have already",
"'from_obj' to the qualified name 'target' on 'to_module # This",
"if they are subpaths of target def _assign_attr(from_obj: Any, to_module:",
"foo.bar # will be assigned before foo.bar.baz. Otherwise, we might",
"dict, the qualified name found in a Node's `target` will",
"up directly in the dict's keys. The object mapped to",
"return orig_cat(*args, **kwargs) # patched_cat.__module__ = 'torch' # patched_cat.__name__ =",
"we can patch # the linecache module to still recover",
"within the GraphModule's module hierarchy. graph - `graph` contains the",
"class, the only difference # is an extra layer to",
"free_variables = self._graph.python_code(root_module='self') body = '\\n'.join(' ' + line for",
"global _next_id key = f'<eval_with_key_{_next_id}>' _next_id += 1 _eval_cache[key] =",
"needs its own forward method # so create a new",
"own forward method # so create a new singleton class",
"for item in prefix: t = getattr(to_module, item, None) if",
"Otherwise, we might assign # the user-provided `foo.bar` and wipe",
"the function generated from `graph` forward : The Python method",
"t in tensors: # if isinstance(t, Proxy): # return t.__torch_function__(patched_cat,",
"(via qualified name) in the Graph's Nodes' `target` field will",
"_: torch.nn.Module, __: str) -> bool: return True return KeepModules().trace(CodeOnlyModule(body))",
"instance or a Dict mapping strings to any attribute type.",
"symbolic tracing to occur every time we try to copy",
"= root.linear.weight, but we have already installed root.linear) # once",
"in body.split('\\n')) + '\\n' self.code = f\"\"\"\\ def forward(self, {',",
"any references to Module-based objects (via qualified name) in the",
"value with qualified name 'target' from 'from_module' to 'to_module' #",
"memo): fake_mod = torch.nn.Module() fake_mod.__dict__ = copy.deepcopy(self.__dict__) return GraphModule(fake_mod, self.graph)",
"will already be present return if t is None: t",
"torch.nn.Module: \"\"\" Deserialize a GraphModule given the dictionary of the",
"orig_cat = torch.cat # def patched_cat(*args, **kwargs): # tensors =",
"extra layer to install the forward method class GraphModuleImpl(cls): #",
"str: orig_str = super().__str__() return '\\n'.join([orig_str, self.code]) # workarounds for",
"import copy # normal exec loses the source code, however",
"= target.split('.') for item in prefix: t = getattr(to_module, item,",
"from an fx.Graph. GraphModule has important attributes: graph : The",
"Graph's Nodes' `target` field will be copied over from the",
"None) if f is t: # we have already installed",
"= val body, result, free_variables = self._graph.python_code(root_module='self') body = '\\n'.join('",
"shouldn't be used in TorchScript anyway __jit_unused_properties__ = ['graph'] @property",
"setattr(to_module, item, t) to_module = t setattr(to_module, field, from_obj) class",
"GraphModule(fake_mod, self.graph) def __copy__(self): return GraphModule(self, self.graph) def __str__(self) ->",
"# workarounds for issues in __torch_function__ # WAR for __torch_function__",
"def _forward_from_src(src : str): gbls: Dict[str, Any] = { 'torch':",
"self._graph @graph.setter def graph(self, val) -> None: self._graph = val",
"previously-assigned # `foo.bar.baz` targets_to_copy.sort(key=lambda t: t.count('.')) for target_to_copy in targets_to_copy:",
"a dict, the qualified name found in a Node's `target`",
"# Shouldn't be an issue since these methods shouldn't be",
"difference # is an extra layer to install the forward",
"of a graph module needs its own forward method #",
"# return t.__torch_function__(patched_cat, (), args, kwargs) # return orig_cat(*args, **kwargs)",
"root.training for node in graph.nodes: if node.op in ['get_attr', 'call_module']:",
"since these methods shouldn't be used in TorchScript anyway __jit_unused_properties__",
"**kwargs) # patched_cat.__module__ = 'torch' # patched_cat.__name__ = 'cat' #",
"get source info. _next_id = 0 def exec_with_source(src: str, globals:",
"copied over from the respective place within `root`'s Module hierarchy",
"GraphModule(torch.nn.Module): \"\"\" GraphModule is an nn.Module generated from an fx.Graph.",
"the case that `root` is a Module, any references to",
"referenced target ' + node.target + ' but that target",
"item in prefix: t = getattr(to_module, item, None) if t",
"f = getattr(from_module, item) t = getattr(to_module, item, None) if",
"graph from which this GraphModule was generated code : The",
"module hierarchy. - In the case that `root` is a",
"wipe out the previously-assigned # `foo.bar.baz` targets_to_copy.sort(key=lambda t: t.count('.')) for",
"for target_to_copy in targets_to_copy: _assign_attr(root[target_to_copy], self, target_to_copy) else: raise RuntimeError('Unsupported",
"= _forward_from_src(self.code) def __reduce__(self): dict_without_graph = self.__dict__.copy() del dict_without_graph['_graph'] return",
"['get_attr', 'call_module']: assert isinstance(node.target, str) _copy_attr(root, self, node.target) elif isinstance(root,",
"will be copied over from the respective place within `root`'s",
"# tensors = args[0] # for t in tensors: #",
"recover it. # using exec_with_source will add it to our",
"not # because they were not traced in the original"
] |
[
"1: select.select([self.sock], [], []) chunk = self.sock.recv(1024) if not len(chunk):",
"self.daemon = True self.sync_queue = queue.Queue() self.routes = {} self.recvbuf",
"= self.client._abspath(path) self.send('file', { 'path': path, 'action': 'receive' }) for",
"b'' for chunk in self.recv(): buffer += chunk if not",
"LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A",
"# # Copyright (c) 2016 <NAME> <<EMAIL>> # # Permission",
"request.is_client: request.client._run_on_peers('queue_event', request, data) ROUTES = { 'filelist': FilelistRoute(), 'file':",
"For rationale, see FileRoute.handle() if not request.is_client: request.client._run_on_peers('queue_event', request, data)",
"elif action == 'send': request.queue_file('send', path) else: log.warn('FileRoute: Unknown action",
"event == 'created': # create the file/directory if f_type ==",
"any, there has to be another newline to separate it",
"up with the server. if self.is_client: # Lock the client",
"super().__init__() self.daemon = True self.sync_queue = queue.Queue() self.routes = {}",
"looks like this: { \"route\": \"<route-name>\", \"data\": \"<data>\" } 'data'",
"self.is_client = bool(self.client._sock) for name, route in ROUTES.items(): route.route_name =",
"the filelist has been sent back by the server. self.client._rlock.acquire()",
"'exit'}) try: self.sock.shutdown(socket.SHUT_RDWR) except OSError: pass def handle(self, data): try:",
"return route = data['route'] data = data['data'] log.info_v('Handling {0}, data:\\n{1}',",
"we can only yield the first # one and have",
"route def setup(self): log.info('Connected to {0}:{1}', self.address[0], self.address[1]) # If",
"not len(chunk): # If select has signaled the socket is",
"{ 'path': path, 'action': 'receive' }) for buf in utils.read_file_seq(abspath,",
"is no special format designed for 'data' and is specific",
"action = data['action'] path = data['path'] if action == 'receive':",
"'receive': tmpf = tempfile.NamedTemporaryFile(delete=False) buffer = b'' for chunk in",
"this: { \"route\": \"<route-name>\", \"data\": \"<data>\" } 'data' holds additional",
"have to leave to others in recvbuf. index = self.recvbuf.find(b'\\n')",
"the route. There is no special format designed for 'data'",
"a text-based format, e.g. base-64 encoding for binary data. After",
"socket, it is a client and # thus needs to",
"recvbuf. index = self.recvbuf.find(b'\\n') if index == -1: yield self.recvbuf",
"TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR",
"zero bytes, the other end probably performed # a close()",
"\"\"\" class FileRoute(Route): def handle(self, data, request): action = data['action']",
"all other clients. if not request.is_client: action = 'send' if",
"# one and have to leave to others in recvbuf.",
"rights # to use, copy, modify, merge, publish, distribute, sublicense,",
"= {} self.recvbuf = b'' RequestHandler.req_handler_num += 1 self.name =",
"\"<relpath-to-file>\" } <action> can be either 'receive' or 'send' Payload",
"'created': # create the file/directory if f_type == 'file': open(abspath,",
"bytes, the other end probably performed # a close() or",
"sent back by the server. self.client._rlock.acquire() self.send('filelist', self.client._filelist) def close(self):",
"self.send('event', entry['event']) self.sync_queue.task_done() def run(self): self.setup() utils.create_thread(self.sync_worker, name=self.name.replace('request-handler', 'sync-worker')) while",
"abspath = self.client._abspath(path) self.send('file', { 'path': path, 'action': 'receive' })",
"a file-deleted and a file-created event, so ignore both. request.client._ignore_next_fsevent(path)",
"a route needs to transfer additional data (a 'payload'), it",
"in events: request.queue_event(e) for f in files: request.queue_file(f[0], f[1]) \"\"\"",
"probably performed # a close() or shutdown() on the socket.",
"portions of the Software. # # THE SOFTWARE IS PROVIDED",
"request = json.dumps({'route': route, 'data': data}) + '\\n' self.sock.sendall(request.encode()) def",
"\"\"\" class EventRoute(Route): def handle(self, data, request): f_type, event =",
"if route in self.routes: self.routes[route].handle(data, self) else: log.error(\"Data received on",
"def recv(self): if self.recvbuf: # This needs special handling because",
"\"<data>\" } 'data' holds additional data which is then passed",
"self.recvbuf self.recvbuf = None else: yield self.recvbuf[:index] self.recvbuf = self.recvbuf[index+1:]",
"def run(self): self.setup() utils.create_thread(self.sync_worker, name=self.name.replace('request-handler', 'sync-worker')) while 1: buffer =",
"'\\n' self.sock.sendall(request.encode()) def recv(self): if self.recvbuf: # This needs special",
"# # The above copyright notice and this permission notice",
"action \\'{0}\\', igoring.', action) # If we are the 'server',",
"and is specific to each route. After each request there",
"action, path): self.sync_queue.put({ 'action': action + '-file', 'path': path })",
"in self.recv(): buffer += chunk if not len(buffer): break self.handle(buffer.decode())",
"not request.is_client: action = 'send' if action == 'receive' else",
"def setup(self): log.info('Connected to {0}:{1}', self.address[0], self.address[1]) # If self.client",
"in a text-based format, e.g. base-64 encoding for binary data.",
"data. After the payload, if any, there has to be",
"has a (active) socket, it is a client and #",
"buffer += chunk if not len(buffer): break self.handle(buffer.decode()) log.info('Disconnected from",
"in files: request.queue_file(f[0], f[1]) \"\"\" { \"action\": \"<action>\", \"path\": \"<relpath-to-file>\"",
"multiple # request in recvbuf. If this is the case,",
"{} self.recvbuf = b'' RequestHandler.req_handler_num += 1 self.name = \"request-handler-{0}\".format(RequestHandler.req_handler_num)",
"self.recvbuf[:index] self.recvbuf = self.recvbuf[index+1:] return while 1: select.select([self.sock], [], [])",
"and associated documentation files (the \"Software\"), to deal # in",
"Software without restriction, including without limitation the rights # to",
"self.routes: self.routes[route].handle(data, self) else: log.error(\"Data received on unknown route '{0}'!\",",
"and to permit persons to whom the Software is #",
"request.queue_event(e) for f in files: request.queue_file(f[0], f[1]) \"\"\" { \"action\":",
"class EventRoute(Route): def handle(self, data, request): f_type, event = data['type'].split('-')",
"else: log.warn('EventRoute: Unknown event {0}', data) # For rationale, see",
"copies of the Software, and to permit persons to whom",
"hereby granted, free of charge, to any person obtaining a",
"recv(self): if self.recvbuf: # This needs special handling because there",
"this permission notice shall be included in all # copies",
"request in recvbuf. If this is the case, we can",
"so ignore both. request.client._ignore_next_fsevent(path) request.client._ignore_next_fsevent(path) os.rename(tmpf.name, request.client._abspath(path)) request.client._update_metadata(path) request.client._event_handler._dispatch( 'received',",
"request): f_type, event = data['type'].split('-') path = data['path'] abspath =",
"setup(self): log.info('Connected to {0}:{1}', self.address[0], self.address[1]) # If self.client has",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE",
"distribute, sublicense, and/or sell # copies of the Software, and",
"route, data) if route in self.routes: self.routes[route].handle(data, self) else: log.error(\"Data",
"to leave to others in recvbuf. index = self.recvbuf.find(b'\\n') if",
"self.recvbuf = self.recvbuf[index+1:] return while 1: select.select([self.sock], [], []) chunk",
"# If select has signaled the socket is readable, yet",
"+= chunk if not len(buffer): break self.handle(buffer.decode()) log.info('Disconnected from {0}:{1}',",
"= data['route'] data = data['data'] log.info_v('Handling {0}, data:\\n{1}', route, data)",
"{0}', entry) if entry['action'] == 'exit': break elif entry['action'] ==",
"OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"request.client._abspath(path)) request.client._update_metadata(path) request.client._event_handler._dispatch( 'received', request.client, path, 'file' ) elif action",
"HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #",
"tmpf.write(base64.b64decode(buffer)) tmpf.close() # watchdog reports a file-deleted and a file-created",
"else: yield self.recvbuf[:index] self.recvbuf = self.recvbuf[index+1:] return while 1: select.select([self.sock],",
"to separate them. (think of HTTP) If a route needs",
"to {0}:{1}', self.address[0], self.address[1]) # If self.client has a (active)",
"self.send('file', { 'path': path, 'action': 'receive' }) for buf in",
"to the route. There is no special format designed for",
"= chunk.find(b'\\n') if index == -1: yield chunk else: yield",
"else: os.mkdir(abspath, 0o755) request.client._add_to_filelist(path, f_type) elif event == 'deleted': request.client._remove_from_filelist(path)",
"queue_event(self, event): self.sync_queue.put({ 'action': 'send-event', 'event': event }) def sync_worker(self):",
"import socket import queue import tempfile import base64 import select",
"request.queue_file('send', path) else: log.warn('FileRoute: Unknown action \\'{0}\\', igoring.', action) #",
"len(buffer) >= BLOCK_SIZE: tmpf.write(base64.b64decode(buffer[:BLOCK_SIZE])) buffer = buffer[:BLOCK_SIZE] tmpf.write(base64.b64decode(buffer)) tmpf.close() #",
"self.sync_queue.put({ 'action': 'send-event', 'event': event }) def sync_worker(self): while 1:",
"index = self.recvbuf.find(b'\\n') if index == -1: yield self.recvbuf self.recvbuf",
"the socket. break index = chunk.find(b'\\n') if index == -1:",
"from behem0th import utils, log BLOCK_SIZE = 4096 class Route:",
"OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH",
"return while 1: select.select([self.sock], [], []) chunk = self.sock.recv(1024) if",
"If we are the 'server', we also need to distribute",
"the server. self.client._rlock.acquire() self.send('filelist', self.client._filelist) def close(self): self.sync_queue.put({'action': 'exit'}) try:",
"deal # in the Software without restriction, including without limitation",
"{ 'filelist': FilelistRoute(), 'file': FileRoute(), 'event': EventRoute() } \"\"\" behem0th's",
"use, copy, modify, merge, publish, distribute, sublicense, and/or sell #",
"'path': path, 'action': 'receive' }) for buf in utils.read_file_seq(abspath, BLOCK_SIZE):",
"be included in all # copies or substantial portions of",
"f in files: request.queue_file(f[0], f[1]) \"\"\" { \"action\": \"<action>\", \"path\":",
"the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\",",
"the socket is readable, yet .recv() # returns zero bytes,",
"copy, modify, merge, publish, distribute, sublicense, and/or sell # copies",
"# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR",
"= route def setup(self): log.info('Connected to {0}:{1}', self.address[0], self.address[1]) #",
"special format designed for 'data' and is specific to each",
"= data['path'] if action == 'receive': tmpf = tempfile.NamedTemporaryFile(delete=False) buffer",
"path) \"\"\" { \"type\": \"<type>\", \"path\": \"<relpath-to-file>\" } <type> can",
"is a newline to separate them. (think of HTTP) If",
"yield the first # one and have to leave to",
"one and have to leave to others in recvbuf. index",
"format, e.g. base-64 encoding for binary data. After the payload,",
"if any, there has to be another newline to separate",
"\"path\": \"<relpath-to-file>\" } <type> can be one of 'file-created', 'file-deleted',",
"protocol is completely text-based, using utf-8 encoding and encoded in",
"+= 1 self.name = \"request-handler-{0}\".format(RequestHandler.req_handler_num) for key, value in kwargs.items():",
"index == -1: yield chunk else: yield chunk[:index] self.recvbuf =",
"software and associated documentation files (the \"Software\"), to deal #",
"action == 'receive' else 'request' request.client._run_on_peers('queue_file', request, action, path) \"\"\"",
"route in ROUTES.items(): route.route_name = name route.handler = self self.routes[name]",
"log.warn('EventRoute: Unknown event {0}', data) # For rationale, see FileRoute.handle()",
"with the server. if self.is_client: # Lock the client until",
"# a close() or shutdown() on the socket. break index",
"if entry['action'] == 'exit': break elif entry['action'] == 'send-file': path",
"watchdog reports a file-deleted and a file-created event, so ignore",
"events: request.queue_event(e) for f in files: request.queue_file(f[0], f[1]) \"\"\" {",
"# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF",
"SOFTWARE. # import os import json import struct import threading",
"AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR",
"the next request. \"\"\" class RequestHandler(threading.Thread): req_handler_num = 0 def",
"the Software without restriction, including without limitation the rights #",
"# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"route. After each request there is a newline to separate",
"{ 'path': entry['path'], 'action': 'send' }) elif entry['action'] == 'send-event':",
"self.address[1]) # If self.client has a (active) socket, it is",
"\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #",
"\"<relpath-to-file>\" } <type> can be one of 'file-created', 'file-deleted', 'file-moved'",
"request.is_client: request.client._filelist = data request.client._rlock.release() else: files, events = request.client._merge_filelist(data)",
"pass def handle(self, data): try: data = json.loads(data) except ValueError:",
"if event == 'created': # create the file/directory if f_type",
"name, route in ROUTES.items(): route.route_name = name route.handler = self",
"self.sync_queue = queue.Queue() self.routes = {} self.recvbuf = b'' RequestHandler.req_handler_num",
"self.sock.sendall(request.encode()) def recv(self): if self.recvbuf: # This needs special handling",
"name route.handler = self self.routes[name] = route def setup(self): log.info('Connected",
"others in recvbuf. index = self.recvbuf.find(b'\\n') if index == -1:",
"open(abspath, 'a').close() else: os.mkdir(abspath, 0o755) request.client._add_to_filelist(path, f_type) elif event ==",
"If select has signaled the socket is readable, yet .recv()",
"self.client has a (active) socket, it is a client and",
"with self.client._rlock: self.client._peers.append(self) self.sock.setblocking(0) self.is_client = bool(self.client._sock) for name, route",
"def close(self): self.sync_queue.put({'action': 'exit'}) try: self.sock.shutdown(socket.SHUT_RDWR) except OSError: pass def",
"base64 encoded chunks (BLOCK_SIZE bytes) \"\"\" class FileRoute(Route): def handle(self,",
"first # one and have to leave to others in",
".recv() # returns zero bytes, the other end probably performed",
"EventRoute(Route): def handle(self, data, request): f_type, event = data['type'].split('-') path",
"'data' and is specific to each route. After each request",
"recvbuf. If this is the case, we can only yield",
"route.route_name = name route.handler = self self.routes[name] = route def",
"log.error(\"Data received on unknown route '{0}'!\", route) def send(self, route,",
"== -1: yield self.recvbuf self.recvbuf = None else: yield self.recvbuf[:index]",
"BLOCK_SIZE = 4096 class Route: def handle(self, data, request): raise",
"rationale, see FileRoute.handle() if not request.is_client: request.client._run_on_peers('queue_event', request, data) ROUTES",
"included in all # copies or substantial portions of the",
"request usually looks like this: { \"route\": \"<route-name>\", \"data\": \"<data>\"",
"there is a newline to separate them. (think of HTTP)",
"# of this software and associated documentation files (the \"Software\"),",
"furnished to do so, subject to the following conditions: #",
"tmpf = tempfile.NamedTemporaryFile(delete=False) buffer = b'' for chunk in request.recv():",
"to do so, subject to the following conditions: # #",
"# The above copyright notice and this permission notice shall",
"self.recvbuf = b'' RequestHandler.req_handler_num += 1 self.name = \"request-handler-{0}\".format(RequestHandler.req_handler_num) for",
"data['data'] log.info_v('Handling {0}, data:\\n{1}', route, data) if route in self.routes:",
"SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR",
"def handle(self, data, request): f_type, event = data['type'].split('-') path =",
"a copy # of this software and associated documentation files",
"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF",
"self.is_client: # Lock the client until the filelist has been",
"= json.loads(data) except ValueError: log.error('Received invalid data: {0}', data) return",
"parsing. A request usually looks like this: { \"route\": \"<route-name>\",",
"not request.is_client: request.client._run_on_peers('queue_event', request, data) ROUTES = { 'filelist': FilelistRoute(),",
"self.setup() utils.create_thread(self.sync_worker, name=self.name.replace('request-handler', 'sync-worker')) while 1: buffer = b'' for",
"== 'exit': break elif entry['action'] == 'send-file': path = entry['path']",
"= data['action'] path = data['path'] if action == 'receive': tmpf",
"permission notice shall be included in all # copies or",
"2016 <NAME> <<EMAIL>> # # Permission is hereby granted, free",
"# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO",
"request.client._filelist = data request.client._rlock.release() else: files, events = request.client._merge_filelist(data) with",
"data = json.loads(data) except ValueError: log.error('Received invalid data: {0}', data)",
"except ValueError: log.error('Received invalid data: {0}', data) return route =",
"'sent', self.client, path, 'file' ) elif entry['action'] == 'request-file': self.send('file',",
"Client._handle_fsevent() and Client._merge_filelist() if event == 'created': # create the",
"IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"code with Client._handle_fsevent() and Client._merge_filelist() if event == 'created': #",
"NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE",
"'send' if action == 'receive' else 'request' request.client._run_on_peers('queue_file', request, action,",
"for f in files: request.queue_file(f[0], f[1]) \"\"\" { \"action\": \"<action>\",",
"'file': FileRoute(), 'event': EventRoute() } \"\"\" behem0th's protocol is completely",
"data): request = json.dumps({'route': route, 'data': data}) + '\\n' self.sock.sendall(request.encode())",
"self.client._rlock.acquire() self.send('filelist', self.client._filelist) def close(self): self.sync_queue.put({'action': 'exit'}) try: self.sock.shutdown(socket.SHUT_RDWR) except",
"case, we can only yield the first # one and",
"following conditions: # # The above copyright notice and this",
"class FilelistRoute(Route): def handle(self, data, request): if request.is_client: request.client._filelist =",
"to deal # in the Software without restriction, including without",
"chunk in self.recv(): buffer += chunk if not len(buffer): break",
"format designed for 'data' and is specific to each route.",
"self.name = \"request-handler-{0}\".format(RequestHandler.req_handler_num) for key, value in kwargs.items(): setattr(self, key,",
"event == 'deleted': request.client._remove_from_filelist(path) os.remove(abspath) elif event == 'moved': request.client._remove_from_filelist(path)",
"elif entry['action'] == 'request-file': self.send('file', { 'path': entry['path'], 'action': 'send'",
"conditions: # # The above copyright notice and this permission",
"'receive' else 'request' request.client._run_on_peers('queue_file', request, action, path) \"\"\" { \"type\":",
"# watchdog reports a file-deleted and a file-created event, so",
"tempfile import base64 import select from behem0th import utils, log",
"specific to each route. After each request there is a",
"SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #",
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
"else: log.error(\"Data received on unknown route '{0}'!\", route) def send(self,",
"+= chunk if len(buffer) >= BLOCK_SIZE: tmpf.write(base64.b64decode(buffer[:BLOCK_SIZE])) buffer = buffer[:BLOCK_SIZE]",
"IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS",
"if f_type == 'file': open(abspath, 'a').close() else: os.mkdir(abspath, 0o755) request.client._add_to_filelist(path,",
"[]) chunk = self.sock.recv(1024) if not len(chunk): # If select",
"route, data): request = json.dumps({'route': route, 'data': data}) + '\\n'",
"request.is_client: action = 'send' if action == 'receive' else 'request'",
"starts syncing up with the server. if self.is_client: # Lock",
"end probably performed # a close() or shutdown() on the",
"be either 'receive' or 'send' Payload are base64 encoded chunks",
") elif action == 'send': request.queue_file('send', path) else: log.warn('FileRoute: Unknown",
"break index = chunk.find(b'\\n') if index == -1: yield chunk",
"chunk[:index] self.recvbuf = chunk[index+1:] break def queue_file(self, action, path): self.sync_queue.put({",
"# If we are the 'server', we also need to",
"FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN",
"self.address[0], self.address[1]) # If self.client has a (active) socket, it",
"can be one of 'file-created', 'file-deleted', 'file-moved' \"\"\" class EventRoute(Route):",
"chunk = self.sock.recv(1024) if not len(chunk): # If select has",
"= { 'filelist': FilelistRoute(), 'file': FileRoute(), 'event': EventRoute() } \"\"\"",
"server. self.client._rlock.acquire() self.send('filelist', self.client._filelist) def close(self): self.sync_queue.put({'action': 'exit'}) try: self.sock.shutdown(socket.SHUT_RDWR)",
"request): action = data['action'] path = data['path'] if action ==",
"if request.is_client: request.client._filelist = data request.client._rlock.release() else: files, events =",
"abspath = request.client._abspath(path) request.client._ignore_next_fsevent(path) # TODO: factor out common code",
"handle(self, data): try: data = json.loads(data) except ValueError: log.error('Received invalid",
"}) def queue_event(self, event): self.sync_queue.put({ 'action': 'send-event', 'event': event })",
"key, value in kwargs.items(): setattr(self, key, value) with self.client._rlock: self.client._peers.append(self)",
"break def queue_file(self, action, path): self.sync_queue.put({ 'action': action + '-file',",
"self.sync_queue.put({ 'action': action + '-file', 'path': path }) def queue_event(self,",
"{ \"route\": \"<route-name>\", \"data\": \"<data>\" } 'data' holds additional data",
"(active) socket, it is a client and # thus needs",
"kwargs.items(): setattr(self, key, value) with self.client._rlock: self.client._peers.append(self) self.sock.setblocking(0) self.is_client =",
"clients. if not request.is_client: action = 'send' if action ==",
"request): if request.is_client: request.client._filelist = data request.client._rlock.release() else: files, events",
"path = entry['path'] abspath = self.client._abspath(path) self.send('file', { 'path': path,",
"After each request there is a newline to separate them.",
"route.handler = self self.routes[name] = route def setup(self): log.info('Connected to",
"'send' Payload are base64 encoded chunks (BLOCK_SIZE bytes) \"\"\" class",
"self.sock.recv(1024) if not len(chunk): # If select has signaled the",
"and/or sell # copies of the Software, and to permit",
"the client until the filelist has been sent back by",
"because there could be multiple # request in recvbuf. If",
"# Lock the client until the filelist has been sent",
"the rights # to use, copy, modify, merge, publish, distribute,",
"== 'send': request.queue_file('send', path) else: log.warn('FileRoute: Unknown action \\'{0}\\', igoring.',",
"and Client._merge_filelist() if event == 'created': # create the file/directory",
"a newline to separate them. (think of HTTP) If a",
"has been sent back by the server. self.client._rlock.acquire() self.send('filelist', self.client._filelist)",
"all # copies or substantial portions of the Software. #",
"to distribute all file request # to all other clients.",
"other clients. if not request.is_client: action = 'send' if action",
"elif entry['action'] == 'send-event': self.send('event', entry['event']) self.sync_queue.task_done() def run(self): self.setup()",
"\"\"\" behem0th's protocol is completely text-based, using utf-8 encoding and",
"encoding and encoded in JSON for easy parsing. A request",
"encoding for binary data. After the payload, if any, there",
"be multiple # request in recvbuf. If this is the",
"'send' }) elif entry['action'] == 'send-event': self.send('event', entry['event']) self.sync_queue.task_done() def",
"notice and this permission notice shall be included in all",
"to send them in a text-based format, e.g. base-64 encoding",
"while 1: buffer = b'' for chunk in self.recv(): buffer",
"is hereby granted, free of charge, to any person obtaining",
"import struct import threading import socket import queue import tempfile",
"NotImplementedError def send(self, data): self.handler.send(self.route_name, data) class FilelistRoute(Route): def handle(self,",
"like this: { \"route\": \"<route-name>\", \"data\": \"<data>\" } 'data' holds",
"ROUTES.items(): route.route_name = name route.handler = self self.routes[name] = route",
"each route. After each request there is a newline to",
"# This needs special handling because there could be multiple",
"request.client._merge_filelist(data) with request.client._rlock: self.send(request.client._filelist) for e in events: request.queue_event(e) for",
"additional data which is then passed to the route. There",
"separate it from the next request. \"\"\" class RequestHandler(threading.Thread): req_handler_num",
"'-file', 'path': path }) def queue_event(self, event): self.sync_queue.put({ 'action': 'send-event',",
"+ '-file', 'path': path }) def queue_event(self, event): self.sync_queue.put({ 'action':",
"'send-event': self.send('event', entry['event']) self.sync_queue.task_done() def run(self): self.setup() utils.create_thread(self.sync_worker, name=self.name.replace('request-handler', 'sync-worker'))",
"(a 'payload'), it has to send them in a text-based",
"value) with self.client._rlock: self.client._peers.append(self) self.sock.setblocking(0) self.is_client = bool(self.client._sock) for name,",
"= b'' for chunk in request.recv(): buffer += chunk if",
"invalid data: {0}', data) return route = data['route'] data =",
"log BLOCK_SIZE = 4096 class Route: def handle(self, data, request):",
"{0}', data) # For rationale, see FileRoute.handle() if not request.is_client:",
"\"<route-name>\", \"data\": \"<data>\" } 'data' holds additional data which is",
"text-based format, e.g. base-64 encoding for binary data. After the",
"self.client, path, 'file' ) elif entry['action'] == 'request-file': self.send('file', {",
"select has signaled the socket is readable, yet .recv() #",
"if index == -1: yield chunk else: yield chunk[:index] self.recvbuf",
"we are the 'server', we also need to distribute all",
"import tempfile import base64 import select from behem0th import utils,",
"Copyright (c) 2016 <NAME> <<EMAIL>> # # Permission is hereby",
"= b'' for chunk in self.recv(): buffer += chunk if",
"= name route.handler = self self.routes[name] = route def setup(self):",
"CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR",
"yield self.recvbuf[:index] self.recvbuf = self.recvbuf[index+1:] return while 1: select.select([self.sock], [],",
"OSError: pass def handle(self, data): try: data = json.loads(data) except",
"data, request): f_type, event = data['type'].split('-') path = data['path'] abspath",
"= data['path'] abspath = request.client._abspath(path) request.client._ignore_next_fsevent(path) # TODO: factor out",
"self.routes = {} self.recvbuf = b'' RequestHandler.req_handler_num += 1 self.name",
"= \"request-handler-{0}\".format(RequestHandler.req_handler_num) for key, value in kwargs.items(): setattr(self, key, value)",
"are the 'server', we also need to distribute all file",
"== 'receive' else 'request' request.client._run_on_peers('queue_file', request, action, path) \"\"\" {",
"person obtaining a copy # of this software and associated",
"# # Permission is hereby granted, free of charge, to",
"without restriction, including without limitation the rights # to use,",
"be another newline to separate it from the next request.",
"route, 'data': data}) + '\\n' self.sock.sendall(request.encode()) def recv(self): if self.recvbuf:",
"returns zero bytes, the other end probably performed # a",
"e in events: request.queue_event(e) for f in files: request.queue_file(f[0], f[1])",
"request. \"\"\" class RequestHandler(threading.Thread): req_handler_num = 0 def __init__(self, **kwargs):",
"client and # thus needs to starts syncing up with",
"to starts syncing up with the server. if self.is_client: #",
"subject to the following conditions: # # The above copyright",
"chunk.find(b'\\n') if index == -1: yield chunk else: yield chunk[:index]",
"send(self, data): self.handler.send(self.route_name, data) class FilelistRoute(Route): def handle(self, data, request):",
"{0}, data:\\n{1}', route, data) if route in self.routes: self.routes[route].handle(data, self)",
"'exit': break elif entry['action'] == 'send-file': path = entry['path'] abspath",
"\"<action>\", \"path\": \"<relpath-to-file>\" } <action> can be either 'receive' or",
"route = data['route'] data = data['data'] log.info_v('Handling {0}, data:\\n{1}', route,",
"all file request # to all other clients. if not",
"them in a text-based format, e.g. base-64 encoding for binary",
"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN",
"send(self, route, data): request = json.dumps({'route': route, 'data': data}) +",
"THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE",
"there has to be another newline to separate it from",
"'data' holds additional data which is then passed to the",
"has signaled the socket is readable, yet .recv() # returns",
"\"<type>\", \"path\": \"<relpath-to-file>\" } <type> can be one of 'file-created',",
"is a client and # thus needs to starts syncing",
"handle(self, data, request): f_type, event = data['type'].split('-') path = data['path']",
"server. if self.is_client: # Lock the client until the filelist",
"route '{0}'!\", route) def send(self, route, data): request = json.dumps({'route':",
"'deleted': request.client._remove_from_filelist(path) os.remove(abspath) elif event == 'moved': request.client._remove_from_filelist(path) os.rename(abspath, data['dest'])",
"readable, yet .recv() # returns zero bytes, the other end",
"request.client._remove_from_filelist(path) os.remove(abspath) elif event == 'moved': request.client._remove_from_filelist(path) os.rename(abspath, data['dest']) request.client._add_to_filelist(data['dest'],",
"or substantial portions of the Software. # # THE SOFTWARE",
"<NAME> <<EMAIL>> # # Permission is hereby granted, free of",
"buffer += chunk if len(buffer) >= BLOCK_SIZE: tmpf.write(base64.b64decode(buffer[:BLOCK_SIZE])) buffer =",
"path, 'action': 'receive' }) for buf in utils.read_file_seq(abspath, BLOCK_SIZE): self.sock.sendall(base64.b64encode(buf))",
"BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS",
"can be either 'receive' or 'send' Payload are base64 encoded",
"holds additional data which is then passed to the route.",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL",
"request.client._run_on_peers('queue_file', request, action, path) \"\"\" { \"type\": \"<type>\", \"path\": \"<relpath-to-file>\"",
"buffer = buffer[:BLOCK_SIZE] tmpf.write(base64.b64decode(buffer)) tmpf.close() # watchdog reports a file-deleted",
"True self.sync_queue = queue.Queue() self.routes = {} self.recvbuf = b''",
">= BLOCK_SIZE: tmpf.write(base64.b64decode(buffer[:BLOCK_SIZE])) buffer = buffer[:BLOCK_SIZE] tmpf.write(base64.b64decode(buffer)) tmpf.close() # watchdog",
"OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR",
"f_type, event = data['type'].split('-') path = data['path'] abspath = request.client._abspath(path)",
"action, path) \"\"\" { \"type\": \"<type>\", \"path\": \"<relpath-to-file>\" } <type>",
"has to be another newline to separate it from the",
"request.client._rlock: self.send(request.client._filelist) for e in events: request.queue_event(e) for f in",
"request.client._event_handler._dispatch( 'received', request.client, path, 'file' ) elif action == 'send':",
"-1: yield chunk else: yield chunk[:index] self.recvbuf = chunk[index+1:] break",
"on the socket. break index = chunk.find(b'\\n') if index ==",
"the server. if self.is_client: # Lock the client until the",
"CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS",
"BLOCK_SIZE): self.sock.sendall(base64.b64encode(buf)) self.sock.sendall(b'\\n') self.client._event_handler._dispatch( 'sent', self.client, path, 'file' ) elif",
"IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER",
"in self.routes: self.routes[route].handle(data, self) else: log.error(\"Data received on unknown route",
"CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION",
"the other end probably performed # a close() or shutdown()",
"# Permission is hereby granted, free of charge, to any",
"of charge, to any person obtaining a copy # of",
"f_type) else: log.warn('EventRoute: Unknown event {0}', data) # For rationale,",
"FileRoute(), 'event': EventRoute() } \"\"\" behem0th's protocol is completely text-based,",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #",
"merge, publish, distribute, sublicense, and/or sell # copies of the",
"to be another newline to separate it from the next",
"it is a client and # thus needs to starts",
"utils.read_file_seq(abspath, BLOCK_SIZE): self.sock.sendall(base64.b64encode(buf)) self.sock.sendall(b'\\n') self.client._event_handler._dispatch( 'sent', self.client, path, 'file' )",
"self.client._abspath(path) self.send('file', { 'path': path, 'action': 'receive' }) for buf",
"# # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY",
"There is no special format designed for 'data' and is",
"for buf in utils.read_file_seq(abspath, BLOCK_SIZE): self.sock.sendall(base64.b64encode(buf)) self.sock.sendall(b'\\n') self.client._event_handler._dispatch( 'sent', self.client,",
"os.rename(abspath, data['dest']) request.client._add_to_filelist(data['dest'], f_type) else: log.warn('EventRoute: Unknown event {0}', data)",
"NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT",
"event): self.sync_queue.put({ 'action': 'send-event', 'event': event }) def sync_worker(self): while",
"f_type == 'file': open(abspath, 'a').close() else: os.mkdir(abspath, 0o755) request.client._add_to_filelist(path, f_type)",
"OTHER DEALINGS IN THE # SOFTWARE. # import os import",
"a file-created event, so ignore both. request.client._ignore_next_fsevent(path) request.client._ignore_next_fsevent(path) os.rename(tmpf.name, request.client._abspath(path))",
"event {0}', data) # For rationale, see FileRoute.handle() if not",
"entry['path'], 'action': 'send' }) elif entry['action'] == 'send-event': self.send('event', entry['event'])",
"name=self.name.replace('request-handler', 'sync-worker')) while 1: buffer = b'' for chunk in",
"path = data['path'] abspath = request.client._abspath(path) request.client._ignore_next_fsevent(path) # TODO: factor",
"NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR",
"can only yield the first # one and have to",
"on unknown route '{0}'!\", route) def send(self, route, data): request",
"= request.client._merge_filelist(data) with request.client._rlock: self.send(request.client._filelist) for e in events: request.queue_event(e)",
"chunks (BLOCK_SIZE bytes) \"\"\" class FileRoute(Route): def handle(self, data, request):",
"'path': path }) def queue_event(self, event): self.sync_queue.put({ 'action': 'send-event', 'event':",
"import os import json import struct import threading import socket",
"yield chunk[:index] self.recvbuf = chunk[index+1:] break def queue_file(self, action, path):",
"self.recvbuf = None else: yield self.recvbuf[:index] self.recvbuf = self.recvbuf[index+1:] return",
"entry) if entry['action'] == 'exit': break elif entry['action'] == 'send-file':",
"request.client._update_metadata(path) request.client._event_handler._dispatch( 'received', request.client, path, 'file' ) elif action ==",
"value in kwargs.items(): setattr(self, key, value) with self.client._rlock: self.client._peers.append(self) self.sock.setblocking(0)",
"= 0 def __init__(self, **kwargs): super().__init__() self.daemon = True self.sync_queue",
"is completely text-based, using utf-8 encoding and encoded in JSON",
"yield self.recvbuf self.recvbuf = None else: yield self.recvbuf[:index] self.recvbuf =",
"request.client._abspath(path) request.client._ignore_next_fsevent(path) # TODO: factor out common code with Client._handle_fsevent()",
"select from behem0th import utils, log BLOCK_SIZE = 4096 class",
"ROUTES = { 'filelist': FilelistRoute(), 'file': FileRoute(), 'event': EventRoute() }",
"while 1: select.select([self.sock], [], []) chunk = self.sock.recv(1024) if not",
"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER",
"} <action> can be either 'receive' or 'send' Payload are",
"data) if route in self.routes: self.routes[route].handle(data, self) else: log.error(\"Data received",
"so, subject to the following conditions: # # The above",
"path, 'file' ) elif action == 'send': request.queue_file('send', path) else:",
"binary data. After the payload, if any, there has to",
"entry['path'] abspath = self.client._abspath(path) self.send('file', { 'path': path, 'action': 'receive'",
"request.client._run_on_peers('queue_event', request, data) ROUTES = { 'filelist': FilelistRoute(), 'file': FileRoute(),",
"and # thus needs to starts syncing up with the",
"req_handler_num = 0 def __init__(self, **kwargs): super().__init__() self.daemon = True",
"'send-file': path = entry['path'] abspath = self.client._abspath(path) self.send('file', { 'path':",
"'receive' }) for buf in utils.read_file_seq(abspath, BLOCK_SIZE): self.sock.sendall(base64.b64encode(buf)) self.sock.sendall(b'\\n') self.client._event_handler._dispatch(",
"if self.is_client: # Lock the client until the filelist has",
"for 'data' and is specific to each route. After each",
"AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #",
"== 'send-event': self.send('event', entry['event']) self.sync_queue.task_done() def run(self): self.setup() utils.create_thread(self.sync_worker, name=self.name.replace('request-handler',",
"import threading import socket import queue import tempfile import base64",
"chunk in request.recv(): buffer += chunk if len(buffer) >= BLOCK_SIZE:",
"DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF",
"completely text-based, using utf-8 encoding and encoded in JSON for",
"= None else: yield self.recvbuf[:index] self.recvbuf = self.recvbuf[index+1:] return while",
"'action': 'send' }) elif entry['action'] == 'send-event': self.send('event', entry['event']) self.sync_queue.task_done()",
"route needs to transfer additional data (a 'payload'), it has",
"if not request.is_client: action = 'send' if action == 'receive'",
"'payload'), it has to send them in a text-based format,",
"'request' request.client._run_on_peers('queue_file', request, action, path) \"\"\" { \"type\": \"<type>\", \"path\":",
"import utils, log BLOCK_SIZE = 4096 class Route: def handle(self,",
"1: buffer = b'' for chunk in self.recv(): buffer +=",
"if action == 'receive': tmpf = tempfile.NamedTemporaryFile(delete=False) buffer = b''",
"if index == -1: yield self.recvbuf self.recvbuf = None else:",
"\"path\": \"<relpath-to-file>\" } <action> can be either 'receive' or 'send'",
"events = request.client._merge_filelist(data) with request.client._rlock: self.send(request.client._filelist) for e in events:",
"== 'send-file': path = entry['path'] abspath = self.client._abspath(path) self.send('file', {",
"Unknown event {0}', data) # For rationale, see FileRoute.handle() if",
"Lock the client until the filelist has been sent back",
"f_type) elif event == 'deleted': request.client._remove_from_filelist(path) os.remove(abspath) elif event ==",
"route. There is no special format designed for 'data' and",
"the following conditions: # # The above copyright notice and",
"FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE",
"igoring.', action) # If we are the 'server', we also",
"os.mkdir(abspath, 0o755) request.client._add_to_filelist(path, f_type) elif event == 'deleted': request.client._remove_from_filelist(path) os.remove(abspath)",
"data): self.handler.send(self.route_name, data) class FilelistRoute(Route): def handle(self, data, request): if",
"EventRoute() } \"\"\" behem0th's protocol is completely text-based, using utf-8",
"base64 import select from behem0th import utils, log BLOCK_SIZE =",
"THE USE OR OTHER DEALINGS IN THE # SOFTWARE. #",
"== 'deleted': request.client._remove_from_filelist(path) os.remove(abspath) elif event == 'moved': request.client._remove_from_filelist(path) os.rename(abspath,",
"using utf-8 encoding and encoded in JSON for easy parsing.",
"designed for 'data' and is specific to each route. After",
"+ '\\n' self.sock.sendall(request.encode()) def recv(self): if self.recvbuf: # This needs",
"socket import queue import tempfile import base64 import select from",
"newline to separate it from the next request. \"\"\" class",
"file-created event, so ignore both. request.client._ignore_next_fsevent(path) request.client._ignore_next_fsevent(path) os.rename(tmpf.name, request.client._abspath(path)) request.client._update_metadata(path)",
"buffer[:BLOCK_SIZE] tmpf.write(base64.b64decode(buffer)) tmpf.close() # watchdog reports a file-deleted and a",
") elif entry['action'] == 'request-file': self.send('file', { 'path': entry['path'], 'action':",
"the Software, and to permit persons to whom the Software",
"close(self): self.sync_queue.put({'action': 'exit'}) try: self.sock.shutdown(socket.SHUT_RDWR) except OSError: pass def handle(self,",
"self.routes[route].handle(data, self) else: log.error(\"Data received on unknown route '{0}'!\", route)",
"'sync-worker')) while 1: buffer = b'' for chunk in self.recv():",
"file/directory if f_type == 'file': open(abspath, 'a').close() else: os.mkdir(abspath, 0o755)",
"buffer = b'' for chunk in request.recv(): buffer += chunk",
"queue import tempfile import base64 import select from behem0th import",
"bool(self.client._sock) for name, route in ROUTES.items(): route.route_name = name route.handler",
"def handle(self, data, request): action = data['action'] path = data['path']",
"if not request.is_client: request.client._run_on_peers('queue_event', request, data) ROUTES = { 'filelist':",
"it has to send them in a text-based format, e.g.",
"= 4096 class Route: def handle(self, data, request): raise NotImplementedError",
"out common code with Client._handle_fsevent() and Client._merge_filelist() if event ==",
"RequestHandler.req_handler_num += 1 self.name = \"request-handler-{0}\".format(RequestHandler.req_handler_num) for key, value in",
"with Client._handle_fsevent() and Client._merge_filelist() if event == 'created': # create",
"\"\"\" { \"type\": \"<type>\", \"path\": \"<relpath-to-file>\" } <type> can be",
"handle(self, data, request): action = data['action'] path = data['path'] if",
"ValueError: log.error('Received invalid data: {0}', data) return route = data['route']",
"self.send('filelist', self.client._filelist) def close(self): self.sync_queue.put({'action': 'exit'}) try: self.sock.shutdown(socket.SHUT_RDWR) except OSError:",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT",
"to transfer additional data (a 'payload'), it has to send",
"persons to whom the Software is # furnished to do",
"(BLOCK_SIZE bytes) \"\"\" class FileRoute(Route): def handle(self, data, request): action",
"action == 'receive': tmpf = tempfile.NamedTemporaryFile(delete=False) buffer = b'' for",
"def sync_worker(self): while 1: entry = self.sync_queue.get() log.info_v('Processing {0}', entry)",
"entry['event']) self.sync_queue.task_done() def run(self): self.setup() utils.create_thread(self.sync_worker, name=self.name.replace('request-handler', 'sync-worker')) while 1:",
"leave to others in recvbuf. index = self.recvbuf.find(b'\\n') if index",
"associated documentation files (the \"Software\"), to deal # in the",
"self self.routes[name] = route def setup(self): log.info('Connected to {0}:{1}', self.address[0],",
"entry['action'] == 'exit': break elif entry['action'] == 'send-file': path =",
"distribute all file request # to all other clients. if",
"needs special handling because there could be multiple # request",
"or shutdown() on the socket. break index = chunk.find(b'\\n') if",
"MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN",
"OR OTHER DEALINGS IN THE # SOFTWARE. # import os",
"utf-8 encoding and encoded in JSON for easy parsing. A",
"self.routes[name] = route def setup(self): log.info('Connected to {0}:{1}', self.address[0], self.address[1])",
"def __init__(self, **kwargs): super().__init__() self.daemon = True self.sync_queue = queue.Queue()",
"action) # If we are the 'server', we also need",
"Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT",
"for easy parsing. A request usually looks like this: {",
"to any person obtaining a copy # of this software",
"no special format designed for 'data' and is specific to",
"else 'request' request.client._run_on_peers('queue_file', request, action, path) \"\"\" { \"type\": \"<type>\",",
"request.queue_file(f[0], f[1]) \"\"\" { \"action\": \"<action>\", \"path\": \"<relpath-to-file>\" } <action>",
"self.recvbuf[index+1:] return while 1: select.select([self.sock], [], []) chunk = self.sock.recv(1024)",
"shutdown() on the socket. break index = chunk.find(b'\\n') if index",
"base-64 encoding for binary data. After the payload, if any,",
"json.loads(data) except ValueError: log.error('Received invalid data: {0}', data) return route",
"= buffer[:BLOCK_SIZE] tmpf.write(base64.b64decode(buffer)) tmpf.close() # watchdog reports a file-deleted and",
"there could be multiple # request in recvbuf. If this",
"a close() or shutdown() on the socket. break index =",
"in all # copies or substantial portions of the Software.",
"of the Software, and to permit persons to whom the",
"this software and associated documentation files (the \"Software\"), to deal",
"ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN",
"**kwargs): super().__init__() self.daemon = True self.sync_queue = queue.Queue() self.routes =",
"= data['type'].split('-') path = data['path'] abspath = request.client._abspath(path) request.client._ignore_next_fsevent(path) #",
"in JSON for easy parsing. A request usually looks like",
"= self.recvbuf[index+1:] return while 1: select.select([self.sock], [], []) chunk =",
"BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY,",
"# to all other clients. if not request.is_client: action =",
"log.info('Connected to {0}:{1}', self.address[0], self.address[1]) # If self.client has a",
"utils.create_thread(self.sync_worker, name=self.name.replace('request-handler', 'sync-worker')) while 1: buffer = b'' for chunk",
"== 'receive': tmpf = tempfile.NamedTemporaryFile(delete=False) buffer = b'' for chunk",
"signaled the socket is readable, yet .recv() # returns zero",
"raise NotImplementedError def send(self, data): self.handler.send(self.route_name, data) class FilelistRoute(Route): def",
"shall be included in all # copies or substantial portions",
"Software is # furnished to do so, subject to the",
"FilelistRoute(Route): def handle(self, data, request): if request.is_client: request.client._filelist = data",
"'file-created', 'file-deleted', 'file-moved' \"\"\" class EventRoute(Route): def handle(self, data, request):",
"threading import socket import queue import tempfile import base64 import",
"PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
"self.client._filelist) def close(self): self.sync_queue.put({'action': 'exit'}) try: self.sock.shutdown(socket.SHUT_RDWR) except OSError: pass",
"entry = self.sync_queue.get() log.info_v('Processing {0}', entry) if entry['action'] == 'exit':",
"self.sock.sendall(base64.b64encode(buf)) self.sock.sendall(b'\\n') self.client._event_handler._dispatch( 'sent', self.client, path, 'file' ) elif entry['action']",
"request.client, path, 'file' ) elif action == 'send': request.queue_file('send', path)",
"whom the Software is # furnished to do so, subject",
"sublicense, and/or sell # copies of the Software, and to",
"entry['action'] == 'send-event': self.send('event', entry['event']) self.sync_queue.task_done() def run(self): self.setup() utils.create_thread(self.sync_worker,",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY",
"__init__(self, **kwargs): super().__init__() self.daemon = True self.sync_queue = queue.Queue() self.routes",
"client until the filelist has been sent back by the",
"substantial portions of the Software. # # THE SOFTWARE IS",
"notice shall be included in all # copies or substantial",
"need to distribute all file request # to all other",
"request # to all other clients. if not request.is_client: action",
"f[1]) \"\"\" { \"action\": \"<action>\", \"path\": \"<relpath-to-file>\" } <action> can",
"def handle(self, data, request): if request.is_client: request.client._filelist = data request.client._rlock.release()",
"do so, subject to the following conditions: # # The",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING",
"request there is a newline to separate them. (think of",
"in the Software without restriction, including without limitation the rights",
"# request in recvbuf. If this is the case, we",
"behem0th's protocol is completely text-based, using utf-8 encoding and encoded",
"if len(buffer) >= BLOCK_SIZE: tmpf.write(base64.b64decode(buffer[:BLOCK_SIZE])) buffer = buffer[:BLOCK_SIZE] tmpf.write(base64.b64decode(buffer)) tmpf.close()",
"for name, route in ROUTES.items(): route.route_name = name route.handler =",
"socket is readable, yet .recv() # returns zero bytes, the",
"data request.client._rlock.release() else: files, events = request.client._merge_filelist(data) with request.client._rlock: self.send(request.client._filelist)",
"}) def sync_worker(self): while 1: entry = self.sync_queue.get() log.info_v('Processing {0}',",
"break elif entry['action'] == 'send-file': path = entry['path'] abspath =",
"self) else: log.error(\"Data received on unknown route '{0}'!\", route) def",
"# furnished to do so, subject to the following conditions:",
"try: self.sock.shutdown(socket.SHUT_RDWR) except OSError: pass def handle(self, data): try: data",
"any person obtaining a copy # of this software and",
"request.client._ignore_next_fsevent(path) # TODO: factor out common code with Client._handle_fsevent() and",
"ARISING FROM, # OUT OF OR IN CONNECTION WITH THE",
"run(self): self.setup() utils.create_thread(self.sync_worker, name=self.name.replace('request-handler', 'sync-worker')) while 1: buffer = b''",
"SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
"path) else: log.warn('FileRoute: Unknown action \\'{0}\\', igoring.', action) # If",
"action + '-file', 'path': path }) def queue_event(self, event): self.sync_queue.put({",
"route) def send(self, route, data): request = json.dumps({'route': route, 'data':",
"request.client._remove_from_filelist(path) os.rename(abspath, data['dest']) request.client._add_to_filelist(data['dest'], f_type) else: log.warn('EventRoute: Unknown event {0}',",
"queue.Queue() self.routes = {} self.recvbuf = b'' RequestHandler.req_handler_num += 1",
"in recvbuf. If this is the case, we can only",
"KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO",
"be one of 'file-created', 'file-deleted', 'file-moved' \"\"\" class EventRoute(Route): def",
"it from the next request. \"\"\" class RequestHandler(threading.Thread): req_handler_num =",
"path): self.sync_queue.put({ 'action': action + '-file', 'path': path }) def",
"OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"restriction, including without limitation the rights # to use, copy,",
"0o755) request.client._add_to_filelist(path, f_type) elif event == 'deleted': request.client._remove_from_filelist(path) os.remove(abspath) elif",
"-1: yield self.recvbuf self.recvbuf = None else: yield self.recvbuf[:index] self.recvbuf",
"if not len(buffer): break self.handle(buffer.decode()) log.info('Disconnected from {0}:{1}', self.address[0], self.address[1])",
"unknown route '{0}'!\", route) def send(self, route, data): request =",
"IN THE # SOFTWARE. # import os import json import",
"event, so ignore both. request.client._ignore_next_fsevent(path) request.client._ignore_next_fsevent(path) os.rename(tmpf.name, request.client._abspath(path)) request.client._update_metadata(path) request.client._event_handler._dispatch(",
"== 'moved': request.client._remove_from_filelist(path) os.rename(abspath, data['dest']) request.client._add_to_filelist(data['dest'], f_type) else: log.warn('EventRoute: Unknown",
"'action': 'receive' }) for buf in utils.read_file_seq(abspath, BLOCK_SIZE): self.sock.sendall(base64.b64encode(buf)) self.sock.sendall(b'\\n')",
"FileRoute(Route): def handle(self, data, request): action = data['action'] path =",
"'action': action + '-file', 'path': path }) def queue_event(self, event):",
"including without limitation the rights # to use, copy, modify,",
"'receive' or 'send' Payload are base64 encoded chunks (BLOCK_SIZE bytes)",
"them. (think of HTTP) If a route needs to transfer",
"HTTP) If a route needs to transfer additional data (a",
"copyright notice and this permission notice shall be included in",
"os.rename(tmpf.name, request.client._abspath(path)) request.client._update_metadata(path) request.client._event_handler._dispatch( 'received', request.client, path, 'file' ) elif",
"action == 'send': request.queue_file('send', path) else: log.warn('FileRoute: Unknown action \\'{0}\\',",
"filelist has been sent back by the server. self.client._rlock.acquire() self.send('filelist',",
"index = chunk.find(b'\\n') if index == -1: yield chunk else:",
"ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED",
"or 'send' Payload are base64 encoded chunks (BLOCK_SIZE bytes) \"\"\"",
"free of charge, to any person obtaining a copy #",
"\"request-handler-{0}\".format(RequestHandler.req_handler_num) for key, value in kwargs.items(): setattr(self, key, value) with",
"files (the \"Software\"), to deal # in the Software without",
"= entry['path'] abspath = self.client._abspath(path) self.send('file', { 'path': path, 'action':",
"= queue.Queue() self.routes = {} self.recvbuf = b'' RequestHandler.req_handler_num +=",
"data, request): raise NotImplementedError def send(self, data): self.handler.send(self.route_name, data) class",
"for chunk in request.recv(): buffer += chunk if len(buffer) >=",
"while 1: entry = self.sync_queue.get() log.info_v('Processing {0}', entry) if entry['action']",
"= 'send' if action == 'receive' else 'request' request.client._run_on_peers('queue_file', request,",
"# Copyright (c) 2016 <NAME> <<EMAIL>> # # Permission is",
"send them in a text-based format, e.g. base-64 encoding for",
"payload, if any, there has to be another newline to",
"data) return route = data['route'] data = data['data'] log.info_v('Handling {0},",
"in kwargs.items(): setattr(self, key, value) with self.client._rlock: self.client._peers.append(self) self.sock.setblocking(0) self.is_client",
"request.client._ignore_next_fsevent(path) request.client._ignore_next_fsevent(path) os.rename(tmpf.name, request.client._abspath(path)) request.client._update_metadata(path) request.client._event_handler._dispatch( 'received', request.client, path, 'file'",
"class FileRoute(Route): def handle(self, data, request): action = data['action'] path",
"the file/directory if f_type == 'file': open(abspath, 'a').close() else: os.mkdir(abspath,",
"# create the file/directory if f_type == 'file': open(abspath, 'a').close()",
"self.send(request.client._filelist) for e in events: request.queue_event(e) for f in files:",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
"common code with Client._handle_fsevent() and Client._merge_filelist() if event == 'created':",
"json import struct import threading import socket import queue import",
"\\'{0}\\', igoring.', action) # If we are the 'server', we",
"of the Software. # # THE SOFTWARE IS PROVIDED \"AS",
"elif event == 'moved': request.client._remove_from_filelist(path) os.rename(abspath, data['dest']) request.client._add_to_filelist(data['dest'], f_type) else:",
"data) ROUTES = { 'filelist': FilelistRoute(), 'file': FileRoute(), 'event': EventRoute()",
"self.sock.sendall(b'\\n') self.client._event_handler._dispatch( 'sent', self.client, path, 'file' ) elif entry['action'] ==",
"'send-event', 'event': event }) def sync_worker(self): while 1: entry =",
"= True self.sync_queue = queue.Queue() self.routes = {} self.recvbuf =",
"then passed to the route. There is no special format",
"'file': open(abspath, 'a').close() else: os.mkdir(abspath, 0o755) request.client._add_to_filelist(path, f_type) elif event",
"FilelistRoute(), 'file': FileRoute(), 'event': EventRoute() } \"\"\" behem0th's protocol is",
"data (a 'payload'), it has to send them in a",
"performed # a close() or shutdown() on the socket. break",
"other end probably performed # a close() or shutdown() on",
"'{0}'!\", route) def send(self, route, data): request = json.dumps({'route': route,",
"request, action, path) \"\"\" { \"type\": \"<type>\", \"path\": \"<relpath-to-file>\" }",
"files: request.queue_file(f[0], f[1]) \"\"\" { \"action\": \"<action>\", \"path\": \"<relpath-to-file>\" }",
"import base64 import select from behem0th import utils, log BLOCK_SIZE",
"[], []) chunk = self.sock.recv(1024) if not len(chunk): # If",
"buf in utils.read_file_seq(abspath, BLOCK_SIZE): self.sock.sendall(base64.b64encode(buf)) self.sock.sendall(b'\\n') self.client._event_handler._dispatch( 'sent', self.client, path,",
"both. request.client._ignore_next_fsevent(path) request.client._ignore_next_fsevent(path) os.rename(tmpf.name, request.client._abspath(path)) request.client._update_metadata(path) request.client._event_handler._dispatch( 'received', request.client, path,",
"chunk if len(buffer) >= BLOCK_SIZE: tmpf.write(base64.b64decode(buffer[:BLOCK_SIZE])) buffer = buffer[:BLOCK_SIZE] tmpf.write(base64.b64decode(buffer))",
"data['dest']) request.client._add_to_filelist(data['dest'], f_type) else: log.warn('EventRoute: Unknown event {0}', data) #",
"= request.client._abspath(path) request.client._ignore_next_fsevent(path) # TODO: factor out common code with",
"separate them. (think of HTTP) If a route needs to",
"which is then passed to the route. There is no",
"the payload, if any, there has to be another newline",
"for key, value in kwargs.items(): setattr(self, key, value) with self.client._rlock:",
"been sent back by the server. self.client._rlock.acquire() self.send('filelist', self.client._filelist) def",
"log.error('Received invalid data: {0}', data) return route = data['route'] data",
"data: {0}', data) return route = data['route'] data = data['data']",
"only yield the first # one and have to leave",
"# returns zero bytes, the other end probably performed #",
"sync_worker(self): while 1: entry = self.sync_queue.get() log.info_v('Processing {0}', entry) if",
"key, value) with self.client._rlock: self.client._peers.append(self) self.sock.setblocking(0) self.is_client = bool(self.client._sock) for",
"os import json import struct import threading import socket import",
"of this software and associated documentation files (the \"Software\"), to",
"OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR",
"OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE",
"data): try: data = json.loads(data) except ValueError: log.error('Received invalid data:",
"self.recv(): buffer += chunk if not len(buffer): break self.handle(buffer.decode()) log.info('Disconnected",
"{ \"action\": \"<action>\", \"path\": \"<relpath-to-file>\" } <action> can be either",
"= self.recvbuf.find(b'\\n') if index == -1: yield self.recvbuf self.recvbuf =",
"EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE",
"'send': request.queue_file('send', path) else: log.warn('FileRoute: Unknown action \\'{0}\\', igoring.', action)",
"self.recvbuf: # This needs special handling because there could be",
"in request.recv(): buffer += chunk if len(buffer) >= BLOCK_SIZE: tmpf.write(base64.b64decode(buffer[:BLOCK_SIZE]))",
"tmpf.close() # watchdog reports a file-deleted and a file-created event,",
"'a').close() else: os.mkdir(abspath, 0o755) request.client._add_to_filelist(path, f_type) elif event == 'deleted':",
"needs to starts syncing up with the server. if self.is_client:",
"= json.dumps({'route': route, 'data': data}) + '\\n' self.sock.sendall(request.encode()) def recv(self):",
"either 'receive' or 'send' Payload are base64 encoded chunks (BLOCK_SIZE",
"This needs special handling because there could be multiple #",
"except OSError: pass def handle(self, data): try: data = json.loads(data)",
"# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,",
"# If self.client has a (active) socket, it is a",
"request.client._add_to_filelist(path, f_type) elif event == 'deleted': request.client._remove_from_filelist(path) os.remove(abspath) elif event",
"PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS",
"# SOFTWARE. # import os import json import struct import",
"buffer = b'' for chunk in self.recv(): buffer += chunk",
"could be multiple # request in recvbuf. If this is",
"data = data['data'] log.info_v('Handling {0}, data:\\n{1}', route, data) if route",
"request.client._ignore_next_fsevent(path) os.rename(tmpf.name, request.client._abspath(path)) request.client._update_metadata(path) request.client._event_handler._dispatch( 'received', request.client, path, 'file' )",
"is specific to each route. After each request there is",
"(the \"Software\"), to deal # in the Software without restriction,",
"handle(self, data, request): if request.is_client: request.client._filelist = data request.client._rlock.release() else:",
"self.handler.send(self.route_name, data) class FilelistRoute(Route): def handle(self, data, request): if request.is_client:",
"<type> can be one of 'file-created', 'file-deleted', 'file-moved' \"\"\" class",
"request): raise NotImplementedError def send(self, data): self.handler.send(self.route_name, data) class FilelistRoute(Route):",
"data['type'].split('-') path = data['path'] abspath = request.client._abspath(path) request.client._ignore_next_fsevent(path) # TODO:",
"easy parsing. A request usually looks like this: { \"route\":",
"see FileRoute.handle() if not request.is_client: request.client._run_on_peers('queue_event', request, data) ROUTES =",
"each request there is a newline to separate them. (think",
"are base64 encoded chunks (BLOCK_SIZE bytes) \"\"\" class FileRoute(Route): def",
"the case, we can only yield the first # one",
"try: data = json.loads(data) except ValueError: log.error('Received invalid data: {0}',",
"bytes) \"\"\" class FileRoute(Route): def handle(self, data, request): action =",
"in ROUTES.items(): route.route_name = name route.handler = self self.routes[name] =",
"WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND",
"\"route\": \"<route-name>\", \"data\": \"<data>\" } 'data' holds additional data which",
"\"action\": \"<action>\", \"path\": \"<relpath-to-file>\" } <action> can be either 'receive'",
"data, request): action = data['action'] path = data['path'] if action",
"{0}', data) return route = data['route'] data = data['data'] log.info_v('Handling",
"charge, to any person obtaining a copy # of this",
"permit persons to whom the Software is # furnished to",
"} 'data' holds additional data which is then passed to",
"is the case, we can only yield the first #",
"THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE",
"files, events = request.client._merge_filelist(data) with request.client._rlock: self.send(request.client._filelist) for e in",
"\"\"\" class RequestHandler(threading.Thread): req_handler_num = 0 def __init__(self, **kwargs): super().__init__()",
"self.send('file', { 'path': entry['path'], 'action': 'send' }) elif entry['action'] ==",
"request.client._rlock.release() else: files, events = request.client._merge_filelist(data) with request.client._rlock: self.send(request.client._filelist) for",
"the Software is # furnished to do so, subject to",
"'received', request.client, path, 'file' ) elif action == 'send': request.queue_file('send',",
"to all other clients. if not request.is_client: action = 'send'",
"above copyright notice and this permission notice shall be included",
"IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED,",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",
"limitation the rights # to use, copy, modify, merge, publish,",
"self.recvbuf = chunk[index+1:] break def queue_file(self, action, path): self.sync_queue.put({ 'action':",
"from the next request. \"\"\" class RequestHandler(threading.Thread): req_handler_num = 0",
"If this is the case, we can only yield the",
"'data': data}) + '\\n' self.sock.sendall(request.encode()) def recv(self): if self.recvbuf: #",
"data['route'] data = data['data'] log.info_v('Handling {0}, data:\\n{1}', route, data) if",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #",
"(c) 2016 <NAME> <<EMAIL>> # # Permission is hereby granted,",
"factor out common code with Client._handle_fsevent() and Client._merge_filelist() if event",
"a client and # thus needs to starts syncing up",
"if not len(chunk): # If select has signaled the socket",
"def send(self, route, data): request = json.dumps({'route': route, 'data': data})",
"without limitation the rights # to use, copy, modify, merge,",
"this is the case, we can only yield the first",
"also need to distribute all file request # to all",
"= data['data'] log.info_v('Handling {0}, data:\\n{1}', route, data) if route in",
"# copies or substantial portions of the Software. # #",
"EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE",
"if action == 'receive' else 'request' request.client._run_on_peers('queue_file', request, action, path)",
"{0}:{1}', self.address[0], self.address[1]) # If self.client has a (active) socket,",
"'action': 'send-event', 'event': event }) def sync_worker(self): while 1: entry",
"reports a file-deleted and a file-created event, so ignore both.",
"USE OR OTHER DEALINGS IN THE # SOFTWARE. # import",
"# in the Software without restriction, including without limitation the",
"to separate it from the next request. \"\"\" class RequestHandler(threading.Thread):",
"documentation files (the \"Software\"), to deal # in the Software",
"newline to separate them. (think of HTTP) If a route",
"action = 'send' if action == 'receive' else 'request' request.client._run_on_peers('queue_file',",
"event = data['type'].split('-') path = data['path'] abspath = request.client._abspath(path) request.client._ignore_next_fsevent(path)",
"JSON for easy parsing. A request usually looks like this:",
"== 'request-file': self.send('file', { 'path': entry['path'], 'action': 'send' }) elif",
"copies or substantial portions of the Software. # # THE",
"data}) + '\\n' self.sock.sendall(request.encode()) def recv(self): if self.recvbuf: # This",
"data) class FilelistRoute(Route): def handle(self, data, request): if request.is_client: request.client._filelist",
"'filelist': FilelistRoute(), 'file': FileRoute(), 'event': EventRoute() } \"\"\" behem0th's protocol",
"= self self.routes[name] = route def setup(self): log.info('Connected to {0}:{1}',",
"chunk else: yield chunk[:index] self.recvbuf = chunk[index+1:] break def queue_file(self,",
"'file-deleted', 'file-moved' \"\"\" class EventRoute(Route): def handle(self, data, request): f_type,",
"next request. \"\"\" class RequestHandler(threading.Thread): req_handler_num = 0 def __init__(self,",
"with request.client._rlock: self.send(request.client._filelist) for e in events: request.queue_event(e) for f",
"entry['action'] == 'request-file': self.send('file', { 'path': entry['path'], 'action': 'send' })",
"{ \"type\": \"<type>\", \"path\": \"<relpath-to-file>\" } <type> can be one",
"'moved': request.client._remove_from_filelist(path) os.rename(abspath, data['dest']) request.client._add_to_filelist(data['dest'], f_type) else: log.warn('EventRoute: Unknown event",
"class RequestHandler(threading.Thread): req_handler_num = 0 def __init__(self, **kwargs): super().__init__() self.daemon",
"self.sync_queue.task_done() def run(self): self.setup() utils.create_thread(self.sync_worker, name=self.name.replace('request-handler', 'sync-worker')) while 1: buffer",
"to each route. After each request there is a newline",
"text-based, using utf-8 encoding and encoded in JSON for easy",
"Route: def handle(self, data, request): raise NotImplementedError def send(self, data):",
"ignore both. request.client._ignore_next_fsevent(path) request.client._ignore_next_fsevent(path) os.rename(tmpf.name, request.client._abspath(path)) request.client._update_metadata(path) request.client._event_handler._dispatch( 'received', request.client,",
"TODO: factor out common code with Client._handle_fsevent() and Client._merge_filelist() if",
"ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT",
"socket. break index = chunk.find(b'\\n') if index == -1: yield",
"sell # copies of the Software, and to permit persons",
"for e in events: request.queue_event(e) for f in files: request.queue_file(f[0],",
"DEALINGS IN THE # SOFTWARE. # import os import json",
"OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT",
"one of 'file-created', 'file-deleted', 'file-moved' \"\"\" class EventRoute(Route): def handle(self,",
"utils, log BLOCK_SIZE = 4096 class Route: def handle(self, data,",
"has to send them in a text-based format, e.g. base-64",
"BLOCK_SIZE: tmpf.write(base64.b64decode(buffer[:BLOCK_SIZE])) buffer = buffer[:BLOCK_SIZE] tmpf.write(base64.b64decode(buffer)) tmpf.close() # watchdog reports",
"for binary data. After the payload, if any, there has",
"and a file-created event, so ignore both. request.client._ignore_next_fsevent(path) request.client._ignore_next_fsevent(path) os.rename(tmpf.name,",
"encoded in JSON for easy parsing. A request usually looks",
"handle(self, data, request): raise NotImplementedError def send(self, data): self.handler.send(self.route_name, data)",
"OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT,",
"\"\"\" { \"action\": \"<action>\", \"path\": \"<relpath-to-file>\" } <action> can be",
"of HTTP) If a route needs to transfer additional data",
"= chunk[index+1:] break def queue_file(self, action, path): self.sync_queue.put({ 'action': action",
"def handle(self, data, request): raise NotImplementedError def send(self, data): self.handler.send(self.route_name,",
"publish, distribute, sublicense, and/or sell # copies of the Software,",
"data:\\n{1}', route, data) if route in self.routes: self.routes[route].handle(data, self) else:",
"== -1: yield chunk else: yield chunk[:index] self.recvbuf = chunk[index+1:]",
"self.client._event_handler._dispatch( 'sent', self.client, path, 'file' ) elif entry['action'] == 'request-file':",
"to the following conditions: # # The above copyright notice",
"\"type\": \"<type>\", \"path\": \"<relpath-to-file>\" } <type> can be one of",
"thus needs to starts syncing up with the server. if",
"needs to transfer additional data (a 'payload'), it has to",
"Client._merge_filelist() if event == 'created': # create the file/directory if",
"the first # one and have to leave to others",
"Payload are base64 encoded chunks (BLOCK_SIZE bytes) \"\"\" class FileRoute(Route):",
"handling because there could be multiple # request in recvbuf.",
"and this permission notice shall be included in all #",
"# TODO: factor out common code with Client._handle_fsevent() and Client._merge_filelist()",
"create the file/directory if f_type == 'file': open(abspath, 'a').close() else:",
"os.remove(abspath) elif event == 'moved': request.client._remove_from_filelist(path) os.rename(abspath, data['dest']) request.client._add_to_filelist(data['dest'], f_type)",
"'event': event }) def sync_worker(self): while 1: entry = self.sync_queue.get()",
"'request-file': self.send('file', { 'path': entry['path'], 'action': 'send' }) elif entry['action']",
"data which is then passed to the route. There is",
"If self.client has a (active) socket, it is a client",
"a (active) socket, it is a client and # thus",
"not len(buffer): break self.handle(buffer.decode()) log.info('Disconnected from {0}:{1}', self.address[0], self.address[1]) self.close()",
"len(chunk): # If select has signaled the socket is readable,",
"modify, merge, publish, distribute, sublicense, and/or sell # copies of",
"event == 'moved': request.client._remove_from_filelist(path) os.rename(abspath, data['dest']) request.client._add_to_filelist(data['dest'], f_type) else: log.warn('EventRoute:",
"(think of HTTP) If a route needs to transfer additional",
"self.sock.setblocking(0) self.is_client = bool(self.client._sock) for name, route in ROUTES.items(): route.route_name",
"by the server. self.client._rlock.acquire() self.send('filelist', self.client._filelist) def close(self): self.sync_queue.put({'action': 'exit'})",
"OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION",
"special handling because there could be multiple # request in",
"} \"\"\" behem0th's protocol is completely text-based, using utf-8 encoding",
"setattr(self, key, value) with self.client._rlock: self.client._peers.append(self) self.sock.setblocking(0) self.is_client = bool(self.client._sock)",
"FileRoute.handle() if not request.is_client: request.client._run_on_peers('queue_event', request, data) ROUTES = {",
"is readable, yet .recv() # returns zero bytes, the other",
"data) # For rationale, see FileRoute.handle() if not request.is_client: request.client._run_on_peers('queue_event',",
"IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"# import os import json import struct import threading import",
"and encoded in JSON for easy parsing. A request usually",
"until the filelist has been sent back by the server.",
"Software, and to permit persons to whom the Software is",
"json.dumps({'route': route, 'data': data}) + '\\n' self.sock.sendall(request.encode()) def recv(self): if",
"# to use, copy, modify, merge, publish, distribute, sublicense, and/or",
"After the payload, if any, there has to be another",
"} <type> can be one of 'file-created', 'file-deleted', 'file-moved' \"\"\"",
"# thus needs to starts syncing up with the server.",
"# For rationale, see FileRoute.handle() if not request.is_client: request.client._run_on_peers('queue_event', request,",
"OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT",
"1: entry = self.sync_queue.get() log.info_v('Processing {0}', entry) if entry['action'] ==",
"b'' for chunk in request.recv(): buffer += chunk if len(buffer)",
"elif event == 'deleted': request.client._remove_from_filelist(path) os.remove(abspath) elif event == 'moved':",
"self.sock.shutdown(socket.SHUT_RDWR) except OSError: pass def handle(self, data): try: data =",
"RequestHandler(threading.Thread): req_handler_num = 0 def __init__(self, **kwargs): super().__init__() self.daemon =",
"select.select([self.sock], [], []) chunk = self.sock.recv(1024) if not len(chunk): #",
"1 self.name = \"request-handler-{0}\".format(RequestHandler.req_handler_num) for key, value in kwargs.items(): setattr(self,",
"struct import threading import socket import queue import tempfile import",
"else: log.warn('FileRoute: Unknown action \\'{0}\\', igoring.', action) # If we",
"data['path'] abspath = request.client._abspath(path) request.client._ignore_next_fsevent(path) # TODO: factor out common",
"log.info_v('Processing {0}', entry) if entry['action'] == 'exit': break elif entry['action']",
"= data request.client._rlock.release() else: files, events = request.client._merge_filelist(data) with request.client._rlock:",
"<action> can be either 'receive' or 'send' Payload are base64",
"\"Software\"), to deal # in the Software without restriction, including",
"request, data) ROUTES = { 'filelist': FilelistRoute(), 'file': FileRoute(), 'event':",
"'event': EventRoute() } \"\"\" behem0th's protocol is completely text-based, using",
"log.info_v('Handling {0}, data:\\n{1}', route, data) if route in self.routes: self.routes[route].handle(data,",
"= self.sock.recv(1024) if not len(chunk): # If select has signaled",
"Unknown action \\'{0}\\', igoring.', action) # If we are the",
"}) for buf in utils.read_file_seq(abspath, BLOCK_SIZE): self.sock.sendall(base64.b64encode(buf)) self.sock.sendall(b'\\n') self.client._event_handler._dispatch( 'sent',",
"queue_file(self, action, path): self.sync_queue.put({ 'action': action + '-file', 'path': path",
"0 def __init__(self, **kwargs): super().__init__() self.daemon = True self.sync_queue =",
"# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR",
"chunk[index+1:] break def queue_file(self, action, path): self.sync_queue.put({ 'action': action +",
"file-deleted and a file-created event, so ignore both. request.client._ignore_next_fsevent(path) request.client._ignore_next_fsevent(path)",
"class Route: def handle(self, data, request): raise NotImplementedError def send(self,",
"log.warn('FileRoute: Unknown action \\'{0}\\', igoring.', action) # If we are",
"we also need to distribute all file request # to",
"= bool(self.client._sock) for name, route in ROUTES.items(): route.route_name = name",
"self.sync_queue.put({'action': 'exit'}) try: self.sock.shutdown(socket.SHUT_RDWR) except OSError: pass def handle(self, data):",
"COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"syncing up with the server. if self.is_client: # Lock the",
"index == -1: yield self.recvbuf self.recvbuf = None else: yield",
"import select from behem0th import utils, log BLOCK_SIZE = 4096",
"yield chunk else: yield chunk[:index] self.recvbuf = chunk[index+1:] break def",
"chunk if not len(buffer): break self.handle(buffer.decode()) log.info('Disconnected from {0}:{1}', self.address[0],",
"\"data\": \"<data>\" } 'data' holds additional data which is then",
"transfer additional data (a 'payload'), it has to send them",
"additional data (a 'payload'), it has to send them in",
"in utils.read_file_seq(abspath, BLOCK_SIZE): self.sock.sendall(base64.b64encode(buf)) self.sock.sendall(b'\\n') self.client._event_handler._dispatch( 'sent', self.client, path, 'file'",
"def handle(self, data): try: data = json.loads(data) except ValueError: log.error('Received",
"'file' ) elif action == 'send': request.queue_file('send', path) else: log.warn('FileRoute:",
"self.client._peers.append(self) self.sock.setblocking(0) self.is_client = bool(self.client._sock) for name, route in ROUTES.items():",
"usually looks like this: { \"route\": \"<route-name>\", \"data\": \"<data>\" }",
"# copies of the Software, and to permit persons to",
"e.g. base-64 encoding for binary data. After the payload, if",
"the 'server', we also need to distribute all file request",
"= b'' RequestHandler.req_handler_num += 1 self.name = \"request-handler-{0}\".format(RequestHandler.req_handler_num) for key,",
"request.recv(): buffer += chunk if len(buffer) >= BLOCK_SIZE: tmpf.write(base64.b64decode(buffer[:BLOCK_SIZE])) buffer",
"path, 'file' ) elif entry['action'] == 'request-file': self.send('file', { 'path':",
"def send(self, data): self.handler.send(self.route_name, data) class FilelistRoute(Route): def handle(self, data,",
"'server', we also need to distribute all file request #",
"in recvbuf. index = self.recvbuf.find(b'\\n') if index == -1: yield",
"def queue_event(self, event): self.sync_queue.put({ 'action': 'send-event', 'event': event }) def",
"granted, free of charge, to any person obtaining a copy",
"behem0th import utils, log BLOCK_SIZE = 4096 class Route: def",
"None else: yield self.recvbuf[:index] self.recvbuf = self.recvbuf[index+1:] return while 1:",
"file request # to all other clients. if not request.is_client:",
"}) elif entry['action'] == 'send-event': self.send('event', entry['event']) self.sync_queue.task_done() def run(self):",
"'path': entry['path'], 'action': 'send' }) elif entry['action'] == 'send-event': self.send('event',",
"obtaining a copy # of this software and associated documentation",
"received on unknown route '{0}'!\", route) def send(self, route, data):",
"TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN",
"is # furnished to do so, subject to the following",
"to whom the Software is # furnished to do so,",
"request.client._add_to_filelist(data['dest'], f_type) else: log.warn('EventRoute: Unknown event {0}', data) # For",
"copy # of this software and associated documentation files (the",
"tempfile.NamedTemporaryFile(delete=False) buffer = b'' for chunk in request.recv(): buffer +=",
"else: files, events = request.client._merge_filelist(data) with request.client._rlock: self.send(request.client._filelist) for e",
"self.client._rlock: self.client._peers.append(self) self.sock.setblocking(0) self.is_client = bool(self.client._sock) for name, route in",
"'file-moved' \"\"\" class EventRoute(Route): def handle(self, data, request): f_type, event",
"THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY",
"OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE.",
"Permission is hereby granted, free of charge, to any person",
"and have to leave to others in recvbuf. index =",
"encoded chunks (BLOCK_SIZE bytes) \"\"\" class FileRoute(Route): def handle(self, data,",
"import json import struct import threading import socket import queue",
"path = data['path'] if action == 'receive': tmpf = tempfile.NamedTemporaryFile(delete=False)",
"THE # SOFTWARE. # import os import json import struct",
"entry['action'] == 'send-file': path = entry['path'] abspath = self.client._abspath(path) self.send('file',",
"for chunk in self.recv(): buffer += chunk if not len(buffer):",
"= tempfile.NamedTemporaryFile(delete=False) buffer = b'' for chunk in request.recv(): buffer",
"close() or shutdown() on the socket. break index = chunk.find(b'\\n')",
"4096 class Route: def handle(self, data, request): raise NotImplementedError def",
"The above copyright notice and this permission notice shall be",
"elif entry['action'] == 'send-file': path = entry['path'] abspath = self.client._abspath(path)",
"A request usually looks like this: { \"route\": \"<route-name>\", \"data\":",
"another newline to separate it from the next request. \"\"\"",
"else: yield chunk[:index] self.recvbuf = chunk[index+1:] break def queue_file(self, action,",
"back by the server. self.client._rlock.acquire() self.send('filelist', self.client._filelist) def close(self): self.sync_queue.put({'action':",
"path }) def queue_event(self, event): self.sync_queue.put({ 'action': 'send-event', 'event': event",
"b'' RequestHandler.req_handler_num += 1 self.name = \"request-handler-{0}\".format(RequestHandler.req_handler_num) for key, value",
"import queue import tempfile import base64 import select from behem0th",
"data, request): if request.is_client: request.client._filelist = data request.client._rlock.release() else: files,",
"If a route needs to transfer additional data (a 'payload'),",
"route in self.routes: self.routes[route].handle(data, self) else: log.error(\"Data received on unknown",
"to others in recvbuf. index = self.recvbuf.find(b'\\n') if index ==",
"<<EMAIL>> # # Permission is hereby granted, free of charge,",
"passed to the route. There is no special format designed",
"def queue_file(self, action, path): self.sync_queue.put({ 'action': action + '-file', 'path':",
"of 'file-created', 'file-deleted', 'file-moved' \"\"\" class EventRoute(Route): def handle(self, data,",
"self.recvbuf.find(b'\\n') if index == -1: yield self.recvbuf self.recvbuf = None",
"== 'created': # create the file/directory if f_type == 'file':",
"'file' ) elif entry['action'] == 'request-file': self.send('file', { 'path': entry['path'],",
"WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT",
"tmpf.write(base64.b64decode(buffer[:BLOCK_SIZE])) buffer = buffer[:BLOCK_SIZE] tmpf.write(base64.b64decode(buffer)) tmpf.close() # watchdog reports a",
"self.sync_queue.get() log.info_v('Processing {0}', entry) if entry['action'] == 'exit': break elif",
"is then passed to the route. There is no special",
"= self.sync_queue.get() log.info_v('Processing {0}', entry) if entry['action'] == 'exit': break",
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES",
"== 'file': open(abspath, 'a').close() else: os.mkdir(abspath, 0o755) request.client._add_to_filelist(path, f_type) elif",
"data['action'] path = data['path'] if action == 'receive': tmpf =",
"if self.recvbuf: # This needs special handling because there could",
"yet .recv() # returns zero bytes, the other end probably",
"data['path'] if action == 'receive': tmpf = tempfile.NamedTemporaryFile(delete=False) buffer =",
"to permit persons to whom the Software is # furnished",
"WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING",
"event }) def sync_worker(self): while 1: entry = self.sync_queue.get() log.info_v('Processing"
] |
[
"np.array([1, 2, 3, 4, 5, 6, 7, 8]) accl =",
"2, 3, 4, 5, 6, 7, 8]) accl = classification_accuracy(true,",
"hover.utils.metrics import classification_accuracy import numpy as np def test_classification_accuracy(): true",
"7, 8]) accl = classification_accuracy(true, pred) accr = classification_accuracy(pred, true)",
"= classification_accuracy(true, pred) accr = classification_accuracy(pred, true) assert np.allclose(accl, 7/8)",
"4, 5, 6, 7, 8]) accl = classification_accuracy(true, pred) accr",
"2, 3, 4, 5, 6, 7, 7]) pred = np.array([1,",
"6, 7, 8]) accl = classification_accuracy(true, pred) accr = classification_accuracy(pred,",
"def test_classification_accuracy(): true = np.array([1, 2, 3, 4, 5, 6,",
"true = np.array([1, 2, 3, 4, 5, 6, 7, 7])",
"classification_accuracy(true, pred) accr = classification_accuracy(pred, true) assert np.allclose(accl, 7/8) assert",
"3, 4, 5, 6, 7, 8]) accl = classification_accuracy(true, pred)",
"5, 6, 7, 7]) pred = np.array([1, 2, 3, 4,",
"import numpy as np def test_classification_accuracy(): true = np.array([1, 2,",
"pred) accr = classification_accuracy(pred, true) assert np.allclose(accl, 7/8) assert np.allclose(accr,",
"as np def test_classification_accuracy(): true = np.array([1, 2, 3, 4,",
"= np.array([1, 2, 3, 4, 5, 6, 7, 8]) accl",
"8]) accl = classification_accuracy(true, pred) accr = classification_accuracy(pred, true) assert",
"accr = classification_accuracy(pred, true) assert np.allclose(accl, 7/8) assert np.allclose(accr, 7/8)",
"5, 6, 7, 8]) accl = classification_accuracy(true, pred) accr =",
"pred = np.array([1, 2, 3, 4, 5, 6, 7, 8])",
"4, 5, 6, 7, 7]) pred = np.array([1, 2, 3,",
"numpy as np def test_classification_accuracy(): true = np.array([1, 2, 3,",
"import classification_accuracy import numpy as np def test_classification_accuracy(): true =",
"accl = classification_accuracy(true, pred) accr = classification_accuracy(pred, true) assert np.allclose(accl,",
"7]) pred = np.array([1, 2, 3, 4, 5, 6, 7,",
"6, 7, 7]) pred = np.array([1, 2, 3, 4, 5,",
"test_classification_accuracy(): true = np.array([1, 2, 3, 4, 5, 6, 7,",
"= np.array([1, 2, 3, 4, 5, 6, 7, 7]) pred",
"np def test_classification_accuracy(): true = np.array([1, 2, 3, 4, 5,",
"from hover.utils.metrics import classification_accuracy import numpy as np def test_classification_accuracy():",
"7, 7]) pred = np.array([1, 2, 3, 4, 5, 6,",
"<filename>tests/utils/test_metrics.py<gh_stars>100-1000 from hover.utils.metrics import classification_accuracy import numpy as np def",
"classification_accuracy import numpy as np def test_classification_accuracy(): true = np.array([1,",
"np.array([1, 2, 3, 4, 5, 6, 7, 7]) pred =",
"3, 4, 5, 6, 7, 7]) pred = np.array([1, 2,"
] |
[
"= build_date self.no_release = no_release def build_package(self): print(\"Building package:\") print(\"\")",
"if f.endswith(\".oso\"): shutil.copy(os.path.join(root, f), target_dir) def download_settings_files(self): progress(\"Downloading settings files",
"LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A",
"self.this_dir = os.path.dirname(os.path.realpath(__file__)) self.root_dir = os.path.join(self.this_dir, \"..\") print(\"Loading settings from",
"\" + self.appleseed_lib_path) print(\" Path to appleseed shaders: \" +",
"filename) self.__change_library_paths_in_binary(exe_path) # Can be used on executables and dynamic",
"self.platform) print(\" Path to appleseed release: \" + self.appleseed_release_path) print(\"",
"dependency {0} as {1}\".format(lib, candidate)) lib = candidate libs.add(lib) if",
"\".gitignore\")) def copy_shaders(self): progress(\"Copying shaders to root directory\") # Create",
"\"appleseed\", \"lib\", \"appleseed\", \"_appleseedpython3.so\")) all_libs = all_libs.union(appleseedpython_libs) # Get shared",
"\"libfontconfig\", \"libutil\", \"libpython\", \"libxshmfence.so\" ] def plugin_extension(self): return \".so\" def",
"to fix them. if fix_paths: for lib in libs: if",
"in order to replace it by the correct one. for",
"args.nozip package_version = subprocess.Popen(\"git describe --long\", stdout=subprocess.PIPE, shell=True).stdout.read().strip() build_date =",
"+ SETTINGS_FILENAME + \"...\") tree = ElementTree() try: tree.parse(SETTINGS_FILENAME) except",
"directory: \" + self.output_dir) print(\"\") def __load_values(self, tree): self.platform =",
"\"appleseed_schemas_path\")) self.appleseed_settings_path = os.path.expandvars(self.__get_required(tree, \"appleseed_settings_path\")) self.appleseed_python_path = os.path.expandvars(self.__get_required(tree, \"appleseed_python_path\")) self.maketx_path",
"= args.nozip package_version = subprocess.Popen(\"git describe --long\", stdout=subprocess.PIPE, shell=True).stdout.read().strip() build_date",
"delete directory '\" + path + \"'\") def safe_delete_directory_recursively(root_path, directory_name):",
"def __fixup_binaries(self): progress(\"Mac-specific: Fixing up binaries\") self.set_libraries_ids() self.__change_library_paths_in_libraries() self.__change_library_paths_in_executables() def",
"lib in [\"libappleseed.dylib\", \"libappleseed.shared.dylib\"]: shutil.copy(os.path.join(self.settings.appleseed_lib_path, lib), lib_dir) # Get shared",
"\\$ORIGIN/../ \" + py_cpp_module) def __is_system_lib(self, lib): for prefix in",
"no_release) elif os.name == \"posix\" and platform.mac_ver()[0] == \"\": package_builder",
"\"appleseed\", \"bin\", \"*\")): libs = self.__get_dependencies_for_file(bin) all_libs = all_libs.union(libs) #",
"builder. #-------------------------------------------------------------------------------------------------- class MacPackageBuilder(PackageBuilder): SYSTEM_LIBS_PREFIXES = [ \"/System/Library/\", \"/usr/lib/libcurl\", \"/usr/lib/libc++\",",
"permission notice shall be included in # all copies or",
"if returncode != 0: fatal(\"Failed to invoke ldd(1) to get",
"libraries. for lib in all_libs: shutil.copy(lib, lib_dir) def post_process_package(self): progress(\"Linux-specific:",
"configuration file '\" + SETTINGS_FILENAME + \"'\") self.__load_values(tree) def print_summary(self):",
"line: continue libs.add(line.split()[2]) return libs #-------------------------------------------------------------------------------------------------- # Entry point. #--------------------------------------------------------------------------------------------------",
"def __change_library_paths_in_executables(self): bin_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"bin\") for dirpath, dirnames,",
"{1}\".format(filepath, err)) libs = set() for line in out.split(\"\\n\")[1:]: #",
"#-------------------------------------------------------------------------------------------------- # Base package builder. #-------------------------------------------------------------------------------------------------- class PackageBuilder(object): def __init__(self,",
"portions of the Software. # # THE SOFTWARE IS PROVIDED",
"__get_required(self, tree, key): value = tree.findtext(key) if value is None:",
"first line line = line.strip() # Ignore empty lines. if",
"#-------------------------------------------------------------------------------------------------- # Linux package builder. #-------------------------------------------------------------------------------------------------- class LinuxPackageBuilder(PackageBuilder): SYSTEM_LIBS_PREFIXES =",
"archive_util, dir_util from xml.etree.ElementTree import ElementTree import argparse import colorama",
"trace(u\" {0} {1}\".format(GREEN_CHECKMARK, lib)) else: trace(u\" {0} {1}\".format(RED_CROSSMARK, lib)) #",
"libs: if not os.path.isfile(lib): fatal(\"Dependency {0} could not be found",
"set to\") trace(\" {0}\".format(loader_path)) trace(\"and @rpath hardcoded to\") trace(\" {0}\".format(rpath))",
"dependencies if we didn't attempt to fix them. if fix_paths:",
"appleseed.python to root directory\") # Create destination directory. lib_dir =",
"err = self.run_subprocess([\"ldd\", filepath]) if returncode != 0: fatal(\"Failed to",
"\"README.md\"]: safe_delete_file(os.path.join(\"blenderseed\", file)) def build_final_zip_file(self): progress(\"Building final zip file from",
"Software without restriction, including without limitation the rights # to",
"cmdline): p = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate()",
"Get shared libs needed by libraries. lib_libs = set() for",
"= lib_libs.union(libs) all_libs = all_libs.union(lib_libs) # Copy all shared libraries.",
"\"blenderseed\") info(\"Package path: {0}\".format(package_path + \".zip\")) def remove_stage(self): progress(\"Deleting staging",
"urllib #-------------------------------------------------------------------------------------------------- # Constants. #-------------------------------------------------------------------------------------------------- VERSION = \"1.1.0\" SETTINGS_FILENAME =",
"\" + lib) appleseed_python_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\", \"appleseed\") for",
"trace(\" Dependencies:\") for lib in all_libs: trace(\" {0}\".format(lib)) # Copy",
"distribute, sublicense, and/or sell # copies of the Software, and",
"def __change_library_path(self, target, old, new): self.run('install_name_tool -change \"{0}\" \"{1}\" {2}'.format(old,",
"needed by appleseed.python. appleseedpython_libs = self.__get_dependencies_for_file( os.path.join(self.settings.root_dir, \"appleseed\", \"lib\", \"appleseed\",",
"package builder. #-------------------------------------------------------------------------------------------------- class PackageBuilder(object): def __init__(self, settings, package_version, build_date,",
"HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #",
"\".dylib\" or ext == \".so\": lib_path = os.path.join(dirpath, filename) self.__change_library_paths_in_binary(lib_path)",
"included in # all copies or substantial portions of the",
"invoke otool(1) to get dependencies for {0}: {1}\".format(filepath, err)) libs",
"frameworks. if re.search(r\"Qt.*\\.framework\", lib): continue if fix_paths: # Handle libs",
"for dll in [\"appleseed.dll\", \"appleseed.shared.dll\"]: shutil.copy(os.path.join(bin_dir, dll), os.path.join(self.settings.root_dir, \"appleseed\", \"bin\"))",
"for filename in filenames: ext = os.path.splitext(filename)[1] if ext !=",
"shaders to root directory\") # Create destination directory. shaders_dir =",
"lib in all_libs: libs = self.__get_dependencies_for_file(lib) lib_libs = lib_libs.union(libs) all_libs",
"Base package builder. #-------------------------------------------------------------------------------------------------- class PackageBuilder(object): def __init__(self, settings, package_version,",
"0: fatal(\"Failed to invoke otool(1) to get dependencies for {0}:",
"else: fatal(\"Failed to delete directory '\" + path + \"'\")",
"removed. # Let's just assume that it's read-only and unlink",
"path: {0}\".format(package_path + \".zip\")) def remove_stage(self): progress(\"Deleting staging directory\") safe_delete_directory(\"blenderseed\")",
"exc_info): # path contains the path of the file that",
"fatal(\"Dependency {0} could not be found on disk\".format(lib)) return libs",
"os.path.isabs(lib): # TODO: generalize to a collection of user-specified search",
"\"/lib64/ld-linux-\", \"libstdc++\", \"libxcb\", \"libdrm\", \"libnsl\", \"libuuid\", \"libgthread\", \"libglib\", \"libgobject\", \"libglapi\",",
"+ \"'\") def on_rmtree_error(func, path, exc_info): # path contains the",
"\\$ORIGIN/../lib \" + bin) for lib in glob.glob(os.path.join(self.settings.root_dir, \"appleseed\", \"lib\",",
"glob.glob(os.path.join(self.settings.root_dir, \"appleseed\", \"lib\", \"*.so\")): self.run(\"chrpath -d \" + lib) appleseed_python_dir",
"the MIT license. # # Copyright (c) 2017-2018 <NAME>, The",
"file\".format(key)) return value #-------------------------------------------------------------------------------------------------- # Base package builder. #-------------------------------------------------------------------------------------------------- class",
"= os.path.join(self.settings.output_dir, package_name) archive_util.make_zipfile(package_path, \"blenderseed\") info(\"Package path: {0}\".format(package_path + \".zip\"))",
"\".exe\" if os.name == \"nt\" else filepath def safe_delete_file(path): try:",
"directory. lib_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") safe_make_directory(lib_dir) # Copy appleseed.python.",
"fatal(\"Failed to parse line from otool(1) output: \" + line)",
"\"appleseed_release_path\") os.environ['APPLESEED'] = self.appleseed_release_path self.appleseed_bin_path = os.path.expandvars(self.__get_required(tree, \"appleseed_bin_path\")) self.appleseed_lib_path =",
"Linux package builder. #-------------------------------------------------------------------------------------------------- class LinuxPackageBuilder(PackageBuilder): SYSTEM_LIBS_PREFIXES = [ \"linux\",",
"\"/usr/lib/libncurses\", \"/usr/lib/libobjc.A.dylib\" ] def copy_dependencies(self): progress(\"Mac-specific: Copying dependencies\") # Create",
"filenames: ext = os.path.splitext(filename)[1] if ext == \".dylib\" or ext",
"#-------------------------------------------------------------------------------------------------- VERSION = \"1.1.0\" SETTINGS_FILENAME = \"blenderseed.package.configuration.xml\" #-------------------------------------------------------------------------------------------------- # Utility",
"__future__ import print_function from distutils import archive_util, dir_util from xml.etree.ElementTree",
"True return False #-------------------------------------------------------------------------------------------------- # Linux package builder. #-------------------------------------------------------------------------------------------------- class",
"filenames in os.walk(bin_dir): for filename in filenames: ext = os.path.splitext(filename)[1]",
"package_path = os.path.join(self.settings.output_dir, package_name) archive_util.make_zipfile(package_path, \"blenderseed\") info(\"Package path: {0}\".format(package_path +",
"these happen?). if lib == filename: continue # Ignore system",
"== \"nt\": package_builder = WindowsPackageBuilder(settings, package_version, build_date, no_release) elif os.name",
"\"docs\", \"scripts\", \"tests\"]: safe_delete_directory(os.path.join(\"blenderseed\", subdirectory)) for file in [\".gitignore\", \"README.md\"]:",
"!= \".conf\": exe_path = os.path.join(dirpath, filename) self.__change_library_paths_in_binary(exe_path) # Can be",
"# encode('utf-8') is required to support output redirection to files",
"hardcoded to\") trace(\" {0}\".format(rpath)) returncode, out, err = self.run_subprocess([\"otool\", \"-L\",",
"argparse.ArgumentParser(description=\"build a blenderseed package from sources\") parser.add_argument(\"--nozip\", action=\"store_true\", help=\"copies appleseed",
"\"__pycache__\") for subdirectory in [\".git\", \".idea\", \"archives\", \"docs\", \"scripts\", \"tests\"]:",
"libraries. def __change_library_paths_in_binary(self, bin_path): progress(\"Patching {0}\".format(bin_path)) bin_dir = os.path.dirname(bin_path) lib_dir",
"filepath def safe_delete_file(path): try: if os.path.exists(path): os.remove(path) except OSError: fatal(\"Failed",
"safe_delete_directory_recursively(subdirectory, directory_name) def safe_make_directory(path): if not os.path.isdir(path): os.makedirs(path) def pushd(path):",
"\"-L\", filepath]) if returncode != 0: fatal(\"Failed to invoke otool(1)",
"m.group(1) # Ignore self-references (why do these happen?). if lib",
"progress(\"Mac-specific: Post-processing package\") self.__fixup_binaries() def __fixup_binaries(self): progress(\"Mac-specific: Fixing up binaries\")",
"main(): colorama.init() parser = argparse.ArgumentParser(description=\"build a blenderseed package from sources\")",
"a copy # of this software and associated documentation files",
"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF",
"except OSError: if attempt < Attempts - 1: time.sleep(0.5) else:",
"\"..\") print(\"Loading settings from \" + SETTINGS_FILENAME + \"...\") tree",
"self.appleseed_lib_path = os.path.expandvars(self.__get_required(tree, \"appleseed_lib_path\")) self.appleseed_shaders_path = os.path.expandvars(self.__get_required(tree, \"appleseed_shaders_path\")) self.appleseed_schemas_path =",
"target, name): self.run('install_name_tool -id \"{0}\" {1}'.format(name, target)) def __change_library_path(self, target,",
"in os.listdir(root_path): subdirectory = os.path.join(root_path, entry) if os.path.isdir(subdirectory): safe_delete_directory_recursively(subdirectory, directory_name)",
"\"appleseed\", \"_appleseedpython.so\")) safe_delete_file(os.path.join(lib_dir, \"appleseed\", \"_appleseedpython.pyd\")) def copy_binaries(self): progress(\"Copying binaries to",
"needed by binaries. all_libs = set() for bin in glob.glob(os.path.join(self.settings.root_dir,",
"notice shall be included in # all copies or substantial",
"{0}{1}{2}\".format(colorama.Style.DIM + colorama.Fore.WHITE, message, colorama.Style.RESET_ALL).encode('utf-8')) def info(message): print(u\" {0}\".format(message).encode('utf-8')) def",
"== \".\": self.__change_library_path(bin_path, lib_path, \"@loader_path/{0}\".format(lib_name)) else: self.__change_library_path(bin_path, lib_path, \"@loader_path/{0}/{1}\".format(path_to_appleseed_lib, lib_name))",
"for prefix in self.SYSTEM_LIBS_PREFIXES: if lib.startswith(prefix): return True return False",
"\"'\") def safe_delete_directory_recursively(root_path, directory_name): safe_delete_directory(os.path.join(root_path, directory_name)) for entry in os.listdir(root_path):",
"settings.print_summary() if os.name == \"nt\": package_builder = WindowsPackageBuilder(settings, package_version, build_date,",
"and this permission notice shall be included in # all",
"\"nt\": package_builder = WindowsPackageBuilder(settings, package_version, build_date, no_release) elif os.name ==",
"trace(\"Dependencies for file {0}:\".format(filepath)) for lib in libs: if os.path.isfile(lib):",
"= os.path.basename(filepath) loader_path = os.path.dirname(filepath) rpath = \"/usr/local/lib/\" # TODO:",
"if not os.path.isfile(lib): fatal(\"Dependency {0} could not be found on",
"self.no_release: self.deploy_blenderseed_to_stage() self.clean_stage() self.build_final_zip_file() self.remove_stage() def remove_leftovers(self): progress(\"Removing leftovers from",
"directory_name) def safe_make_directory(path): if not os.path.isdir(path): os.makedirs(path) def pushd(path): old_path",
"os.path.expandvars(self.__get_required(tree, \"appleseed_settings_path\")) self.appleseed_python_path = os.path.expandvars(self.__get_required(tree, \"appleseed_python_path\")) self.maketx_path = os.path.expandvars(self.__get_required(tree, \"maketx_path\"))",
"orchestrate(self): self.remove_leftovers() self.copy_appleseed_python() self.copy_binaries() self.copy_dependencies() self.copy_schemas() self.copy_shaders() self.download_settings_files() self.remove_pyc_files() self.post_process_package()",
"def __init__(self, settings, package_version, build_date, no_release=False): self.settings = settings self.package_version",
"if self.__is_system_lib(lib): continue # Ignore Qt frameworks. if re.search(r\"Qt.*\\.framework\", lib):",
"in files: if f.endswith(\".oso\"): shutil.copy(os.path.join(root, f), target_dir) def download_settings_files(self): progress(\"Downloading",
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
"IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS",
"root directory\") # Create destination directory. settings_dir = os.path.join(self.settings.root_dir, \"appleseed\",",
"fix_paths=False): lib_name = os.path.basename(lib_path) if path_to_appleseed_lib == \".\": self.__change_library_path(bin_path, lib_path,",
"and dynamic libraries. def __change_library_paths_in_binary(self, bin_path): progress(\"Patching {0}\".format(bin_path)) bin_dir =",
"lib.replace(\"@rpath\", rpath) # Try to handle other relative libs. if",
"from staging directory\") package_name = \"blenderseed-{0}-{1}-{2}\".format(self.package_version, self.settings.platform, self.build_date) package_path =",
"\"*.so\")): self.run(\"chrpath -r \\$ORIGIN/../ \" + py_cpp_module) def __is_system_lib(self, lib):",
"SYSTEM_LIBS_PREFIXES = [ \"/System/Library/\", \"/usr/lib/libcurl\", \"/usr/lib/libc++\", \"/usr/lib/libbz2\", \"/usr/lib/libSystem\", #\"/usr/lib/libz\", \"/usr/lib/libncurses\",",
"not os.path.isfile(lib): fatal(\"Dependency {0} could not be found on disk\".format(lib))",
"root, dirs, files in os.walk(source_dir): for f in files: if",
"< Attempts - 1: time.sleep(0.5) else: fatal(\"Failed to delete directory",
"def __get_dependencies_for_file(self, filepath, fix_paths=True): filename = os.path.basename(filepath) loader_path = os.path.dirname(filepath)",
"{0}: {1}\".format(filepath, err)) libs = set() for line in out.split(\"\\n\"):",
"if path_to_appleseed_lib == \".\": self.__change_library_path(bin_path, lib_path, \"@loader_path/{0}\".format(lib_name)) else: self.__change_library_path(bin_path, lib_path,",
"package_version, build_date, no_release) else: fatal(\"Unsupported platform: \" + os.name) package_builder.build_package()",
"os.path.relpath(lib_dir, bin_dir) # fix_paths set to False because we must",
"= self.__get_required(tree, \"platform\") self.appleseed_release_path = self.__get_required(tree, \"appleseed_release_path\") os.environ['APPLESEED'] = self.appleseed_release_path",
"os.path.join(self.settings.output_dir, package_name) archive_util.make_zipfile(package_path, \"blenderseed\") info(\"Package path: {0}\".format(package_path + \".zip\")) def",
"the rights # to use, copy, modify, merge, publish, distribute,",
"lib_dir) def post_process_package(self): progress(\"Linux-specific: Post-processing package\") for bin in glob.glob(os.path.join(self.settings.root_dir,",
"py_cpp_module) def __is_system_lib(self, lib): for prefix in self.SYSTEM_LIBS_PREFIXES: if lib.startswith(prefix):",
"# Utility functions. #-------------------------------------------------------------------------------------------------- GREEN_CHECKMARK = u\"{0}\\u2713{1}\".format(colorama.Style.BRIGHT + colorama.Fore.GREEN, colorama.Style.RESET_ALL)",
"self.remove_stage() def remove_leftovers(self): progress(\"Removing leftovers from previous invocations\") safe_delete_directory(os.path.join(self.settings.root_dir, \"appleseed\"))",
"\".conf\": exe_path = os.path.join(dirpath, filename) self.__change_library_paths_in_binary(exe_path) # Can be used",
"os.path.dirname(bin_path) lib_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") path_to_appleseed_lib = os.path.relpath(lib_dir, bin_dir)",
"is hereby granted, free of charge, to any person obtaining",
"os.path.isdir(path): os.makedirs(path) def pushd(path): old_path = os.getcwd() os.chdir(path) return old_path",
"shared libs needed by appleseed.python. appleseedpython_libs = self.__get_dependencies_for_file( os.path.join(self.settings.root_dir, \"appleseed\",",
"import glob import os import platform import re import shutil",
"filename) def __change_library_paths_in_libraries(self): lib_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") for dirpath,",
"import traceback import urllib #-------------------------------------------------------------------------------------------------- # Constants. #-------------------------------------------------------------------------------------------------- VERSION =",
"= os.path.join(self.settings.root_dir, \"appleseed\", \"bin\") for dirpath, dirnames, filenames in os.walk(bin_dir):",
"output_path) #-------------------------------------------------------------------------------------------------- # Settings. #-------------------------------------------------------------------------------------------------- class Settings: def load(self): self.this_dir",
"CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR",
"blenderseed to staging directory\") shutil.copytree(self.settings.root_dir, \"blenderseed\", ignore=shutil.ignore_patterns(\"scripts\")) def clean_stage(self): progress(\"Cleaning",
"\"platform\") self.appleseed_release_path = self.__get_required(tree, \"appleseed_release_path\") os.environ['APPLESEED'] = self.appleseed_release_path self.appleseed_bin_path =",
"implement properly. safe_delete_file(os.path.join(lib_dir, \"appleseed\", \"_appleseedpython.so\")) safe_delete_file(os.path.join(lib_dir, \"appleseed\", \"_appleseedpython.pyd\")) def copy_binaries(self):",
"print(u\" {0}{1}{2}\".format(colorama.Style.DIM + colorama.Fore.WHITE, message, colorama.Style.RESET_ALL).encode('utf-8')) def info(message): print(u\" {0}\".format(message).encode('utf-8'))",
"tree): self.platform = self.__get_required(tree, \"platform\") self.appleseed_release_path = self.__get_required(tree, \"appleseed_release_path\") os.environ['APPLESEED']",
"directory\") shutil.copytree(self.settings.root_dir, \"blenderseed\", ignore=shutil.ignore_patterns(\"scripts\")) def clean_stage(self): progress(\"Cleaning staging directory\") safe_delete_directory_recursively(\"blenderseed\",",
"person obtaining a copy # of this software and associated",
"# TODO: implement properly. safe_delete_file(os.path.join(lib_dir, \"appleseed\", \"_appleseedpython.so\")) safe_delete_file(os.path.join(lib_dir, \"appleseed\", \"_appleseedpython.pyd\"))",
"if fix_paths: # Handle libs relative to @loader_path. lib =",
"return value #-------------------------------------------------------------------------------------------------- # Base package builder. #-------------------------------------------------------------------------------------------------- class PackageBuilder(object):",
"\"lib\") for dirpath, dirnames, filenames in os.walk(lib_dir): for filename in",
"set_libraries_ids(self): lib_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") for dirpath, dirnames, filenames",
"Qt frameworks. if re.search(r\"Qt.*\\.framework\", lib): continue if fix_paths: # Handle",
"__change_library_paths_in_executables(self): bin_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"bin\") for dirpath, dirnames, filenames",
"import subprocess import sys import time import traceback import urllib",
"bin_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"bin\") for dirpath, dirnames, filenames in",
"and platform.mac_ver()[0] == \"\": package_builder = LinuxPackageBuilder(settings, package_version, build_date, no_release)",
"fatal(\"Failed to invoke ldd(1) to get dependencies for {0}: {1}\".format(filepath,",
"traceback import urllib #-------------------------------------------------------------------------------------------------- # Constants. #-------------------------------------------------------------------------------------------------- VERSION = \"1.1.0\"",
"Copy appleseed.python. dir_util.copy_tree(self.settings.appleseed_python_path, lib_dir) # Remove _appleseedpython.so (Python 2) since",
"fix_paths=True): filename = os.path.basename(filepath) loader_path = os.path.dirname(filepath) rpath = \"/usr/local/lib/\"",
"\"appleseed\", \"_appleseedpython.pyd\")) def copy_binaries(self): progress(\"Copying binaries to root directory\") #",
"Ignore empty lines. if len(line) == 0: continue # Parse",
"new, target)) def __get_dependencies_for_file(self, filepath, fix_paths=True): filename = os.path.basename(filepath) loader_path",
"\"'\") self.__load_values(tree) def print_summary(self): print(\"\") print(\" Platform: \" + self.platform)",
"in self.__get_dependencies_for_file(bin_path, fix_paths=False): lib_name = os.path.basename(lib_path) if path_to_appleseed_lib == \".\":",
"\"appleseed_settings_path\")) self.appleseed_python_path = os.path.expandvars(self.__get_required(tree, \"appleseed_python_path\")) self.maketx_path = os.path.expandvars(self.__get_required(tree, \"maketx_path\")) self.output_dir",
"for root, dirs, files in os.walk(source_dir): for f in files:",
"colorama.Style.RESET_ALL) RED_CROSSMARK = u\"{0}\\u2717{1}\".format(colorama.Style.BRIGHT + colorama.Fore.RED, colorama.Style.RESET_ALL) def trace(message): #",
"Ignore empty lines. if len(line) == 0: continue # Ignore",
"self.root_dir = os.path.join(self.this_dir, \"..\") print(\"Loading settings from \" + SETTINGS_FILENAME",
"resources. # # This software is released under the MIT",
"previous invocations\") safe_delete_directory(os.path.join(self.settings.root_dir, \"appleseed\")) safe_delete_directory(\"blenderseed\") def copy_appleseed_python(self): progress(\"Copying appleseed.python to",
"CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS",
"relative to @rpath. lib = lib.replace(\"@rpath\", rpath) # Try to",
"in filenames: ext = os.path.splitext(filename)[1] if ext == \".dylib\" or",
"# Permission is hereby granted, free of charge, to any",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #",
"no_release = args.nozip package_version = subprocess.Popen(\"git describe --long\", stdout=subprocess.PIPE, shell=True).stdout.read().strip()",
"file that couldn't be removed. # Let's just assume that",
"directory_name)) for entry in os.listdir(root_path): subdirectory = os.path.join(root_path, entry) if",
"libs def __is_system_lib(self, lib): for prefix in self.SYSTEM_LIBS_PREFIXES: if lib.startswith(prefix):",
"shared libs needed by binaries. all_libs = set() for bin",
"package_builder = MacPackageBuilder(settings, package_version, build_date, no_release) elif os.name == \"posix\"",
"ldd(1) to get dependencies for {0}: {1}\".format(filepath, err)) libs =",
"no_release) else: fatal(\"Unsupported platform: \" + os.name) package_builder.build_package() if __name__",
"libraries. # TODO: we're not computing the full transitive closure",
"directory\") # Create destination directory. bin_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"bin\")",
"trace(u\" {0} {1}\".format(RED_CROSSMARK, lib)) # Don't check for missing dependencies",
"for lib in glob.glob(os.path.join(self.settings.root_dir, \"appleseed\", \"lib\", \"*.so\")): self.run(\"chrpath -d \"",
"= parser.parse_args() no_release = args.nozip package_version = subprocess.Popen(\"git describe --long\",",
"filepath]) if returncode != 0: fatal(\"Failed to invoke otool(1) to",
"+ colorama.Fore.RED, message, colorama.Style.RESET_ALL).encode('utf-8')) if sys.exc_info()[0]: print(traceback.format_exc()) sys.exit(1) def exe(filepath):",
"\"libutil\", \"libpython\", \"libxshmfence.so\" ] def plugin_extension(self): return \".so\" def copy_dependencies(self):",
"# Ignore system libs. if self.__is_system_lib(line): continue # Ignore appleseed",
"lib_path = os.path.join(dirpath, filename) self.__set_library_id(lib_path, filename) def __change_library_paths_in_libraries(self): lib_dir =",
"for dirpath, dirnames, filenames in os.walk(lib_dir): for filename in filenames:",
"== 0: continue # Parse the line. m = re.match(r\"(.*)",
"Post-processing package\") for bin in glob.glob(os.path.join(self.settings.root_dir, \"appleseed\", \"bin\", \"*\")): self.run(\"chrpath",
"Ignore self-references (why do these happen?). if lib == filename:",
"to root directory\") # Create destination directory. shaders_dir = os.path.join(self.settings.root_dir,",
"for input_file in glob.glob(input_pattern): shutil.copy(input_file, output_path) #-------------------------------------------------------------------------------------------------- # Settings. #--------------------------------------------------------------------------------------------------",
"root, dirs, files in os.walk(os.path.join(self.settings.root_dir, \"appleseed\", \"lib\")): for f in",
"def run_subprocess(self, cmdline): p = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err",
"path + \"'\") def on_rmtree_error(func, path, exc_info): # path contains",
"in all_libs: if True: trace(\" Copying {0} to {1}...\".format(lib, lib_dir))",
"no_release) elif os.name == \"posix\" and platform.mac_ver()[0] != \"\": package_builder",
"safe_delete_directory(os.path.join(root_path, directory_name)) for entry in os.listdir(root_path): subdirectory = os.path.join(root_path, entry)",
"if os.path.exists(path): os.remove(path) except OSError: fatal(\"Failed to delete file '\"",
"Settings. #-------------------------------------------------------------------------------------------------- class Settings: def load(self): self.this_dir = os.path.dirname(os.path.realpath(__file__)) self.root_dir",
"copy_schemas(self): progress(\"Copying schemas to root directory\") dir_util.copy_tree(self.settings.appleseed_schemas_path, os.path.join(self.settings.root_dir, \"appleseed\", \"schemas\"))",
"\"appleseed\", \"lib\") safe_make_directory(lib_dir) # Copy appleseed.python. dir_util.copy_tree(self.settings.appleseed_python_path, lib_dir) # Remove",
"copy_dependencies(self): progress(\"Windows-specific: Copying dependencies\") bin_dir = self.settings.appleseed_bin_path for dll in",
"dirpath, dirnames, filenames in os.walk(lib_dir): for filename in filenames: ext",
"onerror=on_rmtree_error) return except OSError: if attempt < Attempts - 1:",
"binaries to blenderseed folder but does not build a release",
"PackageBuilder(object): def __init__(self, settings, package_version, build_date, no_release=False): self.settings = settings",
"else: self.__change_library_path(bin_path, lib_path, \"@loader_path/{0}/{1}\".format(path_to_appleseed_lib, lib_name)) def __set_library_id(self, target, name): self.run('install_name_tool",
"in libs: if not os.path.isfile(lib): fatal(\"Dependency {0} could not be",
"{2}'.format(old, new, target)) def __get_dependencies_for_file(self, filepath, fix_paths=True): filename = os.path.basename(filepath)",
"return p.returncode, out, err #-------------------------------------------------------------------------------------------------- # Windows package builder. #--------------------------------------------------------------------------------------------------",
"= lib.replace(\"@rpath\", rpath) # Try to handle other relative libs.",
"m: fatal(\"Failed to parse line from otool(1) output: \" +",
"\"{0}\" \"{1}\" {2}'.format(old, new, target)) def __get_dependencies_for_file(self, filepath, fix_paths=True): filename",
"libraries. lib_libs = set() for lib in all_libs: libs =",
"== \"nt\" else filepath def safe_delete_file(path): try: if os.path.exists(path): os.remove(path)",
"def copy_schemas(self): progress(\"Copying schemas to root directory\") dir_util.copy_tree(self.settings.appleseed_schemas_path, os.path.join(self.settings.root_dir, \"appleseed\",",
"def deploy_blenderseed_to_stage(self): progress(\"Deploying blenderseed to staging directory\") shutil.copytree(self.settings.root_dir, \"blenderseed\", ignore=shutil.ignore_patterns(\"scripts\"))",
"the full transitive closure here! lib_libs = set() for lib",
"to False because we must retrieve the unmodified dependency in",
"MacPackageBuilder(settings, package_version, build_date, no_release) elif os.name == \"posix\" and platform.mac_ver()[0]",
"False #-------------------------------------------------------------------------------------------------- # Linux package builder. #-------------------------------------------------------------------------------------------------- class LinuxPackageBuilder(PackageBuilder): SYSTEM_LIBS_PREFIXES",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT",
"Try to handle other relative libs. if not os.path.isabs(lib): #",
"appleseed binaries to blenderseed folder but does not build a",
"lib in [\"libappleseed.so\", \"libappleseed.shared.so\"]: shutil.copy(os.path.join(self.settings.appleseed_lib_path, lib), lib_dir) # Get shared",
"safe_delete_directory(\"blenderseed\") def copy_appleseed_python(self): progress(\"Copying appleseed.python to root directory\") # Create",
"directory\") # Create destination directory. shaders_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"shaders\")",
"libs.add(lib) if True: trace(\"Dependencies for file {0}:\".format(filepath)) for lib in",
"+ colorama.Fore.WHITE, message, colorama.Style.RESET_ALL).encode('utf-8')) def info(message): print(u\" {0}\".format(message).encode('utf-8')) def progress(message):",
"\"blenderseed.package.configuration.xml\" #-------------------------------------------------------------------------------------------------- # Utility functions. #-------------------------------------------------------------------------------------------------- GREEN_CHECKMARK = u\"{0}\\u2713{1}\".format(colorama.Style.BRIGHT +",
"destination directory. bin_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"bin\") safe_make_directory(bin_dir) # Copy",
"lib in all_libs: if True: trace(\" Copying {0} to {1}...\".format(lib,",
"version .*\\)\", line) if not m: fatal(\"Failed to parse line",
"True: # Print dependencies. trace(\" Dependencies:\") for lib in all_libs:",
"<NAME>, The appleseedhq Organization # # Permission is hereby granted,",
"binaries: \" + self.appleseed_bin_path) print(\" Path to appleseed libraries: \"",
"self.copy_binaries() self.copy_dependencies() self.copy_schemas() self.copy_shaders() self.download_settings_files() self.remove_pyc_files() self.post_process_package() if not self.no_release:",
"print(traceback.format_exc()) sys.exit(1) def exe(filepath): return filepath + \".exe\" if os.name",
"True: trace(\"Gathering dependencies for file\") trace(\" {0}\".format(filepath)) trace(\"with @loader_path set",
"(why do these happen?). if lib == filename: continue #",
"Path to maketx: \" + self.maketx_path) print(\" Output directory: \"",
"files from root directory\") for root, dirs, files in os.walk(os.path.join(self.settings.root_dir,",
"libs. if self.__is_system_lib(line): continue # Ignore appleseed libs. if \"libappleseed\"",
"\"appleseed\", \"lib\", \"*.so\")): self.run(\"chrpath -d \" + lib) appleseed_python_dir =",
"+ colorama.Fore.RED, colorama.Style.RESET_ALL) def trace(message): # encode('utf-8') is required to",
"build_date, no_release) else: fatal(\"Unsupported platform: \" + os.name) package_builder.build_package() if",
"Ignore Qt frameworks. if re.search(r\"Qt.*\\.framework\", lib): continue if fix_paths: #",
"print(\"\") settings = Settings() settings.load() settings.print_summary() if os.name == \"nt\":",
"shutil.copy(os.path.join(root, f), target_dir) def download_settings_files(self): progress(\"Downloading settings files to root",
"def info(message): print(u\" {0}\".format(message).encode('utf-8')) def progress(message): print(u\" {0}...\".format(message).encode('utf-8')) def warning(message):",
"directory_name): safe_delete_directory(os.path.join(root_path, directory_name)) for entry in os.listdir(root_path): subdirectory = os.path.join(root_path,",
"package_builder = LinuxPackageBuilder(settings, package_version, build_date, no_release) else: fatal(\"Unsupported platform: \"",
"= \"blenderseed.package.configuration.xml\" #-------------------------------------------------------------------------------------------------- # Utility functions. #-------------------------------------------------------------------------------------------------- GREEN_CHECKMARK = u\"{0}\\u2713{1}\".format(colorama.Style.BRIGHT",
"copy_shaders(self): progress(\"Copying shaders to root directory\") # Create destination directory.",
"\"libdl\", \"libm.so\", \"libgcc\", \"libc.so\", \"/lib64/ld-linux-\", \"libstdc++\", \"libxcb\", \"libdrm\", \"libnsl\", \"libuuid\",",
"one. for lib_path in self.__get_dependencies_for_file(bin_path, fix_paths=False): lib_name = os.path.basename(lib_path) if",
"under the MIT license. # # Copyright (c) 2017-2018 <NAME>,",
"os.path.isdir(subdirectory): safe_delete_directory_recursively(subdirectory, directory_name) def safe_make_directory(path): if not os.path.isdir(path): os.makedirs(path) def",
"self.appleseed_shaders_path = os.path.expandvars(self.__get_required(tree, \"appleseed_shaders_path\")) self.appleseed_schemas_path = os.path.expandvars(self.__get_required(tree, \"appleseed_schemas_path\")) self.appleseed_settings_path =",
"closure here! lib_libs = set() for lib in all_libs: libs",
"settings, package_version, build_date, no_release=False): self.settings = settings self.package_version = package_version",
"os.path.join(self.settings.root_dir, \"appleseed\", \"lib\", \"appleseed\") for py_cpp_module in glob.glob(os.path.join(appleseed_python_dir, \"*.so\")): self.run(\"chrpath",
"build_date, no_release) elif os.name == \"posix\" and platform.mac_ver()[0] != \"\":",
"False def __get_dependencies_for_file(self, filepath): returncode, out, err = self.run_subprocess([\"ldd\", filepath])",
"user-specified search paths. candidate = os.path.join(loader_path, lib) if not os.path.exists(candidate):",
"Copy appleseed libraries. for lib in [\"libappleseed.so\", \"libappleseed.shared.so\"]: shutil.copy(os.path.join(self.settings.appleseed_lib_path, lib),",
"os.path.exists(path): shutil.rmtree(path, onerror=on_rmtree_error) return except OSError: if attempt < Attempts",
"print(\" Path to appleseed shaders: \" + self.appleseed_shaders_path) print(\" Path",
"+ SETTINGS_FILENAME + \"'\") self.__load_values(tree) def print_summary(self): print(\"\") print(\" Platform:",
"package:\") print(\"\") self.orchestrate() print(\"\") print(\"The package was successfully built.\") def",
"restriction, including without limitation the rights # to use, copy,",
"safe_delete_file(os.path.join(lib_dir, \"appleseed\", \"_appleseedpython.so\")) safe_delete_file(os.path.join(lib_dir, \"appleseed\", \"_appleseedpython.pyd\")) def copy_binaries(self): progress(\"Copying binaries",
"self.run('install_name_tool -id \"{0}\" {1}'.format(name, target)) def __change_library_path(self, target, old, new):",
"otool(1) output: \" + line) lib = m.group(1) # Ignore",
"in glob.glob(os.path.join(appleseed_python_dir, \"*.so\")): self.run(\"chrpath -r \\$ORIGIN/../ \" + py_cpp_module) def",
"dirnames, filenames in os.walk(bin_dir): for filename in filenames: ext =",
"all_libs: shutil.copy(lib, lib_dir) def post_process_package(self): progress(\"Linux-specific: Post-processing package\") for bin",
"output_path): for input_file in glob.glob(input_pattern): shutil.copy(input_file, output_path) #-------------------------------------------------------------------------------------------------- # Settings.",
"shaders_dir) def __do_copy_shaders(self, source_dir, target_dir): for root, dirs, files in",
"{1}. Aborting.{2}\".format(colorama.Style.BRIGHT + colorama.Fore.RED, message, colorama.Style.RESET_ALL).encode('utf-8')) if sys.exc_info()[0]: print(traceback.format_exc()) sys.exit(1)",
"Can be used on executables and dynamic libraries. def __change_library_paths_in_binary(self,",
"os.path.join(dirpath, filename) self.__change_library_paths_in_binary(exe_path) # Can be used on executables and",
"def exe(filepath): return filepath + \".exe\" if os.name == \"nt\"",
"ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED",
"free of charge, to any person obtaining a copy #",
"from otool(1) output: \" + line) lib = m.group(1) #",
"OTHER DEALINGS IN # THE SOFTWARE. # from __future__ import",
"all_libs = all_libs.union(lib_libs) if True: # Print dependencies. trace(\" Dependencies:\")",
"for bin in [exe(\"appleseed.cli\")]: shutil.copy(os.path.join(self.settings.appleseed_bin_path, bin), bin_dir) # Copy maketx.",
"set() for bin in glob.glob(os.path.join(self.settings.root_dir, \"appleseed\", \"bin\", \"*\")): libs =",
"ElementTree import argparse import colorama import datetime import glob import",
"post_process_package(self): progress(\"Mac-specific: Post-processing package\") self.__fixup_binaries() def __fixup_binaries(self): progress(\"Mac-specific: Fixing up",
"= self.run_subprocess([\"ldd\", filepath]) if returncode != 0: fatal(\"Failed to invoke",
"print(\" Platform: \" + self.platform) print(\" Path to appleseed release:",
"from previous invocations\") safe_delete_directory(os.path.join(self.settings.root_dir, \"appleseed\")) safe_delete_directory(\"blenderseed\") def copy_appleseed_python(self): progress(\"Copying appleseed.python",
"# Remove _appleseedpython.so (Python 2) since blenderseed only needs _appleseedpython3.so",
"trace(\"and @rpath hardcoded to\") trace(\" {0}\".format(rpath)) returncode, out, err =",
"= os.path.join(self.settings.root_dir, \"appleseed\", \"lib\", \"appleseed\") for py_cpp_module in glob.glob(os.path.join(appleseed_python_dir, \"*.so\")):",
"else: fatal(\"Unsupported platform: \" + os.name) package_builder.build_package() if __name__ ==",
"def copy_shaders(self): progress(\"Copying shaders to root directory\") # Create destination",
"safe_delete_directory_recursively(root_path, directory_name): safe_delete_directory(os.path.join(root_path, directory_name)) for entry in os.listdir(root_path): subdirectory =",
"\"output_dir\")) def __get_required(self, tree, key): value = tree.findtext(key) if value",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
"shutil.copy(os.path.join(bin_dir, dll), os.path.join(self.settings.root_dir, \"appleseed\", \"bin\")) def post_process_package(self): pass #-------------------------------------------------------------------------------------------------- #",
"# Get shared libs needed by appleseed.python. appleseedpython_libs = self.__get_dependencies_for_file(",
"\"*.so\")): self.run(\"chrpath -d \" + lib) appleseed_python_dir = os.path.join(self.settings.root_dir, \"appleseed\",",
"\"maketx_path\")) self.output_dir = os.path.expandvars(self.__get_required(tree, \"output_dir\")) def __get_required(self, tree, key): value",
"\"appleseed_shaders_path\")) self.appleseed_schemas_path = os.path.expandvars(self.__get_required(tree, \"appleseed_schemas_path\")) self.appleseed_settings_path = os.path.expandvars(self.__get_required(tree, \"appleseed_settings_path\")) self.appleseed_python_path",
"lib), lib_dir) # Get shared libs needed by binaries. all_libs",
"{0}\".format(message).encode('utf-8')) def progress(message): print(u\" {0}...\".format(message).encode('utf-8')) def warning(message): print(u\" {0}Warning: {1}.{2}\".format(colorama.Style.BRIGHT",
"os.path.join(self.settings.root_dir, \"appleseed\", \"lib\", \"appleseed\", \"_appleseedpython3.so\")) all_libs = all_libs.union(appleseedpython_libs) # Get",
"def safe_delete_directory_recursively(root_path, directory_name): safe_delete_directory(os.path.join(root_path, directory_name)) for entry in os.listdir(root_path): subdirectory",
"build_final_zip_file(self): progress(\"Building final zip file from staging directory\") package_name =",
"print(u\" {0}Warning: {1}.{2}\".format(colorama.Style.BRIGHT + colorama.Fore.MAGENTA, message, colorama.Style.RESET_ALL).encode('utf-8')) def fatal(message): print(u\"{0}Fatal:",
"a great simplification if True: trace(\"Gathering dependencies for file\") trace(\"",
"\"*\")): self.run(\"chrpath -r \\$ORIGIN/../lib \" + bin) for lib in",
"continue # Ignore system libs. if self.__is_system_lib(lib): continue # Ignore",
".*\\)\", line) if not m: fatal(\"Failed to parse line from",
"colorama.Style.RESET_ALL).encode('utf-8')) if sys.exc_info()[0]: print(traceback.format_exc()) sys.exit(1) def exe(filepath): return filepath +",
"not m: fatal(\"Failed to parse line from otool(1) output: \"",
"for {0}: {1}\".format(filepath, err)) libs = set() for line in",
"in [\"appleseed.dll\", \"appleseed.shared.dll\"]: shutil.copy(os.path.join(bin_dir, dll), os.path.join(self.settings.root_dir, \"appleseed\", \"bin\")) def post_process_package(self):",
"OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR",
"a collection of user-specified search paths. candidate = os.path.join(loader_path, lib)",
"os.path.basename(filepath) loader_path = os.path.dirname(filepath) rpath = \"/usr/local/lib/\" # TODO: a",
"in glob.glob(os.path.join(self.settings.root_dir, \"appleseed\", \"lib\", \"*.so\")): self.run(\"chrpath -d \" + lib)",
"= os.path.expandvars(self.__get_required(tree, \"appleseed_python_path\")) self.maketx_path = os.path.expandvars(self.__get_required(tree, \"maketx_path\")) self.output_dir = os.path.expandvars(self.__get_required(tree,",
"== \"posix\" and platform.mac_ver()[0] == \"\": package_builder = LinuxPackageBuilder(settings, package_version,",
"lib = lib.replace(\"@rpath\", rpath) # Try to handle other relative",
"# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,",
"p = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() return",
"\" + py_cpp_module) def __is_system_lib(self, lib): for prefix in self.SYSTEM_LIBS_PREFIXES:",
"if not os.path.isdir(path): os.makedirs(path) def pushd(path): old_path = os.getcwd() os.chdir(path)",
"lib directory. for lib in all_libs: if True: trace(\" Copying",
"entry) if os.path.isdir(subdirectory): safe_delete_directory_recursively(subdirectory, directory_name) def safe_make_directory(path): if not os.path.isdir(path):",
"properly. safe_delete_file(os.path.join(lib_dir, \"appleseed\", \"_appleseedpython.so\")) safe_delete_file(os.path.join(lib_dir, \"appleseed\", \"_appleseedpython.pyd\")) def copy_binaries(self): progress(\"Copying",
"it. os.chmod(path, stat.S_IWRITE) os.unlink(path) def safe_delete_directory(path): Attempts = 10 for",
"= MacPackageBuilder(settings, package_version, build_date, no_release) elif os.name == \"posix\" and",
"for file\") trace(\" {0}\".format(filepath)) trace(\"with @loader_path set to\") trace(\" {0}\".format(loader_path))",
"current version .*\\)\", line) if not m: fatal(\"Failed to parse",
"#\"/usr/lib/libz\", \"/usr/lib/libncurses\", \"/usr/lib/libobjc.A.dylib\" ] def copy_dependencies(self): progress(\"Mac-specific: Copying dependencies\") #",
"print_summary(self): print(\"\") print(\" Platform: \" + self.platform) print(\" Path to",
"charge, to any person obtaining a copy # of this",
"Copy needed libs to lib directory. for lib in all_libs:",
"self.appleseed_settings_path = os.path.expandvars(self.__get_required(tree, \"appleseed_settings_path\")) self.appleseed_python_path = os.path.expandvars(self.__get_required(tree, \"appleseed_python_path\")) self.maketx_path =",
"\"libnsl\", \"libuuid\", \"libgthread\", \"libglib\", \"libgobject\", \"libglapi\", \"libffi\", \"libfontconfig\", \"libutil\", \"libpython\",",
"safe_delete_file(os.path.join(self.settings.root_dir, \"appleseed\", \"schemas\", \".gitignore\")) def copy_shaders(self): progress(\"Copying shaders to root",
"this permission notice shall be included in # all copies",
"dirs, files in os.walk(source_dir): for f in files: if f.endswith(\".oso\"):",
"#-------------------------------------------------------------------------------------------------- # Mac package builder. #-------------------------------------------------------------------------------------------------- class MacPackageBuilder(PackageBuilder): SYSTEM_LIBS_PREFIXES =",
"files: if f.endswith(\".pyc\"): safe_delete_file(os.path.join(root, f)) def deploy_blenderseed_to_stage(self): progress(\"Deploying blenderseed to",
"to support output redirection to files or pipes. print(u\" {0}{1}{2}\".format(colorama.Style.DIM",
"safe_make_directory(path): if not os.path.isdir(path): os.makedirs(path) def pushd(path): old_path = os.getcwd()",
"bin_dir) # Copy maketx. shutil.copy(exe(self.settings.maketx_path), bin_dir) def copy_schemas(self): progress(\"Copying schemas",
"Mac package builder. #-------------------------------------------------------------------------------------------------- class MacPackageBuilder(PackageBuilder): SYSTEM_LIBS_PREFIXES = [ \"/System/Library/\",",
"#!/usr/bin/python # # This source file is part of appleseed.",
"os.walk(bin_dir): for filename in filenames: ext = os.path.splitext(filename)[1] if ext",
"set() for lib in all_libs: libs = self.__get_dependencies_for_file(lib) lib_libs =",
"parser.parse_args() no_release = args.nozip package_version = subprocess.Popen(\"git describe --long\", stdout=subprocess.PIPE,",
"by libraries. # TODO: we're not computing the full transitive",
"glob.glob(input_pattern): shutil.copy(input_file, output_path) #-------------------------------------------------------------------------------------------------- # Settings. #-------------------------------------------------------------------------------------------------- class Settings: def",
"filename = os.path.basename(filepath) loader_path = os.path.dirname(filepath) rpath = \"/usr/local/lib/\" #",
"remove_leftovers(self): progress(\"Removing leftovers from previous invocations\") safe_delete_directory(os.path.join(self.settings.root_dir, \"appleseed\")) safe_delete_directory(\"blenderseed\") def",
"blenderseed only needs _appleseedpython3.so (Python 3). # TODO: implement properly.",
"glob.glob(os.path.join(self.settings.root_dir, \"appleseed\", \"bin\", \"*\")): self.run(\"chrpath -r \\$ORIGIN/../lib \" + bin)",
"lib = m.group(1) # Ignore self-references (why do these happen?).",
"path_to_appleseed_lib == \".\": self.__change_library_path(bin_path, lib_path, \"@loader_path/{0}\".format(lib_name)) else: self.__change_library_path(bin_path, lib_path, \"@loader_path/{0}/{1}\".format(path_to_appleseed_lib,",
"in out.split(\"\\n\"): line = line.strip() # Ignore empty lines. if",
"if lib == filename: continue # Ignore system libs. if",
"return libs #-------------------------------------------------------------------------------------------------- # Entry point. #-------------------------------------------------------------------------------------------------- def main(): colorama.init()",
"#-------------------------------------------------------------------------------------------------- # Constants. #-------------------------------------------------------------------------------------------------- VERSION = \"1.1.0\" SETTINGS_FILENAME = \"blenderseed.package.configuration.xml\"",
"# Linux package builder. #-------------------------------------------------------------------------------------------------- class LinuxPackageBuilder(PackageBuilder): SYSTEM_LIBS_PREFIXES = [",
"= datetime.date.today().isoformat() print(\"blenderseed.package version \" + VERSION) print(\"\") settings =",
"\"libgobject\", \"libglapi\", \"libffi\", \"libfontconfig\", \"libutil\", \"libpython\", \"libxshmfence.so\" ] def plugin_extension(self):",
"lib.startswith(prefix): return True return False #-------------------------------------------------------------------------------------------------- # Linux package builder.",
"to maketx: \" + self.maketx_path) print(\" Output directory: \" +",
"libs needed by binaries. all_libs = set() for bin in",
"= u\"{0}\\u2717{1}\".format(colorama.Style.BRIGHT + colorama.Fore.RED, colorama.Style.RESET_ALL) def trace(message): # encode('utf-8') is",
"= os.path.join(\"/usr/local/lib/\", lib) if os.path.exists(candidate): info(\"Resolved relative dependency {0} as",
"def print_summary(self): print(\"\") print(\" Platform: \" + self.platform) print(\" Path",
"ignore=shutil.ignore_patterns(\"scripts\")) def clean_stage(self): progress(\"Cleaning staging directory\") safe_delete_directory_recursively(\"blenderseed\", \"__pycache__\") for subdirectory",
"modify, merge, publish, distribute, sublicense, and/or sell # copies of",
"a blenderseed package from sources\") parser.add_argument(\"--nozip\", action=\"store_true\", help=\"copies appleseed binaries",
"== 0: continue # Ignore system libs. if self.__is_system_lib(line): continue",
"files in os.walk(os.path.join(self.settings.root_dir, \"appleseed\", \"lib\")): for f in files: if",
"# Copy needed libs to lib directory. for lib in",
"TODO: we're not computing the full transitive closure here! lib_libs",
"= argparse.ArgumentParser(description=\"build a blenderseed package from sources\") parser.add_argument(\"--nozip\", action=\"store_true\", help=\"copies",
"to delete file '\" + path + \"'\") def on_rmtree_error(func,",
"\"libpthread\", \"libGL\", \"libX\", \"libselinux\", \"libICE\", \"libSM\", \"libdl\", \"libm.so\", \"libgcc\", \"libc.so\",",
"shared libraries. for lib in all_libs: shutil.copy(lib, lib_dir) def post_process_package(self):",
"other relative libs. if not os.path.isabs(lib): # TODO: generalize to",
"check for missing dependencies if we didn't attempt to fix",
"platform: \" + os.name) package_builder.build_package() if __name__ == \"__main__\": main()",
"support output redirection to files or pipes. print(u\" {0}{1}{2}\".format(colorama.Style.DIM +",
"in [\"libappleseed.dylib\", \"libappleseed.shared.dylib\"]: shutil.copy(os.path.join(self.settings.appleseed_lib_path, lib), lib_dir) # Get shared libs",
"os.walk(lib_dir): for filename in filenames: ext = os.path.splitext(filename)[1] if ext",
"__load_values(self, tree): self.platform = self.__get_required(tree, \"platform\") self.appleseed_release_path = self.__get_required(tree, \"appleseed_release_path\")",
"if os.path.isdir(subdirectory): safe_delete_directory_recursively(subdirectory, directory_name) def safe_make_directory(path): if not os.path.isdir(path): os.makedirs(path)",
"# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR",
"self.__get_dependencies_for_file(lib) lib_libs = lib_libs.union(libs) all_libs = all_libs.union(lib_libs) if True: #",
"\".so\": lib_path = os.path.join(dirpath, filename) self.__change_library_paths_in_binary(lib_path) def __change_library_paths_in_executables(self): bin_dir =",
"10 for attempt in range(Attempts): try: if os.path.exists(path): shutil.rmtree(path, onerror=on_rmtree_error)",
"libs needed by libraries. # TODO: we're not computing the",
"the unmodified dependency in order to replace it by the",
"\"posix\" and platform.mac_ver()[0] == \"\": package_builder = LinuxPackageBuilder(settings, package_version, build_date,",
"SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE",
"lib_dir)) shutil.copy(lib, lib_dir) def post_process_package(self): progress(\"Mac-specific: Post-processing package\") self.__fixup_binaries() def",
"GREEN_CHECKMARK = u\"{0}\\u2713{1}\".format(colorama.Style.BRIGHT + colorama.Fore.GREEN, colorama.Style.RESET_ALL) RED_CROSSMARK = u\"{0}\\u2717{1}\".format(colorama.Style.BRIGHT +",
"def post_process_package(self): progress(\"Mac-specific: Post-processing package\") self.__fixup_binaries() def __fixup_binaries(self): progress(\"Mac-specific: Fixing",
"up binaries\") self.set_libraries_ids() self.__change_library_paths_in_libraries() self.__change_library_paths_in_executables() def set_libraries_ids(self): lib_dir = os.path.join(self.settings.root_dir,",
"\"libglapi\", \"libffi\", \"libfontconfig\", \"libutil\", \"libpython\", \"libxshmfence.so\" ] def plugin_extension(self): return",
"for subdirectory in [\".git\", \".idea\", \"archives\", \"docs\", \"scripts\", \"tests\"]: safe_delete_directory(os.path.join(\"blenderseed\",",
"os.path.expandvars(self.__get_required(tree, \"output_dir\")) def __get_required(self, tree, key): value = tree.findtext(key) if",
"\" + self.appleseed_shaders_path) print(\" Path to appleseed schemas: \" +",
"in line: continue libs.add(line.split()[2]) return libs #-------------------------------------------------------------------------------------------------- # Entry point.",
"in [\".gitignore\", \"README.md\"]: safe_delete_file(os.path.join(\"blenderseed\", file)) def build_final_zip_file(self): progress(\"Building final zip",
"dir_util.copy_tree(self.settings.appleseed_schemas_path, os.path.join(self.settings.root_dir, \"appleseed\", \"schemas\")) safe_delete_file(os.path.join(self.settings.root_dir, \"appleseed\", \"schemas\", \".gitignore\")) def copy_shaders(self):",
"filepath): returncode, out, err = self.run_subprocess([\"ldd\", filepath]) if returncode !=",
"self.__get_dependencies_for_file( os.path.join(self.settings.root_dir, \"appleseed\", \"lib\", \"appleseed\", \"_appleseedpython3.so\")) all_libs = all_libs.union(appleseedpython_libs) #",
"load(self): self.this_dir = os.path.dirname(os.path.realpath(__file__)) self.root_dir = os.path.join(self.this_dir, \"..\") print(\"Loading settings",
"def load(self): self.this_dir = os.path.dirname(os.path.realpath(__file__)) self.root_dir = os.path.join(self.this_dir, \"..\") print(\"Loading",
"__change_library_paths_in_binary(self, bin_path): progress(\"Patching {0}\".format(bin_path)) bin_dir = os.path.dirname(bin_path) lib_dir = os.path.join(self.settings.root_dir,",
"import sys import time import traceback import urllib #-------------------------------------------------------------------------------------------------- #",
"os.path.expandvars(self.__get_required(tree, \"maketx_path\")) self.output_dir = os.path.expandvars(self.__get_required(tree, \"output_dir\")) def __get_required(self, tree, key):",
"= os.path.dirname(filepath) rpath = \"/usr/local/lib/\" # TODO: a great simplification",
"LinuxPackageBuilder(settings, package_version, build_date, no_release) else: fatal(\"Unsupported platform: \" + os.name)",
"lines. if len(line) == 0: continue # Ignore system libs.",
"if True: # Print dependencies. trace(\" Dependencies:\") for lib in",
"= os.path.join(root_path, entry) if os.path.isdir(subdirectory): safe_delete_directory_recursively(subdirectory, directory_name) def safe_make_directory(path): if",
"\"libgthread\", \"libglib\", \"libgobject\", \"libglapi\", \"libffi\", \"libfontconfig\", \"libutil\", \"libpython\", \"libxshmfence.so\" ]",
"self.maketx_path) print(\" Output directory: \" + self.output_dir) print(\"\") def __load_values(self,",
"print(u\" {0}\".format(message).encode('utf-8')) def progress(message): print(u\" {0}...\".format(message).encode('utf-8')) def warning(message): print(u\" {0}Warning:",
"SETTINGS_FILENAME + \"...\") tree = ElementTree() try: tree.parse(SETTINGS_FILENAME) except IOError:",
"self.SYSTEM_LIBS_PREFIXES: if lib.startswith(prefix): return True return False def __get_dependencies_for_file(self, filepath):",
"os.name == \"nt\": package_builder = WindowsPackageBuilder(settings, package_version, build_date, no_release) elif",
"in configuration file\".format(key)) return value #-------------------------------------------------------------------------------------------------- # Base package builder.",
"os.getcwd() os.chdir(path) return old_path def copy_glob(input_pattern, output_path): for input_file in",
"= all_libs.union(lib_libs) if True: # Print dependencies. trace(\" Dependencies:\") for",
"= set() for line in out.split(\"\\n\"): line = line.strip() #",
"for lib in libs: if os.path.isfile(lib): trace(u\" {0} {1}\".format(GREEN_CHECKMARK, lib))",
"f), target_dir) def download_settings_files(self): progress(\"Downloading settings files to root directory\")",
"package_name = \"blenderseed-{0}-{1}-{2}\".format(self.package_version, self.settings.platform, self.build_date) package_path = os.path.join(self.settings.output_dir, package_name) archive_util.make_zipfile(package_path,",
"for lib in libs: if not os.path.isfile(lib): fatal(\"Dependency {0} could",
"file '\" + path + \"'\") def on_rmtree_error(func, path, exc_info):",
"import print_function from distutils import archive_util, dir_util from xml.etree.ElementTree import",
"progress(\"Cleaning staging directory\") safe_delete_directory_recursively(\"blenderseed\", \"__pycache__\") for subdirectory in [\".git\", \".idea\",",
"not computing the full transitive closure here! lib_libs = set()",
"libs. if not os.path.isabs(lib): # TODO: generalize to a collection",
"as {1}\".format(lib, candidate)) lib = candidate libs.add(lib) if True: trace(\"Dependencies",
"file)) def remove_pyc_files(self): progress(\"Removing pyc files from root directory\") for",
"shaders: \" + self.appleseed_shaders_path) print(\" Path to appleseed schemas: \"",
"= set() for line in out.split(\"\\n\")[1:]: # skip the first",
"path, exc_info): # path contains the path of the file",
"destination directory. settings_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"settings\") safe_make_directory(settings_dir) for file",
"libs = self.__get_dependencies_for_file(bin) all_libs = all_libs.union(libs) # Get shared libs",
"\"lib\") safe_make_directory(lib_dir) # Copy appleseed libraries. for lib in [\"libappleseed.dylib\",",
"root directory\") # Create destination directory. bin_dir = os.path.join(self.settings.root_dir, \"appleseed\",",
"Software. # # THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT",
"lib_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") safe_make_directory(lib_dir) # Copy appleseed libraries.",
"SYSTEM_LIBS_PREFIXES = [ \"linux\", \"librt\", \"libpthread\", \"libGL\", \"libX\", \"libselinux\", \"libICE\",",
"# Can be used on executables and dynamic libraries. def",
"retrieve the unmodified dependency in order to replace it by",
"candidate)) lib = candidate libs.add(lib) if True: trace(\"Dependencies for file",
"in out.split(\"\\n\")[1:]: # skip the first line line = line.strip()",
"os import platform import re import shutil import stat import",
"fatal(\"Failed to load configuration file '\" + SETTINGS_FILENAME + \"'\")",
"except OSError: fatal(\"Failed to delete file '\" + path +",
"safe_delete_file(path): try: if os.path.exists(path): os.remove(path) except OSError: fatal(\"Failed to delete",
"do these happen?). if lib == filename: continue # Ignore",
"from xml.etree.ElementTree import ElementTree import argparse import colorama import datetime",
"shutil.copy(exe(self.settings.maketx_path), bin_dir) def copy_schemas(self): progress(\"Copying schemas to root directory\") dir_util.copy_tree(self.settings.appleseed_schemas_path,",
"os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") for dirpath, dirnames, filenames in os.walk(lib_dir): for",
"\"libdrm\", \"libnsl\", \"libuuid\", \"libgthread\", \"libglib\", \"libgobject\", \"libglapi\", \"libffi\", \"libfontconfig\", \"libutil\",",
"self.run_subprocess([\"ldd\", filepath]) if returncode != 0: fatal(\"Failed to invoke ldd(1)",
"shaders_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"shaders\") safe_make_directory(shaders_dir) self.__do_copy_shaders(os.path.join(self.settings.appleseed_shaders_path, \"appleseed\"), shaders_dir) self.__do_copy_shaders(os.path.join(self.settings.appleseed_shaders_path,",
"Copying dependencies\") bin_dir = self.settings.appleseed_bin_path for dll in [\"appleseed.dll\", \"appleseed.shared.dll\"]:",
"time import traceback import urllib #-------------------------------------------------------------------------------------------------- # Constants. #-------------------------------------------------------------------------------------------------- VERSION",
"def safe_make_directory(path): if not os.path.isdir(path): os.makedirs(path) def pushd(path): old_path =",
"settings from \" + SETTINGS_FILENAME + \"...\") tree = ElementTree()",
"in self.SYSTEM_LIBS_PREFIXES: if lib.startswith(prefix): return True return False #-------------------------------------------------------------------------------------------------- #",
"package_name) archive_util.make_zipfile(package_path, \"blenderseed\") info(\"Package path: {0}\".format(package_path + \".zip\")) def remove_stage(self):",
"value #-------------------------------------------------------------------------------------------------- # Base package builder. #-------------------------------------------------------------------------------------------------- class PackageBuilder(object): def",
"os.chmod(path, stat.S_IWRITE) os.unlink(path) def safe_delete_directory(path): Attempts = 10 for attempt",
"if returncode != 0: fatal(\"Failed to invoke otool(1) to get",
"= os.path.expandvars(self.__get_required(tree, \"appleseed_bin_path\")) self.appleseed_lib_path = os.path.expandvars(self.__get_required(tree, \"appleseed_lib_path\")) self.appleseed_shaders_path = os.path.expandvars(self.__get_required(tree,",
"\"/System/Library/\", \"/usr/lib/libcurl\", \"/usr/lib/libc++\", \"/usr/lib/libbz2\", \"/usr/lib/libSystem\", #\"/usr/lib/libz\", \"/usr/lib/libncurses\", \"/usr/lib/libobjc.A.dylib\" ] def",
"for dirpath, dirnames, filenames in os.walk(bin_dir): for filename in filenames:",
"os.path.basename(lib_path) if path_to_appleseed_lib == \".\": self.__change_library_path(bin_path, lib_path, \"@loader_path/{0}\".format(lib_name)) else: self.__change_library_path(bin_path,",
"# Ignore appleseed libs. if \"libappleseed\" in line: continue libs.add(line.split()[2])",
"fatal(\"Failed to delete file '\" + path + \"'\") def",
"MacPackageBuilder(PackageBuilder): SYSTEM_LIBS_PREFIXES = [ \"/System/Library/\", \"/usr/lib/libcurl\", \"/usr/lib/libc++\", \"/usr/lib/libbz2\", \"/usr/lib/libSystem\", #\"/usr/lib/libz\",",
"to root directory\") # Create destination directory. settings_dir = os.path.join(self.settings.root_dir,",
"\" + self.platform) print(\" Path to appleseed release: \" +",
"= \"1.1.0\" SETTINGS_FILENAME = \"blenderseed.package.configuration.xml\" #-------------------------------------------------------------------------------------------------- # Utility functions. #--------------------------------------------------------------------------------------------------",
"{0} {1}\".format(RED_CROSSMARK, lib)) # Don't check for missing dependencies if",
"relative libs. if not os.path.isabs(lib): # TODO: generalize to a",
"\"appleseed_lib_path\")) self.appleseed_shaders_path = os.path.expandvars(self.__get_required(tree, \"appleseed_shaders_path\")) self.appleseed_schemas_path = os.path.expandvars(self.__get_required(tree, \"appleseed_schemas_path\")) self.appleseed_settings_path",
"= package_version self.build_date = build_date self.no_release = no_release def build_package(self):",
"\" + bin) for lib in glob.glob(os.path.join(self.settings.root_dir, \"appleseed\", \"lib\", \"*.so\")):",
"directory. bin_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"bin\") safe_make_directory(bin_dir) # Copy appleseed",
"__init__(self, settings, package_version, build_date, no_release=False): self.settings = settings self.package_version =",
"def copy_binaries(self): progress(\"Copying binaries to root directory\") # Create destination",
"deal # in the Software without restriction, including without limitation",
"(c) 2017-2018 <NAME>, The appleseedhq Organization # # Permission is",
"use, copy, modify, merge, publish, distribute, sublicense, and/or sell #",
"colorama.init() parser = argparse.ArgumentParser(description=\"build a blenderseed package from sources\") parser.add_argument(\"--nozip\",",
"\"/usr/local/lib/\" # TODO: a great simplification if True: trace(\"Gathering dependencies",
"all_libs = all_libs.union(appleseedpython_libs) # Get shared libs needed by libraries.",
"notice and this permission notice shall be included in #",
"#-------------------------------------------------------------------------------------------------- class PackageBuilder(object): def __init__(self, settings, package_version, build_date, no_release=False): self.settings",
"print(\" Path to appleseed binaries: \" + self.appleseed_bin_path) print(\" Path",
"print(u\"{0}Fatal: {1}. Aborting.{2}\".format(colorama.Style.BRIGHT + colorama.Fore.RED, message, colorama.Style.RESET_ALL).encode('utf-8')) if sys.exc_info()[0]: print(traceback.format_exc())",
"zip file from staging directory\") package_name = \"blenderseed-{0}-{1}-{2}\".format(self.package_version, self.settings.platform, self.build_date)",
"deploy_blenderseed_to_stage(self): progress(\"Deploying blenderseed to staging directory\") shutil.copytree(self.settings.root_dir, \"blenderseed\", ignore=shutil.ignore_patterns(\"scripts\")) def",
"\"appleseed\", \"schemas\", \".gitignore\")) def copy_shaders(self): progress(\"Copying shaders to root directory\")",
"build a release package\") args = parser.parse_args() no_release = args.nozip",
"# THE SOFTWARE. # from __future__ import print_function from distutils",
"f)) def deploy_blenderseed_to_stage(self): progress(\"Deploying blenderseed to staging directory\") shutil.copytree(self.settings.root_dir, \"blenderseed\",",
"] def copy_dependencies(self): progress(\"Mac-specific: Copying dependencies\") # Create destination directory.",
"[\".git\", \".idea\", \"archives\", \"docs\", \"scripts\", \"tests\"]: safe_delete_directory(os.path.join(\"blenderseed\", subdirectory)) for file",
"not be found on disk\".format(lib)) return libs def __is_system_lib(self, lib):",
"== \".so\": lib_path = os.path.join(dirpath, filename) self.__set_library_id(lib_path, filename) def __change_library_paths_in_libraries(self):",
"fix_paths: for lib in libs: if not os.path.isfile(lib): fatal(\"Dependency {0}",
"all_libs.union(lib_libs) # Copy all shared libraries. for lib in all_libs:",
"elif os.name == \"posix\" and platform.mac_ver()[0] != \"\": package_builder =",
"# Create destination directory. settings_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"settings\") safe_make_directory(settings_dir)",
"{0}Warning: {1}.{2}\".format(colorama.Style.BRIGHT + colorama.Fore.MAGENTA, message, colorama.Style.RESET_ALL).encode('utf-8')) def fatal(message): print(u\"{0}Fatal: {1}.",
"SETTINGS_FILENAME = \"blenderseed.package.configuration.xml\" #-------------------------------------------------------------------------------------------------- # Utility functions. #-------------------------------------------------------------------------------------------------- GREEN_CHECKMARK =",
"self.run('install_name_tool -change \"{0}\" \"{1}\" {2}'.format(old, new, target)) def __get_dependencies_for_file(self, filepath,",
"print(\" Path to appleseed release: \" + self.appleseed_release_path) print(\" Path",
"filenames in os.walk(lib_dir): for filename in filenames: ext = os.path.splitext(filename)[1]",
"\"libm.so\", \"libgcc\", \"libc.so\", \"/lib64/ld-linux-\", \"libstdc++\", \"libxcb\", \"libdrm\", \"libnsl\", \"libuuid\", \"libgthread\",",
"{0}\".format(lib)) # Copy needed libs to lib directory. for lib",
"= all_libs.union(appleseedpython_libs) # Get shared libs needed by libraries. lib_libs",
"_appleseedpython3.so (Python 3). # TODO: implement properly. safe_delete_file(os.path.join(lib_dir, \"appleseed\", \"_appleseedpython.so\"))",
"{0}\".format(package_path + \".zip\")) def remove_stage(self): progress(\"Deleting staging directory\") safe_delete_directory(\"blenderseed\") def",
"if len(line) == 0: continue # Parse the line. m",
"= Settings() settings.load() settings.print_summary() if os.name == \"nt\": package_builder =",
"to appleseed schemas: \" + self.appleseed_schemas_path) print(\" Path to appleseed",
"-id \"{0}\" {1}'.format(name, target)) def __change_library_path(self, target, old, new): self.run('install_name_tool",
"settings: \" + self.appleseed_settings_path) print(\" Path to appleseed.python: \" +",
"try: if os.path.exists(path): shutil.rmtree(path, onerror=on_rmtree_error) return except OSError: if attempt",
"+ colorama.Fore.GREEN, colorama.Style.RESET_ALL) RED_CROSSMARK = u\"{0}\\u2717{1}\".format(colorama.Style.BRIGHT + colorama.Fore.RED, colorama.Style.RESET_ALL) def",
"filename in filenames: ext = os.path.splitext(filename)[1] if ext != \".py\"",
"and associated documentation files (the 'Software'), to deal # in",
"+ self.appleseed_settings_path) print(\" Path to appleseed.python: \" + self.appleseed_python_path) print(\"",
"\"bin\", \"*\")): self.run(\"chrpath -r \\$ORIGIN/../lib \" + bin) for lib",
"in glob.glob(os.path.join(self.settings.root_dir, \"appleseed\", \"bin\", \"*\")): libs = self.__get_dependencies_for_file(bin) all_libs =",
"lib_dir) # Get shared libs needed by binaries. all_libs =",
"return libs def __is_system_lib(self, lib): for prefix in self.SYSTEM_LIBS_PREFIXES: if",
"OSError: fatal(\"Failed to delete file '\" + path + \"'\")",
"# This software is released under the MIT license. #",
"root directory\") dir_util.copy_tree(self.settings.appleseed_schemas_path, os.path.join(self.settings.root_dir, \"appleseed\", \"schemas\")) safe_delete_file(os.path.join(self.settings.root_dir, \"appleseed\", \"schemas\", \".gitignore\"))",
"lib in libs: if os.path.isfile(lib): trace(u\" {0} {1}\".format(GREEN_CHECKMARK, lib)) else:",
"Output directory: \" + self.output_dir) print(\"\") def __load_values(self, tree): self.platform",
"old_path def copy_glob(input_pattern, output_path): for input_file in glob.glob(input_pattern): shutil.copy(input_file, output_path)",
"but does not build a release package\") args = parser.parse_args()",
"ext != \".conf\": exe_path = os.path.join(dirpath, filename) self.__change_library_paths_in_binary(exe_path) # Can",
"# Mac package builder. #-------------------------------------------------------------------------------------------------- class MacPackageBuilder(PackageBuilder): SYSTEM_LIBS_PREFIXES = [",
"os.name == \"posix\" and platform.mac_ver()[0] != \"\": package_builder = MacPackageBuilder(settings,",
"# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO",
"empty lines. if len(line) == 0: continue # Parse the",
"trace(message): # encode('utf-8') is required to support output redirection to",
"for root, dirs, files in os.walk(os.path.join(self.settings.root_dir, \"appleseed\", \"lib\")): for f",
"safe_delete_directory(os.path.join(\"blenderseed\", subdirectory)) for file in [\".gitignore\", \"README.md\"]: safe_delete_file(os.path.join(\"blenderseed\", file)) def",
"# TODO: generalize to a collection of user-specified search paths.",
"progress(\"Downloading settings files to root directory\") # Create destination directory.",
"# Create destination directory. lib_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") safe_make_directory(lib_dir)",
"to a collection of user-specified search paths. candidate = os.path.join(loader_path,",
"line.strip() # Ignore empty lines. if len(line) == 0: continue",
"to deal # in the Software without restriction, including without",
"read-only and unlink it. os.chmod(path, stat.S_IWRITE) os.unlink(path) def safe_delete_directory(path): Attempts",
"TODO: generalize to a collection of user-specified search paths. candidate",
"and platform.mac_ver()[0] != \"\": package_builder = MacPackageBuilder(settings, package_version, build_date, no_release)",
"FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN",
"self-references (why do these happen?). if lib == filename: continue",
"SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,",
"= os.getcwd() os.chdir(path) return old_path def copy_glob(input_pattern, output_path): for input_file",
"\"/usr/lib/libSystem\", #\"/usr/lib/libz\", \"/usr/lib/libncurses\", \"/usr/lib/libobjc.A.dylib\" ] def copy_dependencies(self): progress(\"Mac-specific: Copying dependencies\")",
"in all_libs: shutil.copy(lib, lib_dir) def post_process_package(self): progress(\"Linux-specific: Post-processing package\") for",
"since blenderseed only needs _appleseedpython3.so (Python 3). # TODO: implement",
"Create destination directory. bin_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"bin\") safe_make_directory(bin_dir) #",
"from sources\") parser.add_argument(\"--nozip\", action=\"store_true\", help=\"copies appleseed binaries to blenderseed folder",
"VERSION) print(\"\") settings = Settings() settings.load() settings.print_summary() if os.name ==",
"for entry in os.listdir(root_path): subdirectory = os.path.join(root_path, entry) if os.path.isdir(subdirectory):",
"def copy_dependencies(self): progress(\"Linux-specific: Copying dependencies\") # Create destination directory. lib_dir",
"progress(\"Linux-specific: Post-processing package\") for bin in glob.glob(os.path.join(self.settings.root_dir, \"appleseed\", \"bin\", \"*\")):",
"for additional information and resources. # # This software is",
"\" + self.output_dir) print(\"\") def __load_values(self, tree): self.platform = self.__get_required(tree,",
"target, old, new): self.run('install_name_tool -change \"{0}\" \"{1}\" {2}'.format(old, new, target))",
"def __get_dependencies_for_file(self, filepath): returncode, out, err = self.run_subprocess([\"ldd\", filepath]) if",
"value = tree.findtext(key) if value is None: fatal(\"Missing value \\\"{0}\\\"",
"= os.path.expandvars(self.__get_required(tree, \"appleseed_shaders_path\")) self.appleseed_schemas_path = os.path.expandvars(self.__get_required(tree, \"appleseed_schemas_path\")) self.appleseed_settings_path = os.path.expandvars(self.__get_required(tree,",
"self.download_settings_files() self.remove_pyc_files() self.post_process_package() if not self.no_release: self.deploy_blenderseed_to_stage() self.clean_stage() self.build_final_zip_file() self.remove_stage()",
"shutil.copy(input_file, output_path) #-------------------------------------------------------------------------------------------------- # Settings. #-------------------------------------------------------------------------------------------------- class Settings: def load(self):",
"{0}:\".format(filepath)) for lib in libs: if os.path.isfile(lib): trace(u\" {0} {1}\".format(GREEN_CHECKMARK,",
"for filename in filenames: ext = os.path.splitext(filename)[1] if ext ==",
"if attempt < Attempts - 1: time.sleep(0.5) else: fatal(\"Failed to",
"to root directory\") # Create destination directory. bin_dir = os.path.join(self.settings.root_dir,",
"= os.path.relpath(lib_dir, bin_dir) # fix_paths set to False because we",
"Print dependencies. trace(\" Dependencies:\") for lib in all_libs: trace(\" {0}\".format(lib))",
"import stat import subprocess import sys import time import traceback",
"class LinuxPackageBuilder(PackageBuilder): SYSTEM_LIBS_PREFIXES = [ \"linux\", \"librt\", \"libpthread\", \"libGL\", \"libX\",",
"def __change_library_paths_in_binary(self, bin_path): progress(\"Patching {0}\".format(bin_path)) bin_dir = os.path.dirname(bin_path) lib_dir =",
"to parse line from otool(1) output: \" + line) lib",
"Copying dependencies\") # Create destination directory. lib_dir = os.path.join(self.settings.root_dir, \"appleseed\",",
"settings.load() settings.print_summary() if os.name == \"nt\": package_builder = WindowsPackageBuilder(settings, package_version,",
"appleseed.python: \" + self.appleseed_python_path) print(\" Path to maketx: \" +",
"+ colorama.Fore.MAGENTA, message, colorama.Style.RESET_ALL).encode('utf-8')) def fatal(message): print(u\"{0}Fatal: {1}. Aborting.{2}\".format(colorama.Style.BRIGHT +",
"lib_path in self.__get_dependencies_for_file(bin_path, fix_paths=False): lib_name = os.path.basename(lib_path) if path_to_appleseed_lib ==",
"skip the first line line = line.strip() # Ignore empty",
"Get shared libs needed by libraries. # TODO: we're not",
"release: \" + self.appleseed_release_path) print(\" Path to appleseed binaries: \"",
"_appleseedpython.so (Python 2) since blenderseed only needs _appleseedpython3.so (Python 3).",
"self.build_date = build_date self.no_release = no_release def build_package(self): print(\"Building package:\")",
"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN",
"directory\") # Create destination directory. settings_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"settings\")",
"# Base package builder. #-------------------------------------------------------------------------------------------------- class PackageBuilder(object): def __init__(self, settings,",
"in glob.glob(input_pattern): shutil.copy(input_file, output_path) #-------------------------------------------------------------------------------------------------- # Settings. #-------------------------------------------------------------------------------------------------- class Settings:",
"dependencies. trace(\" Dependencies:\") for lib in all_libs: trace(\" {0}\".format(lib)) #",
"not self.no_release: self.deploy_blenderseed_to_stage() self.clean_stage() self.build_final_zip_file() self.remove_stage() def remove_leftovers(self): progress(\"Removing leftovers",
"Copying {0} to {1}...\".format(lib, lib_dir)) shutil.copy(lib, lib_dir) def post_process_package(self): progress(\"Mac-specific:",
"\"libICE\", \"libSM\", \"libdl\", \"libm.so\", \"libgcc\", \"libc.so\", \"/lib64/ld-linux-\", \"libstdc++\", \"libxcb\", \"libdrm\",",
"self.appleseed_bin_path = os.path.expandvars(self.__get_required(tree, \"appleseed_bin_path\")) self.appleseed_lib_path = os.path.expandvars(self.__get_required(tree, \"appleseed_lib_path\")) self.appleseed_shaders_path =",
"continue libs.add(line.split()[2]) return libs #-------------------------------------------------------------------------------------------------- # Entry point. #-------------------------------------------------------------------------------------------------- def",
"# Parse the line. m = re.match(r\"(.*) \\(compatibility version .*,",
"the first line line = line.strip() # Ignore empty lines.",
"or substantial portions of the Software. # # THE SOFTWARE",
"OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR",
"to delete directory '\" + path + \"'\") def safe_delete_directory_recursively(root_path,",
"= [ \"/System/Library/\", \"/usr/lib/libcurl\", \"/usr/lib/libc++\", \"/usr/lib/libbz2\", \"/usr/lib/libSystem\", #\"/usr/lib/libz\", \"/usr/lib/libncurses\", \"/usr/lib/libobjc.A.dylib\"",
"info(\"Resolved relative dependency {0} as {1}\".format(lib, candidate)) lib = candidate",
"= no_release def build_package(self): print(\"Building package:\") print(\"\") self.orchestrate() print(\"\") print(\"The",
"platform.mac_ver()[0] == \"\": package_builder = LinuxPackageBuilder(settings, package_version, build_date, no_release) else:",
"def copy_glob(input_pattern, output_path): for input_file in glob.glob(input_pattern): shutil.copy(input_file, output_path) #--------------------------------------------------------------------------------------------------",
"CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION",
"shutil.copy(lib, lib_dir) def post_process_package(self): progress(\"Linux-specific: Post-processing package\") for bin in",
"IN # THE SOFTWARE. # from __future__ import print_function from",
"libraries: \" + self.appleseed_lib_path) print(\" Path to appleseed shaders: \"",
"if os.path.isfile(lib): trace(u\" {0} {1}\".format(GREEN_CHECKMARK, lib)) else: trace(u\" {0} {1}\".format(RED_CROSSMARK,",
"self.SYSTEM_LIBS_PREFIXES: if lib.startswith(prefix): return True return False #-------------------------------------------------------------------------------------------------- # Linux",
"\"libglib\", \"libgobject\", \"libglapi\", \"libffi\", \"libfontconfig\", \"libutil\", \"libpython\", \"libxshmfence.so\" ] def",
"order to replace it by the correct one. for lib_path",
"trace(\" {0}\".format(rpath)) returncode, out, err = self.run_subprocess([\"otool\", \"-L\", filepath]) if",
"self.appleseed_schemas_path = os.path.expandvars(self.__get_required(tree, \"appleseed_schemas_path\")) self.appleseed_settings_path = os.path.expandvars(self.__get_required(tree, \"appleseed_settings_path\")) self.appleseed_python_path =",
"if not self.no_release: self.deploy_blenderseed_to_stage() self.clean_stage() self.build_final_zip_file() self.remove_stage() def remove_leftovers(self): progress(\"Removing",
"for file in [\".gitignore\", \"README.md\"]: safe_delete_file(os.path.join(\"blenderseed\", file)) def build_final_zip_file(self): progress(\"Building",
"Attempts = 10 for attempt in range(Attempts): try: if os.path.exists(path):",
"if f.endswith(\".pyc\"): safe_delete_file(os.path.join(root, f)) def deploy_blenderseed_to_stage(self): progress(\"Deploying blenderseed to staging",
"file)) def build_final_zip_file(self): progress(\"Building final zip file from staging directory\")",
"trace(\"Gathering dependencies for file\") trace(\" {0}\".format(filepath)) trace(\"with @loader_path set to\")",
"\"libX\", \"libselinux\", \"libICE\", \"libSM\", \"libdl\", \"libm.so\", \"libgcc\", \"libc.so\", \"/lib64/ld-linux-\", \"libstdc++\",",
"fatal(\"Missing value \\\"{0}\\\" in configuration file\".format(key)) return value #-------------------------------------------------------------------------------------------------- #",
"os.path.exists(candidate): candidate = os.path.join(\"/usr/local/lib/\", lib) if os.path.exists(candidate): info(\"Resolved relative dependency",
"colorama.Fore.WHITE, message, colorama.Style.RESET_ALL).encode('utf-8')) def info(message): print(u\" {0}\".format(message).encode('utf-8')) def progress(message): print(u\"",
"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER",
"for lib in all_libs: trace(\" {0}\".format(lib)) # Copy needed libs",
"to appleseed.python: \" + self.appleseed_python_path) print(\" Path to maketx: \"",
"= set() for lib in all_libs: libs = self.__get_dependencies_for_file(lib) lib_libs",
"so, subject to the following conditions: # # The above",
"os.path.expandvars(self.__get_required(tree, \"appleseed_shaders_path\")) self.appleseed_schemas_path = os.path.expandvars(self.__get_required(tree, \"appleseed_schemas_path\")) self.appleseed_settings_path = os.path.expandvars(self.__get_required(tree, \"appleseed_settings_path\"))",
"\"libappleseed\" in line: continue libs.add(line.split()[2]) return libs #-------------------------------------------------------------------------------------------------- # Entry",
"self.run_subprocess([\"otool\", \"-L\", filepath]) if returncode != 0: fatal(\"Failed to invoke",
"all_libs.union(appleseedpython_libs) # Get shared libs needed by libraries. lib_libs =",
"os.system(cmdline) def run_subprocess(self, cmdline): p = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out,",
"import datetime import glob import os import platform import re",
"'\" + SETTINGS_FILENAME + \"'\") self.__load_values(tree) def print_summary(self): print(\"\") print(\"",
"successfully built.\") def orchestrate(self): self.remove_leftovers() self.copy_appleseed_python() self.copy_binaries() self.copy_dependencies() self.copy_schemas() self.copy_shaders()",
"contains the path of the file that couldn't be removed.",
"== \"\": package_builder = LinuxPackageBuilder(settings, package_version, build_date, no_release) else: fatal(\"Unsupported",
"#-------------------------------------------------------------------------------------------------- class MacPackageBuilder(PackageBuilder): SYSTEM_LIBS_PREFIXES = [ \"/System/Library/\", \"/usr/lib/libcurl\", \"/usr/lib/libc++\", \"/usr/lib/libbz2\",",
"to blenderseed folder but does not build a release package\")",
"output: \" + line) lib = m.group(1) # Ignore self-references",
"# Copy all shared libraries. for lib in all_libs: shutil.copy(lib,",
"self.set_libraries_ids() self.__change_library_paths_in_libraries() self.__change_library_paths_in_executables() def set_libraries_ids(self): lib_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\")",
"os.path.join(dirpath, filename) self.__set_library_id(lib_path, filename) def __change_library_paths_in_libraries(self): lib_dir = os.path.join(self.settings.root_dir, \"appleseed\",",
"the following conditions: # # The above copyright notice and",
"{0}\".format(bin_path)) bin_dir = os.path.dirname(bin_path) lib_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") path_to_appleseed_lib",
"FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE",
"self.settings.appleseed_bin_path for dll in [\"appleseed.dll\", \"appleseed.shared.dll\"]: shutil.copy(os.path.join(bin_dir, dll), os.path.join(self.settings.root_dir, \"appleseed\",",
"\"/usr/lib/libc++\", \"/usr/lib/libbz2\", \"/usr/lib/libSystem\", #\"/usr/lib/libz\", \"/usr/lib/libncurses\", \"/usr/lib/libobjc.A.dylib\" ] def copy_dependencies(self): progress(\"Mac-specific:",
"\"libuuid\", \"libgthread\", \"libglib\", \"libgobject\", \"libglapi\", \"libffi\", \"libfontconfig\", \"libutil\", \"libpython\", \"libxshmfence.so\"",
"appleseed binaries: \" + self.appleseed_bin_path) print(\" Path to appleseed libraries:",
"all_libs.union(libs) # Get shared libs needed by appleseed.python. appleseedpython_libs =",
"if sys.exc_info()[0]: print(traceback.format_exc()) sys.exit(1) def exe(filepath): return filepath + \".exe\"",
"This software is released under the MIT license. # #",
"def progress(message): print(u\" {0}...\".format(message).encode('utf-8')) def warning(message): print(u\" {0}Warning: {1}.{2}\".format(colorama.Style.BRIGHT +",
"[\".gitignore\", \"README.md\"]: safe_delete_file(os.path.join(\"blenderseed\", file)) def build_final_zip_file(self): progress(\"Building final zip file",
"self.appleseed_release_path) print(\" Path to appleseed binaries: \" + self.appleseed_bin_path) print(\"",
"\" + self.maketx_path) print(\" Output directory: \" + self.output_dir) print(\"\")",
"package builder. #-------------------------------------------------------------------------------------------------- class WindowsPackageBuilder(PackageBuilder): def copy_dependencies(self): progress(\"Windows-specific: Copying dependencies\")",
"{0} could not be found on disk\".format(lib)) return libs def",
"# Entry point. #-------------------------------------------------------------------------------------------------- def main(): colorama.init() parser = argparse.ArgumentParser(description=\"build",
"in # all copies or substantial portions of the Software.",
"build_date = datetime.date.today().isoformat() print(\"blenderseed.package version \" + VERSION) print(\"\") settings",
"self.build_date) package_path = os.path.join(self.settings.output_dir, package_name) archive_util.make_zipfile(package_path, \"blenderseed\") info(\"Package path: {0}\".format(package_path",
"= os.path.splitext(filename)[1] if ext != \".py\" and ext != \".conf\":",
"# Get shared libs needed by libraries. lib_libs = set()",
"\"_appleseedpython3.so\")) all_libs = all_libs.union(appleseedpython_libs) # Get shared libs needed by",
"package from sources\") parser.add_argument(\"--nozip\", action=\"store_true\", help=\"copies appleseed binaries to blenderseed",
"if os.name == \"nt\" else filepath def safe_delete_file(path): try: if",
"= p.communicate() return p.returncode, out, err #-------------------------------------------------------------------------------------------------- # Windows package",
"\" + self.appleseed_schemas_path) print(\" Path to appleseed settings: \" +",
"to any person obtaining a copy # of this software",
"os.name == \"nt\" else filepath def safe_delete_file(path): try: if os.path.exists(path):",
"\"appleseed\", \"bin\") safe_make_directory(bin_dir) # Copy appleseed binaries. for bin in",
"dll in [\"appleseed.dll\", \"appleseed.shared.dll\"]: shutil.copy(os.path.join(bin_dir, dll), os.path.join(self.settings.root_dir, \"appleseed\", \"bin\")) def",
"Handle libs relative to @rpath. lib = lib.replace(\"@rpath\", rpath) #",
"-d \" + lib) appleseed_python_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\", \"appleseed\")",
"def __set_library_id(self, target, name): self.run('install_name_tool -id \"{0}\" {1}'.format(name, target)) def",
"self.run(\"chrpath -d \" + lib) appleseed_python_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\",",
"of the Software, and to permit persons to whom the",
"safe_make_directory(bin_dir) # Copy appleseed binaries. for bin in [exe(\"appleseed.cli\")]: shutil.copy(os.path.join(self.settings.appleseed_bin_path,",
"package was successfully built.\") def orchestrate(self): self.remove_leftovers() self.copy_appleseed_python() self.copy_binaries() self.copy_dependencies()",
"os.path.join(self.settings.root_dir, \"appleseed\", \"bin\") for dirpath, dirnames, filenames in os.walk(bin_dir): for",
"to handle other relative libs. if not os.path.isabs(lib): # TODO:",
"root directory\") for root, dirs, files in os.walk(os.path.join(self.settings.root_dir, \"appleseed\", \"lib\")):",
"colorama import datetime import glob import os import platform import",
"os.path.isfile(lib): fatal(\"Dependency {0} could not be found on disk\".format(lib)) return",
"import colorama import datetime import glob import os import platform",
"self.run(\"chrpath -r \\$ORIGIN/../ \" + py_cpp_module) def __is_system_lib(self, lib): for",
"= all_libs.union(libs) # Get shared libs needed by appleseed.python. appleseedpython_libs",
"appleseedhq Organization # # Permission is hereby granted, free of",
"dependencies\") bin_dir = self.settings.appleseed_bin_path for dll in [\"appleseed.dll\", \"appleseed.shared.dll\"]: shutil.copy(os.path.join(bin_dir,",
"bin) for lib in glob.glob(os.path.join(self.settings.root_dir, \"appleseed\", \"lib\", \"*.so\")): self.run(\"chrpath -d",
"f.endswith(\".pyc\"): safe_delete_file(os.path.join(root, f)) def deploy_blenderseed_to_stage(self): progress(\"Deploying blenderseed to staging directory\")",
"Copy appleseed binaries. for bin in [exe(\"appleseed.cli\")]: shutil.copy(os.path.join(self.settings.appleseed_bin_path, bin), bin_dir)",
"+ bin) for lib in glob.glob(os.path.join(self.settings.root_dir, \"appleseed\", \"lib\", \"*.so\")): self.run(\"chrpath",
"sublicense, and/or sell # copies of the Software, and to",
"\"/usr/lib/libobjc.A.dylib\" ] def copy_dependencies(self): progress(\"Mac-specific: Copying dependencies\") # Create destination",
"progress(\"Removing leftovers from previous invocations\") safe_delete_directory(os.path.join(self.settings.root_dir, \"appleseed\")) safe_delete_directory(\"blenderseed\") def copy_appleseed_python(self):",
"to invoke otool(1) to get dependencies for {0}: {1}\".format(filepath, err))",
"2017-2018 <NAME>, The appleseedhq Organization # # Permission is hereby",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING",
"self.__change_library_paths_in_binary(lib_path) def __change_library_paths_in_executables(self): bin_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"bin\") for dirpath,",
"file\") trace(\" {0}\".format(filepath)) trace(\"with @loader_path set to\") trace(\" {0}\".format(loader_path)) trace(\"and",
"progress(\"Patching {0}\".format(bin_path)) bin_dir = os.path.dirname(bin_path) lib_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\")",
"in the Software without restriction, including without limitation the rights",
"if re.search(r\"Qt.*\\.framework\", lib): continue if fix_paths: # Handle libs relative",
"os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") path_to_appleseed_lib = os.path.relpath(lib_dir, bin_dir) # fix_paths set",
"+ self.appleseed_lib_path) print(\" Path to appleseed shaders: \" + self.appleseed_shaders_path)",
"self.appleseed_release_path = self.__get_required(tree, \"appleseed_release_path\") os.environ['APPLESEED'] = self.appleseed_release_path self.appleseed_bin_path = os.path.expandvars(self.__get_required(tree,",
"os.path.expandvars(self.__get_required(tree, \"appleseed_lib_path\")) self.appleseed_shaders_path = os.path.expandvars(self.__get_required(tree, \"appleseed_shaders_path\")) self.appleseed_schemas_path = os.path.expandvars(self.__get_required(tree, \"appleseed_schemas_path\"))",
"and ext != \".conf\": exe_path = os.path.join(dirpath, filename) self.__change_library_paths_in_binary(exe_path) #",
"for f in files: if f.endswith(\".pyc\"): safe_delete_file(os.path.join(root, f)) def deploy_blenderseed_to_stage(self):",
"__get_dependencies_for_file(self, filepath, fix_paths=True): filename = os.path.basename(filepath) loader_path = os.path.dirname(filepath) rpath",
"transitive closure here! lib_libs = set() for lib in all_libs:",
"return True return False def __get_dependencies_for_file(self, filepath): returncode, out, err",
"package\") args = parser.parse_args() no_release = args.nozip package_version = subprocess.Popen(\"git",
"dependencies for file\") trace(\" {0}\".format(filepath)) trace(\"with @loader_path set to\") trace(\"",
"safe_make_directory(settings_dir) for file in [\"appleseed.cli.xml\"]: urllib.urlretrieve( \"https://raw.githubusercontent.com/appleseedhq/appleseed/master/sandbox/settings/{0}\".format(file), os.path.join(settings_dir, file)) def",
"re.search(r\"Qt.*\\.framework\", lib): continue if fix_paths: # Handle libs relative to",
"including without limitation the rights # to use, copy, modify,",
"schemas: \" + self.appleseed_schemas_path) print(\" Path to appleseed settings: \"",
"filename in filenames: ext = os.path.splitext(filename)[1] if ext == \".dylib\"",
"because we must retrieve the unmodified dependency in order to",
"os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") safe_make_directory(lib_dir) # Copy appleseed libraries. for lib",
"missing dependencies if we didn't attempt to fix them. if",
"(Python 2) since blenderseed only needs _appleseedpython3.so (Python 3). #",
"dirnames, filenames in os.walk(lib_dir): for filename in filenames: ext =",
"err = p.communicate() return p.returncode, out, err #-------------------------------------------------------------------------------------------------- # Windows",
"{1}\".format(RED_CROSSMARK, lib)) # Don't check for missing dependencies if we",
"target)) def __get_dependencies_for_file(self, filepath, fix_paths=True): filename = os.path.basename(filepath) loader_path =",
"fatal(\"Failed to delete directory '\" + path + \"'\") def",
"os.makedirs(path) def pushd(path): old_path = os.getcwd() os.chdir(path) return old_path def",
"print(\"The package was successfully built.\") def orchestrate(self): self.remove_leftovers() self.copy_appleseed_python() self.copy_binaries()",
"package_version, build_date, no_release) elif os.name == \"posix\" and platform.mac_ver()[0] !=",
"line = line.strip() # Ignore empty lines. if len(line) ==",
"lib.replace(\"@loader_path\", loader_path) # Handle libs relative to @rpath. lib =",
"Get shared libs needed by binaries. all_libs = set() for",
"\"appleseed_python_path\")) self.maketx_path = os.path.expandvars(self.__get_required(tree, \"maketx_path\")) self.output_dir = os.path.expandvars(self.__get_required(tree, \"output_dir\")) def",
"WindowsPackageBuilder(PackageBuilder): def copy_dependencies(self): progress(\"Windows-specific: Copying dependencies\") bin_dir = self.settings.appleseed_bin_path for",
"print(\" Path to appleseed settings: \" + self.appleseed_settings_path) print(\" Path",
"line) lib = m.group(1) # Ignore self-references (why do these",
"OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE",
"return except OSError: if attempt < Attempts - 1: time.sleep(0.5)",
"MIT license. # # Copyright (c) 2017-2018 <NAME>, The appleseedhq",
"xml.etree.ElementTree import ElementTree import argparse import colorama import datetime import",
"if value is None: fatal(\"Missing value \\\"{0}\\\" in configuration file\".format(key))",
"os.name == \"posix\" and platform.mac_ver()[0] == \"\": package_builder = LinuxPackageBuilder(settings,",
"colorama.Fore.RED, colorama.Style.RESET_ALL) def trace(message): # encode('utf-8') is required to support",
"class MacPackageBuilder(PackageBuilder): SYSTEM_LIBS_PREFIXES = [ \"/System/Library/\", \"/usr/lib/libcurl\", \"/usr/lib/libc++\", \"/usr/lib/libbz2\", \"/usr/lib/libSystem\",",
"lib)) # Don't check for missing dependencies if we didn't",
"import argparse import colorama import datetime import glob import os",
"# Ignore self-references (why do these happen?). if lib ==",
"= os.path.join(self.settings.root_dir, \"appleseed\", \"shaders\") safe_make_directory(shaders_dir) self.__do_copy_shaders(os.path.join(self.settings.appleseed_shaders_path, \"appleseed\"), shaders_dir) self.__do_copy_shaders(os.path.join(self.settings.appleseed_shaders_path, \"blenderseed\"),",
"] def plugin_extension(self): return \".so\" def copy_dependencies(self): progress(\"Linux-specific: Copying dependencies\")",
".*, current version .*\\)\", line) if not m: fatal(\"Failed to",
"return False def __get_dependencies_for_file(self, filepath): returncode, out, err = self.run_subprocess([\"ldd\",",
"print(\"\") print(\" Platform: \" + self.platform) print(\" Path to appleseed",
"Get shared libs needed by appleseed.python. appleseedpython_libs = self.__get_dependencies_for_file( os.path.join(self.settings.root_dir,",
"= self.__get_dependencies_for_file(lib) lib_libs = lib_libs.union(libs) all_libs = all_libs.union(lib_libs) # Copy",
"subprocess.Popen(\"git describe --long\", stdout=subprocess.PIPE, shell=True).stdout.read().strip() build_date = datetime.date.today().isoformat() print(\"blenderseed.package version",
"permit persons to whom the Software is # furnished to",
"progress(\"Deploying blenderseed to staging directory\") shutil.copytree(self.settings.root_dir, \"blenderseed\", ignore=shutil.ignore_patterns(\"scripts\")) def clean_stage(self):",
"THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE",
"glob.glob(os.path.join(self.settings.root_dir, \"appleseed\", \"bin\", \"*\")): libs = self.__get_dependencies_for_file(bin) all_libs = all_libs.union(libs)",
"self.__set_library_id(lib_path, filename) def __change_library_paths_in_libraries(self): lib_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") for",
"bin_dir = os.path.dirname(bin_path) lib_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") path_to_appleseed_lib =",
"above copyright notice and this permission notice shall be included",
"safe_make_directory(lib_dir) # Copy appleseed.python. dir_util.copy_tree(self.settings.appleseed_python_path, lib_dir) # Remove _appleseedpython.so (Python",
"\"appleseed\") for py_cpp_module in glob.glob(os.path.join(appleseed_python_dir, \"*.so\")): self.run(\"chrpath -r \\$ORIGIN/../ \"",
"\"appleseed\", \"bin\", \"*\")): self.run(\"chrpath -r \\$ORIGIN/../lib \" + bin) for",
"license. # # Copyright (c) 2017-2018 <NAME>, The appleseedhq Organization",
"not os.path.exists(candidate): candidate = os.path.join(\"/usr/local/lib/\", lib) if os.path.exists(candidate): info(\"Resolved relative",
"in [\"libappleseed.so\", \"libappleseed.shared.so\"]: shutil.copy(os.path.join(self.settings.appleseed_lib_path, lib), lib_dir) # Get shared libs",
"without limitation the rights # to use, copy, modify, merge,",
"\"lib\")): for f in files: if f.endswith(\".pyc\"): safe_delete_file(os.path.join(root, f)) def",
"run(self, cmdline): trace(\"Running command line: {0}\".format(cmdline)) os.system(cmdline) def run_subprocess(self, cmdline):",
"line in out.split(\"\\n\")[1:]: # skip the first line line =",
"!= \"\": package_builder = MacPackageBuilder(settings, package_version, build_date, no_release) elif os.name",
"EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE",
"import time import traceback import urllib #-------------------------------------------------------------------------------------------------- # Constants. #--------------------------------------------------------------------------------------------------",
"pushd(path): old_path = os.getcwd() os.chdir(path) return old_path def copy_glob(input_pattern, output_path):",
"args = parser.parse_args() no_release = args.nozip package_version = subprocess.Popen(\"git describe",
"0: fatal(\"Failed to invoke ldd(1) to get dependencies for {0}:",
"\"settings\") safe_make_directory(settings_dir) for file in [\"appleseed.cli.xml\"]: urllib.urlretrieve( \"https://raw.githubusercontent.com/appleseedhq/appleseed/master/sandbox/settings/{0}\".format(file), os.path.join(settings_dir, file))",
"here! lib_libs = set() for lib in all_libs: libs =",
"fix_paths: # Handle libs relative to @loader_path. lib = lib.replace(\"@loader_path\",",
"to get dependencies for {0}: {1}\".format(filepath, err)) libs = set()",
"def main(): colorama.init() parser = argparse.ArgumentParser(description=\"build a blenderseed package from",
"os.path.join(root_path, entry) if os.path.isdir(subdirectory): safe_delete_directory_recursively(subdirectory, directory_name) def safe_make_directory(path): if not",
"== \"posix\" and platform.mac_ver()[0] != \"\": package_builder = MacPackageBuilder(settings, package_version,",
"# Try to handle other relative libs. if not os.path.isabs(lib):",
"def safe_delete_file(path): try: if os.path.exists(path): os.remove(path) except OSError: fatal(\"Failed to",
"staging directory\") shutil.copytree(self.settings.root_dir, \"blenderseed\", ignore=shutil.ignore_patterns(\"scripts\")) def clean_stage(self): progress(\"Cleaning staging directory\")",
"\"lib\", \"appleseed\", \"_appleseedpython3.so\")) all_libs = all_libs.union(appleseedpython_libs) # Get shared libs",
"ext == \".dylib\" or ext == \".so\": lib_path = os.path.join(dirpath,",
"datetime import glob import os import platform import re import",
"ElementTree() try: tree.parse(SETTINGS_FILENAME) except IOError: fatal(\"Failed to load configuration file",
"candidate = os.path.join(\"/usr/local/lib/\", lib) if os.path.exists(candidate): info(\"Resolved relative dependency {0}",
"ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT",
"def __get_required(self, tree, key): value = tree.findtext(key) if value is",
"progress(\"Building final zip file from staging directory\") package_name = \"blenderseed-{0}-{1}-{2}\".format(self.package_version,",
"os.path.join(self.settings.root_dir, \"appleseed\", \"shaders\") safe_make_directory(shaders_dir) self.__do_copy_shaders(os.path.join(self.settings.appleseed_shaders_path, \"appleseed\"), shaders_dir) self.__do_copy_shaders(os.path.join(self.settings.appleseed_shaders_path, \"blenderseed\"), shaders_dir)",
"+ \"'\") def safe_delete_directory_recursively(root_path, directory_name): safe_delete_directory(os.path.join(root_path, directory_name)) for entry in",
"\"appleseed\"), shaders_dir) self.__do_copy_shaders(os.path.join(self.settings.appleseed_shaders_path, \"blenderseed\"), shaders_dir) def __do_copy_shaders(self, source_dir, target_dir): for",
"__do_copy_shaders(self, source_dir, target_dir): for root, dirs, files in os.walk(source_dir): for",
"OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT,",
"THE SOFTWARE OR THE USE OR OTHER DEALINGS IN #",
"\"shaders\") safe_make_directory(shaders_dir) self.__do_copy_shaders(os.path.join(self.settings.appleseed_shaders_path, \"appleseed\"), shaders_dir) self.__do_copy_shaders(os.path.join(self.settings.appleseed_shaders_path, \"blenderseed\"), shaders_dir) def __do_copy_shaders(self,",
"publish, distribute, sublicense, and/or sell # copies of the Software,",
"path contains the path of the file that couldn't be",
"safe_delete_file(os.path.join(lib_dir, \"appleseed\", \"_appleseedpython.pyd\")) def copy_binaries(self): progress(\"Copying binaries to root directory\")",
"to the following conditions: # # The above copyright notice",
"old_path = os.getcwd() os.chdir(path) return old_path def copy_glob(input_pattern, output_path): for",
"+ self.appleseed_release_path) print(\" Path to appleseed binaries: \" + self.appleseed_bin_path)",
"def on_rmtree_error(func, path, exc_info): # path contains the path of",
"libs relative to @rpath. lib = lib.replace(\"@rpath\", rpath) # Try",
"if os.path.exists(path): shutil.rmtree(path, onerror=on_rmtree_error) return except OSError: if attempt <",
"settings_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"settings\") safe_make_directory(settings_dir) for file in [\"appleseed.cli.xml\"]:",
"\"libstdc++\", \"libxcb\", \"libdrm\", \"libnsl\", \"libuuid\", \"libgthread\", \"libglib\", \"libgobject\", \"libglapi\", \"libffi\",",
"3). # TODO: implement properly. safe_delete_file(os.path.join(lib_dir, \"appleseed\", \"_appleseedpython.so\")) safe_delete_file(os.path.join(lib_dir, \"appleseed\",",
"re import shutil import stat import subprocess import sys import",
"version \" + VERSION) print(\"\") settings = Settings() settings.load() settings.print_summary()",
"print(\" Output directory: \" + self.output_dir) print(\"\") def __load_values(self, tree):",
"os.path.exists(candidate): info(\"Resolved relative dependency {0} as {1}\".format(lib, candidate)) lib =",
"parser.add_argument(\"--nozip\", action=\"store_true\", help=\"copies appleseed binaries to blenderseed folder but does",
"# Visit https://appleseedhq.net/ for additional information and resources. # #",
"\"appleseed\", \"lib\") path_to_appleseed_lib = os.path.relpath(lib_dir, bin_dir) # fix_paths set to",
"trace(\" {0}\".format(filepath)) trace(\"with @loader_path set to\") trace(\" {0}\".format(loader_path)) trace(\"and @rpath",
"(the 'Software'), to deal # in the Software without restriction,",
"# to use, copy, modify, merge, publish, distribute, sublicense, and/or",
"self.no_release = no_release def build_package(self): print(\"Building package:\") print(\"\") self.orchestrate() print(\"\")",
"-change \"{0}\" \"{1}\" {2}'.format(old, new, target)) def __get_dependencies_for_file(self, filepath, fix_paths=True):",
"self.__is_system_lib(lib): continue # Ignore Qt frameworks. if re.search(r\"Qt.*\\.framework\", lib): continue",
"\"libxcb\", \"libdrm\", \"libnsl\", \"libuuid\", \"libgthread\", \"libglib\", \"libgobject\", \"libglapi\", \"libffi\", \"libfontconfig\",",
"self.post_process_package() if not self.no_release: self.deploy_blenderseed_to_stage() self.clean_stage() self.build_final_zip_file() self.remove_stage() def remove_leftovers(self):",
"file from staging directory\") package_name = \"blenderseed-{0}-{1}-{2}\".format(self.package_version, self.settings.platform, self.build_date) package_path",
"full transitive closure here! lib_libs = set() for lib in",
"shutil.copytree(self.settings.root_dir, \"blenderseed\", ignore=shutil.ignore_patterns(\"scripts\")) def clean_stage(self): progress(\"Cleaning staging directory\") safe_delete_directory_recursively(\"blenderseed\", \"__pycache__\")",
"# Copyright (c) 2017-2018 <NAME>, The appleseedhq Organization # #",
"lib_libs = set() for lib in all_libs: libs = self.__get_dependencies_for_file(lib)",
"if len(line) == 0: continue # Ignore system libs. if",
"# Get shared libs needed by libraries. # TODO: we're",
"\"lib\") safe_make_directory(lib_dir) # Copy appleseed libraries. for lib in [\"libappleseed.so\",",
"os.path.splitext(filename)[1] if ext != \".py\" and ext != \".conf\": exe_path",
"\" + self.appleseed_settings_path) print(\" Path to appleseed.python: \" + self.appleseed_python_path)",
"COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"dirpath, dirnames, filenames in os.walk(bin_dir): for filename in filenames: ext",
"= self.__get_dependencies_for_file( os.path.join(self.settings.root_dir, \"appleseed\", \"lib\", \"appleseed\", \"_appleseedpython3.so\")) all_libs = all_libs.union(appleseedpython_libs)",
"empty lines. if len(line) == 0: continue # Ignore system",
"colorama.Style.RESET_ALL).encode('utf-8')) def fatal(message): print(u\"{0}Fatal: {1}. Aborting.{2}\".format(colorama.Style.BRIGHT + colorama.Fore.RED, message, colorama.Style.RESET_ALL).encode('utf-8'))",
"stderr=subprocess.PIPE) out, err = p.communicate() return p.returncode, out, err #--------------------------------------------------------------------------------------------------",
"if we didn't attempt to fix them. if fix_paths: for",
"if os.path.exists(candidate): info(\"Resolved relative dependency {0} as {1}\".format(lib, candidate)) lib",
"computing the full transitive closure here! lib_libs = set() for",
"granted, free of charge, to any person obtaining a copy",
"or ext == \".so\": lib_path = os.path.join(dirpath, filename) self.__change_library_paths_in_binary(lib_path) def",
"Constants. #-------------------------------------------------------------------------------------------------- VERSION = \"1.1.0\" SETTINGS_FILENAME = \"blenderseed.package.configuration.xml\" #-------------------------------------------------------------------------------------------------- #",
"files in os.walk(source_dir): for f in files: if f.endswith(\".oso\"): shutil.copy(os.path.join(root,",
"print(\"\") print(\"The package was successfully built.\") def orchestrate(self): self.remove_leftovers() self.copy_appleseed_python()",
"{1}'.format(name, target)) def __change_library_path(self, target, old, new): self.run('install_name_tool -change \"{0}\"",
"os.path.expandvars(self.__get_required(tree, \"appleseed_python_path\")) self.maketx_path = os.path.expandvars(self.__get_required(tree, \"maketx_path\")) self.output_dir = os.path.expandvars(self.__get_required(tree, \"output_dir\"))",
"@loader_path. lib = lib.replace(\"@loader_path\", loader_path) # Handle libs relative to",
"subdirectory = os.path.join(root_path, entry) if os.path.isdir(subdirectory): safe_delete_directory_recursively(subdirectory, directory_name) def safe_make_directory(path):",
"in files: if f.endswith(\".pyc\"): safe_delete_file(os.path.join(root, f)) def deploy_blenderseed_to_stage(self): progress(\"Deploying blenderseed",
"+ self.output_dir) print(\"\") def __load_values(self, tree): self.platform = self.__get_required(tree, \"platform\")",
"for file in [\"appleseed.cli.xml\"]: urllib.urlretrieve( \"https://raw.githubusercontent.com/appleseedhq/appleseed/master/sandbox/settings/{0}\".format(file), os.path.join(settings_dir, file)) def remove_pyc_files(self):",
"must retrieve the unmodified dependency in order to replace it",
"action=\"store_true\", help=\"copies appleseed binaries to blenderseed folder but does not",
"\"libpython\", \"libxshmfence.so\" ] def plugin_extension(self): return \".so\" def copy_dependencies(self): progress(\"Linux-specific:",
"name): self.run('install_name_tool -id \"{0}\" {1}'.format(name, target)) def __change_library_path(self, target, old,",
"from \" + SETTINGS_FILENAME + \"...\") tree = ElementTree() try:",
"safe_make_directory(lib_dir) # Copy appleseed libraries. for lib in [\"libappleseed.dylib\", \"libappleseed.shared.dylib\"]:",
"def plugin_extension(self): return \".so\" def copy_dependencies(self): progress(\"Linux-specific: Copying dependencies\") #",
"[exe(\"appleseed.cli\")]: shutil.copy(os.path.join(self.settings.appleseed_bin_path, bin), bin_dir) # Copy maketx. shutil.copy(exe(self.settings.maketx_path), bin_dir) def",
"def run(self, cmdline): trace(\"Running command line: {0}\".format(cmdline)) os.system(cmdline) def run_subprocess(self,",
"directory\") # Create destination directory. lib_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\")",
"post_process_package(self): pass #-------------------------------------------------------------------------------------------------- # Mac package builder. #-------------------------------------------------------------------------------------------------- class MacPackageBuilder(PackageBuilder):",
"lib == filename: continue # Ignore system libs. if self.__is_system_lib(lib):",
"prefix in self.SYSTEM_LIBS_PREFIXES: if lib.startswith(prefix): return True return False #--------------------------------------------------------------------------------------------------",
"in [exe(\"appleseed.cli\")]: shutil.copy(os.path.join(self.settings.appleseed_bin_path, bin), bin_dir) # Copy maketx. shutil.copy(exe(self.settings.maketx_path), bin_dir)",
"Don't check for missing dependencies if we didn't attempt to",
"to @rpath. lib = lib.replace(\"@rpath\", rpath) # Try to handle",
"needed by libraries. lib_libs = set() for lib in all_libs:",
"required to support output redirection to files or pipes. print(u\"",
"safe_delete_file(os.path.join(\"blenderseed\", file)) def build_final_zip_file(self): progress(\"Building final zip file from staging",
"os.path.exists(path): os.remove(path) except OSError: fatal(\"Failed to delete file '\" +",
"\"appleseed\", \"lib\") safe_make_directory(lib_dir) # Copy appleseed libraries. for lib in",
"unmodified dependency in order to replace it by the correct",
"True return False def __get_dependencies_for_file(self, filepath): returncode, out, err =",
"happen?). if lib == filename: continue # Ignore system libs.",
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES",
"# TODO: a great simplification if True: trace(\"Gathering dependencies for",
"directory. shaders_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"shaders\") safe_make_directory(shaders_dir) self.__do_copy_shaders(os.path.join(self.settings.appleseed_shaders_path, \"appleseed\"), shaders_dir)",
"new): self.run('install_name_tool -change \"{0}\" \"{1}\" {2}'.format(old, new, target)) def __get_dependencies_for_file(self,",
"def post_process_package(self): progress(\"Linux-specific: Post-processing package\") for bin in glob.glob(os.path.join(self.settings.root_dir, \"appleseed\",",
"colorama.Fore.RED, message, colorama.Style.RESET_ALL).encode('utf-8')) if sys.exc_info()[0]: print(traceback.format_exc()) sys.exit(1) def exe(filepath): return",
"for bin in glob.glob(os.path.join(self.settings.root_dir, \"appleseed\", \"bin\", \"*\")): self.run(\"chrpath -r \\$ORIGIN/../lib",
"to invoke ldd(1) to get dependencies for {0}: {1}\".format(filepath, err))",
"appleseed release: \" + self.appleseed_release_path) print(\" Path to appleseed binaries:",
"to appleseed release: \" + self.appleseed_release_path) print(\" Path to appleseed",
"maketx. shutil.copy(exe(self.settings.maketx_path), bin_dir) def copy_schemas(self): progress(\"Copying schemas to root directory\")",
"\"schemas\")) safe_delete_file(os.path.join(self.settings.root_dir, \"appleseed\", \"schemas\", \".gitignore\")) def copy_shaders(self): progress(\"Copying shaders to",
"= self.__get_dependencies_for_file(bin) all_libs = all_libs.union(libs) # Get shared libs needed",
"if True: trace(\" Copying {0} to {1}...\".format(lib, lib_dir)) shutil.copy(lib, lib_dir)",
"point. #-------------------------------------------------------------------------------------------------- def main(): colorama.init() parser = argparse.ArgumentParser(description=\"build a blenderseed",
"https://appleseedhq.net/ for additional information and resources. # # This software",
"= self.__get_required(tree, \"appleseed_release_path\") os.environ['APPLESEED'] = self.appleseed_release_path self.appleseed_bin_path = os.path.expandvars(self.__get_required(tree, \"appleseed_bin_path\"))",
"files or pipes. print(u\" {0}{1}{2}\".format(colorama.Style.DIM + colorama.Fore.WHITE, message, colorama.Style.RESET_ALL).encode('utf-8')) def",
"filename) self.__change_library_paths_in_binary(lib_path) def __change_library_paths_in_executables(self): bin_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"bin\") for",
"found on disk\".format(lib)) return libs def __is_system_lib(self, lib): for prefix",
"\"*\")): libs = self.__get_dependencies_for_file(bin) all_libs = all_libs.union(libs) # Get shared",
"TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR",
"rights # to use, copy, modify, merge, publish, distribute, sublicense,",
"RED_CROSSMARK = u\"{0}\\u2717{1}\".format(colorama.Style.BRIGHT + colorama.Fore.RED, colorama.Style.RESET_ALL) def trace(message): # encode('utf-8')",
"filepath + \".exe\" if os.name == \"nt\" else filepath def",
"try: tree.parse(SETTINGS_FILENAME) except IOError: fatal(\"Failed to load configuration file '\"",
"m = re.match(r\"(.*) \\(compatibility version .*, current version .*\\)\", line)",
"# Settings. #-------------------------------------------------------------------------------------------------- class Settings: def load(self): self.this_dir = os.path.dirname(os.path.realpath(__file__))",
"trace(\" {0}\".format(loader_path)) trace(\"and @rpath hardcoded to\") trace(\" {0}\".format(rpath)) returncode, out,",
"self.__change_library_paths_in_binary(exe_path) # Can be used on executables and dynamic libraries.",
"lib_path, \"@loader_path/{0}/{1}\".format(path_to_appleseed_lib, lib_name)) def __set_library_id(self, target, name): self.run('install_name_tool -id \"{0}\"",
"shared libs needed by libraries. lib_libs = set() for lib",
"simplification if True: trace(\"Gathering dependencies for file\") trace(\" {0}\".format(filepath)) trace(\"with",
"# # The above copyright notice and this permission notice",
"= lib.replace(\"@loader_path\", loader_path) # Handle libs relative to @rpath. lib",
"correct one. for lib_path in self.__get_dependencies_for_file(bin_path, fix_paths=False): lib_name = os.path.basename(lib_path)",
"by binaries. all_libs = set() for bin in glob.glob(os.path.join(self.settings.root_dir, \"appleseed\",",
"\"lib\") path_to_appleseed_lib = os.path.relpath(lib_dir, bin_dir) # fix_paths set to False",
"trace(\"with @loader_path set to\") trace(\" {0}\".format(loader_path)) trace(\"and @rpath hardcoded to\")",
"to appleseed libraries: \" + self.appleseed_lib_path) print(\" Path to appleseed",
"= os.path.join(self.settings.root_dir, \"appleseed\", \"settings\") safe_make_directory(settings_dir) for file in [\"appleseed.cli.xml\"]: urllib.urlretrieve(",
"self.appleseed_schemas_path) print(\" Path to appleseed settings: \" + self.appleseed_settings_path) print(\"",
"set() for line in out.split(\"\\n\")[1:]: # skip the first line",
"# # THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY",
"This source file is part of appleseed. # Visit https://appleseedhq.net/",
"{0}\".format(loader_path)) trace(\"and @rpath hardcoded to\") trace(\" {0}\".format(rpath)) returncode, out, err",
"# Copy appleseed binaries. for bin in [exe(\"appleseed.cli\")]: shutil.copy(os.path.join(self.settings.appleseed_bin_path, bin),",
"to appleseed shaders: \" + self.appleseed_shaders_path) print(\" Path to appleseed",
"copies of the Software, and to permit persons to whom",
"copy_appleseed_python(self): progress(\"Copying appleseed.python to root directory\") # Create destination directory.",
"# Copy appleseed libraries. for lib in [\"libappleseed.so\", \"libappleseed.shared.so\"]: shutil.copy(os.path.join(self.settings.appleseed_lib_path,",
"self.__get_dependencies_for_file(lib) lib_libs = lib_libs.union(libs) all_libs = all_libs.union(lib_libs) # Copy all",
"bin_dir) def copy_schemas(self): progress(\"Copying schemas to root directory\") dir_util.copy_tree(self.settings.appleseed_schemas_path, os.path.join(self.settings.root_dir,",
"OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"attempt < Attempts - 1: time.sleep(0.5) else: fatal(\"Failed to delete",
"settings files to root directory\") # Create destination directory. settings_dir",
"fatal(\"Failed to invoke otool(1) to get dependencies for {0}: {1}\".format(filepath,",
"bin_dir = self.settings.appleseed_bin_path for dll in [\"appleseed.dll\", \"appleseed.shared.dll\"]: shutil.copy(os.path.join(bin_dir, dll),",
"\"appleseed.shared.dll\"]: shutil.copy(os.path.join(bin_dir, dll), os.path.join(self.settings.root_dir, \"appleseed\", \"bin\")) def post_process_package(self): pass #--------------------------------------------------------------------------------------------------",
"all_libs: trace(\" {0}\".format(lib)) # Copy needed libs to lib directory.",
"continue # Ignore appleseed libs. if \"libappleseed\" in line: continue",
"= set() for bin in glob.glob(os.path.join(self.settings.root_dir, \"appleseed\", \"bin\", \"*\")): libs",
"out, err = self.run_subprocess([\"otool\", \"-L\", filepath]) if returncode != 0:",
"appleseed. # Visit https://appleseedhq.net/ for additional information and resources. #",
"self.copy_shaders() self.download_settings_files() self.remove_pyc_files() self.post_process_package() if not self.no_release: self.deploy_blenderseed_to_stage() self.clean_stage() self.build_final_zip_file()",
"\"scripts\", \"tests\"]: safe_delete_directory(os.path.join(\"blenderseed\", subdirectory)) for file in [\".gitignore\", \"README.md\"]: safe_delete_file(os.path.join(\"blenderseed\",",
"\"libffi\", \"libfontconfig\", \"libutil\", \"libpython\", \"libxshmfence.so\" ] def plugin_extension(self): return \".so\"",
"os.walk(os.path.join(self.settings.root_dir, \"appleseed\", \"lib\")): for f in files: if f.endswith(\".pyc\"): safe_delete_file(os.path.join(root,",
"lines. if len(line) == 0: continue # Parse the line.",
"PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
"copy, modify, merge, publish, distribute, sublicense, and/or sell # copies",
"return \".so\" def copy_dependencies(self): progress(\"Linux-specific: Copying dependencies\") # Create destination",
"# Ignore empty lines. if len(line) == 0: continue #",
"no_release def build_package(self): print(\"Building package:\") print(\"\") self.orchestrate() print(\"\") print(\"The package",
"self.__get_dependencies_for_file(bin) all_libs = all_libs.union(libs) # Get shared libs needed by",
"libs needed by libraries. lib_libs = set() for lib in",
"'\" + path + \"'\") def on_rmtree_error(func, path, exc_info): #",
"for lib in [\"libappleseed.so\", \"libappleseed.shared.so\"]: shutil.copy(os.path.join(self.settings.appleseed_lib_path, lib), lib_dir) # Get",
"os.environ['APPLESEED'] = self.appleseed_release_path self.appleseed_bin_path = os.path.expandvars(self.__get_required(tree, \"appleseed_bin_path\")) self.appleseed_lib_path = os.path.expandvars(self.__get_required(tree,",
"package builder. #-------------------------------------------------------------------------------------------------- class MacPackageBuilder(PackageBuilder): SYSTEM_LIBS_PREFIXES = [ \"/System/Library/\", \"/usr/lib/libcurl\",",
"{1}\".format(lib, candidate)) lib = candidate libs.add(lib) if True: trace(\"Dependencies for",
"or pipes. print(u\" {0}{1}{2}\".format(colorama.Style.DIM + colorama.Fore.WHITE, message, colorama.Style.RESET_ALL).encode('utf-8')) def info(message):",
"AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR",
"the Software without restriction, including without limitation the rights #",
"# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"Path to appleseed release: \" + self.appleseed_release_path) print(\" Path to",
"Create destination directory. settings_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"settings\") safe_make_directory(settings_dir) for",
"output redirection to files or pipes. print(u\" {0}{1}{2}\".format(colorama.Style.DIM + colorama.Fore.WHITE,",
"was successfully built.\") def orchestrate(self): self.remove_leftovers() self.copy_appleseed_python() self.copy_binaries() self.copy_dependencies() self.copy_schemas()",
"libs: if os.path.isfile(lib): trace(u\" {0} {1}\".format(GREEN_CHECKMARK, lib)) else: trace(u\" {0}",
"def __is_system_lib(self, lib): for prefix in self.SYSTEM_LIBS_PREFIXES: if lib.startswith(prefix): return",
"# Handle libs relative to @loader_path. lib = lib.replace(\"@loader_path\", loader_path)",
"copy_dependencies(self): progress(\"Mac-specific: Copying dependencies\") # Create destination directory. lib_dir =",
"#-------------------------------------------------------------------------------------------------- class Settings: def load(self): self.this_dir = os.path.dirname(os.path.realpath(__file__)) self.root_dir =",
"def build_final_zip_file(self): progress(\"Building final zip file from staging directory\") package_name",
"self.run(\"chrpath -r \\$ORIGIN/../lib \" + bin) for lib in glob.glob(os.path.join(self.settings.root_dir,",
"glob.glob(os.path.join(appleseed_python_dir, \"*.so\")): self.run(\"chrpath -r \\$ORIGIN/../ \" + py_cpp_module) def __is_system_lib(self,",
"in self.SYSTEM_LIBS_PREFIXES: if lib.startswith(prefix): return True return False def __get_dependencies_for_file(self,",
"path + \"'\") def safe_delete_directory_recursively(root_path, directory_name): safe_delete_directory(os.path.join(root_path, directory_name)) for entry",
"filenames: ext = os.path.splitext(filename)[1] if ext != \".py\" and ext",
"furnished to do so, subject to the following conditions: #",
"self.appleseed_shaders_path) print(\" Path to appleseed schemas: \" + self.appleseed_schemas_path) print(\"",
"relative dependency {0} as {1}\".format(lib, candidate)) lib = candidate libs.add(lib)",
"lib in glob.glob(os.path.join(self.settings.root_dir, \"appleseed\", \"lib\", \"*.so\")): self.run(\"chrpath -d \" +",
"# The above copyright notice and this permission notice shall",
"== \".dylib\" or ext == \".so\": lib_path = os.path.join(dirpath, filename)",
"for attempt in range(Attempts): try: if os.path.exists(path): shutil.rmtree(path, onerror=on_rmtree_error) return",
"Path to appleseed libraries: \" + self.appleseed_lib_path) print(\" Path to",
"\"appleseed\", \"bin\") for dirpath, dirnames, filenames in os.walk(bin_dir): for filename",
"def orchestrate(self): self.remove_leftovers() self.copy_appleseed_python() self.copy_binaries() self.copy_dependencies() self.copy_schemas() self.copy_shaders() self.download_settings_files() self.remove_pyc_files()",
"self.package_version = package_version self.build_date = build_date self.no_release = no_release def",
"if fix_paths: for lib in libs: if not os.path.isfile(lib): fatal(\"Dependency",
"\\(compatibility version .*, current version .*\\)\", line) if not m:",
"path of the file that couldn't be removed. # Let's",
"= m.group(1) # Ignore self-references (why do these happen?). if",
"\"@loader_path/{0}/{1}\".format(path_to_appleseed_lib, lib_name)) def __set_library_id(self, target, name): self.run('install_name_tool -id \"{0}\" {1}'.format(name,",
"of the file that couldn't be removed. # Let's just",
"trace(\" {0}\".format(lib)) # Copy needed libs to lib directory. for",
"libraries. for lib in [\"libappleseed.so\", \"libappleseed.shared.so\"]: shutil.copy(os.path.join(self.settings.appleseed_lib_path, lib), lib_dir) #",
"bin in glob.glob(os.path.join(self.settings.root_dir, \"appleseed\", \"bin\", \"*\")): self.run(\"chrpath -r \\$ORIGIN/../lib \"",
"following conditions: # # The above copyright notice and this",
"archive_util.make_zipfile(package_path, \"blenderseed\") info(\"Package path: {0}\".format(package_path + \".zip\")) def remove_stage(self): progress(\"Deleting",
"by libraries. lib_libs = set() for lib in all_libs: libs",
"conditions: # # The above copyright notice and this permission",
"returncode != 0: fatal(\"Failed to invoke otool(1) to get dependencies",
"print(\" Path to appleseed.python: \" + self.appleseed_python_path) print(\" Path to",
"\"blenderseed-{0}-{1}-{2}\".format(self.package_version, self.settings.platform, self.build_date) package_path = os.path.join(self.settings.output_dir, package_name) archive_util.make_zipfile(package_path, \"blenderseed\") info(\"Package",
"to files or pipes. print(u\" {0}{1}{2}\".format(colorama.Style.DIM + colorama.Fore.WHITE, message, colorama.Style.RESET_ALL).encode('utf-8'))",
"progress(\"Mac-specific: Copying dependencies\") # Create destination directory. lib_dir = os.path.join(self.settings.root_dir,",
"just assume that it's read-only and unlink it. os.chmod(path, stat.S_IWRITE)",
"help=\"copies appleseed binaries to blenderseed folder but does not build",
"that it's read-only and unlink it. os.chmod(path, stat.S_IWRITE) os.unlink(path) def",
"package_version = subprocess.Popen(\"git describe --long\", stdout=subprocess.PIPE, shell=True).stdout.read().strip() build_date = datetime.date.today().isoformat()",
"directory\") dir_util.copy_tree(self.settings.appleseed_schemas_path, os.path.join(self.settings.root_dir, \"appleseed\", \"schemas\")) safe_delete_file(os.path.join(self.settings.root_dir, \"appleseed\", \"schemas\", \".gitignore\")) def",
"TODO: a great simplification if True: trace(\"Gathering dependencies for file\")",
"self.copy_schemas() self.copy_shaders() self.download_settings_files() self.remove_pyc_files() self.post_process_package() if not self.no_release: self.deploy_blenderseed_to_stage() self.clean_stage()",
"Post-processing package\") self.__fixup_binaries() def __fixup_binaries(self): progress(\"Mac-specific: Fixing up binaries\") self.set_libraries_ids()",
"all_libs: libs = self.__get_dependencies_for_file(lib) lib_libs = lib_libs.union(libs) all_libs = all_libs.union(lib_libs)",
"__set_library_id(self, target, name): self.run('install_name_tool -id \"{0}\" {1}'.format(name, target)) def __change_library_path(self,",
"safe_delete_file(os.path.join(root, f)) def deploy_blenderseed_to_stage(self): progress(\"Deploying blenderseed to staging directory\") shutil.copytree(self.settings.root_dir,",
"a release package\") args = parser.parse_args() no_release = args.nozip package_version",
"Create destination directory. lib_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") safe_make_directory(lib_dir) #",
"stat.S_IWRITE) os.unlink(path) def safe_delete_directory(path): Attempts = 10 for attempt in",
"Utility functions. #-------------------------------------------------------------------------------------------------- GREEN_CHECKMARK = u\"{0}\\u2713{1}\".format(colorama.Style.BRIGHT + colorama.Fore.GREEN, colorama.Style.RESET_ALL) RED_CROSSMARK",
"# Ignore Qt frameworks. if re.search(r\"Qt.*\\.framework\", lib): continue if fix_paths:",
"os.path.dirname(filepath) rpath = \"/usr/local/lib/\" # TODO: a great simplification if",
"in all_libs: libs = self.__get_dependencies_for_file(lib) lib_libs = lib_libs.union(libs) all_libs =",
"# Print dependencies. trace(\" Dependencies:\") for lib in all_libs: trace(\"",
"import urllib #-------------------------------------------------------------------------------------------------- # Constants. #-------------------------------------------------------------------------------------------------- VERSION = \"1.1.0\" SETTINGS_FILENAME",
"os.path.join(self.settings.root_dir, \"appleseed\", \"schemas\")) safe_delete_file(os.path.join(self.settings.root_dir, \"appleseed\", \"schemas\", \".gitignore\")) def copy_shaders(self): progress(\"Copying",
"to replace it by the correct one. for lib_path in",
"information and resources. # # This software is released under",
"sys.exit(1) def exe(filepath): return filepath + \".exe\" if os.name ==",
"be included in # all copies or substantial portions of",
"os.unlink(path) def safe_delete_directory(path): Attempts = 10 for attempt in range(Attempts):",
"1: time.sleep(0.5) else: fatal(\"Failed to delete directory '\" + path",
"range(Attempts): try: if os.path.exists(path): shutil.rmtree(path, onerror=on_rmtree_error) return except OSError: if",
"def remove_pyc_files(self): progress(\"Removing pyc files from root directory\") for root,",
"for lib in all_libs: libs = self.__get_dependencies_for_file(lib) lib_libs = lib_libs.union(libs)",
"= self.appleseed_release_path self.appleseed_bin_path = os.path.expandvars(self.__get_required(tree, \"appleseed_bin_path\")) self.appleseed_lib_path = os.path.expandvars(self.__get_required(tree, \"appleseed_lib_path\"))",
"# Copy appleseed libraries. for lib in [\"libappleseed.dylib\", \"libappleseed.shared.dylib\"]: shutil.copy(os.path.join(self.settings.appleseed_lib_path,",
"staging directory\") safe_delete_directory_recursively(\"blenderseed\", \"__pycache__\") for subdirectory in [\".git\", \".idea\", \"archives\",",
"self.remove_pyc_files() self.post_process_package() if not self.no_release: self.deploy_blenderseed_to_stage() self.clean_stage() self.build_final_zip_file() self.remove_stage() def",
"\"/usr/lib/libcurl\", \"/usr/lib/libc++\", \"/usr/lib/libbz2\", \"/usr/lib/libSystem\", #\"/usr/lib/libz\", \"/usr/lib/libncurses\", \"/usr/lib/libobjc.A.dylib\" ] def copy_dependencies(self):",
"{1}.{2}\".format(colorama.Style.BRIGHT + colorama.Fore.MAGENTA, message, colorama.Style.RESET_ALL).encode('utf-8')) def fatal(message): print(u\"{0}Fatal: {1}. Aborting.{2}\".format(colorama.Style.BRIGHT",
"without restriction, including without limitation the rights # to use,",
"# # Permission is hereby granted, free of charge, to",
"documentation files (the 'Software'), to deal # in the Software",
"{0}\".format(filepath)) trace(\"with @loader_path set to\") trace(\" {0}\".format(loader_path)) trace(\"and @rpath hardcoded",
"self.copy_appleseed_python() self.copy_binaries() self.copy_dependencies() self.copy_schemas() self.copy_shaders() self.download_settings_files() self.remove_pyc_files() self.post_process_package() if not",
"lib)) else: trace(u\" {0} {1}\".format(RED_CROSSMARK, lib)) # Don't check for",
"subject to the following conditions: # # The above copyright",
"\".dylib\" or ext == \".so\": lib_path = os.path.join(dirpath, filename) self.__set_library_id(lib_path,",
"it's read-only and unlink it. os.chmod(path, stat.S_IWRITE) os.unlink(path) def safe_delete_directory(path):",
"None: fatal(\"Missing value \\\"{0}\\\" in configuration file\".format(key)) return value #--------------------------------------------------------------------------------------------------",
"loader_path = os.path.dirname(filepath) rpath = \"/usr/local/lib/\" # TODO: a great",
"# from __future__ import print_function from distutils import archive_util, dir_util",
"# of this software and associated documentation files (the 'Software'),",
"import os import platform import re import shutil import stat",
"key): value = tree.findtext(key) if value is None: fatal(\"Missing value",
"os.remove(path) except OSError: fatal(\"Failed to delete file '\" + path",
"candidate libs.add(lib) if True: trace(\"Dependencies for file {0}:\".format(filepath)) for lib",
"line from otool(1) output: \" + line) lib = m.group(1)",
"to root directory\") dir_util.copy_tree(self.settings.appleseed_schemas_path, os.path.join(self.settings.root_dir, \"appleseed\", \"schemas\")) safe_delete_file(os.path.join(self.settings.root_dir, \"appleseed\", \"schemas\",",
"shutil import stat import subprocess import sys import time import",
"settings self.package_version = package_version self.build_date = build_date self.no_release = no_release",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL",
"info(message): print(u\" {0}\".format(message).encode('utf-8')) def progress(message): print(u\" {0}...\".format(message).encode('utf-8')) def warning(message): print(u\"",
"maketx: \" + self.maketx_path) print(\" Output directory: \" + self.output_dir)",
"shutil.copy(os.path.join(self.settings.appleseed_bin_path, bin), bin_dir) # Copy maketx. shutil.copy(exe(self.settings.maketx_path), bin_dir) def copy_schemas(self):",
"def trace(message): # encode('utf-8') is required to support output redirection",
"IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER",
"libs.add(line.split()[2]) return libs #-------------------------------------------------------------------------------------------------- # Entry point. #-------------------------------------------------------------------------------------------------- def main():",
"\"appleseed\", \"schemas\")) safe_delete_file(os.path.join(self.settings.root_dir, \"appleseed\", \"schemas\", \".gitignore\")) def copy_shaders(self): progress(\"Copying shaders",
"be used on executables and dynamic libraries. def __change_library_paths_in_binary(self, bin_path):",
"appleseed libraries. for lib in [\"libappleseed.so\", \"libappleseed.shared.so\"]: shutil.copy(os.path.join(self.settings.appleseed_lib_path, lib), lib_dir)",
"merge, publish, distribute, sublicense, and/or sell # copies of the",
"progress(\"Windows-specific: Copying dependencies\") bin_dir = self.settings.appleseed_bin_path for dll in [\"appleseed.dll\",",
"Create destination directory. shaders_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"shaders\") safe_make_directory(shaders_dir) self.__do_copy_shaders(os.path.join(self.settings.appleseed_shaders_path,",
"#-------------------------------------------------------------------------------------------------- # Utility functions. #-------------------------------------------------------------------------------------------------- GREEN_CHECKMARK = u\"{0}\\u2713{1}\".format(colorama.Style.BRIGHT + colorama.Fore.GREEN,",
"--long\", stdout=subprocess.PIPE, shell=True).stdout.read().strip() build_date = datetime.date.today().isoformat() print(\"blenderseed.package version \" +",
"NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT",
"NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR",
"Attempts - 1: time.sleep(0.5) else: fatal(\"Failed to delete directory '\"",
"+ self.appleseed_shaders_path) print(\" Path to appleseed schemas: \" + self.appleseed_schemas_path)",
"\"@loader_path/{0}\".format(lib_name)) else: self.__change_library_path(bin_path, lib_path, \"@loader_path/{0}/{1}\".format(path_to_appleseed_lib, lib_name)) def __set_library_id(self, target, name):",
"= os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") for dirpath, dirnames, filenames in os.walk(lib_dir):",
"lib = candidate libs.add(lib) if True: trace(\"Dependencies for file {0}:\".format(filepath))",
"print(\"Loading settings from \" + SETTINGS_FILENAME + \"...\") tree =",
"Dependencies:\") for lib in all_libs: trace(\" {0}\".format(lib)) # Copy needed",
"print_function from distutils import archive_util, dir_util from xml.etree.ElementTree import ElementTree",
"\"tests\"]: safe_delete_directory(os.path.join(\"blenderseed\", subdirectory)) for file in [\".gitignore\", \"README.md\"]: safe_delete_file(os.path.join(\"blenderseed\", file))",
"encode('utf-8') is required to support output redirection to files or",
"to lib directory. for lib in all_libs: if True: trace(\"",
"self.__get_dependencies_for_file(bin_path, fix_paths=False): lib_name = os.path.basename(lib_path) if path_to_appleseed_lib == \".\": self.__change_library_path(bin_path,",
"@loader_path set to\") trace(\" {0}\".format(loader_path)) trace(\"and @rpath hardcoded to\") trace(\"",
"self.__change_library_path(bin_path, lib_path, \"@loader_path/{0}\".format(lib_name)) else: self.__change_library_path(bin_path, lib_path, \"@loader_path/{0}/{1}\".format(path_to_appleseed_lib, lib_name)) def __set_library_id(self,",
"lib): for prefix in self.SYSTEM_LIBS_PREFIXES: if lib.startswith(prefix): return True return",
"\"_appleseedpython.so\")) safe_delete_file(os.path.join(lib_dir, \"appleseed\", \"_appleseedpython.pyd\")) def copy_binaries(self): progress(\"Copying binaries to root",
"out.split(\"\\n\"): line = line.strip() # Ignore empty lines. if len(line)",
"value is None: fatal(\"Missing value \\\"{0}\\\" in configuration file\".format(key)) return",
"copy_binaries(self): progress(\"Copying binaries to root directory\") # Create destination directory.",
"import shutil import stat import subprocess import sys import time",
"DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF",
"root directory\") # Create destination directory. shaders_dir = os.path.join(self.settings.root_dir, \"appleseed\",",
"associated documentation files (the 'Software'), to deal # in the",
"return old_path def copy_glob(input_pattern, output_path): for input_file in glob.glob(input_pattern): shutil.copy(input_file,",
"SOFTWARE. # from __future__ import print_function from distutils import archive_util,",
"libs to lib directory. for lib in all_libs: if True:",
"self.appleseed_bin_path) print(\" Path to appleseed libraries: \" + self.appleseed_lib_path) print(\"",
"+ VERSION) print(\"\") settings = Settings() settings.load() settings.print_summary() if os.name",
"'\" + path + \"'\") def safe_delete_directory_recursively(root_path, directory_name): safe_delete_directory(os.path.join(root_path, directory_name))",
"filename: continue # Ignore system libs. if self.__is_system_lib(lib): continue #",
"lib_name)) def __set_library_id(self, target, name): self.run('install_name_tool -id \"{0}\" {1}'.format(name, target))",
"self.__load_values(tree) def print_summary(self): print(\"\") print(\" Platform: \" + self.platform) print(\"",
"os.path.splitext(filename)[1] if ext == \".dylib\" or ext == \".so\": lib_path",
"= ElementTree() try: tree.parse(SETTINGS_FILENAME) except IOError: fatal(\"Failed to load configuration",
"err #-------------------------------------------------------------------------------------------------- # Windows package builder. #-------------------------------------------------------------------------------------------------- class WindowsPackageBuilder(PackageBuilder): def",
"trace(\"Running command line: {0}\".format(cmdline)) os.system(cmdline) def run_subprocess(self, cmdline): p =",
"built.\") def orchestrate(self): self.remove_leftovers() self.copy_appleseed_python() self.copy_binaries() self.copy_dependencies() self.copy_schemas() self.copy_shaders() self.download_settings_files()",
"build_date, no_release=False): self.settings = settings self.package_version = package_version self.build_date =",
"in glob.glob(os.path.join(self.settings.root_dir, \"appleseed\", \"bin\", \"*\")): self.run(\"chrpath -r \\$ORIGIN/../lib \" +",
"print(\"blenderseed.package version \" + VERSION) print(\"\") settings = Settings() settings.load()",
"persons to whom the Software is # furnished to do",
"for line in out.split(\"\\n\")[1:]: # skip the first line line",
"for lib_path in self.__get_dependencies_for_file(bin_path, fix_paths=False): lib_name = os.path.basename(lib_path) if path_to_appleseed_lib",
"folder but does not build a release package\") args =",
"OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE.",
"= os.path.join(self.settings.root_dir, \"appleseed\", \"bin\") safe_make_directory(bin_dir) # Copy appleseed binaries. for",
"OSError: if attempt < Attempts - 1: time.sleep(0.5) else: fatal(\"Failed",
"root directory\") # Create destination directory. lib_dir = os.path.join(self.settings.root_dir, \"appleseed\",",
"def remove_leftovers(self): progress(\"Removing leftovers from previous invocations\") safe_delete_directory(os.path.join(self.settings.root_dir, \"appleseed\")) safe_delete_directory(\"blenderseed\")",
"== filename: continue # Ignore system libs. if self.__is_system_lib(lib): continue",
"ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN",
"Entry point. #-------------------------------------------------------------------------------------------------- def main(): colorama.init() parser = argparse.ArgumentParser(description=\"build a",
"lib in all_libs: shutil.copy(lib, lib_dir) def post_process_package(self): progress(\"Linux-specific: Post-processing package\")",
"be found on disk\".format(lib)) return libs def __is_system_lib(self, lib): for",
"files (the 'Software'), to deal # in the Software without",
"tree, key): value = tree.findtext(key) if value is None: fatal(\"Missing",
"return filepath + \".exe\" if os.name == \"nt\" else filepath",
"\"'\") def on_rmtree_error(func, path, exc_info): # path contains the path",
"for lib in all_libs: if True: trace(\" Copying {0} to",
"plugin_extension(self): return \".so\" def copy_dependencies(self): progress(\"Linux-specific: Copying dependencies\") # Create",
"Path to appleseed binaries: \" + self.appleseed_bin_path) print(\" Path to",
"colorama.Fore.MAGENTA, message, colorama.Style.RESET_ALL).encode('utf-8')) def fatal(message): print(u\"{0}Fatal: {1}. Aborting.{2}\".format(colorama.Style.BRIGHT + colorama.Fore.RED,",
"datetime.date.today().isoformat() print(\"blenderseed.package version \" + VERSION) print(\"\") settings = Settings()",
"lib_libs.union(libs) all_libs = all_libs.union(lib_libs) # Copy all shared libraries. for",
"substantial portions of the Software. # # THE SOFTWARE IS",
"tree.findtext(key) if value is None: fatal(\"Missing value \\\"{0}\\\" in configuration",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,",
"f in files: if f.endswith(\".oso\"): shutil.copy(os.path.join(root, f), target_dir) def download_settings_files(self):",
"if lib.startswith(prefix): return True return False #-------------------------------------------------------------------------------------------------- # Linux package",
"post_process_package(self): progress(\"Linux-specific: Post-processing package\") for bin in glob.glob(os.path.join(self.settings.root_dir, \"appleseed\", \"bin\",",
"self.__get_required(tree, \"platform\") self.appleseed_release_path = self.__get_required(tree, \"appleseed_release_path\") os.environ['APPLESEED'] = self.appleseed_release_path self.appleseed_bin_path",
"Remove _appleseedpython.so (Python 2) since blenderseed only needs _appleseedpython3.so (Python",
"\"appleseed\", \"settings\") safe_make_directory(settings_dir) for file in [\"appleseed.cli.xml\"]: urllib.urlretrieve( \"https://raw.githubusercontent.com/appleseedhq/appleseed/master/sandbox/settings/{0}\".format(file), os.path.join(settings_dir,",
"binaries\") self.set_libraries_ids() self.__change_library_paths_in_libraries() self.__change_library_paths_in_executables() def set_libraries_ids(self): lib_dir = os.path.join(self.settings.root_dir, \"appleseed\",",
"os.path.join(dirpath, filename) self.__change_library_paths_in_binary(lib_path) def __change_library_paths_in_executables(self): bin_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"bin\")",
"ext != \".py\" and ext != \".conf\": exe_path = os.path.join(dirpath,",
"if ext == \".dylib\" or ext == \".so\": lib_path =",
"def __do_copy_shaders(self, source_dir, target_dir): for root, dirs, files in os.walk(source_dir):",
"Settings: def load(self): self.this_dir = os.path.dirname(os.path.realpath(__file__)) self.root_dir = os.path.join(self.this_dir, \"..\")",
"subdirectory)) for file in [\".gitignore\", \"README.md\"]: safe_delete_file(os.path.join(\"blenderseed\", file)) def build_final_zip_file(self):",
"any person obtaining a copy # of this software and",
"pipes. print(u\" {0}{1}{2}\".format(colorama.Style.DIM + colorama.Fore.WHITE, message, colorama.Style.RESET_ALL).encode('utf-8')) def info(message): print(u\"",
"ARISING FROM, # OUT OF OR IN CONNECTION WITH THE",
"path_to_appleseed_lib = os.path.relpath(lib_dir, bin_dir) # fix_paths set to False because",
"= line.strip() # Ignore empty lines. if len(line) == 0:",
"not build a release package\") args = parser.parse_args() no_release =",
"describe --long\", stdout=subprocess.PIPE, shell=True).stdout.read().strip() build_date = datetime.date.today().isoformat() print(\"blenderseed.package version \"",
"\"bin\") safe_make_directory(bin_dir) # Copy appleseed binaries. for bin in [exe(\"appleseed.cli\")]:",
"to appleseed binaries: \" + self.appleseed_bin_path) print(\" Path to appleseed",
"DEALINGS IN # THE SOFTWARE. # from __future__ import print_function",
"+ self.appleseed_schemas_path) print(\" Path to appleseed settings: \" + self.appleseed_settings_path)",
"#-------------------------------------------------------------------------------------------------- class LinuxPackageBuilder(PackageBuilder): SYSTEM_LIBS_PREFIXES = [ \"linux\", \"librt\", \"libpthread\", \"libGL\",",
"{0} to {1}...\".format(lib, lib_dir)) shutil.copy(lib, lib_dir) def post_process_package(self): progress(\"Mac-specific: Post-processing",
"THE USE OR OTHER DEALINGS IN # THE SOFTWARE. #",
"set() for line in out.split(\"\\n\"): line = line.strip() # Ignore",
"{0}...\".format(message).encode('utf-8')) def warning(message): print(u\" {0}Warning: {1}.{2}\".format(colorama.Style.BRIGHT + colorama.Fore.MAGENTA, message, colorama.Style.RESET_ALL).encode('utf-8'))",
"THE SOFTWARE. # from __future__ import print_function from distutils import",
"copyright notice and this permission notice shall be included in",
"= self.settings.appleseed_bin_path for dll in [\"appleseed.dll\", \"appleseed.shared.dll\"]: shutil.copy(os.path.join(bin_dir, dll), os.path.join(self.settings.root_dir,",
"# # This software is released under the MIT license.",
"= self.__get_dependencies_for_file(lib) lib_libs = lib_libs.union(libs) all_libs = all_libs.union(lib_libs) if True:",
"and unlink it. os.chmod(path, stat.S_IWRITE) os.unlink(path) def safe_delete_directory(path): Attempts =",
"-r \\$ORIGIN/../lib \" + bin) for lib in glob.glob(os.path.join(self.settings.root_dir, \"appleseed\",",
"\"\": package_builder = LinuxPackageBuilder(settings, package_version, build_date, no_release) else: fatal(\"Unsupported platform:",
"p.returncode, out, err #-------------------------------------------------------------------------------------------------- # Windows package builder. #-------------------------------------------------------------------------------------------------- class",
"in filenames: ext = os.path.splitext(filename)[1] if ext != \".py\" and",
"colorama.Style.RESET_ALL).encode('utf-8')) def info(message): print(u\" {0}\".format(message).encode('utf-8')) def progress(message): print(u\" {0}...\".format(message).encode('utf-8')) def",
"os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") safe_make_directory(lib_dir) # Copy appleseed.python. dir_util.copy_tree(self.settings.appleseed_python_path, lib_dir) #",
"lib_path, \"@loader_path/{0}\".format(lib_name)) else: self.__change_library_path(bin_path, lib_path, \"@loader_path/{0}/{1}\".format(path_to_appleseed_lib, lib_name)) def __set_library_id(self, target,",
"used on executables and dynamic libraries. def __change_library_paths_in_binary(self, bin_path): progress(\"Patching",
"{0} {1}\".format(GREEN_CHECKMARK, lib)) else: trace(u\" {0} {1}\".format(RED_CROSSMARK, lib)) # Don't",
"\"archives\", \"docs\", \"scripts\", \"tests\"]: safe_delete_directory(os.path.join(\"blenderseed\", subdirectory)) for file in [\".gitignore\",",
"software and associated documentation files (the 'Software'), to deal #",
"for f in files: if f.endswith(\".oso\"): shutil.copy(os.path.join(root, f), target_dir) def",
"+ self.appleseed_python_path) print(\" Path to maketx: \" + self.maketx_path) print(\"",
"Handle libs relative to @loader_path. lib = lib.replace(\"@loader_path\", loader_path) #",
"pyc files from root directory\") for root, dirs, files in",
"\"bin\", \"*\")): libs = self.__get_dependencies_for_file(bin) all_libs = all_libs.union(libs) # Get",
"print(\"\") self.orchestrate() print(\"\") print(\"The package was successfully built.\") def orchestrate(self):",
"self.__do_copy_shaders(os.path.join(self.settings.appleseed_shaders_path, \"blenderseed\"), shaders_dir) def __do_copy_shaders(self, source_dir, target_dir): for root, dirs,",
"does not build a release package\") args = parser.parse_args() no_release",
"os.path.join(self.settings.root_dir, \"appleseed\", \"bin\") safe_make_directory(bin_dir) # Copy appleseed binaries. for bin",
"py_cpp_module in glob.glob(os.path.join(appleseed_python_dir, \"*.so\")): self.run(\"chrpath -r \\$ORIGIN/../ \" + py_cpp_module)",
"= os.path.basename(lib_path) if path_to_appleseed_lib == \".\": self.__change_library_path(bin_path, lib_path, \"@loader_path/{0}\".format(lib_name)) else:",
"IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #",
"self.copy_dependencies() self.copy_schemas() self.copy_shaders() self.download_settings_files() self.remove_pyc_files() self.post_process_package() if not self.no_release: self.deploy_blenderseed_to_stage()",
"parser = argparse.ArgumentParser(description=\"build a blenderseed package from sources\") parser.add_argument(\"--nozip\", action=\"store_true\",",
"import archive_util, dir_util from xml.etree.ElementTree import ElementTree import argparse import",
"directory\") package_name = \"blenderseed-{0}-{1}-{2}\".format(self.package_version, self.settings.platform, self.build_date) package_path = os.path.join(self.settings.output_dir, package_name)",
"sys.exc_info()[0]: print(traceback.format_exc()) sys.exit(1) def exe(filepath): return filepath + \".exe\" if",
"system libs. if self.__is_system_lib(lib): continue # Ignore Qt frameworks. if",
"EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE",
"package builder. #-------------------------------------------------------------------------------------------------- class LinuxPackageBuilder(PackageBuilder): SYSTEM_LIBS_PREFIXES = [ \"linux\", \"librt\",",
"\"libselinux\", \"libICE\", \"libSM\", \"libdl\", \"libm.so\", \"libgcc\", \"libc.so\", \"/lib64/ld-linux-\", \"libstdc++\", \"libxcb\",",
"bin_path): progress(\"Patching {0}\".format(bin_path)) bin_dir = os.path.dirname(bin_path) lib_dir = os.path.join(self.settings.root_dir, \"appleseed\",",
"lib = lib.replace(\"@loader_path\", loader_path) # Handle libs relative to @rpath.",
"if not m: fatal(\"Failed to parse line from otool(1) output:",
"-r \\$ORIGIN/../ \" + py_cpp_module) def __is_system_lib(self, lib): for prefix",
"filepath]) if returncode != 0: fatal(\"Failed to invoke ldd(1) to",
"PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS",
"appleseed settings: \" + self.appleseed_settings_path) print(\" Path to appleseed.python: \"",
"os.path.join(self.settings.root_dir, \"appleseed\", \"settings\") safe_make_directory(settings_dir) for file in [\"appleseed.cli.xml\"]: urllib.urlretrieve( \"https://raw.githubusercontent.com/appleseedhq/appleseed/master/sandbox/settings/{0}\".format(file),",
"for missing dependencies if we didn't attempt to fix them.",
"= os.path.expandvars(self.__get_required(tree, \"appleseed_schemas_path\")) self.appleseed_settings_path = os.path.expandvars(self.__get_required(tree, \"appleseed_settings_path\")) self.appleseed_python_path = os.path.expandvars(self.__get_required(tree,",
"safe_delete_directory(path): Attempts = 10 for attempt in range(Attempts): try: if",
"if lib.startswith(prefix): return True return False def __get_dependencies_for_file(self, filepath): returncode,",
"binaries. all_libs = set() for bin in glob.glob(os.path.join(self.settings.root_dir, \"appleseed\", \"bin\",",
"import re import shutil import stat import subprocess import sys",
"{0} as {1}\".format(lib, candidate)) lib = candidate libs.add(lib) if True:",
"message, colorama.Style.RESET_ALL).encode('utf-8')) def fatal(message): print(u\"{0}Fatal: {1}. Aborting.{2}\".format(colorama.Style.BRIGHT + colorama.Fore.RED, message,",
"= lib_libs.union(libs) all_libs = all_libs.union(lib_libs) if True: # Print dependencies.",
"+ self.appleseed_bin_path) print(\" Path to appleseed libraries: \" + self.appleseed_lib_path)",
"if True: trace(\"Dependencies for file {0}:\".format(filepath)) for lib in libs:",
"p.communicate() return p.returncode, out, err #-------------------------------------------------------------------------------------------------- # Windows package builder.",
"[ \"linux\", \"librt\", \"libpthread\", \"libGL\", \"libX\", \"libselinux\", \"libICE\", \"libSM\", \"libdl\",",
"Ignore appleseed libs. if \"libappleseed\" in line: continue libs.add(line.split()[2]) return",
"libs relative to @loader_path. lib = lib.replace(\"@loader_path\", loader_path) # Handle",
"os.listdir(root_path): subdirectory = os.path.join(root_path, entry) if os.path.isdir(subdirectory): safe_delete_directory_recursively(subdirectory, directory_name) def",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",
"self.__do_copy_shaders(os.path.join(self.settings.appleseed_shaders_path, \"appleseed\"), shaders_dir) self.__do_copy_shaders(os.path.join(self.settings.appleseed_shaders_path, \"blenderseed\"), shaders_dir) def __do_copy_shaders(self, source_dir, target_dir):",
"destination directory. shaders_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"shaders\") safe_make_directory(shaders_dir) self.__do_copy_shaders(os.path.join(self.settings.appleseed_shaders_path, \"appleseed\"),",
"{1}\".format(GREEN_CHECKMARK, lib)) else: trace(u\" {0} {1}\".format(RED_CROSSMARK, lib)) # Don't check",
"os.path.dirname(os.path.realpath(__file__)) self.root_dir = os.path.join(self.this_dir, \"..\") print(\"Loading settings from \" +",
"old, new): self.run('install_name_tool -change \"{0}\" \"{1}\" {2}'.format(old, new, target)) def",
"didn't attempt to fix them. if fix_paths: for lib in",
"this software and associated documentation files (the 'Software'), to deal",
"= subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() return p.returncode,",
"cmdline): trace(\"Running command line: {0}\".format(cmdline)) os.system(cmdline) def run_subprocess(self, cmdline): p",
"run_subprocess(self, cmdline): p = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err =",
"= os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") path_to_appleseed_lib = os.path.relpath(lib_dir, bin_dir) # fix_paths",
"+ path + \"'\") def safe_delete_directory_recursively(root_path, directory_name): safe_delete_directory(os.path.join(root_path, directory_name)) for",
"bin_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"bin\") safe_make_directory(bin_dir) # Copy appleseed binaries.",
"IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED,",
"couldn't be removed. # Let's just assume that it's read-only",
"is None: fatal(\"Missing value \\\"{0}\\\" in configuration file\".format(key)) return value",
"\"_appleseedpython.pyd\")) def copy_binaries(self): progress(\"Copying binaries to root directory\") # Create",
"# in the Software without restriction, including without limitation the",
"builder. #-------------------------------------------------------------------------------------------------- class LinuxPackageBuilder(PackageBuilder): SYSTEM_LIBS_PREFIXES = [ \"linux\", \"librt\", \"libpthread\",",
"# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF",
"safe_make_directory(shaders_dir) self.__do_copy_shaders(os.path.join(self.settings.appleseed_shaders_path, \"appleseed\"), shaders_dir) self.__do_copy_shaders(os.path.join(self.settings.appleseed_shaders_path, \"blenderseed\"), shaders_dir) def __do_copy_shaders(self, source_dir,",
"to staging directory\") shutil.copytree(self.settings.root_dir, \"blenderseed\", ignore=shutil.ignore_patterns(\"scripts\")) def clean_stage(self): progress(\"Cleaning staging",
"progress(message): print(u\" {0}...\".format(message).encode('utf-8')) def warning(message): print(u\" {0}Warning: {1}.{2}\".format(colorama.Style.BRIGHT + colorama.Fore.MAGENTA,",
"# Ignore system libs. if self.__is_system_lib(lib): continue # Ignore Qt",
"\"{0}\" {1}'.format(name, target)) def __change_library_path(self, target, old, new): self.run('install_name_tool -change",
"returncode != 0: fatal(\"Failed to invoke ldd(1) to get dependencies",
"in os.walk(bin_dir): for filename in filenames: ext = os.path.splitext(filename)[1] if",
"= self.run_subprocess([\"otool\", \"-L\", filepath]) if returncode != 0: fatal(\"Failed to",
"out, err #-------------------------------------------------------------------------------------------------- # Windows package builder. #-------------------------------------------------------------------------------------------------- class WindowsPackageBuilder(PackageBuilder):",
"= os.path.expandvars(self.__get_required(tree, \"output_dir\")) def __get_required(self, tree, key): value = tree.findtext(key)",
"set to False because we must retrieve the unmodified dependency",
"returncode, out, err = self.run_subprocess([\"ldd\", filepath]) if returncode != 0:",
"__get_dependencies_for_file(self, filepath): returncode, out, err = self.run_subprocess([\"ldd\", filepath]) if returncode",
"import ElementTree import argparse import colorama import datetime import glob",
"self.settings.platform, self.build_date) package_path = os.path.join(self.settings.output_dir, package_name) archive_util.make_zipfile(package_path, \"blenderseed\") info(\"Package path:",
"sell # copies of the Software, and to permit persons",
"# Don't check for missing dependencies if we didn't attempt",
"print(\" Path to maketx: \" + self.maketx_path) print(\" Output directory:",
"= tree.findtext(key) if value is None: fatal(\"Missing value \\\"{0}\\\" in",
"parse line from otool(1) output: \" + line) lib =",
"class Settings: def load(self): self.this_dir = os.path.dirname(os.path.realpath(__file__)) self.root_dir = os.path.join(self.this_dir,",
"if not os.path.exists(candidate): candidate = os.path.join(\"/usr/local/lib/\", lib) if os.path.exists(candidate): info(\"Resolved",
"THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY",
"package_version self.build_date = build_date self.no_release = no_release def build_package(self): print(\"Building",
"on_rmtree_error(func, path, exc_info): # path contains the path of the",
"# skip the first line line = line.strip() # Ignore",
"Windows package builder. #-------------------------------------------------------------------------------------------------- class WindowsPackageBuilder(PackageBuilder): def copy_dependencies(self): progress(\"Windows-specific: Copying",
"returncode, out, err = self.run_subprocess([\"otool\", \"-L\", filepath]) if returncode !=",
"progress(\"Copying binaries to root directory\") # Create destination directory. bin_dir",
"print(\" Path to appleseed libraries: \" + self.appleseed_lib_path) print(\" Path",
"if self.__is_system_lib(line): continue # Ignore appleseed libs. if \"libappleseed\" in",
"distutils import archive_util, dir_util from xml.etree.ElementTree import ElementTree import argparse",
"u\"{0}\\u2717{1}\".format(colorama.Style.BRIGHT + colorama.Fore.RED, colorama.Style.RESET_ALL) def trace(message): # encode('utf-8') is required",
"all_libs = all_libs.union(libs) # Get shared libs needed by appleseed.python.",
"\"1.1.0\" SETTINGS_FILENAME = \"blenderseed.package.configuration.xml\" #-------------------------------------------------------------------------------------------------- # Utility functions. #-------------------------------------------------------------------------------------------------- GREEN_CHECKMARK",
"of the Software. # # THE SOFTWARE IS PROVIDED 'AS",
"OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION",
"!= \".py\" and ext != \".conf\": exe_path = os.path.join(dirpath, filename)",
"Let's just assume that it's read-only and unlink it. os.chmod(path,",
"self.clean_stage() self.build_final_zip_file() self.remove_stage() def remove_leftovers(self): progress(\"Removing leftovers from previous invocations\")",
"elif os.name == \"posix\" and platform.mac_ver()[0] == \"\": package_builder =",
"libs = self.__get_dependencies_for_file(lib) lib_libs = lib_libs.union(libs) all_libs = all_libs.union(lib_libs) if",
"= subprocess.Popen(\"git describe --long\", stdout=subprocess.PIPE, shell=True).stdout.read().strip() build_date = datetime.date.today().isoformat() print(\"blenderseed.package",
"\"appleseed\")) safe_delete_directory(\"blenderseed\") def copy_appleseed_python(self): progress(\"Copying appleseed.python to root directory\") #",
"OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT",
"lib in all_libs: trace(\" {0}\".format(lib)) # Copy needed libs to",
"f in files: if f.endswith(\".pyc\"): safe_delete_file(os.path.join(root, f)) def deploy_blenderseed_to_stage(self): progress(\"Deploying",
"progress(\"Copying shaders to root directory\") # Create destination directory. shaders_dir",
"+ line) lib = m.group(1) # Ignore self-references (why do",
"sources\") parser.add_argument(\"--nozip\", action=\"store_true\", help=\"copies appleseed binaries to blenderseed folder but",
"progress(\"Copying appleseed.python to root directory\") # Create destination directory. lib_dir",
"re.match(r\"(.*) \\(compatibility version .*, current version .*\\)\", line) if not",
"safe_delete_directory(os.path.join(self.settings.root_dir, \"appleseed\")) safe_delete_directory(\"blenderseed\") def copy_appleseed_python(self): progress(\"Copying appleseed.python to root directory\")",
"fatal(message): print(u\"{0}Fatal: {1}. Aborting.{2}\".format(colorama.Style.BRIGHT + colorama.Fore.RED, message, colorama.Style.RESET_ALL).encode('utf-8')) if sys.exc_info()[0]:",
"#-------------------------------------------------------------------------------------------------- def main(): colorama.init() parser = argparse.ArgumentParser(description=\"build a blenderseed package",
"self.appleseed_python_path) print(\" Path to maketx: \" + self.maketx_path) print(\" Output",
"= os.path.dirname(bin_path) lib_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") path_to_appleseed_lib = os.path.relpath(lib_dir,",
"lib_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") safe_make_directory(lib_dir) # Copy appleseed.python. dir_util.copy_tree(self.settings.appleseed_python_path,",
"disk\".format(lib)) return libs def __is_system_lib(self, lib): for prefix in self.SYSTEM_LIBS_PREFIXES:",
"\".so\": lib_path = os.path.join(dirpath, filename) self.__set_library_id(lib_path, filename) def __change_library_paths_in_libraries(self): lib_dir",
"lib_path = os.path.join(dirpath, filename) self.__change_library_paths_in_binary(lib_path) def __change_library_paths_in_executables(self): bin_dir = os.path.join(self.settings.root_dir,",
"\"lib\", \"*.so\")): self.run(\"chrpath -d \" + lib) appleseed_python_dir = os.path.join(self.settings.root_dir,",
"from __future__ import print_function from distutils import archive_util, dir_util from",
"is required to support output redirection to files or pipes.",
"\".\": self.__change_library_path(bin_path, lib_path, \"@loader_path/{0}\".format(lib_name)) else: self.__change_library_path(bin_path, lib_path, \"@loader_path/{0}/{1}\".format(path_to_appleseed_lib, lib_name)) def",
"def copy_dependencies(self): progress(\"Windows-specific: Copying dependencies\") bin_dir = self.settings.appleseed_bin_path for dll",
"+ \"'\") self.__load_values(tree) def print_summary(self): print(\"\") print(\" Platform: \" +",
"the path of the file that couldn't be removed. #",
"+ \"...\") tree = ElementTree() try: tree.parse(SETTINGS_FILENAME) except IOError: fatal(\"Failed",
"- 1: time.sleep(0.5) else: fatal(\"Failed to delete directory '\" +",
"# copies of the Software, and to permit persons to",
"shared libs needed by libraries. # TODO: we're not computing",
"self.__change_library_path(bin_path, lib_path, \"@loader_path/{0}/{1}\".format(path_to_appleseed_lib, lib_name)) def __set_library_id(self, target, name): self.run('install_name_tool -id",
"else: trace(u\" {0} {1}\".format(RED_CROSSMARK, lib)) # Don't check for missing",
"os.path.join(loader_path, lib) if not os.path.exists(candidate): candidate = os.path.join(\"/usr/local/lib/\", lib) if",
"err)) libs = set() for line in out.split(\"\\n\")[1:]: # skip",
"the Software. # # THE SOFTWARE IS PROVIDED 'AS IS',",
"TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN",
"bin_dir) # fix_paths set to False because we must retrieve",
"copy # of this software and associated documentation files (the",
"# Create destination directory. bin_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"bin\") safe_make_directory(bin_dir)",
"class WindowsPackageBuilder(PackageBuilder): def copy_dependencies(self): progress(\"Windows-specific: Copying dependencies\") bin_dir = self.settings.appleseed_bin_path",
"clean_stage(self): progress(\"Cleaning staging directory\") safe_delete_directory_recursively(\"blenderseed\", \"__pycache__\") for subdirectory in [\".git\",",
"released under the MIT license. # # Copyright (c) 2017-2018",
"Permission is hereby granted, free of charge, to any person",
"invoke ldd(1) to get dependencies for {0}: {1}\".format(filepath, err)) libs",
"entry in os.listdir(root_path): subdirectory = os.path.join(root_path, entry) if os.path.isdir(subdirectory): safe_delete_directory_recursively(subdirectory,",
"lib_dir) # Remove _appleseedpython.so (Python 2) since blenderseed only needs",
"+ \".zip\")) def remove_stage(self): progress(\"Deleting staging directory\") safe_delete_directory(\"blenderseed\") def run(self,",
"# Copy appleseed.python. dir_util.copy_tree(self.settings.appleseed_python_path, lib_dir) # Remove _appleseedpython.so (Python 2)",
"Parse the line. m = re.match(r\"(.*) \\(compatibility version .*, current",
"= u\"{0}\\u2713{1}\".format(colorama.Style.BRIGHT + colorama.Fore.GREEN, colorama.Style.RESET_ALL) RED_CROSSMARK = u\"{0}\\u2717{1}\".format(colorama.Style.BRIGHT + colorama.Fore.RED,",
"Copy all shared libraries. for lib in all_libs: shutil.copy(lib, lib_dir)",
"from root directory\") for root, dirs, files in os.walk(os.path.join(self.settings.root_dir, \"appleseed\",",
"0: continue # Parse the line. m = re.match(r\"(.*) \\(compatibility",
"package_builder = WindowsPackageBuilder(settings, package_version, build_date, no_release) elif os.name == \"posix\"",
"#-------------------------------------------------------------------------------------------------- GREEN_CHECKMARK = u\"{0}\\u2713{1}\".format(colorama.Style.BRIGHT + colorama.Fore.GREEN, colorama.Style.RESET_ALL) RED_CROSSMARK = u\"{0}\\u2717{1}\".format(colorama.Style.BRIGHT",
"os.path.join(self.settings.root_dir, \"appleseed\", \"bin\")) def post_process_package(self): pass #-------------------------------------------------------------------------------------------------- # Mac package",
"\"schemas\", \".gitignore\")) def copy_shaders(self): progress(\"Copying shaders to root directory\") #",
"The appleseedhq Organization # # Permission is hereby granted, free",
"= WindowsPackageBuilder(settings, package_version, build_date, no_release) elif os.name == \"posix\" and",
"WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT",
"to @loader_path. lib = lib.replace(\"@loader_path\", loader_path) # Handle libs relative",
"software is released under the MIT license. # # Copyright",
"Path to appleseed shaders: \" + self.appleseed_shaders_path) print(\" Path to",
"to permit persons to whom the Software is # furnished",
"WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING",
"try: if os.path.exists(path): os.remove(path) except OSError: fatal(\"Failed to delete file",
"not os.path.isabs(lib): # TODO: generalize to a collection of user-specified",
"WindowsPackageBuilder(settings, package_version, build_date, no_release) elif os.name == \"posix\" and platform.mac_ver()[0]",
"= os.path.expandvars(self.__get_required(tree, \"appleseed_settings_path\")) self.appleseed_python_path = os.path.expandvars(self.__get_required(tree, \"appleseed_python_path\")) self.maketx_path = os.path.expandvars(self.__get_required(tree,",
"\"...\") tree = ElementTree() try: tree.parse(SETTINGS_FILENAME) except IOError: fatal(\"Failed to",
"or ext == \".so\": lib_path = os.path.join(dirpath, filename) self.__set_library_id(lib_path, filename)",
"\"lib\", \"appleseed\") for py_cpp_module in glob.glob(os.path.join(appleseed_python_dir, \"*.so\")): self.run(\"chrpath -r \\$ORIGIN/../",
"continue # Ignore system libs. if self.__is_system_lib(line): continue # Ignore",
"\" + self.appleseed_release_path) print(\" Path to appleseed binaries: \" +",
"self.build_final_zip_file() self.remove_stage() def remove_leftovers(self): progress(\"Removing leftovers from previous invocations\") safe_delete_directory(os.path.join(self.settings.root_dir,",
"self.__fixup_binaries() def __fixup_binaries(self): progress(\"Mac-specific: Fixing up binaries\") self.set_libraries_ids() self.__change_library_paths_in_libraries() self.__change_library_paths_in_executables()",
"bin in [exe(\"appleseed.cli\")]: shutil.copy(os.path.join(self.settings.appleseed_bin_path, bin), bin_dir) # Copy maketx. shutil.copy(exe(self.settings.maketx_path),",
"for lib in all_libs: shutil.copy(lib, lib_dir) def post_process_package(self): progress(\"Linux-specific: Post-processing",
"libs = set() for line in out.split(\"\\n\")[1:]: # skip the",
"dir_util from xml.etree.ElementTree import ElementTree import argparse import colorama import",
"= os.path.join(self.this_dir, \"..\") print(\"Loading settings from \" + SETTINGS_FILENAME +",
"= 10 for attempt in range(Attempts): try: if os.path.exists(path): shutil.rmtree(path,",
"urllib.urlretrieve( \"https://raw.githubusercontent.com/appleseedhq/appleseed/master/sandbox/settings/{0}\".format(file), os.path.join(settings_dir, file)) def remove_pyc_files(self): progress(\"Removing pyc files from",
"# TODO: we're not computing the full transitive closure here!",
"to\") trace(\" {0}\".format(loader_path)) trace(\"and @rpath hardcoded to\") trace(\" {0}\".format(rpath)) returncode,",
"Settings() settings.load() settings.print_summary() if os.name == \"nt\": package_builder = WindowsPackageBuilder(settings,",
"rpath = \"/usr/local/lib/\" # TODO: a great simplification if True:",
"attempt in range(Attempts): try: if os.path.exists(path): shutil.rmtree(path, onerror=on_rmtree_error) return except",
"# # This source file is part of appleseed. #",
"package\") self.__fixup_binaries() def __fixup_binaries(self): progress(\"Mac-specific: Fixing up binaries\") self.set_libraries_ids() self.__change_library_paths_in_libraries()",
"handle other relative libs. if not os.path.isabs(lib): # TODO: generalize",
"file in [\".gitignore\", \"README.md\"]: safe_delete_file(os.path.join(\"blenderseed\", file)) def build_final_zip_file(self): progress(\"Building final",
"Platform: \" + self.platform) print(\" Path to appleseed release: \"",
"= [ \"linux\", \"librt\", \"libpthread\", \"libGL\", \"libX\", \"libselinux\", \"libICE\", \"libSM\",",
"# Let's just assume that it's read-only and unlink it.",
"directory. lib_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") safe_make_directory(lib_dir) # Copy appleseed",
"tree.parse(SETTINGS_FILENAME) except IOError: fatal(\"Failed to load configuration file '\" +",
"self.__change_library_paths_in_executables() def set_libraries_ids(self): lib_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") for dirpath,",
"print(\"\") def __load_values(self, tree): self.platform = self.__get_required(tree, \"platform\") self.appleseed_release_path =",
"!= 0: fatal(\"Failed to invoke otool(1) to get dependencies for",
"= os.path.expandvars(self.__get_required(tree, \"appleseed_lib_path\")) self.appleseed_shaders_path = os.path.expandvars(self.__get_required(tree, \"appleseed_shaders_path\")) self.appleseed_schemas_path = os.path.expandvars(self.__get_required(tree,",
"\" + SETTINGS_FILENAME + \"...\") tree = ElementTree() try: tree.parse(SETTINGS_FILENAME)",
"and to permit persons to whom the Software is #",
"= os.path.splitext(filename)[1] if ext == \".dylib\" or ext == \".so\":",
"hereby granted, free of charge, to any person obtaining a",
"stdout=subprocess.PIPE, shell=True).stdout.read().strip() build_date = datetime.date.today().isoformat() print(\"blenderseed.package version \" + VERSION)",
"\"https://raw.githubusercontent.com/appleseedhq/appleseed/master/sandbox/settings/{0}\".format(file), os.path.join(settings_dir, file)) def remove_pyc_files(self): progress(\"Removing pyc files from root",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE",
"\"nt\" else filepath def safe_delete_file(path): try: if os.path.exists(path): os.remove(path) except",
"needs _appleseedpython3.so (Python 3). # TODO: implement properly. safe_delete_file(os.path.join(lib_dir, \"appleseed\",",
"libraries. for lib in [\"libappleseed.dylib\", \"libappleseed.shared.dylib\"]: shutil.copy(os.path.join(self.settings.appleseed_lib_path, lib), lib_dir) #",
"# all copies or substantial portions of the Software. #",
"os.path.expandvars(self.__get_required(tree, \"appleseed_schemas_path\")) self.appleseed_settings_path = os.path.expandvars(self.__get_required(tree, \"appleseed_settings_path\")) self.appleseed_python_path = os.path.expandvars(self.__get_required(tree, \"appleseed_python_path\"))",
"libs needed by appleseed.python. appleseedpython_libs = self.__get_dependencies_for_file( os.path.join(self.settings.root_dir, \"appleseed\", \"lib\",",
"colorama.Style.RESET_ALL) def trace(message): # encode('utf-8') is required to support output",
"in [\"appleseed.cli.xml\"]: urllib.urlretrieve( \"https://raw.githubusercontent.com/appleseedhq/appleseed/master/sandbox/settings/{0}\".format(file), os.path.join(settings_dir, file)) def remove_pyc_files(self): progress(\"Removing pyc",
"we didn't attempt to fix them. if fix_paths: for lib",
"libs #-------------------------------------------------------------------------------------------------- # Entry point. #-------------------------------------------------------------------------------------------------- def main(): colorama.init() parser",
"target_dir) def download_settings_files(self): progress(\"Downloading settings files to root directory\") #",
"= all_libs.union(appleseedpython_libs) # Get shared libs needed by libraries. #",
"platform import re import shutil import stat import subprocess import",
"dll), os.path.join(self.settings.root_dir, \"appleseed\", \"bin\")) def post_process_package(self): pass #-------------------------------------------------------------------------------------------------- # Mac",
"OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH",
"#-------------------------------------------------------------------------------------------------- # Windows package builder. #-------------------------------------------------------------------------------------------------- class WindowsPackageBuilder(PackageBuilder): def copy_dependencies(self):",
"appleseed binaries. for bin in [exe(\"appleseed.cli\")]: shutil.copy(os.path.join(self.settings.appleseed_bin_path, bin), bin_dir) #",
"no_release=False): self.settings = settings self.package_version = package_version self.build_date = build_date",
"# Windows package builder. #-------------------------------------------------------------------------------------------------- class WindowsPackageBuilder(PackageBuilder): def copy_dependencies(self): progress(\"Windows-specific:",
"self.platform = self.__get_required(tree, \"platform\") self.appleseed_release_path = self.__get_required(tree, \"appleseed_release_path\") os.environ['APPLESEED'] =",
"libs = set() for line in out.split(\"\\n\"): line = line.strip()",
"# Handle libs relative to @rpath. lib = lib.replace(\"@rpath\", rpath)",
"\"posix\" and platform.mac_ver()[0] != \"\": package_builder = MacPackageBuilder(settings, package_version, build_date,",
"# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR",
"paths. candidate = os.path.join(loader_path, lib) if not os.path.exists(candidate): candidate =",
"+ py_cpp_module) def __is_system_lib(self, lib): for prefix in self.SYSTEM_LIBS_PREFIXES: if",
"Aborting.{2}\".format(colorama.Style.BRIGHT + colorama.Fore.RED, message, colorama.Style.RESET_ALL).encode('utf-8')) if sys.exc_info()[0]: print(traceback.format_exc()) sys.exit(1) def",
"def copy_appleseed_python(self): progress(\"Copying appleseed.python to root directory\") # Create destination",
"all copies or substantial portions of the Software. # #",
"# This source file is part of appleseed. # Visit",
"on disk\".format(lib)) return libs def __is_system_lib(self, lib): for prefix in",
"if not os.path.isabs(lib): # TODO: generalize to a collection of",
"builder. #-------------------------------------------------------------------------------------------------- class PackageBuilder(object): def __init__(self, settings, package_version, build_date, no_release=False):",
"binaries. for bin in [exe(\"appleseed.cli\")]: shutil.copy(os.path.join(self.settings.appleseed_bin_path, bin), bin_dir) # Copy",
"out, err = p.communicate() return p.returncode, out, err #-------------------------------------------------------------------------------------------------- #",
"be removed. # Let's just assume that it's read-only and",
"lib_libs.union(libs) all_libs = all_libs.union(lib_libs) if True: # Print dependencies. trace(\"",
"configuration file\".format(key)) return value #-------------------------------------------------------------------------------------------------- # Base package builder. #--------------------------------------------------------------------------------------------------",
"is released under the MIT license. # # Copyright (c)",
"{0}: {1}\".format(filepath, err)) libs = set() for line in out.split(\"\\n\")[1:]:",
"exe_path = os.path.join(dirpath, filename) self.__change_library_paths_in_binary(exe_path) # Can be used on",
"value \\\"{0}\\\" in configuration file\".format(key)) return value #-------------------------------------------------------------------------------------------------- # Base",
"lib): continue if fix_paths: # Handle libs relative to @loader_path.",
"Ignore system libs. if self.__is_system_lib(lib): continue # Ignore Qt frameworks.",
"safe_delete_directory(\"blenderseed\") def run(self, cmdline): trace(\"Running command line: {0}\".format(cmdline)) os.system(cmdline) def",
"to do so, subject to the following conditions: # #",
"SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR",
"# Copy maketx. shutil.copy(exe(self.settings.maketx_path), bin_dir) def copy_schemas(self): progress(\"Copying schemas to",
"libs = self.__get_dependencies_for_file(lib) lib_libs = lib_libs.union(libs) all_libs = all_libs.union(lib_libs) #",
"self.orchestrate() print(\"\") print(\"The package was successfully built.\") def orchestrate(self): self.remove_leftovers()",
"appleseedpython_libs = self.__get_dependencies_for_file( os.path.join(self.settings.root_dir, \"appleseed\", \"lib\", \"appleseed\", \"_appleseedpython3.so\")) all_libs =",
"+ path + \"'\") def on_rmtree_error(func, path, exc_info): # path",
"progress(\"Deleting staging directory\") safe_delete_directory(\"blenderseed\") def run(self, cmdline): trace(\"Running command line:",
"all_libs.union(appleseedpython_libs) # Get shared libs needed by libraries. # TODO:",
"# Get shared libs needed by binaries. all_libs = set()",
"\"appleseed\", \"bin\")) def post_process_package(self): pass #-------------------------------------------------------------------------------------------------- # Mac package builder.",
"warning(message): print(u\" {0}Warning: {1}.{2}\".format(colorama.Style.BRIGHT + colorama.Fore.MAGENTA, message, colorama.Style.RESET_ALL).encode('utf-8')) def fatal(message):",
"\"appleseed\", \"lib\") for dirpath, dirnames, filenames in os.walk(lib_dir): for filename",
"NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE",
"#-------------------------------------------------------------------------------------------------- # Entry point. #-------------------------------------------------------------------------------------------------- def main(): colorama.init() parser =",
"os.path.expandvars(self.__get_required(tree, \"appleseed_bin_path\")) self.appleseed_lib_path = os.path.expandvars(self.__get_required(tree, \"appleseed_lib_path\")) self.appleseed_shaders_path = os.path.expandvars(self.__get_required(tree, \"appleseed_shaders_path\"))",
"build_date self.no_release = no_release def build_package(self): print(\"Building package:\") print(\"\") self.orchestrate()",
"self.output_dir = os.path.expandvars(self.__get_required(tree, \"output_dir\")) def __get_required(self, tree, key): value =",
"except IOError: fatal(\"Failed to load configuration file '\" + SETTINGS_FILENAME",
"dependency in order to replace it by the correct one.",
"\"appleseed_bin_path\")) self.appleseed_lib_path = os.path.expandvars(self.__get_required(tree, \"appleseed_lib_path\")) self.appleseed_shaders_path = os.path.expandvars(self.__get_required(tree, \"appleseed_shaders_path\")) self.appleseed_schemas_path",
"binaries to root directory\") # Create destination directory. bin_dir =",
"!= 0: fatal(\"Failed to invoke ldd(1) to get dependencies for",
"and resources. # # This software is released under the",
"blenderseed package from sources\") parser.add_argument(\"--nozip\", action=\"store_true\", help=\"copies appleseed binaries to",
"lib) if os.path.exists(candidate): info(\"Resolved relative dependency {0} as {1}\".format(lib, candidate))",
"filepath, fix_paths=True): filename = os.path.basename(filepath) loader_path = os.path.dirname(filepath) rpath =",
"\".so\" def copy_dependencies(self): progress(\"Linux-specific: Copying dependencies\") # Create destination directory.",
"invocations\") safe_delete_directory(os.path.join(self.settings.root_dir, \"appleseed\")) safe_delete_directory(\"blenderseed\") def copy_appleseed_python(self): progress(\"Copying appleseed.python to root",
"for lib in [\"libappleseed.dylib\", \"libappleseed.shared.dylib\"]: shutil.copy(os.path.join(self.settings.appleseed_lib_path, lib), lib_dir) # Get",
"progress(\"Removing pyc files from root directory\") for root, dirs, files",
"lib_name = os.path.basename(lib_path) if path_to_appleseed_lib == \".\": self.__change_library_path(bin_path, lib_path, \"@loader_path/{0}\".format(lib_name))",
"argparse import colorama import datetime import glob import os import",
"and/or sell # copies of the Software, and to permit",
"@rpath hardcoded to\") trace(\" {0}\".format(rpath)) returncode, out, err = self.run_subprocess([\"otool\",",
"sys import time import traceback import urllib #-------------------------------------------------------------------------------------------------- # Constants.",
"lib_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") path_to_appleseed_lib = os.path.relpath(lib_dir, bin_dir) #",
"package_version, build_date, no_release) elif os.name == \"posix\" and platform.mac_ver()[0] ==",
"self.settings = settings self.package_version = package_version self.build_date = build_date self.no_release",
"build_package(self): print(\"Building package:\") print(\"\") self.orchestrate() print(\"\") print(\"The package was successfully",
"stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() return p.returncode, out, err",
"files to root directory\") # Create destination directory. settings_dir =",
"package_version, build_date, no_release=False): self.settings = settings self.package_version = package_version self.build_date",
"def warning(message): print(u\" {0}Warning: {1}.{2}\".format(colorama.Style.BRIGHT + colorama.Fore.MAGENTA, message, colorama.Style.RESET_ALL).encode('utf-8')) def",
"file is part of appleseed. # Visit https://appleseedhq.net/ for additional",
"else filepath def safe_delete_file(path): try: if os.path.exists(path): os.remove(path) except OSError:",
"\" + self.appleseed_bin_path) print(\" Path to appleseed libraries: \" +",
"to appleseed settings: \" + self.appleseed_settings_path) print(\" Path to appleseed.python:",
"= \"/usr/local/lib/\" # TODO: a great simplification if True: trace(\"Gathering",
"= os.path.join(dirpath, filename) self.__set_library_id(lib_path, filename) def __change_library_paths_in_libraries(self): lib_dir = os.path.join(self.settings.root_dir,",
"remove_stage(self): progress(\"Deleting staging directory\") safe_delete_directory(\"blenderseed\") def run(self, cmdline): trace(\"Running command",
"redirection to files or pipes. print(u\" {0}{1}{2}\".format(colorama.Style.DIM + colorama.Fore.WHITE, message,",
"file in [\"appleseed.cli.xml\"]: urllib.urlretrieve( \"https://raw.githubusercontent.com/appleseedhq/appleseed/master/sandbox/settings/{0}\".format(file), os.path.join(settings_dir, file)) def remove_pyc_files(self): progress(\"Removing",
"directory\") safe_delete_directory(\"blenderseed\") def run(self, cmdline): trace(\"Running command line: {0}\".format(cmdline)) os.system(cmdline)",
"u\"{0}\\u2713{1}\".format(colorama.Style.BRIGHT + colorama.Fore.GREEN, colorama.Style.RESET_ALL) RED_CROSSMARK = u\"{0}\\u2717{1}\".format(colorama.Style.BRIGHT + colorama.Fore.RED, colorama.Style.RESET_ALL)",
"settings = Settings() settings.load() settings.print_summary() if os.name == \"nt\": package_builder",
"in [\".git\", \".idea\", \"archives\", \"docs\", \"scripts\", \"tests\"]: safe_delete_directory(os.path.join(\"blenderseed\", subdirectory)) for",
"to {1}...\".format(lib, lib_dir)) shutil.copy(lib, lib_dir) def post_process_package(self): progress(\"Mac-specific: Post-processing package\")",
"staging directory\") package_name = \"blenderseed-{0}-{1}-{2}\".format(self.package_version, self.settings.platform, self.build_date) package_path = os.path.join(self.settings.output_dir,",
"dirs, files in os.walk(os.path.join(self.settings.root_dir, \"appleseed\", \"lib\")): for f in files:",
"by appleseed.python. appleseedpython_libs = self.__get_dependencies_for_file( os.path.join(self.settings.root_dir, \"appleseed\", \"lib\", \"appleseed\", \"_appleseedpython3.so\"))",
"self.remove_leftovers() self.copy_appleseed_python() self.copy_binaries() self.copy_dependencies() self.copy_schemas() self.copy_shaders() self.download_settings_files() self.remove_pyc_files() self.post_process_package() if",
"safe_make_directory(lib_dir) # Copy appleseed libraries. for lib in [\"libappleseed.so\", \"libappleseed.shared.so\"]:",
"self.__change_library_paths_in_libraries() self.__change_library_paths_in_executables() def set_libraries_ids(self): lib_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") for",
"def copy_dependencies(self): progress(\"Mac-specific: Copying dependencies\") # Create destination directory. lib_dir",
"[\"appleseed.dll\", \"appleseed.shared.dll\"]: shutil.copy(os.path.join(bin_dir, dll), os.path.join(self.settings.root_dir, \"appleseed\", \"bin\")) def post_process_package(self): pass",
"all_libs: if True: trace(\" Copying {0} to {1}...\".format(lib, lib_dir)) shutil.copy(lib,",
"in os.walk(source_dir): for f in files: if f.endswith(\".oso\"): shutil.copy(os.path.join(root, f),",
"part of appleseed. # Visit https://appleseedhq.net/ for additional information and",
"BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS",
"search paths. candidate = os.path.join(loader_path, lib) if not os.path.exists(candidate): candidate",
"@rpath. lib = lib.replace(\"@rpath\", rpath) # Try to handle other",
"subdirectory in [\".git\", \".idea\", \"archives\", \"docs\", \"scripts\", \"tests\"]: safe_delete_directory(os.path.join(\"blenderseed\", subdirectory))",
"[\"libappleseed.so\", \"libappleseed.shared.so\"]: shutil.copy(os.path.join(self.settings.appleseed_lib_path, lib), lib_dir) # Get shared libs needed",
"= all_libs.union(lib_libs) # Copy all shared libraries. for lib in",
"class PackageBuilder(object): def __init__(self, settings, package_version, build_date, no_release=False): self.settings =",
"shaders_dir) self.__do_copy_shaders(os.path.join(self.settings.appleseed_shaders_path, \"blenderseed\"), shaders_dir) def __do_copy_shaders(self, source_dir, target_dir): for root,",
"line: {0}\".format(cmdline)) os.system(cmdline) def run_subprocess(self, cmdline): p = subprocess.Popen(cmdline, stdout=subprocess.PIPE,",
"\"linux\", \"librt\", \"libpthread\", \"libGL\", \"libX\", \"libselinux\", \"libICE\", \"libSM\", \"libdl\", \"libm.so\",",
"executables and dynamic libraries. def __change_library_paths_in_binary(self, bin_path): progress(\"Patching {0}\".format(bin_path)) bin_dir",
"line. m = re.match(r\"(.*) \\(compatibility version .*, current version .*\\)\",",
"\"libappleseed.shared.dylib\"]: shutil.copy(os.path.join(self.settings.appleseed_lib_path, lib), lib_dir) # Get shared libs needed by",
"Copy appleseed libraries. for lib in [\"libappleseed.dylib\", \"libappleseed.shared.dylib\"]: shutil.copy(os.path.join(self.settings.appleseed_lib_path, lib),",
"import platform import re import shutil import stat import subprocess",
"appleseed.python. appleseedpython_libs = self.__get_dependencies_for_file( os.path.join(self.settings.root_dir, \"appleseed\", \"lib\", \"appleseed\", \"_appleseedpython3.so\")) all_libs",
"message, colorama.Style.RESET_ALL).encode('utf-8')) if sys.exc_info()[0]: print(traceback.format_exc()) sys.exit(1) def exe(filepath): return filepath",
"of charge, to any person obtaining a copy # of",
"if True: trace(\"Gathering dependencies for file\") trace(\" {0}\".format(filepath)) trace(\"with @loader_path",
"print(\" Path to appleseed schemas: \" + self.appleseed_schemas_path) print(\" Path",
"def set_libraries_ids(self): lib_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") for dirpath, dirnames,",
"target)) def __change_library_path(self, target, old, new): self.run('install_name_tool -change \"{0}\" \"{1}\"",
"build_date, no_release) elif os.name == \"posix\" and platform.mac_ver()[0] == \"\":",
"directory. for lib in all_libs: if True: trace(\" Copying {0}",
"filename) self.__set_library_id(lib_path, filename) def __change_library_paths_in_libraries(self): lib_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\")",
"ext == \".so\": lib_path = os.path.join(dirpath, filename) self.__set_library_id(lib_path, filename) def",
"candidate = os.path.join(loader_path, lib) if not os.path.exists(candidate): candidate = os.path.join(\"/usr/local/lib/\",",
"= os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") safe_make_directory(lib_dir) # Copy appleseed libraries. for",
"collection of user-specified search paths. candidate = os.path.join(loader_path, lib) if",
"<filename>scripts/blenderseed.package.py #!/usr/bin/python # # This source file is part of",
"len(line) == 0: continue # Parse the line. m =",
"= os.path.expandvars(self.__get_required(tree, \"maketx_path\")) self.output_dir = os.path.expandvars(self.__get_required(tree, \"output_dir\")) def __get_required(self, tree,",
"\"appleseed\", \"lib\")): for f in files: if f.endswith(\".pyc\"): safe_delete_file(os.path.join(root, f))",
"Organization # # Permission is hereby granted, free of charge,",
"leftovers from previous invocations\") safe_delete_directory(os.path.join(self.settings.root_dir, \"appleseed\")) safe_delete_directory(\"blenderseed\") def copy_appleseed_python(self): progress(\"Copying",
"bin), bin_dir) # Copy maketx. shutil.copy(exe(self.settings.maketx_path), bin_dir) def copy_schemas(self): progress(\"Copying",
"self.deploy_blenderseed_to_stage() self.clean_stage() self.build_final_zip_file() self.remove_stage() def remove_leftovers(self): progress(\"Removing leftovers from previous",
"libs. if \"libappleseed\" in line: continue libs.add(line.split()[2]) return libs #--------------------------------------------------------------------------------------------------",
"Path to appleseed schemas: \" + self.appleseed_schemas_path) print(\" Path to",
"__change_library_path(self, target, old, new): self.run('install_name_tool -change \"{0}\" \"{1}\" {2}'.format(old, new,",
"load configuration file '\" + SETTINGS_FILENAME + \"'\") self.__load_values(tree) def",
"{1}\".format(filepath, err)) libs = set() for line in out.split(\"\\n\"): line",
"time.sleep(0.5) else: fatal(\"Failed to delete directory '\" + path +",
"== \".so\": lib_path = os.path.join(dirpath, filename) self.__change_library_paths_in_binary(lib_path) def __change_library_paths_in_executables(self): bin_dir",
"self.__is_system_lib(line): continue # Ignore appleseed libs. if \"libappleseed\" in line:",
"fatal(\"Unsupported platform: \" + os.name) package_builder.build_package() if __name__ == \"__main__\":",
"AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #",
"\"libSM\", \"libdl\", \"libm.so\", \"libgcc\", \"libc.so\", \"/lib64/ld-linux-\", \"libstdc++\", \"libxcb\", \"libdrm\", \"libnsl\",",
"stat import subprocess import sys import time import traceback import",
"to load configuration file '\" + SETTINGS_FILENAME + \"'\") self.__load_values(tree)",
"# # Copyright (c) 2017-2018 <NAME>, The appleseedhq Organization #",
"lib_libs = lib_libs.union(libs) all_libs = all_libs.union(lib_libs) # Copy all shared",
"all shared libraries. for lib in all_libs: shutil.copy(lib, lib_dir) def",
"[ \"/System/Library/\", \"/usr/lib/libcurl\", \"/usr/lib/libc++\", \"/usr/lib/libbz2\", \"/usr/lib/libSystem\", #\"/usr/lib/libz\", \"/usr/lib/libncurses\", \"/usr/lib/libobjc.A.dylib\" ]",
"appleseed_python_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\", \"appleseed\") for py_cpp_module in glob.glob(os.path.join(appleseed_python_dir,",
"trace(\" Copying {0} to {1}...\".format(lib, lib_dir)) shutil.copy(lib, lib_dir) def post_process_package(self):",
"len(line) == 0: continue # Ignore system libs. if self.__is_system_lib(line):",
"return True return False #-------------------------------------------------------------------------------------------------- # Linux package builder. #--------------------------------------------------------------------------------------------------",
"\"appleseed\", \"lib\", \"appleseed\") for py_cpp_module in glob.glob(os.path.join(appleseed_python_dir, \"*.so\")): self.run(\"chrpath -r",
"TODO: implement properly. safe_delete_file(os.path.join(lib_dir, \"appleseed\", \"_appleseedpython.so\")) safe_delete_file(os.path.join(lib_dir, \"appleseed\", \"_appleseedpython.pyd\")) def",
"\" + self.appleseed_python_path) print(\" Path to maketx: \" + self.maketx_path)",
"[\"appleseed.cli.xml\"]: urllib.urlretrieve( \"https://raw.githubusercontent.com/appleseedhq/appleseed/master/sandbox/settings/{0}\".format(file), os.path.join(settings_dir, file)) def remove_pyc_files(self): progress(\"Removing pyc files",
"lib.startswith(prefix): return True return False def __get_dependencies_for_file(self, filepath): returncode, out,",
"+ self.maketx_path) print(\" Output directory: \" + self.output_dir) print(\"\") def",
"attempt to fix them. if fix_paths: for lib in libs:",
"the Software, and to permit persons to whom the Software",
"\"bin\")) def post_process_package(self): pass #-------------------------------------------------------------------------------------------------- # Mac package builder. #--------------------------------------------------------------------------------------------------",
"Ignore system libs. if self.__is_system_lib(line): continue # Ignore appleseed libs.",
"subprocess import sys import time import traceback import urllib #--------------------------------------------------------------------------------------------------",
"from distutils import archive_util, dir_util from xml.etree.ElementTree import ElementTree import",
"that couldn't be removed. # Let's just assume that it's",
"return False #-------------------------------------------------------------------------------------------------- # Linux package builder. #-------------------------------------------------------------------------------------------------- class LinuxPackageBuilder(PackageBuilder):",
"platform.mac_ver()[0] != \"\": package_builder = MacPackageBuilder(settings, package_version, build_date, no_release) elif",
"= LinuxPackageBuilder(settings, package_version, build_date, no_release) else: fatal(\"Unsupported platform: \" +",
"lib in libs: if not os.path.isfile(lib): fatal(\"Dependency {0} could not",
"\"libgcc\", \"libc.so\", \"/lib64/ld-linux-\", \"libstdc++\", \"libxcb\", \"libdrm\", \"libnsl\", \"libuuid\", \"libgthread\", \"libglib\",",
"\"lib\") safe_make_directory(lib_dir) # Copy appleseed.python. dir_util.copy_tree(self.settings.appleseed_python_path, lib_dir) # Remove _appleseedpython.so",
"ext == \".so\": lib_path = os.path.join(dirpath, filename) self.__change_library_paths_in_binary(lib_path) def __change_library_paths_in_executables(self):",
"line in out.split(\"\\n\"): line = line.strip() # Ignore empty lines.",
"\"appleseed\", \"shaders\") safe_make_directory(shaders_dir) self.__do_copy_shaders(os.path.join(self.settings.appleseed_shaders_path, \"appleseed\"), shaders_dir) self.__do_copy_shaders(os.path.join(self.settings.appleseed_shaders_path, \"blenderseed\"), shaders_dir) def",
"shutil.rmtree(path, onerror=on_rmtree_error) return except OSError: if attempt < Attempts -",
"#-------------------------------------------------------------------------------------------------- # Settings. #-------------------------------------------------------------------------------------------------- class Settings: def load(self): self.this_dir =",
"lib_libs = lib_libs.union(libs) all_libs = all_libs.union(lib_libs) if True: # Print",
"MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN",
"additional information and resources. # # This software is released",
"\".py\" and ext != \".conf\": exe_path = os.path.join(dirpath, filename) self.__change_library_paths_in_binary(exe_path)",
"package\") for bin in glob.glob(os.path.join(self.settings.root_dir, \"appleseed\", \"bin\", \"*\")): self.run(\"chrpath -r",
"#-------------------------------------------------------------------------------------------------- class WindowsPackageBuilder(PackageBuilder): def copy_dependencies(self): progress(\"Windows-specific: Copying dependencies\") bin_dir =",
"them. if fix_paths: for lib in libs: if not os.path.isfile(lib):",
"{0}\".format(cmdline)) os.system(cmdline) def run_subprocess(self, cmdline): p = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=subprocess.PIPE)",
"bin in glob.glob(os.path.join(self.settings.root_dir, \"appleseed\", \"bin\", \"*\")): libs = self.__get_dependencies_for_file(bin) all_libs",
"line) if not m: fatal(\"Failed to parse line from otool(1)",
"staging directory\") safe_delete_directory(\"blenderseed\") def run(self, cmdline): trace(\"Running command line: {0}\".format(cmdline))",
"BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY,",
"info(\"Package path: {0}\".format(package_path + \".zip\")) def remove_stage(self): progress(\"Deleting staging directory\")",
"directory. settings_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"settings\") safe_make_directory(settings_dir) for file in",
"for py_cpp_module in glob.glob(os.path.join(appleseed_python_dir, \"*.so\")): self.run(\"chrpath -r \\$ORIGIN/../ \" +",
"USE OR OTHER DEALINGS IN # THE SOFTWARE. # from",
"Software is # furnished to do so, subject to the",
"continue # Ignore Qt frameworks. if re.search(r\"Qt.*\\.framework\", lib): continue if",
"os.path.isfile(lib): trace(u\" {0} {1}\".format(GREEN_CHECKMARK, lib)) else: trace(u\" {0} {1}\".format(RED_CROSSMARK, lib))",
"appleseed libs. if \"libappleseed\" in line: continue libs.add(line.split()[2]) return libs",
"whom the Software is # furnished to do so, subject",
"# path contains the path of the file that couldn't",
"input_file in glob.glob(input_pattern): shutil.copy(input_file, output_path) #-------------------------------------------------------------------------------------------------- # Settings. #-------------------------------------------------------------------------------------------------- class",
"\"\": package_builder = MacPackageBuilder(settings, package_version, build_date, no_release) elif os.name ==",
"lib_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") for dirpath, dirnames, filenames in",
"of appleseed. # Visit https://appleseedhq.net/ for additional information and resources.",
"do so, subject to the following conditions: # # The",
"rpath) # Try to handle other relative libs. if not",
"out, err = self.run_subprocess([\"ldd\", filepath]) if returncode != 0: fatal(\"Failed",
"True: trace(\"Dependencies for file {0}:\".format(filepath)) for lib in libs: if",
"remove_pyc_files(self): progress(\"Removing pyc files from root directory\") for root, dirs,",
"otool(1) to get dependencies for {0}: {1}\".format(filepath, err)) libs =",
"we're not computing the full transitive closure here! lib_libs =",
"# furnished to do so, subject to the following conditions:",
"directory\") for root, dirs, files in os.walk(os.path.join(self.settings.root_dir, \"appleseed\", \"lib\")): for",
"functions. #-------------------------------------------------------------------------------------------------- GREEN_CHECKMARK = u\"{0}\\u2713{1}\".format(colorama.Style.BRIGHT + colorama.Fore.GREEN, colorama.Style.RESET_ALL) RED_CROSSMARK =",
"os.path.join(self.this_dir, \"..\") print(\"Loading settings from \" + SETTINGS_FILENAME + \"...\")",
"Path to appleseed settings: \" + self.appleseed_settings_path) print(\" Path to",
"shall be included in # all copies or substantial portions",
"KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO",
"in os.walk(os.path.join(self.settings.root_dir, \"appleseed\", \"lib\")): for f in files: if f.endswith(\".pyc\"):",
"pass #-------------------------------------------------------------------------------------------------- # Mac package builder. #-------------------------------------------------------------------------------------------------- class MacPackageBuilder(PackageBuilder): SYSTEM_LIBS_PREFIXES",
"print(u\" {0}...\".format(message).encode('utf-8')) def warning(message): print(u\" {0}Warning: {1}.{2}\".format(colorama.Style.BRIGHT + colorama.Fore.MAGENTA, message,",
"could not be found on disk\".format(lib)) return libs def __is_system_lib(self,",
"OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"ext = os.path.splitext(filename)[1] if ext == \".dylib\" or ext ==",
"self.appleseed_settings_path) print(\" Path to appleseed.python: \" + self.appleseed_python_path) print(\" Path",
"safe_delete_directory_recursively(\"blenderseed\", \"__pycache__\") for subdirectory in [\".git\", \".idea\", \"archives\", \"docs\", \"scripts\",",
"needed libs to lib directory. for lib in all_libs: if",
"err = self.run_subprocess([\"otool\", \"-L\", filepath]) if returncode != 0: fatal(\"Failed",
"\"{1}\" {2}'.format(old, new, target)) def __get_dependencies_for_file(self, filepath, fix_paths=True): filename =",
"to root directory\") # Create destination directory. lib_dir = os.path.join(self.settings.root_dir,",
"= \"blenderseed-{0}-{1}-{2}\".format(self.package_version, self.settings.platform, self.build_date) package_path = os.path.join(self.settings.output_dir, package_name) archive_util.make_zipfile(package_path, \"blenderseed\")",
"\" + line) lib = m.group(1) # Ignore self-references (why",
"= candidate libs.add(lib) if True: trace(\"Dependencies for file {0}:\".format(filepath)) for",
"\"libc.so\", \"/lib64/ld-linux-\", \"libstdc++\", \"libxcb\", \"libdrm\", \"libnsl\", \"libuuid\", \"libgthread\", \"libglib\", \"libgobject\",",
"loader_path) # Handle libs relative to @rpath. lib = lib.replace(\"@rpath\",",
"libs. if self.__is_system_lib(lib): continue # Ignore Qt frameworks. if re.search(r\"Qt.*\\.framework\",",
"fix them. if fix_paths: for lib in libs: if not",
"get dependencies for {0}: {1}\".format(filepath, err)) libs = set() for",
"in all_libs: trace(\" {0}\".format(lib)) # Copy needed libs to lib",
"continue # Parse the line. m = re.match(r\"(.*) \\(compatibility version",
"shell=True).stdout.read().strip() build_date = datetime.date.today().isoformat() print(\"blenderseed.package version \" + VERSION) print(\"\")",
"self.appleseed_release_path self.appleseed_bin_path = os.path.expandvars(self.__get_required(tree, \"appleseed_bin_path\")) self.appleseed_lib_path = os.path.expandvars(self.__get_required(tree, \"appleseed_lib_path\")) self.appleseed_shaders_path",
"for line in out.split(\"\\n\"): line = line.strip() # Ignore empty",
"if os.name == \"nt\": package_builder = WindowsPackageBuilder(settings, package_version, build_date, no_release)",
"\".idea\", \"archives\", \"docs\", \"scripts\", \"tests\"]: safe_delete_directory(os.path.join(\"blenderseed\", subdirectory)) for file in",
"the file that couldn't be removed. # Let's just assume",
"\"libappleseed.shared.so\"]: shutil.copy(os.path.join(self.settings.appleseed_lib_path, lib), lib_dir) # Get shared libs needed by",
"appleseed libraries. for lib in [\"libappleseed.dylib\", \"libappleseed.shared.dylib\"]: shutil.copy(os.path.join(self.settings.appleseed_lib_path, lib), lib_dir)",
"os.walk(source_dir): for f in files: if f.endswith(\".oso\"): shutil.copy(os.path.join(root, f), target_dir)",
"all_libs = set() for bin in glob.glob(os.path.join(self.settings.root_dir, \"appleseed\", \"bin\", \"*\")):",
"we must retrieve the unmodified dependency in order to replace",
"lib) if not os.path.exists(candidate): candidate = os.path.join(\"/usr/local/lib/\", lib) if os.path.exists(candidate):",
"for bin in glob.glob(os.path.join(self.settings.root_dir, \"appleseed\", \"bin\", \"*\")): libs = self.__get_dependencies_for_file(bin)",
"source file is part of appleseed. # Visit https://appleseedhq.net/ for",
"assume that it's read-only and unlink it. os.chmod(path, stat.S_IWRITE) os.unlink(path)",
"shutil.copy(lib, lib_dir) def post_process_package(self): progress(\"Mac-specific: Post-processing package\") self.__fixup_binaries() def __fixup_binaries(self):",
"# fix_paths set to False because we must retrieve the",
"replace it by the correct one. for lib_path in self.__get_dependencies_for_file(bin_path,",
"= os.path.join(dirpath, filename) self.__change_library_paths_in_binary(lib_path) def __change_library_paths_in_executables(self): bin_dir = os.path.join(self.settings.root_dir, \"appleseed\",",
"in range(Attempts): try: if os.path.exists(path): shutil.rmtree(path, onerror=on_rmtree_error) return except OSError:",
"\".zip\")) def remove_stage(self): progress(\"Deleting staging directory\") safe_delete_directory(\"blenderseed\") def run(self, cmdline):",
"= os.path.dirname(os.path.realpath(__file__)) self.root_dir = os.path.join(self.this_dir, \"..\") print(\"Loading settings from \"",
"appleseed.python. dir_util.copy_tree(self.settings.appleseed_python_path, lib_dir) # Remove _appleseedpython.so (Python 2) since blenderseed",
"def __load_values(self, tree): self.platform = self.__get_required(tree, \"platform\") self.appleseed_release_path = self.__get_required(tree,",
"blenderseed folder but does not build a release package\") args",
"in os.walk(lib_dir): for filename in filenames: ext = os.path.splitext(filename)[1] if",
"schemas to root directory\") dir_util.copy_tree(self.settings.appleseed_schemas_path, os.path.join(self.settings.root_dir, \"appleseed\", \"schemas\")) safe_delete_file(os.path.join(self.settings.root_dir, \"appleseed\",",
"\"libxshmfence.so\" ] def plugin_extension(self): return \".so\" def copy_dependencies(self): progress(\"Linux-specific: Copying",
"if ext != \".py\" and ext != \".conf\": exe_path =",
"progress(\"Mac-specific: Fixing up binaries\") self.set_libraries_ids() self.__change_library_paths_in_libraries() self.__change_library_paths_in_executables() def set_libraries_ids(self): lib_dir",
"def clean_stage(self): progress(\"Cleaning staging directory\") safe_delete_directory_recursively(\"blenderseed\", \"__pycache__\") for subdirectory in",
"= re.match(r\"(.*) \\(compatibility version .*, current version .*\\)\", line) if",
"colorama.Fore.GREEN, colorama.Style.RESET_ALL) RED_CROSSMARK = u\"{0}\\u2717{1}\".format(colorama.Style.BRIGHT + colorama.Fore.RED, colorama.Style.RESET_ALL) def trace(message):",
"system libs. if self.__is_system_lib(line): continue # Ignore appleseed libs. if",
"source_dir, target_dir): for root, dirs, files in os.walk(source_dir): for f",
"\\\"{0}\\\" in configuration file\".format(key)) return value #-------------------------------------------------------------------------------------------------- # Base package",
"WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND",
"def pushd(path): old_path = os.getcwd() os.chdir(path) return old_path def copy_glob(input_pattern,",
"exe(filepath): return filepath + \".exe\" if os.name == \"nt\" else",
"it by the correct one. for lib_path in self.__get_dependencies_for_file(bin_path, fix_paths=False):",
"the line. m = re.match(r\"(.*) \\(compatibility version .*, current version",
"the Software is # furnished to do so, subject to",
"limitation the rights # to use, copy, modify, merge, publish,",
"def remove_stage(self): progress(\"Deleting staging directory\") safe_delete_directory(\"blenderseed\") def run(self, cmdline): trace(\"Running",
"all_libs = all_libs.union(lib_libs) # Copy all shared libraries. for lib",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #",
"version .*, current version .*\\)\", line) if not m: fatal(\"Failed",
"def __change_library_paths_in_libraries(self): lib_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") for dirpath, dirnames,",
"prefix in self.SYSTEM_LIBS_PREFIXES: if lib.startswith(prefix): return True return False def",
"great simplification if True: trace(\"Gathering dependencies for file\") trace(\" {0}\".format(filepath))",
"dependencies for {0}: {1}\".format(filepath, err)) libs = set() for line",
"(Python 3). # TODO: implement properly. safe_delete_file(os.path.join(lib_dir, \"appleseed\", \"_appleseedpython.so\")) safe_delete_file(os.path.join(lib_dir,",
"{0}\".format(rpath)) returncode, out, err = self.run_subprocess([\"otool\", \"-L\", filepath]) if returncode",
"ext = os.path.splitext(filename)[1] if ext != \".py\" and ext !=",
"False because we must retrieve the unmodified dependency in order",
"= settings self.package_version = package_version self.build_date = build_date self.no_release =",
"os.path.join(settings_dir, file)) def remove_pyc_files(self): progress(\"Removing pyc files from root directory\")",
"copies or substantial portions of the Software. # # THE",
"[\"libappleseed.dylib\", \"libappleseed.shared.dylib\"]: shutil.copy(os.path.join(self.settings.appleseed_lib_path, lib), lib_dir) # Get shared libs needed",
"def build_package(self): print(\"Building package:\") print(\"\") self.orchestrate() print(\"\") print(\"The package was",
"def post_process_package(self): pass #-------------------------------------------------------------------------------------------------- # Mac package builder. #-------------------------------------------------------------------------------------------------- class",
"for file {0}:\".format(filepath)) for lib in libs: if os.path.isfile(lib): trace(u\"",
"appleseed schemas: \" + self.appleseed_schemas_path) print(\" Path to appleseed settings:",
"continue if fix_paths: # Handle libs relative to @loader_path. lib",
"True: trace(\" Copying {0} to {1}...\".format(lib, lib_dir)) shutil.copy(lib, lib_dir) def",
"+ self.platform) print(\" Path to appleseed release: \" + self.appleseed_release_path)",
"only needs _appleseedpython3.so (Python 3). # TODO: implement properly. safe_delete_file(os.path.join(lib_dir,",
"directory\") safe_delete_directory_recursively(\"blenderseed\", \"__pycache__\") for subdirectory in [\".git\", \".idea\", \"archives\", \"docs\",",
"2) since blenderseed only needs _appleseedpython3.so (Python 3). # TODO:",
"OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT",
"print(\"Building package:\") print(\"\") self.orchestrate() print(\"\") print(\"The package was successfully built.\")",
"self.__get_required(tree, \"appleseed_release_path\") os.environ['APPLESEED'] = self.appleseed_release_path self.appleseed_bin_path = os.path.expandvars(self.__get_required(tree, \"appleseed_bin_path\")) self.appleseed_lib_path",
"0: continue # Ignore system libs. if self.__is_system_lib(line): continue #",
"lib) appleseed_python_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\", \"appleseed\") for py_cpp_module in",
"\"librt\", \"libpthread\", \"libGL\", \"libX\", \"libselinux\", \"libICE\", \"libSM\", \"libdl\", \"libm.so\", \"libgcc\",",
"of this software and associated documentation files (the 'Software'), to",
"lib_dir) def post_process_package(self): progress(\"Mac-specific: Post-processing package\") self.__fixup_binaries() def __fixup_binaries(self): progress(\"Mac-specific:",
"generalize to a collection of user-specified search paths. candidate =",
"delete file '\" + path + \"'\") def on_rmtree_error(func, path,",
"progress(\"Linux-specific: Copying dependencies\") # Create destination directory. lib_dir = os.path.join(self.settings.root_dir,",
"def fatal(message): print(u\"{0}Fatal: {1}. Aborting.{2}\".format(colorama.Style.BRIGHT + colorama.Fore.RED, message, colorama.Style.RESET_ALL).encode('utf-8')) if",
"IOError: fatal(\"Failed to load configuration file '\" + SETTINGS_FILENAME +",
"dependencies\") # Create destination directory. lib_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\")",
"files: if f.endswith(\".oso\"): shutil.copy(os.path.join(root, f), target_dir) def download_settings_files(self): progress(\"Downloading settings",
"progress(\"Copying schemas to root directory\") dir_util.copy_tree(self.settings.appleseed_schemas_path, os.path.join(self.settings.root_dir, \"appleseed\", \"schemas\")) safe_delete_file(os.path.join(self.settings.root_dir,",
"__change_library_paths_in_libraries(self): lib_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") for dirpath, dirnames, filenames",
"# Create destination directory. shaders_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"shaders\") safe_make_directory(shaders_dir)",
"needed by libraries. # TODO: we're not computing the full",
"f.endswith(\".oso\"): shutil.copy(os.path.join(root, f), target_dir) def download_settings_files(self): progress(\"Downloading settings files to",
"VERSION = \"1.1.0\" SETTINGS_FILENAME = \"blenderseed.package.configuration.xml\" #-------------------------------------------------------------------------------------------------- # Utility functions.",
"dynamic libraries. def __change_library_paths_in_binary(self, bin_path): progress(\"Patching {0}\".format(bin_path)) bin_dir = os.path.dirname(bin_path)",
"\"/usr/lib/libbz2\", \"/usr/lib/libSystem\", #\"/usr/lib/libz\", \"/usr/lib/libncurses\", \"/usr/lib/libobjc.A.dylib\" ] def copy_dependencies(self): progress(\"Mac-specific: Copying",
"= os.path.join(loader_path, lib) if not os.path.exists(candidate): candidate = os.path.join(\"/usr/local/lib/\", lib)",
"by the correct one. for lib_path in self.__get_dependencies_for_file(bin_path, fix_paths=False): lib_name",
"self.appleseed_python_path = os.path.expandvars(self.__get_required(tree, \"appleseed_python_path\")) self.maketx_path = os.path.expandvars(self.__get_required(tree, \"maketx_path\")) self.output_dir =",
"IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"\"bin\") for dirpath, dirnames, filenames in os.walk(bin_dir): for filename in",
"Software, and to permit persons to whom the Software is",
"\"blenderseed\", ignore=shutil.ignore_patterns(\"scripts\")) def clean_stage(self): progress(\"Cleaning staging directory\") safe_delete_directory_recursively(\"blenderseed\", \"__pycache__\") for",
"to\") trace(\" {0}\".format(rpath)) returncode, out, err = self.run_subprocess([\"otool\", \"-L\", filepath])",
"Visit https://appleseedhq.net/ for additional information and resources. # # This",
"target_dir): for root, dirs, files in os.walk(source_dir): for f in",
"{1}...\".format(lib, lib_dir)) shutil.copy(lib, lib_dir) def post_process_package(self): progress(\"Mac-specific: Post-processing package\") self.__fixup_binaries()",
"message, colorama.Style.RESET_ALL).encode('utf-8')) def info(message): print(u\" {0}\".format(message).encode('utf-8')) def progress(message): print(u\" {0}...\".format(message).encode('utf-8'))",
"\" + VERSION) print(\"\") settings = Settings() settings.load() settings.print_summary() if",
"line line = line.strip() # Ignore empty lines. if len(line)",
"'Software'), to deal # in the Software without restriction, including",
"LinuxPackageBuilder(PackageBuilder): SYSTEM_LIBS_PREFIXES = [ \"linux\", \"librt\", \"libpthread\", \"libGL\", \"libX\", \"libselinux\",",
"# Constants. #-------------------------------------------------------------------------------------------------- VERSION = \"1.1.0\" SETTINGS_FILENAME = \"blenderseed.package.configuration.xml\" #--------------------------------------------------------------------------------------------------",
"copy_dependencies(self): progress(\"Linux-specific: Copying dependencies\") # Create destination directory. lib_dir =",
"\"libGL\", \"libX\", \"libselinux\", \"libICE\", \"libSM\", \"libdl\", \"libm.so\", \"libgcc\", \"libc.so\", \"/lib64/ld-linux-\",",
"relative to @loader_path. lib = lib.replace(\"@loader_path\", loader_path) # Handle libs",
"the correct one. for lib_path in self.__get_dependencies_for_file(bin_path, fix_paths=False): lib_name =",
"all_libs.union(lib_libs) if True: # Print dependencies. trace(\" Dependencies:\") for lib",
"appleseed shaders: \" + self.appleseed_shaders_path) print(\" Path to appleseed schemas:",
"= os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") safe_make_directory(lib_dir) # Copy appleseed.python. dir_util.copy_tree(self.settings.appleseed_python_path, lib_dir)",
"= os.path.join(dirpath, filename) self.__change_library_paths_in_binary(exe_path) # Can be used on executables",
"release package\") args = parser.parse_args() no_release = args.nozip package_version =",
"def safe_delete_directory(path): Attempts = 10 for attempt in range(Attempts): try:",
"err)) libs = set() for line in out.split(\"\\n\"): line =",
"download_settings_files(self): progress(\"Downloading settings files to root directory\") # Create destination",
"dir_util.copy_tree(self.settings.appleseed_python_path, lib_dir) # Remove _appleseedpython.so (Python 2) since blenderseed only",
"not os.path.isdir(path): os.makedirs(path) def pushd(path): old_path = os.getcwd() os.chdir(path) return",
"shutil.copy(os.path.join(self.settings.appleseed_lib_path, lib), lib_dir) # Get shared libs needed by binaries.",
"if \"libappleseed\" in line: continue libs.add(line.split()[2]) return libs #-------------------------------------------------------------------------------------------------- #",
"self.output_dir) print(\"\") def __load_values(self, tree): self.platform = self.__get_required(tree, \"platform\") self.appleseed_release_path",
"SETTINGS_FILENAME + \"'\") self.__load_values(tree) def print_summary(self): print(\"\") print(\" Platform: \"",
"os.path.join(\"/usr/local/lib/\", lib) if os.path.exists(candidate): info(\"Resolved relative dependency {0} as {1}\".format(lib,",
"file {0}:\".format(filepath)) for lib in libs: if os.path.isfile(lib): trace(u\" {0}",
"self.appleseed_lib_path) print(\" Path to appleseed shaders: \" + self.appleseed_shaders_path) print(\"",
"file '\" + SETTINGS_FILENAME + \"'\") self.__load_values(tree) def print_summary(self): print(\"\")",
"obtaining a copy # of this software and associated documentation",
"builder. #-------------------------------------------------------------------------------------------------- class WindowsPackageBuilder(PackageBuilder): def copy_dependencies(self): progress(\"Windows-specific: Copying dependencies\") bin_dir",
"subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() return p.returncode, out,",
"Copy maketx. shutil.copy(exe(self.settings.maketx_path), bin_dir) def copy_schemas(self): progress(\"Copying schemas to root",
"is # furnished to do so, subject to the following",
"to whom the Software is # furnished to do so,",
"fix_paths set to False because we must retrieve the unmodified",
"glob import os import platform import re import shutil import",
"directory '\" + path + \"'\") def safe_delete_directory_recursively(root_path, directory_name): safe_delete_directory(os.path.join(root_path,",
"THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY",
"Fixing up binaries\") self.set_libraries_ids() self.__change_library_paths_in_libraries() self.__change_library_paths_in_executables() def set_libraries_ids(self): lib_dir =",
"on executables and dynamic libraries. def __change_library_paths_in_binary(self, bin_path): progress(\"Patching {0}\".format(bin_path))",
"+ \".exe\" if os.name == \"nt\" else filepath def safe_delete_file(path):",
"def download_settings_files(self): progress(\"Downloading settings files to root directory\") # Create",
"\"appleseed\", \"_appleseedpython3.so\")) all_libs = all_libs.union(appleseedpython_libs) # Get shared libs needed",
"The above copyright notice and this permission notice shall be",
"of user-specified search paths. candidate = os.path.join(loader_path, lib) if not",
"Path to appleseed.python: \" + self.appleseed_python_path) print(\" Path to maketx:",
"__is_system_lib(self, lib): for prefix in self.SYSTEM_LIBS_PREFIXES: if lib.startswith(prefix): return True",
"unlink it. os.chmod(path, stat.S_IWRITE) os.unlink(path) def safe_delete_directory(path): Attempts = 10",
"Copyright (c) 2017-2018 <NAME>, The appleseedhq Organization # # Permission",
"appleseed libraries: \" + self.appleseed_lib_path) print(\" Path to appleseed shaders:",
"command line: {0}\".format(cmdline)) os.system(cmdline) def run_subprocess(self, cmdline): p = subprocess.Popen(cmdline,",
"out.split(\"\\n\")[1:]: # skip the first line line = line.strip() #",
"\"blenderseed\"), shaders_dir) def __do_copy_shaders(self, source_dir, target_dir): for root, dirs, files",
"tree = ElementTree() try: tree.parse(SETTINGS_FILENAME) except IOError: fatal(\"Failed to load",
"final zip file from staging directory\") package_name = \"blenderseed-{0}-{1}-{2}\".format(self.package_version, self.settings.platform,",
"os.chdir(path) return old_path def copy_glob(input_pattern, output_path): for input_file in glob.glob(input_pattern):",
"destination directory. lib_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\") safe_make_directory(lib_dir) # Copy",
"OR OTHER DEALINGS IN # THE SOFTWARE. # from __future__",
"is part of appleseed. # Visit https://appleseedhq.net/ for additional information",
"+ lib) appleseed_python_dir = os.path.join(self.settings.root_dir, \"appleseed\", \"lib\", \"appleseed\") for py_cpp_module",
"copy_glob(input_pattern, output_path): for input_file in glob.glob(input_pattern): shutil.copy(input_file, output_path) #-------------------------------------------------------------------------------------------------- #",
"in libs: if os.path.isfile(lib): trace(u\" {0} {1}\".format(GREEN_CHECKMARK, lib)) else: trace(u\"",
"self.maketx_path = os.path.expandvars(self.__get_required(tree, \"maketx_path\")) self.output_dir = os.path.expandvars(self.__get_required(tree, \"output_dir\")) def __get_required(self,",
"__fixup_binaries(self): progress(\"Mac-specific: Fixing up binaries\") self.set_libraries_ids() self.__change_library_paths_in_libraries() self.__change_library_paths_in_executables() def set_libraries_ids(self):"
] |
[
"<filename>uts/uts_17_aut_py/2/A.py ser = int(input()) mas = list(map(int, input().split())) mas.sort() print(*mas)"
] |
[
"gettext('Equation'), }, js=[ 'wagtailkatex/katex/katex.min.js', 'wagtailkatex/wagtailkatex.js', ], css={ 'all': [ 'wagtailkatex/katex/katex.min.css',",
"= \\\\pm\\\\sqrt{a^2 + b^2}\">` tag. \"\"\" feature_name = 'katex-embed' type_",
"'icon': 'square-root-alt', 'description': gettext('Equation'), }, js=[ 'wagtailkatex/katex/katex.min.js', 'wagtailkatex/wagtailkatex.js', ], css={",
"[ 'wagtailkatex/katex/katex.min.css', ] } ) ) features.register_converter_rule('contentstate', feature_name, { 'from_database_format':",
"is stored as HTML with a `<div data-katex-embed=\"c = \\\\pm\\\\sqrt{a^2",
"hooks from .richtext import KaTeXEntityElementHandler, katex_entity_decorator @hooks.register('register_rich_text_features') def register_katex_features(features): features.default_features.append('katex')",
"'KATEX-EMBED' features.register_editor_plugin( 'draftail', feature_name, draftail_features.EntityFeature( { 'type': type_, 'icon': 'square-root-alt',",
"tag. \"\"\" feature_name = 'katex-embed' type_ = 'KATEX-EMBED' features.register_editor_plugin( 'draftail',",
"as HTML with a `<div data-katex-embed=\"c = \\\\pm\\\\sqrt{a^2 + b^2}\">`",
"django.utils.translation import gettext from wagtail.admin.rich_text.editors.draftail import features as draftail_features from",
"wagtail.core import hooks from .richtext import KaTeXEntityElementHandler, katex_entity_decorator @hooks.register('register_rich_text_features') def",
"features.register_editor_plugin( 'draftail', feature_name, draftail_features.EntityFeature( { 'type': type_, 'icon': 'square-root-alt', 'description':",
"from django.utils.translation import gettext from wagtail.admin.rich_text.editors.draftail import features as draftail_features",
".richtext import KaTeXEntityElementHandler, katex_entity_decorator @hooks.register('register_rich_text_features') def register_katex_features(features): features.default_features.append('katex') \"\"\" Registering",
"type_ = 'KATEX-EMBED' features.register_editor_plugin( 'draftail', feature_name, draftail_features.EntityFeature( { 'type': type_,",
"from .richtext import KaTeXEntityElementHandler, katex_entity_decorator @hooks.register('register_rich_text_features') def register_katex_features(features): features.default_features.append('katex') \"\"\"",
"a `<div data-katex-embed=\"c = \\\\pm\\\\sqrt{a^2 + b^2}\">` tag. \"\"\" feature_name",
"stored as HTML with a `<div data-katex-embed=\"c = \\\\pm\\\\sqrt{a^2 +",
"import KaTeXEntityElementHandler, katex_entity_decorator @hooks.register('register_rich_text_features') def register_katex_features(features): features.default_features.append('katex') \"\"\" Registering the",
"'wagtailkatex/katex/katex.min.js', 'wagtailkatex/wagtailkatex.js', ], css={ 'all': [ 'wagtailkatex/katex/katex.min.css', ] } )",
"`katex` feature, which uses the `KATEX` Draft.js entity type, and",
"\\\\pm\\\\sqrt{a^2 + b^2}\">` tag. \"\"\" feature_name = 'katex-embed' type_ =",
"and is stored as HTML with a `<div data-katex-embed=\"c =",
"} ) ) features.register_converter_rule('contentstate', feature_name, { 'from_database_format': {'div[data-katex-embed]': KaTeXEntityElementHandler()}, 'to_database_format':",
"'draftail', feature_name, draftail_features.EntityFeature( { 'type': type_, 'icon': 'square-root-alt', 'description': gettext('Equation'),",
"b^2}\">` tag. \"\"\" feature_name = 'katex-embed' type_ = 'KATEX-EMBED' features.register_editor_plugin(",
"from wagtail.core import hooks from .richtext import KaTeXEntityElementHandler, katex_entity_decorator @hooks.register('register_rich_text_features')",
"] } ) ) features.register_converter_rule('contentstate', feature_name, { 'from_database_format': {'div[data-katex-embed]': KaTeXEntityElementHandler()},",
"draftail_features from wagtail.core import hooks from .richtext import KaTeXEntityElementHandler, katex_entity_decorator",
"'katex-embed' type_ = 'KATEX-EMBED' features.register_editor_plugin( 'draftail', feature_name, draftail_features.EntityFeature( { 'type':",
"type, and is stored as HTML with a `<div data-katex-embed=\"c",
"as draftail_features from wagtail.core import hooks from .richtext import KaTeXEntityElementHandler,",
"Registering the `katex` feature, which uses the `KATEX` Draft.js entity",
"\"\"\" Registering the `katex` feature, which uses the `KATEX` Draft.js",
"+ b^2}\">` tag. \"\"\" feature_name = 'katex-embed' type_ = 'KATEX-EMBED'",
"register_katex_features(features): features.default_features.append('katex') \"\"\" Registering the `katex` feature, which uses the",
"css={ 'all': [ 'wagtailkatex/katex/katex.min.css', ] } ) ) features.register_converter_rule('contentstate', feature_name,",
"HTML with a `<div data-katex-embed=\"c = \\\\pm\\\\sqrt{a^2 + b^2}\">` tag.",
"wagtail.admin.rich_text.editors.draftail import features as draftail_features from wagtail.core import hooks from",
"feature_name = 'katex-embed' type_ = 'KATEX-EMBED' features.register_editor_plugin( 'draftail', feature_name, draftail_features.EntityFeature(",
"import features as draftail_features from wagtail.core import hooks from .richtext",
"def register_katex_features(features): features.default_features.append('katex') \"\"\" Registering the `katex` feature, which uses",
"features.default_features.append('katex') \"\"\" Registering the `katex` feature, which uses the `KATEX`",
") ) features.register_converter_rule('contentstate', feature_name, { 'from_database_format': {'div[data-katex-embed]': KaTeXEntityElementHandler()}, 'to_database_format': {'entity_decorators':",
"which uses the `KATEX` Draft.js entity type, and is stored",
"'wagtailkatex/wagtailkatex.js', ], css={ 'all': [ 'wagtailkatex/katex/katex.min.css', ] } ) )",
"feature_name, draftail_features.EntityFeature( { 'type': type_, 'icon': 'square-root-alt', 'description': gettext('Equation'), },",
"'type': type_, 'icon': 'square-root-alt', 'description': gettext('Equation'), }, js=[ 'wagtailkatex/katex/katex.min.js', 'wagtailkatex/wagtailkatex.js',",
"the `KATEX` Draft.js entity type, and is stored as HTML",
"draftail_features.EntityFeature( { 'type': type_, 'icon': 'square-root-alt', 'description': gettext('Equation'), }, js=[",
"features.register_converter_rule('contentstate', feature_name, { 'from_database_format': {'div[data-katex-embed]': KaTeXEntityElementHandler()}, 'to_database_format': {'entity_decorators': {type_: katex_entity_decorator}},",
"= 'KATEX-EMBED' features.register_editor_plugin( 'draftail', feature_name, draftail_features.EntityFeature( { 'type': type_, 'icon':",
"feature, which uses the `KATEX` Draft.js entity type, and is",
"], css={ 'all': [ 'wagtailkatex/katex/katex.min.css', ] } ) ) features.register_converter_rule('contentstate',",
") features.register_converter_rule('contentstate', feature_name, { 'from_database_format': {'div[data-katex-embed]': KaTeXEntityElementHandler()}, 'to_database_format': {'entity_decorators': {type_:",
"feature_name, { 'from_database_format': {'div[data-katex-embed]': KaTeXEntityElementHandler()}, 'to_database_format': {'entity_decorators': {type_: katex_entity_decorator}}, })",
"uses the `KATEX` Draft.js entity type, and is stored as",
"data-katex-embed=\"c = \\\\pm\\\\sqrt{a^2 + b^2}\">` tag. \"\"\" feature_name = 'katex-embed'",
"'wagtailkatex/katex/katex.min.css', ] } ) ) features.register_converter_rule('contentstate', feature_name, { 'from_database_format': {'div[data-katex-embed]':",
"KaTeXEntityElementHandler, katex_entity_decorator @hooks.register('register_rich_text_features') def register_katex_features(features): features.default_features.append('katex') \"\"\" Registering the `katex`",
"'square-root-alt', 'description': gettext('Equation'), }, js=[ 'wagtailkatex/katex/katex.min.js', 'wagtailkatex/wagtailkatex.js', ], css={ 'all':",
"Draft.js entity type, and is stored as HTML with a",
"'description': gettext('Equation'), }, js=[ 'wagtailkatex/katex/katex.min.js', 'wagtailkatex/wagtailkatex.js', ], css={ 'all': [",
"katex_entity_decorator @hooks.register('register_rich_text_features') def register_katex_features(features): features.default_features.append('katex') \"\"\" Registering the `katex` feature,",
"}, js=[ 'wagtailkatex/katex/katex.min.js', 'wagtailkatex/wagtailkatex.js', ], css={ 'all': [ 'wagtailkatex/katex/katex.min.css', ]",
"`<div data-katex-embed=\"c = \\\\pm\\\\sqrt{a^2 + b^2}\">` tag. \"\"\" feature_name =",
"@hooks.register('register_rich_text_features') def register_katex_features(features): features.default_features.append('katex') \"\"\" Registering the `katex` feature, which",
"features as draftail_features from wagtail.core import hooks from .richtext import",
"with a `<div data-katex-embed=\"c = \\\\pm\\\\sqrt{a^2 + b^2}\">` tag. \"\"\"",
"entity type, and is stored as HTML with a `<div",
"import gettext from wagtail.admin.rich_text.editors.draftail import features as draftail_features from wagtail.core",
"`KATEX` Draft.js entity type, and is stored as HTML with",
"import hooks from .richtext import KaTeXEntityElementHandler, katex_entity_decorator @hooks.register('register_rich_text_features') def register_katex_features(features):",
"gettext from wagtail.admin.rich_text.editors.draftail import features as draftail_features from wagtail.core import",
"type_, 'icon': 'square-root-alt', 'description': gettext('Equation'), }, js=[ 'wagtailkatex/katex/katex.min.js', 'wagtailkatex/wagtailkatex.js', ],",
"js=[ 'wagtailkatex/katex/katex.min.js', 'wagtailkatex/wagtailkatex.js', ], css={ 'all': [ 'wagtailkatex/katex/katex.min.css', ] }",
"'all': [ 'wagtailkatex/katex/katex.min.css', ] } ) ) features.register_converter_rule('contentstate', feature_name, {",
"from wagtail.admin.rich_text.editors.draftail import features as draftail_features from wagtail.core import hooks",
"{ 'type': type_, 'icon': 'square-root-alt', 'description': gettext('Equation'), }, js=[ 'wagtailkatex/katex/katex.min.js',",
"\"\"\" feature_name = 'katex-embed' type_ = 'KATEX-EMBED' features.register_editor_plugin( 'draftail', feature_name,",
"the `katex` feature, which uses the `KATEX` Draft.js entity type,",
"= 'katex-embed' type_ = 'KATEX-EMBED' features.register_editor_plugin( 'draftail', feature_name, draftail_features.EntityFeature( {"
] |
[
"topicPartitionSchemas: Dict[int, Schema] = { 0: [(\"topic\", stringSerializer), (\"partition_id\", ArraySerializer(int32Serializer))]",
"protocol_generator/templates instead # ############################################################### from typing import Dict from ...structs.api.elect_preferred_leaders_request",
"electPreferredLeadersRequestDataSchemas: Dict[int, Schema] = { 0: [(\"topic_partitions\", ArraySerializer(topicPartitionSerializers[0])), (\"timeout_ms\", int32Serializer)]",
"from ._main_serializers import ArraySerializer, ClassSerializer, Schema, int32Serializer, stringSerializer topicPartitionSchemas: Dict[int,",
"for version, schema in topicPartitionSchemas.items() } topicPartitionSerializers[-1] = topicPartitionSerializers[0] electPreferredLeadersRequestDataSchemas:",
"ArraySerializer, ClassSerializer, Schema, int32Serializer, stringSerializer topicPartitionSchemas: Dict[int, Schema] = {",
"TopicPartition from ._main_serializers import ArraySerializer, ClassSerializer, Schema, int32Serializer, stringSerializer topicPartitionSchemas:",
"= { 0: [(\"topic_partitions\", ArraySerializer(topicPartitionSerializers[0])), (\"timeout_ms\", int32Serializer)] } electPreferredLeadersRequestDataSerializers: Dict[int,",
"schema) for version, schema in electPreferredLeadersRequestDataSchemas.items() } electPreferredLeadersRequestDataSerializers[-1] = electPreferredLeadersRequestDataSerializers[0]",
"stringSerializer), (\"partition_id\", ArraySerializer(int32Serializer))] } topicPartitionSerializers: Dict[int, ClassSerializer[TopicPartition]] = { version:",
"# Autogenerated module. Please don't modify. # # Edit according",
"from ...structs.api.elect_preferred_leaders_request import ElectPreferredLeadersRequestData, TopicPartition from ._main_serializers import ArraySerializer, ClassSerializer,",
"= topicPartitionSerializers[0] electPreferredLeadersRequestDataSchemas: Dict[int, Schema] = { 0: [(\"topic_partitions\", ArraySerializer(topicPartitionSerializers[0])),",
"from typing import Dict from ...structs.api.elect_preferred_leaders_request import ElectPreferredLeadersRequestData, TopicPartition from",
"(\"partition_id\", ArraySerializer(int32Serializer))] } topicPartitionSerializers: Dict[int, ClassSerializer[TopicPartition]] = { version: ClassSerializer(TopicPartition,",
"topicPartitionSerializers: Dict[int, ClassSerializer[TopicPartition]] = { version: ClassSerializer(TopicPartition, schema) for version,",
"version: ClassSerializer(ElectPreferredLeadersRequestData, schema) for version, schema in electPreferredLeadersRequestDataSchemas.items() } electPreferredLeadersRequestDataSerializers[-1]",
"0: [(\"topic_partitions\", ArraySerializer(topicPartitionSerializers[0])), (\"timeout_ms\", int32Serializer)] } electPreferredLeadersRequestDataSerializers: Dict[int, ClassSerializer[ElectPreferredLeadersRequestData]] =",
"modify. # # Edit according file in protocol_generator/templates instead #",
"# Edit according file in protocol_generator/templates instead # ############################################################### from",
"Dict[int, Schema] = { 0: [(\"topic\", stringSerializer), (\"partition_id\", ArraySerializer(int32Serializer))] }",
"ClassSerializer[TopicPartition]] = { version: ClassSerializer(TopicPartition, schema) for version, schema in",
"Dict[int, ClassSerializer[ElectPreferredLeadersRequestData]] = { version: ClassSerializer(ElectPreferredLeadersRequestData, schema) for version, schema",
"ClassSerializer(TopicPartition, schema) for version, schema in topicPartitionSchemas.items() } topicPartitionSerializers[-1] =",
"{ version: ClassSerializer(ElectPreferredLeadersRequestData, schema) for version, schema in electPreferredLeadersRequestDataSchemas.items() }",
"# # Edit according file in protocol_generator/templates instead # ###############################################################",
"Dict[int, Schema] = { 0: [(\"topic_partitions\", ArraySerializer(topicPartitionSerializers[0])), (\"timeout_ms\", int32Serializer)] }",
"{ 0: [(\"topic\", stringSerializer), (\"partition_id\", ArraySerializer(int32Serializer))] } topicPartitionSerializers: Dict[int, ClassSerializer[TopicPartition]]",
"} topicPartitionSerializers: Dict[int, ClassSerializer[TopicPartition]] = { version: ClassSerializer(TopicPartition, schema) for",
"._main_serializers import ArraySerializer, ClassSerializer, Schema, int32Serializer, stringSerializer topicPartitionSchemas: Dict[int, Schema]",
"ArraySerializer(topicPartitionSerializers[0])), (\"timeout_ms\", int32Serializer)] } electPreferredLeadersRequestDataSerializers: Dict[int, ClassSerializer[ElectPreferredLeadersRequestData]] = { version:",
"topicPartitionSchemas.items() } topicPartitionSerializers[-1] = topicPartitionSerializers[0] electPreferredLeadersRequestDataSchemas: Dict[int, Schema] = {",
"Please don't modify. # # Edit according file in protocol_generator/templates",
"{ 0: [(\"topic_partitions\", ArraySerializer(topicPartitionSerializers[0])), (\"timeout_ms\", int32Serializer)] } electPreferredLeadersRequestDataSerializers: Dict[int, ClassSerializer[ElectPreferredLeadersRequestData]]",
"version, schema in topicPartitionSchemas.items() } topicPartitionSerializers[-1] = topicPartitionSerializers[0] electPreferredLeadersRequestDataSchemas: Dict[int,",
"ClassSerializer, Schema, int32Serializer, stringSerializer topicPartitionSchemas: Dict[int, Schema] = { 0:",
"# ############################################################### from typing import Dict from ...structs.api.elect_preferred_leaders_request import ElectPreferredLeadersRequestData,",
"Edit according file in protocol_generator/templates instead # ############################################################### from typing",
"ClassSerializer(ElectPreferredLeadersRequestData, schema) for version, schema in electPreferredLeadersRequestDataSchemas.items() } electPreferredLeadersRequestDataSerializers[-1] =",
"[(\"topic\", stringSerializer), (\"partition_id\", ArraySerializer(int32Serializer))] } topicPartitionSerializers: Dict[int, ClassSerializer[TopicPartition]] = {",
"Autogenerated module. Please don't modify. # # Edit according file",
"typing import Dict from ...structs.api.elect_preferred_leaders_request import ElectPreferredLeadersRequestData, TopicPartition from ._main_serializers",
"= { version: ClassSerializer(TopicPartition, schema) for version, schema in topicPartitionSchemas.items()",
"ArraySerializer(int32Serializer))] } topicPartitionSerializers: Dict[int, ClassSerializer[TopicPartition]] = { version: ClassSerializer(TopicPartition, schema)",
"int32Serializer)] } electPreferredLeadersRequestDataSerializers: Dict[int, ClassSerializer[ElectPreferredLeadersRequestData]] = { version: ClassSerializer(ElectPreferredLeadersRequestData, schema)",
"topicPartitionSerializers[-1] = topicPartitionSerializers[0] electPreferredLeadersRequestDataSchemas: Dict[int, Schema] = { 0: [(\"topic_partitions\",",
"Dict from ...structs.api.elect_preferred_leaders_request import ElectPreferredLeadersRequestData, TopicPartition from ._main_serializers import ArraySerializer,",
"ElectPreferredLeadersRequestData, TopicPartition from ._main_serializers import ArraySerializer, ClassSerializer, Schema, int32Serializer, stringSerializer",
"topicPartitionSerializers[0] electPreferredLeadersRequestDataSchemas: Dict[int, Schema] = { 0: [(\"topic_partitions\", ArraySerializer(topicPartitionSerializers[0])), (\"timeout_ms\",",
"stringSerializer topicPartitionSchemas: Dict[int, Schema] = { 0: [(\"topic\", stringSerializer), (\"partition_id\",",
"= { 0: [(\"topic\", stringSerializer), (\"partition_id\", ArraySerializer(int32Serializer))] } topicPartitionSerializers: Dict[int,",
"in protocol_generator/templates instead # ############################################################### from typing import Dict from",
"electPreferredLeadersRequestDataSerializers: Dict[int, ClassSerializer[ElectPreferredLeadersRequestData]] = { version: ClassSerializer(ElectPreferredLeadersRequestData, schema) for version,",
"according file in protocol_generator/templates instead # ############################################################### from typing import",
"version: ClassSerializer(TopicPartition, schema) for version, schema in topicPartitionSchemas.items() } topicPartitionSerializers[-1]",
"[(\"topic_partitions\", ArraySerializer(topicPartitionSerializers[0])), (\"timeout_ms\", int32Serializer)] } electPreferredLeadersRequestDataSerializers: Dict[int, ClassSerializer[ElectPreferredLeadersRequestData]] = {",
"############################################################### # Autogenerated module. Please don't modify. # # Edit",
"...structs.api.elect_preferred_leaders_request import ElectPreferredLeadersRequestData, TopicPartition from ._main_serializers import ArraySerializer, ClassSerializer, Schema,",
"Schema] = { 0: [(\"topic\", stringSerializer), (\"partition_id\", ArraySerializer(int32Serializer))] } topicPartitionSerializers:",
"Schema, int32Serializer, stringSerializer topicPartitionSchemas: Dict[int, Schema] = { 0: [(\"topic\",",
"int32Serializer, stringSerializer topicPartitionSchemas: Dict[int, Schema] = { 0: [(\"topic\", stringSerializer),",
"module. Please don't modify. # # Edit according file in",
"import ArraySerializer, ClassSerializer, Schema, int32Serializer, stringSerializer topicPartitionSchemas: Dict[int, Schema] =",
"} electPreferredLeadersRequestDataSerializers: Dict[int, ClassSerializer[ElectPreferredLeadersRequestData]] = { version: ClassSerializer(ElectPreferredLeadersRequestData, schema) for",
"schema in topicPartitionSchemas.items() } topicPartitionSerializers[-1] = topicPartitionSerializers[0] electPreferredLeadersRequestDataSchemas: Dict[int, Schema]",
"don't modify. # # Edit according file in protocol_generator/templates instead",
"0: [(\"topic\", stringSerializer), (\"partition_id\", ArraySerializer(int32Serializer))] } topicPartitionSerializers: Dict[int, ClassSerializer[TopicPartition]] =",
"############################################################### from typing import Dict from ...structs.api.elect_preferred_leaders_request import ElectPreferredLeadersRequestData, TopicPartition",
"= { version: ClassSerializer(ElectPreferredLeadersRequestData, schema) for version, schema in electPreferredLeadersRequestDataSchemas.items()",
"file in protocol_generator/templates instead # ############################################################### from typing import Dict",
"schema) for version, schema in topicPartitionSchemas.items() } topicPartitionSerializers[-1] = topicPartitionSerializers[0]",
"} topicPartitionSerializers[-1] = topicPartitionSerializers[0] electPreferredLeadersRequestDataSchemas: Dict[int, Schema] = { 0:",
"(\"timeout_ms\", int32Serializer)] } electPreferredLeadersRequestDataSerializers: Dict[int, ClassSerializer[ElectPreferredLeadersRequestData]] = { version: ClassSerializer(ElectPreferredLeadersRequestData,",
"import ElectPreferredLeadersRequestData, TopicPartition from ._main_serializers import ArraySerializer, ClassSerializer, Schema, int32Serializer,",
"Schema] = { 0: [(\"topic_partitions\", ArraySerializer(topicPartitionSerializers[0])), (\"timeout_ms\", int32Serializer)] } electPreferredLeadersRequestDataSerializers:",
"import Dict from ...structs.api.elect_preferred_leaders_request import ElectPreferredLeadersRequestData, TopicPartition from ._main_serializers import",
"Dict[int, ClassSerializer[TopicPartition]] = { version: ClassSerializer(TopicPartition, schema) for version, schema",
"in topicPartitionSchemas.items() } topicPartitionSerializers[-1] = topicPartitionSerializers[0] electPreferredLeadersRequestDataSchemas: Dict[int, Schema] =",
"ClassSerializer[ElectPreferredLeadersRequestData]] = { version: ClassSerializer(ElectPreferredLeadersRequestData, schema) for version, schema in",
"{ version: ClassSerializer(TopicPartition, schema) for version, schema in topicPartitionSchemas.items() }",
"instead # ############################################################### from typing import Dict from ...structs.api.elect_preferred_leaders_request import"
] |
[
"SKU: %s \", nodesku) log.info_1(\" Graph Name: Graph.PowerOn.Node\") # Ensure",
"Address']) log.info_1(\" Node BMC IP Addr Src: %s\", catalog.get('data')['IP Address",
"import fit_path # NOQA: unused import from nose.plugins.attrib import attr",
"- Windows 2012 activation key in the installation payload file.",
"\" + str(end_time - start_time)) try: res = json.loads(result['text']) findall(res,",
"obj: findall(item, key) else: pass # this routine polls a",
"start_time < waittime: # limit test to waittime seconds result",
"mount. - Windows 2012 activation key in the installation payload",
"OS bootstrap workflows. The default case is running a minimum",
"payload file and specifiying it using the '-extra' argument. This",
"fit_path # NOQA: unused import from nose.plugins.attrib import attr import",
"+ json.dumps(res, indent=4, separators=(',', ':'))) return False # ------------------------ Tests",
"%s\", v) findall(v, key) elif isinstance(obj, list): for item in",
"separators=(',', ':'))) return False # ------------------------ Tests ------------------------------------- @attr(all=False) class",
"\"vagrant\", \"smbPassword\": \"<PASSWORD>\"}}} # if an external payload file is",
"= fit_common.rackhdapi(nodeinfo.get('sku'))['json']['name'] log.info_1(\" Node ID: \" + self.__class__.__NODE) log.info_1(\" Node",
"file. ''' import fit_path # NOQA: unused import from nose.plugins.attrib",
"import time from nosedep import depends from datetime import datetime",
"action=\"get\") catalog = mondata['json'] bmcresult = mondata['status'] if bmcresult !=",
"BMC IP Addr Src: %s\", catalog.get('data')['IP Address Source']) # delete",
"result['status'] == 201: # workflow running log.info_1(\" InstanceID: \" +",
"True else: end_time = time.time() log.info_1(\" Workflow failed at time:",
"nodeinfo = fit_common.rackhdapi('/api/2.0/nodes/' + self.__class__.__NODE)['json'] nodesku = fit_common.rackhdapi(nodeinfo.get('sku'))['json']['name'] log.info_1(\" Node",
"no nodes currently discovered\" # Select one node at random",
"if bmcresult != 200: log.info_1(\" Node ID: \" + cls.__NODE)",
"\"smbUser\": \"vagrant\", \"smbPassword\": \"<PASSWORD>\"}}} } Example command line using external",
"case is running a minimum payload Windows OS install. Other",
"= result['text'] log.error(\" Workflow failed: status: %s\", result['json']['status']) log.error(\" Data:",
"response code log.error(\" InstanceID: \" + result['text']) self.fail(\"Workflow failed with",
"on and reachable result = fit_common.rackhdapi('/api/2.0/nodes/' + self.__class__.__NODE + '/workflows',",
"result['json']['status'])) fit_common.time.sleep(cycle) elif result['json']['status'] == 'succeeded': log.info_1(\"{} workflow status: {}\".format(result['json']['injectableName'],",
"as documented here: http://rackhd.readthedocs.io/en/latest/rackhd/install_os.html?highlight=os%20install - Windows 2012 installation distro installed",
"of the RackHD API 2.0 OS bootstrap workflows. The default",
"= time.time() log.info_1(\" Workflow completed at time: \" + str(datetime.fromtimestamp(end_time)))",
"see logs.\") self.assertTrue(wait_for_workflow_complete(result['json']['instanceId'], time.time(), 50, 5), \"Node Power on workflow",
"Id, node BMC mac ,node type nodeinfo = fit_common.rackhdapi('/api/2.0/nodes/' +",
"using the '-extra' argument. This test takes 30-45 minutes to",
"+ \"/catalogs/bmc\" mondata = fit_common.rackhdapi(monurl, action=\"get\") catalog = mondata['json'] bmcresult",
"\"vagrant\", \"smbPassword\": \"<PASSWORD>\"}}} } Example command line using external payload",
"it using the '-extra' argument. This test takes 30-45 minutes",
"v) findall(v, key) elif isinstance(obj, list): for item in obj:",
"Inc. or its subsidiaries. All Rights Reserved. This script tests",
"to waittime seconds result = fit_common.rackhdapi(\"/api/2.0/workflows/\" + instanceid) if result['status']",
"json import time from nosedep import depends from datetime import",
"\" + result['text']) return False if result['json']['status'] in ['running', 'pending']:",
"workflowid = None result = fit_common.rackhdapi('/api/2.0/nodes/' + self.__class__.__NODE + '/workflows',",
"import from nose.plugins.attrib import attr import fit_common import flogging import",
"monurl = \"/api/2.0/nodes/\" + cls.__NODE + \"/catalogs/bmc\" mondata = fit_common.rackhdapi(monurl,",
"# if an external payload file is specified, use that",
"workflow failed with response code log.error(\" InstanceID: \" + result['text'])",
"Name: Graph.PowerOn.Node\") # Ensure the compute node is powered on",
"configuration dir): {\"bootstrap-payload\": {\"name\": \"Graph.InstallWindowsServer\", \"options\": {\"defaults\": {\"version\": \"2012\", \"repo\":",
"':'))) return False try: res = json.loads(result['text']) except: res =",
"install. Other Windows-type OS install cases can be specified by",
"# Select one node at random cls.__NODE = NODECATALOG[random.randint(0, len(NODECATALOG)",
"str(datetime.fromtimestamp(end_time))) log.info_1(\" Workflow duration: \" + str(end_time - start_time)) try:",
"on RackHD server as documented here: https://github.com/RackHD/on-tools/tree/master/winpe - Samba installed",
"or equivalent NFS mount. - Windows 2012 activation key in",
"key in the installation payload file. ''' import fit_path #",
"active workflows for specified node result = fit_common.cancel_active_workflows(cls.__NODE) assert (result",
"fit_common.rackhdapi(nodeinfo.get('sku'))['json']['name'] log.info_1(\" Node ID: \" + self.__class__.__NODE) log.info_1(\" Node SKU:",
"list of nodes NODECATALOG = fit_common.node_select() assert (len(NODECATALOG) != 0),",
"This test takes 30-45 minutes to run. Example payload file",
"log.info_1(\" Node SKU: \" + nodesku) log.info_1(\" Graph Name: Graph.InstallWindowsServer\")",
"except: res = result['text'] log.error(\" Workflow Timeout: \" + json.dumps(res,",
"if result['status'] != 200: log.error(\" HTTP error: \" + result['text'])",
"= fit_common.rackhdapi(monurl, action=\"get\") catalog = mondata['json'] bmcresult = mondata['status'] if",
"value of a field from the workflow response def findall(obj,",
"is running a minimum payload Windows OS install. Other Windows-type",
"ID: \" + cls.__NODE) log.info_1(\" Error on catalog/bmc command\") else:",
"workflow status: {}\".format(result['json']['injectableName'], result['json']['status'])) end_time = time.time() log.info_1(\" Workflow completed",
"- start_time)) try: res = json.loads(result['text']) findall(res, \"error\") except: res",
"on the RackHD server and configured as documented here: http://rackhd.readthedocs.io/en/latest/rackhd/install_os.html?highlight=os%20install",
"@attr(all=False) class api20_bootstrap_windows(fit_common.unittest.TestCase): @classmethod def setUpClass(cls): # Get the list",
"workflow task ID for completion def wait_for_workflow_complete(instanceid, start_time, waittime=3200, cycle=30):",
"and reachable result = fit_common.rackhdapi('/api/2.0/nodes/' + self.__class__.__NODE + '/workflows', action='post',",
"workflow workflowid = None result = fit_common.rackhdapi('/api/2.0/nodes/' + self.__class__.__NODE +",
"IP Addr: %s\", catalog.get('data')['IP Address']) log.info_1(\" Node BMC IP Addr",
"!= 200: log.error(\" HTTP error: \" + result['text']) return False",
"IP Addr Src: %s\", catalog.get('data')['IP Address Source']) # delete active",
"node at random cls.__NODE = NODECATALOG[random.randint(0, len(NODECATALOG) - 1)] #",
"res = result['text'] log.error(\" Workflow failed: status: %s\", result['json']['status']) log.error(\"",
"cycle=30): log.info_1(\" Workflow started at time: \" + str(datetime.fromtimestamp(start_time))) while",
"SKU: \" + nodesku) log.info_1(\" Graph Name: Graph.InstallWindowsServer\") log.info_1(\" Payload:",
"the compute node is powered on and reachable result =",
"minutes to run. Example payload file (installed in configuration dir):",
"+ self.__class__.__NODE + '/workflows', action='post', payload={\"name\": \"Graph.PowerOn.Node\"}) self.assertEqual(result['status'], 201, \"Node",
"\"error\") except: res = result['text'] log.error(\" Workflow failed: status: %s\",",
"= mondata['json'] bmcresult = mondata['status'] if bmcresult != 200: log.info_1(\"",
"# delete active workflows for specified node result = fit_common.cancel_active_workflows(cls.__NODE)",
"API failed, see logs.\") self.assertTrue(wait_for_workflow_complete(result['json']['instanceId'], time.time(), 50, 5), \"Node Power",
"str(datetime.fromtimestamp(end_time))) log.info_1(\" Workflow duration: \" + str(end_time - start_time)) return",
"False # ------------------------ Tests ------------------------------------- @attr(all=False) class api20_bootstrap_windows(fit_common.unittest.TestCase): @classmethod def",
"# limit test to waittime seconds result = fit_common.rackhdapi(\"/api/2.0/workflows/\" +",
"= flogging.get_loggers() # sample default base payload PAYLOAD = {\"name\":",
"except: res = result['text'] log.error(\" Workflow failed: status: %s\", result['json']['status'])",
"cls.__NODE + \"/catalogs/bmc\" mondata = fit_common.rackhdapi(monurl, action=\"get\") catalog = mondata['json']",
"workflow status: {}\".format(result['json']['injectableName'], result['json']['status'])) fit_common.time.sleep(cycle) elif result['json']['status'] == 'succeeded': log.info_1(\"{}",
"config = fit_common.fitcfg().get('bootstrap-payload', None) if config: PAYLOAD = config #",
"NFS mount. - Windows 2012 activation key in the installation",
"indent=4, separators=(',', ':'))) return False # ------------------------ Tests ------------------------------------- @attr(all=False)",
"as documented here: https://github.com/RackHD/on-tools/tree/master/winpe - Samba installed on the RackHD",
"(len(NODECATALOG) != 0), \"There are no nodes currently discovered\" #",
"self.__class__.__NODE + '/workflows', action='post', payload={\"name\": \"Graph.PowerOn.Node\"}) self.assertEqual(result['status'], 201, \"Node Power",
"log.info_1(\" Workflow started at time: \" + str(datetime.fromtimestamp(start_time))) while time.time()",
"return the value of a field from the workflow response",
"mac ,node type nodeinfo = fit_common.rackhdapi('/api/2.0/nodes/' + cls.__NODE)['json'] nodesku =",
"fit_common.rackhdapi(nodeinfo.get('sku'))['json']['name'] monurl = \"/api/2.0/nodes/\" + cls.__NODE + \"/catalogs/bmc\" mondata =",
"with response code log.error(\" InstanceID: \" + result['text']) self.fail(\"Workflow failed",
"Windows installation workflow requires special configuration of the RackHD server:",
"start_time, waittime=3200, cycle=30): log.info_1(\" Workflow started at time: \" +",
"fit_common.rackhdapi(monurl, action=\"get\") catalog = mondata['json'] bmcresult = mondata['status'] if bmcresult",
"in the installation payload file. ''' import fit_path # NOQA:",
"if config: PAYLOAD = config # function to return the",
"A customized WinPE environment installed on RackHD server as documented",
"== key: log.error(\" workflow error: %s\", v) findall(v, key) elif",
"Other Windows-type OS install cases can be specified by creating",
"status: {}\".format(result['json']['injectableName'], result['json']['status'])) fit_common.time.sleep(cycle) elif result['json']['status'] == 'succeeded': log.info_1(\"{} workflow",
"\"/api/2.0/nodes/\" + cls.__NODE + \"/catalogs/bmc\" mondata = fit_common.rackhdapi(monurl, action=\"get\") catalog",
"= fit_common.rackhdapi('/api/2.0/nodes/' + cls.__NODE)['json'] nodesku = fit_common.rackhdapi(nodeinfo.get('sku'))['json']['name'] monurl = \"/api/2.0/nodes/\"",
"minimum payload Windows OS install. Other Windows-type OS install cases",
"workflow response def findall(obj, key): if isinstance(obj, dict): for k,",
"# NOQA: unused import from nose.plugins.attrib import attr import fit_common",
"'-extra' argument. This test takes 30-45 minutes to run. Example",
"PAYLOAD = {\"name\": \"Graph.InstallWindowsServer\", \"options\": {\"defaults\": {\"version\": \"2012\", \"repo\": \"http://172.31.128.1:8080/repo/winpe\",",
"some active workflows running against the node\" def test01_node_check(self): #",
"+ '/workflows', action='post', payload=PAYLOAD) if result['status'] == 201: # workflow",
"workflow API failed, see logs.\") self.assertTrue(wait_for_workflow_complete(result['json']['instanceId'], time.time(), 50, 5), \"Node",
"is specified, use that config = fit_common.fitcfg().get('bootstrap-payload', None) if config:",
"30-45 minutes to run. Example payload file (installed in configuration",
"- Windows 2012 installation distro installed on RackHD server or",
"InstanceID: \" + result['text']) self.fail(\"Workflow failed with response code: \"",
"%s \", self.__class__.__NODE) log.info_1(\" Node SKU: %s \", nodesku) log.info_1(\"",
"time from nosedep import depends from datetime import datetime log",
"file (installed in configuration dir): {\"bootstrap-payload\": {\"name\": \"Graph.InstallWindowsServer\", \"options\": {\"defaults\":",
"the list of nodes NODECATALOG = fit_common.node_select() assert (len(NODECATALOG) !=",
"result['json']['instanceId'] else: # workflow failed with response code log.error(\" InstanceID:",
"on workflow failed, see logs.\") @depends(after=test01_node_check) def test02_os_install(self): # Log",
"None) if config: PAYLOAD = config # function to return",
"indent=4, separators=(',', ':'))) return False try: res = json.loads(result['text']) except:",
"\"username\": \"rackhduser\", \"password\": \"<PASSWORD>\", \"smbUser\": \"vagrant\", \"smbPassword\": \"<PASSWORD>\"}}} } Example",
"elif result['json']['status'] == 'succeeded': log.info_1(\"{} workflow status: {}\".format(result['json']['injectableName'], result['json']['status'])) end_time",
"instanceid) if result['status'] != 200: log.error(\" HTTP error: \" +",
"import random import json import time from nosedep import depends",
"end_time = time.time() log.info_1(\" Workflow failed at time: \" +",
"nodesku) log.info_1(\" Graph Name: Graph.InstallWindowsServer\") log.info_1(\" Payload: \" + fit_common.json.dumps(PAYLOAD))",
"in obj.items(): if k == key: log.error(\" workflow error: %s\",",
"return False try: res = json.loads(result['text']) except: res = result['text']",
"logs.\") self.assertTrue(wait_for_workflow_complete(result['json']['instanceId'], time.time(), 50, 5), \"Node Power on workflow failed,",
"\"username\": \"rackhduser\", \"password\": \"<PASSWORD>\", \"smbUser\": \"vagrant\", \"smbPassword\": \"<PASSWORD>\"}}} # if",
"\" + str(end_time - start_time)) return True else: end_time =",
"else: log.info_1(\" Node ID: \" + cls.__NODE) log.info_1(\" Node SKU:",
"log.info_1(\" Node ID: \" + cls.__NODE) log.info_1(\" Error on catalog/bmc",
"res = json.loads(result['text']) except: res = result['text'] log.error(\" Workflow Timeout:",
"= json.loads(result['text']) except: res = result['text'] log.error(\" Workflow Timeout: \"",
"str(datetime.fromtimestamp(start_time))) while time.time() - start_time < waittime: # limit test",
"def test01_node_check(self): # Log node data nodeinfo = fit_common.rackhdapi('/api/2.0/nodes/' +",
"failed, see logs.\") self.assertTrue(wait_for_workflow_complete(result['json']['instanceId'], time.time(), 50, 5), \"Node Power on",
"workflow error: %s\", v) findall(v, key) elif isinstance(obj, list): for",
"bmcresult = mondata['status'] if bmcresult != 200: log.info_1(\" Node ID:",
"nose.plugins.attrib import attr import fit_common import flogging import random import",
"unused import from nose.plugins.attrib import attr import fit_common import flogging",
"\"smbPassword\": \"<PASSWORD>\"}}} } Example command line using external payload file:",
"the value of a field from the workflow response def",
"time.time() log.info_1(\" Workflow failed at time: \" + str(datetime.fromtimestamp(end_time))) log.info_1(\"",
"node\" def test01_node_check(self): # Log node data nodeinfo = fit_common.rackhdapi('/api/2.0/nodes/'",
"running log.info_1(\" InstanceID: \" + result['json']['instanceId']) workflowid = result['json']['instanceId'] else:",
"Name: Graph.InstallWindowsServer\") log.info_1(\" Payload: \" + fit_common.json.dumps(PAYLOAD)) # launch workflow",
"200: log.error(\" HTTP error: \" + result['text']) return False if",
"isinstance(obj, dict): for k, v in obj.items(): if k ==",
"completed at time: \" + str(datetime.fromtimestamp(end_time))) log.info_1(\" Workflow duration: \"",
"workflow requires special configuration of the RackHD server: - A",
"-extra base_windows_2012_install.json RackHD Windows installation workflow requires special configuration of",
"Windows-type OS install cases can be specified by creating a",
"fit_common.fitcfg().get('bootstrap-payload', None) if config: PAYLOAD = config # function to",
"mondata = fit_common.rackhdapi(monurl, action=\"get\") catalog = mondata['json'] bmcresult = mondata['status']",
"+ instanceid) if result['status'] != 200: log.error(\" HTTP error: \"",
"%s \", nodesku) log.info_1(\" Graph Name: Graph.PowerOn.Node\") # Ensure the",
"fit_common.rackhdapi(\"/api/2.0/workflows/\" + instanceid) if result['status'] != 200: log.error(\" HTTP error:",
"of a field from the workflow response def findall(obj, key):",
"nodesku = fit_common.rackhdapi(nodeinfo.get('sku'))['json']['name'] monurl = \"/api/2.0/nodes/\" + cls.__NODE + \"/catalogs/bmc\"",
"test02_os_install(self): # Log node data nodeinfo = fit_common.rackhdapi('/api/2.0/nodes/' + self.__class__.__NODE)['json']",
"= fit_common.fitcfg().get('bootstrap-payload', None) if config: PAYLOAD = config # function",
"return False # ------------------------ Tests ------------------------------------- @attr(all=False) class api20_bootstrap_windows(fit_common.unittest.TestCase): @classmethod",
"# launch workflow workflowid = None result = fit_common.rackhdapi('/api/2.0/nodes/' +",
"time: \" + str(datetime.fromtimestamp(end_time))) log.info_1(\" Workflow duration: \" + str(end_time",
"= fit_common.rackhdapi('/api/2.0/nodes/' + self.__class__.__NODE)['json'] nodesku = fit_common.rackhdapi(nodeinfo.get('sku'))['json']['name'] log.info_1(\" Node ID:",
"dict): for k, v in obj.items(): if k == key:",
"+ self.__class__.__NODE)['json'] nodesku = fit_common.rackhdapi(nodeinfo.get('sku'))['json']['name'] log.info_1(\" Node ID: \" +",
"the installation payload file. ''' import fit_path # NOQA: unused",
"ID: \" + cls.__NODE) log.info_1(\" Node SKU: \" + nodesku)",
"at time: \" + str(datetime.fromtimestamp(start_time))) while time.time() - start_time <",
"still some active workflows running against the node\" def test01_node_check(self):",
"time.time() log.info_1(\" Workflow completed at time: \" + str(datetime.fromtimestamp(end_time))) log.info_1(\"",
"log.error(\" Workflow failed: status: %s\", result['json']['status']) log.error(\" Data: %s\", json.dumps(res,",
"Error on catalog/bmc command\") else: log.info_1(\" Node ID: \" +",
"logs.\") @depends(after=test01_node_check) def test02_os_install(self): # Log node data nodeinfo =",
"catalog.get('data')['IP Address Source']) # delete active workflows for specified node",
"specified, use that config = fit_common.fitcfg().get('bootstrap-payload', None) if config: PAYLOAD",
"fit_common.time.sleep(cycle) elif result['json']['status'] == 'succeeded': log.info_1(\"{} workflow status: {}\".format(result['json']['injectableName'], result['json']['status']))",
"\"rackhduser\", \"password\": \"<PASSWORD>\", \"smbUser\": \"vagrant\", \"smbPassword\": \"<PASSWORD>\"}}} # if an",
"error: \" + result['text']) return False if result['json']['status'] in ['running',",
"code log.error(\" InstanceID: \" + result['text']) self.fail(\"Workflow failed with response",
"InstanceID: \" + result['json']['instanceId']) workflowid = result['json']['instanceId'] else: # workflow",
"log.error(\" Data: %s\", json.dumps(res, indent=4, separators=(',', ':'))) return False try:",
"payload=PAYLOAD) if result['status'] == 201: # workflow running log.info_1(\" InstanceID:",
"%s\", catalog.get('data')['IP Address Source']) # delete active workflows for specified",
"self.assertTrue(wait_for_workflow_complete(workflowid, time.time()), \"OS Install workflow failed, see logs.\") if __name__",
"import json import time from nosedep import depends from datetime",
"Graph Name: Graph.PowerOn.Node\") # Ensure the compute node is powered",
"2017 Dell Inc. or its subsidiaries. All Rights Reserved. This",
"Node BMC IP Addr Src: %s\", catalog.get('data')['IP Address Source']) #",
"duration: \" + str(end_time - start_time)) return True else: end_time",
"the RackHD API 2.0 OS bootstrap workflows. The default case",
"Mac: %s\", catalog.get('data')['MAC Address']) log.info_1(\" Node BMC IP Addr: %s\",",
"\"\\\\\\\\172.31.128.1\\\\windowsServer2012\", \"productkey\": \"<KEY>\", \"username\": \"rackhduser\", \"password\": \"<PASSWORD>\", \"smbUser\": \"vagrant\", \"smbPassword\":",
"status: {}\".format(result['json']['injectableName'], result['json']['status'])) end_time = time.time() log.info_1(\" Workflow completed at",
"\" + cls.__NODE) log.info_1(\" Error on catalog/bmc command\") else: log.info_1(\"",
"routine polls a workflow task ID for completion def wait_for_workflow_complete(instanceid,",
"base payload PAYLOAD = {\"name\": \"Graph.InstallWindowsServer\", \"options\": {\"defaults\": {\"version\": \"2012\",",
"Workflow completed at time: \" + str(datetime.fromtimestamp(end_time))) log.info_1(\" Workflow duration:",
"attr import fit_common import flogging import random import json import",
"'succeeded': log.info_1(\"{} workflow status: {}\".format(result['json']['injectableName'], result['json']['status'])) end_time = time.time() log.info_1(\"",
"workflow failed, see logs.\") @depends(after=test01_node_check) def test02_os_install(self): # Log node",
"{\"version\": \"2012\", \"repo\": \"http://172.31.128.1:8080/repo/winpe\", \"smbRepo\": \"\\\\\\\\172.31.128.1\\\\windowsServer2012\", \"productkey\": \"<KEY>\", \"username\": \"rackhduser\",",
"run. Example payload file (installed in configuration dir): {\"bootstrap-payload\": {\"name\":",
"line using external payload file: python run_tests.py -stack 4 -test",
"file is specified, use that config = fit_common.fitcfg().get('bootstrap-payload', None) if",
"type nodeinfo = fit_common.rackhdapi('/api/2.0/nodes/' + cls.__NODE)['json'] nodesku = fit_common.rackhdapi(nodeinfo.get('sku'))['json']['name'] monurl",
"else: pass # this routine polls a workflow task ID",
"documented here: https://github.com/RackHD/on-tools/tree/master/winpe - Samba installed on the RackHD server",
"at random cls.__NODE = NODECATALOG[random.randint(0, len(NODECATALOG) - 1)] # Print",
"= fit_common.cancel_active_workflows(cls.__NODE) assert (result is True), \"There are still some",
"\"Graph.PowerOn.Node\"}) self.assertEqual(result['status'], 201, \"Node Power on workflow API failed, see",
"running against the node\" def test01_node_check(self): # Log node data",
"can be specified by creating a payload file and specifiying",
"log.info_1(\" Graph Name: Graph.PowerOn.Node\") # Ensure the compute node is",
"key) elif isinstance(obj, list): for item in obj: findall(item, key)",
"argument. This test takes 30-45 minutes to run. Example payload",
"= fit_common.rackhdapi(nodeinfo.get('sku'))['json']['name'] monurl = \"/api/2.0/nodes/\" + cls.__NODE + \"/catalogs/bmc\" mondata",
"fit_common.rackhdapi('/api/2.0/nodes/' + self.__class__.__NODE)['json'] nodesku = fit_common.rackhdapi(nodeinfo.get('sku'))['json']['name'] log.info_1(\" Node ID: %s",
"- 1)] # Print node Id, node BMC mac ,node",
"status: %s\", result['json']['status']) log.error(\" Data: %s\", json.dumps(res, indent=4, separators=(',', ':')))",
"launch workflow workflowid = None result = fit_common.rackhdapi('/api/2.0/nodes/' + self.__class__.__NODE",
"return False if result['json']['status'] in ['running', 'pending']: log.info_5(\"{} workflow status:",
"Src: %s\", catalog.get('data')['IP Address Source']) # delete active workflows for",
"self.__class__.__NODE) log.info_1(\" Node SKU: \" + nodesku) log.info_1(\" Graph Name:",
"['running', 'pending']: log.info_5(\"{} workflow status: {}\".format(result['json']['injectableName'], result['json']['status'])) fit_common.time.sleep(cycle) elif result['json']['status']",
"installed on RackHD server as documented here: https://github.com/RackHD/on-tools/tree/master/winpe - Samba",
"log.info_1(\" Error on catalog/bmc command\") else: log.info_1(\" Node ID: \"",
"SKU: \" + nodesku) log.info_1(\" Node BMC Mac: %s\", catalog.get('data')['MAC",
"log.error(\" HTTP error: \" + result['text']) return False if result['json']['status']",
"Node SKU: %s \", nodesku) log.info_1(\" Graph Name: Graph.PowerOn.Node\") #",
"equivalent NFS mount. - Windows 2012 activation key in the",
"nodes currently discovered\" # Select one node at random cls.__NODE",
"fit_common import flogging import random import json import time from",
"nodes NODECATALOG = fit_common.node_select() assert (len(NODECATALOG) != 0), \"There are",
"isinstance(obj, list): for item in obj: findall(item, key) else: pass",
"for item in obj: findall(item, key) else: pass # this",
"nodesku = fit_common.rackhdapi(nodeinfo.get('sku'))['json']['name'] log.info_1(\" Node ID: %s \", self.__class__.__NODE) log.info_1(\"",
"running a minimum payload Windows OS install. Other Windows-type OS",
"+ self.__class__.__NODE)['json'] nodesku = fit_common.rackhdapi(nodeinfo.get('sku'))['json']['name'] log.info_1(\" Node ID: %s \",",
"key: log.error(\" workflow error: %s\", v) findall(v, key) elif isinstance(obj,",
"Get the list of nodes NODECATALOG = fit_common.node_select() assert (len(NODECATALOG)",
"= config # function to return the value of a",
"+ result['text']) self.fail(\"Workflow failed with response code: \" + result['status'])",
"subsidiaries. All Rights Reserved. This script tests arbitrary payload of",
"server or equivalent NFS mount. - Windows 2012 activation key",
"\" + json.dumps(res, indent=4, separators=(',', ':'))) return False # ------------------------",
"at time: \" + str(datetime.fromtimestamp(end_time))) log.info_1(\" Workflow duration: \" +",
"fit_common.rackhdapi('/api/2.0/nodes/' + self.__class__.__NODE + '/workflows', action='post', payload={\"name\": \"Graph.PowerOn.Node\"}) self.assertEqual(result['status'], 201,",
"this routine polls a workflow task ID for completion def",
"that config = fit_common.fitcfg().get('bootstrap-payload', None) if config: PAYLOAD = config",
"pass # this routine polls a workflow task ID for",
"None result = fit_common.rackhdapi('/api/2.0/nodes/' + self.__class__.__NODE + '/workflows', action='post', payload=PAYLOAD)",
"and configured as documented here: http://rackhd.readthedocs.io/en/latest/rackhd/install_os.html?highlight=os%20install - Windows 2012 installation",
"failed at time: \" + str(datetime.fromtimestamp(end_time))) log.info_1(\" Workflow duration: \"",
"data nodeinfo = fit_common.rackhdapi('/api/2.0/nodes/' + self.__class__.__NODE)['json'] nodesku = fit_common.rackhdapi(nodeinfo.get('sku'))['json']['name'] log.info_1(\"",
"file and specifiying it using the '-extra' argument. This test",
"\"smbRepo\": \"\\\\\\\\172.31.128.1\\\\windowsServer2012\", \"productkey\": \"<KEY>\", \"username\": \"rackhduser\", \"password\": \"<PASSWORD>\", \"smbUser\": \"vagrant\",",
"in ['running', 'pending']: log.info_5(\"{} workflow status: {}\".format(result['json']['injectableName'], result['json']['status'])) fit_common.time.sleep(cycle) elif",
"res = result['text'] log.error(\" Workflow Timeout: \" + json.dumps(res, indent=4,",
"len(NODECATALOG) - 1)] # Print node Id, node BMC mac",
"reachable result = fit_common.rackhdapi('/api/2.0/nodes/' + self.__class__.__NODE + '/workflows', action='post', payload={\"name\":",
"datetime log = flogging.get_loggers() # sample default base payload PAYLOAD",
"on catalog/bmc command\") else: log.info_1(\" Node ID: \" + cls.__NODE)",
"nodesku) log.info_1(\" Graph Name: Graph.PowerOn.Node\") # Ensure the compute node",
"delete active workflows for specified node result = fit_common.cancel_active_workflows(cls.__NODE) assert",
"result = fit_common.cancel_active_workflows(cls.__NODE) assert (result is True), \"There are still",
"result = fit_common.rackhdapi(\"/api/2.0/workflows/\" + instanceid) if result['status'] != 200: log.error(\"",
"try: res = json.loads(result['text']) except: res = result['text'] log.error(\" Workflow",
"cls.__NODE)['json'] nodesku = fit_common.rackhdapi(nodeinfo.get('sku'))['json']['name'] monurl = \"/api/2.0/nodes/\" + cls.__NODE +",
"log.info_1(\" Graph Name: Graph.InstallWindowsServer\") log.info_1(\" Payload: \" + fit_common.json.dumps(PAYLOAD)) #",
"fit_common.rackhdapi('/api/2.0/nodes/' + cls.__NODE)['json'] nodesku = fit_common.rackhdapi(nodeinfo.get('sku'))['json']['name'] monurl = \"/api/2.0/nodes/\" +",
"= fit_common.rackhdapi(\"/api/2.0/workflows/\" + instanceid) if result['status'] != 200: log.error(\" HTTP",
"result['text']) return False if result['json']['status'] in ['running', 'pending']: log.info_5(\"{} workflow",
"log.info_1(\" Node SKU: %s \", nodesku) log.info_1(\" Graph Name: Graph.PowerOn.Node\")",
"the node\" def test01_node_check(self): # Log node data nodeinfo =",
"failed with response code: \" + result['status']) self.assertTrue(wait_for_workflow_complete(workflowid, time.time()), \"OS",
"from the workflow response def findall(obj, key): if isinstance(obj, dict):",
"Address']) log.info_1(\" Node BMC IP Addr: %s\", catalog.get('data')['IP Address']) log.info_1(\"",
"node data nodeinfo = fit_common.rackhdapi('/api/2.0/nodes/' + self.__class__.__NODE)['json'] nodesku = fit_common.rackhdapi(nodeinfo.get('sku'))['json']['name']",
"log.info_1(\" Node ID: \" + self.__class__.__NODE) log.info_1(\" Node SKU: \"",
"mondata['json'] bmcresult = mondata['status'] if bmcresult != 200: log.info_1(\" Node",
"200: log.info_1(\" Node ID: \" + cls.__NODE) log.info_1(\" Error on",
"\" + result['status']) self.assertTrue(wait_for_workflow_complete(workflowid, time.time()), \"OS Install workflow failed, see",
"Graph.PowerOn.Node\") # Ensure the compute node is powered on and",
"log.info_1(\" Node SKU: \" + nodesku) log.info_1(\" Node BMC Mac:",
"Reserved. This script tests arbitrary payload of the RackHD API",
"# Ensure the compute node is powered on and reachable",
"result = fit_common.rackhdapi('/api/2.0/nodes/' + self.__class__.__NODE + '/workflows', action='post', payload={\"name\": \"Graph.PowerOn.Node\"})",
"catalog = mondata['json'] bmcresult = mondata['status'] if bmcresult != 200:",
"\"productkey\": \"<KEY>\", \"username\": \"rackhduser\", \"password\": \"<PASSWORD>\", \"smbUser\": \"vagrant\", \"smbPassword\": \"<PASSWORD>\"}}}",
"if an external payload file is specified, use that config",
"customized WinPE environment installed on RackHD server as documented here:",
"< waittime: # limit test to waittime seconds result =",
"+ cls.__NODE) log.info_1(\" Node SKU: \" + nodesku) log.info_1(\" Node",
"error: %s\", v) findall(v, key) elif isinstance(obj, list): for item",
"assert (len(NODECATALOG) != 0), \"There are no nodes currently discovered\"",
"BMC mac ,node type nodeinfo = fit_common.rackhdapi('/api/2.0/nodes/' + cls.__NODE)['json'] nodesku",
"item in obj: findall(item, key) else: pass # this routine",
"are still some active workflows running against the node\" def",
"\"2012\", \"repo\": \"http://172.31.128.1:8080/repo/winpe\", \"smbRepo\": \"\\\\\\\\172.31.128.1\\\\windowsServer2012\", \"productkey\": \"<KEY>\", \"username\": \"rackhduser\", \"password\":",
"failed with response code log.error(\" InstanceID: \" + result['text']) self.fail(\"Workflow",
"-test tests/bootstrap/test_api20_windows_bootstrap.py -extra base_windows_2012_install.json RackHD Windows installation workflow requires special",
"result['json']['status'] == 'succeeded': log.info_1(\"{} workflow status: {}\".format(result['json']['injectableName'], result['json']['status'])) end_time =",
"log = flogging.get_loggers() # sample default base payload PAYLOAD =",
"Rights Reserved. This script tests arbitrary payload of the RackHD",
"\"<PASSWORD>\"}}} } Example command line using external payload file: python",
"datetime import datetime log = flogging.get_loggers() # sample default base",
"test to waittime seconds result = fit_common.rackhdapi(\"/api/2.0/workflows/\" + instanceid) if",
"\"<KEY>\", \"username\": \"rackhduser\", \"password\": \"<PASSWORD>\", \"smbUser\": \"vagrant\", \"smbPassword\": \"<PASSWORD>\"}}} }",
"+ '/workflows', action='post', payload={\"name\": \"Graph.PowerOn.Node\"}) self.assertEqual(result['status'], 201, \"Node Power on",
"a minimum payload Windows OS install. Other Windows-type OS install",
"findall(v, key) elif isinstance(obj, list): for item in obj: findall(item,",
"return True else: end_time = time.time() log.info_1(\" Workflow failed at",
"+ cls.__NODE)['json'] nodesku = fit_common.rackhdapi(nodeinfo.get('sku'))['json']['name'] monurl = \"/api/2.0/nodes/\" + cls.__NODE",
"def test02_os_install(self): # Log node data nodeinfo = fit_common.rackhdapi('/api/2.0/nodes/' +",
"+ nodesku) log.info_1(\" Graph Name: Graph.InstallWindowsServer\") log.info_1(\" Payload: \" +",
"{\"defaults\": {\"version\": \"2012\", \"repo\": \"http://172.31.128.1:8080/repo/winpe\", \"smbRepo\": \"\\\\\\\\172.31.128.1\\\\windowsServer2012\", \"productkey\": \"<KEY>\", \"username\":",
"tests arbitrary payload of the RackHD API 2.0 OS bootstrap",
"%s\", result['json']['status']) log.error(\" Data: %s\", json.dumps(res, indent=4, separators=(',', ':'))) return",
"%s\", json.dumps(res, indent=4, separators=(',', ':'))) return False try: res =",
"Payload: \" + fit_common.json.dumps(PAYLOAD)) # launch workflow workflowid = None",
"{}\".format(result['json']['injectableName'], result['json']['status'])) end_time = time.time() log.info_1(\" Workflow completed at time:",
"setUpClass(cls): # Get the list of nodes NODECATALOG = fit_common.node_select()",
"50, 5), \"Node Power on workflow failed, see logs.\") @depends(after=test01_node_check)",
"== 'succeeded': log.info_1(\"{} workflow status: {}\".format(result['json']['injectableName'], result['json']['status'])) end_time = time.time()",
"ID for completion def wait_for_workflow_complete(instanceid, start_time, waittime=3200, cycle=30): log.info_1(\" Workflow",
"task ID for completion def wait_for_workflow_complete(instanceid, start_time, waittime=3200, cycle=30): log.info_1(\"",
"\"<PASSWORD>\", \"smbUser\": \"vagrant\", \"smbPassword\": \"<PASSWORD>\"}}} } Example command line using",
"The default case is running a minimum payload Windows OS",
"NODECATALOG = fit_common.node_select() assert (len(NODECATALOG) != 0), \"There are no",
"installed on the RackHD server and configured as documented here:",
"\"repo\": \"http://172.31.128.1:8080/repo/winpe\", \"smbRepo\": \"\\\\\\\\172.31.128.1\\\\windowsServer2012\", \"productkey\": \"<KEY>\", \"username\": \"rackhduser\", \"password\": \"<PASSWORD>\",",
"Select one node at random cls.__NODE = NODECATALOG[random.randint(0, len(NODECATALOG) -",
"\"<KEY>\", \"username\": \"rackhduser\", \"password\": \"<PASSWORD>\", \"smbUser\": \"vagrant\", \"smbPassword\": \"<PASSWORD>\"}}} #",
"@depends(after=test01_node_check) def test02_os_install(self): # Log node data nodeinfo = fit_common.rackhdapi('/api/2.0/nodes/'",
"specified node result = fit_common.cancel_active_workflows(cls.__NODE) assert (result is True), \"There",
"# Get the list of nodes NODECATALOG = fit_common.node_select() assert",
"powered on and reachable result = fit_common.rackhdapi('/api/2.0/nodes/' + self.__class__.__NODE +",
"fit_common.node_select() assert (len(NODECATALOG) != 0), \"There are no nodes currently",
"or its subsidiaries. All Rights Reserved. This script tests arbitrary",
"on RackHD server or equivalent NFS mount. - Windows 2012",
",node type nodeinfo = fit_common.rackhdapi('/api/2.0/nodes/' + cls.__NODE)['json'] nodesku = fit_common.rackhdapi(nodeinfo.get('sku'))['json']['name']",
"(result is True), \"There are still some active workflows running",
"use that config = fit_common.fitcfg().get('bootstrap-payload', None) if config: PAYLOAD =",
"Workflow duration: \" + str(end_time - start_time)) return True else:",
"API 2.0 OS bootstrap workflows. The default case is running",
"\" + result['json']['instanceId']) workflowid = result['json']['instanceId'] else: # workflow failed",
"''' Copyright 2017 Dell Inc. or its subsidiaries. All Rights",
"\"Node Power on workflow API failed, see logs.\") self.assertTrue(wait_for_workflow_complete(result['json']['instanceId'], time.time(),",
"Graph.InstallWindowsServer\") log.info_1(\" Payload: \" + fit_common.json.dumps(PAYLOAD)) # launch workflow workflowid",
"configured as documented here: http://rackhd.readthedocs.io/en/latest/rackhd/install_os.html?highlight=os%20install - Windows 2012 installation distro",
"False if result['json']['status'] in ['running', 'pending']: log.info_5(\"{} workflow status: {}\".format(result['json']['injectableName'],",
"result['json']['status']) log.error(\" Data: %s\", json.dumps(res, indent=4, separators=(',', ':'))) return False",
"time.time(), 50, 5), \"Node Power on workflow failed, see logs.\")",
"for completion def wait_for_workflow_complete(instanceid, start_time, waittime=3200, cycle=30): log.info_1(\" Workflow started",
"= result['json']['instanceId'] else: # workflow failed with response code log.error(\"",
"WinPE environment installed on RackHD server as documented here: https://github.com/RackHD/on-tools/tree/master/winpe",
"{}\".format(result['json']['injectableName'], result['json']['status'])) fit_common.time.sleep(cycle) elif result['json']['status'] == 'succeeded': log.info_1(\"{} workflow status:",
"log.info_1(\" Node BMC Mac: %s\", catalog.get('data')['MAC Address']) log.info_1(\" Node BMC",
"here: http://rackhd.readthedocs.io/en/latest/rackhd/install_os.html?highlight=os%20install - Windows 2012 installation distro installed on RackHD",
"run_tests.py -stack 4 -test tests/bootstrap/test_api20_windows_bootstrap.py -extra base_windows_2012_install.json RackHD Windows installation",
"# Print node Id, node BMC mac ,node type nodeinfo",
"arbitrary payload of the RackHD API 2.0 OS bootstrap workflows.",
"Node BMC IP Addr: %s\", catalog.get('data')['IP Address']) log.info_1(\" Node BMC",
"2012 activation key in the installation payload file. ''' import",
"HTTP error: \" + result['text']) return False if result['json']['status'] in",
"failed: status: %s\", result['json']['status']) log.error(\" Data: %s\", json.dumps(res, indent=4, separators=(',',",
"creating a payload file and specifiying it using the '-extra'",
"with response code: \" + result['status']) self.assertTrue(wait_for_workflow_complete(workflowid, time.time()), \"OS Install",
"https://github.com/RackHD/on-tools/tree/master/winpe - Samba installed on the RackHD server and configured",
"if result['json']['status'] in ['running', 'pending']: log.info_5(\"{} workflow status: {}\".format(result['json']['injectableName'], result['json']['status']))",
"of the RackHD server: - A customized WinPE environment installed",
"limit test to waittime seconds result = fit_common.rackhdapi(\"/api/2.0/workflows/\" + instanceid)",
"= json.loads(result['text']) findall(res, \"error\") except: res = result['text'] log.error(\" Workflow",
"# ------------------------ Tests ------------------------------------- @attr(all=False) class api20_bootstrap_windows(fit_common.unittest.TestCase): @classmethod def setUpClass(cls):",
"Dell Inc. or its subsidiaries. All Rights Reserved. This script",
"assert (result is True), \"There are still some active workflows",
"the RackHD server and configured as documented here: http://rackhd.readthedocs.io/en/latest/rackhd/install_os.html?highlight=os%20install -",
"self.__class__.__NODE) log.info_1(\" Node SKU: %s \", nodesku) log.info_1(\" Graph Name:",
"mondata['status'] if bmcresult != 200: log.info_1(\" Node ID: \" +",
"self.assertTrue(wait_for_workflow_complete(result['json']['instanceId'], time.time(), 50, 5), \"Node Power on workflow failed, see",
"function to return the value of a field from the",
"using external payload file: python run_tests.py -stack 4 -test tests/bootstrap/test_api20_windows_bootstrap.py",
"start_time)) try: res = json.loads(result['text']) findall(res, \"error\") except: res =",
"\"There are no nodes currently discovered\" # Select one node",
"findall(res, \"error\") except: res = result['text'] log.error(\" Workflow failed: status:",
"RackHD server and configured as documented here: http://rackhd.readthedocs.io/en/latest/rackhd/install_os.html?highlight=os%20install - Windows",
"workflowid = result['json']['instanceId'] else: # workflow failed with response code",
"seconds result = fit_common.rackhdapi(\"/api/2.0/workflows/\" + instanceid) if result['status'] != 200:",
"str(end_time - start_time)) try: res = json.loads(result['text']) findall(res, \"error\") except:",
"201: # workflow running log.info_1(\" InstanceID: \" + result['json']['instanceId']) workflowid",
"\" + nodesku) log.info_1(\" Node BMC Mac: %s\", catalog.get('data')['MAC Address'])",
"} Example command line using external payload file: python run_tests.py",
"RackHD API 2.0 OS bootstrap workflows. The default case is",
"Samba installed on the RackHD server and configured as documented",
"# this routine polls a workflow task ID for completion",
"import datetime log = flogging.get_loggers() # sample default base payload",
"bmcresult != 200: log.info_1(\" Node ID: \" + cls.__NODE) log.info_1(\"",
"tests/bootstrap/test_api20_windows_bootstrap.py -extra base_windows_2012_install.json RackHD Windows installation workflow requires special configuration",
"- start_time < waittime: # limit test to waittime seconds",
"result['text'] log.error(\" Workflow failed: status: %s\", result['json']['status']) log.error(\" Data: %s\",",
"= NODECATALOG[random.randint(0, len(NODECATALOG) - 1)] # Print node Id, node",
"depends from datetime import datetime log = flogging.get_loggers() # sample",
"Tests ------------------------------------- @attr(all=False) class api20_bootstrap_windows(fit_common.unittest.TestCase): @classmethod def setUpClass(cls): # Get",
"0), \"There are no nodes currently discovered\" # Select one",
"\", nodesku) log.info_1(\" Graph Name: Graph.PowerOn.Node\") # Ensure the compute",
"# workflow failed with response code log.error(\" InstanceID: \" +",
"- A customized WinPE environment installed on RackHD server as",
"2.0 OS bootstrap workflows. The default case is running a",
"= fit_common.rackhdapi('/api/2.0/nodes/' + self.__class__.__NODE + '/workflows', action='post', payload={\"name\": \"Graph.PowerOn.Node\"}) self.assertEqual(result['status'],",
"fit_common.json.dumps(PAYLOAD)) # launch workflow workflowid = None result = fit_common.rackhdapi('/api/2.0/nodes/'",
"log.info_1(\" Node ID: \" + cls.__NODE) log.info_1(\" Node SKU: \"",
"= result['text'] log.error(\" Workflow Timeout: \" + json.dumps(res, indent=4, separators=(',',",
"default case is running a minimum payload Windows OS install.",
"dir): {\"bootstrap-payload\": {\"name\": \"Graph.InstallWindowsServer\", \"options\": {\"defaults\": {\"version\": \"2012\", \"repo\": \"http://172.31.128.1:8080/repo/winpe\",",
"Workflow started at time: \" + str(datetime.fromtimestamp(start_time))) while time.time() -",
"OS install. Other Windows-type OS install cases can be specified",
"Print node Id, node BMC mac ,node type nodeinfo =",
"http://rackhd.readthedocs.io/en/latest/rackhd/install_os.html?highlight=os%20install - Windows 2012 installation distro installed on RackHD server",
"Workflow failed: status: %s\", result['json']['status']) log.error(\" Data: %s\", json.dumps(res, indent=4,",
"node BMC mac ,node type nodeinfo = fit_common.rackhdapi('/api/2.0/nodes/' + cls.__NODE)['json']",
"completion def wait_for_workflow_complete(instanceid, start_time, waittime=3200, cycle=30): log.info_1(\" Workflow started at",
"workflows running against the node\" def test01_node_check(self): # Log node",
"start_time)) return True else: end_time = time.time() log.info_1(\" Workflow failed",
"json.dumps(res, indent=4, separators=(',', ':'))) return False # ------------------------ Tests -------------------------------------",
"Log node data nodeinfo = fit_common.rackhdapi('/api/2.0/nodes/' + self.__class__.__NODE)['json'] nodesku =",
"server: - A customized WinPE environment installed on RackHD server",
"5), \"Node Power on workflow failed, see logs.\") @depends(after=test01_node_check) def",
"by creating a payload file and specifiying it using the",
"Example command line using external payload file: python run_tests.py -stack",
"+ cls.__NODE) log.info_1(\" Error on catalog/bmc command\") else: log.info_1(\" Node",
"base_windows_2012_install.json RackHD Windows installation workflow requires special configuration of the",
"def findall(obj, key): if isinstance(obj, dict): for k, v in",
"result['json']['status'])) end_time = time.time() log.info_1(\" Workflow completed at time: \"",
"against the node\" def test01_node_check(self): # Log node data nodeinfo",
"sample default base payload PAYLOAD = {\"name\": \"Graph.InstallWindowsServer\", \"options\": {\"defaults\":",
"BMC Mac: %s\", catalog.get('data')['MAC Address']) log.info_1(\" Node BMC IP Addr:",
"nosedep import depends from datetime import datetime log = flogging.get_loggers()",
"\"password\": \"<PASSWORD>\", \"smbUser\": \"vagrant\", \"smbPassword\": \"<PASSWORD>\"}}} # if an external",
"if isinstance(obj, dict): for k, v in obj.items(): if k",
"of nodes NODECATALOG = fit_common.node_select() assert (len(NODECATALOG) != 0), \"There",
"'/workflows', action='post', payload={\"name\": \"Graph.PowerOn.Node\"}) self.assertEqual(result['status'], 201, \"Node Power on workflow",
"RackHD server as documented here: https://github.com/RackHD/on-tools/tree/master/winpe - Samba installed on",
"# sample default base payload PAYLOAD = {\"name\": \"Graph.InstallWindowsServer\", \"options\":",
"def setUpClass(cls): # Get the list of nodes NODECATALOG =",
"!= 0), \"There are no nodes currently discovered\" # Select",
"NODECATALOG[random.randint(0, len(NODECATALOG) - 1)] # Print node Id, node BMC",
"log.error(\" Workflow Timeout: \" + json.dumps(res, indent=4, separators=(',', ':'))) return",
"BMC IP Addr: %s\", catalog.get('data')['IP Address']) log.info_1(\" Node BMC IP",
"Workflow duration: \" + str(end_time - start_time)) try: res =",
"elif isinstance(obj, list): for item in obj: findall(item, key) else:",
"external payload file: python run_tests.py -stack 4 -test tests/bootstrap/test_api20_windows_bootstrap.py -extra",
"Example payload file (installed in configuration dir): {\"bootstrap-payload\": {\"name\": \"Graph.InstallWindowsServer\",",
"result['json']['instanceId']) workflowid = result['json']['instanceId'] else: # workflow failed with response",
"Workflow Timeout: \" + json.dumps(res, indent=4, separators=(',', ':'))) return False",
"discovered\" # Select one node at random cls.__NODE = NODECATALOG[random.randint(0,",
"log.info_1(\" Workflow failed at time: \" + str(datetime.fromtimestamp(end_time))) log.info_1(\" Workflow",
"k, v in obj.items(): if k == key: log.error(\" workflow",
"import fit_common import flogging import random import json import time",
"action='post', payload={\"name\": \"Graph.PowerOn.Node\"}) self.assertEqual(result['status'], 201, \"Node Power on workflow API",
"for specified node result = fit_common.cancel_active_workflows(cls.__NODE) assert (result is True),",
"wait_for_workflow_complete(instanceid, start_time, waittime=3200, cycle=30): log.info_1(\" Workflow started at time: \"",
"Node ID: \" + cls.__NODE) log.info_1(\" Error on catalog/bmc command\")",
"''' import fit_path # NOQA: unused import from nose.plugins.attrib import",
"default base payload PAYLOAD = {\"name\": \"Graph.InstallWindowsServer\", \"options\": {\"defaults\": {\"version\":",
"time.time()), \"OS Install workflow failed, see logs.\") if __name__ ==",
"file: python run_tests.py -stack 4 -test tests/bootstrap/test_api20_windows_bootstrap.py -extra base_windows_2012_install.json RackHD",
"\"http://172.31.128.1:8080/repo/winpe\", \"smbRepo\": \"\\\\\\\\172.31.128.1\\\\windowsServer2012\", \"productkey\": \"<KEY>\", \"username\": \"rackhduser\", \"password\": \"<PASSWORD>\", \"smbUser\":",
"is powered on and reachable result = fit_common.rackhdapi('/api/2.0/nodes/' + self.__class__.__NODE",
"its subsidiaries. All Rights Reserved. This script tests arbitrary payload",
"key): if isinstance(obj, dict): for k, v in obj.items(): if",
"ID: %s \", self.__class__.__NODE) log.info_1(\" Node SKU: %s \", nodesku)",
"+ fit_common.json.dumps(PAYLOAD)) # launch workflow workflowid = None result =",
"Timeout: \" + json.dumps(res, indent=4, separators=(',', ':'))) return False #",
"log.info_1(\" Node BMC IP Addr Src: %s\", catalog.get('data')['IP Address Source'])",
"= fit_common.rackhdapi(nodeinfo.get('sku'))['json']['name'] log.info_1(\" Node ID: %s \", self.__class__.__NODE) log.info_1(\" Node",
"and specifiying it using the '-extra' argument. This test takes",
"import flogging import random import json import time from nosedep",
"+ result['json']['instanceId']) workflowid = result['json']['instanceId'] else: # workflow failed with",
"\"/catalogs/bmc\" mondata = fit_common.rackhdapi(monurl, action=\"get\") catalog = mondata['json'] bmcresult =",
"obj.items(): if k == key: log.error(\" workflow error: %s\", v)",
"cls.__NODE) log.info_1(\" Node SKU: \" + nodesku) log.info_1(\" Node BMC",
"This script tests arbitrary payload of the RackHD API 2.0",
"import attr import fit_common import flogging import random import json",
"{\"name\": \"Graph.InstallWindowsServer\", \"options\": {\"defaults\": {\"version\": \"2012\", \"repo\": \"http://172.31.128.1:8080/repo/winpe\", \"smbRepo\": \"\\\\\\\\172.31.128.1\\\\windowsServer2012\",",
"python run_tests.py -stack 4 -test tests/bootstrap/test_api20_windows_bootstrap.py -extra base_windows_2012_install.json RackHD Windows",
"%s\", catalog.get('data')['MAC Address']) log.info_1(\" Node BMC IP Addr: %s\", catalog.get('data')['IP",
"duration: \" + str(end_time - start_time)) try: res = json.loads(result['text'])",
"activation key in the installation payload file. ''' import fit_path",
"1)] # Print node Id, node BMC mac ,node type",
"= None result = fit_common.rackhdapi('/api/2.0/nodes/' + self.__class__.__NODE + '/workflows', action='post',",
"= time.time() log.info_1(\" Workflow failed at time: \" + str(datetime.fromtimestamp(end_time)))",
"one node at random cls.__NODE = NODECATALOG[random.randint(0, len(NODECATALOG) - 1)]",
"separators=(',', ':'))) return False try: res = json.loads(result['text']) except: res",
"Address Source']) # delete active workflows for specified node result",
"flogging.get_loggers() # sample default base payload PAYLOAD = {\"name\": \"Graph.InstallWindowsServer\",",
"a field from the workflow response def findall(obj, key): if",
"response def findall(obj, key): if isinstance(obj, dict): for k, v",
"+ str(end_time - start_time)) return True else: end_time = time.time()",
"json.dumps(res, indent=4, separators=(',', ':'))) return False try: res = json.loads(result['text'])",
"catalog.get('data')['IP Address']) log.info_1(\" Node BMC IP Addr Src: %s\", catalog.get('data')['IP",
"api20_bootstrap_windows(fit_common.unittest.TestCase): @classmethod def setUpClass(cls): # Get the list of nodes",
"test01_node_check(self): # Log node data nodeinfo = fit_common.rackhdapi('/api/2.0/nodes/' + self.__class__.__NODE)['json']",
"log.error(\" InstanceID: \" + result['text']) self.fail(\"Workflow failed with response code:",
"+ str(datetime.fromtimestamp(start_time))) while time.time() - start_time < waittime: # limit",
"for k, v in obj.items(): if k == key: log.error(\"",
"RackHD server or equivalent NFS mount. - Windows 2012 activation",
"'/workflows', action='post', payload=PAYLOAD) if result['status'] == 201: # workflow running",
"payload file: python run_tests.py -stack 4 -test tests/bootstrap/test_api20_windows_bootstrap.py -extra base_windows_2012_install.json",
"OS install cases can be specified by creating a payload",
"False try: res = json.loads(result['text']) except: res = result['text'] log.error(\"",
"payload file is specified, use that config = fit_common.fitcfg().get('bootstrap-payload', None)",
"- start_time)) return True else: end_time = time.time() log.info_1(\" Workflow",
"log.error(\" workflow error: %s\", v) findall(v, key) elif isinstance(obj, list):",
"try: res = json.loads(result['text']) findall(res, \"error\") except: res = result['text']",
"log.info_1(\" Workflow duration: \" + str(end_time - start_time)) return True",
"log.info_1(\" Node BMC IP Addr: %s\", catalog.get('data')['IP Address']) log.info_1(\" Node",
"= \"/api/2.0/nodes/\" + cls.__NODE + \"/catalogs/bmc\" mondata = fit_common.rackhdapi(monurl, action=\"get\")",
"\"Node Power on workflow failed, see logs.\") @depends(after=test01_node_check) def test02_os_install(self):",
"cases can be specified by creating a payload file and",
"failed, see logs.\") @depends(after=test01_node_check) def test02_os_install(self): # Log node data",
"cls.__NODE) log.info_1(\" Error on catalog/bmc command\") else: log.info_1(\" Node ID:",
"node is powered on and reachable result = fit_common.rackhdapi('/api/2.0/nodes/' +",
"PAYLOAD = config # function to return the value of",
"+ self.__class__.__NODE + '/workflows', action='post', payload=PAYLOAD) if result['status'] == 201:",
"a payload file and specifiying it using the '-extra' argument.",
"takes 30-45 minutes to run. Example payload file (installed in",
"time.time() - start_time < waittime: # limit test to waittime",
"':'))) return False # ------------------------ Tests ------------------------------------- @attr(all=False) class api20_bootstrap_windows(fit_common.unittest.TestCase):",
"Node SKU: \" + nodesku) log.info_1(\" Graph Name: Graph.InstallWindowsServer\") log.info_1(\"",
"2012 installation distro installed on RackHD server or equivalent NFS",
"random cls.__NODE = NODECATALOG[random.randint(0, len(NODECATALOG) - 1)] # Print node",
"end_time = time.time() log.info_1(\" Workflow completed at time: \" +",
"class api20_bootstrap_windows(fit_common.unittest.TestCase): @classmethod def setUpClass(cls): # Get the list of",
"nodesku) log.info_1(\" Node BMC Mac: %s\", catalog.get('data')['MAC Address']) log.info_1(\" Node",
"\" + self.__class__.__NODE) log.info_1(\" Node SKU: \" + nodesku) log.info_1(\"",
"config: PAYLOAD = config # function to return the value",
"payload of the RackHD API 2.0 OS bootstrap workflows. The",
"+ result['status']) self.assertTrue(wait_for_workflow_complete(workflowid, time.time()), \"OS Install workflow failed, see logs.\")",
"action='post', payload=PAYLOAD) if result['status'] == 201: # workflow running log.info_1(\"",
"is True), \"There are still some active workflows running against",
"payload PAYLOAD = {\"name\": \"Graph.InstallWindowsServer\", \"options\": {\"defaults\": {\"version\": \"2012\", \"repo\":",
"= fit_common.node_select() assert (len(NODECATALOG) != 0), \"There are no nodes",
"Node BMC Mac: %s\", catalog.get('data')['MAC Address']) log.info_1(\" Node BMC IP",
"a workflow task ID for completion def wait_for_workflow_complete(instanceid, start_time, waittime=3200,",
"\"password\": \"<PASSWORD>\", \"smbUser\": \"vagrant\", \"smbPassword\": \"<PASSWORD>\"}}} } Example command line",
"201, \"Node Power on workflow API failed, see logs.\") self.assertTrue(wait_for_workflow_complete(result['json']['instanceId'],",
"= fit_common.rackhdapi('/api/2.0/nodes/' + self.__class__.__NODE + '/workflows', action='post', payload=PAYLOAD) if result['status']",
"findall(obj, key): if isinstance(obj, dict): for k, v in obj.items():",
"config # function to return the value of a field",
"cls.__NODE = NODECATALOG[random.randint(0, len(NODECATALOG) - 1)] # Print node Id,",
"from datetime import datetime log = flogging.get_loggers() # sample default",
"fit_common.cancel_active_workflows(cls.__NODE) assert (result is True), \"There are still some active",
"self.fail(\"Workflow failed with response code: \" + result['status']) self.assertTrue(wait_for_workflow_complete(workflowid, time.time()),",
"RackHD server: - A customized WinPE environment installed on RackHD",
"json.loads(result['text']) except: res = result['text'] log.error(\" Workflow Timeout: \" +",
"while time.time() - start_time < waittime: # limit test to",
"compute node is powered on and reachable result = fit_common.rackhdapi('/api/2.0/nodes/'",
"server and configured as documented here: http://rackhd.readthedocs.io/en/latest/rackhd/install_os.html?highlight=os%20install - Windows 2012",
"fit_common.rackhdapi('/api/2.0/nodes/' + self.__class__.__NODE + '/workflows', action='post', payload=PAYLOAD) if result['status'] ==",
"log.info_1(\"{} workflow status: {}\".format(result['json']['injectableName'], result['json']['status'])) end_time = time.time() log.info_1(\" Workflow",
"to return the value of a field from the workflow",
"\"options\": {\"defaults\": {\"version\": \"2012\", \"repo\": \"http://172.31.128.1:8080/repo/winpe\", \"smbRepo\": \"\\\\\\\\172.31.128.1\\\\windowsServer2012\", \"productkey\": \"<KEY>\",",
"'pending']: log.info_5(\"{} workflow status: {}\".format(result['json']['injectableName'], result['json']['status'])) fit_common.time.sleep(cycle) elif result['json']['status'] ==",
"%s\", catalog.get('data')['IP Address']) log.info_1(\" Node BMC IP Addr Src: %s\",",
"fit_common.rackhdapi(nodeinfo.get('sku'))['json']['name'] log.info_1(\" Node ID: %s \", self.__class__.__NODE) log.info_1(\" Node SKU:",
"self.__class__.__NODE)['json'] nodesku = fit_common.rackhdapi(nodeinfo.get('sku'))['json']['name'] log.info_1(\" Node ID: \" + self.__class__.__NODE)",
"installation payload file. ''' import fit_path # NOQA: unused import",
"installed on RackHD server or equivalent NFS mount. - Windows",
"distro installed on RackHD server or equivalent NFS mount. -",
"k == key: log.error(\" workflow error: %s\", v) findall(v, key)",
"code: \" + result['status']) self.assertTrue(wait_for_workflow_complete(workflowid, time.time()), \"OS Install workflow failed,",
"environment installed on RackHD server as documented here: https://github.com/RackHD/on-tools/tree/master/winpe -",
"4 -test tests/bootstrap/test_api20_windows_bootstrap.py -extra base_windows_2012_install.json RackHD Windows installation workflow requires",
"flogging import random import json import time from nosedep import",
"if result['status'] == 201: # workflow running log.info_1(\" InstanceID: \"",
"an external payload file is specified, use that config =",
"command\") else: log.info_1(\" Node ID: \" + cls.__NODE) log.info_1(\" Node",
"response code: \" + result['status']) self.assertTrue(wait_for_workflow_complete(workflowid, time.time()), \"OS Install workflow",
"Source']) # delete active workflows for specified node result =",
"if k == key: log.error(\" workflow error: %s\", v) findall(v,",
"here: https://github.com/RackHD/on-tools/tree/master/winpe - Samba installed on the RackHD server and",
"log.info_1(\" Workflow duration: \" + str(end_time - start_time)) try: res",
"Copyright 2017 Dell Inc. or its subsidiaries. All Rights Reserved.",
"str(end_time - start_time)) return True else: end_time = time.time() log.info_1(\"",
"= mondata['status'] if bmcresult != 200: log.info_1(\" Node ID: \"",
"workflows. The default case is running a minimum payload Windows",
"special configuration of the RackHD server: - A customized WinPE",
"time: \" + str(datetime.fromtimestamp(start_time))) while time.time() - start_time < waittime:",
"catalog/bmc command\") else: log.info_1(\" Node ID: \" + cls.__NODE) log.info_1(\"",
"+ str(end_time - start_time)) try: res = json.loads(result['text']) findall(res, \"error\")",
"server as documented here: https://github.com/RackHD/on-tools/tree/master/winpe - Samba installed on the",
"# function to return the value of a field from",
"- Samba installed on the RackHD server and configured as",
"{\"bootstrap-payload\": {\"name\": \"Graph.InstallWindowsServer\", \"options\": {\"defaults\": {\"version\": \"2012\", \"repo\": \"http://172.31.128.1:8080/repo/winpe\", \"smbRepo\":",
"be specified by creating a payload file and specifiying it",
"the workflow response def findall(obj, key): if isinstance(obj, dict): for",
"------------------------ Tests ------------------------------------- @attr(all=False) class api20_bootstrap_windows(fit_common.unittest.TestCase): @classmethod def setUpClass(cls): #",
"documented here: http://rackhd.readthedocs.io/en/latest/rackhd/install_os.html?highlight=os%20install - Windows 2012 installation distro installed on",
"!= 200: log.info_1(\" Node ID: \" + cls.__NODE) log.info_1(\" Error",
"the RackHD server: - A customized WinPE environment installed on",
"\" + str(datetime.fromtimestamp(end_time))) log.info_1(\" Workflow duration: \" + str(end_time -",
"log.info_1(\" InstanceID: \" + result['json']['instanceId']) workflowid = result['json']['instanceId'] else: #",
"see logs.\") @depends(after=test01_node_check) def test02_os_install(self): # Log node data nodeinfo",
"fit_common.rackhdapi('/api/2.0/nodes/' + self.__class__.__NODE)['json'] nodesku = fit_common.rackhdapi(nodeinfo.get('sku'))['json']['name'] log.info_1(\" Node ID: \"",
"active workflows running against the node\" def test01_node_check(self): # Log",
"(installed in configuration dir): {\"bootstrap-payload\": {\"name\": \"Graph.InstallWindowsServer\", \"options\": {\"defaults\": {\"version\":",
"the '-extra' argument. This test takes 30-45 minutes to run.",
"+ nodesku) log.info_1(\" Node BMC Mac: %s\", catalog.get('data')['MAC Address']) log.info_1(\"",
"result['status']) self.assertTrue(wait_for_workflow_complete(workflowid, time.time()), \"OS Install workflow failed, see logs.\") if",
"catalog.get('data')['MAC Address']) log.info_1(\" Node BMC IP Addr: %s\", catalog.get('data')['IP Address'])",
"findall(item, key) else: pass # this routine polls a workflow",
"to run. Example payload file (installed in configuration dir): {\"bootstrap-payload\":",
"on workflow API failed, see logs.\") self.assertTrue(wait_for_workflow_complete(result['json']['instanceId'], time.time(), 50, 5),",
"payload Windows OS install. Other Windows-type OS install cases can",
"\" + fit_common.json.dumps(PAYLOAD)) # launch workflow workflowid = None result",
"RackHD Windows installation workflow requires special configuration of the RackHD",
"Addr: %s\", catalog.get('data')['IP Address']) log.info_1(\" Node BMC IP Addr Src:",
"Windows OS install. Other Windows-type OS install cases can be",
"script tests arbitrary payload of the RackHD API 2.0 OS",
"from nose.plugins.attrib import attr import fit_common import flogging import random",
"Power on workflow API failed, see logs.\") self.assertTrue(wait_for_workflow_complete(result['json']['instanceId'], time.time(), 50,",
"log.info_1(\" Node ID: %s \", self.__class__.__NODE) log.info_1(\" Node SKU: %s",
"key) else: pass # this routine polls a workflow task",
"install cases can be specified by creating a payload file",
"\", self.__class__.__NODE) log.info_1(\" Node SKU: %s \", nodesku) log.info_1(\" Graph",
"\" + str(datetime.fromtimestamp(start_time))) while time.time() - start_time < waittime: #",
"def wait_for_workflow_complete(instanceid, start_time, waittime=3200, cycle=30): log.info_1(\" Workflow started at time:",
"Power on workflow failed, see logs.\") @depends(after=test01_node_check) def test02_os_install(self): #",
"\"rackhduser\", \"password\": \"<PASSWORD>\", \"smbUser\": \"vagrant\", \"smbPassword\": \"<PASSWORD>\"}}} } Example command",
"node Id, node BMC mac ,node type nodeinfo = fit_common.rackhdapi('/api/2.0/nodes/'",
"Graph Name: Graph.InstallWindowsServer\") log.info_1(\" Payload: \" + fit_common.json.dumps(PAYLOAD)) # launch",
"requires special configuration of the RackHD server: - A customized",
"\"<PASSWORD>\", \"smbUser\": \"vagrant\", \"smbPassword\": \"<PASSWORD>\"}}} # if an external payload",
"self.assertEqual(result['status'], 201, \"Node Power on workflow API failed, see logs.\")",
"test takes 30-45 minutes to run. Example payload file (installed",
"import depends from datetime import datetime log = flogging.get_loggers() #",
"else: end_time = time.time() log.info_1(\" Workflow failed at time: \"",
"Data: %s\", json.dumps(res, indent=4, separators=(',', ':'))) return False try: res",
"installation distro installed on RackHD server or equivalent NFS mount.",
"waittime seconds result = fit_common.rackhdapi(\"/api/2.0/workflows/\" + instanceid) if result['status'] !=",
"v in obj.items(): if k == key: log.error(\" workflow error:",
"Windows 2012 activation key in the installation payload file. '''",
"command line using external payload file: python run_tests.py -stack 4",
"All Rights Reserved. This script tests arbitrary payload of the",
"@classmethod def setUpClass(cls): # Get the list of nodes NODECATALOG",
"------------------------------------- @attr(all=False) class api20_bootstrap_windows(fit_common.unittest.TestCase): @classmethod def setUpClass(cls): # Get the",
"\"OS Install workflow failed, see logs.\") if __name__ == '__main__':",
"\"There are still some active workflows running against the node\"",
"from nosedep import depends from datetime import datetime log =",
"result['text'] log.error(\" Workflow Timeout: \" + json.dumps(res, indent=4, separators=(',', ':')))",
"-stack 4 -test tests/bootstrap/test_api20_windows_bootstrap.py -extra base_windows_2012_install.json RackHD Windows installation workflow",
"\"smbUser\": \"vagrant\", \"smbPassword\": \"<PASSWORD>\"}}} # if an external payload file",
"nodesku = fit_common.rackhdapi(nodeinfo.get('sku'))['json']['name'] log.info_1(\" Node ID: \" + self.__class__.__NODE) log.info_1(\"",
"installation workflow requires special configuration of the RackHD server: -",
"Addr Src: %s\", catalog.get('data')['IP Address Source']) # delete active workflows",
"= {\"name\": \"Graph.InstallWindowsServer\", \"options\": {\"defaults\": {\"version\": \"2012\", \"repo\": \"http://172.31.128.1:8080/repo/winpe\", \"smbRepo\":",
"+ str(datetime.fromtimestamp(end_time))) log.info_1(\" Workflow duration: \" + str(end_time - start_time))",
"result['json']['status'] in ['running', 'pending']: log.info_5(\"{} workflow status: {}\".format(result['json']['injectableName'], result['json']['status'])) fit_common.time.sleep(cycle)",
"log.info_1(\" Workflow completed at time: \" + str(datetime.fromtimestamp(end_time))) log.info_1(\" Workflow",
"external payload file is specified, use that config = fit_common.fitcfg().get('bootstrap-payload',",
"payload={\"name\": \"Graph.PowerOn.Node\"}) self.assertEqual(result['status'], 201, \"Node Power on workflow API failed,",
"Windows 2012 installation distro installed on RackHD server or equivalent",
"Node ID: \" + cls.__NODE) log.info_1(\" Node SKU: \" +",
"bootstrap workflows. The default case is running a minimum payload",
"\"<PASSWORD>\"}}} # if an external payload file is specified, use",
"self.__class__.__NODE)['json'] nodesku = fit_common.rackhdapi(nodeinfo.get('sku'))['json']['name'] log.info_1(\" Node ID: %s \", self.__class__.__NODE)",
"ID: \" + self.__class__.__NODE) log.info_1(\" Node SKU: \" + nodesku)",
"workflows for specified node result = fit_common.cancel_active_workflows(cls.__NODE) assert (result is",
"workflow running log.info_1(\" InstanceID: \" + result['json']['instanceId']) workflowid = result['json']['instanceId']",
"started at time: \" + str(datetime.fromtimestamp(start_time))) while time.time() - start_time",
"field from the workflow response def findall(obj, key): if isinstance(obj,",
"else: # workflow failed with response code log.error(\" InstanceID: \"",
"\" + cls.__NODE) log.info_1(\" Node SKU: \" + nodesku) log.info_1(\"",
"Install workflow failed, see logs.\") if __name__ == '__main__': fit_common.unittest.main()",
"log.info_5(\"{} workflow status: {}\".format(result['json']['injectableName'], result['json']['status'])) fit_common.time.sleep(cycle) elif result['json']['status'] == 'succeeded':",
"self.__class__.__NODE + '/workflows', action='post', payload=PAYLOAD) if result['status'] == 201: #",
"Workflow failed at time: \" + str(datetime.fromtimestamp(end_time))) log.info_1(\" Workflow duration:",
"\"Graph.InstallWindowsServer\", \"options\": {\"defaults\": {\"version\": \"2012\", \"repo\": \"http://172.31.128.1:8080/repo/winpe\", \"smbRepo\": \"\\\\\\\\172.31.128.1\\\\windowsServer2012\", \"productkey\":",
"currently discovered\" # Select one node at random cls.__NODE =",
"result = fit_common.rackhdapi('/api/2.0/nodes/' + self.__class__.__NODE + '/workflows', action='post', payload=PAYLOAD) if",
"NOQA: unused import from nose.plugins.attrib import attr import fit_common import",
"True), \"There are still some active workflows running against the",
"== 201: # workflow running log.info_1(\" InstanceID: \" + result['json']['instanceId'])",
"# workflow running log.info_1(\" InstanceID: \" + result['json']['instanceId']) workflowid =",
"in configuration dir): {\"bootstrap-payload\": {\"name\": \"Graph.InstallWindowsServer\", \"options\": {\"defaults\": {\"version\": \"2012\",",
"payload file (installed in configuration dir): {\"bootstrap-payload\": {\"name\": \"Graph.InstallWindowsServer\", \"options\":",
"Ensure the compute node is powered on and reachable result",
"json.loads(result['text']) findall(res, \"error\") except: res = result['text'] log.error(\" Workflow failed:",
"specifiying it using the '-extra' argument. This test takes 30-45",
"waittime=3200, cycle=30): log.info_1(\" Workflow started at time: \" + str(datetime.fromtimestamp(start_time)))",
"Node ID: %s \", self.__class__.__NODE) log.info_1(\" Node SKU: %s \",",
"in obj: findall(item, key) else: pass # this routine polls",
"+ cls.__NODE + \"/catalogs/bmc\" mondata = fit_common.rackhdapi(monurl, action=\"get\") catalog =",
"Node ID: \" + self.__class__.__NODE) log.info_1(\" Node SKU: \" +",
"log.info_1(\" Payload: \" + fit_common.json.dumps(PAYLOAD)) # launch workflow workflowid =",
"+ self.__class__.__NODE) log.info_1(\" Node SKU: \" + nodesku) log.info_1(\" Graph",
"random import json import time from nosedep import depends from",
"specified by creating a payload file and specifiying it using",
"\" + result['text']) self.fail(\"Workflow failed with response code: \" +",
"polls a workflow task ID for completion def wait_for_workflow_complete(instanceid, start_time,",
"\"smbPassword\": \"<PASSWORD>\"}}} # if an external payload file is specified,",
"res = json.loads(result['text']) findall(res, \"error\") except: res = result['text'] log.error(\"",
"list): for item in obj: findall(item, key) else: pass #",
"nodeinfo = fit_common.rackhdapi('/api/2.0/nodes/' + cls.__NODE)['json'] nodesku = fit_common.rackhdapi(nodeinfo.get('sku'))['json']['name'] monurl =",
"result['text']) self.fail(\"Workflow failed with response code: \" + result['status']) self.assertTrue(wait_for_workflow_complete(workflowid,",
"are no nodes currently discovered\" # Select one node at",
"result['status'] != 200: log.error(\" HTTP error: \" + result['text']) return",
"+ result['text']) return False if result['json']['status'] in ['running', 'pending']: log.info_5(\"{}",
"node result = fit_common.cancel_active_workflows(cls.__NODE) assert (result is True), \"There are",
"# Log node data nodeinfo = fit_common.rackhdapi('/api/2.0/nodes/' + self.__class__.__NODE)['json'] nodesku",
"configuration of the RackHD server: - A customized WinPE environment",
"Node SKU: \" + nodesku) log.info_1(\" Node BMC Mac: %s\",",
"waittime: # limit test to waittime seconds result = fit_common.rackhdapi(\"/api/2.0/workflows/\"",
"\" + nodesku) log.info_1(\" Graph Name: Graph.InstallWindowsServer\") log.info_1(\" Payload: \"",
"payload file. ''' import fit_path # NOQA: unused import from"
] |
[
"= random.randint(lowerLimit, upperLimit) text = render_template('random_number', lowerLimit=lowerLimit, upperLimit=upperLimit, number=number) return",
"@ask.intent('RandomNumber', convert={'lowerLimit': int, 'upperLimit': int}) def hello(lowerLimit, upperLimit): if lowerLimit",
"Ask, statement import random app = Flask(__name__) ask = Ask(app,",
"== None: upperLimit = 100 number = random.randint(lowerLimit, upperLimit) text",
"None: upperLimit = 100 number = random.randint(lowerLimit, upperLimit) text =",
"import random app = Flask(__name__) ask = Ask(app, '/') @ask.intent('RandomNumber',",
"upperLimit = 100 number = random.randint(lowerLimit, upperLimit) text = render_template('random_number',",
"from flask import Flask, render_template from flask_ask import Ask, statement",
"int, 'upperLimit': int}) def hello(lowerLimit, upperLimit): if lowerLimit == None:",
"random app = Flask(__name__) ask = Ask(app, '/') @ask.intent('RandomNumber', convert={'lowerLimit':",
"Ask(app, '/') @ask.intent('RandomNumber', convert={'lowerLimit': int, 'upperLimit': int}) def hello(lowerLimit, upperLimit):",
"= Flask(__name__) ask = Ask(app, '/') @ask.intent('RandomNumber', convert={'lowerLimit': int, 'upperLimit':",
"text = render_template('random_number', lowerLimit=lowerLimit, upperLimit=upperLimit, number=number) return statement(text).simple_card('Flask-Ask Random Number',",
"lowerLimit = 0 if upperLimit == None: upperLimit = 100",
"== None: lowerLimit = 0 if upperLimit == None: upperLimit",
"= Ask(app, '/') @ask.intent('RandomNumber', convert={'lowerLimit': int, 'upperLimit': int}) def hello(lowerLimit,",
"hello(lowerLimit, upperLimit): if lowerLimit == None: lowerLimit = 0 if",
"statement import random app = Flask(__name__) ask = Ask(app, '/')",
"number = random.randint(lowerLimit, upperLimit) text = render_template('random_number', lowerLimit=lowerLimit, upperLimit=upperLimit, number=number)",
"int}) def hello(lowerLimit, upperLimit): if lowerLimit == None: lowerLimit =",
"lowerLimit == None: lowerLimit = 0 if upperLimit == None:",
"number=number) return statement(text).simple_card('Flask-Ask Random Number', text) if __name__ == '__main__':",
"'upperLimit': int}) def hello(lowerLimit, upperLimit): if lowerLimit == None: lowerLimit",
"None: lowerLimit = 0 if upperLimit == None: upperLimit =",
"if lowerLimit == None: lowerLimit = 0 if upperLimit ==",
"random.randint(lowerLimit, upperLimit) text = render_template('random_number', lowerLimit=lowerLimit, upperLimit=upperLimit, number=number) return statement(text).simple_card('Flask-Ask",
"if upperLimit == None: upperLimit = 100 number = random.randint(lowerLimit,",
"app = Flask(__name__) ask = Ask(app, '/') @ask.intent('RandomNumber', convert={'lowerLimit': int,",
"return statement(text).simple_card('Flask-Ask Random Number', text) if __name__ == '__main__': app.run(debug=True)",
"upperLimit == None: upperLimit = 100 number = random.randint(lowerLimit, upperLimit)",
"import Ask, statement import random app = Flask(__name__) ask =",
"100 number = random.randint(lowerLimit, upperLimit) text = render_template('random_number', lowerLimit=lowerLimit, upperLimit=upperLimit,",
"0 if upperLimit == None: upperLimit = 100 number =",
"render_template('random_number', lowerLimit=lowerLimit, upperLimit=upperLimit, number=number) return statement(text).simple_card('Flask-Ask Random Number', text) if",
"= 100 number = random.randint(lowerLimit, upperLimit) text = render_template('random_number', lowerLimit=lowerLimit,",
"upperLimit=upperLimit, number=number) return statement(text).simple_card('Flask-Ask Random Number', text) if __name__ ==",
"= 0 if upperLimit == None: upperLimit = 100 number",
"convert={'lowerLimit': int, 'upperLimit': int}) def hello(lowerLimit, upperLimit): if lowerLimit ==",
"import Flask, render_template from flask_ask import Ask, statement import random",
"flask_ask import Ask, statement import random app = Flask(__name__) ask",
"def hello(lowerLimit, upperLimit): if lowerLimit == None: lowerLimit = 0",
"ask = Ask(app, '/') @ask.intent('RandomNumber', convert={'lowerLimit': int, 'upperLimit': int}) def",
"lowerLimit=lowerLimit, upperLimit=upperLimit, number=number) return statement(text).simple_card('Flask-Ask Random Number', text) if __name__",
"= render_template('random_number', lowerLimit=lowerLimit, upperLimit=upperLimit, number=number) return statement(text).simple_card('Flask-Ask Random Number', text)",
"'/') @ask.intent('RandomNumber', convert={'lowerLimit': int, 'upperLimit': int}) def hello(lowerLimit, upperLimit): if",
"render_template from flask_ask import Ask, statement import random app =",
"upperLimit) text = render_template('random_number', lowerLimit=lowerLimit, upperLimit=upperLimit, number=number) return statement(text).simple_card('Flask-Ask Random",
"flask import Flask, render_template from flask_ask import Ask, statement import",
"upperLimit): if lowerLimit == None: lowerLimit = 0 if upperLimit",
"Flask, render_template from flask_ask import Ask, statement import random app",
"from flask_ask import Ask, statement import random app = Flask(__name__)",
"Flask(__name__) ask = Ask(app, '/') @ask.intent('RandomNumber', convert={'lowerLimit': int, 'upperLimit': int})"
] |
[
"def forward(self, img0, img1): img0 = self.transform(self.rgb2gray(img0)) img1 = self.transform(self.rgb2gray(img1))",
"0) sobel_stack_x = F.conv2d(img_stack, self.kernelX, padding=1) sobel_stack_y = F.conv2d(img_stack, self.kernelY,",
"else: raise ValueError('') return y def gradient_xy(img): gx = img[:,",
"if weight_type == 'gauss': y = x ** 2 elif",
"torch.exp(-torch.mean(weight_fn(constant * img0_gx), 1, keepdim=True)) img0_wy = torch.exp(-torch.mean(weight_fn(constant * img0_gy),",
"transf_norm = transf / torch.sqrt(0.81 + transf**2) return transf_norm def",
"torch.exp(-torch.mean(weight_fn(constant * img1_gx), 1, keepdim=True)) img1_wy = torch.exp(-torch.mean(weight_fn(constant * img1_gy),",
"img_tea, flow_tea): loss_distill = 0 # Ws[0]: weight of teacher",
"weights. # Set Ws[1] to 0 to disable student ->",
"= F.conv2d(img_stack, self.kernelY, padding=1) pred_X, gt_X = sobel_stack_x[:N*C], sobel_stack_x[N*C:] pred_Y,",
"__init__(self, data_mean, data_std, data_range=1, norm=True): c = len(data_mean) super(MeanShift, self).__init__(c,",
"sum of the distillation losses at 2 directions. loss_distill +=",
"data_range=1, norm=True): c = len(data_mean) super(MeanShift, self).__init__(c, c, kernel_size=1) std",
"gradients along x, y axes, respectively. # flow_gx, flow_gy have",
"to disable student -> teacher. Ws = [1, 0.5] use_lap_loss",
"student and teacher, and calculate the distillation loss again. img_stu,",
"def edge_aware_smoothness_order1(img0, img1, flow, constant=1.0, weight_type='exp', error_type='L1'): def weight_fn(x): if",
"weights_y = gradweight_xy(img0, img1) smoothness_x = error_fn(flow_gx) * weights_x smoothness_y",
"loss_map = (loss_map.sum(1, True) + 1e-6) ** 0.5 return (loss_map",
"[2, 7, 12, 21, 30] weights = [1.0/2.6, 1.0/4.8, 1.0/3.7,",
"W), gt.reshape(N*C, 1, H, W)], 0) sobel_stack_x = F.conv2d(img_stack, self.kernelX,",
"i in range(indices[-1]): X = self.vgg_pretrained_features[i](X) Y = self.vgg_pretrained_features[i](Y) if",
"transf = patches - img transf_norm = transf / torch.sqrt(0.81",
"torchvision.models as models from model.laplacian import LapLoss device = torch.device(\"cuda\"",
"for i in range(2): student_error = loss_fun(img_stu, mid_gt).mean(1, True) teacher_error",
"= [1, 0.5] use_lap_loss = False # Laplacian loss performs",
"to perform better than 'gauss'. def edge_aware_smoothness_order1(img0, img1, flow, constant=1.0,",
"respectively. weights_x = torch.cat([img1_wx, img1_wx, img0_wx, img0_wx], dim=1) weights_y =",
"EPE(nn.Module): def __init__(self): super(EPE, self).__init__() def forward(self, flow, gt, loss_mask):",
"= (loss_map.sum(1, True) + 1e-6) ** 0.5 return (loss_map *",
"forward(self, img0, img1): img0 = self.transform(self.rgb2gray(img0)) img1 = self.transform(self.rgb2gray(img1)) return",
"else: self.weight.data.mul_(std.view(c, 1, 1, 1)) self.bias.data = data_range * torch.Tensor(data_mean)",
"param.requires_grad = False def forward(self, X, Y, indices=None): X =",
"img_stu, flow_stu # The distillation loss from the student to",
"= [2, 7, 12, 21, 30] weights = [1.0/2.6, 1.0/4.8,",
"gradient_xy(img1) img0_wx = torch.exp(-torch.mean(weight_fn(constant * img0_gx), 1, keepdim=True)) img0_wy =",
"dy2 = gradient(dy) smooth_loss = dx.abs().mean() + dy.abs().mean() + dx2.abs().mean()",
"else: loss_fun = nn.L1Loss(reduction='none') for i in range(2): student_error =",
"of student -> teacher. # Two directions could take different",
"https://github.com/coolbeam/OIFlow/blob/main/utils/tools.py # weight_type='exp' seems to perform better than 'gauss'. def",
"dy = gradient(flow) # dx2, dxdy = gradient(dx) # dydx,",
"g, b = rgb[:, 0:1, :, :], rgb[:, 1:2, :,",
"losses at 2 directions. loss_distill += Ws[i] * ((flow_tea.detach() -",
"reduction='none') else: loss_fun = nn.L1Loss(reduction='none') for i in range(2): student_error",
":, :-1] return D_dx, D_dy dx, dy = gradient(flow) #",
"use them to teach the student. distill_mask = (student_error >",
"dy.abs().mean() + dx2.abs().mean() + dxdy.abs().mean() + dydx.abs().mean() + dy2.abs().mean() else:",
"def valid_mask(self, t, padding): n, _, h, w = t.size()",
"torch.abs(x) else: raise ValueError('') return y def gradient_xy(img): gx =",
"mid_gt).mean(1, True) teacher_error = loss_fun(img_tea, mid_gt).mean(1, True) # distill_mask indicates",
"+ 0.01).float().detach() # loss_distill is the sum of the distillation",
"distillation loss from the student to the teacher is given",
"smaller weight. # loss_distill = loss_distill / 2 return loss_distill",
"more accurate, and use them to teach the student. distill_mask",
"self.kernelX.unsqueeze(0).unsqueeze(0).to(device) self.kernelY = self.kernelY.unsqueeze(0).unsqueeze(0).to(device) def forward(self, pred, gt): N, C,",
":, 1:, :] return gx, gy def gradweight_xy(img0, img1): img0_gx,",
"* img1_gy), 1, keepdim=True)) # First two flow channels: 1->0",
"transform(self, img): patches = F.conv2d(img, self.w, padding=3, bias=None) transf =",
"weights_x, weights_y = gradweight_xy(img0, img1) smoothness_x = error_fn(flow_gx) * weights_x",
"from the student to the teacher is given a smaller",
"teach the student. distill_mask = (student_error > teacher_error + 0.01).float().detach()",
"- img[:, :, 1:, :] return gx, gy def gradweight_xy(img0,",
"+ 1e-6) ** 0.5 return (loss_map * loss_mask) class Ternary(nn.Module):",
"1, keepdim=True)) img1_wx = torch.exp(-torch.mean(weight_fn(constant * img1_gx), 1, keepdim=True)) img1_wy",
"0.1140 * b return gray def hamming(self, t1, t2): dist",
"x, y axes, respectively. # flow_gx, flow_gy have the same",
"image of the teacher is better than the student, #",
"dydx.abs().mean() + dy2.abs().mean() else: smooth_loss = dx.abs().mean() + dy.abs().mean() #",
"forward(self, flow, gt, loss_mask): loss_map = (flow - gt.detach()) **",
"** 2 dist_norm = torch.mean(dist / (0.1 + dist), 1,",
"class VGGPerceptualLoss(torch.nn.Module): def __init__(self, rank=0): super(VGGPerceptualLoss, self).__init__() blocks = []",
"are more accurate, and use them to teach the student.",
"= self.kernelX.unsqueeze(0).unsqueeze(0).to(device) self.kernelY = self.kernelY.unsqueeze(0).unsqueeze(0).to(device) def forward(self, pred, gt): N,",
"weight. # loss_distill = loss_distill / 2 return loss_distill if",
"dxdy = gradient(dx) dydx, dy2 = gradient(dy) smooth_loss = dx.abs().mean()",
"0.1 k += 1 return loss # flow could have",
"loss_map = (flow - gt.detach()) ** 2 loss_map = (loss_map.sum(1,",
"- Y.detach()).abs().mean() * 0.1 k += 1 return loss #",
"Swap student and teacher, and calculate the distillation loss again.",
"return loss_distill if __name__ == '__main__': img0 = torch.zeros(3, 3,",
"models from model.laplacian import LapLoss device = torch.device(\"cuda\" if torch.cuda.is_available()",
"np.transpose(self.w, (3, 2, 0, 1)) self.w = torch.tensor(self.w).float().to(device) def transform(self,",
"= [1.0/2.6, 1.0/4.8, 1.0/3.7, 1.0/5.6, 10/1.5] k = 0 loss",
"pred.shape[3] img_stack = torch.cat( [pred.reshape(N*C, 1, H, W), gt.reshape(N*C, 1,",
"take different weights. # Set Ws[1] to 0 to disable",
"have 4 channels, same as flow_gx and flow_gy (if the",
"self.w = np.transpose(self.w, (3, 2, 0, 1)) self.w = torch.tensor(self.w).float().to(device)",
"dist = (t1 - t2) ** 2 dist_norm = torch.mean(dist",
"return loss class MeanShift(nn.Conv2d): def __init__(self, data_mean, data_std, data_range=1, norm=True):",
"data_range * torch.Tensor(data_mean) self.bias.data.div_(std) else: self.weight.data.mul_(std.view(c, 1, 1, 1)) self.bias.data",
"else: smooth_loss = dx.abs().mean() + dy.abs().mean() # smooth_loss = dx.abs().mean()",
"elif weight_type == 'exp': y = torch.abs(x) else: raise ValueError('')",
"(i+1) in indices: loss += weights[k] * (X - Y.detach()).abs().mean()",
"dist_norm = torch.mean(dist / (0.1 + dist), 1, True) return",
"# https://github.com/coolbeam/OIFlow/blob/main/utils/tools.py def flow_smooth_delta(flow, if_second_order=False): def gradient(x): D_dx = x[:,",
"= torch.cat([img1_wy, img0_wy, img0_wy, img1_wy], dim=1) return weights_x, weights_y def",
"# distill_mask indicates where the warped images according to student's",
"points, the warped image of the teacher is better than",
"(X - Y.detach()).abs().mean() * 0.1 k += 1 return loss",
"return weights_x, weights_y def error_fn(x): if error_type == 'L1': y",
"= F.conv2d(img, self.w, padding=3, bias=None) transf = patches - img",
"is given a smaller weight. # loss_distill = loss_distill /",
"= sobel_stack_y[:N*C], sobel_stack_y[N*C:] L1X, L1Y = torch.abs(pred_X-gt_X), torch.abs(pred_Y-gt_Y) loss =",
"= img[:, :, :, :-1] - img[:, :, :, 1:]",
"1, 1, 1)) self.bias.data = -1 * data_range * torch.Tensor(data_mean)",
"weights = [1.0/2.6, 1.0/4.8, 1.0/3.7, 1.0/5.6, 10/1.5] k = 0",
"self.kernelX = self.kernelX.unsqueeze(0).unsqueeze(0).to(device) self.kernelY = self.kernelY.unsqueeze(0).unsqueeze(0).to(device) def forward(self, pred, gt):",
"directions. loss_distill += Ws[i] * ((flow_tea.detach() - flow_stu).abs() * distill_mask).mean()",
"dy2.abs().mean() else: smooth_loss = dx.abs().mean() + dy.abs().mean() # smooth_loss =",
"it should be smooth along both x and y axes.",
"[1.0/2.6, 1.0/4.8, 1.0/3.7, 1.0/5.6, 10/1.5] k = 0 loss =",
"return gx, gy def gradweight_xy(img0, img1): img0_gx, img0_gy = gradient_xy(img0)",
"b = rgb[:, 0:1, :, :], rgb[:, 1:2, :, :],",
"= self.vgg_pretrained_features[i](Y) if (i+1) in indices: loss += weights[k] *",
"n, _, h, w = t.size() inner = torch.ones(n, 1,",
"0, -1], [2, 0, -2], [1, 0, -1], ]).float() self.kernelY",
"(patch_size, patch_size, 1, out_channels)) self.w = np.transpose(self.w, (3, 2, 0,",
"loss = (L1X+L1Y) return loss class MeanShift(nn.Conv2d): def __init__(self, data_mean,",
"1->0 flow. So use img1 weights. # Second two flow",
"= gradient_xy(flow) # weights_x, weights_y both have 4 channels, same",
"** 2 loss_map = (loss_map.sum(1, True) + 1e-6) ** 0.5",
"y-flow should also be smooth along x-axis, and x-flow should",
"- x[:, :, :, :-1] D_dy = x[:, :, 1:]",
"a smaller weight. # loss_distill = loss_distill / 2 return",
"data_mean, data_std, data_range=1, norm=True): c = len(data_mean) super(MeanShift, self).__init__(c, c,",
"hamming(self, t1, t2): dist = (t1 - t2) ** 2",
"c, 1, 1) if norm: self.weight.data.div_(std.view(c, 1, 1, 1)) self.bias.data",
"dx2.abs().mean() + dxdy.abs().mean() + dydx.abs().mean() + dy2.abs().mean() else: smooth_loss =",
"gradient_xy(img): gx = img[:, :, :, :-1] - img[:, :,",
"smooth_loss = dx.abs().mean() + dy.abs().mean() # + dx2.abs().mean() + dxdy.abs().mean()",
"same as flow_gx and flow_gy (if the input flow has",
"img1_wy], dim=1) return weights_x, weights_y def error_fn(x): if error_type ==",
"self.kernelX = torch.tensor([ [1, 0, -1], [2, 0, -2], [1,",
"error_fn(flow_gx) * weights_x smoothness_y = error_fn(flow_gy) * weights_y return torch.mean(smoothness_x)",
"the student, # then regard the flow at these points",
"dxdy.abs().mean() + dydx.abs().mean() + dy2.abs().mean() # 暂时不上二阶的平滑损失,似乎加上以后就太猛了,无法降低photo loss TODO return",
"# 暂时不上二阶的平滑损失,似乎加上以后就太猛了,无法降低photo loss TODO return smooth_loss # flow should have",
"patch_size, 1, out_channels)) self.w = np.transpose(self.w, (3, 2, 0, 1))",
"along both x and y axes. # I.e., a y-flow",
"'exp': y = torch.abs(x) else: raise ValueError('') return y def",
"to 0 to disable student -> teacher. Ws = [1,",
"padding, w - 2 * padding).type_as(t) mask = F.pad(inner, [padding]",
"dist_norm def valid_mask(self, t, padding): n, _, h, w =",
"1 return loss # flow could have any channels. #",
"F import torchvision.models as models from model.laplacian import LapLoss device",
"weight of teacher -> student. # Ws[1]: weight of student",
"2, 0, 1)) self.w = torch.tensor(self.w).float().to(device) def transform(self, img): patches",
"1) class SOBEL(nn.Module): def __init__(self): super(SOBEL, self).__init__() self.kernelX = torch.tensor([",
"0.406], [0.229, 0.224, 0.225], norm=True).cuda() for param in self.parameters(): param.requires_grad",
"helps slightly. def dual_teaching_loss(mid_gt, img_stu, flow_stu, img_tea, flow_tea): loss_distill =",
"channels as flow. # No matter the flow is x-",
"= 0 for i in range(indices[-1]): X = self.vgg_pretrained_features[i](X) Y",
"torch.sqrt(0.81 + transf**2) return transf_norm def rgb2gray(self, rgb): r, g,",
"# weight_type='exp' seems to perform better than 'gauss'. def edge_aware_smoothness_order1(img0,",
"flow_gx, flow_gy have the same number of channels as flow.",
"the same number of channels as flow. # No matter",
"def error_fn(x): if error_type == 'L1': y = torch.abs(x) elif",
"weights_y return torch.mean(smoothness_x) + torch.mean(smoothness_y) # Dual teaching helps slightly.",
"could take different weights. # Set Ws[1] to 0 to",
"def __init__(self, rank=0): super(VGGPerceptualLoss, self).__init__() blocks = [] pretrained =",
"img1_wy = torch.exp(-torch.mean(weight_fn(constant * img1_gy), 1, keepdim=True)) # First two",
"# Dual teaching helps slightly. def dual_teaching_loss(mid_gt, img_stu, flow_stu, img_tea,",
"to student's prediction # is worse than that of the",
"256).float().to(device) img1 = torch.tensor(np.random.normal( 0, 1, (3, 3, 256, 256))).float().to(device)",
"torch.mean(smoothness_x) + torch.mean(smoothness_y) # Dual teaching helps slightly. def dual_teaching_loss(mid_gt,",
"loss_distill / 2 return loss_distill if __name__ == '__main__': img0",
":-1, :] - img[:, :, 1:, :] return gx, gy",
"out_channels = patch_size * patch_size self.w = np.eye(out_channels).reshape( (patch_size, patch_size,",
"F.conv2d(img, self.w, padding=3, bias=None) transf = patches - img transf_norm",
"weights_y are for x and y's spatial gradients, respectively. weights_x",
"= x ** 2 elif weight_type == 'exp': y =",
"keepdim=True)) img1_wy = torch.exp(-torch.mean(weight_fn(constant * img1_gy), 1, keepdim=True)) # First",
"1, 1)) self.bias.data = -1 * data_range * torch.Tensor(data_mean) self.bias.data.div_(std)",
"two flow channels: 0->1 flow. So use img0 weights. #",
"1, 1, 1)) self.bias.data = data_range * torch.Tensor(data_mean) self.requires_grad =",
":] gray = 0.2989 * r + 0.5870 * g",
"accurate, and use them to teach the student. distill_mask =",
"x- or y-flow, it should be smooth along both x",
"# loss_distill is the sum of the distillation losses at",
"D_dy = x[:, :, 1:] - x[:, :, :-1] return",
"= self.vgg_pretrained_features[i](X) Y = self.vgg_pretrained_features[i](Y) if (i+1) in indices: loss",
"self.w = torch.tensor(self.w).float().to(device) def transform(self, img): patches = F.conv2d(img, self.w,",
"Y = self.vgg_pretrained_features[i](Y) if (i+1) in indices: loss += weights[k]",
"img transf_norm = transf / torch.sqrt(0.81 + transf**2) return transf_norm",
"* self.valid_mask(img0, 1) class SOBEL(nn.Module): def __init__(self): super(SOBEL, self).__init__() self.kernelX",
"* img1_gx), 1, keepdim=True)) img1_wy = torch.exp(-torch.mean(weight_fn(constant * img1_gy), 1,",
"= (t1 - t2) ** 2 dist_norm = torch.mean(dist /",
"= gradweight_xy(img0, img1) smoothness_x = error_fn(flow_gx) * weights_x smoothness_y =",
"in later epochs. # Moreover, Laplacian loss is significantly slower.",
"1)) self.w = torch.tensor(self.w).float().to(device) def transform(self, img): patches = F.conv2d(img,",
"self.normalize = MeanShift([0.485, 0.456, 0.406], [0.229, 0.224, 0.225], norm=True).cuda() for",
"y def gradient_xy(img): gx = img[:, :, :, :-1] -",
"r + 0.5870 * g + 0.1140 * b return",
"= self.kernelX.clone().T self.kernelX = self.kernelX.unsqueeze(0).unsqueeze(0).to(device) self.kernelY = self.kernelY.unsqueeze(0).unsqueeze(0).to(device) def forward(self,",
"student. # Ws[1]: weight of student -> teacher. # Two",
"earlier epochs, but worse in later epochs. # Moreover, Laplacian",
"D_dy dx, dy = gradient(flow) # dx2, dxdy = gradient(dx)",
"= (torch.abs(x) + 0.01).pow(0.4) else: raise ValueError('') return y #",
"# Ws[1]: weight of student -> teacher. # Two directions",
"as F import torchvision.models as models from model.laplacian import LapLoss",
"smoothness_y = error_fn(flow_gy) * weights_y return torch.mean(smoothness_x) + torch.mean(smoothness_y) #",
"performs better in earlier epochs, but worse in later epochs.",
"teacher. Ws = [1, 0.5] use_lap_loss = False # Laplacian",
"ValueError('') return y def gradient_xy(img): gx = img[:, :, :,",
"indicates where the warped images according to student's prediction #",
"[2, 0, -2], [1, 0, -1], ]).float() self.kernelY = self.kernelX.clone().T",
"def rgb2gray(self, rgb): r, g, b = rgb[:, 0:1, :,",
":], rgb[:, 2:3, :, :] gray = 0.2989 * r",
"-2], [1, 0, -1], ]).float() self.kernelY = self.kernelX.clone().T self.kernelX =",
"sobel_stack_y = F.conv2d(img_stack, self.kernelY, padding=1) pred_X, gt_X = sobel_stack_x[:N*C], sobel_stack_x[N*C:]",
"img0_wy, img1_wy], dim=1) return weights_x, weights_y def error_fn(x): if error_type",
"of the distillation losses at 2 directions. loss_distill += Ws[i]",
"class SOBEL(nn.Module): def __init__(self): super(SOBEL, self).__init__() self.kernelX = torch.tensor([ [1,",
"to the teacher is given a smaller weight. # loss_distill",
"along x-axis, and x-flow should also be smooth along y-axis.",
"should also be smooth along x-axis, and x-flow should also",
"rgb[:, 2:3, :, :] gray = 0.2989 * r +",
"self).__init__() def forward(self, flow, gt, loss_mask): loss_map = (flow -",
"# flow could have any channels. # https://github.com/coolbeam/OIFlow/blob/main/utils/tools.py def flow_smooth_delta(flow,",
"dydx, dy2 = gradient(dy) smooth_loss = dx.abs().mean() + dy.abs().mean() +",
"indices: loss += weights[k] * (X - Y.detach()).abs().mean() * 0.1",
"(torch.abs(x) + 0.01).pow(0.4) else: raise ValueError('') return y # The",
"loss TODO return smooth_loss # flow should have 4 channels.",
"where the warped images according to student's prediction # is",
"img_stu, flow_stu, img_tea, flow_tea): loss_distill = 0 # Ws[0]: weight",
"L1Y = torch.abs(pred_X-gt_X), torch.abs(pred_Y-gt_Y) loss = (L1X+L1Y) return loss class",
"Two directions could take different weights. # Set Ws[1] to",
"= -1 * data_range * torch.Tensor(data_mean) self.bias.data.div_(std) else: self.weight.data.mul_(std.view(c, 1,",
"W)], 0) sobel_stack_x = F.conv2d(img_stack, self.kernelX, padding=1) sobel_stack_y = F.conv2d(img_stack,",
"same number of channels as flow. # No matter the",
"loss_distill = 0 # Ws[0]: weight of teacher -> student.",
"student. distill_mask = (student_error > teacher_error + 0.01).float().detach() # loss_distill",
"teacher -> student. # Ws[1]: weight of student -> teacher.",
":, :, :-1] - img[:, :, :, 1:] gy =",
"# dx2, dxdy = gradient(dx) # dydx, dy2 = gradient(dy)",
"2 return loss_distill if __name__ == '__main__': img0 = torch.zeros(3,",
"VGGPerceptualLoss(torch.nn.Module): def __init__(self, rank=0): super(VGGPerceptualLoss, self).__init__() blocks = [] pretrained",
"if norm: self.weight.data.div_(std.view(c, 1, 1, 1)) self.bias.data = -1 *",
"+ dx2.abs().mean() + dxdy.abs().mean() + dydx.abs().mean() + dy2.abs().mean() # 暂时不上二阶的平滑损失,似乎加上以后就太猛了,无法降低photo",
"smooth_loss = dx.abs().mean() + dy.abs().mean() # smooth_loss = dx.abs().mean() +",
"perform better than 'gauss'. def edge_aware_smoothness_order1(img0, img1, flow, constant=1.0, weight_type='exp',",
"flow channels: 0->1 flow. So use img0 weights. # weights_x",
"# flow_gx, flow_gy have the same number of channels as",
"ValueError('') return y # The flow gradients along x, y",
"= False # Laplacian loss performs better in earlier epochs,",
"use img1 weights. # Second two flow channels: 0->1 flow.",
"points are more accurate, and use them to teach the",
"weights[k] * (X - Y.detach()).abs().mean() * 0.1 k += 1",
"better in earlier epochs, but worse in later epochs. #",
"= gradient(dy) if if_second_order: dx2, dxdy = gradient(dx) dydx, dy2",
"img0_wx], dim=1) weights_y = torch.cat([img1_wy, img0_wy, img0_wy, img1_wy], dim=1) return",
"pred.shape[2], pred.shape[3] img_stack = torch.cat( [pred.reshape(N*C, 1, H, W), gt.reshape(N*C,",
"return transf_norm def rgb2gray(self, rgb): r, g, b = rgb[:,",
"forward(self, pred, gt): N, C, H, W = pred.shape[0], pred.shape[1],",
":, :], rgb[:, 1:2, :, :], rgb[:, 2:3, :, :]",
":, :, 1:] - x[:, :, :, :-1] D_dy =",
"# weights_x and weights_y are for x and y's spatial",
"y's spatial gradients, respectively. weights_x = torch.cat([img1_wx, img1_wx, img0_wx, img0_wx],",
":], rgb[:, 1:2, :, :], rgb[:, 2:3, :, :] gray",
"torch.cuda.is_available() else \"cpu\") class EPE(nn.Module): def __init__(self): super(EPE, self).__init__() def",
"channels. # https://github.com/coolbeam/OIFlow/blob/main/utils/tools.py def flow_smooth_delta(flow, if_second_order=False): def gradient(x): D_dx =",
"student_error = loss_fun(img_stu, mid_gt).mean(1, True) teacher_error = loss_fun(img_tea, mid_gt).mean(1, True)",
"import numpy as np import torch.nn as nn import torch.nn.functional",
"pretrained = True self.vgg_pretrained_features = models.vgg19(pretrained=pretrained).features self.normalize = MeanShift([0.485, 0.456,",
"weights_x smoothness_y = error_fn(flow_gy) * weights_y return torch.mean(smoothness_x) + torch.mean(smoothness_y)",
"False def forward(self, X, Y, indices=None): X = self.normalize(X) Y",
"self.weight.data.div_(std.view(c, 1, 1, 1)) self.bias.data = -1 * data_range *",
"X = self.normalize(X) Y = self.normalize(Y) indices = [2, 7,",
"and weights_y are for x and y's spatial gradients, respectively.",
"or y-flow, it should be smooth along both x and",
"= nn.L1Loss(reduction='none') for i in range(2): student_error = loss_fun(img_stu, mid_gt).mean(1,",
"import LapLoss device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") class",
"raise ValueError('') return y # The flow gradients along x,",
"and use them to teach the student. distill_mask = (student_error",
"import torch.nn as nn import torch.nn.functional as F import torchvision.models",
"self.parameters(): param.requires_grad = False def forward(self, X, Y, indices=None): X",
"error_type == 'L1': y = torch.abs(x) elif error_type == 'abs_robust':",
"distill_mask = (student_error > teacher_error + 0.01).float().detach() # loss_distill is",
"mask def forward(self, img0, img1): img0 = self.transform(self.rgb2gray(img0)) img1 =",
"have any channels. # https://github.com/coolbeam/OIFlow/blob/main/utils/tools.py def flow_smooth_delta(flow, if_second_order=False): def gradient(x):",
"gt, loss_mask): loss_map = (flow - gt.detach()) ** 2 loss_map",
"data_range * torch.Tensor(data_mean) self.requires_grad = False class VGGPerceptualLoss(torch.nn.Module): def __init__(self,",
"warped image of the teacher is better than the student,",
"and y's spatial gradients, respectively. weights_x = torch.cat([img1_wx, img1_wx, img0_wx,",
"# is worse than that of the teacher. # If",
"in range(indices[-1]): X = self.vgg_pretrained_features[i](X) Y = self.vgg_pretrained_features[i](Y) if (i+1)",
"# Two directions could take different weights. # Set Ws[1]",
"patches - img transf_norm = transf / torch.sqrt(0.81 + transf**2)",
"gradient(x): D_dx = x[:, :, :, 1:] - x[:, :,",
"data_std, data_range=1, norm=True): c = len(data_mean) super(MeanShift, self).__init__(c, c, kernel_size=1)",
"transf_norm def rgb2gray(self, rgb): r, g, b = rgb[:, 0:1,",
"transf / torch.sqrt(0.81 + transf**2) return transf_norm def rgb2gray(self, rgb):",
"= torch.ones(n, 1, h - 2 * padding, w -",
"also be smooth along y-axis. flow_gx, flow_gy = gradient_xy(flow) #",
"Laplacian loss is significantly slower. if use_lap_loss: loss_fun = LapLoss(max_levels=3,",
"y # The flow gradients along x, y axes, respectively.",
"for param in self.parameters(): param.requires_grad = False def forward(self, X,",
"== 'gauss': y = x ** 2 elif weight_type ==",
"matter the flow is x- or y-flow, it should be",
"constant=1.0, weight_type='exp', error_type='L1'): def weight_fn(x): if weight_type == 'gauss': y",
"prediction # is worse than that of the teacher. #",
"loss from the student to the teacher is given a",
"flow should have 4 channels. # https://github.com/coolbeam/OIFlow/blob/main/utils/tools.py # weight_type='exp' seems",
"if if_second_order: dx2, dxdy = gradient(dx) dydx, dy2 = gradient(dy)",
"True) return dist_norm def valid_mask(self, t, padding): n, _, h,",
"0, 1)) self.w = torch.tensor(self.w).float().to(device) def transform(self, img): patches =",
"0 for i in range(indices[-1]): X = self.vgg_pretrained_features[i](X) Y =",
"== 'L1': y = torch.abs(x) elif error_type == 'abs_robust': y",
"student, # then regard the flow at these points are",
"in earlier epochs, but worse in later epochs. # Moreover,",
"# I.e., a y-flow should also be smooth along x-axis,",
"* ((flow_tea.detach() - flow_stu).abs() * distill_mask).mean() # Swap student and",
"]).float() self.kernelY = self.kernelX.clone().T self.kernelX = self.kernelX.unsqueeze(0).unsqueeze(0).to(device) self.kernelY = self.kernelY.unsqueeze(0).unsqueeze(0).to(device)",
"import torch import numpy as np import torch.nn as nn",
"0 loss = 0 for i in range(indices[-1]): X =",
"1, 1) if norm: self.weight.data.div_(std.view(c, 1, 1, 1)) self.bias.data =",
"1, h - 2 * padding, w - 2 *",
"self.kernelX, padding=1) sobel_stack_y = F.conv2d(img_stack, self.kernelY, padding=1) pred_X, gt_X =",
":, 1:] - x[:, :, :-1] return D_dx, D_dy dx,",
"The flow gradients along x, y axes, respectively. # flow_gx,",
"+ 0.5870 * g + 0.1140 * b return gray",
"as models from model.laplacian import LapLoss device = torch.device(\"cuda\" if",
"loss class MeanShift(nn.Conv2d): def __init__(self, data_mean, data_std, data_range=1, norm=True): c",
"axes, respectively. # flow_gx, flow_gy have the same number of",
"loss_fun = nn.L1Loss(reduction='none') for i in range(2): student_error = loss_fun(img_stu,",
"img[:, :, :-1, :] - img[:, :, 1:, :] return",
"rgb[:, 0:1, :, :], rgb[:, 1:2, :, :], rgb[:, 2:3,",
"also be smooth along x-axis, and x-flow should also be",
"4 channels). weights_x, weights_y = gradweight_xy(img0, img1) smoothness_x = error_fn(flow_gx)",
"1, True) return dist_norm def valid_mask(self, t, padding): n, _,",
"dx, dy = gradient(flow) # dx2, dxdy = gradient(dx) #",
"[1, 0.5] use_lap_loss = False # Laplacian loss performs better",
"# Swap student and teacher, and calculate the distillation loss",
"= 7 out_channels = patch_size * patch_size self.w = np.eye(out_channels).reshape(",
"edge_aware_smoothness_order1(img0, img1, flow, constant=1.0, weight_type='exp', error_type='L1'): def weight_fn(x): if weight_type",
"def forward(self, X, Y, indices=None): X = self.normalize(X) Y =",
"So use img0 weights. # weights_x and weights_y are for",
"are for x and y's spatial gradients, respectively. weights_x =",
"loss_fun(img_stu, mid_gt).mean(1, True) teacher_error = loss_fun(img_tea, mid_gt).mean(1, True) # distill_mask",
"of channels as flow. # No matter the flow is",
"self).__init__() patch_size = 7 out_channels = patch_size * patch_size self.w",
"super(VGGPerceptualLoss, self).__init__() blocks = [] pretrained = True self.vgg_pretrained_features =",
"= torch.abs(x) else: raise ValueError('') return y def gradient_xy(img): gx",
"could have any channels. # https://github.com/coolbeam/OIFlow/blob/main/utils/tools.py def flow_smooth_delta(flow, if_second_order=False): def",
"* (X - Y.detach()).abs().mean() * 0.1 k += 1 return",
"= torch.tensor([ [1, 0, -1], [2, 0, -2], [1, 0,",
"y = torch.abs(x) else: raise ValueError('') return y def gradient_xy(img):",
"= [] pretrained = True self.vgg_pretrained_features = models.vgg19(pretrained=pretrained).features self.normalize =",
"t2) ** 2 dist_norm = torch.mean(dist / (0.1 + dist),",
"- flow_stu).abs() * distill_mask).mean() # Swap student and teacher, and",
"class MeanShift(nn.Conv2d): def __init__(self, data_mean, data_std, data_range=1, norm=True): c =",
"given a smaller weight. # loss_distill = loss_distill / 2",
"Ws[1]: weight of student -> teacher. # Two directions could",
"be smooth along both x and y axes. # I.e.,",
"= F.pad(inner, [padding] * 4) return mask def forward(self, img0,",
"flow_stu # The distillation loss from the student to the",
"== 'exp': y = torch.abs(x) else: raise ValueError('') return y",
"return gray def hamming(self, t1, t2): dist = (t1 -",
"+ transf**2) return transf_norm def rgb2gray(self, rgb): r, g, b",
"gt.detach()) ** 2 loss_map = (loss_map.sum(1, True) + 1e-6) **",
"def gradient_xy(img): gx = img[:, :, :, :-1] - img[:,",
"loss_distill = loss_distill / 2 return loss_distill if __name__ ==",
"gradients, respectively. weights_x = torch.cat([img1_wx, img1_wx, img0_wx, img0_wx], dim=1) weights_y",
"= dx.abs().mean() + dy.abs().mean() # + dx2.abs().mean() + dxdy.abs().mean() +",
"loss_fun(img_tea, mid_gt).mean(1, True) # distill_mask indicates where the warped images",
"True self.vgg_pretrained_features = models.vgg19(pretrained=pretrained).features self.normalize = MeanShift([0.485, 0.456, 0.406], [0.229,",
"# weights_x, weights_y both have 4 channels, same as flow_gx",
"= gradient_xy(img1) img0_wx = torch.exp(-torch.mean(weight_fn(constant * img0_gx), 1, keepdim=True)) img0_wy",
":, 1:] - x[:, :, :, :-1] D_dy = x[:,",
"sobel_stack_x[N*C:] pred_Y, gt_Y = sobel_stack_y[:N*C], sobel_stack_y[N*C:] L1X, L1Y = torch.abs(pred_X-gt_X),",
"rgb2gray(self, rgb): r, g, b = rgb[:, 0:1, :, :],",
"then regard the flow at these points are more accurate,",
"return dist_norm def valid_mask(self, t, padding): n, _, h, w",
"weights_x, weights_y def error_fn(x): if error_type == 'L1': y =",
"/ (0.1 + dist), 1, True) return dist_norm def valid_mask(self,",
"= sobel_stack_x[:N*C], sobel_stack_x[N*C:] pred_Y, gt_Y = sobel_stack_y[:N*C], sobel_stack_y[N*C:] L1X, L1Y",
"False class VGGPerceptualLoss(torch.nn.Module): def __init__(self, rank=0): super(VGGPerceptualLoss, self).__init__() blocks =",
":, :, 1:] gy = img[:, :, :-1, :] -",
"torch.mean(smoothness_y) # Dual teaching helps slightly. def dual_teaching_loss(mid_gt, img_stu, flow_stu,",
"= transf / torch.sqrt(0.81 + transf**2) return transf_norm def rgb2gray(self,",
"1:, :] return gx, gy def gradweight_xy(img0, img1): img0_gx, img0_gy",
"dy2.abs().mean() # 暂时不上二阶的平滑损失,似乎加上以后就太猛了,无法降低photo loss TODO return smooth_loss # flow should",
"+ dy2.abs().mean() else: smooth_loss = dx.abs().mean() + dy.abs().mean() # smooth_loss",
"Ws[1] to 0 to disable student -> teacher. Ws =",
"D_dx, D_dy dx, dy = gradient(flow) # dx2, dxdy =",
"+= Ws[i] * ((flow_tea.detach() - flow_stu).abs() * distill_mask).mean() # Swap",
"dx2, dxdy = gradient(dx) dydx, dy2 = gradient(dy) smooth_loss =",
"# https://github.com/coolbeam/OIFlow/blob/main/utils/tools.py # weight_type='exp' seems to perform better than 'gauss'.",
"img1_wx = torch.exp(-torch.mean(weight_fn(constant * img1_gx), 1, keepdim=True)) img1_wy = torch.exp(-torch.mean(weight_fn(constant",
"at these points are more accurate, and use them to",
"= self.normalize(Y) indices = [2, 7, 12, 21, 30] weights",
"+ dx2.abs().mean() + dxdy.abs().mean() + dydx.abs().mean() + dy2.abs().mean() else: smooth_loss",
"norm=True).cuda() for param in self.parameters(): param.requires_grad = False def forward(self,",
"at some points, the warped image of the teacher is",
"dual_teaching_loss(mid_gt, img_stu, flow_stu, img_tea, flow_tea): loss_distill = 0 # Ws[0]:",
"= x[:, :, :, 1:] - x[:, :, :, :-1]",
"range(indices[-1]): X = self.vgg_pretrained_features[i](X) Y = self.vgg_pretrained_features[i](Y) if (i+1) in",
"1.0/4.8, 1.0/3.7, 1.0/5.6, 10/1.5] k = 0 loss = 0",
"+ dy.abs().mean() + dx2.abs().mean() + dxdy.abs().mean() + dydx.abs().mean() + dy2.abs().mean()",
"# Set Ws[1] to 0 to disable student -> teacher.",
"distill_mask).mean() # Swap student and teacher, and calculate the distillation",
"h - 2 * padding, w - 2 * padding).type_as(t)",
"H, W)], 0) sobel_stack_x = F.conv2d(img_stack, self.kernelX, padding=1) sobel_stack_y =",
"flow, constant=1.0, weight_type='exp', error_type='L1'): def weight_fn(x): if weight_type == 'gauss':",
"# Second two flow channels: 0->1 flow. So use img0",
"of the teacher is better than the student, # then",
"sobel_stack_x[:N*C], sobel_stack_x[N*C:] pred_Y, gt_Y = sobel_stack_y[:N*C], sobel_stack_y[N*C:] L1X, L1Y =",
"= gradient(dy) smooth_loss = dx.abs().mean() + dy.abs().mean() + dx2.abs().mean() +",
"pred.shape[0], pred.shape[1], pred.shape[2], pred.shape[3] img_stack = torch.cat( [pred.reshape(N*C, 1, H,",
"if (i+1) in indices: loss += weights[k] * (X -",
"+ dydx.abs().mean() + dy2.abs().mean() # 暂时不上二阶的平滑损失,似乎加上以后就太猛了,无法降低photo loss TODO return smooth_loss",
"4 channels, same as flow_gx and flow_gy (if the input",
"# The distillation loss from the student to the teacher",
"12, 21, 30] weights = [1.0/2.6, 1.0/4.8, 1.0/3.7, 1.0/5.6, 10/1.5]",
"The distillation loss from the student to the teacher is",
"暂时不上二阶的平滑损失,似乎加上以后就太猛了,无法降低photo loss TODO return smooth_loss # flow should have 4",
"super(EPE, self).__init__() def forward(self, flow, gt, loss_mask): loss_map = (flow",
"is worse than that of the teacher. # If at",
"number of channels as flow. # No matter the flow",
"flow_stu, img_tea, flow_tea = \\ img_tea, flow_tea, img_stu, flow_stu #",
"teacher_error = loss_fun(img_tea, mid_gt).mean(1, True) # distill_mask indicates where the",
"flow channels: 1->0 flow. So use img1 weights. # Second",
"smooth_loss = dx.abs().mean() + dy.abs().mean() + dx2.abs().mean() + dxdy.abs().mean() +",
"x and y's spatial gradients, respectively. weights_x = torch.cat([img1_wx, img1_wx,",
"teacher. # Two directions could take different weights. # Set",
"should be smooth along both x and y axes. #",
"I.e., a y-flow should also be smooth along x-axis, and",
"weights_y both have 4 channels, same as flow_gx and flow_gy",
"and teacher, and calculate the distillation loss again. img_stu, flow_stu,",
"img0, img1): img0 = self.transform(self.rgb2gray(img0)) img1 = self.transform(self.rgb2gray(img1)) return self.hamming(img0,",
"= torch.exp(-torch.mean(weight_fn(constant * img1_gy), 1, keepdim=True)) # First two flow",
"img0_wy, img0_wy, img1_wy], dim=1) return weights_x, weights_y def error_fn(x): if",
"= dx.abs().mean() + dy.abs().mean() # smooth_loss = dx.abs().mean() + dy.abs().mean()",
"__init__(self): super(SOBEL, self).__init__() self.kernelX = torch.tensor([ [1, 0, -1], [2,",
"= torch.eye(c).view(c, c, 1, 1) if norm: self.weight.data.div_(std.view(c, 1, 1,",
"nn import torch.nn.functional as F import torchvision.models as models from",
"/ torch.sqrt(0.81 + transf**2) return transf_norm def rgb2gray(self, rgb): r,",
"padding).type_as(t) mask = F.pad(inner, [padding] * 4) return mask def",
"self.bias.data = -1 * data_range * torch.Tensor(data_mean) self.bias.data.div_(std) else: self.weight.data.mul_(std.view(c,",
"keepdim=True)) img0_wy = torch.exp(-torch.mean(weight_fn(constant * img0_gy), 1, keepdim=True)) img1_wx =",
"for x and y's spatial gradients, respectively. weights_x = torch.cat([img1_wx,",
"forward(self, X, Y, indices=None): X = self.normalize(X) Y = self.normalize(Y)",
"of teacher -> student. # Ws[1]: weight of student ->",
"[padding] * 4) return mask def forward(self, img0, img1): img0",
"* g + 0.1140 * b return gray def hamming(self,",
"self.vgg_pretrained_features[i](Y) if (i+1) in indices: loss += weights[k] * (X",
"if use_lap_loss: loss_fun = LapLoss(max_levels=3, reduction='none') else: loss_fun = nn.L1Loss(reduction='none')",
"have 4 channels. # https://github.com/coolbeam/OIFlow/blob/main/utils/tools.py # weight_type='exp' seems to perform",
"0:1, :, :], rgb[:, 1:2, :, :], rgb[:, 2:3, :,",
"valid_mask(self, t, padding): n, _, h, w = t.size() inner",
"weight_type='exp' seems to perform better than 'gauss'. def edge_aware_smoothness_order1(img0, img1,",
"img0_gx), 1, keepdim=True)) img0_wy = torch.exp(-torch.mean(weight_fn(constant * img0_gy), 1, keepdim=True))",
"= gradient(dx) # dydx, dy2 = gradient(dy) if if_second_order: dx2,",
"and flow_gy (if the input flow has 4 channels). weights_x,",
"torch.nn as nn import torch.nn.functional as F import torchvision.models as",
"= rgb[:, 0:1, :, :], rgb[:, 1:2, :, :], rgb[:,",
"rgb[:, 1:2, :, :], rgb[:, 2:3, :, :] gray =",
"https://github.com/coolbeam/OIFlow/blob/main/utils/tools.py def flow_smooth_delta(flow, if_second_order=False): def gradient(x): D_dx = x[:, :,",
":, :-1] - img[:, :, :, 1:] gy = img[:,",
"def dual_teaching_loss(mid_gt, img_stu, flow_stu, img_tea, flow_tea): loss_distill = 0 #",
"img0_wx, img0_wx], dim=1) weights_y = torch.cat([img1_wy, img0_wy, img0_wy, img1_wy], dim=1)",
"img1_gx), 1, keepdim=True)) img1_wy = torch.exp(-torch.mean(weight_fn(constant * img1_gy), 1, keepdim=True))",
"= loss_fun(img_tea, mid_gt).mean(1, True) # distill_mask indicates where the warped",
":-1] - img[:, :, :, 1:] gy = img[:, :,",
"x-axis, and x-flow should also be smooth along y-axis. flow_gx,",
"[0.229, 0.224, 0.225], norm=True).cuda() for param in self.parameters(): param.requires_grad =",
"img0 = self.transform(self.rgb2gray(img0)) img1 = self.transform(self.rgb2gray(img1)) return self.hamming(img0, img1) *",
"-1], [2, 0, -2], [1, 0, -1], ]).float() self.kernelY =",
"1, out_channels)) self.w = np.transpose(self.w, (3, 2, 0, 1)) self.w",
"= patches - img transf_norm = transf / torch.sqrt(0.81 +",
"self).__init__() self.kernelX = torch.tensor([ [1, 0, -1], [2, 0, -2],",
"2 elif weight_type == 'exp': y = torch.abs(x) else: raise",
"dxdy = gradient(dx) # dydx, dy2 = gradient(dy) if if_second_order:",
"1, keepdim=True)) img0_wy = torch.exp(-torch.mean(weight_fn(constant * img0_gy), 1, keepdim=True)) img1_wx",
"loss_distill += Ws[i] * ((flow_tea.detach() - flow_stu).abs() * distill_mask).mean() #",
"2 dist_norm = torch.mean(dist / (0.1 + dist), 1, True)",
"nn.L1Loss(reduction='none') for i in range(2): student_error = loss_fun(img_stu, mid_gt).mean(1, True)",
":, :] gray = 0.2989 * r + 0.5870 *",
"than that of the teacher. # If at some points,",
"+= 1 return loss # flow could have any channels.",
"input flow has 4 channels). weights_x, weights_y = gradweight_xy(img0, img1)",
"teacher is better than the student, # then regard the",
"* data_range * torch.Tensor(data_mean) self.bias.data.div_(std) else: self.weight.data.mul_(std.view(c, 1, 1, 1))",
"torch.Tensor(data_mean) self.requires_grad = False class VGGPerceptualLoss(torch.nn.Module): def __init__(self, rank=0): super(VGGPerceptualLoss,",
"at 2 directions. loss_distill += Ws[i] * ((flow_tea.detach() - flow_stu).abs()",
"'abs_robust': y = (torch.abs(x) + 0.01).pow(0.4) else: raise ValueError('') return",
"along y-axis. flow_gx, flow_gy = gradient_xy(flow) # weights_x, weights_y both",
"padding=3, bias=None) transf = patches - img transf_norm = transf",
"10/1.5] k = 0 loss = 0 for i in",
"(t1 - t2) ** 2 dist_norm = torch.mean(dist / (0.1",
"w = t.size() inner = torch.ones(n, 1, h - 2",
"x[:, :, :, 1:] - x[:, :, :, :-1] D_dy",
"C, H, W = pred.shape[0], pred.shape[1], pred.shape[2], pred.shape[3] img_stack =",
"as flow. # No matter the flow is x- or",
"them to teach the student. distill_mask = (student_error > teacher_error",
"bias=None) transf = patches - img transf_norm = transf /",
"return y def gradient_xy(img): gx = img[:, :, :, :-1]",
"= models.vgg19(pretrained=pretrained).features self.normalize = MeanShift([0.485, 0.456, 0.406], [0.229, 0.224, 0.225],",
"for i in range(indices[-1]): X = self.vgg_pretrained_features[i](X) Y = self.vgg_pretrained_features[i](Y)",
"images according to student's prediction # is worse than that",
"according to student's prediction # is worse than that of",
"- gt.detach()) ** 2 loss_map = (loss_map.sum(1, True) + 1e-6)",
"k += 1 return loss # flow could have any",
"the flow is x- or y-flow, it should be smooth",
"0.225], norm=True).cuda() for param in self.parameters(): param.requires_grad = False def",
"(loss_map * loss_mask) class Ternary(nn.Module): def __init__(self): super(Ternary, self).__init__() patch_size",
"+ dy.abs().mean() # + dx2.abs().mean() + dxdy.abs().mean() + dydx.abs().mean() +",
"slower. if use_lap_loss: loss_fun = LapLoss(max_levels=3, reduction='none') else: loss_fun =",
"Y = self.normalize(Y) indices = [2, 7, 12, 21, 30]",
"torch.mean(dist / (0.1 + dist), 1, True) return dist_norm def",
"-1], ]).float() self.kernelY = self.kernelX.clone().T self.kernelX = self.kernelX.unsqueeze(0).unsqueeze(0).to(device) self.kernelY =",
"t.size() inner = torch.ones(n, 1, h - 2 * padding,",
"have the same number of channels as flow. # No",
"* weights_y return torch.mean(smoothness_x) + torch.mean(smoothness_y) # Dual teaching helps",
"\\ img_tea, flow_tea, img_stu, flow_stu # The distillation loss from",
"dy2 = gradient(dy) if if_second_order: dx2, dxdy = gradient(dx) dydx,",
"True) # distill_mask indicates where the warped images according to",
"* img0_gy), 1, keepdim=True)) img1_wx = torch.exp(-torch.mean(weight_fn(constant * img1_gx), 1,",
"# The flow gradients along x, y axes, respectively. #",
"these points are more accurate, and use them to teach",
"** 2 elif weight_type == 'exp': y = torch.abs(x) else:",
"img[:, :, :, :-1] - img[:, :, :, 1:] gy",
"img1) * self.valid_mask(img0, 1) class SOBEL(nn.Module): def __init__(self): super(SOBEL, self).__init__()",
"loss_mask): loss_map = (flow - gt.detach()) ** 2 loss_map =",
"if torch.cuda.is_available() else \"cpu\") class EPE(nn.Module): def __init__(self): super(EPE, self).__init__()",
"gt): N, C, H, W = pred.shape[0], pred.shape[1], pred.shape[2], pred.shape[3]",
"* r + 0.5870 * g + 0.1140 * b",
"[pred.reshape(N*C, 1, H, W), gt.reshape(N*C, 1, H, W)], 0) sobel_stack_x",
"gradient_xy(img0) img1_gx, img1_gy = gradient_xy(img1) img0_wx = torch.exp(-torch.mean(weight_fn(constant * img0_gx),",
"\"cpu\") class EPE(nn.Module): def __init__(self): super(EPE, self).__init__() def forward(self, flow,",
"torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") class EPE(nn.Module): def __init__(self): super(EPE,",
"img_stu, flow_stu, img_tea, flow_tea = \\ img_tea, flow_tea, img_stu, flow_stu",
"return D_dx, D_dy dx, dy = gradient(flow) # dx2, dxdy",
"y = (torch.abs(x) + 0.01).pow(0.4) else: raise ValueError('') return y",
"self.requires_grad = False class VGGPerceptualLoss(torch.nn.Module): def __init__(self, rank=0): super(VGGPerceptualLoss, self).__init__()",
"pred_Y, gt_Y = sobel_stack_y[:N*C], sobel_stack_y[N*C:] L1X, L1Y = torch.abs(pred_X-gt_X), torch.abs(pred_Y-gt_Y)",
"W = pred.shape[0], pred.shape[1], pred.shape[2], pred.shape[3] img_stack = torch.cat( [pred.reshape(N*C,",
"30] weights = [1.0/2.6, 1.0/4.8, 1.0/3.7, 1.0/5.6, 10/1.5] k =",
"img0 = torch.zeros(3, 3, 256, 256).float().to(device) img1 = torch.tensor(np.random.normal( 0,",
"channels: 0->1 flow. So use img0 weights. # weights_x and",
"= True self.vgg_pretrained_features = models.vgg19(pretrained=pretrained).features self.normalize = MeanShift([0.485, 0.456, 0.406],",
"x[:, :, :-1] return D_dx, D_dy dx, dy = gradient(flow)",
"loss is significantly slower. if use_lap_loss: loss_fun = LapLoss(max_levels=3, reduction='none')",
"256, 256).float().to(device) img1 = torch.tensor(np.random.normal( 0, 1, (3, 3, 256,",
"pred.shape[1], pred.shape[2], pred.shape[3] img_stack = torch.cat( [pred.reshape(N*C, 1, H, W),",
"w - 2 * padding).type_as(t) mask = F.pad(inner, [padding] *",
"k = 0 loss = 0 for i in range(indices[-1]):",
"the warped images according to student's prediction # is worse",
"is x- or y-flow, it should be smooth along both",
"directions could take different weights. # Set Ws[1] to 0",
"loss_mask) class Ternary(nn.Module): def __init__(self): super(Ternary, self).__init__() patch_size = 7",
"(3, 2, 0, 1)) self.w = torch.tensor(self.w).float().to(device) def transform(self, img):",
"img1 = torch.tensor(np.random.normal( 0, 1, (3, 3, 256, 256))).float().to(device) ternary_loss",
"= \\ img_tea, flow_tea, img_stu, flow_stu # The distillation loss",
"(L1X+L1Y) return loss class MeanShift(nn.Conv2d): def __init__(self, data_mean, data_std, data_range=1,",
"X = self.vgg_pretrained_features[i](X) Y = self.vgg_pretrained_features[i](Y) if (i+1) in indices:",
":, :, :-1] D_dy = x[:, :, 1:] - x[:,",
"img1, flow, constant=1.0, weight_type='exp', error_type='L1'): def weight_fn(x): if weight_type ==",
"0, -2], [1, 0, -1], ]).float() self.kernelY = self.kernelX.clone().T self.kernelX",
"error_type='L1'): def weight_fn(x): if weight_type == 'gauss': y = x",
"keepdim=True)) img1_wx = torch.exp(-torch.mean(weight_fn(constant * img1_gx), 1, keepdim=True)) img1_wy =",
"the teacher. # If at some points, the warped image",
"teacher, and calculate the distillation loss again. img_stu, flow_stu, img_tea,",
"in range(2): student_error = loss_fun(img_stu, mid_gt).mean(1, True) teacher_error = loss_fun(img_tea,",
"padding=1) pred_X, gt_X = sobel_stack_x[:N*C], sobel_stack_x[N*C:] pred_Y, gt_Y = sobel_stack_y[:N*C],",
"- img[:, :, :, 1:] gy = img[:, :, :-1,",
"two flow channels: 1->0 flow. So use img1 weights. #",
"flow_gy = gradient_xy(flow) # weights_x, weights_y both have 4 channels,",
"param in self.parameters(): param.requires_grad = False def forward(self, X, Y,",
"4 channels. # https://github.com/coolbeam/OIFlow/blob/main/utils/tools.py # weight_type='exp' seems to perform better",
"_, h, w = t.size() inner = torch.ones(n, 1, h",
"= dx.abs().mean() + dy.abs().mean() + dx2.abs().mean() + dxdy.abs().mean() + dydx.abs().mean()",
"+= weights[k] * (X - Y.detach()).abs().mean() * 0.1 k +=",
"y axes, respectively. # flow_gx, flow_gy have the same number",
"epochs, but worse in later epochs. # Moreover, Laplacian loss",
"= 0 # Ws[0]: weight of teacher -> student. #",
"'L1': y = torch.abs(x) elif error_type == 'abs_robust': y =",
"1)) self.bias.data = data_range * torch.Tensor(data_mean) self.requires_grad = False class",
"use_lap_loss: loss_fun = LapLoss(max_levels=3, reduction='none') else: loss_fun = nn.L1Loss(reduction='none') for",
"indices = [2, 7, 12, 21, 30] weights = [1.0/2.6,",
"torch.exp(-torch.mean(weight_fn(constant * img1_gy), 1, keepdim=True)) # First two flow channels:",
"(0.1 + dist), 1, True) return dist_norm def valid_mask(self, t,",
"norm: self.weight.data.div_(std.view(c, 1, 1, 1)) self.bias.data = -1 * data_range",
"the input flow has 4 channels). weights_x, weights_y = gradweight_xy(img0,",
"weights_x, weights_y both have 4 channels, same as flow_gx and",
"__init__(self): super(Ternary, self).__init__() patch_size = 7 out_channels = patch_size *",
"L1X, L1Y = torch.abs(pred_X-gt_X), torch.abs(pred_Y-gt_Y) loss = (L1X+L1Y) return loss",
"dx.abs().mean() + dy.abs().mean() # smooth_loss = dx.abs().mean() + dy.abs().mean() #",
"= data_range * torch.Tensor(data_mean) self.requires_grad = False class VGGPerceptualLoss(torch.nn.Module): def",
"channels. # https://github.com/coolbeam/OIFlow/blob/main/utils/tools.py # weight_type='exp' seems to perform better than",
"torch.zeros(3, 3, 256, 256).float().to(device) img1 = torch.tensor(np.random.normal( 0, 1, (3,",
"+ 0.01).pow(0.4) else: raise ValueError('') return y # The flow",
"img_tea, flow_tea = \\ img_tea, flow_tea, img_stu, flow_stu # The",
"if_second_order: dx2, dxdy = gradient(dx) dydx, dy2 = gradient(dy) smooth_loss",
"epochs. # Moreover, Laplacian loss is significantly slower. if use_lap_loss:",
":] - img[:, :, 1:, :] return gx, gy def",
"x[:, :, 1:] - x[:, :, :-1] return D_dx, D_dy",
"* distill_mask).mean() # Swap student and teacher, and calculate the",
"* b return gray def hamming(self, t1, t2): dist =",
"N, C, H, W = pred.shape[0], pred.shape[1], pred.shape[2], pred.shape[3] img_stack",
"gray def hamming(self, t1, t2): dist = (t1 - t2)",
"img_stack = torch.cat( [pred.reshape(N*C, 1, H, W), gt.reshape(N*C, 1, H,",
"+ dy.abs().mean() # smooth_loss = dx.abs().mean() + dy.abs().mean() # +",
"dx2.abs().mean() + dxdy.abs().mean() + dydx.abs().mean() + dy2.abs().mean() # 暂时不上二阶的平滑损失,似乎加上以后就太猛了,无法降低photo loss",
"# flow should have 4 channels. # https://github.com/coolbeam/OIFlow/blob/main/utils/tools.py # weight_type='exp'",
"img0_gy = gradient_xy(img0) img1_gx, img1_gy = gradient_xy(img1) img0_wx = torch.exp(-torch.mean(weight_fn(constant",
"channels: 1->0 flow. So use img1 weights. # Second two",
"(loss_map.sum(1, True) + 1e-6) ** 0.5 return (loss_map * loss_mask)",
"img): patches = F.conv2d(img, self.w, padding=3, bias=None) transf = patches",
"def __init__(self, data_mean, data_std, data_range=1, norm=True): c = len(data_mean) super(MeanShift,",
"distillation losses at 2 directions. loss_distill += Ws[i] * ((flow_tea.detach()",
"def gradweight_xy(img0, img1): img0_gx, img0_gy = gradient_xy(img0) img1_gx, img1_gy =",
"flow. So use img1 weights. # Second two flow channels:",
"b return gray def hamming(self, t1, t2): dist = (t1",
":, :], rgb[:, 2:3, :, :] gray = 0.2989 *",
"img[:, :, :, 1:] gy = img[:, :, :-1, :]",
"3, 256, 256).float().to(device) img1 = torch.tensor(np.random.normal( 0, 1, (3, 3,",
"return smooth_loss # flow should have 4 channels. # https://github.com/coolbeam/OIFlow/blob/main/utils/tools.py",
"* padding).type_as(t) mask = F.pad(inner, [padding] * 4) return mask",
"self).__init__() blocks = [] pretrained = True self.vgg_pretrained_features = models.vgg19(pretrained=pretrained).features",
"= pred.shape[0], pred.shape[1], pred.shape[2], pred.shape[3] img_stack = torch.cat( [pred.reshape(N*C, 1,",
"both x and y axes. # I.e., a y-flow should",
"(student_error > teacher_error + 0.01).float().detach() # loss_distill is the sum",
"in self.parameters(): param.requires_grad = False def forward(self, X, Y, indices=None):",
"self.kernelY, padding=1) pred_X, gt_X = sobel_stack_x[:N*C], sobel_stack_x[N*C:] pred_Y, gt_Y =",
"gx, gy def gradweight_xy(img0, img1): img0_gx, img0_gy = gradient_xy(img0) img1_gx,",
"= (L1X+L1Y) return loss class MeanShift(nn.Conv2d): def __init__(self, data_mean, data_std,",
"1)) self.bias.data = -1 * data_range * torch.Tensor(data_mean) self.bias.data.div_(std) else:",
"smooth along y-axis. flow_gx, flow_gy = gradient_xy(flow) # weights_x, weights_y",
"should also be smooth along y-axis. flow_gx, flow_gy = gradient_xy(flow)",
"weights_y def error_fn(x): if error_type == 'L1': y = torch.abs(x)",
"dim=1) weights_y = torch.cat([img1_wy, img0_wy, img0_wy, img1_wy], dim=1) return weights_x,",
"(flow - gt.detach()) ** 2 loss_map = (loss_map.sum(1, True) +",
"gy def gradweight_xy(img0, img1): img0_gx, img0_gy = gradient_xy(img0) img1_gx, img1_gy",
"y = torch.abs(x) elif error_type == 'abs_robust': y = (torch.abs(x)",
"teaching helps slightly. def dual_teaching_loss(mid_gt, img_stu, flow_stu, img_tea, flow_tea): loss_distill",
"axes. # I.e., a y-flow should also be smooth along",
"flow_gx and flow_gy (if the input flow has 4 channels).",
"transf**2) return transf_norm def rgb2gray(self, rgb): r, g, b =",
"both have 4 channels, same as flow_gx and flow_gy (if",
"better than the student, # then regard the flow at",
"- img transf_norm = transf / torch.sqrt(0.81 + transf**2) return",
"+ dxdy.abs().mean() + dydx.abs().mean() + dy2.abs().mean() else: smooth_loss = dx.abs().mean()",
"if error_type == 'L1': y = torch.abs(x) elif error_type ==",
"loss_distill if __name__ == '__main__': img0 = torch.zeros(3, 3, 256,",
"loss # flow could have any channels. # https://github.com/coolbeam/OIFlow/blob/main/utils/tools.py def",
"+ torch.mean(smoothness_y) # Dual teaching helps slightly. def dual_teaching_loss(mid_gt, img_stu,",
"gradient(dy) smooth_loss = dx.abs().mean() + dy.abs().mean() + dx2.abs().mean() + dxdy.abs().mean()",
"def __init__(self): super(EPE, self).__init__() def forward(self, flow, gt, loss_mask): loss_map",
"= torch.tensor(np.random.normal( 0, 1, (3, 3, 256, 256))).float().to(device) ternary_loss =",
"Second two flow channels: 0->1 flow. So use img0 weights.",
"range(2): student_error = loss_fun(img_stu, mid_gt).mean(1, True) teacher_error = loss_fun(img_tea, mid_gt).mean(1,",
"img0_gx, img0_gy = gradient_xy(img0) img1_gx, img1_gy = gradient_xy(img1) img0_wx =",
"0.5870 * g + 0.1140 * b return gray def",
"flow_tea, img_stu, flow_stu # The distillation loss from the student",
"self.w, padding=3, bias=None) transf = patches - img transf_norm =",
"'__main__': img0 = torch.zeros(3, 3, 256, 256).float().to(device) img1 = torch.tensor(np.random.normal(",
"flow_tea): loss_distill = 0 # Ws[0]: weight of teacher ->",
"return (loss_map * loss_mask) class Ternary(nn.Module): def __init__(self): super(Ternary, self).__init__()",
":, 1:] gy = img[:, :, :-1, :] - img[:,",
"distillation loss again. img_stu, flow_stu, img_tea, flow_tea = \\ img_tea,",
"any channels. # https://github.com/coolbeam/OIFlow/blob/main/utils/tools.py def flow_smooth_delta(flow, if_second_order=False): def gradient(x): D_dx",
"error_fn(flow_gy) * weights_y return torch.mean(smoothness_x) + torch.mean(smoothness_y) # Dual teaching",
"* padding, w - 2 * padding).type_as(t) mask = F.pad(inner,",
"* weights_x smoothness_y = error_fn(flow_gy) * weights_y return torch.mean(smoothness_x) +",
"student to the teacher is given a smaller weight. #",
"- t2) ** 2 dist_norm = torch.mean(dist / (0.1 +",
"= error_fn(flow_gy) * weights_y return torch.mean(smoothness_x) + torch.mean(smoothness_y) # Dual",
"flow is x- or y-flow, it should be smooth along",
"= torch.abs(pred_X-gt_X), torch.abs(pred_Y-gt_Y) loss = (L1X+L1Y) return loss class MeanShift(nn.Conv2d):",
"= patch_size * patch_size self.w = np.eye(out_channels).reshape( (patch_size, patch_size, 1,",
"= x[:, :, 1:] - x[:, :, :-1] return D_dx,",
"weights_x and weights_y are for x and y's spatial gradients,",
"LapLoss(max_levels=3, reduction='none') else: loss_fun = nn.L1Loss(reduction='none') for i in range(2):",
"F.pad(inner, [padding] * 4) return mask def forward(self, img0, img1):",
"i in range(2): student_error = loss_fun(img_stu, mid_gt).mean(1, True) teacher_error =",
"return loss # flow could have any channels. # https://github.com/coolbeam/OIFlow/blob/main/utils/tools.py",
"t, padding): n, _, h, w = t.size() inner =",
"2:3, :, :] gray = 0.2989 * r + 0.5870",
"indices=None): X = self.normalize(X) Y = self.normalize(Y) indices = [2,",
"dydx.abs().mean() + dy2.abs().mean() # 暂时不上二阶的平滑损失,似乎加上以后就太猛了,无法降低photo loss TODO return smooth_loss #",
"worse than that of the teacher. # If at some",
"= False class VGGPerceptualLoss(torch.nn.Module): def __init__(self, rank=0): super(VGGPerceptualLoss, self).__init__() blocks",
"* 4) return mask def forward(self, img0, img1): img0 =",
"patch_size * patch_size self.w = np.eye(out_channels).reshape( (patch_size, patch_size, 1, out_channels))",
"[] pretrained = True self.vgg_pretrained_features = models.vgg19(pretrained=pretrained).features self.normalize = MeanShift([0.485,",
"Ternary(nn.Module): def __init__(self): super(Ternary, self).__init__() patch_size = 7 out_channels =",
"and calculate the distillation loss again. img_stu, flow_stu, img_tea, flow_tea",
"= torch.exp(-torch.mean(weight_fn(constant * img0_gx), 1, keepdim=True)) img0_wy = torch.exp(-torch.mean(weight_fn(constant *",
"* torch.Tensor(data_mean) self.bias.data.div_(std) else: self.weight.data.mul_(std.view(c, 1, 1, 1)) self.bias.data =",
"rank=0): super(VGGPerceptualLoss, self).__init__() blocks = [] pretrained = True self.vgg_pretrained_features",
"flow_smooth_delta(flow, if_second_order=False): def gradient(x): D_dx = x[:, :, :, 1:]",
"Dual teaching helps slightly. def dual_teaching_loss(mid_gt, img_stu, flow_stu, img_tea, flow_tea):",
"LapLoss device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") class EPE(nn.Module):",
"img_tea, flow_tea, img_stu, flow_stu # The distillation loss from the",
"along x, y axes, respectively. # flow_gx, flow_gy have the",
"> teacher_error + 0.01).float().detach() # loss_distill is the sum of",
"= gradient(flow) # dx2, dxdy = gradient(dx) # dydx, dy2",
"# then regard the flow at these points are more",
"+ dist), 1, True) return dist_norm def valid_mask(self, t, padding):",
"0, 1, (3, 3, 256, 256))).float().to(device) ternary_loss = Ternary() print(ternary_loss(img0,",
"regard the flow at these points are more accurate, and",
"1.0/3.7, 1.0/5.6, 10/1.5] k = 0 loss = 0 for",
"patch_size = 7 out_channels = patch_size * patch_size self.w =",
"self).__init__(c, c, kernel_size=1) std = torch.Tensor(data_std) self.weight.data = torch.eye(c).view(c, c,",
"pred, gt): N, C, H, W = pred.shape[0], pred.shape[1], pred.shape[2],",
"1:] - x[:, :, :, :-1] D_dy = x[:, :,",
":, :-1, :] - img[:, :, 1:, :] return gx,",
"1, keepdim=True)) # First two flow channels: 1->0 flow. So",
"be smooth along x-axis, and x-flow should also be smooth",
"+ dxdy.abs().mean() + dydx.abs().mean() + dy2.abs().mean() # 暂时不上二阶的平滑损失,似乎加上以后就太猛了,无法降低photo loss TODO",
"False # Laplacian loss performs better in earlier epochs, but",
"img0_gy), 1, keepdim=True)) img1_wx = torch.exp(-torch.mean(weight_fn(constant * img1_gx), 1, keepdim=True))",
"padding): n, _, h, w = t.size() inner = torch.ones(n,",
"0.2989 * r + 0.5870 * g + 0.1140 *",
"def __init__(self): super(SOBEL, self).__init__() self.kernelX = torch.tensor([ [1, 0, -1],",
"img1_gx, img1_gy = gradient_xy(img1) img0_wx = torch.exp(-torch.mean(weight_fn(constant * img0_gx), 1,",
"y-axis. flow_gx, flow_gy = gradient_xy(flow) # weights_x, weights_y both have",
"some points, the warped image of the teacher is better",
"np import torch.nn as nn import torch.nn.functional as F import",
"spatial gradients, respectively. weights_x = torch.cat([img1_wx, img1_wx, img0_wx, img0_wx], dim=1)",
"= torch.exp(-torch.mean(weight_fn(constant * img0_gy), 1, keepdim=True)) img1_wx = torch.exp(-torch.mean(weight_fn(constant *",
"and y axes. # I.e., a y-flow should also be",
"0.456, 0.406], [0.229, 0.224, 0.225], norm=True).cuda() for param in self.parameters():",
"self.normalize(X) Y = self.normalize(Y) indices = [2, 7, 12, 21,",
"flow gradients along x, y axes, respectively. # flow_gx, flow_gy",
"error_type == 'abs_robust': y = (torch.abs(x) + 0.01).pow(0.4) else: raise",
"return torch.mean(smoothness_x) + torch.mean(smoothness_y) # Dual teaching helps slightly. def",
"use_lap_loss = False # Laplacian loss performs better in earlier",
"= loss_fun(img_stu, mid_gt).mean(1, True) teacher_error = loss_fun(img_tea, mid_gt).mean(1, True) #",
"gy = img[:, :, :-1, :] - img[:, :, 1:,",
"dxdy.abs().mean() + dydx.abs().mean() + dy2.abs().mean() else: smooth_loss = dx.abs().mean() +",
"F.conv2d(img_stack, self.kernelY, padding=1) pred_X, gt_X = sobel_stack_x[:N*C], sobel_stack_x[N*C:] pred_Y, gt_Y",
"= t.size() inner = torch.ones(n, 1, h - 2 *",
"import torch.nn.functional as F import torchvision.models as models from model.laplacian",
"in indices: loss += weights[k] * (X - Y.detach()).abs().mean() *",
"def gradient(x): D_dx = x[:, :, :, 1:] - x[:,",
"distill_mask indicates where the warped images according to student's prediction",
"student -> teacher. Ws = [1, 0.5] use_lap_loss = False",
"student's prediction # is worse than that of the teacher.",
"y axes. # I.e., a y-flow should also be smooth",
"Ws = [1, 0.5] use_lap_loss = False # Laplacian loss",
"the teacher is better than the student, # then regard",
"2 directions. loss_distill += Ws[i] * ((flow_tea.detach() - flow_stu).abs() *",
"self.hamming(img0, img1) * self.valid_mask(img0, 1) class SOBEL(nn.Module): def __init__(self): super(SOBEL,",
"t2): dist = (t1 - t2) ** 2 dist_norm =",
"flow. # No matter the flow is x- or y-flow,",
"torch.abs(x) elif error_type == 'abs_robust': y = (torch.abs(x) + 0.01).pow(0.4)",
"respectively. # flow_gx, flow_gy have the same number of channels",
"c = len(data_mean) super(MeanShift, self).__init__(c, c, kernel_size=1) std = torch.Tensor(data_std)",
"[1, 0, -1], [2, 0, -2], [1, 0, -1], ]).float()",
"+ dydx.abs().mean() + dy2.abs().mean() else: smooth_loss = dx.abs().mean() + dy.abs().mean()",
"gradweight_xy(img0, img1) smoothness_x = error_fn(flow_gx) * weights_x smoothness_y = error_fn(flow_gy)",
"= self.transform(self.rgb2gray(img0)) img1 = self.transform(self.rgb2gray(img1)) return self.hamming(img0, img1) * self.valid_mask(img0,",
"1:] gy = img[:, :, :-1, :] - img[:, :,",
"gradient(flow) # dx2, dxdy = gradient(dx) # dydx, dy2 =",
"= gradient_xy(img0) img1_gx, img1_gy = gradient_xy(img1) img0_wx = torch.exp(-torch.mean(weight_fn(constant *",
"keepdim=True)) # First two flow channels: 1->0 flow. So use",
"teacher. # If at some points, the warped image of",
"2 loss_map = (loss_map.sum(1, True) + 1e-6) ** 0.5 return",
"= np.transpose(self.w, (3, 2, 0, 1)) self.w = torch.tensor(self.w).float().to(device) def",
"self.w = np.eye(out_channels).reshape( (patch_size, patch_size, 1, out_channels)) self.w = np.transpose(self.w,",
"the warped image of the teacher is better than the",
"torch.ones(n, 1, h - 2 * padding, w - 2",
"H, W), gt.reshape(N*C, 1, H, W)], 0) sobel_stack_x = F.conv2d(img_stack,",
"1, keepdim=True)) img1_wy = torch.exp(-torch.mean(weight_fn(constant * img1_gy), 1, keepdim=True)) #",
"rgb): r, g, b = rgb[:, 0:1, :, :], rgb[:,",
"smooth along x-axis, and x-flow should also be smooth along",
"def forward(self, pred, gt): N, C, H, W = pred.shape[0],",
"torch.exp(-torch.mean(weight_fn(constant * img0_gy), 1, keepdim=True)) img1_wx = torch.exp(-torch.mean(weight_fn(constant * img1_gx),",
"torch.nn.functional as F import torchvision.models as models from model.laplacian import",
"= torch.exp(-torch.mean(weight_fn(constant * img1_gx), 1, keepdim=True)) img1_wy = torch.exp(-torch.mean(weight_fn(constant *",
"-> teacher. # Two directions could take different weights. #",
"disable student -> teacher. Ws = [1, 0.5] use_lap_loss =",
"as nn import torch.nn.functional as F import torchvision.models as models",
"flow_gy have the same number of channels as flow. #",
"Ws[i] * ((flow_tea.detach() - flow_stu).abs() * distill_mask).mean() # Swap student",
"gt.reshape(N*C, 1, H, W)], 0) sobel_stack_x = F.conv2d(img_stack, self.kernelX, padding=1)",
"torch.abs(pred_Y-gt_Y) loss = (L1X+L1Y) return loss class MeanShift(nn.Conv2d): def __init__(self,",
"len(data_mean) super(MeanShift, self).__init__(c, c, kernel_size=1) std = torch.Tensor(data_std) self.weight.data =",
"flow could have any channels. # https://github.com/coolbeam/OIFlow/blob/main/utils/tools.py def flow_smooth_delta(flow, if_second_order=False):",
"* torch.Tensor(data_mean) self.requires_grad = False class VGGPerceptualLoss(torch.nn.Module): def __init__(self, rank=0):",
"as np import torch.nn as nn import torch.nn.functional as F",
"torch.Tensor(data_mean) self.bias.data.div_(std) else: self.weight.data.mul_(std.view(c, 1, 1, 1)) self.bias.data = data_range",
"# If at some points, the warped image of the",
"* img0_gx), 1, keepdim=True)) img0_wy = torch.exp(-torch.mean(weight_fn(constant * img0_gy), 1,",
"weight of student -> teacher. # Two directions could take",
"elif error_type == 'abs_robust': y = (torch.abs(x) + 0.01).pow(0.4) else:",
"1, H, W)], 0) sobel_stack_x = F.conv2d(img_stack, self.kernelX, padding=1) sobel_stack_y",
"dx.abs().mean() + dy.abs().mean() # + dx2.abs().mean() + dxdy.abs().mean() + dydx.abs().mean()",
"torch.abs(pred_X-gt_X), torch.abs(pred_Y-gt_Y) loss = (L1X+L1Y) return loss class MeanShift(nn.Conv2d): def",
"1e-6) ** 0.5 return (loss_map * loss_mask) class Ternary(nn.Module): def",
"better than 'gauss'. def edge_aware_smoothness_order1(img0, img1, flow, constant=1.0, weight_type='exp', error_type='L1'):",
"and x-flow should also be smooth along y-axis. flow_gx, flow_gy",
"the teacher is given a smaller weight. # loss_distill =",
"import torchvision.models as models from model.laplacian import LapLoss device =",
"patch_size self.w = np.eye(out_channels).reshape( (patch_size, patch_size, 1, out_channels)) self.w =",
"= self.normalize(X) Y = self.normalize(Y) indices = [2, 7, 12,",
"1.0/5.6, 10/1.5] k = 0 loss = 0 for i",
"-> teacher. Ws = [1, 0.5] use_lap_loss = False #",
"0, -1], ]).float() self.kernelY = self.kernelX.clone().T self.kernelX = self.kernelX.unsqueeze(0).unsqueeze(0).to(device) self.kernelY",
"torch.cat([img1_wx, img1_wx, img0_wx, img0_wx], dim=1) weights_y = torch.cat([img1_wy, img0_wy, img0_wy,",
"4) return mask def forward(self, img0, img1): img0 = self.transform(self.rgb2gray(img0))",
"the distillation losses at 2 directions. loss_distill += Ws[i] *",
"if_second_order=False): def gradient(x): D_dx = x[:, :, :, 1:] -",
"- 2 * padding, w - 2 * padding).type_as(t) mask",
"- 2 * padding).type_as(t) mask = F.pad(inner, [padding] * 4)",
"smooth along both x and y axes. # I.e., a",
"y-flow, it should be smooth along both x and y",
"loss_distill is the sum of the distillation losses at 2",
"def hamming(self, t1, t2): dist = (t1 - t2) **",
"2 * padding).type_as(t) mask = F.pad(inner, [padding] * 4) return",
"If at some points, the warped image of the teacher",
"self.vgg_pretrained_features[i](X) Y = self.vgg_pretrained_features[i](Y) if (i+1) in indices: loss +=",
"return y # The flow gradients along x, y axes,",
"weights_x = torch.cat([img1_wx, img1_wx, img0_wx, img0_wx], dim=1) weights_y = torch.cat([img1_wy,",
"def weight_fn(x): if weight_type == 'gauss': y = x **",
"self.weight.data.mul_(std.view(c, 1, 1, 1)) self.bias.data = data_range * torch.Tensor(data_mean) self.requires_grad",
"No matter the flow is x- or y-flow, it should",
"torch.tensor(self.w).float().to(device) def transform(self, img): patches = F.conv2d(img, self.w, padding=3, bias=None)",
"flow_stu, img_tea, flow_tea): loss_distill = 0 # Ws[0]: weight of",
"flow at these points are more accurate, and use them",
"1, H, W), gt.reshape(N*C, 1, H, W)], 0) sobel_stack_x =",
"to teach the student. distill_mask = (student_error > teacher_error +",
"the sum of the distillation losses at 2 directions. loss_distill",
"the distillation loss again. img_stu, flow_stu, img_tea, flow_tea = \\",
"again. img_stu, flow_stu, img_tea, flow_tea = \\ img_tea, flow_tea, img_stu,",
"gradient(dx) # dydx, dy2 = gradient(dy) if if_second_order: dx2, dxdy",
"norm=True): c = len(data_mean) super(MeanShift, self).__init__(c, c, kernel_size=1) std =",
"def flow_smooth_delta(flow, if_second_order=False): def gradient(x): D_dx = x[:, :, :,",
"teacher_error + 0.01).float().detach() # loss_distill is the sum of the",
"than 'gauss'. def edge_aware_smoothness_order1(img0, img1, flow, constant=1.0, weight_type='exp', error_type='L1'): def",
"that of the teacher. # If at some points, the",
"- x[:, :, :-1] return D_dx, D_dy dx, dy =",
"(if the input flow has 4 channels). weights_x, weights_y =",
"__init__(self): super(EPE, self).__init__() def forward(self, flow, gt, loss_mask): loss_map =",
"0 to disable student -> teacher. Ws = [1, 0.5]",
"different weights. # Set Ws[1] to 0 to disable student",
"dx.abs().mean() + dy.abs().mean() + dx2.abs().mean() + dxdy.abs().mean() + dydx.abs().mean() +",
"seems to perform better than 'gauss'. def edge_aware_smoothness_order1(img0, img1, flow,",
"raise ValueError('') return y def gradient_xy(img): gx = img[:, :,",
"7 out_channels = patch_size * patch_size self.w = np.eye(out_channels).reshape( (patch_size,",
":, :-1] D_dy = x[:, :, 1:] - x[:, :,",
"= gradient(dx) dydx, dy2 = gradient(dy) smooth_loss = dx.abs().mean() +",
"weight_type == 'gauss': y = x ** 2 elif weight_type",
"0.01).pow(0.4) else: raise ValueError('') return y # The flow gradients",
"worse in later epochs. # Moreover, Laplacian loss is significantly",
"dydx, dy2 = gradient(dy) if if_second_order: dx2, dxdy = gradient(dx)",
"dist), 1, True) return dist_norm def valid_mask(self, t, padding): n,",
"sobel_stack_y[:N*C], sobel_stack_y[N*C:] L1X, L1Y = torch.abs(pred_X-gt_X), torch.abs(pred_Y-gt_Y) loss = (L1X+L1Y)",
"r, g, b = rgb[:, 0:1, :, :], rgb[:, 1:2,",
"loss += weights[k] * (X - Y.detach()).abs().mean() * 0.1 k",
"'gauss'. def edge_aware_smoothness_order1(img0, img1, flow, constant=1.0, weight_type='exp', error_type='L1'): def weight_fn(x):",
"kernel_size=1) std = torch.Tensor(data_std) self.weight.data = torch.eye(c).view(c, c, 1, 1)",
"torch.tensor([ [1, 0, -1], [2, 0, -2], [1, 0, -1],",
"TODO return smooth_loss # flow should have 4 channels. #",
"img1_gy = gradient_xy(img1) img0_wx = torch.exp(-torch.mean(weight_fn(constant * img0_gx), 1, keepdim=True))",
"weights_y = torch.cat([img1_wy, img0_wy, img0_wy, img1_wy], dim=1) return weights_x, weights_y",
"sobel_stack_y[N*C:] L1X, L1Y = torch.abs(pred_X-gt_X), torch.abs(pred_Y-gt_Y) loss = (L1X+L1Y) return",
"loss performs better in earlier epochs, but worse in later",
"self.bias.data.div_(std) else: self.weight.data.mul_(std.view(c, 1, 1, 1)) self.bias.data = data_range *",
"loss = 0 for i in range(indices[-1]): X = self.vgg_pretrained_features[i](X)",
"self.transform(self.rgb2gray(img1)) return self.hamming(img0, img1) * self.valid_mask(img0, 1) class SOBEL(nn.Module): def",
"inner = torch.ones(n, 1, h - 2 * padding, w",
"1:2, :, :], rgb[:, 2:3, :, :] gray = 0.2989",
"super(MeanShift, self).__init__(c, c, kernel_size=1) std = torch.Tensor(data_std) self.weight.data = torch.eye(c).view(c,",
"models.vgg19(pretrained=pretrained).features self.normalize = MeanShift([0.485, 0.456, 0.406], [0.229, 0.224, 0.225], norm=True).cuda()",
"= error_fn(flow_gx) * weights_x smoothness_y = error_fn(flow_gy) * weights_y return",
"t1, t2): dist = (t1 - t2) ** 2 dist_norm",
"= torch.tensor(self.w).float().to(device) def transform(self, img): patches = F.conv2d(img, self.w, padding=3,",
"padding=1) sobel_stack_y = F.conv2d(img_stack, self.kernelY, padding=1) pred_X, gt_X = sobel_stack_x[:N*C],",
"torch.cat([img1_wy, img0_wy, img0_wy, img1_wy], dim=1) return weights_x, weights_y def error_fn(x):",
"mask = F.pad(inner, [padding] * 4) return mask def forward(self,",
"the student to the teacher is given a smaller weight.",
"MeanShift([0.485, 0.456, 0.406], [0.229, 0.224, 0.225], norm=True).cuda() for param in",
"but worse in later epochs. # Moreover, Laplacian loss is",
"super(Ternary, self).__init__() patch_size = 7 out_channels = patch_size * patch_size",
"return mask def forward(self, img0, img1): img0 = self.transform(self.rgb2gray(img0)) img1",
"H, W = pred.shape[0], pred.shape[1], pred.shape[2], pred.shape[3] img_stack = torch.cat(",
"of the teacher. # If at some points, the warped",
"pred_X, gt_X = sobel_stack_x[:N*C], sobel_stack_x[N*C:] pred_Y, gt_Y = sobel_stack_y[:N*C], sobel_stack_y[N*C:]",
"= (flow - gt.detach()) ** 2 loss_map = (loss_map.sum(1, True)",
"h, w = t.size() inner = torch.ones(n, 1, h -",
"self.transform(self.rgb2gray(img0)) img1 = self.transform(self.rgb2gray(img1)) return self.hamming(img0, img1) * self.valid_mask(img0, 1)",
"== 'abs_robust': y = (torch.abs(x) + 0.01).pow(0.4) else: raise ValueError('')",
"is significantly slower. if use_lap_loss: loss_fun = LapLoss(max_levels=3, reduction='none') else:",
"significantly slower. if use_lap_loss: loss_fun = LapLoss(max_levels=3, reduction='none') else: loss_fun",
"self.bias.data = data_range * torch.Tensor(data_mean) self.requires_grad = False class VGGPerceptualLoss(torch.nn.Module):",
"0.01).float().detach() # loss_distill is the sum of the distillation losses",
"+ dy2.abs().mean() # 暂时不上二阶的平滑损失,似乎加上以后就太猛了,无法降低photo loss TODO return smooth_loss # flow",
"gradweight_xy(img0, img1): img0_gx, img0_gy = gradient_xy(img0) img1_gx, img1_gy = gradient_xy(img1)",
"g + 0.1140 * b return gray def hamming(self, t1,",
":] return gx, gy def gradweight_xy(img0, img1): img0_gx, img0_gy =",
"dim=1) return weights_x, weights_y def error_fn(x): if error_type == 'L1':",
"flow. So use img0 weights. # weights_x and weights_y are",
"img1 = self.transform(self.rgb2gray(img1)) return self.hamming(img0, img1) * self.valid_mask(img0, 1) class",
"+ 0.1140 * b return gray def hamming(self, t1, t2):",
"mid_gt).mean(1, True) # distill_mask indicates where the warped images according",
"weights. # weights_x and weights_y are for x and y's",
"<reponame>askerlee/rift import torch import numpy as np import torch.nn as",
"= self.transform(self.rgb2gray(img1)) return self.hamming(img0, img1) * self.valid_mask(img0, 1) class SOBEL(nn.Module):",
"def transform(self, img): patches = F.conv2d(img, self.w, padding=3, bias=None) transf",
"= False def forward(self, X, Y, indices=None): X = self.normalize(X)",
"= (student_error > teacher_error + 0.01).float().detach() # loss_distill is the",
"= 0 loss = 0 for i in range(indices[-1]): X",
"self.kernelX.clone().T self.kernelX = self.kernelX.unsqueeze(0).unsqueeze(0).to(device) self.kernelY = self.kernelY.unsqueeze(0).unsqueeze(0).to(device) def forward(self, pred,",
"self.kernelY.unsqueeze(0).unsqueeze(0).to(device) def forward(self, pred, gt): N, C, H, W =",
"should have 4 channels. # https://github.com/coolbeam/OIFlow/blob/main/utils/tools.py # weight_type='exp' seems to",
"out_channels)) self.w = np.transpose(self.w, (3, 2, 0, 1)) self.w =",
"Laplacian loss performs better in earlier epochs, but worse in",
"7, 12, 21, 30] weights = [1.0/2.6, 1.0/4.8, 1.0/3.7, 1.0/5.6,",
"1) if norm: self.weight.data.div_(std.view(c, 1, 1, 1)) self.bias.data = -1",
"has 4 channels). weights_x, weights_y = gradweight_xy(img0, img1) smoothness_x =",
"def __init__(self): super(Ternary, self).__init__() patch_size = 7 out_channels = patch_size",
"torch.cat( [pred.reshape(N*C, 1, H, W), gt.reshape(N*C, 1, H, W)], 0)",
"torch.eye(c).view(c, c, 1, 1) if norm: self.weight.data.div_(std.view(c, 1, 1, 1))",
"gray = 0.2989 * r + 0.5870 * g +",
"weight_type == 'exp': y = torch.abs(x) else: raise ValueError('') return",
"np.eye(out_channels).reshape( (patch_size, patch_size, 1, out_channels)) self.w = np.transpose(self.w, (3, 2,",
"= img[:, :, :-1, :] - img[:, :, 1:, :]",
"channels, same as flow_gx and flow_gy (if the input flow",
"* 0.1 k += 1 return loss # flow could",
"the student. distill_mask = (student_error > teacher_error + 0.01).float().detach() #",
"__name__ == '__main__': img0 = torch.zeros(3, 3, 256, 256).float().to(device) img1",
"2 * padding, w - 2 * padding).type_as(t) mask =",
"0 # Ws[0]: weight of teacher -> student. # Ws[1]:",
":-1] D_dy = x[:, :, 1:] - x[:, :, :-1]",
"/ 2 return loss_distill if __name__ == '__main__': img0 =",
"a y-flow should also be smooth along x-axis, and x-flow",
"as flow_gx and flow_gy (if the input flow has 4",
"# Moreover, Laplacian loss is significantly slower. if use_lap_loss: loss_fun",
"= LapLoss(max_levels=3, reduction='none') else: loss_fun = nn.L1Loss(reduction='none') for i in",
"= torch.abs(x) elif error_type == 'abs_robust': y = (torch.abs(x) +",
"def forward(self, flow, gt, loss_mask): loss_map = (flow - gt.detach())",
"= torch.cat( [pred.reshape(N*C, 1, H, W), gt.reshape(N*C, 1, H, W)],",
"self.kernelY = self.kernelY.unsqueeze(0).unsqueeze(0).to(device) def forward(self, pred, gt): N, C, H,",
"True) teacher_error = loss_fun(img_tea, mid_gt).mean(1, True) # distill_mask indicates where",
"__init__(self, rank=0): super(VGGPerceptualLoss, self).__init__() blocks = [] pretrained = True",
"= torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") class EPE(nn.Module): def __init__(self):",
"21, 30] weights = [1.0/2.6, 1.0/4.8, 1.0/3.7, 1.0/5.6, 10/1.5] k",
"calculate the distillation loss again. img_stu, flow_stu, img_tea, flow_tea =",
"So use img1 weights. # Second two flow channels: 0->1",
"# Laplacian loss performs better in earlier epochs, but worse",
"y = x ** 2 elif weight_type == 'exp': y",
"patches = F.conv2d(img, self.w, padding=3, bias=None) transf = patches -",
"== '__main__': img0 = torch.zeros(3, 3, 256, 256).float().to(device) img1 =",
"= self.kernelY.unsqueeze(0).unsqueeze(0).to(device) def forward(self, pred, gt): N, C, H, W",
"torch.tensor(np.random.normal( 0, 1, (3, 3, 256, 256))).float().to(device) ternary_loss = Ternary()",
"x-flow should also be smooth along y-axis. flow_gx, flow_gy =",
"self.kernelY = self.kernelX.clone().T self.kernelX = self.kernelX.unsqueeze(0).unsqueeze(0).to(device) self.kernelY = self.kernelY.unsqueeze(0).unsqueeze(0).to(device) def",
"slightly. def dual_teaching_loss(mid_gt, img_stu, flow_stu, img_tea, flow_tea): loss_distill = 0",
"# + dx2.abs().mean() + dxdy.abs().mean() + dydx.abs().mean() + dy2.abs().mean() #",
"= F.conv2d(img_stack, self.kernelX, padding=1) sobel_stack_y = F.conv2d(img_stack, self.kernelY, padding=1) pred_X,",
"D_dx = x[:, :, :, 1:] - x[:, :, :,",
"= loss_distill / 2 return loss_distill if __name__ == '__main__':",
"-1 * data_range * torch.Tensor(data_mean) self.bias.data.div_(std) else: self.weight.data.mul_(std.view(c, 1, 1,",
"is the sum of the distillation losses at 2 directions.",
"channels). weights_x, weights_y = gradweight_xy(img0, img1) smoothness_x = error_fn(flow_gx) *",
"flow_tea = \\ img_tea, flow_tea, img_stu, flow_stu # The distillation",
"gt_Y = sobel_stack_y[:N*C], sobel_stack_y[N*C:] L1X, L1Y = torch.abs(pred_X-gt_X), torch.abs(pred_Y-gt_Y) loss",
"weight_fn(x): if weight_type == 'gauss': y = x ** 2",
"else: raise ValueError('') return y # The flow gradients along",
"# First two flow channels: 1->0 flow. So use img1",
"dx2, dxdy = gradient(dx) # dydx, dy2 = gradient(dy) if",
"if __name__ == '__main__': img0 = torch.zeros(3, 3, 256, 256).float().to(device)",
"model.laplacian import LapLoss device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")",
"gradient(dx) dydx, dy2 = gradient(dy) smooth_loss = dx.abs().mean() + dy.abs().mean()",
"# No matter the flow is x- or y-flow, it",
"** 0.5 return (loss_map * loss_mask) class Ternary(nn.Module): def __init__(self):",
"# smooth_loss = dx.abs().mean() + dy.abs().mean() # + dx2.abs().mean() +",
"img1_gy), 1, keepdim=True)) # First two flow channels: 1->0 flow.",
"teacher is given a smaller weight. # loss_distill = loss_distill",
"weights. # Second two flow channels: 0->1 flow. So use",
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\") class EPE(nn.Module): def",
"be smooth along y-axis. flow_gx, flow_gy = gradient_xy(flow) # weights_x,",
"dy.abs().mean() # smooth_loss = dx.abs().mean() + dy.abs().mean() # + dx2.abs().mean()",
"flow_gx, flow_gy = gradient_xy(flow) # weights_x, weights_y both have 4",
"student -> teacher. # Two directions could take different weights.",
"use img0 weights. # weights_x and weights_y are for x",
"= torch.mean(dist / (0.1 + dist), 1, True) return dist_norm",
"smooth_loss # flow should have 4 channels. # https://github.com/coolbeam/OIFlow/blob/main/utils/tools.py #",
"'gauss': y = x ** 2 elif weight_type == 'exp':",
"later epochs. # Moreover, Laplacian loss is significantly slower. if",
"SOBEL(nn.Module): def __init__(self): super(SOBEL, self).__init__() self.kernelX = torch.tensor([ [1, 0,",
"img1): img0 = self.transform(self.rgb2gray(img0)) img1 = self.transform(self.rgb2gray(img1)) return self.hamming(img0, img1)",
"self.valid_mask(img0, 1) class SOBEL(nn.Module): def __init__(self): super(SOBEL, self).__init__() self.kernelX =",
"Y, indices=None): X = self.normalize(X) Y = self.normalize(Y) indices =",
"= len(data_mean) super(MeanShift, self).__init__(c, c, kernel_size=1) std = torch.Tensor(data_std) self.weight.data",
"weight_type='exp', error_type='L1'): def weight_fn(x): if weight_type == 'gauss': y =",
"-> student. # Ws[1]: weight of student -> teacher. #",
"flow_stu).abs() * distill_mask).mean() # Swap student and teacher, and calculate",
"= MeanShift([0.485, 0.456, 0.406], [0.229, 0.224, 0.225], norm=True).cuda() for param",
"1, (3, 3, 256, 256))).float().to(device) ternary_loss = Ternary() print(ternary_loss(img0, img1).shape)",
"0.5 return (loss_map * loss_mask) class Ternary(nn.Module): def __init__(self): super(Ternary,",
":-1] return D_dx, D_dy dx, dy = gradient(flow) # dx2,",
"class Ternary(nn.Module): def __init__(self): super(Ternary, self).__init__() patch_size = 7 out_channels",
"0.5] use_lap_loss = False # Laplacian loss performs better in",
"= torch.zeros(3, 3, 256, 256).float().to(device) img1 = torch.tensor(np.random.normal( 0, 1,",
"F.conv2d(img_stack, self.kernelX, padding=1) sobel_stack_y = F.conv2d(img_stack, self.kernelY, padding=1) pred_X, gt_X",
"the flow at these points are more accurate, and use",
"torch import numpy as np import torch.nn as nn import",
"= torch.cat([img1_wx, img1_wx, img0_wx, img0_wx], dim=1) weights_y = torch.cat([img1_wy, img0_wy,",
"loss again. img_stu, flow_stu, img_tea, flow_tea = \\ img_tea, flow_tea,",
"gradient(dy) if if_second_order: dx2, dxdy = gradient(dx) dydx, dy2 =",
"dy.abs().mean() # + dx2.abs().mean() + dxdy.abs().mean() + dydx.abs().mean() + dy2.abs().mean()",
"from model.laplacian import LapLoss device = torch.device(\"cuda\" if torch.cuda.is_available() else",
"gt_X = sobel_stack_x[:N*C], sobel_stack_x[N*C:] pred_Y, gt_Y = sobel_stack_y[:N*C], sobel_stack_y[N*C:] L1X,",
"gradient_xy(flow) # weights_x, weights_y both have 4 channels, same as",
"blocks = [] pretrained = True self.vgg_pretrained_features = models.vgg19(pretrained=pretrained).features self.normalize",
"* patch_size self.w = np.eye(out_channels).reshape( (patch_size, patch_size, 1, out_channels)) self.w",
"MeanShift(nn.Conv2d): def __init__(self, data_mean, data_std, data_range=1, norm=True): c = len(data_mean)",
"Set Ws[1] to 0 to disable student -> teacher. Ws",
"img1) smoothness_x = error_fn(flow_gx) * weights_x smoothness_y = error_fn(flow_gy) *",
"img1_wx, img0_wx, img0_wx], dim=1) weights_y = torch.cat([img1_wy, img0_wy, img0_wy, img1_wy],",
"warped images according to student's prediction # is worse than",
"self.vgg_pretrained_features = models.vgg19(pretrained=pretrained).features self.normalize = MeanShift([0.485, 0.456, 0.406], [0.229, 0.224,",
"True) + 1e-6) ** 0.5 return (loss_map * loss_mask) class",
"than the student, # then regard the flow at these",
"X, Y, indices=None): X = self.normalize(X) Y = self.normalize(Y) indices",
"img1 weights. # Second two flow channels: 0->1 flow. So",
"= np.eye(out_channels).reshape( (patch_size, patch_size, 1, out_channels)) self.w = np.transpose(self.w, (3,",
"img[:, :, 1:, :] return gx, gy def gradweight_xy(img0, img1):",
"loss_fun = LapLoss(max_levels=3, reduction='none') else: loss_fun = nn.L1Loss(reduction='none') for i",
"x ** 2 elif weight_type == 'exp': y = torch.abs(x)",
"else \"cpu\") class EPE(nn.Module): def __init__(self): super(EPE, self).__init__() def forward(self,",
"# Ws[0]: weight of teacher -> student. # Ws[1]: weight",
"class EPE(nn.Module): def __init__(self): super(EPE, self).__init__() def forward(self, flow, gt,",
"flow, gt, loss_mask): loss_map = (flow - gt.detach()) ** 2",
"Ws[0]: weight of teacher -> student. # Ws[1]: weight of",
"((flow_tea.detach() - flow_stu).abs() * distill_mask).mean() # Swap student and teacher,",
"# loss_distill = loss_distill / 2 return loss_distill if __name__",
"smoothness_x = error_fn(flow_gx) * weights_x smoothness_y = error_fn(flow_gy) * weights_y",
"numpy as np import torch.nn as nn import torch.nn.functional as",
"img1): img0_gx, img0_gy = gradient_xy(img0) img1_gx, img1_gy = gradient_xy(img1) img0_wx",
"= 0.2989 * r + 0.5870 * g + 0.1140",
"sobel_stack_x = F.conv2d(img_stack, self.kernelX, padding=1) sobel_stack_y = F.conv2d(img_stack, self.kernelY, padding=1)",
"First two flow channels: 1->0 flow. So use img1 weights.",
"c, kernel_size=1) std = torch.Tensor(data_std) self.weight.data = torch.eye(c).view(c, c, 1,",
"is better than the student, # then regard the flow",
"1, 1)) self.bias.data = data_range * torch.Tensor(data_mean) self.requires_grad = False",
"[1, 0, -1], ]).float() self.kernelY = self.kernelX.clone().T self.kernelX = self.kernelX.unsqueeze(0).unsqueeze(0).to(device)",
"img0 weights. # weights_x and weights_y are for x and",
"img0_wy = torch.exp(-torch.mean(weight_fn(constant * img0_gy), 1, keepdim=True)) img1_wx = torch.exp(-torch.mean(weight_fn(constant",
"self.weight.data = torch.eye(c).view(c, c, 1, 1) if norm: self.weight.data.div_(std.view(c, 1,",
"error_fn(x): if error_type == 'L1': y = torch.abs(x) elif error_type",
"x and y axes. # I.e., a y-flow should also",
"std = torch.Tensor(data_std) self.weight.data = torch.eye(c).view(c, c, 1, 1) if",
"# dydx, dy2 = gradient(dy) if if_second_order: dx2, dxdy =",
"return self.hamming(img0, img1) * self.valid_mask(img0, 1) class SOBEL(nn.Module): def __init__(self):",
"super(SOBEL, self).__init__() self.kernelX = torch.tensor([ [1, 0, -1], [2, 0,",
"flow has 4 channels). weights_x, weights_y = gradweight_xy(img0, img1) smoothness_x",
"torch.Tensor(data_std) self.weight.data = torch.eye(c).view(c, c, 1, 1) if norm: self.weight.data.div_(std.view(c,",
"1:] - x[:, :, :-1] return D_dx, D_dy dx, dy",
"gx = img[:, :, :, :-1] - img[:, :, :,",
"* loss_mask) class Ternary(nn.Module): def __init__(self): super(Ternary, self).__init__() patch_size =",
"Moreover, Laplacian loss is significantly slower. if use_lap_loss: loss_fun =",
"flow_gy (if the input flow has 4 channels). weights_x, weights_y",
"= torch.Tensor(data_std) self.weight.data = torch.eye(c).view(c, c, 1, 1) if norm:",
"0->1 flow. So use img0 weights. # weights_x and weights_y",
"self.normalize(Y) indices = [2, 7, 12, 21, 30] weights =",
"Y.detach()).abs().mean() * 0.1 k += 1 return loss # flow",
"x[:, :, :, :-1] D_dy = x[:, :, 1:] -",
"0.224, 0.225], norm=True).cuda() for param in self.parameters(): param.requires_grad = False",
"img0_wx = torch.exp(-torch.mean(weight_fn(constant * img0_gx), 1, keepdim=True)) img0_wy = torch.exp(-torch.mean(weight_fn(constant"
] |
[
"wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [0., 1., 0], (0., 0., 0.5,",
"[] # update the controllers if self.time > 1.0: for",
"0., 0., 1.)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-7.,",
"#reset message received pos1, or1 = r.get_pos_and_orientation() for j,r2 in",
"Add objects wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [0., -1., 0], (0.,",
"for j,r2 in enumerate(self.robots): if(r.id != r2.id): pos2, or2 =",
"#arena # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2, 4., 0],",
"p.resetBasePositionAndOrientation(wallId, [-5., 3., 0], (0., 0., 0., 1.)) # wallId",
"import numpy as np import pybullet as p import itertools",
"id r.messages_to_send = [] # update the controllers if self.time",
"def reset(self): \"\"\" Resets the position of all the robots",
"0.0)) # Add objects wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [0., -1.,",
"in self.robots: r.compute_controller() # do one simulation step p.stepSimulation() self.time",
"[-2., 7., 0], (0., 0., 0.5, 0.5)) # wallId =",
"p.resetBasePositionAndOrientation(wallId, [-2., 9., 0], (0., 0., 0.5, 0.5)) # wallId",
"= p.connect(p.GUI) p.setGravity(0,0,-9.81) self.max_communication_distance = 2.0 # We will integrate",
"12., 0], (0., 0., 0.5, 0.5)) # create 6 robots",
"self.goalId = p.loadURDF(\"../models/goal2.urdf\") # the balls self.ball1 = p.loadURDF(\"../models/ball1.urdf\") p.resetBasePositionAndOrientation(self.ball1,",
"1.)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8, 4., 0],",
"0], (0., 0., 0., 1.)) # tube # wallId =",
"1.0: for r in self.robots: r.compute_controller() # do one simulation",
"self.max_communication_distance = 2.0 # We will integrate every 4ms (250Hz",
"import itertools from robot import Robot class World(): def __init__(self):",
"# p.resetBasePositionAndOrientation(wallId, [-2., 9., 0], (0., 0., 0.5, 0.5)) #",
"p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-3., 3., 0], (0., 0., 0., 1.))",
"9., 0], (0., 0., 0.5, 0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0]",
"create 6 robots self.robots = [] for (i,j) in itertools.product(range(3),",
"0.5, 0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-3., 3.,",
"send and receive messages for i,r in enumerate(self.robots): for msg",
"0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8., 6., 0],",
"0.5, 0.5)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [3., 1., 0], (0.,",
"p.loadURDF(\"../models/ball2.urdf\") p.resetBasePositionAndOrientation(self.ball2, [4., 2., 0.5], (0., 0., 0.5, 0.5)) p.resetDebugVisualizerCamera(7.0,90.0,",
"0], (0., 0., 0., 1.)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [2.,",
"# p.resetBasePositionAndOrientation(wallId, [-5., 3., 0], (0., 0., 0., 1.)) #",
"wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-1., 6., 0], (0., 0.,",
"= p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8., 6., 0], (0., 0., 0.5,",
"range(2)): self.robots.append(Robot([1. * i + 0.5, 1. * j -",
"self.max_communication_distance): r.neighbors.append(j) # for each robot send and receive messages",
"(0., 0., 0.5, 0.5)) self.ball2 = p.loadURDF(\"../models/ball2.urdf\") p.resetBasePositionAndOrientation(self.ball2, [4., 2.,",
"# Create the plane. self.planeId = p.loadURDF(\"../models/plane.urdf\") p.changeDynamics(self.planeId, -1, lateralFriction=5.,",
"in itertools.product(range(3), range(2)): self.robots.append(Robot([1. * i + 0.5, 1. *",
"controllers if self.time > 1.0: for r in self.robots: r.compute_controller()",
"# p.resetBasePositionAndOrientation(wallId, [-8., 10., 0], (0., 0., 0.5, 0.5)) #",
"Create the plane. self.planeId = p.loadURDF(\"../models/plane.urdf\") p.changeDynamics(self.planeId, -1, lateralFriction=5., rollingFriction=0)",
"0.5, 0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2., 11.,",
"i,r in enumerate(self.robots): for msg in r.messages_to_send: if msg[0] in",
"= p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8., 12., 0], (0., 0., 0.5,",
"import Robot class World(): def __init__(self): # create the physics",
"numSubSteps=1) # Create the plane. self.planeId = p.loadURDF(\"../models/plane.urdf\") p.changeDynamics(self.planeId, -1,",
"pybullet as p import itertools from robot import Robot class",
"2., 0], (0., 0., 0., 1.)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId,",
"[-8, 4., 0], (0., 0., 0.5, 0.5)) # wallId =",
"(0., 0., 0.5, 0.5)) p.resetDebugVisualizerCamera(7.0,90.0, -43.0, (1., 1., 0.0)) #",
"the plane. self.planeId = p.loadURDF(\"../models/plane.urdf\") p.changeDynamics(self.planeId, -1, lateralFriction=5., rollingFriction=0) self.goalId",
"# wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2., 11., 0], (0.,",
"if self.time > 1.0: for r in self.robots: r.compute_controller() #",
"r.compute_controller() # do one simulation step p.stepSimulation() self.time += self.dt",
"wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [1., 2., 0], (0., 0., 0.,",
"# p.resetBasePositionAndOrientation(wallId, [-7., 3., 0], (0., 0., 0., 1.)) #",
"p.resetBasePositionAndOrientation(wallId, [3., 1., 0], (0., 0., 0.5, 0.5)) wallId =",
"# p.resetBasePositionAndOrientation(wallId, [-8., 6., 0], (0., 0., 0.5, 0.5)) #",
"# p.resetBasePositionAndOrientation(wallId, [-8, 4., 0], (0., 0., 0.5, 0.5)) #",
"10., 0], (0., 0., 0.5, 0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0]",
"0.5)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [1., 2., 0], (0., 0.,",
"2*i+j, self.dt)) p.stepSimulation() self.time = 0.0 self.stepSimulation() self.stepSimulation() def reset(self):",
"# Add objects wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [0., -1., 0],",
"0., 0., 1.)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [2., -2., 0],",
"the controllers if self.time > 1.0: for r in self.robots:",
"0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-3., 3., 0],",
"0.5, 0.3], 2*i+j, self.dt)) p.stepSimulation() self.time = 0.0 self.stepSimulation() self.stepSimulation()",
"p.resetBasePositionAndOrientation(wallId, [-3., 3., 0], (0., 0., 0., 1.)) # wallId",
"wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [2., -2., 0], (0., 0., 0.,",
"\"\"\" # for each robot construct list of neighbors for",
"p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2., 11., 0], (0., 0., 0.5, 0.5))",
"0], (0., 0., 0., 1.)) # #arena # wallId =",
"0., 0.5, 0.5)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [0., 1., 0],",
"of neighbors for r in self.robots: r.neighbors = [] #reset",
"one step simulation \"\"\" # for each robot construct list",
"p.resetBasePositionAndOrientation(wallId, [2., -2., 0], (0., 0., 0., 1.)) # tube",
"(0., 0., 0., 1.)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId,",
"msg[1]]) #add the sender id r.messages_to_send = [] # update",
"p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8., 10., 0], (0., 0., 0.5, 0.5))",
"neighbors for r in self.robots: r.neighbors = [] #reset neighbors",
"self.stepSimulation() self.stepSimulation() def reset(self): \"\"\" Resets the position of all",
"self.robots: r.neighbors = [] #reset neighbors r.messages_received = [] #reset",
"!= r2.id): pos2, or2 = r2.get_pos_and_orientation() if(np.linalg.norm(pos1-pos2) < self.max_communication_distance): r.neighbors.append(j)",
"= 2.0 # We will integrate every 4ms (250Hz update)",
"# #arena # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2, 4.,",
"self.robots: r.compute_controller() # do one simulation step p.stepSimulation() self.time +=",
"1.)) # #arena # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2,",
"(0., 0., 0.5, 0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId,",
"0.5, 0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8., 10.,",
"from robot import Robot class World(): def __init__(self): # create",
"self.dt = 1./250. p.setPhysicsEngineParameter(self.dt, numSubSteps=1) # Create the plane. self.planeId",
"p.setGravity(0,0,-9.81) self.max_communication_distance = 2.0 # We will integrate every 4ms",
"# p.resetBasePositionAndOrientation(wallId, [-2., 13., 0], (0., 0., 0.5, 0.5)) #",
"# the balls self.ball1 = p.loadURDF(\"../models/ball1.urdf\") p.resetBasePositionAndOrientation(self.ball1, [2., 4., 0.5],",
"p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-7., 3., 0], (0., 0., 0., 1.))",
"as np import pybullet as p import itertools from robot",
"wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-5., 3., 0], (0., 0.,",
"= p.loadURDF(\"../models/ball1.urdf\") p.resetBasePositionAndOrientation(self.ball1, [2., 4., 0.5], (0., 0., 0.5, 0.5))",
"\"\"\" Simulates one step simulation \"\"\" # for each robot",
"4ms (250Hz update) self.dt = 1./250. p.setPhysicsEngineParameter(self.dt, numSubSteps=1) # Create",
"[-1., 6., 0], (0., 0., 0., 1.)) # #arena #",
"self.goalId = p.loadURDF(\"../models/goal.urdf\") self.goalId = p.loadURDF(\"../models/goal2.urdf\") # the balls self.ball1",
"p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [3., -1., 0], (0., 0., 0.5, 0.5)) wallId",
"or1 = r.get_pos_and_orientation() for j,r2 in enumerate(self.robots): if(r.id != r2.id):",
"msg[0] in r.neighbors: #then we can send the message self.robots[msg[0]].messages_received.append([i,",
"position of all the robots \"\"\" for r in self.robots:",
"= p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [0., -1., 0], (0., 0., 0.5, 0.5))",
"-2., 0], (0., 0., 0., 1.)) # tube # wallId",
"for r in self.robots: r.compute_controller() # do one simulation step",
"for msg in r.messages_to_send: if msg[0] in r.neighbors: #then we",
"= p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [3., 1., 0], (0., 0., 0.5, 0.5))",
"if(r.id != r2.id): pos2, or2 = r2.get_pos_and_orientation() if(np.linalg.norm(pos1-pos2) < self.max_communication_distance):",
"(0., 0., 0.5, 0.5)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [0., 1.,",
"0.5, 0.5)) # create 6 robots self.robots = [] for",
"[-2., 13., 0], (0., 0., 0.5, 0.5)) # wallId =",
"p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [0., -1., 0], (0., 0., 0.5, 0.5)) wallId",
"1.)) # tube # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-1.,",
"[1., 2., 0], (0., 0., 0., 1.)) wallId = p.loadSDF(\"../models/walls.sdf\")[0]",
"# wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-1., 5., 0], (0.,",
"np import pybullet as p import itertools from robot import",
"Simulates one step simulation \"\"\" # for each robot construct",
"simulation \"\"\" # for each robot construct list of neighbors",
"0.3], 2*i+j, self.dt)) p.stepSimulation() self.time = 0.0 self.stepSimulation() self.stepSimulation() def",
"[-8., 8., 0], (0., 0., 0.5, 0.5)) # wallId =",
"\"\"\" for r in self.robots: r.reset() p.stepSimulation() def stepSimulation(self): \"\"\"",
"p.changeDynamics(self.planeId, -1, lateralFriction=5., rollingFriction=0) self.goalId = p.loadURDF(\"../models/goal.urdf\") self.goalId = p.loadURDF(\"../models/goal2.urdf\")",
"[-2., 9., 0], (0., 0., 0.5, 0.5)) # wallId =",
"= p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [2., -2., 0], (0., 0., 0., 1.))",
"robots self.robots = [] for (i,j) in itertools.product(range(3), range(2)): self.robots.append(Robot([1.",
"the sender id r.messages_to_send = [] # update the controllers",
"0], (0., 0., 0.5, 0.5)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [3.,",
"2., 0.5], (0., 0., 0.5, 0.5)) p.resetDebugVisualizerCamera(7.0,90.0, -43.0, (1., 1.,",
"3., 0], (0., 0., 0., 1.)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0]",
"(0., 0., 0., 1.)) # #arena # wallId = p.loadSDF(\"../models/walls.sdf\")[0]",
"enumerate(self.robots): if(r.id != r2.id): pos2, or2 = r2.get_pos_and_orientation() if(np.linalg.norm(pos1-pos2) <",
"sender id r.messages_to_send = [] # update the controllers if",
"p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [1., 2., 0], (0., 0., 0., 1.)) wallId",
"(i,j) in itertools.product(range(3), range(2)): self.robots.append(Robot([1. * i + 0.5, 1.",
"msg in r.messages_to_send: if msg[0] in r.neighbors: #then we can",
"0.5], (0., 0., 0.5, 0.5)) self.ball2 = p.loadURDF(\"../models/ball2.urdf\") p.resetBasePositionAndOrientation(self.ball2, [4.,",
"(250Hz update) self.dt = 1./250. p.setPhysicsEngineParameter(self.dt, numSubSteps=1) # Create the",
"# wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2, 4., 0], (0.,",
"integrate every 4ms (250Hz update) self.dt = 1./250. p.setPhysicsEngineParameter(self.dt, numSubSteps=1)",
"[3., -1., 0], (0., 0., 0.5, 0.5)) wallId = p.loadSDF(\"../models/walls.sdf\")[0]",
"= p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-1., 5., 0], (0., 0., 0.,",
"self.stepSimulation() def reset(self): \"\"\" Resets the position of all the",
"r2.get_pos_and_orientation() if(np.linalg.norm(pos1-pos2) < self.max_communication_distance): r.neighbors.append(j) # for each robot send",
"enumerate(self.robots): for msg in r.messages_to_send: if msg[0] in r.neighbors: #then",
"pos2, or2 = r2.get_pos_and_orientation() if(np.linalg.norm(pos1-pos2) < self.max_communication_distance): r.neighbors.append(j) # for",
"message self.robots[msg[0]].messages_received.append([i, msg[1]]) #add the sender id r.messages_to_send = []",
"0.5, 1. * j - 0.5, 0.3], 2*i+j, self.dt)) p.stepSimulation()",
"= p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8., 8., 0], (0., 0., 0.5,",
"+ 0.5, 1. * j - 0.5, 0.3], 2*i+j, self.dt))",
"numpy as np import pybullet as p import itertools from",
"in enumerate(self.robots): if(r.id != r2.id): pos2, or2 = r2.get_pos_and_orientation() if(np.linalg.norm(pos1-pos2)",
"robot send and receive messages for i,r in enumerate(self.robots): for",
"robots \"\"\" for r in self.robots: r.reset() p.stepSimulation() def stepSimulation(self):",
"0., 0., 1.)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-5.,",
"* i + 0.5, 1. * j - 0.5, 0.3],",
"[] #reset message received pos1, or1 = r.get_pos_and_orientation() for j,r2",
"[4., 2., 0.5], (0., 0., 0.5, 0.5)) p.resetDebugVisualizerCamera(7.0,90.0, -43.0, (1.,",
"0.0 self.stepSimulation() self.stepSimulation() def reset(self): \"\"\" Resets the position of",
"r in self.robots: r.compute_controller() # do one simulation step p.stepSimulation()",
"= p.loadURDF(\"../models/ball2.urdf\") p.resetBasePositionAndOrientation(self.ball2, [4., 2., 0.5], (0., 0., 0.5, 0.5))",
"(0., 0., 0.5, 0.5)) # create 6 robots self.robots =",
"simulator self.physicsClient = p.connect(p.GUI) p.setGravity(0,0,-9.81) self.max_communication_distance = 2.0 # We",
"World(): def __init__(self): # create the physics simulator self.physicsClient =",
"p.resetBasePositionAndOrientation(wallId, [1., 2., 0], (0., 0., 0., 1.)) wallId =",
"(1., 1., 0.0)) # Add objects wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId,",
"for r in self.robots: r.neighbors = [] #reset neighbors r.messages_received",
"p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2., 13., 0], (0., 0., 0.5, 0.5))",
"[-2., 11., 0], (0., 0., 0.5, 0.5)) # wallId =",
"and receive messages for i,r in enumerate(self.robots): for msg in",
"[] #reset neighbors r.messages_received = [] #reset message received pos1,",
"r.neighbors: #then we can send the message self.robots[msg[0]].messages_received.append([i, msg[1]]) #add",
"[] for (i,j) in itertools.product(range(3), range(2)): self.robots.append(Robot([1. * i +",
"p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2, 4., 0], (0., 0., 0.5, 0.5))",
"send the message self.robots[msg[0]].messages_received.append([i, msg[1]]) #add the sender id r.messages_to_send",
"[-8., 6., 0], (0., 0., 0.5, 0.5)) # wallId =",
"stepSimulation(self): \"\"\" Simulates one step simulation \"\"\" # for each",
"in self.robots: r.reset() p.stepSimulation() def stepSimulation(self): \"\"\" Simulates one step",
"self.robots: r.reset() p.stepSimulation() def stepSimulation(self): \"\"\" Simulates one step simulation",
"= p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8, 4., 0], (0., 0., 0.5,",
"# wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2., 9., 0], (0.,",
"wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [3., -1., 0], (0., 0., 0.5,",
"= p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-7., 3., 0], (0., 0., 0.,",
"r.messages_to_send: if msg[0] in r.neighbors: #then we can send the",
"each robot construct list of neighbors for r in self.robots:",
"0., 0.5, 0.5)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [3., -1., 0],",
"p import itertools from robot import Robot class World(): def",
"# wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8., 8., 0], (0.,",
"p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-1., 5., 0], (0., 0., 0., 1.))",
"5., 0], (0., 0., 0., 1.)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0]",
"# wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2., 7., 0], (0.,",
"physics simulator self.physicsClient = p.connect(p.GUI) p.setGravity(0,0,-9.81) self.max_communication_distance = 2.0 #",
"We will integrate every 4ms (250Hz update) self.dt = 1./250.",
"0], (0., 0., 0.5, 0.5)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [1.,",
"p.resetBasePositionAndOrientation(wallId, [-2., 13., 0], (0., 0., 0.5, 0.5)) # wallId",
"0., 0., 1.)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-1.,",
"(0., 0., 0.5, 0.5)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [3., 1.,",
"0.5)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [0., 1., 0], (0., 0.,",
"0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2., 7., 0],",
"reset(self): \"\"\" Resets the position of all the robots \"\"\"",
"can send the message self.robots[msg[0]].messages_received.append([i, msg[1]]) #add the sender id",
"6., 0], (0., 0., 0., 1.)) # #arena # wallId",
"0., 0., 1.)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8,",
"= r2.get_pos_and_orientation() if(np.linalg.norm(pos1-pos2) < self.max_communication_distance): r.neighbors.append(j) # for each robot",
"0., 1.)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-1., 6.,",
"the position of all the robots \"\"\" for r in",
"r in self.robots: r.neighbors = [] #reset neighbors r.messages_received =",
"p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8., 12., 0], (0., 0., 0.5, 0.5))",
"# p.resetBasePositionAndOrientation(wallId, [-2, 4., 0], (0., 0., 0.5, 0.5)) #",
"wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-1., 5., 0], (0., 0.,",
"= p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2., 9., 0], (0., 0., 0.5,",
"p.resetBasePositionAndOrientation(wallId, [-8, 4., 0], (0., 0., 0.5, 0.5)) # wallId",
"# p.resetBasePositionAndOrientation(wallId, [-8., 12., 0], (0., 0., 0.5, 0.5)) #",
"#reset neighbors r.messages_received = [] #reset message received pos1, or1",
"[-7., 3., 0], (0., 0., 0., 1.)) # wallId =",
"# wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-7., 3., 0], (0.,",
"= p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-3., 3., 0], (0., 0., 0.,",
"# wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-1., 6., 0], (0.,",
"0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2., 13., 0],",
"> 1.0: for r in self.robots: r.compute_controller() # do one",
"wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8., 10., 0], (0., 0.,",
"* j - 0.5, 0.3], 2*i+j, self.dt)) p.stepSimulation() self.time =",
"p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [0., 1., 0], (0., 0., 0.5, 0.5)) wallId",
"0., 0., 1.)) # tube # wallId = p.loadSDF(\"../models/walls.sdf\")[0] #",
"0], (0., 0., 0.5, 0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] #",
"r.neighbors.append(j) # for each robot send and receive messages for",
"0.5, 0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8., 8.,",
"Robot class World(): def __init__(self): # create the physics simulator",
"0.5)) self.ball2 = p.loadURDF(\"../models/ball2.urdf\") p.resetBasePositionAndOrientation(self.ball2, [4., 2., 0.5], (0., 0.,",
"= p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2, 4., 0], (0., 0., 0.5,",
"itertools from robot import Robot class World(): def __init__(self): #",
"rollingFriction=0) self.goalId = p.loadURDF(\"../models/goal.urdf\") self.goalId = p.loadURDF(\"../models/goal2.urdf\") # the balls",
"all the robots \"\"\" for r in self.robots: r.reset() p.stepSimulation()",
"7., 0], (0., 0., 0.5, 0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0]",
"0., 1.)) # tube # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId,",
"0., 1.)) # #arena # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId,",
"for r in self.robots: r.reset() p.stepSimulation() def stepSimulation(self): \"\"\" Simulates",
"p.stepSimulation() self.time = 0.0 self.stepSimulation() self.stepSimulation() def reset(self): \"\"\" Resets",
"0.5, 0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8., 12.,",
"(0., 0., 0.5, 0.5)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [1., 2.,",
"0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8., 12., 0],",
"1.)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-1., 6., 0],",
"# p.resetBasePositionAndOrientation(wallId, [-3., 3., 0], (0., 0., 0., 1.)) #",
"wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2, 4., 0], (0., 0.,",
"0.5, 0.5)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [0., 1., 0], (0.,",
"# wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8., 6., 0], (0.,",
"0.5], (0., 0., 0.5, 0.5)) p.resetDebugVisualizerCamera(7.0,90.0, -43.0, (1., 1., 0.0))",
"Resets the position of all the robots \"\"\" for r",
"6 robots self.robots = [] for (i,j) in itertools.product(range(3), range(2)):",
"update the controllers if self.time > 1.0: for r in",
"= p.loadURDF(\"../models/plane.urdf\") p.changeDynamics(self.planeId, -1, lateralFriction=5., rollingFriction=0) self.goalId = p.loadURDF(\"../models/goal.urdf\") self.goalId",
"p.resetBasePositionAndOrientation(wallId, [0., -1., 0], (0., 0., 0.5, 0.5)) wallId =",
"robot import Robot class World(): def __init__(self): # create the",
"step simulation \"\"\" # for each robot construct list of",
"= p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [0., 1., 0], (0., 0., 0.5, 0.5))",
"update) self.dt = 1./250. p.setPhysicsEngineParameter(self.dt, numSubSteps=1) # Create the plane.",
"if(np.linalg.norm(pos1-pos2) < self.max_communication_distance): r.neighbors.append(j) # for each robot send and",
"r in self.robots: r.reset() p.stepSimulation() def stepSimulation(self): \"\"\" Simulates one",
"1.)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-5., 3., 0],",
"p.resetBasePositionAndOrientation(wallId, [-7., 3., 0], (0., 0., 0., 1.)) # wallId",
"# create the physics simulator self.physicsClient = p.connect(p.GUI) p.setGravity(0,0,-9.81) self.max_communication_distance",
"(0., 0., 0., 1.)) # tube # wallId = p.loadSDF(\"../models/walls.sdf\")[0]",
"# for each robot send and receive messages for i,r",
"0., 1.)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [2., -2., 0], (0.,",
"def __init__(self): # create the physics simulator self.physicsClient = p.connect(p.GUI)",
"wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [0., -1., 0], (0., 0., 0.5,",
"if msg[0] in r.neighbors: #then we can send the message",
"1./250. p.setPhysicsEngineParameter(self.dt, numSubSteps=1) # Create the plane. self.planeId = p.loadURDF(\"../models/plane.urdf\")",
"[-8., 12., 0], (0., 0., 0.5, 0.5)) # create 6",
"tube # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-1., 5., 0],",
"self.physicsClient = p.connect(p.GUI) p.setGravity(0,0,-9.81) self.max_communication_distance = 2.0 # We will",
"p.loadURDF(\"../models/ball1.urdf\") p.resetBasePositionAndOrientation(self.ball1, [2., 4., 0.5], (0., 0., 0.5, 0.5)) self.ball2",
"#add the sender id r.messages_to_send = [] # update the",
"# wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2., 13., 0], (0.,",
"self.dt)) p.stepSimulation() self.time = 0.0 self.stepSimulation() self.stepSimulation() def reset(self): \"\"\"",
"< self.max_communication_distance): r.neighbors.append(j) # for each robot send and receive",
"0., 0., 1.)) # #arena # wallId = p.loadSDF(\"../models/walls.sdf\")[0] #",
"= p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2., 11., 0], (0., 0., 0.5,",
"self.ball2 = p.loadURDF(\"../models/ball2.urdf\") p.resetBasePositionAndOrientation(self.ball2, [4., 2., 0.5], (0., 0., 0.5,",
"# wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8., 10., 0], (0.,",
"for each robot send and receive messages for i,r in",
"[2., -2., 0], (0., 0., 0., 1.)) # tube #",
"(0., 0., 0.5, 0.5)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [3., -1.,",
"0., 1.)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8, 4.,",
"self.time > 1.0: for r in self.robots: r.compute_controller() # do",
"6., 0], (0., 0., 0.5, 0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0]",
"0.5, 0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8., 6.,",
"= 1./250. p.setPhysicsEngineParameter(self.dt, numSubSteps=1) # Create the plane. self.planeId =",
"0., 0.5, 0.5)) self.ball2 = p.loadURDF(\"../models/ball2.urdf\") p.resetBasePositionAndOrientation(self.ball2, [4., 2., 0.5],",
"0., 0.5, 0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2.,",
"the balls self.ball1 = p.loadURDF(\"../models/ball1.urdf\") p.resetBasePositionAndOrientation(self.ball1, [2., 4., 0.5], (0.,",
"0.5, 0.5)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [1., 2., 0], (0.,",
"(0., 0., 0., 1.)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [2., -2.,",
"self.ball1 = p.loadURDF(\"../models/ball1.urdf\") p.resetBasePositionAndOrientation(self.ball1, [2., 4., 0.5], (0., 0., 0.5,",
"# p.resetBasePositionAndOrientation(wallId, [-8., 8., 0], (0., 0., 0.5, 0.5)) #",
"8., 0], (0., 0., 0.5, 0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0]",
"wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8, 4., 0], (0., 0.,",
"# wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8., 12., 0], (0.,",
"- 0.5, 0.3], 2*i+j, self.dt)) p.stepSimulation() self.time = 0.0 self.stepSimulation()",
"wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8., 8., 0], (0., 0.,",
"in r.messages_to_send: if msg[0] in r.neighbors: #then we can send",
"= p.loadURDF(\"../models/goal.urdf\") self.goalId = p.loadURDF(\"../models/goal2.urdf\") # the balls self.ball1 =",
"0.5)) # create 6 robots self.robots = [] for (i,j)",
"j,r2 in enumerate(self.robots): if(r.id != r2.id): pos2, or2 = r2.get_pos_and_orientation()",
"1., 0.0)) # Add objects wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [0.,",
"each robot send and receive messages for i,r in enumerate(self.robots):",
"r.get_pos_and_orientation() for j,r2 in enumerate(self.robots): if(r.id != r2.id): pos2, or2",
"self.robots[msg[0]].messages_received.append([i, msg[1]]) #add the sender id r.messages_to_send = [] #",
"p.stepSimulation() def stepSimulation(self): \"\"\" Simulates one step simulation \"\"\" #",
"self.robots.append(Robot([1. * i + 0.5, 1. * j - 0.5,",
"0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8., 10., 0],",
"0.5, 0.5)) p.resetDebugVisualizerCamera(7.0,90.0, -43.0, (1., 1., 0.0)) # Add objects",
"0., 0.5, 0.5)) p.resetDebugVisualizerCamera(7.0,90.0, -43.0, (1., 1., 0.0)) # Add",
"j - 0.5, 0.3], 2*i+j, self.dt)) p.stepSimulation() self.time = 0.0",
"for each robot construct list of neighbors for r in",
"p.resetBasePositionAndOrientation(wallId, [-8., 6., 0], (0., 0., 0.5, 0.5)) # wallId",
"[-5., 3., 0], (0., 0., 0., 1.)) # wallId =",
"p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8, 4., 0], (0., 0., 0.5, 0.5))",
"p.resetBasePositionAndOrientation(wallId, [-8., 12., 0], (0., 0., 0.5, 0.5)) # create",
"wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [3., 1., 0], (0., 0., 0.5,",
"p.resetBasePositionAndOrientation(wallId, [-8., 10., 0], (0., 0., 0.5, 0.5)) # wallId",
"or2 = r2.get_pos_and_orientation() if(np.linalg.norm(pos1-pos2) < self.max_communication_distance): r.neighbors.append(j) # for each",
"class World(): def __init__(self): # create the physics simulator self.physicsClient",
"= [] # update the controllers if self.time > 1.0:",
"p.resetBasePositionAndOrientation(wallId, [-8., 8., 0], (0., 0., 0.5, 0.5)) # wallId",
"-1., 0], (0., 0., 0.5, 0.5)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId,",
"r2.id): pos2, or2 = r2.get_pos_and_orientation() if(np.linalg.norm(pos1-pos2) < self.max_communication_distance): r.neighbors.append(j) #",
"p.connect(p.GUI) p.setGravity(0,0,-9.81) self.max_communication_distance = 2.0 # We will integrate every",
"0.5, 0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2., 13.,",
"p.resetBasePositionAndOrientation(self.ball1, [2., 4., 0.5], (0., 0., 0.5, 0.5)) self.ball2 =",
"4., 0.5], (0., 0., 0.5, 0.5)) self.ball2 = p.loadURDF(\"../models/ball2.urdf\") p.resetBasePositionAndOrientation(self.ball2,",
"self.planeId = p.loadURDF(\"../models/plane.urdf\") p.changeDynamics(self.planeId, -1, lateralFriction=5., rollingFriction=0) self.goalId = p.loadURDF(\"../models/goal.urdf\")",
"# wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8, 4., 0], (0.,",
"p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-5., 3., 0], (0., 0., 0., 1.))",
"# p.resetBasePositionAndOrientation(wallId, [-2., 7., 0], (0., 0., 0.5, 0.5)) #",
"0.5, 0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2., 9.,",
"= [] #reset message received pos1, or1 = r.get_pos_and_orientation() for",
"# wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-3., 3., 0], (0.,",
"# for each robot construct list of neighbors for r",
"p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-1., 6., 0], (0., 0., 0., 1.))",
"p.resetBasePositionAndOrientation(wallId, [3., -1., 0], (0., 0., 0.5, 0.5)) wallId =",
"r.neighbors = [] #reset neighbors r.messages_received = [] #reset message",
"# We will integrate every 4ms (250Hz update) self.dt =",
"# p.resetBasePositionAndOrientation(wallId, [-2., 11., 0], (0., 0., 0.5, 0.5)) #",
"in self.robots: r.neighbors = [] #reset neighbors r.messages_received = []",
"0.5)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [3., 1., 0], (0., 0.,",
"wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-3., 3., 0], (0., 0.,",
"for (i,j) in itertools.product(range(3), range(2)): self.robots.append(Robot([1. * i + 0.5,",
"as p import itertools from robot import Robot class World():",
"p.resetBasePositionAndOrientation(wallId, [-2., 7., 0], (0., 0., 0.5, 0.5)) # wallId",
"1. * j - 0.5, 0.3], 2*i+j, self.dt)) p.stepSimulation() self.time",
"p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8., 8., 0], (0., 0., 0.5, 0.5))",
"0], (0., 0., 0.5, 0.5)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [0.,",
"wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8., 6., 0], (0., 0.,",
"= [] for (i,j) in itertools.product(range(3), range(2)): self.robots.append(Robot([1. * i",
"p.setPhysicsEngineParameter(self.dt, numSubSteps=1) # Create the plane. self.planeId = p.loadURDF(\"../models/plane.urdf\") p.changeDynamics(self.planeId,",
"p.loadURDF(\"../models/goal.urdf\") self.goalId = p.loadURDF(\"../models/goal2.urdf\") # the balls self.ball1 = p.loadURDF(\"../models/ball1.urdf\")",
"wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2., 11., 0], (0., 0.,",
"[0., 1., 0], (0., 0., 0.5, 0.5)) wallId = p.loadSDF(\"../models/walls.sdf\")[0]",
"i + 0.5, 1. * j - 0.5, 0.3], 2*i+j,",
"p.loadURDF(\"../models/goal2.urdf\") # the balls self.ball1 = p.loadURDF(\"../models/ball1.urdf\") p.resetBasePositionAndOrientation(self.ball1, [2., 4.,",
"0., 0.5, 0.5)) # create 6 robots self.robots = []",
"plane. self.planeId = p.loadURDF(\"../models/plane.urdf\") p.changeDynamics(self.planeId, -1, lateralFriction=5., rollingFriction=0) self.goalId =",
"pos1, or1 = r.get_pos_and_orientation() for j,r2 in enumerate(self.robots): if(r.id !=",
"0., 1.)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-7., 3.,",
"# wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-5., 3., 0], (0.,",
"# p.resetBasePositionAndOrientation(wallId, [-1., 6., 0], (0., 0., 0., 1.)) #",
"0., 0.5, 0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8.,",
"p.resetBasePositionAndOrientation(wallId, [-2., 11., 0], (0., 0., 0.5, 0.5)) # wallId",
"p.resetBasePositionAndOrientation(wallId, [-1., 5., 0], (0., 0., 0., 1.)) # wallId",
"0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2., 9., 0],",
"p.loadURDF(\"../models/plane.urdf\") p.changeDynamics(self.planeId, -1, lateralFriction=5., rollingFriction=0) self.goalId = p.loadURDF(\"../models/goal.urdf\") self.goalId =",
"p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8., 6., 0], (0., 0., 0.5, 0.5))",
"0.5)) p.resetDebugVisualizerCamera(7.0,90.0, -43.0, (1., 1., 0.0)) # Add objects wallId",
"messages for i,r in enumerate(self.robots): for msg in r.messages_to_send: if",
"wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8., 12., 0], (0., 0.,",
"p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [2., -2., 0], (0., 0., 0., 1.)) #",
"0.5, 0.5)) self.ball2 = p.loadURDF(\"../models/ball2.urdf\") p.resetBasePositionAndOrientation(self.ball2, [4., 2., 0.5], (0.,",
"1., 0], (0., 0., 0.5, 0.5)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId,",
"= p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [3., -1., 0], (0., 0., 0.5, 0.5))",
"[-2, 4., 0], (0., 0., 0.5, 0.5)) # wallId =",
"0.5, 0.5)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [3., -1., 0], (0.,",
"0], (0., 0., 0., 1.)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] #",
"p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2., 9., 0], (0., 0., 0.5, 0.5))",
"-1, lateralFriction=5., rollingFriction=0) self.goalId = p.loadURDF(\"../models/goal.urdf\") self.goalId = p.loadURDF(\"../models/goal2.urdf\") #",
"# create 6 robots self.robots = [] for (i,j) in",
"0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8., 8., 0],",
"self.robots = [] for (i,j) in itertools.product(range(3), range(2)): self.robots.append(Robot([1. *",
"[-1., 5., 0], (0., 0., 0., 1.)) # wallId =",
"self.time = 0.0 self.stepSimulation() self.stepSimulation() def reset(self): \"\"\" Resets the",
"for i,r in enumerate(self.robots): for msg in r.messages_to_send: if msg[0]",
"neighbors r.messages_received = [] #reset message received pos1, or1 =",
"1.)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-7., 3., 0],",
"received pos1, or1 = r.get_pos_and_orientation() for j,r2 in enumerate(self.robots): if(r.id",
"0., 0.5, 0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-3.,",
"# p.resetBasePositionAndOrientation(wallId, [-1., 5., 0], (0., 0., 0., 1.)) #",
"# tube # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-1., 5.,",
"[-8., 10., 0], (0., 0., 0.5, 0.5)) # wallId =",
"= p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-5., 3., 0], (0., 0., 0.,",
"2.0 # We will integrate every 4ms (250Hz update) self.dt",
"= p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2., 7., 0], (0., 0., 0.5,",
"receive messages for i,r in enumerate(self.robots): for msg in r.messages_to_send:",
"wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2., 7., 0], (0., 0.,",
"itertools.product(range(3), range(2)): self.robots.append(Robot([1. * i + 0.5, 1. * j",
"11., 0], (0., 0., 0.5, 0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0]",
"0.5)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [3., -1., 0], (0., 0.,",
"13., 0], (0., 0., 0.5, 0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0]",
"= 0.0 self.stepSimulation() self.stepSimulation() def reset(self): \"\"\" Resets the position",
"= p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-1., 6., 0], (0., 0., 0.,",
"will integrate every 4ms (250Hz update) self.dt = 1./250. p.setPhysicsEngineParameter(self.dt,",
"p.resetBasePositionAndOrientation(wallId, [0., 1., 0], (0., 0., 0.5, 0.5)) wallId =",
"[3., 1., 0], (0., 0., 0.5, 0.5)) wallId = p.loadSDF(\"../models/walls.sdf\")[0]",
"objects wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [0., -1., 0], (0., 0.,",
"= p.loadURDF(\"../models/goal2.urdf\") # the balls self.ball1 = p.loadURDF(\"../models/ball1.urdf\") p.resetBasePositionAndOrientation(self.ball1, [2.,",
"p.resetBasePositionAndOrientation(wallId, [-1., 6., 0], (0., 0., 0., 1.)) # #arena",
"p.resetBasePositionAndOrientation(wallId, [-2, 4., 0], (0., 0., 0.5, 0.5)) # wallId",
"list of neighbors for r in self.robots: r.neighbors = []",
"p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2., 7., 0], (0., 0., 0.5, 0.5))",
"[-3., 3., 0], (0., 0., 0., 1.)) # wallId =",
"the physics simulator self.physicsClient = p.connect(p.GUI) p.setGravity(0,0,-9.81) self.max_communication_distance = 2.0",
"we can send the message self.robots[msg[0]].messages_received.append([i, msg[1]]) #add the sender",
"every 4ms (250Hz update) self.dt = 1./250. p.setPhysicsEngineParameter(self.dt, numSubSteps=1) #",
"wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2., 13., 0], (0., 0.,",
"create the physics simulator self.physicsClient = p.connect(p.GUI) p.setGravity(0,0,-9.81) self.max_communication_distance =",
"-43.0, (1., 1., 0.0)) # Add objects wallId = p.loadSDF(\"../models/walls.sdf\")[0]",
"0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2., 11., 0],",
"[2., 4., 0.5], (0., 0., 0.5, 0.5)) self.ball2 = p.loadURDF(\"../models/ball2.urdf\")",
"p.resetDebugVisualizerCamera(7.0,90.0, -43.0, (1., 1., 0.0)) # Add objects wallId =",
"= r.get_pos_and_orientation() for j,r2 in enumerate(self.robots): if(r.id != r2.id): pos2,",
"1.)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [2., -2., 0], (0., 0.,",
"of all the robots \"\"\" for r in self.robots: r.reset()",
"0., 1.)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-5., 3.,",
"the robots \"\"\" for r in self.robots: r.reset() p.stepSimulation() def",
"= p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2., 13., 0], (0., 0., 0.5,",
"0.5, 0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2., 7.,",
"wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-7., 3., 0], (0., 0.,",
"0], (0., 0., 0.5, 0.5)) # create 6 robots self.robots",
"construct list of neighbors for r in self.robots: r.neighbors =",
"def stepSimulation(self): \"\"\" Simulates one step simulation \"\"\" # for",
"message received pos1, or1 = r.get_pos_and_orientation() for j,r2 in enumerate(self.robots):",
"the message self.robots[msg[0]].messages_received.append([i, msg[1]]) #add the sender id r.messages_to_send =",
"#then we can send the message self.robots[msg[0]].messages_received.append([i, msg[1]]) #add the",
"wallId = p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-2., 9., 0], (0., 0.,",
"[0., -1., 0], (0., 0., 0.5, 0.5)) wallId = p.loadSDF(\"../models/walls.sdf\")[0]",
"r.reset() p.stepSimulation() def stepSimulation(self): \"\"\" Simulates one step simulation \"\"\"",
"lateralFriction=5., rollingFriction=0) self.goalId = p.loadURDF(\"../models/goal.urdf\") self.goalId = p.loadURDF(\"../models/goal2.urdf\") # the",
"r.messages_to_send = [] # update the controllers if self.time >",
"p.resetBasePositionAndOrientation(self.ball2, [4., 2., 0.5], (0., 0., 0.5, 0.5)) p.resetDebugVisualizerCamera(7.0,90.0, -43.0,",
"balls self.ball1 = p.loadURDF(\"../models/ball1.urdf\") p.resetBasePositionAndOrientation(self.ball1, [2., 4., 0.5], (0., 0.,",
"= p.loadSDF(\"../models/walls.sdf\")[0] # p.resetBasePositionAndOrientation(wallId, [-8., 10., 0], (0., 0., 0.5,",
"\"\"\" Resets the position of all the robots \"\"\" for",
"p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [3., 1., 0], (0., 0., 0.5, 0.5)) wallId",
"0., 0.5, 0.5)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [1., 2., 0],",
"in enumerate(self.robots): for msg in r.messages_to_send: if msg[0] in r.neighbors:",
"robot construct list of neighbors for r in self.robots: r.neighbors",
"r.messages_received = [] #reset message received pos1, or1 = r.get_pos_and_orientation()",
"0., 0.5, 0.5)) wallId = p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [3., 1., 0],",
"= p.loadSDF(\"../models/walls.sdf\")[0] p.resetBasePositionAndOrientation(wallId, [1., 2., 0], (0., 0., 0., 1.))",
"= [] #reset neighbors r.messages_received = [] #reset message received",
"__init__(self): # create the physics simulator self.physicsClient = p.connect(p.GUI) p.setGravity(0,0,-9.81)",
"4., 0], (0., 0., 0.5, 0.5)) # wallId = p.loadSDF(\"../models/walls.sdf\")[0]",
"# update the controllers if self.time > 1.0: for r",
"import pybullet as p import itertools from robot import Robot",
"in r.neighbors: #then we can send the message self.robots[msg[0]].messages_received.append([i, msg[1]])"
] |
[
"protocol = listener[2].upper() params['Listeners.member.%d.LoadBalancerPort' % i] = listener[0] params['Listeners.member.%d.InstancePort' %",
"EC2 Load Balancing Service. .. note:: The region argument is",
"Load Balancer. \"\"\" params = {'LoadBalancerName': load_balancer_name} self.build_list_params(params, instances, 'Instances.member.%d.InstanceId')",
"that terminates the specified listener's SSL connections. The specified certificate",
"the policy configuration. None may be passed for cookie_expiration_period. \"\"\"",
"be applied to the front-end listener, or the back-end application",
"= listener[2] if protocol == 'HTTPS' or protocol == 'SSL':",
"i] = listener[0] params['Listeners.member.%d.InstancePort' % i] = listener[1] params['Listeners.member.%d.Protocol' %",
"create an internal LoadBalancer with a DNS name that resolves",
"attributes.cross_zone_load_balancing.enabled if attribute.lower() == 'connectiondraining': return attributes.connection_draining return None def",
"policy can only be associated with HTTP listeners. This policy",
"subnets: list of strings :param subnets: A list of subnet",
"params, verb='GET') def get_all_lb_attributes(self, load_balancer_name): \"\"\"Gets all Attributes of a",
"len(policies): self.build_list_params(params, policies, 'PolicyNames.member.%d') else: params['PolicyNames'] = '' return self.get_status('SetLoadBalancerPoliciesOfListener',",
":type subnets: list of strings :param subnets: A list of",
":return: The new value for the attribute \"\"\" attributes =",
"return None def register_instances(self, load_balancer_name, instances): \"\"\" Add new Instances",
"existing Load Balancer. All zones must be in the same",
"the fol- # lowing conditions: # # The above copyright",
"for this Load Balancer. \"\"\" params = {'LoadBalancerName': name} self.build_list_params(params,",
"The new value for the attribute \"\"\" attributes = self.get_all_lb_attributes(load_balancer_name)",
"\"\"\"Changes an attribute of a Load Balancer :type load_balancer_name: string",
"Load Balancer Adding zones that are already registered with the",
"or protocol == 'SSL': params['Listeners.member.%d.SSLCertificateId' % i] = listener[4] if",
"1 and 65535, Protocol is a string containing either 'TCP',",
"] = value elif attribute.lower() == 'accesslog': params['LoadBalancerAttributes.AccessLog.Enabled'] = \\",
"portions of the Software. # # THE SOFTWARE IS PROVIDED",
"is the ARN of a AWS IAM certificate, and must",
":param zones: The name of the zone(s) to add. :rtype:",
"(or group of listeners) :type name: string :param name: The",
"Balancer. Removing zones that are not registered with the Load",
"ports): \"\"\" Deletes a load balancer listener (or group of",
"lifetimes that follow that of an application-generated cookie. This policy",
"any person obtaining a # copy of this software and",
"items, label): if isinstance(items, basestring): items = [items] for index,",
"instance * connectionDraining - :py:class:`ConnectionDrainingAttribute` instance :type value: string :param",
"state of all instances will be returned. :rtype: List of",
"The load balancer will be automatically created under the VPC",
"the subnet(s) to detach. :rtype: List of strings :return: An",
"ports: Each int represents the port on the ELB to",
"is chosen based on the existing load balancing algorithm. A",
"{'LoadBalancerName': load_balancer_name} if instances: self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return self.get_list('DescribeInstanceHealth', params,",
"name associated with the load balancer :type health_check: :class:`boto.ec2.elb.healthcheck.HealthCheck` :param",
"name, subnets): \"\"\" Attaches load balancer to one or more",
"security_groups: The name of the security group(s) to add. :rtype:",
"= {} if load_balancer_names: self.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') return self.get_list('DescribeLoadBalancers', params,",
"availability zone(s) to add. :type listeners: List of tuples :param",
"the load balancer to create the listeners for :type listeners:",
"str region_name: The name of the region to connect to.",
"params) def create_app_cookie_stickiness_policy(self, name, lb_name, policy_name): \"\"\" Generates a stickiness",
"this option to create an internal LoadBalancer with a DNS",
"to be removed :return: The status of the request \"\"\"",
"Balancer :type instances: List of strings :param instances: The instance",
"zero (0) or one (1) policy can be associated with",
"'elasticloadbalancing.us-east-1.amazonaws.com') def __init__(self, aws_access_key_id=None, aws_secret_access_key=None, is_secure=True, port=None, proxy=None, proxy_port=None, proxy_user=None,",
"Protocol, InstanceProtocol, SSLCertificateId). Where: - LoadBalancerPortNumber and InstancePortNumber are integer",
"attribute.lower() == 'accesslog': params['LoadBalancerAttributes.AccessLog.Enabled'] = \\ value.enabled and 'true' or",
"see. * accessLog - :py:class:`AccessLogAttribute` instance * crossZoneLoadBalancing - Boolean",
"of a Load Balancer This will make an EC2 call",
":param name: The name of the Load Balancer :type subnets:",
"\"\"\" params = {'LoadBalancerName': load_balancer_name} self.build_list_params(params, zones_to_remove, 'AvailabilityZones.member.%d') obj =",
"listener in enumerate(complex_listeners): i = index + 1 protocol =",
"NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS",
"shall be included # in all copies or substantial portions",
"the ELB. \"\"\" from boto.ec2.elb.attributes import LbAttributes params = {'LoadBalancerName':",
"== 'connectiondraining': params['LoadBalancerAttributes.ConnectionDraining.Enabled'] = \\ value.enabled and 'true' or 'false'",
"create_load_balancer_listeners(self, name, listeners=None, complex_listeners=None): \"\"\" Creates a Listener (or group",
"complex_listeners=None): \"\"\" Create a new load balancer for your account.",
"\"\"\" params = {'LoadBalancerName': load_balancer_name} self.build_list_params(params, zones_to_add, 'AvailabilityZones.member.%d') obj =",
"value: string :param value: The new value for the attribute",
"Balancer. \"\"\" params = {'LoadBalancerName': load_balancer_name} if instances: self.build_list_params(params, instances,",
"be associated with a listener. \"\"\" params = {'LoadBalancerName': lb_name,",
"persons to whom the Software is furnished to do so,",
"specified in the cookie. If not, the load balancer sends",
"the cookie is based on the cookie expiration time, which",
"contains the subnet(s) specified. :type name: string :param name: The",
"params['Listeners.member.%d.Protocol' % i] = listener[2] params['Listeners.member.%d.InstanceProtocol' % i] = listener[3]",
"params[label % (index + 1)] = item def get_all_load_balancers(self, load_balancer_names=None):",
"of the load balancer to create the listeners for :type",
"attributes.connection_draining return None def register_instances(self, load_balancer_name, instances): \"\"\" Add new",
"provided, the state of all instances will be returned. :rtype:",
"crossZoneLoadBalancing - Boolean * connectionDraining - :py:class:`ConnectionDrainingAttribute` instance :rtype: Attribute",
"policy type. Policies are settings that are saved for your",
"instances \"\"\" return get_regions('elasticloadbalancing', connection_cls=ELBConnection) def connect_to_region(region_name, **kw_params): \"\"\" Given",
"InstancePortNumber, Protocol, InstanceProtocol, SSLCertificateId). Where: - LoadBalancerPortNumber and InstancePortNumber are",
"self.get_object('EnableAvailabilityZonesForLoadBalancer', params, LoadBalancerZones) return obj.zones def disable_availability_zones(self, load_balancer_name, zones_to_remove): \"\"\"",
"index, item in enumerate(items): params[label % (index + 1)] =",
"ARN of an SSL certificate loaded into AWS IAM :return:",
"= {'LoadBalancerName': lb_name, 'PolicyName': policy_name, 'PolicyTypeName': policy_type} for index, (name,",
"attribute: string :param attribute: The attribute you wish to change.",
"LoadBalancer. :type security_groups: list of strings :param security_groups: The security",
"the Load Balancer :type subnets: List of strings :param subnets:",
"the Load Balancer :rtype: boto.ec2.elb.attribute.LbAttributes :return: The attribute object of",
"= RegionInfo(self, self.DefaultRegionName, self.DefaultRegionEndpoint) self.region = region super(ELBConnection, self).__init__(aws_access_key_id, aws_secret_access_key,",
"index] = value else: params['PolicyAttributes'] = '' return self.get_status('CreateLoadBalancerPolicy', params)",
"(true) * accessLog - :py:class:`AccessLogAttribute` instance * connectionDraining - :py:class:`ConnectionDrainingAttribute`",
"the lifetime of the special Elastic Load Balancing cookie follows",
":type name: string :param name: The name of the Load",
"# without limitation the rights to use, copy, modify, merge,",
"# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF",
"value = 'false' params = {'LoadBalancerName': load_balancer_name} if attribute.lower() ==",
"raise ValueError('InvalidAttribute', attribute) return self.get_status('ModifyLoadBalancerAttributes', params, verb='GET') def get_all_lb_attributes(self, load_balancer_name):",
"cookie specified in the policy configuration. The load balancer only",
"the boto configuration file. \"\"\" if not region: region =",
"tuple contains three or four values, (LoadBalancerPortNumber, InstancePortNumber, Protocol, [SSLCertificateId])",
"any listeners. \"\"\" params = {'LoadBalancerName': lb_name, 'PolicyName': policy_name} return",
"= listener[4] return self.get_status('CreateLoadBalancerListeners', params) def delete_load_balancer(self, name): \"\"\" Delete",
"def create_lb_cookie_stickiness_policy(self, cookie_expiration_period, lb_name, policy_name): \"\"\" Generates a stickiness policy",
"Load Balancer has no effect. :type load_balancer_name: string :param load_balancer_name:",
"name of the subnet(s) to detach. :rtype: List of strings",
"new policy that contais the necessary attributes depending on the",
"if attribute.lower() == 'crosszoneloadbalancing': return attributes.cross_zone_load_balancing.enabled if attribute.lower() == 'connectiondraining':",
"wish to see. * accessLog - :py:class:`AccessLogAttribute` instance * crossZoneLoadBalancing",
"(EC2) load balancing service from AWS. \"\"\" from boto.connection import",
"region in regions(): if region.name == region_name: return region.connect(**kw_params) return",
"= boto.config.get('Boto', 'elb_region_endpoint', 'elasticloadbalancing.us-east-1.amazonaws.com') def __init__(self, aws_access_key_id=None, aws_secret_access_key=None, is_secure=True, port=None,",
"A list of subnet IDs in your VPC to attach",
"Generates a stickiness policy with sticky session lifetimes that follow",
"list of security groups for this Load Balancer. \"\"\" params",
"LoadBalancer) load_balancer.name = name load_balancer.listeners = listeners load_balancer.availability_zones = zones",
"Balancer from your account. :type name: string :param name: The",
"None. The load balancer will be automatically created under the",
"A connection to the given region, or None if an",
"(the # \"Software\"), to deal in the Software without restriction,",
"security_groups, 'SecurityGroups.member.%d') load_balancer = self.get_object('CreateLoadBalancer', params, LoadBalancer) load_balancer.name = name",
"from boto.ec2.elb.attributes import LbAttributes params = {'LoadBalancerName': load_balancer_name} return self.get_object('DescribeLoadBalancerAttributes',",
"OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT,",
"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF",
"None if an invalid region name is given \"\"\" for",
"load balancer uses a special cookie to track the backend",
"Deletes a policy from the LoadBalancer. The specified policy must",
"of the Load Balancer :type instances: List of strings :param",
"status for. If not provided, the state of all instances",
"can only be associated only with HTTP listeners. When a",
"Balancer :type subnets: List of strings :param subnets: The name",
"load_balancer_name} self.build_list_params(params, zones_to_remove, 'AvailabilityZones.member.%d') obj = self.get_object('DisableAvailabilityZonesForLoadBalancer', params, LoadBalancerZones) return",
"desired values. :rtype: :class:`boto.ec2.elb.healthcheck.HealthCheck` :return: The updated :class:`boto.ec2.elb.healthcheck.HealthCheck` \"\"\" params",
"balancer will be automatically created under the VPC that contains",
"params['LoadBalancerPorts.member.%d' % (index + 1)] = port return self.get_status('DeleteLoadBalancerListeners', params)",
"saved for your load balancer and that can be applied",
"return self.get_status('CreateLoadBalancerPolicy', params) def delete_lb_policy(self, lb_name, policy_name): \"\"\" Deletes a",
"of this software and associated documentation files (the # \"Software\"),",
"the two options return None params = {'LoadBalancerName': name, 'Scheme':",
"expires, the session stops being sticky until a new application",
"publish, dis- # tribute, sublicense, and/or sell copies of the",
"zones must be in the same region as the Load",
"'' return self.get_status('CreateLoadBalancerPolicy', params) def delete_lb_policy(self, lb_name, policy_name): \"\"\" Deletes",
"if protocol == 'HTTPS' or protocol == 'SSL': params['Listeners.member.%d.SSLCertificateId' %",
"private IP addresses. This option is only available for LoadBalancers",
"HTTPS. :type subnets: list of strings :param subnets: A list",
"a specified expiration period. This policy can only be associated",
"of the subnet(s) to add. :rtype: List of strings :return:",
"name: The name of the Load Balancer :type security_groups: List",
"port, proxy, proxy_port, proxy_user, proxy_pass, self.region.endpoint, debug, https_connection_factory, path, security_token,",
"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS #",
"all instances will be returned. :rtype: List of :class:`boto.ec2.elb.instancestate.InstanceState` :return:",
"furnished to do so, subject to the fol- # lowing",
"from the same user to that server. The validity of",
"must be in the same region as the Load Balancer.",
"get_all_lb_attributes(self, load_balancer_name): \"\"\"Gets all Attributes of a Load Balancer :type",
"policy_name} return self.get_status('DeleteLoadBalancerPolicy', params) def set_lb_policies_of_listener(self, lb_name, lb_port, policies): \"\"\"",
"get_regions('elasticloadbalancing', connection_cls=ELBConnection) def connect_to_region(region_name, **kw_params): \"\"\" Given a valid region",
"By default, Elastic Load Balancing creates an internet-facing LoadBalancer with",
"Balancer :type security_groups: List of strings :param security_groups: The name",
"of state info for instances in this Load Balancer. \"\"\"",
"{'CookieName': name, 'LoadBalancerName': lb_name, 'PolicyName': policy_name} return self.get_status('CreateAppCookieStickinessPolicy', params) def",
"return self.get_status('CreateLoadBalancerListeners', params) def delete_load_balancer(self, name): \"\"\" Delete a Load",
"the load balancer uses a special cookie to track the",
"if not listeners and not complex_listeners: # Must specify one",
"Handle the full listeners if complex_listeners: for index, listener in",
"params = {'LoadBalancerName': lb_name, 'PolicyName': policy_name, 'PolicyTypeName': policy_type} for index,",
"an internal LoadBalancer with a DNS name that resolves to",
"listener[1] params['Listeners.member.%d.Protocol' % i] = listener[2] if protocol == 'HTTPS'",
"import RegionInfo, get_regions, load_regions import boto RegionData = load_regions().get('elasticloadbalancing', {})",
"The region argument is overridden by the region specified in",
"# in all copies or substantial portions of the Software.",
"(or group of listeners) for an existing Load Balancer :type",
"cookie is present in the request. If so, the load",
"Get current state of all Instances registered to an Load",
"one of the two options return None params = {'LoadBalancerName':",
"== 'accesslog': return attributes.access_log if attribute.lower() == 'crosszoneloadbalancing': return attributes.cross_zone_load_balancing.enabled",
"LoadBalancers attached to an Amazon VPC. :type complex_listeners: List of",
"that are already registered with the Load Balancer has no",
"the attribute \"\"\" attributes = self.get_all_lb_attributes(load_balancer_name) if attribute.lower() == 'accesslog':",
"IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED,",
"KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO",
"value else: params['PolicyAttributes'] = '' return self.get_status('CreateLoadBalancerPolicy', params) def delete_lb_policy(self,",
"balancer only inserts a new stickiness cookie when the application",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING",
"params = {'LoadBalancerName': load_balancer_name} self.build_list_params(params, zones_to_remove, 'AvailabilityZones.member.%d') obj = self.get_object('DisableAvailabilityZonesForLoadBalancer',",
"existing Load Balancer :type name: string :param name: The name",
"that follow that of an application-generated cookie. This policy can",
"# All Rights Reserved # # Permission is hereby granted,",
"balancer receives a request, it first checks to see if",
"created by CreateLBCookieStickinessPolicy, except that the lifetime of the special",
"current state of all Instances registered to an Load Balancer.",
"('crosszoneloadbalancing',) if attribute.lower() in bool_reqs: if isinstance(value, bool): if value:",
"follows the lifetime of the application-generated cookie specified in the",
"name of the Load Balancer :type instances: List of strings",
"zone(s) to add. :type listeners: List of tuples :param listeners:",
"the back-end server is listening with a new set of",
"load_balancer_name} self.build_list_params(params, zones_to_add, 'AvailabilityZones.member.%d') obj = self.get_object('EnableAvailabilityZonesForLoadBalancer', params, LoadBalancerZones) return",
"lb_name, policy_name, policy_type, policy_attributes): \"\"\" Creates a new policy that",
"in this Load Balancer. \"\"\" params = {'LoadBalancerName': load_balancer_name} if",
"is hereby granted, free of charge, to any person obtaining",
"person obtaining a # copy of this software and associated",
"Load Balancer :type zones: List of strings :param zones: The",
"A ResultSet containing instances of :class:`boto.ec2.elb.loadbalancer.LoadBalancer` \"\"\" params = {}",
"An updated list of subnets for this Load Balancer. \"\"\"",
"to detach. :rtype: List of strings :return: An updated list",
"def set_lb_policies_of_backend_server(self, lb_name, instance_port, policies): \"\"\" Replaces the current set",
"\"\"\" Deletes a load balancer listener (or group of listeners)",
"By default the load balancer will be created in EC2.",
"'PolicyName': policy_name} return self.get_status('CreateAppCookieStickinessPolicy', params) def create_lb_cookie_stickiness_policy(self, cookie_expiration_period, lb_name, policy_name):",
"balancer. Currently only zero (0) or one (1) policy can",
"module provides an interface to the Elastic Compute Cloud (EC2)",
"a LoadBalancer. By default, Elastic Load Balancing creates an internet-facing",
"load_balancer_name, attribute, value): \"\"\"Changes an attribute of a Load Balancer",
"params['LoadBalancerAttributes.CrossZoneLoadBalancing.Enabled' ] = value elif attribute.lower() == 'accesslog': params['LoadBalancerAttributes.AccessLog.Enabled'] =",
"connectionDraining - :py:class:`ConnectionDrainingAttribute` instance :rtype: Attribute dependent :return: The new",
"only with HTTP listeners. When a load balancer implements this",
"CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR",
"load_balancer_name} return self.get_object('DescribeLoadBalancerAttributes', params, LbAttributes) def get_lb_attribute(self, load_balancer_name, attribute): \"\"\"Gets",
"= \\ value.enabled and 'true' or 'false' params['LoadBalancerAttributes.AccessLog.S3BucketName'] = \\",
"list of subnets for this Load Balancer. \"\"\" params =",
"ValueError('InvalidAttribute', attribute) return self.get_status('ModifyLoadBalancerAttributes', params, verb='GET') def get_all_lb_attributes(self, load_balancer_name): \"\"\"Gets",
"an interface to the Elastic Compute Cloud (EC2) load balancing",
"dependent :return: The new value for the attribute \"\"\" attributes",
"return self.get_list('ApplySecurityGroupsToLoadBalancer', params, None) def attach_lb_to_subnets(self, name, subnets): \"\"\" Attaches",
"VPC. :type complex_listeners: List of tuples :param complex_listeners: Each tuple",
"The name of the Load Balancer :type instances: List of",
"DNS name that resolves to private IP addresses. This option",
"An optional list of load balancer names. :rtype: :py:class:`boto.resultset.ResultSet` :return:",
"of subnet IDs in your VPC to attach to your",
":class:`boto.ec2.elb.healthcheck.HealthCheck` :return: The updated :class:`boto.ec2.elb.healthcheck.HealthCheck` \"\"\" params = {'LoadBalancerName': name,",
"= self.get_object('CreateLoadBalancer', params, LoadBalancer) load_balancer.name = name load_balancer.listeners = listeners",
"with a new set of policies. \"\"\" params = {'LoadBalancerName':",
"{'LoadBalancerName': name} return self.get_status('DeleteLoadBalancer', params) def delete_load_balancer_listeners(self, name, ports): \"\"\"",
":param zones: The name of the zone(s) to remove. :rtype:",
"1): params['PolicyAttributes.member.%d.AttributeName' % index] = name params['PolicyAttributes.member.%d.AttributeValue' % index] =",
"DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF",
"availability zones to an existing Load Balancer All zones must",
"= {'LoadBalancerName': lb_name, 'PolicyName': policy_name} return self.get_status('DeleteLoadBalancerPolicy', params) def set_lb_policies_of_listener(self,",
"strings :param zones: The name of the zone(s) to remove.",
"the Load Balancer has no effect. :type load_balancer_name: string :param",
"of listeners) :type name: string :param name: The name of",
"with HTTP listeners. This policy is similar to the policy",
"load balancer to one or more subnets. Attaching subnets that",
"The name of the load balancer to create the listeners",
"effect. You cannot remove all zones from an Load Balancer.",
"ListElement from boto.regioninfo import RegionInfo, get_regions, load_regions import boto RegionData",
"health_check.target, 'HealthCheck.Interval': health_check.interval, 'HealthCheck.UnhealthyThreshold': health_check.unhealthy_threshold, 'HealthCheck.HealthyThreshold': health_check.healthy_threshold} return self.get_object('ConfigureHealthCheck', params,",
"and associated documentation files (the # \"Software\"), to deal in",
"updated list of security groups for this Load Balancer. \"\"\"",
"params['LoadBalancerAttributes.AccessLog.EmitInterval'] = \\ value.emit_interval elif attribute.lower() == 'connectiondraining': params['LoadBalancerAttributes.ConnectionDraining.Enabled'] =",
"listeners if complex_listeners: for index, listener in enumerate(complex_listeners): i =",
"granted, free of charge, to any person obtaining a #",
"balancing service from AWS. \"\"\" from boto.connection import AWSQueryConnection from",
"stickiness policy with sticky session lifetimes controlled by the lifetime",
"value for the attribute \"\"\" attributes = self.get_all_lb_attributes(load_balancer_name) if attribute.lower()",
"= region super(ELBConnection, self).__init__(aws_access_key_id, aws_secret_access_key, is_secure, port, proxy, proxy_port, proxy_user,",
"a load balancer inside a VPC, parameter zones must be",
"load balancer only inserts a new stickiness cookie when the",
"# Handle the simple listeners if listeners: for index, listener",
"bool_reqs: if isinstance(value, bool): if value: value = 'true' else:",
"= value elif attribute.lower() == 'accesslog': params['LoadBalancerAttributes.AccessLog.Enabled'] = \\ value.enabled",
"server. \"\"\" params = {'LoadBalancerName': lb_name, 'PolicyName': policy_name, 'PolicyTypeName': policy_type}",
"load balancers associated with your account. :type load_balancer_names: list :keyword",
"CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS",
"= 'true' else: value = 'false' params = {'LoadBalancerName': load_balancer_name}",
"index, listener in enumerate(listeners): i = index + 1 protocol",
"The type of a LoadBalancer. By default, Elastic Load Balancing",
"effect. :type load_balancer_name: string :param load_balancer_name: The name of the",
"self.get_status('DeleteLoadBalancer', params) def delete_load_balancer_listeners(self, name, ports): \"\"\" Deletes a load",
"import HealthCheck from boto.ec2.elb.listelement import ListElement from boto.regioninfo import RegionInfo,",
"# Permission is hereby granted, free of charge, to any",
"{'LoadBalancerName': name} for index, port in enumerate(ports): params['LoadBalancerPorts.member.%d' % (index",
"load balancer will be automatically created under the VPC that",
"Where: - LoadBalancerPortNumber and InstancePortNumber are integer values between 1",
"self.get_status('ModifyLoadBalancerAttributes', params, verb='GET') def get_all_lb_attributes(self, load_balancer_name): \"\"\"Gets all Attributes of",
"if len(policies): self.build_list_params(params, policies, 'PolicyNames.member.%d') else: params['PolicyNames'] = '' return",
"registered with the Load Balancer has no effect. You cannot",
"SSL connections. The specified certificate replaces any prior certificate that",
"_required_auth_capability(self): return ['ec2'] def build_list_params(self, params, items, label): if isinstance(items,",
"Get all available regions for the ELB service. :rtype: list",
"specified in the policy configuration. None may be passed for",
"without limitation the rights to use, copy, modify, merge, publish,",
"the zone(s) to remove. :rtype: List of strings :return: An",
"list :keyword load_balancer_names: An optional list of load balancer names.",
"status of the request \"\"\" if not listeners and not",
"an Load Balancer. :type load_balancer_name: string :param load_balancer_name: The name",
"zones from an existing Load Balancer. All zones must be",
"\"\"\"Gets all Attributes of a Load Balancer :type load_balancer_name: string",
"to an existing Load Balancer All zones must be in",
"params['PolicyAttributes'] = '' return self.get_status('CreateLoadBalancerPolicy', params) def delete_lb_policy(self, lb_name, policy_name):",
"\"\"\" Remove Instances from an existing Load Balancer. :type load_balancer_name:",
"associated with a listener. \"\"\" params = {'LoadBalancerName': lb_name, 'LoadBalancerPort':",
"bool :return: Whether the operation succeeded or not \"\"\" bool_reqs",
"present in the request. If so, the load balancer sends",
"subnet(s) to detach. :rtype: List of strings :return: An updated",
"If not provided, the state of all instances will be",
"Creates a new policy that contais the necessary attributes depending",
"index + 1 protocol = listener[2].upper() params['Listeners.member.%d.LoadBalancerPort' % i] =",
":class:`boto.ec2.ELBConnection` or ``None`` :return: A connection to the given region,",
"set to None and subnets must not be None. The",
"lb_name, 'PolicyName': policy_name} return self.get_status('CreateAppCookieStickinessPolicy', params) def create_lb_cookie_stickiness_policy(self, cookie_expiration_period, lb_name,",
"when doing HTTPS. :type complex_listeners: List of tuples :param complex_listeners:",
"List of strings :param zones: The name of the zone(s)",
"Deletes a load balancer listener (or group of listeners) :type",
"balancer :type zones: List of strings :param zones: The names",
":param load_balancer_name: The name of the Load Balancer :type instances:",
"a string containing either 'TCP', 'SSL', HTTP', or 'HTTPS'; SSLCertificateID",
"A list of :class:`boto.RegionInfo` instances \"\"\" return get_regions('elasticloadbalancing', connection_cls=ELBConnection) def",
"listener[0] params['Listeners.member.%d.InstancePort' % i] = listener[1] params['Listeners.member.%d.Protocol' % i] =",
"'SSL': params['Listeners.member.%d.SSLCertificateId' % i] = listener[4] if zones: self.build_list_params(params, zones,",
"index, (name, value) in enumerate(policy_attributes.iteritems(), 1): params['PolicyAttributes.member.%d.AttributeName' % index] =",
"attribute of a Load Balancer This will make an EC2",
"name params['PolicyAttributes.member.%d.AttributeValue' % index] = value else: params['PolicyAttributes'] = ''",
"attribute, value): \"\"\"Changes an attribute of a Load Balancer :type",
"A HealthCheck object populated with the desired values. :rtype: :class:`boto.ec2.elb.healthcheck.HealthCheck`",
"Cloud (EC2) load balancing service from AWS. \"\"\" from boto.connection",
"listener[4] if zones: self.build_list_params(params, zones, 'AvailabilityZones.member.%d') if subnets: self.build_list_params(params, subnets,",
"algorithm. A cookie is inserted into the response for binding",
"= port return self.get_status('DeleteLoadBalancerListeners', params) def enable_availability_zones(self, load_balancer_name, zones_to_add): \"\"\"",
"stops being sticky until a new application cookie is issued.",
"% i] = listener[2] if protocol == 'HTTPS' or protocol",
"this Load Balancer. \"\"\" params = {'LoadBalancerName': load_balancer_name} self.build_list_params(params, zones_to_add,",
"is similar to the policy created by CreateLBCookieStickinessPolicy, except that",
"to any person obtaining a # copy of this software",
"'PolicyNames.member.%d') else: params['PolicyNames'] = '' return self.get_status('SetLoadBalancerPoliciesOfListener', params) def set_lb_policies_of_backend_server(self,",
"the load balancer sends the request to a server that",
"DNS name, which resolves to public IP addresses. Specify the",
"Define a health check for the EndPoints. :type name: string",
"that is chosen based on the existing load balancing algorithm.",
"= {'LoadBalancerName': name} self.build_list_params(params, subnets, 'Subnets.member.%d') return self.get_list('DetachLoadBalancerFromSubnets', params, None)",
"# copy of this software and associated documentation files (the",
"# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN",
"or four values, (LoadBalancerPortNumber, InstancePortNumber, Protocol, [SSLCertificateId]) where LoadBalancerPortNumber and",
"value: The new value for the attribute :rtype: bool :return:",
"an SSL certificate loaded into AWS IAM :return: The status",
"instance_port, policies): \"\"\" Replaces the current set of policies associated",
"attribute.lower() in bool_reqs: if isinstance(value, bool): if value: value =",
"'accesslog': return attributes.access_log if attribute.lower() == 'crosszoneloadbalancing': return attributes.cross_zone_load_balancing.enabled if",
"for region in regions(): if region.name == region_name: return region.connect(**kw_params)",
"given region, or None if an invalid region name is",
"elif attribute.lower() == 'accesslog': params['LoadBalancerAttributes.AccessLog.Enabled'] = \\ value.enabled and 'true'",
"THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN",
"Remove Instances from an existing Load Balancer. :type load_balancer_name: string",
"ssl_certificate_id} return self.get_status('SetLoadBalancerListenerSSLCertificate', params) def create_app_cookie_stickiness_policy(self, name, lb_name, policy_name): \"\"\"",
"cookie_expiration_period, lb_name, policy_name): \"\"\" Generates a stickiness policy with sticky",
"passed for cookie_expiration_period. \"\"\" params = {'LoadBalancerName': lb_name, 'PolicyName': policy_name}",
"{'LoadBalancerName': lb_name, 'InstancePort': instance_port} if policies: self.build_list_params(params, policies, 'PolicyNames.member.%d') else:",
"of the subnet(s) to detach. :rtype: List of strings :return:",
"__init__(self, aws_access_key_id=None, aws_secret_access_key=None, is_secure=True, port=None, proxy=None, proxy_port=None, proxy_user=None, proxy_pass=None, debug=0,",
"enumerate(complex_listeners): i = index + 1 protocol = listener[2].upper() InstanceProtocol",
"load_balancer def create_load_balancer_listeners(self, name, listeners=None, complex_listeners=None): \"\"\" Creates a Listener",
"all zones from an Load Balancer. :type load_balancer_name: string :param",
"an Amazon VPC. :type complex_listeners: List of tuples :param complex_listeners:",
"not complex_listeners: # Must specify one of the two options",
"certificate loaded into AWS IAM :return: The status of the",
"load balancer :type health_check: :class:`boto.ec2.elb.healthcheck.HealthCheck` :param health_check: A HealthCheck object",
"check for the EndPoints. :type name: string :param name: The",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT",
"back-end application server. \"\"\" params = {'LoadBalancerName': lb_name, 'PolicyName': policy_name,",
"Compute Cloud (EC2) load balancing service from AWS. \"\"\" from",
"are saved for your load balancer and that can be",
"lb_port, policies): \"\"\" Associates, updates, or disables a policy with",
"security groups that are already registered with the Load Balancer",
"notice shall be included # in all copies or substantial",
"from boto.ec2.elb.loadbalancer import LoadBalancer, LoadBalancerZones from boto.ec2.elb.instancestate import InstanceState from",
"Replaces the current set of policies associated with a port",
":py:class:`AccessLogAttribute` instance * connectionDraining - :py:class:`ConnectionDrainingAttribute` instance :type value: string",
"params['Listeners.member.%d.LoadBalancerPort' % i] = listener[0] params['Listeners.member.%d.InstancePort' % i] = listener[1]",
"params = {'LoadBalancerName': load_balancer_name} if instances: self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return",
"{'LoadBalancerName': name} # Handle the simple listeners if listeners: for",
"in enumerate(ports): params['LoadBalancerPorts.member.%d' % (index + 1)] = port return",
"path='/', security_token=None, validate_certs=True, profile_name=None): \"\"\" Init method to create a",
"add. :type listeners: List of tuples :param listeners: Each tuple",
"params['Listeners.member.%d.Protocol' % i] = listener[2] if protocol == 'HTTPS' or",
"load_balancer_name: The name of the Load Balancer :rtype: boto.ec2.elb.attribute.LbAttributes :return:",
"def create_load_balancer(self, name, zones, listeners=None, subnets=None, security_groups=None, scheme='internet-facing', complex_listeners=None): \"\"\"",
"proxy_port=None, proxy_user=None, proxy_pass=None, debug=0, https_connection_factory=None, region=None, path='/', security_token=None, validate_certs=True, profile_name=None):",
"Balancer has no effect. :type load_balancer_name: string :param load_balancer_name: The",
"represents the port on the ELB to be removed :return:",
"health_check: A HealthCheck object populated with the desired values. :rtype:",
"i] = listener[4] if zones: self.build_list_params(params, zones, 'AvailabilityZones.member.%d') if subnets:",
"* crossZoneLoadBalancing - Boolean (true) * accessLog - :py:class:`AccessLogAttribute` instance",
"file. \"\"\" if not region: region = RegionInfo(self, self.DefaultRegionName, self.DefaultRegionEndpoint)",
"attributes = self.get_all_lb_attributes(load_balancer_name) if attribute.lower() == 'accesslog': return attributes.access_log if",
"instances: The instance ID's of the EC2 instances to add.",
"be associated with HTTP listeners. This policy is similar to",
"\"\"\" if not region: region = RegionInfo(self, self.DefaultRegionName, self.DefaultRegionEndpoint) self.region",
"\"\"\" Remove availability zones from an existing Load Balancer. All",
"List of strings :return: An updated list of security groups",
"value.s3_bucket_prefix params['LoadBalancerAttributes.AccessLog.EmitInterval'] = \\ value.emit_interval elif attribute.lower() == 'connectiondraining': params['LoadBalancerAttributes.ConnectionDraining.Enabled']",
"\"\"\" Creates a Listener (or group of listeners) for an",
"enumerate(policy_attributes.iteritems(), 1): params['PolicyAttributes.member.%d.AttributeName' % index] = name params['PolicyAttributes.member.%d.AttributeValue' % index]",
"the load balancer. Currently only zero (0) or one (1)",
"policy with sticky session lifetimes that follow that of an",
"Amazon VPC. :type complex_listeners: List of tuples :param complex_listeners: Each",
"and must be specified when doing HTTPS. :type complex_listeners: List",
"of subnets for this Load Balancer. \"\"\" params = {'LoadBalancerName':",
"contains three or four values, (LoadBalancerPortNumber, InstancePortNumber, Protocol, [SSLCertificateId]) where",
"string :param scheme: The type of a LoadBalancer. By default,",
"balancer to create the listeners for :type ports: List int",
"policy_name, 'PolicyTypeName': policy_type} for index, (name, value) in enumerate(policy_attributes.iteritems(), 1):",
"or more subnets. Attaching subnets that are already registered with",
"# tribute, sublicense, and/or sell copies of the Software, and",
":param load_balancer_name: The name of the Load Balancer :type zones:",
"65535 - Protocol and InstanceProtocol is a string containing either",
"new set of policies. \"\"\" params = {'LoadBalancerName': lb_name, 'InstancePort':",
"set_lb_listener_SSL_certificate(self, lb_name, lb_port, ssl_certificate_id): \"\"\" Sets the certificate that terminates",
"name, listeners=None, complex_listeners=None): \"\"\" Creates a Listener (or group of",
"a Load Balancer from your account. :type name: string :param",
"policies. \"\"\" params = {'LoadBalancerName': lb_name, 'InstancePort': instance_port} if policies:",
"time, which is specified in the policy configuration. None may",
"region as the Load Balancer. Removing zones that are not",
"five values, (LoadBalancerPortNumber, InstancePortNumber, Protocol, InstanceProtocol, SSLCertificateId). Where: - LoadBalancerPortNumber",
"a new load balancer for your account. By default the",
"name, 'HealthCheck.Timeout': health_check.timeout, 'HealthCheck.Target': health_check.target, 'HealthCheck.Interval': health_check.interval, 'HealthCheck.UnhealthyThreshold': health_check.unhealthy_threshold, 'HealthCheck.HealthyThreshold':",
"of the Load Balancer :type subnets: List of strings :param",
"which is specified in the policy configuration. None may be",
"name of the Load Balancer to delete \"\"\" params =",
"of a AWS IAM certificate, and must be specified when",
"else: params['PolicyAttributes'] = '' return self.get_status('CreateLoadBalancerPolicy', params) def delete_lb_policy(self, lb_name,",
"HTTP listeners. This policy is similar to the policy created",
"zones: List of strings :param zones: The names of the",
"- SSLCertificateId is the ARN of an SSL certificate loaded",
"lb_name, instance_port, policies): \"\"\" Replaces the current set of policies",
"params) def enable_availability_zones(self, load_balancer_name, zones_to_add): \"\"\" Add availability zones to",
"- LoadBalancerPortNumber and InstancePortNumber are integer values between 1 and",
"specify one of the two options return None params =",
"uses a special cookie to track the backend server instance",
"SOFTWARE. # \"\"\" This module provides an interface to the",
"'LoadBalancerPort': lb_port, 'SSLCertificateId': ssl_certificate_id} return self.get_status('SetLoadBalancerListenerSSLCertificate', params) def create_app_cookie_stickiness_policy(self, name,",
"to create a new connection to EC2 Load Balancing Service.",
"name associated with the new load balancer :type zones: List",
"to the given region, or None if an invalid region",
"{'LoadBalancerName': name, 'Scheme': scheme} # Handle legacy listeners if listeners:",
"lb_name, 'PolicyName': policy_name} if cookie_expiration_period is not None: params['CookieExpirationPeriod'] =",
"(c) 2012 Amazon.com, Inc. or its affiliates. # All Rights",
":param security_groups: The security groups assigned to your LoadBalancer within",
"OTHER DEALINGS # IN THE SOFTWARE. # \"\"\" This module",
"string :param name: The mnemonic name associated with the new",
"HTTP listeners. When a load balancer implements this policy, the",
"= security_groups return load_balancer def create_load_balancer_listeners(self, name, listeners=None, complex_listeners=None): \"\"\"",
"zones_to_remove): \"\"\" Remove availability zones from an existing Load Balancer.",
"The name of the Load Balancer :rtype: boto.ec2.elb.attribute.LbAttributes :return: The",
"None params = {'LoadBalancerName': name} # Handle the simple listeners",
"def describe_instance_health(self, load_balancer_name, instances=None): \"\"\" Get current state of all",
"When the load balancer receives a request, it first checks",
"policies): \"\"\" Replaces the current set of policies associated with",
"'crosszoneloadbalancing': return attributes.cross_zone_load_balancing.enabled if attribute.lower() == 'connectiondraining': return attributes.connection_draining return",
"cookie. If not, the load balancer sends the request to",
"specified certificate replaces any prior certificate that was used on",
"the lifetime of the application-generated cookie specified in the policy",
"load balancer. Applying security groups that are already registered with",
"InstancePortNumber are integer values between 1 and 65535, Protocol is",
"with a port on which the back-end server is listening",
"DefaultRegionEndpoint = boto.config.get('Boto', 'elb_region_endpoint', 'elasticloadbalancing.us-east-1.amazonaws.com') def __init__(self, aws_access_key_id=None, aws_secret_access_key=None, is_secure=True,",
"The name of the zone(s) to add. :rtype: List of",
"load balancer listener (or group of listeners) :type name: string",
"You cannot remove all zones from an Load Balancer. :type",
"instance * crossZoneLoadBalancing - Boolean * connectionDraining - :py:class:`ConnectionDrainingAttribute` instance",
"of the two options return None params = {'LoadBalancerName': name,",
"# persons to whom the Software is furnished to do",
"listener[2] params['Listeners.member.%d.InstanceProtocol' % i] = listener[3] if protocol == 'HTTPS'",
"attribute.lower() == 'accesslog': return attributes.access_log if attribute.lower() == 'crosszoneloadbalancing': return",
"= {'LoadBalancerName': load_balancer_name} self.build_list_params(params, zones_to_remove, 'AvailabilityZones.member.%d') obj = self.get_object('DisableAvailabilityZonesForLoadBalancer', params,",
"\"\"\" params = {'LoadBalancerName': load_balancer_name} if instances: self.build_list_params(params, instances, 'Instances.member.%d.InstanceId')",
"being sticky until a new application cookie is issued. \"\"\"",
"{'LoadBalancerName': lb_name, 'PolicyName': policy_name, 'PolicyTypeName': policy_type} for index, (name, value)",
"the Load Balancer has no effect. You cannot remove all",
"of strings :param zones: The name of the zone(s) to",
":py:class:`ConnectionDrainingAttribute` instance :rtype: Attribute dependent :return: The new value for",
"may be passed for cookie_expiration_period. \"\"\" params = {'LoadBalancerName': lb_name,",
"type. Policies are settings that are saved for your load",
"load_balancer_name, zones_to_add): \"\"\" Add availability zones to an existing Load",
"regions(): if region.name == region_name: return region.connect(**kw_params) return None class",
"2012 Amazon.com, Inc. or its affiliates. # All Rights Reserved",
"a new stickiness cookie when the application response includes a",
"boto.ec2.elb.instancestate import InstanceState from boto.ec2.elb.healthcheck import HealthCheck from boto.ec2.elb.listelement import",
"{'LoadBalancerName': name, 'HealthCheck.Timeout': health_check.timeout, 'HealthCheck.Target': health_check.target, 'HealthCheck.Interval': health_check.interval, 'HealthCheck.UnhealthyThreshold': health_check.unhealthy_threshold,",
"None) def attach_lb_to_subnets(self, name, subnets): \"\"\" Attaches load balancer to",
"an invalid region name is given \"\"\" for region in",
"to an Load Balancer. :type load_balancer_name: string :param load_balancer_name: The",
"name: The name of the Load Balancer to delete \"\"\"",
"backend server instance for each request. When the load balancer",
"= subnets load_balancer.security_groups = security_groups return load_balancer def create_load_balancer_listeners(self, name,",
"cookie. If the application cookie is explicitly removed or expires,",
"so, subject to the fol- # lowing conditions: # #",
"to the application server specified in the cookie. If not,",
"publicly resolvable DNS name, which resolves to public IP addresses.",
"to create the listeners for :type listeners: List of tuples",
"load_balancer_names: list :keyword load_balancer_names: An optional list of load balancer",
"into AWS IAM :return: The status of the request \"\"\"",
"The name of the subnet(s) to add. :rtype: List of",
"APIVersion = boto.config.get('Boto', 'elb_version', '2012-06-01') DefaultRegionName = boto.config.get('Boto', 'elb_region_name', 'us-east-1')",
"chosen based on the existing load balancing algorithm. A cookie",
"% i] = listener[3] # Handle the full listeners if",
"policy with a listener on the load balancer. Currently only",
"proxy_user, proxy_pass, self.region.endpoint, debug, https_connection_factory, path, security_token, validate_certs=validate_certs, profile_name=profile_name) def",
"self.get_status('CreateAppCookieStickinessPolicy', params) def create_lb_cookie_stickiness_policy(self, cookie_expiration_period, lb_name, policy_name): \"\"\" Generates a",
"instances: self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return self.get_list('DescribeInstanceHealth', params, [('member', InstanceState)]) def",
"of the application-generated cookie specified in the policy configuration. The",
"Must specify one of the two options return None params",
"and to permit # persons to whom the Software is",
"doing HTTPS. :type complex_listeners: List of tuples :param complex_listeners: Each",
"* connectionDraining - :py:class:`ConnectionDrainingAttribute` instance :rtype: Attribute dependent :return: The",
"for instances in this Load Balancer. \"\"\" params = {'LoadBalancerName':",
"create_lb_policy(self, lb_name, policy_name, policy_type, policy_attributes): \"\"\" Creates a new policy",
"ARN of a AWS IAM certificate, and must be specified",
"port return self.get_status('DeleteLoadBalancerListeners', params) def enable_availability_zones(self, load_balancer_name, zones_to_add): \"\"\" Add",
"zones_to_remove, 'AvailabilityZones.member.%d') obj = self.get_object('DisableAvailabilityZonesForLoadBalancer', params, LoadBalancerZones) return obj.zones def",
"'PolicyName': policy_name, 'PolicyTypeName': policy_type} for index, (name, value) in enumerate(policy_attributes.iteritems(),",
"balancer. Applying security groups that are already registered with the",
"request \"\"\" if not listeners and not complex_listeners: # Must",
"'InstancePort': instance_port} if policies: self.build_list_params(params, policies, 'PolicyNames.member.%d') else: params['PolicyNames'] =",
"or None if an invalid region name is given \"\"\"",
"params['Listeners.member.%d.SSLCertificateId' % i] = listener[4] if zones: self.build_list_params(params, zones, 'AvailabilityZones.member.%d')",
"cookie is issued. \"\"\" params = {'CookieName': name, 'LoadBalancerName': lb_name,",
"Creates a Listener (or group of listeners) for an existing",
"bool_reqs = ('crosszoneloadbalancing',) if attribute.lower() in bool_reqs: if isinstance(value, bool):",
"deregister_instances(self, load_balancer_name, instances): \"\"\" Remove Instances from an existing Load",
"associated documentation files (the # \"Software\"), to deal in the",
"class ELBConnection(AWSQueryConnection): APIVersion = boto.config.get('Boto', 'elb_version', '2012-06-01') DefaultRegionName = boto.config.get('Boto',",
"= item def get_all_load_balancers(self, load_balancer_names=None): \"\"\" Retrieve all load balancers",
"{'LoadBalancerName': load_balancer_name} self.build_list_params(params, zones_to_add, 'AvailabilityZones.member.%d') obj = self.get_object('EnableAvailabilityZonesForLoadBalancer', params, LoadBalancerZones)",
":class:`boto.ec2.elb.instancestate.InstanceState` :return: list of state info for instances in this",
"= listener[3] # Handle the full listeners if complex_listeners: for",
"available for LoadBalancers attached to an Amazon VPC. :type complex_listeners:",
"# IN THE SOFTWARE. # \"\"\" This module provides an",
"the new load balancer :type zones: List of strings :param",
"[('member', InstanceState)]) def configure_health_check(self, name, health_check): \"\"\" Define a health",
"track the backend server instance for each request. When the",
"groups for this Load Balancer. \"\"\" params = {'LoadBalancerName': name}",
"has no effect. :type name: string :param name: The name",
":type load_balancer_names: list :keyword load_balancer_names: An optional list of load",
"Balancing creates an internet-facing LoadBalancer with a publicly resolvable DNS",
"resolves to private IP addresses. This option is only available",
"options return None params = {'LoadBalancerName': name, 'Scheme': scheme} #",
"\"\"\" Add new Instances to an existing Load Balancer. :type",
"a health check for the EndPoints. :type name: string :param",
"params = {'LoadBalancerName': lb_name, 'LoadBalancerPort': lb_port} if len(policies): self.build_list_params(params, policies,",
"- :py:class:`ConnectionDrainingAttribute` instance :rtype: Attribute dependent :return: The new value",
"newly created :class:`boto.ec2.elb.loadbalancer.LoadBalancer` \"\"\" if not listeners and not complex_listeners:",
":rtype: Attribute dependent :return: The new value for the attribute",
"necessary attributes depending on the policy type. Policies are settings",
"params = {'LoadBalancerName': name, 'Scheme': scheme} # Handle legacy listeners",
"Elastic Load Balancing creates an internet-facing LoadBalancer with a publicly",
"attribute.lower() == 'connectiondraining': params['LoadBalancerAttributes.ConnectionDraining.Enabled'] = \\ value.enabled and 'true' or",
"name} for index, port in enumerate(ports): params['LoadBalancerPorts.member.%d' % (index +",
":keyword load_balancer_names: An optional list of load balancer names. :rtype:",
"and subnets must not be None. The load balancer will",
"load balancer sends the request to a server that is",
"only available for LoadBalancers attached to an Amazon VPC. :type",
"a request, it first checks to see if this cookie",
"one or more subnets. Attaching subnets that are already registered",
"load_balancer.availability_zones = zones load_balancer.subnets = subnets load_balancer.security_groups = security_groups return",
"the Load Balancer :type attribute: string :param attribute: The attribute",
"listener. \"\"\" params = {'LoadBalancerName': lb_name, 'LoadBalancerPort': lb_port} if len(policies):",
"self.build_list_params(params, security_groups, 'SecurityGroups.member.%d') return self.get_list('ApplySecurityGroupsToLoadBalancer', params, None) def attach_lb_to_subnets(self, name,",
"the same user to that server. The validity of the",
"'TCP', 'SSL', 'HTTP', or 'HTTPS' - SSLCertificateId is the ARN",
"List of strings :return: An updated list of zones for",
"None params = {'LoadBalancerName': name, 'Scheme': scheme} # Handle legacy",
"create the listeners for :type listeners: List of tuples :param",
"params, LbAttributes) def get_lb_attribute(self, load_balancer_name, attribute): \"\"\"Gets an attribute of",
"self.get_all_lb_attributes(load_balancer_name) if attribute.lower() == 'accesslog': return attributes.access_log if attribute.lower() ==",
"= {'LoadBalancerName': load_balancer_name} if instances: self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return self.get_list('DescribeInstanceHealth',",
"policy_type, policy_attributes): \"\"\" Creates a new policy that contais the",
"a new policy that contais the necessary attributes depending on",
":rtype: :py:class:`boto.resultset.ResultSet` :return: A ResultSet containing instances of :class:`boto.ec2.elb.loadbalancer.LoadBalancer` \"\"\"",
"set_lb_policies_of_backend_server(self, lb_name, instance_port, policies): \"\"\" Replaces the current set of",
"certificate that was used on the same LoadBalancer and port.",
"if attribute.lower() == 'accesslog': return attributes.access_log if attribute.lower() == 'crosszoneloadbalancing':",
"cookie_expiration_period return self.get_status('CreateLBCookieStickinessPolicy', params) def create_lb_policy(self, lb_name, policy_name, policy_type, policy_attributes):",
"your account. By default the load balancer will be created",
"service. :rtype: list :return: A list of :class:`boto.RegionInfo` instances \"\"\"",
"'SSL': params['Listeners.member.%d.SSLCertificateId' % i] = listener[3] # Handle the full",
"if attribute.lower() == 'crosszoneloadbalancing': params['LoadBalancerAttributes.CrossZoneLoadBalancing.Enabled' ] = value elif attribute.lower()",
"ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN",
"None) def detach_lb_from_subnets(self, name, subnets): \"\"\" Detaches load balancer from",
"BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY,",
"balancer to create the listeners for :type listeners: List of",
"accessLog - :py:class:`AccessLogAttribute` instance * connectionDraining - :py:class:`ConnectionDrainingAttribute` instance :type",
"params) def delete_lb_policy(self, lb_name, policy_name): \"\"\" Deletes a policy from",
"= {'LoadBalancerName': name} return self.get_status('DeleteLoadBalancer', params) def delete_load_balancer_listeners(self, name, ports):",
"when doing HTTPS. :type subnets: list of strings :param subnets:",
"be created in EC2. To create a load balancer inside",
"The names of the availability zone(s) to add. :type listeners:",
"checks to see if this cookie is present in the",
"self.build_list_params(params, zones, 'AvailabilityZones.member.%d') if subnets: self.build_list_params(params, subnets, 'Subnets.member.%d') if security_groups:",
"not, the load balancer sends the request to a server",
":param subnets: The name of the subnet(s) to add. :rtype:",
"name of the Load Balancer :type subnets: List of strings",
"port. \"\"\" params = {'LoadBalancerName': lb_name, 'LoadBalancerPort': lb_port, 'SSLCertificateId': ssl_certificate_id}",
"name, 'Scheme': scheme} # Handle legacy listeners if listeners: for",
"\"\"\" Deletes a policy from the LoadBalancer. The specified policy",
"subnets load_balancer.security_groups = security_groups return load_balancer def create_load_balancer_listeners(self, name, listeners=None,",
"'AvailabilityZones.member.%d') if subnets: self.build_list_params(params, subnets, 'Subnets.member.%d') if security_groups: self.build_list_params(params, security_groups,",
"instance ID's of the EC2 instances to add. :rtype: List",
"with the Load Balancer has no effect. :type name: string",
"# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR",
"a policy from the LoadBalancer. The specified policy must not",
"add. :rtype: List of strings :return: An updated list of",
"in the policy configuration. None may be passed for cookie_expiration_period.",
"software and associated documentation files (the # \"Software\"), to deal",
"one or more subnets. :type name: string :param name: The",
":type instances: List of strings :param instances: The instance ID's",
"of all instances will be returned. :rtype: List of :class:`boto.ec2.elb.instancestate.InstanceState`",
"connections. The specified certificate replaces any prior certificate that was",
"of security groups for this Load Balancer. \"\"\" params =",
"to return status for. If not provided, the state of",
"= '' return self.get_status('SetLoadBalancerPoliciesOfListener', params) def set_lb_policies_of_backend_server(self, lb_name, instance_port, policies):",
"None and subnets must not be None. The load balancer",
"zones to an existing Load Balancer All zones must be",
"is the ARN of an SSL certificate loaded into AWS",
"AWS. \"\"\" from boto.connection import AWSQueryConnection from boto.ec2.instanceinfo import InstanceInfo",
"region.name == region_name: return region.connect(**kw_params) return None class ELBConnection(AWSQueryConnection): APIVersion",
"self.build_list_params(params, zones_to_remove, 'AvailabilityZones.member.%d') obj = self.get_object('DisableAvailabilityZonesForLoadBalancer', params, LoadBalancerZones) return obj.zones",
"special cookie to track the backend server instance for each",
"expiration time, which is specified in the policy configuration. None",
"USE OR OTHER DEALINGS # IN THE SOFTWARE. # \"\"\"",
"for any listeners. \"\"\" params = {'LoadBalancerName': lb_name, 'PolicyName': policy_name}",
"four values, (LoadBalancerPortNumber, InstancePortNumber, Protocol, [SSLCertificateId]) where LoadBalancerPortNumber and InstancePortNumber",
"self.get_object('DisableAvailabilityZonesForLoadBalancer', params, LoadBalancerZones) return obj.zones def modify_lb_attribute(self, load_balancer_name, attribute, value):",
"Balancer. \"\"\" params = {'LoadBalancerName': load_balancer_name} self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return",
"EC2 instances to remove. :rtype: List of strings :return: An",
"protocol == 'SSL': params['Listeners.member.%d.SSLCertificateId' % i] = listener[3] # Handle",
"deal in the Software without restriction, including # without limitation",
"{'LoadBalancerName': name} self.build_list_params(params, security_groups, 'SecurityGroups.member.%d') return self.get_list('ApplySecurityGroupsToLoadBalancer', params, None) def",
"\"\"\" Get current state of all Instances registered to an",
"obj.zones def disable_availability_zones(self, load_balancer_name, zones_to_remove): \"\"\" Remove availability zones from",
":param complex_listeners: Each tuple contains four or five values, (LoadBalancerPortNumber,",
"subnets, 'Subnets.member.%d') if security_groups: self.build_list_params(params, security_groups, 'SecurityGroups.member.%d') load_balancer = self.get_object('CreateLoadBalancer',",
"AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,",
"dis- # tribute, sublicense, and/or sell copies of the Software,",
"\"\"\" Init method to create a new connection to EC2",
"self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return self.get_list('DeregisterInstancesFromLoadBalancer', params, [('member', InstanceInfo)]) def describe_instance_health(self,",
"in enumerate(items): params[label % (index + 1)] = item def",
"zones for this Load Balancer. \"\"\" params = {'LoadBalancerName': load_balancer_name}",
"import boto RegionData = load_regions().get('elasticloadbalancing', {}) def regions(): \"\"\" Get",
"internet-facing LoadBalancer with a publicly resolvable DNS name, which resolves",
"load balancer inside a VPC, parameter zones must be set",
"EC2. To create a load balancer inside a VPC, parameter",
"subnets: A list of subnet IDs in your VPC to",
"session stops being sticky until a new application cookie is",
"Load Balancer. :type load_balancer_name: string :param load_balancer_name: The name of",
"return self.get_object('DescribeLoadBalancerAttributes', params, LbAttributes) def get_lb_attribute(self, load_balancer_name, attribute): \"\"\"Gets an",
"existing Load Balancer All zones must be in the same",
"Load Balancer has no effect. :type name: string :param name:",
"The name of the Load Balancer to delete \"\"\" params",
"If not, the load balancer sends the request to a",
"SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR",
"return ['ec2'] def build_list_params(self, params, items, label): if isinstance(items, basestring):",
"the region specified in the boto configuration file. \"\"\" if",
"this cookie is present in the request. If so, the",
":param health_check: A HealthCheck object populated with the desired values.",
"InstanceInfo from boto.ec2.elb.loadbalancer import LoadBalancer, LoadBalancerZones from boto.ec2.elb.instancestate import InstanceState",
"if not region: region = RegionInfo(self, self.DefaultRegionName, self.DefaultRegionEndpoint) self.region =",
"specified expiration period. This policy can only be associated only",
"Load Balancer. \"\"\" params = {'LoadBalancerName': name} self.build_list_params(params, subnets, 'Subnets.member.%d')",
"Software is furnished to do so, subject to the fol-",
"modify, merge, publish, dis- # tribute, sublicense, and/or sell copies",
"All zones must be in the same region as the",
"the two options return None params = {'LoadBalancerName': name} #",
"self.build_list_params(params, zones_to_add, 'AvailabilityZones.member.%d') obj = self.get_object('EnableAvailabilityZonesForLoadBalancer', params, LoadBalancerZones) return obj.zones",
"can only be associated with HTTP listeners. This policy is",
"includes a new application cookie. If the application cookie is",
"def delete_lb_policy(self, lb_name, policy_name): \"\"\" Deletes a policy from the",
"lb_name, 'PolicyName': policy_name} return self.get_status('DeleteLoadBalancerPolicy', params) def set_lb_policies_of_listener(self, lb_name, lb_port,",
"of strings :return: An updated list of instances for this",
"and port. \"\"\" params = {'LoadBalancerName': lb_name, 'LoadBalancerPort': lb_port, 'SSLCertificateId':",
"import AWSQueryConnection from boto.ec2.instanceinfo import InstanceInfo from boto.ec2.elb.loadbalancer import LoadBalancer,",
"on the existing load balancing algorithm. A cookie is inserted",
":class:`boto.ec2.elb.ELBConnection`. :param str region_name: The name of the region to",
"connectionDraining - :py:class:`ConnectionDrainingAttribute` instance :type value: string :param value: The",
"if cookie_expiration_period is not None: params['CookieExpirationPeriod'] = cookie_expiration_period return self.get_status('CreateLBCookieStickinessPolicy',",
"The mnemonic name associated with the new load balancer :type",
"== region_name: return region.connect(**kw_params) return None class ELBConnection(AWSQueryConnection): APIVersion =",
"def attach_lb_to_subnets(self, name, subnets): \"\"\" Attaches load balancer to one",
"policy can only be associated only with HTTP listeners. When",
"or more subnets. :type name: string :param name: The name",
"the desired values. :rtype: :class:`boto.ec2.elb.healthcheck.HealthCheck` :return: The updated :class:`boto.ec2.elb.healthcheck.HealthCheck` \"\"\"",
"Balancer. All zones must be in the same region as",
"OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE.",
"security groups to the load balancer. Applying security groups that",
"of an application-generated cookie. This policy can only be associated",
"to None and subnets must not be None. The load",
"enabled for any listeners. \"\"\" params = {'LoadBalancerName': lb_name, 'PolicyName':",
"a listener on the load balancer. Currently only zero (0)",
"65535, Protocol is a string containing either 'TCP', 'SSL', HTTP',",
"from one or more subnets. :type name: string :param name:",
"health_check): \"\"\" Define a health check for the EndPoints. :type",
"LbAttributes params = {'LoadBalancerName': load_balancer_name} return self.get_object('DescribeLoadBalancerAttributes', params, LbAttributes) def",
"to the fol- # lowing conditions: # # The above",
"this Load Balancer. \"\"\" params = {'LoadBalancerName': load_balancer_name} if instances:",
"self.build_list_params(params, security_groups, 'SecurityGroups.member.%d') load_balancer = self.get_object('CreateLoadBalancer', params, LoadBalancer) load_balancer.name =",
"security_groups: List of strings :param security_groups: The name of the",
"policy with sticky session lifetimes controlled by the lifetime of",
"the response for binding subsequent requests from the same user",
"strings :param zones: The name of the zone(s) to add.",
"the policy created by CreateLBCookieStickinessPolicy, except that the lifetime of",
"= [items] for index, item in enumerate(items): params[label % (index",
"LoadBalancerZones) return obj.zones def disable_availability_zones(self, load_balancer_name, zones_to_remove): \"\"\" Remove availability",
"not None: params['CookieExpirationPeriod'] = cookie_expiration_period return self.get_status('CreateLBCookieStickinessPolicy', params) def create_lb_policy(self,",
"ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO",
"the necessary attributes depending on the policy type. Policies are",
"load_balancer_name} if instances: self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return self.get_list('DescribeInstanceHealth', params, [('member',",
"Add availability zones to an existing Load Balancer All zones",
"build_list_params(self, params, items, label): if isinstance(items, basestring): items = [items]",
"of strings :return: An updated list of security groups for",
"three or four values, (LoadBalancerPortNumber, InstancePortNumber, Protocol, [SSLCertificateId]) where LoadBalancerPortNumber",
"proxy_pass, self.region.endpoint, debug, https_connection_factory, path, security_token, validate_certs=validate_certs, profile_name=profile_name) def _required_auth_capability(self):",
"is based on the cookie expiration time, which is specified",
"None: params['CookieExpirationPeriod'] = cookie_expiration_period return self.get_status('CreateLBCookieStickinessPolicy', params) def create_lb_policy(self, lb_name,",
"policy that contais the necessary attributes depending on the policy",
"name: string :param name: The mnemonic name associated with the",
"IN THE SOFTWARE. # \"\"\" This module provides an interface",
"params['LoadBalancerAttributes.ConnectionDraining.Enabled'] = \\ value.enabled and 'true' or 'false' params['LoadBalancerAttributes.ConnectionDraining.Timeout'] =",
"only be associated only with HTTP listeners. When a load",
"instances: The instance ID's of the EC2 instances to remove.",
"'HealthCheck.HealthyThreshold': health_check.healthy_threshold} return self.get_object('ConfigureHealthCheck', params, HealthCheck) def set_lb_listener_SSL_certificate(self, lb_name, lb_port,",
"effect. :type name: string :param name: The name of the",
"from AWS. \"\"\" from boto.connection import AWSQueryConnection from boto.ec2.instanceinfo import",
"'PolicyName': policy_name} if cookie_expiration_period is not None: params['CookieExpirationPeriod'] = cookie_expiration_period",
"load_regions().get('elasticloadbalancing', {}) def regions(): \"\"\" Get all available regions for",
"the EndPoints. :type name: string :param name: The mnemonic name",
"'PolicyName': policy_name} return self.get_status('DeleteLoadBalancerPolicy', params) def set_lb_policies_of_listener(self, lb_name, lb_port, policies):",
"be in the same region as the Load Balancer Adding",
"certificate, and must be specified when doing HTTPS. :type subnets:",
"LoadBalancer. By default, Elastic Load Balancing creates an internet-facing LoadBalancer",
"each request. When the load balancer receives a request, it",
"all load balancers associated with your account. :type load_balancer_names: list",
"return obj.zones def modify_lb_attribute(self, load_balancer_name, attribute, value): \"\"\"Changes an attribute",
"Load Balancer :type instances: List of strings :param instances: The",
"without restriction, including # without limitation the rights to use,",
"IAM :rtype: :class:`boto.ec2.elb.loadbalancer.LoadBalancer` :return: The newly created :class:`boto.ec2.elb.loadbalancer.LoadBalancer` \"\"\" if",
"'' return self.get_status('SetLoadBalancerPoliciesOfListener', params) def set_lb_policies_of_backend_server(self, lb_name, instance_port, policies): \"\"\"",
"listener[2].upper() params['Listeners.member.%d.LoadBalancerPort' % i] = listener[0] params['Listeners.member.%d.InstancePort' % i] =",
"from boto.connection import AWSQueryConnection from boto.ec2.instanceinfo import InstanceInfo from boto.ec2.elb.loadbalancer",
"application response includes a new application cookie. If the application",
":param zones: The names of the availability zone(s) to add.",
"[('member', LoadBalancer)]) def create_load_balancer(self, name, zones, listeners=None, subnets=None, security_groups=None, scheme='internet-facing',",
"ELBConnection(AWSQueryConnection): APIVersion = boto.config.get('Boto', 'elb_version', '2012-06-01') DefaultRegionName = boto.config.get('Boto', 'elb_region_name',",
"def enable_availability_zones(self, load_balancer_name, zones_to_add): \"\"\" Add availability zones to an",
"# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"cookie_expiration_period. \"\"\" params = {'LoadBalancerName': lb_name, 'PolicyName': policy_name} if cookie_expiration_period",
"stickiness cookie when the application response includes a new application",
"1)] = port return self.get_status('DeleteLoadBalancerListeners', params) def enable_availability_zones(self, load_balancer_name, zones_to_add):",
"'HTTPS' or protocol == 'SSL': params['Listeners.member.%d.SSLCertificateId' % i] = listener[4]",
"value internal for this option to create an internal LoadBalancer",
"listener[2].upper() InstanceProtocol = listener[3].upper() params['Listeners.member.%d.LoadBalancerPort' % i] = listener[0] params['Listeners.member.%d.InstancePort'",
"to your LoadBalancer within your VPC. :type scheme: string :param",
"'Instances.member.%d.InstanceId') return self.get_list('DescribeInstanceHealth', params, [('member', InstanceState)]) def configure_health_check(self, name, health_check):",
"subnets. Attaching subnets that are already registered with the Load",
"so, the load balancer sends the request to the application",
"Each tuple contains four or five values, (LoadBalancerPortNumber, InstancePortNumber, Protocol,",
"strings :param subnets: The name of the subnet(s) to add.",
"i] = listener[1] params['Listeners.member.%d.Protocol' % i] = listener[2] if protocol",
"load balancing service from AWS. \"\"\" from boto.connection import AWSQueryConnection",
"inserts a new stickiness cookie when the application response includes",
"The security groups assigned to your LoadBalancer within your VPC.",
"This option is only available for LoadBalancers attached to an",
"% i] = listener[1] params['Listeners.member.%d.Protocol' % i] = listener[2] params['Listeners.member.%d.InstanceProtocol'",
"'accesslog': params['LoadBalancerAttributes.AccessLog.Enabled'] = \\ value.enabled and 'true' or 'false' params['LoadBalancerAttributes.AccessLog.S3BucketName']",
"security groups for this Load Balancer. \"\"\" params = {'LoadBalancerName':",
"RegionInfo, get_regions, load_regions import boto RegionData = load_regions().get('elasticloadbalancing', {}) def",
"= {'LoadBalancerName': load_balancer_name} return self.get_object('DescribeLoadBalancerAttributes', params, LbAttributes) def get_lb_attribute(self, load_balancer_name,",
"ELB service. :rtype: list :return: A list of :class:`boto.RegionInfo` instances",
"The specified certificate replaces any prior certificate that was used",
"balancer from one or more subnets. :type name: string :param",
"or 'false' params['LoadBalancerAttributes.AccessLog.S3BucketName'] = \\ value.s3_bucket_name params['LoadBalancerAttributes.AccessLog.S3BucketPrefix'] = \\ value.s3_bucket_prefix",
"or not \"\"\" bool_reqs = ('crosszoneloadbalancing',) if attribute.lower() in bool_reqs:",
"\"\"\" for region in regions(): if region.name == region_name: return",
"that are saved for your load balancer and that can",
"to private IP addresses. This option is only available for",
"for this Load Balancer. \"\"\" params = {'LoadBalancerName': load_balancer_name} self.build_list_params(params,",
"regions for the ELB service. :rtype: list :return: A list",
"if attribute.lower() in bool_reqs: if isinstance(value, bool): if value: value",
"value = 'true' else: value = 'false' params = {'LoadBalancerName':",
"the ARN of a AWS IAM certificate, and must be",
"by the region specified in the boto configuration file. \"\"\"",
"i] = listener[3] # Handle the full listeners if complex_listeners:",
"return self.get_status('CreateAppCookieStickinessPolicy', params) def create_lb_cookie_stickiness_policy(self, cookie_expiration_period, lb_name, policy_name): \"\"\" Generates",
"'crosszoneloadbalancing': params['LoadBalancerAttributes.CrossZoneLoadBalancing.Enabled' ] = value elif attribute.lower() == 'accesslog': params['LoadBalancerAttributes.AccessLog.Enabled']",
"validate_certs=validate_certs, profile_name=profile_name) def _required_auth_capability(self): return ['ec2'] def build_list_params(self, params, items,",
"values between 1 and 65535 - Protocol and InstanceProtocol is",
"load balancer receives a request, it first checks to see",
"['ec2'] def build_list_params(self, params, items, label): if isinstance(items, basestring): items",
"to connect to. :rtype: :class:`boto.ec2.ELBConnection` or ``None`` :return: A connection",
"List of :class:`boto.ec2.elb.instancestate.InstanceState` :return: list of state info for instances",
":type subnets: List of strings :param subnets: The name of",
"provides an interface to the Elastic Compute Cloud (EC2) load",
"to delete \"\"\" params = {'LoadBalancerName': name} return self.get_status('DeleteLoadBalancer', params)",
"IDs in your VPC to attach to your LoadBalancer. :type",
":param listeners: Each tuple contains three or four values, (LoadBalancerPortNumber,",
"the Load Balancer to delete \"\"\" params = {'LoadBalancerName': name}",
"boto.ec2.elb.loadbalancer import LoadBalancer, LoadBalancerZones from boto.ec2.elb.instancestate import InstanceState from boto.ec2.elb.healthcheck",
"\"\"\" params = {'LoadBalancerName': load_balancer_name} self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return self.get_list('DeregisterInstancesFromLoadBalancer',",
"{'LoadBalancerName': load_balancer_name} self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return self.get_list('DeregisterInstancesFromLoadBalancer', params, [('member', InstanceInfo)])",
"validity of the cookie is based on the cookie expiration",
"is only available for LoadBalancers attached to an Amazon VPC.",
"inserted into the response for binding subsequent requests from the",
"LoadBalancer, LoadBalancerZones from boto.ec2.elb.instancestate import InstanceState from boto.ec2.elb.healthcheck import HealthCheck",
"% i] = listener[2] params['Listeners.member.%d.InstanceProtocol' % i] = listener[3] if",
"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER",
"region super(ELBConnection, self).__init__(aws_access_key_id, aws_secret_access_key, is_secure, port, proxy, proxy_port, proxy_user, proxy_pass,",
"if policies: self.build_list_params(params, policies, 'PolicyNames.member.%d') else: params['PolicyNames'] = '' return",
"a DNS name that resolves to private IP addresses. This",
"merge, publish, dis- # tribute, sublicense, and/or sell copies of",
"and not complex_listeners: # Must specify one of the two",
"state of all Instances registered to an Load Balancer. :type",
"availability zones from an existing Load Balancer. All zones must",
"= index + 1 protocol = listener[2].upper() params['Listeners.member.%d.LoadBalancerPort' % i]",
":return: The newly created :class:`boto.ec2.elb.loadbalancer.LoadBalancer` \"\"\" if not listeners and",
"for the EndPoints. :type name: string :param name: The mnemonic",
"updates, or disables a policy with a listener on the",
"of the browser (user-agent) or a specified expiration period. This",
"to a server that is chosen based on the existing",
"of charge, to any person obtaining a # copy of",
"params = {'LoadBalancerName': name} # Handle the simple listeners if",
"Create a new load balancer for your account. By default",
"Whether the operation succeeded or not \"\"\" bool_reqs = ('crosszoneloadbalancing',)",
"resolvable DNS name, which resolves to public IP addresses. Specify",
"import LoadBalancer, LoadBalancerZones from boto.ec2.elb.instancestate import InstanceState from boto.ec2.elb.healthcheck import",
"InstanceProtocol is a string containing either 'TCP', 'SSL', 'HTTP', or",
"attribute of a Load Balancer :type load_balancer_name: string :param load_balancer_name:",
"the same region as the Load Balancer. Removing zones that",
"subnet IDs in your VPC to attach to your LoadBalancer.",
"to create an internal LoadBalancer with a DNS name that",
"rights to use, copy, modify, merge, publish, dis- # tribute,",
"instances for this Load Balancer. \"\"\" params = {'LoadBalancerName': load_balancer_name}",
"If the application cookie is explicitly removed or expires, the",
"on the load balancer. Currently only zero (0) or one",
"region_name: return region.connect(**kw_params) return None class ELBConnection(AWSQueryConnection): APIVersion = boto.config.get('Boto',",
"of load balancer names. :rtype: :py:class:`boto.resultset.ResultSet` :return: A ResultSet containing",
"is overridden by the region specified in the boto configuration",
"The newly created :class:`boto.ec2.elb.loadbalancer.LoadBalancer` \"\"\" if not listeners and not",
"an existing Load Balancer. :type load_balancer_name: string :param load_balancer_name: The",
"self.get_list('AttachLoadBalancerToSubnets', params, None) def detach_lb_from_subnets(self, name, subnets): \"\"\" Detaches load",
"must be specified when doing HTTPS. :type complex_listeners: List of",
"not be enabled for any listeners. \"\"\" params = {'LoadBalancerName':",
"profile_name=None): \"\"\" Init method to create a new connection to",
"DEALINGS # IN THE SOFTWARE. # \"\"\" This module provides",
"+ 1)] = item def get_all_load_balancers(self, load_balancer_names=None): \"\"\" Retrieve all",
"in the same region as the Load Balancer. Removing zones",
"name load_balancer.listeners = listeners load_balancer.availability_zones = zones load_balancer.subnets = subnets",
"params, [('member', InstanceState)]) def configure_health_check(self, name, health_check): \"\"\" Define a",
"populated with the desired values. :rtype: :class:`boto.ec2.elb.healthcheck.HealthCheck` :return: The updated",
"same region as the Load Balancer Adding zones that are",
"Balancing Service. .. note:: The region argument is overridden by",
"Balancer This will make an EC2 call for each method",
"SSL certificate loaded into AWS IAM :rtype: :class:`boto.ec2.elb.loadbalancer.LoadBalancer` :return: The",
"charge, to any person obtaining a # copy of this",
"copy of this software and associated documentation files (the #",
"the Elastic Compute Cloud (EC2) load balancing service from AWS.",
":rtype: :class:`boto.ec2.ELBConnection` or ``None`` :return: A connection to the given",
"only be associated with HTTP listeners. This policy is similar",
"loaded into AWS IAM :return: The status of the request",
"in enumerate(complex_listeners): i = index + 1 protocol = listener[2].upper()",
"status of the request \"\"\" params = {'LoadBalancerName': name} for",
"PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR",
"listeners: for index, listener in enumerate(listeners): i = index +",
"IP addresses. Specify the value internal for this option to",
":return: A ResultSet containing instances of :class:`boto.ec2.elb.loadbalancer.LoadBalancer` \"\"\" params =",
"listeners for :type ports: List int :param ports: Each int",
":param load_balancer_name: The name of the Load Balancer :type attribute:",
"The attribute object of the ELB. \"\"\" from boto.ec2.elb.attributes import",
"names of the availability zone(s) to add. :type listeners: List",
"Load Balancer :type load_balancer_name: string :param load_balancer_name: The name of",
":type zones: List of strings :param zones: The names of",
"with the desired values. :rtype: :class:`boto.ec2.elb.healthcheck.HealthCheck` :return: The updated :class:`boto.ec2.elb.healthcheck.HealthCheck`",
":type name: string :param name: The name of the load",
"The new value for the attribute :rtype: bool :return: Whether",
"* accessLog - :py:class:`AccessLogAttribute` instance * connectionDraining - :py:class:`ConnectionDrainingAttribute` instance",
"of the ELB. \"\"\" from boto.ec2.elb.attributes import LbAttributes params =",
"self.get_status('DeleteLoadBalancerListeners', params) def enable_availability_zones(self, load_balancer_name, zones_to_add): \"\"\" Add availability zones",
"and InstancePortNumber are integer values between 1 and 65535, Protocol",
"the backend server instance for each request. When the load",
"'SSLCertificateId': ssl_certificate_id} return self.get_status('SetLoadBalancerListenerSSLCertificate', params) def create_app_cookie_stickiness_policy(self, name, lb_name, policy_name):",
"return self.get_status('SetLoadBalancerPoliciesForBackendServer', params) def apply_security_groups_to_lb(self, name, security_groups): \"\"\" Applies security",
"disable_availability_zones(self, load_balancer_name, zones_to_remove): \"\"\" Remove availability zones from an existing",
"load_balancer_names, 'LoadBalancerNames.member.%d') return self.get_list('DescribeLoadBalancers', params, [('member', LoadBalancer)]) def create_load_balancer(self, name,",
"an existing Load Balancer. All zones must be in the",
"def get_all_lb_attributes(self, load_balancer_name): \"\"\"Gets all Attributes of a Load Balancer",
"only zero (0) or one (1) policy can be associated",
"strings :param instances: The instance ID's of the EC2 instances",
"with the load balancer :type health_check: :class:`boto.ec2.elb.healthcheck.HealthCheck` :param health_check: A",
"* crossZoneLoadBalancing - Boolean * connectionDraining - :py:class:`ConnectionDrainingAttribute` instance :rtype:",
"params['PolicyNames'] = '' return self.get_status('SetLoadBalancerPoliciesOfListener', params) def set_lb_policies_of_backend_server(self, lb_name, instance_port,",
"created under the VPC that contains the subnet(s) specified. :type",
"of strings :return: An updated list of subnets for this",
"scheme: The type of a LoadBalancer. By default, Elastic Load",
"port in enumerate(ports): params['LoadBalancerPorts.member.%d' % (index + 1)] = port",
"params = {'CookieName': name, 'LoadBalancerName': lb_name, 'PolicyName': policy_name} return self.get_status('CreateAppCookieStickinessPolicy',",
":type complex_listeners: List of tuples :param complex_listeners: Each tuple contains",
":return: An updated list of zones for this Load Balancer.",
"= name params['PolicyAttributes.member.%d.AttributeValue' % index] = value else: params['PolicyAttributes'] =",
"https_connection_factory, path, security_token, validate_certs=validate_certs, profile_name=profile_name) def _required_auth_capability(self): return ['ec2'] def",
"make an EC2 call for each method call. :type load_balancer_name:",
"application cookie is explicitly removed or expires, the session stops",
"cookie_expiration_period is not None: params['CookieExpirationPeriod'] = cookie_expiration_period return self.get_status('CreateLBCookieStickinessPolicy', params)",
"def create_lb_policy(self, lb_name, policy_name, policy_type, policy_attributes): \"\"\" Creates a new",
"params = {'LoadBalancerName': name, 'HealthCheck.Timeout': health_check.timeout, 'HealthCheck.Target': health_check.target, 'HealthCheck.Interval': health_check.interval,",
"of the cookie is based on the cookie expiration time,",
"List of strings :param subnets: The name of the subnet(s)",
"subsequent requests from the same user to that server. The",
"policies, 'PolicyNames.member.%d') else: params['PolicyNames'] = '' return self.get_status('SetLoadBalancerPoliciesOfListener', params) def",
"return a :class:`boto.ec2.elb.ELBConnection`. :param str region_name: The name of the",
"contains four or five values, (LoadBalancerPortNumber, InstancePortNumber, Protocol, InstanceProtocol, SSLCertificateId).",
"1)] = item def get_all_load_balancers(self, load_balancer_names=None): \"\"\" Retrieve all load",
"or its affiliates. # All Rights Reserved # # Permission",
"new Instances to an existing Load Balancer. :type load_balancer_name: string",
"or substantial portions of the Software. # # THE SOFTWARE",
"can be applied to the front-end listener, or the back-end",
"{} if load_balancer_names: self.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') return self.get_list('DescribeLoadBalancers', params, [('member',",
"params = {'LoadBalancerName': lb_name, 'InstancePort': instance_port} if policies: self.build_list_params(params, policies,",
"load_balancer_name: The name of the Load Balancer :type instances: List",
"= value else: params['PolicyAttributes'] = '' return self.get_status('CreateLoadBalancerPolicy', params) def",
"OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR",
"or 'false' params['LoadBalancerAttributes.ConnectionDraining.Timeout'] = \\ value.timeout else: raise ValueError('InvalidAttribute', attribute)",
"and that can be applied to the front-end listener, or",
"this Load Balancer. \"\"\" params = {'LoadBalancerName': load_balancer_name} self.build_list_params(params, instances,",
"security_groups=None, scheme='internet-facing', complex_listeners=None): \"\"\" Create a new load balancer for",
"list :return: A list of :class:`boto.RegionInfo` instances \"\"\" return get_regions('elasticloadbalancing',",
".. note:: The region argument is overridden by the region",
"params, LoadBalancer) load_balancer.name = name load_balancer.listeners = listeners load_balancer.availability_zones =",
"self.get_list('DescribeInstanceHealth', params, [('member', InstanceState)]) def configure_health_check(self, name, health_check): \"\"\" Define",
"either 'TCP', 'SSL', HTTP', or 'HTTPS'; SSLCertificateID is the ARN",
"load balancer and that can be applied to the front-end",
"of listeners) for an existing Load Balancer :type name: string",
"internal for this option to create an internal LoadBalancer with",
"# # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY",
"info for instances in this Load Balancer. \"\"\" params =",
"name, return a :class:`boto.ec2.elb.ELBConnection`. :param str region_name: The name of",
"and InstanceProtocol is a string containing either 'TCP', 'SSL', 'HTTP',",
"boto.ec2.elb.healthcheck import HealthCheck from boto.ec2.elb.listelement import ListElement from boto.regioninfo import",
"= cookie_expiration_period return self.get_status('CreateLBCookieStickinessPolicy', params) def create_lb_policy(self, lb_name, policy_name, policy_type,",
"listeners. \"\"\" params = {'LoadBalancerName': lb_name, 'PolicyName': policy_name} return self.get_status('DeleteLoadBalancerPolicy',",
"zones: The name of the zone(s) to remove. :rtype: List",
"string :param name: The name of the Load Balancer to",
"is given \"\"\" for region in regions(): if region.name ==",
"The mnemonic name associated with the load balancer :type health_check:",
":param load_balancer_name: The name of the Load Balancer :rtype: boto.ec2.elb.attribute.LbAttributes",
"This module provides an interface to the Elastic Compute Cloud",
"the request \"\"\" if not listeners and not complex_listeners: #",
"the EC2 instances to add. :rtype: List of strings :return:",
":return: An updated list of subnets for this Load Balancer.",
"{'LoadBalancerName': load_balancer_name} self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return self.get_list('RegisterInstancesWithLoadBalancer', params, [('member', InstanceInfo)])",
"if complex_listeners: for index, listener in enumerate(complex_listeners): i = index",
"the Load Balancer :type zones: List of strings :param zones:",
"new stickiness cookie when the application response includes a new",
"and 65535 - Protocol and InstanceProtocol is a string containing",
"of the availability zone(s) to add. :type listeners: List of",
"account. :type name: string :param name: The name of the",
"the full listeners if complex_listeners: for index, listener in enumerate(complex_listeners):",
"= listener[3].upper() params['Listeners.member.%d.LoadBalancerPort' % i] = listener[0] params['Listeners.member.%d.InstancePort' % i]",
"self.region.endpoint, debug, https_connection_factory, path, security_token, validate_certs=validate_certs, profile_name=profile_name) def _required_auth_capability(self): return",
"= listeners load_balancer.availability_zones = zones load_balancer.subnets = subnets load_balancer.security_groups =",
"attributes depending on the policy type. Policies are settings that",
"is issued. \"\"\" params = {'CookieName': name, 'LoadBalancerName': lb_name, 'PolicyName':",
"params = {'LoadBalancerName': lb_name, 'PolicyName': policy_name} if cookie_expiration_period is not",
"the value internal for this option to create an internal",
"policies: self.build_list_params(params, policies, 'PolicyNames.member.%d') else: params['PolicyNames'] = '' return self.get_status('SetLoadBalancerPoliciesForBackendServer',",
"int represents the port on the ELB to be removed",
"= index + 1 protocol = listener[2].upper() InstanceProtocol = listener[3].upper()",
"call for each method call. :type load_balancer_name: string :param load_balancer_name:",
"FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE",
"replaces any prior certificate that was used on the same",
"params['Listeners.member.%d.SSLCertificateId' % i] = listener[3] # Handle the full listeners",
"enumerate(items): params[label % (index + 1)] = item def get_all_load_balancers(self,",
"'elb_version', '2012-06-01') DefaultRegionName = boto.config.get('Boto', 'elb_region_name', 'us-east-1') DefaultRegionEndpoint = boto.config.get('Boto',",
"obj = self.get_object('EnableAvailabilityZonesForLoadBalancer', params, LoadBalancerZones) return obj.zones def disable_availability_zones(self, load_balancer_name,",
"a port on which the back-end server is listening with",
"THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR",
"return get_regions('elasticloadbalancing', connection_cls=ELBConnection) def connect_to_region(region_name, **kw_params): \"\"\" Given a valid",
"the existing load balancing algorithm. A cookie is inserted into",
"InstanceProtocol, SSLCertificateId). Where: - LoadBalancerPortNumber and InstancePortNumber are integer values",
"specified listener's SSL connections. The specified certificate replaces any prior",
"policy is similar to the policy created by CreateLBCookieStickinessPolicy, except",
"RegionData = load_regions().get('elasticloadbalancing', {}) def regions(): \"\"\" Get all available",
"instances: The instance ID's of the EC2 instances to return",
"ELB. \"\"\" from boto.ec2.elb.attributes import LbAttributes params = {'LoadBalancerName': load_balancer_name}",
"lb_name, 'LoadBalancerPort': lb_port, 'SSLCertificateId': ssl_certificate_id} return self.get_status('SetLoadBalancerListenerSSLCertificate', params) def create_app_cookie_stickiness_policy(self,",
"to whom the Software is furnished to do so, subject",
"lb_name, policy_name): \"\"\" Deletes a policy from the LoadBalancer. The",
"= zones load_balancer.subnets = subnets load_balancer.security_groups = security_groups return load_balancer",
"all Instances registered to an Load Balancer. :type load_balancer_name: string",
"self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return self.get_list('DescribeInstanceHealth', params, [('member', InstanceState)]) def configure_health_check(self,",
"+ 1)] = port return self.get_status('DeleteLoadBalancerListeners', params) def enable_availability_zones(self, load_balancer_name,",
"int :param ports: Each int represents the port on the",
"are not registered with the Load Balancer has no effect.",
"only inserts a new stickiness cookie when the application response",
"= \\ value.emit_interval elif attribute.lower() == 'connectiondraining': params['LoadBalancerAttributes.ConnectionDraining.Enabled'] = \\",
"\"\"\" if not listeners and not complex_listeners: # Must specify",
"get_regions, load_regions import boto RegionData = load_regions().get('elasticloadbalancing', {}) def regions():",
"Load Balancing cookie follows the lifetime of the application-generated cookie",
"name, security_groups): \"\"\" Applies security groups to the load balancer.",
"Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT",
"import LbAttributes params = {'LoadBalancerName': load_balancer_name} return self.get_object('DescribeLoadBalancerAttributes', params, LbAttributes)",
"HealthCheck) def set_lb_listener_SSL_certificate(self, lb_name, lb_port, ssl_certificate_id): \"\"\" Sets the certificate",
"crossZoneLoadBalancing - Boolean (true) * accessLog - :py:class:`AccessLogAttribute` instance *",
":param value: The new value for the attribute :rtype: bool",
"must be set to None and subnets must not be",
"is a string containing either 'TCP', 'SSL', 'HTTP', or 'HTTPS'",
"EC2 instances to return status for. If not provided, the",
"listener, or the back-end application server. \"\"\" params = {'LoadBalancerName':",
"boto.ec2.elb.listelement import ListElement from boto.regioninfo import RegionInfo, get_regions, load_regions import",
"contais the necessary attributes depending on the policy type. Policies",
"\"\"\" from boto.ec2.elb.attributes import LbAttributes params = {'LoadBalancerName': load_balancer_name} return",
"InstanceState)]) def configure_health_check(self, name, health_check): \"\"\" Define a health check",
"import InstanceInfo from boto.ec2.elb.loadbalancer import LoadBalancer, LoadBalancerZones from boto.ec2.elb.instancestate import",
"configuration. The load balancer only inserts a new stickiness cookie",
"def __init__(self, aws_access_key_id=None, aws_secret_access_key=None, is_secure=True, port=None, proxy=None, proxy_port=None, proxy_user=None, proxy_pass=None,",
"create_load_balancer(self, name, zones, listeners=None, subnets=None, security_groups=None, scheme='internet-facing', complex_listeners=None): \"\"\" Create",
"% (index + 1)] = port return self.get_status('DeleteLoadBalancerListeners', params) def",
":class:`boto.ec2.elb.loadbalancer.LoadBalancer` \"\"\" if not listeners and not complex_listeners: # Must",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-",
"port on which the back-end server is listening with a",
"# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES",
"with the Load Balancer has no effect. :type load_balancer_name: string",
"load_balancer_names: self.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') return self.get_list('DescribeLoadBalancers', params, [('member', LoadBalancer)]) def",
"of tuples :param listeners: Each tuple contains three or four",
"'true' else: value = 'false' params = {'LoadBalancerName': load_balancer_name} if",
"load_balancer.subnets = subnets load_balancer.security_groups = security_groups return load_balancer def create_load_balancer_listeners(self,",
"detach_lb_from_subnets(self, name, subnets): \"\"\" Detaches load balancer from one or",
"tribute, sublicense, and/or sell copies of the Software, and to",
"must not be None. The load balancer will be automatically",
"strings :param subnets: The name of the subnet(s) to detach.",
"region to connect to. :rtype: :class:`boto.ec2.ELBConnection` or ``None`` :return: A",
"listeners load_balancer.availability_zones = zones load_balancer.subnets = subnets load_balancer.security_groups = security_groups",
"instances, 'Instances.member.%d.InstanceId') return self.get_list('RegisterInstancesWithLoadBalancer', params, [('member', InstanceInfo)]) def deregister_instances(self, load_balancer_name,",
"A cookie is inserted into the response for binding subsequent",
"string :param value: The new value for the attribute :rtype:",
"[('member', InstanceInfo)]) def deregister_instances(self, load_balancer_name, instances): \"\"\" Remove Instances from",
"object populated with the desired values. :rtype: :class:`boto.ec2.elb.healthcheck.HealthCheck` :return: The",
"for your account. By default the load balancer will be",
"return self.get_status('CreateLBCookieStickinessPolicy', params) def create_lb_policy(self, lb_name, policy_name, policy_type, policy_attributes): \"\"\"",
":return: A list of :class:`boto.RegionInfo` instances \"\"\" return get_regions('elasticloadbalancing', connection_cls=ELBConnection)",
"given \"\"\" for region in regions(): if region.name == region_name:",
"of a LoadBalancer. By default, Elastic Load Balancing creates an",
"parameter zones must be set to None and subnets must",
"Balancer :type zones: List of strings :param zones: The name",
"Balancer. \"\"\" params = {'LoadBalancerName': name} self.build_list_params(params, security_groups, 'SecurityGroups.member.%d') return",
"name: The name of the load balancer to create the",
"of the EC2 instances to add. :rtype: List of strings",
"string :param load_balancer_name: The name of the Load Balancer :type",
"This will make an EC2 call for each method call.",
"are integer values between 1 and 65535, Protocol is a",
"option is only available for LoadBalancers attached to an Amazon",
"type of a LoadBalancer. By default, Elastic Load Balancing creates",
"configure_health_check(self, name, health_check): \"\"\" Define a health check for the",
"# \"\"\" This module provides an interface to the Elastic",
"which resolves to public IP addresses. Specify the value internal",
":param attribute: The attribute you wish to change. * crossZoneLoadBalancing",
"\"\"\" Generates a stickiness policy with sticky session lifetimes controlled",
"list of :class:`boto.RegionInfo` instances \"\"\" return get_regions('elasticloadbalancing', connection_cls=ELBConnection) def connect_to_region(region_name,",
"list of strings :param subnets: A list of subnet IDs",
"Load Balancer. Removing zones that are not registered with the",
"settings that are saved for your load balancer and that",
"\"\"\" Creates a new policy that contais the necessary attributes",
"call. :type load_balancer_name: string :param load_balancer_name: The name of the",
"value: value = 'true' else: value = 'false' params =",
"attribute: The attribute you wish to see. * accessLog -",
"of the Software. # # THE SOFTWARE IS PROVIDED \"AS",
"This policy is similar to the policy created by CreateLBCookieStickinessPolicy,",
"limitation the rights to use, copy, modify, merge, publish, dis-",
"List of tuples :param complex_listeners: Each tuple contains four or",
"subnet(s) to add. :rtype: List of strings :return: An updated",
"an internet-facing LoadBalancer with a publicly resolvable DNS name, which",
"HTTP', or 'HTTPS'; SSLCertificateID is the ARN of a AWS",
"an existing Load Balancer :type name: string :param name: The",
"policy can be associated with a listener. \"\"\" params =",
"listening with a new set of policies. \"\"\" params =",
"return attributes.connection_draining return None def register_instances(self, load_balancer_name, instances): \"\"\" Add",
"the lifetime of the browser (user-agent) or a specified expiration",
"LoadBalancer with a DNS name that resolves to private IP",
"name of the Load Balancer :rtype: boto.ec2.elb.attribute.LbAttributes :return: The attribute",
"the security group(s) to add. :rtype: List of strings :return:",
"OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE",
"files (the # \"Software\"), to deal in the Software without",
"has no effect. You cannot remove all zones from an",
"\"\"\" params = {'LoadBalancerName': lb_name, 'PolicyName': policy_name} if cookie_expiration_period is",
"associated with the load balancer :type health_check: :class:`boto.ec2.elb.healthcheck.HealthCheck` :param health_check:",
"this Load Balancer. \"\"\" params = {'LoadBalancerName': load_balancer_name} self.build_list_params(params, zones_to_remove,",
"(LoadBalancerPortNumber, InstancePortNumber, Protocol, InstanceProtocol, SSLCertificateId). Where: - LoadBalancerPortNumber and InstancePortNumber",
"The validity of the cookie is based on the cookie",
"the Software, and to permit # persons to whom the",
"name} # Handle the simple listeners if listeners: for index,",
"that can be applied to the front-end listener, or the",
"policy_name): \"\"\" Generates a stickiness policy with sticky session lifetimes",
"which the back-end server is listening with a new set",
"\"\"\" Sets the certificate that terminates the specified listener's SSL",
"security_token, validate_certs=validate_certs, profile_name=profile_name) def _required_auth_capability(self): return ['ec2'] def build_list_params(self, params,",
"an existing Load Balancer All zones must be in the",
"name, ports): \"\"\" Deletes a load balancer listener (or group",
"AWS IAM :rtype: :class:`boto.ec2.elb.loadbalancer.LoadBalancer` :return: The newly created :class:`boto.ec2.elb.loadbalancer.LoadBalancer` \"\"\"",
"lb_port, ssl_certificate_id): \"\"\" Sets the certificate that terminates the specified",
"set_lb_policies_of_listener(self, lb_name, lb_port, policies): \"\"\" Associates, updates, or disables a",
":rtype: List of strings :return: An updated list of subnets",
"automatically created under the VPC that contains the subnet(s) specified.",
"'Instances.member.%d.InstanceId') return self.get_list('RegisterInstancesWithLoadBalancer', params, [('member', InstanceInfo)]) def deregister_instances(self, load_balancer_name, instances):",
"above copyright notice and this permission notice shall be included",
"of zones for this Load Balancer. \"\"\" params = {'LoadBalancerName':",
"None class ELBConnection(AWSQueryConnection): APIVersion = boto.config.get('Boto', 'elb_version', '2012-06-01') DefaultRegionName =",
"- :py:class:`AccessLogAttribute` instance * crossZoneLoadBalancing - Boolean * connectionDraining -",
"zones that are already registered with the Load Balancer has",
"applied to the front-end listener, or the back-end application server.",
"that server. The validity of the cookie is based on",
"integer values between 1 and 65535, Protocol is a string",
"value.enabled and 'true' or 'false' params['LoadBalancerAttributes.AccessLog.S3BucketName'] = \\ value.s3_bucket_name params['LoadBalancerAttributes.AccessLog.S3BucketPrefix']",
"with sticky session lifetimes that follow that of an application-generated",
"listeners: Each tuple contains three or four values, (LoadBalancerPortNumber, InstancePortNumber,",
"[SSLCertificateId]) where LoadBalancerPortNumber and InstancePortNumber are integer values between 1",
"change. * crossZoneLoadBalancing - Boolean (true) * accessLog - :py:class:`AccessLogAttribute`",
"params) def create_lb_cookie_stickiness_policy(self, cookie_expiration_period, lb_name, policy_name): \"\"\" Generates a stickiness",
"Associates, updates, or disables a policy with a listener on",
"Protocol and InstanceProtocol is a string containing either 'TCP', 'SSL',",
"self.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') return self.get_list('DescribeLoadBalancers', params, [('member', LoadBalancer)]) def create_load_balancer(self,",
"of strings :return: An updated list of zones for this",
"subnets that are already registered with the Load Balancer has",
"with sticky session lifetimes controlled by the lifetime of the",
"self.get_status('DeleteLoadBalancerPolicy', params) def set_lb_policies_of_listener(self, lb_name, lb_port, policies): \"\"\" Associates, updates,",
"THE USE OR OTHER DEALINGS # IN THE SOFTWARE. #",
"lowing conditions: # # The above copyright notice and this",
"security_groups: list of strings :param security_groups: The security groups assigned",
"zones: self.build_list_params(params, zones, 'AvailabilityZones.member.%d') if subnets: self.build_list_params(params, subnets, 'Subnets.member.%d') if",
"- Boolean * connectionDraining - :py:class:`ConnectionDrainingAttribute` instance :rtype: Attribute dependent",
"is listening with a new set of policies. \"\"\" params",
":param ports: Each int represents the port on the ELB",
"= load_regions().get('elasticloadbalancing', {}) def regions(): \"\"\" Get all available regions",
"% index] = name params['PolicyAttributes.member.%d.AttributeValue' % index] = value else:",
"it first checks to see if this cookie is present",
"the listeners for :type listeners: List of tuples :param listeners:",
"registered with the Load Balancer has no effect. :type load_balancer_name:",
"ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT",
"* connectionDraining - :py:class:`ConnectionDrainingAttribute` instance :type value: string :param value:",
"VPC that contains the subnet(s) specified. :type name: string :param",
"name, lb_name, policy_name): \"\"\" Generates a stickiness policy with sticky",
"note:: The region argument is overridden by the region specified",
"your load balancer and that can be applied to the",
"overridden by the region specified in the boto configuration file.",
"of the request \"\"\" params = {'LoadBalancerName': name} for index,",
"no effect. :type load_balancer_name: string :param load_balancer_name: The name of",
"load_balancer_name, instances=None): \"\"\" Get current state of all Instances registered",
"not provided, the state of all instances will be returned.",
"params, None) def detach_lb_from_subnets(self, name, subnets): \"\"\" Detaches load balancer",
"the Load Balancer :type security_groups: List of strings :param security_groups:",
"security_groups return load_balancer def create_load_balancer_listeners(self, name, listeners=None, complex_listeners=None): \"\"\" Creates",
"i] = listener[3] if protocol == 'HTTPS' or protocol ==",
"ResultSet containing instances of :class:`boto.ec2.elb.loadbalancer.LoadBalancer` \"\"\" params = {} if",
"'2012-06-01') DefaultRegionName = boto.config.get('Boto', 'elb_region_name', 'us-east-1') DefaultRegionEndpoint = boto.config.get('Boto', 'elb_region_endpoint',",
"# Copyright (c) 2012 Amazon.com, Inc. or its affiliates. #",
"an SSL certificate loaded into AWS IAM :rtype: :class:`boto.ec2.elb.loadbalancer.LoadBalancer` :return:",
"of the Load Balancer :type security_groups: List of strings :param",
"i] = listener[4] return self.get_status('CreateLoadBalancerListeners', params) def delete_load_balancer(self, name): \"\"\"",
"self.build_list_params(params, policies, 'PolicyNames.member.%d') else: params['PolicyNames'] = '' return self.get_status('SetLoadBalancerPoliciesForBackendServer', params)",
":return: An updated list of instances for this Load Balancer.",
"restriction, including # without limitation the rights to use, copy,",
"application cookie is issued. \"\"\" params = {'CookieName': name, 'LoadBalancerName':",
"+ 1 protocol = listener[2].upper() InstanceProtocol = listener[3].upper() params['Listeners.member.%d.LoadBalancerPort' %",
"balancer listener (or group of listeners) :type name: string :param",
"index, port in enumerate(ports): params['LoadBalancerPorts.member.%d' % (index + 1)] =",
"strings :return: An updated list of security groups for this",
"from boto.ec2.elb.instancestate import InstanceState from boto.ec2.elb.healthcheck import HealthCheck from boto.ec2.elb.listelement",
"is a string containing either 'TCP', 'SSL', HTTP', or 'HTTPS';",
"to that server. The validity of the cookie is based",
"proxy_user=None, proxy_pass=None, debug=0, https_connection_factory=None, region=None, path='/', security_token=None, validate_certs=True, profile_name=None): \"\"\"",
"name: The mnemonic name associated with the load balancer :type",
"To create a load balancer inside a VPC, parameter zones",
"the special Elastic Load Balancing cookie follows the lifetime of",
"\\ value.enabled and 'true' or 'false' params['LoadBalancerAttributes.ConnectionDraining.Timeout'] = \\ value.timeout",
"def set_lb_listener_SSL_certificate(self, lb_name, lb_port, ssl_certificate_id): \"\"\" Sets the certificate that",
"1 protocol = listener[2].upper() InstanceProtocol = listener[3].upper() params['Listeners.member.%d.LoadBalancerPort' % i]",
"the back-end application server. \"\"\" params = {'LoadBalancerName': lb_name, 'PolicyName':",
"a server that is chosen based on the existing load",
"connection to EC2 Load Balancing Service. .. note:: The region",
"values, (LoadBalancerPortNumber, InstancePortNumber, Protocol, [SSLCertificateId]) where LoadBalancerPortNumber and InstancePortNumber are",
"instance ID's of the EC2 instances to return status for.",
"strings :param zones: The names of the availability zone(s) to",
"within your VPC. :type scheme: string :param scheme: The type",
"new value for the attribute :rtype: bool :return: Whether the",
"method to create a new connection to EC2 Load Balancing",
"policy configuration. None may be passed for cookie_expiration_period. \"\"\" params",
"this policy, the load balancer uses a special cookie to",
"Load Balancer :type security_groups: List of strings :param security_groups: The",
"to attach to your LoadBalancer. :type security_groups: list of strings",
"to use, copy, modify, merge, publish, dis- # tribute, sublicense,",
"listeners: List of tuples :param listeners: Each tuple contains three",
"params = {'LoadBalancerName': load_balancer_name} self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return self.get_list('RegisterInstancesWithLoadBalancer', params,",
"a load balancer listener (or group of listeners) :type name:",
"== 'SSL': params['Listeners.member.%d.SSLCertificateId' % i] = listener[4] if zones: self.build_list_params(params,",
"if security_groups: self.build_list_params(params, security_groups, 'SecurityGroups.member.%d') load_balancer = self.get_object('CreateLoadBalancer', params, LoadBalancer)",
"self.get_status('CreateLBCookieStickinessPolicy', params) def create_lb_policy(self, lb_name, policy_name, policy_type, policy_attributes): \"\"\" Creates",
"security group(s) to add. :rtype: List of strings :return: An",
"not listeners and not complex_listeners: # Must specify one of",
":rtype: List of :class:`boto.ec2.elb.instancestate.InstanceState` :return: list of state info for",
"name of the Load Balancer :type security_groups: List of strings",
"index + 1 protocol = listener[2].upper() InstanceProtocol = listener[3].upper() params['Listeners.member.%d.LoadBalancerPort'",
"option to create an internal LoadBalancer with a DNS name",
"a Load Balancer This will make an EC2 call for",
"to see. * accessLog - :py:class:`AccessLogAttribute` instance * crossZoneLoadBalancing -",
"return self.get_list('DescribeInstanceHealth', params, [('member', InstanceState)]) def configure_health_check(self, name, health_check): \"\"\"",
"params) def apply_security_groups_to_lb(self, name, security_groups): \"\"\" Applies security groups to",
"InstancePortNumber, Protocol, [SSLCertificateId]) where LoadBalancerPortNumber and InstancePortNumber are integer values",
":class:`boto.ec2.elb.healthcheck.HealthCheck` \"\"\" params = {'LoadBalancerName': name, 'HealthCheck.Timeout': health_check.timeout, 'HealthCheck.Target': health_check.target,",
"(1) policy can be associated with a listener. \"\"\" params",
"value elif attribute.lower() == 'accesslog': params['LoadBalancerAttributes.AccessLog.Enabled'] = \\ value.enabled and",
"associated with the new load balancer :type zones: List of",
"lifetime of the special Elastic Load Balancing cookie follows the",
"The name of the Load Balancer :type attribute: string :param",
"attribute: string :param attribute: The attribute you wish to see.",
":return: Whether the operation succeeded or not \"\"\" bool_reqs =",
"the same region as the Load Balancer Adding zones that",
"self.get_object('CreateLoadBalancer', params, LoadBalancer) load_balancer.name = name load_balancer.listeners = listeners load_balancer.availability_zones",
"EndPoints. :type name: string :param name: The mnemonic name associated",
"OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT",
"load balancer to create the listeners for :type ports: List",
"index, listener in enumerate(complex_listeners): i = index + 1 protocol",
"explicitly removed or expires, the session stops being sticky until",
"tuples :param complex_listeners: Each tuple contains four or five values,",
"cookie is based on the cookie expiration time, which is",
"List of strings :param security_groups: The name of the security",
":param security_groups: The name of the security group(s) to add.",
"stickiness policy with sticky session lifetimes that follow that of",
"a new application cookie is issued. \"\"\" params = {'CookieName':",
"Load Balancer :rtype: boto.ec2.elb.attribute.LbAttributes :return: The attribute object of the",
"policy_name): \"\"\" Deletes a policy from the LoadBalancer. The specified",
"= self.get_object('DisableAvailabilityZonesForLoadBalancer', params, LoadBalancerZones) return obj.zones def modify_lb_attribute(self, load_balancer_name, attribute,",
"the EC2 instances to return status for. If not provided,",
"permit # persons to whom the Software is furnished to",
"LoadBalancerZones from boto.ec2.elb.instancestate import InstanceState from boto.ec2.elb.healthcheck import HealthCheck from",
"load_balancer_name} self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return self.get_list('DeregisterInstancesFromLoadBalancer', params, [('member', InstanceInfo)]) def",
"of :class:`boto.ec2.elb.instancestate.InstanceState` :return: list of state info for instances in",
"if an invalid region name is given \"\"\" for region",
"OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND",
"list of load balancer names. :rtype: :py:class:`boto.resultset.ResultSet` :return: A ResultSet",
"the application-generated cookie specified in the policy configuration. The load",
"specified in the policy configuration. The load balancer only inserts",
"period. This policy can only be associated only with HTTP",
"boto.regioninfo import RegionInfo, get_regions, load_regions import boto RegionData = load_regions().get('elasticloadbalancing',",
"'' return self.get_status('SetLoadBalancerPoliciesForBackendServer', params) def apply_security_groups_to_lb(self, name, security_groups): \"\"\" Applies",
"request. If so, the load balancer sends the request to",
"def create_app_cookie_stickiness_policy(self, name, lb_name, policy_name): \"\"\" Generates a stickiness policy",
"is furnished to do so, subject to the fol- #",
"self.get_status('SetLoadBalancerPoliciesOfListener', params) def set_lb_policies_of_backend_server(self, lb_name, instance_port, policies): \"\"\" Replaces the",
"boto.config.get('Boto', 'elb_region_endpoint', 'elasticloadbalancing.us-east-1.amazonaws.com') def __init__(self, aws_access_key_id=None, aws_secret_access_key=None, is_secure=True, port=None, proxy=None,",
"of the Load Balancer :type attribute: string :param attribute: The",
"that the lifetime of the special Elastic Load Balancing cookie",
"scheme} # Handle legacy listeners if listeners: for index, listener",
"WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT",
"updated list of subnets for this Load Balancer. \"\"\" params",
"list of zones for this Load Balancer. \"\"\" params =",
"updated :class:`boto.ec2.elb.healthcheck.HealthCheck` \"\"\" params = {'LoadBalancerName': name, 'HealthCheck.Timeout': health_check.timeout, 'HealthCheck.Target':",
"method call. :type load_balancer_name: string :param load_balancer_name: The name of",
"get_all_load_balancers(self, load_balancer_names=None): \"\"\" Retrieve all load balancers associated with your",
":param name: The mnemonic name associated with the load balancer",
"connection to the given region, or None if an invalid",
":type scheme: string :param scheme: The type of a LoadBalancer.",
"from your account. :type name: string :param name: The name",
"= {'LoadBalancerName': name} for index, port in enumerate(ports): params['LoadBalancerPorts.member.%d' %",
"An updated list of instances for this Load Balancer. \"\"\"",
"\"\"\" Retrieve all load balancers associated with your account. :type",
"free of charge, to any person obtaining a # copy",
"the load balancer to create the listeners for :type ports:",
"detach. :rtype: List of strings :return: An updated list of",
"# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,",
"def apply_security_groups_to_lb(self, name, security_groups): \"\"\" Applies security groups to the",
"the browser (user-agent) or a specified expiration period. This policy",
"NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY",
"\"\"\" params = {'LoadBalancerName': name} self.build_list_params(params, security_groups, 'SecurityGroups.member.%d') return self.get_list('ApplySecurityGroupsToLoadBalancer',",
"your LoadBalancer within your VPC. :type scheme: string :param scheme:",
"of the zone(s) to remove. :rtype: List of strings :return:",
"List of strings :return: An updated list of subnets for",
"Load Balancer has no effect. You cannot remove all zones",
"used on the same LoadBalancer and port. \"\"\" params =",
"Remove availability zones from an existing Load Balancer. All zones",
"instances to return status for. If not provided, the state",
"def get_lb_attribute(self, load_balancer_name, attribute): \"\"\"Gets an attribute of a Load",
"the LoadBalancer. The specified policy must not be enabled for",
"# # The above copyright notice and this permission notice",
"Boolean (true) * accessLog - :py:class:`AccessLogAttribute` instance * connectionDraining -",
"strings :return: An updated list of instances for this Load",
"== 'connectiondraining': return attributes.connection_draining return None def register_instances(self, load_balancer_name, instances):",
"\"\"\" params = {'LoadBalancerName': lb_name, 'PolicyName': policy_name} return self.get_status('DeleteLoadBalancerPolicy', params)",
"Listener (or group of listeners) for an existing Load Balancer",
"new connection to EC2 Load Balancing Service. .. note:: The",
"the attribute :rtype: bool :return: Whether the operation succeeded or",
"params = {'LoadBalancerName': name} return self.get_status('DeleteLoadBalancer', params) def delete_load_balancer_listeners(self, name,",
"default the load balancer will be created in EC2. To",
"Balancer :type attribute: string :param attribute: The attribute you wish",
"attributes.access_log if attribute.lower() == 'crosszoneloadbalancing': return attributes.cross_zone_load_balancing.enabled if attribute.lower() ==",
"return load_balancer def create_load_balancer_listeners(self, name, listeners=None, complex_listeners=None): \"\"\" Creates a",
"self.region = region super(ELBConnection, self).__init__(aws_access_key_id, aws_secret_access_key, is_secure, port, proxy, proxy_port,",
"\"\"\" params = {'LoadBalancerName': name} self.build_list_params(params, subnets, 'Subnets.member.%d') return self.get_list('AttachLoadBalancerToSubnets',",
"server is listening with a new set of policies. \"\"\"",
"load_balancer_name, instances): \"\"\" Add new Instances to an existing Load",
"from boto.regioninfo import RegionInfo, get_regions, load_regions import boto RegionData =",
"the ELB service. :rtype: list :return: A list of :class:`boto.RegionInfo`",
"service from AWS. \"\"\" from boto.connection import AWSQueryConnection from boto.ec2.instanceinfo",
"of strings :param instances: The instance ID's of the EC2",
"Rights Reserved # # Permission is hereby granted, free of",
"resolves to public IP addresses. Specify the value internal for",
"name of the Load Balancer :type zones: List of strings",
"balancer to one or more subnets. Attaching subnets that are",
"name, zones, listeners=None, subnets=None, security_groups=None, scheme='internet-facing', complex_listeners=None): \"\"\" Create a",
"balancing algorithm. A cookie is inserted into the response for",
"aws_access_key_id=None, aws_secret_access_key=None, is_secure=True, port=None, proxy=None, proxy_port=None, proxy_user=None, proxy_pass=None, debug=0, https_connection_factory=None,",
"zones, 'AvailabilityZones.member.%d') if subnets: self.build_list_params(params, subnets, 'Subnets.member.%d') if security_groups: self.build_list_params(params,",
"return None params = {'LoadBalancerName': name, 'Scheme': scheme} # Handle",
"= {'LoadBalancerName': lb_name, 'LoadBalancerPort': lb_port} if len(policies): self.build_list_params(params, policies, 'PolicyNames.member.%d')",
":type ports: List int :param ports: Each int represents the",
"self).__init__(aws_access_key_id, aws_secret_access_key, is_secure, port, proxy, proxy_port, proxy_user, proxy_pass, self.region.endpoint, debug,",
"to create the listeners for :type ports: List int :param",
"list of instances for this Load Balancer. \"\"\" params =",
"state info for instances in this Load Balancer. \"\"\" params",
":rtype: list :return: A list of :class:`boto.RegionInfo` instances \"\"\" return",
"will be returned. :rtype: List of :class:`boto.ec2.elb.instancestate.InstanceState` :return: list of",
"else: value = 'false' params = {'LoadBalancerName': load_balancer_name} if attribute.lower()",
"issued. \"\"\" params = {'CookieName': name, 'LoadBalancerName': lb_name, 'PolicyName': policy_name}",
":rtype: :class:`boto.ec2.elb.loadbalancer.LoadBalancer` :return: The newly created :class:`boto.ec2.elb.loadbalancer.LoadBalancer` \"\"\" if not",
"health_check.healthy_threshold} return self.get_object('ConfigureHealthCheck', params, HealthCheck) def set_lb_listener_SSL_certificate(self, lb_name, lb_port, ssl_certificate_id):",
"SSL certificate loaded into AWS IAM :return: The status of",
"\"\"\" return get_regions('elasticloadbalancing', connection_cls=ELBConnection) def connect_to_region(region_name, **kw_params): \"\"\" Given a",
"complex_listeners: Each tuple contains four or five values, (LoadBalancerPortNumber, InstancePortNumber,",
"the Load Balancer :type instances: List of strings :param instances:",
"boto.ec2.elb.attributes import LbAttributes params = {'LoadBalancerName': load_balancer_name} return self.get_object('DescribeLoadBalancerAttributes', params,",
"Balancing cookie follows the lifetime of the application-generated cookie specified",
"zones, listeners=None, subnets=None, security_groups=None, scheme='internet-facing', complex_listeners=None): \"\"\" Create a new",
"first checks to see if this cookie is present in",
"path, security_token, validate_certs=validate_certs, profile_name=profile_name) def _required_auth_capability(self): return ['ec2'] def build_list_params(self,",
"Load Balancer. All zones must be in the same region",
"{'LoadBalancerName': lb_name, 'LoadBalancerPort': lb_port, 'SSLCertificateId': ssl_certificate_id} return self.get_status('SetLoadBalancerListenerSSLCertificate', params) def",
"(user-agent) or a specified expiration period. This policy can only",
"List of tuples :param listeners: Each tuple contains three or",
"# lowing conditions: # # The above copyright notice and",
"Sets the certificate that terminates the specified listener's SSL connections.",
"params, [('member', InstanceInfo)]) def deregister_instances(self, load_balancer_name, instances): \"\"\" Remove Instances",
"copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell",
"that are not registered with the Load Balancer has no",
"LoadBalancer within your VPC. :type scheme: string :param scheme: The",
"region, or None if an invalid region name is given",
"params) def delete_load_balancer_listeners(self, name, ports): \"\"\" Deletes a load balancer",
"def disable_availability_zones(self, load_balancer_name, zones_to_remove): \"\"\" Remove availability zones from an",
"Balancer has no effect. You cannot remove all zones from",
"of an SSL certificate loaded into AWS IAM :rtype: :class:`boto.ec2.elb.loadbalancer.LoadBalancer`",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL",
"Given a valid region name, return a :class:`boto.ec2.elb.ELBConnection`. :param str",
"for each method call. :type load_balancer_name: string :param load_balancer_name: The",
"region argument is overridden by the region specified in the",
"including # without limitation the rights to use, copy, modify,",
"{'LoadBalancerName': lb_name, 'PolicyName': policy_name} if cookie_expiration_period is not None: params['CookieExpirationPeriod']",
"lb_name, policy_name): \"\"\" Generates a stickiness policy with sticky session",
"created in EC2. To create a load balancer inside a",
"and must be specified when doing HTTPS. :type subnets: list",
"(c) 2006-2012 <NAME> http://garnaat.org/ # Copyright (c) 2012 Amazon.com, Inc.",
"the application cookie is explicitly removed or expires, the session",
"attach_lb_to_subnets(self, name, subnets): \"\"\" Attaches load balancer to one or",
"policy from the LoadBalancer. The specified policy must not be",
"Balancer. \"\"\" params = {'LoadBalancerName': name} self.build_list_params(params, subnets, 'Subnets.member.%d') return",
"item in enumerate(items): params[label % (index + 1)] = item",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT #",
"from the LoadBalancer. The specified policy must not be enabled",
"a valid region name, return a :class:`boto.ec2.elb.ELBConnection`. :param str region_name:",
"= \\ value.enabled and 'true' or 'false' params['LoadBalancerAttributes.ConnectionDraining.Timeout'] = \\",
"into AWS IAM :rtype: :class:`boto.ec2.elb.loadbalancer.LoadBalancer` :return: The newly created :class:`boto.ec2.elb.loadbalancer.LoadBalancer`",
"to the front-end listener, or the back-end application server. \"\"\"",
"load_balancer_name: The name of the Load Balancer :type attribute: string",
"Protocol, [SSLCertificateId]) where LoadBalancerPortNumber and InstancePortNumber are integer values between",
"obj.zones def modify_lb_attribute(self, load_balancer_name, attribute, value): \"\"\"Changes an attribute of",
"legacy listeners if listeners: for index, listener in enumerate(listeners): i",
"port on the ELB to be removed :return: The status",
"# The above copyright notice and this permission notice shall",
"new load balancer for your account. By default the load",
"def modify_lb_attribute(self, load_balancer_name, attribute, value): \"\"\"Changes an attribute of a",
"the application response includes a new application cookie. If the",
"the cookie expiration time, which is specified in the policy",
"Delete a Load Balancer from your account. :type name: string",
"addresses. This option is only available for LoadBalancers attached to",
"return self.get_status('DeleteLoadBalancer', params) def delete_load_balancer_listeners(self, name, ports): \"\"\" Deletes a",
"load_balancer_name} self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return self.get_list('RegisterInstancesWithLoadBalancer', params, [('member', InstanceInfo)]) def",
"with your account. :type load_balancer_names: list :keyword load_balancer_names: An optional",
"subnets: self.build_list_params(params, subnets, 'Subnets.member.%d') if security_groups: self.build_list_params(params, security_groups, 'SecurityGroups.member.%d') load_balancer",
"AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE",
"instance :type value: string :param value: The new value for",
"obj = self.get_object('DisableAvailabilityZonesForLoadBalancer', params, LoadBalancerZones) return obj.zones def modify_lb_attribute(self, load_balancer_name,",
"new load balancer :type zones: List of strings :param zones:",
"the operation succeeded or not \"\"\" bool_reqs = ('crosszoneloadbalancing',) if",
"debug, https_connection_factory, path, security_token, validate_certs=validate_certs, profile_name=profile_name) def _required_auth_capability(self): return ['ec2']",
"return self.get_status('ModifyLoadBalancerAttributes', params, verb='GET') def get_all_lb_attributes(self, load_balancer_name): \"\"\"Gets all Attributes",
"def _required_auth_capability(self): return ['ec2'] def build_list_params(self, params, items, label): if",
"IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"listeners) for an existing Load Balancer :type name: string :param",
"VPC, parameter zones must be set to None and subnets",
"(name, value) in enumerate(policy_attributes.iteritems(), 1): params['PolicyAttributes.member.%d.AttributeName' % index] = name",
"notice and this permission notice shall be included # in",
"strings :param security_groups: The name of the security group(s) to",
"Applies security groups to the load balancer. Applying security groups",
"Balancer :rtype: boto.ec2.elb.attribute.LbAttributes :return: The attribute object of the ELB.",
"balancer sends the request to a server that is chosen",
"= {'LoadBalancerName': name} self.build_list_params(params, security_groups, 'SecurityGroups.member.%d') return self.get_list('ApplySecurityGroupsToLoadBalancer', params, None)",
"a publicly resolvable DNS name, which resolves to public IP",
"EC2 instances to add. :rtype: List of strings :return: An",
"load balancer from one or more subnets. :type name: string",
"the region to connect to. :rtype: :class:`boto.ec2.ELBConnection` or ``None`` :return:",
"an EC2 call for each method call. :type load_balancer_name: string",
"When a load balancer implements this policy, the load balancer",
"{'LoadBalancerName': lb_name, 'PolicyName': policy_name} return self.get_status('DeleteLoadBalancerPolicy', params) def set_lb_policies_of_listener(self, lb_name,",
"return self.get_status('SetLoadBalancerPoliciesOfListener', params) def set_lb_policies_of_backend_server(self, lb_name, instance_port, policies): \"\"\" Replaces",
"conditions: # # The above copyright notice and this permission",
"for index, listener in enumerate(listeners): i = index + 1",
"zones must be set to None and subnets must not",
"security_groups, 'SecurityGroups.member.%d') return self.get_list('ApplySecurityGroupsToLoadBalancer', params, None) def attach_lb_to_subnets(self, name, subnets):",
"Instances from an existing Load Balancer. :type load_balancer_name: string :param",
"\"\"\" params = {} if load_balancer_names: self.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') return",
"by the lifetime of the browser (user-agent) or a specified",
":type name: string :param name: The mnemonic name associated with",
"security_groups): \"\"\" Applies security groups to the load balancer. Applying",
"params['LoadBalancerAttributes.AccessLog.S3BucketName'] = \\ value.s3_bucket_name params['LoadBalancerAttributes.AccessLog.S3BucketPrefix'] = \\ value.s3_bucket_prefix params['LoadBalancerAttributes.AccessLog.EmitInterval'] =",
"ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED",
"copies of the Software, and to permit # persons to",
"import ListElement from boto.regioninfo import RegionInfo, get_regions, load_regions import boto",
"security_token=None, validate_certs=True, profile_name=None): \"\"\" Init method to create a new",
"if isinstance(items, basestring): items = [items] for index, item in",
"% i] = listener[0] params['Listeners.member.%d.InstancePort' % i] = listener[1] params['Listeners.member.%d.Protocol'",
"application server. \"\"\" params = {'LoadBalancerName': lb_name, 'PolicyName': policy_name, 'PolicyTypeName':",
"the request to a server that is chosen based on",
"return self.get_list('RegisterInstancesWithLoadBalancer', params, [('member', InstanceInfo)]) def deregister_instances(self, load_balancer_name, instances): \"\"\"",
"Balancer :type load_balancer_name: string :param load_balancer_name: The name of the",
"if this cookie is present in the request. If so,",
"health_check: :class:`boto.ec2.elb.healthcheck.HealthCheck` :param health_check: A HealthCheck object populated with the",
"of strings :param subnets: The name of the subnet(s) to",
"1 and 65535 - Protocol and InstanceProtocol is a string",
"to an existing Load Balancer. :type load_balancer_name: string :param load_balancer_name:",
"the certificate that terminates the specified listener's SSL connections. The",
":param name: The name of the load balancer to create",
"params = {'LoadBalancerName': name} for index, port in enumerate(ports): params['LoadBalancerPorts.member.%d'",
":py:class:`AccessLogAttribute` instance * crossZoneLoadBalancing - Boolean * connectionDraining - :py:class:`ConnectionDrainingAttribute`",
"describe_instance_health(self, load_balancer_name, instances=None): \"\"\" Get current state of all Instances",
"name of the zone(s) to remove. :rtype: List of strings",
"name of the subnet(s) to add. :rtype: List of strings",
"a # copy of this software and associated documentation files",
"attribute you wish to see. * accessLog - :py:class:`AccessLogAttribute` instance",
"Handle legacy listeners if listeners: for index, listener in enumerate(listeners):",
"params['Listeners.member.%d.InstancePort' % i] = listener[1] params['Listeners.member.%d.Protocol' % i] = listener[2]",
"and this permission notice shall be included # in all",
"'true' or 'false' params['LoadBalancerAttributes.ConnectionDraining.Timeout'] = \\ value.timeout else: raise ValueError('InvalidAttribute',",
"return self.get_list('DeregisterInstancesFromLoadBalancer', params, [('member', InstanceInfo)]) def describe_instance_health(self, load_balancer_name, instances=None): \"\"\"",
"== 'accesslog': params['LoadBalancerAttributes.AccessLog.Enabled'] = \\ value.enabled and 'true' or 'false'",
"new value for the attribute \"\"\" attributes = self.get_all_lb_attributes(load_balancer_name) if",
"cookie follows the lifetime of the application-generated cookie specified in",
"None def register_instances(self, load_balancer_name, instances): \"\"\" Add new Instances to",
"Applying security groups that are already registered with the Load",
"subnets): \"\"\" Attaches load balancer to one or more subnets.",
"listeners for :type listeners: List of tuples :param listeners: Each",
"associated only with HTTP listeners. When a load balancer implements",
"with a listener. \"\"\" params = {'LoadBalancerName': lb_name, 'LoadBalancerPort': lb_port}",
"controlled by the lifetime of the browser (user-agent) or a",
"https_connection_factory=None, region=None, path='/', security_token=None, validate_certs=True, profile_name=None): \"\"\" Init method to",
":param instances: The instance ID's of the EC2 instances to",
"validate_certs=True, profile_name=None): \"\"\" Init method to create a new connection",
"instances): \"\"\" Remove Instances from an existing Load Balancer. :type",
":type health_check: :class:`boto.ec2.elb.healthcheck.HealthCheck` :param health_check: A HealthCheck object populated with",
"be automatically created under the VPC that contains the subnet(s)",
"def create_load_balancer_listeners(self, name, listeners=None, complex_listeners=None): \"\"\" Creates a Listener (or",
"boto.ec2.elb.attribute.LbAttributes :return: The attribute object of the ELB. \"\"\" from",
"\"\"\" params = {'LoadBalancerName': lb_name, 'LoadBalancerPort': lb_port, 'SSLCertificateId': ssl_certificate_id} return",
"# # Permission is hereby granted, free of charge, to",
":param name: The name of the Load Balancer :type security_groups:",
"or a specified expiration period. This policy can only be",
"all Attributes of a Load Balancer :type load_balancer_name: string :param",
"InstanceProtocol = listener[3].upper() params['Listeners.member.%d.LoadBalancerPort' % i] = listener[0] params['Listeners.member.%d.InstancePort' %",
"'Subnets.member.%d') return self.get_list('AttachLoadBalancerToSubnets', params, None) def detach_lb_from_subnets(self, name, subnets): \"\"\"",
":type security_groups: list of strings :param security_groups: The security groups",
"complex_listeners: # Must specify one of the two options return",
"options return None params = {'LoadBalancerName': name} # Handle the",
"AWS IAM :return: The status of the request \"\"\" if",
"if isinstance(value, bool): if value: value = 'true' else: value",
"Balancer to delete \"\"\" params = {'LoadBalancerName': name} return self.get_status('DeleteLoadBalancer',",
"= name load_balancer.listeners = listeners load_balancer.availability_zones = zones load_balancer.subnets =",
":type value: string :param value: The new value for the",
"Balancer All zones must be in the same region as",
":rtype: List of strings :return: An updated list of instances",
"a policy with a listener on the load balancer. Currently",
"four or five values, (LoadBalancerPortNumber, InstancePortNumber, Protocol, InstanceProtocol, SSLCertificateId). Where:",
"proxy=None, proxy_port=None, proxy_user=None, proxy_pass=None, debug=0, https_connection_factory=None, region=None, path='/', security_token=None, validate_certs=True,",
"isinstance(items, basestring): items = [items] for index, item in enumerate(items):",
"name: The name of the Load Balancer :type subnets: List",
"enumerate(ports): params['LoadBalancerPorts.member.%d' % (index + 1)] = port return self.get_status('DeleteLoadBalancerListeners',",
"inside a VPC, parameter zones must be set to None",
"The specified policy must not be enabled for any listeners.",
"Load Balancer. \"\"\" params = {'LoadBalancerName': load_balancer_name} self.build_list_params(params, zones_to_add, 'AvailabilityZones.member.%d')",
"special Elastic Load Balancing cookie follows the lifetime of the",
"ARN of an SSL certificate loaded into AWS IAM :rtype:",
"a AWS IAM certificate, and must be specified when doing",
"succeeded or not \"\"\" bool_reqs = ('crosszoneloadbalancing',) if attribute.lower() in",
"instances of :class:`boto.ec2.elb.loadbalancer.LoadBalancer` \"\"\" params = {} if load_balancer_names: self.build_list_params(params,",
"If so, the load balancer sends the request to the",
"params) def create_lb_policy(self, lb_name, policy_name, policy_type, policy_attributes): \"\"\" Creates a",
"be None. The load balancer will be automatically created under",
"of the EC2 instances to return status for. If not",
"receives a request, it first checks to see if this",
"\"\"\" params = {'LoadBalancerName': lb_name, 'PolicyName': policy_name, 'PolicyTypeName': policy_type} for",
"self.build_list_params(params, subnets, 'Subnets.member.%d') if security_groups: self.build_list_params(params, security_groups, 'SecurityGroups.member.%d') load_balancer =",
"SSLCertificateId is the ARN of an SSL certificate loaded into",
"same LoadBalancer and port. \"\"\" params = {'LoadBalancerName': lb_name, 'LoadBalancerPort':",
"value for the attribute :rtype: bool :return: Whether the operation",
"\"\"\" attributes = self.get_all_lb_attributes(load_balancer_name) if attribute.lower() == 'accesslog': return attributes.access_log",
"params['Listeners.member.%d.SSLCertificateId' % i] = listener[4] return self.get_status('CreateLoadBalancerListeners', params) def delete_load_balancer(self,",
"to remove. :rtype: List of strings :return: An updated list",
"listener's SSL connections. The specified certificate replaces any prior certificate",
"IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER",
"\"\"\" Delete a Load Balancer from your account. :type name:",
"instances: List of strings :param instances: The instance ID's of",
"Load Balancer. \"\"\" params = {'LoadBalancerName': load_balancer_name} if instances: self.build_list_params(params,",
"to see if this cookie is present in the request.",
"binding subsequent requests from the same user to that server.",
"subnets): \"\"\" Detaches load balancer from one or more subnets.",
"Reserved # # Permission is hereby granted, free of charge,",
"in the boto configuration file. \"\"\" if not region: region",
"user to that server. The validity of the cookie is",
"'HealthCheck.UnhealthyThreshold': health_check.unhealthy_threshold, 'HealthCheck.HealthyThreshold': health_check.healthy_threshold} return self.get_object('ConfigureHealthCheck', params, HealthCheck) def set_lb_listener_SSL_certificate(self,",
"Balancer :type name: string :param name: The name of the",
"WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE",
"def build_list_params(self, params, items, label): if isinstance(items, basestring): items =",
"boto.config.get('Boto', 'elb_version', '2012-06-01') DefaultRegionName = boto.config.get('Boto', 'elb_region_name', 'us-east-1') DefaultRegionEndpoint =",
"IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR",
"boto.config.get('Boto', 'elb_region_name', 'us-east-1') DefaultRegionEndpoint = boto.config.get('Boto', 'elb_region_endpoint', 'elasticloadbalancing.us-east-1.amazonaws.com') def __init__(self,",
"for the attribute :rtype: bool :return: Whether the operation succeeded",
"(LoadBalancerPortNumber, InstancePortNumber, Protocol, [SSLCertificateId]) where LoadBalancerPortNumber and InstancePortNumber are integer",
"name): \"\"\" Delete a Load Balancer from your account. :type",
"of :class:`boto.ec2.elb.loadbalancer.LoadBalancer` \"\"\" params = {} if load_balancer_names: self.build_list_params(params, load_balancer_names,",
":class:`boto.ec2.elb.loadbalancer.LoadBalancer` :return: The newly created :class:`boto.ec2.elb.loadbalancer.LoadBalancer` \"\"\" if not listeners",
"load balancer. Currently only zero (0) or one (1) policy",
"between 1 and 65535, Protocol is a string containing either",
"lifetime of the browser (user-agent) or a specified expiration period.",
"self.get_object('DescribeLoadBalancerAttributes', params, LbAttributes) def get_lb_attribute(self, load_balancer_name, attribute): \"\"\"Gets an attribute",
"two options return None params = {'LoadBalancerName': name} # Handle",
"create a new connection to EC2 Load Balancing Service. ..",
"- :py:class:`ConnectionDrainingAttribute` instance :type value: string :param value: The new",
"if value: value = 'true' else: value = 'false' params",
"a Listener (or group of listeners) for an existing Load",
"= listener[2].upper() params['Listeners.member.%d.LoadBalancerPort' % i] = listener[0] params['Listeners.member.%d.InstancePort' % i]",
":param name: The name of the Load Balancer to delete",
"params = {'LoadBalancerName': load_balancer_name} if attribute.lower() == 'crosszoneloadbalancing': params['LoadBalancerAttributes.CrossZoneLoadBalancing.Enabled' ]",
"the load balancer sends the request to the application server",
"params, [('member', LoadBalancer)]) def create_load_balancer(self, name, zones, listeners=None, subnets=None, security_groups=None,",
"from an Load Balancer. :type load_balancer_name: string :param load_balancer_name: The",
"browser (user-agent) or a specified expiration period. This policy can",
"for the ELB service. :rtype: list :return: A list of",
"specified. :type name: string :param name: The mnemonic name associated",
"security_groups: self.build_list_params(params, security_groups, 'SecurityGroups.member.%d') load_balancer = self.get_object('CreateLoadBalancer', params, LoadBalancer) load_balancer.name",
"load_balancer_name: The name of the Load Balancer :type zones: List",
"is explicitly removed or expires, the session stops being sticky",
"the cookie. If not, the load balancer sends the request",
"\"\"\" from boto.connection import AWSQueryConnection from boto.ec2.instanceinfo import InstanceInfo from",
"for the attribute \"\"\" attributes = self.get_all_lb_attributes(load_balancer_name) if attribute.lower() ==",
"== 'HTTPS' or protocol == 'SSL': params['Listeners.member.%d.SSLCertificateId' % i] =",
"a stickiness policy with sticky session lifetimes controlled by the",
"a stickiness policy with sticky session lifetimes that follow that",
"create_app_cookie_stickiness_policy(self, name, lb_name, policy_name): \"\"\" Generates a stickiness policy with",
"new application cookie. If the application cookie is explicitly removed",
"remove all zones from an Load Balancer. :type load_balancer_name: string",
"(0) or one (1) policy can be associated with a",
"the load balancer receives a request, it first checks to",
"label): if isinstance(items, basestring): items = [items] for index, item",
"'HealthCheck.Target': health_check.target, 'HealthCheck.Interval': health_check.interval, 'HealthCheck.UnhealthyThreshold': health_check.unhealthy_threshold, 'HealthCheck.HealthyThreshold': health_check.healthy_threshold} return self.get_object('ConfigureHealthCheck',",
"listener in enumerate(listeners): i = index + 1 protocol =",
"prior certificate that was used on the same LoadBalancer and",
"balancer sends the request to the application server specified in",
"can be associated with a listener. \"\"\" params = {'LoadBalancerName':",
"cookie. This policy can only be associated with HTTP listeners.",
"params['CookieExpirationPeriod'] = cookie_expiration_period return self.get_status('CreateLBCookieStickinessPolicy', params) def create_lb_policy(self, lb_name, policy_name,",
"to add. :type listeners: List of tuples :param listeners: Each",
"similar to the policy created by CreateLBCookieStickinessPolicy, except that the",
"list of state info for instances in this Load Balancer.",
"values. :rtype: :class:`boto.ec2.elb.healthcheck.HealthCheck` :return: The updated :class:`boto.ec2.elb.healthcheck.HealthCheck` \"\"\" params =",
"DefaultRegionName = boto.config.get('Boto', 'elb_region_name', 'us-east-1') DefaultRegionEndpoint = boto.config.get('Boto', 'elb_region_endpoint', 'elasticloadbalancing.us-east-1.amazonaws.com')",
"The status of the request \"\"\" params = {'LoadBalancerName': name}",
"load_balancer.listeners = listeners load_balancer.availability_zones = zones load_balancer.subnets = subnets load_balancer.security_groups",
"for index, (name, value) in enumerate(policy_attributes.iteritems(), 1): params['PolicyAttributes.member.%d.AttributeName' % index]",
"a load balancer implements this policy, the load balancer uses",
"attach to your LoadBalancer. :type security_groups: list of strings :param",
"'LoadBalancerName': lb_name, 'PolicyName': policy_name} return self.get_status('CreateAppCookieStickinessPolicy', params) def create_lb_cookie_stickiness_policy(self, cookie_expiration_period,",
"copyright notice and this permission notice shall be included #",
"\"\"\" Create a new load balancer for your account. By",
"load_balancer.name = name load_balancer.listeners = listeners load_balancer.availability_zones = zones load_balancer.subnets",
"[('member', InstanceInfo)]) def describe_instance_health(self, load_balancer_name, instances=None): \"\"\" Get current state",
"certificate replaces any prior certificate that was used on the",
"name: string :param name: The name of the load balancer",
"params) def set_lb_policies_of_backend_server(self, lb_name, instance_port, policies): \"\"\" Replaces the current",
"= \\ value.s3_bucket_prefix params['LoadBalancerAttributes.AccessLog.EmitInterval'] = \\ value.emit_interval elif attribute.lower() ==",
"self.get_list('ApplySecurityGroupsToLoadBalancer', params, None) def attach_lb_to_subnets(self, name, subnets): \"\"\" Attaches load",
"sell copies of the Software, and to permit # persons",
"or 'HTTPS' - SSLCertificateId is the ARN of an SSL",
"load_balancer_names: An optional list of load balancer names. :rtype: :py:class:`boto.resultset.ResultSet`",
"\\ value.s3_bucket_prefix params['LoadBalancerAttributes.AccessLog.EmitInterval'] = \\ value.emit_interval elif attribute.lower() == 'connectiondraining':",
"balancer will be created in EC2. To create a load",
"THE SOFTWARE. # \"\"\" This module provides an interface to",
"must be in the same region as the Load Balancer",
"zone(s) to remove. :rtype: List of strings :return: An updated",
"session lifetimes that follow that of an application-generated cookie. This",
"be associated only with HTTP listeners. When a load balancer",
"List of strings :param zones: The names of the availability",
"balancer names. :rtype: :py:class:`boto.resultset.ResultSet` :return: A ResultSet containing instances of",
"name is given \"\"\" for region in regions(): if region.name",
"return obj.zones def disable_availability_zones(self, load_balancer_name, zones_to_remove): \"\"\" Remove availability zones",
"Elastic Load Balancing cookie follows the lifetime of the application-generated",
"the session stops being sticky until a new application cookie",
"value) in enumerate(policy_attributes.iteritems(), 1): params['PolicyAttributes.member.%d.AttributeName' % index] = name params['PolicyAttributes.member.%d.AttributeValue'",
"in EC2. To create a load balancer inside a VPC,",
"a special cookie to track the backend server instance for",
"and 'true' or 'false' params['LoadBalancerAttributes.AccessLog.S3BucketName'] = \\ value.s3_bucket_name params['LoadBalancerAttributes.AccessLog.S3BucketPrefix'] =",
"or one (1) policy can be associated with a listener.",
"has no effect. :type load_balancer_name: string :param load_balancer_name: The name",
"'HTTPS'; SSLCertificateID is the ARN of a AWS IAM certificate,",
":return: The updated :class:`boto.ec2.elb.healthcheck.HealthCheck` \"\"\" params = {'LoadBalancerName': name, 'HealthCheck.Timeout':",
"is inserted into the response for binding subsequent requests from",
"List of strings :param instances: The instance ID's of the",
"The name of the Load Balancer :type subnets: List of",
"params, HealthCheck) def set_lb_listener_SSL_certificate(self, lb_name, lb_port, ssl_certificate_id): \"\"\" Sets the",
"listener[3].upper() params['Listeners.member.%d.LoadBalancerPort' % i] = listener[0] params['Listeners.member.%d.InstancePort' % i] =",
"+ 1 protocol = listener[2].upper() params['Listeners.member.%d.LoadBalancerPort' % i] = listener[0]",
"strings :param security_groups: The security groups assigned to your LoadBalancer",
"of the request \"\"\" if not listeners and not complex_listeners:",
"Load Balancer This will make an EC2 call for each",
"balancer implements this policy, the load balancer uses a special",
"that resolves to private IP addresses. This option is only",
"a new application cookie. If the application cookie is explicitly",
"as the Load Balancer Adding zones that are already registered",
"was used on the same LoadBalancer and port. \"\"\" params",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY",
"substantial portions of the Software. # # THE SOFTWARE IS",
"proxy, proxy_port, proxy_user, proxy_pass, self.region.endpoint, debug, https_connection_factory, path, security_token, validate_certs=validate_certs,",
"string containing either 'TCP', 'SSL', HTTP', or 'HTTPS'; SSLCertificateID is",
"params['PolicyAttributes.member.%d.AttributeValue' % index] = value else: params['PolicyAttributes'] = '' return",
"if load_balancer_names: self.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') return self.get_list('DescribeLoadBalancers', params, [('member', LoadBalancer)])",
"and/or sell copies of the Software, and to permit #",
"load_balancer.security_groups = security_groups return load_balancer def create_load_balancer_listeners(self, name, listeners=None, complex_listeners=None):",
"attribute you wish to change. * crossZoneLoadBalancing - Boolean (true)",
"lb_port, 'SSLCertificateId': ssl_certificate_id} return self.get_status('SetLoadBalancerListenerSSLCertificate', params) def create_app_cookie_stickiness_policy(self, name, lb_name,",
"of all Instances registered to an Load Balancer. :type load_balancer_name:",
"for index, listener in enumerate(complex_listeners): i = index + 1",
"listeners and not complex_listeners: # Must specify one of the",
"\\ value.s3_bucket_name params['LoadBalancerAttributes.AccessLog.S3BucketPrefix'] = \\ value.s3_bucket_prefix params['LoadBalancerAttributes.AccessLog.EmitInterval'] = \\ value.emit_interval",
"- :py:class:`AccessLogAttribute` instance * connectionDraining - :py:class:`ConnectionDrainingAttribute` instance :type value:",
"strings :return: An updated list of subnets for this Load",
"Handle the simple listeners if listeners: for index, listener in",
"sticky session lifetimes that follow that of an application-generated cookie.",
"<NAME> http://garnaat.org/ # Copyright (c) 2012 Amazon.com, Inc. or its",
"ARISING FROM, # OUT OF OR IN CONNECTION WITH THE",
"zones: The name of the zone(s) to add. :rtype: List",
"SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
"= {'LoadBalancerName': name, 'HealthCheck.Timeout': health_check.timeout, 'HealthCheck.Target': health_check.target, 'HealthCheck.Interval': health_check.interval, 'HealthCheck.UnhealthyThreshold':",
"name} return self.get_status('DeleteLoadBalancer', params) def delete_load_balancer_listeners(self, name, ports): \"\"\" Deletes",
"must not be enabled for any listeners. \"\"\" params =",
"set of policies. \"\"\" params = {'LoadBalancerName': lb_name, 'InstancePort': instance_port}",
"for :type ports: List int :param ports: Each int represents",
"else: raise ValueError('InvalidAttribute', attribute) return self.get_status('ModifyLoadBalancerAttributes', params, verb='GET') def get_all_lb_attributes(self,",
"listeners. When a load balancer implements this policy, the load",
"simple listeners if listeners: for index, listener in enumerate(listeners): i",
"\"\"\" Attaches load balancer to one or more subnets. Attaching",
"cookie is explicitly removed or expires, the session stops being",
":type security_groups: List of strings :param security_groups: The name of",
"interface to the Elastic Compute Cloud (EC2) load balancing service",
"self.get_list('DeregisterInstancesFromLoadBalancer', params, [('member', InstanceInfo)]) def describe_instance_health(self, load_balancer_name, instances=None): \"\"\" Get",
"Inc. or its affiliates. # All Rights Reserved # #",
"of :class:`boto.RegionInfo` instances \"\"\" return get_regions('elasticloadbalancing', connection_cls=ELBConnection) def connect_to_region(region_name, **kw_params):",
"\"\"\" params = {'LoadBalancerName': name} for index, port in enumerate(ports):",
"the subnet(s) to add. :rtype: List of strings :return: An",
"in bool_reqs: if isinstance(value, bool): if value: value = 'true'",
"instance_port} if policies: self.build_list_params(params, policies, 'PolicyNames.member.%d') else: params['PolicyNames'] = ''",
"name: string :param name: The name of the Load Balancer",
"i] = listener[2] if protocol == 'HTTPS' or protocol ==",
"\"\"\" params = {'CookieName': name, 'LoadBalancerName': lb_name, 'PolicyName': policy_name} return",
"not registered with the Load Balancer has no effect. You",
"or 'HTTPS'; SSLCertificateID is the ARN of a AWS IAM",
"if listeners: for index, listener in enumerate(listeners): i = index",
"LoadBalancerZones) return obj.zones def modify_lb_attribute(self, load_balancer_name, attribute, value): \"\"\"Changes an",
":return: The status of the request \"\"\" if not listeners",
"of the Load Balancer :rtype: boto.ec2.elb.attribute.LbAttributes :return: The attribute object",
"= ('crosszoneloadbalancing',) if attribute.lower() in bool_reqs: if isinstance(value, bool): if",
"modify_lb_attribute(self, load_balancer_name, attribute, value): \"\"\"Changes an attribute of a Load",
"your account. :type name: string :param name: The name of",
"delete_lb_policy(self, lb_name, policy_name): \"\"\" Deletes a policy from the LoadBalancer.",
"ports: List int :param ports: Each int represents the port",
"name of the security group(s) to add. :rtype: List of",
"this software and associated documentation files (the # \"Software\"), to",
"% i] = listener[4] return self.get_status('CreateLoadBalancerListeners', params) def delete_load_balancer(self, name):",
"lifetimes controlled by the lifetime of the browser (user-agent) or",
"return attributes.access_log if attribute.lower() == 'crosszoneloadbalancing': return attributes.cross_zone_load_balancing.enabled if attribute.lower()",
"1 protocol = listener[2].upper() params['Listeners.member.%d.LoadBalancerPort' % i] = listener[0] params['Listeners.member.%d.InstancePort'",
"for index, item in enumerate(items): params[label % (index + 1)]",
"load_regions import boto RegionData = load_regions().get('elasticloadbalancing', {}) def regions(): \"\"\"",
"Attaches load balancer to one or more subnets. Attaching subnets",
"Removing zones that are not registered with the Load Balancer",
"whom the Software is furnished to do so, subject to",
"Elastic Compute Cloud (EC2) load balancing service from AWS. \"\"\"",
"subnets, 'Subnets.member.%d') return self.get_list('AttachLoadBalancerToSubnets', params, None) def detach_lb_from_subnets(self, name, subnets):",
"string :param attribute: The attribute you wish to see. *",
"i = index + 1 protocol = listener[2].upper() params['Listeners.member.%d.LoadBalancerPort' %",
"def get_all_load_balancers(self, load_balancer_names=None): \"\"\" Retrieve all load balancers associated with",
"to track the backend server instance for each request. When",
"name, 'LoadBalancerName': lb_name, 'PolicyName': policy_name} return self.get_status('CreateAppCookieStickinessPolicy', params) def create_lb_cookie_stickiness_policy(self,",
"http://garnaat.org/ # Copyright (c) 2012 Amazon.com, Inc. or its affiliates.",
"listener (or group of listeners) :type name: string :param name:",
"with the new load balancer :type zones: List of strings",
"params = {'LoadBalancerName': load_balancer_name} self.build_list_params(params, zones_to_add, 'AvailabilityZones.member.%d') obj = self.get_object('EnableAvailabilityZonesForLoadBalancer',",
"'SSL': params['Listeners.member.%d.SSLCertificateId' % i] = listener[4] return self.get_status('CreateLoadBalancerListeners', params) def",
"documentation files (the # \"Software\"), to deal in the Software",
"returned. :rtype: List of :class:`boto.ec2.elb.instancestate.InstanceState` :return: list of state info",
"removed or expires, the session stops being sticky until a",
"sublicense, and/or sell copies of the Software, and to permit",
"region = RegionInfo(self, self.DefaultRegionName, self.DefaultRegionEndpoint) self.region = region super(ELBConnection, self).__init__(aws_access_key_id,",
"be set to None and subnets must not be None.",
"and InstancePortNumber are integer values between 1 and 65535 -",
"not be None. The load balancer will be automatically created",
"group(s) to add. :rtype: List of strings :return: An updated",
"\"\"\" Get all available regions for the ELB service. :rtype:",
"instances to add. :rtype: List of strings :return: An updated",
"List of strings :return: An updated list of instances for",
"None may be passed for cookie_expiration_period. \"\"\" params = {'LoadBalancerName':",
"with a DNS name that resolves to private IP addresses.",
"new application cookie is issued. \"\"\" params = {'CookieName': name,",
"'HTTPS' - SSLCertificateId is the ARN of an SSL certificate",
"the application server specified in the cookie. If not, the",
"Load Balancer from your account. :type name: string :param name:",
"attribute.lower() == 'connectiondraining': return attributes.connection_draining return None def register_instances(self, load_balancer_name,",
"any prior certificate that was used on the same LoadBalancer",
"front-end listener, or the back-end application server. \"\"\" params =",
"self.get_object('ConfigureHealthCheck', params, HealthCheck) def set_lb_listener_SSL_certificate(self, lb_name, lb_port, ssl_certificate_id): \"\"\" Sets",
"Load Balancer :type attribute: string :param attribute: The attribute you",
"= boto.config.get('Boto', 'elb_region_name', 'us-east-1') DefaultRegionEndpoint = boto.config.get('Boto', 'elb_region_endpoint', 'elasticloadbalancing.us-east-1.amazonaws.com') def",
"is present in the request. If so, the load balancer",
"of the Software, and to permit # persons to whom",
"'elb_region_endpoint', 'elasticloadbalancing.us-east-1.amazonaws.com') def __init__(self, aws_access_key_id=None, aws_secret_access_key=None, is_secure=True, port=None, proxy=None, proxy_port=None,",
"'LoadBalancerNames.member.%d') return self.get_list('DescribeLoadBalancers', params, [('member', LoadBalancer)]) def create_load_balancer(self, name, zones,",
"LbAttributes) def get_lb_attribute(self, load_balancer_name, attribute): \"\"\"Gets an attribute of a",
"def delete_load_balancer_listeners(self, name, ports): \"\"\" Deletes a load balancer listener",
"return self.get_object('ConfigureHealthCheck', params, HealthCheck) def set_lb_listener_SSL_certificate(self, lb_name, lb_port, ssl_certificate_id): \"\"\"",
"'Scheme': scheme} # Handle legacy listeners if listeners: for index,",
"your account. :type load_balancer_names: list :keyword load_balancer_names: An optional list",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- #",
"specified policy must not be enabled for any listeners. \"\"\"",
"of policies associated with a port on which the back-end",
"for each request. When the load balancer receives a request,",
"are already registered with the Load Balancer has no effect.",
"register_instances(self, load_balancer_name, instances): \"\"\" Add new Instances to an existing",
"is_secure, port, proxy, proxy_port, proxy_user, proxy_pass, self.region.endpoint, debug, https_connection_factory, path,",
"Load Balancer. \"\"\" params = {'LoadBalancerName': load_balancer_name} self.build_list_params(params, zones_to_remove, 'AvailabilityZones.member.%d')",
"a Load Balancer :type load_balancer_name: string :param load_balancer_name: The name",
"load_balancer_name): \"\"\"Gets all Attributes of a Load Balancer :type load_balancer_name:",
"LoadBalancerPortNumber and InstancePortNumber are integer values between 1 and 65535",
"params['LoadBalancerAttributes.AccessLog.S3BucketPrefix'] = \\ value.s3_bucket_prefix params['LoadBalancerAttributes.AccessLog.EmitInterval'] = \\ value.emit_interval elif attribute.lower()",
"'HealthCheck.Timeout': health_check.timeout, 'HealthCheck.Target': health_check.target, 'HealthCheck.Interval': health_check.interval, 'HealthCheck.UnhealthyThreshold': health_check.unhealthy_threshold, 'HealthCheck.HealthyThreshold': health_check.healthy_threshold}",
"instances): \"\"\" Add new Instances to an existing Load Balancer.",
"listener[1] params['Listeners.member.%d.Protocol' % i] = listener[2] params['Listeners.member.%d.InstanceProtocol' % i] =",
"string :param name: The mnemonic name associated with the load",
"def regions(): \"\"\" Get all available regions for the ELB",
"= boto.config.get('Boto', 'elb_version', '2012-06-01') DefaultRegionName = boto.config.get('Boto', 'elb_region_name', 'us-east-1') DefaultRegionEndpoint",
"in all copies or substantial portions of the Software. #",
"params, [('member', InstanceInfo)]) def describe_instance_health(self, load_balancer_name, instances=None): \"\"\" Get current",
"The load balancer only inserts a new stickiness cookie when",
"into the response for binding subsequent requests from the same",
"of policies. \"\"\" params = {'LoadBalancerName': lb_name, 'InstancePort': instance_port} if",
"LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR",
"\"\"\" params = {'LoadBalancerName': name, 'HealthCheck.Timeout': health_check.timeout, 'HealthCheck.Target': health_check.target, 'HealthCheck.Interval':",
"return None params = {'LoadBalancerName': name} # Handle the simple",
"of strings :param security_groups: The name of the security group(s)",
"if subnets: self.build_list_params(params, subnets, 'Subnets.member.%d') if security_groups: self.build_list_params(params, security_groups, 'SecurityGroups.member.%d')",
"health check for the EndPoints. :type name: string :param name:",
"CreateLBCookieStickinessPolicy, except that the lifetime of the special Elastic Load",
"attribute.lower() == 'crosszoneloadbalancing': params['LoadBalancerAttributes.CrossZoneLoadBalancing.Enabled' ] = value elif attribute.lower() ==",
"return region.connect(**kw_params) return None class ELBConnection(AWSQueryConnection): APIVersion = boto.config.get('Boto', 'elb_version',",
"\"\"\" Given a valid region name, return a :class:`boto.ec2.elb.ELBConnection`. :param",
"name of the Load Balancer :type attribute: string :param attribute:",
"to the load balancer. Applying security groups that are already",
"The updated :class:`boto.ec2.elb.healthcheck.HealthCheck` \"\"\" params = {'LoadBalancerName': name, 'HealthCheck.Timeout': health_check.timeout,",
"THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"Init method to create a new connection to EC2 Load",
"LoadBalancer and port. \"\"\" params = {'LoadBalancerName': lb_name, 'LoadBalancerPort': lb_port,",
"Load Balancer :type subnets: List of strings :param subnets: The",
"to permit # persons to whom the Software is furnished",
"groups to the load balancer. Applying security groups that are",
"This policy can only be associated only with HTTP listeners.",
"boto.connection import AWSQueryConnection from boto.ec2.instanceinfo import InstanceInfo from boto.ec2.elb.loadbalancer import",
"boto RegionData = load_regions().get('elasticloadbalancing', {}) def regions(): \"\"\" Get all",
"containing either 'TCP', 'SSL', HTTP', or 'HTTPS'; SSLCertificateID is the",
"All Rights Reserved # # Permission is hereby granted, free",
"{'LoadBalancerName': load_balancer_name} if attribute.lower() == 'crosszoneloadbalancing': params['LoadBalancerAttributes.CrossZoneLoadBalancing.Enabled' ] = value",
"BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, #",
":type listeners: List of tuples :param listeners: Each tuple contains",
"not region: region = RegionInfo(self, self.DefaultRegionName, self.DefaultRegionEndpoint) self.region = region",
"\"\"\"Gets an attribute of a Load Balancer This will make",
"except that the lifetime of the special Elastic Load Balancing",
"params['Listeners.member.%d.InstanceProtocol' % i] = listener[3] if protocol == 'HTTPS' or",
"set of policies associated with a port on which the",
":type load_balancer_name: string :param load_balancer_name: The name of the Load",
"the port on the ELB to be removed :return: The",
"your LoadBalancer. :type security_groups: list of strings :param security_groups: The",
"of tuples :param complex_listeners: Each tuple contains four or five",
"lb_name, lb_port, ssl_certificate_id): \"\"\" Sets the certificate that terminates the",
"name, which resolves to public IP addresses. Specify the value",
"health_check.timeout, 'HealthCheck.Target': health_check.target, 'HealthCheck.Interval': health_check.interval, 'HealthCheck.UnhealthyThreshold': health_check.unhealthy_threshold, 'HealthCheck.HealthyThreshold': health_check.healthy_threshold} return",
"% index] = value else: params['PolicyAttributes'] = '' return self.get_status('CreateLoadBalancerPolicy',",
"boto configuration file. \"\"\" if not region: region = RegionInfo(self,",
"OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION",
"= listener[2] params['Listeners.member.%d.InstanceProtocol' % i] = listener[3] if protocol ==",
"region=None, path='/', security_token=None, validate_certs=True, profile_name=None): \"\"\" Init method to create",
"the Software is furnished to do so, subject to the",
"based on the cookie expiration time, which is specified in",
"group of listeners) :type name: string :param name: The name",
"MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"return None class ELBConnection(AWSQueryConnection): APIVersion = boto.config.get('Boto', 'elb_version', '2012-06-01') DefaultRegionName",
"optional list of load balancer names. :rtype: :py:class:`boto.resultset.ResultSet` :return: A",
"containing either 'TCP', 'SSL', 'HTTP', or 'HTTPS' - SSLCertificateId is",
"items = [items] for index, item in enumerate(items): params[label %",
"to one or more subnets. Attaching subnets that are already",
"load_balancer_name, zones_to_remove): \"\"\" Remove availability zones from an existing Load",
"addresses. Specify the value internal for this option to create",
"scheme='internet-facing', complex_listeners=None): \"\"\" Create a new load balancer for your",
"or protocol == 'SSL': params['Listeners.member.%d.SSLCertificateId' % i] = listener[3] #",
"\"Software\"), to deal in the Software without restriction, including #",
"cookie expiration time, which is specified in the policy configuration.",
"your VPC. :type scheme: string :param scheme: The type of",
"associated with a port on which the back-end server is",
"the request. If so, the load balancer sends the request",
"Load Balancing creates an internet-facing LoadBalancer with a publicly resolvable",
"for binding subsequent requests from the same user to that",
"permission notice shall be included # in all copies or",
"'us-east-1') DefaultRegionEndpoint = boto.config.get('Boto', 'elb_region_endpoint', 'elasticloadbalancing.us-east-1.amazonaws.com') def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,",
"CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION",
"no effect. :type name: string :param name: The name of",
":py:class:`ConnectionDrainingAttribute` instance :type value: string :param value: The new value",
"self.DefaultRegionName, self.DefaultRegionEndpoint) self.region = region super(ELBConnection, self).__init__(aws_access_key_id, aws_secret_access_key, is_secure, port,",
"'HTTPS' or protocol == 'SSL': params['Listeners.member.%d.SSLCertificateId' % i] = listener[3]",
"region_name: The name of the region to connect to. :rtype:",
"this permission notice shall be included # in all copies",
"already registered with the Load Balancer has no effect. :type",
"IAM certificate, and must be specified when doing HTTPS. :type",
"a listener. \"\"\" params = {'LoadBalancerName': lb_name, 'LoadBalancerPort': lb_port} if",
"to do so, subject to the fol- # lowing conditions:",
"TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN",
"for LoadBalancers attached to an Amazon VPC. :type complex_listeners: List",
"load_balancer_name} if attribute.lower() == 'crosszoneloadbalancing': params['LoadBalancerAttributes.CrossZoneLoadBalancing.Enabled' ] = value elif",
"Permission is hereby granted, free of charge, to any person",
"names. :rtype: :py:class:`boto.resultset.ResultSet` :return: A ResultSet containing instances of :class:`boto.ec2.elb.loadbalancer.LoadBalancer`",
"by CreateLBCookieStickinessPolicy, except that the lifetime of the special Elastic",
"specified when doing HTTPS. :type subnets: list of strings :param",
"tuple contains four or five values, (LoadBalancerPortNumber, InstancePortNumber, Protocol, InstanceProtocol,",
"in regions(): if region.name == region_name: return region.connect(**kw_params) return None",
"to public IP addresses. Specify the value internal for this",
"registered with the Load Balancer has no effect. :type name:",
"self.build_list_params(params, subnets, 'Subnets.member.%d') return self.get_list('AttachLoadBalancerToSubnets', params, None) def detach_lb_from_subnets(self, name,",
"instances to remove. :rtype: List of strings :return: An updated",
"balancer :type health_check: :class:`boto.ec2.elb.healthcheck.HealthCheck` :param health_check: A HealthCheck object populated",
"\"\"\" Replaces the current set of policies associated with a",
"verb='GET') def get_all_lb_attributes(self, load_balancer_name): \"\"\"Gets all Attributes of a Load",
"current set of policies associated with a port on which",
"on the same LoadBalancer and port. \"\"\" params = {'LoadBalancerName':",
"load_balancer_name, instances): \"\"\" Remove Instances from an existing Load Balancer.",
"policy_name} if cookie_expiration_period is not None: params['CookieExpirationPeriod'] = cookie_expiration_period return",
"= listener[4] if zones: self.build_list_params(params, zones, 'AvailabilityZones.member.%d') if subnets: self.build_list_params(params,",
"in the cookie. If not, the load balancer sends the",
"= 'false' params = {'LoadBalancerName': load_balancer_name} if attribute.lower() == 'crosszoneloadbalancing':",
"sends the request to the application server specified in the",
"values, (LoadBalancerPortNumber, InstancePortNumber, Protocol, InstanceProtocol, SSLCertificateId). Where: - LoadBalancerPortNumber and",
"be returned. :rtype: List of :class:`boto.ec2.elb.instancestate.InstanceState` :return: list of state",
"WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING",
"name of the region to connect to. :rtype: :class:`boto.ec2.ELBConnection` or",
"a :class:`boto.ec2.elb.ELBConnection`. :param str region_name: The name of the region",
"security groups assigned to your LoadBalancer within your VPC. :type",
"of strings :param security_groups: The security groups assigned to your",
"region: region = RegionInfo(self, self.DefaultRegionName, self.DefaultRegionEndpoint) self.region = region super(ELBConnection,",
"sticky session lifetimes controlled by the lifetime of the browser",
"specified in the boto configuration file. \"\"\" if not region:",
"value): \"\"\"Changes an attribute of a Load Balancer :type load_balancer_name:",
"included # in all copies or substantial portions of the",
"from boto.ec2.elb.listelement import ListElement from boto.regioninfo import RegionInfo, get_regions, load_regions",
"request. When the load balancer receives a request, it first",
"doing HTTPS. :type subnets: list of strings :param subnets: A",
"EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE",
"follow that of an application-generated cookie. This policy can only",
"the EC2 instances to remove. :rtype: List of strings :return:",
"instances=None): \"\"\" Get current state of all Instances registered to",
":rtype: boto.ec2.elb.attribute.LbAttributes :return: The attribute object of the ELB. \"\"\"",
"def detach_lb_from_subnets(self, name, subnets): \"\"\" Detaches load balancer from one",
"existing Load Balancer. :type load_balancer_name: string :param load_balancer_name: The name",
"you wish to change. * crossZoneLoadBalancing - Boolean (true) *",
"the load balancer :type health_check: :class:`boto.ec2.elb.healthcheck.HealthCheck` :param health_check: A HealthCheck",
"PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS #",
"for :type listeners: List of tuples :param listeners: Each tuple",
"ssl_certificate_id): \"\"\" Sets the certificate that terminates the specified listener's",
"policies, 'PolicyNames.member.%d') else: params['PolicyNames'] = '' return self.get_status('SetLoadBalancerPoliciesForBackendServer', params) def",
"is_secure=True, port=None, proxy=None, proxy_port=None, proxy_user=None, proxy_pass=None, debug=0, https_connection_factory=None, region=None, path='/',",
"load_balancer_names=None): \"\"\" Retrieve all load balancers associated with your account.",
"self.get_status('SetLoadBalancerListenerSSLCertificate', params) def create_app_cookie_stickiness_policy(self, name, lb_name, policy_name): \"\"\" Generates a",
"under the VPC that contains the subnet(s) specified. :type name:",
"'TCP', 'SSL', HTTP', or 'HTTPS'; SSLCertificateID is the ARN of",
"loaded into AWS IAM :rtype: :class:`boto.ec2.elb.loadbalancer.LoadBalancer` :return: The newly created",
"The name of the region to connect to. :rtype: :class:`boto.ec2.ELBConnection`",
"AWS IAM certificate, and must be specified when doing HTTPS.",
"ID's of the EC2 instances to return status for. If",
"the specified listener's SSL connections. The specified certificate replaces any",
"subnets. :type name: string :param name: The name of the",
"boto.ec2.instanceinfo import InstanceInfo from boto.ec2.elb.loadbalancer import LoadBalancer, LoadBalancerZones from boto.ec2.elb.instancestate",
"= listener[1] params['Listeners.member.%d.Protocol' % i] = listener[2] params['Listeners.member.%d.InstanceProtocol' % i]",
"see if this cookie is present in the request. If",
"that contains the subnet(s) specified. :type name: string :param name:",
"will be automatically created under the VPC that contains the",
"must be specified when doing HTTPS. :type subnets: list of",
"string :param name: The name of the load balancer to",
"if zones: self.build_list_params(params, zones, 'AvailabilityZones.member.%d') if subnets: self.build_list_params(params, subnets, 'Subnets.member.%d')",
"use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or",
"attribute.lower() == 'crosszoneloadbalancing': return attributes.cross_zone_load_balancing.enabled if attribute.lower() == 'connectiondraining': return",
":return: The status of the request \"\"\" params = {'LoadBalancerName':",
"\"\"\" Associates, updates, or disables a policy with a listener",
"\"\"\" Detaches load balancer from one or more subnets. :type",
"the load balancer. Applying security groups that are already registered",
"and 65535, Protocol is a string containing either 'TCP', 'SSL',",
"ID's of the EC2 instances to remove. :rtype: List of",
"[items] for index, item in enumerate(items): params[label % (index +",
"operation succeeded or not \"\"\" bool_reqs = ('crosszoneloadbalancing',) if attribute.lower()",
"\"\"\" params = {'LoadBalancerName': load_balancer_name} self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return self.get_list('RegisterInstancesWithLoadBalancer',",
"lb_name, 'PolicyName': policy_name, 'PolicyTypeName': policy_type} for index, (name, value) in",
"return status for. If not provided, the state of all",
"elif attribute.lower() == 'connectiondraining': params['LoadBalancerAttributes.ConnectionDraining.Enabled'] = \\ value.enabled and 'true'",
"\"\"\" params = {'LoadBalancerName': lb_name, 'LoadBalancerPort': lb_port} if len(policies): self.build_list_params(params,",
"argument is overridden by the region specified in the boto",
"return self.get_list('DescribeLoadBalancers', params, [('member', LoadBalancer)]) def create_load_balancer(self, name, zones, listeners=None,",
"account. By default the load balancer will be created in",
"complex_listeners: List of tuples :param complex_listeners: Each tuple contains four",
"{}) def regions(): \"\"\" Get all available regions for the",
"instance for each request. When the load balancer receives a",
"hereby granted, free of charge, to any person obtaining a",
"server that is chosen based on the existing load balancing",
"policies associated with a port on which the back-end server",
"a VPC, parameter zones must be set to None and",
"protocol == 'HTTPS' or protocol == 'SSL': params['Listeners.member.%d.SSLCertificateId' % i]",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE",
"for index, port in enumerate(ports): params['LoadBalancerPorts.member.%d' % (index + 1)]",
"expiration period. This policy can only be associated only with",
"Load Balancer to delete \"\"\" params = {'LoadBalancerName': name} return",
"list of subnet IDs in your VPC to attach to",
"profile_name=profile_name) def _required_auth_capability(self): return ['ec2'] def build_list_params(self, params, items, label):",
"policy_attributes): \"\"\" Creates a new policy that contais the necessary",
"configuration file. \"\"\" if not region: region = RegionInfo(self, self.DefaultRegionName,",
"an attribute of a Load Balancer This will make an",
"zones load_balancer.subnets = subnets load_balancer.security_groups = security_groups return load_balancer def",
"load balancer for your account. By default the load balancer",
"VPC to attach to your LoadBalancer. :type security_groups: list of",
"to the Elastic Compute Cloud (EC2) load balancing service from",
"name} self.build_list_params(params, subnets, 'Subnets.member.%d') return self.get_list('AttachLoadBalancerToSubnets', params, None) def detach_lb_from_subnets(self,",
"from boto.ec2.instanceinfo import InstanceInfo from boto.ec2.elb.loadbalancer import LoadBalancer, LoadBalancerZones from",
":param str region_name: The name of the region to connect",
"instances in this Load Balancer. \"\"\" params = {'LoadBalancerName': load_balancer_name}",
"wish to change. * crossZoneLoadBalancing - Boolean (true) * accessLog",
"mnemonic name associated with the load balancer :type health_check: :class:`boto.ec2.elb.healthcheck.HealthCheck`",
"if region.name == region_name: return region.connect(**kw_params) return None class ELBConnection(AWSQueryConnection):",
"no effect. You cannot remove all zones from an Load",
"Instances to an existing Load Balancer. :type load_balancer_name: string :param",
"name of the load balancer to create the listeners for",
"attribute: The attribute you wish to change. * crossZoneLoadBalancing -",
"lb_name, 'InstancePort': instance_port} if policies: self.build_list_params(params, policies, 'PolicyNames.member.%d') else: params['PolicyNames']",
"params['PolicyAttributes.member.%d.AttributeName' % index] = name params['PolicyAttributes.member.%d.AttributeValue' % index] = value",
"OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH",
"server. The validity of the cookie is based on the",
"specified when doing HTTPS. :type complex_listeners: List of tuples :param",
"with the Load Balancer has no effect. You cannot remove",
"lb_port} if len(policies): self.build_list_params(params, policies, 'PolicyNames.member.%d') else: params['PolicyNames'] = ''",
"delete_load_balancer_listeners(self, name, ports): \"\"\" Deletes a load balancer listener (or",
"integer values between 1 and 65535 - Protocol and InstanceProtocol",
"Instances registered to an Load Balancer. :type load_balancer_name: string :param",
"scheme: string :param scheme: The type of a LoadBalancer. By",
":param attribute: The attribute you wish to see. * accessLog",
"load balancer sends the request to the application server specified",
"the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\",",
"VPC. :type scheme: string :param scheme: The type of a",
"Load Balancer All zones must be in the same region",
"in the request. If so, the load balancer sends the",
"``None`` :return: A connection to the given region, or None",
"tuples :param listeners: Each tuple contains three or four values,",
"import InstanceState from boto.ec2.elb.healthcheck import HealthCheck from boto.ec2.elb.listelement import ListElement",
"aws_secret_access_key, is_secure, port, proxy, proxy_port, proxy_user, proxy_pass, self.region.endpoint, debug, https_connection_factory,",
"attribute object of the ELB. \"\"\" from boto.ec2.elb.attributes import LbAttributes",
"complex_listeners: for index, listener in enumerate(complex_listeners): i = index +",
"= self.get_all_lb_attributes(load_balancer_name) if attribute.lower() == 'accesslog': return attributes.access_log if attribute.lower()",
"OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT",
"the listeners for :type ports: List int :param ports: Each",
"all copies or substantial portions of the Software. # #",
"Load Balancer. \"\"\" params = {'LoadBalancerName': name} self.build_list_params(params, security_groups, 'SecurityGroups.member.%d')",
"from boto.ec2.elb.healthcheck import HealthCheck from boto.ec2.elb.listelement import ListElement from boto.regioninfo",
":py:class:`boto.resultset.ResultSet` :return: A ResultSet containing instances of :class:`boto.ec2.elb.loadbalancer.LoadBalancer` \"\"\" params",
"load_balancer = self.get_object('CreateLoadBalancer', params, LoadBalancer) load_balancer.name = name load_balancer.listeners =",
"in enumerate(listeners): i = index + 1 protocol = listener[2].upper()",
"IAM :return: The status of the request \"\"\" if not",
"cannot remove all zones from an Load Balancer. :type load_balancer_name:",
"with HTTP listeners. When a load balancer implements this policy,",
"zones_to_add, 'AvailabilityZones.member.%d') obj = self.get_object('EnableAvailabilityZonesForLoadBalancer', params, LoadBalancerZones) return obj.zones def",
"aws_secret_access_key=None, is_secure=True, port=None, proxy=None, proxy_port=None, proxy_user=None, proxy_pass=None, debug=0, https_connection_factory=None, region=None,",
"InstanceInfo)]) def describe_instance_health(self, load_balancer_name, instances=None): \"\"\" Get current state of",
"request to a server that is chosen based on the",
"more subnets. :type name: string :param name: The name of",
"to an Amazon VPC. :type complex_listeners: List of tuples :param",
"are integer values between 1 and 65535 - Protocol and",
"HTTPS. :type complex_listeners: List of tuples :param complex_listeners: Each tuple",
"- Boolean (true) * accessLog - :py:class:`AccessLogAttribute` instance * connectionDraining",
"a new set of policies. \"\"\" params = {'LoadBalancerName': lb_name,",
"# Copyright (c) 2006-2012 <NAME> http://garnaat.org/ # Copyright (c) 2012",
"the zone(s) to add. :rtype: List of strings :return: An",
"EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM,",
"= self.get_object('EnableAvailabilityZonesForLoadBalancer', params, LoadBalancerZones) return obj.zones def disable_availability_zones(self, load_balancer_name, zones_to_remove):",
"Software, and to permit # persons to whom the Software",
":return: A connection to the given region, or None if",
"request to the application server specified in the cookie. If",
"params) def delete_load_balancer(self, name): \"\"\" Delete a Load Balancer from",
"% i] = listener[4] if zones: self.build_list_params(params, zones, 'AvailabilityZones.member.%d') if",
":rtype: List of strings :return: An updated list of zones",
"Software without restriction, including # without limitation the rights to",
"valid region name, return a :class:`boto.ec2.elb.ELBConnection`. :param str region_name: The",
"'true' or 'false' params['LoadBalancerAttributes.AccessLog.S3BucketName'] = \\ value.s3_bucket_name params['LoadBalancerAttributes.AccessLog.S3BucketPrefix'] = \\",
"params = {'LoadBalancerName': load_balancer_name} return self.get_object('DescribeLoadBalancerAttributes', params, LbAttributes) def get_lb_attribute(self,",
"self.get_list('RegisterInstancesWithLoadBalancer', params, [('member', InstanceInfo)]) def deregister_instances(self, load_balancer_name, instances): \"\"\" Remove",
"The instance ID's of the EC2 instances to return status",
"string :param name: The name of the Load Balancer :type",
":param subnets: The name of the subnet(s) to detach. :rtype:",
"of the two options return None params = {'LoadBalancerName': name}",
"policy created by CreateLBCookieStickinessPolicy, except that the lifetime of the",
"\"\"\" Define a health check for the EndPoints. :type name:",
"in the Software without restriction, including # without limitation the",
"self.get_status('CreateLoadBalancerListeners', params) def delete_load_balancer(self, name): \"\"\" Delete a Load Balancer",
"'SecurityGroups.member.%d') return self.get_list('ApplySecurityGroupsToLoadBalancer', params, None) def attach_lb_to_subnets(self, name, subnets): \"\"\"",
"load balancing algorithm. A cookie is inserted into the response",
"lifetime of the application-generated cookie specified in the policy configuration.",
"region.connect(**kw_params) return None class ELBConnection(AWSQueryConnection): APIVersion = boto.config.get('Boto', 'elb_version', '2012-06-01')",
"The attribute you wish to see. * accessLog - :py:class:`AccessLogAttribute`",
"an attribute of a Load Balancer :type load_balancer_name: string :param",
"\"\"\" Add availability zones to an existing Load Balancer All",
"if attribute.lower() == 'connectiondraining': return attributes.connection_draining return None def register_instances(self,",
"a string containing either 'TCP', 'SSL', 'HTTP', or 'HTTPS' -",
"Balancer Adding zones that are already registered with the Load",
"creates an internet-facing LoadBalancer with a publicly resolvable DNS name,",
"this Load Balancer. \"\"\" params = {'LoadBalancerName': name} self.build_list_params(params, subnets,",
"with a listener on the load balancer. Currently only zero",
"server instance for each request. When the load balancer receives",
"assigned to your LoadBalancer within your VPC. :type scheme: string",
"associated with your account. :type load_balancer_names: list :keyword load_balancer_names: An",
"params = {'LoadBalancerName': name} self.build_list_params(params, subnets, 'Subnets.member.%d') return self.get_list('AttachLoadBalancerToSubnets', params,",
"group of listeners) for an existing Load Balancer :type name:",
"affiliates. # All Rights Reserved # # Permission is hereby",
"load balancer names. :rtype: :py:class:`boto.resultset.ResultSet` :return: A ResultSet containing instances",
"self.get_status('CreateLoadBalancerPolicy', params) def delete_lb_policy(self, lb_name, policy_name): \"\"\" Deletes a policy",
"that was used on the same LoadBalancer and port. \"\"\"",
"params = {'LoadBalancerName': name} self.build_list_params(params, security_groups, 'SecurityGroups.member.%d') return self.get_list('ApplySecurityGroupsToLoadBalancer', params,",
"<gh_stars>10-100 # Copyright (c) 2006-2012 <NAME> http://garnaat.org/ # Copyright (c)",
"'LoadBalancerPort': lb_port} if len(policies): self.build_list_params(params, policies, 'PolicyNames.member.%d') else: params['PolicyNames'] =",
"listeners=None, complex_listeners=None): \"\"\" Creates a Listener (or group of listeners)",
"= \\ value.s3_bucket_name params['LoadBalancerAttributes.AccessLog.S3BucketPrefix'] = \\ value.s3_bucket_prefix params['LoadBalancerAttributes.AccessLog.EmitInterval'] = \\",
"Specify the value internal for this option to create an",
"Policies are settings that are saved for your load balancer",
"an application-generated cookie. This policy can only be associated with",
"your VPC to attach to your LoadBalancer. :type security_groups: list",
"containing instances of :class:`boto.ec2.elb.loadbalancer.LoadBalancer` \"\"\" params = {} if load_balancer_names:",
"= {'LoadBalancerName': lb_name, 'InstancePort': instance_port} if policies: self.build_list_params(params, policies, 'PolicyNames.member.%d')",
"is not None: params['CookieExpirationPeriod'] = cookie_expiration_period return self.get_status('CreateLBCookieStickinessPolicy', params) def",
"for cookie_expiration_period. \"\"\" params = {'LoadBalancerName': lb_name, 'PolicyName': policy_name} if",
"% (index + 1)] = item def get_all_load_balancers(self, load_balancer_names=None): \"\"\"",
"'false' params['LoadBalancerAttributes.AccessLog.S3BucketName'] = \\ value.s3_bucket_name params['LoadBalancerAttributes.AccessLog.S3BucketPrefix'] = \\ value.s3_bucket_prefix params['LoadBalancerAttributes.AccessLog.EmitInterval']",
"response for binding subsequent requests from the same user to",
"subnets for this Load Balancer. \"\"\" params = {'LoadBalancerName': name}",
":rtype: :class:`boto.ec2.elb.healthcheck.HealthCheck` :return: The updated :class:`boto.ec2.elb.healthcheck.HealthCheck` \"\"\" params = {'LoadBalancerName':",
"LoadBalancerPortNumber and InstancePortNumber are integer values between 1 and 65535,",
"self.DefaultRegionEndpoint) self.region = region super(ELBConnection, self).__init__(aws_access_key_id, aws_secret_access_key, is_secure, port, proxy,",
"\"\"\" This module provides an interface to the Elastic Compute",
"'HTTP', or 'HTTPS' - SSLCertificateId is the ARN of an",
"= {'LoadBalancerName': name} self.build_list_params(params, subnets, 'Subnets.member.%d') return self.get_list('AttachLoadBalancerToSubnets', params, None)",
"name, subnets): \"\"\" Detaches load balancer from one or more",
"listeners. This policy is similar to the policy created by",
"List int :param ports: Each int represents the port on",
"response includes a new application cookie. If the application cookie",
"\\ value.enabled and 'true' or 'false' params['LoadBalancerAttributes.AccessLog.S3BucketName'] = \\ value.s3_bucket_name",
":rtype: List of strings :return: An updated list of security",
"string containing either 'TCP', 'SSL', 'HTTP', or 'HTTPS' - SSLCertificateId",
"either 'TCP', 'SSL', 'HTTP', or 'HTTPS' - SSLCertificateId is the",
"zone(s) to add. :rtype: List of strings :return: An updated",
"delete \"\"\" params = {'LoadBalancerName': name} return self.get_status('DeleteLoadBalancer', params) def",
"security_groups: The security groups assigned to your LoadBalancer within your",
"Balancer. :type load_balancer_name: string :param load_balancer_name: The name of the",
"params['PolicyNames'] = '' return self.get_status('SetLoadBalancerPoliciesForBackendServer', params) def apply_security_groups_to_lb(self, name, security_groups):",
"to your LoadBalancer. :type security_groups: list of strings :param security_groups:",
"subnets=None, security_groups=None, scheme='internet-facing', complex_listeners=None): \"\"\" Create a new load balancer",
"ID's of the EC2 instances to add. :rtype: List of",
"Balancer. \"\"\" params = {'LoadBalancerName': load_balancer_name} self.build_list_params(params, zones_to_add, 'AvailabilityZones.member.%d') obj",
"get_lb_attribute(self, load_balancer_name, attribute): \"\"\"Gets an attribute of a Load Balancer",
"name: The mnemonic name associated with the new load balancer",
"disables a policy with a listener on the load balancer.",
"# Handle the full listeners if complex_listeners: for index, listener",
"index] = name params['PolicyAttributes.member.%d.AttributeValue' % index] = value else: params['PolicyAttributes']",
"the simple listeners if listeners: for index, listener in enumerate(listeners):",
"'elb_region_name', 'us-east-1') DefaultRegionEndpoint = boto.config.get('Boto', 'elb_region_endpoint', 'elasticloadbalancing.us-east-1.amazonaws.com') def __init__(self, aws_access_key_id=None,",
"else: params['PolicyNames'] = '' return self.get_status('SetLoadBalancerPoliciesOfListener', params) def set_lb_policies_of_backend_server(self, lb_name,",
":type zones: List of strings :param zones: The name of",
"= {'LoadBalancerName': load_balancer_name} if attribute.lower() == 'crosszoneloadbalancing': params['LoadBalancerAttributes.CrossZoneLoadBalancing.Enabled' ] =",
"the given region, or None if an invalid region name",
"AWSQueryConnection from boto.ec2.instanceinfo import InstanceInfo from boto.ec2.elb.loadbalancer import LoadBalancer, LoadBalancerZones",
"= {'LoadBalancerName': load_balancer_name} self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return self.get_list('RegisterInstancesWithLoadBalancer', params, [('member',",
"certificate that terminates the specified listener's SSL connections. The specified",
"load balancer :type zones: List of strings :param zones: The",
"created :class:`boto.ec2.elb.loadbalancer.LoadBalancer` \"\"\" if not listeners and not complex_listeners: #",
"not \"\"\" bool_reqs = ('crosszoneloadbalancing',) if attribute.lower() in bool_reqs: if",
"policy_name, policy_type, policy_attributes): \"\"\" Creates a new policy that contais",
"'Subnets.member.%d') if security_groups: self.build_list_params(params, security_groups, 'SecurityGroups.member.%d') load_balancer = self.get_object('CreateLoadBalancer', params,",
"object of the ELB. \"\"\" from boto.ec2.elb.attributes import LbAttributes params",
"instance ID's of the EC2 instances to remove. :rtype: List",
"health_check.interval, 'HealthCheck.UnhealthyThreshold': health_check.unhealthy_threshold, 'HealthCheck.HealthyThreshold': health_check.healthy_threshold} return self.get_object('ConfigureHealthCheck', params, HealthCheck) def",
"policy configuration. The load balancer only inserts a new stickiness",
"- Protocol and InstanceProtocol is a string containing either 'TCP',",
"the front-end listener, or the back-end application server. \"\"\" params",
"be specified when doing HTTPS. :type complex_listeners: List of tuples",
"remove. :rtype: List of strings :return: An updated list of",
"each method call. :type load_balancer_name: string :param load_balancer_name: The name",
"return self.get_status('DeleteLoadBalancerPolicy', params) def set_lb_policies_of_listener(self, lb_name, lb_port, policies): \"\"\" Associates,",
"region name, return a :class:`boto.ec2.elb.ELBConnection`. :param str region_name: The name",
"account. :type load_balancer_names: list :keyword load_balancer_names: An optional list of",
"strings :return: An updated list of zones for this Load",
"create_lb_cookie_stickiness_policy(self, cookie_expiration_period, lb_name, policy_name): \"\"\" Generates a stickiness policy with",
"SSLCertificateID is the ARN of a AWS IAM certificate, and",
"that of an application-generated cookie. This policy can only be",
"% i] = listener[3] if protocol == 'HTTPS' or protocol",
"the state of all instances will be returned. :rtype: List",
"params = {'LoadBalancerName': load_balancer_name} self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return self.get_list('DeregisterInstancesFromLoadBalancer', params,",
"The instance ID's of the EC2 instances to remove. :rtype:",
"in the same region as the Load Balancer Adding zones",
":param subnets: A list of subnet IDs in your VPC",
"the request \"\"\" params = {'LoadBalancerName': name} for index, port",
"implements this policy, the load balancer uses a special cookie",
"mnemonic name associated with the new load balancer :type zones:",
"connect_to_region(region_name, **kw_params): \"\"\" Given a valid region name, return a",
"Each int represents the port on the ELB to be",
"public IP addresses. Specify the value internal for this option",
"== 'SSL': params['Listeners.member.%d.SSLCertificateId' % i] = listener[4] return self.get_status('CreateLoadBalancerListeners', params)",
"'HealthCheck.Interval': health_check.interval, 'HealthCheck.UnhealthyThreshold': health_check.unhealthy_threshold, 'HealthCheck.HealthyThreshold': health_check.healthy_threshold} return self.get_object('ConfigureHealthCheck', params, HealthCheck)",
"The name of the zone(s) to remove. :rtype: List of",
"Service. .. note:: The region argument is overridden by the",
"of the zone(s) to add. :rtype: List of strings :return:",
"as the Load Balancer. Removing zones that are not registered",
"name, health_check): \"\"\" Define a health check for the EndPoints.",
"of strings :param subnets: A list of subnet IDs in",
"HealthCheck from boto.ec2.elb.listelement import ListElement from boto.regioninfo import RegionInfo, get_regions,",
"application-generated cookie. This policy can only be associated with HTTP",
"of instances for this Load Balancer. \"\"\" params = {'LoadBalancerName':",
"apply_security_groups_to_lb(self, name, security_groups): \"\"\" Applies security groups to the load",
"2006-2012 <NAME> http://garnaat.org/ # Copyright (c) 2012 Amazon.com, Inc. or",
"fol- # lowing conditions: # # The above copyright notice",
"Attaching subnets that are already registered with the Load Balancer",
"value.emit_interval elif attribute.lower() == 'connectiondraining': params['LoadBalancerAttributes.ConnectionDraining.Enabled'] = \\ value.enabled and",
"of the Load Balancer :type zones: List of strings :param",
"params = {} if load_balancer_names: self.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') return self.get_list('DescribeLoadBalancers',",
"if instances: self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return self.get_list('DescribeInstanceHealth', params, [('member', InstanceState)])",
"listener[4] return self.get_status('CreateLoadBalancerListeners', params) def delete_load_balancer(self, name): \"\"\" Delete a",
"to change. * crossZoneLoadBalancing - Boolean (true) * accessLog -",
"The attribute you wish to change. * crossZoneLoadBalancing - Boolean",
"params, None) def attach_lb_to_subnets(self, name, subnets): \"\"\" Attaches load balancer",
"a new connection to EC2 Load Balancing Service. .. note::",
"balancer inside a VPC, parameter zones must be set to",
":type attribute: string :param attribute: The attribute you wish to",
"listener[3] if protocol == 'HTTPS' or protocol == 'SSL': params['Listeners.member.%d.SSLCertificateId'",
"zones: List of strings :param zones: The name of the",
"associated with HTTP listeners. This policy is similar to the",
"params['LoadBalancerAttributes.AccessLog.Enabled'] = \\ value.enabled and 'true' or 'false' params['LoadBalancerAttributes.AccessLog.S3BucketName'] =",
"protocol = listener[2].upper() InstanceProtocol = listener[3].upper() params['Listeners.member.%d.LoadBalancerPort' % i] =",
"region as the Load Balancer Adding zones that are already",
"attribute): \"\"\"Gets an attribute of a Load Balancer This will",
"the Load Balancer has no effect. :type name: string :param",
"obtaining a # copy of this software and associated documentation",
"enable_availability_zones(self, load_balancer_name, zones_to_add): \"\"\" Add availability zones to an existing",
"def connect_to_region(region_name, **kw_params): \"\"\" Given a valid region name, return",
"OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"The name of the Load Balancer :type zones: List of",
"InstancePortNumber are integer values between 1 and 65535 - Protocol",
"== 'crosszoneloadbalancing': params['LoadBalancerAttributes.CrossZoneLoadBalancing.Enabled' ] = value elif attribute.lower() == 'accesslog':",
"the ELB to be removed :return: The status of the",
"= {'LoadBalancerName': load_balancer_name} self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return self.get_list('DeregisterInstancesFromLoadBalancer', params, [('member',",
"IP addresses. This option is only available for LoadBalancers attached",
"load balancer will be created in EC2. To create a",
"is specified in the policy configuration. None may be passed",
"The instance ID's of the EC2 instances to add. :rtype:",
"basestring): items = [items] for index, item in enumerate(items): params[label",
"AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #",
"'SSL', HTTP', or 'HTTPS'; SSLCertificateID is the ARN of a",
"to the policy created by CreateLBCookieStickinessPolicy, except that the lifetime",
"'PolicyTypeName': policy_type} for index, (name, value) in enumerate(policy_attributes.iteritems(), 1): params['PolicyAttributes.member.%d.AttributeName'",
"connection_cls=ELBConnection) def connect_to_region(region_name, **kw_params): \"\"\" Given a valid region name,",
"The status of the request \"\"\" if not listeners and",
":rtype: bool :return: Whether the operation succeeded or not \"\"\"",
":return: The attribute object of the ELB. \"\"\" from boto.ec2.elb.attributes",
"of the EC2 instances to remove. :rtype: List of strings",
"that contais the necessary attributes depending on the policy type.",
"are settings that are saved for your load balancer and",
"params, items, label): if isinstance(items, basestring): items = [items] for",
"on which the back-end server is listening with a new",
"balancers associated with your account. :type load_balancer_names: list :keyword load_balancer_names:",
"= {'CookieName': name, 'LoadBalancerName': lb_name, 'PolicyName': policy_name} return self.get_status('CreateAppCookieStickinessPolicy', params)",
"where LoadBalancerPortNumber and InstancePortNumber are integer values between 1 and",
"'AvailabilityZones.member.%d') obj = self.get_object('EnableAvailabilityZonesForLoadBalancer', params, LoadBalancerZones) return obj.zones def disable_availability_zones(self,",
"\\ value.timeout else: raise ValueError('InvalidAttribute', attribute) return self.get_status('ModifyLoadBalancerAttributes', params, verb='GET')",
"be enabled for any listeners. \"\"\" params = {'LoadBalancerName': lb_name,",
"# \"Software\"), to deal in the Software without restriction, including",
"protocol == 'SSL': params['Listeners.member.%d.SSLCertificateId' % i] = listener[4] return self.get_status('CreateLoadBalancerListeners',",
"{'LoadBalancerName': load_balancer_name} return self.get_object('DescribeLoadBalancerAttributes', params, LbAttributes) def get_lb_attribute(self, load_balancer_name, attribute):",
"'SecurityGroups.member.%d') load_balancer = self.get_object('CreateLoadBalancer', params, LoadBalancer) load_balancer.name = name load_balancer.listeners",
"lb_name, lb_port, policies): \"\"\" Associates, updates, or disables a policy",
":class:`boto.ec2.elb.loadbalancer.LoadBalancer` \"\"\" params = {} if load_balancer_names: self.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d')",
"return self.get_status('DeleteLoadBalancerListeners', params) def enable_availability_zones(self, load_balancer_name, zones_to_add): \"\"\" Add availability",
"return attributes.cross_zone_load_balancing.enabled if attribute.lower() == 'connectiondraining': return attributes.connection_draining return None",
"load balancer to create the listeners for :type listeners: List",
"certificate loaded into AWS IAM :rtype: :class:`boto.ec2.elb.loadbalancer.LoadBalancer` :return: The newly",
"\\ value.emit_interval elif attribute.lower() == 'connectiondraining': params['LoadBalancerAttributes.ConnectionDraining.Enabled'] = \\ value.enabled",
"def register_instances(self, load_balancer_name, instances): \"\"\" Add new Instances to an",
"be passed for cookie_expiration_period. \"\"\" params = {'LoadBalancerName': lb_name, 'PolicyName':",
"the request to the application server specified in the cookie.",
"on the ELB to be removed :return: The status of",
"(index + 1)] = item def get_all_load_balancers(self, load_balancer_names=None): \"\"\" Retrieve",
"do so, subject to the fol- # lowing conditions: #",
"or protocol == 'SSL': params['Listeners.member.%d.SSLCertificateId' % i] = listener[4] return",
"attribute \"\"\" attributes = self.get_all_lb_attributes(load_balancer_name) if attribute.lower() == 'accesslog': return",
"invalid region name is given \"\"\" for region in regions():",
"InstanceState from boto.ec2.elb.healthcheck import HealthCheck from boto.ec2.elb.listelement import ListElement from",
"SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE",
"attribute :rtype: bool :return: Whether the operation succeeded or not",
"This policy can only be associated with HTTP listeners. This",
"= '' return self.get_status('CreateLoadBalancerPolicy', params) def delete_lb_policy(self, lb_name, policy_name): \"\"\"",
"ELB to be removed :return: The status of the request",
"== 'crosszoneloadbalancing': return attributes.cross_zone_load_balancing.enabled if attribute.lower() == 'connectiondraining': return attributes.connection_draining",
":class:`boto.RegionInfo` instances \"\"\" return get_regions('elasticloadbalancing', connection_cls=ELBConnection) def connect_to_region(region_name, **kw_params): \"\"\"",
"the VPC that contains the subnet(s) specified. :type name: string",
"requests from the same user to that server. The validity",
"self.get_status('SetLoadBalancerPoliciesForBackendServer', params) def apply_security_groups_to_lb(self, name, security_groups): \"\"\" Applies security groups",
"params['LoadBalancerAttributes.ConnectionDraining.Timeout'] = \\ value.timeout else: raise ValueError('InvalidAttribute', attribute) return self.get_status('ModifyLoadBalancerAttributes',",
"subnets: The name of the subnet(s) to detach. :rtype: List",
"more subnets. Attaching subnets that are already registered with the",
"enumerate(listeners): i = index + 1 protocol = listener[2].upper() params['Listeners.member.%d.LoadBalancerPort'",
"subnets: The name of the subnet(s) to add. :rtype: List",
"complex_listeners=None): \"\"\" Creates a Listener (or group of listeners) for",
"the subnet(s) specified. :type name: string :param name: The mnemonic",
"subnet(s) specified. :type name: string :param name: The mnemonic name",
"updated list of zones for this Load Balancer. \"\"\" params",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE",
"name that resolves to private IP addresses. This option is",
"'PolicyNames.member.%d') else: params['PolicyNames'] = '' return self.get_status('SetLoadBalancerPoliciesForBackendServer', params) def apply_security_groups_to_lb(self,",
"from an existing Load Balancer. All zones must be in",
"port=None, proxy=None, proxy_port=None, proxy_user=None, proxy_pass=None, debug=0, https_connection_factory=None, region=None, path='/', security_token=None,",
"full listeners if complex_listeners: for index, listener in enumerate(complex_listeners): i",
"\"\"\" bool_reqs = ('crosszoneloadbalancing',) if attribute.lower() in bool_reqs: if isinstance(value,",
"Balancer has no effect. :type name: string :param name: The",
"of the Load Balancer to delete \"\"\" params = {'LoadBalancerName':",
"to EC2 Load Balancing Service. .. note:: The region argument",
"Copyright (c) 2012 Amazon.com, Inc. or its affiliates. # All",
"balancer for your account. By default the load balancer will",
"with a publicly resolvable DNS name, which resolves to public",
"and 'true' or 'false' params['LoadBalancerAttributes.ConnectionDraining.Timeout'] = \\ value.timeout else: raise",
"\"\"\" params = {'LoadBalancerName': lb_name, 'InstancePort': instance_port} if policies: self.build_list_params(params,",
"available regions for the ELB service. :rtype: list :return: A",
"default, Elastic Load Balancing creates an internet-facing LoadBalancer with a",
"RegionInfo(self, self.DefaultRegionName, self.DefaultRegionEndpoint) self.region = region super(ELBConnection, self).__init__(aws_access_key_id, aws_secret_access_key, is_secure,",
"InstanceInfo)]) def deregister_instances(self, load_balancer_name, instances): \"\"\" Remove Instances from an",
"or expires, the session stops being sticky until a new",
"terminates the specified listener's SSL connections. The specified certificate replaces",
"bool): if value: value = 'true' else: value = 'false'",
"item def get_all_load_balancers(self, load_balancer_names=None): \"\"\" Retrieve all load balancers associated",
"instances, 'Instances.member.%d.InstanceId') return self.get_list('DescribeInstanceHealth', params, [('member', InstanceState)]) def configure_health_check(self, name,",
"session lifetimes controlled by the lifetime of the browser (user-agent)",
"internal LoadBalancer with a DNS name that resolves to private",
":param scheme: The type of a LoadBalancer. By default, Elastic",
"or disables a policy with a listener on the load",
"= {'LoadBalancerName': load_balancer_name} self.build_list_params(params, zones_to_add, 'AvailabilityZones.member.%d') obj = self.get_object('EnableAvailabilityZonesForLoadBalancer', params,",
"connect to. :rtype: :class:`boto.ec2.ELBConnection` or ``None`` :return: A connection to",
"be removed :return: The status of the request \"\"\" params",
"params, LoadBalancerZones) return obj.zones def modify_lb_attribute(self, load_balancer_name, attribute, value): \"\"\"Changes",
"sends the request to a server that is chosen based",
"\"\"\" params = {'LoadBalancerName': name} self.build_list_params(params, subnets, 'Subnets.member.%d') return self.get_list('DetachLoadBalancerFromSubnets',",
":class:`boto.ec2.elb.healthcheck.HealthCheck` :param health_check: A HealthCheck object populated with the desired",
"= listener[3] if protocol == 'HTTPS' or protocol == 'SSL':",
"def deregister_instances(self, load_balancer_name, instances): \"\"\" Remove Instances from an existing",
"def delete_load_balancer(self, name): \"\"\" Delete a Load Balancer from your",
"Add new Instances to an existing Load Balancer. :type load_balancer_name:",
":return: list of state info for instances in this Load",
"zones from an Load Balancer. :type load_balancer_name: string :param load_balancer_name:",
"configuration. None may be passed for cookie_expiration_period. \"\"\" params =",
"or ``None`` :return: A connection to the given region, or",
"subnets: List of strings :param subnets: The name of the",
"of the special Elastic Load Balancing cookie follows the lifetime",
"load balancer implements this policy, the load balancer uses a",
"groups assigned to your LoadBalancer within your VPC. :type scheme:",
"'connectiondraining': return attributes.connection_draining return None def register_instances(self, load_balancer_name, instances): \"\"\"",
"FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN",
"same region as the Load Balancer. Removing zones that are",
"# Must specify one of the two options return None",
"region name is given \"\"\" for region in regions(): if",
"proxy_pass=None, debug=0, https_connection_factory=None, region=None, path='/', security_token=None, validate_certs=True, profile_name=None): \"\"\" Init",
"= listener[0] params['Listeners.member.%d.InstancePort' % i] = listener[1] params['Listeners.member.%d.Protocol' % i]",
"accessLog - :py:class:`AccessLogAttribute` instance * crossZoneLoadBalancing - Boolean * connectionDraining",
"name of the zone(s) to add. :rtype: List of strings",
":param name: The mnemonic name associated with the new load",
"sticky until a new application cookie is issued. \"\"\" params",
"one (1) policy can be associated with a listener. \"\"\"",
"'Instances.member.%d.InstanceId') return self.get_list('DeregisterInstancesFromLoadBalancer', params, [('member', InstanceInfo)]) def describe_instance_health(self, load_balancer_name, instances=None):",
"= {'LoadBalancerName': lb_name, 'PolicyName': policy_name} if cookie_expiration_period is not None:",
"balancer uses a special cookie to track the backend server",
"the same LoadBalancer and port. \"\"\" params = {'LoadBalancerName': lb_name,",
"params) def set_lb_policies_of_listener(self, lb_name, lb_port, policies): \"\"\" Associates, updates, or",
"you wish to see. * accessLog - :py:class:`AccessLogAttribute` instance *",
"to. :rtype: :class:`boto.ec2.ELBConnection` or ``None`` :return: A connection to the",
"policy must not be enabled for any listeners. \"\"\" params",
"until a new application cookie is issued. \"\"\" params =",
"the ARN of an SSL certificate loaded into AWS IAM",
"'AvailabilityZones.member.%d') obj = self.get_object('DisableAvailabilityZonesForLoadBalancer', params, LoadBalancerZones) return obj.zones def modify_lb_attribute(self,",
"params = {'LoadBalancerName': lb_name, 'PolicyName': policy_name} return self.get_status('DeleteLoadBalancerPolicy', params) def",
"delete_load_balancer(self, name): \"\"\" Delete a Load Balancer from your account.",
"{'LoadBalancerName': lb_name, 'LoadBalancerPort': lb_port} if len(policies): self.build_list_params(params, policies, 'PolicyNames.member.%d') else:",
"Currently only zero (0) or one (1) policy can be",
"Copyright (c) 2006-2012 <NAME> http://garnaat.org/ # Copyright (c) 2012 Amazon.com,",
"listener[2] if protocol == 'HTTPS' or protocol == 'SSL': params['Listeners.member.%d.SSLCertificateId'",
"of strings :param zones: The names of the availability zone(s)",
"updated list of instances for this Load Balancer. \"\"\" params",
"\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR",
"\"\"\" Generates a stickiness policy with sticky session lifetimes that",
"in enumerate(policy_attributes.iteritems(), 1): params['PolicyAttributes.member.%d.AttributeName' % index] = name params['PolicyAttributes.member.%d.AttributeValue' %",
"server specified in the cookie. If not, the load balancer",
"listeners if listeners: for index, listener in enumerate(listeners): i =",
"the current set of policies associated with a port on",
"this Load Balancer. \"\"\" params = {'LoadBalancerName': name} self.build_list_params(params, security_groups,",
"'SSL', 'HTTP', or 'HTTPS' - SSLCertificateId is the ARN of",
"{'LoadBalancerName': name} self.build_list_params(params, subnets, 'Subnets.member.%d') return self.get_list('AttachLoadBalancerToSubnets', params, None) def",
"params, LoadBalancerZones) return obj.zones def disable_availability_zones(self, load_balancer_name, zones_to_remove): \"\"\" Remove",
"protocol == 'SSL': params['Listeners.member.%d.SSLCertificateId' % i] = listener[4] if zones:",
"between 1 and 65535 - Protocol and InstanceProtocol is a",
"registered to an Load Balancer. :type load_balancer_name: string :param load_balancer_name:",
"lb_name, 'LoadBalancerPort': lb_port} if len(policies): self.build_list_params(params, policies, 'PolicyNames.member.%d') else: params['PolicyNames']",
"policy_type} for index, (name, value) in enumerate(policy_attributes.iteritems(), 1): params['PolicyAttributes.member.%d.AttributeName' %",
"back-end server is listening with a new set of policies.",
"application-generated cookie specified in the policy configuration. The load balancer",
"cookie when the application response includes a new application cookie.",
"values between 1 and 65535, Protocol is a string containing",
"policy_name} return self.get_status('CreateAppCookieStickinessPolicy', params) def create_lb_cookie_stickiness_policy(self, cookie_expiration_period, lb_name, policy_name): \"\"\"",
"based on the existing load balancing algorithm. A cookie is",
"= listener[2].upper() InstanceProtocol = listener[3].upper() params['Listeners.member.%d.LoadBalancerPort' % i] = listener[0]",
"when the application response includes a new application cookie. If",
"i] = listener[1] params['Listeners.member.%d.Protocol' % i] = listener[2] params['Listeners.member.%d.InstanceProtocol' %",
"region specified in the boto configuration file. \"\"\" if not",
"i = index + 1 protocol = listener[2].upper() InstanceProtocol =",
"Load Balancer :type name: string :param name: The name of",
"= {'LoadBalancerName': lb_name, 'LoadBalancerPort': lb_port, 'SSLCertificateId': ssl_certificate_id} return self.get_status('SetLoadBalancerListenerSSLCertificate', params)",
"be included # in all copies or substantial portions of",
"attached to an Amazon VPC. :type complex_listeners: List of tuples",
"the rights to use, copy, modify, merge, publish, dis- #",
"the availability zone(s) to add. :type listeners: List of tuples",
"= '' return self.get_status('SetLoadBalancerPoliciesForBackendServer', params) def apply_security_groups_to_lb(self, name, security_groups): \"\"\"",
"application server specified in the cookie. If not, the load",
"of the region to connect to. :rtype: :class:`boto.ec2.ELBConnection` or ``None``",
"\"\"\" params = {'LoadBalancerName': name} return self.get_status('DeleteLoadBalancer', params) def delete_load_balancer_listeners(self,",
"subject to the fol- # lowing conditions: # # The",
"listener[3] # Handle the full listeners if complex_listeners: for index,",
"Amazon.com, Inc. or its affiliates. # All Rights Reserved #",
"instances, 'Instances.member.%d.InstanceId') return self.get_list('DeregisterInstancesFromLoadBalancer', params, [('member', InstanceInfo)]) def describe_instance_health(self, load_balancer_name,",
"LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR",
"cookie to track the backend server instance for each request.",
"of an SSL certificate loaded into AWS IAM :return: The",
"the policy type. Policies are settings that are saved for",
"EC2 call for each method call. :type load_balancer_name: string :param",
"Boolean * connectionDraining - :py:class:`ConnectionDrainingAttribute` instance :rtype: Attribute dependent :return:",
"for your load balancer and that can be applied to",
"super(ELBConnection, self).__init__(aws_access_key_id, aws_secret_access_key, is_secure, port, proxy, proxy_port, proxy_user, proxy_pass, self.region.endpoint,",
"listeners=None, subnets=None, security_groups=None, scheme='internet-facing', complex_listeners=None): \"\"\" Create a new load",
"the Load Balancer Adding zones that are already registered with",
"def configure_health_check(self, name, health_check): \"\"\" Define a health check for",
"The name of the security group(s) to add. :rtype: List",
"on the policy type. Policies are settings that are saved",
"on the cookie expiration time, which is specified in the",
"groups that are already registered with the Load Balancer has",
"NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE",
"% i] = listener[1] params['Listeners.member.%d.Protocol' % i] = listener[2] if",
"its affiliates. # All Rights Reserved # # Permission is",
"create a load balancer inside a VPC, parameter zones must",
"An updated list of zones for this Load Balancer. \"\"\"",
"cookie is inserted into the response for binding subsequent requests",
"Each tuple contains three or four values, (LoadBalancerPortNumber, InstancePortNumber, Protocol,",
"Balancer. \"\"\" params = {'LoadBalancerName': load_balancer_name} self.build_list_params(params, zones_to_remove, 'AvailabilityZones.member.%d') obj",
"copies or substantial portions of the Software. # # THE",
"attribute) return self.get_status('ModifyLoadBalancerAttributes', params, verb='GET') def get_all_lb_attributes(self, load_balancer_name): \"\"\"Gets all",
"or the back-end application server. \"\"\" params = {'LoadBalancerName': lb_name,",
"Attribute dependent :return: The new value for the attribute \"\"\"",
"in the policy configuration. The load balancer only inserts a",
"of the security group(s) to add. :rtype: List of strings",
"to deal in the Software without restriction, including # without",
"listeners) :type name: string :param name: The name of the",
"the load balancer will be created in EC2. To create",
"instance :rtype: Attribute dependent :return: The new value for the",
"**kw_params): \"\"\" Given a valid region name, return a :class:`boto.ec2.elb.ELBConnection`.",
"existing load balancing algorithm. A cookie is inserted into the",
"LoadBalancer)]) def create_load_balancer(self, name, zones, listeners=None, subnets=None, security_groups=None, scheme='internet-facing', complex_listeners=None):",
"TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A",
"name} self.build_list_params(params, security_groups, 'SecurityGroups.member.%d') return self.get_list('ApplySecurityGroupsToLoadBalancer', params, None) def attach_lb_to_subnets(self,",
"value.timeout else: raise ValueError('InvalidAttribute', attribute) return self.get_status('ModifyLoadBalancerAttributes', params, verb='GET') def",
"proxy_port, proxy_user, proxy_pass, self.region.endpoint, debug, https_connection_factory, path, security_token, validate_certs=validate_certs, profile_name=profile_name)",
"instances will be returned. :rtype: List of :class:`boto.ec2.elb.instancestate.InstanceState` :return: list",
"will be created in EC2. To create a load balancer",
"depending on the policy type. Policies are settings that are",
"'false' params = {'LoadBalancerName': load_balancer_name} if attribute.lower() == 'crosszoneloadbalancing': params['LoadBalancerAttributes.CrossZoneLoadBalancing.Enabled'",
"removed :return: The status of the request \"\"\" params =",
"isinstance(value, bool): if value: value = 'true' else: value =",
"= \\ value.timeout else: raise ValueError('InvalidAttribute', attribute) return self.get_status('ModifyLoadBalancerAttributes', params,",
"subnets must not be None. The load balancer will be",
"Protocol is a string containing either 'TCP', 'SSL', HTTP', or",
"health_check.unhealthy_threshold, 'HealthCheck.HealthyThreshold': health_check.healthy_threshold} return self.get_object('ConfigureHealthCheck', params, HealthCheck) def set_lb_listener_SSL_certificate(self, lb_name,",
"LoadBalancer. The specified policy must not be enabled for any",
"def set_lb_policies_of_listener(self, lb_name, lb_port, policies): \"\"\" Associates, updates, or disables",
"The name of the subnet(s) to detach. :rtype: List of",
"listener on the load balancer. Currently only zero (0) or",
"zones: The names of the availability zone(s) to add. :type",
"= {'LoadBalancerName': name} # Handle the simple listeners if listeners:",
"'false' params['LoadBalancerAttributes.ConnectionDraining.Timeout'] = \\ value.timeout else: raise ValueError('InvalidAttribute', attribute) return",
"the Software without restriction, including # without limitation the rights",
"# Handle legacy listeners if listeners: for index, listener in",
"create the listeners for :type ports: List int :param ports:",
"Detaches load balancer from one or more subnets. :type name:",
"list of strings :param security_groups: The security groups assigned to",
"The name of the Load Balancer :type security_groups: List of",
"IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"for this option to create an internal LoadBalancer with a",
"policies): \"\"\" Associates, updates, or disables a policy with a",
"all available regions for the ELB service. :rtype: list :return:",
"the Load Balancer. Removing zones that are not registered with",
"params = {'LoadBalancerName': lb_name, 'LoadBalancerPort': lb_port, 'SSLCertificateId': ssl_certificate_id} return self.get_status('SetLoadBalancerListenerSSLCertificate',",
"value.s3_bucket_name params['LoadBalancerAttributes.AccessLog.S3BucketPrefix'] = \\ value.s3_bucket_prefix params['LoadBalancerAttributes.AccessLog.EmitInterval'] = \\ value.emit_interval elif",
"return self.get_list('AttachLoadBalancerToSubnets', params, None) def detach_lb_from_subnets(self, name, subnets): \"\"\" Detaches",
"zones_to_add): \"\"\" Add availability zones to an existing Load Balancer",
"load_balancer_name, attribute): \"\"\"Gets an attribute of a Load Balancer This",
"two options return None params = {'LoadBalancerName': name, 'Scheme': scheme}",
"for an existing Load Balancer :type name: string :param name:",
"(index + 1)] = port return self.get_status('DeleteLoadBalancerListeners', params) def enable_availability_zones(self,",
"* accessLog - :py:class:`AccessLogAttribute` instance * crossZoneLoadBalancing - Boolean *",
"will make an EC2 call for each method call. :type",
"load_balancer_name: string :param load_balancer_name: The name of the Load Balancer",
"value.enabled and 'true' or 'false' params['LoadBalancerAttributes.ConnectionDraining.Timeout'] = \\ value.timeout else:",
":return: An updated list of security groups for this Load",
"== 'SSL': params['Listeners.member.%d.SSLCertificateId' % i] = listener[3] # Handle the",
"string :param load_balancer_name: The name of the Load Balancer :rtype:",
"be specified when doing HTTPS. :type subnets: list of strings",
"'connectiondraining': params['LoadBalancerAttributes.ConnectionDraining.Enabled'] = \\ value.enabled and 'true' or 'false' params['LoadBalancerAttributes.ConnectionDraining.Timeout']",
"same user to that server. The validity of the cookie",
"self.build_list_params(params, policies, 'PolicyNames.member.%d') else: params['PolicyNames'] = '' return self.get_status('SetLoadBalancerPoliciesOfListener', params)",
"SSLCertificateId). Where: - LoadBalancerPortNumber and InstancePortNumber are integer values between",
"LoadBalancer with a publicly resolvable DNS name, which resolves to",
"zones that are not registered with the Load Balancer has",
"application cookie. If the application cookie is explicitly removed or",
"= {'LoadBalancerName': name, 'Scheme': scheme} # Handle legacy listeners if",
"Generates a stickiness policy with sticky session lifetimes controlled by",
"\"\"\" Applies security groups to the load balancer. Applying security",
"self.build_list_params(params, instances, 'Instances.member.%d.InstanceId') return self.get_list('RegisterInstancesWithLoadBalancer', params, [('member', InstanceInfo)]) def deregister_instances(self,",
"be in the same region as the Load Balancer. Removing",
"string :param attribute: The attribute you wish to change. *",
"policy, the load balancer uses a special cookie to track",
"balancer and that can be applied to the front-end listener,",
"request \"\"\" params = {'LoadBalancerName': name} for index, port in",
"HealthCheck object populated with the desired values. :rtype: :class:`boto.ec2.elb.healthcheck.HealthCheck` :return:",
"i] = listener[2] params['Listeners.member.%d.InstanceProtocol' % i] = listener[3] if protocol",
"An updated list of security groups for this Load Balancer.",
"else: params['PolicyNames'] = '' return self.get_status('SetLoadBalancerPoliciesForBackendServer', params) def apply_security_groups_to_lb(self, name,",
"params = {'LoadBalancerName': name} self.build_list_params(params, subnets, 'Subnets.member.%d') return self.get_list('DetachLoadBalancerFromSubnets', params,",
"for. If not provided, the state of all instances will",
"return self.get_status('SetLoadBalancerListenerSSLCertificate', params) def create_app_cookie_stickiness_policy(self, name, lb_name, policy_name): \"\"\" Generates",
"debug=0, https_connection_factory=None, region=None, path='/', security_token=None, validate_certs=True, profile_name=None): \"\"\" Init method",
"Attributes of a Load Balancer :type load_balancer_name: string :param load_balancer_name:",
"Retrieve all load balancers associated with your account. :type load_balancer_names:",
"to add. :rtype: List of strings :return: An updated list",
"in your VPC to attach to your LoadBalancer. :type security_groups:",
"self.get_list('DescribeLoadBalancers', params, [('member', LoadBalancer)]) def create_load_balancer(self, name, zones, listeners=None, subnets=None,",
"the policy configuration. The load balancer only inserts a new",
"The above copyright notice and this permission notice shall be",
"= listener[1] params['Listeners.member.%d.Protocol' % i] = listener[2] if protocol ==",
"certificate, and must be specified when doing HTTPS. :type complex_listeners:",
"from an existing Load Balancer. :type load_balancer_name: string :param load_balancer_name:",
"strings :param subnets: A list of subnet IDs in your",
"of a Load Balancer :type load_balancer_name: string :param load_balancer_name: The",
"OR OTHER DEALINGS # IN THE SOFTWARE. # \"\"\" This",
"or five values, (LoadBalancerPortNumber, InstancePortNumber, Protocol, InstanceProtocol, SSLCertificateId). Where: -",
"regions(): \"\"\" Get all available regions for the ELB service.",
"Load Balancing Service. .. note:: The region argument is overridden",
"Adding zones that are already registered with the Load Balancer",
"request, it first checks to see if this cookie is",
"{'LoadBalancerName': load_balancer_name} self.build_list_params(params, zones_to_remove, 'AvailabilityZones.member.%d') obj = self.get_object('DisableAvailabilityZonesForLoadBalancer', params, LoadBalancerZones)"
] |
[
"a list all available versions of a basis set') subp.add_argument('basis',",
"# list-basis-sets subcommand subp = subparsers.add_parser('list-basis-sets', help='Output a list all",
"the specified substring') subp.add_argument('-e', '--elements', help='Limit the basis set list",
"a companion/auxiliary basis by primary basis and role') subp.add_argument('basis', help='Name",
"# Actually generate the output output = bse_cli_handle_subcmd(args) if args.output:",
"to output. Default is all defined in the given basis')",
"family for').completer = cli_bsname_completer # get-versions subcommand subp = subparsers.add_parser('get-versions',",
"type=str.lower, help='The basis set family to the get the notes",
"to only basis sets that contain all the given elements')",
"be read') subp.add_argument('-n', '--no-description', action='store_true', help='Print only the format names')",
"= subparsers.add_parser('get-notes', help='Output the notes for a basis set') subp.add_argument('basis',",
"subp = subparsers.add_parser('list-ref-formats', help='Output a list all available reference formats",
"name contains the specified substring') subp.add_argument('-e', '--elements', help='Limit the basis",
"basis set to output').completer = cli_bsname_completer subp.add_argument('fmt', help='Which format to",
"basis set to output. Default is all defined in the",
"line interface for the basis set exchange ''' import argparse",
"cli_bsname_completer subp.add_argument('role', help='Role of the auxiliary basis to look for').completer",
"help='Role of the auxiliary basis to look for').completer = cli_role_completer",
"'choices' argument in add_argument. I could use it # for",
"# list-reader-formats subp = subparsers.add_parser('list-reader-formats', help='Output a list of basis",
"help='Output a list all available roles and descriptions') subp.add_argument('-n', '--no-description',",
"################################# # Converting basis sets ################################# subp = subparsers.add_parser('convert-basis', help='Convert",
"directory to use') parser.add_argument('-o', '--output', metavar='PATH', help='Output to given file",
"output filename').completer = cli_write_fmt_completer ################################# # Creating bundles ################################# subp",
"format names') # list-ref-formats subcommand subp = subparsers.add_parser('list-ref-formats', help='Output a",
"names') # list-reader-formats subp = subparsers.add_parser('list-reader-formats', help='Output a list of",
"sets and descriptions') subp.add_argument('-n', '--no-description', action='store_true', help='Print only the basis",
"file') subp.add_argument('--in-fmt', type=str, default=None, help='Input format (default: autodetected from input",
"of the basis set to output the references for').completer =",
"subp.add_argument('fmt', help='Which format to output the basis set as').completer =",
"and make sure basis sets, roles, etc, are valid args",
"and metadata ######################################## # get-data-dir subparsers.add_parser('get-data-dir', help='Output the default data",
"the specified role').completer = cli_role_completer subp.add_argument('-s', '--substr', help='Limit the basis",
"notes for a basis set') subp.add_argument('basis', help='Name of the basis",
"the references for') # get-info subcommand subp = subparsers.add_parser('get-info', help='Output",
"subp = subparsers.add_parser('get-versions', help='Output a list all available versions of",
"= subparsers.add_parser('lookup-by-role', help='Lookup a companion/auxiliary basis by primary basis and",
"default=None, help='Input format (default: autodetected from input filename').completer = cli_read_fmt_completer",
"the basis set exchange ''' import argparse import argcomplete from",
"NOTE: I am deliberately not using the 'choices' argument in",
"basis set families') # lookup-by-role subp = subparsers.add_parser('lookup-by-role', help='Lookup a",
"the header at the top') subp.add_argument('--unc-gen', action='store_true', help='Remove general contractions')",
"set to list the versions of').completer = cli_bsname_completer subp.add_argument('-n', '--no-description',",
"'--elements', help='Limit the basis set list to only basis sets",
"and handle the args args = parser.parse_args() # Check and",
"use') parser.add_argument('-o', '--output', metavar='PATH', help='Output to given file rather than",
"args.output: with open(args.output, 'w', encoding='utf-8') as outfile: outfile.write(output) else: print(output)",
"all available versions of a basis set') subp.add_argument('basis', help='Name of",
"to only basis sets whose name contains the specified substring')",
"a list available basis set formats that can be written')",
"to output the basis set as').completer = cli_write_fmt_completer subp.add_argument('--elements', help='Which",
"def run_bse_cli(): ################################################################################################ # NOTE: I am deliberately not using",
"of basis sets') subp.add_argument('fmt', help='Which format to output the basis",
"only the reference format names') # list-roles subcommand subp =",
"basis set') subp.add_argument('-n', '--no-description', action='store_true', help='Print only the format names')",
"action='store_true', help='Print only the basis set names') subp.add_argument('-f', '--family', help='Limit",
"= cli_bsname_completer subp.add_argument('fmt', help='Which format to output the basis set",
"help='Limit the basis set list to only the specified role').completer",
"subp = subparsers.add_parser('list-basis-sets', help='Output a list all available basis sets",
"basis set') subp.add_argument('basis', help='Name of the basis set to output",
"archive to create (zip or tbz)') ############################# # DONE WITH",
"data directory to use') parser.add_argument('-o', '--output', metavar='PATH', help='Output to given",
"'--role', help='Limit the basis set list to only the specified",
"available basis set formats that can be written') subp.add_argument('-n', '--no-description',",
"the basis set to get the references for') # get-info",
"set file') subp.add_argument('--in-fmt', type=str, default=None, help='Input format (default: autodetected from",
"help='Name of the basis set to output the notes for').completer",
"that manually so that error output is consistent and clean",
"subp = subparsers.add_parser('list-reader-formats', help='Output a list of basis set formats",
"look for').completer = cli_role_completer ################################# # Output of info #################################",
"the default data directory of this package') # list-basis-sets subcommand",
"# NOTE: I am deliberately not using the 'choices' argument",
"one format to another') subp.add_argument('input_file', type=str, help='Basis set file to",
"references for') # get-info subcommand subp = subparsers.add_parser('get-info', help='Output general",
"set exchange ''' import argparse import argcomplete from .. import",
"the notes for').completer = cli_bsname_completer # get-family subcommand subp =",
"######################################## # Main global options ######################################## parser = argparse.ArgumentParser(description='Description of",
"basis set list to only the specified role').completer = cli_role_completer",
"all of that manually so that error output is consistent",
"the family for').completer = cli_bsname_completer # get-versions subcommand subp =",
"than stdout') subparsers = parser.add_subparsers(metavar='subcommand', dest='subcmd') subparsers.required = True #",
"''' Command line interface for the basis set exchange '''",
"references as').completer = cli_reffmt_completer subp.add_argument('--elements', help='Which elements to output the",
"a list all available reference formats and descriptions') subp.add_argument('-n', '--no-description',",
"# get-family subcommand subp = subparsers.add_parser('get-family', help='Output the family of",
"subp = subparsers.add_parser('get-family-notes', help='Get the notes of a family of",
"the basis set as').completer = cli_write_fmt_completer subp.add_argument('reffmt', help='Which format to",
"= cli_bsname_completer # get-family subcommand subp = subparsers.add_parser('get-family', help='Output the",
"the format names') # list-writer-formats subcommand subp = subparsers.add_parser('list-writer-formats', help='Output",
"file to convert') subp.add_argument('output_file', type=str, help='Converted basis set file') subp.add_argument('--in-fmt',",
"subcommand subp = subparsers.add_parser('list-writer-formats', help='Output a list available basis set",
"'--substr', help='Limit the basis set list to only basis sets",
"output the info for').completer = cli_bsname_completer # get-notes subcommand subp",
"basis sets and descriptions') subp.add_argument('-n', '--no-description', action='store_true', help='Print only the",
"the notes for a basis set') subp.add_argument('basis', help='Name of the",
"basis set formats that can be read') subp.add_argument('-n', '--no-description', action='store_true',",
"of the basis set to output. Default is the latest",
"subp.add_argument('basis', help='Name of the basis set to output the references",
"general contractions') subp.add_argument('--make-gen', action='store_true', help='Make the basis set as generally-contracted",
"parser.add_argument('-d', '--data-dir', metavar='PATH', help='Override which data directory to use') parser.add_argument('-o',",
"get-family-notes subcommand subp = subparsers.add_parser('get-family-notes', help='Get the notes of a",
"argparse import argcomplete from .. import version from .bse_handlers import",
"subparsers.add_parser('list-basis-sets', help='Output a list all available basis sets and descriptions')",
"basis set list to only basis sets whose name contains",
"set list to only basis sets whose name contains the",
"type=str, help='Converted basis set file') subp.add_argument('--in-fmt', type=str, default=None, help='Input format",
"subcommand subp = subparsers.add_parser('get-info', help='Output general info and metadata for",
"basis set as').completer = cli_write_fmt_completer subp.add_argument('reffmt', help='Which format to output",
"can be read') subp.add_argument('-n', '--no-description', action='store_true', help='Print only the format",
"subparsers.add_parser('list-roles', help='Output a list all available roles and descriptions') subp.add_argument('-n',",
"all available basis sets and descriptions') subp.add_argument('-n', '--no-description', action='store_true', help='Print",
"output. Default is the latest version') subp.add_argument('--noheader', action='store_true', help='Do not",
"to output the references as').completer = cli_reffmt_completer subp.add_argument('bundle_file', help='Bundle/Archive file",
"# Converting basis sets ################################# subp = subparsers.add_parser('convert-basis', help='Convert basis",
"the given basis') subp.add_argument('--version', help='Which version of the basis set",
"parser.add_argument('-o', '--output', metavar='PATH', help='Output to given file rather than stdout')",
"package') # list-basis-sets subcommand subp = subparsers.add_parser('list-basis-sets', help='Output a list",
"############################# # DONE WITH SUBCOMMANDS ############################# # setup autocomplete argcomplete.autocomplete(parser,",
"it for basis set names. Therefore, I handle # all",
"the family of a basis set') subp.add_argument('basis', help='Name of the",
"# Now parse and handle the args args = parser.parse_args()",
"action='store_true', help='Make the basis set as generally-contracted as possible') #",
"that can be read') subp.add_argument('-n', '--no-description', action='store_true', help='Print only the",
"of the basis set to output. Default is all defined",
"from output filename').completer = cli_write_fmt_completer ################################# # Creating bundles #################################",
"basis sets, roles, etc, are valid args = cli_check_normalize_args(args) #",
"list all available versions of a basis set') subp.add_argument('basis', help='Name",
"cli_write_fmt_completer subp.add_argument('reffmt', help='Which format to output the references as').completer =",
"'--no-description', action='store_true', help='Print only the role names') ######################################## # Listing",
"list-reader-formats subp = subparsers.add_parser('list-reader-formats', help='Output a list of basis set",
"directory of this package') # list-basis-sets subcommand subp = subparsers.add_parser('list-basis-sets',",
"numbers') # get-family-notes subcommand subp = subparsers.add_parser('get-family-notes', help='Get the notes",
"subcommand subp = subparsers.add_parser('get-refs', help='Output references for a basis set')",
"set to output the notes for').completer = cli_bsname_completer # get-family",
"= subparsers.add_parser('list-basis-sets', help='Output a list all available basis sets and",
"of the basis set to output the notes for').completer =",
"'--family', help='Limit the basis set list to only the specified",
"basis') subp.add_argument('--version', help='Which version of the basis set to output.",
"= subparsers.add_parser('convert-basis', help='Convert basis set files from one format to",
"' + version()) parser.add_argument('-d', '--data-dir', metavar='PATH', help='Override which data directory",
"the version numbers') # get-family-notes subcommand subp = subparsers.add_parser('get-family-notes', help='Get",
"for basis set names. Therefore, I handle # all of",
"info ######################################## # list-formats subcommand subp = subparsers.add_parser('list-formats', help='Output a",
"general info and metadata for a basis set') subp.add_argument('basis', help='Name",
"'--no-description', action='store_true', help='Print only the version numbers') # get-family-notes subcommand",
"+ version()) parser.add_argument('-d', '--data-dir', metavar='PATH', help='Override which data directory to",
"############################# # setup autocomplete argcomplete.autocomplete(parser, validator=cli_case_insensitive_validator) # Now parse and",
"however I wouldn't want to use it for basis set",
".bse_handlers import bse_cli_handle_subcmd from .check import cli_check_normalize_args from .complete import",
"to use it for basis set names. Therefore, I handle",
"subcommand subp = subparsers.add_parser('get-basis', help='Output a formatted basis set') subp.add_argument('basis',",
"in the given basis.') subp.add_argument('--version', help='Which version of the basis",
"subparsers.add_parser('list-families', help='Output a list all available basis set families') #",
"and descriptions') subp.add_argument('-n', '--no-description', action='store_true', help='Print only the role names')",
"args = cli_check_normalize_args(args) # Actually generate the output output =",
"open(args.output, 'w', encoding='utf-8') as outfile: outfile.write(output) else: print(output) return 0",
"whose name contains the specified substring') subp.add_argument('-e', '--elements', help='Limit the",
"# Listing of data-independent info ######################################## # list-formats subcommand subp",
"read') subp.add_argument('-n', '--no-description', action='store_true', help='Print only the format names') #",
"references for. Default is all defined in the given basis.')",
"of the auxiliary basis to look for').completer = cli_role_completer #################################",
"consistent and clean ################################################################################################ ######################################## # Main global options ########################################",
"the basis set list to only basis sets that contain",
"to output the family for').completer = cli_bsname_completer # get-versions subcommand",
"for').completer = cli_bsname_completer # get-family subcommand subp = subparsers.add_parser('get-family', help='Output",
"help='Limit the basis set list to only the specified family').completer",
"help='Optimize general contractions') subp.add_argument('--make-gen', action='store_true', help='Make the basis set as",
"lookup-by-role subp = subparsers.add_parser('lookup-by-role', help='Lookup a companion/auxiliary basis by primary",
"= subparsers.add_parser('get-info', help='Output general info and metadata for a basis",
"cli_family_completer, cli_role_completer, cli_bsname_completer, cli_write_fmt_completer, cli_read_fmt_completer, cli_reffmt_completer) def run_bse_cli(): ################################################################################################ #",
"so that error output is consistent and clean ################################################################################################ ########################################",
"a basis set') subp.add_argument('-n', '--no-description', action='store_true', help='Print only the format",
"cli_reffmt_completer subp.add_argument('bundle_file', help='Bundle/Archive file to create') subp.add_argument('--archive-type', help='Override the type",
"for formats, etc, however I wouldn't want to use it",
"cli_bsname_completer subp.add_argument('-n', '--no-description', action='store_true', help='Print only the version numbers') #",
"subp.add_argument('-n', '--no-description', action='store_true', help='Print only the basis set names') subp.add_argument('-f',",
"subp.add_argument('--archive-type', help='Override the type of archive to create (zip or",
"basis for').completer = cli_bsname_completer subp.add_argument('role', help='Role of the auxiliary basis",
"for').completer = cli_bsname_completer subp.add_argument('reffmt', help='Which format to output the references",
"DONE WITH SUBCOMMANDS ############################# # setup autocomplete argcomplete.autocomplete(parser, validator=cli_case_insensitive_validator) #",
"setup autocomplete argcomplete.autocomplete(parser, validator=cli_case_insensitive_validator) # Now parse and handle the",
"info for').completer = cli_bsname_completer # get-notes subcommand subp = subparsers.add_parser('get-notes',",
"the latest version') subp.add_argument('--noheader', action='store_true', help='Do not output the header",
"help='Output format (default: autodetected from output filename').completer = cli_write_fmt_completer #################################",
"list all available roles and descriptions') subp.add_argument('-n', '--no-description', action='store_true', help='Print",
"################################################################################################ # NOTE: I am deliberately not using the 'choices'",
"# get-basis subcommand subp = subparsers.add_parser('get-basis', help='Output a formatted basis",
"list all available reference formats and descriptions') subp.add_argument('-n', '--no-description', action='store_true',",
"metadata for a basis set') subp.add_argument('basis', help='Name of the basis",
"subparsers = parser.add_subparsers(metavar='subcommand', dest='subcmd') subparsers.required = True # https://bugs.python.org/issue9253#msg186387 ########################################",
"formats that can be read') subp.add_argument('-n', '--no-description', action='store_true', help='Print only",
"subp = subparsers.add_parser('get-notes', help='Output the notes for a basis set')",
"= cli_check_normalize_args(args) # Actually generate the output output = bse_cli_handle_subcmd(args)",
"sets') subp.add_argument('family', type=str.lower, help='The basis set family to the get",
"header at the top') subp.add_argument('--unc-gen', action='store_true', help='Remove general contractions') subp.add_argument('--unc-spdf',",
"help='Output the notes for a basis set') subp.add_argument('basis', help='Name of",
"we want the auxiliary basis for').completer = cli_bsname_completer subp.add_argument('role', help='Role",
"to list the versions of').completer = cli_bsname_completer subp.add_argument('-n', '--no-description', action='store_true',",
"contractions') subp.add_argument('--unc-spdf', action='store_true', help='Remove combined sp, spd, ... contractions') subp.add_argument('--unc-seg',",
"subp = subparsers.add_parser('convert-basis', help='Convert basis set files from one format",
"default data directory of this package') # list-basis-sets subcommand subp",
"action='store_true', help='Print only the format names') # list-writer-formats subcommand subp",
"for').completer = cli_bsname_completer subp.add_argument('role', help='Role of the auxiliary basis to",
"only basis sets whose name contains the specified substring') subp.add_argument('-e',",
"the basis set to output. Default is all defined in",
"to another') subp.add_argument('input_file', type=str, help='Basis set file to convert') subp.add_argument('output_file',",
"= cli_read_fmt_completer subp.add_argument('--out-fmt', type=str, default=None, help='Output format (default: autodetected from",
"args args = parser.parse_args() # Check and make sure basis",
"format names') # list-roles subcommand subp = subparsers.add_parser('list-roles', help='Output a",
"help='Which format to output the references as').completer = cli_reffmt_completer subp.add_argument('bundle_file',",
"of the basis set to output').completer = cli_bsname_completer subp.add_argument('fmt', help='Which",
"families') # lookup-by-role subp = subparsers.add_parser('lookup-by-role', help='Lookup a companion/auxiliary basis",
"of that manually so that error output is consistent and",
"of archive to create (zip or tbz)') ############################# # DONE",
"subp.add_argument('-n', '--no-description', action='store_true', help='Print only the reference format names') #",
"help='Which format to output the references as').completer = cli_reffmt_completer subp.add_argument('--elements',",
"deliberately not using the 'choices' argument in add_argument. I could",
"help='Convert basis set files from one format to another') subp.add_argument('input_file',",
"SUBCOMMANDS ############################# # setup autocomplete argcomplete.autocomplete(parser, validator=cli_case_insensitive_validator) # Now parse",
"set names. Therefore, I handle # all of that manually",
"(default: autodetected from output filename').completer = cli_write_fmt_completer ################################# # Creating",
"action='store_true', help='Print only the format names') # list-reader-formats subp =",
"companion/auxiliary basis by primary basis and role') subp.add_argument('basis', help='Name of",
"= subparsers.add_parser('get-basis', help='Output a formatted basis set') subp.add_argument('basis', help='Name of",
"subp = subparsers.add_parser('create-bundle', help='Create a bundle of basis sets') subp.add_argument('fmt',",
"subparsers.required = True # https://bugs.python.org/issue9253#msg186387 ######################################## # Listing of data-independent",
"subp.add_argument('--elements', help='Which elements of the basis set to output. Default",
"not output the header at the top') subp.add_argument('--unc-gen', action='store_true', help='Remove",
"set') subp.add_argument('basis', help='Name of the basis set to output the",
"from .complete import (cli_case_insensitive_validator, cli_family_completer, cli_role_completer, cli_bsname_completer, cli_write_fmt_completer, cli_read_fmt_completer, cli_reffmt_completer)",
"help='Output a list of basis set formats that can be",
"Check and make sure basis sets, roles, etc, are valid",
"= subparsers.add_parser('list-ref-formats', help='Output a list all available reference formats and",
"= cli_write_fmt_completer ################################# # Creating bundles ################################# subp = subparsers.add_parser('create-bundle',",
"set families') # lookup-by-role subp = subparsers.add_parser('lookup-by-role', help='Lookup a companion/auxiliary",
"parser.add_argument('-V', action='version', version='basis_set_exchange ' + version()) parser.add_argument('-d', '--data-dir', metavar='PATH', help='Override",
"get-refs subcommand subp = subparsers.add_parser('get-refs', help='Output references for a basis",
"= subparsers.add_parser('get-versions', help='Output a list all available versions of a",
"to only the specified role').completer = cli_role_completer subp.add_argument('-s', '--substr', help='Limit",
"''' import argparse import argcomplete from .. import version from",
"help='Output the family of a basis set') subp.add_argument('basis', help='Name of",
"basis sets') subp.add_argument('family', type=str.lower, help='The basis set family to the",
"only the specified family').completer = cli_family_completer subp.add_argument('-r', '--role', help='Limit the",
"action='store_true', help='Print only the version numbers') # get-family-notes subcommand subp",
"your program') parser.add_argument('-V', action='version', version='basis_set_exchange ' + version()) parser.add_argument('-d', '--data-dir',",
"cli_read_fmt_completer subp.add_argument('--out-fmt', type=str, default=None, help='Output format (default: autodetected from output",
"general contractions') subp.add_argument('--unc-spdf', action='store_true', help='Remove combined sp, spd, ... contractions')",
"# get-info subcommand subp = subparsers.add_parser('get-info', help='Output general info and",
"basis by primary basis and role') subp.add_argument('basis', help='Name of the",
"basis set to get the references for') # get-info subcommand",
"formats that can be written') subp.add_argument('-n', '--no-description', action='store_true', help='Print only",
"subp.add_argument('-f', '--family', help='Limit the basis set list to only the",
"use it # for formats, etc, however I wouldn't want",
"################################# # Output of info ################################# # get-basis subcommand subp",
"want the auxiliary basis for').completer = cli_bsname_completer subp.add_argument('role', help='Role of",
"all available basis set families') # lookup-by-role subp = subparsers.add_parser('lookup-by-role',",
"basis set formats that can be used with obtaining a",
"notes of a family of basis sets') subp.add_argument('family', type=str.lower, help='The",
"help='Remove combined sp, spd, ... contractions') subp.add_argument('--unc-seg', action='store_true', help='Remove general",
"latest version') subp.add_argument('--noheader', action='store_true', help='Do not output the header at",
"set') subp.add_argument('basis', help='Name of the basis set to output').completer =",
"subparsers.add_parser('create-bundle', help='Create a bundle of basis sets') subp.add_argument('fmt', help='Which format",
"######################################## parser = argparse.ArgumentParser(description='Description of your program') parser.add_argument('-V', action='version', version='basis_set_exchange",
"cli_role_completer, cli_bsname_completer, cli_write_fmt_completer, cli_read_fmt_completer, cli_reffmt_completer) def run_bse_cli(): ################################################################################################ # NOTE:",
"the basis set names') subp.add_argument('-f', '--family', help='Limit the basis set",
"subp.add_argument('-r', '--role', help='Limit the basis set list to only the",
"of info ################################# # get-basis subcommand subp = subparsers.add_parser('get-basis', help='Output",
"# DONE WITH SUBCOMMANDS ############################# # setup autocomplete argcomplete.autocomplete(parser, validator=cli_case_insensitive_validator)",
"basis set as').completer = cli_write_fmt_completer subp.add_argument('--elements', help='Which elements of the",
"... contractions') subp.add_argument('--unc-seg', action='store_true', help='Remove general contractions') subp.add_argument('--opt-gen', action='store_true', help='Optimize",
"Therefore, I handle # all of that manually so that",
"written') subp.add_argument('-n', '--no-description', action='store_true', help='Print only the format names') #",
"subp.add_argument('--unc-spdf', action='store_true', help='Remove combined sp, spd, ... contractions') subp.add_argument('--unc-seg', action='store_true',",
"cli_write_fmt_completer ################################# # Creating bundles ################################# subp = subparsers.add_parser('create-bundle', help='Create",
"subparsers.add_parser('get-versions', help='Output a list all available versions of a basis",
"import version from .bse_handlers import bse_cli_handle_subcmd from .check import cli_check_normalize_args",
"of the basis set to output the family for').completer =",
"of basis sets') subp.add_argument('family', type=str.lower, help='The basis set family to",
"substring') subp.add_argument('-e', '--elements', help='Limit the basis set list to only",
"used with obtaining a basis set') subp.add_argument('-n', '--no-description', action='store_true', help='Print",
"# lookup-by-role subp = subparsers.add_parser('lookup-by-role', help='Lookup a companion/auxiliary basis by",
"action='store_true', help='Print only the reference format names') # list-roles subcommand",
"cli_reffmt_completer subp.add_argument('--elements', help='Which elements to output the references for. Default",
"subcommand subp = subparsers.add_parser('list-roles', help='Output a list all available roles",
"a formatted basis set') subp.add_argument('basis', help='Name of the basis set",
"family of basis sets') subp.add_argument('family', type=str.lower, help='The basis set family",
"file to create') subp.add_argument('--archive-type', help='Override the type of archive to",
"help='Print only the format names') # list-writer-formats subcommand subp =",
"to create (zip or tbz)') ############################# # DONE WITH SUBCOMMANDS",
"bse_cli_handle_subcmd(args) if args.output: with open(args.output, 'w', encoding='utf-8') as outfile: outfile.write(output)",
"subp.add_argument('-n', '--no-description', action='store_true', help='Print only the format names') # list-ref-formats",
"args = parser.parse_args() # Check and make sure basis sets,",
"is all defined in the given basis.') subp.add_argument('--version', help='Which version",
"Default is the latest version') subp.add_argument('--noheader', action='store_true', help='Do not output",
"help='Output a list all available versions of a basis set')",
"to convert') subp.add_argument('output_file', type=str, help='Converted basis set file') subp.add_argument('--in-fmt', type=str,",
"the reference format names') # list-roles subcommand subp = subparsers.add_parser('list-roles',",
"list-basis-sets subcommand subp = subparsers.add_parser('list-basis-sets', help='Output a list all available",
"for the basis set exchange ''' import argparse import argcomplete",
"create') subp.add_argument('--archive-type', help='Override the type of archive to create (zip",
"set') subp.add_argument('basis', help='Name of the basis set to list the",
"basis set names. Therefore, I handle # all of that",
"convert') subp.add_argument('output_file', type=str, help='Converted basis set file') subp.add_argument('--in-fmt', type=str, default=None,",
"subp.add_argument('basis', help='Name of the basis set to output the info",
"sets that contain all the given elements') # list-families subcommand",
"the basis set to output the notes for').completer = cli_bsname_completer",
"contain all the given elements') # list-families subcommand subparsers.add_parser('list-families', help='Output",
"help='Output a list all available reference formats and descriptions') subp.add_argument('-n',",
"from input filename').completer = cli_read_fmt_completer subp.add_argument('--out-fmt', type=str, default=None, help='Output format",
"parser = argparse.ArgumentParser(description='Description of your program') parser.add_argument('-V', action='version', version='basis_set_exchange '",
"using the 'choices' argument in add_argument. I could use it",
"which data directory to use') parser.add_argument('-o', '--output', metavar='PATH', help='Output to",
"the basis set list to only basis sets whose name",
"defined in the given basis.') subp.add_argument('--version', help='Which version of the",
"help='Which format to output the basis set as').completer = cli_write_fmt_completer",
"################################################################################################ ######################################## # Main global options ######################################## parser = argparse.ArgumentParser(description='Description",
"subparsers.add_parser('get-basis', help='Output a formatted basis set') subp.add_argument('basis', help='Name of the",
"basis set exchange ''' import argparse import argcomplete from ..",
"list to only basis sets whose name contains the specified",
"a family of basis sets') subp.add_argument('family', type=str.lower, help='The basis set",
"######################################## # Listing of data-independent info ######################################## # list-formats subcommand",
"set as').completer = cli_write_fmt_completer subp.add_argument('--elements', help='Which elements of the basis",
"for').completer = cli_bsname_completer # get-versions subcommand subp = subparsers.add_parser('get-versions', help='Output",
"# list-ref-formats subcommand subp = subparsers.add_parser('list-ref-formats', help='Output a list all",
"to get the references for') # get-info subcommand subp =",
"set') subp.add_argument('-n', '--no-description', action='store_true', help='Print only the format names') #",
"references as').completer = cli_reffmt_completer subp.add_argument('bundle_file', help='Bundle/Archive file to create') subp.add_argument('--archive-type',",
".. import version from .bse_handlers import bse_cli_handle_subcmd from .check import",
"that error output is consistent and clean ################################################################################################ ######################################## #",
"the 'choices' argument in add_argument. I could use it #",
"True # https://bugs.python.org/issue9253#msg186387 ######################################## # Listing of data-independent info ########################################",
"subp.add_argument('--opt-gen', action='store_true', help='Optimize general contractions') subp.add_argument('--make-gen', action='store_true', help='Make the basis",
"list-roles subcommand subp = subparsers.add_parser('list-roles', help='Output a list all available",
"of').completer = cli_bsname_completer subp.add_argument('-n', '--no-description', action='store_true', help='Print only the version",
"I could use it # for formats, etc, however I",
"= subparsers.add_parser('get-family-notes', help='Get the notes of a family of basis",
"type=str, default=None, help='Output format (default: autodetected from output filename').completer =",
"version from .bse_handlers import bse_cli_handle_subcmd from .check import cli_check_normalize_args from",
"= cli_role_completer subp.add_argument('-s', '--substr', help='Limit the basis set list to",
"action='store_true', help='Remove general contractions') subp.add_argument('--opt-gen', action='store_true', help='Optimize general contractions') subp.add_argument('--make-gen',",
"the basis set to output the references for').completer = cli_bsname_completer",
"the info for').completer = cli_bsname_completer # get-notes subcommand subp =",
"of this package') # list-basis-sets subcommand subp = subparsers.add_parser('list-basis-sets', help='Output",
"type=str, default=None, help='Input format (default: autodetected from input filename').completer =",
"for') # get-info subcommand subp = subparsers.add_parser('get-info', help='Output general info",
"the get the notes of').completer = cli_family_completer ################################# # Converting",
"help='Remove general contractions') subp.add_argument('--opt-gen', action='store_true', help='Optimize general contractions') subp.add_argument('--make-gen', action='store_true',",
"handle the args args = parser.parse_args() # Check and make",
"subp = subparsers.add_parser('lookup-by-role', help='Lookup a companion/auxiliary basis by primary basis",
"# list-formats subcommand subp = subparsers.add_parser('list-formats', help='Output a list of",
"with obtaining a basis set') subp.add_argument('-n', '--no-description', action='store_true', help='Print only",
"import cli_check_normalize_args from .complete import (cli_case_insensitive_validator, cli_family_completer, cli_role_completer, cli_bsname_completer, cli_write_fmt_completer,",
"subp.add_argument('--version', help='Which version of the basis set to get the",
"sets whose name contains the specified substring') subp.add_argument('-e', '--elements', help='Limit",
"as').completer = cli_write_fmt_completer subp.add_argument('--elements', help='Which elements of the basis set",
"filename').completer = cli_read_fmt_completer subp.add_argument('--out-fmt', type=str, default=None, help='Output format (default: autodetected",
"add_argument. I could use it # for formats, etc, however",
"the basis set to output the family for').completer = cli_bsname_completer",
"subparsers.add_parser('list-reader-formats', help='Output a list of basis set formats that can",
"WITH SUBCOMMANDS ############################# # setup autocomplete argcomplete.autocomplete(parser, validator=cli_case_insensitive_validator) # Now",
"defined in the given basis') subp.add_argument('--version', help='Which version of the",
"help='Override the type of archive to create (zip or tbz)')",
"# Creating bundles ################################# subp = subparsers.add_parser('create-bundle', help='Create a bundle",
"the basis set to output. Default is the latest version')",
"################################# subp = subparsers.add_parser('create-bundle', help='Create a bundle of basis sets')",
"file rather than stdout') subparsers = parser.add_subparsers(metavar='subcommand', dest='subcmd') subparsers.required =",
"import bse_cli_handle_subcmd from .check import cli_check_normalize_args from .complete import (cli_case_insensitive_validator,",
"get-info subcommand subp = subparsers.add_parser('get-info', help='Output general info and metadata",
"cli_bsname_completer # get-notes subcommand subp = subparsers.add_parser('get-notes', help='Output the notes",
"help='Get the notes of a family of basis sets') subp.add_argument('family',",
"is the latest version') subp.add_argument('--noheader', action='store_true', help='Do not output the",
"output the references for. Default is all defined in the",
"bundle of basis sets') subp.add_argument('fmt', help='Which format to output the",
"the output output = bse_cli_handle_subcmd(args) if args.output: with open(args.output, 'w',",
"list-families subcommand subparsers.add_parser('list-families', help='Output a list all available basis set",
"version numbers') # get-family-notes subcommand subp = subparsers.add_parser('get-family-notes', help='Get the",
"names') # list-roles subcommand subp = subparsers.add_parser('list-roles', help='Output a list",
"of the basis set to list the versions of').completer =",
"subp.add_argument('input_file', type=str, help='Basis set file to convert') subp.add_argument('output_file', type=str, help='Converted",
"'--no-description', action='store_true', help='Print only the format names') # list-ref-formats subcommand",
"help='Name of the primary basis we want the auxiliary basis",
"data-independent info ######################################## # list-formats subcommand subp = subparsers.add_parser('list-formats', help='Output",
"for a basis set') subp.add_argument('basis', help='Name of the basis set",
"subp.add_argument('--out-fmt', type=str, default=None, help='Output format (default: autodetected from output filename').completer",
"basis set list to only basis sets that contain all",
"help='Output a list all available basis set families') # lookup-by-role",
"basis.') subp.add_argument('--version', help='Which version of the basis set to get",
"run_bse_cli(): ################################################################################################ # NOTE: I am deliberately not using the",
"help='Print only the format names') # list-ref-formats subcommand subp =",
"output the basis set as').completer = cli_write_fmt_completer subp.add_argument('reffmt', help='Which format",
"contractions') subp.add_argument('--make-gen', action='store_true', help='Make the basis set as generally-contracted as",
"cli_bsname_completer subp.add_argument('fmt', help='Which format to output the basis set as').completer",
"with open(args.output, 'w', encoding='utf-8') as outfile: outfile.write(output) else: print(output) return",
"for').completer = cli_bsname_completer # get-notes subcommand subp = subparsers.add_parser('get-notes', help='Output",
"help='Output to given file rather than stdout') subparsers = parser.add_subparsers(metavar='subcommand',",
"the given elements') # list-families subcommand subparsers.add_parser('list-families', help='Output a list",
"sets') subp.add_argument('fmt', help='Which format to output the basis set as').completer",
"of data-independent info ######################################## # list-formats subcommand subp = subparsers.add_parser('list-formats',",
"list-writer-formats subcommand subp = subparsers.add_parser('list-writer-formats', help='Output a list available basis",
"sp, spd, ... contractions') subp.add_argument('--unc-seg', action='store_true', help='Remove general contractions') subp.add_argument('--opt-gen',",
"the notes of a family of basis sets') subp.add_argument('family', type=str.lower,",
"of').completer = cli_family_completer ################################# # Converting basis sets ################################# subp",
"# list-roles subcommand subp = subparsers.add_parser('list-roles', help='Output a list all",
"'--no-description', action='store_true', help='Print only the basis set names') subp.add_argument('-f', '--family',",
"for. Default is all defined in the given basis.') subp.add_argument('--version',",
"the format names') # list-reader-formats subp = subparsers.add_parser('list-reader-formats', help='Output a",
"import argcomplete from .. import version from .bse_handlers import bse_cli_handle_subcmd",
"subp.add_argument('role', help='Role of the auxiliary basis to look for').completer =",
"auxiliary basis for').completer = cli_bsname_completer subp.add_argument('role', help='Role of the auxiliary",
"list of basis set formats that can be used with",
"clean ################################################################################################ ######################################## # Main global options ######################################## parser =",
"version of the basis set to output. Default is the",
"as').completer = cli_reffmt_completer subp.add_argument('--elements', help='Which elements to output the references",
"all defined in the given basis.') subp.add_argument('--version', help='Which version of",
"to output the basis set as').completer = cli_write_fmt_completer subp.add_argument('reffmt', help='Which",
"valid args = cli_check_normalize_args(args) # Actually generate the output output",
"format (default: autodetected from output filename').completer = cli_write_fmt_completer ################################# #",
"= cli_bsname_completer # get-versions subcommand subp = subparsers.add_parser('get-versions', help='Output a",
"basis set to list the versions of').completer = cli_bsname_completer subp.add_argument('-n',",
"Actually generate the output output = bse_cli_handle_subcmd(args) if args.output: with",
"generate the output output = bse_cli_handle_subcmd(args) if args.output: with open(args.output,",
"action='store_true', help='Remove combined sp, spd, ... contractions') subp.add_argument('--unc-seg', action='store_true', help='Remove",
"# get-refs subcommand subp = subparsers.add_parser('get-refs', help='Output references for a",
"cli_write_fmt_completer subp.add_argument('--elements', help='Which elements of the basis set to output.",
"= parser.parse_args() # Check and make sure basis sets, roles,",
"cli_check_normalize_args from .complete import (cli_case_insensitive_validator, cli_family_completer, cli_role_completer, cli_bsname_completer, cli_write_fmt_completer, cli_read_fmt_completer,",
"all the given elements') # list-families subcommand subparsers.add_parser('list-families', help='Output a",
"format to output the references as').completer = cli_reffmt_completer subp.add_argument('bundle_file', help='Bundle/Archive",
"a list of basis set formats that can be read')",
"names') ######################################## # Listing of general info and metadata ########################################",
"'--no-description', action='store_true', help='Print only the format names') # list-reader-formats subp",
"= argparse.ArgumentParser(description='Description of your program') parser.add_argument('-V', action='version', version='basis_set_exchange ' +",
"role') subp.add_argument('basis', help='Name of the primary basis we want the",
"can be written') subp.add_argument('-n', '--no-description', action='store_true', help='Print only the format",
"= subparsers.add_parser('list-reader-formats', help='Output a list of basis set formats that",
"subp = subparsers.add_parser('list-formats', help='Output a list of basis set formats",
"subcommand subp = subparsers.add_parser('list-ref-formats', help='Output a list all available reference",
"info and metadata for a basis set') subp.add_argument('basis', help='Name of",
"help='Name of the basis set to output the family for').completer",
"= cli_bsname_completer subp.add_argument('-n', '--no-description', action='store_true', help='Print only the version numbers')",
"subparsers.add_parser('convert-basis', help='Convert basis set files from one format to another')",
"sure basis sets, roles, etc, are valid args = cli_check_normalize_args(args)",
"basis and role') subp.add_argument('basis', help='Name of the primary basis we",
"is all defined in the given basis') subp.add_argument('--version', help='Which version",
"could use it # for formats, etc, however I wouldn't",
"subp = subparsers.add_parser('get-family', help='Output the family of a basis set')",
".complete import (cli_case_insensitive_validator, cli_family_completer, cli_role_completer, cli_bsname_completer, cli_write_fmt_completer, cli_read_fmt_completer, cli_reffmt_completer) def",
"names. Therefore, I handle # all of that manually so",
"is consistent and clean ################################################################################################ ######################################## # Main global options",
"basis set to output the references for').completer = cli_bsname_completer subp.add_argument('reffmt',",
"rather than stdout') subparsers = parser.add_subparsers(metavar='subcommand', dest='subcmd') subparsers.required = True",
"global options ######################################## parser = argparse.ArgumentParser(description='Description of your program') parser.add_argument('-V',",
"autodetected from output filename').completer = cli_write_fmt_completer ################################# # Creating bundles",
"argparse.ArgumentParser(description='Description of your program') parser.add_argument('-V', action='version', version='basis_set_exchange ' + version())",
"only the format names') # list-writer-formats subcommand subp = subparsers.add_parser('list-writer-formats',",
"subp.add_argument('--in-fmt', type=str, default=None, help='Input format (default: autodetected from input filename').completer",
"to output the references as').completer = cli_reffmt_completer subp.add_argument('--elements', help='Which elements",
"help='Print only the role names') ######################################## # Listing of general",
"combined sp, spd, ... contractions') subp.add_argument('--unc-seg', action='store_true', help='Remove general contractions')",
"descriptions') subp.add_argument('-n', '--no-description', action='store_true', help='Print only the role names') ########################################",
"and descriptions') subp.add_argument('-n', '--no-description', action='store_true', help='Print only the reference format",
"<reponame>atomse/basis_set_exchange ''' Command line interface for the basis set exchange",
"I wouldn't want to use it for basis set names.",
"Command line interface for the basis set exchange ''' import",
"only the format names') # list-ref-formats subcommand subp = subparsers.add_parser('list-ref-formats',",
"set list to only the specified role').completer = cli_role_completer subp.add_argument('-s',",
"the specified family').completer = cli_family_completer subp.add_argument('-r', '--role', help='Limit the basis",
"help='Limit the basis set list to only basis sets whose",
"help='Output a formatted basis set') subp.add_argument('basis', help='Name of the basis",
"the top') subp.add_argument('--unc-gen', action='store_true', help='Remove general contractions') subp.add_argument('--unc-spdf', action='store_true', help='Remove",
"help='Print only the format names') # list-reader-formats subp = subparsers.add_parser('list-reader-formats',",
"or tbz)') ############################# # DONE WITH SUBCOMMANDS ############################# # setup",
"# get-data-dir subparsers.add_parser('get-data-dir', help='Output the default data directory of this",
"(default: autodetected from input filename').completer = cli_read_fmt_completer subp.add_argument('--out-fmt', type=str, default=None,",
"help='Output a list all available basis sets and descriptions') subp.add_argument('-n',",
"= parser.add_subparsers(metavar='subcommand', dest='subcmd') subparsers.required = True # https://bugs.python.org/issue9253#msg186387 ######################################## #",
"output the basis set as').completer = cli_write_fmt_completer subp.add_argument('--elements', help='Which elements",
"error output is consistent and clean ################################################################################################ ######################################## # Main",
"action='store_true', help='Optimize general contractions') subp.add_argument('--make-gen', action='store_true', help='Make the basis set",
"that can be used with obtaining a basis set') subp.add_argument('-n',",
"given file rather than stdout') subparsers = parser.add_subparsers(metavar='subcommand', dest='subcmd') subparsers.required",
"list all available basis set families') # lookup-by-role subp =",
"= cli_write_fmt_completer subp.add_argument('--elements', help='Which elements of the basis set to",
"given basis') subp.add_argument('--version', help='Which version of the basis set to",
"general info and metadata ######################################## # get-data-dir subparsers.add_parser('get-data-dir', help='Output the",
"cli_read_fmt_completer, cli_reffmt_completer) def run_bse_cli(): ################################################################################################ # NOTE: I am deliberately",
"family').completer = cli_family_completer subp.add_argument('-r', '--role', help='Limit the basis set list",
"subp.add_argument('-s', '--substr', help='Limit the basis set list to only basis",
"basis sets whose name contains the specified substring') subp.add_argument('-e', '--elements',",
"import argparse import argcomplete from .. import version from .bse_handlers",
"help='Which version of the basis set to get the references",
"help='Print only the version numbers') # get-family-notes subcommand subp =",
"tbz)') ############################# # DONE WITH SUBCOMMANDS ############################# # setup autocomplete",
"of your program') parser.add_argument('-V', action='version', version='basis_set_exchange ' + version()) parser.add_argument('-d',",
"subp.add_argument('output_file', type=str, help='Converted basis set file') subp.add_argument('--in-fmt', type=str, default=None, help='Input",
"names') # list-ref-formats subcommand subp = subparsers.add_parser('list-ref-formats', help='Output a list",
"cli_bsname_completer subp.add_argument('reffmt', help='Which format to output the references as').completer =",
"output output = bse_cli_handle_subcmd(args) if args.output: with open(args.output, 'w', encoding='utf-8')",
"= cli_bsname_completer subp.add_argument('role', help='Role of the auxiliary basis to look",
"available versions of a basis set') subp.add_argument('basis', help='Name of the",
"set family to the get the notes of').completer = cli_family_completer",
"wouldn't want to use it for basis set names. Therefore,",
"of the primary basis we want the auxiliary basis for').completer",
"################################# subp = subparsers.add_parser('convert-basis', help='Convert basis set files from one",
"make sure basis sets, roles, etc, are valid args =",
"to only the specified family').completer = cli_family_completer subp.add_argument('-r', '--role', help='Limit",
"= cli_bsname_completer subp.add_argument('reffmt', help='Which format to output the references as').completer",
"contains the specified substring') subp.add_argument('-e', '--elements', help='Limit the basis set",
"for').completer = cli_role_completer ################################# # Output of info ################################# #",
"that can be written') subp.add_argument('-n', '--no-description', action='store_true', help='Print only the",
"given basis.') subp.add_argument('--version', help='Which version of the basis set to",
"cli_family_completer subp.add_argument('-r', '--role', help='Limit the basis set list to only",
"'--data-dir', metavar='PATH', help='Override which data directory to use') parser.add_argument('-o', '--output',",
"notes of').completer = cli_family_completer ################################# # Converting basis sets #################################",
"subcommand subp = subparsers.add_parser('get-versions', help='Output a list all available versions",
"of general info and metadata ######################################## # get-data-dir subparsers.add_parser('get-data-dir', help='Output",
"to output the info for').completer = cli_bsname_completer # get-notes subcommand",
"reference format names') # list-roles subcommand subp = subparsers.add_parser('list-roles', help='Output",
"of a family of basis sets') subp.add_argument('family', type=str.lower, help='The basis",
"the references for').completer = cli_bsname_completer subp.add_argument('reffmt', help='Which format to output",
"versions of a basis set') subp.add_argument('basis', help='Name of the basis",
"parser.parse_args() # Check and make sure basis sets, roles, etc,",
"get-data-dir subparsers.add_parser('get-data-dir', help='Output the default data directory of this package')",
"at the top') subp.add_argument('--unc-gen', action='store_true', help='Remove general contractions') subp.add_argument('--unc-spdf', action='store_true',",
"only the basis set names') subp.add_argument('-f', '--family', help='Limit the basis",
"cli_bsname_completer # get-versions subcommand subp = subparsers.add_parser('get-versions', help='Output a list",
"(cli_case_insensitive_validator, cli_family_completer, cli_role_completer, cli_bsname_completer, cli_write_fmt_completer, cli_read_fmt_completer, cli_reffmt_completer) def run_bse_cli(): ################################################################################################",
"subp.add_argument('-n', '--no-description', action='store_true', help='Print only the version numbers') # get-family-notes",
"to output the references for. Default is all defined in",
"list to only the specified role').completer = cli_role_completer subp.add_argument('-s', '--substr',",
"list available basis set formats that can be written') subp.add_argument('-n',",
"elements to output the references for. Default is all defined",
"set as').completer = cli_write_fmt_completer subp.add_argument('reffmt', help='Which format to output the",
"references for a basis set') subp.add_argument('basis', help='Name of the basis",
"help='Name of the basis set to output the info for').completer",
"argcomplete from .. import version from .bse_handlers import bse_cli_handle_subcmd from",
"a list of basis set formats that can be used",
"formats and descriptions') subp.add_argument('-n', '--no-description', action='store_true', help='Print only the reference",
"names') subp.add_argument('-f', '--family', help='Limit the basis set list to only",
"of the basis set to output the info for').completer =",
"Listing of data-independent info ######################################## # list-formats subcommand subp =",
"all available roles and descriptions') subp.add_argument('-n', '--no-description', action='store_true', help='Print only",
"descriptions') subp.add_argument('-n', '--no-description', action='store_true', help='Print only the basis set names')",
"spd, ... contractions') subp.add_argument('--unc-seg', action='store_true', help='Remove general contractions') subp.add_argument('--opt-gen', action='store_true',",
"want to use it for basis set names. Therefore, I",
"I am deliberately not using the 'choices' argument in add_argument.",
"options ######################################## parser = argparse.ArgumentParser(description='Description of your program') parser.add_argument('-V', action='version',",
"as possible') # get-refs subcommand subp = subparsers.add_parser('get-refs', help='Output references",
"subp.add_argument('--make-gen', action='store_true', help='Make the basis set as generally-contracted as possible')",
"version') subp.add_argument('--noheader', action='store_true', help='Do not output the header at the",
"info and metadata ######################################## # get-data-dir subparsers.add_parser('get-data-dir', help='Output the default",
"subp.add_argument('--elements', help='Which elements to output the references for. Default is",
"version of the basis set to get the references for')",
"as').completer = cli_write_fmt_completer subp.add_argument('reffmt', help='Which format to output the references",
"sets, roles, etc, are valid args = cli_check_normalize_args(args) # Actually",
"references for').completer = cli_bsname_completer subp.add_argument('reffmt', help='Which format to output the",
"output the family for').completer = cli_bsname_completer # get-versions subcommand subp",
"specified role').completer = cli_role_completer subp.add_argument('-s', '--substr', help='Limit the basis set",
"set formats that can be read') subp.add_argument('-n', '--no-description', action='store_true', help='Print",
"# Output of info ################################# # get-basis subcommand subp =",
"subparsers.add_parser('get-refs', help='Output references for a basis set') subp.add_argument('basis', help='Name of",
"help='Name of the basis set to list the versions of').completer",
"help='Remove general contractions') subp.add_argument('--unc-spdf', action='store_true', help='Remove combined sp, spd, ...",
"help='Which elements to output the references for. Default is all",
"set files from one format to another') subp.add_argument('input_file', type=str, help='Basis",
"######################################## # Listing of general info and metadata ######################################## #",
"set to output. Default is all defined in the given",
"of basis set formats that can be read') subp.add_argument('-n', '--no-description',",
"the basis set list to only the specified role').completer =",
"action='store_true', help='Do not output the header at the top') subp.add_argument('--unc-gen',",
"a list all available basis set families') # lookup-by-role subp",
"# https://bugs.python.org/issue9253#msg186387 ######################################## # Listing of data-independent info ######################################## #",
"subp.add_argument('--noheader', action='store_true', help='Do not output the header at the top')",
"output the references as').completer = cli_reffmt_completer subp.add_argument('--elements', help='Which elements to",
"general contractions') subp.add_argument('--opt-gen', action='store_true', help='Optimize general contractions') subp.add_argument('--make-gen', action='store_true', help='Make",
"list all available basis sets and descriptions') subp.add_argument('-n', '--no-description', action='store_true',",
"basis set to output the family for').completer = cli_bsname_completer #",
"# for formats, etc, however I wouldn't want to use",
"cli_role_completer ################################# # Output of info ################################# # get-basis subcommand",
"a list all available roles and descriptions') subp.add_argument('-n', '--no-description', action='store_true',",
"family of a basis set') subp.add_argument('basis', help='Name of the basis",
"basis set list to only the specified family').completer = cli_family_completer",
"Converting basis sets ################################# subp = subparsers.add_parser('convert-basis', help='Convert basis set",
"argcomplete.autocomplete(parser, validator=cli_case_insensitive_validator) # Now parse and handle the args args",
"help='Name of the basis set to output the references for').completer",
"help='Basis set file to convert') subp.add_argument('output_file', type=str, help='Converted basis set",
"and descriptions') subp.add_argument('-n', '--no-description', action='store_true', help='Print only the basis set",
"basis set as generally-contracted as possible') # get-refs subcommand subp",
"# setup autocomplete argcomplete.autocomplete(parser, validator=cli_case_insensitive_validator) # Now parse and handle",
"the args args = parser.parse_args() # Check and make sure",
"basis set family to the get the notes of').completer =",
"= subparsers.add_parser('create-bundle', help='Create a bundle of basis sets') subp.add_argument('fmt', help='Which",
"= cli_reffmt_completer subp.add_argument('bundle_file', help='Bundle/Archive file to create') subp.add_argument('--archive-type', help='Override the",
"cli_reffmt_completer) def run_bse_cli(): ################################################################################################ # NOTE: I am deliberately not",
"help='Output the default data directory of this package') # list-basis-sets",
"obtaining a basis set') subp.add_argument('-n', '--no-description', action='store_true', help='Print only the",
"roles and descriptions') subp.add_argument('-n', '--no-description', action='store_true', help='Print only the role",
"the auxiliary basis for').completer = cli_bsname_completer subp.add_argument('role', help='Role of the",
"basis set') subp.add_argument('basis', help='Name of the basis set to list",
"subcommand subp = subparsers.add_parser('list-basis-sets', help='Output a list all available basis",
"subp.add_argument('reffmt', help='Which format to output the references as').completer = cli_reffmt_completer",
"subcommand subp = subparsers.add_parser('get-family-notes', help='Get the notes of a family",
"elements of the basis set to output. Default is all",
"= subparsers.add_parser('list-writer-formats', help='Output a list available basis set formats that",
"= subparsers.add_parser('get-refs', help='Output references for a basis set') subp.add_argument('basis', help='Name",
"format to another') subp.add_argument('input_file', type=str, help='Basis set file to convert')",
"generally-contracted as possible') # get-refs subcommand subp = subparsers.add_parser('get-refs', help='Output",
"metadata ######################################## # get-data-dir subparsers.add_parser('get-data-dir', help='Output the default data directory",
"set to output the references for').completer = cli_bsname_completer subp.add_argument('reffmt', help='Which",
"elements') # list-families subcommand subparsers.add_parser('list-families', help='Output a list all available",
"a basis set') subp.add_argument('basis', help='Name of the basis set to",
"get-notes subcommand subp = subparsers.add_parser('get-notes', help='Output the notes for a",
"contractions') subp.add_argument('--opt-gen', action='store_true', help='Optimize general contractions') subp.add_argument('--make-gen', action='store_true', help='Make the",
"output is consistent and clean ################################################################################################ ######################################## # Main global",
"subp.add_argument('-n', '--no-description', action='store_true', help='Print only the format names') # list-writer-formats",
"subparsers.add_parser('get-data-dir', help='Output the default data directory of this package') #",
"help='The basis set family to the get the notes of').completer",
"cli_bsname_completer, cli_write_fmt_completer, cli_read_fmt_completer, cli_reffmt_completer) def run_bse_cli(): ################################################################################################ # NOTE: I",
"help='Lookup a companion/auxiliary basis by primary basis and role') subp.add_argument('basis',",
"help='Create a bundle of basis sets') subp.add_argument('fmt', help='Which format to",
"family to the get the notes of').completer = cli_family_completer #################################",
"available basis set families') # lookup-by-role subp = subparsers.add_parser('lookup-by-role', help='Lookup",
"# Main global options ######################################## parser = argparse.ArgumentParser(description='Description of your",
"set formats that can be written') subp.add_argument('-n', '--no-description', action='store_true', help='Print",
"version()) parser.add_argument('-d', '--data-dir', metavar='PATH', help='Override which data directory to use')",
"the references for. Default is all defined in the given",
"set names') subp.add_argument('-f', '--family', help='Limit the basis set list to",
"help='Output general info and metadata for a basis set') subp.add_argument('basis',",
"type=str, help='Basis set file to convert') subp.add_argument('output_file', type=str, help='Converted basis",
"# all of that manually so that error output is",
"help='Name of the basis set to output').completer = cli_bsname_completer subp.add_argument('fmt',",
"default=None, help='Output format (default: autodetected from output filename').completer = cli_write_fmt_completer",
"from .check import cli_check_normalize_args from .complete import (cli_case_insensitive_validator, cli_family_completer, cli_role_completer,",
"version='basis_set_exchange ' + version()) parser.add_argument('-d', '--data-dir', metavar='PATH', help='Override which data",
"are valid args = cli_check_normalize_args(args) # Actually generate the output",
"output. Default is all defined in the given basis') subp.add_argument('--version',",
"output the references as').completer = cli_reffmt_completer subp.add_argument('bundle_file', help='Bundle/Archive file to",
"(zip or tbz)') ############################# # DONE WITH SUBCOMMANDS ############################# #",
"= cli_role_completer ################################# # Output of info ################################# # get-basis",
"to create') subp.add_argument('--archive-type', help='Override the type of archive to create",
"be used with obtaining a basis set') subp.add_argument('-n', '--no-description', action='store_true',",
"list the versions of').completer = cli_bsname_completer subp.add_argument('-n', '--no-description', action='store_true', help='Print",
"'--no-description', action='store_true', help='Print only the format names') # list-writer-formats subcommand",
"subparsers.add_parser('list-formats', help='Output a list of basis set formats that can",
"the type of archive to create (zip or tbz)') #############################",
"subp.add_argument('basis', help='Name of the primary basis we want the auxiliary",
"files from one format to another') subp.add_argument('input_file', type=str, help='Basis set",
"data directory of this package') # list-basis-sets subcommand subp =",
"list-formats subcommand subp = subparsers.add_parser('list-formats', help='Output a list of basis",
"output the header at the top') subp.add_argument('--unc-gen', action='store_true', help='Remove general",
"help='Bundle/Archive file to create') subp.add_argument('--archive-type', help='Override the type of archive",
"sets ################################# subp = subparsers.add_parser('convert-basis', help='Convert basis set files from",
"only basis sets that contain all the given elements') #",
"it # for formats, etc, however I wouldn't want to",
"info ################################# # get-basis subcommand subp = subparsers.add_parser('get-basis', help='Output a",
"# Listing of general info and metadata ######################################## # get-data-dir",
"primary basis we want the auxiliary basis for').completer = cli_bsname_completer",
"format (default: autodetected from input filename').completer = cli_read_fmt_completer subp.add_argument('--out-fmt', type=str,",
"roles, etc, are valid args = cli_check_normalize_args(args) # Actually generate",
"parse and handle the args args = parser.parse_args() # Check",
"available reference formats and descriptions') subp.add_argument('-n', '--no-description', action='store_true', help='Print only",
"the notes of').completer = cli_family_completer ################################# # Converting basis sets",
"basis set to output the info for').completer = cli_bsname_completer #",
"subparsers.add_parser('get-family-notes', help='Get the notes of a family of basis sets')",
"basis sets that contain all the given elements') # list-families",
"if args.output: with open(args.output, 'w', encoding='utf-8') as outfile: outfile.write(output) else:",
"by primary basis and role') subp.add_argument('basis', help='Name of the primary",
"only the format names') # list-reader-formats subp = subparsers.add_parser('list-reader-formats', help='Output",
"all available reference formats and descriptions') subp.add_argument('-n', '--no-description', action='store_true', help='Print",
"'--output', metavar='PATH', help='Output to given file rather than stdout') subparsers",
"I handle # all of that manually so that error",
"subp = subparsers.add_parser('list-roles', help='Output a list all available roles and",
"in the given basis') subp.add_argument('--version', help='Which version of the basis",
"the basis set to list the versions of').completer = cli_bsname_completer",
"versions of').completer = cli_bsname_completer subp.add_argument('-n', '--no-description', action='store_true', help='Print only the",
"Main global options ######################################## parser = argparse.ArgumentParser(description='Description of your program')",
"help='Print only the basis set names') subp.add_argument('-f', '--family', help='Limit the",
"the basis set list to only the specified family').completer =",
"autocomplete argcomplete.autocomplete(parser, validator=cli_case_insensitive_validator) # Now parse and handle the args",
"from .. import version from .bse_handlers import bse_cli_handle_subcmd from .check",
"the basis set as').completer = cli_write_fmt_completer subp.add_argument('--elements', help='Which elements of",
"format to output the basis set as').completer = cli_write_fmt_completer subp.add_argument('--elements',",
"subp.add_argument('basis', help='Name of the basis set to output the family",
"exchange ''' import argparse import argcomplete from .. import version",
"argument in add_argument. I could use it # for formats,",
"auxiliary basis to look for').completer = cli_role_completer ################################# # Output",
"help='Which version of the basis set to output. Default is",
"role names') ######################################## # Listing of general info and metadata",
"a bundle of basis sets') subp.add_argument('fmt', help='Which format to output",
"# list-families subcommand subparsers.add_parser('list-families', help='Output a list all available basis",
"subparsers.add_parser('list-ref-formats', help='Output a list all available reference formats and descriptions')",
"set to get the references for') # get-info subcommand subp",
"cli_write_fmt_completer, cli_read_fmt_completer, cli_reffmt_completer) def run_bse_cli(): ################################################################################################ # NOTE: I am",
"parser.add_subparsers(metavar='subcommand', dest='subcmd') subparsers.required = True # https://bugs.python.org/issue9253#msg186387 ######################################## # Listing",
"metavar='PATH', help='Override which data directory to use') parser.add_argument('-o', '--output', metavar='PATH',",
"and metadata for a basis set') subp.add_argument('basis', help='Name of the",
"help='Output references for a basis set') subp.add_argument('basis', help='Name of the",
"notes for').completer = cli_bsname_completer # get-family subcommand subp = subparsers.add_parser('get-family',",
"the versions of').completer = cli_bsname_completer subp.add_argument('-n', '--no-description', action='store_true', help='Print only",
"subp.add_argument('basis', help='Name of the basis set to list the versions",
"possible') # get-refs subcommand subp = subparsers.add_parser('get-refs', help='Output references for",
"subparsers.add_parser('list-writer-formats', help='Output a list available basis set formats that can",
"subp.add_argument('--unc-seg', action='store_true', help='Remove general contractions') subp.add_argument('--opt-gen', action='store_true', help='Optimize general contractions')",
"Now parse and handle the args args = parser.parse_args() #",
"specified family').completer = cli_family_completer subp.add_argument('-r', '--role', help='Limit the basis set",
"cli_role_completer subp.add_argument('-s', '--substr', help='Limit the basis set list to only",
"role').completer = cli_role_completer subp.add_argument('-s', '--substr', help='Limit the basis set list",
"basis to look for').completer = cli_role_completer ################################# # Output of",
"basis set') subp.add_argument('basis', help='Name of the basis set to output').completer",
"to output the notes for').completer = cli_bsname_completer # get-family subcommand",
"subp = subparsers.add_parser('get-refs', help='Output references for a basis set') subp.add_argument('basis',",
"of the basis set to get the references for') #",
"action='store_true', help='Print only the format names') # list-ref-formats subcommand subp",
"######################################## # list-formats subcommand subp = subparsers.add_parser('list-formats', help='Output a list",
"Listing of general info and metadata ######################################## # get-data-dir subparsers.add_parser('get-data-dir',",
"Output of info ################################# # get-basis subcommand subp = subparsers.add_parser('get-basis',",
"subp.add_argument('-e', '--elements', help='Limit the basis set list to only basis",
"manually so that error output is consistent and clean ################################################################################################",
"from one format to another') subp.add_argument('input_file', type=str, help='Basis set file",
"format to output the basis set as').completer = cli_write_fmt_completer subp.add_argument('reffmt',",
"set list to only basis sets that contain all the",
"subp.add_argument('--unc-gen', action='store_true', help='Remove general contractions') subp.add_argument('--unc-spdf', action='store_true', help='Remove combined sp,",
"autodetected from input filename').completer = cli_read_fmt_completer subp.add_argument('--out-fmt', type=str, default=None, help='Output",
"subp.add_argument('-n', '--no-description', action='store_true', help='Print only the format names') # list-reader-formats",
"type of archive to create (zip or tbz)') ############################# #",
"basis set formats that can be written') subp.add_argument('-n', '--no-description', action='store_true',",
"= subparsers.add_parser('list-formats', help='Output a list of basis set formats that",
"basis we want the auxiliary basis for').completer = cli_bsname_completer subp.add_argument('role',",
"a list all available basis sets and descriptions') subp.add_argument('-n', '--no-description',",
"the auxiliary basis to look for').completer = cli_role_completer ################################# #",
"subp.add_argument('basis', help='Name of the basis set to output').completer = cli_bsname_completer",
"etc, however I wouldn't want to use it for basis",
"list of basis set formats that can be read') subp.add_argument('-n',",
"the role names') ######################################## # Listing of general info and",
"in add_argument. I could use it # for formats, etc,",
"'--no-description', action='store_true', help='Print only the reference format names') # list-roles",
"the given basis.') subp.add_argument('--version', help='Which version of the basis set",
"format names') # list-writer-formats subcommand subp = subparsers.add_parser('list-writer-formats', help='Output a",
"action='version', version='basis_set_exchange ' + version()) parser.add_argument('-d', '--data-dir', metavar='PATH', help='Override which",
"validator=cli_case_insensitive_validator) # Now parse and handle the args args =",
"subp = subparsers.add_parser('get-info', help='Output general info and metadata for a",
"help='Override which data directory to use') parser.add_argument('-o', '--output', metavar='PATH', help='Output",
"not using the 'choices' argument in add_argument. I could use",
"help='Print only the reference format names') # list-roles subcommand subp",
"output the notes for').completer = cli_bsname_completer # get-family subcommand subp",
"# get-versions subcommand subp = subparsers.add_parser('get-versions', help='Output a list all",
"######################################## # get-data-dir subparsers.add_parser('get-data-dir', help='Output the default data directory of",
"get the references for') # get-info subcommand subp = subparsers.add_parser('get-info',",
"################################# # get-basis subcommand subp = subparsers.add_parser('get-basis', help='Output a formatted",
"of a basis set') subp.add_argument('basis', help='Name of the basis set",
"can be used with obtaining a basis set') subp.add_argument('-n', '--no-description',",
"output the references for').completer = cli_bsname_completer subp.add_argument('reffmt', help='Which format to",
"= cli_write_fmt_completer subp.add_argument('reffmt', help='Which format to output the references as').completer",
"get the notes of').completer = cli_family_completer ################################# # Converting basis",
"as').completer = cli_reffmt_completer subp.add_argument('bundle_file', help='Bundle/Archive file to create') subp.add_argument('--archive-type', help='Override",
"handle # all of that manually so that error output",
"= cli_family_completer subp.add_argument('-r', '--role', help='Limit the basis set list to",
"subp.add_argument('-n', '--no-description', action='store_true', help='Print only the role names') ######################################## #",
"set to output').completer = cli_bsname_completer subp.add_argument('fmt', help='Which format to output",
"subparsers.add_parser('lookup-by-role', help='Lookup a companion/auxiliary basis by primary basis and role')",
"the basis set to output the info for').completer = cli_bsname_completer",
"to output').completer = cli_bsname_completer subp.add_argument('fmt', help='Which format to output the",
"format names') # list-reader-formats subp = subparsers.add_parser('list-reader-formats', help='Output a list",
"set as generally-contracted as possible') # get-refs subcommand subp =",
"bse_cli_handle_subcmd from .check import cli_check_normalize_args from .complete import (cli_case_insensitive_validator, cli_family_completer,",
"set file to convert') subp.add_argument('output_file', type=str, help='Converted basis set file')",
"input filename').completer = cli_read_fmt_completer subp.add_argument('--out-fmt', type=str, default=None, help='Output format (default:",
"subcommand subparsers.add_parser('list-families', help='Output a list all available basis set families')",
"################################# # Creating bundles ################################# subp = subparsers.add_parser('create-bundle', help='Create a",
"Creating bundles ################################# subp = subparsers.add_parser('create-bundle', help='Create a bundle of",
"only the specified role').completer = cli_role_completer subp.add_argument('-s', '--substr', help='Limit the",
"import (cli_case_insensitive_validator, cli_family_completer, cli_role_completer, cli_bsname_completer, cli_write_fmt_completer, cli_read_fmt_completer, cli_reffmt_completer) def run_bse_cli():",
"# get-notes subcommand subp = subparsers.add_parser('get-notes', help='Output the notes for",
"= bse_cli_handle_subcmd(args) if args.output: with open(args.output, 'w', encoding='utf-8') as outfile:",
"format to output the references as').completer = cli_reffmt_completer subp.add_argument('--elements', help='Which",
"of basis set formats that can be used with obtaining",
"use it for basis set names. Therefore, I handle #",
"to given file rather than stdout') subparsers = parser.add_subparsers(metavar='subcommand', dest='subcmd')",
"subp.add_argument('family', type=str.lower, help='The basis set family to the get the",
"set formats that can be used with obtaining a basis",
"help='Input format (default: autodetected from input filename').completer = cli_read_fmt_completer subp.add_argument('--out-fmt',",
"basis set names') subp.add_argument('-f', '--family', help='Limit the basis set list",
"specified substring') subp.add_argument('-e', '--elements', help='Limit the basis set list to",
"that contain all the given elements') # list-families subcommand subparsers.add_parser('list-families',",
"help='Do not output the header at the top') subp.add_argument('--unc-gen', action='store_true',",
"= cli_reffmt_completer subp.add_argument('--elements', help='Which elements to output the references for.",
"am deliberately not using the 'choices' argument in add_argument. I",
"get-versions subcommand subp = subparsers.add_parser('get-versions', help='Output a list all available",
"cli_family_completer ################################# # Converting basis sets ################################# subp = subparsers.add_parser('convert-basis',",
"be written') subp.add_argument('-n', '--no-description', action='store_true', help='Print only the format names')",
"subcommand subp = subparsers.add_parser('get-family', help='Output the family of a basis",
"the basis set to output').completer = cli_bsname_completer subp.add_argument('fmt', help='Which format",
"filename').completer = cli_write_fmt_completer ################################# # Creating bundles ################################# subp =",
"basis sets') subp.add_argument('fmt', help='Which format to output the basis set",
"# get-family-notes subcommand subp = subparsers.add_parser('get-family-notes', help='Get the notes of",
"list to only the specified family').completer = cli_family_completer subp.add_argument('-r', '--role',",
"set to output the info for').completer = cli_bsname_completer # get-notes",
"help='Make the basis set as generally-contracted as possible') # get-refs",
"subparsers.add_parser('get-notes', help='Output the notes for a basis set') subp.add_argument('basis', help='Name",
"= subparsers.add_parser('list-roles', help='Output a list all available roles and descriptions')",
"as generally-contracted as possible') # get-refs subcommand subp = subparsers.add_parser('get-refs',",
"output = bse_cli_handle_subcmd(args) if args.output: with open(args.output, 'w', encoding='utf-8') as",
"to the get the notes of').completer = cli_family_completer ################################# #",
"cli_bsname_completer # get-family subcommand subp = subparsers.add_parser('get-family', help='Output the family",
"all defined in the given basis') subp.add_argument('--version', help='Which version of",
"etc, are valid args = cli_check_normalize_args(args) # Actually generate the",
"output').completer = cli_bsname_completer subp.add_argument('fmt', help='Which format to output the basis",
"contractions') subp.add_argument('--unc-seg', action='store_true', help='Remove general contractions') subp.add_argument('--opt-gen', action='store_true', help='Optimize general",
"list to only basis sets that contain all the given",
"another') subp.add_argument('input_file', type=str, help='Basis set file to convert') subp.add_argument('output_file', type=str,",
"= True # https://bugs.python.org/issue9253#msg186387 ######################################## # Listing of data-independent info",
"Default is all defined in the given basis.') subp.add_argument('--version', help='Which",
"the format names') # list-ref-formats subcommand subp = subparsers.add_parser('list-ref-formats', help='Output",
"basis set files from one format to another') subp.add_argument('input_file', type=str,",
"basis sets ################################# subp = subparsers.add_parser('convert-basis', help='Convert basis set files",
"basis set to output the notes for').completer = cli_bsname_completer #",
"subp = subparsers.add_parser('list-writer-formats', help='Output a list available basis set formats",
"basis set to output. Default is the latest version') subp.add_argument('--noheader',",
"help='Which elements of the basis set to output. Default is",
"set to output. Default is the latest version') subp.add_argument('--noheader', action='store_true',",
"and role') subp.add_argument('basis', help='Name of the primary basis we want",
"set to output the family for').completer = cli_bsname_completer # get-versions",
"get-basis subcommand subp = subparsers.add_parser('get-basis', help='Output a formatted basis set')",
"= cli_bsname_completer # get-notes subcommand subp = subparsers.add_parser('get-notes', help='Output the",
"help='Limit the basis set list to only basis sets that",
"# Check and make sure basis sets, roles, etc, are",
"the primary basis we want the auxiliary basis for').completer =",
"set list to only the specified family').completer = cli_family_completer subp.add_argument('-r',",
"formatted basis set') subp.add_argument('basis', help='Name of the basis set to",
"metavar='PATH', help='Output to given file rather than stdout') subparsers =",
"# list-writer-formats subcommand subp = subparsers.add_parser('list-writer-formats', help='Output a list available",
"subparsers.add_parser('get-family', help='Output the family of a basis set') subp.add_argument('basis', help='Name",
"only the role names') ######################################## # Listing of general info",
"the basis set as generally-contracted as possible') # get-refs subcommand",
"interface for the basis set exchange ''' import argparse import",
"from .bse_handlers import bse_cli_handle_subcmd from .check import cli_check_normalize_args from .complete",
"formats that can be used with obtaining a basis set')",
"stdout') subparsers = parser.add_subparsers(metavar='subcommand', dest='subcmd') subparsers.required = True # https://bugs.python.org/issue9253#msg186387",
"help='Output a list available basis set formats that can be",
"get-family subcommand subp = subparsers.add_parser('get-family', help='Output the family of a",
"create (zip or tbz)') ############################# # DONE WITH SUBCOMMANDS #############################",
"https://bugs.python.org/issue9253#msg186387 ######################################## # Listing of data-independent info ######################################## # list-formats",
"only the version numbers') # get-family-notes subcommand subp = subparsers.add_parser('get-family-notes',",
"to output. Default is the latest version') subp.add_argument('--noheader', action='store_true', help='Do",
"subcommand subp = subparsers.add_parser('get-notes', help='Output the notes for a basis",
"= cli_family_completer ################################# # Converting basis sets ################################# subp =",
"dest='subcmd') subparsers.required = True # https://bugs.python.org/issue9253#msg186387 ######################################## # Listing of",
"= subparsers.add_parser('get-family', help='Output the family of a basis set') subp.add_argument('basis',",
"cli_check_normalize_args(args) # Actually generate the output output = bse_cli_handle_subcmd(args) if",
"available roles and descriptions') subp.add_argument('-n', '--no-description', action='store_true', help='Print only the",
"descriptions') subp.add_argument('-n', '--no-description', action='store_true', help='Print only the reference format names')",
"names') # list-writer-formats subcommand subp = subparsers.add_parser('list-writer-formats', help='Output a list",
"top') subp.add_argument('--unc-gen', action='store_true', help='Remove general contractions') subp.add_argument('--unc-spdf', action='store_true', help='Remove combined",
"Default is all defined in the given basis') subp.add_argument('--version', help='Which",
"the references as').completer = cli_reffmt_completer subp.add_argument('bundle_file', help='Bundle/Archive file to create')",
"subp.add_argument('bundle_file', help='Bundle/Archive file to create') subp.add_argument('--archive-type', help='Override the type of",
"subcommand subp = subparsers.add_parser('list-formats', help='Output a list of basis set",
"subp.add_argument('--version', help='Which version of the basis set to output. Default",
"the references as').completer = cli_reffmt_completer subp.add_argument('--elements', help='Which elements to output",
"to look for').completer = cli_role_completer ################################# # Output of info",
"this package') # list-basis-sets subcommand subp = subparsers.add_parser('list-basis-sets', help='Output a",
"reference formats and descriptions') subp.add_argument('-n', '--no-description', action='store_true', help='Print only the",
"action='store_true', help='Remove general contractions') subp.add_argument('--unc-spdf', action='store_true', help='Remove combined sp, spd,",
"program') parser.add_argument('-V', action='version', version='basis_set_exchange ' + version()) parser.add_argument('-d', '--data-dir', metavar='PATH',",
"to use') parser.add_argument('-o', '--output', metavar='PATH', help='Output to given file rather",
"to output the references for').completer = cli_bsname_completer subp.add_argument('reffmt', help='Which format",
".check import cli_check_normalize_args from .complete import (cli_case_insensitive_validator, cli_family_completer, cli_role_completer, cli_bsname_completer,",
"available basis sets and descriptions') subp.add_argument('-n', '--no-description', action='store_true', help='Print only",
"basis set file') subp.add_argument('--in-fmt', type=str, default=None, help='Input format (default: autodetected",
"bundles ################################# subp = subparsers.add_parser('create-bundle', help='Create a bundle of basis",
"help='Converted basis set file') subp.add_argument('--in-fmt', type=str, default=None, help='Input format (default:",
"action='store_true', help='Print only the role names') ######################################## # Listing of",
"given elements') # list-families subcommand subparsers.add_parser('list-families', help='Output a list all",
"and clean ################################################################################################ ######################################## # Main global options ######################################## parser",
"subp.add_argument('basis', help='Name of the basis set to output the notes",
"primary basis and role') subp.add_argument('basis', help='Name of the primary basis",
"subp = subparsers.add_parser('get-basis', help='Output a formatted basis set') subp.add_argument('basis', help='Name",
"formats, etc, however I wouldn't want to use it for",
"list-ref-formats subcommand subp = subparsers.add_parser('list-ref-formats', help='Output a list all available",
"subparsers.add_parser('get-info', help='Output general info and metadata for a basis set')"
] |
[
"= 2 while i * j <= right: array[i *",
"True: j = 2 while i * j <= right:",
"left, right = map(int, input().split()) array = [True for i",
"예시 3 16 출력 예시 3 5 7 11 13",
"input().split()) array = [True for i in range(right+1)] array[1] =",
"for i in range(right+1)] array[1] = 0 for i in",
"입력 예시 3 16 출력 예시 3 5 7 11",
"= [True for i in range(right+1)] array[1] = 0 for",
"0 for i in range(2, int(math.sqrt(right)) + 1): if array[i]",
"i in range(2, int(math.sqrt(right)) + 1): if array[i] == True:",
"i in range(right+1)] array[1] = 0 for i in range(2,",
"right = map(int, input().split()) array = [True for i in",
"[True for i in range(right+1)] array[1] = 0 for i",
"for i in range(2, int(math.sqrt(right)) + 1): if array[i] ==",
"7 11 13 \"\"\" import math left, right = map(int,",
"1): if array[i] == True: j = 2 while i",
"2 while i * j <= right: array[i * j]",
"i * j <= right: array[i * j] = False",
"= 0 for i in range(2, int(math.sqrt(right)) + 1): if",
"if array[i] == True: j = 2 while i *",
"\"\"\" import math left, right = map(int, input().split()) array =",
"right: array[i * j] = False j += 1 for",
"= False j += 1 for i in range(left, right+1):",
"출력 예시 3 5 7 11 13 \"\"\" import math",
"array[i] == True: j = 2 while i * j",
"* j] = False j += 1 for i in",
"11 13 \"\"\" import math left, right = map(int, input().split())",
"예시 3 5 7 11 13 \"\"\" import math left,",
"in range(right+1)] array[1] = 0 for i in range(2, int(math.sqrt(right))",
"= map(int, input().split()) array = [True for i in range(right+1)]",
"3 16 출력 예시 3 5 7 11 13 \"\"\"",
"False j += 1 for i in range(left, right+1): if",
"j += 1 for i in range(left, right+1): if array[i]:",
"* j <= right: array[i * j] = False j",
"array[1] = 0 for i in range(2, int(math.sqrt(right)) + 1):",
"== True: j = 2 while i * j <=",
"13 \"\"\" import math left, right = map(int, input().split()) array",
"\"\"\" 입력 예시 3 16 출력 예시 3 5 7",
"array = [True for i in range(right+1)] array[1] = 0",
"range(2, int(math.sqrt(right)) + 1): if array[i] == True: j =",
"j <= right: array[i * j] = False j +=",
"+ 1): if array[i] == True: j = 2 while",
"<= right: array[i * j] = False j += 1",
"j] = False j += 1 for i in range(left,",
"16 출력 예시 3 5 7 11 13 \"\"\" import",
"import math left, right = map(int, input().split()) array = [True",
"+= 1 for i in range(left, right+1): if array[i]: print(i)",
"int(math.sqrt(right)) + 1): if array[i] == True: j = 2",
"range(right+1)] array[1] = 0 for i in range(2, int(math.sqrt(right)) +",
"in range(2, int(math.sqrt(right)) + 1): if array[i] == True: j",
"3 5 7 11 13 \"\"\" import math left, right",
"while i * j <= right: array[i * j] =",
"5 7 11 13 \"\"\" import math left, right =",
"j = 2 while i * j <= right: array[i",
"array[i * j] = False j += 1 for i",
"math left, right = map(int, input().split()) array = [True for",
"map(int, input().split()) array = [True for i in range(right+1)] array[1]"
] |
[
"bias_add_n = quantize_graph.create_node(\"BiasAdd\", \"bias_add\", [input_n.name, offset_n.name]) quantize_graph.set_attr_dtype(bias_add_n, \"T\", dtypes.float32) float_graph_def",
"extra quantize/dequantize.\"\"\" def make_matmul(name, a, b): n = quantize_graph.create_node(\"MatMul\", name,",
"shape=[2]) float_graph_def.node.extend([variance_constant]) beta_constant = quantize_graph.create_constant_node( beta_constant_name, value=[0.1, 0.6], dtype=dtypes.float32, shape=[2])",
"get_top_value(input_values): max_value = None max_index = None for index, value",
"2, 3, 4, 5, 6, 7, 8, 9]) def test_mat_mul_tiny(self):",
"# One dequantize at the end. self.assertEqual(1, ops.count(\"Dequantize\")) # No",
"\"weights_rounded\", [0, 1]) with self.assertRaises(ValueError): # Invalid range. quantize_graph.GraphRewriter(graph_pb2.GraphDef(), \"eightbit\",",
"2, b\"SAME\", [1, 2, 3, 4, 5, 6, 7, 8,",
"a_quantize_name, b_quantize_name, a_quantize_name + \":1\", a_quantize_name + \":2\", b_quantize_name +",
"2.0 (the \"License\"); # you may not use this file",
"inputs were close enough. \"\"\" flat_a = a.flatten() flat_b =",
"weight_1_node = quantize_graph.create_constant_node( \"weight_1\", value=[.5, .6, .7, .8, .9], dtype=dtypes.float32,",
"value=1, dtype=dtypes.float32, shape=[]) graph_def.node.extend([b_constant]) b_check_node = quantize_graph.create_node(\"CheckNumerics\", b_check_name, [b_constant_name]) graph_def.node.extend([b_check_node])",
"dtype=dtypes.float32, shape=[]) expected_output.node.extend([b_constant_min]) b_constant_max = quantize_graph.create_constant_node( b_constant_max_name, value=3, dtype=dtypes.float32, shape=[])",
"shape=[2, 2, 3]) float_graph_def.node.extend([a_constant]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=[13, 14,",
"arrays. arr = np.array([0, 0.3, 0.6, 1]) qarr = quantize_graph.quantize_array(arr,",
"no_op = quantize_graph.create_node(\"NoOp\", no_op_name, []) expected_output.node.extend([no_op]) a_constant = quantize_graph.create_constant_node( a_constant_name,",
"ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) # One dequantize at the end. self.assertEqual(1,",
"\"round\") # round_graph_def = round_rewriter.rewrite(output_name) # round_results = run_graph_def(round_graph_def, input_map,",
"= quantize_graph.create_constant_node( \"max_bias_add\", value=15.5, dtype=dtypes.float32, shape=[]) fake_quant_node = quantize_graph.create_node( \"FakeQuantWithMinMaxVars\",",
"filter_count, stride, padding, input_values, filter_values): \"\"\"Tests a Conv replacement.\"\"\" input_constant_name",
"[ a_quantize_name, b_quantize_name, a_quantize_name + \":1\", a_quantize_name + \":2\", b_quantize_name",
"from tensorflow.tools.quantization import quantize_graph flags = flags_lib FLAGS = flags.FLAGS",
"max_node, fake_quant_node]) test_graph(float_graph_def, {}, [fake_quant_node.name], log_graph=True) # Verify there is",
"= quantize_graph.create_constant_node( \"min_bias_add\", value=0, dtype=dtypes.float32, shape=[]) max_node = quantize_graph.create_constant_node( \"max_bias_add\",",
"quantize_graph.create_node(\"NoOp\", no_op_name, []) graph_def.node.extend([no_op]) a_constant = quantize_graph.create_constant_node( a_constant_name, value=1, dtype=dtypes.float32,",
"Verify there is only one Quantize, one Requantize op, and",
"24], dtype=dtypes.float32, shape=[2, 2, 3]) float_graph_def.node.extend([b_constant]) concat_node = quantize_graph.create_node( \"Concat\",",
"test for \"quantize\" mode. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None)",
"quantize_graph.create_node(\"Placeholder\", \"input_%s\" % i, []) quantize_graph.set_attr_dtype(node, \"dtype\", dtypes.float32) quantize_graph.set_attr_shape(node, \"shape\",",
"different values ({1}%), with mean\" \" difference {2} and mean",
"graph_util.extract_sub_graph(output, [add_name]) self.assertProtoEquals(expected_output, stripped_output) def test_batch_norm(self): input_constant_name = \"input_constant\" mean_constant_name",
"tf_logging.info(\"Tensors have {0} different values ({1}%), with mean\" \" difference",
"matmul_1 = input*weight_1 input_node = quantize_graph.create_constant_node( \"input\", value=[0, 1, 2,",
"shape=[2, 2, 3]) shape = quantize_graph.create_constant_node( \"shape\", value=[12], dtype=dtypes.int32, shape=[1])",
"dtypes.uint8) graph_def.node.extend([b_dequantize_node]) b_quantize_node = quantize_graph.create_node( \"QuantizeV2\", b_quantize_name, [b_dequantize_name, b_dequantize_name +",
"avg_pool_name, [input_constant_name]) quantize_graph.set_attr_dtype(avg_pool_node, \"T\", dtypes.float32) quantize_graph.set_attr_int_list(avg_pool_node, \"ksize\", [1, 2, 2,",
"a_constant = quantize_graph.create_constant_node( a_constant_name, value=(0,), dtype=dtypes.quint8, shape=[]) expected_output.node.extend([a_constant]) a_constant_min =",
"= run_graph_def(graph_def, input_map, output_tensors) for expected, result in zip(float_results, results):",
"[ a_constant_name, b_constant_name, a_constant_min_name, a_constant_max_name, b_constant_min_name, b_constant_max_name ]) quantize_graph.set_attr_dtype(mat_mul_node, \"T1\",",
"float_graph_def.node.extend([relu_node]) test_graph(float_graph_def, {}, [relu_name]) def test_relu_w_fake_quant_w_min_max_vars(self): input_node = quantize_graph.create_constant_node( \"input\",",
"shape=[2, 6]) float_graph_def.node.extend([input_constant]) split_constant = quantize_graph.create_constant_node( split_constant_name, value=1, dtype=dtypes.int32, shape=[])",
"dtypes.float32) quantize_graph.set_attr_int_list(avg_pool_node, \"ksize\", [1, 2, 2, 1]) quantize_graph.set_attr_int_list(avg_pool_node, \"strides\", [1,",
"between tensors on failure, paying special attention to possible biases",
"self.assertProtoEquals(expected_output, stripped_output) def test_batch_norm(self): input_constant_name = \"input_constant\" mean_constant_name = \"mean_constant\"",
"n]) float_graph_def.node.extend([b_constant]) mat_mul_node = quantize_graph.create_node(\"MatMul\", mat_mul_name, [a_constant_name, b_constant_name]) quantize_graph.set_attr_dtype(mat_mul_node, \"T\",",
"\"max_bias_add\", value=12, dtype=dtypes.float32, shape=[]) fake_quant_node = quantize_graph.create_node( \"FakeQuantWithMinMaxVars\", \"fake_quant\", [relu_node.name,",
"g.node.extend([ input_node, weight_1_node, matmul_1_node, new_shape_node, reshape_node, weight_2_node, matmul_2_node ]) #",
"[mat_mul_name], quantized_input_range=None) output = rewriter.remove_redundant_quantization(graph_def) stripped_output = graph_util.extract_sub_graph(output, [mat_mul_name]) self.assertProtoEquals(expected_output,",
"= quantize_graph.create_constant_node( \"input\", value=[0, 1, 2, 3], dtype=dtypes.float32, shape=[4, 1])",
"input_map, # [output_name + \":0\"]) # assert are_tensors_near(expected, round_results[0], 1.0)",
"11, 12], dtype=dtypes.float32, shape=[1, 2, 6, 1]) float_graph_def.node.extend([input_constant]) max_pool_node =",
"stride, padding, input_values, filter_values): \"\"\"Tests a Conv replacement.\"\"\" input_constant_name =",
"float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend([input_node, offset_node, bias_add_node]) test_graph(float_graph_def, {}, [bias_add_node.name], log_graph=True)",
"10, 11, 12], dtype=dtypes.float32, shape=[1, 2, 6, 1]) relu_node =",
"<input_range>. rewriter = quantize_graph.GraphRewriter(float_graph_def, \"eightbit\", input_range) graph_def = rewriter.rewrite(output_names) results",
"\"Conv2D\", conv_name, [input_constant_name, filter_constant_name]) quantize_graph.set_attr_dtype(conv_node, \"T\", dtypes.float32) quantize_graph.set_attr_int_list(conv_node, \"strides\", [1,",
"g = graph_pb2.GraphDef() g.node.extend([a, shape, reshape]) test_graph(g, {}, [reshape.name]) def",
"\":1\", b_dequantize_name + \":2\"]) quantize_graph.set_attr_dtype(b_quantize_node, \"T\", dtypes.uint8) graph_def.node.extend([b_quantize_node]) mat_mul_node =",
"weights_rounded_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"weights_rounded\", quantized_input_range=None) weights_rounded_graph_def = weights_rounded_rewriter.rewrite(output_names) weights_rounded_results",
"quantize_graph.set_attr_dtype(mat_mul_node, \"T\", dtypes.float32) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend(inputs + [mat_mul_node]) input_map",
"5, 6], [7, 8, 9, 10, 11, 12, 13, 14,",
"script. \"\"\" from __future__ import absolute_import from __future__ import division",
"there is only one Quantize, one Requantize op, and no",
"in output_names]) # TODO(petewarden): round test is currently failing because",
"quantize_graph.create_node( \"BatchNormWithGlobalNormalization\", batch_norm_name, [ input_constant_name, mean_constant_name, variance_constant_name, beta_constant_name, gamma_constant_name ])",
"working currently. return quantized_input_map = {} for k, v in",
"max: max_value = value max_index = index return max_index, max_value",
"input_map, output_tensors) # Quantize treating the input as quantized in",
"quantized. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite([concat_name])",
"no_op_name]) graph_def.node.extend([a_identity_node]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=1, dtype=dtypes.float32, shape=[]) graph_def.node.extend([b_constant])",
"are nearly identical. This is a specialized comparison function designed",
"round((n - input_range[0]) * 255 / (input_range[1] - input_range[ 0])))",
"= arr.astype(dtypes.quint8.as_numpy_dtype) quantized_input_map[k] = arr output_tensors = [output_name + \":0\"",
"[a_identity_name, b_constant_name]) quantize_graph.set_attr_dtype(add_node, \"T\", dtypes.float32) expected_output.node.extend([add_node]) expected_output.versions.CopyFrom(graph_def.versions) expected_output.library.CopyFrom(graph_def.library) output =",
"License for the specific language governing permissions and # limitations",
"def test_mat_mul(m, n, k, a, b): \"\"\"Tests a MatMul replacement.\"\"\"",
"14, 15, 16, 17, 18]) def test_conv(self): test_conv(1, 4, 3,",
"op. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite([fake_quant_node.name])",
"Reserved. # # Licensed under the Apache License, Version 2.0",
"are const and can be quantized up-front. self.assertEqual(0, ops.count(\"QuantizeV2\") +",
"= \"bias_add\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=[1,",
"\"T\", dtypes.float32) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend([input_node, offset_node, bias_add_node]) test_graph(float_graph_def, {},",
"3, 1, 2, b\"SAME\", [1, 2, 3, 4, 5, 6,",
"test_graph(float_graph_def, {}, [bias_add_name]) def test_quantized_input_range_errors(self): with self.assertRaises(ValueError): # Invalid mode.",
"and mean absolute difference {3}\".format( how_many_different, proportion_different * 100, mean_difference,",
"+ [mat_mul_node]) input_map = { inputs[0].name + \":0\": np.reshape([1, 2,",
"\"input_constant\" offset_constant_name = \"offset_constant\" bias_add_name = \"bias_add\" float_graph_def = graph_pb2.GraphDef()",
"inputs[1].name + \":0\": np.reshape([.8, .7, .6, .5, .4, .3, .2,",
"value_count mean_abs_difference = total_abs_difference / value_count proportion_different = (how_many_different *",
"[output_name + \":0\" for output_name in output_names]) for expected, result",
"array of length 1. arr = np.array([1]) qarr = quantize_graph.quantize_array(arr,",
"b_check_name, [b_constant_name]) graph_def.node.extend([b_check_node]) b_identity_node = quantize_graph.create_node( \"Identity\", b_identity_name, [b_constant_name, \"^\"",
"in graph_def.node] self.assertEqual(0, ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) self.assertEqual(len(output_names), ops.count(\"Dequantize\")) # Quantize",
"quantize_graph.create_node( \"BiasAdd\", \"bias_add\", [input_node.name, offset_node.name]) quantize_graph.set_attr_dtype(bias_add_node, \"T\", dtypes.float32) float_graph_def =",
"6, 7, 8, 9, 10, 11, 12, 13, 14, 15,",
"[2], [3]) test_mat_mul(1, 2, 1, [1], [2, 3]) test_mat_mul(1, 1,",
"[a_constant_name, b_constant_name]) quantize_graph.set_attr_dtype(mat_mul_node, \"T\", dtypes.float32) quantize_graph.set_attr_bool(mat_mul_node, \"transpose_a\", False) quantize_graph.set_attr_bool(mat_mul_node, \"transpose_b\",",
"-2, -5, -3, -6], dtype=dtypes.float32, shape=[1, 1, 6, 2]) float_graph_def.node.extend([input_constant])",
"1]) float_graph_def.node.extend([input_constant]) max_pool_node = quantize_graph.create_node(\"MaxPool\", max_pool_name, [input_constant_name]) quantize_graph.set_attr_int_list(max_pool_node, \"ksize\", [1,",
"9, 10, 11, 12], dtype=dtypes.float32, shape=[1, 1, 2, 6]) float_graph_def.node.extend([input_constant])",
"in zip(float_results, weights_rounded_results): assert are_tensors_near(expected, result, 1.0) class QuantizeGraphTest(test.TestCase): def",
"quantize_graph.create_node( \"BiasAdd\", \"bias_add\", [input_node.name, offset_node.name]) quantize_graph.set_attr_dtype(bias_add_node, \"T\", dtypes.float32) min_node =",
"= quantize_graph.create_node(\"Placeholder\", \"input_%s\" % i, []) quantize_graph.set_attr_dtype(node, \"dtype\", dtypes.float32) quantize_graph.set_attr_shape(node,",
"= \"b_constant\" a_check_name = \"a_check\" b_check_name = \"b_check\" a_identity_name =",
"return True else: tf_logging.info(\"Tensors have {0} different values ({1}%), with",
"expected_output.node.extend([a_identity_node]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=1, dtype=dtypes.float32, shape=[]) expected_output.node.extend([b_constant]) add_node",
"rewriter and tests the results.\"\"\" float_results = run_graph_def( float_graph_def, input_map,",
"dtypes.float32) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend(inputs + [mat_mul_node]) input_map = {",
"expected, result in zip(float_results, eightbit_results): assert are_tensors_near(expected, result, 1.0) if",
"quantize_graph.create_node( \"Identity\", a_identity_name, [a_constant_name, \"^\" + no_op_name]) expected_output.node.extend([a_identity_node]) b_constant =",
"b_constant = quantize_graph.create_constant_node( b_constant_name, value=1, dtype=dtypes.float32, shape=[]) graph_def.node.extend([b_constant]) b_check_node =",
"fallback_quantization_range=[-100, 100]) eightbit_graph_def = eightbit_rewriter.rewrite([fake_quant_node.name]) ops = [node.op for node",
"\"T\", dtypes.float32) float_graph_def.node.extend([identity_node]) mul_name = \"mul\" mul_node = quantize_graph.create_node(\"Mul\", mul_name,",
"a.name, b.name]) quantize_graph.set_attr_int(concat, \"N\", 2) quantize_graph.set_attr_dtype(concat, \"T\", dtypes.int32) g =",
"in graph_def.node] self.assertEqual( len(input_map), ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) self.assertEqual(len(output_names), ops.count(\"Dequantize\")) def",
"= flags_lib FLAGS = flags.FLAGS def run_graph_def(graph_def, input_map, outputs): graph",
"for output_name in output_names]) for expected, result in zip(float_results, eightbit_results):",
"3, 4, 5, 6], [7, 8, 9, 10, 11, 12,",
"input_constant = quantize_graph.create_constant_node( input_constant_name, value=[1, 2, 3, 4, 5, 6,",
"= \"shape_constant\" shape_constant = quantize_graph.create_constant_node( shape_constant_name, value=-0.8, dtype=dtypes.float32, shape=[1]) quantization_result",
"7, 8, 9, 10, 11, 12], dtype=dtypes.float32, shape=[2, 6]) float_graph_def.node.extend([input_constant])",
"quantize_graph.set_attr_dtype(conv_node, \"T\", dtypes.float32) quantize_graph.set_attr_int_list(conv_node, \"strides\", [1, stride, stride, 1]) quantize_graph.set_attr_string(conv_node,",
"tensorflow.python.framework import ops as ops_lib from tensorflow.python.platform import flags as",
"3, 4, 5, 6], shapes[0]), inputs[1].name + \":0\": np.reshape([.8, .7,",
"def test_relu_w_fake_quant_w_min_max_vars(self): input_node = quantize_graph.create_constant_node( \"input\", value=[1, 2, 3, 4,",
"11, 12], dtype=dtypes.float32, shape=[1, 2, 6, 1]) float_graph_def.node.extend([input_constant]) relu6_node =",
"used instead. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None, fallback_quantization_range=[-100, 100])",
"proportion_different = (how_many_different * 1.0) / value_count if how_many_different ==",
"Quantize treating the input as quantized in range <input_range>. rewriter",
"value=a, dtype=dtypes.float32, shape=[m, k]) float_graph_def.node.extend([a_constant]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=b,",
"\"eightbit\", quantized_input_range=None) graph_def = rewriter.rewrite(output_names) results = run_graph_def(graph_def, input_map, output_tensors)",
"different sizes: \" + str(len(flat_a)) + \" vs \" +",
"ops.count(\"Dequantize\")) # The fallback constants are not in the graph.",
"a = quantize_graph.create_constant_node( \"a\", value=[1, 2, 3, 4, 5, 6,",
"a_constant_max_name, value=2, dtype=dtypes.float32, shape=[]) expected_output.node.extend([a_constant_max]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=(0,),",
"dtype=dtypes.int32, shape=[]) float_graph_def.node.extend([split_constant]) split_node = quantize_graph.create_node( \"Split\", split_name, [split_constant_name, input_constant_name])",
"Args: a: First comparison tensor. b: Second comparison tensor. tolerance:",
"OF ANY KIND, either express or implied. # See the",
"test the generate case where # min(matrix) == max(matrix), which",
"min(matrix) == max(matrix), which used to cause problems. test_mat_mul(1, 1,",
"See the License for the specific language governing permissions and",
"value=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10,",
"test_graph(float_graph_def, {}, [mul_name]) def test_keep_control_edges(self): no_op_name = \"no_op\" a_constant_name =",
"test_bias_add_w_fallback_min_max_vars(self): input_node = quantize_graph.create_constant_node( \"input\", value=[1, 2, 3, 4, 5,",
"1]) quantize_graph.set_attr_string(avg_pool_node, \"padding\", b\"SAME\") float_graph_def.node.extend([avg_pool_node]) test_graph(float_graph_def, {}, [avg_pool_name]) def test_relu(self):",
"= quantize_graph.create_constant_node( beta_constant_name, value=[0.1, 0.6], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([beta_constant]) gamma_constant =",
"quantize_graph.create_constant_node( mean_constant_name, value=[10, 20], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([mean_constant]) variance_constant = quantize_graph.create_constant_node(",
"to in writing, software # distributed under the License is",
"10x2. new_shape_node = quantize_graph.create_constant_node( \"new_shape_node\", value=[10, 2], dtype=dtypes.int32, shape=[2]) reshape_node",
"value=[0, 0], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([gamma_constant]) batch_norm_node = quantize_graph.create_node( \"BatchNormWithGlobalNormalization\", batch_norm_name,",
"float_graph_def.node.extend([max_pool_node]) test_graph(float_graph_def, {}, [max_pool_name]) def test_avg_pool(self): input_constant_name = \"input_constant\" avg_pool_name",
"12], dtype=dtypes.float32, shape=[1, 2, 6, 1]) float_graph_def.node.extend([input_constant]) max_pool_node = quantize_graph.create_node(\"MaxPool\",",
"b): \"\"\"Tests a MatMul replacement.\"\"\" a_constant_name = \"a_constant\" b_constant_name =",
"\"b_dequantize\" b_quantize_name = \"b_quantize\" mat_mul_name = \"mat_mul\" graph_def = graph_pb2.GraphDef()",
"make_matmul(\"matmul_1\", input_node, weight_1_node) # Reshape 4x5 to 10x2. new_shape_node =",
"\"weight_1\", value=[.5, .6, .7, .8, .9], dtype=dtypes.float32, shape=[1, 5]) matmul_1_node",
"5, 6], shapes[0]), inputs[1].name + \":0\": np.reshape([.8, .7, .6, .5,",
"test_quantized_input_range_errors(self): with self.assertRaises(ValueError): # Invalid mode. quantize_graph.GraphRewriter(graph_pb2.GraphDef(), \"weights_rounded\", [0, 1])",
"or agreed to in writing, software # distributed under the",
"\"a_constant_min\" a_constant_max_name = \"a_constant_max\" a_dequantize_name = \"a_dequantize\" a_quantize_name = \"a_quantize\"",
"== qarr).all()) def test_non_float_concat(self): concat_dim = quantize_graph.create_constant_node( \"concat_dim\", value=0, dtype=dtypes.int32,",
"range <input_range>. rewriter = quantize_graph.GraphRewriter(float_graph_def, \"eightbit\", input_range) graph_def = rewriter.rewrite(output_names)",
"return results def test_mat_mul(m, n, k, a, b): \"\"\"Tests a",
"a_constant_name, value=1, dtype=dtypes.float32, shape=[]) graph_def.node.extend([a_constant]) a_check_node = quantize_graph.create_node(\"CheckNumerics\", a_check_name, [a_constant_name])",
"b\"MIN_COMBINED\") self.assertEqual(4, len(quantization_result)) def test_odd_padding_problem(self): \"\"\"Tests one error case we",
"effect # because the FakeQuantWithMinMaxVars are used instead. eightbit_rewriter =",
"b_constant_min_name, value=3, dtype=dtypes.float32, shape=[]) graph_def.node.extend([b_constant_min]) b_constant_max = quantize_graph.create_constant_node( b_constant_max_name, value=3,",
"the mean and absolute average errors. Args: a: First comparison",
"eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite([fake_quant_node.name]) ops",
"value=-0.8, dtype=dtypes.float32, shape=[1]) quantization_result = quantize_graph.quantize_weight_eightbit( shape_constant, b\"MIN_COMBINED\") self.assertEqual(4, len(quantization_result))",
"16, 17, 18, 19, 20, 21, 22, 23, 24], dtype=dtypes.int32,",
"11, 12], [1, 4, 7, 2, 5, 8, 3, 6,",
"# Test the graph test_graph(g, {}, [\"matmul_2\"]) # Verify there",
"differences between tensors on failure, paying special attention to possible",
"6], dtype=dtypes.float32, shape=[6]) float_graph_def.node.extend([offset_constant]) bias_add_node = quantize_graph.create_node( \"BiasAdd\", bias_add_name, [input_constant_name,",
"results): assert are_tensors_near(expected, result, .5) ops = [node.op for node",
"add_name, [a_identity_name, b_constant_name]) quantize_graph.set_attr_dtype(add_node, \"T\", dtypes.float32) expected_output.node.extend([add_node]) expected_output.versions.CopyFrom(graph_def.versions) expected_output.library.CopyFrom(graph_def.library) output",
"# ============================================================================== \"\"\"Tests the graph quantization script. \"\"\" from __future__",
"the default bit_depth. weights_rounded_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"weights_rounded\", quantized_input_range=None) weights_rounded_graph_def",
"\"shape_constant\" shape_constant = quantize_graph.create_constant_node( shape_constant_name, value=-0.8, dtype=dtypes.float32, shape=[1]) quantization_result =",
"2) quantize_graph.set_attr_dtype(concat_node, \"T\", dtypes.float32) float_graph_def.node.extend([concat_node]) test_graph(float_graph_def, {}, [concat_name]) # Verify",
"value=[10, 20], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([mean_constant]) variance_constant = quantize_graph.create_constant_node( variance_constant_name, value=[0.25,",
"6]) float_graph_def.node.extend([input_constant]) offset_constant = quantize_graph.create_constant_node( offset_constant_name, value=[1, 2, 3, 4,",
"100, mean_difference, mean_abs_difference)) return False def get_top_value(input_values): max_value = None",
"= quantize_graph.create_constant_node( \"b\", value=[13, 14, 15, 16, 17, 18, 19,",
"compliance with the License. # You may obtain a copy",
"return quantized_input_map = {} for k, v in input_map.items(): arr",
"All Rights Reserved. # # Licensed under the Apache License,",
"0.5, 0.5, 0.5]) == qarr).all()) qarr = quantize_graph.quantize_array(arr, 2) self.assertTrue((np.array([0.25,",
"def test_relu6(self): input_constant_name = \"input_constant\" relu6_name = \"relu6\" float_graph_def =",
"= ops_lib.Graph() with graph.as_default(): importer.import_graph_def(graph_def, input_map={}, name=\"\") with session.Session(graph=graph) as",
"results = sess.run(outputs, feed_dict=input_map) return results def test_mat_mul(m, n, k,",
"0.75]) == qarr).all()) qarr = quantize_graph.quantize_array(arr.reshape((2, 2)), 2) self.assertTrue((np.array([[0.25, 0.25],",
"= \"b_constant_min\" b_constant_max_name = \"b_constant_max\" b_dequantize_name = \"b_dequantize\" b_quantize_name =",
"weights_rounded_rewriter.rewrite(output_names) weights_rounded_results = run_graph_def( weights_rounded_graph_def, input_map, [output_name + \":0\" for",
"input_map={}, name=\"\") with session.Session(graph=graph) as sess: results = sess.run(outputs, feed_dict=input_map)",
"11, 12], dtype=dtypes.float32, shape=[1, 2, 6, 1]) relu_node = quantize_graph.create_node(\"Relu\",",
"expected_output = graph_pb2.GraphDef() a_constant = quantize_graph.create_constant_node( a_constant_name, value=(0,), dtype=dtypes.quint8, shape=[])",
"graph_pb2.GraphDef() a_constant = quantize_graph.create_constant_node( a_constant_name, value=(0,), dtype=dtypes.quint8, shape=[]) expected_output.node.extend([a_constant]) a_constant_min",
"input_map, output_names, input_range): if sys.version_info[0] == 3: # uint8->quint8 conversion",
"dtype=dtypes.float32, shape=[image_batch_count, image_height, image_width, depth]) float_graph_def.node.extend([input_constant]) filter_constant = quantize_graph.create_constant_node( filter_constant_name,",
"[1, 1], [1, 1]) test_mat_mul(1, 1, 2, [0, 0], [1,",
"[1, 1, 1, 1]) quantize_graph.set_attr_string(avg_pool_node, \"padding\", b\"SAME\") float_graph_def.node.extend([avg_pool_node]) test_graph(float_graph_def, {},",
"\"T\", dtypes.int32) g = graph_pb2.GraphDef() g.node.extend([a, shape, reshape]) test_graph(g, {},",
"one Quantize and one Requantize op. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def,",
"not use this file except in compliance with the License.",
"results = run_graph_def(graph_def, input_map, output_tensors) for expected, result in zip(float_results,",
"4, 5, 6, 7, 8, 9, 10, 11, 12], dtype=dtypes.int32,",
"float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=input_values, dtype=dtypes.float32, shape=[image_batch_count,",
"\"scale_after_normalization\", False) quantize_graph.set_attr_float(batch_norm_node, \"variance_epsilon\", 0.001) float_graph_def.node.extend([batch_norm_node]) test_graph(float_graph_def, {}, [batch_norm_name]) def",
"a_constant = quantize_graph.create_constant_node( a_constant_name, value=(0,), dtype=dtypes.quint8, shape=[]) graph_def.node.extend([a_constant]) a_constant_min =",
"input_constant_name, mean_constant_name, variance_constant_name, beta_constant_name, gamma_constant_name ]) quantize_graph.set_attr_dtype(batch_norm_node, \"T\", dtypes.float32) quantize_graph.set_attr_bool(batch_norm_node,",
"min_node, max_node, fake_quant_node ]) test_graph(float_graph_def, {}, [fake_quant_node.name], log_graph=True) # Verify",
"quantize_graph.create_node(\"MatMul\", mat_mul_name, [a_constant_name, b_constant_name]) quantize_graph.set_attr_dtype(mat_mul_node, \"T\", dtypes.float32) quantize_graph.set_attr_bool(mat_mul_node, \"transpose_a\", False)",
"session.Session(graph=graph) as sess: results = sess.run(outputs, feed_dict=input_map) return results def",
"in a real graph.\"\"\" test_conv(1, 4, 4, 1, 3, 1,",
"Requantize op, and no # RequantizationRange op. eightbit_rewriter = quantize_graph.GraphRewriter(",
"you may not use this file except in compliance with",
"\"transpose_b\", False) return n # matmul_1 = input*weight_1 input_node =",
"= \"b_dequantize\" b_quantize_name = \"b_quantize\" mat_mul_name = \"mat_mul\" graph_def =",
"No RequantizationRange self.assertEqual(0, ops.count(\"RequantizationRange\")) # The fallback constants are in",
"relu_node, min_node, max_node, fake_quant_node]) test_graph(float_graph_def, {}, [fake_quant_node.name], log_graph=True) # Verify",
"6, 1]) float_graph_def.node.extend([input_constant]) max_pool_node = quantize_graph.create_node(\"MaxPool\", max_pool_name, [input_constant_name]) quantize_graph.set_attr_int_list(max_pool_node, \"ksize\",",
"import division from __future__ import print_function import sys import numpy",
"\"avg_pool\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=[1, 2,",
"[ input_constant_name, mean_constant_name, variance_constant_name, beta_constant_name, gamma_constant_name ]) quantize_graph.set_attr_dtype(batch_norm_node, \"T\", dtypes.float32)",
"i, shape in enumerate(shapes): node = quantize_graph.create_node(\"Placeholder\", \"input_%s\" % i,",
"float_graph_def.node.extend([split_constant]) split_node = quantize_graph.create_node( \"Split\", split_name, [split_constant_name, input_constant_name]) quantize_graph.set_attr_int(split_node, \"num_split\",",
"= \"concat_constant\" concat_name = \"concat\" float_graph_def = graph_pb2.GraphDef() input_constant =",
"input_constant_name = \"input_constant\" avg_pool_name = \"avg_pool\" float_graph_def = graph_pb2.GraphDef() input_constant",
"\"fake_quant\", [bias_add_node.name, min_node.name, max_node.name]) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend([ input_node, offset_node,",
"tensorflow.python.platform import flags as flags_lib from tensorflow.python.platform import test from",
"large an error between values is ok. Returns: Boolean indicating",
"mat_mul_node = quantize_graph.create_node(\"QuantizedMatMul\", mat_mul_name, [ a_constant_name, b_constant_name, a_constant_min_name, a_constant_max_name, b_constant_min_name,",
"[1, 1, 1, 1]) quantize_graph.set_attr_string(max_pool_node, \"padding\", b\"SAME\") float_graph_def.node.extend([max_pool_node]) test_graph(float_graph_def, {},",
"\"\"\"Runs the float graph through the rewriter and tests the",
"concat_node = quantize_graph.create_node( \"Concat\", concat_name, [shape_constant_name, a_constant_name, b_constant_name]) quantize_graph.set_attr_int(concat_node, \"N\",",
"\"b_constant\" b_constant_min_name = \"b_constant_min\" b_constant_max_name = \"b_constant_max\" b_dequantize_name = \"b_dequantize\"",
"a_quantize_name, [a_dequantize_name, a_dequantize_name + \":1\", a_dequantize_name + \":2\"]) quantize_graph.set_attr_dtype(a_quantize_node, \"T\",",
"\"transpose_b\", False) float_graph_def.node.extend([mat_mul_node]) test_graph(float_graph_def, {}, [mat_mul_name]) def test_conv(depth, image_width, image_height,",
"special attention to possible biases by looking at the mean",
"23, 24], dtype=dtypes.float32, shape=[2, 2, 3]) float_graph_def.node.extend([b_constant]) concat_node = quantize_graph.create_node(",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"result in zip(float_results, weights_rounded_results): assert are_tensors_near(expected, result, 1.0) class QuantizeGraphTest(test.TestCase):",
"One dequantize at the end. self.assertEqual(1, ops.count(\"Dequantize\")) def test_quantize_array(self): #",
"into in a real graph.\"\"\" test_conv(1, 4, 4, 1, 3,",
"self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [mat_mul_node.name], [0, 6.]) def _RunTestsForQuantizedInputRange(self, float_graph_def, input_map, output_names,",
"no # RoundToSteps op available. # round_rewriter = quantize_graph.GraphRewriter(float_graph_def, \"round\")",
"\"N\", 2) quantize_graph.set_attr_dtype(concat, \"T\", dtypes.int32) g = graph_pb2.GraphDef() g.node.extend([concat_dim, a,",
"one Requantize op. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None) eightbit_graph_def",
"6, 1]) float_graph_def.node.extend([input_constant]) relu_node = quantize_graph.create_node(\"Relu\", relu_name, [input_constant_name]) quantize_graph.set_attr_dtype(relu_node, \"T\",",
"dtype=dtypes.float32, shape=[1, 2, 6, 1]) relu_node = quantize_graph.create_node(\"Relu\", \"relu\", [input_node.name])",
"= graph_pb2.GraphDef() float_graph_def.node.extend([input_n, offset_n, bias_add_n]) input_map = { input_n.name +",
"range(value_count): a_value = flat_a[index] b_value = flat_b[index] difference = a_value",
"quantize_graph.create_constant_node( shape_constant_name, value=0, dtype=dtypes.int32, shape=[]) float_graph_def.node.extend([shape_constant]) a_constant = quantize_graph.create_constant_node( a_constant_name,",
"feed_dict=input_map) return results def test_mat_mul(m, n, k, a, b): \"\"\"Tests",
"\"input_constant\" split_constant_name = \"split_constant\" split_name = \"split\" concat_constant_name = \"concat_constant\"",
"the graph test_graph(g, {}, [\"matmul_2\"]) # Verify there is only",
"test_quantized_input_range_mat_mul(self): shapes = [[3, 2], [2, 4]] inputs = []",
"= quantize_graph.quantize_array(arr, 1) self.assertTrue((np.array([0.5, 0.5, 0.5, 0.5]) == qarr).all()) qarr",
"float_graph_def.node.extend([input_constant]) avg_pool_node = quantize_graph.create_node(\"AvgPool\", avg_pool_name, [input_constant_name]) quantize_graph.set_attr_dtype(avg_pool_node, \"T\", dtypes.float32) quantize_graph.set_attr_int_list(avg_pool_node,",
"[]) quantize_graph.set_attr_dtype(node, \"dtype\", dtypes.float32) quantize_graph.set_attr_shape(node, \"shape\", shape) inputs.append(node) mat_mul_node =",
"currently failing because there is no # RoundToSteps op available.",
"= quantize_graph.create_constant_node( split_constant_name, value=1, dtype=dtypes.int32, shape=[]) float_graph_def.node.extend([split_constant]) split_node = quantize_graph.create_node(",
"eightbit_rewriter.rewrite([fake_quant_node.name]) ops = [node.op for node in eightbit_graph_def.node] node_names =",
"b\"SAME\", [1, 2, 3, 4, 5, 6, 7, 8, 9,",
"ops.count(\"QuantizedReshape\")) # One dequantize at the end. self.assertEqual(1, ops.count(\"Dequantize\")) def",
"dtype=dtypes.float32, shape=[1, 2, 6, 1]) float_graph_def.node.extend([input_constant]) relu6_node = quantize_graph.create_node(\"Relu6\", relu6_name,",
"= graph_util.extract_sub_graph(output, [mat_mul_name]) self.assertProtoEquals(expected_output, stripped_output) if __name__ == \"__main__\": test.main()",
"float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=[1, 2, 3,",
"3, [1, 2, 3, 4, 5, 6], [7, 8, 9,",
"11, 12], dtype=dtypes.float32, shape=[2, 6]) float_graph_def.node.extend([input_constant]) split_constant = quantize_graph.create_constant_node( split_constant_name,",
"= graph_pb2.GraphDef() no_op = quantize_graph.create_node(\"NoOp\", no_op_name, []) expected_output.node.extend([no_op]) a_constant =",
"quantize_graph.create_node(\"NoOp\", no_op_name, []) expected_output.node.extend([no_op]) a_constant = quantize_graph.create_constant_node( a_constant_name, value=1, dtype=dtypes.float32,",
"round test is currently failing because there is no #",
"= \"input_constant\" relu6_name = \"relu6\" float_graph_def = graph_pb2.GraphDef() input_constant =",
"mat_mul_name, [ a_constant_name, b_constant_name, a_constant_min_name, a_constant_max_name, b_constant_min_name, b_constant_max_name ]) quantize_graph.set_attr_dtype(mat_mul_node,",
"expected, result in zip(float_results, results): assert are_tensors_near(expected, result, .5) ops",
"+ \":0\" for output_name in output_names] float_results = run_graph_def(float_graph_def, input_map,",
"self.assertEqual( len(input_map), ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) self.assertEqual(len(output_names), ops.count(\"Dequantize\")) def test_bias_add_w_fake_quant_w_min_max_vars(self): input_node",
"# Verify the concat is quantized. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def,",
"\"T\", dtypes.float32) float_graph_def.node.extend([relu_node]) test_graph(float_graph_def, {}, [relu_name]) def test_relu_w_fake_quant_w_min_max_vars(self): input_node =",
"weight_2_node, matmul_2_node ]) # Test the graph test_graph(g, {}, [\"matmul_2\"])",
"float_graph_def.node.extend([input_node, offset_node, bias_add_node]) test_graph(float_graph_def, {}, [bias_add_node.name], log_graph=True) # Verify there",
"[input_node, relu_node, min_node, max_node, fake_quant_node]) test_graph(float_graph_def, {}, [fake_quant_node.name], log_graph=True) #",
".1], shapes[1]) } self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [mat_mul_node.name], [-1, 20.]) self._RunTestsForQuantizedInputRange(float_graph_def, input_map,",
"in the graph. self.assertEqual(1, node_names.count(\"fallback_quantization_min_value\")) self.assertEqual(1, node_names.count(\"fallback_quantization_max_value\")) def test_remove_redundant_quantization(self): a_constant_name",
"\"T1\", dtypes.uint8) quantize_graph.set_attr_dtype(mat_mul_node, \"T2\", dtypes.int32) expected_output.node.extend([mat_mul_node]) expected_output.versions.CopyFrom(graph_def.versions) expected_output.library.CopyFrom(graph_def.library) rewriter =",
"0) # Test input array of length 1. arr =",
"max_index, max_value def test_graph(float_graph_def, input_map, output_names, log_graph=False): \"\"\"Runs the float",
"zip(float_results, results): assert are_tensors_near(expected, result, .5) ops = [node.op for",
"be quantized up-front. self.assertEqual(0, ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) # One dequantize",
"node in graph_def.node] self.assertEqual( len(input_map), ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) self.assertEqual(len(output_names), ops.count(\"Dequantize\"))",
"tensors on failure, paying special attention to possible biases by",
"run_graph_def(round_graph_def, input_map, # [output_name + \":0\"]) # assert are_tensors_near(expected, round_results[0],",
"a, b): \"\"\"Tests a MatMul replacement.\"\"\" a_constant_name = \"a_constant\" b_constant_name",
"graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=[1, 4, 2, 5, 3,",
"dtype=dtypes.float32, shape=[]) max_node = quantize_graph.create_constant_node( \"max_bias_add\", value=12, dtype=dtypes.float32, shape=[]) fake_quant_node",
"graph_def.node.extend([a_check_node]) a_identity_node = quantize_graph.create_node( \"Identity\", a_identity_name, [a_constant_name, \"^\" + a_check_name,",
"weight_2_node = quantize_graph.create_constant_node( \"weight_2\", value=[1.5, 2.5], dtype=dtypes.float32, shape=[2, 1]) matmul_2_node",
"12], dtype=dtypes.int32, shape=[2, 2, 3]) b = quantize_graph.create_constant_node( \"b\", value=[13,",
"graph through the rewriter and tests the results.\"\"\" float_results =",
"input_node, weight_1_node, matmul_1_node, new_shape_node, reshape_node, weight_2_node, matmul_2_node ]) # Test",
"# limitations under the License. # ============================================================================== \"\"\"Tests the graph",
"float_graph_def = graph_pb2.GraphDef() shape_constant = quantize_graph.create_constant_node( shape_constant_name, value=0, dtype=dtypes.int32, shape=[])",
"input_node = quantize_graph.create_constant_node( \"input\", value=[1, 2, 3, 4, 5, 6,",
"= quantize_graph.create_constant_node( filter_constant_name, value=filter_values, dtype=dtypes.float32, shape=[filter_size, filter_size, depth, filter_count]) float_graph_def.node.extend([filter_constant])",
"quantize_graph flags = flags_lib FLAGS = flags.FLAGS def run_graph_def(graph_def, input_map,",
"7, 8, 9, 10, 11, 12], dtype=dtypes.float32, shape=[1, 2, 6,",
"value=3, dtype=dtypes.float32, shape=[]) expected_output.node.extend([b_constant_min]) b_constant_max = quantize_graph.create_constant_node( b_constant_max_name, value=3, dtype=dtypes.float32,",
"conversion for numpy is not working currently. return quantized_input_map =",
"\"T\", dtypes.float32) min_node = quantize_graph.create_constant_node( \"min_bias_add\", value=-.5, dtype=dtypes.float32, shape=[]) max_node",
"Pass in fallback_quantization_range, although it will have no effect #",
"self.assertRaises(ValueError, quantize_graph.quantize_array, np.array([1, 2]), 0) # Test input array of",
"float_graph_def.node.extend([conv_node]) test_graph(float_graph_def, {}, [conv_name]) def are_tensors_near(a, b, tolerance): \"\"\"Tests whether",
"\"T\", dtypes.float32) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend([input_n, offset_n, bias_add_n]) input_map =",
"instead. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None, fallback_quantization_range=[-100, 100]) eightbit_graph_def",
"b_quantize_name + \":1\", b_quantize_name + \":2\" ]) quantize_graph.set_attr_dtype(mat_mul_node, \"T1\", dtypes.uint8)",
"at the mean and absolute average errors. Args: a: First",
"quantize_graph.create_constant_node( \"concat_dim\", value=0, dtype=dtypes.int32, shape=[]) a = quantize_graph.create_constant_node( \"a\", value=[1,",
"test_reshape(self): \"\"\"Tests that MatMul->Reshape->MatMul avoids extra quantize/dequantize.\"\"\" def make_matmul(name, a,",
"2, 6, 1]) float_graph_def.node.extend([input_constant]) avg_pool_node = quantize_graph.create_node(\"AvgPool\", avg_pool_name, [input_constant_name]) quantize_graph.set_attr_dtype(avg_pool_node,",
"[bias_add_node.name, min_node.name, max_node.name]) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend([ input_node, offset_node, bias_add_node,",
"\"N\", 2) quantize_graph.set_attr_dtype(concat_node, \"T\", dtypes.float32) float_graph_def.node.extend([concat_node]) test_graph(float_graph_def, {}, [concat_name]) #",
"MatMul->Reshape->MatMul avoids extra quantize/dequantize.\"\"\" def make_matmul(name, a, b): n =",
"b_constant_name = \"b_constant\" mat_mul_name = \"mat_mul\" float_graph_def = graph_pb2.GraphDef() a_constant",
"License. # ============================================================================== \"\"\"Tests the graph quantization script. \"\"\" from",
"[1, 2], [1, 2]) def test_mat_mul_small(self): test_mat_mul(2, 4, 3, [1,",
"Quantize without treating input as quantized. rewriter = quantize_graph.GraphRewriter( float_graph_def,",
"mean_constant_name, value=[10, 20], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([mean_constant]) variance_constant = quantize_graph.create_constant_node( variance_constant_name,",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"2, 2, 1]) quantize_graph.set_attr_int_list(max_pool_node, \"strides\", [1, 1, 1, 1]) quantize_graph.set_attr_string(max_pool_node,",
"1, 1, [2], [3]) test_mat_mul(1, 2, 1, [1], [2, 3])",
"ops.count(\"Dequantize\")) # Quantize without treating input as quantized. rewriter =",
"max_pool_name = \"max_pool\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name,",
"\"relu\", [input_node.name]) quantize_graph.set_attr_dtype(relu_node, \"T\", dtypes.float32) min_node = quantize_graph.create_constant_node( \"min_bias_add\", value=0,",
"dtypes.float32) float_graph_def.node.extend([relu6_node]) test_graph(float_graph_def, {}, [relu6_name]) def test_bias_add(self): input_constant_name = \"input_constant\"",
"eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite(output_names) eightbit_results",
"float_graph_def.node.extend(inputs + [mat_mul_node]) input_map = { inputs[0].name + \":0\": np.reshape([1,",
"quantize_graph.create_constant_node( concat_constant_name, value=1, dtype=dtypes.int32, shape=[]) float_graph_def.node.extend([concat_constant]) concat_node = quantize_graph.create_node( \"Concat\",",
"quantize_graph.quantize_array(arr, 1) self.assertTrue((np.array([0.5, 0.5, 0.5, 0.5]) == qarr).all()) qarr =",
"round_rewriter = quantize_graph.GraphRewriter(float_graph_def, \"round\") # round_graph_def = round_rewriter.rewrite(output_name) # round_results",
"output_names, input_range): if sys.version_info[0] == 3: # uint8->quint8 conversion for",
"\"\"\"Tests a Conv replacement.\"\"\" input_constant_name = \"input_constant\" filter_constant_name = \"filter_constant\"",
"image_height, image_batch_count, filter_size, filter_count, stride, padding, input_values, filter_values): \"\"\"Tests a",
"quantize_graph.create_constant_node( b_constant_name, value=(0,), dtype=dtypes.quint8, shape=[]) expected_output.node.extend([b_constant]) b_constant_min = quantize_graph.create_constant_node( b_constant_min_name,",
"relu6_name = \"relu6\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name,",
"[a_constant_name]) graph_def.node.extend([a_check_node]) a_identity_node = quantize_graph.create_node( \"Identity\", a_identity_name, [a_constant_name, \"^\" +",
"quantize_graph.quantize_array(arr, 2) self.assertTrue((np.array([0.25, 0.25, 0.75, 0.75]) == qarr).all()) qarr =",
"tensorflow.python.platform import test from tensorflow.python.platform import tf_logging from tensorflow.tools.quantization import",
"2) self.assertRaises(ValueError, quantize_graph.quantize_array, np.array([1, 2]), 0) # Test input array",
"quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite(output_names) eightbit_results = run_graph_def( eightbit_graph_def, input_map, [output_name",
"import absolute_import from __future__ import division from __future__ import print_function",
"quantize_graph.create_node( \"Dequantize\", b_dequantize_name, [b_constant_name, b_constant_min_name, b_constant_max_name]) quantize_graph.set_attr_dtype(b_dequantize_node, \"T\", dtypes.uint8) graph_def.node.extend([b_dequantize_node])",
"log_graph=True) # Verify there is only one Quantize, one Requantize",
"mean absolute difference {3}\".format( how_many_different, proportion_different * 100, mean_difference, mean_abs_difference))",
"+ \":0\" for output_name in output_names]) for expected, result in",
"+ \":2\"]) quantize_graph.set_attr_dtype(a_quantize_node, \"T\", dtypes.uint8) graph_def.node.extend([a_quantize_node]) b_constant = quantize_graph.create_constant_node( b_constant_name,",
"test_graph(g, {}, [reshape.name]) def test_concat(self): shape_constant_name = \"shape_constant\" a_constant_name =",
"= quantize_graph.quantize_array(arr.reshape((2, 2)), 2) self.assertTrue((np.array([[0.25, 0.25], [0.75, 0.75]]) == qarr).all())",
"quantize_graph.create_constant_node( split_constant_name, value=1, dtype=dtypes.int32, shape=[]) float_graph_def.node.extend([split_constant]) split_node = quantize_graph.create_node( \"Split\",",
"2) self.assertEqual(arr, qarr) # Test input array with all elements",
"quantize_graph.create_constant_node( b_constant_name, value=b, dtype=dtypes.float32, shape=[k, n]) float_graph_def.node.extend([b_constant]) mat_mul_node = quantize_graph.create_node(\"MatMul\",",
"file except in compliance with the License. # You may",
"value=[1, 2, 3, 4, 5], dtype=dtypes.float32, shape=[5]) bias_add_node = quantize_graph.create_node(",
"quantize_graph.set_attr_dtype(relu_node, \"T\", dtypes.float32) float_graph_def.node.extend([relu_node]) test_graph(float_graph_def, {}, [relu_name]) def test_relu_w_fake_quant_w_min_max_vars(self): input_node",
"len(flat_b): tf_logging.info(\"Tensors are different sizes: \" + str(len(flat_a)) + \"",
"input_constant_name = \"input_constant\" max_pool_name = \"max_pool\" float_graph_def = graph_pb2.GraphDef() input_constant",
"how_many_different == 0: return True else: tf_logging.info(\"Tensors have {0} different",
"7, 2, 5, 8, 3, 6, 9]) def test_reshape(self): \"\"\"Tests",
"= quantize_graph.create_constant_node( \"a\", value=[1, 2, 3, 4, 5, 6, 7,",
"g.node.extend([a, shape, reshape]) test_graph(g, {}, [reshape.name]) def test_concat(self): shape_constant_name =",
"3, 1, 3, 1, 1, b\"SAME\", [1, 2, 3, 4,",
"quantized_input_range=None) graph_def = rewriter.rewrite(output_names) results = run_graph_def(graph_def, input_map, output_tensors) for",
"have no effect # because the FakeQuantWithMinMaxVars are used instead.",
"9, 10, 11, 12], dtype=dtypes.float32, shape=[2, 2, 3]) float_graph_def.node.extend([a_constant]) b_constant",
"9]) def test_mat_mul_tiny(self): # These tests are added to test",
"4, 3, 1, 3, 1, 1, b\"SAME\", [1, 2, 3,",
"numpy is not working currently. return quantized_input_map = {} for",
"QuantizeGraphTest(test.TestCase): def test_negative_const_problem(self): shape_constant_name = \"shape_constant\" shape_constant = quantize_graph.create_constant_node( shape_constant_name,",
"arr = np.array([1]) qarr = quantize_graph.quantize_array(arr, 1) self.assertEqual(arr, qarr) qarr",
"image_height, image_width, depth]) float_graph_def.node.extend([input_constant]) filter_constant = quantize_graph.create_constant_node( filter_constant_name, value=filter_values, dtype=dtypes.float32,",
"test_quantized_input_range_bias_add(self): input_shape = [1, 1, 2, 6] input_n = quantize_graph.create_node(\"Placeholder\",",
"5, 6], dtype=dtypes.float32, shape=[6]) bias_add_n = quantize_graph.create_node(\"BiasAdd\", \"bias_add\", [input_n.name, offset_n.name])",
"One dequantize at the end. self.assertEqual(1, ops.count(\"Dequantize\")) # The fallback",
"= run_graph_def( float_graph_def, input_map, [output_name + \":0\" for output_name in",
"one Requantize op. eightbit_rewriter = quantize_graph.GraphRewriter( g, \"eightbit\", quantized_input_range=None) eightbit_graph_def",
"def test_conv(self): test_conv(1, 4, 3, 1, 3, 1, 1, b\"SAME\",",
"quantize_graph.set_attr_dtype(split_node, \"T\", dtypes.float32) float_graph_def.node.extend([split_node]) concat_constant = quantize_graph.create_constant_node( concat_constant_name, value=1, dtype=dtypes.int32,",
"import graph_util from tensorflow.python.framework import importer from tensorflow.python.framework import ops",
"[0, -1]) def test_quantized_input_range_bias_add(self): input_shape = [1, 1, 2, 6]",
"a_constant_max = quantize_graph.create_constant_node( a_constant_max_name, value=2, dtype=dtypes.float32, shape=[]) expected_output.node.extend([a_constant_max]) b_constant =",
"quantize_graph.set_attr_dtype(bias_add_node, \"T\", dtypes.float32) float_graph_def.node.extend([bias_add_node]) test_graph(float_graph_def, {}, [bias_add_name]) def test_quantized_input_range_errors(self): with",
"for i, shape in enumerate(shapes): node = quantize_graph.create_node(\"Placeholder\", \"input_%s\" %",
"a_check_name, [a_constant_name]) graph_def.node.extend([a_check_node]) a_identity_node = quantize_graph.create_node( \"Identity\", a_identity_name, [a_constant_name, \"^\"",
"quantize_graph.GraphRewriter(float_graph_def, \"round\") # round_graph_def = round_rewriter.rewrite(output_name) # round_results = run_graph_def(round_graph_def,",
"a_dequantize_node = quantize_graph.create_node( \"Dequantize\", a_dequantize_name, [a_constant_name, a_constant_min_name, a_constant_max_name]) quantize_graph.set_attr_dtype(a_dequantize_node, \"T\",",
"5, 6, 7, 8, 9, 10, 11, 12], dtype=dtypes.int32, shape=[2,",
"quantize_graph.set_attr_dtype(a_dequantize_node, \"T\", dtypes.uint8) graph_def.node.extend([a_dequantize_node]) a_quantize_node = quantize_graph.create_node( \"QuantizeV2\", a_quantize_name, [a_dequantize_name,",
"Test invalid parameters (empty array, or 0 buckets. self.assertRaises(ValueError, quantize_graph.quantize_array,",
"float_graph_def.node.extend([b_constant]) concat_node = quantize_graph.create_node( \"Concat\", concat_name, [shape_constant_name, a_constant_name, b_constant_name]) quantize_graph.set_attr_int(concat_node,",
"\"^\" + no_op_name]) graph_def.node.extend([a_identity_node]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=1, dtype=dtypes.float32,",
"importer from tensorflow.python.framework import ops as ops_lib from tensorflow.python.platform import",
"3, 4, 5, 6], dtype=dtypes.float32, shape=[6]) float_graph_def.node.extend([offset_constant]) bias_add_node = quantize_graph.create_node(",
"def test_avg_pool(self): input_constant_name = \"input_constant\" avg_pool_name = \"avg_pool\" float_graph_def =",
"+ \" vs \" + str(len(flat_b))) return False value_count =",
"2, 3]) concat = quantize_graph.create_node(\"Concat\", \"concat\", [concat_dim.name, a.name, b.name]) quantize_graph.set_attr_int(concat,",
"\"T\", dtypes.float32) float_graph_def.node.extend([mul_node]) test_graph(float_graph_def, {}, [mul_name]) def test_keep_control_edges(self): no_op_name =",
"and one Requantize op. # Pass in fallback_quantization_range, although it",
"are_tensors_near(expected, result, 1.0) if log_graph: tf_logging.info(\"8bit:\\n%s\", str(eightbit_graph_def)) # Test the",
"eightbit_graph_def = eightbit_rewriter.rewrite([bias_add_node.name]) ops = [node.op for node in eightbit_graph_def.node]",
"quantize_graph.create_node(\"Placeholder\", \"input\", []) quantize_graph.set_attr_dtype(input_n, \"dtype\", dtypes.float32) quantize_graph.set_attr_shape(input_n, \"shape\", input_shape) offset_n",
"mat_mul_node = quantize_graph.create_node(\"QuantizedMatMul\", mat_mul_name, [ a_quantize_name, b_quantize_name, a_quantize_name + \":1\",",
"in input_map.items(): arr = [ int( round((n - input_range[0]) *",
"node in eightbit_graph_def.node] node_names = [node.name for node in eightbit_graph_def.node]",
"KIND, either express or implied. # See the License for",
"6, 7, 8, 9, 10, 11, 12], [1, 4, 7,",
"self.assertTrue((np.array([1, 1, 1]) == qarr).all()) # Test \"normal\" input arrays.",
"is not working currently. return quantized_input_map = {} for k,",
"shape=[1, 1, 2, 5]) offset_node = quantize_graph.create_constant_node( \"offset\", value=[1, 2,",
"from tensorflow.python.client import session from tensorflow.python.framework import dtypes from tensorflow.python.framework",
"max_node, fake_quant_node ]) test_graph(float_graph_def, {}, [fake_quant_node.name], log_graph=True) # Verify there",
"1, 2, 5]) offset_node = quantize_graph.create_constant_node( \"offset\", value=[1, 2, 3,",
"graph. self.assertEqual(0, node_names.count(\"fallback_quantization_min_value\")) self.assertEqual(0, node_names.count(\"fallback_quantization_max_value\")) def test_bias_add_w_fallback_min_max_vars(self): input_node = quantize_graph.create_constant_node(",
"np.reshape([.8, .7, .6, .5, .4, .3, .2, .1], shapes[1]) }",
"dtype=dtypes.int32, shape=[2, 2, 3]) shape = quantize_graph.create_constant_node( \"shape\", value=[12], dtype=dtypes.int32,",
"4, 3, [1, 2, 3, 4, 5, 6], [7, 8,",
"b: Second comparison tensor. tolerance: Float value indicating how large",
"value in enumerate(input_values.flatten()): if max_value is None or value >",
"input_map = { input_n.name + \":0\": np.reshape([1, 2, 3, 4,",
"input_map = { inputs[0].name + \":0\": np.reshape([1, 2, 3, 4,",
"8, 9, 10, 11, 12], dtype=dtypes.int32, shape=[2, 2, 3]) shape",
"offset_constant_name, value=[1, 2, 3, 4, 5, 6], dtype=dtypes.float32, shape=[6]) float_graph_def.node.extend([offset_constant])",
"np.uint8) arr = arr.reshape(v.shape) arr = arr.astype(dtypes.quint8.as_numpy_dtype) quantized_input_map[k] = arr",
"= quantize_graph.create_constant_node( \"min_bias_add\", value=-.5, dtype=dtypes.float32, shape=[]) max_node = quantize_graph.create_constant_node( \"max_bias_add\",",
"(the \"License\"); # you may not use this file except",
"6] input_n = quantize_graph.create_node(\"Placeholder\", \"input\", []) quantize_graph.set_attr_dtype(input_n, \"dtype\", dtypes.float32) quantize_graph.set_attr_shape(input_n,",
"18, 19, 20, 21, 22, 23, 24], dtype=dtypes.int32, shape=[2, 2,",
"10, 11, 12], dtype=dtypes.float32, shape=[1, 2, 6, 1]) float_graph_def.node.extend([input_constant]) max_pool_node",
"matmul_2_node ]) # Test the graph test_graph(g, {}, [\"matmul_2\"]) #",
"from tensorflow.python.framework import dtypes from tensorflow.python.framework import graph_util from tensorflow.python.framework",
"= graph_util.remove_training_nodes(graph_def) stripped_output = graph_util.extract_sub_graph(output, [add_name]) self.assertProtoEquals(expected_output, stripped_output) def test_batch_norm(self):",
"float_results = run_graph_def(float_graph_def, input_map, output_tensors) # Quantize treating the input",
"Copyright 2015 The TensorFlow Authors. All Rights Reserved. # #",
"value=3, dtype=dtypes.float32, shape=[]) graph_def.node.extend([b_constant_min]) b_constant_max = quantize_graph.create_constant_node( b_constant_max_name, value=3, dtype=dtypes.float32,",
"\"\"\"Tests a MatMul replacement.\"\"\" a_constant_name = \"a_constant\" b_constant_name = \"b_constant\"",
"= \"gamma_constant\" batch_norm_name = \"batch_norm\" float_graph_def = graph_pb2.GraphDef() input_constant =",
"v.flat ] arr = np.array(arr, np.uint8) arr = arr.reshape(v.shape) arr",
"# # Unless required by applicable law or agreed to",
"dtypes.float32) min_node = quantize_graph.create_constant_node( \"min_bias_add\", value=0, dtype=dtypes.float32, shape=[]) max_node =",
"dtypes.uint8) graph_def.node.extend([a_dequantize_node]) a_quantize_node = quantize_graph.create_node( \"QuantizeV2\", a_quantize_name, [a_dequantize_name, a_dequantize_name +",
"\"b_check\" a_identity_name = \"a_identity\" b_identity_name = \"b_identity\" add_name = \"add\"",
"-4, -2, -5, -3, -6], dtype=dtypes.float32, shape=[1, 1, 6, 2])",
"[shape_constant_name, a_constant_name, b_constant_name]) quantize_graph.set_attr_int(concat_node, \"N\", 2) quantize_graph.set_attr_dtype(concat_node, \"T\", dtypes.float32) float_graph_def.node.extend([concat_node])",
"2, 3, 4, 5], dtype=dtypes.float32, shape=[5]) bias_add_node = quantize_graph.create_node( \"BiasAdd\",",
"ops.count(\"Dequantize\")) def test_quantize_array(self): # Test invalid parameters (empty array, or",
"output_names, log_graph=False): \"\"\"Runs the float graph through the rewriter and",
"[input_constant_name]) quantize_graph.set_attr_dtype(avg_pool_node, \"T\", dtypes.float32) quantize_graph.set_attr_int_list(avg_pool_node, \"ksize\", [1, 2, 2, 1])",
"which used to cause problems. test_mat_mul(1, 1, 1, [2], [3])",
"how_many_different = 0 total_difference = 0 total_abs_difference = 0 for",
"0]))) for n in v.flat ] arr = np.array(arr, np.uint8)",
"filter_size, depth, filter_count]) float_graph_def.node.extend([filter_constant]) conv_node = quantize_graph.create_node( \"Conv2D\", conv_name, [input_constant_name,",
"total_abs_difference / value_count proportion_different = (how_many_different * 1.0) / value_count",
"dtype=dtypes.float32, shape=[]) graph_def.node.extend([a_constant]) a_check_node = quantize_graph.create_node(\"CheckNumerics\", a_check_name, [a_constant_name]) graph_def.node.extend([a_check_node]) a_identity_node",
"proportion_different * 100, mean_difference, mean_abs_difference)) return False def get_top_value(input_values): max_value",
"def run_graph_def(graph_def, input_map, outputs): graph = ops_lib.Graph() with graph.as_default(): importer.import_graph_def(graph_def,",
"\":0\" for output_name in output_names]) # TODO(petewarden): round test is",
"{0} different values ({1}%), with mean\" \" difference {2} and",
"identity_name, [input_constant_name]) quantize_graph.set_attr_dtype(identity_node, \"T\", dtypes.float32) float_graph_def.node.extend([identity_node]) mul_name = \"mul\" mul_node",
"test_bias_add(self): input_constant_name = \"input_constant\" offset_constant_name = \"offset_constant\" bias_add_name = \"bias_add\"",
"value=2, dtype=dtypes.float32, shape=[]) expected_output.node.extend([a_constant_max]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=(0,), dtype=dtypes.quint8,",
"= quantize_graph.create_node( \"Reshape\", \"reshape\", [matmul_1_node.name, new_shape_node.name]) quantize_graph.set_attr_dtype(reshape_node, \"T\", dtypes.float32) #",
"log_graph: tf_logging.info(\"8bit:\\n%s\", str(eightbit_graph_def)) # Test the weights_rounded mode. This uses",
"implied. # See the License for the specific language governing",
"test_mat_mul_small(self): test_mat_mul(2, 4, 3, [1, 2, 3, 4, 5, 6],",
"{}, [concat_name]) def test_node_name_from_input(self): self.assertEqual(\"SomeName\", quantize_graph.node_name_from_input(\"^SomeName:2\")) def test_unique_node_name_from_input(self): self.assertEqual(\"__hat__SomeName__port__2\", quantize_graph.unique_node_name_from_input(\"^SomeName:2\"))",
"a: First comparison tensor. b: Second comparison tensor. tolerance: Float",
"import session from tensorflow.python.framework import dtypes from tensorflow.python.framework import graph_util",
"quantize_graph.set_attr_float(batch_norm_node, \"variance_epsilon\", 0.001) float_graph_def.node.extend([batch_norm_node]) test_graph(float_graph_def, {}, [batch_norm_name]) def test_max_pool(self): input_constant_name",
"\"FakeQuantWithMinMaxVars\", \"fake_quant\", [relu_node.name, min_node.name, max_node.name]) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend( [input_node,",
"between values is ok. Returns: Boolean indicating whether the two",
"2, 6, 1]) float_graph_def.node.extend([input_constant]) relu6_node = quantize_graph.create_node(\"Relu6\", relu6_name, [input_constant_name]) quantize_graph.set_attr_dtype(relu6_node,",
"\"FakeQuantWithMinMaxVars\", \"fake_quant\", [bias_add_node.name, min_node.name, max_node.name]) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend([ input_node,",
"reshape_node, weight_2_node) g = graph_pb2.GraphDef() g.node.extend([ input_node, weight_1_node, matmul_1_node, new_shape_node,",
"weight_1_node) # Reshape 4x5 to 10x2. new_shape_node = quantize_graph.create_constant_node( \"new_shape_node\",",
"self.assertEqual(\"__hat__SomeName__port__2\", quantize_graph.unique_node_name_from_input(\"^SomeName:2\")) def test_identity(self): input_constant_name = \"input_constant\" identity_name = \"identity\"",
"arr = [ int( round((n - input_range[0]) * 255 /",
"in output_names] float_results = run_graph_def(float_graph_def, input_map, output_tensors) # Quantize treating",
"return False def get_top_value(input_values): max_value = None max_index = None",
"for node in eightbit_graph_def.node] node_names = [node.name for node in",
"2) self.assertTrue((np.array([0.25, 0.25, 0.75, 0.75]) == qarr).all()) qarr = quantize_graph.quantize_array(arr.reshape((2,",
"max_node = quantize_graph.create_constant_node( \"max_bias_add\", value=15.5, dtype=dtypes.float32, shape=[]) fake_quant_node = quantize_graph.create_node(",
"[1, 2, 2, 1]) quantize_graph.set_attr_int_list(max_pool_node, \"strides\", [1, 1, 1, 1])",
"test_conv(1, 4, 3, 1, 3, 1, 1, b\"SAME\", [1, 2,",
"= total_difference / value_count mean_abs_difference = total_abs_difference / value_count proportion_different",
"min_node = quantize_graph.create_constant_node( \"min_bias_add\", value=-.5, dtype=dtypes.float32, shape=[]) max_node = quantize_graph.create_constant_node(",
"2, 3, 4, 5, 6], [7, 8, 9, 10, 11,",
"float_graph_def.node.extend([input_constant]) offset_constant = quantize_graph.create_constant_node( offset_constant_name, value=[1, 2, 3, 4, 5,",
"dtype=dtypes.quint8, shape=[]) expected_output.node.extend([a_constant]) a_constant_min = quantize_graph.create_constant_node( a_constant_min_name, value=2, dtype=dtypes.float32, shape=[])",
"= quantize_graph.create_node( \"Split\", split_name, [split_constant_name, input_constant_name]) quantize_graph.set_attr_int(split_node, \"num_split\", 2) quantize_graph.set_attr_dtype(split_node,",
"= quantize_graph.create_constant_node( \"max_bias_add\", value=12, dtype=dtypes.float32, shape=[]) fake_quant_node = quantize_graph.create_node( \"FakeQuantWithMinMaxVars\",",
"- input_range[ 0]))) for n in v.flat ] arr =",
"flat_a = a.flatten() flat_b = b.flatten() if len(flat_a) != len(flat_b):",
"g.node.extend([concat_dim, a, b, concat]) test_graph(g, {}, [concat.name]) def test_non_float_reshape(self): a",
"bias_add_node]) test_graph(float_graph_def, {}, [bias_add_node.name], log_graph=True) # Verify there is only",
"new_shape_node, reshape_node, weight_2_node, matmul_2_node ]) # Test the graph test_graph(g,",
"20.]) self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [mat_mul_node.name], [0, 6.]) def _RunTestsForQuantizedInputRange(self, float_graph_def, input_map,",
"tensorflow.python.framework import dtypes from tensorflow.python.framework import graph_util from tensorflow.python.framework import",
"mean_difference, mean_abs_difference)) return False def get_top_value(input_values): max_value = None max_index",
"eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None, fallback_quantization_range=[-100, 100]) eightbit_graph_def =",
"through the rewriter and tests the results.\"\"\" float_results = run_graph_def(",
"test_graph(float_graph_def, {}, [avg_pool_name]) def test_relu(self): input_constant_name = \"input_constant\" relu_name =",
"the License. # ============================================================================== \"\"\"Tests the graph quantization script. \"\"\"",
"quantize_graph.create_node( \"Dequantize\", a_dequantize_name, [a_constant_name, a_constant_min_name, a_constant_max_name]) quantize_graph.set_attr_dtype(a_dequantize_node, \"T\", dtypes.uint8) graph_def.node.extend([a_dequantize_node])",
"\"b\", value=[13, 14, 15, 16, 17, 18, 19, 20, 21,",
"expected_output = graph_pb2.GraphDef() no_op = quantize_graph.create_node(\"NoOp\", no_op_name, []) expected_output.node.extend([no_op]) a_constant",
"[input_n.name, offset_n.name]) quantize_graph.set_attr_dtype(bias_add_n, \"T\", dtypes.float32) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend([input_n, offset_n,",
"\"weights_rounded\", quantized_input_range=None) weights_rounded_graph_def = weights_rounded_rewriter.rewrite(output_names) weights_rounded_results = run_graph_def( weights_rounded_graph_def, input_map,",
"two inputs were close enough. \"\"\" flat_a = a.flatten() flat_b",
"{2} and mean absolute difference {3}\".format( how_many_different, proportion_different * 100,",
"bias_add_node = quantize_graph.create_node( \"BiasAdd\", \"bias_add\", [input_node.name, offset_node.name]) quantize_graph.set_attr_dtype(bias_add_node, \"T\", dtypes.float32)",
"b_constant_name, value=b, dtype=dtypes.float32, shape=[k, n]) float_graph_def.node.extend([b_constant]) mat_mul_node = quantize_graph.create_node(\"MatMul\", mat_mul_name,",
"\"Identity\", a_identity_name, [a_constant_name, \"^\" + no_op_name]) expected_output.node.extend([a_identity_node]) b_constant = quantize_graph.create_constant_node(",
"1, 1, 1]) quantize_graph.set_attr_string(max_pool_node, \"padding\", b\"SAME\") float_graph_def.node.extend([max_pool_node]) test_graph(float_graph_def, {}, [max_pool_name])",
"value=filter_values, dtype=dtypes.float32, shape=[filter_size, filter_size, depth, filter_count]) float_graph_def.node.extend([filter_constant]) conv_node = quantize_graph.create_node(",
"shape_constant, b\"MIN_COMBINED\") self.assertEqual(4, len(quantization_result)) def test_odd_padding_problem(self): \"\"\"Tests one error case",
"input array with all elements equal. arr = np.array([1, 1,",
"= quantize_graph.GraphRewriter( g, \"eightbit\", quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite([\"matmul_2\"]) ops =",
"6, 1]) float_graph_def.node.extend([input_constant]) avg_pool_node = quantize_graph.create_node(\"AvgPool\", avg_pool_name, [input_constant_name]) quantize_graph.set_attr_dtype(avg_pool_node, \"T\",",
"4, 5], dtype=dtypes.float32, shape=[5]) bias_add_node = quantize_graph.create_node( \"BiasAdd\", \"bias_add\", [input_node.name,",
"Unless required by applicable law or agreed to in writing,",
"as quantized in range <input_range>. rewriter = quantize_graph.GraphRewriter(float_graph_def, \"eightbit\", input_range)",
"\"^\" + no_op_name]) expected_output.node.extend([a_identity_node]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=1, dtype=dtypes.float32,",
"looking at the mean and absolute average errors. Args: a:",
"# Pass in fallback_quantization_range, although it will have no effect",
"graph_def.node.extend([a_constant]) a_constant_min = quantize_graph.create_constant_node( a_constant_min_name, value=2, dtype=dtypes.float32, shape=[]) graph_def.node.extend([a_constant_min]) a_constant_max",
"= flat_b[index] difference = a_value - b_value total_difference += difference",
"self.assertEqual(arr, qarr) qarr = quantize_graph.quantize_array(arr, 2) self.assertEqual(arr, qarr) # Test",
"to possible biases by looking at the mean and absolute",
"qarr) qarr = quantize_graph.quantize_array(arr, 2) self.assertEqual(arr, qarr) # Test input",
"quantize_graph.GraphRewriter(graph_pb2.GraphDef(), \"weights_rounded\", [0, 1]) with self.assertRaises(ValueError): # Invalid range. quantize_graph.GraphRewriter(graph_pb2.GraphDef(),",
"the specific language governing permissions and # limitations under the",
"# These tests are added to test the generate case",
"ops = [node.op for node in eightbit_graph_def.node] self.assertEqual(1, ops.count(\"QuantizedConcat\")) def",
"quantize_graph.set_attr_dtype(avg_pool_node, \"T\", dtypes.float32) quantize_graph.set_attr_int_list(avg_pool_node, \"ksize\", [1, 2, 2, 1]) quantize_graph.set_attr_int_list(avg_pool_node,",
"\"max_pool\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=[1, 2,",
"= quantize_graph.create_constant_node( \"input\", value=[1, 2, 3, 4, 5, 6, 7,",
"float_graph_def.node.extend([batch_norm_node]) test_graph(float_graph_def, {}, [batch_norm_name]) def test_max_pool(self): input_constant_name = \"input_constant\" max_pool_name",
"ops.count(\"Quantize\")) self.assertEqual(len(output_names), ops.count(\"Dequantize\")) # Quantize without treating input as quantized.",
"quantization_result = quantize_graph.quantize_weight_eightbit( shape_constant, b\"MIN_COMBINED\") self.assertEqual(4, len(quantization_result)) def test_odd_padding_problem(self): \"\"\"Tests",
".5) ops = [node.op for node in graph_def.node] self.assertEqual(0, ops.count(\"QuantizeV2\")",
"1.0) class QuantizeGraphTest(test.TestCase): def test_negative_const_problem(self): shape_constant_name = \"shape_constant\" shape_constant =",
"ops.count(\"Quantize\")) self.assertEqual(len(output_names), ops.count(\"Dequantize\")) def test_bias_add_w_fake_quant_w_min_max_vars(self): input_node = quantize_graph.create_constant_node( \"input\", value=[1,",
"b, tolerance): \"\"\"Tests whether two tensors are nearly identical. This",
"\":2\", b_quantize_name + \":1\", b_quantize_name + \":2\" ]) quantize_graph.set_attr_dtype(mat_mul_node, \"T1\",",
"= quantize_graph.quantize_array(arr, 10) self.assertTrue((np.array([1, 1, 1]) == qarr).all()) # Test",
"= quantize_graph.create_constant_node( a_constant_name, value=1, dtype=dtypes.float32, shape=[]) expected_output.node.extend([a_constant]) a_identity_node = quantize_graph.create_node(",
"quantize_graph.create_constant_node( a_constant_max_name, value=2, dtype=dtypes.float32, shape=[]) expected_output.node.extend([a_constant_max]) b_constant = quantize_graph.create_constant_node( b_constant_name,",
"b\"SAME\") float_graph_def.node.extend([max_pool_node]) test_graph(float_graph_def, {}, [max_pool_name]) def test_avg_pool(self): input_constant_name = \"input_constant\"",
"offset_constant_name = \"offset_constant\" bias_add_name = \"bias_add\" float_graph_def = graph_pb2.GraphDef() input_constant",
"4, 4, 1, 3, 1, 2, b\"SAME\", [1, 2, 3,",
"value=(0,), dtype=dtypes.quint8, shape=[]) expected_output.node.extend([a_constant]) a_constant_min = quantize_graph.create_constant_node( a_constant_min_name, value=2, dtype=dtypes.float32,",
"inputs[0].name + \":0\": np.reshape([1, 2, 3, 4, 5, 6], shapes[0]),",
"a_constant_name, b_constant_name, a_constant_min_name, a_constant_max_name, b_constant_min_name, b_constant_max_name ]) quantize_graph.set_attr_dtype(mat_mul_node, \"T1\", dtypes.uint8)",
"shape=[2, 2, 3]) float_graph_def.node.extend([b_constant]) concat_node = quantize_graph.create_node( \"Concat\", concat_name, [shape_constant_name,",
"= quantize_graph.create_constant_node( b_constant_name, value=1, dtype=dtypes.float32, shape=[]) expected_output.node.extend([b_constant]) add_node = quantize_graph.create_node(\"Add\",",
"= \"input_constant\" relu_name = \"relu\" float_graph_def = graph_pb2.GraphDef() input_constant =",
"quantize_graph.create_node(\"Add\", add_name, [a_identity_name, b_constant_name]) quantize_graph.set_attr_dtype(add_node, \"T\", dtypes.float32) expected_output.node.extend([add_node]) expected_output.versions.CopyFrom(graph_def.versions) expected_output.library.CopyFrom(graph_def.library)",
"values ({1}%), with mean\" \" difference {2} and mean absolute",
"14, 15, 16, 17, 18, 19, 20, 21, 22, 23,",
"2]) float_graph_def.node.extend([input_constant]) mean_constant = quantize_graph.create_constant_node( mean_constant_name, value=[10, 20], dtype=dtypes.float32, shape=[2])",
"1]) test_mat_mul(1, 1, 2, [0, 0], [1, 1]) # The",
"7, 8, 9, 10, 11, 12, 13, 14, 15, 16],",
"\"a_constant\" a_constant_min_name = \"a_constant_min\" a_constant_max_name = \"a_constant_max\" a_dequantize_name = \"a_dequantize\"",
"quantize_graph.create_constant_node( \"weight_2\", value=[1.5, 2.5], dtype=dtypes.float32, shape=[2, 1]) matmul_2_node = make_matmul(\"matmul_2\",",
".6, .7, .8, .9], dtype=dtypes.float32, shape=[1, 5]) matmul_1_node = make_matmul(\"matmul_1\",",
"[input_constant_name]) quantize_graph.set_attr_dtype(relu_node, \"T\", dtypes.float32) float_graph_def.node.extend([relu_node]) test_graph(float_graph_def, {}, [relu_name]) def test_relu_w_fake_quant_w_min_max_vars(self):",
"\"min_bias_add\", value=-.5, dtype=dtypes.float32, shape=[]) max_node = quantize_graph.create_constant_node( \"max_bias_add\", value=15.5, dtype=dtypes.float32,",
"dtype=dtypes.int32, shape=[2]) reshape_node = quantize_graph.create_node( \"Reshape\", \"reshape\", [matmul_1_node.name, new_shape_node.name]) quantize_graph.set_attr_dtype(reshape_node,",
"= quantize_graph.create_node(\"MatMul\", \"mat_mul\", [n.name for n in inputs]) quantize_graph.set_attr_dtype(mat_mul_node, \"T\",",
"offset_node.name]) quantize_graph.set_attr_dtype(bias_add_node, \"T\", dtypes.float32) min_node = quantize_graph.create_constant_node( \"min_bias_add\", value=-.5, dtype=dtypes.float32,",
"16], [1, 2, 3, 4, 5, 6, 7, 8, 9])",
"\"\"\"Tests that MatMul->Reshape->MatMul avoids extra quantize/dequantize.\"\"\" def make_matmul(name, a, b):",
"4, 5, 6], shapes[0]), inputs[1].name + \":0\": np.reshape([.8, .7, .6,",
"arr = np.array([1, 1, 1]) qarr = quantize_graph.quantize_array(arr, 10) self.assertTrue((np.array([1,",
"test_bias_add_w_fake_quant_w_min_max_vars(self): input_node = quantize_graph.create_constant_node( \"input\", value=[1, 2, 3, 4, 5,",
"ops as ops_lib from tensorflow.python.platform import flags as flags_lib from",
"# Test the weights_rounded mode. This uses the default bit_depth.",
"from tensorflow.core.framework import graph_pb2 from tensorflow.python.client import session from tensorflow.python.framework",
"quantize_graph.set_attr_bool(n, \"transpose_b\", False) return n # matmul_1 = input*weight_1 input_node",
"\"shape_constant\" a_constant_name = \"a_constant\" b_constant_name = \"b_constant\" concat_name = \"concat\"",
"4, 5, 6, 7, 8, 9, 10, 11, 12], dtype=dtypes.float32,",
"= graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=[1, 4, 2, 5,",
"\"input_constant\" identity_name = \"identity\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node(",
"# Invalid range. quantize_graph.GraphRewriter(graph_pb2.GraphDef(), \"eightbit\", [0, -1]) def test_quantized_input_range_bias_add(self): input_shape",
"rewriter = quantize_graph.GraphRewriter(float_graph_def, \"eightbit\", input_range) graph_def = rewriter.rewrite(output_names) results =",
"= \"b_constant_max\" b_dequantize_name = \"b_dequantize\" b_quantize_name = \"b_quantize\" mat_mul_name =",
"value indicating how large an error between values is ok.",
"shape=[]) graph_def.node.extend([b_constant_max]) b_dequantize_node = quantize_graph.create_node( \"Dequantize\", b_dequantize_name, [b_constant_name, b_constant_min_name, b_constant_max_name])",
"8, 9, 10, 11, 12, 13, 14, 15, 16], [1,",
"9]) def test_reshape(self): \"\"\"Tests that MatMul->Reshape->MatMul avoids extra quantize/dequantize.\"\"\" def",
"in eightbit_graph_def.node] self.assertEqual(1, ops.count(\"QuantizedConcat\")) def test_multiple_outputs(self): input_constant_name = \"input_constant\" split_constant_name",
"a_quantize_node = quantize_graph.create_node( \"QuantizeV2\", a_quantize_name, [a_dequantize_name, a_dequantize_name + \":1\", a_dequantize_name",
"expected_output.versions.CopyFrom(graph_def.versions) expected_output.library.CopyFrom(graph_def.library) output = graph_util.remove_training_nodes(graph_def) stripped_output = graph_util.extract_sub_graph(output, [add_name]) self.assertProtoEquals(expected_output,",
"[a.name, b.name]) quantize_graph.set_attr_dtype(n, \"T\", dtypes.float32) quantize_graph.set_attr_bool(n, \"transpose_a\", False) quantize_graph.set_attr_bool(n, \"transpose_b\",",
"4, 5, 6], [7, 8, 9, 10, 11, 12, 13,",
"gamma_constant_name, value=[0, 0], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([gamma_constant]) batch_norm_node = quantize_graph.create_node( \"BatchNormWithGlobalNormalization\",",
"arr = np.array([0, 0.3, 0.6, 1]) qarr = quantize_graph.quantize_array(arr, 1)",
"\"transpose_a\", False) quantize_graph.set_attr_bool(mat_mul_node, \"transpose_b\", False) float_graph_def.node.extend([mat_mul_node]) test_graph(float_graph_def, {}, [mat_mul_name]) def",
"general case. test_mat_mul(1, 1, 2, [1, 2], [1, 2]) def",
"\"input_constant\" mean_constant_name = \"mean_constant\" variance_constant_name = \"variance_constant\" beta_constant_name = \"beta_constant\"",
"[input_node.name, offset_node.name]) quantize_graph.set_attr_dtype(bias_add_node, \"T\", dtypes.float32) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend([input_node, offset_node,",
"shape=[]) graph_def.node.extend([b_constant]) b_check_node = quantize_graph.create_node(\"CheckNumerics\", b_check_name, [b_constant_name]) graph_def.node.extend([b_check_node]) b_identity_node =",
"dtype=dtypes.float32, shape=[1, 2, 6, 1]) float_graph_def.node.extend([input_constant]) max_pool_node = quantize_graph.create_node(\"MaxPool\", max_pool_name,",
"def test_unique_node_name_from_input(self): self.assertEqual(\"__hat__SomeName__port__2\", quantize_graph.unique_node_name_from_input(\"^SomeName:2\")) def test_identity(self): input_constant_name = \"input_constant\" identity_name",
"\"a_constant\" b_constant_name = \"b_constant\" a_check_name = \"a_check\" b_check_name = \"b_check\"",
"def test_batch_norm(self): input_constant_name = \"input_constant\" mean_constant_name = \"mean_constant\" variance_constant_name =",
"quantize_graph.set_attr_dtype(concat_node, \"T\", dtypes.float32) float_graph_def.node.extend([concat_node]) test_graph(float_graph_def, {}, [concat_name]) # Verify the",
"quantize_graph.create_node(\"CheckNumerics\", b_check_name, [b_constant_name]) graph_def.node.extend([b_check_node]) b_identity_node = quantize_graph.create_node( \"Identity\", b_identity_name, [b_constant_name,",
"graph_def.node.extend([add_node]) expected_output = graph_pb2.GraphDef() no_op = quantize_graph.create_node(\"NoOp\", no_op_name, []) expected_output.node.extend([no_op])",
"n, k, a, b): \"\"\"Tests a MatMul replacement.\"\"\" a_constant_name =",
"= graph_pb2.GraphDef() g.node.extend([concat_dim, a, b, concat]) test_graph(g, {}, [concat.name]) def",
"16, 17, 18, 19, 20, 21, 22, 23, 24], dtype=dtypes.float32,",
"can be quantized up-front. self.assertEqual(0, ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) # One",
"for n in v.flat ] arr = np.array(arr, np.uint8) arr",
"\"input_constant\" avg_pool_name = \"avg_pool\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node(",
"an error between values is ok. Returns: Boolean indicating whether",
"shape=[1, 1, 2, 6]) float_graph_def.node.extend([input_constant]) offset_constant = quantize_graph.create_constant_node( offset_constant_name, value=[1,",
"b_constant_max_name ]) quantize_graph.set_attr_dtype(mat_mul_node, \"T1\", dtypes.uint8) quantize_graph.set_attr_dtype(mat_mul_node, \"T2\", dtypes.int32) expected_output.node.extend([mat_mul_node]) expected_output.versions.CopyFrom(graph_def.versions)",
"expected_output.library.CopyFrom(graph_def.library) rewriter = quantize_graph.GraphRewriter( graph_def, [mat_mul_name], quantized_input_range=None) output = rewriter.remove_redundant_quantization(graph_def)",
"\"Dequantize\", a_dequantize_name, [a_constant_name, a_constant_min_name, a_constant_max_name]) quantize_graph.set_attr_dtype(a_dequantize_node, \"T\", dtypes.uint8) graph_def.node.extend([a_dequantize_node]) a_quantize_node",
"ran into in a real graph.\"\"\" test_conv(1, 4, 4, 1,",
"is only one Quantize, one Requantize op, and no #",
"MatMul replacement.\"\"\" a_constant_name = \"a_constant\" b_constant_name = \"b_constant\" mat_mul_name =",
"9, 10, 11, 12, 13, 14, 15, 16, 17, 18])",
"graph_pb2.GraphDef() float_graph_def.node.extend( [input_node, relu_node, min_node, max_node, fake_quant_node]) test_graph(float_graph_def, {}, [fake_quant_node.name],",
"21, 22, 23, 24], dtype=dtypes.float32, shape=[2, 2, 3]) float_graph_def.node.extend([b_constant]) concat_node",
"= b.flatten() if len(flat_a) != len(flat_b): tf_logging.info(\"Tensors are different sizes:",
"# One dequantize at the end. self.assertEqual(1, ops.count(\"Dequantize\")) def test_quantize_array(self):",
"4, 2, 5, 3, 6, -1, -4, -2, -5, -3,",
"} self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [bias_add_n.name], [-1, 20.]) self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [bias_add_n.name], [0,",
"limitations under the License. # ============================================================================== \"\"\"Tests the graph quantization",
"qarr).all()) def test_non_float_concat(self): concat_dim = quantize_graph.create_constant_node( \"concat_dim\", value=0, dtype=dtypes.int32, shape=[])",
"shape_constant = quantize_graph.create_constant_node( shape_constant_name, value=0, dtype=dtypes.int32, shape=[]) float_graph_def.node.extend([shape_constant]) a_constant =",
"absolute_import from __future__ import division from __future__ import print_function import",
"output_names]) for expected, result in zip(float_results, eightbit_results): assert are_tensors_near(expected, result,",
"if max_value is None or value > max: max_value =",
"quantize_graph.set_attr_string(conv_node, \"padding\", padding) float_graph_def.node.extend([conv_node]) test_graph(float_graph_def, {}, [conv_name]) def are_tensors_near(a, b,",
"# assert are_tensors_near(expected, round_results[0], 1.0) # # TODO(petewarden): Add test",
"graph test_graph(g, {}, [\"matmul_2\"]) # Verify there is only one",
"1]) matmul_2_node = make_matmul(\"matmul_2\", reshape_node, weight_2_node) g = graph_pb2.GraphDef() g.node.extend([",
"output_names]) for expected, result in zip(float_results, weights_rounded_results): assert are_tensors_near(expected, result,",
"b_check_name = \"b_check\" a_identity_name = \"a_identity\" b_identity_name = \"b_identity\" add_name",
"ops.count(\"Quantize\")) # One dequantize at the end. self.assertEqual(1, ops.count(\"Dequantize\")) def",
"in eightbit_graph_def.node] node_names = [node.name for node in eightbit_graph_def.node] #",
"run_graph_def(graph_def, input_map, outputs): graph = ops_lib.Graph() with graph.as_default(): importer.import_graph_def(graph_def, input_map={},",
"were close enough. \"\"\" flat_a = a.flatten() flat_b = b.flatten()",
"1]) weight_1_node = quantize_graph.create_constant_node( \"weight_1\", value=[.5, .6, .7, .8, .9],",
"1]) qarr = quantize_graph.quantize_array(arr, 10) self.assertTrue((np.array([1, 1, 1]) == qarr).all())",
"quantized_input_map = {} for k, v in input_map.items(): arr =",
"\"T\", dtypes.float32) float_graph_def.node.extend([relu6_node]) test_graph(float_graph_def, {}, [relu6_name]) def test_bias_add(self): input_constant_name =",
"\"Concat\", concat_name, [shape_constant_name, a_constant_name, b_constant_name]) quantize_graph.set_attr_int(concat_node, \"N\", 2) quantize_graph.set_attr_dtype(concat_node, \"T\",",
"quantize_graph.create_constant_node( \"min_bias_add\", value=0, dtype=dtypes.float32, shape=[]) max_node = quantize_graph.create_constant_node( \"max_bias_add\", value=12,",
"def test_bias_add_w_fake_quant_w_min_max_vars(self): input_node = quantize_graph.create_constant_node( \"input\", value=[1, 2, 3, 4,",
"flags_lib FLAGS = flags.FLAGS def run_graph_def(graph_def, input_map, outputs): graph =",
"10, 11, 12], [1, 4, 7, 2, 5, 8, 3,",
"= value max_index = index return max_index, max_value def test_graph(float_graph_def,",
"12], dtype=dtypes.float32, shape=[1, 2, 6, 1]) relu_node = quantize_graph.create_node(\"Relu\", \"relu\",",
"qarr).all()) # Test \"normal\" input arrays. arr = np.array([0, 0.3,",
"8, 9, 10, 11, 12], dtype=dtypes.float32, shape=[2, 6]) float_graph_def.node.extend([input_constant]) split_constant",
"quantize_graph.set_attr_shape(node, \"shape\", shape) inputs.append(node) mat_mul_node = quantize_graph.create_node(\"MatMul\", \"mat_mul\", [n.name for",
"a_identity_name, [a_constant_name, \"^\" + a_check_name, \"^\" + no_op_name]) graph_def.node.extend([a_identity_node]) b_constant",
"add_node = quantize_graph.create_node(\"Add\", add_name, [a_identity_name, b_identity_name]) quantize_graph.set_attr_dtype(add_node, \"T\", dtypes.float32) graph_def.node.extend([add_node])",
"[output_name + \":0\"]) # assert are_tensors_near(expected, round_results[0], 1.0) # #",
"[avg_pool_name]) def test_relu(self): input_constant_name = \"input_constant\" relu_name = \"relu\" float_graph_def",
"You may obtain a copy of the License at #",
"shapes = [[3, 2], [2, 4]] inputs = [] for",
"the weights_rounded mode. This uses the default bit_depth. weights_rounded_rewriter =",
"0.5, 0.5]) == qarr).all()) qarr = quantize_graph.quantize_array(arr, 2) self.assertTrue((np.array([0.25, 0.25,",
"treating the input as quantized in range <input_range>. rewriter =",
"is a specialized comparison function designed to help debug problems",
"0.6, 1]) qarr = quantize_graph.quantize_array(arr, 1) self.assertTrue((np.array([0.5, 0.5, 0.5, 0.5])",
"b.name]) quantize_graph.set_attr_dtype(n, \"T\", dtypes.float32) quantize_graph.set_attr_bool(n, \"transpose_a\", False) quantize_graph.set_attr_bool(n, \"transpose_b\", False)",
"failing because there is no # RoundToSteps op available. #",
"test_node_name_from_input(self): self.assertEqual(\"SomeName\", quantize_graph.node_name_from_input(\"^SomeName:2\")) def test_unique_node_name_from_input(self): self.assertEqual(\"__hat__SomeName__port__2\", quantize_graph.unique_node_name_from_input(\"^SomeName:2\")) def test_identity(self): input_constant_name",
"15, 16, 17, 18, 19, 20, 21, 22, 23, 24],",
"test_graph(g, {}, [concat.name]) def test_non_float_reshape(self): a = quantize_graph.create_constant_node( \"a\", value=[1,",
"quantize_graph.create_constant_node( b_constant_max_name, value=3, dtype=dtypes.float32, shape=[]) expected_output.node.extend([b_constant_max]) mat_mul_node = quantize_graph.create_node(\"QuantizedMatMul\", mat_mul_name,",
"results = run_graph_def(graph_def, quantized_input_map, output_tensors) for expected, result in zip(float_results,",
"offset_n = quantize_graph.create_constant_node( \"offset\", value=[1, 2, 3, 4, 5, 6],",
"# Verify there is only one Quantize, one Requantize op,",
"b_dequantize_name, [b_constant_name, b_constant_min_name, b_constant_max_name]) quantize_graph.set_attr_dtype(b_dequantize_node, \"T\", dtypes.uint8) graph_def.node.extend([b_dequantize_node]) b_quantize_node =",
"It prints out information about the differences between tensors on",
"[concat_name]) # Verify the concat is quantized. eightbit_rewriter = quantize_graph.GraphRewriter(",
"input_shape = [1, 1, 2, 6] input_n = quantize_graph.create_node(\"Placeholder\", \"input\",",
"b_constant_max_name, value=3, dtype=dtypes.float32, shape=[]) expected_output.node.extend([b_constant_max]) mat_mul_node = quantize_graph.create_node(\"QuantizedMatMul\", mat_mul_name, [",
"quantize_graph.create_node( \"Reshape\", \"reshape\", [matmul_1_node.name, new_shape_node.name]) quantize_graph.set_attr_dtype(reshape_node, \"T\", dtypes.float32) # matmul_2_node",
"node_names.count(\"fallback_quantization_max_value\")) def test_remove_redundant_quantization(self): a_constant_name = \"a_constant\" a_constant_min_name = \"a_constant_min\" a_constant_max_name",
"value=input_values, dtype=dtypes.float32, shape=[image_batch_count, image_height, image_width, depth]) float_graph_def.node.extend([input_constant]) filter_constant = quantize_graph.create_constant_node(",
"5]) offset_node = quantize_graph.create_constant_node( \"offset\", value=[1, 2, 3, 4, 5],",
"= graph_pb2.GraphDef() float_graph_def.node.extend( [input_node, relu_node, min_node, max_node, fake_quant_node]) test_graph(float_graph_def, {},",
"8, 9, 10, 11, 12], input_shape) } self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [bias_add_n.name],",
"\"input_constant\" filter_constant_name = \"filter_constant\" conv_name = \"conv\" float_graph_def = graph_pb2.GraphDef()",
"7, 8, 9, 10, 11, 12], dtype=dtypes.float32, shape=[2, 2, 3])",
"value > max: max_value = value max_index = index return",
"ops.count(\"QuantizedConcat\")) def test_multiple_outputs(self): input_constant_name = \"input_constant\" split_constant_name = \"split_constant\" split_name",
"dtype=dtypes.float32, shape=[k, n]) float_graph_def.node.extend([b_constant]) mat_mul_node = quantize_graph.create_node(\"MatMul\", mat_mul_name, [a_constant_name, b_constant_name])",
"float_graph_def.node.extend([input_constant]) relu6_node = quantize_graph.create_node(\"Relu6\", relu6_name, [input_constant_name]) quantize_graph.set_attr_dtype(relu6_node, \"T\", dtypes.float32) float_graph_def.node.extend([relu6_node])",
"error between values is ok. Returns: Boolean indicating whether the",
"The general case. test_mat_mul(1, 1, 2, [1, 2], [1, 2])",
"= quantize_graph.create_constant_node( mean_constant_name, value=[10, 20], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([mean_constant]) variance_constant =",
"10, 11, 12], dtype=dtypes.float32, shape=[1, 2, 6, 1]) float_graph_def.node.extend([input_constant]) relu6_node",
"for node in graph_def.node] self.assertEqual(0, ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) self.assertEqual(len(output_names), ops.count(\"Dequantize\"))",
"[3]) test_mat_mul(1, 2, 1, [1], [2, 3]) test_mat_mul(1, 1, 2,",
"mean_difference = total_difference / value_count mean_abs_difference = total_abs_difference / value_count",
"i, []) quantize_graph.set_attr_dtype(node, \"dtype\", dtypes.float32) quantize_graph.set_attr_shape(node, \"shape\", shape) inputs.append(node) mat_mul_node",
"quantize_graph.create_constant_node( variance_constant_name, value=[0.25, 0.5], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([variance_constant]) beta_constant = quantize_graph.create_constant_node(",
"conv_name, [input_constant_name, filter_constant_name]) quantize_graph.set_attr_dtype(conv_node, \"T\", dtypes.float32) quantize_graph.set_attr_int_list(conv_node, \"strides\", [1, stride,",
"# The fallback constants are in the graph. self.assertEqual(1, node_names.count(\"fallback_quantization_min_value\"))",
"fallback constants are in the graph. self.assertEqual(1, node_names.count(\"fallback_quantization_min_value\")) self.assertEqual(1, node_names.count(\"fallback_quantization_max_value\"))",
"reshape_node = quantize_graph.create_node( \"Reshape\", \"reshape\", [matmul_1_node.name, new_shape_node.name]) quantize_graph.set_attr_dtype(reshape_node, \"T\", dtypes.float32)",
"dtypes.float32) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend([input_node, offset_node, bias_add_node]) test_graph(float_graph_def, {}, [bias_add_node.name],",
"= None for index, value in enumerate(input_values.flatten()): if max_value is",
"float_graph_def.node.extend([bias_add_node]) test_graph(float_graph_def, {}, [bias_add_name]) def test_quantized_input_range_errors(self): with self.assertRaises(ValueError): # Invalid",
"no_op_name, []) graph_def.node.extend([no_op]) a_constant = quantize_graph.create_constant_node( a_constant_name, value=1, dtype=dtypes.float32, shape=[])",
"graph quantization script. \"\"\" from __future__ import absolute_import from __future__",
"0], [1, 1]) # The general case. test_mat_mul(1, 1, 2,",
"11, 12], dtype=dtypes.float32, shape=[1, 1, 2, 6]) float_graph_def.node.extend([input_constant]) offset_constant =",
"ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) self.assertEqual(len(output_names), ops.count(\"Dequantize\")) # Quantize without treating input",
"bias_add_node = quantize_graph.create_node( \"BiasAdd\", bias_add_name, [input_constant_name, offset_constant_name]) quantize_graph.set_attr_dtype(bias_add_node, \"T\", dtypes.float32)",
"treating input as quantized. rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None)",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"weights_rounded mode. This uses the default bit_depth. weights_rounded_rewriter = quantize_graph.GraphRewriter(",
"quantize_graph.set_attr_dtype(add_node, \"T\", dtypes.float32) graph_def.node.extend([add_node]) expected_output = graph_pb2.GraphDef() no_op = quantize_graph.create_node(\"NoOp\",",
"paying special attention to possible biases by looking at the",
"qarr).all()) qarr = quantize_graph.quantize_array(arr.reshape((2, 2)), 2) self.assertTrue((np.array([[0.25, 0.25], [0.75, 0.75]])",
"for expected, result in zip(float_results, weights_rounded_results): assert are_tensors_near(expected, result, 1.0)",
"# No quantize since all inputs are const and can",
"7, 8, 9, 10, 11, 12], dtype=dtypes.int32, shape=[2, 2, 3])",
".4, .3, .2, .1], shapes[1]) } self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [mat_mul_node.name], [-1,",
"6], dtype=dtypes.float32, shape=[6]) bias_add_n = quantize_graph.create_node(\"BiasAdd\", \"bias_add\", [input_n.name, offset_n.name]) quantize_graph.set_attr_dtype(bias_add_n,",
"quantize_graph.set_attr_dtype(mat_mul_node, \"T\", dtypes.float32) quantize_graph.set_attr_bool(mat_mul_node, \"transpose_a\", False) quantize_graph.set_attr_bool(mat_mul_node, \"transpose_b\", False) float_graph_def.node.extend([mat_mul_node])",
"self.assertEqual(1, ops.count(\"Dequantize\")) # The fallback constants are not in the",
"2)), 2) self.assertTrue((np.array([[0.25, 0.25], [0.75, 0.75]]) == qarr).all()) def test_non_float_concat(self):",
"graph_pb2.GraphDef() no_op = quantize_graph.create_node(\"NoOp\", no_op_name, []) graph_def.node.extend([no_op]) a_constant = quantize_graph.create_constant_node(",
"= \"mul\" mul_node = quantize_graph.create_node(\"Mul\", mul_name, [identity_name, identity_name]) quantize_graph.set_attr_dtype(mul_node, \"T\",",
"shape=[1, 1, 6, 2]) float_graph_def.node.extend([input_constant]) mean_constant = quantize_graph.create_constant_node( mean_constant_name, value=[10,",
"quantize_graph.create_constant_node( gamma_constant_name, value=[0, 0], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([gamma_constant]) batch_norm_node = quantize_graph.create_node(",
"eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None, fallback_quantization_range=[-.5, 15.5]) eightbit_graph_def =",
"max_value = value max_index = index return max_index, max_value def",
"the graph quantization script. \"\"\" from __future__ import absolute_import from",
"quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None, fallback_quantization_range=[-100, 100]) eightbit_graph_def = eightbit_rewriter.rewrite([fake_quant_node.name]) ops",
"= run_graph_def( weights_rounded_graph_def, input_map, [output_name + \":0\" for output_name in",
"a_constant_max_name = \"a_constant_max\" a_dequantize_name = \"a_dequantize\" a_quantize_name = \"a_quantize\" b_constant_name",
"+ \":0\": np.reshape([.8, .7, .6, .5, .4, .3, .2, .1],",
"test_mat_mul(1, 1, 1, [2], [3]) test_mat_mul(1, 2, 1, [1], [2,",
"True else: tf_logging.info(\"Tensors have {0} different values ({1}%), with mean\"",
"dtype=dtypes.float32, shape=[4, 1]) weight_1_node = quantize_graph.create_constant_node( \"weight_1\", value=[.5, .6, .7,",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"dtypes.float32) float_graph_def.node.extend([concat_node]) test_graph(float_graph_def, {}, [concat_name]) def test_node_name_from_input(self): self.assertEqual(\"SomeName\", quantize_graph.node_name_from_input(\"^SomeName:2\")) def",
"run_graph_def(graph_def, input_map, output_tensors) for expected, result in zip(float_results, results): assert",
"4, 5, 6, 7, 8, 9, 10], dtype=dtypes.float32, shape=[1, 1,",
"b_constant_name, value=(0,), dtype=dtypes.quint8, shape=[]) expected_output.node.extend([b_constant]) b_constant_min = quantize_graph.create_constant_node( b_constant_min_name, value=3,",
"License. # You may obtain a copy of the License",
"the results.\"\"\" float_results = run_graph_def( float_graph_def, input_map, [output_name + \":0\"",
"9, 10, 11, 12], dtype=dtypes.float32, shape=[1, 2, 6, 1]) relu_node",
"quantize_graph.set_attr_dtype(mat_mul_node, \"T2\", dtypes.int32) expected_output.node.extend([mat_mul_node]) expected_output.versions.CopyFrom(graph_def.versions) expected_output.library.CopyFrom(graph_def.library) rewriter = quantize_graph.GraphRewriter( graph_def,",
"1]) float_graph_def.node.extend([input_constant]) relu_node = quantize_graph.create_node(\"Relu\", relu_name, [input_constant_name]) quantize_graph.set_attr_dtype(relu_node, \"T\", dtypes.float32)",
"[[3, 2], [2, 4]] inputs = [] for i, shape",
"self.assertRaises(ValueError): # Invalid range. quantize_graph.GraphRewriter(graph_pb2.GraphDef(), \"eightbit\", [0, -1]) def test_quantized_input_range_bias_add(self):",
"test_graph(float_graph_def, {}, [relu_name]) def test_relu_w_fake_quant_w_min_max_vars(self): input_node = quantize_graph.create_constant_node( \"input\", value=[1,",
"inputs are const and can be quantized up-front. self.assertEqual(0, ops.count(\"QuantizeV2\")",
"!= len(flat_b): tf_logging.info(\"Tensors are different sizes: \" + str(len(flat_a)) +",
"expected_output.node.extend([mat_mul_node]) expected_output.versions.CopyFrom(graph_def.versions) expected_output.library.CopyFrom(graph_def.library) rewriter = quantize_graph.GraphRewriter( graph_def, [mat_mul_name], quantized_input_range=None) output",
"= quantize_graph.create_node( \"QuantizeV2\", a_quantize_name, [a_dequantize_name, a_dequantize_name + \":1\", a_dequantize_name +",
"tensors are nearly identical. This is a specialized comparison function",
"quantize_graph.set_attr_dtype(concat_node, \"T\", dtypes.float32) float_graph_def.node.extend([concat_node]) test_graph(float_graph_def, {}, [concat_name]) def test_node_name_from_input(self): self.assertEqual(\"SomeName\",",
"1]) quantize_graph.set_attr_string(max_pool_node, \"padding\", b\"SAME\") float_graph_def.node.extend([max_pool_node]) test_graph(float_graph_def, {}, [max_pool_name]) def test_avg_pool(self):",
"input_constant_name = \"input_constant\" mean_constant_name = \"mean_constant\" variance_constant_name = \"variance_constant\" beta_constant_name",
"as quantized. rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None) graph_def =",
"matmul_2_node = make_matmul(\"matmul_2\", reshape_node, weight_2_node) g = graph_pb2.GraphDef() g.node.extend([ input_node,",
"[1, 1]) test_mat_mul(1, 1, 2, [0, 0], [1, 1]) #",
"log_graph=True) # Verify there is only one Quantize and one",
"split_name = \"split\" concat_constant_name = \"concat_constant\" concat_name = \"concat\" float_graph_def",
"comparison tensor. b: Second comparison tensor. tolerance: Float value indicating",
"sizes: \" + str(len(flat_a)) + \" vs \" + str(len(flat_b)))",
"quantize_graph.GraphRewriter( float_graph_def, \"weights_rounded\", quantized_input_range=None) weights_rounded_graph_def = weights_rounded_rewriter.rewrite(output_names) weights_rounded_results = run_graph_def(",
"governing permissions and # limitations under the License. # ==============================================================================",
"\"concat\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=[1, 2,",
"{}, [conv_name]) def are_tensors_near(a, b, tolerance): \"\"\"Tests whether two tensors",
"= quantize_graph.create_node(\"MaxPool\", max_pool_name, [input_constant_name]) quantize_graph.set_attr_int_list(max_pool_node, \"ksize\", [1, 2, 2, 1])",
"float_graph_def.node.extend([a_constant]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=b, dtype=dtypes.float32, shape=[k, n]) float_graph_def.node.extend([b_constant])",
"TensorFlow Authors. All Rights Reserved. # # Licensed under the",
"= index return max_index, max_value def test_graph(float_graph_def, input_map, output_names, log_graph=False):",
"quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite([fake_quant_node.name]) ops = [node.op",
"shape=[]) max_node = quantize_graph.create_constant_node( \"max_bias_add\", value=15.5, dtype=dtypes.float32, shape=[]) fake_quant_node =",
"[1, 1]) # The general case. test_mat_mul(1, 1, 2, [1,",
"expected_output.node.extend([a_constant]) a_identity_node = quantize_graph.create_node( \"Identity\", a_identity_name, [a_constant_name, \"^\" + no_op_name])",
"\"mat_mul\", [n.name for n in inputs]) quantize_graph.set_attr_dtype(mat_mul_node, \"T\", dtypes.float32) float_graph_def",
"[relu_name]) def test_relu_w_fake_quant_w_min_max_vars(self): input_node = quantize_graph.create_constant_node( \"input\", value=[1, 2, 3,",
"qarr) # Test input array with all elements equal. arr",
"for node in graph_def.node] self.assertEqual( len(input_map), ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) self.assertEqual(len(output_names),",
"[relu_node.name, min_node.name, max_node.name]) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend( [input_node, relu_node, min_node,",
"comparison tensor. tolerance: Float value indicating how large an error",
"\"transpose_a\", False) quantize_graph.set_attr_bool(n, \"transpose_b\", False) return n # matmul_1 =",
"relu_name, [input_constant_name]) quantize_graph.set_attr_dtype(relu_node, \"T\", dtypes.float32) float_graph_def.node.extend([relu_node]) test_graph(float_graph_def, {}, [relu_name]) def",
"tensorflow.python.platform import tf_logging from tensorflow.tools.quantization import quantize_graph flags = flags_lib",
"float_graph_def.node.extend([identity_node]) mul_name = \"mul\" mul_node = quantize_graph.create_node(\"Mul\", mul_name, [identity_name, identity_name])",
"10, 11, 12], dtype=dtypes.float32, shape=[2, 6]) float_graph_def.node.extend([input_constant]) split_constant = quantize_graph.create_constant_node(",
"= quantize_graph.create_node( \"Identity\", b_identity_name, [b_constant_name, \"^\" + b_check_name]) graph_def.node.extend([b_identity_node]) add_node",
"\"weight_2\", value=[1.5, 2.5], dtype=dtypes.float32, shape=[2, 1]) matmul_2_node = make_matmul(\"matmul_2\", reshape_node,",
"the end. self.assertEqual(1, ops.count(\"Dequantize\")) def test_quantize_array(self): # Test invalid parameters",
"False def get_top_value(input_values): max_value = None max_index = None for",
"2, 1]) quantize_graph.set_attr_int_list(avg_pool_node, \"strides\", [1, 1, 1, 1]) quantize_graph.set_attr_string(avg_pool_node, \"padding\",",
"= graph_pb2.GraphDef() a_constant = quantize_graph.create_constant_node( a_constant_name, value=a, dtype=dtypes.float32, shape=[m, k])",
"test_graph(float_graph_def, {}, [bias_add_node.name], log_graph=True) # Verify there is only one",
"a_constant_max = quantize_graph.create_constant_node( a_constant_max_name, value=2, dtype=dtypes.float32, shape=[]) graph_def.node.extend([a_constant_max]) a_dequantize_node =",
"filter_values): \"\"\"Tests a Conv replacement.\"\"\" input_constant_name = \"input_constant\" filter_constant_name =",
"# Test input array of length 1. arr = np.array([1])",
"a_dequantize_name + \":2\"]) quantize_graph.set_attr_dtype(a_quantize_node, \"T\", dtypes.uint8) graph_def.node.extend([a_quantize_node]) b_constant = quantize_graph.create_constant_node(",
"b_constant_min_name, value=3, dtype=dtypes.float32, shape=[]) expected_output.node.extend([b_constant_min]) b_constant_max = quantize_graph.create_constant_node( b_constant_max_name, value=3,",
"test_graph(float_graph_def, {}, [concat_name]) # Verify the concat is quantized. eightbit_rewriter",
"absolute difference {3}\".format( how_many_different, proportion_different * 100, mean_difference, mean_abs_difference)) return",
"output_name in output_names]) for expected, result in zip(float_results, eightbit_results): assert",
"dtype=dtypes.float32, shape=[6]) float_graph_def.node.extend([offset_constant]) bias_add_node = quantize_graph.create_node( \"BiasAdd\", bias_add_name, [input_constant_name, offset_constant_name])",
"qarr = quantize_graph.quantize_array(arr.reshape((2, 2)), 2) self.assertTrue((np.array([[0.25, 0.25], [0.75, 0.75]]) ==",
"quantize_graph.set_attr_dtype(relu_node, \"T\", dtypes.float32) min_node = quantize_graph.create_constant_node( \"min_bias_add\", value=0, dtype=dtypes.float32, shape=[])",
"- b_value total_difference += difference total_abs_difference += abs(difference) if abs(difference)",
"0 total_difference = 0 total_abs_difference = 0 for index in",
"12], dtype=dtypes.float32, shape=[1, 2, 6, 1]) float_graph_def.node.extend([input_constant]) relu_node = quantize_graph.create_node(\"Relu\",",
"3], dtype=dtypes.float32, shape=[4, 1]) weight_1_node = quantize_graph.create_constant_node( \"weight_1\", value=[.5, .6,",
"[split_constant_name, input_constant_name]) quantize_graph.set_attr_int(split_node, \"num_split\", 2) quantize_graph.set_attr_dtype(split_node, \"T\", dtypes.float32) float_graph_def.node.extend([split_node]) concat_constant",
"\"T\", dtypes.uint8) graph_def.node.extend([b_quantize_node]) mat_mul_node = quantize_graph.create_node(\"QuantizedMatMul\", mat_mul_name, [ a_quantize_name, b_quantize_name,",
"3]) test_mat_mul(1, 1, 2, [1, 1], [1, 1]) test_mat_mul(1, 1,",
"b_constant_name]) quantize_graph.set_attr_int(concat_node, \"N\", 2) quantize_graph.set_attr_dtype(concat_node, \"T\", dtypes.float32) float_graph_def.node.extend([concat_node]) test_graph(float_graph_def, {},",
"6.]) def _RunTestsForQuantizedInputRange(self, float_graph_def, input_map, output_names, input_range): if sys.version_info[0] ==",
"8, 9, 10], dtype=dtypes.float32, shape=[1, 1, 2, 5]) offset_node =",
"\"ksize\", [1, 2, 2, 1]) quantize_graph.set_attr_int_list(max_pool_node, \"strides\", [1, 1, 1,",
"graph_def.node.extend([a_quantize_node]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=(0,), dtype=dtypes.quint8, shape=[]) graph_def.node.extend([b_constant]) b_constant_min",
"value=15.5, dtype=dtypes.float32, shape=[]) fake_quant_node = quantize_graph.create_node( \"FakeQuantWithMinMaxVars\", \"fake_quant\", [bias_add_node.name, min_node.name,",
"test_graph(float_graph_def, {}, [fake_quant_node.name], log_graph=True) # Verify there is only one",
"float_graph_def, \"eightbit\", quantized_input_range=None, fallback_quantization_range=[-.5, 15.5]) eightbit_graph_def = eightbit_rewriter.rewrite([bias_add_node.name]) ops =",
"value=2, dtype=dtypes.float32, shape=[]) expected_output.node.extend([a_constant_min]) a_constant_max = quantize_graph.create_constant_node( a_constant_max_name, value=2, dtype=dtypes.float32,",
"1], [1, 1]) test_mat_mul(1, 1, 2, [0, 0], [1, 1])",
"== max(matrix), which used to cause problems. test_mat_mul(1, 1, 1,",
"\" difference {2} and mean absolute difference {3}\".format( how_many_different, proportion_different",
"= [output_name + \":0\" for output_name in output_names] float_results =",
"+ ops.count(\"Quantize\")) # One dequantize at the end. self.assertEqual(1, ops.count(\"Dequantize\"))",
"ops.count(\"Dequantize\")) def test_bias_add_w_fake_quant_w_min_max_vars(self): input_node = quantize_graph.create_constant_node( \"input\", value=[1, 2, 3,",
"arr = arr.reshape(v.shape) arr = arr.astype(dtypes.quint8.as_numpy_dtype) quantized_input_map[k] = arr output_tensors",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"are in the graph. self.assertEqual(1, node_names.count(\"fallback_quantization_min_value\")) self.assertEqual(1, node_names.count(\"fallback_quantization_max_value\")) def test_remove_redundant_quantization(self):",
"sys import numpy as np from tensorflow.core.framework import graph_pb2 from",
"def test_conv(depth, image_width, image_height, image_batch_count, filter_size, filter_count, stride, padding, input_values,",
"or value > max: max_value = value max_index = index",
"graph_pb2.GraphDef() g.node.extend([a, shape, reshape]) test_graph(g, {}, [reshape.name]) def test_concat(self): shape_constant_name",
"False) quantize_graph.set_attr_bool(mat_mul_node, \"transpose_b\", False) float_graph_def.node.extend([mat_mul_node]) test_graph(float_graph_def, {}, [mat_mul_name]) def test_conv(depth,",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"for the specific language governing permissions and # limitations under",
"= quantize_graph.create_constant_node( b_constant_name, value=[13, 14, 15, 16, 17, 18, 19,",
"quantize_graph.create_constant_node( b_constant_min_name, value=3, dtype=dtypes.float32, shape=[]) expected_output.node.extend([b_constant_min]) b_constant_max = quantize_graph.create_constant_node( b_constant_max_name,",
"dtypes.uint8) quantize_graph.set_attr_dtype(mat_mul_node, \"T2\", dtypes.int32) expected_output.node.extend([mat_mul_node]) expected_output.versions.CopyFrom(graph_def.versions) expected_output.library.CopyFrom(graph_def.library) rewriter = quantize_graph.GraphRewriter(",
"4, 5, 6, 7, 8, 9]) def test_mat_mul_tiny(self): # These",
"= None max_index = None for index, value in enumerate(input_values.flatten()):",
"shape=[image_batch_count, image_height, image_width, depth]) float_graph_def.node.extend([input_constant]) filter_constant = quantize_graph.create_constant_node( filter_constant_name, value=filter_values,",
"end. self.assertEqual(1, ops.count(\"Dequantize\")) def test_quantize_array(self): # Test invalid parameters (empty",
"and can be quantized up-front. self.assertEqual(0, ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) #",
"invalid parameters (empty array, or 0 buckets. self.assertRaises(ValueError, quantize_graph.quantize_array, np.array([]),",
"language governing permissions and # limitations under the License. #",
"quantize_graph.unique_node_name_from_input(\"^SomeName:2\")) def test_identity(self): input_constant_name = \"input_constant\" identity_name = \"identity\" float_graph_def",
"+ \":2\" ]) quantize_graph.set_attr_dtype(mat_mul_node, \"T1\", dtypes.uint8) quantize_graph.set_attr_dtype(mat_mul_node, \"T2\", dtypes.int32) graph_def.node.extend([mat_mul_node])",
"required by applicable law or agreed to in writing, software",
"to help debug problems with quantization. It prints out information",
"quantize_graph.set_attr_dtype(relu6_node, \"T\", dtypes.float32) float_graph_def.node.extend([relu6_node]) test_graph(float_graph_def, {}, [relu6_name]) def test_bias_add(self): input_constant_name",
"graph_def.node.extend([a_identity_node]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=1, dtype=dtypes.float32, shape=[]) graph_def.node.extend([b_constant]) b_check_node",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"absolute average errors. Args: a: First comparison tensor. b: Second",
"[output_name + \":0\" for output_name in output_names] float_results = run_graph_def(float_graph_def,",
"a_dequantize_name + \":1\", a_dequantize_name + \":2\"]) quantize_graph.set_attr_dtype(a_quantize_node, \"T\", dtypes.uint8) graph_def.node.extend([a_quantize_node])",
"\"gamma_constant\" batch_norm_name = \"batch_norm\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node(",
"import flags as flags_lib from tensorflow.python.platform import test from tensorflow.python.platform",
"output_name in output_names] float_results = run_graph_def(float_graph_def, input_map, output_tensors) # Quantize",
"difference {3}\".format( how_many_different, proportion_different * 100, mean_difference, mean_abs_difference)) return False",
"concat_node = quantize_graph.create_node( \"Concat\", concat_name, [concat_constant_name, split_name + \":0\", split_name",
"float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend(inputs + [mat_mul_node]) input_map = { inputs[0].name",
"/ value_count if how_many_different == 0: return True else: tf_logging.info(\"Tensors",
"= \"a_quantize\" b_constant_name = \"b_constant\" b_constant_min_name = \"b_constant_min\" b_constant_max_name =",
"[0, 0], [1, 1]) # The general case. test_mat_mul(1, 1,",
"dtype=dtypes.int32, shape=[]) float_graph_def.node.extend([shape_constant]) a_constant = quantize_graph.create_constant_node( a_constant_name, value=[1, 2, 3,",
"quantize_graph.create_node( \"Identity\", b_identity_name, [b_constant_name, \"^\" + b_check_name]) graph_def.node.extend([b_identity_node]) add_node =",
"input_constant_name = \"input_constant\" relu6_name = \"relu6\" float_graph_def = graph_pb2.GraphDef() input_constant",
"\"mat_mul\" float_graph_def = graph_pb2.GraphDef() a_constant = quantize_graph.create_constant_node( a_constant_name, value=a, dtype=dtypes.float32,",
"[node.op for node in eightbit_graph_def.node] # No quantize since all",
"== qarr).all()) qarr = quantize_graph.quantize_array(arr, 2) self.assertTrue((np.array([0.25, 0.25, 0.75, 0.75])",
"are_tensors_near(expected, result, 1.0) class QuantizeGraphTest(test.TestCase): def test_negative_const_problem(self): shape_constant_name = \"shape_constant\"",
"agreed to in writing, software # distributed under the License",
"mean_constant_name, variance_constant_name, beta_constant_name, gamma_constant_name ]) quantize_graph.set_attr_dtype(batch_norm_node, \"T\", dtypes.float32) quantize_graph.set_attr_bool(batch_norm_node, \"scale_after_normalization\",",
"the differences between tensors on failure, paying special attention to",
"graph_pb2.GraphDef() g.node.extend([concat_dim, a, b, concat]) test_graph(g, {}, [concat.name]) def test_non_float_reshape(self):",
"= [node.op for node in eightbit_graph_def.node] # No quantize since",
"value=0, dtype=dtypes.float32, shape=[]) max_node = quantize_graph.create_constant_node( \"max_bias_add\", value=12, dtype=dtypes.float32, shape=[])",
"= quantize_graph.create_node( \"BiasAdd\", \"bias_add\", [input_node.name, offset_node.name]) quantize_graph.set_attr_dtype(bias_add_node, \"T\", dtypes.float32) float_graph_def",
"result, 1.0) if log_graph: tf_logging.info(\"8bit:\\n%s\", str(eightbit_graph_def)) # Test the weights_rounded",
"10, 11, 12], dtype=dtypes.float32, shape=[1, 1, 2, 6]) float_graph_def.node.extend([input_constant]) offset_constant",
"distributed under the License is distributed on an \"AS IS\"",
"float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=[1, 4, 2,",
"self.assertEqual(1, node_names.count(\"fallback_quantization_max_value\")) def test_remove_redundant_quantization(self): a_constant_name = \"a_constant\" a_constant_min_name = \"a_constant_min\"",
"1]) == qarr).all()) # Test \"normal\" input arrays. arr =",
"\":2\"]) quantize_graph.set_attr_dtype(a_quantize_node, \"T\", dtypes.uint8) graph_def.node.extend([a_quantize_node]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=(0,),",
"value=[10, 2], dtype=dtypes.int32, shape=[2]) reshape_node = quantize_graph.create_node( \"Reshape\", \"reshape\", [matmul_1_node.name,",
"= graph_pb2.GraphDef() shape_constant = quantize_graph.create_constant_node( shape_constant_name, value=0, dtype=dtypes.int32, shape=[]) float_graph_def.node.extend([shape_constant])",
"importer.import_graph_def(graph_def, input_map={}, name=\"\") with session.Session(graph=graph) as sess: results = sess.run(outputs,",
"* 1.0) / value_count if how_many_different == 0: return True",
"quantize_graph.create_constant_node( \"input\", value=[0, 1, 2, 3], dtype=dtypes.float32, shape=[4, 1]) weight_1_node",
"graph_def.node.extend([no_op]) a_constant = quantize_graph.create_constant_node( a_constant_name, value=1, dtype=dtypes.float32, shape=[]) graph_def.node.extend([a_constant]) a_check_node",
"end. self.assertEqual(1, ops.count(\"Dequantize\")) # The fallback constants are not in",
"shape=[6]) float_graph_def.node.extend([offset_constant]) bias_add_node = quantize_graph.create_node( \"BiasAdd\", bias_add_name, [input_constant_name, offset_constant_name]) quantize_graph.set_attr_dtype(bias_add_node,",
"shape=[]) fake_quant_node = quantize_graph.create_node( \"FakeQuantWithMinMaxVars\", \"fake_quant\", [relu_node.name, min_node.name, max_node.name]) float_graph_def",
"7, 8, 9, 10, 11, 12], dtype=dtypes.float32, shape=[1, 1, 2,",
"shape=[]) graph_def.node.extend([b_constant_min]) b_constant_max = quantize_graph.create_constant_node( b_constant_max_name, value=3, dtype=dtypes.float32, shape=[]) graph_def.node.extend([b_constant_max])",
"\"reshape\", [a.name, shape.name]) quantize_graph.set_attr_dtype(reshape, \"T\", dtypes.int32) g = graph_pb2.GraphDef() g.node.extend([a,",
"dtype=dtypes.float32, shape=[]) expected_output.node.extend([a_constant]) a_identity_node = quantize_graph.create_node( \"Identity\", a_identity_name, [a_constant_name, \"^\"",
"Test the graph test_graph(g, {}, [\"matmul_2\"]) # Verify there is",
"error case we ran into in a real graph.\"\"\" test_conv(1,",
"dtypes.int32) g = graph_pb2.GraphDef() g.node.extend([concat_dim, a, b, concat]) test_graph(g, {},",
"in inputs]) quantize_graph.set_attr_dtype(mat_mul_node, \"T\", dtypes.float32) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend(inputs +",
"batch_norm_node = quantize_graph.create_node( \"BatchNormWithGlobalNormalization\", batch_norm_name, [ input_constant_name, mean_constant_name, variance_constant_name, beta_constant_name,",
"[bias_add_n.name], [-1, 20.]) self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [bias_add_n.name], [0, 12.]) def test_quantized_input_range_mat_mul(self):",
"15, 16], [1, 2, 3, 4, 5, 6, 7, 8,",
"[-1, 20.]) self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [mat_mul_node.name], [0, 6.]) def _RunTestsForQuantizedInputRange(self, float_graph_def,",
"def test_non_float_concat(self): concat_dim = quantize_graph.create_constant_node( \"concat_dim\", value=0, dtype=dtypes.int32, shape=[]) a",
"a_dequantize_name = \"a_dequantize\" a_quantize_name = \"a_quantize\" b_constant_name = \"b_constant\" b_constant_min_name",
"12, 13, 14, 15, 16], [1, 2, 3, 4, 5,",
"graph_pb2.GraphDef() float_graph_def.node.extend(inputs + [mat_mul_node]) input_map = { inputs[0].name + \":0\":",
"quantize_graph.create_constant_node( shape_constant_name, value=-0.8, dtype=dtypes.float32, shape=[1]) quantization_result = quantize_graph.quantize_weight_eightbit( shape_constant, b\"MIN_COMBINED\")",
"\"a_constant_max\" a_dequantize_name = \"a_dequantize\" a_quantize_name = \"a_quantize\" b_constant_name = \"b_constant\"",
"shape=[1, 5]) matmul_1_node = make_matmul(\"matmul_1\", input_node, weight_1_node) # Reshape 4x5",
"6, 7, 8, 9, 10, 11, 12], dtype=dtypes.float32, shape=[1, 1,",
"[b_constant_name]) graph_def.node.extend([b_check_node]) b_identity_node = quantize_graph.create_node( \"Identity\", b_identity_name, [b_constant_name, \"^\" +",
"import sys import numpy as np from tensorflow.core.framework import graph_pb2",
"\"b_constant_min\" b_constant_max_name = \"b_constant_max\" b_dequantize_name = \"b_dequantize\" b_quantize_name = \"b_quantize\"",
".7, .8, .9], dtype=dtypes.float32, shape=[1, 5]) matmul_1_node = make_matmul(\"matmul_1\", input_node,",
"quantize_graph.set_attr_dtype(mat_mul_node, \"T1\", dtypes.uint8) quantize_graph.set_attr_dtype(mat_mul_node, \"T2\", dtypes.int32) expected_output.node.extend([mat_mul_node]) expected_output.versions.CopyFrom(graph_def.versions) expected_output.library.CopyFrom(graph_def.library) rewriter",
"flags as flags_lib from tensorflow.python.platform import test from tensorflow.python.platform import",
"\"T\", dtypes.float32) quantize_graph.set_attr_bool(mat_mul_node, \"transpose_a\", False) quantize_graph.set_attr_bool(mat_mul_node, \"transpose_b\", False) float_graph_def.node.extend([mat_mul_node]) test_graph(float_graph_def,",
"\"concat\", [concat_dim.name, a.name, b.name]) quantize_graph.set_attr_int(concat, \"N\", 2) quantize_graph.set_attr_dtype(concat, \"T\", dtypes.int32)",
"flat_b[index] difference = a_value - b_value total_difference += difference total_abs_difference",
"zip(float_results, weights_rounded_results): assert are_tensors_near(expected, result, 1.0) class QuantizeGraphTest(test.TestCase): def test_negative_const_problem(self):",
"graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=[1, 2, 3, 4, 5,",
"quantize_graph.node_name_from_input(\"^SomeName:2\")) def test_unique_node_name_from_input(self): self.assertEqual(\"__hat__SomeName__port__2\", quantize_graph.unique_node_name_from_input(\"^SomeName:2\")) def test_identity(self): input_constant_name = \"input_constant\"",
"as ops_lib from tensorflow.python.platform import flags as flags_lib from tensorflow.python.platform",
"quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite([concat_name]) ops = [node.op for node in",
"float_graph_def = graph_pb2.GraphDef() a_constant = quantize_graph.create_constant_node( a_constant_name, value=a, dtype=dtypes.float32, shape=[m,",
"\"bias_add\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=[1, 2,",
"= quantize_graph.create_node( \"Concat\", concat_name, [concat_constant_name, split_name + \":0\", split_name +",
"= [node.op for node in eightbit_graph_def.node] self.assertEqual(1, ops.count(\"QuantizedConcat\")) def test_multiple_outputs(self):",
"tensorflow.python.client import session from tensorflow.python.framework import dtypes from tensorflow.python.framework import",
"test_conv(depth, image_width, image_height, image_batch_count, filter_size, filter_count, stride, padding, input_values, filter_values):",
"test_keep_control_edges(self): no_op_name = \"no_op\" a_constant_name = \"a_constant\" b_constant_name = \"b_constant\"",
"{}, [fake_quant_node.name], log_graph=True) # Verify there is only one Quantize",
"mat_mul_node = quantize_graph.create_node(\"MatMul\", \"mat_mul\", [n.name for n in inputs]) quantize_graph.set_attr_dtype(mat_mul_node,",
"quantize_graph.create_constant_node( \"new_shape_node\", value=[10, 2], dtype=dtypes.int32, shape=[2]) reshape_node = quantize_graph.create_node( \"Reshape\",",
"= quantize_graph.create_constant_node( a_constant_max_name, value=2, dtype=dtypes.float32, shape=[]) graph_def.node.extend([a_constant_max]) a_dequantize_node = quantize_graph.create_node(",
"a_identity_name = \"a_identity\" b_identity_name = \"b_identity\" add_name = \"add\" graph_def",
"index in range(value_count): a_value = flat_a[index] b_value = flat_b[index] difference",
"6, 7, 8, 9, 10], dtype=dtypes.float32, shape=[1, 1, 2, 5])",
"quantize_graph.create_constant_node( a_constant_max_name, value=2, dtype=dtypes.float32, shape=[]) graph_def.node.extend([a_constant_max]) a_dequantize_node = quantize_graph.create_node( \"Dequantize\",",
"5]) matmul_1_node = make_matmul(\"matmul_1\", input_node, weight_1_node) # Reshape 4x5 to",
"shape=[]) expected_output.node.extend([a_constant]) a_constant_min = quantize_graph.create_constant_node( a_constant_min_name, value=2, dtype=dtypes.float32, shape=[]) expected_output.node.extend([a_constant_min])",
"input_range[ 0]))) for n in v.flat ] arr = np.array(arr,",
"2, 3, 4, 5, 6], dtype=dtypes.float32, shape=[6]) float_graph_def.node.extend([offset_constant]) bias_add_node =",
"offset_n.name]) quantize_graph.set_attr_dtype(bias_add_n, \"T\", dtypes.float32) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend([input_n, offset_n, bias_add_n])",
"test_mat_mul(2, 4, 3, [1, 2, 3, 4, 5, 6], [7,",
"\"eightbit\", quantized_input_range=None, fallback_quantization_range=[-.5, 15.5]) eightbit_graph_def = eightbit_rewriter.rewrite([bias_add_node.name]) ops = [node.op",
"n in inputs]) quantize_graph.set_attr_dtype(mat_mul_node, \"T\", dtypes.float32) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend(inputs",
"0.5]) == qarr).all()) qarr = quantize_graph.quantize_array(arr, 2) self.assertTrue((np.array([0.25, 0.25, 0.75,",
"No quantize since all inputs are const and can be",
"dtype=dtypes.float32, shape=[]) graph_def.node.extend([a_constant_min]) a_constant_max = quantize_graph.create_constant_node( a_constant_max_name, value=2, dtype=dtypes.float32, shape=[])",
"max(matrix), which used to cause problems. test_mat_mul(1, 1, 1, [2],",
"without treating input as quantized. rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\",",
"quantize_graph.create_constant_node( input_constant_name, value=[1, 2, 3, 4, 5, 6, 7, 8,",
"2) self.assertTrue((np.array([[0.25, 0.25], [0.75, 0.75]]) == qarr).all()) def test_non_float_concat(self): concat_dim",
"dtype=dtypes.int32, shape=[]) float_graph_def.node.extend([concat_constant]) concat_node = quantize_graph.create_node( \"Concat\", concat_name, [concat_constant_name, split_name",
"eightbit_rewriter.rewrite([fake_quant_node.name]) ops = [node.op for node in eightbit_graph_def.node] # No",
"total_difference = 0 total_abs_difference = 0 for index in range(value_count):",
"2, 3, 4, 5, 6], shapes[0]), inputs[1].name + \":0\": np.reshape([.8,",
"float_graph_def.node.extend( [input_node, relu_node, min_node, max_node, fake_quant_node]) test_graph(float_graph_def, {}, [fake_quant_node.name], log_graph=True)",
"16, 17, 18]) def test_conv(self): test_conv(1, 4, 3, 1, 3,",
"10], dtype=dtypes.float32, shape=[1, 1, 2, 5]) offset_node = quantize_graph.create_constant_node( \"offset\",",
"[-1, 20.]) self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [bias_add_n.name], [0, 12.]) def test_quantized_input_range_mat_mul(self): shapes",
"5, 8, 3, 6, 9]) def test_reshape(self): \"\"\"Tests that MatMul->Reshape->MatMul",
"in the graph. self.assertEqual(0, node_names.count(\"fallback_quantization_min_value\")) self.assertEqual(0, node_names.count(\"fallback_quantization_max_value\")) def test_bias_add_w_fallback_min_max_vars(self): input_node",
"shape=[1]) quantization_result = quantize_graph.quantize_weight_eightbit( shape_constant, b\"MIN_COMBINED\") self.assertEqual(4, len(quantization_result)) def test_odd_padding_problem(self):",
"tensor. tolerance: Float value indicating how large an error between",
"quantize_graph.create_constant_node( \"input\", value=[1, 2, 3, 4, 5, 6, 7, 8,",
"= quantize_graph.quantize_array(arr, 2) self.assertEqual(arr, qarr) # Test input array with",
"biases by looking at the mean and absolute average errors.",
"12], dtype=dtypes.float32, shape=[1, 2, 6, 1]) float_graph_def.node.extend([input_constant]) relu6_node = quantize_graph.create_node(\"Relu6\",",
"float_graph_def.node.extend([input_constant]) max_pool_node = quantize_graph.create_node(\"MaxPool\", max_pool_name, [input_constant_name]) quantize_graph.set_attr_int_list(max_pool_node, \"ksize\", [1, 2,",
"-3, -6], dtype=dtypes.float32, shape=[1, 1, 6, 2]) float_graph_def.node.extend([input_constant]) mean_constant =",
"\"input_constant\" max_pool_name = \"max_pool\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node(",
"float_graph_def.node.extend([avg_pool_node]) test_graph(float_graph_def, {}, [avg_pool_name]) def test_relu(self): input_constant_name = \"input_constant\" relu_name",
"input_map, [mat_mul_node.name], [0, 6.]) def _RunTestsForQuantizedInputRange(self, float_graph_def, input_map, output_names, input_range):",
"12], dtype=dtypes.int32, shape=[2, 2, 3]) shape = quantize_graph.create_constant_node( \"shape\", value=[12],",
"= \"b_check\" a_identity_name = \"a_identity\" b_identity_name = \"b_identity\" add_name =",
"False) float_graph_def.node.extend([mat_mul_node]) test_graph(float_graph_def, {}, [mat_mul_name]) def test_conv(depth, image_width, image_height, image_batch_count,",
"quantize_graph.create_node(\"QuantizedMatMul\", mat_mul_name, [ a_quantize_name, b_quantize_name, a_quantize_name + \":1\", a_quantize_name +",
"index, value in enumerate(input_values.flatten()): if max_value is None or value",
"a_constant_max_name]) quantize_graph.set_attr_dtype(a_dequantize_node, \"T\", dtypes.uint8) graph_def.node.extend([a_dequantize_node]) a_quantize_node = quantize_graph.create_node( \"QuantizeV2\", a_quantize_name,",
"6, 7, 8, 9, 10, 11, 12], input_shape) } self._RunTestsForQuantizedInputRange(float_graph_def,",
"filter_size, filter_count, stride, padding, input_values, filter_values): \"\"\"Tests a Conv replacement.\"\"\"",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"from tensorflow.python.platform import test from tensorflow.python.platform import tf_logging from tensorflow.tools.quantization",
"quantize_graph.create_constant_node( \"b\", value=[13, 14, 15, 16, 17, 18, 19, 20,",
"dtypes.uint8) graph_def.node.extend([b_quantize_node]) mat_mul_node = quantize_graph.create_node(\"QuantizedMatMul\", mat_mul_name, [ a_quantize_name, b_quantize_name, a_quantize_name",
"Test input array of length 1. arr = np.array([1]) qarr",
"add_node = quantize_graph.create_node(\"Add\", add_name, [a_identity_name, b_constant_name]) quantize_graph.set_attr_dtype(add_node, \"T\", dtypes.float32) expected_output.node.extend([add_node])",
"average errors. Args: a: First comparison tensor. b: Second comparison",
"the License is distributed on an \"AS IS\" BASIS, #",
"the FakeQuantWithMinMaxVars are used instead. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\",",
"= quantize_graph.create_node(\"Reshape\", \"reshape\", [a.name, shape.name]) quantize_graph.set_attr_dtype(reshape, \"T\", dtypes.int32) g =",
"expected_output.node.extend([b_constant]) add_node = quantize_graph.create_node(\"Add\", add_name, [a_identity_name, b_constant_name]) quantize_graph.set_attr_dtype(add_node, \"T\", dtypes.float32)",
"input_constant_name, value=[1, 4, 2, 5, 3, 6, -1, -4, -2,",
"mode. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite(output_names)",
"case where # min(matrix) == max(matrix), which used to cause",
"[1, 2, 3, 4, 5, 6], [7, 8, 9, 10,",
"6], [7, 8, 9, 10, 11, 12, 13, 14, 15,",
"np.array([0, 0.3, 0.6, 1]) qarr = quantize_graph.quantize_array(arr, 1) self.assertTrue((np.array([0.5, 0.5,",
"the generate case where # min(matrix) == max(matrix), which used",
"max_pool_node = quantize_graph.create_node(\"MaxPool\", max_pool_name, [input_constant_name]) quantize_graph.set_attr_int_list(max_pool_node, \"ksize\", [1, 2, 2,",
"max_value = None max_index = None for index, value in",
"because there is no # RoundToSteps op available. # round_rewriter",
"input_map, [mat_mul_node.name], [-1, 20.]) self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [mat_mul_node.name], [0, 6.]) def",
"flat_a[index] b_value = flat_b[index] difference = a_value - b_value total_difference",
"result in zip(float_results, results): assert are_tensors_near(expected, result, .5) ops =",
"input_map, outputs): graph = ops_lib.Graph() with graph.as_default(): importer.import_graph_def(graph_def, input_map={}, name=\"\")",
"quantize_graph.create_constant_node( a_constant_name, value=1, dtype=dtypes.float32, shape=[]) expected_output.node.extend([a_constant]) a_identity_node = quantize_graph.create_node( \"Identity\",",
"shape=[1, 2, 6, 1]) relu_node = quantize_graph.create_node(\"Relu\", \"relu\", [input_node.name]) quantize_graph.set_attr_dtype(relu_node,",
"1, 2, [1, 1], [1, 1]) test_mat_mul(1, 1, 2, [0,",
"\"dtype\", dtypes.float32) quantize_graph.set_attr_shape(input_n, \"shape\", input_shape) offset_n = quantize_graph.create_constant_node( \"offset\", value=[1,",
"only one Quantize, one Requantize op, and no # RequantizationRange",
"quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite(output_names) eightbit_results = run_graph_def(",
"b_identity_name]) quantize_graph.set_attr_dtype(add_node, \"T\", dtypes.float32) graph_def.node.extend([add_node]) expected_output = graph_pb2.GraphDef() no_op =",
"= quantize_graph.create_constant_node( b_constant_max_name, value=3, dtype=dtypes.float32, shape=[]) expected_output.node.extend([b_constant_max]) mat_mul_node = quantize_graph.create_node(\"QuantizedMatMul\",",
"replacement.\"\"\" input_constant_name = \"input_constant\" filter_constant_name = \"filter_constant\" conv_name = \"conv\"",
"flat_b = b.flatten() if len(flat_a) != len(flat_b): tf_logging.info(\"Tensors are different",
"input_node, offset_node, bias_add_node, min_node, max_node, fake_quant_node ]) test_graph(float_graph_def, {}, [fake_quant_node.name],",
"law or agreed to in writing, software # distributed under",
"[input_constant_name]) quantize_graph.set_attr_int_list(max_pool_node, \"ksize\", [1, 2, 2, 1]) quantize_graph.set_attr_int_list(max_pool_node, \"strides\", [1,",
"input_constant_name = \"input_constant\" relu_name = \"relu\" float_graph_def = graph_pb2.GraphDef() input_constant",
"op available. # round_rewriter = quantize_graph.GraphRewriter(float_graph_def, \"round\") # round_graph_def =",
"+ \":0\"]) # assert are_tensors_near(expected, round_results[0], 1.0) # # TODO(petewarden):",
"= graph_pb2.GraphDef() float_graph_def.node.extend(inputs + [mat_mul_node]) input_map = { inputs[0].name +",
"2, 5, 3, 6, -1, -4, -2, -5, -3, -6],",
"numpy as np from tensorflow.core.framework import graph_pb2 from tensorflow.python.client import",
"eightbit_graph_def = eightbit_rewriter.rewrite([\"matmul_2\"]) ops = [node.op for node in eightbit_graph_def.node]",
"avg_pool_node = quantize_graph.create_node(\"AvgPool\", avg_pool_name, [input_constant_name]) quantize_graph.set_attr_dtype(avg_pool_node, \"T\", dtypes.float32) quantize_graph.set_attr_int_list(avg_pool_node, \"ksize\",",
"+ \":1\", a_dequantize_name + \":2\"]) quantize_graph.set_attr_dtype(a_quantize_node, \"T\", dtypes.uint8) graph_def.node.extend([a_quantize_node]) b_constant",
"import tf_logging from tensorflow.tools.quantization import quantize_graph flags = flags_lib FLAGS",
"dtype=dtypes.float32, shape=[2, 1]) matmul_2_node = make_matmul(\"matmul_2\", reshape_node, weight_2_node) g =",
"quantize_graph.set_attr_int(concat, \"N\", 2) quantize_graph.set_attr_dtype(concat, \"T\", dtypes.int32) g = graph_pb2.GraphDef() g.node.extend([concat_dim,",
"the two inputs were close enough. \"\"\" flat_a = a.flatten()",
"b_constant_max_name = \"b_constant_max\" b_dequantize_name = \"b_dequantize\" b_quantize_name = \"b_quantize\" mat_mul_name",
"[concat_name]) def test_node_name_from_input(self): self.assertEqual(\"SomeName\", quantize_graph.node_name_from_input(\"^SomeName:2\")) def test_unique_node_name_from_input(self): self.assertEqual(\"__hat__SomeName__port__2\", quantize_graph.unique_node_name_from_input(\"^SomeName:2\")) def",
"self.assertEqual(0, ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) self.assertEqual(len(output_names), ops.count(\"Dequantize\")) # Quantize without treating",
"debug problems with quantization. It prints out information about the",
"One dequantize at the end. self.assertEqual(1, ops.count(\"Dequantize\")) # No RequantizationRange",
"a_constant_name, b_constant_name]) quantize_graph.set_attr_int(concat_node, \"N\", 2) quantize_graph.set_attr_dtype(concat_node, \"T\", dtypes.float32) float_graph_def.node.extend([concat_node]) test_graph(float_graph_def,",
"b_quantize_name + \":2\" ]) quantize_graph.set_attr_dtype(mat_mul_node, \"T1\", dtypes.uint8) quantize_graph.set_attr_dtype(mat_mul_node, \"T2\", dtypes.int32)",
"bias_add_node, min_node, max_node, fake_quant_node ]) test_graph(float_graph_def, {}, [fake_quant_node.name], log_graph=True) #",
"only one Quantize and one Requantize op. # Pass in",
"float_graph_def.node.extend([concat_constant]) concat_node = quantize_graph.create_node( \"Concat\", concat_name, [concat_constant_name, split_name + \":0\",",
"a_dequantize_name, [a_constant_name, a_constant_min_name, a_constant_max_name]) quantize_graph.set_attr_dtype(a_dequantize_node, \"T\", dtypes.uint8) graph_def.node.extend([a_dequantize_node]) a_quantize_node =",
"input_constant_name = \"input_constant\" offset_constant_name = \"offset_constant\" bias_add_name = \"bias_add\" float_graph_def",
"may obtain a copy of the License at # #",
"assert are_tensors_near(expected, result, 1.0) class QuantizeGraphTest(test.TestCase): def test_negative_const_problem(self): shape_constant_name =",
"a real graph.\"\"\" test_conv(1, 4, 4, 1, 3, 1, 2,",
"= flat_a[index] b_value = flat_b[index] difference = a_value - b_value",
"\"T\", dtypes.uint8) graph_def.node.extend([a_dequantize_node]) a_quantize_node = quantize_graph.create_node( \"QuantizeV2\", a_quantize_name, [a_dequantize_name, a_dequantize_name",
"self.assertEqual(arr, qarr) # Test input array with all elements equal.",
"graph_def.node.extend([b_constant]) b_check_node = quantize_graph.create_node(\"CheckNumerics\", b_check_name, [b_constant_name]) graph_def.node.extend([b_check_node]) b_identity_node = quantize_graph.create_node(",
"k, a, b): \"\"\"Tests a MatMul replacement.\"\"\" a_constant_name = \"a_constant\"",
"= eightbit_rewriter.rewrite([fake_quant_node.name]) ops = [node.op for node in eightbit_graph_def.node] #",
"def _RunTestsForQuantizedInputRange(self, float_graph_def, input_map, output_names, input_range): if sys.version_info[0] == 3:",
"self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [mat_mul_node.name], [-1, 20.]) self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [mat_mul_node.name], [0, 6.])",
"dtype=dtypes.float32, shape=[filter_size, filter_size, depth, filter_count]) float_graph_def.node.extend([filter_constant]) conv_node = quantize_graph.create_node( \"Conv2D\",",
"split_name + \":1\"]) quantize_graph.set_attr_int(concat_node, \"N\", 2) quantize_graph.set_attr_dtype(concat_node, \"T\", dtypes.float32) float_graph_def.node.extend([concat_node])",
"may not use this file except in compliance with the",
"float_graph_def.node.extend([shape_constant]) a_constant = quantize_graph.create_constant_node( a_constant_name, value=[1, 2, 3, 4, 5,",
"2, 6]) float_graph_def.node.extend([input_constant]) offset_constant = quantize_graph.create_constant_node( offset_constant_name, value=[1, 2, 3,",
"quantized_input_range=None, fallback_quantization_range=[-100, 100]) eightbit_graph_def = eightbit_rewriter.rewrite([fake_quant_node.name]) ops = [node.op for",
"= \"no_op\" a_constant_name = \"a_constant\" b_constant_name = \"b_constant\" a_check_name =",
"float_graph_def.node.extend([a_constant]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=[13, 14, 15, 16, 17,",
"9, 10], dtype=dtypes.float32, shape=[1, 1, 2, 5]) offset_node = quantize_graph.create_constant_node(",
"\"T\", dtypes.int32) g = graph_pb2.GraphDef() g.node.extend([concat_dim, a, b, concat]) test_graph(g,",
"max_node.name]) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend([ input_node, offset_node, bias_add_node, min_node, max_node,",
"result, 1.0) class QuantizeGraphTest(test.TestCase): def test_negative_const_problem(self): shape_constant_name = \"shape_constant\" shape_constant",
"total_difference += difference total_abs_difference += abs(difference) if abs(difference) > tolerance:",
"one Quantize, one Requantize op, and no # RequantizationRange op.",
"this file except in compliance with the License. # You",
"flags.FLAGS def run_graph_def(graph_def, input_map, outputs): graph = ops_lib.Graph() with graph.as_default():",
"ops_lib.Graph() with graph.as_default(): importer.import_graph_def(graph_def, input_map={}, name=\"\") with session.Session(graph=graph) as sess:",
"beta_constant_name = \"beta_constant\" gamma_constant_name = \"gamma_constant\" batch_norm_name = \"batch_norm\" float_graph_def",
"\"Identity\", a_identity_name, [a_constant_name, \"^\" + a_check_name, \"^\" + no_op_name]) graph_def.node.extend([a_identity_node])",
"up-front. self.assertEqual(0, ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) self.assertEqual(1, ops.count(\"QuantizedReshape\")) # One dequantize",
"+ \":0\": np.reshape([1, 2, 3, 4, 5, 6], shapes[0]), inputs[1].name",
"[\"matmul_2\"]) # Verify there is only one Quantize and one",
"[b_constant_name, b_constant_min_name, b_constant_max_name]) quantize_graph.set_attr_dtype(b_dequantize_node, \"T\", dtypes.uint8) graph_def.node.extend([b_dequantize_node]) b_quantize_node = quantize_graph.create_node(",
"test_graph(float_graph_def, {}, [conv_name]) def are_tensors_near(a, b, tolerance): \"\"\"Tests whether two",
"\":1\"]) quantize_graph.set_attr_int(concat_node, \"N\", 2) quantize_graph.set_attr_dtype(concat_node, \"T\", dtypes.float32) float_graph_def.node.extend([concat_node]) test_graph(float_graph_def, {},",
"dtypes.float32) graph_def.node.extend([add_node]) expected_output = graph_pb2.GraphDef() no_op = quantize_graph.create_node(\"NoOp\", no_op_name, [])",
"\"ksize\", [1, 2, 2, 1]) quantize_graph.set_attr_int_list(avg_pool_node, \"strides\", [1, 1, 1,",
"# # Licensed under the Apache License, Version 2.0 (the",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"a_constant = quantize_graph.create_constant_node( a_constant_name, value=[1, 2, 3, 4, 5, 6,",
"= quantize_graph.GraphRewriter(float_graph_def, \"round\") # round_graph_def = round_rewriter.rewrite(output_name) # round_results =",
"stride, 1]) quantize_graph.set_attr_string(conv_node, \"padding\", padding) float_graph_def.node.extend([conv_node]) test_graph(float_graph_def, {}, [conv_name]) def",
"ops.count(\"Dequantize\")) def test_relu6(self): input_constant_name = \"input_constant\" relu6_name = \"relu6\" float_graph_def",
"float_graph_def.node.extend([input_constant]) filter_constant = quantize_graph.create_constant_node( filter_constant_name, value=filter_values, dtype=dtypes.float32, shape=[filter_size, filter_size, depth,",
"abs(difference) > tolerance: how_many_different += 1 mean_difference = total_difference /",
"\"Identity\", b_identity_name, [b_constant_name, \"^\" + b_check_name]) graph_def.node.extend([b_identity_node]) add_node = quantize_graph.create_node(\"Add\",",
"[node.op for node in eightbit_graph_def.node] node_names = [node.name for node",
"one error case we ran into in a real graph.\"\"\"",
"about the differences between tensors on failure, paying special attention",
"import dtypes from tensorflow.python.framework import graph_util from tensorflow.python.framework import importer",
"graph. self.assertEqual(1, node_names.count(\"fallback_quantization_min_value\")) self.assertEqual(1, node_names.count(\"fallback_quantization_max_value\")) def test_remove_redundant_quantization(self): a_constant_name = \"a_constant\"",
"max_index = None for index, value in enumerate(input_values.flatten()): if max_value",
"quantize_graph.create_constant_node( \"weight_1\", value=[.5, .6, .7, .8, .9], dtype=dtypes.float32, shape=[1, 5])",
"\"identity\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=[1, 2,",
"3, 6, -1, -4, -2, -5, -3, -6], dtype=dtypes.float32, shape=[1,",
"quantize_graph.create_constant_node( b_constant_name, value=1, dtype=dtypes.float32, shape=[]) expected_output.node.extend([b_constant]) add_node = quantize_graph.create_node(\"Add\", add_name,",
"output_names] float_results = run_graph_def(float_graph_def, input_map, output_tensors) # Quantize treating the",
"a_identity_node = quantize_graph.create_node( \"Identity\", a_identity_name, [a_constant_name, \"^\" + no_op_name]) expected_output.node.extend([a_identity_node])",
"\"\"\"Tests whether two tensors are nearly identical. This is a",
"b_identity_name = \"b_identity\" add_name = \"add\" graph_def = graph_pb2.GraphDef() no_op",
"quantize_graph.create_node(\"Relu6\", relu6_name, [input_constant_name]) quantize_graph.set_attr_dtype(relu6_node, \"T\", dtypes.float32) float_graph_def.node.extend([relu6_node]) test_graph(float_graph_def, {}, [relu6_name])",
"out information about the differences between tensors on failure, paying",
"dtype=dtypes.quint8, shape=[]) expected_output.node.extend([b_constant]) b_constant_min = quantize_graph.create_constant_node( b_constant_min_name, value=3, dtype=dtypes.float32, shape=[])",
"quantize_graph.create_node(\"QuantizedMatMul\", mat_mul_name, [ a_constant_name, b_constant_name, a_constant_min_name, a_constant_max_name, b_constant_min_name, b_constant_max_name ])",
"\"T\", dtypes.float32) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend(inputs + [mat_mul_node]) input_map =",
"quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None, fallback_quantization_range=[-.5, 15.5]) eightbit_graph_def = eightbit_rewriter.rewrite([bias_add_node.name]) ops",
"quantize_graph.set_attr_dtype(reshape, \"T\", dtypes.int32) g = graph_pb2.GraphDef() g.node.extend([a, shape, reshape]) test_graph(g,",
"11, 12], input_shape) } self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [bias_add_n.name], [-1, 20.]) self._RunTestsForQuantizedInputRange(float_graph_def,",
"float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend( [input_node, relu_node, min_node, max_node, fake_quant_node]) test_graph(float_graph_def,",
"split_name + \":0\", split_name + \":1\"]) quantize_graph.set_attr_int(concat_node, \"N\", 2) quantize_graph.set_attr_dtype(concat_node,",
"flags = flags_lib FLAGS = flags.FLAGS def run_graph_def(graph_def, input_map, outputs):",
"\"bias_add\", [input_n.name, offset_n.name]) quantize_graph.set_attr_dtype(bias_add_n, \"T\", dtypes.float32) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend([input_n,",
"if log_graph: tf_logging.info(\"8bit:\\n%s\", str(eightbit_graph_def)) # Test the weights_rounded mode. This",
"# uint8->quint8 conversion for numpy is not working currently. return",
"9, 10, 11, 12], dtype=dtypes.float32, shape=[2, 6]) float_graph_def.node.extend([input_constant]) identity_node =",
"shape=[]) fake_quant_node = quantize_graph.create_node( \"FakeQuantWithMinMaxVars\", \"fake_quant\", [bias_add_node.name, min_node.name, max_node.name]) float_graph_def",
"ops = [node.op for node in graph_def.node] self.assertEqual(0, ops.count(\"QuantizeV2\") +",
"1, 3, 1, 2, b\"SAME\", [1, 2, 3, 4, 5,",
"const and can be quantized up-front. self.assertEqual(0, ops.count(\"QuantizeV2\") + ops.count(\"Quantize\"))",
"quantized_input_map, output_tensors) for expected, result in zip(float_results, results): assert are_tensors_near(expected,",
"= [] for i, shape in enumerate(shapes): node = quantize_graph.create_node(\"Placeholder\",",
"\"T\", dtypes.float32) # matmul_2_node = reshape*weight_2 weight_2_node = quantize_graph.create_constant_node( \"weight_2\",",
"or implied. # See the License for the specific language",
"test_max_pool(self): input_constant_name = \"input_constant\" max_pool_name = \"max_pool\" float_graph_def = graph_pb2.GraphDef()",
"since all inputs are const and can be quantized up-front.",
"output_name in output_names]) for expected, result in zip(float_results, weights_rounded_results): assert",
"shape=[]) expected_output.node.extend([a_constant_max]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=(0,), dtype=dtypes.quint8, shape=[]) expected_output.node.extend([b_constant])",
"beta_constant_name, gamma_constant_name ]) quantize_graph.set_attr_dtype(batch_norm_node, \"T\", dtypes.float32) quantize_graph.set_attr_bool(batch_norm_node, \"scale_after_normalization\", False) quantize_graph.set_attr_float(batch_norm_node,",
"self.assertRaises(ValueError, quantize_graph.quantize_array, np.array([]), 2) self.assertRaises(ValueError, quantize_graph.quantize_array, np.array([1, 2]), 0) #",
"failure, paying special attention to possible biases by looking at",
"op. # Pass in fallback_quantization_range, although it will have no",
"in enumerate(input_values.flatten()): if max_value is None or value > max:",
"value=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],",
"quantize_graph.set_attr_dtype(input_n, \"dtype\", dtypes.float32) quantize_graph.set_attr_shape(input_n, \"shape\", input_shape) offset_n = quantize_graph.create_constant_node( \"offset\",",
"3, 4, 5, 6, 7, 8, 9]) def test_mat_mul_tiny(self): #",
"dtypes.uint8) quantize_graph.set_attr_dtype(mat_mul_node, \"T2\", dtypes.int32) graph_def.node.extend([mat_mul_node]) expected_output = graph_pb2.GraphDef() a_constant =",
"(input_range[1] - input_range[ 0]))) for n in v.flat ] arr",
"test_quantize_array(self): # Test invalid parameters (empty array, or 0 buckets.",
"value=(0,), dtype=dtypes.quint8, shape=[]) graph_def.node.extend([b_constant]) b_constant_min = quantize_graph.create_constant_node( b_constant_min_name, value=3, dtype=dtypes.float32,",
"dtypes.float32) # matmul_2_node = reshape*weight_2 weight_2_node = quantize_graph.create_constant_node( \"weight_2\", value=[1.5,",
"dtype=dtypes.float32, shape=[1, 1, 6, 2]) float_graph_def.node.extend([input_constant]) mean_constant = quantize_graph.create_constant_node( mean_constant_name,",
"graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=input_values, dtype=dtypes.float32, shape=[image_batch_count, image_height, image_width,",
"= { inputs[0].name + \":0\": np.reshape([1, 2, 3, 4, 5,",
"9, 10, 11, 12, 13, 14, 15, 16], [1, 2,",
"test_avg_pool(self): input_constant_name = \"input_constant\" avg_pool_name = \"avg_pool\" float_graph_def = graph_pb2.GraphDef()",
"in range <input_range>. rewriter = quantize_graph.GraphRewriter(float_graph_def, \"eightbit\", input_range) graph_def =",
"1, 1, b\"SAME\", [1, 2, 3, 4, 5, 6, 7,",
"0.6], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([beta_constant]) gamma_constant = quantize_graph.create_constant_node( gamma_constant_name, value=[0, 0],",
"= quantize_graph.create_constant_node( \"weight_2\", value=[1.5, 2.5], dtype=dtypes.float32, shape=[2, 1]) matmul_2_node =",
"\"num_split\", 2) quantize_graph.set_attr_dtype(split_node, \"T\", dtypes.float32) float_graph_def.node.extend([split_node]) concat_constant = quantize_graph.create_constant_node( concat_constant_name,",
"11, 12], dtype=dtypes.float32, shape=[1, 2, 6, 1]) float_graph_def.node.extend([input_constant]) relu_node =",
"b_dequantize_name + \":1\", b_dequantize_name + \":2\"]) quantize_graph.set_attr_dtype(b_quantize_node, \"T\", dtypes.uint8) graph_def.node.extend([b_quantize_node])",
"quantize_graph.set_attr_dtype(batch_norm_node, \"T\", dtypes.float32) quantize_graph.set_attr_bool(batch_norm_node, \"scale_after_normalization\", False) quantize_graph.set_attr_float(batch_norm_node, \"variance_epsilon\", 0.001) float_graph_def.node.extend([batch_norm_node])",
"beta_constant_name, value=[0.1, 0.6], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([beta_constant]) gamma_constant = quantize_graph.create_constant_node( gamma_constant_name,",
"self.assertRaises(ValueError): # Invalid mode. quantize_graph.GraphRewriter(graph_pb2.GraphDef(), \"weights_rounded\", [0, 1]) with self.assertRaises(ValueError):",
"b.name]) quantize_graph.set_attr_int(concat, \"N\", 2) quantize_graph.set_attr_dtype(concat, \"T\", dtypes.int32) g = graph_pb2.GraphDef()",
"sys.version_info[0] == 3: # uint8->quint8 conversion for numpy is not",
"def test_mat_mul_small(self): test_mat_mul(2, 4, 3, [1, 2, 3, 4, 5,",
"* 100, mean_difference, mean_abs_difference)) return False def get_top_value(input_values): max_value =",
"shape=[]) expected_output.node.extend([a_constant_min]) a_constant_max = quantize_graph.create_constant_node( a_constant_max_name, value=2, dtype=dtypes.float32, shape=[]) expected_output.node.extend([a_constant_max])",
"name=\"\") with session.Session(graph=graph) as sess: results = sess.run(outputs, feed_dict=input_map) return",
"b_constant_min_name = \"b_constant_min\" b_constant_max_name = \"b_constant_max\" b_dequantize_name = \"b_dequantize\" b_quantize_name",
"padding, input_values, filter_values): \"\"\"Tests a Conv replacement.\"\"\" input_constant_name = \"input_constant\"",
"dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([beta_constant]) gamma_constant = quantize_graph.create_constant_node( gamma_constant_name, value=[0, 0], dtype=dtypes.float32,",
"__future__ import print_function import sys import numpy as np from",
"+ ops.count(\"Quantize\")) self.assertEqual(1, ops.count(\"QuantizedReshape\")) # One dequantize at the end.",
"= quantize_graph.create_node( \"Identity\", a_identity_name, [a_constant_name, \"^\" + a_check_name, \"^\" +",
"in v.flat ] arr = np.array(arr, np.uint8) arr = arr.reshape(v.shape)",
"ops.count(\"Dequantize\")) # No RequantizationRange self.assertEqual(0, ops.count(\"RequantizationRange\")) # The fallback constants",
"concat_name, [shape_constant_name, a_constant_name, b_constant_name]) quantize_graph.set_attr_int(concat_node, \"N\", 2) quantize_graph.set_attr_dtype(concat_node, \"T\", dtypes.float32)",
"quantize_graph.create_node(\"Relu\", \"relu\", [input_node.name]) quantize_graph.set_attr_dtype(relu_node, \"T\", dtypes.float32) min_node = quantize_graph.create_constant_node( \"min_bias_add\",",
"self.assertEqual(0, node_names.count(\"fallback_quantization_min_value\")) self.assertEqual(0, node_names.count(\"fallback_quantization_max_value\")) def test_bias_add_w_fallback_min_max_vars(self): input_node = quantize_graph.create_constant_node( \"input\",",
"dtypes.float32) quantize_graph.set_attr_shape(input_n, \"shape\", input_shape) offset_n = quantize_graph.create_constant_node( \"offset\", value=[1, 2,",
"= eightbit_rewriter.rewrite([\"matmul_2\"]) ops = [node.op for node in eightbit_graph_def.node] #",
"dtype=dtypes.float32, shape=[2, 2, 3]) float_graph_def.node.extend([b_constant]) concat_node = quantize_graph.create_node( \"Concat\", concat_name,",
"Invalid range. quantize_graph.GraphRewriter(graph_pb2.GraphDef(), \"eightbit\", [0, -1]) def test_quantized_input_range_bias_add(self): input_shape =",
"= quantize_graph.create_node( \"BatchNormWithGlobalNormalization\", batch_norm_name, [ input_constant_name, mean_constant_name, variance_constant_name, beta_constant_name, gamma_constant_name",
"graph_util.remove_training_nodes(graph_def) stripped_output = graph_util.extract_sub_graph(output, [add_name]) self.assertProtoEquals(expected_output, stripped_output) def test_batch_norm(self): input_constant_name",
"no_op_name]) expected_output.node.extend([a_identity_node]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=1, dtype=dtypes.float32, shape=[]) expected_output.node.extend([b_constant])",
"1. arr = np.array([1]) qarr = quantize_graph.quantize_array(arr, 1) self.assertEqual(arr, qarr)",
"g = graph_pb2.GraphDef() g.node.extend([concat_dim, a, b, concat]) test_graph(g, {}, [concat.name])",
"quantize_graph.set_attr_bool(n, \"transpose_a\", False) quantize_graph.set_attr_bool(n, \"transpose_b\", False) return n # matmul_1",
"mean_abs_difference = total_abs_difference / value_count proportion_different = (how_many_different * 1.0)",
"not working currently. return quantized_input_map = {} for k, v",
"\"reshape\", [matmul_1_node.name, new_shape_node.name]) quantize_graph.set_attr_dtype(reshape_node, \"T\", dtypes.float32) # matmul_2_node = reshape*weight_2",
"+ str(len(flat_b))) return False value_count = len(flat_a) how_many_different = 0",
"= quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None) graph_def = rewriter.rewrite(output_names) results =",
"filter_count]) float_graph_def.node.extend([filter_constant]) conv_node = quantize_graph.create_node( \"Conv2D\", conv_name, [input_constant_name, filter_constant_name]) quantize_graph.set_attr_dtype(conv_node,",
"dtypes.float32) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend([input_n, offset_n, bias_add_n]) input_map = {",
"test_mat_mul_tiny(self): # These tests are added to test the generate",
"value_count proportion_different = (how_many_different * 1.0) / value_count if how_many_different",
"# RequantizationRange op. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None, fallback_quantization_range=[-.5,",
"shape=[2]) reshape_node = quantize_graph.create_node( \"Reshape\", \"reshape\", [matmul_1_node.name, new_shape_node.name]) quantize_graph.set_attr_dtype(reshape_node, \"T\",",
"\"input_constant\" relu_name = \"relu\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node(",
"10, 11, 12, 13, 14, 15, 16, 17, 18]) def",
"quantize_graph.set_attr_string(max_pool_node, \"padding\", b\"SAME\") float_graph_def.node.extend([max_pool_node]) test_graph(float_graph_def, {}, [max_pool_name]) def test_avg_pool(self): input_constant_name",
"{}, [avg_pool_name]) def test_relu(self): input_constant_name = \"input_constant\" relu_name = \"relu\"",
"= flags.FLAGS def run_graph_def(graph_def, input_map, outputs): graph = ops_lib.Graph() with",
"eightbit_graph_def = eightbit_rewriter.rewrite(output_names) eightbit_results = run_graph_def( eightbit_graph_def, input_map, [output_name +",
"\":0\", split_name + \":1\"]) quantize_graph.set_attr_int(concat_node, \"N\", 2) quantize_graph.set_attr_dtype(concat_node, \"T\", dtypes.float32)",
"len(flat_a) how_many_different = 0 total_difference = 0 total_abs_difference = 0",
"no_op_name, []) expected_output.node.extend([no_op]) a_constant = quantize_graph.create_constant_node( a_constant_name, value=1, dtype=dtypes.float32, shape=[])",
"= graph_pb2.GraphDef() a_constant = quantize_graph.create_constant_node( a_constant_name, value=(0,), dtype=dtypes.quint8, shape=[]) expected_output.node.extend([a_constant])",
"for k, v in input_map.items(): arr = [ int( round((n",
"= quantize_graph.create_node( \"Concat\", concat_name, [shape_constant_name, a_constant_name, b_constant_name]) quantize_graph.set_attr_int(concat_node, \"N\", 2)",
"dtypes.float32) expected_output.node.extend([add_node]) expected_output.versions.CopyFrom(graph_def.versions) expected_output.library.CopyFrom(graph_def.library) output = graph_util.remove_training_nodes(graph_def) stripped_output = graph_util.extract_sub_graph(output,",
"import test from tensorflow.python.platform import tf_logging from tensorflow.tools.quantization import quantize_graph",
"np.reshape([1, 2, 3, 4, 5, 6], shapes[0]), inputs[1].name + \":0\":",
"uses the default bit_depth. weights_rounded_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"weights_rounded\", quantized_input_range=None)",
"graph_def = graph_pb2.GraphDef() a_constant = quantize_graph.create_constant_node( a_constant_name, value=(0,), dtype=dtypes.quint8, shape=[])",
"outputs): graph = ops_lib.Graph() with graph.as_default(): importer.import_graph_def(graph_def, input_map={}, name=\"\") with",
"1]) with self.assertRaises(ValueError): # Invalid range. quantize_graph.GraphRewriter(graph_pb2.GraphDef(), \"eightbit\", [0, -1])",
"np.array([1]) qarr = quantize_graph.quantize_array(arr, 1) self.assertEqual(arr, qarr) qarr = quantize_graph.quantize_array(arr,",
"[node.op for node in graph_def.node] self.assertEqual(0, ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) self.assertEqual(len(output_names),",
"\"mat_mul\" graph_def = graph_pb2.GraphDef() a_constant = quantize_graph.create_constant_node( a_constant_name, value=(0,), dtype=dtypes.quint8,",
"shape_constant_name, value=0, dtype=dtypes.int32, shape=[]) float_graph_def.node.extend([shape_constant]) a_constant = quantize_graph.create_constant_node( a_constant_name, value=[1,",
"\"padding\", b\"SAME\") float_graph_def.node.extend([avg_pool_node]) test_graph(float_graph_def, {}, [avg_pool_name]) def test_relu(self): input_constant_name =",
"the rewriter and tests the results.\"\"\" float_results = run_graph_def( float_graph_def,",
".3, .2, .1], shapes[1]) } self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [mat_mul_node.name], [-1, 20.])",
"input_shape) offset_n = quantize_graph.create_constant_node( \"offset\", value=[1, 2, 3, 4, 5,",
"# Quantize treating the input as quantized in range <input_range>.",
"= quantize_graph.create_constant_node( shape_constant_name, value=-0.8, dtype=dtypes.float32, shape=[1]) quantization_result = quantize_graph.quantize_weight_eightbit( shape_constant,",
"# No RequantizationRange self.assertEqual(0, ops.count(\"RequantizationRange\")) # The fallback constants are",
"fake_quant_node]) test_graph(float_graph_def, {}, [fake_quant_node.name], log_graph=True) # Verify there is only",
"concat_name = \"concat\" float_graph_def = graph_pb2.GraphDef() shape_constant = quantize_graph.create_constant_node( shape_constant_name,",
"there is only one Quantize and one Requantize op. eightbit_rewriter",
"two tensors are nearly identical. This is a specialized comparison",
"tf_logging.info(\"Tensors are different sizes: \" + str(len(flat_a)) + \" vs",
"self.assertEqual(len(output_names), ops.count(\"Dequantize\")) # Quantize without treating input as quantized. rewriter",
"input_constant_name, value=input_values, dtype=dtypes.float32, shape=[image_batch_count, image_height, image_width, depth]) float_graph_def.node.extend([input_constant]) filter_constant =",
"offset_constant = quantize_graph.create_constant_node( offset_constant_name, value=[1, 2, 3, 4, 5, 6],",
"= \"input_constant\" max_pool_name = \"max_pool\" float_graph_def = graph_pb2.GraphDef() input_constant =",
"quantized_input_map[k] = arr output_tensors = [output_name + \":0\" for output_name",
"with session.Session(graph=graph) as sess: results = sess.run(outputs, feed_dict=input_map) return results",
"quantize_graph.set_attr_int_list(max_pool_node, \"ksize\", [1, 2, 2, 1]) quantize_graph.set_attr_int_list(max_pool_node, \"strides\", [1, 1,",
"round_results = run_graph_def(round_graph_def, input_map, # [output_name + \":0\"]) # assert",
"arr = np.array(arr, np.uint8) arr = arr.reshape(v.shape) arr = arr.astype(dtypes.quint8.as_numpy_dtype)",
"a_constant_min_name = \"a_constant_min\" a_constant_max_name = \"a_constant_max\" a_dequantize_name = \"a_dequantize\" a_quantize_name",
"None or value > max: max_value = value max_index =",
"eightbit_rewriter.rewrite([concat_name]) ops = [node.op for node in eightbit_graph_def.node] self.assertEqual(1, ops.count(\"QuantizedConcat\"))",
"dtype=dtypes.quint8, shape=[]) graph_def.node.extend([b_constant]) b_constant_min = quantize_graph.create_constant_node( b_constant_min_name, value=3, dtype=dtypes.float32, shape=[])",
"\"BiasAdd\", bias_add_name, [input_constant_name, offset_constant_name]) quantize_graph.set_attr_dtype(bias_add_node, \"T\", dtypes.float32) float_graph_def.node.extend([bias_add_node]) test_graph(float_graph_def, {},",
"0.25], [0.75, 0.75]]) == qarr).all()) def test_non_float_concat(self): concat_dim = quantize_graph.create_constant_node(",
"7, 8, 9]) def test_mat_mul_tiny(self): # These tests are added",
"input arrays. arr = np.array([0, 0.3, 0.6, 1]) qarr =",
"quantize_graph.create_constant_node( a_constant_name, value=[1, 2, 3, 4, 5, 6, 7, 8,",
"gamma_constant = quantize_graph.create_constant_node( gamma_constant_name, value=[0, 0], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([gamma_constant]) batch_norm_node",
"parameters (empty array, or 0 buckets. self.assertRaises(ValueError, quantize_graph.quantize_array, np.array([]), 2)",
"= quantize_graph.create_node(\"CheckNumerics\", b_check_name, [b_constant_name]) graph_def.node.extend([b_check_node]) b_identity_node = quantize_graph.create_node( \"Identity\", b_identity_name,",
"Add test for \"quantize\" mode. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\",",
"mode. This uses the default bit_depth. weights_rounded_rewriter = quantize_graph.GraphRewriter( float_graph_def,",
"quantize_graph.create_constant_node( \"shape\", value=[12], dtype=dtypes.int32, shape=[1]) reshape = quantize_graph.create_node(\"Reshape\", \"reshape\", [a.name,",
"for numpy is not working currently. return quantized_input_map = {}",
"are added to test the generate case where # min(matrix)",
"+ \":1\", b_quantize_name + \":2\" ]) quantize_graph.set_attr_dtype(mat_mul_node, \"T1\", dtypes.uint8) quantize_graph.set_attr_dtype(mat_mul_node,",
"\"mul\" mul_node = quantize_graph.create_node(\"Mul\", mul_name, [identity_name, identity_name]) quantize_graph.set_attr_dtype(mul_node, \"T\", dtypes.float32)",
"\"T2\", dtypes.int32) graph_def.node.extend([mat_mul_node]) expected_output = graph_pb2.GraphDef() a_constant = quantize_graph.create_constant_node( a_constant_name,",
"shape=[5]) bias_add_node = quantize_graph.create_node( \"BiasAdd\", \"bias_add\", [input_node.name, offset_node.name]) quantize_graph.set_attr_dtype(bias_add_node, \"T\",",
"are not in the graph. self.assertEqual(0, node_names.count(\"fallback_quantization_min_value\")) self.assertEqual(0, node_names.count(\"fallback_quantization_max_value\")) def",
"not in the graph. self.assertEqual(0, node_names.count(\"fallback_quantization_min_value\")) self.assertEqual(0, node_names.count(\"fallback_quantization_max_value\")) def test_bias_add_w_fallback_min_max_vars(self):",
"quantized up-front. self.assertEqual(0, ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) self.assertEqual(1, ops.count(\"QuantizedReshape\")) # One",
"1.0) if log_graph: tf_logging.info(\"8bit:\\n%s\", str(eightbit_graph_def)) # Test the weights_rounded mode.",
"generate case where # min(matrix) == max(matrix), which used to",
"[input_node.name]) quantize_graph.set_attr_dtype(relu_node, \"T\", dtypes.float32) min_node = quantize_graph.create_constant_node( \"min_bias_add\", value=0, dtype=dtypes.float32,",
"0], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([gamma_constant]) batch_norm_node = quantize_graph.create_node( \"BatchNormWithGlobalNormalization\", batch_norm_name, [",
"in writing, software # distributed under the License is distributed",
"18, 19, 20, 21, 22, 23, 24], dtype=dtypes.float32, shape=[2, 2,",
"[1, 4, 7, 2, 5, 8, 3, 6, 9]) def",
"import importer from tensorflow.python.framework import ops as ops_lib from tensorflow.python.platform",
"= sess.run(outputs, feed_dict=input_map) return results def test_mat_mul(m, n, k, a,",
"\"concat_constant\" concat_name = \"concat\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node(",
"float_graph_def, \"eightbit\", quantized_input_range=None, fallback_quantization_range=[-100, 100]) eightbit_graph_def = eightbit_rewriter.rewrite([fake_quant_node.name]) ops =",
"3, 4, 5, 6, 7, 8, 9, 10, 11, 12],",
"shape=[]) graph_def.node.extend([a_constant]) a_check_node = quantize_graph.create_node(\"CheckNumerics\", a_check_name, [a_constant_name]) graph_def.node.extend([a_check_node]) a_identity_node =",
"= \"a_identity\" b_identity_name = \"b_identity\" add_name = \"add\" graph_def =",
"dtype=dtypes.float32, shape=[]) expected_output.node.extend([b_constant]) add_node = quantize_graph.create_node(\"Add\", add_name, [a_identity_name, b_constant_name]) quantize_graph.set_attr_dtype(add_node,",
"(how_many_different * 1.0) / value_count if how_many_different == 0: return",
"quantize_graph.create_node( \"Concat\", concat_name, [shape_constant_name, a_constant_name, b_constant_name]) quantize_graph.set_attr_int(concat_node, \"N\", 2) quantize_graph.set_attr_dtype(concat_node,",
"end. self.assertEqual(1, ops.count(\"Dequantize\")) # No RequantizationRange self.assertEqual(0, ops.count(\"RequantizationRange\")) # The",
"\":1\", a_quantize_name + \":2\", b_quantize_name + \":1\", b_quantize_name + \":2\"",
"a_constant = quantize_graph.create_constant_node( a_constant_name, value=1, dtype=dtypes.float32, shape=[]) expected_output.node.extend([a_constant]) a_identity_node =",
"\"T\", dtypes.uint8) graph_def.node.extend([a_quantize_node]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=(0,), dtype=dtypes.quint8, shape=[])",
"= quantize_graph.create_node( \"FakeQuantWithMinMaxVars\", \"fake_quant\", [relu_node.name, min_node.name, max_node.name]) float_graph_def = graph_pb2.GraphDef()",
"= rewriter.rewrite(output_names) results = run_graph_def(graph_def, input_map, output_tensors) for expected, result",
"= quantize_graph.create_constant_node( a_constant_max_name, value=2, dtype=dtypes.float32, shape=[]) expected_output.node.extend([a_constant_max]) b_constant = quantize_graph.create_constant_node(",
"quantize_graph.create_node(\"Add\", add_name, [a_identity_name, b_identity_name]) quantize_graph.set_attr_dtype(add_node, \"T\", dtypes.float32) graph_def.node.extend([add_node]) expected_output =",
"def test_odd_padding_problem(self): \"\"\"Tests one error case we ran into in",
"22, 23, 24], dtype=dtypes.int32, shape=[2, 2, 3]) concat = quantize_graph.create_node(\"Concat\",",
"= graph_pb2.GraphDef() no_op = quantize_graph.create_node(\"NoOp\", no_op_name, []) graph_def.node.extend([no_op]) a_constant =",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"License, Version 2.0 (the \"License\"); # you may not use",
"\"eightbit\", quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite([\"matmul_2\"]) ops = [node.op for node",
"= \"input_constant\" identity_name = \"identity\" float_graph_def = graph_pb2.GraphDef() input_constant =",
"= len(flat_a) how_many_different = 0 total_difference = 0 total_abs_difference =",
"test from tensorflow.python.platform import tf_logging from tensorflow.tools.quantization import quantize_graph flags",
"= \"relu\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=[1,",
"quantize_graph.create_node( \"BiasAdd\", bias_add_name, [input_constant_name, offset_constant_name]) quantize_graph.set_attr_dtype(bias_add_node, \"T\", dtypes.float32) float_graph_def.node.extend([bias_add_node]) test_graph(float_graph_def,",
"1, 1]) quantize_graph.set_attr_string(avg_pool_node, \"padding\", b\"SAME\") float_graph_def.node.extend([avg_pool_node]) test_graph(float_graph_def, {}, [avg_pool_name]) def",
"\"QuantizeV2\", a_quantize_name, [a_dequantize_name, a_dequantize_name + \":1\", a_dequantize_name + \":2\"]) quantize_graph.set_attr_dtype(a_quantize_node,",
"quantize_graph.set_attr_int_list(avg_pool_node, \"ksize\", [1, 2, 2, 1]) quantize_graph.set_attr_int_list(avg_pool_node, \"strides\", [1, 1,",
"expected_output.node.extend([add_node]) expected_output.versions.CopyFrom(graph_def.versions) expected_output.library.CopyFrom(graph_def.library) output = graph_util.remove_training_nodes(graph_def) stripped_output = graph_util.extract_sub_graph(output, [add_name])",
"One dequantize at the end. self.assertEqual(1, ops.count(\"Dequantize\")) def test_relu6(self): input_constant_name",
"= [ int( round((n - input_range[0]) * 255 / (input_range[1]",
"2, 5]) offset_node = quantize_graph.create_constant_node( \"offset\", value=[1, 2, 3, 4,",
"quantize_graph.quantize_weight_eightbit( shape_constant, b\"MIN_COMBINED\") self.assertEqual(4, len(quantization_result)) def test_odd_padding_problem(self): \"\"\"Tests one error",
"length 1. arr = np.array([1]) qarr = quantize_graph.quantize_array(arr, 1) self.assertEqual(arr,",
"\"T\", dtypes.float32) quantize_graph.set_attr_int_list(avg_pool_node, \"ksize\", [1, 2, 2, 1]) quantize_graph.set_attr_int_list(avg_pool_node, \"strides\",",
"def test_quantized_input_range_mat_mul(self): shapes = [[3, 2], [2, 4]] inputs =",
"3, 1, 1, b\"SAME\", [1, 2, 3, 4, 5, 6,",
"dequantize at the end. self.assertEqual(1, ops.count(\"Dequantize\")) def test_quantize_array(self): # Test",
"[node.op for node in eightbit_graph_def.node] self.assertEqual(1, ops.count(\"QuantizedConcat\")) def test_multiple_outputs(self): input_constant_name",
"return False value_count = len(flat_a) how_many_different = 0 total_difference =",
"quantize_graph.set_attr_int_list(avg_pool_node, \"strides\", [1, 1, 1, 1]) quantize_graph.set_attr_string(avg_pool_node, \"padding\", b\"SAME\") float_graph_def.node.extend([avg_pool_node])",
"the License for the specific language governing permissions and #",
"= quantize_graph.create_constant_node( offset_constant_name, value=[1, 2, 3, 4, 5, 6], dtype=dtypes.float32,",
"= graph_pb2.GraphDef() a_constant = quantize_graph.create_constant_node( a_constant_name, value=(0,), dtype=dtypes.quint8, shape=[]) graph_def.node.extend([a_constant])",
"quantize_graph.create_constant_node( a_constant_name, value=a, dtype=dtypes.float32, shape=[m, k]) float_graph_def.node.extend([a_constant]) b_constant = quantize_graph.create_constant_node(",
"= quantize_graph.create_constant_node( \"concat_dim\", value=0, dtype=dtypes.int32, shape=[]) a = quantize_graph.create_constant_node( \"a\",",
"= quantize_graph.create_node(\"Concat\", \"concat\", [concat_dim.name, a.name, b.name]) quantize_graph.set_attr_int(concat, \"N\", 2) quantize_graph.set_attr_dtype(concat,",
"b_constant_name = \"b_constant\" concat_name = \"concat\" float_graph_def = graph_pb2.GraphDef() shape_constant",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"6, 1]) float_graph_def.node.extend([input_constant]) relu6_node = quantize_graph.create_node(\"Relu6\", relu6_name, [input_constant_name]) quantize_graph.set_attr_dtype(relu6_node, \"T\",",
"12, 13, 14, 15, 16, 17, 18]) def test_conv(self): test_conv(1,",
"as flags_lib from tensorflow.python.platform import test from tensorflow.python.platform import tf_logging",
"12], dtype=dtypes.float32, shape=[2, 2, 3]) float_graph_def.node.extend([a_constant]) b_constant = quantize_graph.create_constant_node( b_constant_name,",
"from tensorflow.python.platform import flags as flags_lib from tensorflow.python.platform import test",
"fake_quant_node ]) test_graph(float_graph_def, {}, [fake_quant_node.name], log_graph=True) # Verify there is",
"self.assertEqual(1, ops.count(\"QuantizedConcat\")) def test_multiple_outputs(self): input_constant_name = \"input_constant\" split_constant_name = \"split_constant\"",
"shape=[1, 2, 6, 1]) float_graph_def.node.extend([input_constant]) max_pool_node = quantize_graph.create_node(\"MaxPool\", max_pool_name, [input_constant_name])",
"b_value total_difference += difference total_abs_difference += abs(difference) if abs(difference) >",
"in enumerate(shapes): node = quantize_graph.create_node(\"Placeholder\", \"input_%s\" % i, []) quantize_graph.set_attr_dtype(node,",
"help debug problems with quantization. It prints out information about",
"\"eightbit\", quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite([concat_name]) ops = [node.op for node",
"eightbit_results = run_graph_def( eightbit_graph_def, input_map, [output_name + \":0\" for output_name",
"value_count if how_many_different == 0: return True else: tf_logging.info(\"Tensors have",
"fallback constants are not in the graph. self.assertEqual(0, node_names.count(\"fallback_quantization_min_value\")) self.assertEqual(0,",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"quantize_graph.create_node( \"QuantizeV2\", a_quantize_name, [a_dequantize_name, a_dequantize_name + \":1\", a_dequantize_name + \":2\"])",
"run_graph_def(float_graph_def, input_map, output_tensors) # Quantize treating the input as quantized",
"= quantize_graph.create_node( \"QuantizeV2\", b_quantize_name, [b_dequantize_name, b_dequantize_name + \":1\", b_dequantize_name +",
"tensorflow.core.framework import graph_pb2 from tensorflow.python.client import session from tensorflow.python.framework import",
"\"T\", dtypes.float32) quantize_graph.set_attr_bool(batch_norm_node, \"scale_after_normalization\", False) quantize_graph.set_attr_float(batch_norm_node, \"variance_epsilon\", 0.001) float_graph_def.node.extend([batch_norm_node]) test_graph(float_graph_def,",
"quantized up-front. self.assertEqual(0, ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) # One dequantize at",
"bias_add_name, [input_constant_name, offset_constant_name]) quantize_graph.set_attr_dtype(bias_add_node, \"T\", dtypes.float32) float_graph_def.node.extend([bias_add_node]) test_graph(float_graph_def, {}, [bias_add_name])",
"qarr = quantize_graph.quantize_array(arr, 1) self.assertTrue((np.array([0.5, 0.5, 0.5, 0.5]) == qarr).all())",
"indicating how large an error between values is ok. Returns:",
"is currently failing because there is no # RoundToSteps op",
"a_constant = quantize_graph.create_constant_node( a_constant_name, value=1, dtype=dtypes.float32, shape=[]) graph_def.node.extend([a_constant]) a_check_node =",
"graph_def.node.extend([a_constant_max]) a_dequantize_node = quantize_graph.create_node( \"Dequantize\", a_dequantize_name, [a_constant_name, a_constant_min_name, a_constant_max_name]) quantize_graph.set_attr_dtype(a_dequantize_node,",
"= \"input_constant\" offset_constant_name = \"offset_constant\" bias_add_name = \"bias_add\" float_graph_def =",
"at the end. self.assertEqual(1, ops.count(\"Dequantize\")) def test_relu6(self): input_constant_name = \"input_constant\"",
"__future__ import division from __future__ import print_function import sys import",
"[mat_mul_name]) def test_conv(depth, image_width, image_height, image_batch_count, filter_size, filter_count, stride, padding,",
"self.assertEqual(\"SomeName\", quantize_graph.node_name_from_input(\"^SomeName:2\")) def test_unique_node_name_from_input(self): self.assertEqual(\"__hat__SomeName__port__2\", quantize_graph.unique_node_name_from_input(\"^SomeName:2\")) def test_identity(self): input_constant_name =",
"a_constant_name = \"a_constant\" a_constant_min_name = \"a_constant_min\" a_constant_max_name = \"a_constant_max\" a_dequantize_name",
"+= abs(difference) if abs(difference) > tolerance: how_many_different += 1 mean_difference",
"RequantizationRange self.assertEqual(0, ops.count(\"RequantizationRange\")) # The fallback constants are in the",
"a, b, concat]) test_graph(g, {}, [concat.name]) def test_non_float_reshape(self): a =",
"2, 3]) b = quantize_graph.create_constant_node( \"b\", value=[13, 14, 15, 16,",
"vs \" + str(len(flat_b))) return False value_count = len(flat_a) how_many_different",
"tests are added to test the generate case where #",
"shape=[2, 6]) float_graph_def.node.extend([input_constant]) identity_node = quantize_graph.create_node(\"Identity\", identity_name, [input_constant_name]) quantize_graph.set_attr_dtype(identity_node, \"T\",",
"self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [bias_add_n.name], [0, 12.]) def test_quantized_input_range_mat_mul(self): shapes = [[3,",
"information about the differences between tensors on failure, paying special",
"real graph.\"\"\" test_conv(1, 4, 4, 1, 3, 1, 2, b\"SAME\",",
"quantize_graph.quantize_array(arr, 1) self.assertEqual(arr, qarr) qarr = quantize_graph.quantize_array(arr, 2) self.assertEqual(arr, qarr)",
"graph_def.node] self.assertEqual( len(input_map), ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) self.assertEqual(len(output_names), ops.count(\"Dequantize\")) def test_bias_add_w_fake_quant_w_min_max_vars(self):",
"designed to help debug problems with quantization. It prints out",
"= \"a_constant\" b_constant_name = \"b_constant\" concat_name = \"concat\" float_graph_def =",
"# distributed under the License is distributed on an \"AS",
"# Unless required by applicable law or agreed to in",
"quantize_graph.create_node( \"Concat\", concat_name, [concat_constant_name, split_name + \":0\", split_name + \":1\"])",
"ops = [node.op for node in graph_def.node] self.assertEqual( len(input_map), ops.count(\"QuantizeV2\")",
"= quantize_graph.GraphRewriter(float_graph_def, \"eightbit\", input_range) graph_def = rewriter.rewrite(output_names) results = run_graph_def(graph_def,",
"= \"split_constant\" split_name = \"split\" concat_constant_name = \"concat_constant\" concat_name =",
"float_results = run_graph_def( float_graph_def, input_map, [output_name + \":0\" for output_name",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"Test the weights_rounded mode. This uses the default bit_depth. weights_rounded_rewriter",
"4, 5, 6, 7, 8, 9, 10, 11, 12], input_shape)",
"quantize_graph.create_constant_node( input_constant_name, value=input_values, dtype=dtypes.float32, shape=[image_batch_count, image_height, image_width, depth]) float_graph_def.node.extend([input_constant]) filter_constant",
"\"\"\"Tests the graph quantization script. \"\"\" from __future__ import absolute_import",
"= quantize_graph.create_node( \"BiasAdd\", bias_add_name, [input_constant_name, offset_constant_name]) quantize_graph.set_attr_dtype(bias_add_node, \"T\", dtypes.float32) float_graph_def.node.extend([bias_add_node])",
"= graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=input_values, dtype=dtypes.float32, shape=[image_batch_count, image_height,",
"[]) quantize_graph.set_attr_dtype(input_n, \"dtype\", dtypes.float32) quantize_graph.set_attr_shape(input_n, \"shape\", input_shape) offset_n = quantize_graph.create_constant_node(",
".5, .4, .3, .2, .1], shapes[1]) } self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [mat_mul_node.name],",
"output_tensors) for expected, result in zip(float_results, results): assert are_tensors_near(expected, result,",
"quantized_input_range=None) output = rewriter.remove_redundant_quantization(graph_def) stripped_output = graph_util.extract_sub_graph(output, [mat_mul_name]) self.assertProtoEquals(expected_output, stripped_output)",
"17, 18, 19, 20, 21, 22, 23, 24], dtype=dtypes.int32, shape=[2,",
"mean_constant = quantize_graph.create_constant_node( mean_constant_name, value=[10, 20], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([mean_constant]) variance_constant",
"\"a_constant\" b_constant_name = \"b_constant\" concat_name = \"concat\" float_graph_def = graph_pb2.GraphDef()",
"test_conv(1, 4, 4, 1, 3, 1, 2, b\"SAME\", [1, 2,",
"6]) float_graph_def.node.extend([input_constant]) split_constant = quantize_graph.create_constant_node( split_constant_name, value=1, dtype=dtypes.int32, shape=[]) float_graph_def.node.extend([split_constant])",
"# Copyright 2015 The TensorFlow Authors. All Rights Reserved. #",
"({1}%), with mean\" \" difference {2} and mean absolute difference",
"a_constant_min = quantize_graph.create_constant_node( a_constant_min_name, value=2, dtype=dtypes.float32, shape=[]) graph_def.node.extend([a_constant_min]) a_constant_max =",
"[fake_quant_node.name], log_graph=True) # Verify there is only one Quantize and",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"\":0\"]) # assert are_tensors_near(expected, round_results[0], 1.0) # # TODO(petewarden): Add",
"op. eightbit_rewriter = quantize_graph.GraphRewriter( g, \"eightbit\", quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite([\"matmul_2\"])",
"ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) self.assertEqual(1, ops.count(\"QuantizedReshape\")) # One dequantize at the",
"to cause problems. test_mat_mul(1, 1, 1, [2], [3]) test_mat_mul(1, 2,",
"tests the results.\"\"\" float_results = run_graph_def( float_graph_def, input_map, [output_name +",
"weights_rounded_results = run_graph_def( weights_rounded_graph_def, input_map, [output_name + \":0\" for output_name",
"concat = quantize_graph.create_node(\"Concat\", \"concat\", [concat_dim.name, a.name, b.name]) quantize_graph.set_attr_int(concat, \"N\", 2)",
"in range(value_count): a_value = flat_a[index] b_value = flat_b[index] difference =",
"quantize_graph.GraphRewriter( g, \"eightbit\", quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite([\"matmul_2\"]) ops = [node.op",
"the end. self.assertEqual(1, ops.count(\"Dequantize\")) # No RequantizationRange self.assertEqual(0, ops.count(\"RequantizationRange\")) #",
"4, 1, 3, 1, 2, b\"SAME\", [1, 2, 3, 4,",
"be quantized up-front. self.assertEqual(0, ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) self.assertEqual(1, ops.count(\"QuantizedReshape\")) #",
"= quantize_graph.create_constant_node( a_constant_name, value=(0,), dtype=dtypes.quint8, shape=[]) expected_output.node.extend([a_constant]) a_constant_min = quantize_graph.create_constant_node(",
"def test_non_float_reshape(self): a = quantize_graph.create_constant_node( \"a\", value=[1, 2, 3, 4,",
"11, 12], dtype=dtypes.int32, shape=[2, 2, 3]) shape = quantize_graph.create_constant_node( \"shape\",",
"float_graph_def.node.extend([input_constant]) mean_constant = quantize_graph.create_constant_node( mean_constant_name, value=[10, 20], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([mean_constant])",
"quantize_graph.create_constant_node( b_constant_name, value=1, dtype=dtypes.float32, shape=[]) graph_def.node.extend([b_constant]) b_check_node = quantize_graph.create_node(\"CheckNumerics\", b_check_name,",
"\"offset\", value=[1, 2, 3, 4, 5, 6], dtype=dtypes.float32, shape=[6]) bias_add_n",
"\"T\", dtypes.float32) float_graph_def.node.extend([split_node]) concat_constant = quantize_graph.create_constant_node( concat_constant_name, value=1, dtype=dtypes.int32, shape=[])",
"= graph_pb2.GraphDef() g.node.extend([ input_node, weight_1_node, matmul_1_node, new_shape_node, reshape_node, weight_2_node, matmul_2_node",
"11, 12, 13, 14, 15, 16, 17, 18]) def test_conv(self):",
"filter_constant_name = \"filter_constant\" conv_name = \"conv\" float_graph_def = graph_pb2.GraphDef() input_constant",
"quantize_graph.set_attr_dtype(mul_node, \"T\", dtypes.float32) float_graph_def.node.extend([mul_node]) test_graph(float_graph_def, {}, [mul_name]) def test_keep_control_edges(self): no_op_name",
"= quantize_graph.quantize_weight_eightbit( shape_constant, b\"MIN_COMBINED\") self.assertEqual(4, len(quantization_result)) def test_odd_padding_problem(self): \"\"\"Tests one",
"1, 2, [0, 0], [1, 1]) # The general case.",
"min_node.name, max_node.name]) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend( [input_node, relu_node, min_node, max_node,",
"RoundToSteps op available. # round_rewriter = quantize_graph.GraphRewriter(float_graph_def, \"round\") # round_graph_def",
"test_mat_mul(1, 1, 2, [1, 2], [1, 2]) def test_mat_mul_small(self): test_mat_mul(2,",
"close enough. \"\"\" flat_a = a.flatten() flat_b = b.flatten() if",
"offset_constant_name]) quantize_graph.set_attr_dtype(bias_add_node, \"T\", dtypes.float32) float_graph_def.node.extend([bias_add_node]) test_graph(float_graph_def, {}, [bias_add_name]) def test_quantized_input_range_errors(self):",
"dtypes.uint8) graph_def.node.extend([a_quantize_node]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=(0,), dtype=dtypes.quint8, shape=[]) graph_def.node.extend([b_constant])",
"= quantize_graph.create_node( \"Identity\", a_identity_name, [a_constant_name, \"^\" + no_op_name]) expected_output.node.extend([a_identity_node]) b_constant",
"qarr = quantize_graph.quantize_array(arr, 1) self.assertEqual(arr, qarr) qarr = quantize_graph.quantize_array(arr, 2)",
"quantize_graph.create_node( \"Conv2D\", conv_name, [input_constant_name, filter_constant_name]) quantize_graph.set_attr_dtype(conv_node, \"T\", dtypes.float32) quantize_graph.set_attr_int_list(conv_node, \"strides\",",
"Reshape 4x5 to 10x2. new_shape_node = quantize_graph.create_constant_node( \"new_shape_node\", value=[10, 2],",
"1, 1]) == qarr).all()) # Test \"normal\" input arrays. arr",
"5, 6], dtype=dtypes.float32, shape=[6]) float_graph_def.node.extend([offset_constant]) bias_add_node = quantize_graph.create_node( \"BiasAdd\", bias_add_name,",
"shape=[]) graph_def.node.extend([b_constant]) b_constant_min = quantize_graph.create_constant_node( b_constant_min_name, value=3, dtype=dtypes.float32, shape=[]) graph_def.node.extend([b_constant_min])",
"[1, 2, 3, 4, 5, 6, 7, 8, 9, 10,",
"= quantize_graph.create_node(\"Mul\", mul_name, [identity_name, identity_name]) quantize_graph.set_attr_dtype(mul_node, \"T\", dtypes.float32) float_graph_def.node.extend([mul_node]) test_graph(float_graph_def,",
"[identity_name, identity_name]) quantize_graph.set_attr_dtype(mul_node, \"T\", dtypes.float32) float_graph_def.node.extend([mul_node]) test_graph(float_graph_def, {}, [mul_name]) def",
"if len(flat_a) != len(flat_b): tf_logging.info(\"Tensors are different sizes: \" +",
"self.assertEqual(0, node_names.count(\"fallback_quantization_max_value\")) def test_bias_add_w_fallback_min_max_vars(self): input_node = quantize_graph.create_constant_node( \"input\", value=[1, 2,",
"This is a specialized comparison function designed to help debug",
"quantize_graph.set_attr_dtype(b_quantize_node, \"T\", dtypes.uint8) graph_def.node.extend([b_quantize_node]) mat_mul_node = quantize_graph.create_node(\"QuantizedMatMul\", mat_mul_name, [ a_quantize_name,",
".7, .6, .5, .4, .3, .2, .1], shapes[1]) } self._RunTestsForQuantizedInputRange(float_graph_def,",
"[node.name for node in eightbit_graph_def.node] # No quantize since all",
"graph_def = graph_pb2.GraphDef() no_op = quantize_graph.create_node(\"NoOp\", no_op_name, []) graph_def.node.extend([no_op]) a_constant",
"stripped_output = graph_util.extract_sub_graph(output, [add_name]) self.assertProtoEquals(expected_output, stripped_output) def test_batch_norm(self): input_constant_name =",
"1, 1, 1]) quantize_graph.set_attr_string(avg_pool_node, \"padding\", b\"SAME\") float_graph_def.node.extend([avg_pool_node]) test_graph(float_graph_def, {}, [avg_pool_name])",
"\"a_dequantize\" a_quantize_name = \"a_quantize\" b_constant_name = \"b_constant\" b_constant_min_name = \"b_constant_min\"",
"inputs.append(node) mat_mul_node = quantize_graph.create_node(\"MatMul\", \"mat_mul\", [n.name for n in inputs])",
"input_constant_name = \"input_constant\" split_constant_name = \"split_constant\" split_name = \"split\" concat_constant_name",
"shapes[1]) } self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [mat_mul_node.name], [-1, 20.]) self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [mat_mul_node.name],",
"k]) float_graph_def.node.extend([a_constant]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=b, dtype=dtypes.float32, shape=[k, n])",
"= reshape*weight_2 weight_2_node = quantize_graph.create_constant_node( \"weight_2\", value=[1.5, 2.5], dtype=dtypes.float32, shape=[2,",
"shape=[]) a = quantize_graph.create_constant_node( \"a\", value=[1, 2, 3, 4, 5,",
"1]) relu_node = quantize_graph.create_node(\"Relu\", \"relu\", [input_node.name]) quantize_graph.set_attr_dtype(relu_node, \"T\", dtypes.float32) min_node",
"\"T\", dtypes.float32) expected_output.node.extend([add_node]) expected_output.versions.CopyFrom(graph_def.versions) expected_output.library.CopyFrom(graph_def.library) output = graph_util.remove_training_nodes(graph_def) stripped_output =",
"quantize_graph.create_node( \"QuantizeV2\", b_quantize_name, [b_dequantize_name, b_dequantize_name + \":1\", b_dequantize_name + \":2\"])",
"== 0: return True else: tf_logging.info(\"Tensors have {0} different values",
"and no # RequantizationRange op. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\",",
"[mat_mul_node]) input_map = { inputs[0].name + \":0\": np.reshape([1, 2, 3,",
"stride, stride, 1]) quantize_graph.set_attr_string(conv_node, \"padding\", padding) float_graph_def.node.extend([conv_node]) test_graph(float_graph_def, {}, [conv_name])",
"quantization. It prints out information about the differences between tensors",
"Requantize op. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None) eightbit_graph_def =",
"expected_output.node.extend([a_constant_min]) a_constant_max = quantize_graph.create_constant_node( a_constant_max_name, value=2, dtype=dtypes.float32, shape=[]) expected_output.node.extend([a_constant_max]) b_constant",
"\":0\" for output_name in output_names]) for expected, result in zip(float_results,",
"8, 9, 10, 11, 12], dtype=dtypes.float32, shape=[2, 6]) float_graph_def.node.extend([input_constant]) identity_node",
"min_node = quantize_graph.create_constant_node( \"min_bias_add\", value=0, dtype=dtypes.float32, shape=[]) max_node = quantize_graph.create_constant_node(",
"quantize_graph.set_attr_bool(batch_norm_node, \"scale_after_normalization\", False) quantize_graph.set_attr_float(batch_norm_node, \"variance_epsilon\", 0.001) float_graph_def.node.extend([batch_norm_node]) test_graph(float_graph_def, {}, [batch_norm_name])",
"= quantize_graph.create_constant_node( \"shape\", value=[12], dtype=dtypes.int32, shape=[1]) reshape = quantize_graph.create_node(\"Reshape\", \"reshape\",",
"concat_dim = quantize_graph.create_constant_node( \"concat_dim\", value=0, dtype=dtypes.int32, shape=[]) a = quantize_graph.create_constant_node(",
"b_constant_name = \"b_constant\" b_constant_min_name = \"b_constant_min\" b_constant_max_name = \"b_constant_max\" b_dequantize_name",
"test_mat_mul(1, 1, 2, [1, 1], [1, 1]) test_mat_mul(1, 1, 2,",
"from tensorflow.python.platform import tf_logging from tensorflow.tools.quantization import quantize_graph flags =",
"concat_constant_name, value=1, dtype=dtypes.int32, shape=[]) float_graph_def.node.extend([concat_constant]) concat_node = quantize_graph.create_node( \"Concat\", concat_name,",
"concat is quantized. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None) eightbit_graph_def",
"\"normal\" input arrays. arr = np.array([0, 0.3, 0.6, 1]) qarr",
"Conv replacement.\"\"\" input_constant_name = \"input_constant\" filter_constant_name = \"filter_constant\" conv_name =",
"under the License is distributed on an \"AS IS\" BASIS,",
"= quantize_graph.create_constant_node( a_constant_min_name, value=2, dtype=dtypes.float32, shape=[]) graph_def.node.extend([a_constant_min]) a_constant_max = quantize_graph.create_constant_node(",
"1.0) / value_count if how_many_different == 0: return True else:",
"quantize_graph.set_attr_dtype(bias_add_node, \"T\", dtypes.float32) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend([input_node, offset_node, bias_add_node]) test_graph(float_graph_def,",
"dtypes.float32) quantize_graph.set_attr_bool(batch_norm_node, \"scale_after_normalization\", False) quantize_graph.set_attr_float(batch_norm_node, \"variance_epsilon\", 0.001) float_graph_def.node.extend([batch_norm_node]) test_graph(float_graph_def, {},",
"3, 4, 5, 6], dtype=dtypes.float32, shape=[6]) bias_add_n = quantize_graph.create_node(\"BiasAdd\", \"bias_add\",",
"rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None) graph_def = rewriter.rewrite(output_names) results",
"test_relu6(self): input_constant_name = \"input_constant\" relu6_name = \"relu6\" float_graph_def = graph_pb2.GraphDef()",
"\"input\", []) quantize_graph.set_attr_dtype(input_n, \"dtype\", dtypes.float32) quantize_graph.set_attr_shape(input_n, \"shape\", input_shape) offset_n =",
"rewriter = quantize_graph.GraphRewriter( graph_def, [mat_mul_name], quantized_input_range=None) output = rewriter.remove_redundant_quantization(graph_def) stripped_output",
"quantize_graph.create_node( \"Identity\", a_identity_name, [a_constant_name, \"^\" + a_check_name, \"^\" + no_op_name])",
"variance_constant_name, value=[0.25, 0.5], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([variance_constant]) beta_constant = quantize_graph.create_constant_node( beta_constant_name,",
"a_value - b_value total_difference += difference total_abs_difference += abs(difference) if",
"= \"a_constant_min\" a_constant_max_name = \"a_constant_max\" a_dequantize_name = \"a_dequantize\" a_quantize_name =",
"shape=[]) max_node = quantize_graph.create_constant_node( \"max_bias_add\", value=12, dtype=dtypes.float32, shape=[]) fake_quant_node =",
"= a_value - b_value total_difference += difference total_abs_difference += abs(difference)",
"\":1\", a_dequantize_name + \":2\"]) quantize_graph.set_attr_dtype(a_quantize_node, \"T\", dtypes.uint8) graph_def.node.extend([a_quantize_node]) b_constant =",
"will have no effect # because the FakeQuantWithMinMaxVars are used",
"= \"mean_constant\" variance_constant_name = \"variance_constant\" beta_constant_name = \"beta_constant\" gamma_constant_name =",
"= \"relu6\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=[1,",
"shape=[2]) float_graph_def.node.extend([gamma_constant]) batch_norm_node = quantize_graph.create_node( \"BatchNormWithGlobalNormalization\", batch_norm_name, [ input_constant_name, mean_constant_name,",
"output_name in output_names]) # TODO(petewarden): round test is currently failing",
"test_identity(self): input_constant_name = \"input_constant\" identity_name = \"identity\" float_graph_def = graph_pb2.GraphDef()",
"0 for index in range(value_count): a_value = flat_a[index] b_value =",
"bit_depth. weights_rounded_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"weights_rounded\", quantized_input_range=None) weights_rounded_graph_def = weights_rounded_rewriter.rewrite(output_names)",
"== 3: # uint8->quint8 conversion for numpy is not working",
"input_range[0]) * 255 / (input_range[1] - input_range[ 0]))) for n",
"test is currently failing because there is no # RoundToSteps",
"from __future__ import absolute_import from __future__ import division from __future__",
"a_constant_min_name, a_constant_max_name, b_constant_min_name, b_constant_max_name ]) quantize_graph.set_attr_dtype(mat_mul_node, \"T1\", dtypes.uint8) quantize_graph.set_attr_dtype(mat_mul_node, \"T2\",",
"def test_reshape(self): \"\"\"Tests that MatMul->Reshape->MatMul avoids extra quantize/dequantize.\"\"\" def make_matmul(name,",
"with quantization. It prints out information about the differences between",
"np.array(arr, np.uint8) arr = arr.reshape(v.shape) arr = arr.astype(dtypes.quint8.as_numpy_dtype) quantized_input_map[k] =",
"self.assertEqual(1, ops.count(\"Dequantize\")) # No RequantizationRange self.assertEqual(0, ops.count(\"RequantizationRange\")) # The fallback",
"12], input_shape) } self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [bias_add_n.name], [-1, 20.]) self._RunTestsForQuantizedInputRange(float_graph_def, input_map,",
"dtypes.float32) quantize_graph.set_attr_bool(n, \"transpose_a\", False) quantize_graph.set_attr_bool(n, \"transpose_b\", False) return n #",
"have {0} different values ({1}%), with mean\" \" difference {2}",
"input_map, output_tensors) for expected, result in zip(float_results, results): assert are_tensors_near(expected,",
"v in input_map.items(): arr = [ int( round((n - input_range[0])",
"]) test_graph(float_graph_def, {}, [fake_quant_node.name], log_graph=True) # Verify there is only",
"n # matmul_1 = input*weight_1 input_node = quantize_graph.create_constant_node( \"input\", value=[0,",
"FLAGS = flags.FLAGS def run_graph_def(graph_def, input_map, outputs): graph = ops_lib.Graph()",
"quantize_graph.create_node(\"BiasAdd\", \"bias_add\", [input_n.name, offset_n.name]) quantize_graph.set_attr_dtype(bias_add_n, \"T\", dtypes.float32) float_graph_def = graph_pb2.GraphDef()",
"= \"concat\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=[1,",
"import quantize_graph flags = flags_lib FLAGS = flags.FLAGS def run_graph_def(graph_def,",
"\"strides\", [1, 1, 1, 1]) quantize_graph.set_attr_string(max_pool_node, \"padding\", b\"SAME\") float_graph_def.node.extend([max_pool_node]) test_graph(float_graph_def,",
"float_graph_def, input_map, output_names, input_range): if sys.version_info[0] == 3: # uint8->quint8",
"shape=[]) expected_output.node.extend([b_constant_max]) mat_mul_node = quantize_graph.create_node(\"QuantizedMatMul\", mat_mul_name, [ a_constant_name, b_constant_name, a_constant_min_name,",
"for \"quantize\" mode. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None) eightbit_graph_def",
"float_graph_def, \"eightbit\", quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite([concat_name]) ops = [node.op for",
"graph_util from tensorflow.python.framework import importer from tensorflow.python.framework import ops as",
"= weights_rounded_rewriter.rewrite(output_names) weights_rounded_results = run_graph_def( weights_rounded_graph_def, input_map, [output_name + \":0\"",
"13, 14, 15, 16, 17, 18]) def test_conv(self): test_conv(1, 4,",
"weights_rounded_graph_def = weights_rounded_rewriter.rewrite(output_names) weights_rounded_results = run_graph_def( weights_rounded_graph_def, input_map, [output_name +",
"= a.flatten() flat_b = b.flatten() if len(flat_a) != len(flat_b): tf_logging.info(\"Tensors",
"is None or value > max: max_value = value max_index",
"TODO(petewarden): Add test for \"quantize\" mode. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def,",
"= quantize_graph.create_constant_node( concat_constant_name, value=1, dtype=dtypes.int32, shape=[]) float_graph_def.node.extend([concat_constant]) concat_node = quantize_graph.create_node(",
"15, 16, 17, 18]) def test_conv(self): test_conv(1, 4, 3, 1,",
"for output_name in output_names] float_results = run_graph_def(float_graph_def, input_map, output_tensors) #",
"+ \":0\", split_name + \":1\"]) quantize_graph.set_attr_int(concat_node, \"N\", 2) quantize_graph.set_attr_dtype(concat_node, \"T\",",
"split_constant_name, value=1, dtype=dtypes.int32, shape=[]) float_graph_def.node.extend([split_constant]) split_node = quantize_graph.create_node( \"Split\", split_name,",
"dequantize at the end. self.assertEqual(1, ops.count(\"Dequantize\")) # No RequantizationRange self.assertEqual(0,",
"new_shape_node.name]) quantize_graph.set_attr_dtype(reshape_node, \"T\", dtypes.float32) # matmul_2_node = reshape*weight_2 weight_2_node =",
"shape=[4, 1]) weight_1_node = quantize_graph.create_constant_node( \"weight_1\", value=[.5, .6, .7, .8,",
"and tests the results.\"\"\" float_results = run_graph_def( float_graph_def, input_map, [output_name",
"eightbit_graph_def.node] node_names = [node.name for node in eightbit_graph_def.node] # No",
"shape=[1]) reshape = quantize_graph.create_node(\"Reshape\", \"reshape\", [a.name, shape.name]) quantize_graph.set_attr_dtype(reshape, \"T\", dtypes.int32)",
"of length 1. arr = np.array([1]) qarr = quantize_graph.quantize_array(arr, 1)",
"input_n = quantize_graph.create_node(\"Placeholder\", \"input\", []) quantize_graph.set_attr_dtype(input_n, \"dtype\", dtypes.float32) quantize_graph.set_attr_shape(input_n, \"shape\",",
"for expected, result in zip(float_results, eightbit_results): assert are_tensors_near(expected, result, 1.0)",
"prints out information about the differences between tensors on failure,",
"ANY KIND, either express or implied. # See the License",
"split_name, [split_constant_name, input_constant_name]) quantize_graph.set_attr_int(split_node, \"num_split\", 2) quantize_graph.set_attr_dtype(split_node, \"T\", dtypes.float32) float_graph_def.node.extend([split_node])",
"\":0\": np.reshape([1, 2, 3, 4, 5, 6], shapes[0]), inputs[1].name +",
"if how_many_different == 0: return True else: tf_logging.info(\"Tensors have {0}",
"relu6_name, [input_constant_name]) quantize_graph.set_attr_dtype(relu6_node, \"T\", dtypes.float32) float_graph_def.node.extend([relu6_node]) test_graph(float_graph_def, {}, [relu6_name]) def",
"the License. # You may obtain a copy of the",
"eightbit_results): assert are_tensors_near(expected, result, 1.0) if log_graph: tf_logging.info(\"8bit:\\n%s\", str(eightbit_graph_def)) #",
"{}, [reshape.name]) def test_concat(self): shape_constant_name = \"shape_constant\" a_constant_name = \"a_constant\"",
"= quantize_graph.create_constant_node( b_constant_name, value=(0,), dtype=dtypes.quint8, shape=[]) graph_def.node.extend([b_constant]) b_constant_min = quantize_graph.create_constant_node(",
"quantize_graph.create_constant_node( a_constant_name, value=(0,), dtype=dtypes.quint8, shape=[]) graph_def.node.extend([a_constant]) a_constant_min = quantize_graph.create_constant_node( a_constant_min_name,",
"# See the License for the specific language governing permissions",
"% i, []) quantize_graph.set_attr_dtype(node, \"dtype\", dtypes.float32) quantize_graph.set_attr_shape(node, \"shape\", shape) inputs.append(node)",
"] arr = np.array(arr, np.uint8) arr = arr.reshape(v.shape) arr =",
"1, b\"SAME\", [1, 2, 3, 4, 5, 6, 7, 8,",
"8, 3, 6, 9]) def test_reshape(self): \"\"\"Tests that MatMul->Reshape->MatMul avoids",
"that MatMul->Reshape->MatMul avoids extra quantize/dequantize.\"\"\" def make_matmul(name, a, b): n",
"\"Split\", split_name, [split_constant_name, input_constant_name]) quantize_graph.set_attr_int(split_node, \"num_split\", 2) quantize_graph.set_attr_dtype(split_node, \"T\", dtypes.float32)",
"2, [0, 0], [1, 1]) # The general case. test_mat_mul(1,",
"no_op_name = \"no_op\" a_constant_name = \"a_constant\" b_constant_name = \"b_constant\" a_check_name",
"\"add\" graph_def = graph_pb2.GraphDef() no_op = quantize_graph.create_node(\"NoOp\", no_op_name, []) graph_def.node.extend([no_op])",
"7, 8, 9, 10], dtype=dtypes.float32, shape=[1, 1, 2, 5]) offset_node",
"dtypes.float32) quantize_graph.set_attr_int_list(conv_node, \"strides\", [1, stride, stride, 1]) quantize_graph.set_attr_string(conv_node, \"padding\", padding)",
"bias_add_name = \"bias_add\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name,",
"float_graph_def.node.extend([concat_node]) test_graph(float_graph_def, {}, [concat_name]) def test_node_name_from_input(self): self.assertEqual(\"SomeName\", quantize_graph.node_name_from_input(\"^SomeName:2\")) def test_unique_node_name_from_input(self):",
"expected_output.node.extend([b_constant]) b_constant_min = quantize_graph.create_constant_node( b_constant_min_name, value=3, dtype=dtypes.float32, shape=[]) expected_output.node.extend([b_constant_min]) b_constant_max",
"5, 6, 7, 8, 9]) def test_mat_mul_tiny(self): # These tests",
".8, .9], dtype=dtypes.float32, shape=[1, 5]) matmul_1_node = make_matmul(\"matmul_1\", input_node, weight_1_node)",
"is quantized. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None) eightbit_graph_def =",
"is no # RoundToSteps op available. # round_rewriter = quantize_graph.GraphRewriter(float_graph_def,",
"def test_keep_control_edges(self): no_op_name = \"no_op\" a_constant_name = \"a_constant\" b_constant_name =",
"# min(matrix) == max(matrix), which used to cause problems. test_mat_mul(1,",
"= \"a_check\" b_check_name = \"b_check\" a_identity_name = \"a_identity\" b_identity_name =",
"= np.array([1]) qarr = quantize_graph.quantize_array(arr, 1) self.assertEqual(arr, qarr) qarr =",
"input array of length 1. arr = np.array([1]) qarr =",
"input_map.items(): arr = [ int( round((n - input_range[0]) * 255",
"- input_range[0]) * 255 / (input_range[1] - input_range[ 0]))) for",
"quantize_graph.create_node(\"Relu\", relu_name, [input_constant_name]) quantize_graph.set_attr_dtype(relu_node, \"T\", dtypes.float32) float_graph_def.node.extend([relu_node]) test_graph(float_graph_def, {}, [relu_name])",
"\"max_bias_add\", value=15.5, dtype=dtypes.float32, shape=[]) fake_quant_node = quantize_graph.create_node( \"FakeQuantWithMinMaxVars\", \"fake_quant\", [bias_add_node.name,",
"shape=[]) expected_output.node.extend([b_constant_min]) b_constant_max = quantize_graph.create_constant_node( b_constant_max_name, value=3, dtype=dtypes.float32, shape=[]) expected_output.node.extend([b_constant_max])",
"import graph_pb2 from tensorflow.python.client import session from tensorflow.python.framework import dtypes",
"variance_constant_name, beta_constant_name, gamma_constant_name ]) quantize_graph.set_attr_dtype(batch_norm_node, \"T\", dtypes.float32) quantize_graph.set_attr_bool(batch_norm_node, \"scale_after_normalization\", False)",
"elements equal. arr = np.array([1, 1, 1]) qarr = quantize_graph.quantize_array(arr,",
"quantize_graph.set_attr_bool(mat_mul_node, \"transpose_b\", False) float_graph_def.node.extend([mat_mul_node]) test_graph(float_graph_def, {}, [mat_mul_name]) def test_conv(depth, image_width,",
"float_graph_def, \"weights_rounded\", quantized_input_range=None) weights_rounded_graph_def = weights_rounded_rewriter.rewrite(output_names) weights_rounded_results = run_graph_def( weights_rounded_graph_def,",
"relu6_node = quantize_graph.create_node(\"Relu6\", relu6_name, [input_constant_name]) quantize_graph.set_attr_dtype(relu6_node, \"T\", dtypes.float32) float_graph_def.node.extend([relu6_node]) test_graph(float_graph_def,",
"quantize_graph.create_constant_node( b_constant_name, value=(0,), dtype=dtypes.quint8, shape=[]) graph_def.node.extend([b_constant]) b_constant_min = quantize_graph.create_constant_node( b_constant_min_name,",
"quantize_graph.create_node( \"FakeQuantWithMinMaxVars\", \"fake_quant\", [bias_add_node.name, min_node.name, max_node.name]) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend([",
"= make_matmul(\"matmul_1\", input_node, weight_1_node) # Reshape 4x5 to 10x2. new_shape_node",
"12], dtype=dtypes.float32, shape=[2, 6]) float_graph_def.node.extend([input_constant]) identity_node = quantize_graph.create_node(\"Identity\", identity_name, [input_constant_name])",
"dtypes.int32) expected_output.node.extend([mat_mul_node]) expected_output.versions.CopyFrom(graph_def.versions) expected_output.library.CopyFrom(graph_def.library) rewriter = quantize_graph.GraphRewriter( graph_def, [mat_mul_name], quantized_input_range=None)",
"quantize_graph.set_attr_shape(input_n, \"shape\", input_shape) offset_n = quantize_graph.create_constant_node( \"offset\", value=[1, 2, 3,",
"b_constant_name]) quantize_graph.set_attr_dtype(mat_mul_node, \"T\", dtypes.float32) quantize_graph.set_attr_bool(mat_mul_node, \"transpose_a\", False) quantize_graph.set_attr_bool(mat_mul_node, \"transpose_b\", False)",
"= [node.op for node in graph_def.node] self.assertEqual( len(input_map), ops.count(\"QuantizeV2\") +",
"quantize_graph.create_node(\"Reshape\", \"reshape\", [a.name, shape.name]) quantize_graph.set_attr_dtype(reshape, \"T\", dtypes.int32) g = graph_pb2.GraphDef()",
"# matmul_1 = input*weight_1 input_node = quantize_graph.create_constant_node( \"input\", value=[0, 1,",
"quantize_graph.set_attr_int(split_node, \"num_split\", 2) quantize_graph.set_attr_dtype(split_node, \"T\", dtypes.float32) float_graph_def.node.extend([split_node]) concat_constant = quantize_graph.create_constant_node(",
"b_quantize_name, a_quantize_name + \":1\", a_quantize_name + \":2\", b_quantize_name + \":1\",",
"2, 1]) quantize_graph.set_attr_int_list(max_pool_node, \"strides\", [1, 1, 1, 1]) quantize_graph.set_attr_string(max_pool_node, \"padding\",",
"= quantize_graph.create_constant_node( \"offset\", value=[1, 2, 3, 4, 5, 6], dtype=dtypes.float32,",
"1]) float_graph_def.node.extend([input_constant]) relu6_node = quantize_graph.create_node(\"Relu6\", relu6_name, [input_constant_name]) quantize_graph.set_attr_dtype(relu6_node, \"T\", dtypes.float32)",
"= \"batch_norm\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=[1,",
"quantize_graph.set_attr_int_list(conv_node, \"strides\", [1, stride, stride, 1]) quantize_graph.set_attr_string(conv_node, \"padding\", padding) float_graph_def.node.extend([conv_node])",
"dtype=dtypes.quint8, shape=[]) graph_def.node.extend([a_constant]) a_constant_min = quantize_graph.create_constant_node( a_constant_min_name, value=2, dtype=dtypes.float32, shape=[])",
"shape=[2]) float_graph_def.node.extend([beta_constant]) gamma_constant = quantize_graph.create_constant_node( gamma_constant_name, value=[0, 0], dtype=dtypes.float32, shape=[2])",
"1, 2, 6]) float_graph_def.node.extend([input_constant]) offset_constant = quantize_graph.create_constant_node( offset_constant_name, value=[1, 2,",
"\":2\"]) quantize_graph.set_attr_dtype(b_quantize_node, \"T\", dtypes.uint8) graph_def.node.extend([b_quantize_node]) mat_mul_node = quantize_graph.create_node(\"QuantizedMatMul\", mat_mul_name, [",
"# round_rewriter = quantize_graph.GraphRewriter(float_graph_def, \"round\") # round_graph_def = round_rewriter.rewrite(output_name) #",
"2, 3]) float_graph_def.node.extend([b_constant]) concat_node = quantize_graph.create_node( \"Concat\", concat_name, [shape_constant_name, a_constant_name,",
"\"a_quantize\" b_constant_name = \"b_constant\" b_constant_min_name = \"b_constant_min\" b_constant_max_name = \"b_constant_max\"",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"9, 10, 11, 12], dtype=dtypes.float32, shape=[1, 2, 6, 1]) float_graph_def.node.extend([input_constant])",
"(empty array, or 0 buckets. self.assertRaises(ValueError, quantize_graph.quantize_array, np.array([]), 2) self.assertRaises(ValueError,",
"float_graph_def.node.extend([b_constant]) mat_mul_node = quantize_graph.create_node(\"MatMul\", mat_mul_name, [a_constant_name, b_constant_name]) quantize_graph.set_attr_dtype(mat_mul_node, \"T\", dtypes.float32)",
"eightbit_graph_def = eightbit_rewriter.rewrite([concat_name]) ops = [node.op for node in eightbit_graph_def.node]",
"writing, software # distributed under the License is distributed on",
"1]) qarr = quantize_graph.quantize_array(arr, 1) self.assertTrue((np.array([0.5, 0.5, 0.5, 0.5]) ==",
"2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=dtypes.float32,",
"and # limitations under the License. # ============================================================================== \"\"\"Tests the",
"quantize/dequantize.\"\"\" def make_matmul(name, a, b): n = quantize_graph.create_node(\"MatMul\", name, [a.name,",
"test_graph(float_graph_def, {}, [batch_norm_name]) def test_max_pool(self): input_constant_name = \"input_constant\" max_pool_name =",
"enumerate(input_values.flatten()): if max_value is None or value > max: max_value",
"[a_dequantize_name, a_dequantize_name + \":1\", a_dequantize_name + \":2\"]) quantize_graph.set_attr_dtype(a_quantize_node, \"T\", dtypes.uint8)",
"graph_def.node.extend([a_dequantize_node]) a_quantize_node = quantize_graph.create_node( \"QuantizeV2\", a_quantize_name, [a_dequantize_name, a_dequantize_name + \":1\",",
"graph_def = rewriter.rewrite(output_names) results = run_graph_def(graph_def, quantized_input_map, output_tensors) for expected,",
"\"bias_add\", [input_node.name, offset_node.name]) quantize_graph.set_attr_dtype(bias_add_node, \"T\", dtypes.float32) min_node = quantize_graph.create_constant_node( \"min_bias_add\",",
"6, 2]) float_graph_def.node.extend([input_constant]) mean_constant = quantize_graph.create_constant_node( mean_constant_name, value=[10, 20], dtype=dtypes.float32,",
"offset_n, bias_add_n]) input_map = { input_n.name + \":0\": np.reshape([1, 2,",
"1) self.assertEqual(arr, qarr) qarr = quantize_graph.quantize_array(arr, 2) self.assertEqual(arr, qarr) #",
"20], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([mean_constant]) variance_constant = quantize_graph.create_constant_node( variance_constant_name, value=[0.25, 0.5],",
"= quantize_graph.create_constant_node( shape_constant_name, value=0, dtype=dtypes.int32, shape=[]) float_graph_def.node.extend([shape_constant]) a_constant = quantize_graph.create_constant_node(",
"= arr.reshape(v.shape) arr = arr.astype(dtypes.quint8.as_numpy_dtype) quantized_input_map[k] = arr output_tensors =",
"def test_concat(self): shape_constant_name = \"shape_constant\" a_constant_name = \"a_constant\" b_constant_name =",
"if abs(difference) > tolerance: how_many_different += 1 mean_difference = total_difference",
"First comparison tensor. b: Second comparison tensor. tolerance: Float value",
"dtypes.int32) g = graph_pb2.GraphDef() g.node.extend([a, shape, reshape]) test_graph(g, {}, [reshape.name])",
"expected_output.node.extend([a_constant_max]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=(0,), dtype=dtypes.quint8, shape=[]) expected_output.node.extend([b_constant]) b_constant_min",
"test_relu_w_fake_quant_w_min_max_vars(self): input_node = quantize_graph.create_constant_node( \"input\", value=[1, 2, 3, 4, 5,",
"= quantize_graph.create_constant_node( input_constant_name, value=[1, 2, 3, 4, 5, 6, 7,",
"eightbit_graph_def, input_map, [output_name + \":0\" for output_name in output_names]) for",
"\"shape\", shape) inputs.append(node) mat_mul_node = quantize_graph.create_node(\"MatMul\", \"mat_mul\", [n.name for n",
"float_graph_def.node.extend([concat_node]) test_graph(float_graph_def, {}, [concat_name]) # Verify the concat is quantized.",
"graph_pb2.GraphDef() float_graph_def.node.extend([ input_node, offset_node, bias_add_node, min_node, max_node, fake_quant_node ]) test_graph(float_graph_def,",
"\" + str(len(flat_a)) + \" vs \" + str(len(flat_b))) return",
"self.assertEqual(1, ops.count(\"Dequantize\")) def test_quantize_array(self): # Test invalid parameters (empty array,",
"+ \":1\"]) quantize_graph.set_attr_int(concat_node, \"N\", 2) quantize_graph.set_attr_dtype(concat_node, \"T\", dtypes.float32) float_graph_def.node.extend([concat_node]) test_graph(float_graph_def,",
"= quantize_graph.create_constant_node( a_constant_name, value=a, dtype=dtypes.float32, shape=[m, k]) float_graph_def.node.extend([a_constant]) b_constant =",
"{}, [batch_norm_name]) def test_max_pool(self): input_constant_name = \"input_constant\" max_pool_name = \"max_pool\"",
"permissions and # limitations under the License. # ============================================================================== \"\"\"Tests",
"as np from tensorflow.core.framework import graph_pb2 from tensorflow.python.client import session",
"\"strides\", [1, 1, 1, 1]) quantize_graph.set_attr_string(avg_pool_node, \"padding\", b\"SAME\") float_graph_def.node.extend([avg_pool_node]) test_graph(float_graph_def,",
"float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend([input_n, offset_n, bias_add_n]) input_map = { input_n.name",
"shape, reshape]) test_graph(g, {}, [reshape.name]) def test_concat(self): shape_constant_name = \"shape_constant\"",
"5, 6, 7, 8, 9, 10, 11, 12], dtype=dtypes.float32, shape=[1,",
"fake_quant_node = quantize_graph.create_node( \"FakeQuantWithMinMaxVars\", \"fake_quant\", [bias_add_node.name, min_node.name, max_node.name]) float_graph_def =",
"+ \":2\"]) quantize_graph.set_attr_dtype(b_quantize_node, \"T\", dtypes.uint8) graph_def.node.extend([b_quantize_node]) mat_mul_node = quantize_graph.create_node(\"QuantizedMatMul\", mat_mul_name,",
"quantize_graph.set_attr_int_list(max_pool_node, \"strides\", [1, 1, 1, 1]) quantize_graph.set_attr_string(max_pool_node, \"padding\", b\"SAME\") float_graph_def.node.extend([max_pool_node])",
"eightbit_rewriter = quantize_graph.GraphRewriter( g, \"eightbit\", quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite([\"matmul_2\"]) ops",
"shape=[]) float_graph_def.node.extend([concat_constant]) concat_node = quantize_graph.create_node( \"Concat\", concat_name, [concat_constant_name, split_name +",
"This uses the default bit_depth. weights_rounded_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"weights_rounded\",",
"\"quantize\" mode. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None) eightbit_graph_def =",
"for output_name in output_names]) for expected, result in zip(float_results, weights_rounded_results):",
"= \"add\" graph_def = graph_pb2.GraphDef() no_op = quantize_graph.create_node(\"NoOp\", no_op_name, [])",
"]) quantize_graph.set_attr_dtype(mat_mul_node, \"T1\", dtypes.uint8) quantize_graph.set_attr_dtype(mat_mul_node, \"T2\", dtypes.int32) graph_def.node.extend([mat_mul_node]) expected_output =",
"1, 2, b\"SAME\", [1, 2, 3, 4, 5, 6, 7,",
"stripped_output = graph_util.extract_sub_graph(output, [mat_mul_name]) self.assertProtoEquals(expected_output, stripped_output) if __name__ == \"__main__\":",
"specialized comparison function designed to help debug problems with quantization.",
"nearly identical. This is a specialized comparison function designed to",
"[matmul_1_node.name, new_shape_node.name]) quantize_graph.set_attr_dtype(reshape_node, \"T\", dtypes.float32) # matmul_2_node = reshape*weight_2 weight_2_node",
"dtype=dtypes.float32, shape=[2, 6]) float_graph_def.node.extend([input_constant]) split_constant = quantize_graph.create_constant_node( split_constant_name, value=1, dtype=dtypes.int32,",
"arr output_tensors = [output_name + \":0\" for output_name in output_names]",
"a specialized comparison function designed to help debug problems with",
"= quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite(output_names) eightbit_results =",
"a_constant = quantize_graph.create_constant_node( a_constant_name, value=a, dtype=dtypes.float32, shape=[m, k]) float_graph_def.node.extend([a_constant]) b_constant",
"print_function import sys import numpy as np from tensorflow.core.framework import",
"np.array([]), 2) self.assertRaises(ValueError, quantize_graph.quantize_array, np.array([1, 2]), 0) # Test input",
"# matmul_2_node = reshape*weight_2 weight_2_node = quantize_graph.create_constant_node( \"weight_2\", value=[1.5, 2.5],",
"run_graph_def( weights_rounded_graph_def, input_map, [output_name + \":0\" for output_name in output_names])",
"np.array([1, 1, 1]) qarr = quantize_graph.quantize_array(arr, 10) self.assertTrue((np.array([1, 1, 1])",
"Boolean indicating whether the two inputs were close enough. \"\"\"",
"= graph_pb2.GraphDef() g.node.extend([a, shape, reshape]) test_graph(g, {}, [reshape.name]) def test_concat(self):",
"are different sizes: \" + str(len(flat_a)) + \" vs \"",
"5, 6, 7, 8, 9, 10, 11, 12, 13, 14,",
"quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite([\"matmul_2\"]) ops = [node.op for node in",
"k, v in input_map.items(): arr = [ int( round((n -",
"mean\" \" difference {2} and mean absolute difference {3}\".format( how_many_different,",
"100]) eightbit_graph_def = eightbit_rewriter.rewrite([fake_quant_node.name]) ops = [node.op for node in",
"a_check_node = quantize_graph.create_node(\"CheckNumerics\", a_check_name, [a_constant_name]) graph_def.node.extend([a_check_node]) a_identity_node = quantize_graph.create_node( \"Identity\",",
"17, 18]) def test_conv(self): test_conv(1, 4, 3, 1, 3, 1,",
"else: tf_logging.info(\"Tensors have {0} different values ({1}%), with mean\" \"",
"image_width, depth]) float_graph_def.node.extend([input_constant]) filter_constant = quantize_graph.create_constant_node( filter_constant_name, value=filter_values, dtype=dtypes.float32, shape=[filter_size,",
"graph_def.node] self.assertEqual(0, ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) self.assertEqual(len(output_names), ops.count(\"Dequantize\")) # Quantize without",
"quantize_graph.set_attr_bool(mat_mul_node, \"transpose_a\", False) quantize_graph.set_attr_bool(mat_mul_node, \"transpose_b\", False) float_graph_def.node.extend([mat_mul_node]) test_graph(float_graph_def, {}, [mat_mul_name])",
"dtype=dtypes.float32, shape=[1, 1, 2, 6]) float_graph_def.node.extend([input_constant]) offset_constant = quantize_graph.create_constant_node( offset_constant_name,",
"total_abs_difference = 0 for index in range(value_count): a_value = flat_a[index]",
"expected_output.node.extend([no_op]) a_constant = quantize_graph.create_constant_node( a_constant_name, value=1, dtype=dtypes.float32, shape=[]) expected_output.node.extend([a_constant]) a_identity_node",
"= \"variance_constant\" beta_constant_name = \"beta_constant\" gamma_constant_name = \"gamma_constant\" batch_norm_name =",
"graph_pb2.GraphDef() a_constant = quantize_graph.create_constant_node( a_constant_name, value=(0,), dtype=dtypes.quint8, shape=[]) graph_def.node.extend([a_constant]) a_constant_min",
"graph_def.node.extend([b_identity_node]) add_node = quantize_graph.create_node(\"Add\", add_name, [a_identity_name, b_identity_name]) quantize_graph.set_attr_dtype(add_node, \"T\", dtypes.float32)",
"= quantize_graph.GraphRewriter( float_graph_def, \"weights_rounded\", quantized_input_range=None) weights_rounded_graph_def = weights_rounded_rewriter.rewrite(output_names) weights_rounded_results =",
"1]) quantize_graph.set_attr_int_list(avg_pool_node, \"strides\", [1, 1, 1, 1]) quantize_graph.set_attr_string(avg_pool_node, \"padding\", b\"SAME\")",
"input_constant = quantize_graph.create_constant_node( input_constant_name, value=input_values, dtype=dtypes.float32, shape=[image_batch_count, image_height, image_width, depth])",
"7, 8, 9, 10, 11, 12], [1, 4, 7, 2,",
"= quantize_graph.create_node(\"QuantizedMatMul\", mat_mul_name, [ a_quantize_name, b_quantize_name, a_quantize_name + \":1\", a_quantize_name",
"test_graph(float_graph_def, input_map, output_names, log_graph=False): \"\"\"Runs the float graph through the",
"8, 9, 10, 11, 12], [1, 4, 7, 2, 5,",
"Requantize op. eightbit_rewriter = quantize_graph.GraphRewriter( g, \"eightbit\", quantized_input_range=None) eightbit_graph_def =",
"\"fake_quant\", [relu_node.name, min_node.name, max_node.name]) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend( [input_node, relu_node,",
"\"T2\", dtypes.int32) expected_output.node.extend([mat_mul_node]) expected_output.versions.CopyFrom(graph_def.versions) expected_output.library.CopyFrom(graph_def.library) rewriter = quantize_graph.GraphRewriter( graph_def, [mat_mul_name],",
"len(flat_a) != len(flat_b): tf_logging.info(\"Tensors are different sizes: \" + str(len(flat_a))",
"= quantize_graph.create_constant_node( \"new_shape_node\", value=[10, 2], dtype=dtypes.int32, shape=[2]) reshape_node = quantize_graph.create_node(",
"relu_name = \"relu\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name,",
"b_quantize_node = quantize_graph.create_node( \"QuantizeV2\", b_quantize_name, [b_dequantize_name, b_dequantize_name + \":1\", b_dequantize_name",
"= quantize_graph.create_constant_node( a_constant_name, value=[1, 2, 3, 4, 5, 6, 7,",
"0 total_abs_difference = 0 for index in range(value_count): a_value =",
"dtype=dtypes.float32, shape=[m, k]) float_graph_def.node.extend([a_constant]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=b, dtype=dtypes.float32,",
"a MatMul replacement.\"\"\" a_constant_name = \"a_constant\" b_constant_name = \"b_constant\" mat_mul_name",
"[input_constant_name]) quantize_graph.set_attr_dtype(relu6_node, \"T\", dtypes.float32) float_graph_def.node.extend([relu6_node]) test_graph(float_graph_def, {}, [relu6_name]) def test_bias_add(self):",
"# One dequantize at the end. self.assertEqual(1, ops.count(\"Dequantize\")) def test_relu6(self):",
"no effect # because the FakeQuantWithMinMaxVars are used instead. eightbit_rewriter",
"dtypes.float32) quantize_graph.set_attr_bool(mat_mul_node, \"transpose_a\", False) quantize_graph.set_attr_bool(mat_mul_node, \"transpose_b\", False) float_graph_def.node.extend([mat_mul_node]) test_graph(float_graph_def, {},",
"Quantize and one Requantize op. # Pass in fallback_quantization_range, although",
"== qarr).all()) # Test \"normal\" input arrays. arr = np.array([0,",
"= quantize_graph.GraphRewriter( graph_def, [mat_mul_name], quantized_input_range=None) output = rewriter.remove_redundant_quantization(graph_def) stripped_output =",
"quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None) graph_def = rewriter.rewrite(output_names) results = run_graph_def(graph_def,",
"shape in enumerate(shapes): node = quantize_graph.create_node(\"Placeholder\", \"input_%s\" % i, [])",
"problems with quantization. It prints out information about the differences",
"dtype=dtypes.float32, shape=[]) expected_output.node.extend([b_constant_max]) mat_mul_node = quantize_graph.create_node(\"QuantizedMatMul\", mat_mul_name, [ a_constant_name, b_constant_name,",
"are used instead. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None, fallback_quantization_range=[-100,",
"tolerance): \"\"\"Tests whether two tensors are nearly identical. This is",
"+ \":1\", a_quantize_name + \":2\", b_quantize_name + \":1\", b_quantize_name +",
"[batch_norm_name]) def test_max_pool(self): input_constant_name = \"input_constant\" max_pool_name = \"max_pool\" float_graph_def",
"eightbit_rewriter.rewrite([bias_add_node.name]) ops = [node.op for node in eightbit_graph_def.node] node_names =",
"[1, 2]) def test_mat_mul_small(self): test_mat_mul(2, 4, 3, [1, 2, 3,",
"in eightbit_graph_def.node] # No quantize since all inputs are const",
"graph_def.node.extend([b_quantize_node]) mat_mul_node = quantize_graph.create_node(\"QuantizedMatMul\", mat_mul_name, [ a_quantize_name, b_quantize_name, a_quantize_name +",
"dtype=dtypes.float32, shape=[]) graph_def.node.extend([a_constant_max]) a_dequantize_node = quantize_graph.create_node( \"Dequantize\", a_dequantize_name, [a_constant_name, a_constant_min_name,",
"ops.count(\"Quantize\")) # One dequantize at the end. self.assertEqual(1, ops.count(\"Dequantize\")) #",
"= [node.op for node in eightbit_graph_def.node] node_names = [node.name for",
"to 10x2. new_shape_node = quantize_graph.create_constant_node( \"new_shape_node\", value=[10, 2], dtype=dtypes.int32, shape=[2])",
"10, 11, 12], dtype=dtypes.float32, shape=[2, 2, 3]) float_graph_def.node.extend([a_constant]) b_constant =",
"the end. self.assertEqual(1, ops.count(\"Dequantize\")) def test_relu6(self): input_constant_name = \"input_constant\" relu6_name",
"[relu6_name]) def test_bias_add(self): input_constant_name = \"input_constant\" offset_constant_name = \"offset_constant\" bias_add_name",
"255 / (input_range[1] - input_range[ 0]))) for n in v.flat",
"buckets. self.assertRaises(ValueError, quantize_graph.quantize_array, np.array([]), 2) self.assertRaises(ValueError, quantize_graph.quantize_array, np.array([1, 2]), 0)",
"if sys.version_info[0] == 3: # uint8->quint8 conversion for numpy is",
"is only one Quantize and one Requantize op. eightbit_rewriter =",
"weights_rounded_graph_def, input_map, [output_name + \":0\" for output_name in output_names]) for",
"value=1, dtype=dtypes.float32, shape=[]) graph_def.node.extend([a_constant]) a_check_node = quantize_graph.create_node(\"CheckNumerics\", a_check_name, [a_constant_name]) graph_def.node.extend([a_check_node])",
"quantized_input_range=None, fallback_quantization_range=[-.5, 15.5]) eightbit_graph_def = eightbit_rewriter.rewrite([bias_add_node.name]) ops = [node.op for",
"results.\"\"\" float_results = run_graph_def( float_graph_def, input_map, [output_name + \":0\" for",
"6, 1]) relu_node = quantize_graph.create_node(\"Relu\", \"relu\", [input_node.name]) quantize_graph.set_attr_dtype(relu_node, \"T\", dtypes.float32)",
"matmul_1_node, new_shape_node, reshape_node, weight_2_node, matmul_2_node ]) # Test the graph",
"= \"b_constant\" b_constant_min_name = \"b_constant_min\" b_constant_max_name = \"b_constant_max\" b_dequantize_name =",
"value=2, dtype=dtypes.float32, shape=[]) graph_def.node.extend([a_constant_min]) a_constant_max = quantize_graph.create_constant_node( a_constant_max_name, value=2, dtype=dtypes.float32,",
"quantize_graph.set_attr_dtype(identity_node, \"T\", dtypes.float32) float_graph_def.node.extend([identity_node]) mul_name = \"mul\" mul_node = quantize_graph.create_node(\"Mul\",",
"quantize_graph.set_attr_dtype(b_dequantize_node, \"T\", dtypes.uint8) graph_def.node.extend([b_dequantize_node]) b_quantize_node = quantize_graph.create_node( \"QuantizeV2\", b_quantize_name, [b_dequantize_name,",
"\"QuantizeV2\", b_quantize_name, [b_dequantize_name, b_dequantize_name + \":1\", b_dequantize_name + \":2\"]) quantize_graph.set_attr_dtype(b_quantize_node,",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"output = rewriter.remove_redundant_quantization(graph_def) stripped_output = graph_util.extract_sub_graph(output, [mat_mul_name]) self.assertProtoEquals(expected_output, stripped_output) if",
"quantize_graph.create_constant_node( a_constant_name, value=1, dtype=dtypes.float32, shape=[]) graph_def.node.extend([a_constant]) a_check_node = quantize_graph.create_node(\"CheckNumerics\", a_check_name,",
"-1]) def test_quantized_input_range_bias_add(self): input_shape = [1, 1, 2, 6] input_n",
"dtype=dtypes.int32, shape=[]) a = quantize_graph.create_constant_node( \"a\", value=[1, 2, 3, 4,",
"and one Requantize op. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None)",
"= quantize_graph.create_node( \"Dequantize\", b_dequantize_name, [b_constant_name, b_constant_min_name, b_constant_max_name]) quantize_graph.set_attr_dtype(b_dequantize_node, \"T\", dtypes.uint8)",
"\" + str(len(flat_b))) return False value_count = len(flat_a) how_many_different =",
"def test_multiple_outputs(self): input_constant_name = \"input_constant\" split_constant_name = \"split_constant\" split_name =",
"def test_mat_mul_tiny(self): # These tests are added to test the",
"\"BiasAdd\", \"bias_add\", [input_node.name, offset_node.name]) quantize_graph.set_attr_dtype(bias_add_node, \"T\", dtypes.float32) float_graph_def = graph_pb2.GraphDef()",
"float_graph_def.node.extend([gamma_constant]) batch_norm_node = quantize_graph.create_node( \"BatchNormWithGlobalNormalization\", batch_norm_name, [ input_constant_name, mean_constant_name, variance_constant_name,",
"matmul_2_node = reshape*weight_2 weight_2_node = quantize_graph.create_constant_node( \"weight_2\", value=[1.5, 2.5], dtype=dtypes.float32,",
"\"T\", dtypes.float32) graph_def.node.extend([add_node]) expected_output = graph_pb2.GraphDef() no_op = quantize_graph.create_node(\"NoOp\", no_op_name,",
"shape=[k, n]) float_graph_def.node.extend([b_constant]) mat_mul_node = quantize_graph.create_node(\"MatMul\", mat_mul_name, [a_constant_name, b_constant_name]) quantize_graph.set_attr_dtype(mat_mul_node,",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"output_tensors = [output_name + \":0\" for output_name in output_names] float_results",
"float_graph_def, \"eightbit\", quantized_input_range=None) graph_def = rewriter.rewrite(output_names) results = run_graph_def(graph_def, input_map,",
"-5, -3, -6], dtype=dtypes.float32, shape=[1, 1, 6, 2]) float_graph_def.node.extend([input_constant]) mean_constant",
"\"input_%s\" % i, []) quantize_graph.set_attr_dtype(node, \"dtype\", dtypes.float32) quantize_graph.set_attr_shape(node, \"shape\", shape)",
"case. test_mat_mul(1, 1, 2, [1, 2], [1, 2]) def test_mat_mul_small(self):",
"mean_abs_difference)) return False def get_top_value(input_values): max_value = None max_index =",
"[concat_constant_name, split_name + \":0\", split_name + \":1\"]) quantize_graph.set_attr_int(concat_node, \"N\", 2)",
"self.assertEqual(0, ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) # One dequantize at the end.",
"Verify the concat is quantized. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\",",
"assert are_tensors_near(expected, round_results[0], 1.0) # # TODO(petewarden): Add test for",
"a_value = flat_a[index] b_value = flat_b[index] difference = a_value -",
"new_shape_node = quantize_graph.create_constant_node( \"new_shape_node\", value=[10, 2], dtype=dtypes.int32, shape=[2]) reshape_node =",
"for node in eightbit_graph_def.node] # No quantize since all inputs",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"= quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite([fake_quant_node.name]) ops =",
"\"b_quantize\" mat_mul_name = \"mat_mul\" graph_def = graph_pb2.GraphDef() a_constant = quantize_graph.create_constant_node(",
"a_constant_max_name, value=2, dtype=dtypes.float32, shape=[]) graph_def.node.extend([a_constant_max]) a_dequantize_node = quantize_graph.create_node( \"Dequantize\", a_dequantize_name,",
"b_constant_name, value=[13, 14, 15, 16, 17, 18, 19, 20, 21,",
"+ \":0\": np.reshape([1, 2, 3, 4, 5, 6, 7, 8,",
"expected_output.node.extend([b_constant_min]) b_constant_max = quantize_graph.create_constant_node( b_constant_max_name, value=3, dtype=dtypes.float32, shape=[]) expected_output.node.extend([b_constant_max]) mat_mul_node",
"{}, [concat_name]) # Verify the concat is quantized. eightbit_rewriter =",
"concat_constant_name = \"concat_constant\" concat_name = \"concat\" float_graph_def = graph_pb2.GraphDef() input_constant",
"result, .5) ops = [node.op for node in graph_def.node] self.assertEqual(",
"a_constant_min = quantize_graph.create_constant_node( a_constant_min_name, value=2, dtype=dtypes.float32, shape=[]) expected_output.node.extend([a_constant_min]) a_constant_max =",
"\"bias_add\", [input_node.name, offset_node.name]) quantize_graph.set_attr_dtype(bias_add_node, \"T\", dtypes.float32) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend([input_node,",
"[a_constant_name, \"^\" + a_check_name, \"^\" + no_op_name]) graph_def.node.extend([a_identity_node]) b_constant =",
"quantize_graph.set_attr_dtype(mat_mul_node, \"T1\", dtypes.uint8) quantize_graph.set_attr_dtype(mat_mul_node, \"T2\", dtypes.int32) graph_def.node.extend([mat_mul_node]) expected_output = graph_pb2.GraphDef()",
"no # RequantizationRange op. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None,",
"result in zip(float_results, eightbit_results): assert are_tensors_near(expected, result, 1.0) if log_graph:",
"split_node = quantize_graph.create_node( \"Split\", split_name, [split_constant_name, input_constant_name]) quantize_graph.set_attr_int(split_node, \"num_split\", 2)",
"2) quantize_graph.set_attr_dtype(concat, \"T\", dtypes.int32) g = graph_pb2.GraphDef() g.node.extend([concat_dim, a, b,",
"\"T\", dtypes.float32) quantize_graph.set_attr_bool(n, \"transpose_a\", False) quantize_graph.set_attr_bool(n, \"transpose_b\", False) return n",
"2, [1, 1], [1, 1]) test_mat_mul(1, 1, 2, [0, 0],",
"23, 24], dtype=dtypes.int32, shape=[2, 2, 3]) concat = quantize_graph.create_node(\"Concat\", \"concat\",",
"# # TODO(petewarden): Add test for \"quantize\" mode. eightbit_rewriter =",
"\"T\", dtypes.float32) float_graph_def.node.extend([concat_node]) test_graph(float_graph_def, {}, [concat_name]) def test_node_name_from_input(self): self.assertEqual(\"SomeName\", quantize_graph.node_name_from_input(\"^SomeName:2\"))",
"5, 3, 6, -1, -4, -2, -5, -3, -6], dtype=dtypes.float32,",
"quantize_graph.create_constant_node( \"offset\", value=[1, 2, 3, 4, 5, 6], dtype=dtypes.float32, shape=[6])",
"+ a_check_name, \"^\" + no_op_name]) graph_def.node.extend([a_identity_node]) b_constant = quantize_graph.create_constant_node( b_constant_name,",
"]) quantize_graph.set_attr_dtype(batch_norm_node, \"T\", dtypes.float32) quantize_graph.set_attr_bool(batch_norm_node, \"scale_after_normalization\", False) quantize_graph.set_attr_float(batch_norm_node, \"variance_epsilon\", 0.001)",
"\"T\", dtypes.uint8) graph_def.node.extend([b_dequantize_node]) b_quantize_node = quantize_graph.create_node( \"QuantizeV2\", b_quantize_name, [b_dequantize_name, b_dequantize_name",
"test_multiple_outputs(self): input_constant_name = \"input_constant\" split_constant_name = \"split_constant\" split_name = \"split\"",
"test_graph(float_graph_def, {}, [relu6_name]) def test_bias_add(self): input_constant_name = \"input_constant\" offset_constant_name =",
"17, 18, 19, 20, 21, 22, 23, 24], dtype=dtypes.float32, shape=[2,",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"\"b_constant\" a_check_name = \"a_check\" b_check_name = \"b_check\" a_identity_name = \"a_identity\"",
"dtype=dtypes.float32, shape=[]) graph_def.node.extend([b_constant]) b_check_node = quantize_graph.create_node(\"CheckNumerics\", b_check_name, [b_constant_name]) graph_def.node.extend([b_check_node]) b_identity_node",
"= quantize_graph.create_node( \"FakeQuantWithMinMaxVars\", \"fake_quant\", [bias_add_node.name, min_node.name, max_node.name]) float_graph_def = graph_pb2.GraphDef()",
"self.assertTrue((np.array([[0.25, 0.25], [0.75, 0.75]]) == qarr).all()) def test_non_float_concat(self): concat_dim =",
"values is ok. Returns: Boolean indicating whether the two inputs",
"with mean\" \" difference {2} and mean absolute difference {3}\".format(",
"quantize_graph.quantize_array(arr, 10) self.assertTrue((np.array([1, 1, 1]) == qarr).all()) # Test \"normal\"",
"a_identity_node = quantize_graph.create_node( \"Identity\", a_identity_name, [a_constant_name, \"^\" + a_check_name, \"^\"",
"shape=[6]) bias_add_n = quantize_graph.create_node(\"BiasAdd\", \"bias_add\", [input_n.name, offset_n.name]) quantize_graph.set_attr_dtype(bias_add_n, \"T\", dtypes.float32)",
"b_check_node = quantize_graph.create_node(\"CheckNumerics\", b_check_name, [b_constant_name]) graph_def.node.extend([b_check_node]) b_identity_node = quantize_graph.create_node( \"Identity\",",
"shape=[]) graph_def.node.extend([a_constant_max]) a_dequantize_node = quantize_graph.create_node( \"Dequantize\", a_dequantize_name, [a_constant_name, a_constant_min_name, a_constant_max_name])",
"quantize_graph.create_node(\"CheckNumerics\", a_check_name, [a_constant_name]) graph_def.node.extend([a_check_node]) a_identity_node = quantize_graph.create_node( \"Identity\", a_identity_name, [a_constant_name,",
"Rights Reserved. # # Licensed under the Apache License, Version",
"with all elements equal. arr = np.array([1, 1, 1]) qarr",
"input_constant = quantize_graph.create_constant_node( input_constant_name, value=[1, 4, 2, 5, 3, 6,",
"currently. return quantized_input_map = {} for k, v in input_map.items():",
"specific language governing permissions and # limitations under the License.",
"self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [bias_add_n.name], [-1, 20.]) self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [bias_add_n.name], [0, 12.])",
"str(len(flat_a)) + \" vs \" + str(len(flat_b))) return False value_count",
"def test_identity(self): input_constant_name = \"input_constant\" identity_name = \"identity\" float_graph_def =",
"round_results[0], 1.0) # # TODO(petewarden): Add test for \"quantize\" mode.",
"\"eightbit\", [0, -1]) def test_quantized_input_range_bias_add(self): input_shape = [1, 1, 2,",
"conv_name = \"conv\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name,",
"one Quantize and one Requantize op. eightbit_rewriter = quantize_graph.GraphRewriter( g,",
"qarr = quantize_graph.quantize_array(arr, 2) self.assertEqual(arr, qarr) # Test input array",
"= { input_n.name + \":0\": np.reshape([1, 2, 3, 4, 5,",
"inputs]) quantize_graph.set_attr_dtype(mat_mul_node, \"T\", dtypes.float32) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend(inputs + [mat_mul_node])",
"zip(float_results, eightbit_results): assert are_tensors_near(expected, result, 1.0) if log_graph: tf_logging.info(\"8bit:\\n%s\", str(eightbit_graph_def))",
"4, 5, 6, 7, 8, 9, 10, 11, 12, 13,",
"quantize_graph.quantize_array, np.array([]), 2) self.assertRaises(ValueError, quantize_graph.quantize_array, np.array([1, 2]), 0) # Test",
"qarr = quantize_graph.quantize_array(arr, 10) self.assertTrue((np.array([1, 1, 1]) == qarr).all()) #",
"for index, value in enumerate(input_values.flatten()): if max_value is None or",
"qarr = quantize_graph.quantize_array(arr, 2) self.assertTrue((np.array([0.25, 0.25, 0.75, 0.75]) == qarr).all())",
"test_mat_mul(1, 1, 2, [0, 0], [1, 1]) # The general",
"run_graph_def(graph_def, quantized_input_map, output_tensors) for expected, result in zip(float_results, results): assert",
"2], [1, 2]) def test_mat_mul_small(self): test_mat_mul(2, 4, 3, [1, 2,",
"= quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite([concat_name]) ops =",
"# you may not use this file except in compliance",
"and one Requantize op. eightbit_rewriter = quantize_graph.GraphRewriter( g, \"eightbit\", quantized_input_range=None)",
"indicating whether the two inputs were close enough. \"\"\" flat_a",
"2, 6, 1]) float_graph_def.node.extend([input_constant]) max_pool_node = quantize_graph.create_node(\"MaxPool\", max_pool_name, [input_constant_name]) quantize_graph.set_attr_int_list(max_pool_node,",
"[input_constant_name, filter_constant_name]) quantize_graph.set_attr_dtype(conv_node, \"T\", dtypes.float32) quantize_graph.set_attr_int_list(conv_node, \"strides\", [1, stride, stride,",
"[]) graph_def.node.extend([no_op]) a_constant = quantize_graph.create_constant_node( a_constant_name, value=1, dtype=dtypes.float32, shape=[]) graph_def.node.extend([a_constant])",
"difference total_abs_difference += abs(difference) if abs(difference) > tolerance: how_many_different +=",
"difference = a_value - b_value total_difference += difference total_abs_difference +=",
"concat]) test_graph(g, {}, [concat.name]) def test_non_float_reshape(self): a = quantize_graph.create_constant_node( \"a\",",
"graph_pb2.GraphDef() float_graph_def.node.extend([input_n, offset_n, bias_add_n]) input_map = { input_n.name + \":0\":",
"12.]) def test_quantized_input_range_mat_mul(self): shapes = [[3, 2], [2, 4]] inputs",
"quantize_graph.set_attr_dtype(node, \"dtype\", dtypes.float32) quantize_graph.set_attr_shape(node, \"shape\", shape) inputs.append(node) mat_mul_node = quantize_graph.create_node(\"MatMul\",",
"import numpy as np from tensorflow.core.framework import graph_pb2 from tensorflow.python.client",
"where # min(matrix) == max(matrix), which used to cause problems.",
"\":0\": np.reshape([1, 2, 3, 4, 5, 6, 7, 8, 9,",
"\"eightbit\", input_range) graph_def = rewriter.rewrite(output_names) results = run_graph_def(graph_def, quantized_input_map, output_tensors)",
"\"offset_constant\" bias_add_name = \"bias_add\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node(",
"RequantizationRange op. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None, fallback_quantization_range=[-.5, 15.5])",
"from __future__ import print_function import sys import numpy as np",
"output_names]) # TODO(petewarden): round test is currently failing because there",
"fake_quant_node = quantize_graph.create_node( \"FakeQuantWithMinMaxVars\", \"fake_quant\", [relu_node.name, min_node.name, max_node.name]) float_graph_def =",
"{} for k, v in input_map.items(): arr = [ int(",
"4, 5, 6], dtype=dtypes.float32, shape=[6]) float_graph_def.node.extend([offset_constant]) bias_add_node = quantize_graph.create_node( \"BiasAdd\",",
"mat_mul_node = quantize_graph.create_node(\"MatMul\", mat_mul_name, [a_constant_name, b_constant_name]) quantize_graph.set_attr_dtype(mat_mul_node, \"T\", dtypes.float32) quantize_graph.set_attr_bool(mat_mul_node,",
"[a_identity_name, b_identity_name]) quantize_graph.set_attr_dtype(add_node, \"T\", dtypes.float32) graph_def.node.extend([add_node]) expected_output = graph_pb2.GraphDef() no_op",
"Quantize, one Requantize op, and no # RequantizationRange op. eightbit_rewriter",
"although it will have no effect # because the FakeQuantWithMinMaxVars",
"dtype=dtypes.float32, shape=[]) expected_output.node.extend([a_constant_max]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=(0,), dtype=dtypes.quint8, shape=[])",
"end. self.assertEqual(1, ops.count(\"Dequantize\")) def test_relu6(self): input_constant_name = \"input_constant\" relu6_name =",
"quantize_graph.set_attr_dtype(bias_add_n, \"T\", dtypes.float32) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend([input_n, offset_n, bias_add_n]) input_map",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"b_quantize_name, [b_dequantize_name, b_dequantize_name + \":1\", b_dequantize_name + \":2\"]) quantize_graph.set_attr_dtype(b_quantize_node, \"T\",",
"b_constant_name, value=(0,), dtype=dtypes.quint8, shape=[]) graph_def.node.extend([b_constant]) b_constant_min = quantize_graph.create_constant_node( b_constant_min_name, value=3,",
"shape = quantize_graph.create_constant_node( \"shape\", value=[12], dtype=dtypes.int32, shape=[1]) reshape = quantize_graph.create_node(\"Reshape\",",
"\"b_identity\" add_name = \"add\" graph_def = graph_pb2.GraphDef() no_op = quantize_graph.create_node(\"NoOp\",",
"ops = [node.op for node in eightbit_graph_def.node] # No quantize",
"dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([variance_constant]) beta_constant = quantize_graph.create_constant_node( beta_constant_name, value=[0.1, 0.6], dtype=dtypes.float32,",
"# Test \"normal\" input arrays. arr = np.array([0, 0.3, 0.6,",
"def test_remove_redundant_quantization(self): a_constant_name = \"a_constant\" a_constant_min_name = \"a_constant_min\" a_constant_max_name =",
"[] for i, shape in enumerate(shapes): node = quantize_graph.create_node(\"Placeholder\", \"input_%s\"",
"is only one Quantize and one Requantize op. # Pass",
"def test_negative_const_problem(self): shape_constant_name = \"shape_constant\" shape_constant = quantize_graph.create_constant_node( shape_constant_name, value=-0.8,",
"weight_2_node) g = graph_pb2.GraphDef() g.node.extend([ input_node, weight_1_node, matmul_1_node, new_shape_node, reshape_node,",
"input_map, output_names, log_graph=False): \"\"\"Runs the float graph through the rewriter",
"= \"filter_constant\" conv_name = \"conv\" float_graph_def = graph_pb2.GraphDef() input_constant =",
"> tolerance: how_many_different += 1 mean_difference = total_difference / value_count",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"identity_name = \"identity\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name,",
"2], [2, 4]] inputs = [] for i, shape in",
"a_constant_max_name, b_constant_min_name, b_constant_max_name ]) quantize_graph.set_attr_dtype(mat_mul_node, \"T1\", dtypes.uint8) quantize_graph.set_attr_dtype(mat_mul_node, \"T2\", dtypes.int32)",
"str(len(flat_b))) return False value_count = len(flat_a) how_many_different = 0 total_difference",
"op. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None, fallback_quantization_range=[-.5, 15.5]) eightbit_graph_def",
"total_abs_difference += abs(difference) if abs(difference) > tolerance: how_many_different += 1",
"= \"offset_constant\" bias_add_name = \"bias_add\" float_graph_def = graph_pb2.GraphDef() input_constant =",
".2, .1], shapes[1]) } self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [mat_mul_node.name], [-1, 20.]) self._RunTestsForQuantizedInputRange(float_graph_def,",
"[concat_dim.name, a.name, b.name]) quantize_graph.set_attr_int(concat, \"N\", 2) quantize_graph.set_attr_dtype(concat, \"T\", dtypes.int32) g",
"Quantize and one Requantize op. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\",",
"[0.75, 0.75]]) == qarr).all()) def test_non_float_concat(self): concat_dim = quantize_graph.create_constant_node( \"concat_dim\",",
"6, 7, 8, 9, 10, 11, 12], dtype=dtypes.float32, shape=[2, 2,",
"[1, 1, 2, 6] input_n = quantize_graph.create_node(\"Placeholder\", \"input\", []) quantize_graph.set_attr_dtype(input_n,",
"total_difference / value_count mean_abs_difference = total_abs_difference / value_count proportion_different =",
"test_mat_mul(1, 2, 1, [1], [2, 3]) test_mat_mul(1, 1, 2, [1,",
"constants are not in the graph. self.assertEqual(0, node_names.count(\"fallback_quantization_min_value\")) self.assertEqual(0, node_names.count(\"fallback_quantization_max_value\"))",
"all inputs are const and can be quantized up-front. self.assertEqual(0,",
"[input_constant_name, offset_constant_name]) quantize_graph.set_attr_dtype(bias_add_node, \"T\", dtypes.float32) float_graph_def.node.extend([bias_add_node]) test_graph(float_graph_def, {}, [bias_add_name]) def",
"arr.astype(dtypes.quint8.as_numpy_dtype) quantized_input_map[k] = arr output_tensors = [output_name + \":0\" for",
"= graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=[1, 2, 3, 4,",
"float_graph_def.node.extend([input_constant]) relu_node = quantize_graph.create_node(\"Relu\", relu_name, [input_constant_name]) quantize_graph.set_attr_dtype(relu_node, \"T\", dtypes.float32) float_graph_def.node.extend([relu_node])",
"quantize_graph.create_constant_node( b_constant_max_name, value=3, dtype=dtypes.float32, shape=[]) graph_def.node.extend([b_constant_max]) b_dequantize_node = quantize_graph.create_node( \"Dequantize\",",
"mat_mul_name, [a_constant_name, b_constant_name]) quantize_graph.set_attr_dtype(mat_mul_node, \"T\", dtypes.float32) quantize_graph.set_attr_bool(mat_mul_node, \"transpose_a\", False) quantize_graph.set_attr_bool(mat_mul_node,",
"= quantize_graph.create_constant_node( b_constant_min_name, value=3, dtype=dtypes.float32, shape=[]) expected_output.node.extend([b_constant_min]) b_constant_max = quantize_graph.create_constant_node(",
"= make_matmul(\"matmul_2\", reshape_node, weight_2_node) g = graph_pb2.GraphDef() g.node.extend([ input_node, weight_1_node,",
"\":1\", b_quantize_name + \":2\" ]) quantize_graph.set_attr_dtype(mat_mul_node, \"T1\", dtypes.uint8) quantize_graph.set_attr_dtype(mat_mul_node, \"T2\",",
"= \"input_constant\" mean_constant_name = \"mean_constant\" variance_constant_name = \"variance_constant\" beta_constant_name =",
"enumerate(shapes): node = quantize_graph.create_node(\"Placeholder\", \"input_%s\" % i, []) quantize_graph.set_attr_dtype(node, \"dtype\",",
"0.25, 0.75, 0.75]) == qarr).all()) qarr = quantize_graph.quantize_array(arr.reshape((2, 2)), 2)",
"1, 3, 1, 1, b\"SAME\", [1, 2, 3, 4, 5,",
"10, 11, 12], dtype=dtypes.float32, shape=[2, 6]) float_graph_def.node.extend([input_constant]) identity_node = quantize_graph.create_node(\"Identity\",",
"> max: max_value = value max_index = index return max_index,",
"expected, result in zip(float_results, weights_rounded_results): assert are_tensors_near(expected, result, 1.0) class",
"n = quantize_graph.create_node(\"MatMul\", name, [a.name, b.name]) quantize_graph.set_attr_dtype(n, \"T\", dtypes.float32) quantize_graph.set_attr_bool(n,",
"= quantize_graph.quantize_array(arr, 1) self.assertEqual(arr, qarr) qarr = quantize_graph.quantize_array(arr, 2) self.assertEqual(arr,",
"image_batch_count, filter_size, filter_count, stride, padding, input_values, filter_values): \"\"\"Tests a Conv",
"available. # round_rewriter = quantize_graph.GraphRewriter(float_graph_def, \"round\") # round_graph_def = round_rewriter.rewrite(output_name)",
"\"variance_epsilon\", 0.001) float_graph_def.node.extend([batch_norm_node]) test_graph(float_graph_def, {}, [batch_norm_name]) def test_max_pool(self): input_constant_name =",
"quantize_graph.create_node(\"Mul\", mul_name, [identity_name, identity_name]) quantize_graph.set_attr_dtype(mul_node, \"T\", dtypes.float32) float_graph_def.node.extend([mul_node]) test_graph(float_graph_def, {},",
"= \"mat_mul\" graph_def = graph_pb2.GraphDef() a_constant = quantize_graph.create_constant_node( a_constant_name, value=(0,),",
"eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite([concat_name]) ops",
"shape=[]) float_graph_def.node.extend([split_constant]) split_node = quantize_graph.create_node( \"Split\", split_name, [split_constant_name, input_constant_name]) quantize_graph.set_attr_int(split_node,",
"= \"a_constant\" b_constant_name = \"b_constant\" a_check_name = \"a_check\" b_check_name =",
"\"padding\", padding) float_graph_def.node.extend([conv_node]) test_graph(float_graph_def, {}, [conv_name]) def are_tensors_near(a, b, tolerance):",
"in output_names]) for expected, result in zip(float_results, eightbit_results): assert are_tensors_near(expected,",
"\"variance_constant\" beta_constant_name = \"beta_constant\" gamma_constant_name = \"gamma_constant\" batch_norm_name = \"batch_norm\"",
"for output_name in output_names]) # TODO(petewarden): round test is currently",
"in zip(float_results, results): assert are_tensors_near(expected, result, .5) ops = [node.op",
"are_tensors_near(expected, round_results[0], 1.0) # # TODO(petewarden): Add test for \"quantize\"",
"ops.count(\"RequantizationRange\")) # The fallback constants are in the graph. self.assertEqual(1,",
"graph_pb2 from tensorflow.python.client import session from tensorflow.python.framework import dtypes from",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"identity_node = quantize_graph.create_node(\"Identity\", identity_name, [input_constant_name]) quantize_graph.set_attr_dtype(identity_node, \"T\", dtypes.float32) float_graph_def.node.extend([identity_node]) mul_name",
"value=[1, 2, 3, 4, 5, 6], dtype=dtypes.float32, shape=[6]) float_graph_def.node.extend([offset_constant]) bias_add_node",
"9, 10, 11, 12], input_shape) } self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [bias_add_n.name], [-1,",
"self.assertEqual(1, ops.count(\"QuantizedReshape\")) # One dequantize at the end. self.assertEqual(1, ops.count(\"Dequantize\"))",
"\"Dequantize\", b_dequantize_name, [b_constant_name, b_constant_min_name, b_constant_max_name]) quantize_graph.set_attr_dtype(b_dequantize_node, \"T\", dtypes.uint8) graph_def.node.extend([b_dequantize_node]) b_quantize_node",
"b_constant = quantize_graph.create_constant_node( b_constant_name, value=(0,), dtype=dtypes.quint8, shape=[]) expected_output.node.extend([b_constant]) b_constant_min =",
"TODO(petewarden): round test is currently failing because there is no",
"\"N\", 2) quantize_graph.set_attr_dtype(concat_node, \"T\", dtypes.float32) float_graph_def.node.extend([concat_node]) test_graph(float_graph_def, {}, [concat_name]) def",
"rewriter.rewrite(output_names) results = run_graph_def(graph_def, input_map, output_tensors) for expected, result in",
"= \"concat\" float_graph_def = graph_pb2.GraphDef() shape_constant = quantize_graph.create_constant_node( shape_constant_name, value=0,",
"2) quantize_graph.set_attr_dtype(concat_node, \"T\", dtypes.float32) float_graph_def.node.extend([concat_node]) test_graph(float_graph_def, {}, [concat_name]) def test_node_name_from_input(self):",
"op, and no # RequantizationRange op. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def,",
"abs(difference) if abs(difference) > tolerance: how_many_different += 1 mean_difference =",
"quantize_graph.create_node(\"MaxPool\", max_pool_name, [input_constant_name]) quantize_graph.set_attr_int_list(max_pool_node, \"ksize\", [1, 2, 2, 1]) quantize_graph.set_attr_int_list(max_pool_node,",
"[bias_add_n.name], [0, 12.]) def test_quantized_input_range_mat_mul(self): shapes = [[3, 2], [2,",
"value=[1, 4, 2, 5, 3, 6, -1, -4, -2, -5,",
"[n.name for n in inputs]) quantize_graph.set_attr_dtype(mat_mul_node, \"T\", dtypes.float32) float_graph_def =",
"max_value is None or value > max: max_value = value",
"\"input\", value=[0, 1, 2, 3], dtype=dtypes.float32, shape=[4, 1]) weight_1_node =",
"[b_dequantize_name, b_dequantize_name + \":1\", b_dequantize_name + \":2\"]) quantize_graph.set_attr_dtype(b_quantize_node, \"T\", dtypes.uint8)",
"results def test_mat_mul(m, n, k, a, b): \"\"\"Tests a MatMul",
"problems. test_mat_mul(1, 1, 1, [2], [3]) test_mat_mul(1, 2, 1, [1],",
"def test_node_name_from_input(self): self.assertEqual(\"SomeName\", quantize_graph.node_name_from_input(\"^SomeName:2\")) def test_unique_node_name_from_input(self): self.assertEqual(\"__hat__SomeName__port__2\", quantize_graph.unique_node_name_from_input(\"^SomeName:2\")) def test_identity(self):",
"= \"avg_pool\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=[1,",
"def test_max_pool(self): input_constant_name = \"input_constant\" max_pool_name = \"max_pool\" float_graph_def =",
"float_graph_def, \"eightbit\", quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite([fake_quant_node.name]) ops = [node.op for",
"dtypes.int32) graph_def.node.extend([mat_mul_node]) expected_output = graph_pb2.GraphDef() a_constant = quantize_graph.create_constant_node( a_constant_name, value=(0,),",
"= 0 total_abs_difference = 0 for index in range(value_count): a_value",
"graph.as_default(): importer.import_graph_def(graph_def, input_map={}, name=\"\") with session.Session(graph=graph) as sess: results =",
"equal. arr = np.array([1, 1, 1]) qarr = quantize_graph.quantize_array(arr, 10)",
"3, 6, 9]) def test_reshape(self): \"\"\"Tests that MatMul->Reshape->MatMul avoids extra",
"{}, [relu_name]) def test_relu_w_fake_quant_w_min_max_vars(self): input_node = quantize_graph.create_constant_node( \"input\", value=[1, 2,",
"3]) b = quantize_graph.create_constant_node( \"b\", value=[13, 14, 15, 16, 17,",
"test_remove_redundant_quantization(self): a_constant_name = \"a_constant\" a_constant_min_name = \"a_constant_min\" a_constant_max_name = \"a_constant_max\"",
"dtype=dtypes.int32, shape=[2, 2, 3]) concat = quantize_graph.create_node(\"Concat\", \"concat\", [concat_dim.name, a.name,",
"dtype=dtypes.float32, shape=[1, 2, 6, 1]) float_graph_def.node.extend([input_constant]) relu_node = quantize_graph.create_node(\"Relu\", relu_name,",
"0.001) float_graph_def.node.extend([batch_norm_node]) test_graph(float_graph_def, {}, [batch_norm_name]) def test_max_pool(self): input_constant_name = \"input_constant\"",
"Second comparison tensor. tolerance: Float value indicating how large an",
"quantize_graph.create_constant_node( \"min_bias_add\", value=-.5, dtype=dtypes.float32, shape=[]) max_node = quantize_graph.create_constant_node( \"max_bias_add\", value=15.5,",
"because the FakeQuantWithMinMaxVars are used instead. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def,",
"def test_graph(float_graph_def, input_map, output_names, log_graph=False): \"\"\"Runs the float graph through",
"= quantize_graph.create_node( \"Conv2D\", conv_name, [input_constant_name, filter_constant_name]) quantize_graph.set_attr_dtype(conv_node, \"T\", dtypes.float32) quantize_graph.set_attr_int_list(conv_node,",
"b.flatten() if len(flat_a) != len(flat_b): tf_logging.info(\"Tensors are different sizes: \"",
"18]) def test_conv(self): test_conv(1, 4, 3, 1, 3, 1, 1,",
"Quantize and one Requantize op. eightbit_rewriter = quantize_graph.GraphRewriter( g, \"eightbit\",",
"and absolute average errors. Args: a: First comparison tensor. b:",
"tolerance: how_many_different += 1 mean_difference = total_difference / value_count mean_abs_difference",
"[bias_add_name]) def test_quantized_input_range_errors(self): with self.assertRaises(ValueError): # Invalid mode. quantize_graph.GraphRewriter(graph_pb2.GraphDef(), \"weights_rounded\",",
"= run_graph_def( eightbit_graph_def, input_map, [output_name + \":0\" for output_name in",
"concat_name, [concat_constant_name, split_name + \":0\", split_name + \":1\"]) quantize_graph.set_attr_int(concat_node, \"N\",",
"2, 3]) shape = quantize_graph.create_constant_node( \"shape\", value=[12], dtype=dtypes.int32, shape=[1]) reshape",
"+ \":0\" for output_name in output_names]) # TODO(petewarden): round test",
"min_node, max_node, fake_quant_node]) test_graph(float_graph_def, {}, [fake_quant_node.name], log_graph=True) # Verify there",
"a_constant_name, value=1, dtype=dtypes.float32, shape=[]) expected_output.node.extend([a_constant]) a_identity_node = quantize_graph.create_node( \"Identity\", a_identity_name,",
"tf_logging from tensorflow.tools.quantization import quantize_graph flags = flags_lib FLAGS =",
"# TODO(petewarden): Add test for \"quantize\" mode. eightbit_rewriter = quantize_graph.GraphRewriter(",
"array, or 0 buckets. self.assertRaises(ValueError, quantize_graph.quantize_array, np.array([]), 2) self.assertRaises(ValueError, quantize_graph.quantize_array,",
"the input as quantized in range <input_range>. rewriter = quantize_graph.GraphRewriter(float_graph_def,",
"4, 5, 6], dtype=dtypes.float32, shape=[6]) bias_add_n = quantize_graph.create_node(\"BiasAdd\", \"bias_add\", [input_n.name,",
"add_name, [a_identity_name, b_identity_name]) quantize_graph.set_attr_dtype(add_node, \"T\", dtypes.float32) graph_def.node.extend([add_node]) expected_output = graph_pb2.GraphDef()",
"relu_node = quantize_graph.create_node(\"Relu\", relu_name, [input_constant_name]) quantize_graph.set_attr_dtype(relu_node, \"T\", dtypes.float32) float_graph_def.node.extend([relu_node]) test_graph(float_graph_def,",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"quantized in range <input_range>. rewriter = quantize_graph.GraphRewriter(float_graph_def, \"eightbit\", input_range) graph_def",
"= {} for k, v in input_map.items(): arr = [",
"= \"input_constant\" avg_pool_name = \"avg_pool\" float_graph_def = graph_pb2.GraphDef() input_constant =",
"Authors. All Rights Reserved. # # Licensed under the Apache",
"a_constant_name = \"a_constant\" b_constant_name = \"b_constant\" concat_name = \"concat\" float_graph_def",
"\"T\", dtypes.float32) min_node = quantize_graph.create_constant_node( \"min_bias_add\", value=0, dtype=dtypes.float32, shape=[]) max_node",
"def test_quantized_input_range_bias_add(self): input_shape = [1, 1, 2, 6] input_n =",
"= quantize_graph.create_constant_node( b_constant_name, value=b, dtype=dtypes.float32, shape=[k, n]) float_graph_def.node.extend([b_constant]) mat_mul_node =",
"value=[0, 1, 2, 3], dtype=dtypes.float32, shape=[4, 1]) weight_1_node = quantize_graph.create_constant_node(",
"= quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None, fallback_quantization_range=[-100, 100]) eightbit_graph_def = eightbit_rewriter.rewrite([fake_quant_node.name])",
"a_constant_min_name, value=2, dtype=dtypes.float32, shape=[]) expected_output.node.extend([a_constant_min]) a_constant_max = quantize_graph.create_constant_node( a_constant_max_name, value=2,",
"2, 3], dtype=dtypes.float32, shape=[4, 1]) weight_1_node = quantize_graph.create_constant_node( \"weight_1\", value=[.5,",
"as sess: results = sess.run(outputs, feed_dict=input_map) return results def test_mat_mul(m,",
"reshape = quantize_graph.create_node(\"Reshape\", \"reshape\", [a.name, shape.name]) quantize_graph.set_attr_dtype(reshape, \"T\", dtypes.int32) g",
"test_relu(self): input_constant_name = \"input_constant\" relu_name = \"relu\" float_graph_def = graph_pb2.GraphDef()",
"max_value def test_graph(float_graph_def, input_map, output_names, log_graph=False): \"\"\"Runs the float graph",
"= \"b_constant\" mat_mul_name = \"mat_mul\" float_graph_def = graph_pb2.GraphDef() a_constant =",
"4x5 to 10x2. new_shape_node = quantize_graph.create_constant_node( \"new_shape_node\", value=[10, 2], dtype=dtypes.int32,",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"float_graph_def.node.extend([input_n, offset_n, bias_add_n]) input_map = { input_n.name + \":0\": np.reshape([1,",
"10, 11, 12], dtype=dtypes.int32, shape=[2, 2, 3]) b = quantize_graph.create_constant_node(",
"either express or implied. # See the License for the",
"= quantize_graph.create_constant_node( b_constant_name, value=1, dtype=dtypes.float32, shape=[]) graph_def.node.extend([b_constant]) b_check_node = quantize_graph.create_node(\"CheckNumerics\",",
"3, 4, 5], dtype=dtypes.float32, shape=[5]) bias_add_node = quantize_graph.create_node( \"BiasAdd\", \"bias_add\",",
"value=1, dtype=dtypes.float32, shape=[]) expected_output.node.extend([a_constant]) a_identity_node = quantize_graph.create_node( \"Identity\", a_identity_name, [a_constant_name,",
"value=3, dtype=dtypes.float32, shape=[]) graph_def.node.extend([b_constant_max]) b_dequantize_node = quantize_graph.create_node( \"Dequantize\", b_dequantize_name, [b_constant_name,",
"# The fallback constants are not in the graph. self.assertEqual(0,",
"function designed to help debug problems with quantization. It prints",
"dtype=dtypes.float32, shape=[2, 2, 3]) float_graph_def.node.extend([a_constant]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=[13,",
"value=[13, 14, 15, 16, 17, 18, 19, 20, 21, 22,",
"a_quantize_name + \":1\", a_quantize_name + \":2\", b_quantize_name + \":1\", b_quantize_name",
"name, [a.name, b.name]) quantize_graph.set_attr_dtype(n, \"T\", dtypes.float32) quantize_graph.set_attr_bool(n, \"transpose_a\", False) quantize_graph.set_attr_bool(n,",
"\"a_check\" b_check_name = \"b_check\" a_identity_name = \"a_identity\" b_identity_name = \"b_identity\"",
"g = graph_pb2.GraphDef() g.node.extend([ input_node, weight_1_node, matmul_1_node, new_shape_node, reshape_node, weight_2_node,",
"= quantize_graph.create_constant_node( gamma_constant_name, value=[0, 0], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([gamma_constant]) batch_norm_node =",
"eightbit_graph_def.node] self.assertEqual(1, ops.count(\"QuantizedConcat\")) def test_multiple_outputs(self): input_constant_name = \"input_constant\" split_constant_name =",
"difference {2} and mean absolute difference {3}\".format( how_many_different, proportion_different *",
"a_constant_name = \"a_constant\" b_constant_name = \"b_constant\" mat_mul_name = \"mat_mul\" float_graph_def",
"2, 1, [1], [2, 3]) test_mat_mul(1, 1, 2, [1, 1],",
"= np.array([0, 0.3, 0.6, 1]) qarr = quantize_graph.quantize_array(arr, 1) self.assertTrue((np.array([0.5,",
"{ inputs[0].name + \":0\": np.reshape([1, 2, 3, 4, 5, 6],",
"0.75, 0.75]) == qarr).all()) qarr = quantize_graph.quantize_array(arr.reshape((2, 2)), 2) self.assertTrue((np.array([[0.25,",
"input_map, [bias_add_n.name], [0, 12.]) def test_quantized_input_range_mat_mul(self): shapes = [[3, 2],",
"Verify there is only one Quantize and one Requantize op.",
"shape=[]) graph_def.node.extend([a_constant]) a_constant_min = quantize_graph.create_constant_node( a_constant_min_name, value=2, dtype=dtypes.float32, shape=[]) graph_def.node.extend([a_constant_min])",
".6, .5, .4, .3, .2, .1], shapes[1]) } self._RunTestsForQuantizedInputRange(float_graph_def, input_map,",
"inputs = [] for i, shape in enumerate(shapes): node =",
"1, 6, 2]) float_graph_def.node.extend([input_constant]) mean_constant = quantize_graph.create_constant_node( mean_constant_name, value=[10, 20],",
"filter_constant_name]) quantize_graph.set_attr_dtype(conv_node, \"T\", dtypes.float32) quantize_graph.set_attr_int_list(conv_node, \"strides\", [1, stride, stride, 1])",
"avg_pool_name = \"avg_pool\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name,",
"\"split_constant\" split_name = \"split\" concat_constant_name = \"concat_constant\" concat_name = \"concat\"",
"\":0\" for output_name in output_names] float_results = run_graph_def(float_graph_def, input_map, output_tensors)",
"beta_constant = quantize_graph.create_constant_node( beta_constant_name, value=[0.1, 0.6], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([beta_constant]) gamma_constant",
"shape=[2, 2, 3]) b = quantize_graph.create_constant_node( \"b\", value=[13, 14, 15,",
"2, [1, 2], [1, 2]) def test_mat_mul_small(self): test_mat_mul(2, 4, 3,",
"assert are_tensors_near(expected, result, .5) ops = [node.op for node in",
"from __future__ import division from __future__ import print_function import sys",
"quantize_graph.quantize_array(arr.reshape((2, 2)), 2) self.assertTrue((np.array([[0.25, 0.25], [0.75, 0.75]]) == qarr).all()) def",
"tensor. b: Second comparison tensor. tolerance: Float value indicating how",
"with graph.as_default(): importer.import_graph_def(graph_def, input_map={}, name=\"\") with session.Session(graph=graph) as sess: results",
"dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([mean_constant]) variance_constant = quantize_graph.create_constant_node( variance_constant_name, value=[0.25, 0.5], dtype=dtypes.float32,",
"\"a\", value=[1, 2, 3, 4, 5, 6, 7, 8, 9,",
"{}, [mat_mul_name]) def test_conv(depth, image_width, image_height, image_batch_count, filter_size, filter_count, stride,",
"[reshape.name]) def test_concat(self): shape_constant_name = \"shape_constant\" a_constant_name = \"a_constant\" b_constant_name",
"case we ran into in a real graph.\"\"\" test_conv(1, 4,",
"shape=[1, 2, 6, 1]) float_graph_def.node.extend([input_constant]) avg_pool_node = quantize_graph.create_node(\"AvgPool\", avg_pool_name, [input_constant_name])",
"reshape_node, weight_2_node, matmul_2_node ]) # Test the graph test_graph(g, {},",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"+ b_check_name]) graph_def.node.extend([b_identity_node]) add_node = quantize_graph.create_node(\"Add\", add_name, [a_identity_name, b_identity_name]) quantize_graph.set_attr_dtype(add_node,",
"6], shapes[0]), inputs[1].name + \":0\": np.reshape([.8, .7, .6, .5, .4,",
"test_conv(self): test_conv(1, 4, 3, 1, 3, 1, 1, b\"SAME\", [1,",
"identical. This is a specialized comparison function designed to help",
"= \"input_constant\" filter_constant_name = \"filter_constant\" conv_name = \"conv\" float_graph_def =",
"and can be quantized up-front. self.assertEqual(0, ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) self.assertEqual(1,",
"\"T\", dtypes.float32) quantize_graph.set_attr_int_list(conv_node, \"strides\", [1, stride, stride, 1]) quantize_graph.set_attr_string(conv_node, \"padding\",",
"10, 11, 12], dtype=dtypes.int32, shape=[2, 2, 3]) shape = quantize_graph.create_constant_node(",
"# round_results = run_graph_def(round_graph_def, input_map, # [output_name + \":0\"]) #",
"quantize_graph.set_attr_dtype(n, \"T\", dtypes.float32) quantize_graph.set_attr_bool(n, \"transpose_a\", False) quantize_graph.set_attr_bool(n, \"transpose_b\", False) return",
"dtype=dtypes.float32, shape=[6]) bias_add_n = quantize_graph.create_node(\"BiasAdd\", \"bias_add\", [input_n.name, offset_n.name]) quantize_graph.set_attr_dtype(bias_add_n, \"T\",",
"[a_constant_name, a_constant_min_name, a_constant_max_name]) quantize_graph.set_attr_dtype(a_dequantize_node, \"T\", dtypes.uint8) graph_def.node.extend([a_dequantize_node]) a_quantize_node = quantize_graph.create_node(",
"9, 10, 11, 12], dtype=dtypes.int32, shape=[2, 2, 3]) b =",
"[2, 4]] inputs = [] for i, shape in enumerate(shapes):",
"only one Quantize and one Requantize op. eightbit_rewriter = quantize_graph.GraphRewriter(",
"= quantize_graph.create_node(\"Relu6\", relu6_name, [input_constant_name]) quantize_graph.set_attr_dtype(relu6_node, \"T\", dtypes.float32) float_graph_def.node.extend([relu6_node]) test_graph(float_graph_def, {},",
"bias_add_n]) input_map = { input_n.name + \":0\": np.reshape([1, 2, 3,",
"we ran into in a real graph.\"\"\" test_conv(1, 4, 4,",
"= \"mat_mul\" float_graph_def = graph_pb2.GraphDef() a_constant = quantize_graph.create_constant_node( a_constant_name, value=a,",
"def test_relu(self): input_constant_name = \"input_constant\" relu_name = \"relu\" float_graph_def =",
"it will have no effect # because the FakeQuantWithMinMaxVars are",
"# TODO(petewarden): round test is currently failing because there is",
"b_constant = quantize_graph.create_constant_node( b_constant_name, value=b, dtype=dtypes.float32, shape=[k, n]) float_graph_def.node.extend([b_constant]) mat_mul_node",
"weights_rounded_results): assert are_tensors_near(expected, result, 1.0) class QuantizeGraphTest(test.TestCase): def test_negative_const_problem(self): shape_constant_name",
"self.assertEqual(len(output_names), ops.count(\"Dequantize\")) def test_bias_add_w_fake_quant_w_min_max_vars(self): input_node = quantize_graph.create_constant_node( \"input\", value=[1, 2,",
"= quantize_graph.create_node( \"BiasAdd\", \"bias_add\", [input_node.name, offset_node.name]) quantize_graph.set_attr_dtype(bias_add_node, \"T\", dtypes.float32) min_node",
"rewriter.remove_redundant_quantization(graph_def) stripped_output = graph_util.extract_sub_graph(output, [mat_mul_name]) self.assertProtoEquals(expected_output, stripped_output) if __name__ ==",
"= quantize_graph.create_constant_node( variance_constant_name, value=[0.25, 0.5], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([variance_constant]) beta_constant =",
"rewriter.rewrite(output_names) results = run_graph_def(graph_def, quantized_input_map, output_tensors) for expected, result in",
"b_constant_name, value=1, dtype=dtypes.float32, shape=[]) expected_output.node.extend([b_constant]) add_node = quantize_graph.create_node(\"Add\", add_name, [a_identity_name,",
"/ (input_range[1] - input_range[ 0]))) for n in v.flat ]",
"= \"a_dequantize\" a_quantize_name = \"a_quantize\" b_constant_name = \"b_constant\" b_constant_min_name =",
"2, 3, 4, 5, 6, 7, 8, 9, 10, 11,",
"quantize_graph.create_node(\"MatMul\", \"mat_mul\", [n.name for n in inputs]) quantize_graph.set_attr_dtype(mat_mul_node, \"T\", dtypes.float32)",
"one Quantize and one Requantize op. # Pass in fallback_quantization_range,",
"{}, [\"matmul_2\"]) # Verify there is only one Quantize and",
"b_constant = quantize_graph.create_constant_node( b_constant_name, value=1, dtype=dtypes.float32, shape=[]) expected_output.node.extend([b_constant]) add_node =",
"up-front. self.assertEqual(0, ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) # One dequantize at the",
"offset_node, bias_add_node, min_node, max_node, fake_quant_node ]) test_graph(float_graph_def, {}, [fake_quant_node.name], log_graph=True)",
"value=12, dtype=dtypes.float32, shape=[]) fake_quant_node = quantize_graph.create_node( \"FakeQuantWithMinMaxVars\", \"fake_quant\", [relu_node.name, min_node.name,",
"\"b_constant\" concat_name = \"concat\" float_graph_def = graph_pb2.GraphDef() shape_constant = quantize_graph.create_constant_node(",
"node = quantize_graph.create_node(\"Placeholder\", \"input_%s\" % i, []) quantize_graph.set_attr_dtype(node, \"dtype\", dtypes.float32)",
"4]] inputs = [] for i, shape in enumerate(shapes): node",
"5], dtype=dtypes.float32, shape=[5]) bias_add_node = quantize_graph.create_node( \"BiasAdd\", \"bias_add\", [input_node.name, offset_node.name])",
"node_names.count(\"fallback_quantization_min_value\")) self.assertEqual(1, node_names.count(\"fallback_quantization_max_value\")) def test_remove_redundant_quantization(self): a_constant_name = \"a_constant\" a_constant_min_name =",
"quantize_graph.set_attr_dtype(mat_mul_node, \"T2\", dtypes.int32) graph_def.node.extend([mat_mul_node]) expected_output = graph_pb2.GraphDef() a_constant = quantize_graph.create_constant_node(",
"variance_constant = quantize_graph.create_constant_node( variance_constant_name, value=[0.25, 0.5], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([variance_constant]) beta_constant",
"self.assertEqual(4, len(quantization_result)) def test_odd_padding_problem(self): \"\"\"Tests one error case we ran",
"19, 20, 21, 22, 23, 24], dtype=dtypes.float32, shape=[2, 2, 3])",
"19, 20, 21, 22, 23, 24], dtype=dtypes.int32, shape=[2, 2, 3])",
"0.3, 0.6, 1]) qarr = quantize_graph.quantize_array(arr, 1) self.assertTrue((np.array([0.5, 0.5, 0.5,",
"dtypes from tensorflow.python.framework import graph_util from tensorflow.python.framework import importer from",
"ok. Returns: Boolean indicating whether the two inputs were close",
"shape_constant_name, value=-0.8, dtype=dtypes.float32, shape=[1]) quantization_result = quantize_graph.quantize_weight_eightbit( shape_constant, b\"MIN_COMBINED\") self.assertEqual(4,",
"quantize_graph.quantize_array(arr, 2) self.assertEqual(arr, qarr) # Test input array with all",
"test_non_float_reshape(self): a = quantize_graph.create_constant_node( \"a\", value=[1, 2, 3, 4, 5,",
"errors. Args: a: First comparison tensor. b: Second comparison tensor.",
"{}, [max_pool_name]) def test_avg_pool(self): input_constant_name = \"input_constant\" avg_pool_name = \"avg_pool\"",
"= run_graph_def(float_graph_def, input_map, output_tensors) # Quantize treating the input as",
"value=0, dtype=dtypes.int32, shape=[]) float_graph_def.node.extend([shape_constant]) a_constant = quantize_graph.create_constant_node( a_constant_name, value=[1, 2,",
"1, 2, [1, 2], [1, 2]) def test_mat_mul_small(self): test_mat_mul(2, 4,",
"\"mean_constant\" variance_constant_name = \"variance_constant\" beta_constant_name = \"beta_constant\" gamma_constant_name = \"gamma_constant\"",
"eightbit_graph_def.node] # No quantize since all inputs are const and",
"\"\"\"Tests one error case we ran into in a real",
"============================================================================== \"\"\"Tests the graph quantization script. \"\"\" from __future__ import",
"Requantize op. # Pass in fallback_quantization_range, although it will have",
"b_constant_name = \"b_constant\" a_check_name = \"a_check\" b_check_name = \"b_check\" a_identity_name",
"FakeQuantWithMinMaxVars are used instead. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None,",
"stripped_output) def test_batch_norm(self): input_constant_name = \"input_constant\" mean_constant_name = \"mean_constant\" variance_constant_name",
"= \"a_constant_max\" a_dequantize_name = \"a_dequantize\" a_quantize_name = \"a_quantize\" b_constant_name =",
"b): n = quantize_graph.create_node(\"MatMul\", name, [a.name, b.name]) quantize_graph.set_attr_dtype(n, \"T\", dtypes.float32)",
"2], dtype=dtypes.int32, shape=[2]) reshape_node = quantize_graph.create_node( \"Reshape\", \"reshape\", [matmul_1_node.name, new_shape_node.name])",
"mean_constant_name = \"mean_constant\" variance_constant_name = \"variance_constant\" beta_constant_name = \"beta_constant\" gamma_constant_name",
"8, 9, 10, 11, 12, 13, 14, 15, 16, 17,",
"\"padding\", b\"SAME\") float_graph_def.node.extend([max_pool_node]) test_graph(float_graph_def, {}, [max_pool_name]) def test_avg_pool(self): input_constant_name =",
"for node in eightbit_graph_def.node] self.assertEqual(1, ops.count(\"QuantizedConcat\")) def test_multiple_outputs(self): input_constant_name =",
"quantize_graph.GraphRewriter(graph_pb2.GraphDef(), \"eightbit\", [0, -1]) def test_quantized_input_range_bias_add(self): input_shape = [1, 1,",
"\"b_constant_max\" b_dequantize_name = \"b_dequantize\" b_quantize_name = \"b_quantize\" mat_mul_name = \"mat_mul\"",
"a, b): n = quantize_graph.create_node(\"MatMul\", name, [a.name, b.name]) quantize_graph.set_attr_dtype(n, \"T\",",
"\"^\" + b_check_name]) graph_def.node.extend([b_identity_node]) add_node = quantize_graph.create_node(\"Add\", add_name, [a_identity_name, b_identity_name])",
"input_n.name + \":0\": np.reshape([1, 2, 3, 4, 5, 6, 7,",
"graph_def.node.extend([a_constant_min]) a_constant_max = quantize_graph.create_constant_node( a_constant_max_name, value=2, dtype=dtypes.float32, shape=[]) graph_def.node.extend([a_constant_max]) a_dequantize_node",
"2]) def test_mat_mul_small(self): test_mat_mul(2, 4, 3, [1, 2, 3, 4,",
"return n # matmul_1 = input*weight_1 input_node = quantize_graph.create_constant_node( \"input\",",
"= [node.op for node in graph_def.node] self.assertEqual(0, ops.count(\"QuantizeV2\") + ops.count(\"Quantize\"))",
"False) return n # matmul_1 = input*weight_1 input_node = quantize_graph.create_constant_node(",
"use this file except in compliance with the License. #",
"n in v.flat ] arr = np.array(arr, np.uint8) arr =",
"+= difference total_abs_difference += abs(difference) if abs(difference) > tolerance: how_many_different",
"dtypes.float32) quantize_graph.set_attr_shape(node, \"shape\", shape) inputs.append(node) mat_mul_node = quantize_graph.create_node(\"MatMul\", \"mat_mul\", [n.name",
"# Reshape 4x5 to 10x2. new_shape_node = quantize_graph.create_constant_node( \"new_shape_node\", value=[10,",
"log_graph=False): \"\"\"Runs the float graph through the rewriter and tests",
"for n in inputs]) quantize_graph.set_attr_dtype(mat_mul_node, \"T\", dtypes.float32) float_graph_def = graph_pb2.GraphDef()",
"b_constant = quantize_graph.create_constant_node( b_constant_name, value=[13, 14, 15, 16, 17, 18,",
"shape_constant_name = \"shape_constant\" shape_constant = quantize_graph.create_constant_node( shape_constant_name, value=-0.8, dtype=dtypes.float32, shape=[1])",
"6, 7, 8, 9, 10, 11, 12], dtype=dtypes.float32, shape=[2, 6])",
"the float graph through the rewriter and tests the results.\"\"\"",
"float_graph_def.node.extend([mul_node]) test_graph(float_graph_def, {}, [mul_name]) def test_keep_control_edges(self): no_op_name = \"no_op\" a_constant_name",
"[a_constant_name, \"^\" + no_op_name]) expected_output.node.extend([a_identity_node]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=1,",
"= quantize_graph.create_node(\"CheckNumerics\", a_check_name, [a_constant_name]) graph_def.node.extend([a_check_node]) a_identity_node = quantize_graph.create_node( \"Identity\", a_identity_name,",
"= eightbit_rewriter.rewrite([fake_quant_node.name]) ops = [node.op for node in eightbit_graph_def.node] node_names",
"The TensorFlow Authors. All Rights Reserved. # # Licensed under",
"9, 10, 11, 12], dtype=dtypes.float32, shape=[2, 6]) float_graph_def.node.extend([input_constant]) split_constant =",
"default bit_depth. weights_rounded_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"weights_rounded\", quantized_input_range=None) weights_rounded_graph_def =",
"ops = [node.op for node in eightbit_graph_def.node] node_names = [node.name",
"the end. self.assertEqual(1, ops.count(\"Dequantize\")) # The fallback constants are not",
"by looking at the mean and absolute average errors. Args:",
"quantize_graph.quantize_array, np.array([1, 2]), 0) # Test input array of length",
"filter_constant = quantize_graph.create_constant_node( filter_constant_name, value=filter_values, dtype=dtypes.float32, shape=[filter_size, filter_size, depth, filter_count])",
"quantize_graph.create_constant_node( beta_constant_name, value=[0.1, 0.6], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([beta_constant]) gamma_constant = quantize_graph.create_constant_node(",
"_RunTestsForQuantizedInputRange(self, float_graph_def, input_map, output_names, input_range): if sys.version_info[0] == 3: #",
"np.array([1, 2]), 0) # Test input array of length 1.",
"+ str(len(flat_a)) + \" vs \" + str(len(flat_b))) return False",
"\"BatchNormWithGlobalNormalization\", batch_norm_name, [ input_constant_name, mean_constant_name, variance_constant_name, beta_constant_name, gamma_constant_name ]) quantize_graph.set_attr_dtype(batch_norm_node,",
"graph_def.node.extend([a_constant]) a_check_node = quantize_graph.create_node(\"CheckNumerics\", a_check_name, [a_constant_name]) graph_def.node.extend([a_check_node]) a_identity_node = quantize_graph.create_node(",
"division from __future__ import print_function import sys import numpy as",
"= \"input_constant\" split_constant_name = \"split_constant\" split_name = \"split\" concat_constant_name =",
"one Requantize op, and no # RequantizationRange op. eightbit_rewriter =",
"-6], dtype=dtypes.float32, shape=[1, 1, 6, 2]) float_graph_def.node.extend([input_constant]) mean_constant = quantize_graph.create_constant_node(",
"with self.assertRaises(ValueError): # Invalid range. quantize_graph.GraphRewriter(graph_pb2.GraphDef(), \"eightbit\", [0, -1]) def",
"float_graph_def.node.extend([mean_constant]) variance_constant = quantize_graph.create_constant_node( variance_constant_name, value=[0.25, 0.5], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([variance_constant])",
"20.]) self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [bias_add_n.name], [0, 12.]) def test_quantized_input_range_mat_mul(self): shapes =",
"= \"identity\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=[1,",
"0.5], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([variance_constant]) beta_constant = quantize_graph.create_constant_node( beta_constant_name, value=[0.1, 0.6],",
"dtype=dtypes.float32, shape=[1, 5]) matmul_1_node = make_matmul(\"matmul_1\", input_node, weight_1_node) # Reshape",
"= quantize_graph.create_node(\"Add\", add_name, [a_identity_name, b_constant_name]) quantize_graph.set_attr_dtype(add_node, \"T\", dtypes.float32) expected_output.node.extend([add_node]) expected_output.versions.CopyFrom(graph_def.versions)",
"graph_pb2.GraphDef() shape_constant = quantize_graph.create_constant_node( shape_constant_name, value=0, dtype=dtypes.int32, shape=[]) float_graph_def.node.extend([shape_constant]) a_constant",
"\"Reshape\", \"reshape\", [matmul_1_node.name, new_shape_node.name]) quantize_graph.set_attr_dtype(reshape_node, \"T\", dtypes.float32) # matmul_2_node =",
"= \"beta_constant\" gamma_constant_name = \"gamma_constant\" batch_norm_name = \"batch_norm\" float_graph_def =",
"# Quantize without treating input as quantized. rewriter = quantize_graph.GraphRewriter(",
"len(quantization_result)) def test_odd_padding_problem(self): \"\"\"Tests one error case we ran into",
"None for index, value in enumerate(input_values.flatten()): if max_value is None",
"test_graph(g, {}, [\"matmul_2\"]) # Verify there is only one Quantize",
"2]), 0) # Test input array of length 1. arr",
"dtype=dtypes.int32, shape=[1]) reshape = quantize_graph.create_node(\"Reshape\", \"reshape\", [a.name, shape.name]) quantize_graph.set_attr_dtype(reshape, \"T\",",
"in compliance with the License. # You may obtain a",
"8, 9]) def test_mat_mul_tiny(self): # These tests are added to",
"software # distributed under the License is distributed on an",
"6, -1, -4, -2, -5, -3, -6], dtype=dtypes.float32, shape=[1, 1,",
"float_graph_def.node.extend([variance_constant]) beta_constant = quantize_graph.create_constant_node( beta_constant_name, value=[0.1, 0.6], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([beta_constant])",
"+ \":1\", b_dequantize_name + \":2\"]) quantize_graph.set_attr_dtype(b_quantize_node, \"T\", dtypes.uint8) graph_def.node.extend([b_quantize_node]) mat_mul_node",
"quantized_input_range=None) weights_rounded_graph_def = weights_rounded_rewriter.rewrite(output_names) weights_rounded_results = run_graph_def( weights_rounded_graph_def, input_map, [output_name",
"value=b, dtype=dtypes.float32, shape=[k, n]) float_graph_def.node.extend([b_constant]) mat_mul_node = quantize_graph.create_node(\"MatMul\", mat_mul_name, [a_constant_name,",
"min_node.name, max_node.name]) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend([ input_node, offset_node, bias_add_node, min_node,",
"21, 22, 23, 24], dtype=dtypes.int32, shape=[2, 2, 3]) concat =",
"concat_constant = quantize_graph.create_constant_node( concat_constant_name, value=1, dtype=dtypes.int32, shape=[]) float_graph_def.node.extend([concat_constant]) concat_node =",
"= round_rewriter.rewrite(output_name) # round_results = run_graph_def(round_graph_def, input_map, # [output_name +",
"= quantize_graph.create_constant_node( a_constant_min_name, value=2, dtype=dtypes.float32, shape=[]) expected_output.node.extend([a_constant_min]) a_constant_max = quantize_graph.create_constant_node(",
"# Verify there is only one Quantize and one Requantize",
"b_constant_min_name, b_constant_max_name ]) quantize_graph.set_attr_dtype(mat_mul_node, \"T1\", dtypes.uint8) quantize_graph.set_attr_dtype(mat_mul_node, \"T2\", dtypes.int32) expected_output.node.extend([mat_mul_node])",
"a_constant_name = \"a_constant\" b_constant_name = \"b_constant\" a_check_name = \"a_check\" b_check_name",
"quantization script. \"\"\" from __future__ import absolute_import from __future__ import",
"input_range): if sys.version_info[0] == 3: # uint8->quint8 conversion for numpy",
"input_map, [output_name + \":0\" for output_name in output_names]) # TODO(petewarden):",
"mul_name, [identity_name, identity_name]) quantize_graph.set_attr_dtype(mul_node, \"T\", dtypes.float32) float_graph_def.node.extend([mul_node]) test_graph(float_graph_def, {}, [mul_name])",
"11, 12], dtype=dtypes.float32, shape=[1, 2, 6, 1]) float_graph_def.node.extend([input_constant]) avg_pool_node =",
"def test_quantize_array(self): # Test invalid parameters (empty array, or 0",
"= 0 total_difference = 0 total_abs_difference = 0 for index",
"\"dtype\", dtypes.float32) quantize_graph.set_attr_shape(node, \"shape\", shape) inputs.append(node) mat_mul_node = quantize_graph.create_node(\"MatMul\", \"mat_mul\",",
"value=(0,), dtype=dtypes.quint8, shape=[]) expected_output.node.extend([b_constant]) b_constant_min = quantize_graph.create_constant_node( b_constant_min_name, value=3, dtype=dtypes.float32,",
"graph_def.node.extend([mat_mul_node]) expected_output = graph_pb2.GraphDef() a_constant = quantize_graph.create_constant_node( a_constant_name, value=(0,), dtype=dtypes.quint8,",
"14, 15, 16], [1, 2, 3, 4, 5, 6, 7,",
"6, 9]) def test_reshape(self): \"\"\"Tests that MatMul->Reshape->MatMul avoids extra quantize/dequantize.\"\"\"",
"\"Concat\", concat_name, [concat_constant_name, split_name + \":0\", split_name + \":1\"]) quantize_graph.set_attr_int(concat_node,",
"Test input array with all elements equal. arr = np.array([1,",
"# One dequantize at the end. self.assertEqual(1, ops.count(\"Dequantize\")) # The",
"dtypes.float32) float_graph_def.node.extend([bias_add_node]) test_graph(float_graph_def, {}, [bias_add_name]) def test_quantized_input_range_errors(self): with self.assertRaises(ValueError): #",
"[1, stride, stride, 1]) quantize_graph.set_attr_string(conv_node, \"padding\", padding) float_graph_def.node.extend([conv_node]) test_graph(float_graph_def, {},",
"2, 6] input_n = quantize_graph.create_node(\"Placeholder\", \"input\", []) quantize_graph.set_attr_dtype(input_n, \"dtype\", dtypes.float32)",
"[0, 12.]) def test_quantized_input_range_mat_mul(self): shapes = [[3, 2], [2, 4]]",
"self.assertEqual(1, node_names.count(\"fallback_quantization_min_value\")) self.assertEqual(1, node_names.count(\"fallback_quantization_max_value\")) def test_remove_redundant_quantization(self): a_constant_name = \"a_constant\" a_constant_min_name",
"\"eightbit\", quantized_input_range=None, fallback_quantization_range=[-100, 100]) eightbit_graph_def = eightbit_rewriter.rewrite([fake_quant_node.name]) ops = [node.op",
"4, 5, 6, 7, 8, 9, 10, 11, 12], [1,",
"\"T\", dtypes.float32) float_graph_def.node.extend([bias_add_node]) test_graph(float_graph_def, {}, [bias_add_name]) def test_quantized_input_range_errors(self): with self.assertRaises(ValueError):",
"dtype=dtypes.float32, shape=[5]) bias_add_node = quantize_graph.create_node( \"BiasAdd\", \"bias_add\", [input_node.name, offset_node.name]) quantize_graph.set_attr_dtype(bias_add_node,",
"= quantize_graph.create_node(\"NoOp\", no_op_name, []) graph_def.node.extend([no_op]) a_constant = quantize_graph.create_constant_node( a_constant_name, value=1,",
"variance_constant_name = \"variance_constant\" beta_constant_name = \"beta_constant\" gamma_constant_name = \"gamma_constant\" batch_norm_name",
"a_constant_name, value=[1, 2, 3, 4, 5, 6, 7, 8, 9,",
"max_node.name]) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend( [input_node, relu_node, min_node, max_node, fake_quant_node])",
"These tests are added to test the generate case where",
"\"offset\", value=[1, 2, 3, 4, 5], dtype=dtypes.float32, shape=[5]) bias_add_node =",
"== qarr).all()) qarr = quantize_graph.quantize_array(arr.reshape((2, 2)), 2) self.assertTrue((np.array([[0.25, 0.25], [0.75,",
"\"relu6\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=[1, 2,",
"[mat_mul_node.name], [0, 6.]) def _RunTestsForQuantizedInputRange(self, float_graph_def, input_map, output_names, input_range): if",
"22, 23, 24], dtype=dtypes.float32, shape=[2, 2, 3]) float_graph_def.node.extend([b_constant]) concat_node =",
"{3}\".format( how_many_different, proportion_different * 100, mean_difference, mean_abs_difference)) return False def",
"= quantize_graph.create_constant_node( b_constant_name, value=(0,), dtype=dtypes.quint8, shape=[]) expected_output.node.extend([b_constant]) b_constant_min = quantize_graph.create_constant_node(",
"input_constant_name = \"input_constant\" identity_name = \"identity\" float_graph_def = graph_pb2.GraphDef() input_constant",
"quantize_graph.GraphRewriter( graph_def, [mat_mul_name], quantized_input_range=None) output = rewriter.remove_redundant_quantization(graph_def) stripped_output = graph_util.extract_sub_graph(output,",
"= \"a_constant\" b_constant_name = \"b_constant\" mat_mul_name = \"mat_mul\" float_graph_def =",
"value=[1, 2, 3, 4, 5, 6], dtype=dtypes.float32, shape=[6]) bias_add_n =",
"\"T1\", dtypes.uint8) quantize_graph.set_attr_dtype(mat_mul_node, \"T2\", dtypes.int32) graph_def.node.extend([mat_mul_node]) expected_output = graph_pb2.GraphDef() a_constant",
"float_graph_def.node.extend([relu6_node]) test_graph(float_graph_def, {}, [relu6_name]) def test_bias_add(self): input_constant_name = \"input_constant\" offset_constant_name",
"2, 6, 1]) float_graph_def.node.extend([input_constant]) relu_node = quantize_graph.create_node(\"Relu\", relu_name, [input_constant_name]) quantize_graph.set_attr_dtype(relu_node,",
"input_map, [bias_add_n.name], [-1, 20.]) self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [bias_add_n.name], [0, 12.]) def",
"len(input_map), ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) self.assertEqual(len(output_names), ops.count(\"Dequantize\")) def test_bias_add_w_fake_quant_w_min_max_vars(self): input_node =",
"input_shape) } self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [bias_add_n.name], [-1, 20.]) self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [bias_add_n.name],",
"\"strides\", [1, stride, stride, 1]) quantize_graph.set_attr_string(conv_node, \"padding\", padding) float_graph_def.node.extend([conv_node]) test_graph(float_graph_def,",
"False value_count = len(flat_a) how_many_different = 0 total_difference = 0",
"dtype=dtypes.float32, shape=[1, 2, 6, 1]) float_graph_def.node.extend([input_constant]) avg_pool_node = quantize_graph.create_node(\"AvgPool\", avg_pool_name,",
"how large an error between values is ok. Returns: Boolean",
"is ok. Returns: Boolean indicating whether the two inputs were",
"float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend([ input_node, offset_node, bias_add_node, min_node, max_node, fake_quant_node",
"= total_abs_difference / value_count proportion_different = (how_many_different * 1.0) /",
"node in eightbit_graph_def.node] self.assertEqual(1, ops.count(\"QuantizedConcat\")) def test_multiple_outputs(self): input_constant_name = \"input_constant\"",
"import ops as ops_lib from tensorflow.python.platform import flags as flags_lib",
"with the License. # You may obtain a copy of",
"# Invalid mode. quantize_graph.GraphRewriter(graph_pb2.GraphDef(), \"weights_rounded\", [0, 1]) with self.assertRaises(ValueError): #",
"8, 9, 10, 11, 12], dtype=dtypes.float32, shape=[1, 1, 2, 6])",
"\"concat_dim\", value=0, dtype=dtypes.int32, shape=[]) a = quantize_graph.create_constant_node( \"a\", value=[1, 2,",
"= quantize_graph.create_node(\"MatMul\", name, [a.name, b.name]) quantize_graph.set_attr_dtype(n, \"T\", dtypes.float32) quantize_graph.set_attr_bool(n, \"transpose_a\",",
"\"shape\", value=[12], dtype=dtypes.int32, shape=[1]) reshape = quantize_graph.create_node(\"Reshape\", \"reshape\", [a.name, shape.name])",
"how_many_different, proportion_different * 100, mean_difference, mean_abs_difference)) return False def get_top_value(input_values):",
"one Requantize op. # Pass in fallback_quantization_range, although it will",
"added to test the generate case where # min(matrix) ==",
"float_graph_def.node.extend([input_constant]) split_constant = quantize_graph.create_constant_node( split_constant_name, value=1, dtype=dtypes.int32, shape=[]) float_graph_def.node.extend([split_constant]) split_node",
"input_constant_name, value=[1, 2, 3, 4, 5, 6, 7, 8, 9,",
"10, 11, 12, 13, 14, 15, 16], [1, 2, 3,",
"shape=[2, 1]) matmul_2_node = make_matmul(\"matmul_2\", reshape_node, weight_2_node) g = graph_pb2.GraphDef()",
"\"shape\", input_shape) offset_n = quantize_graph.create_constant_node( \"offset\", value=[1, 2, 3, 4,",
"} self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [mat_mul_node.name], [-1, 20.]) self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [mat_mul_node.name], [0,",
"= \"a_constant\" a_constant_min_name = \"a_constant_min\" a_constant_max_name = \"a_constant_max\" a_dequantize_name =",
"graph = ops_lib.Graph() with graph.as_default(): importer.import_graph_def(graph_def, input_map={}, name=\"\") with session.Session(graph=graph)",
"whether the two inputs were close enough. \"\"\" flat_a =",
"value=[0.1, 0.6], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([beta_constant]) gamma_constant = quantize_graph.create_constant_node( gamma_constant_name, value=[0,",
"can be quantized up-front. self.assertEqual(0, ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) self.assertEqual(1, ops.count(\"QuantizedReshape\"))",
"a_constant_min_name, a_constant_max_name]) quantize_graph.set_attr_dtype(a_dequantize_node, \"T\", dtypes.uint8) graph_def.node.extend([a_dequantize_node]) a_quantize_node = quantize_graph.create_node( \"QuantizeV2\",",
"[0, 6.]) def _RunTestsForQuantizedInputRange(self, float_graph_def, input_map, output_names, input_range): if sys.version_info[0]",
"= \"shape_constant\" a_constant_name = \"a_constant\" b_constant_name = \"b_constant\" concat_name =",
"shape_constant_name = \"shape_constant\" a_constant_name = \"a_constant\" b_constant_name = \"b_constant\" concat_name",
"\"concat\" float_graph_def = graph_pb2.GraphDef() shape_constant = quantize_graph.create_constant_node( shape_constant_name, value=0, dtype=dtypes.int32,",
"self.assertTrue((np.array([0.25, 0.25, 0.75, 0.75]) == qarr).all()) qarr = quantize_graph.quantize_array(arr.reshape((2, 2)),",
"= quantize_graph.create_node(\"Placeholder\", \"input\", []) quantize_graph.set_attr_dtype(input_n, \"dtype\", dtypes.float32) quantize_graph.set_attr_shape(input_n, \"shape\", input_shape)",
"a_quantize_name = \"a_quantize\" b_constant_name = \"b_constant\" b_constant_min_name = \"b_constant_min\" b_constant_max_name",
"mat_mul_name = \"mat_mul\" float_graph_def = graph_pb2.GraphDef() a_constant = quantize_graph.create_constant_node( a_constant_name,",
"[1], [2, 3]) test_mat_mul(1, 1, 2, [1, 1], [1, 1])",
"in fallback_quantization_range, although it will have no effect # because",
"express or implied. # See the License for the specific",
"except in compliance with the License. # You may obtain",
"The fallback constants are not in the graph. self.assertEqual(0, node_names.count(\"fallback_quantization_min_value\"))",
"graph_pb2.GraphDef() float_graph_def.node.extend([input_node, offset_node, bias_add_node]) test_graph(float_graph_def, {}, [bias_add_node.name], log_graph=True) # Verify",
"b_constant_min = quantize_graph.create_constant_node( b_constant_min_name, value=3, dtype=dtypes.float32, shape=[]) expected_output.node.extend([b_constant_min]) b_constant_max =",
"dtype=dtypes.float32, shape=[2, 6]) float_graph_def.node.extend([input_constant]) identity_node = quantize_graph.create_node(\"Identity\", identity_name, [input_constant_name]) quantize_graph.set_attr_dtype(identity_node,",
"False) quantize_graph.set_attr_bool(n, \"transpose_b\", False) return n # matmul_1 = input*weight_1",
"quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite([concat_name]) ops = [node.op",
"ops_lib from tensorflow.python.platform import flags as flags_lib from tensorflow.python.platform import",
"b_identity_name, [b_constant_name, \"^\" + b_check_name]) graph_def.node.extend([b_identity_node]) add_node = quantize_graph.create_node(\"Add\", add_name,",
"test_batch_norm(self): input_constant_name = \"input_constant\" mean_constant_name = \"mean_constant\" variance_constant_name = \"variance_constant\"",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"= quantize_graph.create_node(\"BiasAdd\", \"bias_add\", [input_n.name, offset_n.name]) quantize_graph.set_attr_dtype(bias_add_n, \"T\", dtypes.float32) float_graph_def =",
"+= 1 mean_difference = total_difference / value_count mean_abs_difference = total_abs_difference",
"filter_constant_name, value=filter_values, dtype=dtypes.float32, shape=[filter_size, filter_size, depth, filter_count]) float_graph_def.node.extend([filter_constant]) conv_node =",
"\"^\" + a_check_name, \"^\" + no_op_name]) graph_def.node.extend([a_identity_node]) b_constant = quantize_graph.create_constant_node(",
"24], dtype=dtypes.int32, shape=[2, 2, 3]) concat = quantize_graph.create_node(\"Concat\", \"concat\", [concat_dim.name,",
"\"a_identity\" b_identity_name = \"b_identity\" add_name = \"add\" graph_def = graph_pb2.GraphDef()",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"value=0, dtype=dtypes.int32, shape=[]) a = quantize_graph.create_constant_node( \"a\", value=[1, 2, 3,",
"mode. quantize_graph.GraphRewriter(graph_pb2.GraphDef(), \"weights_rounded\", [0, 1]) with self.assertRaises(ValueError): # Invalid range.",
"[]) expected_output.node.extend([no_op]) a_constant = quantize_graph.create_constant_node( a_constant_name, value=1, dtype=dtypes.float32, shape=[]) expected_output.node.extend([a_constant])",
"np.reshape([1, 2, 3, 4, 5, 6, 7, 8, 9, 10,",
"+ ops.count(\"Quantize\")) self.assertEqual(len(output_names), ops.count(\"Dequantize\")) def test_bias_add_w_fake_quant_w_min_max_vars(self): input_node = quantize_graph.create_constant_node( \"input\",",
"graph_def.node.extend([b_constant_max]) b_dequantize_node = quantize_graph.create_node( \"Dequantize\", b_dequantize_name, [b_constant_name, b_constant_min_name, b_constant_max_name]) quantize_graph.set_attr_dtype(b_dequantize_node,",
"quantize_graph.create_node(\"MatMul\", name, [a.name, b.name]) quantize_graph.set_attr_dtype(n, \"T\", dtypes.float32) quantize_graph.set_attr_bool(n, \"transpose_a\", False)",
"= \"b_constant\" concat_name = \"concat\" float_graph_def = graph_pb2.GraphDef() shape_constant =",
"= quantize_graph.quantize_array(arr, 2) self.assertTrue((np.array([0.25, 0.25, 0.75, 0.75]) == qarr).all()) qarr",
"input_node = quantize_graph.create_constant_node( \"input\", value=[0, 1, 2, 3], dtype=dtypes.float32, shape=[4,",
"12], dtype=dtypes.float32, shape=[2, 6]) float_graph_def.node.extend([input_constant]) split_constant = quantize_graph.create_constant_node( split_constant_name, value=1,",
"used to cause problems. test_mat_mul(1, 1, 1, [2], [3]) test_mat_mul(1,",
"tensorflow.python.framework import importer from tensorflow.python.framework import ops as ops_lib from",
"value=2, dtype=dtypes.float32, shape=[]) graph_def.node.extend([a_constant_max]) a_dequantize_node = quantize_graph.create_node( \"Dequantize\", a_dequantize_name, [a_constant_name,",
"\"new_shape_node\", value=[10, 2], dtype=dtypes.int32, shape=[2]) reshape_node = quantize_graph.create_node( \"Reshape\", \"reshape\",",
"expected_output.node.extend([a_constant]) a_constant_min = quantize_graph.create_constant_node( a_constant_min_name, value=2, dtype=dtypes.float32, shape=[]) expected_output.node.extend([a_constant_min]) a_constant_max",
"/ value_count mean_abs_difference = total_abs_difference / value_count proportion_different = (how_many_different",
"= run_graph_def(round_graph_def, input_map, # [output_name + \":0\"]) # assert are_tensors_near(expected,",
"the graph. self.assertEqual(0, node_names.count(\"fallback_quantization_min_value\")) self.assertEqual(0, node_names.count(\"fallback_quantization_max_value\")) def test_bias_add_w_fallback_min_max_vars(self): input_node =",
"15.5]) eightbit_graph_def = eightbit_rewriter.rewrite([bias_add_node.name]) ops = [node.op for node in",
"quantize_graph.create_constant_node( a_constant_name, value=(0,), dtype=dtypes.quint8, shape=[]) expected_output.node.extend([a_constant]) a_constant_min = quantize_graph.create_constant_node( a_constant_min_name,",
"identity_name]) quantize_graph.set_attr_dtype(mul_node, \"T\", dtypes.float32) float_graph_def.node.extend([mul_node]) test_graph(float_graph_def, {}, [mul_name]) def test_keep_control_edges(self):",
"test_graph(float_graph_def, {}, [max_pool_name]) def test_avg_pool(self): input_constant_name = \"input_constant\" avg_pool_name =",
"value=1, dtype=dtypes.int32, shape=[]) float_graph_def.node.extend([concat_constant]) concat_node = quantize_graph.create_node( \"Concat\", concat_name, [concat_constant_name,",
"= quantize_graph.create_constant_node( input_constant_name, value=input_values, dtype=dtypes.float32, shape=[image_batch_count, image_height, image_width, depth]) float_graph_def.node.extend([input_constant])",
"from tensorflow.python.framework import importer from tensorflow.python.framework import ops as ops_lib",
"\"relu\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=[1, 2,",
"b_constant_max = quantize_graph.create_constant_node( b_constant_max_name, value=3, dtype=dtypes.float32, shape=[]) graph_def.node.extend([b_constant_max]) b_dequantize_node =",
"{}, [relu6_name]) def test_bias_add(self): input_constant_name = \"input_constant\" offset_constant_name = \"offset_constant\"",
"1, [1], [2, 3]) test_mat_mul(1, 1, 2, [1, 1], [1,",
"add_name = \"add\" graph_def = graph_pb2.GraphDef() no_op = quantize_graph.create_node(\"NoOp\", no_op_name,",
"3]) float_graph_def.node.extend([b_constant]) concat_node = quantize_graph.create_node( \"Concat\", concat_name, [shape_constant_name, a_constant_name, b_constant_name])",
"make_matmul(name, a, b): n = quantize_graph.create_node(\"MatMul\", name, [a.name, b.name]) quantize_graph.set_attr_dtype(n,",
"round_graph_def = round_rewriter.rewrite(output_name) # round_results = run_graph_def(round_graph_def, input_map, # [output_name",
"dtype=dtypes.float32, shape=[]) expected_output.node.extend([a_constant_min]) a_constant_max = quantize_graph.create_constant_node( a_constant_max_name, value=2, dtype=dtypes.float32, shape=[])",
"whether two tensors are nearly identical. This is a specialized",
"[1, 2, 2, 1]) quantize_graph.set_attr_int_list(avg_pool_node, \"strides\", [1, 1, 1, 1])",
"under the License. # ============================================================================== \"\"\"Tests the graph quantization script.",
"= quantize_graph.create_node(\"MatMul\", mat_mul_name, [a_constant_name, b_constant_name]) quantize_graph.set_attr_dtype(mat_mul_node, \"T\", dtypes.float32) quantize_graph.set_attr_bool(mat_mul_node, \"transpose_a\",",
"uint8->quint8 conversion for numpy is not working currently. return quantized_input_map",
"= quantize_graph.create_constant_node( a_constant_name, value=1, dtype=dtypes.float32, shape=[]) graph_def.node.extend([a_constant]) a_check_node = quantize_graph.create_node(\"CheckNumerics\",",
"quantize_graph.create_node(\"AvgPool\", avg_pool_name, [input_constant_name]) quantize_graph.set_attr_dtype(avg_pool_node, \"T\", dtypes.float32) quantize_graph.set_attr_int_list(avg_pool_node, \"ksize\", [1, 2,",
"# [output_name + \":0\"]) # assert are_tensors_near(expected, round_results[0], 1.0) #",
"quantize_graph.create_constant_node( \"a\", value=[1, 2, 3, 4, 5, 6, 7, 8,",
"from tensorflow.python.framework import graph_util from tensorflow.python.framework import importer from tensorflow.python.framework",
"11, 12, 13, 14, 15, 16], [1, 2, 3, 4,",
"value_count = len(flat_a) how_many_different = 0 total_difference = 0 total_abs_difference",
"round_rewriter.rewrite(output_name) # round_results = run_graph_def(round_graph_def, input_map, # [output_name + \":0\"])",
"node in graph_def.node] self.assertEqual(0, ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) self.assertEqual(len(output_names), ops.count(\"Dequantize\")) #",
"2015 The TensorFlow Authors. All Rights Reserved. # # Licensed",
"= [1, 1, 2, 6] input_n = quantize_graph.create_node(\"Placeholder\", \"input\", [])",
"The fallback constants are in the graph. self.assertEqual(1, node_names.count(\"fallback_quantization_min_value\")) self.assertEqual(1,",
"[7, 8, 9, 10, 11, 12, 13, 14, 15, 16,",
"\"T\", dtypes.float32) float_graph_def.node.extend([concat_node]) test_graph(float_graph_def, {}, [concat_name]) # Verify the concat",
"Returns: Boolean indicating whether the two inputs were close enough.",
"mean and absolute average errors. Args: a: First comparison tensor.",
"a_check_name, \"^\" + no_op_name]) graph_def.node.extend([a_identity_node]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=1,",
"= quantize_graph.create_node(\"NoOp\", no_op_name, []) expected_output.node.extend([no_op]) a_constant = quantize_graph.create_constant_node( a_constant_name, value=1,",
"= quantize_graph.create_constant_node( \"offset\", value=[1, 2, 3, 4, 5], dtype=dtypes.float32, shape=[5])",
"\"BiasAdd\", \"bias_add\", [input_node.name, offset_node.name]) quantize_graph.set_attr_dtype(bias_add_node, \"T\", dtypes.float32) min_node = quantize_graph.create_constant_node(",
"b_dequantize_name + \":2\"]) quantize_graph.set_attr_dtype(b_quantize_node, \"T\", dtypes.uint8) graph_def.node.extend([b_quantize_node]) mat_mul_node = quantize_graph.create_node(\"QuantizedMatMul\",",
"test_graph(float_graph_def, {}, [concat_name]) def test_node_name_from_input(self): self.assertEqual(\"SomeName\", quantize_graph.node_name_from_input(\"^SomeName:2\")) def test_unique_node_name_from_input(self): self.assertEqual(\"__hat__SomeName__port__2\",",
"batch_norm_name = \"batch_norm\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name,",
"input*weight_1 input_node = quantize_graph.create_constant_node( \"input\", value=[0, 1, 2, 3], dtype=dtypes.float32,",
"value=(0,), dtype=dtypes.quint8, shape=[]) graph_def.node.extend([a_constant]) a_constant_min = quantize_graph.create_constant_node( a_constant_min_name, value=2, dtype=dtypes.float32,",
"concat_name = \"concat\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name,",
"\":0\": np.reshape([.8, .7, .6, .5, .4, .3, .2, .1], shapes[1])",
"dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([gamma_constant]) batch_norm_node = quantize_graph.create_node( \"BatchNormWithGlobalNormalization\", batch_norm_name, [ input_constant_name,",
"dtypes.float32) float_graph_def.node.extend([relu_node]) test_graph(float_graph_def, {}, [relu_name]) def test_relu_w_fake_quant_w_min_max_vars(self): input_node = quantize_graph.create_constant_node(",
"sess: results = sess.run(outputs, feed_dict=input_map) return results def test_mat_mul(m, n,",
"quantize_graph.create_constant_node( filter_constant_name, value=filter_values, dtype=dtypes.float32, shape=[filter_size, filter_size, depth, filter_count]) float_graph_def.node.extend([filter_constant]) conv_node",
"tolerance: Float value indicating how large an error between values",
"max_index = index return max_index, max_value def test_graph(float_graph_def, input_map, output_names,",
"mul_node = quantize_graph.create_node(\"Mul\", mul_name, [identity_name, identity_name]) quantize_graph.set_attr_dtype(mul_node, \"T\", dtypes.float32) float_graph_def.node.extend([mul_node])",
"8, 9, 10, 11, 12], dtype=dtypes.float32, shape=[2, 2, 3]) float_graph_def.node.extend([a_constant])",
"b_check_name]) graph_def.node.extend([b_identity_node]) add_node = quantize_graph.create_node(\"Add\", add_name, [a_identity_name, b_identity_name]) quantize_graph.set_attr_dtype(add_node, \"T\",",
"quantize_graph.create_node( \"FakeQuantWithMinMaxVars\", \"fake_quant\", [relu_node.name, min_node.name, max_node.name]) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend(",
"Invalid mode. quantize_graph.GraphRewriter(graph_pb2.GraphDef(), \"weights_rounded\", [0, 1]) with self.assertRaises(ValueError): # Invalid",
"attention to possible biases by looking at the mean and",
"graph_pb2.GraphDef() no_op = quantize_graph.create_node(\"NoOp\", no_op_name, []) expected_output.node.extend([no_op]) a_constant = quantize_graph.create_constant_node(",
"def test_bias_add(self): input_constant_name = \"input_constant\" offset_constant_name = \"offset_constant\" bias_add_name =",
"\"\"\" from __future__ import absolute_import from __future__ import division from",
"input_constant_name = \"input_constant\" filter_constant_name = \"filter_constant\" conv_name = \"conv\" float_graph_def",
"\" vs \" + str(len(flat_b))) return False value_count = len(flat_a)",
"= \"conv\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=input_values,",
"dtypes.float32) float_graph_def.node.extend([identity_node]) mul_name = \"mul\" mul_node = quantize_graph.create_node(\"Mul\", mul_name, [identity_name,",
"b_identity_node = quantize_graph.create_node( \"Identity\", b_identity_name, [b_constant_name, \"^\" + b_check_name]) graph_def.node.extend([b_identity_node])",
"run_graph_def( float_graph_def, input_map, [output_name + \":0\" for output_name in output_names])",
"output_tensors) # Quantize treating the input as quantized in range",
"\"beta_constant\" gamma_constant_name = \"gamma_constant\" batch_norm_name = \"batch_norm\" float_graph_def = graph_pb2.GraphDef()",
"ops.count(\"Quantize\")) self.assertEqual(1, ops.count(\"QuantizedReshape\")) # One dequantize at the end. self.assertEqual(1,",
"b_constant_name, value=1, dtype=dtypes.float32, shape=[]) graph_def.node.extend([b_constant]) b_check_node = quantize_graph.create_node(\"CheckNumerics\", b_check_name, [b_constant_name])",
"quantize_graph.set_attr_int(concat_node, \"N\", 2) quantize_graph.set_attr_dtype(concat_node, \"T\", dtypes.float32) float_graph_def.node.extend([concat_node]) test_graph(float_graph_def, {}, [concat_name])",
"# Test invalid parameters (empty array, or 0 buckets. self.assertRaises(ValueError,",
"shape_constant = quantize_graph.create_constant_node( shape_constant_name, value=-0.8, dtype=dtypes.float32, shape=[1]) quantization_result = quantize_graph.quantize_weight_eightbit(",
"[ int( round((n - input_range[0]) * 255 / (input_range[1] -",
"b_dequantize_name = \"b_dequantize\" b_quantize_name = \"b_quantize\" mat_mul_name = \"mat_mul\" graph_def",
"at the end. self.assertEqual(1, ops.count(\"Dequantize\")) # No RequantizationRange self.assertEqual(0, ops.count(\"RequantizationRange\"))",
"-1, -4, -2, -5, -3, -6], dtype=dtypes.float32, shape=[1, 1, 6,",
"index return max_index, max_value def test_graph(float_graph_def, input_map, output_names, log_graph=False): \"\"\"Runs",
"cause problems. test_mat_mul(1, 1, 1, [2], [3]) test_mat_mul(1, 2, 1,",
"shapes[0]), inputs[1].name + \":0\": np.reshape([.8, .7, .6, .5, .4, .3,",
"3, 4, 5, 6, 7, 8, 9, 10], dtype=dtypes.float32, shape=[1,",
"2, 2, 1]) quantize_graph.set_attr_int_list(avg_pool_node, \"strides\", [1, 1, 1, 1]) quantize_graph.set_attr_string(avg_pool_node,",
"b_constant = quantize_graph.create_constant_node( b_constant_name, value=(0,), dtype=dtypes.quint8, shape=[]) graph_def.node.extend([b_constant]) b_constant_min =",
"float_graph_def.node.extend([ input_node, offset_node, bias_add_node, min_node, max_node, fake_quant_node ]) test_graph(float_graph_def, {},",
"to test the generate case where # min(matrix) == max(matrix),",
"quantize_graph.create_constant_node( input_constant_name, value=[1, 4, 2, 5, 3, 6, -1, -4,",
"1]) quantize_graph.set_attr_string(conv_node, \"padding\", padding) float_graph_def.node.extend([conv_node]) test_graph(float_graph_def, {}, [conv_name]) def are_tensors_near(a,",
"def get_top_value(input_values): max_value = None max_index = None for index,",
"= quantize_graph.create_constant_node( b_constant_max_name, value=3, dtype=dtypes.float32, shape=[]) graph_def.node.extend([b_constant_max]) b_dequantize_node = quantize_graph.create_node(",
"test_graph(float_graph_def, {}, [mat_mul_name]) def test_conv(depth, image_width, image_height, image_batch_count, filter_size, filter_count,",
"= graph_pb2.GraphDef() float_graph_def.node.extend([input_node, offset_node, bias_add_node]) test_graph(float_graph_def, {}, [bias_add_node.name], log_graph=True) #",
"5, 6, 7, 8, 9, 10, 11, 12], [1, 4,",
"are_tensors_near(expected, result, .5) ops = [node.op for node in graph_def.node]",
"arr = arr.astype(dtypes.quint8.as_numpy_dtype) quantized_input_map[k] = arr output_tensors = [output_name +",
"dtype=dtypes.float32, shape=[]) graph_def.node.extend([b_constant_max]) b_dequantize_node = quantize_graph.create_node( \"Dequantize\", b_dequantize_name, [b_constant_name, b_constant_min_name,",
"quantize_graph.create_constant_node( offset_constant_name, value=[1, 2, 3, 4, 5, 6], dtype=dtypes.float32, shape=[6])",
"[bias_add_node.name], log_graph=True) # Verify there is only one Quantize, one",
"g, \"eightbit\", quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite([\"matmul_2\"]) ops = [node.op for",
"max_node = quantize_graph.create_constant_node( \"max_bias_add\", value=12, dtype=dtypes.float32, shape=[]) fake_quant_node = quantize_graph.create_node(",
"array with all elements equal. arr = np.array([1, 1, 1])",
"shape=[filter_size, filter_size, depth, filter_count]) float_graph_def.node.extend([filter_constant]) conv_node = quantize_graph.create_node( \"Conv2D\", conv_name,",
"1, [2], [3]) test_mat_mul(1, 2, 1, [1], [2, 3]) test_mat_mul(1,",
"offset_node.name]) quantize_graph.set_attr_dtype(bias_add_node, \"T\", dtypes.float32) float_graph_def = graph_pb2.GraphDef() float_graph_def.node.extend([input_node, offset_node, bias_add_node])",
"test_concat(self): shape_constant_name = \"shape_constant\" a_constant_name = \"a_constant\" b_constant_name = \"b_constant\"",
"quantize_graph.create_constant_node( \"max_bias_add\", value=15.5, dtype=dtypes.float32, shape=[]) fake_quant_node = quantize_graph.create_node( \"FakeQuantWithMinMaxVars\", \"fake_quant\",",
"dtypes.float32) min_node = quantize_graph.create_constant_node( \"min_bias_add\", value=-.5, dtype=dtypes.float32, shape=[]) max_node =",
"= eightbit_rewriter.rewrite(output_names) eightbit_results = run_graph_def( eightbit_graph_def, input_map, [output_name + \":0\"",
"quantize_graph.create_node(\"Concat\", \"concat\", [concat_dim.name, a.name, b.name]) quantize_graph.set_attr_int(concat, \"N\", 2) quantize_graph.set_attr_dtype(concat, \"T\",",
"b_constant_min = quantize_graph.create_constant_node( b_constant_min_name, value=3, dtype=dtypes.float32, shape=[]) graph_def.node.extend([b_constant_min]) b_constant_max =",
"b, concat]) test_graph(g, {}, [concat.name]) def test_non_float_reshape(self): a = quantize_graph.create_constant_node(",
"avoids extra quantize/dequantize.\"\"\" def make_matmul(name, a, b): n = quantize_graph.create_node(\"MatMul\",",
"dtypes.float32) float_graph_def.node.extend([concat_node]) test_graph(float_graph_def, {}, [concat_name]) # Verify the concat is",
"= [[3, 2], [2, 4]] inputs = [] for i,",
"# round_graph_def = round_rewriter.rewrite(output_name) # round_results = run_graph_def(round_graph_def, input_map, #",
"+ no_op_name]) expected_output.node.extend([a_identity_node]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=1, dtype=dtypes.float32, shape=[])",
"def are_tensors_near(a, b, tolerance): \"\"\"Tests whether two tensors are nearly",
"split_constant = quantize_graph.create_constant_node( split_constant_name, value=1, dtype=dtypes.int32, shape=[]) float_graph_def.node.extend([split_constant]) split_node =",
"eightbit_rewriter.rewrite(output_names) eightbit_results = run_graph_def( eightbit_graph_def, input_map, [output_name + \":0\" for",
"assert are_tensors_near(expected, result, 1.0) if log_graph: tf_logging.info(\"8bit:\\n%s\", str(eightbit_graph_def)) # Test",
"quantize_graph.set_attr_dtype(a_quantize_node, \"T\", dtypes.uint8) graph_def.node.extend([a_quantize_node]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=(0,), dtype=dtypes.quint8,",
"shape=[1, 2, 6, 1]) float_graph_def.node.extend([input_constant]) relu6_node = quantize_graph.create_node(\"Relu6\", relu6_name, [input_constant_name])",
"= quantize_graph.create_constant_node( a_constant_name, value=(0,), dtype=dtypes.quint8, shape=[]) graph_def.node.extend([a_constant]) a_constant_min = quantize_graph.create_constant_node(",
"4, 7, 2, 5, 8, 3, 6, 9]) def test_reshape(self):",
"# because the FakeQuantWithMinMaxVars are used instead. eightbit_rewriter = quantize_graph.GraphRewriter(",
"dtype=dtypes.float32, shape=[1]) quantization_result = quantize_graph.quantize_weight_eightbit( shape_constant, b\"MIN_COMBINED\") self.assertEqual(4, len(quantization_result)) def",
"= \"max_pool\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=[1,",
"tf_logging.info(\"8bit:\\n%s\", str(eightbit_graph_def)) # Test the weights_rounded mode. This uses the",
"fallback_quantization_range=[-.5, 15.5]) eightbit_graph_def = eightbit_rewriter.rewrite([bias_add_node.name]) ops = [node.op for node",
"1) self.assertTrue((np.array([0.5, 0.5, 0.5, 0.5]) == qarr).all()) qarr = quantize_graph.quantize_array(arr,",
"shape=[1, 2, 6, 1]) float_graph_def.node.extend([input_constant]) relu_node = quantize_graph.create_node(\"Relu\", relu_name, [input_constant_name])",
"1]) # The general case. test_mat_mul(1, 1, 2, [1, 2],",
"5, 6, 7, 8, 9, 10], dtype=dtypes.float32, shape=[1, 1, 2,",
"graph_def.node.extend([b_constant]) b_constant_min = quantize_graph.create_constant_node( b_constant_min_name, value=3, dtype=dtypes.float32, shape=[]) graph_def.node.extend([b_constant_min]) b_constant_max",
"make_matmul(\"matmul_2\", reshape_node, weight_2_node) g = graph_pb2.GraphDef() g.node.extend([ input_node, weight_1_node, matmul_1_node,",
"a_constant_name, value=(0,), dtype=dtypes.quint8, shape=[]) graph_def.node.extend([a_constant]) a_constant_min = quantize_graph.create_constant_node( a_constant_min_name, value=2,",
"np from tensorflow.core.framework import graph_pb2 from tensorflow.python.client import session from",
"[conv_name]) def are_tensors_near(a, b, tolerance): \"\"\"Tests whether two tensors are",
"3]) concat = quantize_graph.create_node(\"Concat\", \"concat\", [concat_dim.name, a.name, b.name]) quantize_graph.set_attr_int(concat, \"N\",",
"quantize_graph.set_attr_string(avg_pool_node, \"padding\", b\"SAME\") float_graph_def.node.extend([avg_pool_node]) test_graph(float_graph_def, {}, [avg_pool_name]) def test_relu(self): input_constant_name",
"= quantize_graph.create_node(\"QuantizedMatMul\", mat_mul_name, [ a_constant_name, b_constant_name, a_constant_min_name, a_constant_max_name, b_constant_min_name, b_constant_max_name",
"dtype=dtypes.float32, shape=[]) fake_quant_node = quantize_graph.create_node( \"FakeQuantWithMinMaxVars\", \"fake_quant\", [relu_node.name, min_node.name, max_node.name])",
"import print_function import sys import numpy as np from tensorflow.core.framework",
"float_graph_def.node.extend([filter_constant]) conv_node = quantize_graph.create_node( \"Conv2D\", conv_name, [input_constant_name, filter_constant_name]) quantize_graph.set_attr_dtype(conv_node, \"T\",",
"[mat_mul_node.name], [-1, 20.]) self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [mat_mul_node.name], [0, 6.]) def _RunTestsForQuantizedInputRange(self,",
"3: # uint8->quint8 conversion for numpy is not working currently.",
"= eightbit_rewriter.rewrite([bias_add_node.name]) ops = [node.op for node in eightbit_graph_def.node] node_names",
"11, 12], dtype=dtypes.float32, shape=[2, 6]) float_graph_def.node.extend([input_constant]) identity_node = quantize_graph.create_node(\"Identity\", identity_name,",
"graph_pb2.GraphDef() g.node.extend([ input_node, weight_1_node, matmul_1_node, new_shape_node, reshape_node, weight_2_node, matmul_2_node ])",
"0: return True else: tf_logging.info(\"Tensors have {0} different values ({1}%),",
"2, 3]) float_graph_def.node.extend([a_constant]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=[13, 14, 15,",
"quantized. rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None) graph_def = rewriter.rewrite(output_names)",
"1, 1]) quantize_graph.set_attr_string(max_pool_node, \"padding\", b\"SAME\") float_graph_def.node.extend([max_pool_node]) test_graph(float_graph_def, {}, [max_pool_name]) def",
"12], [1, 4, 7, 2, 5, 8, 3, 6, 9])",
"dtypes.float32) float_graph_def.node.extend([mul_node]) test_graph(float_graph_def, {}, [mul_name]) def test_keep_control_edges(self): no_op_name = \"no_op\"",
"replacement.\"\"\" a_constant_name = \"a_constant\" b_constant_name = \"b_constant\" mat_mul_name = \"mat_mul\"",
"1, 2, 6] input_n = quantize_graph.create_node(\"Placeholder\", \"input\", []) quantize_graph.set_attr_dtype(input_n, \"dtype\",",
"batch_norm_name, [ input_constant_name, mean_constant_name, variance_constant_name, beta_constant_name, gamma_constant_name ]) quantize_graph.set_attr_dtype(batch_norm_node, \"T\",",
"Test \"normal\" input arrays. arr = np.array([0, 0.3, 0.6, 1])",
"0.75]]) == qarr).all()) def test_non_float_concat(self): concat_dim = quantize_graph.create_constant_node( \"concat_dim\", value=0,",
"input_node, weight_1_node) # Reshape 4x5 to 10x2. new_shape_node = quantize_graph.create_constant_node(",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"= quantize_graph.create_constant_node( \"weight_1\", value=[.5, .6, .7, .8, .9], dtype=dtypes.float32, shape=[1,",
"= quantize_graph.create_node(\"Relu\", relu_name, [input_constant_name]) quantize_graph.set_attr_dtype(relu_node, \"T\", dtypes.float32) float_graph_def.node.extend([relu_node]) test_graph(float_graph_def, {},",
"def test_quantized_input_range_errors(self): with self.assertRaises(ValueError): # Invalid mode. quantize_graph.GraphRewriter(graph_pb2.GraphDef(), \"weights_rounded\", [0,",
"b = quantize_graph.create_constant_node( \"b\", value=[13, 14, 15, 16, 17, 18,",
"[a.name, shape.name]) quantize_graph.set_attr_dtype(reshape, \"T\", dtypes.int32) g = graph_pb2.GraphDef() g.node.extend([a, shape,",
"2, 5, 8, 3, 6, 9]) def test_reshape(self): \"\"\"Tests that",
"shape=[]) float_graph_def.node.extend([shape_constant]) a_constant = quantize_graph.create_constant_node( a_constant_name, value=[1, 2, 3, 4,",
"3]) float_graph_def.node.extend([a_constant]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=[13, 14, 15, 16,",
"no_op = quantize_graph.create_node(\"NoOp\", no_op_name, []) graph_def.node.extend([no_op]) a_constant = quantize_graph.create_constant_node( a_constant_name,",
"12], dtype=dtypes.float32, shape=[1, 2, 6, 1]) float_graph_def.node.extend([input_constant]) avg_pool_node = quantize_graph.create_node(\"AvgPool\",",
"value=[.5, .6, .7, .8, .9], dtype=dtypes.float32, shape=[1, 5]) matmul_1_node =",
"dequantize at the end. self.assertEqual(1, ops.count(\"Dequantize\")) def test_relu6(self): input_constant_name =",
"depth, filter_count]) float_graph_def.node.extend([filter_constant]) conv_node = quantize_graph.create_node( \"Conv2D\", conv_name, [input_constant_name, filter_constant_name])",
"dtype=dtypes.int32, shape=[2, 2, 3]) b = quantize_graph.create_constant_node( \"b\", value=[13, 14,",
"+ no_op_name]) graph_def.node.extend([a_identity_node]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=1, dtype=dtypes.float32, shape=[])",
"range. quantize_graph.GraphRewriter(graph_pb2.GraphDef(), \"eightbit\", [0, -1]) def test_quantized_input_range_bias_add(self): input_shape = [1,",
"b_constant_max_name, value=3, dtype=dtypes.float32, shape=[]) graph_def.node.extend([b_constant_max]) b_dequantize_node = quantize_graph.create_node( \"Dequantize\", b_dequantize_name,",
"* 255 / (input_range[1] - input_range[ 0]))) for n in",
"node_names = [node.name for node in eightbit_graph_def.node] # No quantize",
"= input*weight_1 input_node = quantize_graph.create_constant_node( \"input\", value=[0, 1, 2, 3],",
"]) # Test the graph test_graph(g, {}, [\"matmul_2\"]) # Verify",
"expected_output.library.CopyFrom(graph_def.library) output = graph_util.remove_training_nodes(graph_def) stripped_output = graph_util.extract_sub_graph(output, [add_name]) self.assertProtoEquals(expected_output, stripped_output)",
"8, 9, 10, 11, 12], dtype=dtypes.float32, shape=[1, 2, 6, 1])",
"graph_def.node.extend([b_dequantize_node]) b_quantize_node = quantize_graph.create_node( \"QuantizeV2\", b_quantize_name, [b_dequantize_name, b_dequantize_name + \":1\",",
"float_graph_def.node.extend([offset_constant]) bias_add_node = quantize_graph.create_node( \"BiasAdd\", bias_add_name, [input_constant_name, offset_constant_name]) quantize_graph.set_attr_dtype(bias_add_node, \"T\",",
"6]) float_graph_def.node.extend([input_constant]) identity_node = quantize_graph.create_node(\"Identity\", identity_name, [input_constant_name]) quantize_graph.set_attr_dtype(identity_node, \"T\", dtypes.float32)",
"Float value indicating how large an error between values is",
"\"no_op\" a_constant_name = \"a_constant\" b_constant_name = \"b_constant\" a_check_name = \"a_check\"",
"dtype=dtypes.float32, shape=[1, 1, 2, 5]) offset_node = quantize_graph.create_constant_node( \"offset\", value=[1,",
"test_odd_padding_problem(self): \"\"\"Tests one error case we ran into in a",
"20, 21, 22, 23, 24], dtype=dtypes.int32, shape=[2, 2, 3]) concat",
"]) quantize_graph.set_attr_dtype(mat_mul_node, \"T1\", dtypes.uint8) quantize_graph.set_attr_dtype(mat_mul_node, \"T2\", dtypes.int32) expected_output.node.extend([mat_mul_node]) expected_output.versions.CopyFrom(graph_def.versions) expected_output.library.CopyFrom(graph_def.library)",
"= quantize_graph.create_node(\"AvgPool\", avg_pool_name, [input_constant_name]) quantize_graph.set_attr_dtype(avg_pool_node, \"T\", dtypes.float32) quantize_graph.set_attr_int_list(avg_pool_node, \"ksize\", [1,",
"value=[12], dtype=dtypes.int32, shape=[1]) reshape = quantize_graph.create_node(\"Reshape\", \"reshape\", [a.name, shape.name]) quantize_graph.set_attr_dtype(reshape,",
"dtype=dtypes.float32, shape=[]) fake_quant_node = quantize_graph.create_node( \"FakeQuantWithMinMaxVars\", \"fake_quant\", [bias_add_node.name, min_node.name, max_node.name])",
"9, 10, 11, 12], [1, 4, 7, 2, 5, 8,",
"3, 4, 5, 6, 7, 8, 9, 10, 11, 12,",
"shape=[m, k]) float_graph_def.node.extend([a_constant]) b_constant = quantize_graph.create_constant_node( b_constant_name, value=b, dtype=dtypes.float32, shape=[k,",
"b\"SAME\") float_graph_def.node.extend([avg_pool_node]) test_graph(float_graph_def, {}, [avg_pool_name]) def test_relu(self): input_constant_name = \"input_constant\"",
"quantize_graph.create_constant_node( a_constant_min_name, value=2, dtype=dtypes.float32, shape=[]) graph_def.node.extend([a_constant_min]) a_constant_max = quantize_graph.create_constant_node( a_constant_max_name,",
"11, 12], dtype=dtypes.int32, shape=[2, 2, 3]) b = quantize_graph.create_constant_node( \"b\",",
"how_many_different += 1 mean_difference = total_difference / value_count mean_abs_difference =",
"13, 14, 15, 16], [1, 2, 3, 4, 5, 6,",
"5, 6, 7, 8, 9, 10, 11, 12], dtype=dtypes.float32, shape=[2,",
"12], dtype=dtypes.float32, shape=[1, 1, 2, 6]) float_graph_def.node.extend([input_constant]) offset_constant = quantize_graph.create_constant_node(",
"{}, [bias_add_name]) def test_quantized_input_range_errors(self): with self.assertRaises(ValueError): # Invalid mode. quantize_graph.GraphRewriter(graph_pb2.GraphDef(),",
"0 buckets. self.assertRaises(ValueError, quantize_graph.quantize_array, np.array([]), 2) self.assertRaises(ValueError, quantize_graph.quantize_array, np.array([1, 2]),",
".5) ops = [node.op for node in graph_def.node] self.assertEqual( len(input_map),",
"b_constant_name, a_constant_min_name, a_constant_max_name, b_constant_min_name, b_constant_max_name ]) quantize_graph.set_attr_dtype(mat_mul_node, \"T1\", dtypes.uint8) quantize_graph.set_attr_dtype(mat_mul_node,",
"value=[1.5, 2.5], dtype=dtypes.float32, shape=[2, 1]) matmul_2_node = make_matmul(\"matmul_2\", reshape_node, weight_2_node)",
"Version 2.0 (the \"License\"); # you may not use this",
"qarr).all()) qarr = quantize_graph.quantize_array(arr, 2) self.assertTrue((np.array([0.25, 0.25, 0.75, 0.75]) ==",
"{ input_n.name + \":0\": np.reshape([1, 2, 3, 4, 5, 6,",
"a.flatten() flat_b = b.flatten() if len(flat_a) != len(flat_b): tf_logging.info(\"Tensors are",
"b_value = flat_b[index] difference = a_value - b_value total_difference +=",
"{}, [bias_add_node.name], log_graph=True) # Verify there is only one Quantize,",
"= (how_many_different * 1.0) / value_count if how_many_different == 0:",
"int( round((n - input_range[0]) * 255 / (input_range[1] - input_range[",
"= quantize_graph.create_node(\"Add\", add_name, [a_identity_name, b_identity_name]) quantize_graph.set_attr_dtype(add_node, \"T\", dtypes.float32) graph_def.node.extend([add_node]) expected_output",
"9, 10, 11, 12], dtype=dtypes.int32, shape=[2, 2, 3]) shape =",
"run_graph_def( eightbit_graph_def, input_map, [output_name + \":0\" for output_name in output_names])",
"dtype=dtypes.float32, shape=[]) max_node = quantize_graph.create_constant_node( \"max_bias_add\", value=15.5, dtype=dtypes.float32, shape=[]) fake_quant_node",
"shape=[]) graph_def.node.extend([a_constant_min]) a_constant_max = quantize_graph.create_constant_node( a_constant_max_name, value=2, dtype=dtypes.float32, shape=[]) graph_def.node.extend([a_constant_max])",
"= quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None, fallback_quantization_range=[-.5, 15.5]) eightbit_graph_def = eightbit_rewriter.rewrite([bias_add_node.name])",
"2, 6, 1]) relu_node = quantize_graph.create_node(\"Relu\", \"relu\", [input_node.name]) quantize_graph.set_attr_dtype(relu_node, \"T\",",
"\"a_constant\" b_constant_name = \"b_constant\" mat_mul_name = \"mat_mul\" float_graph_def = graph_pb2.GraphDef()",
"+ ops.count(\"Quantize\")) self.assertEqual(len(output_names), ops.count(\"Dequantize\")) # Quantize without treating input as",
"a Conv replacement.\"\"\" input_constant_name = \"input_constant\" filter_constant_name = \"filter_constant\" conv_name",
"\"filter_constant\" conv_name = \"conv\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node(",
"\"batch_norm\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=[1, 4,",
"node_names.count(\"fallback_quantization_min_value\")) self.assertEqual(0, node_names.count(\"fallback_quantization_max_value\")) def test_bias_add_w_fallback_min_max_vars(self): input_node = quantize_graph.create_constant_node( \"input\", value=[1,",
"__future__ import absolute_import from __future__ import division from __future__ import",
"relu_node = quantize_graph.create_node(\"Relu\", \"relu\", [input_node.name]) quantize_graph.set_attr_dtype(relu_node, \"T\", dtypes.float32) min_node =",
"quantize_graph.create_node(\"Identity\", identity_name, [input_constant_name]) quantize_graph.set_attr_dtype(identity_node, \"T\", dtypes.float32) float_graph_def.node.extend([identity_node]) mul_name = \"mul\"",
"self.assertTrue((np.array([0.5, 0.5, 0.5, 0.5]) == qarr).all()) qarr = quantize_graph.quantize_array(arr, 2)",
"quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite([fake_quant_node.name]) ops = [node.op for node in",
"eightbit_rewriter.rewrite([\"matmul_2\"]) ops = [node.op for node in eightbit_graph_def.node] # No",
"= eightbit_rewriter.rewrite([concat_name]) ops = [node.op for node in eightbit_graph_def.node] self.assertEqual(1,",
"at the end. self.assertEqual(1, ops.count(\"Dequantize\")) def test_quantize_array(self): # Test invalid",
"= rewriter.remove_redundant_quantization(graph_def) stripped_output = graph_util.extract_sub_graph(output, [mat_mul_name]) self.assertProtoEquals(expected_output, stripped_output) if __name__",
"test_non_float_concat(self): concat_dim = quantize_graph.create_constant_node( \"concat_dim\", value=0, dtype=dtypes.int32, shape=[]) a =",
"1]) quantize_graph.set_attr_int_list(max_pool_node, \"strides\", [1, 1, 1, 1]) quantize_graph.set_attr_string(max_pool_node, \"padding\", b\"SAME\")",
"value=3, dtype=dtypes.float32, shape=[]) expected_output.node.extend([b_constant_max]) mat_mul_node = quantize_graph.create_node(\"QuantizedMatMul\", mat_mul_name, [ a_constant_name,",
"by applicable law or agreed to in writing, software #",
"str(eightbit_graph_def)) # Test the weights_rounded mode. This uses the default",
"float_graph_def.node.extend([split_node]) concat_constant = quantize_graph.create_constant_node( concat_constant_name, value=1, dtype=dtypes.int32, shape=[]) float_graph_def.node.extend([concat_constant]) concat_node",
"{}, [concat.name]) def test_non_float_reshape(self): a = quantize_graph.create_constant_node( \"a\", value=[1, 2,",
"shape) inputs.append(node) mat_mul_node = quantize_graph.create_node(\"MatMul\", \"mat_mul\", [n.name for n in",
"in output_names]) for expected, result in zip(float_results, weights_rounded_results): assert are_tensors_near(expected,",
"\":2\" ]) quantize_graph.set_attr_dtype(mat_mul_node, \"T1\", dtypes.uint8) quantize_graph.set_attr_dtype(mat_mul_node, \"T2\", dtypes.int32) graph_def.node.extend([mat_mul_node]) expected_output",
"expected_output.node.extend([b_constant_max]) mat_mul_node = quantize_graph.create_node(\"QuantizedMatMul\", mat_mul_name, [ a_constant_name, b_constant_name, a_constant_min_name, a_constant_max_name,",
"1 mean_difference = total_difference / value_count mean_abs_difference = total_abs_difference /",
"[output_name + \":0\" for output_name in output_names]) # TODO(petewarden): round",
"b_quantize_name = \"b_quantize\" mat_mul_name = \"mat_mul\" graph_def = graph_pb2.GraphDef() a_constant",
"float_graph_def.node.extend([mat_mul_node]) test_graph(float_graph_def, {}, [mat_mul_name]) def test_conv(depth, image_width, image_height, image_batch_count, filter_size,",
"[input_node.name, offset_node.name]) quantize_graph.set_attr_dtype(bias_add_node, \"T\", dtypes.float32) min_node = quantize_graph.create_constant_node( \"min_bias_add\", value=-.5,",
"conv_node = quantize_graph.create_node( \"Conv2D\", conv_name, [input_constant_name, filter_constant_name]) quantize_graph.set_attr_dtype(conv_node, \"T\", dtypes.float32)",
"\"min_bias_add\", value=0, dtype=dtypes.float32, shape=[]) max_node = quantize_graph.create_constant_node( \"max_bias_add\", value=12, dtype=dtypes.float32,",
"comparison function designed to help debug problems with quantization. It",
"2, 3, 4, 5, 6], dtype=dtypes.float32, shape=[6]) bias_add_n = quantize_graph.create_node(\"BiasAdd\",",
"quantize since all inputs are const and can be quantized",
"node in eightbit_graph_def.node] # No quantize since all inputs are",
"\"\"\" flat_a = a.flatten() flat_b = b.flatten() if len(flat_a) !=",
"weight_1_node, matmul_1_node, new_shape_node, reshape_node, weight_2_node, matmul_2_node ]) # Test the",
"a_quantize_name + \":2\", b_quantize_name + \":1\", b_quantize_name + \":2\" ])",
"expected_output.versions.CopyFrom(graph_def.versions) expected_output.library.CopyFrom(graph_def.library) rewriter = quantize_graph.GraphRewriter( graph_def, [mat_mul_name], quantized_input_range=None) output =",
"3]) shape = quantize_graph.create_constant_node( \"shape\", value=[12], dtype=dtypes.int32, shape=[1]) reshape =",
"padding) float_graph_def.node.extend([conv_node]) test_graph(float_graph_def, {}, [conv_name]) def are_tensors_near(a, b, tolerance): \"\"\"Tests",
"reshape*weight_2 weight_2_node = quantize_graph.create_constant_node( \"weight_2\", value=[1.5, 2.5], dtype=dtypes.float32, shape=[2, 1])",
"are_tensors_near(a, b, tolerance): \"\"\"Tests whether two tensors are nearly identical.",
"fallback_quantization_range, although it will have no effect # because the",
"2) quantize_graph.set_attr_dtype(split_node, \"T\", dtypes.float32) float_graph_def.node.extend([split_node]) concat_constant = quantize_graph.create_constant_node( concat_constant_name, value=1,",
"11, 12], dtype=dtypes.float32, shape=[2, 2, 3]) float_graph_def.node.extend([a_constant]) b_constant = quantize_graph.create_constant_node(",
"None max_index = None for index, value in enumerate(input_values.flatten()): if",
"# RoundToSteps op available. # round_rewriter = quantize_graph.GraphRewriter(float_graph_def, \"round\") #",
"dtypes.float32) float_graph_def.node.extend([split_node]) concat_constant = quantize_graph.create_constant_node( concat_constant_name, value=1, dtype=dtypes.int32, shape=[]) float_graph_def.node.extend([concat_constant])",
"[b_constant_name, \"^\" + b_check_name]) graph_def.node.extend([b_identity_node]) add_node = quantize_graph.create_node(\"Add\", add_name, [a_identity_name,",
"shape=[2]) float_graph_def.node.extend([mean_constant]) variance_constant = quantize_graph.create_constant_node( variance_constant_name, value=[0.25, 0.5], dtype=dtypes.float32, shape=[2])",
"quantize_graph.create_constant_node( a_constant_min_name, value=2, dtype=dtypes.float32, shape=[]) expected_output.node.extend([a_constant_min]) a_constant_max = quantize_graph.create_constant_node( a_constant_max_name,",
"flags_lib from tensorflow.python.platform import test from tensorflow.python.platform import tf_logging from",
"= run_graph_def(graph_def, quantized_input_map, output_tensors) for expected, result in zip(float_results, results):",
"value=1, dtype=dtypes.int32, shape=[]) float_graph_def.node.extend([split_constant]) split_node = quantize_graph.create_node( \"Split\", split_name, [split_constant_name,",
"value=1, dtype=dtypes.float32, shape=[]) expected_output.node.extend([b_constant]) add_node = quantize_graph.create_node(\"Add\", add_name, [a_identity_name, b_constant_name])",
"on failure, paying special attention to possible biases by looking",
"6, 7, 8, 9, 10, 11, 12], dtype=dtypes.float32, shape=[1, 2,",
"10, 11, 12], dtype=dtypes.float32, shape=[1, 2, 6, 1]) float_graph_def.node.extend([input_constant]) relu_node",
"graph_def, [mat_mul_name], quantized_input_range=None) output = rewriter.remove_redundant_quantization(graph_def) stripped_output = graph_util.extract_sub_graph(output, [mat_mul_name])",
"[max_pool_name]) def test_avg_pool(self): input_constant_name = \"input_constant\" avg_pool_name = \"avg_pool\" float_graph_def",
".9], dtype=dtypes.float32, shape=[1, 5]) matmul_1_node = make_matmul(\"matmul_1\", input_node, weight_1_node) #",
"/ value_count proportion_different = (how_many_different * 1.0) / value_count if",
"= \"b_quantize\" mat_mul_name = \"mat_mul\" graph_def = graph_pb2.GraphDef() a_constant =",
"graph_def.node.extend([b_constant_min]) b_constant_max = quantize_graph.create_constant_node( b_constant_max_name, value=3, dtype=dtypes.float32, shape=[]) graph_def.node.extend([b_constant_max]) b_dequantize_node",
"2.5], dtype=dtypes.float32, shape=[2, 1]) matmul_2_node = make_matmul(\"matmul_2\", reshape_node, weight_2_node) g",
"mat_mul_name, [ a_quantize_name, b_quantize_name, a_quantize_name + \":1\", a_quantize_name + \":2\",",
"there is no # RoundToSteps op available. # round_rewriter =",
"a_constant_min_name, value=2, dtype=dtypes.float32, shape=[]) graph_def.node.extend([a_constant_min]) a_constant_max = quantize_graph.create_constant_node( a_constant_max_name, value=2,",
"applicable law or agreed to in writing, software # distributed",
"quantize_graph.create_constant_node( \"offset\", value=[1, 2, 3, 4, 5], dtype=dtypes.float32, shape=[5]) bias_add_node",
"b_constant_max = quantize_graph.create_constant_node( b_constant_max_name, value=3, dtype=dtypes.float32, shape=[]) expected_output.node.extend([b_constant_max]) mat_mul_node =",
"graph.\"\"\" test_conv(1, 4, 4, 1, 3, 1, 2, b\"SAME\", [1,",
"ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) self.assertEqual(len(output_names), ops.count(\"Dequantize\")) def test_bias_add_w_fake_quant_w_min_max_vars(self): input_node = quantize_graph.create_constant_node(",
"1, 2, 3], dtype=dtypes.float32, shape=[4, 1]) weight_1_node = quantize_graph.create_constant_node( \"weight_1\",",
"reshape]) test_graph(g, {}, [reshape.name]) def test_concat(self): shape_constant_name = \"shape_constant\" a_constant_name",
"dtype=dtypes.float32, shape=[]) graph_def.node.extend([b_constant_min]) b_constant_max = quantize_graph.create_constant_node( b_constant_max_name, value=3, dtype=dtypes.float32, shape=[])",
"gamma_constant_name ]) quantize_graph.set_attr_dtype(batch_norm_node, \"T\", dtypes.float32) quantize_graph.set_attr_bool(batch_norm_node, \"scale_after_normalization\", False) quantize_graph.set_attr_float(batch_norm_node, \"variance_epsilon\",",
"= \"split\" concat_constant_name = \"concat_constant\" concat_name = \"concat\" float_graph_def =",
"\"split\" concat_constant_name = \"concat_constant\" concat_name = \"concat\" float_graph_def = graph_pb2.GraphDef()",
"\"eightbit\", quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite(output_names) eightbit_results = run_graph_def( eightbit_graph_def, input_map,",
"eightbit_graph_def = eightbit_rewriter.rewrite([fake_quant_node.name]) ops = [node.op for node in eightbit_graph_def.node]",
"all elements equal. arr = np.array([1, 1, 1]) qarr =",
"[2, 3]) test_mat_mul(1, 1, 2, [1, 1], [1, 1]) test_mat_mul(1,",
"from tensorflow.python.framework import ops as ops_lib from tensorflow.python.platform import flags",
"max_pool_name, [input_constant_name]) quantize_graph.set_attr_int_list(max_pool_node, \"ksize\", [1, 2, 2, 1]) quantize_graph.set_attr_int_list(max_pool_node, \"strides\",",
"[node.op for node in graph_def.node] self.assertEqual( len(input_map), ops.count(\"QuantizeV2\") + ops.count(\"Quantize\"))",
"sess.run(outputs, feed_dict=input_map) return results def test_mat_mul(m, n, k, a, b):",
"20, 21, 22, 23, 24], dtype=dtypes.float32, shape=[2, 2, 3]) float_graph_def.node.extend([b_constant])",
"float graph through the rewriter and tests the results.\"\"\" float_results",
"float_graph_def, \"eightbit\", quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite(output_names) eightbit_results = run_graph_def( eightbit_graph_def,",
"test_negative_const_problem(self): shape_constant_name = \"shape_constant\" shape_constant = quantize_graph.create_constant_node( shape_constant_name, value=-0.8, dtype=dtypes.float32,",
"8, 9, 10, 11, 12], dtype=dtypes.int32, shape=[2, 2, 3]) b",
"quantize_graph.create_node( \"Split\", split_name, [split_constant_name, input_constant_name]) quantize_graph.set_attr_int(split_node, \"num_split\", 2) quantize_graph.set_attr_dtype(split_node, \"T\",",
"= \"b_identity\" add_name = \"add\" graph_def = graph_pb2.GraphDef() no_op =",
"value=-.5, dtype=dtypes.float32, shape=[]) max_node = quantize_graph.create_constant_node( \"max_bias_add\", value=15.5, dtype=dtypes.float32, shape=[])",
"a_constant_name, value=a, dtype=dtypes.float32, shape=[m, k]) float_graph_def.node.extend([a_constant]) b_constant = quantize_graph.create_constant_node( b_constant_name,",
"# You may obtain a copy of the License at",
"value=[0.25, 0.5], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([variance_constant]) beta_constant = quantize_graph.create_constant_node( beta_constant_name, value=[0.1,",
"1, 1]) qarr = quantize_graph.quantize_array(arr, 10) self.assertTrue((np.array([1, 1, 1]) ==",
"the concat is quantized. eightbit_rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None)",
"depth]) float_graph_def.node.extend([input_constant]) filter_constant = quantize_graph.create_constant_node( filter_constant_name, value=filter_values, dtype=dtypes.float32, shape=[filter_size, filter_size,",
"offset_node = quantize_graph.create_constant_node( \"offset\", value=[1, 2, 3, 4, 5], dtype=dtypes.float32,",
"[1, 2, 3, 4, 5, 6, 7, 8, 9]) def",
"quantize_graph.set_attr_dtype(concat, \"T\", dtypes.int32) g = graph_pb2.GraphDef() g.node.extend([concat_dim, a, b, concat])",
"= graph_pb2.GraphDef() float_graph_def.node.extend([ input_node, offset_node, bias_add_node, min_node, max_node, fake_quant_node ])",
"input as quantized. rewriter = quantize_graph.GraphRewriter( float_graph_def, \"eightbit\", quantized_input_range=None) graph_def",
"constants are in the graph. self.assertEqual(1, node_names.count(\"fallback_quantization_min_value\")) self.assertEqual(1, node_names.count(\"fallback_quantization_max_value\")) def",
"= quantize_graph.create_constant_node( b_constant_min_name, value=3, dtype=dtypes.float32, shape=[]) graph_def.node.extend([b_constant_min]) b_constant_max = quantize_graph.create_constant_node(",
"= quantize_graph.create_node(\"Relu\", \"relu\", [input_node.name]) quantize_graph.set_attr_dtype(relu_node, \"T\", dtypes.float32) min_node = quantize_graph.create_constant_node(",
"test_mat_mul(m, n, k, a, b): \"\"\"Tests a MatMul replacement.\"\"\" a_constant_name",
"shape=[]) expected_output.node.extend([b_constant]) add_node = quantize_graph.create_node(\"Add\", add_name, [a_identity_name, b_constant_name]) quantize_graph.set_attr_dtype(add_node, \"T\",",
"a_check_name = \"a_check\" b_check_name = \"b_check\" a_identity_name = \"a_identity\" b_identity_name",
"return max_index, max_value def test_graph(float_graph_def, input_map, output_names, log_graph=False): \"\"\"Runs the",
"b_constant_max_name]) quantize_graph.set_attr_dtype(b_dequantize_node, \"T\", dtypes.uint8) graph_def.node.extend([b_dequantize_node]) b_quantize_node = quantize_graph.create_node( \"QuantizeV2\", b_quantize_name,",
"node_names.count(\"fallback_quantization_max_value\")) def test_bias_add_w_fallback_min_max_vars(self): input_node = quantize_graph.create_constant_node( \"input\", value=[1, 2, 3,",
"in zip(float_results, eightbit_results): assert are_tensors_near(expected, result, 1.0) if log_graph: tf_logging.info(\"8bit:\\n%s\",",
"input_constant_name]) quantize_graph.set_attr_int(split_node, \"num_split\", 2) quantize_graph.set_attr_dtype(split_node, \"T\", dtypes.float32) float_graph_def.node.extend([split_node]) concat_constant =",
"tensorflow.tools.quantization import quantize_graph flags = flags_lib FLAGS = flags.FLAGS def",
"self.assertEqual(0, ops.count(\"RequantizationRange\")) # The fallback constants are in the graph.",
"mul_name = \"mul\" mul_node = quantize_graph.create_node(\"Mul\", mul_name, [identity_name, identity_name]) quantize_graph.set_attr_dtype(mul_node,",
"= np.array([1, 1, 1]) qarr = quantize_graph.quantize_array(arr, 10) self.assertTrue((np.array([1, 1,",
"graph_pb2.GraphDef() a_constant = quantize_graph.create_constant_node( a_constant_name, value=a, dtype=dtypes.float32, shape=[m, k]) float_graph_def.node.extend([a_constant])",
"session from tensorflow.python.framework import dtypes from tensorflow.python.framework import graph_util from",
"graph_def.node.extend([b_check_node]) b_identity_node = quantize_graph.create_node( \"Identity\", b_identity_name, [b_constant_name, \"^\" + b_check_name])",
"mat_mul_name = \"mat_mul\" graph_def = graph_pb2.GraphDef() a_constant = quantize_graph.create_constant_node( a_constant_name,",
"# The general case. test_mat_mul(1, 1, 2, [1, 2], [1,",
"{}, [mul_name]) def test_keep_control_edges(self): no_op_name = \"no_op\" a_constant_name = \"a_constant\"",
"\"b_constant\" mat_mul_name = \"mat_mul\" float_graph_def = graph_pb2.GraphDef() a_constant = quantize_graph.create_constant_node(",
"shape=[]) expected_output.node.extend([a_constant]) a_identity_node = quantize_graph.create_node( \"Identity\", a_identity_name, [a_constant_name, \"^\" +",
"float_graph_def.node.extend([beta_constant]) gamma_constant = quantize_graph.create_constant_node( gamma_constant_name, value=[0, 0], dtype=dtypes.float32, shape=[2]) float_graph_def.node.extend([gamma_constant])",
"result, .5) ops = [node.op for node in graph_def.node] self.assertEqual(0,",
"graph_def = rewriter.rewrite(output_names) results = run_graph_def(graph_def, input_map, output_tensors) for expected,",
"quantize_graph.set_attr_dtype(bias_add_node, \"T\", dtypes.float32) min_node = quantize_graph.create_constant_node( \"min_bias_add\", value=-.5, dtype=dtypes.float32, shape=[])",
"gamma_constant_name = \"gamma_constant\" batch_norm_name = \"batch_norm\" float_graph_def = graph_pb2.GraphDef() input_constant",
"input as quantized in range <input_range>. rewriter = quantize_graph.GraphRewriter(float_graph_def, \"eightbit\",",
"shape.name]) quantize_graph.set_attr_dtype(reshape, \"T\", dtypes.int32) g = graph_pb2.GraphDef() g.node.extend([a, shape, reshape])",
"there is only one Quantize and one Requantize op. #",
"input_map, [output_name + \":0\" for output_name in output_names]) for expected,",
"output = graph_util.remove_training_nodes(graph_def) stripped_output = graph_util.extract_sub_graph(output, [add_name]) self.assertProtoEquals(expected_output, stripped_output) def",
"shape=[]) expected_output.node.extend([b_constant]) b_constant_min = quantize_graph.create_constant_node( b_constant_min_name, value=3, dtype=dtypes.float32, shape=[]) expected_output.node.extend([b_constant_min])",
"[concat.name]) def test_non_float_reshape(self): a = quantize_graph.create_constant_node( \"a\", value=[1, 2, 3,",
"\"input\", value=[1, 2, 3, 4, 5, 6, 7, 8, 9,",
"10, 11, 12], dtype=dtypes.float32, shape=[1, 2, 6, 1]) float_graph_def.node.extend([input_constant]) avg_pool_node",
"offset_node, bias_add_node]) test_graph(float_graph_def, {}, [bias_add_node.name], log_graph=True) # Verify there is",
"[0, 1]) with self.assertRaises(ValueError): # Invalid range. quantize_graph.GraphRewriter(graph_pb2.GraphDef(), \"eightbit\", [0,",
"= [node.name for node in eightbit_graph_def.node] # No quantize since",
"1]) float_graph_def.node.extend([input_constant]) avg_pool_node = quantize_graph.create_node(\"AvgPool\", avg_pool_name, [input_constant_name]) quantize_graph.set_attr_dtype(avg_pool_node, \"T\", dtypes.float32)",
"input_range) graph_def = rewriter.rewrite(output_names) results = run_graph_def(graph_def, quantized_input_map, output_tensors) for",
"shape=[2, 2, 3]) concat = quantize_graph.create_node(\"Concat\", \"concat\", [concat_dim.name, a.name, b.name])",
"a_identity_name, [a_constant_name, \"^\" + no_op_name]) expected_output.node.extend([a_identity_node]) b_constant = quantize_graph.create_constant_node( b_constant_name,",
"with self.assertRaises(ValueError): # Invalid mode. quantize_graph.GraphRewriter(graph_pb2.GraphDef(), \"weights_rounded\", [0, 1]) with",
"7, 8, 9, 10, 11, 12], input_shape) } self._RunTestsForQuantizedInputRange(float_graph_def, input_map,",
"\"License\"); # you may not use this file except in",
"possible biases by looking at the mean and absolute average",
"[mul_name]) def test_keep_control_edges(self): no_op_name = \"no_op\" a_constant_name = \"a_constant\" b_constant_name",
"test_unique_node_name_from_input(self): self.assertEqual(\"__hat__SomeName__port__2\", quantize_graph.unique_node_name_from_input(\"^SomeName:2\")) def test_identity(self): input_constant_name = \"input_constant\" identity_name =",
"quantize_graph.create_constant_node( \"max_bias_add\", value=12, dtype=dtypes.float32, shape=[]) fake_quant_node = quantize_graph.create_node( \"FakeQuantWithMinMaxVars\", \"fake_quant\",",
"= quantize_graph.create_constant_node( input_constant_name, value=[1, 4, 2, 5, 3, 6, -1,",
"image_width, image_height, image_batch_count, filter_size, filter_count, stride, padding, input_values, filter_values): \"\"\"Tests",
"b_constant_min_name, b_constant_max_name]) quantize_graph.set_attr_dtype(b_dequantize_node, \"T\", dtypes.uint8) graph_def.node.extend([b_dequantize_node]) b_quantize_node = quantize_graph.create_node( \"QuantizeV2\",",
"+ \":2\", b_quantize_name + \":1\", b_quantize_name + \":2\" ]) quantize_graph.set_attr_dtype(mat_mul_node,",
"float_graph_def.node.extend([input_constant]) identity_node = quantize_graph.create_node(\"Identity\", identity_name, [input_constant_name]) quantize_graph.set_attr_dtype(identity_node, \"T\", dtypes.float32) float_graph_def.node.extend([identity_node])",
"# Test input array with all elements equal. arr =",
"quantize_graph.GraphRewriter(float_graph_def, \"eightbit\", input_range) graph_def = rewriter.rewrite(output_names) results = run_graph_def(graph_def, quantized_input_map,",
"for expected, result in zip(float_results, results): assert are_tensors_near(expected, result, .5)",
"or 0 buckets. self.assertRaises(ValueError, quantize_graph.quantize_array, np.array([]), 2) self.assertRaises(ValueError, quantize_graph.quantize_array, np.array([1,",
"10) self.assertTrue((np.array([1, 1, 1]) == qarr).all()) # Test \"normal\" input",
"split_constant_name = \"split_constant\" split_name = \"split\" concat_constant_name = \"concat_constant\" concat_name",
"at the end. self.assertEqual(1, ops.count(\"Dequantize\")) # The fallback constants are",
"= 0 for index in range(value_count): a_value = flat_a[index] b_value",
"False) quantize_graph.set_attr_float(batch_norm_node, \"variance_epsilon\", 0.001) float_graph_def.node.extend([batch_norm_node]) test_graph(float_graph_def, {}, [batch_norm_name]) def test_max_pool(self):",
"dequantize at the end. self.assertEqual(1, ops.count(\"Dequantize\")) # The fallback constants",
"float_graph_def, input_map, [output_name + \":0\" for output_name in output_names]) #",
"a_constant_name, value=(0,), dtype=dtypes.quint8, shape=[]) expected_output.node.extend([a_constant]) a_constant_min = quantize_graph.create_constant_node( a_constant_min_name, value=2,",
"6, 7, 8, 9]) def test_mat_mul_tiny(self): # These tests are",
"def test_bias_add_w_fallback_min_max_vars(self): input_node = quantize_graph.create_constant_node( \"input\", value=[1, 2, 3, 4,",
"class QuantizeGraphTest(test.TestCase): def test_negative_const_problem(self): shape_constant_name = \"shape_constant\" shape_constant = quantize_graph.create_constant_node(",
"[add_name]) self.assertProtoEquals(expected_output, stripped_output) def test_batch_norm(self): input_constant_name = \"input_constant\" mean_constant_name =",
"\"eightbit\", quantized_input_range=None) eightbit_graph_def = eightbit_rewriter.rewrite([fake_quant_node.name]) ops = [node.op for node",
"tensorflow.python.framework import graph_util from tensorflow.python.framework import importer from tensorflow.python.framework import",
"quantize_graph.set_attr_dtype(reshape_node, \"T\", dtypes.float32) # matmul_2_node = reshape*weight_2 weight_2_node = quantize_graph.create_constant_node(",
"= quantize_graph.create_node(\"Identity\", identity_name, [input_constant_name]) quantize_graph.set_attr_dtype(identity_node, \"T\", dtypes.float32) float_graph_def.node.extend([identity_node]) mul_name =",
"self.assertEqual(1, ops.count(\"Dequantize\")) def test_relu6(self): input_constant_name = \"input_constant\" relu6_name = \"relu6\"",
"= rewriter.rewrite(output_names) results = run_graph_def(graph_def, quantized_input_map, output_tensors) for expected, result",
"the graph. self.assertEqual(1, node_names.count(\"fallback_quantization_min_value\")) self.assertEqual(1, node_names.count(\"fallback_quantization_max_value\")) def test_remove_redundant_quantization(self): a_constant_name =",
"b_dequantize_node = quantize_graph.create_node( \"Dequantize\", b_dequantize_name, [b_constant_name, b_constant_min_name, b_constant_max_name]) quantize_graph.set_attr_dtype(b_dequantize_node, \"T\",",
"enough. \"\"\" flat_a = a.flatten() flat_b = b.flatten() if len(flat_a)",
"= quantize_graph.create_node( \"Dequantize\", a_dequantize_name, [a_constant_name, a_constant_min_name, a_constant_max_name]) quantize_graph.set_attr_dtype(a_dequantize_node, \"T\", dtypes.uint8)",
"matmul_1_node = make_matmul(\"matmul_1\", input_node, weight_1_node) # Reshape 4x5 to 10x2.",
"= np.array(arr, np.uint8) arr = arr.reshape(v.shape) arr = arr.astype(dtypes.quint8.as_numpy_dtype) quantized_input_map[k]",
"5, 6, 7, 8, 9, 10, 11, 12], input_shape) }",
"6, 7, 8, 9, 10, 11, 12], dtype=dtypes.int32, shape=[2, 2,",
"= arr output_tensors = [output_name + \":0\" for output_name in",
"\"input_constant\" relu6_name = \"relu6\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node(",
"input_values, filter_values): \"\"\"Tests a Conv replacement.\"\"\" input_constant_name = \"input_constant\" filter_constant_name",
"value max_index = index return max_index, max_value def test_graph(float_graph_def, input_map,",
"= graph_util.extract_sub_graph(output, [add_name]) self.assertProtoEquals(expected_output, stripped_output) def test_batch_norm(self): input_constant_name = \"input_constant\"",
"1.0) # # TODO(petewarden): Add test for \"quantize\" mode. eightbit_rewriter",
"quantize_graph.create_constant_node( b_constant_min_name, value=3, dtype=dtypes.float32, shape=[]) graph_def.node.extend([b_constant_min]) b_constant_max = quantize_graph.create_constant_node( b_constant_max_name,",
"b_constant_name]) quantize_graph.set_attr_dtype(add_node, \"T\", dtypes.float32) expected_output.node.extend([add_node]) expected_output.versions.CopyFrom(graph_def.versions) expected_output.library.CopyFrom(graph_def.library) output = graph_util.remove_training_nodes(graph_def)",
"\"conv\" float_graph_def = graph_pb2.GraphDef() input_constant = quantize_graph.create_constant_node( input_constant_name, value=input_values, dtype=dtypes.float32,",
"10, 11, 12], input_shape) } self._RunTestsForQuantizedInputRange(float_graph_def, input_map, [bias_add_n.name], [-1, 20.])",
"self.assertEqual(0, ops.count(\"QuantizeV2\") + ops.count(\"Quantize\")) self.assertEqual(1, ops.count(\"QuantizedReshape\")) # One dequantize at",
"quantize_graph.create_constant_node( b_constant_name, value=[13, 14, 15, 16, 17, 18, 19, 20,",
"quantize_graph.set_attr_dtype(add_node, \"T\", dtypes.float32) expected_output.node.extend([add_node]) expected_output.versions.CopyFrom(graph_def.versions) expected_output.library.CopyFrom(graph_def.library) output = graph_util.remove_training_nodes(graph_def) stripped_output",
"arr.reshape(v.shape) arr = arr.astype(dtypes.quint8.as_numpy_dtype) quantized_input_map[k] = arr output_tensors = [output_name",
"for index in range(value_count): a_value = flat_a[index] b_value = flat_b[index]",
"def make_matmul(name, a, b): n = quantize_graph.create_node(\"MatMul\", name, [a.name, b.name])",
"[input_constant_name]) quantize_graph.set_attr_dtype(identity_node, \"T\", dtypes.float32) float_graph_def.node.extend([identity_node]) mul_name = \"mul\" mul_node ="
] |
[
"models.CharField(choices=[('private', 'Private'), ('public', 'Public')], default='private', max_length=10)), ('visible_on_geoportal', models.BooleanField(default=False)), ('shapetype', models.CharField(blank=True,",
"('service_path', models.CharField(max_length=255)), ('cache_time', models.IntegerField(blank=True, null=True)), ('last_fetch_on', models.DateField(blank=True, null=True)), ('category', models.ForeignKey(blank=True,",
"('giscube', '0002_update'), ] operations = [ migrations.CreateModel( name='GeoJsonLayer', fields=[ ('id',",
"coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-04-26",
"max_length=18, null=True)), ('fill_opacity', models.DecimalField(blank=True, decimal_places=1, default=1, max_digits=2, null=True)), ('url', models.CharField(blank=True,",
"max_length=100, null=True)), ('data_file', models.FileField(blank=True, null=True, upload_to=giscube.utils.unique_service_directory)), ('service_path', models.CharField(max_length=255)), ('cache_time', models.IntegerField(blank=True,",
"max_length=18, null=True)), ('stroke_width', models.IntegerField(blank=True, default=1, null=True)), ('stroke_dash_array', models.CharField(blank=True, default='', max_length=25,",
"django.db.models.deletion import giscube.utils class Migration(migrations.Migration): initial = True dependencies =",
"models.CharField(blank=True, choices=[('marker', 'Marker'), ('line', 'Line'), ('polygon', 'Polygon'), ('Circle', 'Circle')], max_length=20,",
"('stroke_color', colorfield.fields.ColorField(blank=True, default=b'#FF3333', max_length=18, null=True)), ('stroke_width', models.IntegerField(blank=True, default=1, null=True)), ('stroke_dash_array',",
"models.DecimalField(blank=True, decimal_places=1, default=1, max_digits=2, null=True)), ('url', models.CharField(blank=True, max_length=100, null=True)), ('data_file',",
"-*- coding: utf-8 -*- # Generated by Django 1.11.10 on",
"null=True)), ('fill_opacity', models.DecimalField(blank=True, decimal_places=1, default=1, max_digits=2, null=True)), ('url', models.CharField(blank=True, max_length=100,",
"null=True)), ('description', models.TextField(blank=True, null=True)), ('keywords', models.CharField(blank=True, max_length=200, null=True)), ('active', models.BooleanField(default=True)),",
"on 2018-04-26 09:14 import colorfield.fields from django.db import migrations, models",
"('fill_color', colorfield.fields.ColorField(blank=True, default=b'#FFC300', max_length=18, null=True)), ('fill_opacity', models.DecimalField(blank=True, decimal_places=1, default=1, max_digits=2,",
"migrations.CreateModel( name='GeoJsonLayer', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50,",
"null=True)), ('shape_radius', models.IntegerField(blank=True, null=True)), ('stroke_color', colorfield.fields.ColorField(blank=True, default=b'#FF3333', max_length=18, null=True)), ('stroke_width',",
"null=True)), ('stroke_dash_array', models.CharField(blank=True, default='', max_length=25, null=True)), ('fill_color', colorfield.fields.ColorField(blank=True, default=b'#FFC300', max_length=18,",
"models.CharField(blank=True, max_length=100, null=True)), ('data_file', models.FileField(blank=True, null=True, upload_to=giscube.utils.unique_service_directory)), ('service_path', models.CharField(max_length=255)), ('cache_time',",
"models.IntegerField(blank=True, default=1, null=True)), ('stroke_dash_array', models.CharField(blank=True, default='', max_length=25, null=True)), ('fill_color', colorfield.fields.ColorField(blank=True,",
"('shape_radius', models.IntegerField(blank=True, null=True)), ('stroke_color', colorfield.fields.ColorField(blank=True, default=b'#FF3333', max_length=18, null=True)), ('stroke_width', models.IntegerField(blank=True,",
"('last_fetch_on', models.DateField(blank=True, null=True)), ('category', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='giscube.Category')), ], options={",
"= [ ('giscube', '0002_update'), ] operations = [ migrations.CreateModel( name='GeoJsonLayer',",
"= [ migrations.CreateModel( name='GeoJsonLayer', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"models.CharField(max_length=50, unique=True)), ('title', models.CharField(blank=True, max_length=100, null=True)), ('description', models.TextField(blank=True, null=True)), ('keywords',",
"colorfield.fields.ColorField(blank=True, default=b'#FF3333', max_length=18, null=True)), ('stroke_width', models.IntegerField(blank=True, default=1, null=True)), ('stroke_dash_array', models.CharField(blank=True,",
"max_length=25, null=True)), ('fill_color', colorfield.fields.ColorField(blank=True, default=b'#FFC300', max_length=18, null=True)), ('fill_opacity', models.DecimalField(blank=True, decimal_places=1,",
"'Marker'), ('line', 'Line'), ('polygon', 'Polygon'), ('Circle', 'Circle')], max_length=20, null=True)), ('shape_radius',",
"class Migration(migrations.Migration): initial = True dependencies = [ ('giscube', '0002_update'),",
"models.BooleanField(default=False)), ('shapetype', models.CharField(blank=True, choices=[('marker', 'Marker'), ('line', 'Line'), ('polygon', 'Polygon'), ('Circle',",
"('name', models.CharField(max_length=50, unique=True)), ('title', models.CharField(blank=True, max_length=100, null=True)), ('description', models.TextField(blank=True, null=True)),",
"('category', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='giscube.Category')), ], options={ 'verbose_name': 'GeoJSONLayer', 'verbose_name_plural':",
"2018-04-26 09:14 import colorfield.fields from django.db import migrations, models import",
"models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='giscube.Category')), ], options={ 'verbose_name': 'GeoJSONLayer', 'verbose_name_plural': 'GeoJSONLayers',",
"serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50, unique=True)), ('title', models.CharField(blank=True, max_length=100, null=True)), ('description',",
"-*- # Generated by Django 1.11.10 on 2018-04-26 09:14 import",
"'Line'), ('polygon', 'Polygon'), ('Circle', 'Circle')], max_length=20, null=True)), ('shape_radius', models.IntegerField(blank=True, null=True)),",
"('line', 'Line'), ('polygon', 'Polygon'), ('Circle', 'Circle')], max_length=20, null=True)), ('shape_radius', models.IntegerField(blank=True,",
"default='private', max_length=10)), ('visible_on_geoportal', models.BooleanField(default=False)), ('shapetype', models.CharField(blank=True, choices=[('marker', 'Marker'), ('line', 'Line'),",
"default=b'#FFC300', max_length=18, null=True)), ('fill_opacity', models.DecimalField(blank=True, decimal_places=1, default=1, max_digits=2, null=True)), ('url',",
"django.db import migrations, models import django.db.models.deletion import giscube.utils class Migration(migrations.Migration):",
"('fill_opacity', models.DecimalField(blank=True, decimal_places=1, default=1, max_digits=2, null=True)), ('url', models.CharField(blank=True, max_length=100, null=True)),",
"Generated by Django 1.11.10 on 2018-04-26 09:14 import colorfield.fields from",
"('cache_time', models.IntegerField(blank=True, null=True)), ('last_fetch_on', models.DateField(blank=True, null=True)), ('category', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL,",
"('stroke_width', models.IntegerField(blank=True, default=1, null=True)), ('stroke_dash_array', models.CharField(blank=True, default='', max_length=25, null=True)), ('fill_color',",
"default='', max_length=25, null=True)), ('fill_color', colorfield.fields.ColorField(blank=True, default=b'#FFC300', max_length=18, null=True)), ('fill_opacity', models.DecimalField(blank=True,",
"initial = True dependencies = [ ('giscube', '0002_update'), ] operations",
"import migrations, models import django.db.models.deletion import giscube.utils class Migration(migrations.Migration): initial",
"null=True)), ('stroke_width', models.IntegerField(blank=True, default=1, null=True)), ('stroke_dash_array', models.CharField(blank=True, default='', max_length=25, null=True)),",
"models.CharField(blank=True, max_length=200, null=True)), ('active', models.BooleanField(default=True)), ('visibility', models.CharField(choices=[('private', 'Private'), ('public', 'Public')],",
"null=True, on_delete=django.db.models.deletion.SET_NULL, to='giscube.Category')), ], options={ 'verbose_name': 'GeoJSONLayer', 'verbose_name_plural': 'GeoJSONLayers', },",
"max_length=100, null=True)), ('description', models.TextField(blank=True, null=True)), ('keywords', models.CharField(blank=True, max_length=200, null=True)), ('active',",
"09:14 import colorfield.fields from django.db import migrations, models import django.db.models.deletion",
"by Django 1.11.10 on 2018-04-26 09:14 import colorfield.fields from django.db",
"models.BooleanField(default=True)), ('visibility', models.CharField(choices=[('private', 'Private'), ('public', 'Public')], default='private', max_length=10)), ('visible_on_geoportal', models.BooleanField(default=False)),",
"('Circle', 'Circle')], max_length=20, null=True)), ('shape_radius', models.IntegerField(blank=True, null=True)), ('stroke_color', colorfield.fields.ColorField(blank=True, default=b'#FF3333',",
"default=1, null=True)), ('stroke_dash_array', models.CharField(blank=True, default='', max_length=25, null=True)), ('fill_color', colorfield.fields.ColorField(blank=True, default=b'#FFC300',",
"models.TextField(blank=True, null=True)), ('keywords', models.CharField(blank=True, max_length=200, null=True)), ('active', models.BooleanField(default=True)), ('visibility', models.CharField(choices=[('private',",
"models.IntegerField(blank=True, null=True)), ('last_fetch_on', models.DateField(blank=True, null=True)), ('category', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='giscube.Category')),",
"import django.db.models.deletion import giscube.utils class Migration(migrations.Migration): initial = True dependencies",
"# -*- coding: utf-8 -*- # Generated by Django 1.11.10",
"default=1, max_digits=2, null=True)), ('url', models.CharField(blank=True, max_length=100, null=True)), ('data_file', models.FileField(blank=True, null=True,",
"[ migrations.CreateModel( name='GeoJsonLayer', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name',",
"null=True, upload_to=giscube.utils.unique_service_directory)), ('service_path', models.CharField(max_length=255)), ('cache_time', models.IntegerField(blank=True, null=True)), ('last_fetch_on', models.DateField(blank=True, null=True)),",
"null=True)), ('category', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='giscube.Category')), ], options={ 'verbose_name': 'GeoJSONLayer',",
"models.CharField(blank=True, max_length=100, null=True)), ('description', models.TextField(blank=True, null=True)), ('keywords', models.CharField(blank=True, max_length=200, null=True)),",
"null=True)), ('url', models.CharField(blank=True, max_length=100, null=True)), ('data_file', models.FileField(blank=True, null=True, upload_to=giscube.utils.unique_service_directory)), ('service_path',",
"unique=True)), ('title', models.CharField(blank=True, max_length=100, null=True)), ('description', models.TextField(blank=True, null=True)), ('keywords', models.CharField(blank=True,",
"('visibility', models.CharField(choices=[('private', 'Private'), ('public', 'Public')], default='private', max_length=10)), ('visible_on_geoportal', models.BooleanField(default=False)), ('shapetype',",
"upload_to=giscube.utils.unique_service_directory)), ('service_path', models.CharField(max_length=255)), ('cache_time', models.IntegerField(blank=True, null=True)), ('last_fetch_on', models.DateField(blank=True, null=True)), ('category',",
"models.DateField(blank=True, null=True)), ('category', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='giscube.Category')), ], options={ 'verbose_name':",
"giscube.utils class Migration(migrations.Migration): initial = True dependencies = [ ('giscube',",
"'0002_update'), ] operations = [ migrations.CreateModel( name='GeoJsonLayer', fields=[ ('id', models.AutoField(auto_created=True,",
"[ ('giscube', '0002_update'), ] operations = [ migrations.CreateModel( name='GeoJsonLayer', fields=[",
"max_length=200, null=True)), ('active', models.BooleanField(default=True)), ('visibility', models.CharField(choices=[('private', 'Private'), ('public', 'Public')], default='private',",
"('keywords', models.CharField(blank=True, max_length=200, null=True)), ('active', models.BooleanField(default=True)), ('visibility', models.CharField(choices=[('private', 'Private'), ('public',",
"max_digits=2, null=True)), ('url', models.CharField(blank=True, max_length=100, null=True)), ('data_file', models.FileField(blank=True, null=True, upload_to=giscube.utils.unique_service_directory)),",
"to='giscube.Category')), ], options={ 'verbose_name': 'GeoJSONLayer', 'verbose_name_plural': 'GeoJSONLayers', }, ), ]",
"] operations = [ migrations.CreateModel( name='GeoJsonLayer', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"'Private'), ('public', 'Public')], default='private', max_length=10)), ('visible_on_geoportal', models.BooleanField(default=False)), ('shapetype', models.CharField(blank=True, choices=[('marker',",
"('active', models.BooleanField(default=True)), ('visibility', models.CharField(choices=[('private', 'Private'), ('public', 'Public')], default='private', max_length=10)), ('visible_on_geoportal',",
"decimal_places=1, default=1, max_digits=2, null=True)), ('url', models.CharField(blank=True, max_length=100, null=True)), ('data_file', models.FileField(blank=True,",
"Migration(migrations.Migration): initial = True dependencies = [ ('giscube', '0002_update'), ]",
"('stroke_dash_array', models.CharField(blank=True, default='', max_length=25, null=True)), ('fill_color', colorfield.fields.ColorField(blank=True, default=b'#FFC300', max_length=18, null=True)),",
"dependencies = [ ('giscube', '0002_update'), ] operations = [ migrations.CreateModel(",
"verbose_name='ID')), ('name', models.CharField(max_length=50, unique=True)), ('title', models.CharField(blank=True, max_length=100, null=True)), ('description', models.TextField(blank=True,",
"null=True)), ('fill_color', colorfield.fields.ColorField(blank=True, default=b'#FFC300', max_length=18, null=True)), ('fill_opacity', models.DecimalField(blank=True, decimal_places=1, default=1,",
"import colorfield.fields from django.db import migrations, models import django.db.models.deletion import",
"null=True)), ('stroke_color', colorfield.fields.ColorField(blank=True, default=b'#FF3333', max_length=18, null=True)), ('stroke_width', models.IntegerField(blank=True, default=1, null=True)),",
"('url', models.CharField(blank=True, max_length=100, null=True)), ('data_file', models.FileField(blank=True, null=True, upload_to=giscube.utils.unique_service_directory)), ('service_path', models.CharField(max_length=255)),",
"models.FileField(blank=True, null=True, upload_to=giscube.utils.unique_service_directory)), ('service_path', models.CharField(max_length=255)), ('cache_time', models.IntegerField(blank=True, null=True)), ('last_fetch_on', models.DateField(blank=True,",
"primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50, unique=True)), ('title', models.CharField(blank=True, max_length=100, null=True)),",
"models import django.db.models.deletion import giscube.utils class Migration(migrations.Migration): initial = True",
"colorfield.fields from django.db import migrations, models import django.db.models.deletion import giscube.utils",
"models.CharField(max_length=255)), ('cache_time', models.IntegerField(blank=True, null=True)), ('last_fetch_on', models.DateField(blank=True, null=True)), ('category', models.ForeignKey(blank=True, null=True,",
"'Polygon'), ('Circle', 'Circle')], max_length=20, null=True)), ('shape_radius', models.IntegerField(blank=True, null=True)), ('stroke_color', colorfield.fields.ColorField(blank=True,",
"from django.db import migrations, models import django.db.models.deletion import giscube.utils class",
"operations = [ migrations.CreateModel( name='GeoJsonLayer', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"models.CharField(blank=True, default='', max_length=25, null=True)), ('fill_color', colorfield.fields.ColorField(blank=True, default=b'#FFC300', max_length=18, null=True)), ('fill_opacity',",
"1.11.10 on 2018-04-26 09:14 import colorfield.fields from django.db import migrations,",
"max_length=10)), ('visible_on_geoportal', models.BooleanField(default=False)), ('shapetype', models.CharField(blank=True, choices=[('marker', 'Marker'), ('line', 'Line'), ('polygon',",
"migrations, models import django.db.models.deletion import giscube.utils class Migration(migrations.Migration): initial =",
"models.IntegerField(blank=True, null=True)), ('stroke_color', colorfield.fields.ColorField(blank=True, default=b'#FF3333', max_length=18, null=True)), ('stroke_width', models.IntegerField(blank=True, default=1,",
"on_delete=django.db.models.deletion.SET_NULL, to='giscube.Category')), ], options={ 'verbose_name': 'GeoJSONLayer', 'verbose_name_plural': 'GeoJSONLayers', }, ),",
"Django 1.11.10 on 2018-04-26 09:14 import colorfield.fields from django.db import",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50, unique=True)), ('title', models.CharField(blank=True,",
"True dependencies = [ ('giscube', '0002_update'), ] operations = [",
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50, unique=True)), ('title',",
"('data_file', models.FileField(blank=True, null=True, upload_to=giscube.utils.unique_service_directory)), ('service_path', models.CharField(max_length=255)), ('cache_time', models.IntegerField(blank=True, null=True)), ('last_fetch_on',",
"= True dependencies = [ ('giscube', '0002_update'), ] operations =",
"null=True)), ('active', models.BooleanField(default=True)), ('visibility', models.CharField(choices=[('private', 'Private'), ('public', 'Public')], default='private', max_length=10)),",
"'Public')], default='private', max_length=10)), ('visible_on_geoportal', models.BooleanField(default=False)), ('shapetype', models.CharField(blank=True, choices=[('marker', 'Marker'), ('line',",
"'Circle')], max_length=20, null=True)), ('shape_radius', models.IntegerField(blank=True, null=True)), ('stroke_color', colorfield.fields.ColorField(blank=True, default=b'#FF3333', max_length=18,",
"('description', models.TextField(blank=True, null=True)), ('keywords', models.CharField(blank=True, max_length=200, null=True)), ('active', models.BooleanField(default=True)), ('visibility',",
"colorfield.fields.ColorField(blank=True, default=b'#FFC300', max_length=18, null=True)), ('fill_opacity', models.DecimalField(blank=True, decimal_places=1, default=1, max_digits=2, null=True)),",
"('public', 'Public')], default='private', max_length=10)), ('visible_on_geoportal', models.BooleanField(default=False)), ('shapetype', models.CharField(blank=True, choices=[('marker', 'Marker'),",
"('title', models.CharField(blank=True, max_length=100, null=True)), ('description', models.TextField(blank=True, null=True)), ('keywords', models.CharField(blank=True, max_length=200,",
"null=True)), ('keywords', models.CharField(blank=True, max_length=200, null=True)), ('active', models.BooleanField(default=True)), ('visibility', models.CharField(choices=[('private', 'Private'),",
"name='GeoJsonLayer', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50, unique=True)),",
"('polygon', 'Polygon'), ('Circle', 'Circle')], max_length=20, null=True)), ('shape_radius', models.IntegerField(blank=True, null=True)), ('stroke_color',",
"choices=[('marker', 'Marker'), ('line', 'Line'), ('polygon', 'Polygon'), ('Circle', 'Circle')], max_length=20, null=True)),",
"max_length=20, null=True)), ('shape_radius', models.IntegerField(blank=True, null=True)), ('stroke_color', colorfield.fields.ColorField(blank=True, default=b'#FF3333', max_length=18, null=True)),",
"import giscube.utils class Migration(migrations.Migration): initial = True dependencies = [",
"null=True)), ('data_file', models.FileField(blank=True, null=True, upload_to=giscube.utils.unique_service_directory)), ('service_path', models.CharField(max_length=255)), ('cache_time', models.IntegerField(blank=True, null=True)),",
"('shapetype', models.CharField(blank=True, choices=[('marker', 'Marker'), ('line', 'Line'), ('polygon', 'Polygon'), ('Circle', 'Circle')],",
"# Generated by Django 1.11.10 on 2018-04-26 09:14 import colorfield.fields",
"models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50, unique=True)), ('title', models.CharField(blank=True, max_length=100,",
"null=True)), ('last_fetch_on', models.DateField(blank=True, null=True)), ('category', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='giscube.Category')), ],",
"default=b'#FF3333', max_length=18, null=True)), ('stroke_width', models.IntegerField(blank=True, default=1, null=True)), ('stroke_dash_array', models.CharField(blank=True, default='',",
"('visible_on_geoportal', models.BooleanField(default=False)), ('shapetype', models.CharField(blank=True, choices=[('marker', 'Marker'), ('line', 'Line'), ('polygon', 'Polygon'),",
"utf-8 -*- # Generated by Django 1.11.10 on 2018-04-26 09:14"
] |
[
"<- Leave it empty if you dont want one watermarksize",
"True # <- Display the Set of the Item raritytext",
"{ \"BannerToken\": True, \"AthenaBackpack\": True, \"AthenaPetCarrier\": True, \"AthenaPet\": True, \"AthenaPickaxe\":",
"the Item raritytext = True # <- Display the Rarity",
"True, \"AthenaItemWrap\": True } interval = 5 # <- Time",
"Display the Rarity of the Item typeconfig = { \"BannerToken\":",
"Time (in seconds) until the bot checks for leaks again",
"\"AthenaPetCarrier\": True, \"AthenaPet\": True, \"AthenaPickaxe\": True, \"AthenaCharacter\": True, \"AthenaSkyDiveContrail\": True,",
"# <- Display the Set of the Item raritytext =",
"True, \"AthenaSpray\": True, \"AthenaToy\": True, \"AthenaBattleBus\": True, \"AthenaItemWrap\": True }",
"\"\" # <- Leave it empty if you dont want",
"= \"en\" # <- language code displayset = True #",
"raritytext = True # <- Display the Rarity of the",
"be a Image URL!!! lang = \"en\" # <- language",
"True, \"AthenaPet\": True, \"AthenaPickaxe\": True, \"AthenaCharacter\": True, \"AthenaSkyDiveContrail\": True, \"AthenaGlider\":",
"Image URL!!! lang = \"en\" # <- language code displayset",
"leaks again | Recommend: 7 watermark = \"\" # <-",
"= True # <- Display the Set of the Item",
"True, \"AthenaLoadingScreen\": True, \"AthenaMusicPack\": True, \"AthenaSpray\": True, \"AthenaToy\": True, \"AthenaBattleBus\":",
"Item raritytext = True # <- Display the Rarity of",
"True, \"AthenaCharacter\": True, \"AthenaSkyDiveContrail\": True, \"AthenaGlider\": True, \"AthenaDance\": True, \"AthenaEmoji\":",
"= True # <- Display the Rarity of the Item",
"Item typeconfig = { \"BannerToken\": True, \"AthenaBackpack\": True, \"AthenaPetCarrier\": True,",
"\"AthenaSkyDiveContrail\": True, \"AthenaGlider\": True, \"AthenaDance\": True, \"AthenaEmoji\": True, \"AthenaLoadingScreen\": True,",
"the Item typeconfig = { \"BannerToken\": True, \"AthenaBackpack\": True, \"AthenaPetCarrier\":",
"for leaks again | Recommend: 7 watermark = \"\" #",
"True } interval = 5 # <- Time (in seconds)",
"= 5 # <- Time (in seconds) until the bot",
"# <- language code displayset = True # <- Display",
"True, \"AthenaPickaxe\": True, \"AthenaCharacter\": True, \"AthenaSkyDiveContrail\": True, \"AthenaGlider\": True, \"AthenaDance\":",
"\"AthenaDance\": True, \"AthenaEmoji\": True, \"AthenaLoadingScreen\": True, \"AthenaMusicPack\": True, \"AthenaSpray\": True,",
"# <- Need to be a Image URL!!! lang =",
"the Rarity of the Item typeconfig = { \"BannerToken\": True,",
"bot checks for leaks again | Recommend: 7 watermark =",
"True # <- Display the Rarity of the Item typeconfig",
"# <- Display the Rarity of the Item typeconfig =",
"| Recommend: 7 watermark = \"\" # <- Leave it",
"} interval = 5 # <- Time (in seconds) until",
"you dont want one watermarksize = 25 # <- Size",
"<- Time (in seconds) until the bot checks for leaks",
"\"AthenaEmoji\": True, \"AthenaLoadingScreen\": True, \"AthenaMusicPack\": True, \"AthenaSpray\": True, \"AthenaToy\": True,",
"to be a Image URL!!! lang = \"en\" # <-",
"code displayset = True # <- Display the Set of",
"interval = 5 # <- Time (in seconds) until the",
"True, \"AthenaBattleBus\": True, \"AthenaItemWrap\": True } interval = 5 #",
"\"BannerToken\": True, \"AthenaBackpack\": True, \"AthenaPetCarrier\": True, \"AthenaPet\": True, \"AthenaPickaxe\": True,",
"\"AthenaGlider\": True, \"AthenaDance\": True, \"AthenaEmoji\": True, \"AthenaLoadingScreen\": True, \"AthenaMusicPack\": True,",
"one watermarksize = 25 # <- Size of the Watermark",
"Need to be a Image URL!!! lang = \"en\" #",
"7 watermark = \"\" # <- Leave it empty if",
"# <- Time (in seconds) until the bot checks for",
"of the Item raritytext = True # <- Display the",
"displayset = True # <- Display the Set of the",
"of the Item typeconfig = { \"BannerToken\": True, \"AthenaBackpack\": True,",
"Set of the Item raritytext = True # <- Display",
"True, \"AthenaSkyDiveContrail\": True, \"AthenaGlider\": True, \"AthenaDance\": True, \"AthenaEmoji\": True, \"AthenaLoadingScreen\":",
"True, \"AthenaMusicPack\": True, \"AthenaSpray\": True, \"AthenaToy\": True, \"AthenaBattleBus\": True, \"AthenaItemWrap\":",
"(in seconds) until the bot checks for leaks again |",
"True, \"AthenaDance\": True, \"AthenaEmoji\": True, \"AthenaLoadingScreen\": True, \"AthenaMusicPack\": True, \"AthenaSpray\":",
"Rarity of the Item typeconfig = { \"BannerToken\": True, \"AthenaBackpack\":",
"until the bot checks for leaks again | Recommend: 7",
"\"AthenaItemWrap\": True } interval = 5 # <- Time (in",
"= { \"BannerToken\": True, \"AthenaBackpack\": True, \"AthenaPetCarrier\": True, \"AthenaPet\": True,",
"<- Display the Rarity of the Item typeconfig = {",
"backgroundurl = \"https://storage.needpix.com/rsynced_images/colored-background.jpg\" # <- Need to be a Image",
"it empty if you dont want one watermarksize = 25",
"True, \"AthenaPetCarrier\": True, \"AthenaPet\": True, \"AthenaPickaxe\": True, \"AthenaCharacter\": True, \"AthenaSkyDiveContrail\":",
"the Set of the Item raritytext = True # <-",
"URL!!! lang = \"en\" # <- language code displayset =",
"\"AthenaMusicPack\": True, \"AthenaSpray\": True, \"AthenaToy\": True, \"AthenaBattleBus\": True, \"AthenaItemWrap\": True",
"a Image URL!!! lang = \"en\" # <- language code",
"True, \"AthenaBackpack\": True, \"AthenaPetCarrier\": True, \"AthenaPet\": True, \"AthenaPickaxe\": True, \"AthenaCharacter\":",
"lang = \"en\" # <- language code displayset = True",
"Recommend: 7 watermark = \"\" # <- Leave it empty",
"<- Display the Set of the Item raritytext = True",
"\"AthenaBattleBus\": True, \"AthenaItemWrap\": True } interval = 5 # <-",
"typeconfig = { \"BannerToken\": True, \"AthenaBackpack\": True, \"AthenaPetCarrier\": True, \"AthenaPet\":",
"<- Need to be a Image URL!!! lang = \"en\"",
"the bot checks for leaks again | Recommend: 7 watermark",
"language code displayset = True # <- Display the Set",
"dont want one watermarksize = 25 # <- Size of",
"watermark = \"\" # <- Leave it empty if you",
"Leave it empty if you dont want one watermarksize =",
"5 # <- Time (in seconds) until the bot checks",
"<filename>SETTINGS.py backgroundurl = \"https://storage.needpix.com/rsynced_images/colored-background.jpg\" # <- Need to be a",
"\"AthenaPet\": True, \"AthenaPickaxe\": True, \"AthenaCharacter\": True, \"AthenaSkyDiveContrail\": True, \"AthenaGlider\": True,",
"True, \"AthenaEmoji\": True, \"AthenaLoadingScreen\": True, \"AthenaMusicPack\": True, \"AthenaSpray\": True, \"AthenaToy\":",
"want one watermarksize = 25 # <- Size of the",
"\"https://storage.needpix.com/rsynced_images/colored-background.jpg\" # <- Need to be a Image URL!!! lang",
"= \"https://storage.needpix.com/rsynced_images/colored-background.jpg\" # <- Need to be a Image URL!!!",
"\"AthenaCharacter\": True, \"AthenaSkyDiveContrail\": True, \"AthenaGlider\": True, \"AthenaDance\": True, \"AthenaEmoji\": True,",
"\"AthenaBackpack\": True, \"AthenaPetCarrier\": True, \"AthenaPet\": True, \"AthenaPickaxe\": True, \"AthenaCharacter\": True,",
"# <- Leave it empty if you dont want one",
"\"en\" # <- language code displayset = True # <-",
"\"AthenaPickaxe\": True, \"AthenaCharacter\": True, \"AthenaSkyDiveContrail\": True, \"AthenaGlider\": True, \"AthenaDance\": True,",
"\"AthenaLoadingScreen\": True, \"AthenaMusicPack\": True, \"AthenaSpray\": True, \"AthenaToy\": True, \"AthenaBattleBus\": True,",
"\"AthenaToy\": True, \"AthenaBattleBus\": True, \"AthenaItemWrap\": True } interval = 5",
"if you dont want one watermarksize = 25 # <-",
"Display the Set of the Item raritytext = True #",
"empty if you dont want one watermarksize = 25 #",
"again | Recommend: 7 watermark = \"\" # <- Leave",
"= \"\" # <- Leave it empty if you dont",
"checks for leaks again | Recommend: 7 watermark = \"\"",
"seconds) until the bot checks for leaks again | Recommend:",
"True, \"AthenaToy\": True, \"AthenaBattleBus\": True, \"AthenaItemWrap\": True } interval =",
"\"AthenaSpray\": True, \"AthenaToy\": True, \"AthenaBattleBus\": True, \"AthenaItemWrap\": True } interval",
"True, \"AthenaGlider\": True, \"AthenaDance\": True, \"AthenaEmoji\": True, \"AthenaLoadingScreen\": True, \"AthenaMusicPack\":",
"<- language code displayset = True # <- Display the"
] |
[
"from healthvaultlib.helpers.connection import Connection class TestBase(unittest.TestCase): def setUp(self): self.connection =",
"= Connection(settings.HV_APPID, settings.HV_SERVICE_SERVER) conn.thumbprint = settings.APP_THUMBPRINT conn.publickey = settings.APP_PUBLIC_KEY conn.privatekey",
"get_connection(self): conn = Connection(settings.HV_APPID, settings.HV_SERVICE_SERVER) conn.thumbprint = settings.APP_THUMBPRINT conn.publickey =",
"conn.thumbprint = settings.APP_THUMBPRINT conn.publickey = settings.APP_PUBLIC_KEY conn.privatekey = settings.APP_PRIVATE_KEY conn.connect()",
"unittest import settings from healthvaultlib.helpers.connection import Connection class TestBase(unittest.TestCase): def",
"= settings.APP_THUMBPRINT conn.publickey = settings.APP_PUBLIC_KEY conn.privatekey = settings.APP_PRIVATE_KEY conn.connect() conn.set_person_and_record(settings.OFFLINE_PERSON_ID,",
"healthvaultlib.helpers.connection import Connection class TestBase(unittest.TestCase): def setUp(self): self.connection = self.get_connection()",
"import settings from healthvaultlib.helpers.connection import Connection class TestBase(unittest.TestCase): def setUp(self):",
"conn = Connection(settings.HV_APPID, settings.HV_SERVICE_SERVER) conn.thumbprint = settings.APP_THUMBPRINT conn.publickey = settings.APP_PUBLIC_KEY",
"setUp(self): self.connection = self.get_connection() def get_connection(self): conn = Connection(settings.HV_APPID, settings.HV_SERVICE_SERVER)",
"settings.HV_SERVICE_SERVER) conn.thumbprint = settings.APP_THUMBPRINT conn.publickey = settings.APP_PUBLIC_KEY conn.privatekey = settings.APP_PRIVATE_KEY",
"settings.APP_THUMBPRINT conn.publickey = settings.APP_PUBLIC_KEY conn.privatekey = settings.APP_PRIVATE_KEY conn.connect() conn.set_person_and_record(settings.OFFLINE_PERSON_ID, settings.OFFLINE_RECORD_ID)",
"import unittest import settings from healthvaultlib.helpers.connection import Connection class TestBase(unittest.TestCase):",
"Connection(settings.HV_APPID, settings.HV_SERVICE_SERVER) conn.thumbprint = settings.APP_THUMBPRINT conn.publickey = settings.APP_PUBLIC_KEY conn.privatekey =",
"def setUp(self): self.connection = self.get_connection() def get_connection(self): conn = Connection(settings.HV_APPID,",
"= self.get_connection() def get_connection(self): conn = Connection(settings.HV_APPID, settings.HV_SERVICE_SERVER) conn.thumbprint =",
"self.connection = self.get_connection() def get_connection(self): conn = Connection(settings.HV_APPID, settings.HV_SERVICE_SERVER) conn.thumbprint",
"= settings.APP_PUBLIC_KEY conn.privatekey = settings.APP_PRIVATE_KEY conn.connect() conn.set_person_and_record(settings.OFFLINE_PERSON_ID, settings.OFFLINE_RECORD_ID) return conn",
"self.get_connection() def get_connection(self): conn = Connection(settings.HV_APPID, settings.HV_SERVICE_SERVER) conn.thumbprint = settings.APP_THUMBPRINT",
"def get_connection(self): conn = Connection(settings.HV_APPID, settings.HV_SERVICE_SERVER) conn.thumbprint = settings.APP_THUMBPRINT conn.publickey",
"Connection class TestBase(unittest.TestCase): def setUp(self): self.connection = self.get_connection() def get_connection(self):",
"conn.publickey = settings.APP_PUBLIC_KEY conn.privatekey = settings.APP_PRIVATE_KEY conn.connect() conn.set_person_and_record(settings.OFFLINE_PERSON_ID, settings.OFFLINE_RECORD_ID) return",
"class TestBase(unittest.TestCase): def setUp(self): self.connection = self.get_connection() def get_connection(self): conn",
"settings from healthvaultlib.helpers.connection import Connection class TestBase(unittest.TestCase): def setUp(self): self.connection",
"import Connection class TestBase(unittest.TestCase): def setUp(self): self.connection = self.get_connection() def",
"<filename>src/healthvaultlib/tests/testbase.py import unittest import settings from healthvaultlib.helpers.connection import Connection class",
"TestBase(unittest.TestCase): def setUp(self): self.connection = self.get_connection() def get_connection(self): conn ="
] |
[
"[ ('extensions', '0011_auto_20170502_0908'), ] operations = [ migrations.AlterField( model_name='extension', name='imports_path',",
"# Generated by Django 1.10.6 on 2017-06-09 03:01 from __future__",
"migrations, models class Migration(migrations.Migration): dependencies = [ ('extensions', '0011_auto_20170502_0908'), ]",
"import migrations, models class Migration(migrations.Migration): dependencies = [ ('extensions', '0011_auto_20170502_0908'),",
"dependencies = [ ('extensions', '0011_auto_20170502_0908'), ] operations = [ migrations.AlterField(",
"'0011_auto_20170502_0908'), ] operations = [ migrations.AlterField( model_name='extension', name='imports_path', field=models.CharField(default='imports/', max_length=255),",
"utf-8 -*- # Generated by Django 1.10.6 on 2017-06-09 03:01",
"Generated by Django 1.10.6 on 2017-06-09 03:01 from __future__ import",
"models class Migration(migrations.Migration): dependencies = [ ('extensions', '0011_auto_20170502_0908'), ] operations",
"unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies =",
"# -*- coding: utf-8 -*- # Generated by Django 1.10.6",
"Migration(migrations.Migration): dependencies = [ ('extensions', '0011_auto_20170502_0908'), ] operations = [",
"('extensions', '0011_auto_20170502_0908'), ] operations = [ migrations.AlterField( model_name='extension', name='imports_path', field=models.CharField(default='imports/',",
"03:01 from __future__ import unicode_literals from django.db import migrations, models",
"1.10.6 on 2017-06-09 03:01 from __future__ import unicode_literals from django.db",
"from django.db import migrations, models class Migration(migrations.Migration): dependencies = [",
"-*- # Generated by Django 1.10.6 on 2017-06-09 03:01 from",
"2017-06-09 03:01 from __future__ import unicode_literals from django.db import migrations,",
"coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-06-09",
"by Django 1.10.6 on 2017-06-09 03:01 from __future__ import unicode_literals",
"import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies",
"on 2017-06-09 03:01 from __future__ import unicode_literals from django.db import",
"] operations = [ migrations.AlterField( model_name='extension', name='imports_path', field=models.CharField(default='imports/', max_length=255), ),",
"= [ ('extensions', '0011_auto_20170502_0908'), ] operations = [ migrations.AlterField( model_name='extension',",
"Django 1.10.6 on 2017-06-09 03:01 from __future__ import unicode_literals from",
"-*- coding: utf-8 -*- # Generated by Django 1.10.6 on",
"from __future__ import unicode_literals from django.db import migrations, models class",
"__future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):",
"django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('extensions',",
"class Migration(migrations.Migration): dependencies = [ ('extensions', '0011_auto_20170502_0908'), ] operations =",
"operations = [ migrations.AlterField( model_name='extension', name='imports_path', field=models.CharField(default='imports/', max_length=255), ), ]"
] |
[
"t = threading.Thread( target=test_globals, args=() ) t.start() threads.append( t )",
"test_globals(): global A, B, C for i in range(1024*1024): lock.acquire()",
"from time import clock import threading THREADS=2 lock = threading.Lock()",
"main(): print( 'starting threading test') starttime = clock() threads =",
"''' multi-threading (python3 version) https://docs.python.org/3/library/threading.html ''' from time import clock",
"import clock import threading THREADS=2 lock = threading.Lock() A =",
"= 0 def test_globals(): global A, B, C for i",
"C for i in range(1024*1024): lock.acquire() A += 1 B",
"threads = [] for i in range(THREADS): t = threading.Thread(",
"t.join() print( clock()-starttime) print('A:', A) print('B:', B) print('C:', C) main()",
"1 B += 2 C = A + B lock.release()",
"= threading.Thread( target=test_globals, args=() ) t.start() threads.append( t ) for",
"in threads: t.join() print( clock()-starttime) print('A:', A) print('B:', B) print('C:',",
"= A + B lock.release() def main(): print( 'starting threading",
"lock.acquire() A += 1 B += 2 C = A",
"t ) for t in threads: t.join() print( clock()-starttime) print('A:',",
"range(1024*1024): lock.acquire() A += 1 B += 2 C =",
"B += 2 C = A + B lock.release() def",
"+ B lock.release() def main(): print( 'starting threading test') starttime",
"'starting threading test') starttime = clock() threads = [] for",
"0 B = 0 C = 0 def test_globals(): global",
"[] for i in range(THREADS): t = threading.Thread( target=test_globals, args=()",
"import threading THREADS=2 lock = threading.Lock() A = 0 B",
"in range(1024*1024): lock.acquire() A += 1 B += 2 C",
"threading.Thread( target=test_globals, args=() ) t.start() threads.append( t ) for t",
"test') starttime = clock() threads = [] for i in",
"threads.append( t ) for t in threads: t.join() print( clock()-starttime)",
"clock import threading THREADS=2 lock = threading.Lock() A = 0",
"= threading.Lock() A = 0 B = 0 C =",
"version) https://docs.python.org/3/library/threading.html ''' from time import clock import threading THREADS=2",
"A += 1 B += 2 C = A +",
"= 0 B = 0 C = 0 def test_globals():",
"lock = threading.Lock() A = 0 B = 0 C",
"time import clock import threading THREADS=2 lock = threading.Lock() A",
"target=test_globals, args=() ) t.start() threads.append( t ) for t in",
"args=() ) t.start() threads.append( t ) for t in threads:",
"range(THREADS): t = threading.Thread( target=test_globals, args=() ) t.start() threads.append( t",
"for t in threads: t.join() print( clock()-starttime) print('A:', A) print('B:',",
") for t in threads: t.join() print( clock()-starttime) print('A:', A)",
"i in range(1024*1024): lock.acquire() A += 1 B += 2",
"= clock() threads = [] for i in range(THREADS): t",
"A + B lock.release() def main(): print( 'starting threading test')",
"= 0 C = 0 def test_globals(): global A, B,",
"threads: t.join() print( clock()-starttime) print('A:', A) print('B:', B) print('C:', C)",
"B = 0 C = 0 def test_globals(): global A,",
"print( 'starting threading test') starttime = clock() threads = []",
"t in threads: t.join() print( clock()-starttime) print('A:', A) print('B:', B)",
"= [] for i in range(THREADS): t = threading.Thread( target=test_globals,",
"for i in range(THREADS): t = threading.Thread( target=test_globals, args=() )",
"THREADS=2 lock = threading.Lock() A = 0 B = 0",
"+= 2 C = A + B lock.release() def main():",
") t.start() threads.append( t ) for t in threads: t.join()",
"lock.release() def main(): print( 'starting threading test') starttime = clock()",
"+= 1 B += 2 C = A + B",
"clock() threads = [] for i in range(THREADS): t =",
"C = A + B lock.release() def main(): print( 'starting",
"starttime = clock() threads = [] for i in range(THREADS):",
"(python3 version) https://docs.python.org/3/library/threading.html ''' from time import clock import threading",
"B lock.release() def main(): print( 'starting threading test') starttime =",
"for i in range(1024*1024): lock.acquire() A += 1 B +=",
"B, C for i in range(1024*1024): lock.acquire() A += 1",
"global A, B, C for i in range(1024*1024): lock.acquire() A",
"A = 0 B = 0 C = 0 def",
"def test_globals(): global A, B, C for i in range(1024*1024):",
"threading test') starttime = clock() threads = [] for i",
"threading.Lock() A = 0 B = 0 C = 0",
"t.start() threads.append( t ) for t in threads: t.join() print(",
"threading THREADS=2 lock = threading.Lock() A = 0 B =",
"0 C = 0 def test_globals(): global A, B, C",
"def main(): print( 'starting threading test') starttime = clock() threads",
"2 C = A + B lock.release() def main(): print(",
"C = 0 def test_globals(): global A, B, C for",
"''' from time import clock import threading THREADS=2 lock =",
"0 def test_globals(): global A, B, C for i in",
"https://docs.python.org/3/library/threading.html ''' from time import clock import threading THREADS=2 lock",
"i in range(THREADS): t = threading.Thread( target=test_globals, args=() ) t.start()",
"A, B, C for i in range(1024*1024): lock.acquire() A +=",
"multi-threading (python3 version) https://docs.python.org/3/library/threading.html ''' from time import clock import",
"in range(THREADS): t = threading.Thread( target=test_globals, args=() ) t.start() threads.append("
] |
[
"self.board = np.array(board) self.players_board = np.array(players_board) self.x_size = 8 self.y_size",
"'Won {} - row {}'.format(self.player(self.player_who_won), i) # return True #",
"self.result = 'Won {} - anty-diagonal {}'.format(self.player(self.player_who_won), i) # return",
"2 (O)' # def show_player_info(self, player_no): # print(\"It's turn of",
"in range(0, self.y_size): # columns # if self.are_same_and_non_zero(self.board[:, i]): #",
"self.are_same_and_non_zero(np.diag(self.board)): # diagonal # self.player_who_won = self.board[1, 1] # self.result",
"= self.board[1, 1] # self.result = 'Won {} - diagonal",
"= 'Won {} - col {}'.format(self.player(self.player_who_won), i) # return True",
"4 ] * 4 players_board = [ [0, 1] *",
"* 4 + [ # 4 rows of nothing [0,",
"- row {}'.format(self.player(self.player_who_won), i) # return True # for i",
"* 4 ] self.board = np.array(board) self.players_board = np.array(players_board) self.x_size",
"row {}'.format(self.player(self.player_who_won), i) # return True # for i in",
"- col {}'.format(self.player(self.player_who_won), i) # return True # if self.are_same_and_non_zero(np.diag(self.board)):",
"return True # draw return False def show(self): # print(self.board)",
"(O)' # def show_player_info(self, player_no): # print(\"It's turn of \",",
"self.player_who_won = self.board[1, 1] # self.result = 'Won {} -",
"True # if self.are_same_and_non_zero(np.diag(self.board)): # diagonal # self.player_who_won = self.board[1,",
"[[0] * 8] * 4 + [ # 4 rows",
"2] * 4, # player 2 [2, 0] * 4",
"- anty-diagonal {}'.format(self.player(self.player_who_won), i) # return True # if self.is_board_full():",
"self.players_board = np.array(players_board) self.x_size = 8 self.y_size = 8 #",
"# def move(self, x, y, current_player): # self.board[x, y] =",
"return np.unique(array).size == 1 and array[0] != 0 # def",
"np.unique(array).size == 1 and array[0] != 0 # def is_board_full(self):",
"self.are_same_and_non_zero(self.board[i, :]): # self.player_who_won = self.board[i, 0] # self.result =",
"# return True # if self.are_same_and_non_zero(np.diag(self.board)): # diagonal # self.player_who_won",
"return 'Player 1 (X)' # if player_no == 2: return",
"for i in range(0, self.y_size): # columns # if self.are_same_and_non_zero(self.board[:,",
"'Won {} - anty-diagonal {}'.format(self.player(self.player_who_won), i) # return True #",
"# self.result = 'Won {} - diagonal {}'.format(self.player(self.player_who_won), i) #",
"0] # self.result = 'Won {} - row {}'.format(self.player(self.player_who_won), i)",
"of nothing [0, 2] * 4, # player 2 [2,",
"8 self.y_size = 8 # def move(self, x, y, current_player):",
"are_same_and_non_zero(self, array): # return np.unique(array).size == 1 and array[0] !=",
"i in range(0, self.y_size): # columns # if self.are_same_and_non_zero(self.board[:, i]):",
"[0, 2] * 4, # player 2 [2, 0] *",
"= 'Won {} - diagonal {}'.format(self.player(self.player_who_won), i) # return True",
"* 4 players_board = [ [0, 1] * 4, #",
"anty-diagonal # self.player_who_won = self.board[1, 1] # self.result = 'Won",
"anty-diagonal {}'.format(self.player(self.player_who_won), i) # return True # if self.is_board_full(): #",
"# if player_no == 1: return 'Player 1 (X)' #",
"1 and array[0] != 0 # def is_board_full(self): # return",
"is_board_full(self): # return not np.any(np.unique(self.board) == 0) def is_finished(self): \"\"\"is",
"in range(0, self.x_size): # rows # if self.are_same_and_non_zero(self.board[i, :]): #",
"self.player_who_won = self.board[i, 0] # self.result = 'Won {} -",
"__init__(self): board = [ [0, 1] * 4, [1, 0]",
"i] # self.result = 'Won {} - col {}'.format(self.player(self.player_who_won), i)",
"return # def player(self, player_no): # if player_no == 1:",
"* 8] * 4 + [ # 4 rows of",
"# self.player_who_won = self.board[1, 1] # self.result = 'Won {}",
"4 players_board = [ [0, 1] * 4, # player",
"self.x_size = 8 self.y_size = 8 # def move(self, x,",
"{} - anty-diagonal {}'.format(self.player(self.player_who_won), i) # return True # if",
"0] * 4 ] * 4 players_board = [ [0,",
"= np.array(board) self.players_board = np.array(players_board) self.x_size = 8 self.y_size =",
"numpy as np class Board: \"\"\" 0 - black 1",
"'Player 2 (O)' # def show_player_info(self, player_no): # print(\"It's turn",
"np.array(board) self.players_board = np.array(players_board) self.x_size = 8 self.y_size = 8",
"* 4, # player 1 [1, 0] * 4 ]",
"array): # return np.unique(array).size == 1 and array[0] != 0",
"# self.board[x, y] = current_player # def are_same_and_non_zero(self, array): #",
"return True # if self.are_same_and_non_zero(np.diag(self.board)): # diagonal # self.player_who_won =",
"self.result = 'Won {} - col {}'.format(self.player(self.player_who_won), i) # return",
"# anty-diagonal # self.player_who_won = self.board[1, 1] # self.result =",
"i) # return True # if self.are_same_and_non_zero(np.diag(self.board)): # diagonal #",
"self.are_same_and_non_zero(np.diag(np.flipud(self.board))): # anty-diagonal # self.player_who_won = self.board[1, 1] # self.result",
"# for i in range(0, self.y_size): # columns # if",
"] self.board = np.array(board) self.players_board = np.array(players_board) self.x_size = 8",
"if self.is_board_full(): # self.player_who_won = 0 # nobody # self.result",
"{}'.format(self.player(self.player_who_won), i) # return True # if self.are_same_and_non_zero(np.diag(self.board)): # diagonal",
"diagonal {}'.format(self.player(self.player_who_won), i) # return True # if self.are_same_and_non_zero(np.diag(np.flipud(self.board))): #",
"[ # 4 rows of nothing [0, 2] * 4,",
"player_no == 2: return 'Player 2 (O)' # def show_player_info(self,",
"return True # for i in range(0, self.y_size): # columns",
"= 0 # nobody # self.result = 'Draw' # return",
"[2, 0] * 4 ] self.board = np.array(board) self.players_board =",
"0] * 4 ] + [[0] * 8] * 4",
"array[0] != 0 # def is_board_full(self): # return not np.any(np.unique(self.board)",
"def is_finished(self): \"\"\"is game finished\"\"\" return True # for i",
"4 ] + [[0] * 8] * 4 + [",
"self.x_size): # rows # if self.are_same_and_non_zero(self.board[i, :]): # self.player_who_won =",
"game finished\"\"\" return True # for i in range(0, self.x_size):",
"1 - white \"\"\" def __init__(self): board = [ [0,",
"!= 0 # def is_board_full(self): # return not np.any(np.unique(self.board) ==",
"x, y, current_player): # self.board[x, y] = current_player # def",
"np class Board: \"\"\" 0 - black 1 - white",
"self.board[x, y] = current_player # def are_same_and_non_zero(self, array): # return",
"self.board[i, 0] # self.result = 'Won {} - row {}'.format(self.player(self.player_who_won),",
"if self.are_same_and_non_zero(np.diag(self.board)): # diagonal # self.player_who_won = self.board[1, 1] #",
"if player_no == 1: return 'Player 1 (X)' # if",
"i) # return True # for i in range(0, self.y_size):",
"4, # player 2 [2, 0] * 4 ] self.board",
"# if self.are_same_and_non_zero(self.board[i, :]): # self.player_who_won = self.board[i, 0] #",
"True # for i in range(0, self.y_size): # columns #",
"i) # return True # if self.are_same_and_non_zero(np.diag(np.flipud(self.board))): # anty-diagonal #",
"# 4 rows of nothing [0, 2] * 4, #",
"current_player): # self.board[x, y] = current_player # def are_same_and_non_zero(self, array):",
"board = [ [0, 1] * 4, [1, 0] *",
"i]): # self.player_who_won = self.board[0, i] # self.result = 'Won",
"current_player # def are_same_and_non_zero(self, array): # return np.unique(array).size == 1",
"columns # if self.are_same_and_non_zero(self.board[:, i]): # self.player_who_won = self.board[0, i]",
"1] # self.result = 'Won {} - diagonal {}'.format(self.player(self.player_who_won), i)",
"print(self.board) # print(self.players_board) return # def player(self, player_no): # if",
"* 4 ] + [[0] * 8] * 4 +",
"# return True # for i in range(0, self.y_size): #",
"= np.array(players_board) self.x_size = 8 self.y_size = 8 # def",
"# def is_board_full(self): # return not np.any(np.unique(self.board) == 0) def",
":]): # self.player_who_won = self.board[i, 0] # self.result = 'Won",
"# self.player_who_won = 0 # nobody # self.result = 'Draw'",
"draw return False def show(self): # print(self.board) # print(self.players_board) return",
"i) # return True # if self.is_board_full(): # self.player_who_won =",
"= current_player # def are_same_and_non_zero(self, array): # return np.unique(array).size ==",
"[1, 0] * 4 ] + [[0] * 8] *",
"0) def is_finished(self): \"\"\"is game finished\"\"\" return True # for",
"# return not np.any(np.unique(self.board) == 0) def is_finished(self): \"\"\"is game",
"return True # for i in range(0, self.x_size): # rows",
"0] * 4 ] self.board = np.array(board) self.players_board = np.array(players_board)",
"True # if self.are_same_and_non_zero(np.diag(np.flipud(self.board))): # anty-diagonal # self.player_who_won = self.board[1,",
"= 'Draw' # return True # draw return False def",
"\"\"\" 0 - black 1 - white \"\"\" def __init__(self):",
"# print(self.board) # print(self.players_board) return # def player(self, player_no): #",
"def __init__(self): board = [ [0, 1] * 4, [1,",
"+ [[0] * 8] * 4 + [ # 4",
"{} - diagonal {}'.format(self.player(self.player_who_won), i) # return True # if",
"player_no): # if player_no == 1: return 'Player 1 (X)'",
"if self.are_same_and_non_zero(self.board[i, :]): # self.player_who_won = self.board[i, 0] # self.result",
"def show(self): # print(self.board) # print(self.players_board) return # def player(self,",
"# self.result = 'Draw' # return True # draw return",
"False def show(self): # print(self.board) # print(self.players_board) return # def",
"move(self, x, y, current_player): # self.board[x, y] = current_player #",
"player 1 [1, 0] * 4 ] + [[0] *",
"self.is_board_full(): # self.player_who_won = 0 # nobody # self.result =",
"return 'Player 2 (O)' # def show_player_info(self, player_no): # print(\"It's",
"player 2 [2, 0] * 4 ] self.board = np.array(board)",
"{} - row {}'.format(self.player(self.player_who_won), i) # return True # for",
"{} - col {}'.format(self.player(self.player_who_won), i) # return True # if",
"'Player 1 (X)' # if player_no == 2: return 'Player",
"{}'.format(self.player(self.player_who_won), i) # return True # if self.are_same_and_non_zero(np.diag(np.flipud(self.board))): # anty-diagonal",
"\"\"\"is game finished\"\"\" return True # for i in range(0,",
"= 'Won {} - row {}'.format(self.player(self.player_who_won), i) # return True",
"as np class Board: \"\"\" 0 - black 1 -",
"show(self): # print(self.board) # print(self.players_board) return # def player(self, player_no):",
"and array[0] != 0 # def is_board_full(self): # return not",
"True # for i in range(0, self.x_size): # rows #",
"return False def show(self): # print(self.board) # print(self.players_board) return #",
"2: return 'Player 2 (O)' # def show_player_info(self, player_no): #",
"# for i in range(0, self.x_size): # rows # if",
"1] * 4, # player 1 [1, 0] * 4",
"True # if self.is_board_full(): # self.player_who_won = 0 # nobody",
"np.array(players_board) self.x_size = 8 self.y_size = 8 # def move(self,",
"= self.board[1, 1] # self.result = 'Won {} - anty-diagonal",
"# return True # draw return False def show(self): #",
"nothing [0, 2] * 4, # player 2 [2, 0]",
"4 + [ # 4 rows of nothing [0, 2]",
"range(0, self.y_size): # columns # if self.are_same_and_non_zero(self.board[:, i]): # self.player_who_won",
"4, [1, 0] * 4 ] * 4 players_board =",
"= [ [0, 1] * 4, [1, 0] * 4",
"[ [0, 1] * 4, # player 1 [1, 0]",
"True # draw return False def show(self): # print(self.board) #",
"y, current_player): # self.board[x, y] = current_player # def are_same_and_non_zero(self,",
"diagonal # self.player_who_won = self.board[1, 1] # self.result = 'Won",
"8] * 4 + [ # 4 rows of nothing",
"# if self.are_same_and_non_zero(np.diag(np.flipud(self.board))): # anty-diagonal # self.player_who_won = self.board[1, 1]",
"= 8 # def move(self, x, y, current_player): # self.board[x,",
"def move(self, x, y, current_player): # self.board[x, y] = current_player",
"return True # if self.are_same_and_non_zero(np.diag(np.flipud(self.board))): # anty-diagonal # self.player_who_won =",
"if player_no == 2: return 'Player 2 (O)' # def",
"- diagonal {}'.format(self.player(self.player_who_won), i) # return True # if self.are_same_and_non_zero(np.diag(np.flipud(self.board))):",
"# def are_same_and_non_zero(self, array): # return np.unique(array).size == 1 and",
"1 [1, 0] * 4 ] + [[0] * 8]",
"i in range(0, self.x_size): # rows # if self.are_same_and_non_zero(self.board[i, :]):",
"# self.player_who_won = self.board[0, i] # self.result = 'Won {}",
"{}'.format(self.player(self.player_who_won), i) # return True # for i in range(0,",
"'Won {} - diagonal {}'.format(self.player(self.player_who_won), i) # return True #",
"# columns # if self.are_same_and_non_zero(self.board[:, i]): # self.player_who_won = self.board[0,",
"nobody # self.result = 'Draw' # return True # draw",
"self.result = 'Draw' # return True # draw return False",
"print(self.players_board) return # def player(self, player_no): # if player_no ==",
"# def show_player_info(self, player_no): # print(\"It's turn of \", self.player(player_no))",
"# player 2 [2, 0] * 4 ] self.board =",
"white \"\"\" def __init__(self): board = [ [0, 1] *",
"== 1: return 'Player 1 (X)' # if player_no ==",
"# print(self.players_board) return # def player(self, player_no): # if player_no",
"- black 1 - white \"\"\" def __init__(self): board =",
"range(0, self.x_size): # rows # if self.are_same_and_non_zero(self.board[i, :]): # self.player_who_won",
"0 # def is_board_full(self): # return not np.any(np.unique(self.board) == 0)",
"self.result = 'Won {} - row {}'.format(self.player(self.player_who_won), i) # return",
"self.y_size = 8 # def move(self, x, y, current_player): #",
"# self.player_who_won = self.board[i, 0] # self.result = 'Won {}",
"== 0) def is_finished(self): \"\"\"is game finished\"\"\" return True #",
"4, # player 1 [1, 0] * 4 ] +",
"== 1 and array[0] != 0 # def is_board_full(self): #",
"self.board[0, i] # self.result = 'Won {} - col {}'.format(self.player(self.player_who_won),",
"] + [[0] * 8] * 4 + [ #",
"'Won {} - col {}'.format(self.player(self.player_who_won), i) # return True #",
"# self.result = 'Won {} - row {}'.format(self.player(self.player_who_won), i) #",
"# def player(self, player_no): # if player_no == 1: return",
"player(self, player_no): # if player_no == 1: return 'Player 1",
"2 [2, 0] * 4 ] self.board = np.array(board) self.players_board",
"[0, 1] * 4, [1, 0] * 4 ] *",
"y] = current_player # def are_same_and_non_zero(self, array): # return np.unique(array).size",
"self.result = 'Won {} - diagonal {}'.format(self.player(self.player_who_won), i) # return",
"player_no == 1: return 'Player 1 (X)' # if player_no",
"# diagonal # self.player_who_won = self.board[1, 1] # self.result =",
"black 1 - white \"\"\" def __init__(self): board = [",
"not np.any(np.unique(self.board) == 0) def is_finished(self): \"\"\"is game finished\"\"\" return",
"1] * 4, [1, 0] * 4 ] * 4",
"import numpy as np class Board: \"\"\" 0 - black",
"return True # if self.is_board_full(): # self.player_who_won = 0 #",
"# nobody # self.result = 'Draw' # return True #",
"col {}'.format(self.player(self.player_who_won), i) # return True # if self.are_same_and_non_zero(np.diag(self.board)): #",
"= 8 self.y_size = 8 # def move(self, x, y,",
"def is_board_full(self): # return not np.any(np.unique(self.board) == 0) def is_finished(self):",
"# if self.are_same_and_non_zero(self.board[:, i]): # self.player_who_won = self.board[0, i] #",
"= [ [0, 1] * 4, # player 1 [1,",
"def player(self, player_no): # if player_no == 1: return 'Player",
"self.player_who_won = 0 # nobody # self.result = 'Draw' #",
"# if player_no == 2: return 'Player 2 (O)' #",
"# if self.are_same_and_non_zero(np.diag(self.board)): # diagonal # self.player_who_won = self.board[1, 1]",
"1 (X)' # if player_no == 2: return 'Player 2",
"# self.result = 'Won {} - col {}'.format(self.player(self.player_who_won), i) #",
"\"\"\" def __init__(self): board = [ [0, 1] * 4,",
"# rows # if self.are_same_and_non_zero(self.board[i, :]): # self.player_who_won = self.board[i,",
"is_finished(self): \"\"\"is game finished\"\"\" return True # for i in",
"[1, 0] * 4 ] * 4 players_board = [",
"self.board[1, 1] # self.result = 'Won {} - anty-diagonal {}'.format(self.player(self.player_who_won),",
"players_board = [ [0, 1] * 4, # player 1",
"= self.board[0, i] # self.result = 'Won {} - col",
"self.board[1, 1] # self.result = 'Won {} - diagonal {}'.format(self.player(self.player_who_won),",
"= self.board[i, 0] # self.result = 'Won {} - row",
"if self.are_same_and_non_zero(np.diag(np.flipud(self.board))): # anty-diagonal # self.player_who_won = self.board[1, 1] #",
"4 ] self.board = np.array(board) self.players_board = np.array(players_board) self.x_size =",
"] * 4 players_board = [ [0, 1] * 4,",
"rows of nothing [0, 2] * 4, # player 2",
"self.y_size): # columns # if self.are_same_and_non_zero(self.board[:, i]): # self.player_who_won =",
"8 # def move(self, x, y, current_player): # self.board[x, y]",
"# return True # if self.is_board_full(): # self.player_who_won = 0",
"# self.result = 'Won {} - anty-diagonal {}'.format(self.player(self.player_who_won), i) #",
"0 - black 1 - white \"\"\" def __init__(self): board",
"* 4, [1, 0] * 4 ] * 4 players_board",
"== 2: return 'Player 2 (O)' # def show_player_info(self, player_no):",
"# return np.unique(array).size == 1 and array[0] != 0 #",
"1] # self.result = 'Won {} - anty-diagonal {}'.format(self.player(self.player_who_won), i)",
"rows # if self.are_same_and_non_zero(self.board[i, :]): # self.player_who_won = self.board[i, 0]",
"[ [0, 1] * 4, [1, 0] * 4 ]",
"def are_same_and_non_zero(self, array): # return np.unique(array).size == 1 and array[0]",
"0 # nobody # self.result = 'Draw' # return True",
"return not np.any(np.unique(self.board) == 0) def is_finished(self): \"\"\"is game finished\"\"\"",
"self.are_same_and_non_zero(self.board[:, i]): # self.player_who_won = self.board[0, i] # self.result =",
"'Draw' # return True # draw return False def show(self):",
"# draw return False def show(self): # print(self.board) # print(self.players_board)",
"# player 1 [1, 0] * 4 ] + [[0]",
"- white \"\"\" def __init__(self): board = [ [0, 1]",
"* 4 ] * 4 players_board = [ [0, 1]",
"= 'Won {} - anty-diagonal {}'.format(self.player(self.player_who_won), i) # return True",
"np.any(np.unique(self.board) == 0) def is_finished(self): \"\"\"is game finished\"\"\" return True",
"for i in range(0, self.x_size): # rows # if self.are_same_and_non_zero(self.board[i,",
"class Board: \"\"\" 0 - black 1 - white \"\"\"",
"finished\"\"\" return True # for i in range(0, self.x_size): #",
"self.player_who_won = self.board[0, i] # self.result = 'Won {} -",
"Board: \"\"\" 0 - black 1 - white \"\"\" def",
"[0, 1] * 4, # player 1 [1, 0] *",
"{}'.format(self.player(self.player_who_won), i) # return True # if self.is_board_full(): # self.player_who_won",
"# if self.is_board_full(): # self.player_who_won = 0 # nobody #",
"* 4, # player 2 [2, 0] * 4 ]",
"if self.are_same_and_non_zero(self.board[:, i]): # self.player_who_won = self.board[0, i] # self.result",
"# return True # if self.are_same_and_non_zero(np.diag(np.flipud(self.board))): # anty-diagonal # self.player_who_won",
"1: return 'Player 1 (X)' # if player_no == 2:",
"+ [ # 4 rows of nothing [0, 2] *",
"4 rows of nothing [0, 2] * 4, # player",
"(X)' # if player_no == 2: return 'Player 2 (O)'"
] |
[
"= price[thing]['week'] * amount other_thing_price_month = price[thing]['month'] * amount return",
"price[thing]['month'] * amount return f'Стоимость составит {other_thing_price_week} р./неделю' + \\",
"wheel_price = price[thing]['month'] * amount return f'Стоимость составит {wheel_price}/месяц' else:",
"return f'Стоимость составит {other_thing_price_week} р./неделю' + \\ f' или {other_thing_price_month}",
"return f'Стоимость составит {wheel_price}/месяц' else: other_thing_price_week = price[thing]['week'] * amount",
"price[thing]['month'] * amount return f'Стоимость составит {wheel_price}/месяц' else: other_thing_price_week =",
"amount return f'Стоимость составит {other_thing_price_week} р./неделю' + \\ f' или",
"f'Стоимость составит {wheel_price}/месяц' else: other_thing_price_week = price[thing]['week'] * amount other_thing_price_month",
"f'Стоимость составит {other_thing_price_week} р./неделю' + \\ f' или {other_thing_price_month} р./месяц'",
"{wheel_price}/месяц' else: other_thing_price_week = price[thing]['week'] * amount other_thing_price_month = price[thing]['month']",
"thing == 'wheel': wheel_price = price[thing]['month'] * amount return f'Стоимость",
"amount other_thing_price_month = price[thing]['month'] * amount return f'Стоимость составит {other_thing_price_week}",
"* amount return f'Стоимость составит {wheel_price}/месяц' else: other_thing_price_week = price[thing]['week']",
"get_season_things_price(thing, amount, price): if thing == 'wheel': wheel_price = price[thing]['month']",
"составит {wheel_price}/месяц' else: other_thing_price_week = price[thing]['week'] * amount other_thing_price_month =",
"= price[thing]['month'] * amount return f'Стоимость составит {wheel_price}/месяц' else: other_thing_price_week",
"def get_season_things_price(thing, amount, price): if thing == 'wheel': wheel_price =",
"if thing == 'wheel': wheel_price = price[thing]['month'] * amount return",
"other_thing_price_month = price[thing]['month'] * amount return f'Стоимость составит {other_thing_price_week} р./неделю'",
"amount, price): if thing == 'wheel': wheel_price = price[thing]['month'] *",
"else: other_thing_price_week = price[thing]['week'] * amount other_thing_price_month = price[thing]['month'] *",
"* amount other_thing_price_month = price[thing]['month'] * amount return f'Стоимость составит",
"* amount return f'Стоимость составит {other_thing_price_week} р./неделю' + \\ f'",
"price[thing]['week'] * amount other_thing_price_month = price[thing]['month'] * amount return f'Стоимость",
"= price[thing]['month'] * amount return f'Стоимость составит {other_thing_price_week} р./неделю' +",
"price): if thing == 'wheel': wheel_price = price[thing]['month'] * amount",
"== 'wheel': wheel_price = price[thing]['month'] * amount return f'Стоимость составит",
"amount return f'Стоимость составит {wheel_price}/месяц' else: other_thing_price_week = price[thing]['week'] *",
"'wheel': wheel_price = price[thing]['month'] * amount return f'Стоимость составит {wheel_price}/месяц'",
"other_thing_price_week = price[thing]['week'] * amount other_thing_price_month = price[thing]['month'] * amount"
] |
[
"root display surface self.window = pygame.display.set_mode( size, 0, 32 )",
"process event queue for event in pygame.event.get(): # check for",
"if event.type == pygame.KEYUP: self._debug = '({})'.format( mod_str ) elif",
"delta < self._tick_step: self._last_wait = self._tick_step - delta else: self._last_wait",
"short debug string for various things self._debug = '' #=========================================================================",
"# third-party packages import pygame # local package import layer",
"background self.window.fill( ( 32, 32, 32 ) ) # blit",
"# update FPS value if delta > 0: self._fps =",
"= '0.0.0' #============================================================================= class Engine( object ): \"\"\" Simple game",
"'../assets/z32.png' ) pygame.display.set_icon( icon ) # create a list of",
"application loop if done if self._is_running == False: break #",
"<reponame>zhester/zge \"\"\" Zoe Game Engine Core Implementation =================================== Requirements ------------",
"for overlayed information self._top = layer.TextLayer() # initialize last tick",
"initialize last tick value self._last_tick = pygame.time.get_ticks() self._last_wait = 0",
"check for quit event if event.type == pygame.QUIT: self._is_running =",
"- temp, just seeing how to poll the keys mods",
") ) #========================================================================= def update( self ): \"\"\" Updates the",
"self._debug = '({})'.format( mod_str ) elif event.type == pygame.KEYDOWN: self._debug",
"elif ( event.type == pygame.KEYDOWN ) \\ or ( event.type",
"display layers onto the back buffer. \"\"\" # fill the",
"normal display layers self._layers = [] # create a transparent",
"\"\"\" # fill the background self.window.fill( ( 32, 32, 32",
"fill the background self.window.fill( ( 32, 32, 32 ) )",
"def trigger_key_event( self, event ): \"\"\" Initiates key input events.",
"float( delta ) else: self._fps = self._fps_limit # compute remaining",
"\"\"\" # ZIH - temp, just seeing how to poll",
"self._last_tick, self._debug ) ) # draw the display on the",
"\"\"\" Initiates key input events. \"\"\" # ZIH - temp,",
"= pygame.time.get_ticks() self._last_wait = 0 # set an FPS cap",
"title bar text and iconification text pygame.display.set_caption( 'Demonstration', 'Demo' )",
"\"top\" layer for overlayed information self._top = layer.TextLayer() # initialize",
"pygame.image.load( '../assets/z32.png' ) pygame.display.set_icon( icon ) # create a list",
"the application quits). \"\"\" # update tick value before entering",
"# check for key event elif ( event.type == pygame.KEYDOWN",
"let the OS do other stuff on this core pygame.time.wait(",
"layer __version__ = '0.0.0' #============================================================================= class Engine( object ): \"\"\"",
"== pygame.KEYUP: self._debug = '({})'.format( mod_str ) elif event.type ==",
"pygame.KEYUP: self._debug = '({})'.format( mod_str ) elif event.type == pygame.KEYDOWN:",
"# set the title bar text and iconification text pygame.display.set_caption(",
"seeing how to poll the keys mods = pygame.key.get_mods() mod_bits",
"the display on the back buffer self._draw_layers() # update the",
"update overlayed information self._top.set_text( ' [ fps:{:4.0f} sch:{:3} tck:{:08} dbg:{}",
"- delta else: self._last_wait = 0 # let the OS",
"self._tick_step = int( round( 1000.0 / self._fps_limit ) ) #",
"< self._tick_step: self._last_wait = self._tick_step - delta else: self._last_wait =",
"): \"\"\" Updates the display. \"\"\" # update overlayed information",
"keys mods = pygame.key.get_mods() mod_bits = [ ( pygame.KMOD_ALT, 'A'",
"sch:{:3} tck:{:08} dbg:{} ]'.format( self._fps, self._last_wait, self._last_tick, self._debug ) )",
"self._last_wait, self._last_tick, self._debug ) ) # draw the display on",
"= False # short debug string for various things self._debug",
"currently running self._is_running = False # short debug string for",
"self._fps, self._last_wait, self._last_tick, self._debug ) ) # draw the display",
"application loop self._is_running = True while self._is_running: # process event",
"#========================================================================= def update( self ): \"\"\" Updates the display. \"\"\"",
"icon icon = pygame.image.load( '../assets/z32.png' ) pygame.display.set_icon( icon ) #",
"self._debug = '({}){}'.format( mod_str, pygame.key.name( event.key ) ) #========================================================================= def",
"self.trigger_key_event( event ) # exit application loop if done if",
"= pygame.time.get_ticks() delta = end_tick - self._last_tick self._last_tick = end_tick",
"pygame.key.get_mods() mod_bits = [ ( pygame.KMOD_ALT, 'A' ), ( pygame.KMOD_CTRL,",
") : self.trigger_key_event( event ) # exit application loop if",
"= 0 # let the OS do other stuff on",
"( pygame.KMOD_ALT, 'A' ), ( pygame.KMOD_CTRL, 'C' ), ( pygame.KMOD_SHIFT,",
"exit application loop if done if self._is_running == False: break",
"buffer self._draw_layers() # update the display (swap video buffers) pygame.display.update()",
"self._tick_step - delta else: self._last_wait = 0 # let the",
"\"\"\" # update overlayed information self._top.set_text( ' [ fps:{:4.0f} sch:{:3}",
"run( self ): \"\"\" Run the game loop (does not",
"third-party packages import pygame # local package import layer __version__",
"value self._last_tick = pygame.time.get_ticks() self._last_wait = 0 # set an",
"layers onto the back buffer. \"\"\" # fill the background",
"done if self._is_running == False: break # update the game",
"update FPS value if delta > 0: self._fps = 1000.0",
"def __init__( self, size ): \"\"\" Initializes an Engine object.",
"pygame.display.set_mode( size, 0, 32 ) # set the title bar",
"layer.TextLayer() # initialize last tick value self._last_tick = pygame.time.get_ticks() self._last_wait",
"value if delta > 0: self._fps = 1000.0 / float(",
"elif event.type == pygame.KEYDOWN: self._debug = '({}){}'.format( mod_str, pygame.key.name( event.key",
"loop (does not return until the application quits). \"\"\" #",
"= self._tick_step - delta else: self._last_wait = 0 # let",
"for layer in self._layers: layer.blit( self.window ) # blit the",
"this iteration if delta < self._tick_step: self._last_wait = self._tick_step -",
"transparent \"top\" layer for overlayed information self._top = layer.TextLayer() #",
"=================================== Requirements ------------ [pygame](http://www.pygame.org/) \"\"\" # core packages # third-party",
"__version__ = '0.0.0' #============================================================================= class Engine( object ): \"\"\" Simple",
") # blit all user layers for layer in self._layers:",
"display. \"\"\" # update overlayed information self._top.set_text( ' [ fps:{:4.0f}",
"display on the back buffer self._draw_layers() # update the display",
"[pygame](http://www.pygame.org/) \"\"\" # core packages # third-party packages import pygame",
"core pygame.time.wait( self._last_wait ) # shut down pygame pygame.quit() #",
"def update( self ): \"\"\" Updates the display. \"\"\" #",
"duration of last event/render loop end_tick = pygame.time.get_ticks() delta =",
"set the application icon icon = pygame.image.load( '../assets/z32.png' ) pygame.display.set_icon(",
"key event elif ( event.type == pygame.KEYDOWN ) \\ or",
"for key event elif ( event.type == pygame.KEYDOWN ) \\",
"return exit status return 0 #========================================================================= def trigger_key_event( self, event",
"self._fps = self._fps_limit # compute remaining time available inside this",
"event ): \"\"\" Initiates key input events. \"\"\" # ZIH",
"all the display layers onto the back buffer. \"\"\" #",
"text pygame.display.set_caption( 'Demonstration', 'Demo' ) # set the application icon",
"pygame.init() # initialize the root display surface self.window = pygame.display.set_mode(",
"0 # let the OS do other stuff on this",
"a transparent \"top\" layer for overlayed information self._top = layer.TextLayer()",
"the root display surface self.window = pygame.display.set_mode( size, 0, 32",
"== pygame.KEYDOWN ) \\ or ( event.type == pygame.KEYUP )",
"32 ) ) # blit all user layers for layer",
"): \"\"\" Blits all the display layers onto the back",
"self._tick_step: self._last_wait = self._tick_step - delta else: self._last_wait = 0",
"pygame.QUIT: self._is_running = False # check for key event elif",
"self._last_wait = self._tick_step - delta else: self._last_wait = 0 #",
"execute infinite application loop self._is_running = True while self._is_running: #",
"self.update() # ZIH - simulate hard work #pygame.time.delay( 3 )",
"the display. \"\"\" # update overlayed information self._top.set_text( ' [",
"package import layer __version__ = '0.0.0' #============================================================================= class Engine( object",
"b[ 0 ] & mods ) if event.type == pygame.KEYUP:",
"mods ) if event.type == pygame.KEYUP: self._debug = '({})'.format( mod_str",
"mod_str, pygame.key.name( event.key ) ) #========================================================================= def update( self ):",
"): \"\"\" Simple game engine object. \"\"\" #========================================================================= def __init__(",
"# blit all user layers for layer in self._layers: layer.blit(",
"engine is currently running self._is_running = False # short debug",
"( pygame.KMOD_CTRL, 'C' ), ( pygame.KMOD_SHIFT, 'S' ) ] mod_str",
"self._last_tick = pygame.time.get_ticks() self._last_wait = 0 # set an FPS",
"''.join( b[ 1 ] for b in mod_bits if b[",
"dbg:{} ]'.format( self._fps, self._last_wait, self._last_tick, self._debug ) ) # draw",
"check for key event elif ( event.type == pygame.KEYDOWN )",
") ] mod_str = ''.join( b[ 1 ] for b",
"else: self._last_wait = 0 # let the OS do other",
"0.0 self._fps_limit = 120.0 self._tick_step = int( round( 1000.0 /",
") # create a list of normal display layers self._layers",
"self._debug ) ) # draw the display on the back",
"pygame.quit() # return exit status return 0 #========================================================================= def trigger_key_event(",
"if b[ 0 ] & mods ) if event.type ==",
"\\ or ( event.type == pygame.KEYUP ) : self.trigger_key_event( event",
"# update overlayed information self._top.set_text( ' [ fps:{:4.0f} sch:{:3} tck:{:08}",
"------------ [pygame](http://www.pygame.org/) \"\"\" # core packages # third-party packages import",
"= pygame.time.get_ticks() # execute infinite application loop self._is_running = True",
"local package import layer __version__ = '0.0.0' #============================================================================= class Engine(",
"pygame.KMOD_CTRL, 'C' ), ( pygame.KMOD_SHIFT, 'S' ) ] mod_str =",
"- simulate hard work #pygame.time.delay( 3 ) # compute duration",
"display (swap video buffers) pygame.display.update() #========================================================================= def _draw_layers( self ):",
"( 32, 32, 32 ) ) # blit all user",
"mod_bits if b[ 0 ] & mods ) if event.type",
"tick value before entering the loop self._last_tick = pygame.time.get_ticks() #",
"the loop self._last_tick = pygame.time.get_ticks() # execute infinite application loop",
"' [ fps:{:4.0f} sch:{:3} tck:{:08} dbg:{} ]'.format( self._fps, self._last_wait, self._last_tick,",
"engine object. \"\"\" #========================================================================= def __init__( self, size ): \"\"\"",
"\"\"\" Updates the display. \"\"\" # update overlayed information self._top.set_text(",
"layer in self._layers: layer.blit( self.window ) # blit the top",
"32 ) # set the title bar text and iconification",
"event.type == pygame.KEYUP: self._debug = '({})'.format( mod_str ) elif event.type",
"False # short debug string for various things self._debug =",
"Game Engine Core Implementation =================================== Requirements ------------ [pygame](http://www.pygame.org/) \"\"\" #",
"mod_str ) elif event.type == pygame.KEYDOWN: self._debug = '({}){}'.format( mod_str,",
"the display layers onto the back buffer. \"\"\" # fill",
"# update the game display self.update() # ZIH - simulate",
"# exit application loop if done if self._is_running == False:",
"if self._is_running == False: break # update the game display",
"# short debug string for various things self._debug = ''",
"'A' ), ( pygame.KMOD_CTRL, 'C' ), ( pygame.KMOD_SHIFT, 'S' )",
"and iconification text pygame.display.set_caption( 'Demonstration', 'Demo' ) # set the",
"list of normal display layers self._layers = [] # create",
"is currently running self._is_running = False # short debug string",
"loop self._is_running = True while self._is_running: # process event queue",
"# process event queue for event in pygame.event.get(): # check",
"compute remaining time available inside this iteration if delta <",
"Simple game engine object. \"\"\" #========================================================================= def __init__( self, size",
"the game loop (does not return until the application quits).",
"initialize the root display surface self.window = pygame.display.set_mode( size, 0,",
"\"\"\" Simple game engine object. \"\"\" #========================================================================= def __init__( self,",
"self._fps_limit = 120.0 self._tick_step = int( round( 1000.0 / self._fps_limit",
"the back buffer self._draw_layers() # update the display (swap video",
"def _draw_layers( self ): \"\"\" Blits all the display layers",
"3 ) # compute duration of last event/render loop end_tick",
"debug string for various things self._debug = '' #========================================================================= def",
"self._last_wait ) # shut down pygame pygame.quit() # return exit",
"pygame.time.get_ticks() self._last_wait = 0 # set an FPS cap self._fps",
"back buffer. \"\"\" # fill the background self.window.fill( ( 32,",
"= 1000.0 / float( delta ) else: self._fps = self._fps_limit",
"if done if self._is_running == False: break # update the",
") ) # blit all user layers for layer in",
"self._layers: layer.blit( self.window ) # blit the top layer self._top.blit(",
"# ZIH - temp, just seeing how to poll the",
"# set an FPS cap self._fps = 0.0 self._fps_limit =",
"delta > 0: self._fps = 1000.0 / float( delta )",
"packages import pygame # local package import layer __version__ =",
"= '({})'.format( mod_str ) elif event.type == pygame.KEYDOWN: self._debug =",
"pygame.KEYUP ) : self.trigger_key_event( event ) # exit application loop",
"Initiates key input events. \"\"\" # ZIH - temp, just",
"\"\"\" # update tick value before entering the loop self._last_tick",
"event in pygame.event.get(): # check for quit event if event.type",
"the game display self.update() # ZIH - simulate hard work",
"in pygame.event.get(): # check for quit event if event.type ==",
"text and iconification text pygame.display.set_caption( 'Demonstration', 'Demo' ) # set",
"\"\"\" # pygame initialization pygame.init() # initialize the root display",
"self._fps_limit ) ) # engine is currently running self._is_running =",
"( event.type == pygame.KEYDOWN ) \\ or ( event.type ==",
"bar text and iconification text pygame.display.set_caption( 'Demonstration', 'Demo' ) #",
"all user layers for layer in self._layers: layer.blit( self.window )",
"display self.update() # ZIH - simulate hard work #pygame.time.delay( 3",
"available inside this iteration if delta < self._tick_step: self._last_wait =",
"= int( round( 1000.0 / self._fps_limit ) ) # engine",
"entering the loop self._last_tick = pygame.time.get_ticks() # execute infinite application",
"event.type == pygame.KEYDOWN: self._debug = '({}){}'.format( mod_str, pygame.key.name( event.key )",
"event.type == pygame.KEYUP ) : self.trigger_key_event( event ) # exit",
"#========================================================================= def _draw_layers( self ): \"\"\" Blits all the display",
"\"\"\" Initializes an Engine object. \"\"\" # pygame initialization pygame.init()",
") ) # draw the display on the back buffer",
"end_tick = pygame.time.get_ticks() delta = end_tick - self._last_tick self._last_tick =",
"the application icon icon = pygame.image.load( '../assets/z32.png' ) pygame.display.set_icon( icon",
"# local package import layer __version__ = '0.0.0' #============================================================================= class",
") if event.type == pygame.KEYUP: self._debug = '({})'.format( mod_str )",
"self._layers = [] # create a transparent \"top\" layer for",
"icon = pygame.image.load( '../assets/z32.png' ) pygame.display.set_icon( icon ) # create",
"self.window = pygame.display.set_mode( size, 0, 32 ) # set the",
"Engine( object ): \"\"\" Simple game engine object. \"\"\" #=========================================================================",
"round( 1000.0 / self._fps_limit ) ) # engine is currently",
"= 0.0 self._fps_limit = 120.0 self._tick_step = int( round( 1000.0",
"application quits). \"\"\" # update tick value before entering the",
"# return exit status return 0 #========================================================================= def trigger_key_event( self,",
"or ( event.type == pygame.KEYUP ) : self.trigger_key_event( event )",
") # set the application icon icon = pygame.image.load( '../assets/z32.png'",
"[] # create a transparent \"top\" layer for overlayed information",
"layer.blit( self.window ) # blit the top layer self._top.blit( self.window",
"# execute infinite application loop self._is_running = True while self._is_running:",
"120.0 self._tick_step = int( round( 1000.0 / self._fps_limit ) )",
"'({}){}'.format( mod_str, pygame.key.name( event.key ) ) #========================================================================= def update( self",
"self.window ) # blit the top layer self._top.blit( self.window )",
"Zoe Game Engine Core Implementation =================================== Requirements ------------ [pygame](http://www.pygame.org/) \"\"\"",
"game loop (does not return until the application quits). \"\"\"",
"(swap video buffers) pygame.display.update() #========================================================================= def _draw_layers( self ): \"\"\"",
"] mod_str = ''.join( b[ 1 ] for b in",
"video buffers) pygame.display.update() #========================================================================= def _draw_layers( self ): \"\"\" Blits",
"to poll the keys mods = pygame.key.get_mods() mod_bits = [",
"= pygame.key.get_mods() mod_bits = [ ( pygame.KMOD_ALT, 'A' ), (",
"= ''.join( b[ 1 ] for b in mod_bits if",
"pygame.display.set_icon( icon ) # create a list of normal display",
"= self._fps_limit # compute remaining time available inside this iteration",
"self._fps = 1000.0 / float( delta ) else: self._fps =",
"of last event/render loop end_tick = pygame.time.get_ticks() delta = end_tick",
"size ): \"\"\" Initializes an Engine object. \"\"\" # pygame",
"icon ) # create a list of normal display layers",
"\"\"\" # core packages # third-party packages import pygame #",
"/ float( delta ) else: self._fps = self._fps_limit # compute",
"loop if done if self._is_running == False: break # update",
"'0.0.0' #============================================================================= class Engine( object ): \"\"\" Simple game engine",
"how to poll the keys mods = pygame.key.get_mods() mod_bits =",
"queue for event in pygame.event.get(): # check for quit event",
": self.trigger_key_event( event ) # exit application loop if done",
"event elif ( event.type == pygame.KEYDOWN ) \\ or (",
"inside this iteration if delta < self._tick_step: self._last_wait = self._tick_step",
"just seeing how to poll the keys mods = pygame.key.get_mods()",
"self ): \"\"\" Blits all the display layers onto the",
"pygame.KEYDOWN ) \\ or ( event.type == pygame.KEYUP ) :",
"( pygame.KMOD_SHIFT, 'S' ) ] mod_str = ''.join( b[ 1",
"self._last_wait = 0 # set an FPS cap self._fps =",
"buffers) pygame.display.update() #========================================================================= def _draw_layers( self ): \"\"\" Blits all",
"string for various things self._debug = '' #========================================================================= def run(",
") \\ or ( event.type == pygame.KEYUP ) : self.trigger_key_event(",
") # draw the display on the back buffer self._draw_layers()",
"self ): \"\"\" Run the game loop (does not return",
"an FPS cap self._fps = 0.0 self._fps_limit = 120.0 self._tick_step",
"while self._is_running: # process event queue for event in pygame.event.get():",
"\"\"\" Blits all the display layers onto the back buffer.",
"event if event.type == pygame.QUIT: self._is_running = False # check",
"class Engine( object ): \"\"\" Simple game engine object. \"\"\"",
"self, event ): \"\"\" Initiates key input events. \"\"\" #",
"fps:{:4.0f} sch:{:3} tck:{:08} dbg:{} ]'.format( self._fps, self._last_wait, self._last_tick, self._debug )",
"size, 0, 32 ) # set the title bar text",
"status return 0 #========================================================================= def trigger_key_event( self, event ): \"\"\"",
"pygame.event.get(): # check for quit event if event.type == pygame.QUIT:",
"'S' ) ] mod_str = ''.join( b[ 1 ] for",
"time available inside this iteration if delta < self._tick_step: self._last_wait",
"work #pygame.time.delay( 3 ) # compute duration of last event/render",
"cap self._fps = 0.0 self._fps_limit = 120.0 self._tick_step = int(",
"overlayed information self._top = layer.TextLayer() # initialize last tick value",
"FPS cap self._fps = 0.0 self._fps_limit = 120.0 self._tick_step =",
"#pygame.time.delay( 3 ) # compute duration of last event/render loop",
"== pygame.KEYDOWN: self._debug = '({}){}'.format( mod_str, pygame.key.name( event.key ) )",
"the display (swap video buffers) pygame.display.update() #========================================================================= def _draw_layers( self",
"Run the game loop (does not return until the application",
"an Engine object. \"\"\" # pygame initialization pygame.init() # initialize",
"return 0 #========================================================================= def trigger_key_event( self, event ): \"\"\" Initiates",
"= [] # create a transparent \"top\" layer for overlayed",
"loop end_tick = pygame.time.get_ticks() delta = end_tick - self._last_tick self._last_tick",
"object. \"\"\" #========================================================================= def __init__( self, size ): \"\"\" Initializes",
"return until the application quits). \"\"\" # update tick value",
"display layers self._layers = [] # create a transparent \"top\"",
"event.type == pygame.KEYDOWN ) \\ or ( event.type == pygame.KEYUP",
"packages # third-party packages import pygame # local package import",
"loop self._last_tick = pygame.time.get_ticks() # execute infinite application loop self._is_running",
"0 #========================================================================= def trigger_key_event( self, event ): \"\"\" Initiates key",
"] & mods ) if event.type == pygame.KEYUP: self._debug =",
"& mods ) if event.type == pygame.KEYUP: self._debug = '({})'.format(",
"in self._layers: layer.blit( self.window ) # blit the top layer",
"of normal display layers self._layers = [] # create a",
"\"\"\" Run the game loop (does not return until the",
"layers self._layers = [] # create a transparent \"top\" layer",
"end_tick # update FPS value if delta > 0: self._fps",
"self._is_running = False # check for key event elif (",
"update the game display self.update() # ZIH - simulate hard",
"remaining time available inside this iteration if delta < self._tick_step:",
"information self._top = layer.TextLayer() # initialize last tick value self._last_tick",
"event queue for event in pygame.event.get(): # check for quit",
"'Demo' ) # set the application icon icon = pygame.image.load(",
"compute duration of last event/render loop end_tick = pygame.time.get_ticks() delta",
"if delta < self._tick_step: self._last_wait = self._tick_step - delta else:",
"b[ 1 ] for b in mod_bits if b[ 0",
"self._is_running == False: break # update the game display self.update()",
"self._last_tick = end_tick # update FPS value if delta >",
"= end_tick - self._last_tick self._last_tick = end_tick # update FPS",
"= 0 # set an FPS cap self._fps = 0.0",
") # set the title bar text and iconification text",
"# initialize the root display surface self.window = pygame.display.set_mode( size,",
") pygame.display.set_icon( icon ) # create a list of normal",
"pygame.KMOD_SHIFT, 'S' ) ] mod_str = ''.join( b[ 1 ]",
"update tick value before entering the loop self._last_tick = pygame.time.get_ticks()",
"), ( pygame.KMOD_SHIFT, 'S' ) ] mod_str = ''.join( b[",
"0, 32 ) # set the title bar text and",
"\"\"\" Zoe Game Engine Core Implementation =================================== Requirements ------------ [pygame](http://www.pygame.org/)",
"for various things self._debug = '' #========================================================================= def run( self",
"= pygame.display.set_mode( size, 0, 32 ) # set the title",
"display surface self.window = pygame.display.set_mode( size, 0, 32 ) #",
"mod_bits = [ ( pygame.KMOD_ALT, 'A' ), ( pygame.KMOD_CTRL, 'C'",
"/ self._fps_limit ) ) # engine is currently running self._is_running",
"if delta > 0: self._fps = 1000.0 / float( delta",
"= end_tick # update FPS value if delta > 0:",
"delta = end_tick - self._last_tick self._last_tick = end_tick # update",
"game display self.update() # ZIH - simulate hard work #pygame.time.delay(",
"do other stuff on this core pygame.time.wait( self._last_wait ) #",
"== pygame.QUIT: self._is_running = False # check for key event",
"if event.type == pygame.QUIT: self._is_running = False # check for",
"buffer. \"\"\" # fill the background self.window.fill( ( 32, 32,",
"poll the keys mods = pygame.key.get_mods() mod_bits = [ (",
"Updates the display. \"\"\" # update overlayed information self._top.set_text( '",
"break # update the game display self.update() # ZIH -",
") # engine is currently running self._is_running = False #",
"'C' ), ( pygame.KMOD_SHIFT, 'S' ) ] mod_str = ''.join(",
"self.window.fill( ( 32, 32, 32 ) ) # blit all",
"self._top = layer.TextLayer() # initialize last tick value self._last_tick =",
"Implementation =================================== Requirements ------------ [pygame](http://www.pygame.org/) \"\"\" # core packages #",
"'' #========================================================================= def run( self ): \"\"\" Run the game",
"= [ ( pygame.KMOD_ALT, 'A' ), ( pygame.KMOD_CTRL, 'C' ),",
") elif event.type == pygame.KEYDOWN: self._debug = '({}){}'.format( mod_str, pygame.key.name(",
"self, size ): \"\"\" Initializes an Engine object. \"\"\" #",
"# shut down pygame pygame.quit() # return exit status return",
"game engine object. \"\"\" #========================================================================= def __init__( self, size ):",
"self._last_wait = 0 # let the OS do other stuff",
"events. \"\"\" # ZIH - temp, just seeing how to",
"False # check for key event elif ( event.type ==",
"onto the back buffer. \"\"\" # fill the background self.window.fill(",
"the background self.window.fill( ( 32, 32, 32 ) ) #",
"0 ] & mods ) if event.type == pygame.KEYUP: self._debug",
"before entering the loop self._last_tick = pygame.time.get_ticks() # execute infinite",
"value before entering the loop self._last_tick = pygame.time.get_ticks() # execute",
"self._fps_limit # compute remaining time available inside this iteration if",
"update the display (swap video buffers) pygame.display.update() #========================================================================= def _draw_layers(",
"other stuff on this core pygame.time.wait( self._last_wait ) # shut",
"create a list of normal display layers self._layers = []",
"'({})'.format( mod_str ) elif event.type == pygame.KEYDOWN: self._debug = '({}){}'.format(",
"core packages # third-party packages import pygame # local package",
"not return until the application quits). \"\"\" # update tick",
"overlayed information self._top.set_text( ' [ fps:{:4.0f} sch:{:3} tck:{:08} dbg:{} ]'.format(",
"# initialize last tick value self._last_tick = pygame.time.get_ticks() self._last_wait =",
"- self._last_tick self._last_tick = end_tick # update FPS value if",
"this core pygame.time.wait( self._last_wait ) # shut down pygame pygame.quit()",
"import layer __version__ = '0.0.0' #============================================================================= class Engine( object ):",
"information self._top.set_text( ' [ fps:{:4.0f} sch:{:3} tck:{:08} dbg:{} ]'.format( self._fps,",
"= '({}){}'.format( mod_str, pygame.key.name( event.key ) ) #========================================================================= def update(",
"# create a transparent \"top\" layer for overlayed information self._top",
"1 ] for b in mod_bits if b[ 0 ]",
"), ( pygame.KMOD_CTRL, 'C' ), ( pygame.KMOD_SHIFT, 'S' ) ]",
"# ZIH - simulate hard work #pygame.time.delay( 3 ) #",
"down pygame pygame.quit() # return exit status return 0 #=========================================================================",
"else: self._fps = self._fps_limit # compute remaining time available inside",
"user layers for layer in self._layers: layer.blit( self.window ) #",
"trigger_key_event( self, event ): \"\"\" Initiates key input events. \"\"\"",
"self._fps = 0.0 self._fps_limit = 120.0 self._tick_step = int( round(",
"end_tick - self._last_tick self._last_tick = end_tick # update FPS value",
"until the application quits). \"\"\" # update tick value before",
"set the title bar text and iconification text pygame.display.set_caption( 'Demonstration',",
"exit status return 0 #========================================================================= def trigger_key_event( self, event ):",
"= True while self._is_running: # process event queue for event",
"True while self._is_running: # process event queue for event in",
"in mod_bits if b[ 0 ] & mods ) if",
"self ): \"\"\" Updates the display. \"\"\" # update overlayed",
"key input events. \"\"\" # ZIH - temp, just seeing",
"#========================================================================= def run( self ): \"\"\" Run the game loop",
"# set the application icon icon = pygame.image.load( '../assets/z32.png' )",
"for event in pygame.event.get(): # check for quit event if",
"#========================================================================= def __init__( self, size ): \"\"\" Initializes an Engine",
") # compute duration of last event/render loop end_tick =",
"ZIH - temp, just seeing how to poll the keys",
"OS do other stuff on this core pygame.time.wait( self._last_wait )",
"= 120.0 self._tick_step = int( round( 1000.0 / self._fps_limit )",
"self._is_running: # process event queue for event in pygame.event.get(): #",
"FPS value if delta > 0: self._fps = 1000.0 /",
"Core Implementation =================================== Requirements ------------ [pygame](http://www.pygame.org/) \"\"\" # core packages",
"iconification text pygame.display.set_caption( 'Demonstration', 'Demo' ) # set the application",
"# update the display (swap video buffers) pygame.display.update() #========================================================================= def",
"layers for layer in self._layers: layer.blit( self.window ) # blit",
"\"\"\" #========================================================================= def __init__( self, size ): \"\"\" Initializes an",
"delta ) else: self._fps = self._fps_limit # compute remaining time",
"pygame.KMOD_ALT, 'A' ), ( pygame.KMOD_CTRL, 'C' ), ( pygame.KMOD_SHIFT, 'S'",
"]'.format( self._fps, self._last_wait, self._last_tick, self._debug ) ) # draw the",
"iteration if delta < self._tick_step: self._last_wait = self._tick_step - delta",
"pygame # local package import layer __version__ = '0.0.0' #=============================================================================",
"pygame pygame.quit() # return exit status return 0 #========================================================================= def",
"pygame initialization pygame.init() # initialize the root display surface self.window",
"# engine is currently running self._is_running = False # short",
"the keys mods = pygame.key.get_mods() mod_bits = [ ( pygame.KMOD_ALT,",
"self._draw_layers() # update the display (swap video buffers) pygame.display.update() #=========================================================================",
"Initializes an Engine object. \"\"\" # pygame initialization pygame.init() #",
"# compute duration of last event/render loop end_tick = pygame.time.get_ticks()",
"False: break # update the game display self.update() # ZIH",
"32, 32, 32 ) ) # blit all user layers",
"# core packages # third-party packages import pygame # local",
"the back buffer. \"\"\" # fill the background self.window.fill( (",
"ZIH - simulate hard work #pygame.time.delay( 3 ) # compute",
") else: self._fps = self._fps_limit # compute remaining time available",
"1000.0 / self._fps_limit ) ) # engine is currently running",
"== pygame.KEYUP ) : self.trigger_key_event( event ) # exit application",
"layer for overlayed information self._top = layer.TextLayer() # initialize last",
"delta else: self._last_wait = 0 # let the OS do",
"Engine object. \"\"\" # pygame initialization pygame.init() # initialize the",
"things self._debug = '' #========================================================================= def run( self ): \"\"\"",
"last event/render loop end_tick = pygame.time.get_ticks() delta = end_tick -",
"pygame.key.name( event.key ) ) #========================================================================= def update( self ): \"\"\"",
"running self._is_running = False # short debug string for various",
"32, 32 ) ) # blit all user layers for",
"Requirements ------------ [pygame](http://www.pygame.org/) \"\"\" # core packages # third-party packages",
"int( round( 1000.0 / self._fps_limit ) ) # engine is",
"# update tick value before entering the loop self._last_tick =",
"hard work #pygame.time.delay( 3 ) # compute duration of last",
"temp, just seeing how to poll the keys mods =",
"1000.0 / float( delta ) else: self._fps = self._fps_limit #",
"the title bar text and iconification text pygame.display.set_caption( 'Demonstration', 'Demo'",
"draw the display on the back buffer self._draw_layers() # update",
"= '' #========================================================================= def run( self ): \"\"\" Run the",
"blit all user layers for layer in self._layers: layer.blit( self.window",
"= pygame.image.load( '../assets/z32.png' ) pygame.display.set_icon( icon ) # create a",
"stuff on this core pygame.time.wait( self._last_wait ) # shut down",
"self._debug = '' #========================================================================= def run( self ): \"\"\" Run",
"== False: break # update the game display self.update() #",
"): \"\"\" Initiates key input events. \"\"\" # ZIH -",
"self._last_tick = pygame.time.get_ticks() # execute infinite application loop self._is_running =",
"simulate hard work #pygame.time.delay( 3 ) # compute duration of",
"# create a list of normal display layers self._layers =",
") #========================================================================= def update( self ): \"\"\" Updates the display.",
"): \"\"\" Initializes an Engine object. \"\"\" # pygame initialization",
"> 0: self._fps = 1000.0 / float( delta ) else:",
"Blits all the display layers onto the back buffer. \"\"\"",
"= layer.TextLayer() # initialize last tick value self._last_tick = pygame.time.get_ticks()",
"for b in mod_bits if b[ 0 ] & mods",
"[ fps:{:4.0f} sch:{:3} tck:{:08} dbg:{} ]'.format( self._fps, self._last_wait, self._last_tick, self._debug",
") # exit application loop if done if self._is_running ==",
"self._is_running = False # short debug string for various things",
"tck:{:08} dbg:{} ]'.format( self._fps, self._last_wait, self._last_tick, self._debug ) ) #",
"shut down pygame pygame.quit() # return exit status return 0",
"self._last_tick self._last_tick = end_tick # update FPS value if delta",
"# draw the display on the back buffer self._draw_layers() #",
"on this core pygame.time.wait( self._last_wait ) # shut down pygame",
"event.key ) ) #========================================================================= def update( self ): \"\"\" Updates",
"on the back buffer self._draw_layers() # update the display (swap",
"update( self ): \"\"\" Updates the display. \"\"\" # update",
") ) # engine is currently running self._is_running = False",
"0 # set an FPS cap self._fps = 0.0 self._fps_limit",
"): \"\"\" Run the game loop (does not return until",
"pygame.display.update() #========================================================================= def _draw_layers( self ): \"\"\" Blits all the",
"pygame.time.get_ticks() # execute infinite application loop self._is_running = True while",
"#========================================================================= def trigger_key_event( self, event ): \"\"\" Initiates key input",
"# fill the background self.window.fill( ( 32, 32, 32 )",
"_draw_layers( self ): \"\"\" Blits all the display layers onto",
"self._top.set_text( ' [ fps:{:4.0f} sch:{:3} tck:{:08} dbg:{} ]'.format( self._fps, self._last_wait,",
"pygame.time.get_ticks() delta = end_tick - self._last_tick self._last_tick = end_tick #",
"b in mod_bits if b[ 0 ] & mods )",
"0: self._fps = 1000.0 / float( delta ) else: self._fps",
"the OS do other stuff on this core pygame.time.wait( self._last_wait",
"event/render loop end_tick = pygame.time.get_ticks() delta = end_tick - self._last_tick",
"set an FPS cap self._fps = 0.0 self._fps_limit = 120.0",
"initialization pygame.init() # initialize the root display surface self.window =",
"( event.type == pygame.KEYUP ) : self.trigger_key_event( event ) #",
"] for b in mod_bits if b[ 0 ] &",
"a list of normal display layers self._layers = [] #",
"infinite application loop self._is_running = True while self._is_running: # process",
"# compute remaining time available inside this iteration if delta",
"mod_str = ''.join( b[ 1 ] for b in mod_bits",
"#============================================================================= class Engine( object ): \"\"\" Simple game engine object.",
"object ): \"\"\" Simple game engine object. \"\"\" #========================================================================= def",
"'Demonstration', 'Demo' ) # set the application icon icon =",
"mods = pygame.key.get_mods() mod_bits = [ ( pygame.KMOD_ALT, 'A' ),",
"event.type == pygame.QUIT: self._is_running = False # check for key",
"pygame.time.wait( self._last_wait ) # shut down pygame pygame.quit() # return",
"object. \"\"\" # pygame initialization pygame.init() # initialize the root",
"# let the OS do other stuff on this core",
"for quit event if event.type == pygame.QUIT: self._is_running = False",
"[ ( pygame.KMOD_ALT, 'A' ), ( pygame.KMOD_CTRL, 'C' ), (",
"last tick value self._last_tick = pygame.time.get_ticks() self._last_wait = 0 #",
"# check for quit event if event.type == pygame.QUIT: self._is_running",
"# pygame initialization pygame.init() # initialize the root display surface",
"quits). \"\"\" # update tick value before entering the loop",
"quit event if event.type == pygame.QUIT: self._is_running = False #",
"pygame.KEYDOWN: self._debug = '({}){}'.format( mod_str, pygame.key.name( event.key ) ) #=========================================================================",
"tick value self._last_tick = pygame.time.get_ticks() self._last_wait = 0 # set",
"event ) # exit application loop if done if self._is_running",
") # shut down pygame pygame.quit() # return exit status",
"Engine Core Implementation =================================== Requirements ------------ [pygame](http://www.pygame.org/) \"\"\" # core",
"surface self.window = pygame.display.set_mode( size, 0, 32 ) # set",
"import pygame # local package import layer __version__ = '0.0.0'",
"(does not return until the application quits). \"\"\" # update",
"input events. \"\"\" # ZIH - temp, just seeing how",
"__init__( self, size ): \"\"\" Initializes an Engine object. \"\"\"",
"= False # check for key event elif ( event.type",
"def run( self ): \"\"\" Run the game loop (does",
"pygame.display.set_caption( 'Demonstration', 'Demo' ) # set the application icon icon",
"application icon icon = pygame.image.load( '../assets/z32.png' ) pygame.display.set_icon( icon )",
"self._is_running = True while self._is_running: # process event queue for",
"back buffer self._draw_layers() # update the display (swap video buffers)",
"various things self._debug = '' #========================================================================= def run( self ):",
"create a transparent \"top\" layer for overlayed information self._top ="
] |
[
"09:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies =",
"operations = [ migrations.AlterField( model_name='profiles', name='Qu_Shares', field=models.IntegerField(default=0), ), migrations.AlterField( model_name='profiles',",
"'0003_auto_20201113_2210'), ] operations = [ migrations.AlterField( model_name='profiles', name='Qu_Shares', field=models.IntegerField(default=0), ),",
"Generated by Django 3.0.6 on 2020-11-15 09:05 from django.db import",
"django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Authentication',",
"model_name='profiles', name='Qu_Shares', field=models.IntegerField(default=0), ), migrations.AlterField( model_name='profiles', name='Questionnais', field=models.IntegerField(default=0), ), ]",
"migrations, models class Migration(migrations.Migration): dependencies = [ ('Authentication', '0003_auto_20201113_2210'), ]",
"class Migration(migrations.Migration): dependencies = [ ('Authentication', '0003_auto_20201113_2210'), ] operations =",
"dependencies = [ ('Authentication', '0003_auto_20201113_2210'), ] operations = [ migrations.AlterField(",
"on 2020-11-15 09:05 from django.db import migrations, models class Migration(migrations.Migration):",
"# Generated by Django 3.0.6 on 2020-11-15 09:05 from django.db",
"] operations = [ migrations.AlterField( model_name='profiles', name='Qu_Shares', field=models.IntegerField(default=0), ), migrations.AlterField(",
"[ ('Authentication', '0003_auto_20201113_2210'), ] operations = [ migrations.AlterField( model_name='profiles', name='Qu_Shares',",
"migrations.AlterField( model_name='profiles', name='Qu_Shares', field=models.IntegerField(default=0), ), migrations.AlterField( model_name='profiles', name='Questionnais', field=models.IntegerField(default=0), ),",
"Migration(migrations.Migration): dependencies = [ ('Authentication', '0003_auto_20201113_2210'), ] operations = [",
"Django 3.0.6 on 2020-11-15 09:05 from django.db import migrations, models",
"from django.db import migrations, models class Migration(migrations.Migration): dependencies = [",
"= [ migrations.AlterField( model_name='profiles', name='Qu_Shares', field=models.IntegerField(default=0), ), migrations.AlterField( model_name='profiles', name='Questionnais',",
"3.0.6 on 2020-11-15 09:05 from django.db import migrations, models class",
"models class Migration(migrations.Migration): dependencies = [ ('Authentication', '0003_auto_20201113_2210'), ] operations",
"by Django 3.0.6 on 2020-11-15 09:05 from django.db import migrations,",
"[ migrations.AlterField( model_name='profiles', name='Qu_Shares', field=models.IntegerField(default=0), ), migrations.AlterField( model_name='profiles', name='Questionnais', field=models.IntegerField(default=0),",
"= [ ('Authentication', '0003_auto_20201113_2210'), ] operations = [ migrations.AlterField( model_name='profiles',",
"<filename>Authentication/migrations/0004_auto_20201115_1105.py # Generated by Django 3.0.6 on 2020-11-15 09:05 from",
"('Authentication', '0003_auto_20201113_2210'), ] operations = [ migrations.AlterField( model_name='profiles', name='Qu_Shares', field=models.IntegerField(default=0),",
"2020-11-15 09:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies",
"import migrations, models class Migration(migrations.Migration): dependencies = [ ('Authentication', '0003_auto_20201113_2210'),"
] |
[
"import TemplateView from .views import dashboard_cost, dashboard_energy, MotorDataListView app_name =",
"MotorDataListView.as_view(), name='dashboard_custom'), #path('', dashboard_custom, name='dashboard_custom'), path('energy', dashboard_energy, name='dashboard_energy'), path('cost', dashboard_cost,",
"from django.urls import path, re_path from django.views.generic.base import TemplateView from",
"TemplateView from .views import dashboard_cost, dashboard_energy, MotorDataListView app_name = 'dashboard'",
"= [ path('', MotorDataListView.as_view(), name='dashboard_custom'), #path('', dashboard_custom, name='dashboard_custom'), path('energy', dashboard_energy,",
"#path('', dashboard_custom, name='dashboard_custom'), path('energy', dashboard_energy, name='dashboard_energy'), path('cost', dashboard_cost, name='dashboard_cost'), ]",
"<filename>dashboard/urls.py from django.urls import path, re_path from django.views.generic.base import TemplateView",
"import dashboard_cost, dashboard_energy, MotorDataListView app_name = 'dashboard' urlpatterns = [",
"path, re_path from django.views.generic.base import TemplateView from .views import dashboard_cost,",
".views import dashboard_cost, dashboard_energy, MotorDataListView app_name = 'dashboard' urlpatterns =",
"MotorDataListView app_name = 'dashboard' urlpatterns = [ path('', MotorDataListView.as_view(), name='dashboard_custom'),",
"app_name = 'dashboard' urlpatterns = [ path('', MotorDataListView.as_view(), name='dashboard_custom'), #path('',",
"path('', MotorDataListView.as_view(), name='dashboard_custom'), #path('', dashboard_custom, name='dashboard_custom'), path('energy', dashboard_energy, name='dashboard_energy'), path('cost',",
"re_path from django.views.generic.base import TemplateView from .views import dashboard_cost, dashboard_energy,",
"django.urls import path, re_path from django.views.generic.base import TemplateView from .views",
"= 'dashboard' urlpatterns = [ path('', MotorDataListView.as_view(), name='dashboard_custom'), #path('', dashboard_custom,",
"django.views.generic.base import TemplateView from .views import dashboard_cost, dashboard_energy, MotorDataListView app_name",
"from django.views.generic.base import TemplateView from .views import dashboard_cost, dashboard_energy, MotorDataListView",
"'dashboard' urlpatterns = [ path('', MotorDataListView.as_view(), name='dashboard_custom'), #path('', dashboard_custom, name='dashboard_custom'),",
"from .views import dashboard_cost, dashboard_energy, MotorDataListView app_name = 'dashboard' urlpatterns",
"urlpatterns = [ path('', MotorDataListView.as_view(), name='dashboard_custom'), #path('', dashboard_custom, name='dashboard_custom'), path('energy',",
"[ path('', MotorDataListView.as_view(), name='dashboard_custom'), #path('', dashboard_custom, name='dashboard_custom'), path('energy', dashboard_energy, name='dashboard_energy'),",
"dashboard_energy, MotorDataListView app_name = 'dashboard' urlpatterns = [ path('', MotorDataListView.as_view(),",
"import path, re_path from django.views.generic.base import TemplateView from .views import",
"name='dashboard_custom'), #path('', dashboard_custom, name='dashboard_custom'), path('energy', dashboard_energy, name='dashboard_energy'), path('cost', dashboard_cost, name='dashboard_cost'),",
"dashboard_cost, dashboard_energy, MotorDataListView app_name = 'dashboard' urlpatterns = [ path('',"
] |
[
"= input(\"Enter rate:\") pay = float(hrs) * float(rate) print(\"Pay: \"",
"= input(\"Enter Hours:\") rate = input(\"Enter rate:\") pay = float(hrs)",
"rate = input(\"Enter rate:\") pay = float(hrs) * float(rate) print(\"Pay:",
"input(\"Enter rate:\") pay = float(hrs) * float(rate) print(\"Pay: \" +str(pay))",
"input(\"Enter Hours:\") rate = input(\"Enter rate:\") pay = float(hrs) *",
"hrs = input(\"Enter Hours:\") rate = input(\"Enter rate:\") pay =",
"Hours:\") rate = input(\"Enter rate:\") pay = float(hrs) * float(rate)"
] |
[
"(\"ddram\", 0, Subsignal(\"a\", Pins( \"AE17 AH17 AE18 AJ15 AG16 AL17",
"\"LA14_N\" : \"A10\", \"LA18_CC_P\" : \"E22\", \"LA18_CC_N\" : \"E23\", \"LA27_P\"",
": \"G16\", \"HA04_P\" : \"G19\", \"HA04_N\" : \"F19\", \"HA08_P\" :",
"Pins(\"V2\")), Subsignal(\"rxn\", Pins(\"V1\")) ), (\"sfp_tx\", 1, Subsignal(\"p\", Pins(\"W4\")), Subsignal(\"n\", Pins(\"W3\")),",
"#Subsignal(\"ten\", Pins(\"AH16\"), IOStandard(\"SSTL12_DCI\")), #Subsignal(\"alert_n\", Pins(\"AJ16\"), IOStandard(\"SSTL12_DCI\")), #Subsignal(\"par\", Pins(\"AD18\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"dm\",",
"Pins(\"P26\"), IOStandard(\"LVDS_25\")), Subsignal(\"n\", Pins(\"N26\"), IOStandard(\"LVDS_25\")) ), # SI570 (\"si570_refclk\", 0,",
"AN9 AH9 AH8\"), Misc(\"PULLUP True\")), Misc(\"SLEW=FAST\"), IOStandard(\"LVCMOS18\") ), # Rotary",
"\"HA04_N\" : \"F19\", \"HA08_P\" : \"K18\", \"HA08_N\" : \"K17\", \"HA12_P\"",
"\"L8\", \"LA10_N\" : \"K8\", \"LA14_P\" : \"B10\", \"LA14_N\" : \"A10\",",
"\"LA15_N\" : \"AB26\", \"LA19_P\" : \"AA29\", \"LA19_N\" : \"AB29\", \"LA21_P\"",
"), (\"user_sma_clock_p\", 0, Pins(\"D23\"), IOStandard(\"LVCMOS18\")), (\"user_sma_clock_n\", 0, Pins(\"C23\"), IOStandard(\"LVCMOS18\")), (\"user_sma_gpio\",",
"\"AB21\", \"LA16_N\" : \"AC21\", \"LA20_P\" : \"AA34\", \"LA20_N\" : \"AB34\",",
": \"F25\", \"LA25_P\" : \"D20\", \"LA25_N\" : \"D21\", \"LA29_P\" :",
": \"B21\", \"LA28_N\" : \"B22\", \"LA30_P\" : \"C26\", \"LA30_N\" :",
": \"G21\", \"HA01_CC_P\" : \"E16\", \"HA01_CC_N\" : \"D16\", \"HA05_P\" :",
"AL28 AP30 AJ33 AP34\"), IOStandard(\"DIFF_POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"clk_p\", Pins(\"AE16\"), IOStandard(\"DIFF_SSTL12_DCI\")),",
": \"C9\", \"LA17_CC_P\" : \"D24\", \"LA17_CC_N\" : \"C24\", \"LA23_P\" :",
"Subsignal(\"rx_p\", Pins(\"AB2 AD2 AF2 AH2\")), Subsignal(\"rx_n\", Pins(\"AB1 AD1 AF1 AH1\")),",
"\"H2\", \"DP5_M2C_N\" : \"H1\", \"DP6_C2M_P\" : \"L4\", \"DP6_C2M_N\" : \"L3\",",
"# HDMI (\"hdmi\", 0, Subsignal(\"d\", Pins( \"AK11 AP11 AP13 AN13",
"AN22 AP24 AM22\", \"AH28 AK26 AK28 AM27 AJ28 AH27 AK27",
"Pins(\"U7\")), Subsignal(\"dq\", Pins(\"AC7 AB7 AA7 Y7\")), IOStandard(\"LVCMOS18\") ), (\"spiflash\", 1,",
"IOStandard(\"LVCMOS18\")), (\"user_btn_n\", 0, Pins(\"AD10\"), IOStandard(\"LVCMOS18\")), (\"user_btn_s\", 0, Pins(\"AF8\"), IOStandard(\"LVCMOS18\")), (\"user_btn_w\",",
"0, Pins(\"C23\"), IOStandard(\"LVCMOS18\")), (\"user_sma_gpio\", 0, Subsignal(\"p\", Pins(\"H27\"), IOStandard(\"LVDS\")), Subsignal(\"n\", Pins(\"G27\"),",
": \"D1\", \"DP2_C2M_P\" : \"C4\", \"DP2_C2M_N\" : \"C3\", \"DP2_M2C_P\" :",
"Pins(\"AL10\")), Subsignal(\"cs_n\", Pins(\"AH8\")), Subsignal(\"mosi\", Pins(\"AD9\"), Misc(\"PULLUP\")), Subsignal(\"miso\", Pins(\"AP9\"), Misc(\"PULLUP\")), Misc(\"SLEW=FAST\"),",
"Pins( \"AE23 AG20 AF22 AF20 AE22 AD20 AG22 AE20\", \"AJ24",
"----------------------------------------------------------------------------------------- class Platform(XilinxPlatform): default_clk_name = \"clk125\" default_clk_period = 1e9/125e6 def",
"\"M1\", \"DP5_C2M_P\" : \"J4\", \"DP5_C2M_N\" : \"J3\", \"DP5_M2C_P\" : \"H2\",",
": \"V34\", \"LA31_P\" : \"V33\", \"LA31_N\" : \"W34\", \"LA33_P\" :",
": \"B10\", \"LA14_N\" : \"A10\", \"LA18_CC_P\" : \"E22\", \"LA18_CC_N\" :",
"L20 R21 R22\")), IOStandard(\"LVCMOS18\") ), # SDCard (\"spisdcard\", 0, Subsignal(\"clk\",",
": \"B9\", \"LA16_N\" : \"A9\", \"LA20_P\" : \"B24\", \"LA20_N\" :",
"\"HA04_P\" : \"G19\", \"HA04_N\" : \"F19\", \"HA08_P\" : \"K18\", \"HA08_N\"",
"Subsignal(\"txn\", Pins(\"U3\")), Subsignal(\"rxp\", Pins(\"T2\")), Subsignal(\"rxn\", Pins(\"T1\")) ), (\"sfp_tx\", 0, Subsignal(\"p\",",
"\"G20\", \"LA26_N\" : \"F20\", \"PG_M2C\" : \"L27\", \"HA00_CC_P\" : \"G17\",",
"\"HA15_N\" : \"C14\", \"HA19_P\" : \"D19\", \"HA19_N\" : \"D18\", \"PRSNT_M2C_B\"",
"\"LA09_P\" : \"V26\", \"LA09_N\" : \"W26\", \"LA13_P\" : \"AA20\", \"LA13_N\"",
"\"W29\", \"LA10_P\" : \"T22\", \"LA10_N\" : \"T23\", \"LA14_P\" : \"U21\",",
"Subsignal(\"n\", Pins(\"W3\")), ), (\"sfp_rx\", 1, Subsignal(\"p\", Pins(\"V2\")), Subsignal(\"n\", Pins(\"V1\")), ),",
"Subsignal(\"tx_n\", Pins(\"AC3 AE3 AG3 AH5 AK5 AL3 AM5 AN3\")) ),",
"\"LA24_N\" : \"AF32\", \"LA28_P\" : \"V31\", \"LA28_N\" : \"W31\", \"LA30_P\"",
"(\"sfp_tx_disable_n\", 0, Pins(\"AL8\"), IOStandard(\"LVCMOS18\")), (\"sfp\", 1, Subsignal(\"txp\", Pins(\"W4\")), Subsignal(\"txn\", Pins(\"W3\")),",
"\"HA19_P\" : \"D19\", \"HA19_N\" : \"D18\", \"PRSNT_M2C_B\" : \"H24\", \"CLK0_M2C_P\"",
": \"AG31\", \"LA27_N\" : \"AG32\", \"CLK1_M2C_P\" : \"AC31\", \"CLK1_M2C_N\" :",
"AL13 AK13 AD11 AH12 AG12 AJ11\", \"AG10 AK8\")), Subsignal(\"de\", Pins(\"AE11\")),",
"# Switches (\"user_dip_btn\", 0, Pins(\"AN16\"), IOStandard(\"LVCMOS12\")), (\"user_dip_btn\", 1, Pins(\"AN19\"), IOStandard(\"LVCMOS12\")),",
"), (\"clk300\", 0, Subsignal(\"p\", Pins(\"AK17\"), IOStandard(\"DIFF_SSTL12\")), Subsignal(\"n\", Pins(\"AK16\"), IOStandard(\"DIFF_SSTL12\")) ),",
"\"D19\", \"HA19_N\" : \"D18\", \"PRSNT_M2C_B\" : \"H24\", \"CLK0_M2C_P\" : \"H12\",",
": \"V29\", \"LA06_N\" : \"W29\", \"LA10_P\" : \"T22\", \"LA10_N\" :",
"Subsignal(\"vsync\", Pins(\"AH13\")), Subsignal(\"hsync\", Pins(\"AE13\")), Subsignal(\"spdif\", Pins(\"AE12\")), Subsignal(\"spdif_out\", Pins(\"AF12\")), IOStandard(\"LVCMOS18\") ),",
"\"LA28_N\" : \"B22\", \"LA30_P\" : \"C26\", \"LA30_N\" : \"B26\", \"LA32_P\"",
"\"AF33\", \"LA26_N\" : \"AG34\", \"CLK0_M2C_P\" : \"AA24\", \"CLK0_M2C_N\" : \"AA25\",",
"AP24 AM22\", \"AH28 AK26 AK28 AM27 AJ28 AH27 AK27 AM26\",",
"1, Subsignal(\"p\", Pins(\"V2\")), Subsignal(\"n\", Pins(\"V1\")), ), (\"sfp_tx_disable_n\", 1, Pins(\"D28\"), IOStandard(\"LVCMOS18\")),",
"\"LA14_P\" : \"U21\", \"LA14_N\" : \"U22\", \"LA18_CC_P\" : \"AB30\", \"LA18_CC_N\"",
"\"AG32\", \"CLK1_M2C_P\" : \"AC31\", \"CLK1_M2C_N\" : \"AC32\", \"LA00_CC_P\" : \"W23\",",
"\"U26\", \"LA04_N\" : \"U27\", \"LA07_P\" : \"V22\", \"LA07_N\" : \"V23\",",
": \"AA24\", \"GBTCLK0_M2C_N\" : \"AA25\", \"LA01_CC_P\" : \"W25\", \"LA01_CC_N\" :",
"Pins(\"H27\"), IOStandard(\"LVDS\")), Subsignal(\"n\", Pins(\"G27\"), IOStandard(\"LVDS\")) ), (\"user_sma_gpio_p\", 0, Pins(\"H27\"), IOStandard(\"LVCMOS18\")),",
"_connectors, toolchain=\"vivado\") def create_programmer(self): return VivadoProgrammer() def do_finalize(self, fragment): XilinxPlatform.do_finalize(self,",
"\"G15\", \"HA03_N\" : \"G14\", \"HA07_P\" : \"L19\", \"HA07_N\" : \"L18\",",
"\"M2\", \"DP4_M2C_N\" : \"M1\", \"DP5_C2M_P\" : \"J4\", \"DP5_C2M_N\" : \"J3\",",
"Subsignal(\"txn\", Pins(\"W3\")), Subsignal(\"rxp\", Pins(\"V2\")), Subsignal(\"rxn\", Pins(\"V1\")) ), (\"sfp_tx\", 1, Subsignal(\"p\",",
"\"W26\", \"LA13_P\" : \"AA20\", \"LA13_N\" : \"AB20\", \"LA17_CC_P\" : \"AA32\",",
"IOStandard(\"LVCMOS12\")), (\"user_dip_btn\", 1, Pins(\"AN19\"), IOStandard(\"LVCMOS12\")), (\"user_dip_btn\", 2, Pins(\"AP18\"), IOStandard(\"LVCMOS12\")), (\"user_dip_btn\",",
"* from litex.build.xilinx import XilinxPlatform, VivadoProgrammer # IOs ---------------------------------------------------------------------------------------------- _io",
": \"H2\", \"DP5_M2C_N\" : \"H1\", \"DP6_C2M_P\" : \"L4\", \"DP6_C2M_N\" :",
"Pins(\"AB1\")), Subsignal(\"tx_p\", Pins(\"AC4\")), Subsignal(\"tx_n\", Pins(\"AC3\")) ), (\"pcie_x2\", 0, Subsignal(\"rst_n\", Pins(\"K22\"),",
"\"DP3_M2C_N\" : \"A3\", \"DP4_C2M_P\" : \"N4\", \"DP4_C2M_N\" : \"N3\", \"DP4_M2C_P\"",
"AL25 AM20 AK23 AK22 AL24 AL20 AL23\", \"AM24 AN23 AN24",
": \"B22\", \"LA30_P\" : \"C26\", \"LA30_N\" : \"B26\", \"LA32_P\" :",
"\"LA05_N\" : \"K13\", \"LA09_P\" : \"J9\", \"LA09_N\" : \"H9\", \"LA13_P\"",
"primitive Subsignal(\"cs_n\", Pins(\"U7\")), Subsignal(\"dq\", Pins(\"AC7 AB7 AA7 Y7\")), IOStandard(\"LVCMOS18\") ),",
": \"M1\", \"DP5_C2M_P\" : \"J4\", \"DP5_C2M_N\" : \"J3\", \"DP5_M2C_P\" :",
"AG19\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"ba\", Pins(\"AF17 AL15\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"bg\", Pins(\"AG15\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"ras_n\",",
"\"LA02_P\" : \"K10\", \"LA02_N\" : \"J10\", \"LA04_P\" : \"L12\", \"LA04_N\"",
"XilinxPlatform, VivadoProgrammer # IOs ---------------------------------------------------------------------------------------------- _io = [ # Clk",
"\"AA25\", \"LA01_CC_P\" : \"W25\", \"LA01_CC_N\" : \"Y25\", \"LA05_P\" : \"V27\",",
"Subsignal(\"rx_p\", Pins(\"AB2\")), Subsignal(\"rx_n\", Pins(\"AB1\")), Subsignal(\"tx_p\", Pins(\"AC4\")), Subsignal(\"tx_n\", Pins(\"AC3\")) ), (\"pcie_x2\",",
"Subsignal(\"rx_n\", Pins(\"AB1\")), Subsignal(\"tx_p\", Pins(\"AC4\")), Subsignal(\"tx_n\", Pins(\"AC3\")) ), (\"pcie_x2\", 0, Subsignal(\"rst_n\",",
"Subsignal(\"p\", Pins(\"H27\"), IOStandard(\"LVDS\")), Subsignal(\"n\", Pins(\"G27\"), IOStandard(\"LVDS\")) ), (\"user_sma_gpio_p\", 0, Pins(\"H27\"),",
"\"A10\", \"LA18_CC_P\" : \"E22\", \"LA18_CC_N\" : \"E23\", \"LA27_P\" : \"H21\",",
"Pins(\"AH14\"), IOStandard(\"SSTL12_DCI\")), #Subsignal(\"ten\", Pins(\"AH16\"), IOStandard(\"SSTL12_DCI\")), #Subsignal(\"alert_n\", Pins(\"AJ16\"), IOStandard(\"SSTL12_DCI\")), #Subsignal(\"par\", Pins(\"AD18\"),",
": \"J3\", \"DP5_M2C_P\" : \"H2\", \"DP5_M2C_N\" : \"H1\", \"DP6_C2M_P\" :",
": \"AC31\", \"CLK1_M2C_N\" : \"AC32\", \"LA00_CC_P\" : \"W23\", \"LA00_CC_N\" :",
"AH26 AN26 AJ29 AL32\"), IOStandard(\"POD12_DCI\")), Subsignal(\"dq\", Pins( \"AE23 AG20 AF22",
"Pins(\"AB2 AD2 AF2 AH2\")), Subsignal(\"rx_n\", Pins(\"AB1 AD1 AF1 AH1\")), Subsignal(\"tx_p\",",
"\"HA00_CC_P\" : \"G17\", \"HA00_CC_N\" : \"G16\", \"HA04_P\" : \"G19\", \"HA04_N\"",
": \"K8\", \"LA14_P\" : \"B10\", \"LA14_N\" : \"A10\", \"LA18_CC_P\" :",
"AF22 AF20 AE22 AD20 AG22 AE20\", \"AJ24 AG24 AJ23 AF23",
"IOStandard(\"LVCMOS18\")), (\"sfp\", 1, Subsignal(\"txp\", Pins(\"W4\")), Subsignal(\"txn\", Pins(\"W3\")), Subsignal(\"rxp\", Pins(\"V2\")), Subsignal(\"rxn\",",
"\"B25\", \"LA31_N\" : \"A25\", \"LA33_P\" : \"A27\", \"LA33_N\" : \"A28\",",
": \"U24\", \"LA08_N\" : \"U25\", \"LA12_P\" : \"AC22\", \"LA12_N\" :",
"AE4 AG4 AH6 AK6 AL4 AM6 AN4\")), Subsignal(\"tx_n\", Pins(\"AC3 AE3",
"\"DP1_M2C_N\" : \"D1\", \"DP2_C2M_P\" : \"C4\", \"DP2_C2M_N\" : \"C3\", \"DP2_M2C_P\"",
": \"D26\", \"HA02_P\" : \"H19\", \"HA02_N\" : \"H18\", \"HA06_P\" :",
": \"AE33\", \"LA25_N\" : \"AF34\", \"LA29_P\" : \"U34\", \"LA29_N\" :",
"self.add_period_constraint(self.lookup_request(\"clk300\", loose=True), 1e9/300e6) self.add_platform_command(\"set_property INTERNAL_VREF 0.84 [get_iobanks 44]\") self.add_platform_command(\"set_property INTERNAL_VREF",
"\"AE32\", \"LA24_N\" : \"AF32\", \"LA28_P\" : \"V31\", \"LA28_N\" : \"W31\",",
"), (\"user_sma_mgt_rx\", 0, Subsignal(\"p\", Pins(\"P2\")), Subsignal(\"n\", Pins(\"P1\")) ), # SFP",
"\"GBTCLK0_M2C_P\" : \"K6\", \"GBTCLK0_M2C_N\" : \"K5\", \"LA01_CC_P\" : \"G9\", \"LA01_CC_N\"",
"Encoder (\"rotary\", 0, Subsignal(\"a\", Pins(\"Y21\")), Subsignal(\"b\", Pins(\"AD26\")), Subsignal(\"push\", Pins(\"AF28\")), IOStandard(\"LVCMOS18\")",
"\"F9\", \"LA05_P\" : \"L13\", \"LA05_N\" : \"K13\", \"LA09_P\" : \"J9\",",
"\"HA00_CC_N\" : \"G16\", \"HA04_P\" : \"G19\", \"HA04_N\" : \"F19\", \"HA08_P\"",
"AH8\"), Misc(\"PULLUP True\")), Misc(\"SLEW=FAST\"), IOStandard(\"LVCMOS18\") ), # Rotary Encoder (\"rotary\",",
": \"K16\", \"HA12_N\" : \"J16\", \"HA15_P\" : \"D14\", \"HA15_N\" :",
": \"B24\", \"LA20_N\" : \"A24\", \"LA22_P\" : \"G24\", \"LA22_N\" :",
"AJ30 AH34 AK32\", \"AN33 AP33 AM34 AP31 AM32 AN31 AL34",
"SI570 (\"si570_refclk\", 0, Subsignal(\"p\", Pins(\"P6\")), Subsignal(\"n\", Pins(\"P5\")) ), # SMA",
": \"L8\", \"LA10_N\" : \"K8\", \"LA14_P\" : \"B10\", \"LA14_N\" :",
"AJ21 AM21 AH26 AN26 AJ29 AL32\"), IOStandard(\"POD12_DCI\")), Subsignal(\"dq\", Pins( \"AE23",
"Pins( \"AK11 AP11 AP13 AN13 AN11 AM11 AN12 AM12\", \"AL12",
"\"DP3_C2M_P\" : \"B6\", \"DP3_C2M_N\" : \"B5\", \"DP3_M2C_P\" : \"A4\", \"DP3_M2C_N\"",
"Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"clk_p\", Pins(\"AE16\"), IOStandard(\"DIFF_SSTL12_DCI\")), Subsignal(\"clk_n\", Pins(\"AE15\"), IOStandard(\"DIFF_SSTL12_DCI\")), Subsignal(\"cke\", Pins(\"AD15\"), IOStandard(\"SSTL12_DCI\")),",
"\"AD33\", \"LA24_P\" : \"AE32\", \"LA24_N\" : \"AF32\", \"LA28_P\" : \"V31\",",
": \"E17\", \"HA21_P\" : \"E15\", \"HA21_N\" : \"D15\", \"HA23_P\" :",
"\"HA20_N\" : \"B19\", \"CLK1_M2C_P\" : \"E25\", \"CLK1_M2C_N\" : \"D25\", \"LA00_CC_P\"",
"\"LA19_N\" : \"C22\", \"LA21_P\" : \"F23\", \"LA21_N\" : \"F24\", \"LA24_P\"",
"is part of LiteX-Boards. # # Copyright (c) 2017-2019 <NAME>",
"Pins(\"AC3\")) ), (\"pcie_x2\", 0, Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\",",
"IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2\")), Subsignal(\"rx_n\", Pins(\"AB1\")), Subsignal(\"tx_p\",",
": \"C13\", \"LA10_P\" : \"L8\", \"LA10_N\" : \"K8\", \"LA14_P\" :",
"\"Y31\", \"LA30_N\" : \"Y32\", \"LA32_P\" : \"W30\", \"LA32_N\" : \"Y30\",",
"/ Rst (\"clk125\", 0, Subsignal(\"p\", Pins(\"G10\"), IOStandard(\"LVDS\")), Subsignal(\"n\", Pins(\"F10\"), IOStandard(\"LVDS\"))",
"Subsignal(\"rx_p\", Pins(\"AB2 AD2\")), Subsignal(\"rx_n\", Pins(\"AB1 AD1\")), Subsignal(\"tx_p\", Pins(\"AC4 AE4\")), Subsignal(\"tx_n\",",
"\"LA14_N\" : \"U22\", \"LA18_CC_P\" : \"AB30\", \"LA18_CC_N\" : \"AB31\", \"LA27_P\"",
"Pins(\"H23\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 2, Pins(\"P20\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 3, Pins(\"P21\"), IOStandard(\"LVCMOS18\")),",
"Pins(\"AH21 AJ25 AK20 AP21 AL28 AP30 AJ33 AP34\"), IOStandard(\"DIFF_POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"),",
": \"K5\", \"LA01_CC_P\" : \"G9\", \"LA01_CC_N\" : \"F9\", \"LA05_P\" :",
"litex.build.generic_platform import * from litex.build.xilinx import XilinxPlatform, VivadoProgrammer # IOs",
"IOStandard(\"DIFF_SSTL12_DCI\")), Subsignal(\"clk_n\", Pins(\"AE15\"), IOStandard(\"DIFF_SSTL12_DCI\")), Subsignal(\"cke\", Pins(\"AD15\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"odt\", Pins(\"AJ18\"), IOStandard(\"SSTL12_DCI\")),",
": \"F19\", \"HA08_P\" : \"K18\", \"HA08_N\" : \"K17\", \"HA12_P\" :",
"\"DP2_M2C_N\" : \"B1\", \"DP3_C2M_P\" : \"B6\", \"DP3_C2M_N\" : \"B5\", \"DP3_M2C_P\"",
"\"HA10_P\" : \"H17\", \"HA10_N\" : \"H16\", \"HA17_CC_P\" : \"E18\", \"HA17_CC_N\"",
"\"HA09_P\" : \"F18\", \"HA09_N\" : \"F17\", \"HA13_P\" : \"B14\", \"HA13_N\"",
": \"V27\", \"LA05_N\" : \"V28\", \"LA09_P\" : \"V26\", \"LA09_N\" :",
"\"A12\", \"LA08_P\" : \"J8\", \"LA08_N\" : \"H8\", \"LA12_P\" : \"E10\",",
"Pins(\"AG14\"), IOStandard(\"SSTL12_DCI\")), # A15 Subsignal(\"we_n\", Pins(\"AD16\"), IOStandard(\"SSTL12_DCI\")), # A14 Subsignal(\"cs_n\",",
"\"Y33\", } ), (\"pmod0\", \"AK25 AN21 AH18 AM19 AE26 AF25",
"Pins(\"AN8\"), IOStandard(\"LVCMOS18\")), # Leds (\"user_led\", 0, Pins(\"AP8\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 1,",
"A15 Subsignal(\"we_n\", Pins(\"AD16\"), IOStandard(\"SSTL12_DCI\")), # A14 Subsignal(\"cs_n\", Pins(\"AL19\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"act_n\",",
"\"AC21\", \"LA20_P\" : \"AA34\", \"LA20_N\" : \"AB34\", \"LA22_P\" : \"AC34\",",
": \"G24\", \"LA22_N\" : \"F25\", \"LA25_P\" : \"D20\", \"LA25_N\" :",
"Subsignal(\"n\", Pins(\"V1\")), ), (\"sfp_tx_disable_n\", 1, Pins(\"D28\"), IOStandard(\"LVCMOS18\")), ] # Connectors",
"\"DP0_C2M_N\" : \"F5\", \"DP0_M2C_P\" : \"E4\", \"DP0_M2C_N\" : \"E3\", \"DP1_C2M_P\"",
"# Platform ----------------------------------------------------------------------------------------- class Platform(XilinxPlatform): default_clk_name = \"clk125\" default_clk_period =",
"\"LA08_P\" : \"J8\", \"LA08_N\" : \"H8\", \"LA12_P\" : \"E10\", \"LA12_N\"",
"(\"user_dip_btn\", 2, Pins(\"AP18\"), IOStandard(\"LVCMOS12\")), (\"user_dip_btn\", 3, Pins(\"AN14\"), IOStandard(\"LVCMOS12\")), # SMA",
"IOStandard(\"SSTL12_DCI\")), # A16 Subsignal(\"cas_n\", Pins(\"AG14\"), IOStandard(\"SSTL12_DCI\")), # A15 Subsignal(\"we_n\", Pins(\"AD16\"),",
"\"LA16_N\" : \"A9\", \"LA20_P\" : \"B24\", \"LA20_N\" : \"A24\", \"LA22_P\"",
"0, Subsignal(\"p\", Pins(\"AK17\"), IOStandard(\"DIFF_SSTL12\")), Subsignal(\"n\", Pins(\"AK16\"), IOStandard(\"DIFF_SSTL12\")) ), (\"cpu_reset\", 0,",
"True\")), Misc(\"SLEW=FAST\"), IOStandard(\"LVCMOS18\") ), # Rotary Encoder (\"rotary\", 0, Subsignal(\"a\",",
": \"B2\", \"DP2_M2C_N\" : \"B1\", \"DP3_C2M_P\" : \"B6\", \"DP3_C2M_N\" :",
": \"A27\", \"LA33_N\" : \"A28\", \"HA03_P\" : \"G15\", \"HA03_N\" :",
"Pins(\"AN14\"), IOStandard(\"LVCMOS12\")), # SMA (\"user_sma_clock\", 0, Subsignal(\"p\", Pins(\"D23\"), IOStandard(\"LVDS\")), Subsignal(\"n\",",
"(\"LPC\", { \"GBTCLK0_M2C_P\" : \"AA24\", \"GBTCLK0_M2C_N\" : \"AA25\", \"LA01_CC_P\" :",
"0, Subsignal(\"p\", Pins(\"D23\"), IOStandard(\"LVDS\")), Subsignal(\"n\", Pins(\"C23\"), IOStandard(\"LVDS\")) ), (\"user_sma_clock_p\", 0,",
"\"H19\", \"HA02_N\" : \"H18\", \"HA06_P\" : \"L15\", \"HA06_N\" : \"K15\",",
"(\"hdmi\", 0, Subsignal(\"d\", Pins( \"AK11 AP11 AP13 AN13 AN11 AM11",
"0, Pins(\"AF8\"), IOStandard(\"LVCMOS18\")), (\"user_btn_w\", 0, Pins(\"AF9\"), IOStandard(\"LVCMOS18\")), (\"user_btn_e\", 0, Pins(\"AE8\"),",
"\"DP3_M2C_P\" : \"A4\", \"DP3_M2C_N\" : \"A3\", \"DP4_C2M_P\" : \"N4\", \"DP4_C2M_N\"",
": \"W26\", \"LA13_P\" : \"AA20\", \"LA13_N\" : \"AB20\", \"LA17_CC_P\" :",
": \"D5\", \"DP1_M2C_P\" : \"D2\", \"DP1_M2C_N\" : \"D1\", \"DP2_C2M_P\" :",
"\"HA19_N\" : \"D18\", \"PRSNT_M2C_B\" : \"H24\", \"CLK0_M2C_P\" : \"H12\", \"CLK0_M2C_N\"",
"#Subsignal(\"alert_n\", Pins(\"AJ16\"), IOStandard(\"SSTL12_DCI\")), #Subsignal(\"par\", Pins(\"AD18\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"dm\", Pins(\"AD21 AE25 AJ21",
"AL32\"), IOStandard(\"POD12_DCI\")), Subsignal(\"dq\", Pins( \"AE23 AG20 AF22 AF20 AE22 AD20",
"0, Pins(\"AE8\"), IOStandard(\"LVCMOS18\")), # Switches (\"user_dip_btn\", 0, Pins(\"AN16\"), IOStandard(\"LVCMOS12\")), (\"user_dip_btn\",",
"\"HA11_P\" : \"J19\", \"HA11_N\" : \"J18\", \"HA14_P\" : \"F15\", \"HA14_N\"",
"(\"pcie_x1\", 0, Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\",",
"\"G16\", \"HA04_P\" : \"G19\", \"HA04_N\" : \"F19\", \"HA08_P\" : \"K18\",",
"), (\"spiflash\", 1, # clock needs to be accessed through",
"\"GBTCLK0_M2C_P\" : \"AA24\", \"GBTCLK0_M2C_N\" : \"AA25\", \"LA01_CC_P\" : \"W25\", \"LA01_CC_N\"",
"IOStandard(\"LVCMOS18\")), # Switches (\"user_dip_btn\", 0, Pins(\"AN16\"), IOStandard(\"LVCMOS12\")), (\"user_dip_btn\", 1, Pins(\"AN19\"),",
": \"W23\", \"LA00_CC_N\" : \"W24\", \"LA03_P\" : \"W28\", \"LA03_N\" :",
"\"AF34\", \"LA29_P\" : \"U34\", \"LA29_N\" : \"V34\", \"LA31_P\" : \"V33\",",
": \"J9\", \"LA09_N\" : \"H9\", \"LA13_P\" : \"D9\", \"LA13_N\" :",
"0, Pins(\"AE10\"), IOStandard(\"LVCMOS18\")), (\"user_btn_n\", 0, Pins(\"AD10\"), IOStandard(\"LVCMOS18\")), (\"user_btn_s\", 0, Pins(\"AF8\"),",
"\"A27\", \"LA33_N\" : \"A28\", \"HA03_P\" : \"G15\", \"HA03_N\" : \"G14\",",
"AG12 AJ11\", \"AG10 AK8\")), Subsignal(\"de\", Pins(\"AE11\")), Subsignal(\"clk\", Pins(\"AF13\")), Subsignal(\"vsync\", Pins(\"AH13\")),",
"of LiteX-Boards. # # Copyright (c) 2017-2019 <NAME> <<EMAIL>> #",
"\"LA18_CC_N\" : \"E23\", \"LA27_P\" : \"H21\", \"LA27_N\" : \"G21\", \"HA01_CC_P\"",
"Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2\")), Subsignal(\"rx_n\", Pins(\"AB1\")), Subsignal(\"tx_p\", Pins(\"AC4\")), Subsignal(\"tx_n\",",
"AG17\", \"AF18 AH19 AF15 AD19 AJ14 AG19\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"ba\", Pins(\"AF17",
"\"E3\", \"DP1_C2M_P\" : \"D6\", \"DP1_C2M_N\" : \"D5\", \"DP1_M2C_P\" : \"D2\",",
"AG3 AH5 AK5 AL3 AM5 AN3\")) ), # SGMII Clk",
"\"K1\", \"DP7_C2M_P\" : \"G4\", \"DP7_C2M_N\" : \"G3\", \"DP7_M2C_P\" : \"F2\",",
"\"HA17_CC_N\" : \"E17\", \"HA21_P\" : \"E15\", \"HA21_N\" : \"D15\", \"HA23_P\"",
"\"AB29\", \"LA21_P\" : \"AC33\", \"LA21_N\" : \"AD33\", \"LA24_P\" : \"AE32\",",
"Pins(\"V1\")) ), (\"sfp_tx\", 1, Subsignal(\"p\", Pins(\"W4\")), Subsignal(\"n\", Pins(\"W3\")), ), (\"sfp_rx\",",
"IOStandard(\"LVCMOS12\")), (\"user_dip_btn\", 2, Pins(\"AP18\"), IOStandard(\"LVCMOS12\")), (\"user_dip_btn\", 3, Pins(\"AN14\"), IOStandard(\"LVCMOS12\")), #",
"\"C9\", \"LA17_CC_P\" : \"D24\", \"LA17_CC_N\" : \"C24\", \"LA23_P\" : \"G22\",",
"\"HA06_N\" : \"K15\", \"HA10_P\" : \"H17\", \"HA10_N\" : \"H16\", \"HA17_CC_P\"",
"Serial (\"serial\", 0, Subsignal(\"cts\", Pins(\"L23\")), Subsignal(\"rts\", Pins(\"K27\")), Subsignal(\"tx\", Pins(\"K26\")), Subsignal(\"rx\",",
"Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2 AD2 AF2 AH2 AJ4 AK2 AM2",
"\"U22\", \"LA18_CC_P\" : \"AB30\", \"LA18_CC_N\" : \"AB31\", \"LA27_P\" : \"AG31\",",
": \"H8\", \"LA12_P\" : \"E10\", \"LA12_N\" : \"D10\", \"LA16_P\" :",
"Subsignal(\"rx_p\", Pins(\"AB2 AD2 AF2 AH2 AJ4 AK2 AM2 AP2\")), Subsignal(\"rx_n\",",
": \"W24\", \"LA03_P\" : \"W28\", \"LA03_N\" : \"Y28\", \"LA08_P\" :",
": \"D25\", \"LA00_CC_P\" : \"H11\", \"LA00_CC_N\" : \"G11\", \"LA03_P\" :",
"AN3\")) ), # SGMII Clk (\"sgmii_clock\", 0, Subsignal(\"p\", Pins(\"P26\"), IOStandard(\"LVDS_25\")),",
"\"H9\", \"LA13_P\" : \"D9\", \"LA13_N\" : \"C9\", \"LA17_CC_P\" : \"D24\",",
"\"DP6_C2M_P\" : \"L4\", \"DP6_C2M_N\" : \"L3\", \"DP6_M2C_P\" : \"K2\", \"DP6_M2C_N\"",
"Misc(\"SLEW=FAST\"), IOStandard(\"LVCMOS18\") ), # Rotary Encoder (\"rotary\", 0, Subsignal(\"a\", Pins(\"Y21\")),",
"\"HA07_P\" : \"L19\", \"HA07_N\" : \"L18\", \"HA11_P\" : \"J19\", \"HA11_N\"",
"} ), (\"LPC\", { \"GBTCLK0_M2C_P\" : \"AA24\", \"GBTCLK0_M2C_N\" : \"AA25\",",
"0, Subsignal(\"p\", Pins(\"R4\")), Subsignal(\"n\", Pins(\"R3\")) ), (\"user_sma_mgt_rx\", 0, Subsignal(\"p\", Pins(\"P2\")),",
"Pins(\"T2\")), Subsignal(\"rxn\", Pins(\"T1\")) ), (\"sfp_tx\", 0, Subsignal(\"p\", Pins(\"U4\")), Subsignal(\"n\", Pins(\"U3\")),",
"\"A18\", \"HA20_P\" : \"C19\", \"HA20_N\" : \"B19\", \"CLK1_M2C_P\" : \"E25\",",
": \"C17\", \"GBTCLK1_M2C_P\" : \"H6\", \"GBTCLK1_M2C_N\" : \"H5\", \"GBTCLK0_M2C_P\" :",
"\"HA18_N\" : \"B16\", \"HA22_P\" : \"C18\", \"HA22_N\" : \"C17\", \"GBTCLK1_M2C_P\"",
"AM2 AP2\")), Subsignal(\"rx_n\", Pins(\"AB1 AD1 AF1 AH1 AJ3 AK1 AM1",
"Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"dqs_n\", Pins(\"AH21 AJ25 AK20 AP21 AL28 AP30 AJ33 AP34\"),",
"\"LA06_N\" : \"W29\", \"LA10_P\" : \"T22\", \"LA10_N\" : \"T23\", \"LA14_P\"",
"\"V28\", \"LA09_P\" : \"V26\", \"LA09_N\" : \"W26\", \"LA13_P\" : \"AA20\",",
"\"AA20\", \"LA13_N\" : \"AB20\", \"LA17_CC_P\" : \"AA32\", \"LA17_CC_N\" : \"AB32\",",
"Subsignal(\"cs_n\", Pins(\"AH8\")), Subsignal(\"mosi\", Pins(\"AD9\"), Misc(\"PULLUP\")), Subsignal(\"miso\", Pins(\"AP9\"), Misc(\"PULLUP\")), Misc(\"SLEW=FAST\"), IOStandard(\"LVCMOS18\")",
"Pins(\"AC3 AE3\")) ), (\"pcie_x4\", 0, Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")),",
"\"HA11_N\" : \"J18\", \"HA14_P\" : \"F15\", \"HA14_N\" : \"F14\", \"HA18_P\"",
"AP16 AP15 AM16 AM15 AN18 AN17\"), ] # Platform -----------------------------------------------------------------------------------------",
": \"F23\", \"LA21_N\" : \"F24\", \"LA24_P\" : \"E20\", \"LA24_N\" :",
": \"C21\", \"LA19_N\" : \"C22\", \"LA21_P\" : \"F23\", \"LA21_N\" :",
"Subsignal(\"cs_n\", Pins(\"U7\")), Subsignal(\"dq\", Pins(\"AC7 AB7 AA7 Y7\")), IOStandard(\"LVCMOS18\") ), (\"spiflash\",",
"AE4 AG4 AH6\")), Subsignal(\"tx_n\", Pins(\"AC3 AE3 AG3 AH5\")) ), (\"pcie_x8\",",
"\"F18\", \"HA09_N\" : \"F17\", \"HA13_P\" : \"B14\", \"HA13_N\" : \"A14\",",
"IOStandard(\"LVCMOS18\") ), # Serial (\"serial\", 0, Subsignal(\"cts\", Pins(\"L23\")), Subsignal(\"rts\", Pins(\"K27\")),",
"Subsignal(\"tx_n\", Pins(\"AC3\")) ), (\"pcie_x2\", 0, Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")),",
"\"LA08_N\" : \"H8\", \"LA12_P\" : \"E10\", \"LA12_N\" : \"D10\", \"LA16_P\"",
"Pins(\"C23\"), IOStandard(\"LVCMOS18\")), (\"user_sma_gpio\", 0, Subsignal(\"p\", Pins(\"H27\"), IOStandard(\"LVDS\")), Subsignal(\"n\", Pins(\"G27\"), IOStandard(\"LVDS\"))",
": \"B1\", \"DP3_C2M_P\" : \"B6\", \"DP3_C2M_N\" : \"B5\", \"DP3_M2C_P\" :",
"Pins(\"AP8\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 1, Pins(\"H23\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 2, Pins(\"P20\"), IOStandard(\"LVCMOS18\")),",
"\"J18\", \"HA14_P\" : \"F15\", \"HA14_N\" : \"F14\", \"HA18_P\" : \"B17\",",
"\"E26\", \"LA32_N\" : \"D26\", \"HA02_P\" : \"H19\", \"HA02_N\" : \"H18\",",
"Subsignal(\"tx_p\", Pins(\"AC4\")), Subsignal(\"tx_n\", Pins(\"AC3\")) ), (\"pcie_x2\", 0, Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")),",
": \"AB20\", \"LA17_CC_P\" : \"AA32\", \"LA17_CC_N\" : \"AB32\", \"LA23_P\" :",
"Subsignal(\"p\", Pins(\"V2\")), Subsignal(\"n\", Pins(\"V1\")), ), (\"sfp_tx_disable_n\", 1, Pins(\"D28\"), IOStandard(\"LVCMOS18\")), ]",
"# PCIe (\"pcie_x1\", 0, Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\",",
"\"LA18_CC_P\" : \"AB30\", \"LA18_CC_N\" : \"AB31\", \"LA27_P\" : \"AG31\", \"LA27_N\"",
"Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2 AD2\")), Subsignal(\"rx_n\", Pins(\"AB1 AD1\")), Subsignal(\"tx_p\", Pins(\"AC4 AE4\")),",
": \"K13\", \"LA09_P\" : \"J9\", \"LA09_N\" : \"H9\", \"LA13_P\" :",
"\"HA01_CC_N\" : \"D16\", \"HA05_P\" : \"J15\", \"HA05_N\" : \"J14\", \"HA09_P\"",
"\"AC34\", \"LA22_N\" : \"AD34\", \"LA25_P\" : \"AE33\", \"LA25_N\" : \"AF34\",",
"\"D25\", \"LA00_CC_P\" : \"H11\", \"LA00_CC_N\" : \"G11\", \"LA03_P\" : \"A13\",",
"class Platform(XilinxPlatform): default_clk_name = \"clk125\" default_clk_period = 1e9/125e6 def __init__(self):",
"Pins(\"AB2 AD2 AF2 AH2 AJ4 AK2 AM2 AP2\")), Subsignal(\"rx_n\", Pins(\"AB1",
"\"E16\", \"HA01_CC_N\" : \"D16\", \"HA05_P\" : \"J15\", \"HA05_N\" : \"J14\",",
"\"LA28_P\" : \"B21\", \"LA28_N\" : \"B22\", \"LA30_P\" : \"C26\", \"LA30_N\"",
"Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2 AD2 AF2 AH2\")), Subsignal(\"rx_n\",",
"\"LA19_N\" : \"AB29\", \"LA21_P\" : \"AC33\", \"LA21_N\" : \"AD33\", \"LA24_P\"",
"\"DP4_C2M_N\" : \"N3\", \"DP4_M2C_P\" : \"M2\", \"DP4_M2C_N\" : \"M1\", \"DP5_C2M_P\"",
"\"D13\", \"LA06_N\" : \"C13\", \"LA10_P\" : \"L8\", \"LA10_N\" : \"K8\",",
"IOStandard(\"SSTL12_DCI\")), #Subsignal(\"ten\", Pins(\"AH16\"), IOStandard(\"SSTL12_DCI\")), #Subsignal(\"alert_n\", Pins(\"AJ16\"), IOStandard(\"SSTL12_DCI\")), #Subsignal(\"par\", Pins(\"AD18\"), IOStandard(\"SSTL12_DCI\")),",
"Pins(\"D23\"), IOStandard(\"LVDS\")), Subsignal(\"n\", Pins(\"C23\"), IOStandard(\"LVDS\")) ), (\"user_sma_clock_p\", 0, Pins(\"D23\"), IOStandard(\"LVCMOS18\")),",
"# SFP (\"sfp\", 0, Subsignal(\"txp\", Pins(\"U4\")), Subsignal(\"txn\", Pins(\"U3\")), Subsignal(\"rxp\", Pins(\"T2\")),",
"{ \"GBTCLK0_M2C_P\" : \"AA24\", \"GBTCLK0_M2C_N\" : \"AA25\", \"LA01_CC_P\" : \"W25\",",
"<<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause from litex.build.generic_platform import * from litex.build.xilinx",
"\"LA05_P\" : \"V27\", \"LA05_N\" : \"V28\", \"LA09_P\" : \"V26\", \"LA09_N\"",
"\"LA14_P\" : \"B10\", \"LA14_N\" : \"A10\", \"LA18_CC_P\" : \"E22\", \"LA18_CC_N\"",
"\"LA17_CC_N\" : \"C24\", \"LA23_P\" : \"G22\", \"LA23_N\" : \"F22\", \"LA26_P\"",
"needs to be accessed through primitive Subsignal(\"cs_n\", Pins(\"G26\")), Subsignal(\"dq\", Pins(\"M20",
": \"G17\", \"HA00_CC_N\" : \"G16\", \"HA04_P\" : \"G19\", \"HA04_N\" :",
"Subsignal(\"txp\", Pins(\"W4\")), Subsignal(\"txn\", Pins(\"W3\")), Subsignal(\"rxp\", Pins(\"V2\")), Subsignal(\"rxn\", Pins(\"V1\")) ), (\"sfp_tx\",",
"\"F20\", \"PG_M2C\" : \"L27\", \"HA00_CC_P\" : \"G17\", \"HA00_CC_N\" : \"G16\",",
"3, Pins(\"AN14\"), IOStandard(\"LVCMOS12\")), # SMA (\"user_sma_clock\", 0, Subsignal(\"p\", Pins(\"D23\"), IOStandard(\"LVDS\")),",
"\"LA04_P\" : \"U26\", \"LA04_N\" : \"U27\", \"LA07_P\" : \"V22\", \"LA07_N\"",
"\"E25\", \"CLK1_M2C_N\" : \"D25\", \"LA00_CC_P\" : \"H11\", \"LA00_CC_N\" : \"G11\",",
"(\"user_sma_gpio\", 0, Subsignal(\"p\", Pins(\"H27\"), IOStandard(\"LVDS\")), Subsignal(\"n\", Pins(\"G27\"), IOStandard(\"LVDS\")) ), (\"user_sma_gpio_p\",",
"Pins(\"AD21 AE25 AJ21 AM21 AH26 AN26 AJ29 AL32\"), IOStandard(\"POD12_DCI\")), Subsignal(\"dq\",",
"<NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause from litex.build.generic_platform import * from",
"\"U24\", \"LA08_N\" : \"U25\", \"LA12_P\" : \"AC22\", \"LA12_N\" : \"AC23\",",
"\"G21\", \"HA01_CC_P\" : \"E16\", \"HA01_CC_N\" : \"D16\", \"HA05_P\" : \"J15\",",
"\"LA11_P\" : \"K11\", \"LA11_N\" : \"J11\", \"LA15_P\" : \"D8\", \"LA15_N\"",
"SPDX-License-Identifier: BSD-2-Clause from litex.build.generic_platform import * from litex.build.xilinx import XilinxPlatform,",
"AH2\")), Subsignal(\"rx_n\", Pins(\"AB1 AD1 AF1 AH1\")), Subsignal(\"tx_p\", Pins(\"AC4 AE4 AG4",
"\"J11\", \"LA15_P\" : \"D8\", \"LA15_N\" : \"C8\", \"LA19_P\" : \"C21\",",
"1, Pins(\"D28\"), IOStandard(\"LVCMOS18\")), ] # Connectors --------------------------------------------------------------------------------------- _connectors = [",
": \"D9\", \"LA13_N\" : \"C9\", \"LA17_CC_P\" : \"D24\", \"LA17_CC_N\" :",
"Pins(\"AF12\")), IOStandard(\"LVCMOS18\") ), # DDR4 SDRAM (\"ddram\", 0, Subsignal(\"a\", Pins(",
"), (\"user_sma_gpio_p\", 0, Pins(\"H27\"), IOStandard(\"LVCMOS18\")), (\"user_sma_gpio_n\", 0, Pins(\"G27\"), IOStandard(\"LVCMOS18\")), #",
"\"G11\", \"LA03_P\" : \"A13\", \"LA03_N\" : \"A12\", \"LA08_P\" : \"J8\",",
"\"HA16_N\" : \"A18\", \"HA20_P\" : \"C19\", \"HA20_N\" : \"B19\", \"CLK1_M2C_P\"",
"\"HA22_P\" : \"C18\", \"HA22_N\" : \"C17\", \"GBTCLK1_M2C_P\" : \"H6\", \"GBTCLK1_M2C_N\"",
"Subsignal(\"cke\", Pins(\"AD15\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"odt\", Pins(\"AJ18\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"reset_n\", Pins(\"AL18\"), IOStandard(\"LVCMOS12\")), Misc(\"SLEW=FAST\"),",
"\"H8\", \"LA12_P\" : \"E10\", \"LA12_N\" : \"D10\", \"LA16_P\" : \"B9\",",
"AM20 AK23 AK22 AL24 AL20 AL23\", \"AM24 AN23 AN24 AP23",
": \"H11\", \"LA00_CC_N\" : \"G11\", \"LA03_P\" : \"A13\", \"LA03_N\" :",
": \"C14\", \"HA19_P\" : \"D19\", \"HA19_N\" : \"D18\", \"PRSNT_M2C_B\" :",
": \"D8\", \"LA15_N\" : \"C8\", \"LA19_P\" : \"C21\", \"LA19_N\" :",
"Subsignal(\"cs_n\", Pins(\"G26\")), Subsignal(\"dq\", Pins(\"M20 L20 R21 R22\")), IOStandard(\"LVCMOS18\") ), #",
"\"K13\", \"LA09_P\" : \"J9\", \"LA09_N\" : \"H9\", \"LA13_P\" : \"D9\",",
"\"LA21_N\" : \"F24\", \"LA24_P\" : \"E20\", \"LA24_N\" : \"E21\", \"LA28_P\"",
"), (\"LPC\", { \"GBTCLK0_M2C_P\" : \"AA24\", \"GBTCLK0_M2C_N\" : \"AA25\", \"LA01_CC_P\"",
"\"DP4_M2C_P\" : \"M2\", \"DP4_M2C_N\" : \"M1\", \"DP5_C2M_P\" : \"J4\", \"DP5_C2M_N\"",
": \"K2\", \"DP6_M2C_N\" : \"K1\", \"DP7_C2M_P\" : \"G4\", \"DP7_C2M_N\" :",
"Subsignal(\"p\", Pins(\"AK17\"), IOStandard(\"DIFF_SSTL12\")), Subsignal(\"n\", Pins(\"AK16\"), IOStandard(\"DIFF_SSTL12\")) ), (\"cpu_reset\", 0, Pins(\"AN8\"),",
": \"W34\", \"LA33_P\" : \"W33\", \"LA33_N\" : \"Y33\", } ),",
": \"U27\", \"LA07_P\" : \"V22\", \"LA07_N\" : \"V23\", \"LA11_P\" :",
": \"C22\", \"LA21_P\" : \"F23\", \"LA21_N\" : \"F24\", \"LA24_P\" :",
"IOStandard(\"SSTL12_DCI\")), # A14 Subsignal(\"cs_n\", Pins(\"AL19\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"act_n\", Pins(\"AH14\"), IOStandard(\"SSTL12_DCI\")), #Subsignal(\"ten\",",
"AN23 AN24 AP23 AP25 AN22 AP24 AM22\", \"AH28 AK26 AK28",
"Pins(\"AE8\"), IOStandard(\"LVCMOS18\")), # Switches (\"user_dip_btn\", 0, Pins(\"AN16\"), IOStandard(\"LVCMOS12\")), (\"user_dip_btn\", 1,",
"), (\"sfp_tx_disable_n\", 0, Pins(\"AL8\"), IOStandard(\"LVCMOS18\")), (\"sfp\", 1, Subsignal(\"txp\", Pins(\"W4\")), Subsignal(\"txn\",",
"\"F24\", \"LA24_P\" : \"E20\", \"LA24_N\" : \"E21\", \"LA28_P\" : \"B21\",",
": \"AB34\", \"LA22_P\" : \"AC34\", \"LA22_N\" : \"AD34\", \"LA25_P\" :",
"Pins(\"P23\"), IOStandard(\"LVCMOS18\")), # Buttons (\"user_btn_c\", 0, Pins(\"AE10\"), IOStandard(\"LVCMOS18\")), (\"user_btn_n\", 0,",
": \"U26\", \"LA04_N\" : \"U27\", \"LA07_P\" : \"V22\", \"LA07_N\" :",
"), # DDR4 SDRAM (\"ddram\", 0, Subsignal(\"a\", Pins( \"AE17 AH17",
"\"HA03_N\" : \"G14\", \"HA07_P\" : \"L19\", \"HA07_N\" : \"L18\", \"HA11_P\"",
"AE21 AM17\"), (\"pmod1\", \"AL14 AM14 AP16 AP15 AM16 AM15 AN18",
"AP15 AM16 AM15 AN18 AN17\"), ] # Platform ----------------------------------------------------------------------------------------- class",
"Subsignal(\"de\", Pins(\"AE11\")), Subsignal(\"clk\", Pins(\"AF13\")), Subsignal(\"vsync\", Pins(\"AH13\")), Subsignal(\"hsync\", Pins(\"AE13\")), Subsignal(\"spdif\", Pins(\"AE12\")),",
": \"K1\", \"DP7_C2M_P\" : \"G4\", \"DP7_C2M_N\" : \"G3\", \"DP7_M2C_P\" :",
"1e9/300e6) self.add_platform_command(\"set_property INTERNAL_VREF 0.84 [get_iobanks 44]\") self.add_platform_command(\"set_property INTERNAL_VREF 0.84 [get_iobanks",
"\"G24\", \"LA22_N\" : \"F25\", \"LA25_P\" : \"D20\", \"LA25_N\" : \"D21\",",
"AH9 AH8\"), Misc(\"PULLUP True\")), Misc(\"SLEW=FAST\"), IOStandard(\"LVCMOS18\") ), # Rotary Encoder",
"VivadoProgrammer # IOs ---------------------------------------------------------------------------------------------- _io = [ # Clk /",
"\"LA26_P\" : \"G20\", \"LA26_N\" : \"F20\", \"PG_M2C\" : \"L27\", \"HA00_CC_P\"",
"Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2 AD2 AF2",
"3, Pins(\"P21\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 4, Pins(\"N22\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 5, Pins(\"M22\"),",
"\"AC32\", \"LA00_CC_P\" : \"W23\", \"LA00_CC_N\" : \"W24\", \"LA03_P\" : \"W28\",",
"(\"sfp_rx\", 0, Subsignal(\"p\", Pins(\"T2\")), Subsignal(\"n\", Pins(\"T1\")), ), (\"sfp_tx_disable_n\", 0, Pins(\"AL8\"),",
"\"AL12 AK12 AL13 AK13 AD11 AH12 AG12 AJ11\", \"AG10 AK8\")),",
"Subsignal(\"tx_p\", Pins(\"AC4 AE4 AG4 AH6\")), Subsignal(\"tx_n\", Pins(\"AC3 AE3 AG3 AH5\"))",
"(\"clk300\", 0, Subsignal(\"p\", Pins(\"AK17\"), IOStandard(\"DIFF_SSTL12\")), Subsignal(\"n\", Pins(\"AK16\"), IOStandard(\"DIFF_SSTL12\")) ), (\"cpu_reset\",",
"Pins(\"T2\")), Subsignal(\"n\", Pins(\"T1\")), ), (\"sfp_tx_disable_n\", 0, Pins(\"AL8\"), IOStandard(\"LVCMOS18\")), (\"sfp\", 1,",
"\"V29\", \"LA06_N\" : \"W29\", \"LA10_P\" : \"T22\", \"LA10_N\" : \"T23\",",
"AM21 AH26 AN26 AJ29 AL32\"), IOStandard(\"POD12_DCI\")), Subsignal(\"dq\", Pins( \"AE23 AG20",
"IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2 AD2 AF2 AH2",
": \"V26\", \"LA09_N\" : \"W26\", \"LA13_P\" : \"AA20\", \"LA13_N\" :",
"Subsignal(\"p\", Pins(\"V6\")), Subsignal(\"n\", Pins(\"V5\")) ), (\"user_sma_mgt_tx\", 0, Subsignal(\"p\", Pins(\"R4\")), Subsignal(\"n\",",
"\"AK11 AP11 AP13 AN13 AN11 AM11 AN12 AM12\", \"AL12 AK12",
"default_clk_name = \"clk125\" default_clk_period = 1e9/125e6 def __init__(self): XilinxPlatform.__init__(self, \"xcku040-ffva1156-2-e\",",
"# Serial (\"serial\", 0, Subsignal(\"cts\", Pins(\"L23\")), Subsignal(\"rts\", Pins(\"K27\")), Subsignal(\"tx\", Pins(\"K26\")),",
"\"CLK1_M2C_N\" : \"AC32\", \"LA00_CC_P\" : \"W23\", \"LA00_CC_N\" : \"W24\", \"LA03_P\"",
": \"AC33\", \"LA21_N\" : \"AD33\", \"LA24_P\" : \"AE32\", \"LA24_N\" :",
": \"J16\", \"HA15_P\" : \"D14\", \"HA15_N\" : \"C14\", \"HA19_P\" :",
"# Leds (\"user_led\", 0, Pins(\"AP8\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 1, Pins(\"H23\"), IOStandard(\"LVCMOS18\")),",
"AB7 AA7 Y7\")), IOStandard(\"LVCMOS18\") ), (\"spiflash\", 1, # clock needs",
"Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2 AD2 AF2 AH2 AJ4 AK2",
"Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2 AD2\")), Subsignal(\"rx_n\", Pins(\"AB1 AD1\")),",
": \"F9\", \"LA05_P\" : \"L13\", \"LA05_N\" : \"K13\", \"LA09_P\" :",
": \"B17\", \"HA18_N\" : \"B16\", \"HA22_P\" : \"C18\", \"HA22_N\" :",
"IOStandard(\"LVCMOS18\") ), # HDMI (\"hdmi\", 0, Subsignal(\"d\", Pins( \"AK11 AP11",
"import XilinxPlatform, VivadoProgrammer # IOs ---------------------------------------------------------------------------------------------- _io = [ #",
"Pins(\"AF17 AL15\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"bg\", Pins(\"AG15\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"ras_n\", Pins(\"AF14\"), IOStandard(\"SSTL12_DCI\")), #",
"(\"spiflash\", 1, # clock needs to be accessed through primitive",
"AM11 AN12 AM12\", \"AL12 AK12 AL13 AK13 AD11 AH12 AG12",
"Subsignal(\"p\", Pins(\"G10\"), IOStandard(\"LVDS\")), Subsignal(\"n\", Pins(\"F10\"), IOStandard(\"LVDS\")) ), (\"clk300\", 0, Subsignal(\"p\",",
"Pins(\"R4\")), Subsignal(\"n\", Pins(\"R3\")) ), (\"user_sma_mgt_rx\", 0, Subsignal(\"p\", Pins(\"P2\")), Subsignal(\"n\", Pins(\"P1\"))",
"AG25\", \"AL22 AL25 AM20 AK23 AK22 AL24 AL20 AL23\", \"AM24",
": \"K15\", \"HA10_P\" : \"H17\", \"HA10_N\" : \"H16\", \"HA17_CC_P\" :",
"AP2\")), Subsignal(\"rx_n\", Pins(\"AB1 AD1 AF1 AH1 AJ3 AK1 AM1 AP1\")),",
"\"C3\", \"DP2_M2C_P\" : \"B2\", \"DP2_M2C_N\" : \"B1\", \"DP3_C2M_P\" : \"B6\",",
"\"C22\", \"LA21_P\" : \"F23\", \"LA21_N\" : \"F24\", \"LA24_P\" : \"E20\",",
"Pins(\"G27\"), IOStandard(\"LVDS\")) ), (\"user_sma_gpio_p\", 0, Pins(\"H27\"), IOStandard(\"LVCMOS18\")), (\"user_sma_gpio_n\", 0, Pins(\"G27\"),",
"Pins(\"M20 L20 R21 R22\")), IOStandard(\"LVCMOS18\") ), # SDCard (\"spisdcard\", 0,",
"(\"user_btn_s\", 0, Pins(\"AF8\"), IOStandard(\"LVCMOS18\")), (\"user_btn_w\", 0, Pins(\"AF9\"), IOStandard(\"LVCMOS18\")), (\"user_btn_e\", 0,",
": \"AB22\", \"LA04_P\" : \"U26\", \"LA04_N\" : \"U27\", \"LA07_P\" :",
": \"E25\", \"CLK1_M2C_N\" : \"D25\", \"LA00_CC_P\" : \"H11\", \"LA00_CC_N\" :",
"\"LA22_N\" : \"F25\", \"LA25_P\" : \"D20\", \"LA25_N\" : \"D21\", \"LA29_P\"",
"\"W34\", \"LA33_P\" : \"W33\", \"LA33_N\" : \"Y33\", } ), (\"pmod0\",",
"AK13 AD11 AH12 AG12 AJ11\", \"AG10 AK8\")), Subsignal(\"de\", Pins(\"AE11\")), Subsignal(\"clk\",",
"Subsignal(\"ras_n\", Pins(\"AF14\"), IOStandard(\"SSTL12_DCI\")), # A16 Subsignal(\"cas_n\", Pins(\"AG14\"), IOStandard(\"SSTL12_DCI\")), # A15",
"Pins(\"P20\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 3, Pins(\"P21\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 4, Pins(\"N22\"), IOStandard(\"LVCMOS18\")),",
": \"B15\", \"HA23_N\" : \"A15\", } ), (\"LPC\", { \"GBTCLK0_M2C_P\"",
"\"W31\", \"LA30_P\" : \"Y31\", \"LA30_N\" : \"Y32\", \"LA32_P\" : \"W30\",",
"0, Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2\")),",
"IOStandard(\"LVCMOS18\")), # Leds (\"user_led\", 0, Pins(\"AP8\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 1, Pins(\"H23\"),",
"(\"user_dip_btn\", 0, Pins(\"AN16\"), IOStandard(\"LVCMOS12\")), (\"user_dip_btn\", 1, Pins(\"AN19\"), IOStandard(\"LVCMOS12\")), (\"user_dip_btn\", 2,",
"(\"user_led\", 1, Pins(\"H23\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 2, Pins(\"P20\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 3,",
"AH32 AJ34 AK31 AJ31 AJ30 AH34 AK32\", \"AN33 AP33 AM34",
"\"LA09_N\" : \"W26\", \"LA13_P\" : \"AA20\", \"LA13_N\" : \"AB20\", \"LA17_CC_P\"",
"IOStandard(\"LVCMOS18\")), (\"user_btn_s\", 0, Pins(\"AF8\"), IOStandard(\"LVCMOS18\")), (\"user_btn_w\", 0, Pins(\"AF9\"), IOStandard(\"LVCMOS18\")), (\"user_btn_e\",",
"(\"rotary\", 0, Subsignal(\"a\", Pins(\"Y21\")), Subsignal(\"b\", Pins(\"AD26\")), Subsignal(\"push\", Pins(\"AF28\")), IOStandard(\"LVCMOS18\") ),",
"Subsignal(\"rx_n\", Pins(\"AB1 AD1\")), Subsignal(\"tx_p\", Pins(\"AC4 AE4\")), Subsignal(\"tx_n\", Pins(\"AC3 AE3\")) ),",
"\"F14\", \"HA18_P\" : \"B17\", \"HA18_N\" : \"B16\", \"HA22_P\" : \"C18\",",
"Subsignal(\"rxn\", Pins(\"T1\")) ), (\"sfp_tx\", 0, Subsignal(\"p\", Pins(\"U4\")), Subsignal(\"n\", Pins(\"U3\")), ),",
"Pins(\"AH8\")), Subsignal(\"mosi\", Pins(\"AD9\"), Misc(\"PULLUP\")), Subsignal(\"miso\", Pins(\"AP9\"), Misc(\"PULLUP\")), Misc(\"SLEW=FAST\"), IOStandard(\"LVCMOS18\") ),",
"Pins(\"AF14\"), IOStandard(\"SSTL12_DCI\")), # A16 Subsignal(\"cas_n\", Pins(\"AG14\"), IOStandard(\"SSTL12_DCI\")), # A15 Subsignal(\"we_n\",",
"\"AF18 AH19 AF15 AD19 AJ14 AG19\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"ba\", Pins(\"AF17 AL15\"),",
"\"LA19_P\" : \"AA29\", \"LA19_N\" : \"AB29\", \"LA21_P\" : \"AC33\", \"LA21_N\"",
": \"G14\", \"HA07_P\" : \"L19\", \"HA07_N\" : \"L18\", \"HA11_P\" :",
"be accessed through primitive Subsignal(\"cs_n\", Pins(\"U7\")), Subsignal(\"dq\", Pins(\"AC7 AB7 AA7",
"AH1 AJ3 AK1 AM1 AP1\")), Subsignal(\"tx_p\", Pins(\"AC4 AE4 AG4 AH6",
"\"LA10_N\" : \"T23\", \"LA14_P\" : \"U21\", \"LA14_N\" : \"U22\", \"LA18_CC_P\"",
"Pins(\"N22\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 5, Pins(\"M22\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 6, Pins(\"R23\"), IOStandard(\"LVCMOS18\")),",
"\"AD30\", \"LA23_N\" : \"AD31\", \"LA26_P\" : \"AF33\", \"LA26_N\" : \"AG34\",",
"Subsignal(\"reset_n\", Pins(\"AL18\"), IOStandard(\"LVCMOS12\")), Misc(\"SLEW=FAST\"), ), # PCIe (\"pcie_x1\", 0, Subsignal(\"rst_n\",",
": \"U25\", \"LA12_P\" : \"AC22\", \"LA12_N\" : \"AC23\", \"LA16_P\" :",
"0, Subsignal(\"cts\", Pins(\"L23\")), Subsignal(\"rts\", Pins(\"K27\")), Subsignal(\"tx\", Pins(\"K26\")), Subsignal(\"rx\", Pins(\"G25\")), IOStandard(\"LVCMOS18\")",
"Pins(\"H27\"), IOStandard(\"LVCMOS18\")), (\"user_sma_gpio_n\", 0, Pins(\"G27\"), IOStandard(\"LVCMOS18\")), # I2C (\"i2c\", 0,",
"\"F19\", \"HA08_P\" : \"K18\", \"HA08_N\" : \"K17\", \"HA12_P\" : \"K16\",",
"Subsignal(\"dqs_p\", Pins(\"AG21 AH24 AJ20 AP20 AL27 AN29 AH33 AN34\"), IOStandard(\"DIFF_POD12_DCI\"),",
"\"C24\", \"LA23_P\" : \"G22\", \"LA23_N\" : \"F22\", \"LA26_P\" : \"G20\",",
"Subsignal(\"p\", Pins(\"T2\")), Subsignal(\"n\", Pins(\"T1\")), ), (\"sfp_tx_disable_n\", 0, Pins(\"AL8\"), IOStandard(\"LVCMOS18\")), (\"sfp\",",
"\"D21\", \"LA29_P\" : \"B20\", \"LA29_N\" : \"A20\", \"LA31_P\" : \"B25\",",
"\"LA11_P\" : \"V21\", \"LA11_N\" : \"W21\", \"LA15_P\" : \"AB25\", \"LA15_N\"",
"Pins(\"G27\"), IOStandard(\"LVCMOS18\")), # I2C (\"i2c\", 0, Subsignal(\"scl\", Pins(\"J24\")), Subsignal(\"sda\", Pins(\"J25\")),",
": \"AB30\", \"LA18_CC_N\" : \"AB31\", \"LA27_P\" : \"AG31\", \"LA27_N\" :",
"\"LA05_N\" : \"V28\", \"LA09_P\" : \"V26\", \"LA09_N\" : \"W26\", \"LA13_P\"",
": \"AB29\", \"LA21_P\" : \"AC33\", \"LA21_N\" : \"AD33\", \"LA24_P\" :",
"from litex.build.xilinx import XilinxPlatform, VivadoProgrammer # IOs ---------------------------------------------------------------------------------------------- _io =",
"---------------------------------------------------------------------------------------------- _io = [ # Clk / Rst (\"clk125\", 0,",
"AH22 AG25\", \"AL22 AL25 AM20 AK23 AK22 AL24 AL20 AL23\",",
"\"AE17 AH17 AE18 AJ15 AG16 AL17 AK18 AG17\", \"AF18 AH19",
"AE3 AG3 AH5\")) ), (\"pcie_x8\", 0, Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\",",
"Pins(\"R23\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 7, Pins(\"P23\"), IOStandard(\"LVCMOS18\")), # Buttons (\"user_btn_c\", 0,",
"\"W24\", \"LA03_P\" : \"W28\", \"LA03_N\" : \"Y28\", \"LA08_P\" : \"U24\",",
": \"AB31\", \"LA27_P\" : \"AG31\", \"LA27_N\" : \"AG32\", \"CLK1_M2C_P\" :",
"AK27 AM26\", \"AL30 AP29 AM30 AN28 AL29 AP28 AM29 AN27\",",
"\"H6\", \"GBTCLK1_M2C_N\" : \"H5\", \"GBTCLK0_M2C_P\" : \"K6\", \"GBTCLK0_M2C_N\" : \"K5\",",
"Pins(\"AE15\"), IOStandard(\"DIFF_SSTL12_DCI\")), Subsignal(\"cke\", Pins(\"AD15\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"odt\", Pins(\"AJ18\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"reset_n\", Pins(\"AL18\"),",
"AH19 AF15 AD19 AJ14 AG19\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"ba\", Pins(\"AF17 AL15\"), IOStandard(\"SSTL12_DCI\")),",
"Subsignal(\"dqs_n\", Pins(\"AH21 AJ25 AK20 AP21 AL28 AP30 AJ33 AP34\"), IOStandard(\"DIFF_POD12_DCI\"),",
"\"AK25 AN21 AH18 AM19 AE26 AF25 AE21 AM17\"), (\"pmod1\", \"AL14",
"\"AE33\", \"LA25_N\" : \"AF34\", \"LA29_P\" : \"U34\", \"LA29_N\" : \"V34\",",
"Pins(\"AB1 AD1\")), Subsignal(\"tx_p\", Pins(\"AC4 AE4\")), Subsignal(\"tx_n\", Pins(\"AC3 AE3\")) ), (\"pcie_x4\",",
"AJ25 AK20 AP21 AL28 AP30 AJ33 AP34\"), IOStandard(\"DIFF_POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")),",
": \"F5\", \"DP0_M2C_P\" : \"E4\", \"DP0_M2C_N\" : \"E3\", \"DP1_C2M_P\" :",
"(\"user_led\", 5, Pins(\"M22\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 6, Pins(\"R23\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 7,",
": \"G19\", \"HA04_N\" : \"F19\", \"HA08_P\" : \"K18\", \"HA08_N\" :",
"AD11 AH12 AG12 AJ11\", \"AG10 AK8\")), Subsignal(\"de\", Pins(\"AE11\")), Subsignal(\"clk\", Pins(\"AF13\")),",
"AJ11\", \"AG10 AK8\")), Subsignal(\"de\", Pins(\"AE11\")), Subsignal(\"clk\", Pins(\"AF13\")), Subsignal(\"vsync\", Pins(\"AH13\")), Subsignal(\"hsync\",",
": \"Y33\", } ), (\"pmod0\", \"AK25 AN21 AH18 AM19 AE26",
"Misc(\"PULLUP True\")), Misc(\"SLEW=FAST\"), IOStandard(\"LVCMOS18\") ), # Rotary Encoder (\"rotary\", 0,",
": \"J18\", \"HA14_P\" : \"F15\", \"HA14_N\" : \"F14\", \"HA18_P\" :",
"AM6 AN4\")), Subsignal(\"tx_n\", Pins(\"AC3 AE3 AG3 AH5 AK5 AL3 AM5",
"\"HA14_P\" : \"F15\", \"HA14_N\" : \"F14\", \"HA18_P\" : \"B17\", \"HA18_N\"",
": \"E4\", \"DP0_M2C_N\" : \"E3\", \"DP1_C2M_P\" : \"D6\", \"DP1_C2M_N\" :",
"\"B19\", \"CLK1_M2C_P\" : \"E25\", \"CLK1_M2C_N\" : \"D25\", \"LA00_CC_P\" : \"H11\",",
"SFP (\"sfp\", 0, Subsignal(\"txp\", Pins(\"U4\")), Subsignal(\"txn\", Pins(\"U3\")), Subsignal(\"rxp\", Pins(\"T2\")), Subsignal(\"rxn\",",
"\"CLK0_M2C_P\" : \"H12\", \"CLK0_M2C_N\" : \"G12\", \"LA02_P\" : \"K10\", \"LA02_N\"",
"(c) 2017-2019 <NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause from litex.build.generic_platform import",
"Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"dqs_p\", Pins(\"AG21 AH24 AJ20 AP20 AL27 AN29 AH33 AN34\"),",
"\"DP2_C2M_P\" : \"C4\", \"DP2_C2M_N\" : \"C3\", \"DP2_M2C_P\" : \"B2\", \"DP2_M2C_N\"",
"Pins(\"AC3 AE3 AG3 AH5\")) ), (\"pcie_x8\", 0, Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")),",
": \"AD33\", \"LA24_P\" : \"AE32\", \"LA24_N\" : \"AF32\", \"LA28_P\" :",
": \"A25\", \"LA33_P\" : \"A27\", \"LA33_N\" : \"A28\", \"HA03_P\" :",
"\"AL14 AM14 AP16 AP15 AM16 AM15 AN18 AN17\"), ] #",
"Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2\")), Subsignal(\"rx_n\", Pins(\"AB1\")), Subsignal(\"tx_p\", Pins(\"AC4\")), Subsignal(\"tx_n\", Pins(\"AC3\")) ),",
"Pins(\"AK16\"), IOStandard(\"DIFF_SSTL12\")) ), (\"cpu_reset\", 0, Pins(\"AN8\"), IOStandard(\"LVCMOS18\")), # Leds (\"user_led\",",
"Subsignal(\"rxp\", Pins(\"T2\")), Subsignal(\"rxn\", Pins(\"T1\")) ), (\"sfp_tx\", 0, Subsignal(\"p\", Pins(\"U4\")), Subsignal(\"n\",",
": \"B5\", \"DP3_M2C_P\" : \"A4\", \"DP3_M2C_N\" : \"A3\", \"DP4_C2M_P\" :",
"Platform ----------------------------------------------------------------------------------------- class Platform(XilinxPlatform): default_clk_name = \"clk125\" default_clk_period = 1e9/125e6",
": \"W33\", \"LA33_N\" : \"Y33\", } ), (\"pmod0\", \"AK25 AN21",
": \"A28\", \"HA03_P\" : \"G15\", \"HA03_N\" : \"G14\", \"HA07_P\" :",
"\"CLK1_M2C_P\" : \"AC31\", \"CLK1_M2C_N\" : \"AC32\", \"LA00_CC_P\" : \"W23\", \"LA00_CC_N\"",
"Pins(\"AE10\"), IOStandard(\"LVCMOS18\")), (\"user_btn_n\", 0, Pins(\"AD10\"), IOStandard(\"LVCMOS18\")), (\"user_btn_s\", 0, Pins(\"AF8\"), IOStandard(\"LVCMOS18\")),",
"AD20 AG22 AE20\", \"AJ24 AG24 AJ23 AF23 AH23 AF24 AH22",
"\"LA03_P\" : \"W28\", \"LA03_N\" : \"Y28\", \"LA08_P\" : \"U24\", \"LA08_N\"",
"\"LA16_P\" : \"AB21\", \"LA16_N\" : \"AC21\", \"LA20_P\" : \"AA34\", \"LA20_N\"",
"toolchain=\"vivado\") def create_programmer(self): return VivadoProgrammer() def do_finalize(self, fragment): XilinxPlatform.do_finalize(self, fragment)",
"AF2 AH2 AJ4 AK2 AM2 AP2\")), Subsignal(\"rx_n\", Pins(\"AB1 AD1 AF1",
"\"B14\", \"HA13_N\" : \"A14\", \"HA16_P\" : \"A19\", \"HA16_N\" : \"A18\",",
"\"DP2_M2C_P\" : \"B2\", \"DP2_M2C_N\" : \"B1\", \"DP3_C2M_P\" : \"B6\", \"DP3_C2M_N\"",
"(\"user_led\", 7, Pins(\"P23\"), IOStandard(\"LVCMOS18\")), # Buttons (\"user_btn_c\", 0, Pins(\"AE10\"), IOStandard(\"LVCMOS18\")),",
": \"G12\", \"LA02_P\" : \"K10\", \"LA02_N\" : \"J10\", \"LA04_P\" :",
"create_programmer(self): return VivadoProgrammer() def do_finalize(self, fragment): XilinxPlatform.do_finalize(self, fragment) self.add_period_constraint(self.lookup_request(\"clk125\", loose=True),",
"\"LA20_P\" : \"AA34\", \"LA20_N\" : \"AB34\", \"LA22_P\" : \"AC34\", \"LA22_N\"",
"AH27 AK27 AM26\", \"AL30 AP29 AM30 AN28 AL29 AP28 AM29",
"Subsignal(\"act_n\", Pins(\"AH14\"), IOStandard(\"SSTL12_DCI\")), #Subsignal(\"ten\", Pins(\"AH16\"), IOStandard(\"SSTL12_DCI\")), #Subsignal(\"alert_n\", Pins(\"AJ16\"), IOStandard(\"SSTL12_DCI\")), #Subsignal(\"par\",",
"Subsignal(\"clk\", Pins(\"AL10\")), Subsignal(\"cmd\", Pins(\"AD9\"), Misc(\"PULLUP True\")), Subsignal(\"data\", Pins(\"AP9 AN9 AH9",
"AN26 AJ29 AL32\"), IOStandard(\"POD12_DCI\")), Subsignal(\"dq\", Pins( \"AE23 AG20 AF22 AF20",
"This file is part of LiteX-Boards. # # Copyright (c)",
": \"A20\", \"LA31_P\" : \"B25\", \"LA31_N\" : \"A25\", \"LA33_P\" :",
"# Rotary Encoder (\"rotary\", 0, Subsignal(\"a\", Pins(\"Y21\")), Subsignal(\"b\", Pins(\"AD26\")), Subsignal(\"push\",",
"AK28 AM27 AJ28 AH27 AK27 AM26\", \"AL30 AP29 AM30 AN28",
": \"D20\", \"LA25_N\" : \"D21\", \"LA29_P\" : \"B20\", \"LA29_N\" :",
"IOStandard(\"LVDS\")), Subsignal(\"n\", Pins(\"F10\"), IOStandard(\"LVDS\")) ), (\"clk300\", 0, Subsignal(\"p\", Pins(\"AK17\"), IOStandard(\"DIFF_SSTL12\")),",
"\"G19\", \"HA04_N\" : \"F19\", \"HA08_P\" : \"K18\", \"HA08_N\" : \"K17\",",
"\"D9\", \"LA13_N\" : \"C9\", \"LA17_CC_P\" : \"D24\", \"LA17_CC_N\" : \"C24\",",
"Pins(\"L23\")), Subsignal(\"rts\", Pins(\"K27\")), Subsignal(\"tx\", Pins(\"K26\")), Subsignal(\"rx\", Pins(\"G25\")), IOStandard(\"LVCMOS18\") ), #",
"\"A13\", \"LA03_N\" : \"A12\", \"LA08_P\" : \"J8\", \"LA08_N\" : \"H8\",",
"AL20 AL23\", \"AM24 AN23 AN24 AP23 AP25 AN22 AP24 AM22\",",
"\"J3\", \"DP5_M2C_P\" : \"H2\", \"DP5_M2C_N\" : \"H1\", \"DP6_C2M_P\" : \"L4\",",
"\"B22\", \"LA30_P\" : \"C26\", \"LA30_N\" : \"B26\", \"LA32_P\" : \"E26\",",
"\"LA12_N\" : \"AC23\", \"LA16_P\" : \"AB21\", \"LA16_N\" : \"AC21\", \"LA20_P\"",
"\"LA00_CC_P\" : \"W23\", \"LA00_CC_N\" : \"W24\", \"LA03_P\" : \"W28\", \"LA03_N\"",
"Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2 AD2\")), Subsignal(\"rx_n\",",
"\"H21\", \"LA27_N\" : \"G21\", \"HA01_CC_P\" : \"E16\", \"HA01_CC_N\" : \"D16\",",
": \"Y31\", \"LA30_N\" : \"Y32\", \"LA32_P\" : \"W30\", \"LA32_N\" :",
"AM16 AM15 AN18 AN17\"), ] # Platform ----------------------------------------------------------------------------------------- class Platform(XilinxPlatform):",
": \"A4\", \"DP3_M2C_N\" : \"A3\", \"DP4_C2M_P\" : \"N4\", \"DP4_C2M_N\" :",
": \"F20\", \"PG_M2C\" : \"L27\", \"HA00_CC_P\" : \"G17\", \"HA00_CC_N\" :",
": \"V22\", \"LA07_N\" : \"V23\", \"LA11_P\" : \"V21\", \"LA11_N\" :",
"IOStandard(\"LVCMOS18\") ), (\"sdcard\", 0, Subsignal(\"clk\", Pins(\"AL10\")), Subsignal(\"cmd\", Pins(\"AD9\"), Misc(\"PULLUP True\")),",
"AL3 AM5 AN3\")) ), # SGMII Clk (\"sgmii_clock\", 0, Subsignal(\"p\",",
"AJ28 AH27 AK27 AM26\", \"AL30 AP29 AM30 AN28 AL29 AP28",
"\"G4\", \"DP7_C2M_N\" : \"G3\", \"DP7_M2C_P\" : \"F2\", \"DP7_M2C_N\" : \"F1\",",
"\"D5\", \"DP1_M2C_P\" : \"D2\", \"DP1_M2C_N\" : \"D1\", \"DP2_C2M_P\" : \"C4\",",
"Subsignal(\"p\", Pins(\"D23\"), IOStandard(\"LVDS\")), Subsignal(\"n\", Pins(\"C23\"), IOStandard(\"LVDS\")) ), (\"user_sma_clock_p\", 0, Pins(\"D23\"),",
"LiteX-Boards. # # Copyright (c) 2017-2019 <NAME> <<EMAIL>> # SPDX-License-Identifier:",
"Subsignal(\"n\", Pins(\"T1\")), ), (\"sfp_tx_disable_n\", 0, Pins(\"AL8\"), IOStandard(\"LVCMOS18\")), (\"sfp\", 1, Subsignal(\"txp\",",
"AK20 AP21 AL28 AP30 AJ33 AP34\"), IOStandard(\"DIFF_POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"clk_p\",",
": \"AE32\", \"LA24_N\" : \"AF32\", \"LA28_P\" : \"V31\", \"LA28_N\" :",
"\"K12\", \"LA07_P\" : \"F8\", \"LA07_N\" : \"E8\", \"LA11_P\" : \"K11\",",
"\"LA26_N\" : \"F20\", \"PG_M2C\" : \"L27\", \"HA00_CC_P\" : \"G17\", \"HA00_CC_N\"",
"\"G14\", \"HA07_P\" : \"L19\", \"HA07_N\" : \"L18\", \"HA11_P\" : \"J19\",",
"\"LA11_N\" : \"J11\", \"LA15_P\" : \"D8\", \"LA15_N\" : \"C8\", \"LA19_P\"",
"\"LA00_CC_N\" : \"W24\", \"LA03_P\" : \"W28\", \"LA03_N\" : \"Y28\", \"LA08_P\"",
"AE25 AJ21 AM21 AH26 AN26 AJ29 AL32\"), IOStandard(\"POD12_DCI\")), Subsignal(\"dq\", Pins(",
": \"E15\", \"HA21_N\" : \"D15\", \"HA23_P\" : \"B15\", \"HA23_N\" :",
"\"D18\", \"PRSNT_M2C_B\" : \"H24\", \"CLK0_M2C_P\" : \"H12\", \"CLK0_M2C_N\" : \"G12\",",
"\"LA29_N\" : \"A20\", \"LA31_P\" : \"B25\", \"LA31_N\" : \"A25\", \"LA33_P\"",
"\"HA13_N\" : \"A14\", \"HA16_P\" : \"A19\", \"HA16_N\" : \"A18\", \"HA20_P\"",
"Pins(\"AN16\"), IOStandard(\"LVCMOS12\")), (\"user_dip_btn\", 1, Pins(\"AN19\"), IOStandard(\"LVCMOS12\")), (\"user_dip_btn\", 2, Pins(\"AP18\"), IOStandard(\"LVCMOS12\")),",
": \"B14\", \"HA13_N\" : \"A14\", \"HA16_P\" : \"A19\", \"HA16_N\" :",
"AE18 AJ15 AG16 AL17 AK18 AG17\", \"AF18 AH19 AF15 AD19",
"\"W23\", \"LA00_CC_N\" : \"W24\", \"LA03_P\" : \"W28\", \"LA03_N\" : \"Y28\",",
"Misc(\"PULLUP\")), Subsignal(\"miso\", Pins(\"AP9\"), Misc(\"PULLUP\")), Misc(\"SLEW=FAST\"), IOStandard(\"LVCMOS18\") ), (\"sdcard\", 0, Subsignal(\"clk\",",
"2, Pins(\"P20\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 3, Pins(\"P21\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 4, Pins(\"N22\"),",
"\"LA00_CC_N\" : \"G11\", \"LA03_P\" : \"A13\", \"LA03_N\" : \"A12\", \"LA08_P\"",
"IOStandard(\"SSTL12_DCI\")), Subsignal(\"dm\", Pins(\"AD21 AE25 AJ21 AM21 AH26 AN26 AJ29 AL32\"),",
"Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2 AD2 AF2 AH2\")), Subsignal(\"rx_n\", Pins(\"AB1",
"Leds (\"user_led\", 0, Pins(\"AP8\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 1, Pins(\"H23\"), IOStandard(\"LVCMOS18\")), (\"user_led\",",
"\"HA17_CC_P\" : \"E18\", \"HA17_CC_N\" : \"E17\", \"HA21_P\" : \"E15\", \"HA21_N\"",
"\"LA04_N\" : \"U27\", \"LA07_P\" : \"V22\", \"LA07_N\" : \"V23\", \"LA11_P\"",
"\"D14\", \"HA15_N\" : \"C14\", \"HA19_P\" : \"D19\", \"HA19_N\" : \"D18\",",
"AJ31 AJ30 AH34 AK32\", \"AN33 AP33 AM34 AP31 AM32 AN31",
"Pins(\"AB2\")), Subsignal(\"rx_n\", Pins(\"AB1\")), Subsignal(\"tx_p\", Pins(\"AC4\")), Subsignal(\"tx_n\", Pins(\"AC3\")) ), (\"pcie_x2\", 0,",
"Pins(\"J25\")), IOStandard(\"LVCMOS18\") ), # Serial (\"serial\", 0, Subsignal(\"cts\", Pins(\"L23\")), Subsignal(\"rts\",",
"\"LA30_P\" : \"Y31\", \"LA30_N\" : \"Y32\", \"LA32_P\" : \"W30\", \"LA32_N\"",
"# A15 Subsignal(\"we_n\", Pins(\"AD16\"), IOStandard(\"SSTL12_DCI\")), # A14 Subsignal(\"cs_n\", Pins(\"AL19\"), IOStandard(\"SSTL12_DCI\")),",
"IOs ---------------------------------------------------------------------------------------------- _io = [ # Clk / Rst (\"clk125\",",
": \"J15\", \"HA05_N\" : \"J14\", \"HA09_P\" : \"F18\", \"HA09_N\" :",
"\"HA14_N\" : \"F14\", \"HA18_P\" : \"B17\", \"HA18_N\" : \"B16\", \"HA22_P\"",
"I2C (\"i2c\", 0, Subsignal(\"scl\", Pins(\"J24\")), Subsignal(\"sda\", Pins(\"J25\")), IOStandard(\"LVCMOS18\") ), #",
"AN17\"), ] # Platform ----------------------------------------------------------------------------------------- class Platform(XilinxPlatform): default_clk_name = \"clk125\"",
"AL27 AN29 AH33 AN34\"), IOStandard(\"DIFF_POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"dqs_n\", Pins(\"AH21 AJ25",
"Pins(\"D28\"), IOStandard(\"LVCMOS18\")), ] # Connectors --------------------------------------------------------------------------------------- _connectors = [ (\"HPC\",",
"HDMI (\"hdmi\", 0, Subsignal(\"d\", Pins( \"AK11 AP11 AP13 AN13 AN11",
"(\"sfp\", 1, Subsignal(\"txp\", Pins(\"W4\")), Subsignal(\"txn\", Pins(\"W3\")), Subsignal(\"rxp\", Pins(\"V2\")), Subsignal(\"rxn\", Pins(\"V1\"))",
"\"LA28_N\" : \"W31\", \"LA30_P\" : \"Y31\", \"LA30_N\" : \"Y32\", \"LA32_P\"",
"\"GBTCLK1_M2C_P\" : \"H6\", \"GBTCLK1_M2C_N\" : \"H5\", \"GBTCLK0_M2C_P\" : \"K6\", \"GBTCLK0_M2C_N\"",
"\"HA01_CC_P\" : \"E16\", \"HA01_CC_N\" : \"D16\", \"HA05_P\" : \"J15\", \"HA05_N\"",
"\"AC23\", \"LA16_P\" : \"AB21\", \"LA16_N\" : \"AC21\", \"LA20_P\" : \"AA34\",",
"\"LA01_CC_N\" : \"Y25\", \"LA05_P\" : \"V27\", \"LA05_N\" : \"V28\", \"LA09_P\"",
": \"T22\", \"LA10_N\" : \"T23\", \"LA14_P\" : \"U21\", \"LA14_N\" :",
"\"B21\", \"LA28_N\" : \"B22\", \"LA30_P\" : \"C26\", \"LA30_N\" : \"B26\",",
"\"xcku040-ffva1156-2-e\", _io, _connectors, toolchain=\"vivado\") def create_programmer(self): return VivadoProgrammer() def do_finalize(self,",
"Pins(\"W3\")), Subsignal(\"rxp\", Pins(\"V2\")), Subsignal(\"rxn\", Pins(\"V1\")) ), (\"sfp_tx\", 1, Subsignal(\"p\", Pins(\"W4\")),",
"\"H16\", \"HA17_CC_P\" : \"E18\", \"HA17_CC_N\" : \"E17\", \"HA21_P\" : \"E15\",",
"\"LA21_P\" : \"AC33\", \"LA21_N\" : \"AD33\", \"LA24_P\" : \"AE32\", \"LA24_N\"",
"\"HA20_P\" : \"C19\", \"HA20_N\" : \"B19\", \"CLK1_M2C_P\" : \"E25\", \"CLK1_M2C_N\"",
"loose=True), 1e9/125e6) self.add_period_constraint(self.lookup_request(\"clk300\", loose=True), 1e9/300e6) self.add_platform_command(\"set_property INTERNAL_VREF 0.84 [get_iobanks 44]\")",
"\"D16\", \"HA05_P\" : \"J15\", \"HA05_N\" : \"J14\", \"HA09_P\" : \"F18\",",
": \"AA25\", \"LA02_P\" : \"AA22\", \"LA02_N\" : \"AB22\", \"LA04_P\" :",
"\"LA16_N\" : \"AC21\", \"LA20_P\" : \"AA34\", \"LA20_N\" : \"AB34\", \"LA22_P\"",
"(\"user_dip_btn\", 3, Pins(\"AN14\"), IOStandard(\"LVCMOS12\")), # SMA (\"user_sma_clock\", 0, Subsignal(\"p\", Pins(\"D23\"),",
"\"HA05_P\" : \"J15\", \"HA05_N\" : \"J14\", \"HA09_P\" : \"F18\", \"HA09_N\"",
": \"AC22\", \"LA12_N\" : \"AC23\", \"LA16_P\" : \"AB21\", \"LA16_N\" :",
"fragment): XilinxPlatform.do_finalize(self, fragment) self.add_period_constraint(self.lookup_request(\"clk125\", loose=True), 1e9/125e6) self.add_period_constraint(self.lookup_request(\"clk300\", loose=True), 1e9/300e6) self.add_platform_command(\"set_property",
"Pins(\"AF9\"), IOStandard(\"LVCMOS18\")), (\"user_btn_e\", 0, Pins(\"AE8\"), IOStandard(\"LVCMOS18\")), # Switches (\"user_dip_btn\", 0,",
"(\"user_btn_w\", 0, Pins(\"AF9\"), IOStandard(\"LVCMOS18\")), (\"user_btn_e\", 0, Pins(\"AE8\"), IOStandard(\"LVCMOS18\")), # Switches",
": \"E16\", \"HA01_CC_N\" : \"D16\", \"HA05_P\" : \"J15\", \"HA05_N\" :",
": \"A24\", \"LA22_P\" : \"G24\", \"LA22_N\" : \"F25\", \"LA25_P\" :",
"\"PG_M2C\" : \"L27\", \"HA00_CC_P\" : \"G17\", \"HA00_CC_N\" : \"G16\", \"HA04_P\"",
": \"K6\", \"GBTCLK0_M2C_N\" : \"K5\", \"LA01_CC_P\" : \"G9\", \"LA01_CC_N\" :",
"AJ3 AK1 AM1 AP1\")), Subsignal(\"tx_p\", Pins(\"AC4 AE4 AG4 AH6 AK6",
"\"LA20_P\" : \"B24\", \"LA20_N\" : \"A24\", \"LA22_P\" : \"G24\", \"LA22_N\"",
": \"Y25\", \"LA05_P\" : \"V27\", \"LA05_N\" : \"V28\", \"LA09_P\" :",
"to be accessed through primitive Subsignal(\"cs_n\", Pins(\"U7\")), Subsignal(\"dq\", Pins(\"AC7 AB7",
"(\"user_led\", 4, Pins(\"N22\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 5, Pins(\"M22\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 6,",
"\"CLK1_M2C_N\" : \"D25\", \"LA00_CC_P\" : \"H11\", \"LA00_CC_N\" : \"G11\", \"LA03_P\"",
": \"H17\", \"HA10_N\" : \"H16\", \"HA17_CC_P\" : \"E18\", \"HA17_CC_N\" :",
"\"DP1_C2M_N\" : \"D5\", \"DP1_M2C_P\" : \"D2\", \"DP1_M2C_N\" : \"D1\", \"DP2_C2M_P\"",
"), # SGMII Clk (\"sgmii_clock\", 0, Subsignal(\"p\", Pins(\"P26\"), IOStandard(\"LVDS_25\")), Subsignal(\"n\",",
"\"V31\", \"LA28_N\" : \"W31\", \"LA30_P\" : \"Y31\", \"LA30_N\" : \"Y32\",",
": \"AB21\", \"LA16_N\" : \"AC21\", \"LA20_P\" : \"AA34\", \"LA20_N\" :",
"def do_finalize(self, fragment): XilinxPlatform.do_finalize(self, fragment) self.add_period_constraint(self.lookup_request(\"clk125\", loose=True), 1e9/125e6) self.add_period_constraint(self.lookup_request(\"clk300\", loose=True),",
"\"DP7_M2C_P\" : \"F2\", \"DP7_M2C_N\" : \"F1\", \"LA06_P\" : \"D13\", \"LA06_N\"",
"Subsignal(\"tx_p\", Pins(\"AC4 AE4\")), Subsignal(\"tx_n\", Pins(\"AC3 AE3\")) ), (\"pcie_x4\", 0, Subsignal(\"rst_n\",",
"AJ23 AF23 AH23 AF24 AH22 AG25\", \"AL22 AL25 AM20 AK23",
"SDCard (\"spisdcard\", 0, Subsignal(\"clk\", Pins(\"AL10\")), Subsignal(\"cs_n\", Pins(\"AH8\")), Subsignal(\"mosi\", Pins(\"AD9\"), Misc(\"PULLUP\")),",
": \"C8\", \"LA19_P\" : \"C21\", \"LA19_N\" : \"C22\", \"LA21_P\" :",
": \"AG32\", \"CLK1_M2C_P\" : \"AC31\", \"CLK1_M2C_N\" : \"AC32\", \"LA00_CC_P\" :",
"AF25 AE21 AM17\"), (\"pmod1\", \"AL14 AM14 AP16 AP15 AM16 AM15",
"IOStandard(\"SSTL12_DCI\")), Subsignal(\"ba\", Pins(\"AF17 AL15\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"bg\", Pins(\"AG15\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"ras_n\", Pins(\"AF14\"),",
": \"E3\", \"DP1_C2M_P\" : \"D6\", \"DP1_C2M_N\" : \"D5\", \"DP1_M2C_P\" :",
": \"L19\", \"HA07_N\" : \"L18\", \"HA11_P\" : \"J19\", \"HA11_N\" :",
"\"A20\", \"LA31_P\" : \"B25\", \"LA31_N\" : \"A25\", \"LA33_P\" : \"A27\",",
": \"AA24\", \"CLK0_M2C_N\" : \"AA25\", \"LA02_P\" : \"AA22\", \"LA02_N\" :",
"Pins(\"F10\"), IOStandard(\"LVDS\")) ), (\"clk300\", 0, Subsignal(\"p\", Pins(\"AK17\"), IOStandard(\"DIFF_SSTL12\")), Subsignal(\"n\", Pins(\"AK16\"),",
"AK2 AM2 AP2\")), Subsignal(\"rx_n\", Pins(\"AB1 AD1 AF1 AH1 AJ3 AK1",
"\"V26\", \"LA09_N\" : \"W26\", \"LA13_P\" : \"AA20\", \"LA13_N\" : \"AB20\",",
"\"E17\", \"HA21_P\" : \"E15\", \"HA21_N\" : \"D15\", \"HA23_P\" : \"B15\",",
"Switches (\"user_dip_btn\", 0, Pins(\"AN16\"), IOStandard(\"LVCMOS12\")), (\"user_dip_btn\", 1, Pins(\"AN19\"), IOStandard(\"LVCMOS12\")), (\"user_dip_btn\",",
": \"L3\", \"DP6_M2C_P\" : \"K2\", \"DP6_M2C_N\" : \"K1\", \"DP7_C2M_P\" :",
"Pins(\"AP9\"), Misc(\"PULLUP\")), Misc(\"SLEW=FAST\"), IOStandard(\"LVCMOS18\") ), (\"sdcard\", 0, Subsignal(\"clk\", Pins(\"AL10\")), Subsignal(\"cmd\",",
"Subsignal(\"hsync\", Pins(\"AE13\")), Subsignal(\"spdif\", Pins(\"AE12\")), Subsignal(\"spdif_out\", Pins(\"AF12\")), IOStandard(\"LVCMOS18\") ), # DDR4",
"SGMII Clk (\"sgmii_clock\", 0, Subsignal(\"p\", Pins(\"P26\"), IOStandard(\"LVDS_25\")), Subsignal(\"n\", Pins(\"N26\"), IOStandard(\"LVDS_25\"))",
"AK8\")), Subsignal(\"de\", Pins(\"AE11\")), Subsignal(\"clk\", Pins(\"AF13\")), Subsignal(\"vsync\", Pins(\"AH13\")), Subsignal(\"hsync\", Pins(\"AE13\")), Subsignal(\"spdif\",",
": \"A10\", \"LA18_CC_P\" : \"E22\", \"LA18_CC_N\" : \"E23\", \"LA27_P\" :",
"Pins(\"AL10\")), Subsignal(\"cmd\", Pins(\"AD9\"), Misc(\"PULLUP True\")), Subsignal(\"data\", Pins(\"AP9 AN9 AH9 AH8\"),",
"0, Subsignal(\"p\", Pins(\"T2\")), Subsignal(\"n\", Pins(\"T1\")), ), (\"sfp_tx_disable_n\", 0, Pins(\"AL8\"), IOStandard(\"LVCMOS18\")),",
"), (\"sfp_tx\", 0, Subsignal(\"p\", Pins(\"U4\")), Subsignal(\"n\", Pins(\"U3\")), ), (\"sfp_rx\", 0,",
"} ), (\"pmod0\", \"AK25 AN21 AH18 AM19 AE26 AF25 AE21",
": \"W30\", \"LA32_N\" : \"Y30\", \"LA06_P\" : \"V29\", \"LA06_N\" :",
"), # SPIFlash (\"spiflash\", 0, # clock needs to be",
"Pins(\"J24\")), Subsignal(\"sda\", Pins(\"J25\")), IOStandard(\"LVCMOS18\") ), # Serial (\"serial\", 0, Subsignal(\"cts\",",
"Pins(\"AJ16\"), IOStandard(\"SSTL12_DCI\")), #Subsignal(\"par\", Pins(\"AD18\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"dm\", Pins(\"AD21 AE25 AJ21 AM21",
"AD1 AF1 AH1\")), Subsignal(\"tx_p\", Pins(\"AC4 AE4 AG4 AH6\")), Subsignal(\"tx_n\", Pins(\"AC3",
"\"HA09_N\" : \"F17\", \"HA13_P\" : \"B14\", \"HA13_N\" : \"A14\", \"HA16_P\"",
"AP34\"), IOStandard(\"DIFF_POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"clk_p\", Pins(\"AE16\"), IOStandard(\"DIFF_SSTL12_DCI\")), Subsignal(\"clk_n\", Pins(\"AE15\"), IOStandard(\"DIFF_SSTL12_DCI\")),",
"\"B10\", \"LA14_N\" : \"A10\", \"LA18_CC_P\" : \"E22\", \"LA18_CC_N\" : \"E23\",",
": \"J4\", \"DP5_C2M_N\" : \"J3\", \"DP5_M2C_P\" : \"H2\", \"DP5_M2C_N\" :",
"\"LA20_N\" : \"A24\", \"LA22_P\" : \"G24\", \"LA22_N\" : \"F25\", \"LA25_P\"",
"(\"spisdcard\", 0, Subsignal(\"clk\", Pins(\"AL10\")), Subsignal(\"cs_n\", Pins(\"AH8\")), Subsignal(\"mosi\", Pins(\"AD9\"), Misc(\"PULLUP\")), Subsignal(\"miso\",",
"\"HA10_N\" : \"H16\", \"HA17_CC_P\" : \"E18\", \"HA17_CC_N\" : \"E17\", \"HA21_P\"",
"IOStandard(\"LVCMOS18\")), (\"user_led\", 1, Pins(\"H23\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 2, Pins(\"P20\"), IOStandard(\"LVCMOS18\")), (\"user_led\",",
"Subsignal(\"sda\", Pins(\"J25\")), IOStandard(\"LVCMOS18\") ), # Serial (\"serial\", 0, Subsignal(\"cts\", Pins(\"L23\")),",
"\"LA22_P\" : \"G24\", \"LA22_N\" : \"F25\", \"LA25_P\" : \"D20\", \"LA25_N\"",
"\"DP5_C2M_N\" : \"J3\", \"DP5_M2C_P\" : \"H2\", \"DP5_M2C_N\" : \"H1\", \"DP6_C2M_P\"",
": \"AF34\", \"LA29_P\" : \"U34\", \"LA29_N\" : \"V34\", \"LA31_P\" :",
"IOStandard(\"LVCMOS18\")), # Buttons (\"user_btn_c\", 0, Pins(\"AE10\"), IOStandard(\"LVCMOS18\")), (\"user_btn_n\", 0, Pins(\"AD10\"),",
"AD19 AJ14 AG19\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"ba\", Pins(\"AF17 AL15\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"bg\", Pins(\"AG15\"),",
"), (\"pmod0\", \"AK25 AN21 AH18 AM19 AE26 AF25 AE21 AM17\"),",
": \"J14\", \"HA09_P\" : \"F18\", \"HA09_N\" : \"F17\", \"HA13_P\" :",
"\"L3\", \"DP6_M2C_P\" : \"K2\", \"DP6_M2C_N\" : \"K1\", \"DP7_C2M_P\" : \"G4\",",
": \"F1\", \"LA06_P\" : \"D13\", \"LA06_N\" : \"C13\", \"LA10_P\" :",
"Buttons (\"user_btn_c\", 0, Pins(\"AE10\"), IOStandard(\"LVCMOS18\")), (\"user_btn_n\", 0, Pins(\"AD10\"), IOStandard(\"LVCMOS18\")), (\"user_btn_s\",",
"# SI570 (\"si570_refclk\", 0, Subsignal(\"p\", Pins(\"P6\")), Subsignal(\"n\", Pins(\"P5\")) ), #",
": \"A19\", \"HA16_N\" : \"A18\", \"HA20_P\" : \"C19\", \"HA20_N\" :",
"\"C8\", \"LA19_P\" : \"C21\", \"LA19_N\" : \"C22\", \"LA21_P\" : \"F23\",",
"IOStandard(\"LVDS_25\")), Subsignal(\"n\", Pins(\"N26\"), IOStandard(\"LVDS_25\")) ), # SI570 (\"si570_refclk\", 0, Subsignal(\"p\",",
"\"LA13_N\" : \"C9\", \"LA17_CC_P\" : \"D24\", \"LA17_CC_N\" : \"C24\", \"LA23_P\"",
"\"AG10 AK8\")), Subsignal(\"de\", Pins(\"AE11\")), Subsignal(\"clk\", Pins(\"AF13\")), Subsignal(\"vsync\", Pins(\"AH13\")), Subsignal(\"hsync\", Pins(\"AE13\")),",
"accessed through primitive Subsignal(\"cs_n\", Pins(\"G26\")), Subsignal(\"dq\", Pins(\"M20 L20 R21 R22\")),",
"\"LA31_N\" : \"A25\", \"LA33_P\" : \"A27\", \"LA33_N\" : \"A28\", \"HA03_P\"",
"\"HA23_P\" : \"B15\", \"HA23_N\" : \"A15\", } ), (\"LPC\", {",
"\"AC33\", \"LA21_N\" : \"AD33\", \"LA24_P\" : \"AE32\", \"LA24_N\" : \"AF32\",",
"Pins(\"AG21 AH24 AJ20 AP20 AL27 AN29 AH33 AN34\"), IOStandard(\"DIFF_POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"),",
": \"A15\", } ), (\"LPC\", { \"GBTCLK0_M2C_P\" : \"AA24\", \"GBTCLK0_M2C_N\"",
"\"DP6_M2C_N\" : \"K1\", \"DP7_C2M_P\" : \"G4\", \"DP7_C2M_N\" : \"G3\", \"DP7_M2C_P\"",
"\"V22\", \"LA07_N\" : \"V23\", \"LA11_P\" : \"V21\", \"LA11_N\" : \"W21\",",
"\"LA31_P\" : \"V33\", \"LA31_N\" : \"W34\", \"LA33_P\" : \"W33\", \"LA33_N\"",
": \"G15\", \"HA03_N\" : \"G14\", \"HA07_P\" : \"L19\", \"HA07_N\" :",
": \"C24\", \"LA23_P\" : \"G22\", \"LA23_N\" : \"F22\", \"LA26_P\" :",
"\"HA15_P\" : \"D14\", \"HA15_N\" : \"C14\", \"HA19_P\" : \"D19\", \"HA19_N\"",
"\"LA00_CC_P\" : \"H11\", \"LA00_CC_N\" : \"G11\", \"LA03_P\" : \"A13\", \"LA03_N\"",
"def __init__(self): XilinxPlatform.__init__(self, \"xcku040-ffva1156-2-e\", _io, _connectors, toolchain=\"vivado\") def create_programmer(self): return",
"\"K15\", \"HA10_P\" : \"H17\", \"HA10_N\" : \"H16\", \"HA17_CC_P\" : \"E18\",",
"IOStandard(\"SSTL12_DCI\")), Subsignal(\"odt\", Pins(\"AJ18\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"reset_n\", Pins(\"AL18\"), IOStandard(\"LVCMOS12\")), Misc(\"SLEW=FAST\"), ), #",
"\"AM24 AN23 AN24 AP23 AP25 AN22 AP24 AM22\", \"AH28 AK26",
"\"CLK1_M2C_P\" : \"E25\", \"CLK1_M2C_N\" : \"D25\", \"LA00_CC_P\" : \"H11\", \"LA00_CC_N\"",
": \"J10\", \"LA04_P\" : \"L12\", \"LA04_N\" : \"K12\", \"LA07_P\" :",
"Subsignal(\"we_n\", Pins(\"AD16\"), IOStandard(\"SSTL12_DCI\")), # A14 Subsignal(\"cs_n\", Pins(\"AL19\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"act_n\", Pins(\"AH14\"),",
"\"C21\", \"LA19_N\" : \"C22\", \"LA21_P\" : \"F23\", \"LA21_N\" : \"F24\",",
"\"F23\", \"LA21_N\" : \"F24\", \"LA24_P\" : \"E20\", \"LA24_N\" : \"E21\",",
"fragment) self.add_period_constraint(self.lookup_request(\"clk125\", loose=True), 1e9/125e6) self.add_period_constraint(self.lookup_request(\"clk300\", loose=True), 1e9/300e6) self.add_platform_command(\"set_property INTERNAL_VREF 0.84",
": \"B19\", \"CLK1_M2C_P\" : \"E25\", \"CLK1_M2C_N\" : \"D25\", \"LA00_CC_P\" :",
"AG24 AJ23 AF23 AH23 AF24 AH22 AG25\", \"AL22 AL25 AM20",
"(\"user_sma_mgt_tx\", 0, Subsignal(\"p\", Pins(\"R4\")), Subsignal(\"n\", Pins(\"R3\")) ), (\"user_sma_mgt_rx\", 0, Subsignal(\"p\",",
"BSD-2-Clause from litex.build.generic_platform import * from litex.build.xilinx import XilinxPlatform, VivadoProgrammer",
"Pins(\"U4\")), Subsignal(\"n\", Pins(\"U3\")), ), (\"sfp_rx\", 0, Subsignal(\"p\", Pins(\"T2\")), Subsignal(\"n\", Pins(\"T1\")),",
"] # Platform ----------------------------------------------------------------------------------------- class Platform(XilinxPlatform): default_clk_name = \"clk125\" default_clk_period",
"IOStandard(\"SSTL12_DCI\")), #Subsignal(\"alert_n\", Pins(\"AJ16\"), IOStandard(\"SSTL12_DCI\")), #Subsignal(\"par\", Pins(\"AD18\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"dm\", Pins(\"AD21 AE25",
"\"LA06_P\" : \"V29\", \"LA06_N\" : \"W29\", \"LA10_P\" : \"T22\", \"LA10_N\"",
"accessed through primitive Subsignal(\"cs_n\", Pins(\"U7\")), Subsignal(\"dq\", Pins(\"AC7 AB7 AA7 Y7\")),",
"\"AB20\", \"LA17_CC_P\" : \"AA32\", \"LA17_CC_N\" : \"AB32\", \"LA23_P\" : \"AD30\",",
"AL17 AK18 AG17\", \"AF18 AH19 AF15 AD19 AJ14 AG19\"), IOStandard(\"SSTL12_DCI\")),",
"\"AA29\", \"LA19_N\" : \"AB29\", \"LA21_P\" : \"AC33\", \"LA21_N\" : \"AD33\",",
"AG3 AH5\")) ), (\"pcie_x8\", 0, Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")),",
"IOStandard(\"DIFF_SSTL12\")), Subsignal(\"n\", Pins(\"AK16\"), IOStandard(\"DIFF_SSTL12\")) ), (\"cpu_reset\", 0, Pins(\"AN8\"), IOStandard(\"LVCMOS18\")), #",
": \"U34\", \"LA29_N\" : \"V34\", \"LA31_P\" : \"V33\", \"LA31_N\" :",
"SDRAM (\"ddram\", 0, Subsignal(\"a\", Pins( \"AE17 AH17 AE18 AJ15 AG16",
": \"D2\", \"DP1_M2C_N\" : \"D1\", \"DP2_C2M_P\" : \"C4\", \"DP2_C2M_N\" :",
"Rst (\"clk125\", 0, Subsignal(\"p\", Pins(\"G10\"), IOStandard(\"LVDS\")), Subsignal(\"n\", Pins(\"F10\"), IOStandard(\"LVDS\")) ),",
"AN11 AM11 AN12 AM12\", \"AL12 AK12 AL13 AK13 AD11 AH12",
"Subsignal(\"tx_n\", Pins(\"AC3 AE3 AG3 AH5\")) ), (\"pcie_x8\", 0, Subsignal(\"rst_n\", Pins(\"K22\"),",
"\"LA25_P\" : \"D20\", \"LA25_N\" : \"D21\", \"LA29_P\" : \"B20\", \"LA29_N\"",
"IOStandard(\"LVDS\")) ), (\"user_sma_clock_p\", 0, Pins(\"D23\"), IOStandard(\"LVCMOS18\")), (\"user_sma_clock_n\", 0, Pins(\"C23\"), IOStandard(\"LVCMOS18\")),",
"0, Subsignal(\"p\", Pins(\"P6\")), Subsignal(\"n\", Pins(\"P5\")) ), # SMA (\"user_sma_mgt_refclk\", 0,",
"# I2C (\"i2c\", 0, Subsignal(\"scl\", Pins(\"J24\")), Subsignal(\"sda\", Pins(\"J25\")), IOStandard(\"LVCMOS18\") ),",
"Pins(\"P1\")) ), # SFP (\"sfp\", 0, Subsignal(\"txp\", Pins(\"U4\")), Subsignal(\"txn\", Pins(\"U3\")),",
"0, Subsignal(\"p\", Pins(\"U4\")), Subsignal(\"n\", Pins(\"U3\")), ), (\"sfp_rx\", 0, Subsignal(\"p\", Pins(\"T2\")),",
"\"LA25_N\" : \"AF34\", \"LA29_P\" : \"U34\", \"LA29_N\" : \"V34\", \"LA31_P\"",
"Pins(\"AF28\")), IOStandard(\"LVCMOS18\") ), # HDMI (\"hdmi\", 0, Subsignal(\"d\", Pins( \"AK11",
"AK6 AL4 AM6 AN4\")), Subsignal(\"tx_n\", Pins(\"AC3 AE3 AG3 AH5 AK5",
"\"CLK0_M2C_P\" : \"AA24\", \"CLK0_M2C_N\" : \"AA25\", \"LA02_P\" : \"AA22\", \"LA02_N\"",
"\"LA12_P\" : \"AC22\", \"LA12_N\" : \"AC23\", \"LA16_P\" : \"AB21\", \"LA16_N\"",
"Subsignal(\"n\", Pins(\"U3\")), ), (\"sfp_rx\", 0, Subsignal(\"p\", Pins(\"T2\")), Subsignal(\"n\", Pins(\"T1\")), ),",
"\"DP4_M2C_N\" : \"M1\", \"DP5_C2M_P\" : \"J4\", \"DP5_C2M_N\" : \"J3\", \"DP5_M2C_P\"",
"R22\")), IOStandard(\"LVCMOS18\") ), # SDCard (\"spisdcard\", 0, Subsignal(\"clk\", Pins(\"AL10\")), Subsignal(\"cs_n\",",
"IOStandard(\"LVDS\")), Subsignal(\"n\", Pins(\"C23\"), IOStandard(\"LVDS\")) ), (\"user_sma_clock_p\", 0, Pins(\"D23\"), IOStandard(\"LVCMOS18\")), (\"user_sma_clock_n\",",
"Copyright (c) 2017-2019 <NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause from litex.build.generic_platform",
"Pins(\"AN19\"), IOStandard(\"LVCMOS12\")), (\"user_dip_btn\", 2, Pins(\"AP18\"), IOStandard(\"LVCMOS12\")), (\"user_dip_btn\", 3, Pins(\"AN14\"), IOStandard(\"LVCMOS12\")),",
"[ # Clk / Rst (\"clk125\", 0, Subsignal(\"p\", Pins(\"G10\"), IOStandard(\"LVDS\")),",
"), # PCIe (\"pcie_x1\", 0, Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")),",
"1, Pins(\"AN19\"), IOStandard(\"LVCMOS12\")), (\"user_dip_btn\", 2, Pins(\"AP18\"), IOStandard(\"LVCMOS12\")), (\"user_dip_btn\", 3, Pins(\"AN14\"),",
"Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"clk_p\", Pins(\"AE16\"), IOStandard(\"DIFF_SSTL12_DCI\")), Subsignal(\"clk_n\", Pins(\"AE15\"), IOStandard(\"DIFF_SSTL12_DCI\")), Subsignal(\"cke\", Pins(\"AD15\"),",
"Subsignal(\"tx_p\", Pins(\"AC4 AE4 AG4 AH6 AK6 AL4 AM6 AN4\")), Subsignal(\"tx_n\",",
"\"LA07_N\" : \"V23\", \"LA11_P\" : \"V21\", \"LA11_N\" : \"W21\", \"LA15_P\"",
"Pins(\"AD9\"), Misc(\"PULLUP\")), Subsignal(\"miso\", Pins(\"AP9\"), Misc(\"PULLUP\")), Misc(\"SLEW=FAST\"), IOStandard(\"LVCMOS18\") ), (\"sdcard\", 0,",
"AK31 AJ31 AJ30 AH34 AK32\", \"AN33 AP33 AM34 AP31 AM32",
"IOStandard(\"LVCMOS18\")), (\"user_led\", 7, Pins(\"P23\"), IOStandard(\"LVCMOS18\")), # Buttons (\"user_btn_c\", 0, Pins(\"AE10\"),",
"\"A14\", \"HA16_P\" : \"A19\", \"HA16_N\" : \"A18\", \"HA20_P\" : \"C19\",",
"(\"i2c\", 0, Subsignal(\"scl\", Pins(\"J24\")), Subsignal(\"sda\", Pins(\"J25\")), IOStandard(\"LVCMOS18\") ), # Serial",
"Subsignal(\"txp\", Pins(\"U4\")), Subsignal(\"txn\", Pins(\"U3\")), Subsignal(\"rxp\", Pins(\"T2\")), Subsignal(\"rxn\", Pins(\"T1\")) ), (\"sfp_tx\",",
"\"LA31_P\" : \"B25\", \"LA31_N\" : \"A25\", \"LA33_P\" : \"A27\", \"LA33_N\"",
"\"LA33_P\" : \"W33\", \"LA33_N\" : \"Y33\", } ), (\"pmod0\", \"AK25",
": \"AG34\", \"CLK0_M2C_P\" : \"AA24\", \"CLK0_M2C_N\" : \"AA25\", \"LA02_P\" :",
"AM12\", \"AL12 AK12 AL13 AK13 AD11 AH12 AG12 AJ11\", \"AG10",
"\"LA07_N\" : \"E8\", \"LA11_P\" : \"K11\", \"LA11_N\" : \"J11\", \"LA15_P\"",
"Pins(\"AD16\"), IOStandard(\"SSTL12_DCI\")), # A14 Subsignal(\"cs_n\", Pins(\"AL19\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"act_n\", Pins(\"AH14\"), IOStandard(\"SSTL12_DCI\")),",
"2, Pins(\"AP18\"), IOStandard(\"LVCMOS12\")), (\"user_dip_btn\", 3, Pins(\"AN14\"), IOStandard(\"LVCMOS12\")), # SMA (\"user_sma_clock\",",
"Subsignal(\"cmd\", Pins(\"AD9\"), Misc(\"PULLUP True\")), Subsignal(\"data\", Pins(\"AP9 AN9 AH9 AH8\"), Misc(\"PULLUP",
"), # SI570 (\"si570_refclk\", 0, Subsignal(\"p\", Pins(\"P6\")), Subsignal(\"n\", Pins(\"P5\")) ),",
"IOStandard(\"LVDS\")), Subsignal(\"n\", Pins(\"G27\"), IOStandard(\"LVDS\")) ), (\"user_sma_gpio_p\", 0, Pins(\"H27\"), IOStandard(\"LVCMOS18\")), (\"user_sma_gpio_n\",",
"\"G17\", \"HA00_CC_N\" : \"G16\", \"HA04_P\" : \"G19\", \"HA04_N\" : \"F19\",",
"IOStandard(\"POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"dqs_p\", Pins(\"AG21 AH24 AJ20 AP20 AL27 AN29",
"(\"HPC\", { \"DP0_C2M_P\" : \"F6\", \"DP0_C2M_N\" : \"F5\", \"DP0_M2C_P\" :",
"AP13 AN13 AN11 AM11 AN12 AM12\", \"AL12 AK12 AL13 AK13",
"\"L18\", \"HA11_P\" : \"J19\", \"HA11_N\" : \"J18\", \"HA14_P\" : \"F15\",",
"IOStandard(\"LVDS_25\")) ), # SI570 (\"si570_refclk\", 0, Subsignal(\"p\", Pins(\"P6\")), Subsignal(\"n\", Pins(\"P5\"))",
"\"CLK0_M2C_N\" : \"AA25\", \"LA02_P\" : \"AA22\", \"LA02_N\" : \"AB22\", \"LA04_P\"",
"IOStandard(\"SSTL12_DCI\")), Subsignal(\"reset_n\", Pins(\"AL18\"), IOStandard(\"LVCMOS12\")), Misc(\"SLEW=FAST\"), ), # PCIe (\"pcie_x1\", 0,",
"\"B5\", \"DP3_M2C_P\" : \"A4\", \"DP3_M2C_N\" : \"A3\", \"DP4_C2M_P\" : \"N4\",",
"\"E21\", \"LA28_P\" : \"B21\", \"LA28_N\" : \"B22\", \"LA30_P\" : \"C26\",",
"AM32 AN31 AL34 AN32\"), IOStandard(\"POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"dqs_p\", Pins(\"AG21 AH24",
": \"AA22\", \"LA02_N\" : \"AB22\", \"LA04_P\" : \"U26\", \"LA04_N\" :",
"Pins(\"T1\")) ), (\"sfp_tx\", 0, Subsignal(\"p\", Pins(\"U4\")), Subsignal(\"n\", Pins(\"U3\")), ), (\"sfp_rx\",",
": \"E26\", \"LA32_N\" : \"D26\", \"HA02_P\" : \"H19\", \"HA02_N\" :",
"IOStandard(\"LVCMOS18\")), # I2C (\"i2c\", 0, Subsignal(\"scl\", Pins(\"J24\")), Subsignal(\"sda\", Pins(\"J25\")), IOStandard(\"LVCMOS18\")",
"AH2 AJ4 AK2 AM2 AP2\")), Subsignal(\"rx_n\", Pins(\"AB1 AD1 AF1 AH1",
"2017-2019 <NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause from litex.build.generic_platform import *",
"\"D15\", \"HA23_P\" : \"B15\", \"HA23_N\" : \"A15\", } ), (\"LPC\",",
"AL34 AN32\"), IOStandard(\"POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"dqs_p\", Pins(\"AG21 AH24 AJ20 AP20",
"\"LA33_P\" : \"A27\", \"LA33_N\" : \"A28\", \"HA03_P\" : \"G15\", \"HA03_N\"",
"\"AH28 AK26 AK28 AM27 AJ28 AH27 AK27 AM26\", \"AL30 AP29",
"\"F25\", \"LA25_P\" : \"D20\", \"LA25_N\" : \"D21\", \"LA29_P\" : \"B20\",",
"\"HA05_N\" : \"J14\", \"HA09_P\" : \"F18\", \"HA09_N\" : \"F17\", \"HA13_P\"",
"IOStandard(\"SSTL12_DCI\")), Subsignal(\"act_n\", Pins(\"AH14\"), IOStandard(\"SSTL12_DCI\")), #Subsignal(\"ten\", Pins(\"AH16\"), IOStandard(\"SSTL12_DCI\")), #Subsignal(\"alert_n\", Pins(\"AJ16\"), IOStandard(\"SSTL12_DCI\")),",
"\"LA21_N\" : \"AD33\", \"LA24_P\" : \"AE32\", \"LA24_N\" : \"AF32\", \"LA28_P\"",
": \"U22\", \"LA18_CC_P\" : \"AB30\", \"LA18_CC_N\" : \"AB31\", \"LA27_P\" :",
"\"D8\", \"LA15_N\" : \"C8\", \"LA19_P\" : \"C21\", \"LA19_N\" : \"C22\",",
": \"L13\", \"LA05_N\" : \"K13\", \"LA09_P\" : \"J9\", \"LA09_N\" :",
"\"LA01_CC_P\" : \"W25\", \"LA01_CC_N\" : \"Y25\", \"LA05_P\" : \"V27\", \"LA05_N\"",
": \"F8\", \"LA07_N\" : \"E8\", \"LA11_P\" : \"K11\", \"LA11_N\" :",
"Subsignal(\"dq\", Pins( \"AE23 AG20 AF22 AF20 AE22 AD20 AG22 AE20\",",
"\"Y28\", \"LA08_P\" : \"U24\", \"LA08_N\" : \"U25\", \"LA12_P\" : \"AC22\",",
": \"L4\", \"DP6_C2M_N\" : \"L3\", \"DP6_M2C_P\" : \"K2\", \"DP6_M2C_N\" :",
"\"HA22_N\" : \"C17\", \"GBTCLK1_M2C_P\" : \"H6\", \"GBTCLK1_M2C_N\" : \"H5\", \"GBTCLK0_M2C_P\"",
"AF1 AH1 AJ3 AK1 AM1 AP1\")), Subsignal(\"tx_p\", Pins(\"AC4 AE4 AG4",
"IOStandard(\"LVCMOS12\")), # SMA (\"user_sma_clock\", 0, Subsignal(\"p\", Pins(\"D23\"), IOStandard(\"LVDS\")), Subsignal(\"n\", Pins(\"C23\"),",
"Pins(\"AH16\"), IOStandard(\"SSTL12_DCI\")), #Subsignal(\"alert_n\", Pins(\"AJ16\"), IOStandard(\"SSTL12_DCI\")), #Subsignal(\"par\", Pins(\"AD18\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"dm\", Pins(\"AD21",
": \"D13\", \"LA06_N\" : \"C13\", \"LA10_P\" : \"L8\", \"LA10_N\" :",
": \"F24\", \"LA24_P\" : \"E20\", \"LA24_N\" : \"E21\", \"LA28_P\" :",
"Subsignal(\"miso\", Pins(\"AP9\"), Misc(\"PULLUP\")), Misc(\"SLEW=FAST\"), IOStandard(\"LVCMOS18\") ), (\"sdcard\", 0, Subsignal(\"clk\", Pins(\"AL10\")),",
"\"LA30_N\" : \"B26\", \"LA32_P\" : \"E26\", \"LA32_N\" : \"D26\", \"HA02_P\"",
"Pins(\"AC4\")), Subsignal(\"tx_n\", Pins(\"AC3\")) ), (\"pcie_x2\", 0, Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\",",
"\"W33\", \"LA33_N\" : \"Y33\", } ), (\"pmod0\", \"AK25 AN21 AH18",
"AN12 AM12\", \"AL12 AK12 AL13 AK13 AD11 AH12 AG12 AJ11\",",
"\"AD34\", \"LA25_P\" : \"AE33\", \"LA25_N\" : \"AF34\", \"LA29_P\" : \"U34\",",
"Pins(\"K26\")), Subsignal(\"rx\", Pins(\"G25\")), IOStandard(\"LVCMOS18\") ), # SPIFlash (\"spiflash\", 0, #",
": \"H9\", \"LA13_P\" : \"D9\", \"LA13_N\" : \"C9\", \"LA17_CC_P\" :",
"\"A9\", \"LA20_P\" : \"B24\", \"LA20_N\" : \"A24\", \"LA22_P\" : \"G24\",",
"Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2 AD2\")), Subsignal(\"rx_n\", Pins(\"AB1 AD1\")), Subsignal(\"tx_p\", Pins(\"AC4",
"Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2 AD2 AF2 AH2\")), Subsignal(\"rx_n\", Pins(\"AB1 AD1 AF1",
"\"B26\", \"LA32_P\" : \"E26\", \"LA32_N\" : \"D26\", \"HA02_P\" : \"H19\",",
"\"LA13_N\" : \"AB20\", \"LA17_CC_P\" : \"AA32\", \"LA17_CC_N\" : \"AB32\", \"LA23_P\"",
": \"Y32\", \"LA32_P\" : \"W30\", \"LA32_N\" : \"Y30\", \"LA06_P\" :",
"\"V27\", \"LA05_N\" : \"V28\", \"LA09_P\" : \"V26\", \"LA09_N\" : \"W26\",",
"Pins(\"T1\")), ), (\"sfp_tx_disable_n\", 0, Pins(\"AL8\"), IOStandard(\"LVCMOS18\")), (\"sfp\", 1, Subsignal(\"txp\", Pins(\"W4\")),",
"\"K17\", \"HA12_P\" : \"K16\", \"HA12_N\" : \"J16\", \"HA15_P\" : \"D14\",",
": \"N3\", \"DP4_M2C_P\" : \"M2\", \"DP4_M2C_N\" : \"M1\", \"DP5_C2M_P\" :",
"AH34 AK32\", \"AN33 AP33 AM34 AP31 AM32 AN31 AL34 AN32\"),",
": \"D10\", \"LA16_P\" : \"B9\", \"LA16_N\" : \"A9\", \"LA20_P\" :",
"\"HA18_P\" : \"B17\", \"HA18_N\" : \"B16\", \"HA22_P\" : \"C18\", \"HA22_N\"",
"# A14 Subsignal(\"cs_n\", Pins(\"AL19\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"act_n\", Pins(\"AH14\"), IOStandard(\"SSTL12_DCI\")), #Subsignal(\"ten\", Pins(\"AH16\"),",
"\"D24\", \"LA17_CC_N\" : \"C24\", \"LA23_P\" : \"G22\", \"LA23_N\" : \"F22\",",
"# Buttons (\"user_btn_c\", 0, Pins(\"AE10\"), IOStandard(\"LVCMOS18\")), (\"user_btn_n\", 0, Pins(\"AD10\"), IOStandard(\"LVCMOS18\")),",
"\"W21\", \"LA15_P\" : \"AB25\", \"LA15_N\" : \"AB26\", \"LA19_P\" : \"AA29\",",
"Pins(\"W4\")), Subsignal(\"txn\", Pins(\"W3\")), Subsignal(\"rxp\", Pins(\"V2\")), Subsignal(\"rxn\", Pins(\"V1\")) ), (\"sfp_tx\", 1,",
"\"AL30 AP29 AM30 AN28 AL29 AP28 AM29 AN27\", \"AH31 AH32",
"Pins(\"AH13\")), Subsignal(\"hsync\", Pins(\"AE13\")), Subsignal(\"spdif\", Pins(\"AE12\")), Subsignal(\"spdif_out\", Pins(\"AF12\")), IOStandard(\"LVCMOS18\") ), #",
"through primitive Subsignal(\"cs_n\", Pins(\"G26\")), Subsignal(\"dq\", Pins(\"M20 L20 R21 R22\")), IOStandard(\"LVCMOS18\")",
"\"LA17_CC_P\" : \"D24\", \"LA17_CC_N\" : \"C24\", \"LA23_P\" : \"G22\", \"LA23_N\"",
"\"AG31\", \"LA27_N\" : \"AG32\", \"CLK1_M2C_P\" : \"AC31\", \"CLK1_M2C_N\" : \"AC32\",",
"# clock needs to be accessed through primitive Subsignal(\"cs_n\", Pins(\"G26\")),",
": \"E18\", \"HA17_CC_N\" : \"E17\", \"HA21_P\" : \"E15\", \"HA21_N\" :",
"(\"user_sma_clock_n\", 0, Pins(\"C23\"), IOStandard(\"LVCMOS18\")), (\"user_sma_gpio\", 0, Subsignal(\"p\", Pins(\"H27\"), IOStandard(\"LVDS\")), Subsignal(\"n\",",
": \"H12\", \"CLK0_M2C_N\" : \"G12\", \"LA02_P\" : \"K10\", \"LA02_N\" :",
"AG16 AL17 AK18 AG17\", \"AF18 AH19 AF15 AD19 AJ14 AG19\"),",
"# Connectors --------------------------------------------------------------------------------------- _connectors = [ (\"HPC\", { \"DP0_C2M_P\" :",
": \"D15\", \"HA23_P\" : \"B15\", \"HA23_N\" : \"A15\", } ),",
"# # This file is part of LiteX-Boards. # #",
"# SMA (\"user_sma_mgt_refclk\", 0, Subsignal(\"p\", Pins(\"V6\")), Subsignal(\"n\", Pins(\"V5\")) ), (\"user_sma_mgt_tx\",",
"IOStandard(\"LVCMOS18\")), (\"user_led\", 3, Pins(\"P21\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 4, Pins(\"N22\"), IOStandard(\"LVCMOS18\")), (\"user_led\",",
"Subsignal(\"odt\", Pins(\"AJ18\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"reset_n\", Pins(\"AL18\"), IOStandard(\"LVCMOS12\")), Misc(\"SLEW=FAST\"), ), # PCIe",
"\"AL22 AL25 AM20 AK23 AK22 AL24 AL20 AL23\", \"AM24 AN23",
"\"LA32_N\" : \"D26\", \"HA02_P\" : \"H19\", \"HA02_N\" : \"H18\", \"HA06_P\"",
"\"T23\", \"LA14_P\" : \"U21\", \"LA14_N\" : \"U22\", \"LA18_CC_P\" : \"AB30\",",
"clock needs to be accessed through primitive Subsignal(\"cs_n\", Pins(\"G26\")), Subsignal(\"dq\",",
"Subsignal(\"dm\", Pins(\"AD21 AE25 AJ21 AM21 AH26 AN26 AJ29 AL32\"), IOStandard(\"POD12_DCI\")),",
"\"K11\", \"LA11_N\" : \"J11\", \"LA15_P\" : \"D8\", \"LA15_N\" : \"C8\",",
"AP30 AJ33 AP34\"), IOStandard(\"DIFF_POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"clk_p\", Pins(\"AE16\"), IOStandard(\"DIFF_SSTL12_DCI\")), Subsignal(\"clk_n\",",
"Pins(\"AF13\")), Subsignal(\"vsync\", Pins(\"AH13\")), Subsignal(\"hsync\", Pins(\"AE13\")), Subsignal(\"spdif\", Pins(\"AE12\")), Subsignal(\"spdif_out\", Pins(\"AF12\")), IOStandard(\"LVCMOS18\")",
"--------------------------------------------------------------------------------------- _connectors = [ (\"HPC\", { \"DP0_C2M_P\" : \"F6\", \"DP0_C2M_N\"",
"AN24 AP23 AP25 AN22 AP24 AM22\", \"AH28 AK26 AK28 AM27",
"IOStandard(\"DIFF_POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"clk_p\", Pins(\"AE16\"), IOStandard(\"DIFF_SSTL12_DCI\")), Subsignal(\"clk_n\", Pins(\"AE15\"), IOStandard(\"DIFF_SSTL12_DCI\")), Subsignal(\"cke\",",
"\"N3\", \"DP4_M2C_P\" : \"M2\", \"DP4_M2C_N\" : \"M1\", \"DP5_C2M_P\" : \"J4\",",
"\"LA25_N\" : \"D21\", \"LA29_P\" : \"B20\", \"LA29_N\" : \"A20\", \"LA31_P\"",
"IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2 AD2\")), Subsignal(\"rx_n\", Pins(\"AB1",
"\"AA24\", \"GBTCLK0_M2C_N\" : \"AA25\", \"LA01_CC_P\" : \"W25\", \"LA01_CC_N\" : \"Y25\",",
"\"DP0_M2C_P\" : \"E4\", \"DP0_M2C_N\" : \"E3\", \"DP1_C2M_P\" : \"D6\", \"DP1_C2M_N\"",
"Pins(\"AC4 AE4 AG4 AH6\")), Subsignal(\"tx_n\", Pins(\"AC3 AE3 AG3 AH5\")) ),",
"Pins(\"P6\")), Subsignal(\"n\", Pins(\"P5\")) ), # SMA (\"user_sma_mgt_refclk\", 0, Subsignal(\"p\", Pins(\"V6\")),",
": \"W31\", \"LA30_P\" : \"Y31\", \"LA30_N\" : \"Y32\", \"LA32_P\" :",
"\"U27\", \"LA07_P\" : \"V22\", \"LA07_N\" : \"V23\", \"LA11_P\" : \"V21\",",
"\"D6\", \"DP1_C2M_N\" : \"D5\", \"DP1_M2C_P\" : \"D2\", \"DP1_M2C_N\" : \"D1\",",
"Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2 AD2\")),",
"IOStandard(\"LVCMOS12\")), (\"user_dip_btn\", 3, Pins(\"AN14\"), IOStandard(\"LVCMOS12\")), # SMA (\"user_sma_clock\", 0, Subsignal(\"p\",",
"\"LA01_CC_N\" : \"F9\", \"LA05_P\" : \"L13\", \"LA05_N\" : \"K13\", \"LA09_P\"",
"(\"spiflash\", 0, # clock needs to be accessed through primitive",
"IOStandard(\"LVCMOS18\")), (\"user_led\", 4, Pins(\"N22\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 5, Pins(\"M22\"), IOStandard(\"LVCMOS18\")), (\"user_led\",",
"AM26\", \"AL30 AP29 AM30 AN28 AL29 AP28 AM29 AN27\", \"AH31",
"\"GBTCLK0_M2C_N\" : \"K5\", \"LA01_CC_P\" : \"G9\", \"LA01_CC_N\" : \"F9\", \"LA05_P\"",
"Pins(\"V5\")) ), (\"user_sma_mgt_tx\", 0, Subsignal(\"p\", Pins(\"R4\")), Subsignal(\"n\", Pins(\"R3\")) ), (\"user_sma_mgt_rx\",",
"INTERNAL_VREF 0.84 [get_iobanks 44]\") self.add_platform_command(\"set_property INTERNAL_VREF 0.84 [get_iobanks 45]\") self.add_platform_command(\"set_property",
"), # SFP (\"sfp\", 0, Subsignal(\"txp\", Pins(\"U4\")), Subsignal(\"txn\", Pins(\"U3\")), Subsignal(\"rxp\",",
"_io, _connectors, toolchain=\"vivado\") def create_programmer(self): return VivadoProgrammer() def do_finalize(self, fragment):",
"(\"user_sma_gpio_n\", 0, Pins(\"G27\"), IOStandard(\"LVCMOS18\")), # I2C (\"i2c\", 0, Subsignal(\"scl\", Pins(\"J24\")),",
"(\"user_btn_n\", 0, Pins(\"AD10\"), IOStandard(\"LVCMOS18\")), (\"user_btn_s\", 0, Pins(\"AF8\"), IOStandard(\"LVCMOS18\")), (\"user_btn_w\", 0,",
": \"F14\", \"HA18_P\" : \"B17\", \"HA18_N\" : \"B16\", \"HA22_P\" :",
"\"B16\", \"HA22_P\" : \"C18\", \"HA22_N\" : \"C17\", \"GBTCLK1_M2C_P\" : \"H6\",",
"\"LA03_P\" : \"A13\", \"LA03_N\" : \"A12\", \"LA08_P\" : \"J8\", \"LA08_N\"",
"SMA (\"user_sma_clock\", 0, Subsignal(\"p\", Pins(\"D23\"), IOStandard(\"LVDS\")), Subsignal(\"n\", Pins(\"C23\"), IOStandard(\"LVDS\")) ),",
": \"A18\", \"HA20_P\" : \"C19\", \"HA20_N\" : \"B19\", \"CLK1_M2C_P\" :",
"\"C18\", \"HA22_N\" : \"C17\", \"GBTCLK1_M2C_P\" : \"H6\", \"GBTCLK1_M2C_N\" : \"H5\",",
"Pins(\"U3\")), Subsignal(\"rxp\", Pins(\"T2\")), Subsignal(\"rxn\", Pins(\"T1\")) ), (\"sfp_tx\", 0, Subsignal(\"p\", Pins(\"U4\")),",
"AK1 AM1 AP1\")), Subsignal(\"tx_p\", Pins(\"AC4 AE4 AG4 AH6 AK6 AL4",
"AE4\")), Subsignal(\"tx_n\", Pins(\"AC3 AE3\")) ), (\"pcie_x4\", 0, Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")),",
"AP11 AP13 AN13 AN11 AM11 AN12 AM12\", \"AL12 AK12 AL13",
"0, Subsignal(\"p\", Pins(\"V6\")), Subsignal(\"n\", Pins(\"V5\")) ), (\"user_sma_mgt_tx\", 0, Subsignal(\"p\", Pins(\"R4\")),",
"(\"sfp_tx\", 0, Subsignal(\"p\", Pins(\"U4\")), Subsignal(\"n\", Pins(\"U3\")), ), (\"sfp_rx\", 0, Subsignal(\"p\",",
"\"H1\", \"DP6_C2M_P\" : \"L4\", \"DP6_C2M_N\" : \"L3\", \"DP6_M2C_P\" : \"K2\",",
"AM17\"), (\"pmod1\", \"AL14 AM14 AP16 AP15 AM16 AM15 AN18 AN17\"),",
"Subsignal(\"n\", Pins(\"AK16\"), IOStandard(\"DIFF_SSTL12\")) ), (\"cpu_reset\", 0, Pins(\"AN8\"), IOStandard(\"LVCMOS18\")), # Leds",
"(\"user_sma_mgt_refclk\", 0, Subsignal(\"p\", Pins(\"V6\")), Subsignal(\"n\", Pins(\"V5\")) ), (\"user_sma_mgt_tx\", 0, Subsignal(\"p\",",
"0, Subsignal(\"scl\", Pins(\"J24\")), Subsignal(\"sda\", Pins(\"J25\")), IOStandard(\"LVCMOS18\") ), # Serial (\"serial\",",
"0, Pins(\"G27\"), IOStandard(\"LVCMOS18\")), # I2C (\"i2c\", 0, Subsignal(\"scl\", Pins(\"J24\")), Subsignal(\"sda\",",
"Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2 AD2 AF2 AH2\")), Subsignal(\"rx_n\", Pins(\"AB1 AD1",
": \"C26\", \"LA30_N\" : \"B26\", \"LA32_P\" : \"E26\", \"LA32_N\" :",
"# SMA (\"user_sma_clock\", 0, Subsignal(\"p\", Pins(\"D23\"), IOStandard(\"LVDS\")), Subsignal(\"n\", Pins(\"C23\"), IOStandard(\"LVDS\"))",
"0, Pins(\"AL8\"), IOStandard(\"LVCMOS18\")), (\"sfp\", 1, Subsignal(\"txp\", Pins(\"W4\")), Subsignal(\"txn\", Pins(\"W3\")), Subsignal(\"rxp\",",
": \"V23\", \"LA11_P\" : \"V21\", \"LA11_N\" : \"W21\", \"LA15_P\" :",
"\"J10\", \"LA04_P\" : \"L12\", \"LA04_N\" : \"K12\", \"LA07_P\" : \"F8\",",
": \"AB26\", \"LA19_P\" : \"AA29\", \"LA19_N\" : \"AB29\", \"LA21_P\" :",
"clock needs to be accessed through primitive Subsignal(\"cs_n\", Pins(\"U7\")), Subsignal(\"dq\",",
": \"AA20\", \"LA13_N\" : \"AB20\", \"LA17_CC_P\" : \"AA32\", \"LA17_CC_N\" :",
"\"H11\", \"LA00_CC_N\" : \"G11\", \"LA03_P\" : \"A13\", \"LA03_N\" : \"A12\",",
"AM1 AP1\")), Subsignal(\"tx_p\", Pins(\"AC4 AE4 AG4 AH6 AK6 AL4 AM6",
"Pins(\"R3\")) ), (\"user_sma_mgt_rx\", 0, Subsignal(\"p\", Pins(\"P2\")), Subsignal(\"n\", Pins(\"P1\")) ), #",
"\"LA10_N\" : \"K8\", \"LA14_P\" : \"B10\", \"LA14_N\" : \"A10\", \"LA18_CC_P\"",
": \"Y30\", \"LA06_P\" : \"V29\", \"LA06_N\" : \"W29\", \"LA10_P\" :",
"Pins(\"AC4 AE4\")), Subsignal(\"tx_n\", Pins(\"AC3 AE3\")) ), (\"pcie_x4\", 0, Subsignal(\"rst_n\", Pins(\"K22\"),",
"to be accessed through primitive Subsignal(\"cs_n\", Pins(\"G26\")), Subsignal(\"dq\", Pins(\"M20 L20",
": \"D6\", \"DP1_C2M_N\" : \"D5\", \"DP1_M2C_P\" : \"D2\", \"DP1_M2C_N\" :",
"), (\"sfp_rx\", 1, Subsignal(\"p\", Pins(\"V2\")), Subsignal(\"n\", Pins(\"V1\")), ), (\"sfp_tx_disable_n\", 1,",
"(\"pmod1\", \"AL14 AM14 AP16 AP15 AM16 AM15 AN18 AN17\"), ]",
"Pins(\"N26\"), IOStandard(\"LVDS_25\")) ), # SI570 (\"si570_refclk\", 0, Subsignal(\"p\", Pins(\"P6\")), Subsignal(\"n\",",
"\"E22\", \"LA18_CC_N\" : \"E23\", \"LA27_P\" : \"H21\", \"LA27_N\" : \"G21\",",
"(\"sfp\", 0, Subsignal(\"txp\", Pins(\"U4\")), Subsignal(\"txn\", Pins(\"U3\")), Subsignal(\"rxp\", Pins(\"T2\")), Subsignal(\"rxn\", Pins(\"T1\"))",
"AG22 AE20\", \"AJ24 AG24 AJ23 AF23 AH23 AF24 AH22 AG25\",",
"True\")), Subsignal(\"data\", Pins(\"AP9 AN9 AH9 AH8\"), Misc(\"PULLUP True\")), Misc(\"SLEW=FAST\"), IOStandard(\"LVCMOS18\")",
"\"Y32\", \"LA32_P\" : \"W30\", \"LA32_N\" : \"Y30\", \"LA06_P\" : \"V29\",",
"\"A24\", \"LA22_P\" : \"G24\", \"LA22_N\" : \"F25\", \"LA25_P\" : \"D20\",",
"Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2\")), Subsignal(\"rx_n\", Pins(\"AB1\")),",
"Pins(\"C23\"), IOStandard(\"LVDS\")) ), (\"user_sma_clock_p\", 0, Pins(\"D23\"), IOStandard(\"LVCMOS18\")), (\"user_sma_clock_n\", 0, Pins(\"C23\"),",
"\"B17\", \"HA18_N\" : \"B16\", \"HA22_P\" : \"C18\", \"HA22_N\" : \"C17\",",
"\"LA15_P\" : \"D8\", \"LA15_N\" : \"C8\", \"LA19_P\" : \"C21\", \"LA19_N\"",
"# Clk / Rst (\"clk125\", 0, Subsignal(\"p\", Pins(\"G10\"), IOStandard(\"LVDS\")), Subsignal(\"n\",",
"\"DP0_C2M_P\" : \"F6\", \"DP0_C2M_N\" : \"F5\", \"DP0_M2C_P\" : \"E4\", \"DP0_M2C_N\"",
": \"G22\", \"LA23_N\" : \"F22\", \"LA26_P\" : \"G20\", \"LA26_N\" :",
"\"AA34\", \"LA20_N\" : \"AB34\", \"LA22_P\" : \"AC34\", \"LA22_N\" : \"AD34\",",
"Subsignal(\"rx\", Pins(\"G25\")), IOStandard(\"LVCMOS18\") ), # SPIFlash (\"spiflash\", 0, # clock",
"AE20\", \"AJ24 AG24 AJ23 AF23 AH23 AF24 AH22 AG25\", \"AL22",
"\"LA27_P\" : \"H21\", \"LA27_N\" : \"G21\", \"HA01_CC_P\" : \"E16\", \"HA01_CC_N\"",
"PCIe (\"pcie_x1\", 0, Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")),",
"Subsignal(\"a\", Pins(\"Y21\")), Subsignal(\"b\", Pins(\"AD26\")), Subsignal(\"push\", Pins(\"AF28\")), IOStandard(\"LVCMOS18\") ), # HDMI",
"AP25 AN22 AP24 AM22\", \"AH28 AK26 AK28 AM27 AJ28 AH27",
": \"G9\", \"LA01_CC_N\" : \"F9\", \"LA05_P\" : \"L13\", \"LA05_N\" :",
"\"LA20_N\" : \"AB34\", \"LA22_P\" : \"AC34\", \"LA22_N\" : \"AD34\", \"LA25_P\"",
": \"AC32\", \"LA00_CC_P\" : \"W23\", \"LA00_CC_N\" : \"W24\", \"LA03_P\" :",
"\"J16\", \"HA15_P\" : \"D14\", \"HA15_N\" : \"C14\", \"HA19_P\" : \"D19\",",
"\"clk125\" default_clk_period = 1e9/125e6 def __init__(self): XilinxPlatform.__init__(self, \"xcku040-ffva1156-2-e\", _io, _connectors,",
"Pins(\"W4\")), Subsignal(\"n\", Pins(\"W3\")), ), (\"sfp_rx\", 1, Subsignal(\"p\", Pins(\"V2\")), Subsignal(\"n\", Pins(\"V1\")),",
"IOStandard(\"LVCMOS18\")), (\"user_sma_clock_n\", 0, Pins(\"C23\"), IOStandard(\"LVCMOS18\")), (\"user_sma_gpio\", 0, Subsignal(\"p\", Pins(\"H27\"), IOStandard(\"LVDS\")),",
"XilinxPlatform.do_finalize(self, fragment) self.add_period_constraint(self.lookup_request(\"clk125\", loose=True), 1e9/125e6) self.add_period_constraint(self.lookup_request(\"clk300\", loose=True), 1e9/300e6) self.add_platform_command(\"set_property INTERNAL_VREF",
": \"AB32\", \"LA23_P\" : \"AD30\", \"LA23_N\" : \"AD31\", \"LA26_P\" :",
"= [ # Clk / Rst (\"clk125\", 0, Subsignal(\"p\", Pins(\"G10\"),",
"Pins(\"P2\")), Subsignal(\"n\", Pins(\"P1\")) ), # SFP (\"sfp\", 0, Subsignal(\"txp\", Pins(\"U4\")),",
"Subsignal(\"cs_n\", Pins(\"AL19\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"act_n\", Pins(\"AH14\"), IOStandard(\"SSTL12_DCI\")), #Subsignal(\"ten\", Pins(\"AH16\"), IOStandard(\"SSTL12_DCI\")), #Subsignal(\"alert_n\",",
"AN28 AL29 AP28 AM29 AN27\", \"AH31 AH32 AJ34 AK31 AJ31",
"return VivadoProgrammer() def do_finalize(self, fragment): XilinxPlatform.do_finalize(self, fragment) self.add_period_constraint(self.lookup_request(\"clk125\", loose=True), 1e9/125e6)",
"AJ20 AP20 AL27 AN29 AH33 AN34\"), IOStandard(\"DIFF_POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"dqs_n\",",
"), # HDMI (\"hdmi\", 0, Subsignal(\"d\", Pins( \"AK11 AP11 AP13",
"AH5 AK5 AL3 AM5 AN3\")) ), # SGMII Clk (\"sgmii_clock\",",
"\"HA13_P\" : \"B14\", \"HA13_N\" : \"A14\", \"HA16_P\" : \"A19\", \"HA16_N\"",
": \"E8\", \"LA11_P\" : \"K11\", \"LA11_N\" : \"J11\", \"LA15_P\" :",
"\"LA29_P\" : \"U34\", \"LA29_N\" : \"V34\", \"LA31_P\" : \"V33\", \"LA31_N\"",
"{ \"DP0_C2M_P\" : \"F6\", \"DP0_C2M_N\" : \"F5\", \"DP0_M2C_P\" : \"E4\",",
"\"LA22_P\" : \"AC34\", \"LA22_N\" : \"AD34\", \"LA25_P\" : \"AE33\", \"LA25_N\"",
"\"LA33_N\" : \"Y33\", } ), (\"pmod0\", \"AK25 AN21 AH18 AM19",
"(\"pmod0\", \"AK25 AN21 AH18 AM19 AE26 AF25 AE21 AM17\"), (\"pmod1\",",
"\"C26\", \"LA30_N\" : \"B26\", \"LA32_P\" : \"E26\", \"LA32_N\" : \"D26\",",
"(\"pcie_x8\", 0, Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\",",
"(\"user_led\", 6, Pins(\"R23\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 7, Pins(\"P23\"), IOStandard(\"LVCMOS18\")), # Buttons",
"AK18 AG17\", \"AF18 AH19 AF15 AD19 AJ14 AG19\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"ba\",",
"def create_programmer(self): return VivadoProgrammer() def do_finalize(self, fragment): XilinxPlatform.do_finalize(self, fragment) self.add_period_constraint(self.lookup_request(\"clk125\",",
"\"K16\", \"HA12_N\" : \"J16\", \"HA15_P\" : \"D14\", \"HA15_N\" : \"C14\",",
"\"LA12_P\" : \"E10\", \"LA12_N\" : \"D10\", \"LA16_P\" : \"B9\", \"LA16_N\"",
"AD1 AF1 AH1 AJ3 AK1 AM1 AP1\")), Subsignal(\"tx_p\", Pins(\"AC4 AE4",
": \"F15\", \"HA14_N\" : \"F14\", \"HA18_P\" : \"B17\", \"HA18_N\" :",
": \"AD31\", \"LA26_P\" : \"AF33\", \"LA26_N\" : \"AG34\", \"CLK0_M2C_P\" :",
": \"W28\", \"LA03_N\" : \"Y28\", \"LA08_P\" : \"U24\", \"LA08_N\" :",
": \"AA25\", \"LA01_CC_P\" : \"W25\", \"LA01_CC_N\" : \"Y25\", \"LA05_P\" :",
"VivadoProgrammer() def do_finalize(self, fragment): XilinxPlatform.do_finalize(self, fragment) self.add_period_constraint(self.lookup_request(\"clk125\", loose=True), 1e9/125e6) self.add_period_constraint(self.lookup_request(\"clk300\",",
"\"AD31\", \"LA26_P\" : \"AF33\", \"LA26_N\" : \"AG34\", \"CLK0_M2C_P\" : \"AA24\",",
"\"AA25\", \"LA02_P\" : \"AA22\", \"LA02_N\" : \"AB22\", \"LA04_P\" : \"U26\",",
": \"C4\", \"DP2_C2M_N\" : \"C3\", \"DP2_M2C_P\" : \"B2\", \"DP2_M2C_N\" :",
"\"K8\", \"LA14_P\" : \"B10\", \"LA14_N\" : \"A10\", \"LA18_CC_P\" : \"E22\",",
": \"H21\", \"LA27_N\" : \"G21\", \"HA01_CC_P\" : \"E16\", \"HA01_CC_N\" :",
"Subsignal(\"p\", Pins(\"P6\")), Subsignal(\"n\", Pins(\"P5\")) ), # SMA (\"user_sma_mgt_refclk\", 0, Subsignal(\"p\",",
": \"D14\", \"HA15_N\" : \"C14\", \"HA19_P\" : \"D19\", \"HA19_N\" :",
"\"J4\", \"DP5_C2M_N\" : \"J3\", \"DP5_M2C_P\" : \"H2\", \"DP5_M2C_N\" : \"H1\",",
": \"J11\", \"LA15_P\" : \"D8\", \"LA15_N\" : \"C8\", \"LA19_P\" :",
"\"PRSNT_M2C_B\" : \"H24\", \"CLK0_M2C_P\" : \"H12\", \"CLK0_M2C_N\" : \"G12\", \"LA02_P\"",
"Pins(\"AD18\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"dm\", Pins(\"AD21 AE25 AJ21 AM21 AH26 AN26 AJ29",
"IOStandard(\"SSTL12_DCI\")), Subsignal(\"bg\", Pins(\"AG15\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"ras_n\", Pins(\"AF14\"), IOStandard(\"SSTL12_DCI\")), # A16 Subsignal(\"cas_n\",",
"\"H24\", \"CLK0_M2C_P\" : \"H12\", \"CLK0_M2C_N\" : \"G12\", \"LA02_P\" : \"K10\",",
"IOStandard(\"SSTL12_DCI\")), Subsignal(\"ras_n\", Pins(\"AF14\"), IOStandard(\"SSTL12_DCI\")), # A16 Subsignal(\"cas_n\", Pins(\"AG14\"), IOStandard(\"SSTL12_DCI\")), #",
"\"A4\", \"DP3_M2C_N\" : \"A3\", \"DP4_C2M_P\" : \"N4\", \"DP4_C2M_N\" : \"N3\",",
"# A16 Subsignal(\"cas_n\", Pins(\"AG14\"), IOStandard(\"SSTL12_DCI\")), # A15 Subsignal(\"we_n\", Pins(\"AD16\"), IOStandard(\"SSTL12_DCI\")),",
": \"V31\", \"LA28_N\" : \"W31\", \"LA30_P\" : \"Y31\", \"LA30_N\" :",
"\"LA24_N\" : \"E21\", \"LA28_P\" : \"B21\", \"LA28_N\" : \"B22\", \"LA30_P\"",
": \"G3\", \"DP7_M2C_P\" : \"F2\", \"DP7_M2C_N\" : \"F1\", \"LA06_P\" :",
"\"HA08_P\" : \"K18\", \"HA08_N\" : \"K17\", \"HA12_P\" : \"K16\", \"HA12_N\"",
": \"G20\", \"LA26_N\" : \"F20\", \"PG_M2C\" : \"L27\", \"HA00_CC_P\" :",
"Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2 AD2",
"AN27\", \"AH31 AH32 AJ34 AK31 AJ31 AJ30 AH34 AK32\", \"AN33",
"IOStandard(\"LVCMOS18\")), ] # Connectors --------------------------------------------------------------------------------------- _connectors = [ (\"HPC\", {",
"\"K5\", \"LA01_CC_P\" : \"G9\", \"LA01_CC_N\" : \"F9\", \"LA05_P\" : \"L13\",",
"Pins(\"AD15\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"odt\", Pins(\"AJ18\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"reset_n\", Pins(\"AL18\"), IOStandard(\"LVCMOS12\")), Misc(\"SLEW=FAST\"), ),",
"AK12 AL13 AK13 AD11 AH12 AG12 AJ11\", \"AG10 AK8\")), Subsignal(\"de\",",
"(\"user_sma_gpio_p\", 0, Pins(\"H27\"), IOStandard(\"LVCMOS18\")), (\"user_sma_gpio_n\", 0, Pins(\"G27\"), IOStandard(\"LVCMOS18\")), # I2C",
"\"LA29_P\" : \"B20\", \"LA29_N\" : \"A20\", \"LA31_P\" : \"B25\", \"LA31_N\"",
"_io = [ # Clk / Rst (\"clk125\", 0, Subsignal(\"p\",",
"[ (\"HPC\", { \"DP0_C2M_P\" : \"F6\", \"DP0_C2M_N\" : \"F5\", \"DP0_M2C_P\"",
"Pins(\"V6\")), Subsignal(\"n\", Pins(\"V5\")) ), (\"user_sma_mgt_tx\", 0, Subsignal(\"p\", Pins(\"R4\")), Subsignal(\"n\", Pins(\"R3\"))",
": \"H5\", \"GBTCLK0_M2C_P\" : \"K6\", \"GBTCLK0_M2C_N\" : \"K5\", \"LA01_CC_P\" :",
"Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2 AD2\")), Subsignal(\"rx_n\", Pins(\"AB1 AD1\")), Subsignal(\"tx_p\",",
"\"B1\", \"DP3_C2M_P\" : \"B6\", \"DP3_C2M_N\" : \"B5\", \"DP3_M2C_P\" : \"A4\",",
"0, Subsignal(\"a\", Pins( \"AE17 AH17 AE18 AJ15 AG16 AL17 AK18",
"AD2 AF2 AH2\")), Subsignal(\"rx_n\", Pins(\"AB1 AD1 AF1 AH1\")), Subsignal(\"tx_p\", Pins(\"AC4",
"Subsignal(\"d\", Pins( \"AK11 AP11 AP13 AN13 AN11 AM11 AN12 AM12\",",
"Subsignal(\"cts\", Pins(\"L23\")), Subsignal(\"rts\", Pins(\"K27\")), Subsignal(\"tx\", Pins(\"K26\")), Subsignal(\"rx\", Pins(\"G25\")), IOStandard(\"LVCMOS18\") ),",
"\"LA09_P\" : \"J9\", \"LA09_N\" : \"H9\", \"LA13_P\" : \"D9\", \"LA13_N\"",
"(\"sgmii_clock\", 0, Subsignal(\"p\", Pins(\"P26\"), IOStandard(\"LVDS_25\")), Subsignal(\"n\", Pins(\"N26\"), IOStandard(\"LVDS_25\")) ), #",
": \"AD30\", \"LA23_N\" : \"AD31\", \"LA26_P\" : \"AF33\", \"LA26_N\" :",
"\"D10\", \"LA16_P\" : \"B9\", \"LA16_N\" : \"A9\", \"LA20_P\" : \"B24\",",
"6, Pins(\"R23\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 7, Pins(\"P23\"), IOStandard(\"LVCMOS18\")), # Buttons (\"user_btn_c\",",
"(\"user_dip_btn\", 1, Pins(\"AN19\"), IOStandard(\"LVCMOS12\")), (\"user_dip_btn\", 2, Pins(\"AP18\"), IOStandard(\"LVCMOS12\")), (\"user_dip_btn\", 3,",
"AH6 AK6 AL4 AM6 AN4\")), Subsignal(\"tx_n\", Pins(\"AC3 AE3 AG3 AH5",
": \"E22\", \"LA18_CC_N\" : \"E23\", \"LA27_P\" : \"H21\", \"LA27_N\" :",
"\"H17\", \"HA10_N\" : \"H16\", \"HA17_CC_P\" : \"E18\", \"HA17_CC_N\" : \"E17\",",
"\"LA05_P\" : \"L13\", \"LA05_N\" : \"K13\", \"LA09_P\" : \"J9\", \"LA09_N\"",
"Y7\")), IOStandard(\"LVCMOS18\") ), (\"spiflash\", 1, # clock needs to be",
"\"LA13_P\" : \"AA20\", \"LA13_N\" : \"AB20\", \"LA17_CC_P\" : \"AA32\", \"LA17_CC_N\"",
"1, Subsignal(\"txp\", Pins(\"W4\")), Subsignal(\"txn\", Pins(\"W3\")), Subsignal(\"rxp\", Pins(\"V2\")), Subsignal(\"rxn\", Pins(\"V1\")) ),",
"# DDR4 SDRAM (\"ddram\", 0, Subsignal(\"a\", Pins( \"AE17 AH17 AE18",
": \"A3\", \"DP4_C2M_P\" : \"N4\", \"DP4_C2M_N\" : \"N3\", \"DP4_M2C_P\" :",
"\"LA18_CC_P\" : \"E22\", \"LA18_CC_N\" : \"E23\", \"LA27_P\" : \"H21\", \"LA27_N\"",
"# SGMII Clk (\"sgmii_clock\", 0, Subsignal(\"p\", Pins(\"P26\"), IOStandard(\"LVDS_25\")), Subsignal(\"n\", Pins(\"N26\"),",
"\"LA13_P\" : \"D9\", \"LA13_N\" : \"C9\", \"LA17_CC_P\" : \"D24\", \"LA17_CC_N\"",
": \"AF32\", \"LA28_P\" : \"V31\", \"LA28_N\" : \"W31\", \"LA30_P\" :",
"\"LA11_N\" : \"W21\", \"LA15_P\" : \"AB25\", \"LA15_N\" : \"AB26\", \"LA19_P\"",
"AN31 AL34 AN32\"), IOStandard(\"POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"dqs_p\", Pins(\"AG21 AH24 AJ20",
"\"LA29_N\" : \"V34\", \"LA31_P\" : \"V33\", \"LA31_N\" : \"W34\", \"LA33_P\"",
"\"HA08_N\" : \"K17\", \"HA12_P\" : \"K16\", \"HA12_N\" : \"J16\", \"HA15_P\"",
"Pins(\"AL8\"), IOStandard(\"LVCMOS18\")), (\"sfp\", 1, Subsignal(\"txp\", Pins(\"W4\")), Subsignal(\"txn\", Pins(\"W3\")), Subsignal(\"rxp\", Pins(\"V2\")),",
"#Subsignal(\"par\", Pins(\"AD18\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"dm\", Pins(\"AD21 AE25 AJ21 AM21 AH26 AN26",
"= 1e9/125e6 def __init__(self): XilinxPlatform.__init__(self, \"xcku040-ffva1156-2-e\", _io, _connectors, toolchain=\"vivado\") def",
"AJ14 AG19\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"ba\", Pins(\"AF17 AL15\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"bg\", Pins(\"AG15\"), IOStandard(\"SSTL12_DCI\")),",
"# clock needs to be accessed through primitive Subsignal(\"cs_n\", Pins(\"U7\")),",
"IOStandard(\"LVCMOS12\")), Misc(\"SLEW=FAST\"), ), # PCIe (\"pcie_x1\", 0, Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")),",
": \"D16\", \"HA05_P\" : \"J15\", \"HA05_N\" : \"J14\", \"HA09_P\" :",
"AP33 AM34 AP31 AM32 AN31 AL34 AN32\"), IOStandard(\"POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")),",
": \"AC21\", \"LA20_P\" : \"AA34\", \"LA20_N\" : \"AB34\", \"LA22_P\" :",
"Pins(\"AK17\"), IOStandard(\"DIFF_SSTL12\")), Subsignal(\"n\", Pins(\"AK16\"), IOStandard(\"DIFF_SSTL12\")) ), (\"cpu_reset\", 0, Pins(\"AN8\"), IOStandard(\"LVCMOS18\")),",
"Pins(\"U3\")), ), (\"sfp_rx\", 0, Subsignal(\"p\", Pins(\"T2\")), Subsignal(\"n\", Pins(\"T1\")), ), (\"sfp_tx_disable_n\",",
"file is part of LiteX-Boards. # # Copyright (c) 2017-2019",
"Subsignal(\"p\", Pins(\"P26\"), IOStandard(\"LVDS_25\")), Subsignal(\"n\", Pins(\"N26\"), IOStandard(\"LVDS_25\")) ), # SI570 (\"si570_refclk\",",
"AE26 AF25 AE21 AM17\"), (\"pmod1\", \"AL14 AM14 AP16 AP15 AM16",
"0, Pins(\"AP8\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 1, Pins(\"H23\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 2, Pins(\"P20\"),",
"AM34 AP31 AM32 AN31 AL34 AN32\"), IOStandard(\"POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"dqs_p\",",
"= \"clk125\" default_clk_period = 1e9/125e6 def __init__(self): XilinxPlatform.__init__(self, \"xcku040-ffva1156-2-e\", _io,",
"(\"serial\", 0, Subsignal(\"cts\", Pins(\"L23\")), Subsignal(\"rts\", Pins(\"K27\")), Subsignal(\"tx\", Pins(\"K26\")), Subsignal(\"rx\", Pins(\"G25\")),",
": \"F6\", \"DP0_C2M_N\" : \"F5\", \"DP0_M2C_P\" : \"E4\", \"DP0_M2C_N\" :",
"), (\"cpu_reset\", 0, Pins(\"AN8\"), IOStandard(\"LVCMOS18\")), # Leds (\"user_led\", 0, Pins(\"AP8\"),",
"\"V21\", \"LA11_N\" : \"W21\", \"LA15_P\" : \"AB25\", \"LA15_N\" : \"AB26\",",
": \"E21\", \"LA28_P\" : \"B21\", \"LA28_N\" : \"B22\", \"LA30_P\" :",
"Subsignal(\"n\", Pins(\"P5\")) ), # SMA (\"user_sma_mgt_refclk\", 0, Subsignal(\"p\", Pins(\"V6\")), Subsignal(\"n\",",
"AL29 AP28 AM29 AN27\", \"AH31 AH32 AJ34 AK31 AJ31 AJ30",
"IOStandard(\"LVDS\")) ), (\"user_sma_gpio_p\", 0, Pins(\"H27\"), IOStandard(\"LVCMOS18\")), (\"user_sma_gpio_n\", 0, Pins(\"G27\"), IOStandard(\"LVCMOS18\")),",
"), # SMA (\"user_sma_mgt_refclk\", 0, Subsignal(\"p\", Pins(\"V6\")), Subsignal(\"n\", Pins(\"V5\")) ),",
"Rotary Encoder (\"rotary\", 0, Subsignal(\"a\", Pins(\"Y21\")), Subsignal(\"b\", Pins(\"AD26\")), Subsignal(\"push\", Pins(\"AF28\")),",
"Pins(\"AE11\")), Subsignal(\"clk\", Pins(\"AF13\")), Subsignal(\"vsync\", Pins(\"AH13\")), Subsignal(\"hsync\", Pins(\"AE13\")), Subsignal(\"spdif\", Pins(\"AE12\")), Subsignal(\"spdif_out\",",
": \"K18\", \"HA08_N\" : \"K17\", \"HA12_P\" : \"K16\", \"HA12_N\" :",
"Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2\")), Subsignal(\"rx_n\", Pins(\"AB1\")), Subsignal(\"tx_p\", Pins(\"AC4\")), Subsignal(\"tx_n\", Pins(\"AC3\"))",
"__init__(self): XilinxPlatform.__init__(self, \"xcku040-ffva1156-2-e\", _io, _connectors, toolchain=\"vivado\") def create_programmer(self): return VivadoProgrammer()",
": \"AC23\", \"LA16_P\" : \"AB21\", \"LA16_N\" : \"AC21\", \"LA20_P\" :",
"(\"user_led\", 2, Pins(\"P20\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 3, Pins(\"P21\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 4,",
"Subsignal(\"tx_n\", Pins(\"AC3 AE3\")) ), (\"pcie_x4\", 0, Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\",",
"0.84 [get_iobanks 44]\") self.add_platform_command(\"set_property INTERNAL_VREF 0.84 [get_iobanks 45]\") self.add_platform_command(\"set_property INTERNAL_VREF",
"\"A19\", \"HA16_N\" : \"A18\", \"HA20_P\" : \"C19\", \"HA20_N\" : \"B19\",",
"A14 Subsignal(\"cs_n\", Pins(\"AL19\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"act_n\", Pins(\"AH14\"), IOStandard(\"SSTL12_DCI\")), #Subsignal(\"ten\", Pins(\"AH16\"), IOStandard(\"SSTL12_DCI\")),",
": \"L12\", \"LA04_N\" : \"K12\", \"LA07_P\" : \"F8\", \"LA07_N\" :",
"\"E4\", \"DP0_M2C_N\" : \"E3\", \"DP1_C2M_P\" : \"D6\", \"DP1_C2M_N\" : \"D5\",",
"Subsignal(\"clk\", Pins(\"AF13\")), Subsignal(\"vsync\", Pins(\"AH13\")), Subsignal(\"hsync\", Pins(\"AE13\")), Subsignal(\"spdif\", Pins(\"AE12\")), Subsignal(\"spdif_out\", Pins(\"AF12\")),",
"Subsignal(\"dq\", Pins(\"AC7 AB7 AA7 Y7\")), IOStandard(\"LVCMOS18\") ), (\"spiflash\", 1, #",
"Subsignal(\"data\", Pins(\"AP9 AN9 AH9 AH8\"), Misc(\"PULLUP True\")), Misc(\"SLEW=FAST\"), IOStandard(\"LVCMOS18\") ),",
"AK26 AK28 AM27 AJ28 AH27 AK27 AM26\", \"AL30 AP29 AM30",
"Pins(\"G10\"), IOStandard(\"LVDS\")), Subsignal(\"n\", Pins(\"F10\"), IOStandard(\"LVDS\")) ), (\"clk300\", 0, Subsignal(\"p\", Pins(\"AK17\"),",
"AH6\")), Subsignal(\"tx_n\", Pins(\"AC3 AE3 AG3 AH5\")) ), (\"pcie_x8\", 0, Subsignal(\"rst_n\",",
": \"G11\", \"LA03_P\" : \"A13\", \"LA03_N\" : \"A12\", \"LA08_P\" :",
"\"F1\", \"LA06_P\" : \"D13\", \"LA06_N\" : \"C13\", \"LA10_P\" : \"L8\",",
"\"F6\", \"DP0_C2M_N\" : \"F5\", \"DP0_M2C_P\" : \"E4\", \"DP0_M2C_N\" : \"E3\",",
"\"LA09_N\" : \"H9\", \"LA13_P\" : \"D9\", \"LA13_N\" : \"C9\", \"LA17_CC_P\"",
"IOStandard(\"LVCMOS18\")), (\"user_led\", 2, Pins(\"P20\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 3, Pins(\"P21\"), IOStandard(\"LVCMOS18\")), (\"user_led\",",
"\"DP5_C2M_P\" : \"J4\", \"DP5_C2M_N\" : \"J3\", \"DP5_M2C_P\" : \"H2\", \"DP5_M2C_N\"",
"\"K6\", \"GBTCLK0_M2C_N\" : \"K5\", \"LA01_CC_P\" : \"G9\", \"LA01_CC_N\" : \"F9\",",
"\"F17\", \"HA13_P\" : \"B14\", \"HA13_N\" : \"A14\", \"HA16_P\" : \"A19\",",
"Pins(\"AE16\"), IOStandard(\"DIFF_SSTL12_DCI\")), Subsignal(\"clk_n\", Pins(\"AE15\"), IOStandard(\"DIFF_SSTL12_DCI\")), Subsignal(\"cke\", Pins(\"AD15\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"odt\", Pins(\"AJ18\"),",
"Pins(\"AB2 AD2\")), Subsignal(\"rx_n\", Pins(\"AB1 AD1\")), Subsignal(\"tx_p\", Pins(\"AC4 AE4\")), Subsignal(\"tx_n\", Pins(\"AC3",
"\"AH31 AH32 AJ34 AK31 AJ31 AJ30 AH34 AK32\", \"AN33 AP33",
"(\"user_btn_e\", 0, Pins(\"AE8\"), IOStandard(\"LVCMOS18\")), # Switches (\"user_dip_btn\", 0, Pins(\"AN16\"), IOStandard(\"LVCMOS12\")),",
": \"AC34\", \"LA22_N\" : \"AD34\", \"LA25_P\" : \"AE33\", \"LA25_N\" :",
"AM15 AN18 AN17\"), ] # Platform ----------------------------------------------------------------------------------------- class Platform(XilinxPlatform): default_clk_name",
"XilinxPlatform.__init__(self, \"xcku040-ffva1156-2-e\", _io, _connectors, toolchain=\"vivado\") def create_programmer(self): return VivadoProgrammer() def",
"Pins(\"AP9 AN9 AH9 AH8\"), Misc(\"PULLUP True\")), Misc(\"SLEW=FAST\"), IOStandard(\"LVCMOS18\") ), #",
"AK22 AL24 AL20 AL23\", \"AM24 AN23 AN24 AP23 AP25 AN22",
"AN13 AN11 AM11 AN12 AM12\", \"AL12 AK12 AL13 AK13 AD11",
"\"LA23_N\" : \"AD31\", \"LA26_P\" : \"AF33\", \"LA26_N\" : \"AG34\", \"CLK0_M2C_P\"",
"\"K18\", \"HA08_N\" : \"K17\", \"HA12_P\" : \"K16\", \"HA12_N\" : \"J16\",",
"Subsignal(\"n\", Pins(\"F10\"), IOStandard(\"LVDS\")) ), (\"clk300\", 0, Subsignal(\"p\", Pins(\"AK17\"), IOStandard(\"DIFF_SSTL12\")), Subsignal(\"n\",",
": \"V21\", \"LA11_N\" : \"W21\", \"LA15_P\" : \"AB25\", \"LA15_N\" :",
"\"AE23 AG20 AF22 AF20 AE22 AD20 AG22 AE20\", \"AJ24 AG24",
"\"LA32_P\" : \"W30\", \"LA32_N\" : \"Y30\", \"LA06_P\" : \"V29\", \"LA06_N\"",
"AL15\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"bg\", Pins(\"AG15\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"ras_n\", Pins(\"AF14\"), IOStandard(\"SSTL12_DCI\")), # A16",
"IOStandard(\"LVCMOS18\")), (\"user_sma_gpio_n\", 0, Pins(\"G27\"), IOStandard(\"LVCMOS18\")), # I2C (\"i2c\", 0, Subsignal(\"scl\",",
"\"LA32_P\" : \"E26\", \"LA32_N\" : \"D26\", \"HA02_P\" : \"H19\", \"HA02_N\"",
"Subsignal(\"a\", Pins( \"AE17 AH17 AE18 AJ15 AG16 AL17 AK18 AG17\",",
"Subsignal(\"spdif_out\", Pins(\"AF12\")), IOStandard(\"LVCMOS18\") ), # DDR4 SDRAM (\"ddram\", 0, Subsignal(\"a\",",
"AG20 AF22 AF20 AE22 AD20 AG22 AE20\", \"AJ24 AG24 AJ23",
": \"A9\", \"LA20_P\" : \"B24\", \"LA20_N\" : \"A24\", \"LA22_P\" :",
"Pins(\"AL18\"), IOStandard(\"LVCMOS12\")), Misc(\"SLEW=FAST\"), ), # PCIe (\"pcie_x1\", 0, Subsignal(\"rst_n\", Pins(\"K22\"),",
"\"LA06_N\" : \"C13\", \"LA10_P\" : \"L8\", \"LA10_N\" : \"K8\", \"LA14_P\"",
"[get_iobanks 44]\") self.add_platform_command(\"set_property INTERNAL_VREF 0.84 [get_iobanks 45]\") self.add_platform_command(\"set_property INTERNAL_VREF 0.84",
"Pins(\"AB1 AD1 AF1 AH1\")), Subsignal(\"tx_p\", Pins(\"AC4 AE4 AG4 AH6\")), Subsignal(\"tx_n\",",
"\"LA10_P\" : \"T22\", \"LA10_N\" : \"T23\", \"LA14_P\" : \"U21\", \"LA14_N\"",
"0, Pins(\"AN8\"), IOStandard(\"LVCMOS18\")), # Leds (\"user_led\", 0, Pins(\"AP8\"), IOStandard(\"LVCMOS18\")), (\"user_led\",",
"\"E23\", \"LA27_P\" : \"H21\", \"LA27_N\" : \"G21\", \"HA01_CC_P\" : \"E16\",",
"self.add_platform_command(\"set_property INTERNAL_VREF 0.84 [get_iobanks 45]\") self.add_platform_command(\"set_property INTERNAL_VREF 0.84 [get_iobanks 46]\")",
"AP20 AL27 AN29 AH33 AN34\"), IOStandard(\"DIFF_POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"dqs_n\", Pins(\"AH21",
"\"LA25_P\" : \"AE33\", \"LA25_N\" : \"AF34\", \"LA29_P\" : \"U34\", \"LA29_N\"",
"\"V33\", \"LA31_N\" : \"W34\", \"LA33_P\" : \"W33\", \"LA33_N\" : \"Y33\",",
"\"LA04_N\" : \"K12\", \"LA07_P\" : \"F8\", \"LA07_N\" : \"E8\", \"LA11_P\"",
"Subsignal(\"cas_n\", Pins(\"AG14\"), IOStandard(\"SSTL12_DCI\")), # A15 Subsignal(\"we_n\", Pins(\"AD16\"), IOStandard(\"SSTL12_DCI\")), # A14",
"\"B15\", \"HA23_N\" : \"A15\", } ), (\"LPC\", { \"GBTCLK0_M2C_P\" :",
"\"DP2_C2M_N\" : \"C3\", \"DP2_M2C_P\" : \"B2\", \"DP2_M2C_N\" : \"B1\", \"DP3_C2M_P\"",
"0, Subsignal(\"txp\", Pins(\"U4\")), Subsignal(\"txn\", Pins(\"U3\")), Subsignal(\"rxp\", Pins(\"T2\")), Subsignal(\"rxn\", Pins(\"T1\")) ),",
"\"F8\", \"LA07_N\" : \"E8\", \"LA11_P\" : \"K11\", \"LA11_N\" : \"J11\",",
"Pins(\"G26\")), Subsignal(\"dq\", Pins(\"M20 L20 R21 R22\")), IOStandard(\"LVCMOS18\") ), # SDCard",
": \"W29\", \"LA10_P\" : \"T22\", \"LA10_N\" : \"T23\", \"LA14_P\" :",
"0, Subsignal(\"clk\", Pins(\"AL10\")), Subsignal(\"cs_n\", Pins(\"AH8\")), Subsignal(\"mosi\", Pins(\"AD9\"), Misc(\"PULLUP\")), Subsignal(\"miso\", Pins(\"AP9\"),",
"AH23 AF24 AH22 AG25\", \"AL22 AL25 AM20 AK23 AK22 AL24",
"\"AC22\", \"LA12_N\" : \"AC23\", \"LA16_P\" : \"AB21\", \"LA16_N\" : \"AC21\",",
"\"LA24_P\" : \"E20\", \"LA24_N\" : \"E21\", \"LA28_P\" : \"B21\", \"LA28_N\"",
"Subsignal(\"p\", Pins(\"P2\")), Subsignal(\"n\", Pins(\"P1\")) ), # SFP (\"sfp\", 0, Subsignal(\"txp\",",
"\"LA10_P\" : \"L8\", \"LA10_N\" : \"K8\", \"LA14_P\" : \"B10\", \"LA14_N\"",
"Pins(\"AD9\"), Misc(\"PULLUP True\")), Subsignal(\"data\", Pins(\"AP9 AN9 AH9 AH8\"), Misc(\"PULLUP True\")),",
": \"L15\", \"HA06_N\" : \"K15\", \"HA10_P\" : \"H17\", \"HA10_N\" :",
"AJ29 AL32\"), IOStandard(\"POD12_DCI\")), Subsignal(\"dq\", Pins( \"AE23 AG20 AF22 AF20 AE22",
": \"F18\", \"HA09_N\" : \"F17\", \"HA13_P\" : \"B14\", \"HA13_N\" :",
"\"J9\", \"LA09_N\" : \"H9\", \"LA13_P\" : \"D9\", \"LA13_N\" : \"C9\",",
"AE3\")) ), (\"pcie_x4\", 0, Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\",",
": \"AA29\", \"LA19_N\" : \"AB29\", \"LA21_P\" : \"AC33\", \"LA21_N\" :",
"\"DP0_M2C_N\" : \"E3\", \"DP1_C2M_P\" : \"D6\", \"DP1_C2M_N\" : \"D5\", \"DP1_M2C_P\"",
"), # SDCard (\"spisdcard\", 0, Subsignal(\"clk\", Pins(\"AL10\")), Subsignal(\"cs_n\", Pins(\"AH8\")), Subsignal(\"mosi\",",
"\"AB25\", \"LA15_N\" : \"AB26\", \"LA19_P\" : \"AA29\", \"LA19_N\" : \"AB29\",",
"AP28 AM29 AN27\", \"AH31 AH32 AJ34 AK31 AJ31 AJ30 AH34",
"Pins(\"V2\")), Subsignal(\"n\", Pins(\"V1\")), ), (\"sfp_tx_disable_n\", 1, Pins(\"D28\"), IOStandard(\"LVCMOS18\")), ] #",
": \"U21\", \"LA14_N\" : \"U22\", \"LA18_CC_P\" : \"AB30\", \"LA18_CC_N\" :",
"\"AB26\", \"LA19_P\" : \"AA29\", \"LA19_N\" : \"AB29\", \"LA21_P\" : \"AC33\",",
"), (\"pcie_x4\", 0, Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")),",
"\"LA03_N\" : \"Y28\", \"LA08_P\" : \"U24\", \"LA08_N\" : \"U25\", \"LA12_P\"",
"\"LA02_P\" : \"AA22\", \"LA02_N\" : \"AB22\", \"LA04_P\" : \"U26\", \"LA04_N\"",
"\"L15\", \"HA06_N\" : \"K15\", \"HA10_P\" : \"H17\", \"HA10_N\" : \"H16\",",
": \"B16\", \"HA22_P\" : \"C18\", \"HA22_N\" : \"C17\", \"GBTCLK1_M2C_P\" :",
"\"DP3_C2M_N\" : \"B5\", \"DP3_M2C_P\" : \"A4\", \"DP3_M2C_N\" : \"A3\", \"DP4_C2M_P\"",
"Misc(\"SLEW=FAST\"), ), # PCIe (\"pcie_x1\", 0, Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\",",
"\"GBTCLK0_M2C_N\" : \"AA25\", \"LA01_CC_P\" : \"W25\", \"LA01_CC_N\" : \"Y25\", \"LA05_P\"",
"\"A25\", \"LA33_P\" : \"A27\", \"LA33_N\" : \"A28\", \"HA03_P\" : \"G15\",",
"\"LA23_P\" : \"AD30\", \"LA23_N\" : \"AD31\", \"LA26_P\" : \"AF33\", \"LA26_N\"",
"1, # clock needs to be accessed through primitive Subsignal(\"cs_n\",",
"\"K2\", \"DP6_M2C_N\" : \"K1\", \"DP7_C2M_P\" : \"G4\", \"DP7_C2M_N\" : \"G3\",",
"\"D26\", \"HA02_P\" : \"H19\", \"HA02_N\" : \"H18\", \"HA06_P\" : \"L15\",",
"Subsignal(\"n\", Pins(\"G27\"), IOStandard(\"LVDS\")) ), (\"user_sma_gpio_p\", 0, Pins(\"H27\"), IOStandard(\"LVCMOS18\")), (\"user_sma_gpio_n\", 0,",
"Pins(\"AG15\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"ras_n\", Pins(\"AF14\"), IOStandard(\"SSTL12_DCI\")), # A16 Subsignal(\"cas_n\", Pins(\"AG14\"), IOStandard(\"SSTL12_DCI\")),",
"Subsignal(\"rxp\", Pins(\"V2\")), Subsignal(\"rxn\", Pins(\"V1\")) ), (\"sfp_tx\", 1, Subsignal(\"p\", Pins(\"W4\")), Subsignal(\"n\",",
"0, Subsignal(\"a\", Pins(\"Y21\")), Subsignal(\"b\", Pins(\"AD26\")), Subsignal(\"push\", Pins(\"AF28\")), IOStandard(\"LVCMOS18\") ), #",
"\"AB34\", \"LA22_P\" : \"AC34\", \"LA22_N\" : \"AD34\", \"LA25_P\" : \"AE33\",",
"# Copyright (c) 2017-2019 <NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause from",
"needs to be accessed through primitive Subsignal(\"cs_n\", Pins(\"U7\")), Subsignal(\"dq\", Pins(\"AC7",
": \"D24\", \"LA17_CC_N\" : \"C24\", \"LA23_P\" : \"G22\", \"LA23_N\" :",
"# # Copyright (c) 2017-2019 <NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause",
"\"LA03_N\" : \"A12\", \"LA08_P\" : \"J8\", \"LA08_N\" : \"H8\", \"LA12_P\"",
": \"F17\", \"HA13_P\" : \"B14\", \"HA13_N\" : \"A14\", \"HA16_P\" :",
"\"U21\", \"LA14_N\" : \"U22\", \"LA18_CC_P\" : \"AB30\", \"LA18_CC_N\" : \"AB31\",",
"# SPIFlash (\"spiflash\", 0, # clock needs to be accessed",
"IOStandard(\"DIFF_POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"dqs_n\", Pins(\"AH21 AJ25 AK20 AP21 AL28 AP30",
"\"E18\", \"HA17_CC_N\" : \"E17\", \"HA21_P\" : \"E15\", \"HA21_N\" : \"D15\",",
"(\"pcie_x4\", 0, Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\",",
"\"DP1_M2C_P\" : \"D2\", \"DP1_M2C_N\" : \"D1\", \"DP2_C2M_P\" : \"C4\", \"DP2_C2M_N\"",
": \"B25\", \"LA31_N\" : \"A25\", \"LA33_P\" : \"A27\", \"LA33_N\" :",
": \"AA32\", \"LA17_CC_N\" : \"AB32\", \"LA23_P\" : \"AD30\", \"LA23_N\" :",
"self.add_platform_command(\"set_property INTERNAL_VREF 0.84 [get_iobanks 44]\") self.add_platform_command(\"set_property INTERNAL_VREF 0.84 [get_iobanks 45]\")",
"Subsignal(\"clk\", Pins(\"AL10\")), Subsignal(\"cs_n\", Pins(\"AH8\")), Subsignal(\"mosi\", Pins(\"AD9\"), Misc(\"PULLUP\")), Subsignal(\"miso\", Pins(\"AP9\"), Misc(\"PULLUP\")),",
"0, Subsignal(\"d\", Pins( \"AK11 AP11 AP13 AN13 AN11 AM11 AN12",
": \"L27\", \"HA00_CC_P\" : \"G17\", \"HA00_CC_N\" : \"G16\", \"HA04_P\" :",
"Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2\")), Subsignal(\"rx_n\",",
"AF1 AH1\")), Subsignal(\"tx_p\", Pins(\"AC4 AE4 AG4 AH6\")), Subsignal(\"tx_n\", Pins(\"AC3 AE3",
"\"AB32\", \"LA23_P\" : \"AD30\", \"LA23_N\" : \"AD31\", \"LA26_P\" : \"AF33\",",
"IOStandard(\"LVCMOS18\") ), # SDCard (\"spisdcard\", 0, Subsignal(\"clk\", Pins(\"AL10\")), Subsignal(\"cs_n\", Pins(\"AH8\")),",
"Subsignal(\"mosi\", Pins(\"AD9\"), Misc(\"PULLUP\")), Subsignal(\"miso\", Pins(\"AP9\"), Misc(\"PULLUP\")), Misc(\"SLEW=FAST\"), IOStandard(\"LVCMOS18\") ), (\"sdcard\",",
"Misc(\"PULLUP\")), Misc(\"SLEW=FAST\"), IOStandard(\"LVCMOS18\") ), (\"sdcard\", 0, Subsignal(\"clk\", Pins(\"AL10\")), Subsignal(\"cmd\", Pins(\"AD9\"),",
"\"B20\", \"LA29_N\" : \"A20\", \"LA31_P\" : \"B25\", \"LA31_N\" : \"A25\",",
": \"H16\", \"HA17_CC_P\" : \"E18\", \"HA17_CC_N\" : \"E17\", \"HA21_P\" :",
"\"A3\", \"DP4_C2M_P\" : \"N4\", \"DP4_C2M_N\" : \"N3\", \"DP4_M2C_P\" : \"M2\",",
"\"DP7_C2M_P\" : \"G4\", \"DP7_C2M_N\" : \"G3\", \"DP7_M2C_P\" : \"F2\", \"DP7_M2C_N\"",
"AH1\")), Subsignal(\"tx_p\", Pins(\"AC4 AE4 AG4 AH6\")), Subsignal(\"tx_n\", Pins(\"AC3 AE3 AG3",
"Subsignal(\"bg\", Pins(\"AG15\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"ras_n\", Pins(\"AF14\"), IOStandard(\"SSTL12_DCI\")), # A16 Subsignal(\"cas_n\", Pins(\"AG14\"),",
"\"E20\", \"LA24_N\" : \"E21\", \"LA28_P\" : \"B21\", \"LA28_N\" : \"B22\",",
"), (\"sdcard\", 0, Subsignal(\"clk\", Pins(\"AL10\")), Subsignal(\"cmd\", Pins(\"AD9\"), Misc(\"PULLUP True\")), Subsignal(\"data\",",
"AG4 AH6 AK6 AL4 AM6 AN4\")), Subsignal(\"tx_n\", Pins(\"AC3 AE3 AG3",
"AP1\")), Subsignal(\"tx_p\", Pins(\"AC4 AE4 AG4 AH6 AK6 AL4 AM6 AN4\")),",
"\"H12\", \"CLK0_M2C_N\" : \"G12\", \"LA02_P\" : \"K10\", \"LA02_N\" : \"J10\",",
"\"LA26_N\" : \"AG34\", \"CLK0_M2C_P\" : \"AA24\", \"CLK0_M2C_N\" : \"AA25\", \"LA02_P\"",
"AH5\")) ), (\"pcie_x8\", 0, Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\",",
"Pins(\"AF8\"), IOStandard(\"LVCMOS18\")), (\"user_btn_w\", 0, Pins(\"AF9\"), IOStandard(\"LVCMOS18\")), (\"user_btn_e\", 0, Pins(\"AE8\"), IOStandard(\"LVCMOS18\")),",
"Pins(\"AC7 AB7 AA7 Y7\")), IOStandard(\"LVCMOS18\") ), (\"spiflash\", 1, # clock",
"Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"dqs_n\", Pins(\"AH21 AJ25 AK20 AP21 AL28 AP30 AJ33",
"\"F22\", \"LA26_P\" : \"G20\", \"LA26_N\" : \"F20\", \"PG_M2C\" : \"L27\",",
"IOStandard(\"DIFF_SSTL12\")) ), (\"cpu_reset\", 0, Pins(\"AN8\"), IOStandard(\"LVCMOS18\")), # Leds (\"user_led\", 0,",
"Subsignal(\"ba\", Pins(\"AF17 AL15\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"bg\", Pins(\"AG15\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"ras_n\", Pins(\"AF14\"), IOStandard(\"SSTL12_DCI\")),",
"\"DP5_M2C_N\" : \"H1\", \"DP6_C2M_P\" : \"L4\", \"DP6_C2M_N\" : \"L3\", \"DP6_M2C_P\"",
"DDR4 SDRAM (\"ddram\", 0, Subsignal(\"a\", Pins( \"AE17 AH17 AE18 AJ15",
"Misc(\"PULLUP True\")), Subsignal(\"data\", Pins(\"AP9 AN9 AH9 AH8\"), Misc(\"PULLUP True\")), Misc(\"SLEW=FAST\"),",
"AP31 AM32 AN31 AL34 AN32\"), IOStandard(\"POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"dqs_p\", Pins(\"AG21",
"AN18 AN17\"), ] # Platform ----------------------------------------------------------------------------------------- class Platform(XilinxPlatform): default_clk_name =",
": \"W21\", \"LA15_P\" : \"AB25\", \"LA15_N\" : \"AB26\", \"LA19_P\" :",
"Pins(\"AE13\")), Subsignal(\"spdif\", Pins(\"AE12\")), Subsignal(\"spdif_out\", Pins(\"AF12\")), IOStandard(\"LVCMOS18\") ), # DDR4 SDRAM",
"Clk / Rst (\"clk125\", 0, Subsignal(\"p\", Pins(\"G10\"), IOStandard(\"LVDS\")), Subsignal(\"n\", Pins(\"F10\"),",
"Pins(\"AD10\"), IOStandard(\"LVCMOS18\")), (\"user_btn_s\", 0, Pins(\"AF8\"), IOStandard(\"LVCMOS18\")), (\"user_btn_w\", 0, Pins(\"AF9\"), IOStandard(\"LVCMOS18\")),",
"AJ4 AK2 AM2 AP2\")), Subsignal(\"rx_n\", Pins(\"AB1 AD1 AF1 AH1 AJ3",
"part of LiteX-Boards. # # Copyright (c) 2017-2019 <NAME> <<EMAIL>>",
"\"LA07_P\" : \"V22\", \"LA07_N\" : \"V23\", \"LA11_P\" : \"V21\", \"LA11_N\"",
": \"AB25\", \"LA15_N\" : \"AB26\", \"LA19_P\" : \"AA29\", \"LA19_N\" :",
"0, Pins(\"AN16\"), IOStandard(\"LVCMOS12\")), (\"user_dip_btn\", 1, Pins(\"AN19\"), IOStandard(\"LVCMOS12\")), (\"user_dip_btn\", 2, Pins(\"AP18\"),",
"IOStandard(\"LVCMOS18\") ), # DDR4 SDRAM (\"ddram\", 0, Subsignal(\"a\", Pins( \"AE17",
"AF2 AH2\")), Subsignal(\"rx_n\", Pins(\"AB1 AD1 AF1 AH1\")), Subsignal(\"tx_p\", Pins(\"AC4 AE4",
"\"AA22\", \"LA02_N\" : \"AB22\", \"LA04_P\" : \"U26\", \"LA04_N\" : \"U27\",",
"7, Pins(\"P23\"), IOStandard(\"LVCMOS18\")), # Buttons (\"user_btn_c\", 0, Pins(\"AE10\"), IOStandard(\"LVCMOS18\")), (\"user_btn_n\",",
"Subsignal(\"clk_p\", Pins(\"AE16\"), IOStandard(\"DIFF_SSTL12_DCI\")), Subsignal(\"clk_n\", Pins(\"AE15\"), IOStandard(\"DIFF_SSTL12_DCI\")), Subsignal(\"cke\", Pins(\"AD15\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"odt\",",
"\"W28\", \"LA03_N\" : \"Y28\", \"LA08_P\" : \"U24\", \"LA08_N\" : \"U25\",",
"(\"sfp_tx_disable_n\", 1, Pins(\"D28\"), IOStandard(\"LVCMOS18\")), ] # Connectors --------------------------------------------------------------------------------------- _connectors =",
"through primitive Subsignal(\"cs_n\", Pins(\"U7\")), Subsignal(\"dq\", Pins(\"AC7 AB7 AA7 Y7\")), IOStandard(\"LVCMOS18\")",
"AE22 AD20 AG22 AE20\", \"AJ24 AG24 AJ23 AF23 AH23 AF24",
"\"HA12_P\" : \"K16\", \"HA12_N\" : \"J16\", \"HA15_P\" : \"D14\", \"HA15_N\"",
"\"LA32_N\" : \"Y30\", \"LA06_P\" : \"V29\", \"LA06_N\" : \"W29\", \"LA10_P\"",
"(\"cpu_reset\", 0, Pins(\"AN8\"), IOStandard(\"LVCMOS18\")), # Leds (\"user_led\", 0, Pins(\"AP8\"), IOStandard(\"LVCMOS18\")),",
"self.add_period_constraint(self.lookup_request(\"clk125\", loose=True), 1e9/125e6) self.add_period_constraint(self.lookup_request(\"clk300\", loose=True), 1e9/300e6) self.add_platform_command(\"set_property INTERNAL_VREF 0.84 [get_iobanks",
"Subsignal(\"p\", Pins(\"U4\")), Subsignal(\"n\", Pins(\"U3\")), ), (\"sfp_rx\", 0, Subsignal(\"p\", Pins(\"T2\")), Subsignal(\"n\",",
"AK5 AL3 AM5 AN3\")) ), # SGMII Clk (\"sgmii_clock\", 0,",
"\"LA27_N\" : \"AG32\", \"CLK1_M2C_P\" : \"AC31\", \"CLK1_M2C_N\" : \"AC32\", \"LA00_CC_P\"",
"AM30 AN28 AL29 AP28 AM29 AN27\", \"AH31 AH32 AJ34 AK31",
"default_clk_period = 1e9/125e6 def __init__(self): XilinxPlatform.__init__(self, \"xcku040-ffva1156-2-e\", _io, _connectors, toolchain=\"vivado\")",
"\"C4\", \"DP2_C2M_N\" : \"C3\", \"DP2_M2C_P\" : \"B2\", \"DP2_M2C_N\" : \"B1\",",
"\"K10\", \"LA02_N\" : \"J10\", \"LA04_P\" : \"L12\", \"LA04_N\" : \"K12\",",
"\"HA02_P\" : \"H19\", \"HA02_N\" : \"H18\", \"HA06_P\" : \"L15\", \"HA06_N\"",
"\"E8\", \"LA11_P\" : \"K11\", \"LA11_N\" : \"J11\", \"LA15_P\" : \"D8\",",
"Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"dqs_p\", Pins(\"AG21 AH24 AJ20 AP20 AL27 AN29 AH33",
"Subsignal(\"scl\", Pins(\"J24\")), Subsignal(\"sda\", Pins(\"J25\")), IOStandard(\"LVCMOS18\") ), # Serial (\"serial\", 0,",
"\"DP7_M2C_N\" : \"F1\", \"LA06_P\" : \"D13\", \"LA06_N\" : \"C13\", \"LA10_P\"",
"\"DP4_C2M_P\" : \"N4\", \"DP4_C2M_N\" : \"N3\", \"DP4_M2C_P\" : \"M2\", \"DP4_M2C_N\"",
"\"LA17_CC_N\" : \"AB32\", \"LA23_P\" : \"AD30\", \"LA23_N\" : \"AD31\", \"LA26_P\"",
"AN29 AH33 AN34\"), IOStandard(\"DIFF_POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"dqs_n\", Pins(\"AH21 AJ25 AK20",
"Subsignal(\"rx_n\", Pins(\"AB1 AD1 AF1 AH1 AJ3 AK1 AM1 AP1\")), Subsignal(\"tx_p\",",
"AF15 AD19 AJ14 AG19\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"ba\", Pins(\"AF17 AL15\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"bg\",",
"\"G9\", \"LA01_CC_N\" : \"F9\", \"LA05_P\" : \"L13\", \"LA05_N\" : \"K13\",",
"1, Pins(\"H23\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 2, Pins(\"P20\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 3, Pins(\"P21\"),",
"0, Pins(\"AD10\"), IOStandard(\"LVCMOS18\")), (\"user_btn_s\", 0, Pins(\"AF8\"), IOStandard(\"LVCMOS18\")), (\"user_btn_w\", 0, Pins(\"AF9\"),",
"\"D1\", \"DP2_C2M_P\" : \"C4\", \"DP2_C2M_N\" : \"C3\", \"DP2_M2C_P\" : \"B2\",",
"AM19 AE26 AF25 AE21 AM17\"), (\"pmod1\", \"AL14 AM14 AP16 AP15",
"\"GBTCLK1_M2C_N\" : \"H5\", \"GBTCLK0_M2C_P\" : \"K6\", \"GBTCLK0_M2C_N\" : \"K5\", \"LA01_CC_P\"",
"\"L19\", \"HA07_N\" : \"L18\", \"HA11_P\" : \"J19\", \"HA11_N\" : \"J18\",",
"\"L27\", \"HA00_CC_P\" : \"G17\", \"HA00_CC_N\" : \"G16\", \"HA04_P\" : \"G19\",",
"\"L13\", \"LA05_N\" : \"K13\", \"LA09_P\" : \"J9\", \"LA09_N\" : \"H9\",",
"\"LA21_P\" : \"F23\", \"LA21_N\" : \"F24\", \"LA24_P\" : \"E20\", \"LA24_N\"",
"), (\"sfp_tx_disable_n\", 1, Pins(\"D28\"), IOStandard(\"LVCMOS18\")), ] # Connectors --------------------------------------------------------------------------------------- _connectors",
"from litex.build.generic_platform import * from litex.build.xilinx import XilinxPlatform, VivadoProgrammer #",
"Subsignal(\"n\", Pins(\"N26\"), IOStandard(\"LVDS_25\")) ), # SI570 (\"si570_refclk\", 0, Subsignal(\"p\", Pins(\"P6\")),",
"AA7 Y7\")), IOStandard(\"LVCMOS18\") ), (\"spiflash\", 1, # clock needs to",
"Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2\")), Subsignal(\"rx_n\", Pins(\"AB1\")), Subsignal(\"tx_p\", Pins(\"AC4\")),",
"AK23 AK22 AL24 AL20 AL23\", \"AM24 AN23 AN24 AP23 AP25",
"Misc(\"SLEW=FAST\"), IOStandard(\"LVCMOS18\") ), (\"sdcard\", 0, Subsignal(\"clk\", Pins(\"AL10\")), Subsignal(\"cmd\", Pins(\"AD9\"), Misc(\"PULLUP",
"IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2 AD2 AF2 AH2\")),",
": \"M2\", \"DP4_M2C_N\" : \"M1\", \"DP5_C2M_P\" : \"J4\", \"DP5_C2M_N\" :",
"\"AA24\", \"CLK0_M2C_N\" : \"AA25\", \"LA02_P\" : \"AA22\", \"LA02_N\" : \"AB22\",",
"\"AJ24 AG24 AJ23 AF23 AH23 AF24 AH22 AG25\", \"AL22 AL25",
"), (\"pcie_x2\", 0, Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")),",
"Pins(\"W3\")), ), (\"sfp_rx\", 1, Subsignal(\"p\", Pins(\"V2\")), Subsignal(\"n\", Pins(\"V1\")), ), (\"sfp_tx_disable_n\",",
"\"HA21_N\" : \"D15\", \"HA23_P\" : \"B15\", \"HA23_N\" : \"A15\", }",
"\"DP1_C2M_P\" : \"D6\", \"DP1_C2M_N\" : \"D5\", \"DP1_M2C_P\" : \"D2\", \"DP1_M2C_N\"",
"AM29 AN27\", \"AH31 AH32 AJ34 AK31 AJ31 AJ30 AH34 AK32\",",
"0, Pins(\"AF9\"), IOStandard(\"LVCMOS18\")), (\"user_btn_e\", 0, Pins(\"AE8\"), IOStandard(\"LVCMOS18\")), # Switches (\"user_dip_btn\",",
"Subsignal(\"n\", Pins(\"V5\")) ), (\"user_sma_mgt_tx\", 0, Subsignal(\"p\", Pins(\"R4\")), Subsignal(\"n\", Pins(\"R3\")) ),",
"Subsignal(\"dq\", Pins(\"M20 L20 R21 R22\")), IOStandard(\"LVCMOS18\") ), # SDCard (\"spisdcard\",",
": \"F2\", \"DP7_M2C_N\" : \"F1\", \"LA06_P\" : \"D13\", \"LA06_N\" :",
"\"LA01_CC_P\" : \"G9\", \"LA01_CC_N\" : \"F9\", \"LA05_P\" : \"L13\", \"LA05_N\"",
"Pins(\"AE12\")), Subsignal(\"spdif_out\", Pins(\"AF12\")), IOStandard(\"LVCMOS18\") ), # DDR4 SDRAM (\"ddram\", 0,",
"AF24 AH22 AG25\", \"AL22 AL25 AM20 AK23 AK22 AL24 AL20",
"IOStandard(\"SSTL12_DCI\")), #Subsignal(\"par\", Pins(\"AD18\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"dm\", Pins(\"AD21 AE25 AJ21 AM21 AH26",
"AH18 AM19 AE26 AF25 AE21 AM17\"), (\"pmod1\", \"AL14 AM14 AP16",
"(\"user_sma_mgt_rx\", 0, Subsignal(\"p\", Pins(\"P2\")), Subsignal(\"n\", Pins(\"P1\")) ), # SFP (\"sfp\",",
"AN34\"), IOStandard(\"DIFF_POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"dqs_n\", Pins(\"AH21 AJ25 AK20 AP21 AL28",
"Subsignal(\"n\", Pins(\"P1\")) ), # SFP (\"sfp\", 0, Subsignal(\"txp\", Pins(\"U4\")), Subsignal(\"txn\",",
"\"LA15_N\" : \"C8\", \"LA19_P\" : \"C21\", \"LA19_N\" : \"C22\", \"LA21_P\"",
"\"LA22_N\" : \"AD34\", \"LA25_P\" : \"AE33\", \"LA25_N\" : \"AF34\", \"LA29_P\"",
"# IOs ---------------------------------------------------------------------------------------------- _io = [ # Clk / Rst",
"# SPDX-License-Identifier: BSD-2-Clause from litex.build.generic_platform import * from litex.build.xilinx import",
": \"G4\", \"DP7_C2M_N\" : \"G3\", \"DP7_M2C_P\" : \"F2\", \"DP7_M2C_N\" :",
"(\"user_btn_c\", 0, Pins(\"AE10\"), IOStandard(\"LVCMOS18\")), (\"user_btn_n\", 0, Pins(\"AD10\"), IOStandard(\"LVCMOS18\")), (\"user_btn_s\", 0,",
"AL23\", \"AM24 AN23 AN24 AP23 AP25 AN22 AP24 AM22\", \"AH28",
"\"HA06_P\" : \"L15\", \"HA06_N\" : \"K15\", \"HA10_P\" : \"H17\", \"HA10_N\"",
"\"A15\", } ), (\"LPC\", { \"GBTCLK0_M2C_P\" : \"AA24\", \"GBTCLK0_M2C_N\" :",
"0, Subsignal(\"clk\", Pins(\"AL10\")), Subsignal(\"cmd\", Pins(\"AD9\"), Misc(\"PULLUP True\")), Subsignal(\"data\", Pins(\"AP9 AN9",
"\"LA15_P\" : \"AB25\", \"LA15_N\" : \"AB26\", \"LA19_P\" : \"AA29\", \"LA19_N\"",
"\"Y25\", \"LA05_P\" : \"V27\", \"LA05_N\" : \"V28\", \"LA09_P\" : \"V26\",",
": \"B6\", \"DP3_C2M_N\" : \"B5\", \"DP3_M2C_P\" : \"A4\", \"DP3_M2C_N\" :",
"\"LA30_P\" : \"C26\", \"LA30_N\" : \"B26\", \"LA32_P\" : \"E26\", \"LA32_N\"",
"Subsignal(\"rxn\", Pins(\"V1\")) ), (\"sfp_tx\", 1, Subsignal(\"p\", Pins(\"W4\")), Subsignal(\"n\", Pins(\"W3\")), ),",
"IOStandard(\"SSTL12_DCI\")), # A15 Subsignal(\"we_n\", Pins(\"AD16\"), IOStandard(\"SSTL12_DCI\")), # A14 Subsignal(\"cs_n\", Pins(\"AL19\"),",
"\"V23\", \"LA11_P\" : \"V21\", \"LA11_N\" : \"W21\", \"LA15_P\" : \"AB25\",",
"# This file is part of LiteX-Boards. # # Copyright",
"\"HA02_N\" : \"H18\", \"HA06_P\" : \"L15\", \"HA06_N\" : \"K15\", \"HA10_P\"",
"Pins(\"AC3 AE3 AG3 AH5 AK5 AL3 AM5 AN3\")) ), #",
"AJ15 AG16 AL17 AK18 AG17\", \"AF18 AH19 AF15 AD19 AJ14",
"\"HA12_N\" : \"J16\", \"HA15_P\" : \"D14\", \"HA15_N\" : \"C14\", \"HA19_P\"",
"AM14 AP16 AP15 AM16 AM15 AN18 AN17\"), ] # Platform",
"AE3 AG3 AH5 AK5 AL3 AM5 AN3\")) ), # SGMII",
"AP29 AM30 AN28 AL29 AP28 AM29 AN27\", \"AH31 AH32 AJ34",
"\"HA21_P\" : \"E15\", \"HA21_N\" : \"D15\", \"HA23_P\" : \"B15\", \"HA23_N\"",
"AL24 AL20 AL23\", \"AM24 AN23 AN24 AP23 AP25 AN22 AP24",
"\"LA16_P\" : \"B9\", \"LA16_N\" : \"A9\", \"LA20_P\" : \"B24\", \"LA20_N\"",
"Platform(XilinxPlatform): default_clk_name = \"clk125\" default_clk_period = 1e9/125e6 def __init__(self): XilinxPlatform.__init__(self,",
"\"LA08_N\" : \"U25\", \"LA12_P\" : \"AC22\", \"LA12_N\" : \"AC23\", \"LA16_P\"",
"IOStandard(\"LVCMOS18\")), (\"user_btn_w\", 0, Pins(\"AF9\"), IOStandard(\"LVCMOS18\")), (\"user_btn_e\", 0, Pins(\"AE8\"), IOStandard(\"LVCMOS18\")), #",
"\"LA31_N\" : \"W34\", \"LA33_P\" : \"W33\", \"LA33_N\" : \"Y33\", }",
"Pins(\"K27\")), Subsignal(\"tx\", Pins(\"K26\")), Subsignal(\"rx\", Pins(\"G25\")), IOStandard(\"LVCMOS18\") ), # SPIFlash (\"spiflash\",",
": \"AF33\", \"LA26_N\" : \"AG34\", \"CLK0_M2C_P\" : \"AA24\", \"CLK0_M2C_N\" :",
"SPIFlash (\"spiflash\", 0, # clock needs to be accessed through",
"IOStandard(\"LVCMOS18\")), (\"user_led\", 6, Pins(\"R23\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 7, Pins(\"P23\"), IOStandard(\"LVCMOS18\")), #",
"AH33 AN34\"), IOStandard(\"DIFF_POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"dqs_n\", Pins(\"AH21 AJ25 AK20 AP21",
"\"LA18_CC_N\" : \"AB31\", \"LA27_P\" : \"AG31\", \"LA27_N\" : \"AG32\", \"CLK1_M2C_P\"",
"Pins(\"V1\")), ), (\"sfp_tx_disable_n\", 1, Pins(\"D28\"), IOStandard(\"LVCMOS18\")), ] # Connectors ---------------------------------------------------------------------------------------",
": \"C18\", \"HA22_N\" : \"C17\", \"GBTCLK1_M2C_P\" : \"H6\", \"GBTCLK1_M2C_N\" :",
"loose=True), 1e9/300e6) self.add_platform_command(\"set_property INTERNAL_VREF 0.84 [get_iobanks 44]\") self.add_platform_command(\"set_property INTERNAL_VREF 0.84",
": \"H18\", \"HA06_P\" : \"L15\", \"HA06_N\" : \"K15\", \"HA10_P\" :",
": \"F22\", \"LA26_P\" : \"G20\", \"LA26_N\" : \"F20\", \"PG_M2C\" :",
": \"V33\", \"LA31_N\" : \"W34\", \"LA33_P\" : \"W33\", \"LA33_N\" :",
": \"H1\", \"DP6_C2M_P\" : \"L4\", \"DP6_C2M_N\" : \"L3\", \"DP6_M2C_P\" :",
"Clk (\"sgmii_clock\", 0, Subsignal(\"p\", Pins(\"P26\"), IOStandard(\"LVDS_25\")), Subsignal(\"n\", Pins(\"N26\"), IOStandard(\"LVDS_25\")) ),",
": \"N4\", \"DP4_C2M_N\" : \"N3\", \"DP4_M2C_P\" : \"M2\", \"DP4_M2C_N\" :",
"), # Rotary Encoder (\"rotary\", 0, Subsignal(\"a\", Pins(\"Y21\")), Subsignal(\"b\", Pins(\"AD26\")),",
"(\"sfp_tx\", 1, Subsignal(\"p\", Pins(\"W4\")), Subsignal(\"n\", Pins(\"W3\")), ), (\"sfp_rx\", 1, Subsignal(\"p\",",
": \"E23\", \"LA27_P\" : \"H21\", \"LA27_N\" : \"G21\", \"HA01_CC_P\" :",
"Subsignal(\"n\", Pins(\"C23\"), IOStandard(\"LVDS\")) ), (\"user_sma_clock_p\", 0, Pins(\"D23\"), IOStandard(\"LVCMOS18\")), (\"user_sma_clock_n\", 0,",
"\"LA27_P\" : \"AG31\", \"LA27_N\" : \"AG32\", \"CLK1_M2C_P\" : \"AC31\", \"CLK1_M2C_N\"",
"(\"clk125\", 0, Subsignal(\"p\", Pins(\"G10\"), IOStandard(\"LVDS\")), Subsignal(\"n\", Pins(\"F10\"), IOStandard(\"LVDS\")) ), (\"clk300\",",
"\"LA26_P\" : \"AF33\", \"LA26_N\" : \"AG34\", \"CLK0_M2C_P\" : \"AA24\", \"CLK0_M2C_N\"",
"\"LA17_CC_P\" : \"AA32\", \"LA17_CC_N\" : \"AB32\", \"LA23_P\" : \"AD30\", \"LA23_N\"",
"] # Connectors --------------------------------------------------------------------------------------- _connectors = [ (\"HPC\", { \"DP0_C2M_P\"",
"\"J15\", \"HA05_N\" : \"J14\", \"HA09_P\" : \"F18\", \"HA09_N\" : \"F17\",",
"AN21 AH18 AM19 AE26 AF25 AE21 AM17\"), (\"pmod1\", \"AL14 AM14",
"\"G3\", \"DP7_M2C_P\" : \"F2\", \"DP7_M2C_N\" : \"F1\", \"LA06_P\" : \"D13\",",
"Pins(\"AJ18\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"reset_n\", Pins(\"AL18\"), IOStandard(\"LVCMOS12\")), Misc(\"SLEW=FAST\"), ), # PCIe (\"pcie_x1\",",
"AG4 AH6\")), Subsignal(\"tx_n\", Pins(\"AC3 AE3 AG3 AH5\")) ), (\"pcie_x8\", 0,",
"(\"sdcard\", 0, Subsignal(\"clk\", Pins(\"AL10\")), Subsignal(\"cmd\", Pins(\"AD9\"), Misc(\"PULLUP True\")), Subsignal(\"data\", Pins(\"AP9",
"\"HA23_N\" : \"A15\", } ), (\"LPC\", { \"GBTCLK0_M2C_P\" : \"AA24\",",
"\"U34\", \"LA29_N\" : \"V34\", \"LA31_P\" : \"V33\", \"LA31_N\" : \"W34\",",
"\"J19\", \"HA11_N\" : \"J18\", \"HA14_P\" : \"F15\", \"HA14_N\" : \"F14\",",
"\"DP5_M2C_P\" : \"H2\", \"DP5_M2C_N\" : \"H1\", \"DP6_C2M_P\" : \"L4\", \"DP6_C2M_N\"",
"AM27 AJ28 AH27 AK27 AM26\", \"AL30 AP29 AM30 AN28 AL29",
"AN4\")), Subsignal(\"tx_n\", Pins(\"AC3 AE3 AG3 AH5 AK5 AL3 AM5 AN3\"))",
"IOStandard(\"LVCMOS18\") ), # SPIFlash (\"spiflash\", 0, # clock needs to",
"# SDCard (\"spisdcard\", 0, Subsignal(\"clk\", Pins(\"AL10\")), Subsignal(\"cs_n\", Pins(\"AH8\")), Subsignal(\"mosi\", Pins(\"AD9\"),",
"IOStandard(\"LVCMOS18\") ), # Rotary Encoder (\"rotary\", 0, Subsignal(\"a\", Pins(\"Y21\")), Subsignal(\"b\",",
"Pins( \"AE17 AH17 AE18 AJ15 AG16 AL17 AK18 AG17\", \"AF18",
"0, Pins(\"H27\"), IOStandard(\"LVCMOS18\")), (\"user_sma_gpio_n\", 0, Pins(\"G27\"), IOStandard(\"LVCMOS18\")), # I2C (\"i2c\",",
"Pins(\"P5\")) ), # SMA (\"user_sma_mgt_refclk\", 0, Subsignal(\"p\", Pins(\"V6\")), Subsignal(\"n\", Pins(\"V5\"))",
"\"LA06_P\" : \"D13\", \"LA06_N\" : \"C13\", \"LA10_P\" : \"L8\", \"LA10_N\"",
"litex.build.xilinx import XilinxPlatform, VivadoProgrammer # IOs ---------------------------------------------------------------------------------------------- _io = [",
"Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2 AD2 AF2 AH2 AJ4",
"\"LA30_N\" : \"Y32\", \"LA32_P\" : \"W30\", \"LA32_N\" : \"Y30\", \"LA06_P\"",
": \"J19\", \"HA11_N\" : \"J18\", \"HA14_P\" : \"F15\", \"HA14_N\" :",
"Subsignal(\"rx_n\", Pins(\"AB1 AD1 AF1 AH1\")), Subsignal(\"tx_p\", Pins(\"AC4 AE4 AG4 AH6\")),",
"(\"user_led\", 0, Pins(\"AP8\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 1, Pins(\"H23\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 2,",
"\"LA23_N\" : \"F22\", \"LA26_P\" : \"G20\", \"LA26_N\" : \"F20\", \"PG_M2C\"",
"AP21 AL28 AP30 AJ33 AP34\"), IOStandard(\"DIFF_POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"clk_p\", Pins(\"AE16\"),",
"), (\"pcie_x8\", 0, Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")),",
"(\"sfp_rx\", 1, Subsignal(\"p\", Pins(\"V2\")), Subsignal(\"n\", Pins(\"V1\")), ), (\"sfp_tx_disable_n\", 1, Pins(\"D28\"),",
"(\"si570_refclk\", 0, Subsignal(\"p\", Pins(\"P6\")), Subsignal(\"n\", Pins(\"P5\")) ), # SMA (\"user_sma_mgt_refclk\",",
"\"L4\", \"DP6_C2M_N\" : \"L3\", \"DP6_M2C_P\" : \"K2\", \"DP6_M2C_N\" : \"K1\",",
": \"H6\", \"GBTCLK1_M2C_N\" : \"H5\", \"GBTCLK0_M2C_P\" : \"K6\", \"GBTCLK0_M2C_N\" :",
"Pins(\"AL19\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"act_n\", Pins(\"AH14\"), IOStandard(\"SSTL12_DCI\")), #Subsignal(\"ten\", Pins(\"AH16\"), IOStandard(\"SSTL12_DCI\")), #Subsignal(\"alert_n\", Pins(\"AJ16\"),",
"\"B2\", \"DP2_M2C_N\" : \"B1\", \"DP3_C2M_P\" : \"B6\", \"DP3_C2M_N\" : \"B5\",",
"IOStandard(\"DIFF_SSTL12_DCI\")), Subsignal(\"cke\", Pins(\"AD15\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"odt\", Pins(\"AJ18\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"reset_n\", Pins(\"AL18\"), IOStandard(\"LVCMOS12\")),",
"IOStandard(\"LVCMOS18\")), (\"user_led\", 5, Pins(\"M22\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 6, Pins(\"R23\"), IOStandard(\"LVCMOS18\")), (\"user_led\",",
"AJ34 AK31 AJ31 AJ30 AH34 AK32\", \"AN33 AP33 AM34 AP31",
"be accessed through primitive Subsignal(\"cs_n\", Pins(\"G26\")), Subsignal(\"dq\", Pins(\"M20 L20 R21",
"Subsignal(\"n\", Pins(\"R3\")) ), (\"user_sma_mgt_rx\", 0, Subsignal(\"p\", Pins(\"P2\")), Subsignal(\"n\", Pins(\"P1\")) ),",
"1e9/125e6 def __init__(self): XilinxPlatform.__init__(self, \"xcku040-ffva1156-2-e\", _io, _connectors, toolchain=\"vivado\") def create_programmer(self):",
"\"F2\", \"DP7_M2C_N\" : \"F1\", \"LA06_P\" : \"D13\", \"LA06_N\" : \"C13\",",
"4, Pins(\"N22\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 5, Pins(\"M22\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 6, Pins(\"R23\"),",
"\"H18\", \"HA06_P\" : \"L15\", \"HA06_N\" : \"K15\", \"HA10_P\" : \"H17\",",
"\"LA28_P\" : \"V31\", \"LA28_N\" : \"W31\", \"LA30_P\" : \"Y31\", \"LA30_N\"",
": \"L18\", \"HA11_P\" : \"J19\", \"HA11_N\" : \"J18\", \"HA14_P\" :",
"\"AC31\", \"CLK1_M2C_N\" : \"AC32\", \"LA00_CC_P\" : \"W23\", \"LA00_CC_N\" : \"W24\",",
"\"LA02_N\" : \"J10\", \"LA04_P\" : \"L12\", \"LA04_N\" : \"K12\", \"LA07_P\"",
"0, Subsignal(\"p\", Pins(\"H27\"), IOStandard(\"LVDS\")), Subsignal(\"n\", Pins(\"G27\"), IOStandard(\"LVDS\")) ), (\"user_sma_gpio_p\", 0,",
"\"HA07_N\" : \"L18\", \"HA11_P\" : \"J19\", \"HA11_N\" : \"J18\", \"HA14_P\"",
"AD2\")), Subsignal(\"rx_n\", Pins(\"AB1 AD1\")), Subsignal(\"tx_p\", Pins(\"AC4 AE4\")), Subsignal(\"tx_n\", Pins(\"AC3 AE3\"))",
"\"LA08_P\" : \"U24\", \"LA08_N\" : \"U25\", \"LA12_P\" : \"AC22\", \"LA12_N\"",
"\"V34\", \"LA31_P\" : \"V33\", \"LA31_N\" : \"W34\", \"LA33_P\" : \"W33\",",
"Pins(\"P21\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 4, Pins(\"N22\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 5, Pins(\"M22\"), IOStandard(\"LVCMOS18\")),",
"\"CLK0_M2C_N\" : \"G12\", \"LA02_P\" : \"K10\", \"LA02_N\" : \"J10\", \"LA04_P\"",
": \"J8\", \"LA08_N\" : \"H8\", \"LA12_P\" : \"E10\", \"LA12_N\" :",
": \"E10\", \"LA12_N\" : \"D10\", \"LA16_P\" : \"B9\", \"LA16_N\" :",
"AF23 AH23 AF24 AH22 AG25\", \"AL22 AL25 AM20 AK23 AK22",
"), (\"sfp_rx\", 0, Subsignal(\"p\", Pins(\"T2\")), Subsignal(\"n\", Pins(\"T1\")), ), (\"sfp_tx_disable_n\", 0,",
"Pins(\"AB1 AD1 AF1 AH1 AJ3 AK1 AM1 AP1\")), Subsignal(\"tx_p\", Pins(\"AC4",
"(\"user_sma_clock\", 0, Subsignal(\"p\", Pins(\"D23\"), IOStandard(\"LVDS\")), Subsignal(\"n\", Pins(\"C23\"), IOStandard(\"LVDS\")) ), (\"user_sma_clock_p\",",
"Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2 AD2 AF2 AH2 AJ4 AK2 AM2 AP2\")),",
"A16 Subsignal(\"cas_n\", Pins(\"AG14\"), IOStandard(\"SSTL12_DCI\")), # A15 Subsignal(\"we_n\", Pins(\"AD16\"), IOStandard(\"SSTL12_DCI\")), #",
"0, # clock needs to be accessed through primitive Subsignal(\"cs_n\",",
"Pins(\"U4\")), Subsignal(\"txn\", Pins(\"U3\")), Subsignal(\"rxp\", Pins(\"T2\")), Subsignal(\"rxn\", Pins(\"T1\")) ), (\"sfp_tx\", 0,",
"0, Subsignal(\"p\", Pins(\"P2\")), Subsignal(\"n\", Pins(\"P1\")) ), # SFP (\"sfp\", 0,",
": \"C19\", \"HA20_N\" : \"B19\", \"CLK1_M2C_P\" : \"E25\", \"CLK1_M2C_N\" :",
"SMA (\"user_sma_mgt_refclk\", 0, Subsignal(\"p\", Pins(\"V6\")), Subsignal(\"n\", Pins(\"V5\")) ), (\"user_sma_mgt_tx\", 0,",
"AD2 AF2 AH2 AJ4 AK2 AM2 AP2\")), Subsignal(\"rx_n\", Pins(\"AB1 AD1",
"IOStandard(\"LVDS\")) ), (\"clk300\", 0, Subsignal(\"p\", Pins(\"AK17\"), IOStandard(\"DIFF_SSTL12\")), Subsignal(\"n\", Pins(\"AK16\"), IOStandard(\"DIFF_SSTL12\"))",
"0, Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\", Pins(\"AB2",
"IOStandard(\"LVCMOS18\")), (\"user_btn_e\", 0, Pins(\"AE8\"), IOStandard(\"LVCMOS18\")), # Switches (\"user_dip_btn\", 0, Pins(\"AN16\"),",
"\"A28\", \"HA03_P\" : \"G15\", \"HA03_N\" : \"G14\", \"HA07_P\" : \"L19\",",
": \"K17\", \"HA12_P\" : \"K16\", \"HA12_N\" : \"J16\", \"HA15_P\" :",
"\"LA24_P\" : \"AE32\", \"LA24_N\" : \"AF32\", \"LA28_P\" : \"V31\", \"LA28_N\"",
"1e9/125e6) self.add_period_constraint(self.lookup_request(\"clk300\", loose=True), 1e9/300e6) self.add_platform_command(\"set_property INTERNAL_VREF 0.84 [get_iobanks 44]\") self.add_platform_command(\"set_property",
"AN32\"), IOStandard(\"POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"dqs_p\", Pins(\"AG21 AH24 AJ20 AP20 AL27",
"\"LA27_N\" : \"G21\", \"HA01_CC_P\" : \"E16\", \"HA01_CC_N\" : \"D16\", \"HA05_P\"",
"Pins(\"Y21\")), Subsignal(\"b\", Pins(\"AD26\")), Subsignal(\"push\", Pins(\"AF28\")), IOStandard(\"LVCMOS18\") ), # HDMI (\"hdmi\",",
": \"V28\", \"LA09_P\" : \"V26\", \"LA09_N\" : \"W26\", \"LA13_P\" :",
"\"LA19_P\" : \"C21\", \"LA19_N\" : \"C22\", \"LA21_P\" : \"F23\", \"LA21_N\"",
": \"A12\", \"LA08_P\" : \"J8\", \"LA08_N\" : \"H8\", \"LA12_P\" :",
"\"C17\", \"GBTCLK1_M2C_P\" : \"H6\", \"GBTCLK1_M2C_N\" : \"H5\", \"GBTCLK0_M2C_P\" : \"K6\",",
"= [ (\"HPC\", { \"DP0_C2M_P\" : \"F6\", \"DP0_C2M_N\" : \"F5\",",
"0, Subsignal(\"p\", Pins(\"P26\"), IOStandard(\"LVDS_25\")), Subsignal(\"n\", Pins(\"N26\"), IOStandard(\"LVDS_25\")) ), # SI570",
": \"K10\", \"LA02_N\" : \"J10\", \"LA04_P\" : \"L12\", \"LA04_N\" :",
"\"H5\", \"GBTCLK0_M2C_P\" : \"K6\", \"GBTCLK0_M2C_N\" : \"K5\", \"LA01_CC_P\" : \"G9\",",
"\"AN33 AP33 AM34 AP31 AM32 AN31 AL34 AN32\"), IOStandard(\"POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"),",
": \"Y28\", \"LA08_P\" : \"U24\", \"LA08_N\" : \"U25\", \"LA12_P\" :",
"), (\"user_sma_mgt_tx\", 0, Subsignal(\"p\", Pins(\"R4\")), Subsignal(\"n\", Pins(\"R3\")) ), (\"user_sma_mgt_rx\", 0,",
": \"D18\", \"PRSNT_M2C_B\" : \"H24\", \"CLK0_M2C_P\" : \"H12\", \"CLK0_M2C_N\" :",
"\"AB31\", \"LA27_P\" : \"AG31\", \"LA27_N\" : \"AG32\", \"CLK1_M2C_P\" : \"AC31\",",
": \"D19\", \"HA19_N\" : \"D18\", \"PRSNT_M2C_B\" : \"H24\", \"CLK0_M2C_P\" :",
"\"LA07_P\" : \"F8\", \"LA07_N\" : \"E8\", \"LA11_P\" : \"K11\", \"LA11_N\"",
": \"AD34\", \"LA25_P\" : \"AE33\", \"LA25_N\" : \"AF34\", \"LA29_P\" :",
"AM5 AN3\")) ), # SGMII Clk (\"sgmii_clock\", 0, Subsignal(\"p\", Pins(\"P26\"),",
"\"J8\", \"LA08_N\" : \"H8\", \"LA12_P\" : \"E10\", \"LA12_N\" : \"D10\",",
"import * from litex.build.xilinx import XilinxPlatform, VivadoProgrammer # IOs ----------------------------------------------------------------------------------------------",
"\"J14\", \"HA09_P\" : \"F18\", \"HA09_N\" : \"F17\", \"HA13_P\" : \"B14\",",
"\"G22\", \"LA23_N\" : \"F22\", \"LA26_P\" : \"G20\", \"LA26_N\" : \"F20\",",
"IOStandard(\"LVCMOS18\") ), (\"spiflash\", 1, # clock needs to be accessed",
"Subsignal(\"p\", Pins(\"R4\")), Subsignal(\"n\", Pins(\"R3\")) ), (\"user_sma_mgt_rx\", 0, Subsignal(\"p\", Pins(\"P2\")), Subsignal(\"n\",",
"\"F5\", \"DP0_M2C_P\" : \"E4\", \"DP0_M2C_N\" : \"E3\", \"DP1_C2M_P\" : \"D6\",",
"\"LA04_P\" : \"L12\", \"LA04_N\" : \"K12\", \"LA07_P\" : \"F8\", \"LA07_N\"",
"\"B6\", \"DP3_C2M_N\" : \"B5\", \"DP3_M2C_P\" : \"A4\", \"DP3_M2C_N\" : \"A3\",",
"Subsignal(\"clk_n\", Pins(\"AE15\"), IOStandard(\"DIFF_SSTL12_DCI\")), Subsignal(\"cke\", Pins(\"AD15\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"odt\", Pins(\"AJ18\"), IOStandard(\"SSTL12_DCI\")), Subsignal(\"reset_n\",",
"\"Y30\", \"LA06_P\" : \"V29\", \"LA06_N\" : \"W29\", \"LA10_P\" : \"T22\",",
"primitive Subsignal(\"cs_n\", Pins(\"G26\")), Subsignal(\"dq\", Pins(\"M20 L20 R21 R22\")), IOStandard(\"LVCMOS18\") ),",
"AD1\")), Subsignal(\"tx_p\", Pins(\"AC4 AE4\")), Subsignal(\"tx_n\", Pins(\"AC3 AE3\")) ), (\"pcie_x4\", 0,",
"Subsignal(\"p\", Pins(\"W4\")), Subsignal(\"n\", Pins(\"W3\")), ), (\"sfp_rx\", 1, Subsignal(\"p\", Pins(\"V2\")), Subsignal(\"n\",",
"\"E10\", \"LA12_N\" : \"D10\", \"LA16_P\" : \"B9\", \"LA16_N\" : \"A9\",",
": \"K11\", \"LA11_N\" : \"J11\", \"LA15_P\" : \"D8\", \"LA15_N\" :",
"Subsignal(\"rts\", Pins(\"K27\")), Subsignal(\"tx\", Pins(\"K26\")), Subsignal(\"rx\", Pins(\"G25\")), IOStandard(\"LVCMOS18\") ), # SPIFlash",
": \"E20\", \"LA24_N\" : \"E21\", \"LA28_P\" : \"B21\", \"LA28_N\" :",
"AJ33 AP34\"), IOStandard(\"DIFF_POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")), Subsignal(\"clk_p\", Pins(\"AE16\"), IOStandard(\"DIFF_SSTL12_DCI\")), Subsignal(\"clk_n\", Pins(\"AE15\"),",
"\"HA03_P\" : \"G15\", \"HA03_N\" : \"G14\", \"HA07_P\" : \"L19\", \"HA07_N\"",
": \"H19\", \"HA02_N\" : \"H18\", \"HA06_P\" : \"L15\", \"HA06_N\" :",
"), # Serial (\"serial\", 0, Subsignal(\"cts\", Pins(\"L23\")), Subsignal(\"rts\", Pins(\"K27\")), Subsignal(\"tx\",",
"1, Subsignal(\"p\", Pins(\"W4\")), Subsignal(\"n\", Pins(\"W3\")), ), (\"sfp_rx\", 1, Subsignal(\"p\", Pins(\"V2\")),",
"Pins(\"AD26\")), Subsignal(\"push\", Pins(\"AF28\")), IOStandard(\"LVCMOS18\") ), # HDMI (\"hdmi\", 0, Subsignal(\"d\",",
"\"W25\", \"LA01_CC_N\" : \"Y25\", \"LA05_P\" : \"V27\", \"LA05_N\" : \"V28\",",
": \"B26\", \"LA32_P\" : \"E26\", \"LA32_N\" : \"D26\", \"HA02_P\" :",
"\"AF32\", \"LA28_P\" : \"V31\", \"LA28_N\" : \"W31\", \"LA30_P\" : \"Y31\",",
"0, Pins(\"D23\"), IOStandard(\"LVCMOS18\")), (\"user_sma_clock_n\", 0, Pins(\"C23\"), IOStandard(\"LVCMOS18\")), (\"user_sma_gpio\", 0, Subsignal(\"p\",",
"Subsignal(\"push\", Pins(\"AF28\")), IOStandard(\"LVCMOS18\") ), # HDMI (\"hdmi\", 0, Subsignal(\"d\", Pins(",
"_connectors = [ (\"HPC\", { \"DP0_C2M_P\" : \"F6\", \"DP0_C2M_N\" :",
"\"AG34\", \"CLK0_M2C_P\" : \"AA24\", \"CLK0_M2C_N\" : \"AA25\", \"LA02_P\" : \"AA22\",",
"Subsignal(\"tx\", Pins(\"K26\")), Subsignal(\"rx\", Pins(\"G25\")), IOStandard(\"LVCMOS18\") ), # SPIFlash (\"spiflash\", 0,",
"Subsignal(\"spdif\", Pins(\"AE12\")), Subsignal(\"spdif_out\", Pins(\"AF12\")), IOStandard(\"LVCMOS18\") ), # DDR4 SDRAM (\"ddram\",",
"do_finalize(self, fragment): XilinxPlatform.do_finalize(self, fragment) self.add_period_constraint(self.lookup_request(\"clk125\", loose=True), 1e9/125e6) self.add_period_constraint(self.lookup_request(\"clk300\", loose=True), 1e9/300e6)",
": \"AA34\", \"LA20_N\" : \"AB34\", \"LA22_P\" : \"AC34\", \"LA22_N\" :",
"\"LA12_N\" : \"D10\", \"LA16_P\" : \"B9\", \"LA16_N\" : \"A9\", \"LA20_P\"",
"IOStandard(\"LVCMOS18\")), (\"user_sma_gpio\", 0, Subsignal(\"p\", Pins(\"H27\"), IOStandard(\"LVDS\")), Subsignal(\"n\", Pins(\"G27\"), IOStandard(\"LVDS\")) ),",
"AK32\", \"AN33 AP33 AM34 AP31 AM32 AN31 AL34 AN32\"), IOStandard(\"POD12_DCI\"),",
"Connectors --------------------------------------------------------------------------------------- _connectors = [ (\"HPC\", { \"DP0_C2M_P\" : \"F6\",",
"Pins(\"AC4 AE4 AG4 AH6 AK6 AL4 AM6 AN4\")), Subsignal(\"tx_n\", Pins(\"AC3",
": \"B20\", \"LA29_N\" : \"A20\", \"LA31_P\" : \"B25\", \"LA31_N\" :",
"Pins(\"AP18\"), IOStandard(\"LVCMOS12\")), (\"user_dip_btn\", 3, Pins(\"AN14\"), IOStandard(\"LVCMOS12\")), # SMA (\"user_sma_clock\", 0,",
"AH24 AJ20 AP20 AL27 AN29 AH33 AN34\"), IOStandard(\"DIFF_POD12_DCI\"), Misc(\"PRE_EMPHASIS=RDRV_240\"), Misc(\"EQUALIZATION=EQ_LEVEL2\")),",
"\"W30\", \"LA32_N\" : \"Y30\", \"LA06_P\" : \"V29\", \"LA06_N\" : \"W29\",",
"\"B9\", \"LA16_N\" : \"A9\", \"LA20_P\" : \"B24\", \"LA20_N\" : \"A24\",",
"\"B24\", \"LA20_N\" : \"A24\", \"LA22_P\" : \"G24\", \"LA22_N\" : \"F25\",",
": \"A14\", \"HA16_P\" : \"A19\", \"HA16_N\" : \"A18\", \"HA20_P\" :",
": \"H24\", \"CLK0_M2C_P\" : \"H12\", \"CLK0_M2C_N\" : \"G12\", \"LA02_P\" :",
"IOStandard(\"POD12_DCI\")), Subsignal(\"dq\", Pins( \"AE23 AG20 AF22 AF20 AE22 AD20 AG22",
"\"DP6_M2C_P\" : \"K2\", \"DP6_M2C_N\" : \"K1\", \"DP7_C2M_P\" : \"G4\", \"DP7_C2M_N\"",
"44]\") self.add_platform_command(\"set_property INTERNAL_VREF 0.84 [get_iobanks 45]\") self.add_platform_command(\"set_property INTERNAL_VREF 0.84 [get_iobanks",
"AM22\", \"AH28 AK26 AK28 AM27 AJ28 AH27 AK27 AM26\", \"AL30",
"\"C19\", \"HA20_N\" : \"B19\", \"CLK1_M2C_P\" : \"E25\", \"CLK1_M2C_N\" : \"D25\",",
"\"LA02_N\" : \"AB22\", \"LA04_P\" : \"U26\", \"LA04_N\" : \"U27\", \"LA07_P\"",
"Pins(\"G25\")), IOStandard(\"LVCMOS18\") ), # SPIFlash (\"spiflash\", 0, # clock needs",
"\"D2\", \"DP1_M2C_N\" : \"D1\", \"DP2_C2M_P\" : \"C4\", \"DP2_C2M_N\" : \"C3\",",
"5, Pins(\"M22\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 6, Pins(\"R23\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 7, Pins(\"P23\"),",
"\"E15\", \"HA21_N\" : \"D15\", \"HA23_P\" : \"B15\", \"HA23_N\" : \"A15\",",
"Pins(\"M22\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 6, Pins(\"R23\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 7, Pins(\"P23\"), IOStandard(\"LVCMOS18\")),",
": \"D21\", \"LA29_P\" : \"B20\", \"LA29_N\" : \"A20\", \"LA31_P\" :",
"\"C14\", \"HA19_P\" : \"D19\", \"HA19_N\" : \"D18\", \"PRSNT_M2C_B\" : \"H24\",",
": \"C3\", \"DP2_M2C_P\" : \"B2\", \"DP2_M2C_N\" : \"B1\", \"DP3_C2M_P\" :",
"Pins(\"D23\"), IOStandard(\"LVCMOS18\")), (\"user_sma_clock_n\", 0, Pins(\"C23\"), IOStandard(\"LVCMOS18\")), (\"user_sma_gpio\", 0, Subsignal(\"p\", Pins(\"H27\"),",
"\"D20\", \"LA25_N\" : \"D21\", \"LA29_P\" : \"B20\", \"LA29_N\" : \"A20\",",
"\"L12\", \"LA04_N\" : \"K12\", \"LA07_P\" : \"F8\", \"LA07_N\" : \"E8\",",
"(\"pcie_x2\", 0, Subsignal(\"rst_n\", Pins(\"K22\"), IOStandard(\"LVCMOS18\")), Subsignal(\"clk_p\", Pins(\"AB6\")), Subsignal(\"clk_n\", Pins(\"AB5\")), Subsignal(\"rx_p\",",
": \"K12\", \"LA07_P\" : \"F8\", \"LA07_N\" : \"E8\", \"LA11_P\" :",
"AL4 AM6 AN4\")), Subsignal(\"tx_n\", Pins(\"AC3 AE3 AG3 AH5 AK5 AL3",
"(\"user_led\", 3, Pins(\"P21\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 4, Pins(\"N22\"), IOStandard(\"LVCMOS18\")), (\"user_led\", 5,",
"\"LA23_P\" : \"G22\", \"LA23_N\" : \"F22\", \"LA26_P\" : \"G20\", \"LA26_N\"",
"\"HA16_P\" : \"A19\", \"HA16_N\" : \"A18\", \"HA20_P\" : \"C19\", \"HA20_N\"",
"AH17 AE18 AJ15 AG16 AL17 AK18 AG17\", \"AF18 AH19 AF15",
"R21 R22\")), IOStandard(\"LVCMOS18\") ), # SDCard (\"spisdcard\", 0, Subsignal(\"clk\", Pins(\"AL10\")),",
"), (\"sfp_tx\", 1, Subsignal(\"p\", Pins(\"W4\")), Subsignal(\"n\", Pins(\"W3\")), ), (\"sfp_rx\", 1,",
"\"F15\", \"HA14_N\" : \"F14\", \"HA18_P\" : \"B17\", \"HA18_N\" : \"B16\",",
"\"C13\", \"LA10_P\" : \"L8\", \"LA10_N\" : \"K8\", \"LA14_P\" : \"B10\",",
"\"DP7_C2M_N\" : \"G3\", \"DP7_M2C_P\" : \"F2\", \"DP7_M2C_N\" : \"F1\", \"LA06_P\"",
"\"DP6_C2M_N\" : \"L3\", \"DP6_M2C_P\" : \"K2\", \"DP6_M2C_N\" : \"K1\", \"DP7_C2M_P\"",
"\"AB22\", \"LA04_P\" : \"U26\", \"LA04_N\" : \"U27\", \"LA07_P\" : \"V22\",",
": \"T23\", \"LA14_P\" : \"U21\", \"LA14_N\" : \"U22\", \"LA18_CC_P\" :",
"\"U25\", \"LA12_P\" : \"AC22\", \"LA12_N\" : \"AC23\", \"LA16_P\" : \"AB21\",",
"(\"user_sma_clock_p\", 0, Pins(\"D23\"), IOStandard(\"LVCMOS18\")), (\"user_sma_clock_n\", 0, Pins(\"C23\"), IOStandard(\"LVCMOS18\")), (\"user_sma_gpio\", 0,",
"\"AB30\", \"LA18_CC_N\" : \"AB31\", \"LA27_P\" : \"AG31\", \"LA27_N\" : \"AG32\",",
"AH12 AG12 AJ11\", \"AG10 AK8\")), Subsignal(\"de\", Pins(\"AE11\")), Subsignal(\"clk\", Pins(\"AF13\")), Subsignal(\"vsync\",",
"0, Subsignal(\"p\", Pins(\"G10\"), IOStandard(\"LVDS\")), Subsignal(\"n\", Pins(\"F10\"), IOStandard(\"LVDS\")) ), (\"clk300\", 0,",
"AP23 AP25 AN22 AP24 AM22\", \"AH28 AK26 AK28 AM27 AJ28",
"\"AA32\", \"LA17_CC_N\" : \"AB32\", \"LA23_P\" : \"AD30\", \"LA23_N\" : \"AD31\",",
"\"G12\", \"LA02_P\" : \"K10\", \"LA02_N\" : \"J10\", \"LA04_P\" : \"L12\",",
"\"LA33_N\" : \"A28\", \"HA03_P\" : \"G15\", \"HA03_N\" : \"G14\", \"HA07_P\"",
": \"W25\", \"LA01_CC_N\" : \"Y25\", \"LA05_P\" : \"V27\", \"LA05_N\" :",
"\"N4\", \"DP4_C2M_N\" : \"N3\", \"DP4_M2C_P\" : \"M2\", \"DP4_M2C_N\" : \"M1\",",
"Subsignal(\"b\", Pins(\"AD26\")), Subsignal(\"push\", Pins(\"AF28\")), IOStandard(\"LVCMOS18\") ), # HDMI (\"hdmi\", 0,",
": \"A13\", \"LA03_N\" : \"A12\", \"LA08_P\" : \"J8\", \"LA08_N\" :",
"AF20 AE22 AD20 AG22 AE20\", \"AJ24 AG24 AJ23 AF23 AH23",
"\"T22\", \"LA10_N\" : \"T23\", \"LA14_P\" : \"U21\", \"LA14_N\" : \"U22\","
] |
[
"holding[holding == '#'] = 1 holding = holding.astype(int) print (holding)",
"results = np.array([down1_right3, down1_right1, down1_right5, down1_right7, down2_right1], dtype=np.int64) print(results) product",
"down = np.arange(0,(needed_slope_elements)*downstep,downstep).astype(int) moves = [] for ii in range(len(right)):",
"rightstep).astype(int) down = np.arange(0,(needed_slope_elements)*downstep,downstep).astype(int) moves = [] for ii in",
"down1_right3 = dup_and_count(3,1,holding) down1_right1 = dup_and_count(1,1,holding) down1_right5 = dup_and_count(5,1,holding) down1_right7",
"math # In[2]: fileObj = open('../data/advent_of_code_input_day_three.txt', \"r\") #opens the file",
"= np.arange(0,(needed_slope_elements)*downstep,downstep).astype(int) moves = [] for ii in range(len(right)): moves.append(duplicated[down[ii],",
"(items) def split(line): return list(line) holding = [] for i,",
"= dup_and_count(7,1,holding) down2_right1 = dup_and_count(1,2,holding) results = np.array([down1_right3, down1_right1, down1_right5,",
"file into an array. # In[3]: #print (items) def split(line):",
"dup_and_count(5,1,holding) down1_right7 = dup_and_count(7,1,holding) down2_right1 = dup_and_count(1,2,holding) results = np.array([down1_right3,",
"dup_and_count(7,1,holding) down2_right1 = dup_and_count(1,2,holding) results = np.array([down1_right3, down1_right1, down1_right5, down1_right7,",
"np import math # In[2]: fileObj = open('../data/advent_of_code_input_day_three.txt', \"r\") #opens",
"# In[1]: import numpy as np import math # In[2]:",
"<gh_stars>0 #!/usr/bin/env python # coding: utf-8 # In[1]: import numpy",
"coding: utf-8 # In[1]: import numpy as np import math",
"result = split(line) holding.append(result) holding = np.array(holding) holding[holding == '.']",
"= math.floor(basedata.shape[0]/downstep) replications_needed = (needed_slope_elements* rightstep)/basedata.shape[1] duplicated = np.tile(basedata, math.ceil(replications_needed))",
"needed_slope_elements = math.floor(basedata.shape[0]/downstep) replications_needed = (needed_slope_elements* rightstep)/basedata.shape[1] duplicated = np.tile(basedata,",
"holding = np.array(holding) holding[holding == '.'] = 0 holding[holding ==",
"0 holding[holding == '#'] = 1 holding = holding.astype(int) print",
"print (holding) # In[7]: def dup_and_count(rightstep, downstep, basedata): needed_slope_elements =",
"python # coding: utf-8 # In[1]: import numpy as np",
"def split(line): return list(line) holding = [] for i, line",
"down2_right1 = dup_and_count(1,2,holding) results = np.array([down1_right3, down1_right1, down1_right5, down1_right7, down2_right1],",
"right = np.arange(0,(needed_slope_elements)*rightstep, rightstep).astype(int) down = np.arange(0,(needed_slope_elements)*downstep,downstep).astype(int) moves = []",
"(needed_slope_elements* rightstep)/basedata.shape[1] duplicated = np.tile(basedata, math.ceil(replications_needed)) right = np.arange(0,(needed_slope_elements)*rightstep, rightstep).astype(int)",
"In[3]: #print (items) def split(line): return list(line) holding = []",
"import numpy as np import math # In[2]: fileObj =",
"down1_right1 = dup_and_count(1,1,holding) down1_right5 = dup_and_count(5,1,holding) down1_right7 = dup_and_count(7,1,holding) down2_right1",
"the file into an array. # In[3]: #print (items) def",
"hits down1_right3 = dup_and_count(3,1,holding) down1_right1 = dup_and_count(1,1,holding) down1_right5 = dup_and_count(5,1,holding)",
"splitlines() #puts the file into an array. # In[3]: #print",
"#print (items) def split(line): return list(line) holding = [] for",
"in enumerate(items): result = split(line) holding.append(result) holding = np.array(holding) holding[holding",
"In[2]: fileObj = open('../data/advent_of_code_input_day_three.txt', \"r\") #opens the file in read",
"= (needed_slope_elements* rightstep)/basedata.shape[1] duplicated = np.tile(basedata, math.ceil(replications_needed)) right = np.arange(0,(needed_slope_elements)*rightstep,",
"math.ceil(replications_needed)) right = np.arange(0,(needed_slope_elements)*rightstep, rightstep).astype(int) down = np.arange(0,(needed_slope_elements)*downstep,downstep).astype(int) moves =",
"open('../data/advent_of_code_input_day_three.txt', \"r\") #opens the file in read mode. items =",
"holding[holding == '.'] = 0 holding[holding == '#'] = 1",
"split(line): return list(line) holding = [] for i, line in",
"holding = [] for i, line in enumerate(items): result =",
"In[1]: import numpy as np import math # In[2]: fileObj",
"dup_and_count(3,1,holding) down1_right1 = dup_and_count(1,1,holding) down1_right5 = dup_and_count(5,1,holding) down1_right7 = dup_and_count(7,1,holding)",
"def dup_and_count(rightstep, downstep, basedata): needed_slope_elements = math.floor(basedata.shape[0]/downstep) replications_needed = (needed_slope_elements*",
"= split(line) holding.append(result) holding = np.array(holding) holding[holding == '.'] =",
"items = fileObj. read(). splitlines() #puts the file into an",
"= [] for ii in range(len(right)): moves.append(duplicated[down[ii], right[ii]]) hits =",
"np.sum(moves) return hits down1_right3 = dup_and_count(3,1,holding) down1_right1 = dup_and_count(1,1,holding) down1_right5",
"'.'] = 0 holding[holding == '#'] = 1 holding =",
"holding = holding.astype(int) print (holding) # In[7]: def dup_and_count(rightstep, downstep,",
"# coding: utf-8 # In[1]: import numpy as np import",
"the file in read mode. items = fileObj. read(). splitlines()",
"range(len(right)): moves.append(duplicated[down[ii], right[ii]]) hits = np.sum(moves) return hits down1_right3 =",
"in range(len(right)): moves.append(duplicated[down[ii], right[ii]]) hits = np.sum(moves) return hits down1_right3",
"#opens the file in read mode. items = fileObj. read().",
"numpy as np import math # In[2]: fileObj = open('../data/advent_of_code_input_day_three.txt',",
"i, line in enumerate(items): result = split(line) holding.append(result) holding =",
"hits = np.sum(moves) return hits down1_right3 = dup_and_count(3,1,holding) down1_right1 =",
"= dup_and_count(3,1,holding) down1_right1 = dup_and_count(1,1,holding) down1_right5 = dup_and_count(5,1,holding) down1_right7 =",
"= fileObj. read(). splitlines() #puts the file into an array.",
"into an array. # In[3]: #print (items) def split(line): return",
"dup_and_count(1,2,holding) results = np.array([down1_right3, down1_right1, down1_right5, down1_right7, down2_right1], dtype=np.int64) print(results)",
"down1_right5 = dup_and_count(5,1,holding) down1_right7 = dup_and_count(7,1,holding) down2_right1 = dup_and_count(1,2,holding) results",
"# In[3]: #print (items) def split(line): return list(line) holding =",
"dup_and_count(rightstep, downstep, basedata): needed_slope_elements = math.floor(basedata.shape[0]/downstep) replications_needed = (needed_slope_elements* rightstep)/basedata.shape[1]",
"#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as",
"basedata): needed_slope_elements = math.floor(basedata.shape[0]/downstep) replications_needed = (needed_slope_elements* rightstep)/basedata.shape[1] duplicated =",
"= np.sum(moves) return hits down1_right3 = dup_and_count(3,1,holding) down1_right1 = dup_and_count(1,1,holding)",
"np.arange(0,(needed_slope_elements)*rightstep, rightstep).astype(int) down = np.arange(0,(needed_slope_elements)*downstep,downstep).astype(int) moves = [] for ii",
"'#'] = 1 holding = holding.astype(int) print (holding) # In[7]:",
"replications_needed = (needed_slope_elements* rightstep)/basedata.shape[1] duplicated = np.tile(basedata, math.ceil(replications_needed)) right =",
"import math # In[2]: fileObj = open('../data/advent_of_code_input_day_three.txt', \"r\") #opens the",
"return list(line) holding = [] for i, line in enumerate(items):",
"[] for ii in range(len(right)): moves.append(duplicated[down[ii], right[ii]]) hits = np.sum(moves)",
"enumerate(items): result = split(line) holding.append(result) holding = np.array(holding) holding[holding ==",
"list(line) holding = [] for i, line in enumerate(items): result",
"#puts the file into an array. # In[3]: #print (items)",
"down1_right7 = dup_and_count(7,1,holding) down2_right1 = dup_and_count(1,2,holding) results = np.array([down1_right3, down1_right1,",
"np.arange(0,(needed_slope_elements)*downstep,downstep).astype(int) moves = [] for ii in range(len(right)): moves.append(duplicated[down[ii], right[ii]])",
"right[ii]]) hits = np.sum(moves) return hits down1_right3 = dup_and_count(3,1,holding) down1_right1",
"duplicated = np.tile(basedata, math.ceil(replications_needed)) right = np.arange(0,(needed_slope_elements)*rightstep, rightstep).astype(int) down =",
"= 1 holding = holding.astype(int) print (holding) # In[7]: def",
"mode. items = fileObj. read(). splitlines() #puts the file into",
"= np.array([down1_right3, down1_right1, down1_right5, down1_right7, down2_right1], dtype=np.int64) print(results) product =",
"math.floor(basedata.shape[0]/downstep) replications_needed = (needed_slope_elements* rightstep)/basedata.shape[1] duplicated = np.tile(basedata, math.ceil(replications_needed)) right",
"# In[7]: def dup_and_count(rightstep, downstep, basedata): needed_slope_elements = math.floor(basedata.shape[0]/downstep) replications_needed",
"= np.tile(basedata, math.ceil(replications_needed)) right = np.arange(0,(needed_slope_elements)*rightstep, rightstep).astype(int) down = np.arange(0,(needed_slope_elements)*downstep,downstep).astype(int)",
"as np import math # In[2]: fileObj = open('../data/advent_of_code_input_day_three.txt', \"r\")",
"moves.append(duplicated[down[ii], right[ii]]) hits = np.sum(moves) return hits down1_right3 = dup_and_count(3,1,holding)",
"rightstep)/basedata.shape[1] duplicated = np.tile(basedata, math.ceil(replications_needed)) right = np.arange(0,(needed_slope_elements)*rightstep, rightstep).astype(int) down",
"dtype=np.int64) print(results) product = np.prod(results) print (product) # In[ ]:",
"np.tile(basedata, math.ceil(replications_needed)) right = np.arange(0,(needed_slope_elements)*rightstep, rightstep).astype(int) down = np.arange(0,(needed_slope_elements)*downstep,downstep).astype(int) moves",
"== '#'] = 1 holding = holding.astype(int) print (holding) #",
"== '.'] = 0 holding[holding == '#'] = 1 holding",
"moves = [] for ii in range(len(right)): moves.append(duplicated[down[ii], right[ii]]) hits",
"down1_right5, down1_right7, down2_right1], dtype=np.int64) print(results) product = np.prod(results) print (product)",
"holding.append(result) holding = np.array(holding) holding[holding == '.'] = 0 holding[holding",
"dup_and_count(1,1,holding) down1_right5 = dup_and_count(5,1,holding) down1_right7 = dup_and_count(7,1,holding) down2_right1 = dup_and_count(1,2,holding)",
"= holding.astype(int) print (holding) # In[7]: def dup_and_count(rightstep, downstep, basedata):",
"= np.arange(0,(needed_slope_elements)*rightstep, rightstep).astype(int) down = np.arange(0,(needed_slope_elements)*downstep,downstep).astype(int) moves = [] for",
"file in read mode. items = fileObj. read(). splitlines() #puts",
"In[7]: def dup_and_count(rightstep, downstep, basedata): needed_slope_elements = math.floor(basedata.shape[0]/downstep) replications_needed =",
"read(). splitlines() #puts the file into an array. # In[3]:",
"= open('../data/advent_of_code_input_day_three.txt', \"r\") #opens the file in read mode. items",
"split(line) holding.append(result) holding = np.array(holding) holding[holding == '.'] = 0",
"return hits down1_right3 = dup_and_count(3,1,holding) down1_right1 = dup_and_count(1,1,holding) down1_right5 =",
"= [] for i, line in enumerate(items): result = split(line)",
"(holding) # In[7]: def dup_and_count(rightstep, downstep, basedata): needed_slope_elements = math.floor(basedata.shape[0]/downstep)",
"= dup_and_count(1,1,holding) down1_right5 = dup_and_count(5,1,holding) down1_right7 = dup_and_count(7,1,holding) down2_right1 =",
"# In[2]: fileObj = open('../data/advent_of_code_input_day_three.txt', \"r\") #opens the file in",
"array. # In[3]: #print (items) def split(line): return list(line) holding",
"= dup_and_count(1,2,holding) results = np.array([down1_right3, down1_right1, down1_right5, down1_right7, down2_right1], dtype=np.int64)",
"[] for i, line in enumerate(items): result = split(line) holding.append(result)",
"\"r\") #opens the file in read mode. items = fileObj.",
"read mode. items = fileObj. read(). splitlines() #puts the file",
"downstep, basedata): needed_slope_elements = math.floor(basedata.shape[0]/downstep) replications_needed = (needed_slope_elements* rightstep)/basedata.shape[1] duplicated",
"ii in range(len(right)): moves.append(duplicated[down[ii], right[ii]]) hits = np.sum(moves) return hits",
"utf-8 # In[1]: import numpy as np import math #",
"np.array(holding) holding[holding == '.'] = 0 holding[holding == '#'] =",
"for ii in range(len(right)): moves.append(duplicated[down[ii], right[ii]]) hits = np.sum(moves) return",
"fileObj = open('../data/advent_of_code_input_day_three.txt', \"r\") #opens the file in read mode.",
"= dup_and_count(5,1,holding) down1_right7 = dup_and_count(7,1,holding) down2_right1 = dup_and_count(1,2,holding) results =",
"np.array([down1_right3, down1_right1, down1_right5, down1_right7, down2_right1], dtype=np.int64) print(results) product = np.prod(results)",
"line in enumerate(items): result = split(line) holding.append(result) holding = np.array(holding)",
"down1_right1, down1_right5, down1_right7, down2_right1], dtype=np.int64) print(results) product = np.prod(results) print",
"in read mode. items = fileObj. read(). splitlines() #puts the",
"1 holding = holding.astype(int) print (holding) # In[7]: def dup_and_count(rightstep,",
"for i, line in enumerate(items): result = split(line) holding.append(result) holding",
"holding.astype(int) print (holding) # In[7]: def dup_and_count(rightstep, downstep, basedata): needed_slope_elements",
"down2_right1], dtype=np.int64) print(results) product = np.prod(results) print (product) # In[",
"an array. # In[3]: #print (items) def split(line): return list(line)",
"down1_right7, down2_right1], dtype=np.int64) print(results) product = np.prod(results) print (product) #",
"fileObj. read(). splitlines() #puts the file into an array. #",
"= 0 holding[holding == '#'] = 1 holding = holding.astype(int)",
"= np.array(holding) holding[holding == '.'] = 0 holding[holding == '#']"
] |
[
"import os import traceback class InputHandler: IMAGES_PARENT_FOLDER = './images' def",
"def __init__(self): filesList = [] def listFiles(self,path=''): if path !=",
"return self.listFiles if __name__ == '__main__': obj = InputHandler() print(obj.listFiles())",
"= [] def listFiles(self,path=''): if path != '': self.IMAGES_PARENT_FOLDER =",
"path != '': self.IMAGES_PARENT_FOLDER = path try: self.listFiles = [os.path.join(self.IMAGES_PARENT_FOLDER,imageFile)",
"filesList = [] def listFiles(self,path=''): if path != '': self.IMAGES_PARENT_FOLDER",
"if os.path.isfile(os.path.join(self.IMAGES_PARENT_FOLDER,imageFile))] except: print(traceback.print_exec()) return self.listFiles if __name__ == '__main__':",
"self.IMAGES_PARENT_FOLDER = path try: self.listFiles = [os.path.join(self.IMAGES_PARENT_FOLDER,imageFile) for imageFile in",
"InputHandler: IMAGES_PARENT_FOLDER = './images' def __init__(self): filesList = [] def",
"= './images' def __init__(self): filesList = [] def listFiles(self,path=''): if",
"class InputHandler: IMAGES_PARENT_FOLDER = './images' def __init__(self): filesList = []",
"os import traceback class InputHandler: IMAGES_PARENT_FOLDER = './images' def __init__(self):",
"!= '': self.IMAGES_PARENT_FOLDER = path try: self.listFiles = [os.path.join(self.IMAGES_PARENT_FOLDER,imageFile) for",
"os.listdir(self.IMAGES_PARENT_FOLDER)\\ if os.path.isfile(os.path.join(self.IMAGES_PARENT_FOLDER,imageFile))] except: print(traceback.print_exec()) return self.listFiles if __name__ ==",
"[] def listFiles(self,path=''): if path != '': self.IMAGES_PARENT_FOLDER = path",
"imageFile in os.listdir(self.IMAGES_PARENT_FOLDER)\\ if os.path.isfile(os.path.join(self.IMAGES_PARENT_FOLDER,imageFile))] except: print(traceback.print_exec()) return self.listFiles if",
"for imageFile in os.listdir(self.IMAGES_PARENT_FOLDER)\\ if os.path.isfile(os.path.join(self.IMAGES_PARENT_FOLDER,imageFile))] except: print(traceback.print_exec()) return self.listFiles",
"traceback class InputHandler: IMAGES_PARENT_FOLDER = './images' def __init__(self): filesList =",
"except: print(traceback.print_exec()) return self.listFiles if __name__ == '__main__': obj =",
"__init__(self): filesList = [] def listFiles(self,path=''): if path != '':",
"def listFiles(self,path=''): if path != '': self.IMAGES_PARENT_FOLDER = path try:",
"self.listFiles = [os.path.join(self.IMAGES_PARENT_FOLDER,imageFile) for imageFile in os.listdir(self.IMAGES_PARENT_FOLDER)\\ if os.path.isfile(os.path.join(self.IMAGES_PARENT_FOLDER,imageFile))] except:",
"import traceback class InputHandler: IMAGES_PARENT_FOLDER = './images' def __init__(self): filesList",
"try: self.listFiles = [os.path.join(self.IMAGES_PARENT_FOLDER,imageFile) for imageFile in os.listdir(self.IMAGES_PARENT_FOLDER)\\ if os.path.isfile(os.path.join(self.IMAGES_PARENT_FOLDER,imageFile))]",
"print(traceback.print_exec()) return self.listFiles if __name__ == '__main__': obj = InputHandler()",
"listFiles(self,path=''): if path != '': self.IMAGES_PARENT_FOLDER = path try: self.listFiles",
"IMAGES_PARENT_FOLDER = './images' def __init__(self): filesList = [] def listFiles(self,path=''):",
"= [os.path.join(self.IMAGES_PARENT_FOLDER,imageFile) for imageFile in os.listdir(self.IMAGES_PARENT_FOLDER)\\ if os.path.isfile(os.path.join(self.IMAGES_PARENT_FOLDER,imageFile))] except: print(traceback.print_exec())",
"os.path.isfile(os.path.join(self.IMAGES_PARENT_FOLDER,imageFile))] except: print(traceback.print_exec()) return self.listFiles if __name__ == '__main__': obj",
"in os.listdir(self.IMAGES_PARENT_FOLDER)\\ if os.path.isfile(os.path.join(self.IMAGES_PARENT_FOLDER,imageFile))] except: print(traceback.print_exec()) return self.listFiles if __name__",
"= path try: self.listFiles = [os.path.join(self.IMAGES_PARENT_FOLDER,imageFile) for imageFile in os.listdir(self.IMAGES_PARENT_FOLDER)\\",
"'./images' def __init__(self): filesList = [] def listFiles(self,path=''): if path",
"'': self.IMAGES_PARENT_FOLDER = path try: self.listFiles = [os.path.join(self.IMAGES_PARENT_FOLDER,imageFile) for imageFile",
"[os.path.join(self.IMAGES_PARENT_FOLDER,imageFile) for imageFile in os.listdir(self.IMAGES_PARENT_FOLDER)\\ if os.path.isfile(os.path.join(self.IMAGES_PARENT_FOLDER,imageFile))] except: print(traceback.print_exec()) return",
"if path != '': self.IMAGES_PARENT_FOLDER = path try: self.listFiles =",
"path try: self.listFiles = [os.path.join(self.IMAGES_PARENT_FOLDER,imageFile) for imageFile in os.listdir(self.IMAGES_PARENT_FOLDER)\\ if"
] |
[
"set.\") sys.exit(1) APP_BASE_PATH = os.environ.get(\"BEPASTY_APP_BASE_PATH\", None) STORAGE_FILESYSTEM_DIRECTORY = os.environ.get( \"BEPASTY_STORAGE_FILESYSTEM_DIRECTORY\",",
"int(max_allowed_file_size) except ValueError as err: print(\"\\n\\nInvalid BEPASTY_MAX_ALLOWED_FILE_SIZE: %s\", str(err)) sys.exit(1)",
") DEFAULT_PERMISSIONS = os.environ.get(\"BEPASTY_DEFAULT_PERMISSIONS\", \"create,read\") PERMISSIONS = {} admin_secret =",
"PERMISSIONS = {} admin_secret = os.environ.get(\"BEPASTY_ADMIN_SECRET\", None) if admin_secret is",
"print(\"\\n\\nEnvironment variable BEPASTY_SITENAME must be set.\") sys.exit(1) SECRET_KEY = os.environ.get(\"BEPASTY_SECRET_KEY\",",
"os.environ.get(\"BEPASTY_MAX_BODY_SIZE\", 1040384) MAX_BODY_SIZE = int(max_body_size) except ValueError as err: print(\"\\n\\nInvalid",
"None) if SITENAME is None: print(\"\\n\\nEnvironment variable BEPASTY_SITENAME must be",
"sys.exit(1) APP_BASE_PATH = os.environ.get(\"BEPASTY_APP_BASE_PATH\", None) STORAGE_FILESYSTEM_DIRECTORY = os.environ.get( \"BEPASTY_STORAGE_FILESYSTEM_DIRECTORY\", \"/app/data\",",
"= os.environ.get(\"BEPASTY_APP_BASE_PATH\", None) STORAGE_FILESYSTEM_DIRECTORY = os.environ.get( \"BEPASTY_STORAGE_FILESYSTEM_DIRECTORY\", \"/app/data\", ) DEFAULT_PERMISSIONS",
"= {} admin_secret = os.environ.get(\"BEPASTY_ADMIN_SECRET\", None) if admin_secret is not",
"None: print(\"\\n\\nEnvironment variable BEPASTY_SITENAME must be set.\") sys.exit(1) SECRET_KEY =",
"BEPASTY_SECRET_KEY must be set.\") sys.exit(1) APP_BASE_PATH = os.environ.get(\"BEPASTY_APP_BASE_PATH\", None) STORAGE_FILESYSTEM_DIRECTORY",
"DEFAULT_PERMISSIONS = os.environ.get(\"BEPASTY_DEFAULT_PERMISSIONS\", \"create,read\") PERMISSIONS = {} admin_secret = os.environ.get(\"BEPASTY_ADMIN_SECRET\",",
"SITENAME = os.environ.get(\"BEPASTY_SITENAME\", None) if SITENAME is None: print(\"\\n\\nEnvironment variable",
"if SECRET_KEY is None: print(\"\\n\\nEnvironment variable BEPASTY_SECRET_KEY must be set.\")",
"admin_secret = os.environ.get(\"BEPASTY_ADMIN_SECRET\", None) if admin_secret is not None: PERMISSIONS.update({admin_secret:",
"is None: print(\"\\n\\nEnvironment variable BEPASTY_SECRET_KEY must be set.\") sys.exit(1) APP_BASE_PATH",
"sys.exit(1) SECRET_KEY = os.environ.get(\"BEPASTY_SECRET_KEY\", None) if SECRET_KEY is None: print(\"\\n\\nEnvironment",
"err: print(\"\\n\\nInvalid BEPASTY_MAX_ALLOWED_FILE_SIZE: %s\", str(err)) sys.exit(1) try: max_body_size = os.environ.get(\"BEPASTY_MAX_BODY_SIZE\",",
"os.environ.get(\"BEPASTY_SITENAME\", None) if SITENAME is None: print(\"\\n\\nEnvironment variable BEPASTY_SITENAME must",
"APP_BASE_PATH = os.environ.get(\"BEPASTY_APP_BASE_PATH\", None) STORAGE_FILESYSTEM_DIRECTORY = os.environ.get( \"BEPASTY_STORAGE_FILESYSTEM_DIRECTORY\", \"/app/data\", )",
"os import sys SITENAME = os.environ.get(\"BEPASTY_SITENAME\", None) if SITENAME is",
"PERMISSIONS.update({admin_secret: \"admin,list,create,modify,read,delete\"}) try: max_allowed_file_size = os.environ.get(\"BEPASTY_MAX_ALLOWED_FILE_SIZE\", 5000000000) MAX_ALLOWED_FILE_SIZE = int(max_allowed_file_size)",
"MAX_ALLOWED_FILE_SIZE = int(max_allowed_file_size) except ValueError as err: print(\"\\n\\nInvalid BEPASTY_MAX_ALLOWED_FILE_SIZE: %s\",",
"BEPASTY_MAX_ALLOWED_FILE_SIZE: %s\", str(err)) sys.exit(1) try: max_body_size = os.environ.get(\"BEPASTY_MAX_BODY_SIZE\", 1040384) MAX_BODY_SIZE",
"is None: print(\"\\n\\nEnvironment variable BEPASTY_SITENAME must be set.\") sys.exit(1) SECRET_KEY",
"admin_secret is not None: PERMISSIONS.update({admin_secret: \"admin,list,create,modify,read,delete\"}) try: max_allowed_file_size = os.environ.get(\"BEPASTY_MAX_ALLOWED_FILE_SIZE\",",
"= os.environ.get(\"BEPASTY_MAX_ALLOWED_FILE_SIZE\", 5000000000) MAX_ALLOWED_FILE_SIZE = int(max_allowed_file_size) except ValueError as err:",
"variable BEPASTY_SITENAME must be set.\") sys.exit(1) SECRET_KEY = os.environ.get(\"BEPASTY_SECRET_KEY\", None)",
"print(\"\\n\\nEnvironment variable BEPASTY_SECRET_KEY must be set.\") sys.exit(1) APP_BASE_PATH = os.environ.get(\"BEPASTY_APP_BASE_PATH\",",
"\"admin,list,create,modify,read,delete\"}) try: max_allowed_file_size = os.environ.get(\"BEPASTY_MAX_ALLOWED_FILE_SIZE\", 5000000000) MAX_ALLOWED_FILE_SIZE = int(max_allowed_file_size) except",
"SECRET_KEY is None: print(\"\\n\\nEnvironment variable BEPASTY_SECRET_KEY must be set.\") sys.exit(1)",
"SITENAME is None: print(\"\\n\\nEnvironment variable BEPASTY_SITENAME must be set.\") sys.exit(1)",
"is not None: PERMISSIONS.update({admin_secret: \"admin,list,create,modify,read,delete\"}) try: max_allowed_file_size = os.environ.get(\"BEPASTY_MAX_ALLOWED_FILE_SIZE\", 5000000000)",
"None: PERMISSIONS.update({admin_secret: \"admin,list,create,modify,read,delete\"}) try: max_allowed_file_size = os.environ.get(\"BEPASTY_MAX_ALLOWED_FILE_SIZE\", 5000000000) MAX_ALLOWED_FILE_SIZE =",
"= int(max_allowed_file_size) except ValueError as err: print(\"\\n\\nInvalid BEPASTY_MAX_ALLOWED_FILE_SIZE: %s\", str(err))",
"= os.environ.get( \"BEPASTY_STORAGE_FILESYSTEM_DIRECTORY\", \"/app/data\", ) DEFAULT_PERMISSIONS = os.environ.get(\"BEPASTY_DEFAULT_PERMISSIONS\", \"create,read\") PERMISSIONS",
"MAX_BODY_SIZE = int(max_body_size) except ValueError as err: print(\"\\n\\nInvalid BEPASTY_MAX_BODY_SIZE: %s\",",
"be set.\") sys.exit(1) APP_BASE_PATH = os.environ.get(\"BEPASTY_APP_BASE_PATH\", None) STORAGE_FILESYSTEM_DIRECTORY = os.environ.get(",
"1040384) MAX_BODY_SIZE = int(max_body_size) except ValueError as err: print(\"\\n\\nInvalid BEPASTY_MAX_BODY_SIZE:",
"= int(max_body_size) except ValueError as err: print(\"\\n\\nInvalid BEPASTY_MAX_BODY_SIZE: %s\", str(err))",
"#!/usr/bin/python import os import sys SITENAME = os.environ.get(\"BEPASTY_SITENAME\", None) if",
"must be set.\") sys.exit(1) APP_BASE_PATH = os.environ.get(\"BEPASTY_APP_BASE_PATH\", None) STORAGE_FILESYSTEM_DIRECTORY =",
"if admin_secret is not None: PERMISSIONS.update({admin_secret: \"admin,list,create,modify,read,delete\"}) try: max_allowed_file_size =",
"max_allowed_file_size = os.environ.get(\"BEPASTY_MAX_ALLOWED_FILE_SIZE\", 5000000000) MAX_ALLOWED_FILE_SIZE = int(max_allowed_file_size) except ValueError as",
"import sys SITENAME = os.environ.get(\"BEPASTY_SITENAME\", None) if SITENAME is None:",
"import os import sys SITENAME = os.environ.get(\"BEPASTY_SITENAME\", None) if SITENAME",
"int(max_body_size) except ValueError as err: print(\"\\n\\nInvalid BEPASTY_MAX_BODY_SIZE: %s\", str(err)) sys.exit(1)",
"except ValueError as err: print(\"\\n\\nInvalid BEPASTY_MAX_ALLOWED_FILE_SIZE: %s\", str(err)) sys.exit(1) try:",
"as err: print(\"\\n\\nInvalid BEPASTY_MAX_ALLOWED_FILE_SIZE: %s\", str(err)) sys.exit(1) try: max_body_size =",
"\"create,read\") PERMISSIONS = {} admin_secret = os.environ.get(\"BEPASTY_ADMIN_SECRET\", None) if admin_secret",
"SECRET_KEY = os.environ.get(\"BEPASTY_SECRET_KEY\", None) if SECRET_KEY is None: print(\"\\n\\nEnvironment variable",
"if SITENAME is None: print(\"\\n\\nEnvironment variable BEPASTY_SITENAME must be set.\")",
"sys SITENAME = os.environ.get(\"BEPASTY_SITENAME\", None) if SITENAME is None: print(\"\\n\\nEnvironment",
"BEPASTY_SITENAME must be set.\") sys.exit(1) SECRET_KEY = os.environ.get(\"BEPASTY_SECRET_KEY\", None) if",
"set.\") sys.exit(1) SECRET_KEY = os.environ.get(\"BEPASTY_SECRET_KEY\", None) if SECRET_KEY is None:",
"os.environ.get(\"BEPASTY_ADMIN_SECRET\", None) if admin_secret is not None: PERMISSIONS.update({admin_secret: \"admin,list,create,modify,read,delete\"}) try:",
"= os.environ.get(\"BEPASTY_MAX_BODY_SIZE\", 1040384) MAX_BODY_SIZE = int(max_body_size) except ValueError as err:",
"os.environ.get(\"BEPASTY_APP_BASE_PATH\", None) STORAGE_FILESYSTEM_DIRECTORY = os.environ.get( \"BEPASTY_STORAGE_FILESYSTEM_DIRECTORY\", \"/app/data\", ) DEFAULT_PERMISSIONS =",
"print(\"\\n\\nInvalid BEPASTY_MAX_ALLOWED_FILE_SIZE: %s\", str(err)) sys.exit(1) try: max_body_size = os.environ.get(\"BEPASTY_MAX_BODY_SIZE\", 1040384)",
"try: max_allowed_file_size = os.environ.get(\"BEPASTY_MAX_ALLOWED_FILE_SIZE\", 5000000000) MAX_ALLOWED_FILE_SIZE = int(max_allowed_file_size) except ValueError",
"= os.environ.get(\"BEPASTY_DEFAULT_PERMISSIONS\", \"create,read\") PERMISSIONS = {} admin_secret = os.environ.get(\"BEPASTY_ADMIN_SECRET\", None)",
"<filename>docker/autoconfig.py #!/usr/bin/python import os import sys SITENAME = os.environ.get(\"BEPASTY_SITENAME\", None)",
"must be set.\") sys.exit(1) SECRET_KEY = os.environ.get(\"BEPASTY_SECRET_KEY\", None) if SECRET_KEY",
"None) if admin_secret is not None: PERMISSIONS.update({admin_secret: \"admin,list,create,modify,read,delete\"}) try: max_allowed_file_size",
"try: max_body_size = os.environ.get(\"BEPASTY_MAX_BODY_SIZE\", 1040384) MAX_BODY_SIZE = int(max_body_size) except ValueError",
"variable BEPASTY_SECRET_KEY must be set.\") sys.exit(1) APP_BASE_PATH = os.environ.get(\"BEPASTY_APP_BASE_PATH\", None)",
"%s\", str(err)) sys.exit(1) try: max_body_size = os.environ.get(\"BEPASTY_MAX_BODY_SIZE\", 1040384) MAX_BODY_SIZE =",
"None) if SECRET_KEY is None: print(\"\\n\\nEnvironment variable BEPASTY_SECRET_KEY must be",
"sys.exit(1) try: max_body_size = os.environ.get(\"BEPASTY_MAX_BODY_SIZE\", 1040384) MAX_BODY_SIZE = int(max_body_size) except",
"not None: PERMISSIONS.update({admin_secret: \"admin,list,create,modify,read,delete\"}) try: max_allowed_file_size = os.environ.get(\"BEPASTY_MAX_ALLOWED_FILE_SIZE\", 5000000000) MAX_ALLOWED_FILE_SIZE",
"os.environ.get( \"BEPASTY_STORAGE_FILESYSTEM_DIRECTORY\", \"/app/data\", ) DEFAULT_PERMISSIONS = os.environ.get(\"BEPASTY_DEFAULT_PERMISSIONS\", \"create,read\") PERMISSIONS =",
"\"/app/data\", ) DEFAULT_PERMISSIONS = os.environ.get(\"BEPASTY_DEFAULT_PERMISSIONS\", \"create,read\") PERMISSIONS = {} admin_secret",
"= os.environ.get(\"BEPASTY_SECRET_KEY\", None) if SECRET_KEY is None: print(\"\\n\\nEnvironment variable BEPASTY_SECRET_KEY",
"os.environ.get(\"BEPASTY_MAX_ALLOWED_FILE_SIZE\", 5000000000) MAX_ALLOWED_FILE_SIZE = int(max_allowed_file_size) except ValueError as err: print(\"\\n\\nInvalid",
"= os.environ.get(\"BEPASTY_ADMIN_SECRET\", None) if admin_secret is not None: PERMISSIONS.update({admin_secret: \"admin,list,create,modify,read,delete\"})",
"be set.\") sys.exit(1) SECRET_KEY = os.environ.get(\"BEPASTY_SECRET_KEY\", None) if SECRET_KEY is",
"STORAGE_FILESYSTEM_DIRECTORY = os.environ.get( \"BEPASTY_STORAGE_FILESYSTEM_DIRECTORY\", \"/app/data\", ) DEFAULT_PERMISSIONS = os.environ.get(\"BEPASTY_DEFAULT_PERMISSIONS\", \"create,read\")",
"os.environ.get(\"BEPASTY_DEFAULT_PERMISSIONS\", \"create,read\") PERMISSIONS = {} admin_secret = os.environ.get(\"BEPASTY_ADMIN_SECRET\", None) if",
"{} admin_secret = os.environ.get(\"BEPASTY_ADMIN_SECRET\", None) if admin_secret is not None:",
"\"BEPASTY_STORAGE_FILESYSTEM_DIRECTORY\", \"/app/data\", ) DEFAULT_PERMISSIONS = os.environ.get(\"BEPASTY_DEFAULT_PERMISSIONS\", \"create,read\") PERMISSIONS = {}",
"str(err)) sys.exit(1) try: max_body_size = os.environ.get(\"BEPASTY_MAX_BODY_SIZE\", 1040384) MAX_BODY_SIZE = int(max_body_size)",
"None) STORAGE_FILESYSTEM_DIRECTORY = os.environ.get( \"BEPASTY_STORAGE_FILESYSTEM_DIRECTORY\", \"/app/data\", ) DEFAULT_PERMISSIONS = os.environ.get(\"BEPASTY_DEFAULT_PERMISSIONS\",",
"ValueError as err: print(\"\\n\\nInvalid BEPASTY_MAX_ALLOWED_FILE_SIZE: %s\", str(err)) sys.exit(1) try: max_body_size",
"None: print(\"\\n\\nEnvironment variable BEPASTY_SECRET_KEY must be set.\") sys.exit(1) APP_BASE_PATH =",
"max_body_size = os.environ.get(\"BEPASTY_MAX_BODY_SIZE\", 1040384) MAX_BODY_SIZE = int(max_body_size) except ValueError as",
"5000000000) MAX_ALLOWED_FILE_SIZE = int(max_allowed_file_size) except ValueError as err: print(\"\\n\\nInvalid BEPASTY_MAX_ALLOWED_FILE_SIZE:",
"= os.environ.get(\"BEPASTY_SITENAME\", None) if SITENAME is None: print(\"\\n\\nEnvironment variable BEPASTY_SITENAME",
"os.environ.get(\"BEPASTY_SECRET_KEY\", None) if SECRET_KEY is None: print(\"\\n\\nEnvironment variable BEPASTY_SECRET_KEY must"
] |
[
"+= self.eval_expr(expr) return accum def eval(self): mut_args = deque(self.args) cmd",
"expr<' ls foo${bar} ' !! #!/bin/fish ls .* '''.strip() #TODO:",
"os.environ[expr.name] elif isinstance(expr, BangGlob): return PathWrapper().glob(expr.glob) else: return str(expr) def",
"# it's intended for this to be global def build_scanner(self):",
"whitespace operator if needed if token != 'OP' and last_token",
"v: v[1:])), (r'\\${( \\\\. | [^\\\\}]+ )+}', t('EXPR', lambda v:",
")+}', t('EXPR', lambda v: v[2:-1])), (r'[^\\\\\\$]+', t('SQS')) # handle as",
"grep = command('grep') bar = 10 print('::BangExpr::') be = BangExpr('ls',",
"def __repr__(self): return 'BangGlob<{}>'.format(self.glob) class BangExpr: __slots__ = ('args', 'vars')",
"@lru_cache() # it's intended for this to be global def",
"yield from parse_bangexpr(' '.join(lines)).split('\\n') from io import StringIO code =",
"cmd def __str__(self): return str(self.eval()) def __repr__(self): return 'BangExpr<{!r}>'.format(self.args) class",
"the transformed code line by line. \"\"\" tokens = tokenize.generate_tokens(code.readline)",
"(r'\\#.+', t('COMMENT', lambda v: v[1:])), (r'\\\\.', t('ESCAPE')), (r\"'( \\\\. |",
"can report back the transformation. Returns a generator that allows",
"def __init__(self, *args, locals=None, globals=None): assert locals is not None",
"tokens: if tkn == 'DQS': yield from self.scan_dqs(val, offset=pos[0]+1) else:",
"= 10 print('::BangExpr::') be = BangExpr('ls', BangSeq('foo', bar, BangGlob('.*')), BangOp(\"|\"),",
"BangTokenType.EXPR): seq.append(tkn.value) elif tkn.type == BangTokenType.ENV: seq.append('pysh.BangEnv({})'.format(as_str(tkn.value))) elif tkn.type ==",
"pos in tokens: if tkn == 'DQS': yield from self.scan_dqs(val,",
"BangGlob: __slots__ = ('glob',) def __init__(self, glob): self.glob = glob",
"mut_args.popleft() assert isinstance(arg, BangOp), 'Expected OP but found: {}'.format(arg) assert",
"StringIO code = r''' foo = ! ls foo${bar}.* \\",
"seq') return PathWrapper(accum).glob(expr.glob) accum += self.eval_expr(expr) return accum def eval(self):",
"continue exprs.append('pysh.BangOp(\"{}\")'.format(tkn.value)) # We need to provide locals/globals so we",
"eval_command(self, mut_args): arg = mut_args.popleft() cmd = self.vars.get(str(arg)) if cmd",
"ctkn.line.rstrip('\\r\\n') bangexpr.append(line) bangcont = line.endswith('\\\\') last_bang_line = ctkn.start[0] elif bangexpr:",
"in self.demux_dqs(tokens): assert token != 'DQS' # double quoted are",
"means with variables interpolated # < is plain text ls",
"1: exprs.append('pysh.BangSeq({})'.format(', '.join(seq))) else: exprs.append(seq[0]) seq = [] if not",
"type: List[str] bangcont = False prebang = None ptkn =",
"'', (len(code),len(code)))) last_token = last_pos = None for token, value,",
"exprs: raise RuntimeError('Globbing can only occur at the end of",
"is tokenize.ENDMARKER: raise SyntaxError('BangExpr continuation at program end') line =",
"ctkn.line[0:col] line = ctkn.line[col+1:].lstrip(' \\t').rstrip('\\r\\n') bangexpr.append(line.rstrip('\\\\')) bangcont = line.endswith('\\\\') last_bang_line",
"Scans python code to transform bang expressions. Given some python",
"bang_indent = indent elif ctkn.type == tokenize.DEDENT: indent -= 1",
"plain text ls .* ''' for line in transform(StringIO(code), transformer):",
"elif ctkn.type == tokenize.DEDENT: indent -= 1 if bang_indent >",
"__init__(self, glob): self.glob = glob def __repr__(self): return 'BangGlob<{}>'.format(self.glob) class",
"\"\"\" tokens = tokenize.generate_tokens(code.readline) bangexpr = [] # type: List[str]",
"ctkn.line[col+1:].lstrip(' \\t').rstrip('\\r\\n') bangexpr.append(line.rstrip('\\\\')) bangcont = line.endswith('\\\\') last_bang_line = ctkn.start[0] assert",
"> 1: exprs.append('pysh.BangSeq({})'.format(', '.join(seq))) else: exprs.append(seq[0]) seq = [] if",
"transformed code line by line. \"\"\" tokens = tokenize.generate_tokens(code.readline) bangexpr",
"[] # type: List[str] bangcont = False prebang = None",
"BangSeq): return self.eval_seq(expr) elif isinstance(expr, BangEnv): return os.environ[expr.name] elif isinstance(expr,",
"tokens.append(('END', '', (len(code),len(code)))) last_token = last_pos = None for token,",
"t('VAR', lambda v: v[1:])), (r'\\${( \\\\. | [^\\\\}]+ )+}', t('EXPR',",
"__all__ = ['BangExpr', 'BangOp', 'BangSeq', 'BangGlob', 'BangEnv', 'BangBang'] class BangTokenType(Enum):",
"token in ('ESCAPE', 'SQS'): #TODO: handle special escapes \\n value",
"bangexpr.append(line.rstrip('\\\\')) bangcont = line.endswith('\\\\') last_bang_line = ctkn.start[0] assert not bangexpr,",
"RuntimeError('Unable to find {}'.format(arg)) while mut_args: if isinstance(mut_args[0], BangOp): break",
"mut_args: arg = mut_args.popleft() assert isinstance(arg, BangOp), 'Expected OP but",
"remaining: raise SyntaxError('Unexpected char at position {}'.format(len(code)-len(remaining))) # Add a",
"self.vars = ChainMap(locals, globals) def eval_command(self, mut_args): arg = mut_args.popleft()",
"\"\"\" Split double quoted strings into parts \"\"\" for tkn,",
"def __str__(self): return str(self.eval()) def __repr__(self): return 'BangBang<{}>'.format(self.code) def parse_bangexpr(code:",
"if ctkn.type is tokenize.ENDMARKER: raise SyntaxError('BangExpr continuation at program end')",
"solved with inspect.frame.f_locals sh << r''' # << means with",
"Add a terminating token so we can simplify the parsing",
"v[1:-1])), (r'\\$[A-Za-z_][A-Za-z0-9_]*', t('VAR', lambda v: v[1:])), (r'\\${( \\\\. | [^\\\\}]+",
"|= self.eval_command(mut_args) elif arg.op == '^': cmd ^= self.eval_command(mut_args) elif",
"parts \"\"\" for tkn, val, pos in tokens: if tkn",
"tkn.type == BangTokenType.GLOB: seq.append('pysh.BangGlob({})'.format(as_str(tkn.value))) else: assert False, 'Unexpected token {}'.format(tkn.type)",
"tokens: Iterator[TBangLexerToken]) -> Iterator[TBangLexerToken]: \"\"\" Split double quoted strings into",
"if re.search(r'(?!<\\\\)[~*?{]', value): yield BangToken(BangTokenType.GLOB, value, pos) else: yield BangToken(BangTokenType.OPAQUE,",
"= cmd > self.eval_expr(mut_args.popleft()) elif arg.op == '>>': cmd =",
"information to detect when we're on a new line #TODO:",
"def __init__(self, *items): self.items = items def __repr__(self): return 'BangSeq<{!r}>'.format(self.items)",
"class BangEnv: __slots__ = ('name',) def __init__(self, name): self.name =",
"deque(self.args) cmd = self.eval_command(mut_args) while mut_args: arg = mut_args.popleft() assert",
"token == 'EXPR' value = re.sub(r'\\\\(.)', r'\\1', value) yield BangToken(BangTokenType.EXPR,",
"and ctkn.start[0] > ptkn.start[0]: if bangcont or bang_indent == indent:",
"{}'.format(arg)) while mut_args: if isinstance(mut_args[0], BangOp): break arg = mut_args.popleft()",
"Iterator[TBangLexerToken]) -> Iterator[TBangLexerToken]: \"\"\" Split double quoted strings into parts",
"in lines: yield line else: yield from parse_bangexpr(' '.join(lines)).split('\\n') from",
"io import StringIO code = r''' foo = ! ls",
"= mut_args.popleft() cmd = self.vars.get(str(arg)) if cmd is None: raise",
"$ident to expose them on env when evaluated lines[0] =",
"that allows to consume the transformed code line by line.",
"BangLexer: def _tokener(self, token, transformer=lambda x: x, **kwargs): def cb(s,",
"raise RuntimeError('Unsupported operator {}'.format(arg.op)) return cmd def __str__(self): return str(self.eval())",
"lines[0] = prebang + lines[0] yield from lines bangexpr =",
"= -100 # due to continuations we can't rely on",
"foo${bar} ' !! #!/bin/fish ls .* '''.strip() #TODO: !! is",
"BangToken(NamedTuple): type: BangTokenType value: str span: Tuple[int, int] TBangLexerToken =",
"lambda v: v[1:])), (r'\\\\.', t('ESCAPE')), (r\"'( \\\\. | [^\\\\']+ )+'\",",
"token == 'WS': pass elif token == 'OP': value =",
"= 'EXPR' OP = 'OP' class BangToken(NamedTuple): type: BangTokenType value:",
"self.name = name def __repr__(self): return 'BangEnv<{}>'.format(self.name) class BangSeq: __slots__",
"= deque(seq.items) accum = '' while exprs: expr = exprs.popleft()",
"token {}'.format(tkn.type) continue if seq: if len(seq) > 1: exprs.append('pysh.BangSeq({})'.format(',",
"special escapes \\n value = re.sub(r'\\\\(.)', r'\\1', value) yield BangToken(BangTokenType.OPAQUE,",
"ptkn.line ptkn = ctkn if bangexpr: continue if ctkn.string ==",
"def eval_command(self, mut_args): arg = mut_args.popleft() cmd = self.vars.get(str(arg)) if",
"ctkn.start[0]: bang_indent = indent elif ctkn.type == tokenize.DEDENT: indent -=",
"'SQS'): #TODO: handle special escapes \\n value = re.sub(r'\\\\(.)', r'\\1',",
"line. \"\"\" tokens = tokenize.generate_tokens(code.readline) bangexpr = [] # type:",
"= code def eval(self): #TODO: Detect shebang and use it",
"while mut_args: arg = mut_args.popleft() assert isinstance(arg, BangOp), 'Expected OP",
"while mut_args: if isinstance(mut_args[0], BangOp): break arg = mut_args.popleft() cmd",
"'EXPR' OP = 'OP' class BangToken(NamedTuple): type: BangTokenType value: str",
"str span: Tuple[int, int] TBangLexerToken = Tuple[str, str, Tuple[int,int]] class",
"= code.split('\\n') for line in lines: yield line else: yield",
"operator if needed if token != 'OP' and last_token and",
"*items): self.items = items def __repr__(self): return 'BangSeq<{!r}>'.format(self.items) class BangOp:",
"Any TBangTransformer = Callable[ [List[str]], Iterator[str]] # runtime symbols __all__",
"| grep foo > /dev/null foo = r' ls foo${bar}",
"interpolated # < is plain text ls .* ''' for",
"False prebang = None ptkn = None indent = 0",
"and last_token == 'WS': yield BangToken(BangTokenType.OP, ' ', last_pos) if",
"provide locals/globals so we can resolve commands to variables return",
"lambda v: v[1:])), (r'\\${( \\\\. | [^\\\\}]+ )+}', t('EXPR', lambda",
"instead we have # use the lexical information to detect",
"class BangLexer: def _tokener(self, token, transformer=lambda x: x, **kwargs): def",
"__slots__ = ('args', 'vars') def __init__(self, *args, locals=None, globals=None): assert",
"class BangGlob: __slots__ = ('glob',) def __init__(self, glob): self.glob =",
"tokens: yield tkn, val, (offset+pos[0], offset+pos[1]) def demux_dqs(self, tokens: Iterator[TBangLexerToken])",
"= transformer(v, **kwargs) return None if v is None else",
".* '''.strip() #TODO: !! is probably better solved with: #",
"ctkn.type is tokenize.ENDMARKER: raise SyntaxError('BangExpr continuation at program end') line",
"'.join(lines)).split('\\n') from io import StringIO code = r''' foo =",
"with variables interpolated # < is plain text ls .*",
"__str__(self): return str(self.eval()) def __repr__(self): return 'BangBang<{}>'.format(self.code) def parse_bangexpr(code: str)",
"= 0 bang_indent = -100 last_bang_line = -100 for ctkn",
"== BangTokenType.OP if tkn.value == ' ': continue exprs.append('pysh.BangOp(\"{}\")'.format(tkn.value)) #",
"break arg = mut_args.popleft() cmd = cmd(self.eval_expr(arg)) return cmd def",
"foo = ! ls foo${bar}.* \\ | grep foo >",
"== '^': cmd ^= self.eval_command(mut_args) elif arg.op == '>': cmd",
"def __repr__(self): return 'BangBang<{}>'.format(self.code) def parse_bangexpr(code: str) -> str: as_str",
"default shell import sys, subprocess result = subprocess.run( ['bash', '-c',",
"to detect when we're on a new line #TODO: Support",
"= ('op',) def __init__(self, op): self.op = op def __repr__(self):",
"len(lines) <= len(bangexpr) if lines and prebang: lines[0] = prebang",
"to be global def build_scanner(self): t = self._tokener return re.Scanner([",
"tokens, remaining = self.build_scanner().scan(code) if remaining: raise SyntaxError('Unexpected char <{}>",
"self.demux_dqs(tokens): assert token != 'DQS' # double quoted are demuxed",
"Callable[ [List[str]], Iterator[str]] # runtime symbols __all__ = ['BangExpr', 'BangOp',",
"t('WS')), ], flags=re.X) @lru_cache() def build_dqs_scanner(self): t = self._tokener return",
"__init__(self, name): self.name = name def __repr__(self): return 'BangEnv<{}>'.format(self.name) class",
"yield tkn, val, (offset+pos[0], offset+pos[1]) def demux_dqs(self, tokens: Iterator[TBangLexerToken]) ->",
"+ 1 == ctkn.start[0]: bang_indent = indent elif ctkn.type ==",
"value.strip() if value.isalnum() and not value.isdigit(): if value.isupper(): yield BangToken(BangTokenType.ENV,",
"result = subprocess.run( ['bash', '-c', self.code], encoding='utf-8', stdout=subprocess.PIPE, stderr=subprocess.PIPE) if",
"'>>': cmd = cmd >> self.eval_expr(mut_args.popleft()) else: raise RuntimeError('Unsupported operator",
"ls = command('ls') grep = command('grep') bar = 10 print('::BangExpr::')",
"else: exprs.append(seq[0]) seq = [] if not tkn: break assert",
"single quoted ], flags=re.X) def scan_dqs(self, code: str, offset=0) ->",
"cmd def eval_expr(self, expr: Any) -> Union[str, Iterator[Path]]: if isinstance(expr,",
"Union, Any TBangTransformer = Callable[ [List[str]], Iterator[str]] # runtime symbols",
"v[1:-1])), (r'\"( \\\\. | [^\\\\\"]+ )+\"', t('DQS', lambda v: v[1:-1])),",
"in ('VAR', 'EXPR'): value = value.strip() if value.isalnum() and not",
"(BangTokenType.LOCAL, BangTokenType.EXPR): seq.append(tkn.value) elif tkn.type == BangTokenType.ENV: seq.append('pysh.BangEnv({})'.format(as_str(tkn.value))) elif tkn.type",
"BangEnv): return os.environ[expr.name] elif isinstance(expr, BangGlob): return PathWrapper().glob(expr.glob) else: return",
"if v is None else (token, v, (s.match.start(), s.match.end())) return",
"cb @lru_cache() # it's intended for this to be global",
"tkn.type == BangTokenType.ENV: seq.append('pysh.BangEnv({})'.format(as_str(tkn.value))) elif tkn.type == BangTokenType.OPAQUE: seq.append('{}'.format(as_str(tkn.value))) elif",
"token != 'DQS' # double quoted are demuxed # Inject",
"due to continuations we can't rely on NEWLINE tokens, instead",
"last_bang_line = ctkn.start[0] assert not bangexpr, bangexpr def transformer(lines: List[str])",
"= [] last_bang_line = ptkn.start[0] else: yield ptkn.line ptkn =",
"re.search(r'(?!<\\\\)[~*?{]', value): yield BangToken(BangTokenType.GLOB, value, pos) else: yield BangToken(BangTokenType.OPAQUE, value,",
"!= BangTokenType.OP: if tkn.type in (BangTokenType.LOCAL, BangTokenType.EXPR): seq.append(tkn.value) elif tkn.type",
"exprs: expr = exprs.popleft() if isinstance(expr, BangGlob): if exprs: raise",
"for multiline if ptkn and ctkn.start[0] > ptkn.start[0]: if bangcont",
"consume the transformed code line by line. \"\"\" tokens =",
"@lru_cache() def build_dqs_scanner(self): t = self._tokener return re.Scanner([ (r'\\\\.', t('ESCAPE')),",
"self.items = items def __repr__(self): return 'BangSeq<{!r}>'.format(self.items) class BangOp: __slots__",
"self.code = code def eval(self): #TODO: Detect shebang and use",
"ptkn.start[0]: if bangcont or bang_indent == indent: if ctkn.type is",
"s.match.end())) return cb @lru_cache() # it's intended for this to",
"as_str = lambda s: \"'{}'\".format(s.replace(\"\\\\\", \"\\\\\\\\\").replace(\"'\", \"\\\\'\")) lexer = BangLexer().scan(code)",
"ctkn.type == tokenize.INDENT: indent += 1 if last_bang_line + 1",
"pos def scan(self, code: str) -> Iterator[BangToken]: tokens, remaining =",
"can simplify the parsing tokens.append(('END', '', (len(code),len(code)))) last_token = last_pos",
"seq.append(tkn.value) elif tkn.type == BangTokenType.ENV: seq.append('pysh.BangEnv({})'.format(as_str(tkn.value))) elif tkn.type == BangTokenType.OPAQUE:",
"def transform(code: StringIO, transformer: TBangTransformer) -> Iterator[str]: \"\"\" Scans python",
"token so we can simplify the parsing tokens.append(('END', '', (len(code),len(code))))",
"tkn, val, (offset+pos[0], offset+pos[1]) def demux_dqs(self, tokens: Iterator[TBangLexerToken]) -> Iterator[TBangLexerToken]:",
"None ptkn = None indent = 0 bang_indent = -100",
"inspect.frame.f_locals sh << r''' # << means with variables interpolated",
"= ctkn.line.rstrip('\\r\\n') bangexpr.append(line) bangcont = line.endswith('\\\\') last_bang_line = ctkn.start[0] elif",
"else: yield tkn, val, pos def scan(self, code: str) ->",
"if bangcont or bang_indent == indent: if ctkn.type is tokenize.ENDMARKER:",
"variables interpolated # < is plain text ls .* '''",
"return 'pysh.BangExpr({}, locals=locals(), globals=globals())'.format(', '.join(exprs)) def transform(code: StringIO, transformer: TBangTransformer)",
"'BangEnv<{}>'.format(self.name) class BangSeq: __slots__ = ('items',) def __init__(self, *items): self.items",
"assert token != 'DQS' # double quoted are demuxed #",
"self.eval_expr(mut_args.popleft()) elif arg.op == '>>': cmd = cmd >> self.eval_expr(mut_args.popleft())",
"seq = [] exprs = [] while True: tkn =",
"of default shell import sys, subprocess result = subprocess.run( ['bash',",
"== BangTokenType.GLOB: seq.append('pysh.BangGlob({})'.format(as_str(tkn.value))) else: assert False, 'Unexpected token {}'.format(tkn.type) continue",
"transform(StringIO(code), transformer): print(line.rstrip('\\n')) from pysh.command import command ls = command('ls')",
"t('COMMENT', lambda v: v[1:])), (r'\\\\.', t('ESCAPE')), (r\"'( \\\\. | [^\\\\']+",
"v: v[2:-1])), (r'[^\\\\\\$]+', t('SQS')) # handle as single quoted ],",
"{}'.format(arg) assert len(mut_args) > 0, 'No operands left!' if arg.op",
"Union[str, Iterator[Path]]: if isinstance(expr, BangSeq): return self.eval_seq(expr) elif isinstance(expr, BangEnv):",
"Tuple[int, int] TBangLexerToken = Tuple[str, str, Tuple[int,int]] class BangLexer: def",
"to variables return 'pysh.BangExpr({}, locals=locals(), globals=globals())'.format(', '.join(exprs)) def transform(code: StringIO,",
"self.args = args self.vars = ChainMap(locals, globals) def eval_command(self, mut_args):",
"code = r''' foo = ! ls foo${bar}.* \\ |",
"elif token in ('ESCAPE', 'SQS'): #TODO: handle special escapes \\n",
"elif isinstance(expr, BangGlob): return PathWrapper().glob(expr.glob) else: return str(expr) def eval_seq(self,",
"return str(self.eval()) def __repr__(self): return 'BangBang<{}>'.format(self.code) def parse_bangexpr(code: str) ->",
"it will extract bang expressions and process them with a",
"value.isalnum() and not value.isdigit(): if value.isupper(): yield BangToken(BangTokenType.ENV, value, pos)",
"# double quoted are demuxed # Inject whitespace operator if",
"= ctkn.start[0] assert not bangexpr, bangexpr def transformer(lines: List[str]) ->",
"import command ls = command('ls') grep = command('grep') bar =",
"bangexpr = [] last_bang_line = ptkn.start[0] else: yield ptkn.line ptkn",
"BangSeq: __slots__ = ('items',) def __init__(self, *items): self.items = items",
"assert locals is not None assert globals is not None",
"in tokens: if tkn == 'DQS': yield from self.scan_dqs(val, offset=pos[0]+1)",
"tokenize.DEDENT: indent -= 1 if bang_indent > indent: bang_indent =",
"re.Scanner([ (r'\\\\.', t('ESCAPE')), (r'\\$[A-Za-z_][A-Za-z0-9_]*', t('VAR', lambda v: v[1:])), (r'\\${( \\\\.",
"value.isdigit(): if value.isupper(): yield BangToken(BangTokenType.ENV, value, pos) else: yield BangToken(BangTokenType.LOCAL,",
"globals is not None self.args = args self.vars = ChainMap(locals,",
"tkn, val, pos in tokens: if tkn == 'DQS': yield",
"end of a seq') return PathWrapper(accum).glob(expr.glob) accum += self.eval_expr(expr) return",
"rely on NEWLINE tokens, instead we have # use the",
"bangexpr: lines = list(transformer(bangexpr)) assert len(lines) <= len(bangexpr) if lines",
"BangGlob): if exprs: raise RuntimeError('Globbing can only occur at the",
"code = \"pysh.BangBang('{}')\".format(code) lines = code.split('\\n') for line in lines:",
"'/dev/null', locals=locals(), globals=globals()) # print(be) print('::BangBang::') bb = BangBang('''#!/bin/bash ls",
"in tokens: yield tkn, val, (offset+pos[0], offset+pos[1]) def demux_dqs(self, tokens:",
"def cb(s, v): v = transformer(v, **kwargs) return None if",
"self.code], encoding='utf-8', stdout=subprocess.PIPE, stderr=subprocess.PIPE) if result.stderr: print(result.stderr, file=sys.stderr) if result.returncode",
"op def __repr__(self): return 'BangOp<{}>'.format(self.op) class BangGlob: __slots__ = ('glob',)",
"to transform bang expressions. Given some python code it will",
"deque(seq.items) accum = '' while exprs: expr = exprs.popleft() if",
"self.eval_expr(expr) return accum def eval(self): mut_args = deque(self.args) cmd =",
"len(seq) > 1: exprs.append('pysh.BangSeq({})'.format(', '.join(seq))) else: exprs.append(seq[0]) seq = []",
"continuation at program end') line = ctkn.line.rstrip('\\r\\n') bangexpr.append(line) bangcont =",
"transformer): print(line.rstrip('\\n')) from pysh.command import command ls = command('ls') grep",
"foo = r' ls foo${bar} ' >> expr expr<' ls",
"value, pos) elif token in ('ESCAPE', 'SQS'): #TODO: handle special",
"foo > /dev/null foo = r' ls foo${bar} ' >>",
"Enum import pysh from pysh.path import PathWrapper, Path from typing",
"tkn.type in (BangTokenType.LOCAL, BangTokenType.EXPR): seq.append(tkn.value) elif tkn.type == BangTokenType.ENV: seq.append('pysh.BangEnv({})'.format(as_str(tkn.value)))",
"cmd = cmd >> self.eval_expr(mut_args.popleft()) else: raise RuntimeError('Unsupported operator {}'.format(arg.op))",
"-> Iterator[str]: if lines[0].startswith('!'): #TODO: Detect $ident to expose them",
"last_token == 'WS': yield BangToken(BangTokenType.OP, ' ', last_pos) if token",
"str, offset=0) -> Iterator[TBangLexerToken]: tokens, remaining = self.build_scanner().scan(code) if remaining:",
"'baz', BangOp(\">\"), '/dev/null', locals=locals(), globals=globals()) # print(be) print('::BangBang::') bb =",
"BangGlob('.*')), BangOp(\"|\"), 'grep', 'foo', 'baz', BangOp(\">\"), '/dev/null', locals=locals(), globals=globals()) #",
"BangToken(BangTokenType.LOCAL, value, pos) else: assert token == 'EXPR' value =",
"quoted are demuxed # Inject whitespace operator if needed if",
"> 0: if result.stdout: print(result.stdout) raise pysh.ExitStatusError(result.returncode) return result.stdout def",
"lambda v: v[1:-1])), (r'\"( \\\\. | [^\\\\\"]+ )+\"', t('DQS', lambda",
"expose them on env when evaluated lines[0] = lines[0][1:] code",
"seq = [] if not tkn: break assert tkn.type ==",
"BangExpr('ls', BangSeq('foo', bar, BangGlob('.*')), BangOp(\"|\"), 'grep', 'foo', 'baz', BangOp(\">\"), '/dev/null',",
"__repr__(self): return 'BangEnv<{}>'.format(self.name) class BangSeq: __slots__ = ('items',) def __init__(self,",
"def eval_seq(self, seq: BangSeq) -> Union[str, Iterator[Path]]: exprs: Deque[Any] =",
"enum import Enum import pysh from pysh.path import PathWrapper, Path",
"io import StringIO import re import tokenize import os from",
"[List[str]], Iterator[str]] # runtime symbols __all__ = ['BangExpr', 'BangOp', 'BangSeq',",
"SyntaxError('Unexpected char <{}> at position {}'.format(remaining[0], len(code)-len(remaining))) for tkn, val,",
"= token, pos class BangEnv: __slots__ = ('name',) def __init__(self,",
"v = transformer(v, **kwargs) return None if v is None",
"arg = mut_args.popleft() assert isinstance(arg, BangOp), 'Expected OP but found:",
"parse_bangexpr(' '.join(lines)).split('\\n') from io import StringIO code = r''' foo",
"'grep', 'foo', 'baz', BangOp(\">\"), '/dev/null', locals=locals(), globals=globals()) # print(be) print('::BangBang::')",
"return 'BangExpr<{!r}>'.format(self.args) class BangBang: __slots__ = ('code',) def __init__(self, code):",
"from collections import deque, ChainMap from functools import lru_cache from",
"[^\\\\}]+ )+}', t('EXPR', lambda v: v[2:-1])), (r'[^\\\\\\$]+', t('SQS')) # handle",
"tokenize.ENDMARKER: raise SyntaxError('BangExpr continuation at program end') line = ctkn.line.rstrip('\\r\\n')",
"# handle as single quoted ], flags=re.X) def scan_dqs(self, code:",
"('op',) def __init__(self, op): self.op = op def __repr__(self): return",
"r' ls foo${bar} ' >> expr expr<' ls foo${bar} '",
"bar = 10 print('::BangExpr::') be = BangExpr('ls', BangSeq('foo', bar, BangGlob('.*')),",
"as single quoted ], flags=re.X) def scan_dqs(self, code: str, offset=0)",
"from parse_bangexpr(' '.join(lines)).split('\\n') from io import StringIO code = r'''",
"= line.endswith('\\\\') last_bang_line = ctkn.start[0] assert not bangexpr, bangexpr def",
"next(lexer, None) if tkn and tkn.type != BangTokenType.OP: if tkn.type",
"at program end') line = ctkn.line.rstrip('\\r\\n') bangexpr.append(line) bangcont = line.endswith('\\\\')",
"we can simplify the parsing tokens.append(('END', '', (len(code),len(code)))) last_token =",
"import Enum import pysh from pysh.path import PathWrapper, Path from",
"= lambda s: \"'{}'\".format(s.replace(\"\\\\\", \"\\\\\\\\\").replace(\"'\", \"\\\\'\")) lexer = BangLexer().scan(code) seq",
"elif tkn.type == BangTokenType.OPAQUE: seq.append('{}'.format(as_str(tkn.value))) elif tkn.type == BangTokenType.GLOB: seq.append('pysh.BangGlob({})'.format(as_str(tkn.value)))",
"ls foo${bar}.* \\ | grep foo > /dev/null foo =",
"evaluated lines[0] = lines[0][1:] code = '\\n'.join(lines) code = code.strip().replace(\"'\",",
"= ctkn.start[1] prebang = ctkn.line[0:col] line = ctkn.line[col+1:].lstrip(' \\t').rstrip('\\r\\n') bangexpr.append(line.rstrip('\\\\'))",
"return re.Scanner([ (r'\\\\.', t('ESCAPE')), (r'\\$[A-Za-z_][A-Za-z0-9_]*', t('VAR', lambda v: v[1:])), (r'\\${(",
"glob def __repr__(self): return 'BangGlob<{}>'.format(self.glob) class BangExpr: __slots__ = ('args',",
"callback that can report back the transformation. Returns a generator",
"val, pos in tokens: yield tkn, val, (offset+pos[0], offset+pos[1]) def",
"'OP' and last_token and last_token == 'WS': yield BangToken(BangTokenType.OP, '",
"operands left!' if arg.op == '|': cmd |= self.eval_command(mut_args) elif",
"(r'[^\\\\\\$]+', t('SQS')) # handle as single quoted ], flags=re.X) def",
"if value.isupper(): yield BangToken(BangTokenType.ENV, value, pos) else: yield BangToken(BangTokenType.LOCAL, value,",
"return PathWrapper().glob(expr.glob) else: return str(expr) def eval_seq(self, seq: BangSeq) ->",
"= exprs.popleft() if isinstance(expr, BangGlob): if exprs: raise RuntimeError('Globbing can",
"\"\"\" Scans python code to transform bang expressions. Given some",
"token, pos class BangEnv: __slots__ = ('name',) def __init__(self, name):",
"'EXPR' value = re.sub(r'\\\\(.)', r'\\1', value) yield BangToken(BangTokenType.EXPR, value, pos)",
"not None assert globals is not None self.args = args",
"Callable, Iterator, Tuple, NamedTuple, Deque, Union, Any TBangTransformer = Callable[",
"(r'\\$[A-Za-z_][A-Za-z0-9_]*', t('VAR', lambda v: v[1:])), (r'\\${( \\\\. | [^\\\\}]+ )+}',",
"else: return str(expr) def eval_seq(self, seq: BangSeq) -> Union[str, Iterator[Path]]:",
"code): self.code = code def eval(self): #TODO: Detect shebang and",
"code def eval(self): #TODO: Detect shebang and use it instead",
"command('grep') bar = 10 print('::BangExpr::') be = BangExpr('ls', BangSeq('foo', bar,",
"for ctkn in tokens: if ctkn.type == tokenize.INDENT: indent +=",
"else: raise RuntimeError('Unsupported operator {}'.format(arg.op)) return cmd def __str__(self): return",
"= ctkn if bangexpr: continue if ctkn.string == '!': col",
"simplify the parsing tokens.append(('END', '', (len(code),len(code)))) last_token = last_pos =",
"if len(seq) > 1: exprs.append('pysh.BangSeq({})'.format(', '.join(seq))) else: exprs.append(seq[0]) seq =",
"<= len(bangexpr) if lines and prebang: lines[0] = prebang +",
"str(self.eval()) def __repr__(self): return 'BangBang<{}>'.format(self.code) def parse_bangexpr(code: str) -> str:",
"= code.strip().replace(\"'\", \"\\\\'\").replace(\"\\\\\", \"\\\\\\\\\") code = \"pysh.BangBang('{}')\".format(code) lines = code.split('\\n')",
"last_bang_line = ctkn.start[0] elif bangexpr: lines = list(transformer(bangexpr)) assert len(lines)",
"__init__(self, *args, locals=None, globals=None): assert locals is not None assert",
"return cmd def __str__(self): return str(self.eval()) def __repr__(self): return 'BangExpr<{!r}>'.format(self.args)",
"result.returncode > 0: if result.stdout: print(result.stdout) raise pysh.ExitStatusError(result.returncode) return result.stdout",
"Iterator, Tuple, NamedTuple, Deque, Union, Any TBangTransformer = Callable[ [List[str]],",
"yield BangToken(BangTokenType.OP, value, pos) else: if token == 'OPAQUE': if",
"#TODO: Detect shebang and use it instead of default shell",
"print(result.stdout) raise pysh.ExitStatusError(result.returncode) return result.stdout def __str__(self): return str(self.eval()) def",
"re import tokenize import os from collections import deque, ChainMap",
"yield from self.scan_dqs(val, offset=pos[0]+1) else: yield tkn, val, pos def",
"if tkn.type in (BangTokenType.LOCAL, BangTokenType.EXPR): seq.append(tkn.value) elif tkn.type == BangTokenType.ENV:",
"== tokenize.DEDENT: indent -= 1 if bang_indent > indent: bang_indent",
"lines[0][1:] code = '\\n'.join(lines) code = code.strip().replace(\"'\", \"\\\\'\").replace(\"\\\\\", \"\\\\\\\\\") code",
"deque, ChainMap from functools import lru_cache from enum import Enum",
"this to be global def build_scanner(self): t = self._tokener return",
"def eval(self): #TODO: Detect shebang and use it instead of",
"that can report back the transformation. Returns a generator that",
"0, 'No operands left!' if arg.op == '|': cmd |=",
"and process them with a callback that can report back",
"last_token, last_pos = token, pos class BangEnv: __slots__ = ('name',)",
"BangOp), 'Expected OP but found: {}'.format(arg) assert len(mut_args) > 0,",
"line by line. \"\"\" tokens = tokenize.generate_tokens(code.readline) bangexpr = []",
"ChainMap from functools import lru_cache from enum import Enum import",
"-> Iterator[TBangLexerToken]: tokens, remaining = self.build_scanner().scan(code) if remaining: raise SyntaxError('Unexpected",
"pos) else: if token == 'OPAQUE': if re.search(r'(?!<\\\\)[~*?{]', value): yield",
"return 'BangGlob<{}>'.format(self.glob) class BangExpr: __slots__ = ('args', 'vars') def __init__(self,",
"use it instead of default shell import sys, subprocess result",
"10 print('::BangExpr::') be = BangExpr('ls', BangSeq('foo', bar, BangGlob('.*')), BangOp(\"|\"), 'grep',",
"'END'): continue elif token == 'WS': pass elif token ==",
"remaining: raise SyntaxError('Unexpected char <{}> at position {}'.format(remaining[0], len(code)-len(remaining))) for",
"from io import StringIO import re import tokenize import os",
"raise pysh.ExitStatusError(result.returncode) return result.stdout def __str__(self): return str(self.eval()) def __repr__(self):",
"= ChainMap(locals, globals) def eval_command(self, mut_args): arg = mut_args.popleft() cmd",
"= line.endswith('\\\\') last_bang_line = ctkn.start[0] elif bangexpr: lines = list(transformer(bangexpr))",
"yield from lines bangexpr = [] last_bang_line = ptkn.start[0] else:",
"use the lexical information to detect when we're on a",
"name def __repr__(self): return 'BangEnv<{}>'.format(self.name) class BangSeq: __slots__ = ('items',)",
"self.op = op def __repr__(self): return 'BangOp<{}>'.format(self.op) class BangGlob: __slots__",
"tkn = next(lexer, None) if tkn and tkn.type != BangTokenType.OP:",
"Tuple[str, str, Tuple[int,int]] class BangLexer: def _tokener(self, token, transformer=lambda x:",
"them on env when evaluated lines[0] = lines[0][1:] code =",
"v): v = transformer(v, **kwargs) return None if v is",
"raise SyntaxError('Unexpected char at position {}'.format(len(code)-len(remaining))) # Add a terminating",
"BangToken(BangTokenType.OP, ' ', last_pos) if token in ('COMMENT', 'END'): continue",
"= 'GLOB' LOCAL = 'LOCAL' ENV = 'ENV' EXPR =",
"in tokens: if ctkn.type == tokenize.INDENT: indent += 1 if",
"LOCAL = 'LOCAL' ENV = 'ENV' EXPR = 'EXPR' OP",
"foo${bar}.* \\ | grep foo > /dev/null foo = r'",
"BangTokenType.OP if tkn.value == ' ': continue exprs.append('pysh.BangOp(\"{}\")'.format(tkn.value)) # We",
"or bang_indent == indent: if ctkn.type is tokenize.ENDMARKER: raise SyntaxError('BangExpr",
"= ptkn.start[0] else: yield ptkn.line ptkn = ctkn if bangexpr:",
"Tuple[int,int]] class BangLexer: def _tokener(self, token, transformer=lambda x: x, **kwargs):",
"Split double quoted strings into parts \"\"\" for tkn, val,",
"yield BangToken(BangTokenType.OPAQUE, value, pos) elif token in ('ESCAPE', 'SQS'): #TODO:",
"(r'\\\\.', t('ESCAPE')), (r'\\$[A-Za-z_][A-Za-z0-9_]*', t('VAR', lambda v: v[1:])), (r'\\${( \\\\. |",
"= self.build_scanner().scan(code) if remaining: raise SyntaxError('Unexpected char at position {}'.format(len(code)-len(remaining)))",
"bang_indent = -100 last_bang_line = -100 for ctkn in tokens:",
"val, pos def scan(self, code: str) -> Iterator[BangToken]: tokens, remaining",
"and prebang: lines[0] = prebang + lines[0] yield from lines",
"a seq') return PathWrapper(accum).glob(expr.glob) accum += self.eval_expr(expr) return accum def",
"from self.scan_dqs(val, offset=pos[0]+1) else: yield tkn, val, pos def scan(self,",
"return str(expr) def eval_seq(self, seq: BangSeq) -> Union[str, Iterator[Path]]: exprs:",
"= 'LOCAL' ENV = 'ENV' EXPR = 'EXPR' OP =",
"', last_pos) if token in ('COMMENT', 'END'): continue elif token",
"\"\\\\'\")) lexer = BangLexer().scan(code) seq = [] exprs = []",
"token in ('COMMENT', 'END'): continue elif token == 'WS': pass",
"but found: {}'.format(arg) assert len(mut_args) > 0, 'No operands left!'",
"text ls .* ''' for line in transform(StringIO(code), transformer): print(line.rstrip('\\n'))",
"stderr=subprocess.PIPE) if result.stderr: print(result.stderr, file=sys.stderr) if result.returncode > 0: if",
"lines = list(transformer(bangexpr)) assert len(lines) <= len(bangexpr) if lines and",
"eval(self): mut_args = deque(self.args) cmd = self.eval_command(mut_args) while mut_args: arg",
"Tuple, NamedTuple, Deque, Union, Any TBangTransformer = Callable[ [List[str]], Iterator[str]]",
"'BangSeq', 'BangGlob', 'BangEnv', 'BangBang'] class BangTokenType(Enum): OPAQUE = 'OPAQUE' GLOB",
"' ': continue exprs.append('pysh.BangOp(\"{}\")'.format(tkn.value)) # We need to provide locals/globals",
"> /dev/null foo = r' ls foo${bar} ' >> expr",
"= ('code',) def __init__(self, code): self.code = code def eval(self):",
"(r'\\s+', t('WS')), ], flags=re.X) @lru_cache() def build_dqs_scanner(self): t = self._tokener",
"'BangGlob<{}>'.format(self.glob) class BangExpr: __slots__ = ('args', 'vars') def __init__(self, *args,",
"v: v[2:-1])), (r'[|<>^]+', t('OP')), (r'[A-Za-z0-9_%*+:.,=/@~\\[\\]{}-]+', t('OPAQUE')), (r'\\s+', t('WS')), ], flags=re.X)",
"self.eval_command(mut_args) elif arg.op == '^': cmd ^= self.eval_command(mut_args) elif arg.op",
"t = self._tokener return re.Scanner([ (r'\\\\.', t('ESCAPE')), (r'\\$[A-Za-z_][A-Za-z0-9_]*', t('VAR', lambda",
"the lexical information to detect when we're on a new",
"assert False, 'unexpected {}, what happened?'.format(token) last_token, last_pos = token,",
"return PathWrapper(accum).glob(expr.glob) accum += self.eval_expr(expr) return accum def eval(self): mut_args",
"import sys, subprocess result = subprocess.run( ['bash', '-c', self.code], encoding='utf-8',",
"char <{}> at position {}'.format(remaining[0], len(code)-len(remaining))) for tkn, val, pos",
"strings into parts \"\"\" for tkn, val, pos in tokens:",
"exprs.append('pysh.BangOp(\"{}\")'.format(tkn.value)) # We need to provide locals/globals so we can",
"break assert tkn.type == BangTokenType.OP if tkn.value == ' ':",
"typing import List, Callable, Iterator, Tuple, NamedTuple, Deque, Union, Any",
"if result.stderr: print(result.stderr, file=sys.stderr) if result.returncode > 0: if result.stdout:",
"def __init__(self, name): self.name = name def __repr__(self): return 'BangEnv<{}>'.format(self.name)",
"accum = '' while exprs: expr = exprs.popleft() if isinstance(expr,",
"[^\\\\}]+ )+}', t('EXPR', lambda v: v[2:-1])), (r'[|<>^]+', t('OP')), (r'[A-Za-z0-9_%*+:.,=/@~\\[\\]{}-]+', t('OPAQUE')),",
"= self.vars.get(str(arg)) if cmd is None: raise RuntimeError('Unable to find",
"tkn.type != BangTokenType.OP: if tkn.type in (BangTokenType.LOCAL, BangTokenType.EXPR): seq.append(tkn.value) elif",
"we can resolve commands to variables return 'pysh.BangExpr({}, locals=locals(), globals=globals())'.format(',",
"scan(self, code: str) -> Iterator[BangToken]: tokens, remaining = self.build_scanner().scan(code) if",
"ptkn.start[0] else: yield ptkn.line ptkn = ctkn if bangexpr: continue",
"<{}> at position {}'.format(remaining[0], len(code)-len(remaining))) for tkn, val, pos in",
"= lines[0][1:] code = '\\n'.join(lines) code = code.strip().replace(\"'\", \"\\\\'\").replace(\"\\\\\", \"\\\\\\\\\")",
"tokenize import os from collections import deque, ChainMap from functools",
"mut_args.popleft() cmd = cmd(self.eval_expr(arg)) return cmd def eval_expr(self, expr: Any)",
"'BangSeq<{!r}>'.format(self.items) class BangOp: __slots__ = ('op',) def __init__(self, op): self.op",
"pos in self.demux_dqs(tokens): assert token != 'DQS' # double quoted",
"__repr__(self): return 'BangBang<{}>'.format(self.code) def parse_bangexpr(code: str) -> str: as_str =",
"import os from collections import deque, ChainMap from functools import",
"if isinstance(expr, BangGlob): if exprs: raise RuntimeError('Globbing can only occur",
"[] while True: tkn = next(lexer, None) if tkn and",
"= [] if not tkn: break assert tkn.type == BangTokenType.OP",
")+\"', t('DQS', lambda v: v[1:-1])), (r'\\$[A-Za-z_][A-Za-z0-9_]*', t('VAR', lambda v: v[1:])),",
"tkn.type == BangTokenType.OP if tkn.value == ' ': continue exprs.append('pysh.BangOp(\"{}\")'.format(tkn.value))",
"transformer(v, **kwargs) return None if v is None else (token,",
"= self._tokener return re.Scanner([ (r'\\\\.', t('ESCAPE')), (r'\\$[A-Za-z_][A-Za-z0-9_]*', t('VAR', lambda v:",
"if isinstance(mut_args[0], BangOp): break arg = mut_args.popleft() cmd = cmd(self.eval_expr(arg))",
"(r'\\${( \\\\. | [^\\\\}]+ )+}', t('EXPR', lambda v: v[2:-1])), (r'[|<>^]+',",
"'OP' class BangToken(NamedTuple): type: BangTokenType value: str span: Tuple[int, int]",
"^= self.eval_command(mut_args) elif arg.op == '>': cmd = cmd >",
"value = value.strip() if value.isalnum() and not value.isdigit(): if value.isupper():",
"__repr__(self): return 'BangExpr<{!r}>'.format(self.args) class BangBang: __slots__ = ('code',) def __init__(self,",
"Detect $ident to expose them on env when evaluated lines[0]",
"generator that allows to consume the transformed code line by",
"locals are solved with inspect.frame.f_locals sh << r''' # <<",
"= [] # type: List[str] bangcont = False prebang =",
"'^': cmd ^= self.eval_command(mut_args) elif arg.op == '>': cmd =",
"last_token and last_token == 'WS': yield BangToken(BangTokenType.OP, ' ', last_pos)",
"'WS': yield BangToken(BangTokenType.OP, ' ', last_pos) if token in ('COMMENT',",
"expressions and process them with a callback that can report",
"globals) def eval_command(self, mut_args): arg = mut_args.popleft() cmd = self.vars.get(str(arg))",
"on NEWLINE tokens, instead we have # use the lexical",
"return 'BangEnv<{}>'.format(self.name) class BangSeq: __slots__ = ('items',) def __init__(self, *items):",
"x, **kwargs): def cb(s, v): v = transformer(v, **kwargs) return",
"detect when we're on a new line #TODO: Support indent/dedent",
"from pysh.command import command ls = command('ls') grep = command('grep')",
"def scan(self, code: str) -> Iterator[BangToken]: tokens, remaining = self.build_scanner().scan(code)",
"result.stdout def __str__(self): return str(self.eval()) def __repr__(self): return 'BangBang<{}>'.format(self.code) def",
"if ctkn.type == tokenize.INDENT: indent += 1 if last_bang_line +",
"from pysh.path import PathWrapper, Path from typing import List, Callable,",
"offset=0) -> Iterator[TBangLexerToken]: tokens, remaining = self.build_scanner().scan(code) if remaining: raise",
"arg.op == '^': cmd ^= self.eval_command(mut_args) elif arg.op == '>':",
"pos) elif token in ('ESCAPE', 'SQS'): #TODO: handle special escapes",
"GLOB = 'GLOB' LOCAL = 'LOCAL' ENV = 'ENV' EXPR",
"is None: raise RuntimeError('Unable to find {}'.format(arg)) while mut_args: if",
"instead of default shell import sys, subprocess result = subprocess.run(",
"line.endswith('\\\\') last_bang_line = ctkn.start[0] assert not bangexpr, bangexpr def transformer(lines:",
"v[1:])), (r'\\\\.', t('ESCAPE')), (r\"'( \\\\. | [^\\\\']+ )+'\", t('SQS', lambda",
"Iterator[TBangLexerToken]: \"\"\" Split double quoted strings into parts \"\"\" for",
"of a seq') return PathWrapper(accum).glob(expr.glob) accum += self.eval_expr(expr) return accum",
"into parts \"\"\" for tkn, val, pos in tokens: if",
"remaining = self.build_scanner().scan(code) if remaining: raise SyntaxError('Unexpected char at position",
"None for token, value, pos in self.demux_dqs(tokens): assert token !=",
"BangToken(BangTokenType.ENV, value, pos) else: yield BangToken(BangTokenType.LOCAL, value, pos) else: assert",
"value.strip() yield BangToken(BangTokenType.OP, value, pos) else: if token == 'OPAQUE':",
"build_scanner(self): t = self._tokener return re.Scanner([ (r'\\#.+', t('COMMENT', lambda v:",
"\"\\\\'\").replace(\"\\\\\", \"\\\\\\\\\") code = \"pysh.BangBang('{}')\".format(code) lines = code.split('\\n') for line",
"['BangExpr', 'BangOp', 'BangSeq', 'BangGlob', 'BangEnv', 'BangBang'] class BangTokenType(Enum): OPAQUE =",
"StringIO, transformer: TBangTransformer) -> Iterator[str]: \"\"\" Scans python code to",
"for tkn, val, pos in tokens: if tkn == 'DQS':",
"v is None else (token, v, (s.match.start(), s.match.end())) return cb",
"\\ | grep foo > /dev/null foo = r' ls",
"if token != 'OP' and last_token and last_token == 'WS':",
"continue if ctkn.string == '!': col = ctkn.start[1] prebang =",
"t('SQS')) # handle as single quoted ], flags=re.X) def scan_dqs(self,",
"globals=globals())'.format(', '.join(exprs)) def transform(code: StringIO, transformer: TBangTransformer) -> Iterator[str]: \"\"\"",
"if bangexpr: continue if ctkn.string == '!': col = ctkn.start[1]",
"and tkn.type != BangTokenType.OP: if tkn.type in (BangTokenType.LOCAL, BangTokenType.EXPR): seq.append(tkn.value)",
"# Inject whitespace operator if needed if token != 'OP'",
"Iterator[Path]]: if isinstance(expr, BangSeq): return self.eval_seq(expr) elif isinstance(expr, BangEnv): return",
"tokenize.INDENT: indent += 1 if last_bang_line + 1 == ctkn.start[0]:",
"# Add a terminating token so we can simplify the",
"functools import lru_cache from enum import Enum import pysh from",
"= r' ls foo${bar} ' >> expr expr<' ls foo${bar}",
"intended for this to be global def build_scanner(self): t =",
"bangexpr def transformer(lines: List[str]) -> Iterator[str]: if lines[0].startswith('!'): #TODO: Detect",
"mut_args: if isinstance(mut_args[0], BangOp): break arg = mut_args.popleft() cmd =",
"None if v is None else (token, v, (s.match.start(), s.match.end()))",
"assert len(lines) <= len(bangexpr) if lines and prebang: lines[0] =",
"code.strip().replace(\"'\", \"\\\\'\").replace(\"\\\\\", \"\\\\\\\\\") code = \"pysh.BangBang('{}')\".format(code) lines = code.split('\\n') for",
"'-c', self.code], encoding='utf-8', stdout=subprocess.PIPE, stderr=subprocess.PIPE) if result.stderr: print(result.stderr, file=sys.stderr) if",
"bang expressions and process them with a callback that can",
"# type: List[str] bangcont = False prebang = None ptkn",
"commands to variables return 'pysh.BangExpr({}, locals=locals(), globals=globals())'.format(', '.join(exprs)) def transform(code:",
"tkn, val, pos in tokens: yield tkn, val, (offset+pos[0], offset+pos[1])",
"value, pos) else: yield BangToken(BangTokenType.OPAQUE, value, pos) elif token in",
"code to transform bang expressions. Given some python code it",
"== '!': col = ctkn.start[1] prebang = ctkn.line[0:col] line =",
"''' for line in transform(StringIO(code), transformer): print(line.rstrip('\\n')) from pysh.command import",
"[^\\\\\"]+ )+\"', t('DQS', lambda v: v[1:-1])), (r'\\$[A-Za-z_][A-Za-z0-9_]*', t('VAR', lambda v:",
"= cmd(self.eval_expr(arg)) return cmd def eval_expr(self, expr: Any) -> Union[str,",
"print('::BangExpr::') be = BangExpr('ls', BangSeq('foo', bar, BangGlob('.*')), BangOp(\"|\"), 'grep', 'foo',",
"List[str] bangcont = False prebang = None ptkn = None",
"== '>>': cmd = cmd >> self.eval_expr(mut_args.popleft()) else: raise RuntimeError('Unsupported",
"variables return 'pysh.BangExpr({}, locals=locals(), globals=globals())'.format(', '.join(exprs)) def transform(code: StringIO, transformer:",
"python code it will extract bang expressions and process them",
"BangToken(BangTokenType.EXPR, value, pos) else: assert False, 'unexpected {}, what happened?'.format(token)",
"# < is plain text ls .* ''' for line",
"lru_cache from enum import Enum import pysh from pysh.path import",
"if result.stdout: print(result.stdout) raise pysh.ExitStatusError(result.returncode) return result.stdout def __str__(self): return",
"Support indent/dedent for multiline if ptkn and ctkn.start[0] > ptkn.start[0]:",
"not bangexpr, bangexpr def transformer(lines: List[str]) -> Iterator[str]: if lines[0].startswith('!'):",
"return os.environ[expr.name] elif isinstance(expr, BangGlob): return PathWrapper().glob(expr.glob) else: return str(expr)",
"probably better solved with: # locals are solved with inspect.frame.f_locals",
"!= 'OP' and last_token and last_token == 'WS': yield BangToken(BangTokenType.OP,",
"'BangOp', 'BangSeq', 'BangGlob', 'BangEnv', 'BangBang'] class BangTokenType(Enum): OPAQUE = 'OPAQUE'",
"= self.build_scanner().scan(code) if remaining: raise SyntaxError('Unexpected char <{}> at position",
"= None for token, value, pos in self.demux_dqs(tokens): assert token",
"== 'OP': value = value.strip() yield BangToken(BangTokenType.OP, value, pos) else:",
"last_token = last_pos = None for token, value, pos in",
"end') line = ctkn.line.rstrip('\\r\\n') bangexpr.append(line) bangcont = line.endswith('\\\\') last_bang_line =",
"'vars') def __init__(self, *args, locals=None, globals=None): assert locals is not",
"'BangBang<{}>'.format(self.code) def parse_bangexpr(code: str) -> str: as_str = lambda s:",
"r'\\1', value) yield BangToken(BangTokenType.OPAQUE, value, pos) elif token in ('VAR',",
"a new line #TODO: Support indent/dedent for multiline if ptkn",
"BangSeq('foo', bar, BangGlob('.*')), BangOp(\"|\"), 'grep', 'foo', 'baz', BangOp(\">\"), '/dev/null', locals=locals(),",
"what happened?'.format(token) last_token, last_pos = token, pos class BangEnv: __slots__",
"assert tkn.type == BangTokenType.OP if tkn.value == ' ': continue",
"-= 1 if bang_indent > indent: bang_indent = -100 #",
"eval(self): #TODO: Detect shebang and use it instead of default",
"cmd |= self.eval_command(mut_args) elif arg.op == '^': cmd ^= self.eval_command(mut_args)",
"__init__(self, op): self.op = op def __repr__(self): return 'BangOp<{}>'.format(self.op) class",
"== 'EXPR' value = re.sub(r'\\\\(.)', r'\\1', value) yield BangToken(BangTokenType.EXPR, value,",
"def build_dqs_scanner(self): t = self._tokener return re.Scanner([ (r'\\\\.', t('ESCAPE')), (r'\\$[A-Za-z_][A-Za-z0-9_]*',",
"value, pos) else: yield BangToken(BangTokenType.LOCAL, value, pos) else: assert token",
"**kwargs): def cb(s, v): v = transformer(v, **kwargs) return None",
"parse_bangexpr(code: str) -> str: as_str = lambda s: \"'{}'\".format(s.replace(\"\\\\\", \"\\\\\\\\\").replace(\"'\",",
"prebang: lines[0] = prebang + lines[0] yield from lines bangexpr",
"arg = mut_args.popleft() cmd = cmd(self.eval_expr(arg)) return cmd def eval_expr(self,",
"arg.op == '>': cmd = cmd > self.eval_expr(mut_args.popleft()) elif arg.op",
"value = re.sub(r'\\\\(.)', r'\\1', value) yield BangToken(BangTokenType.EXPR, value, pos) else:",
"pass elif token == 'OP': value = value.strip() yield BangToken(BangTokenType.OP,",
"args self.vars = ChainMap(locals, globals) def eval_command(self, mut_args): arg =",
"ctkn.start[0] assert not bangexpr, bangexpr def transformer(lines: List[str]) -> Iterator[str]:",
"process them with a callback that can report back the",
"str(expr) def eval_seq(self, seq: BangSeq) -> Union[str, Iterator[Path]]: exprs: Deque[Any]",
"BangTokenType.ENV: seq.append('pysh.BangEnv({})'.format(as_str(tkn.value))) elif tkn.type == BangTokenType.OPAQUE: seq.append('{}'.format(as_str(tkn.value))) elif tkn.type ==",
"indent -= 1 if bang_indent > indent: bang_indent = -100",
"we can't rely on NEWLINE tokens, instead we have #",
"== 'OPAQUE': if re.search(r'(?!<\\\\)[~*?{]', value): yield BangToken(BangTokenType.GLOB, value, pos) else:",
"and last_token and last_token == 'WS': yield BangToken(BangTokenType.OP, ' ',",
"None: raise RuntimeError('Unable to find {}'.format(arg)) while mut_args: if isinstance(mut_args[0],",
"if cmd is None: raise RuntimeError('Unable to find {}'.format(arg)) while",
"transformer=lambda x: x, **kwargs): def cb(s, v): v = transformer(v,",
"\"\"\" for tkn, val, pos in tokens: if tkn ==",
"value, pos) else: assert False, 'unexpected {}, what happened?'.format(token) last_token,",
"-> str: as_str = lambda s: \"'{}'\".format(s.replace(\"\\\\\", \"\\\\\\\\\").replace(\"'\", \"\\\\'\")) lexer",
"accum += self.eval_expr(expr) return accum def eval(self): mut_args = deque(self.args)",
"Given some python code it will extract bang expressions and",
"locals=locals(), globals=globals())'.format(', '.join(exprs)) def transform(code: StringIO, transformer: TBangTransformer) -> Iterator[str]:",
"value, pos) else: assert token == 'EXPR' value = re.sub(r'\\\\(.)',",
"'' while exprs: expr = exprs.popleft() if isinstance(expr, BangGlob): if",
"bangexpr: continue if ctkn.string == '!': col = ctkn.start[1] prebang",
"extract bang expressions and process them with a callback that",
"= False prebang = None ptkn = None indent =",
"indent elif ctkn.type == tokenize.DEDENT: indent -= 1 if bang_indent",
"(offset+pos[0], offset+pos[1]) def demux_dqs(self, tokens: Iterator[TBangLexerToken]) -> Iterator[TBangLexerToken]: \"\"\" Split",
"lines bangexpr = [] last_bang_line = ptkn.start[0] else: yield ptkn.line",
"\"\\\\\\\\\").replace(\"'\", \"\\\\'\")) lexer = BangLexer().scan(code) seq = [] exprs =",
"str(self.eval()) def __repr__(self): return 'BangExpr<{!r}>'.format(self.args) class BangBang: __slots__ = ('code',)",
"+ lines[0] yield from lines bangexpr = [] last_bang_line =",
"'EXPR'): value = value.strip() if value.isalnum() and not value.isdigit(): if",
"{}'.format(len(code)-len(remaining))) # Add a terminating token so we can simplify",
"'OPAQUE' GLOB = 'GLOB' LOCAL = 'LOCAL' ENV = 'ENV'",
"token == 'OPAQUE': if re.search(r'(?!<\\\\)[~*?{]', value): yield BangToken(BangTokenType.GLOB, value, pos)",
"\\\\. | [^\\\\']+ )+'\", t('SQS', lambda v: v[1:-1])), (r'\"( \\\\.",
"if token in ('COMMENT', 'END'): continue elif token == 'WS':",
"cmd = cmd(self.eval_expr(arg)) return cmd def eval_expr(self, expr: Any) ->",
"' ', last_pos) if token in ('COMMENT', 'END'): continue elif",
"a generator that allows to consume the transformed code line",
"v, (s.match.start(), s.match.end())) return cb @lru_cache() # it's intended for",
"mut_args.popleft() cmd = self.vars.get(str(arg)) if cmd is None: raise RuntimeError('Unable",
"ctkn in tokens: if ctkn.type == tokenize.INDENT: indent += 1",
"v: v[1:-1])), (r'\"( \\\\. | [^\\\\\"]+ )+\"', t('DQS', lambda v:",
"globals=None): assert locals is not None assert globals is not",
"BangTokenType value: str span: Tuple[int, int] TBangLexerToken = Tuple[str, str,",
"locals is not None assert globals is not None self.args",
"t('SQS', lambda v: v[1:-1])), (r'\"( \\\\. | [^\\\\\"]+ )+\"', t('DQS',",
"accum def eval(self): mut_args = deque(self.args) cmd = self.eval_command(mut_args) while",
"v[2:-1])), (r'[|<>^]+', t('OP')), (r'[A-Za-z0-9_%*+:.,=/@~\\[\\]{}-]+', t('OPAQUE')), (r'\\s+', t('WS')), ], flags=re.X) @lru_cache()",
"from enum import Enum import pysh from pysh.path import PathWrapper,",
"transformer: TBangTransformer) -> Iterator[str]: \"\"\" Scans python code to transform",
"not value.isdigit(): if value.isupper(): yield BangToken(BangTokenType.ENV, value, pos) else: yield",
"tkn and tkn.type != BangTokenType.OP: if tkn.type in (BangTokenType.LOCAL, BangTokenType.EXPR):",
"lines = code.split('\\n') for line in lines: yield line else:",
"lines[0].startswith('!'): #TODO: Detect $ident to expose them on env when",
"= 'OP' class BangToken(NamedTuple): type: BangTokenType value: str span: Tuple[int,",
"indent: bang_indent = -100 # due to continuations we can't",
"None self.args = args self.vars = ChainMap(locals, globals) def eval_command(self,",
"self.build_scanner().scan(code) if remaining: raise SyntaxError('Unexpected char at position {}'.format(len(code)-len(remaining))) #",
"glob): self.glob = glob def __repr__(self): return 'BangGlob<{}>'.format(self.glob) class BangExpr:",
"return self.eval_seq(expr) elif isinstance(expr, BangEnv): return os.environ[expr.name] elif isinstance(expr, BangGlob):",
"= ('name',) def __init__(self, name): self.name = name def __repr__(self):",
"cmd = self.vars.get(str(arg)) if cmd is None: raise RuntimeError('Unable to",
"= [] exprs = [] while True: tkn = next(lexer,",
"elif arg.op == '>': cmd = cmd > self.eval_expr(mut_args.popleft()) elif",
"are solved with inspect.frame.f_locals sh << r''' # << means",
"def transformer(lines: List[str]) -> Iterator[str]: if lines[0].startswith('!'): #TODO: Detect $ident",
"('name',) def __init__(self, name): self.name = name def __repr__(self): return",
"1 == ctkn.start[0]: bang_indent = indent elif ctkn.type == tokenize.DEDENT:",
"indent: if ctkn.type is tokenize.ENDMARKER: raise SyntaxError('BangExpr continuation at program",
"'>': cmd = cmd > self.eval_expr(mut_args.popleft()) elif arg.op == '>>':",
"'!': col = ctkn.start[1] prebang = ctkn.line[0:col] line = ctkn.line[col+1:].lstrip('",
"import StringIO code = r''' foo = ! ls foo${bar}.*",
"self.eval_seq(expr) elif isinstance(expr, BangEnv): return os.environ[expr.name] elif isinstance(expr, BangGlob): return",
"ctkn.string == '!': col = ctkn.start[1] prebang = ctkn.line[0:col] line",
"type: BangTokenType value: str span: Tuple[int, int] TBangLexerToken = Tuple[str,",
"return str(self.eval()) def __repr__(self): return 'BangExpr<{!r}>'.format(self.args) class BangBang: __slots__ =",
"if tkn.value == ' ': continue exprs.append('pysh.BangOp(\"{}\")'.format(tkn.value)) # We need",
"List, Callable, Iterator, Tuple, NamedTuple, Deque, Union, Any TBangTransformer =",
"demux_dqs(self, tokens: Iterator[TBangLexerToken]) -> Iterator[TBangLexerToken]: \"\"\" Split double quoted strings",
"line else: yield from parse_bangexpr(' '.join(lines)).split('\\n') from io import StringIO",
"global def build_scanner(self): t = self._tokener return re.Scanner([ (r'\\#.+', t('COMMENT',",
"# due to continuations we can't rely on NEWLINE tokens,",
"#!/bin/fish ls .* '''.strip() #TODO: !! is probably better solved",
"self.build_scanner().scan(code) if remaining: raise SyntaxError('Unexpected char <{}> at position {}'.format(remaining[0],",
"else: yield ptkn.line ptkn = ctkn if bangexpr: continue if",
"= value.strip() if value.isalnum() and not value.isdigit(): if value.isupper(): yield",
"v: v[1:-1])), (r'\\$[A-Za-z_][A-Za-z0-9_]*', t('VAR', lambda v: v[1:])), (r'\\${( \\\\. |",
"runtime symbols __all__ = ['BangExpr', 'BangOp', 'BangSeq', 'BangGlob', 'BangEnv', 'BangBang']",
"seq.append('pysh.BangEnv({})'.format(as_str(tkn.value))) elif tkn.type == BangTokenType.OPAQUE: seq.append('{}'.format(as_str(tkn.value))) elif tkn.type == BangTokenType.GLOB:",
"**kwargs) return None if v is None else (token, v,",
"'|': cmd |= self.eval_command(mut_args) elif arg.op == '^': cmd ^=",
"('ESCAPE', 'SQS'): #TODO: handle special escapes \\n value = re.sub(r'\\\\(.)',",
"def eval_expr(self, expr: Any) -> Union[str, Iterator[Path]]: if isinstance(expr, BangSeq):",
"return cb @lru_cache() # it's intended for this to be",
"__slots__ = ('name',) def __init__(self, name): self.name = name def",
"program end') line = ctkn.line.rstrip('\\r\\n') bangexpr.append(line) bangcont = line.endswith('\\\\') last_bang_line",
"bangexpr = [] # type: List[str] bangcont = False prebang",
"line #TODO: Support indent/dedent for multiline if ptkn and ctkn.start[0]",
"t('DQS', lambda v: v[1:-1])), (r'\\$[A-Za-z_][A-Za-z0-9_]*', t('VAR', lambda v: v[1:])), (r'\\${(",
"seq.append('{}'.format(as_str(tkn.value))) elif tkn.type == BangTokenType.GLOB: seq.append('pysh.BangGlob({})'.format(as_str(tkn.value))) else: assert False, 'Unexpected",
")+}', t('EXPR', lambda v: v[2:-1])), (r'[|<>^]+', t('OP')), (r'[A-Za-z0-9_%*+:.,=/@~\\[\\]{}-]+', t('OPAQUE')), (r'\\s+',",
"False, 'unexpected {}, what happened?'.format(token) last_token, last_pos = token, pos",
"bang_indent > indent: bang_indent = -100 # due to continuations",
"bangexpr.append(line) bangcont = line.endswith('\\\\') last_bang_line = ctkn.start[0] elif bangexpr: lines",
"NamedTuple, Deque, Union, Any TBangTransformer = Callable[ [List[str]], Iterator[str]] #",
"name): self.name = name def __repr__(self): return 'BangEnv<{}>'.format(self.name) class BangSeq:",
"pos) else: yield BangToken(BangTokenType.OPAQUE, value, pos) elif token in ('ESCAPE',",
"if remaining: raise SyntaxError('Unexpected char at position {}'.format(len(code)-len(remaining))) # Add",
"import tokenize import os from collections import deque, ChainMap from",
"pysh.path import PathWrapper, Path from typing import List, Callable, Iterator,",
"value.isupper(): yield BangToken(BangTokenType.ENV, value, pos) else: yield BangToken(BangTokenType.LOCAL, value, pos)",
"command('ls') grep = command('grep') bar = 10 print('::BangExpr::') be =",
"with a callback that can report back the transformation. Returns",
"arg.op == '>>': cmd = cmd >> self.eval_expr(mut_args.popleft()) else: raise",
"= deque(self.args) cmd = self.eval_command(mut_args) while mut_args: arg = mut_args.popleft()",
"exprs.append('pysh.BangSeq({})'.format(', '.join(seq))) else: exprs.append(seq[0]) seq = [] if not tkn:",
"be global def build_scanner(self): t = self._tokener return re.Scanner([ (r'\\#.+',",
"= last_pos = None for token, value, pos in self.demux_dqs(tokens):",
"| [^\\\\\"]+ )+\"', t('DQS', lambda v: v[1:-1])), (r'\\$[A-Za-z_][A-Za-z0-9_]*', t('VAR', lambda",
"len(code)-len(remaining))) for tkn, val, pos in tokens: yield tkn, val,",
"\"'{}'\".format(s.replace(\"\\\\\", \"\\\\\\\\\").replace(\"'\", \"\\\\'\")) lexer = BangLexer().scan(code) seq = [] exprs",
"shell import sys, subprocess result = subprocess.run( ['bash', '-c', self.code],",
"mut_args): arg = mut_args.popleft() cmd = self.vars.get(str(arg)) if cmd is",
"last_bang_line = ptkn.start[0] else: yield ptkn.line ptkn = ctkn if",
"double quoted strings into parts \"\"\" for tkn, val, pos",
"val, (offset+pos[0], offset+pos[1]) def demux_dqs(self, tokens: Iterator[TBangLexerToken]) -> Iterator[TBangLexerToken]: \"\"\"",
"val, pos in tokens: if tkn == 'DQS': yield from",
"value): yield BangToken(BangTokenType.GLOB, value, pos) else: yield BangToken(BangTokenType.OPAQUE, value, pos)",
"last_bang_line + 1 == ctkn.start[0]: bang_indent = indent elif ctkn.type",
"= None ptkn = None indent = 0 bang_indent =",
"locals=locals(), globals=globals()) # print(be) print('::BangBang::') bb = BangBang('''#!/bin/bash ls *.py''')",
"continue if seq: if len(seq) > 1: exprs.append('pysh.BangSeq({})'.format(', '.join(seq))) else:",
"SyntaxError('Unexpected char at position {}'.format(len(code)-len(remaining))) # Add a terminating token",
"import lru_cache from enum import Enum import pysh from pysh.path",
"by line. \"\"\" tokens = tokenize.generate_tokens(code.readline) bangexpr = [] #",
"if result.returncode > 0: if result.stdout: print(result.stdout) raise pysh.ExitStatusError(result.returncode) return",
"while exprs: expr = exprs.popleft() if isinstance(expr, BangGlob): if exprs:",
"ls .* '''.strip() #TODO: !! is probably better solved with:",
"TBangTransformer = Callable[ [List[str]], Iterator[str]] # runtime symbols __all__ =",
"(r'[A-Za-z0-9_%*+:.,=/@~\\[\\]{}-]+', t('OPAQUE')), (r'\\s+', t('WS')), ], flags=re.X) @lru_cache() def build_dqs_scanner(self): t",
"== indent: if ctkn.type is tokenize.ENDMARKER: raise SyntaxError('BangExpr continuation at",
"'OPAQUE': if re.search(r'(?!<\\\\)[~*?{]', value): yield BangToken(BangTokenType.GLOB, value, pos) else: yield",
"t('EXPR', lambda v: v[2:-1])), (r'[|<>^]+', t('OP')), (r'[A-Za-z0-9_%*+:.,=/@~\\[\\]{}-]+', t('OPAQUE')), (r'\\s+', t('WS')),",
"tkn: break assert tkn.type == BangTokenType.OP if tkn.value == '",
"ctkn.type == tokenize.DEDENT: indent -= 1 if bang_indent > indent:",
"def __repr__(self): return 'BangSeq<{!r}>'.format(self.items) class BangOp: __slots__ = ('op',) def",
"BangExpr: __slots__ = ('args', 'vars') def __init__(self, *args, locals=None, globals=None):",
"'WS': pass elif token == 'OP': value = value.strip() yield",
"! ls foo${bar}.* \\ | grep foo > /dev/null foo",
"/dev/null foo = r' ls foo${bar} ' >> expr expr<'",
"def __repr__(self): return 'BangExpr<{!r}>'.format(self.args) class BangBang: __slots__ = ('code',) def",
"re.sub(r'\\\\(.)', r'\\1', value) yield BangToken(BangTokenType.OPAQUE, value, pos) elif token in",
"to expose them on env when evaluated lines[0] = lines[0][1:]",
"ptkn = ctkn if bangexpr: continue if ctkn.string == '!':",
"import pysh from pysh.path import PathWrapper, Path from typing import",
"return None if v is None else (token, v, (s.match.start(),",
"new line #TODO: Support indent/dedent for multiline if ptkn and",
"EXPR = 'EXPR' OP = 'OP' class BangToken(NamedTuple): type: BangTokenType",
"Union[str, Iterator[Path]]: exprs: Deque[Any] = deque(seq.items) accum = '' while",
"can resolve commands to variables return 'pysh.BangExpr({}, locals=locals(), globals=globals())'.format(', '.join(exprs))",
"line.endswith('\\\\') last_bang_line = ctkn.start[0] elif bangexpr: lines = list(transformer(bangexpr)) assert",
"== BangTokenType.ENV: seq.append('pysh.BangEnv({})'.format(as_str(tkn.value))) elif tkn.type == BangTokenType.OPAQUE: seq.append('{}'.format(as_str(tkn.value))) elif tkn.type",
"= list(transformer(bangexpr)) assert len(lines) <= len(bangexpr) if lines and prebang:",
"raise RuntimeError('Unable to find {}'.format(arg)) while mut_args: if isinstance(mut_args[0], BangOp):",
"bang_indent == indent: if ctkn.type is tokenize.ENDMARKER: raise SyntaxError('BangExpr continuation",
"def __repr__(self): return 'BangEnv<{}>'.format(self.name) class BangSeq: __slots__ = ('items',) def",
"None indent = 0 bang_indent = -100 last_bang_line = -100",
"BangOp(\">\"), '/dev/null', locals=locals(), globals=globals()) # print(be) print('::BangBang::') bb = BangBang('''#!/bin/bash",
"= self.eval_command(mut_args) while mut_args: arg = mut_args.popleft() assert isinstance(arg, BangOp),",
"'pysh.BangExpr({}, locals=locals(), globals=globals())'.format(', '.join(exprs)) def transform(code: StringIO, transformer: TBangTransformer) ->",
"bangcont or bang_indent == indent: if ctkn.type is tokenize.ENDMARKER: raise",
"found: {}'.format(arg) assert len(mut_args) > 0, 'No operands left!' if",
"elif arg.op == '^': cmd ^= self.eval_command(mut_args) elif arg.op ==",
"= ctkn.line[0:col] line = ctkn.line[col+1:].lstrip(' \\t').rstrip('\\r\\n') bangexpr.append(line.rstrip('\\\\')) bangcont = line.endswith('\\\\')",
"transform(code: StringIO, transformer: TBangTransformer) -> Iterator[str]: \"\"\" Scans python code",
"def _tokener(self, token, transformer=lambda x: x, **kwargs): def cb(s, v):",
"def scan_dqs(self, code: str, offset=0) -> Iterator[TBangLexerToken]: tokens, remaining =",
"Any) -> Union[str, Iterator[Path]]: if isinstance(expr, BangSeq): return self.eval_seq(expr) elif",
"= ctkn.line[col+1:].lstrip(' \\t').rstrip('\\r\\n') bangexpr.append(line.rstrip('\\\\')) bangcont = line.endswith('\\\\') last_bang_line = ctkn.start[0]",
"subprocess.run( ['bash', '-c', self.code], encoding='utf-8', stdout=subprocess.PIPE, stderr=subprocess.PIPE) if result.stderr: print(result.stderr,",
"seq.append('pysh.BangGlob({})'.format(as_str(tkn.value))) else: assert False, 'Unexpected token {}'.format(tkn.type) continue if seq:",
"so we can simplify the parsing tokens.append(('END', '', (len(code),len(code)))) last_token",
"the end of a seq') return PathWrapper(accum).glob(expr.glob) accum += self.eval_expr(expr)",
"= name def __repr__(self): return 'BangEnv<{}>'.format(self.name) class BangSeq: __slots__ =",
"handle special escapes \\n value = re.sub(r'\\\\(.)', r'\\1', value) yield",
"class BangBang: __slots__ = ('code',) def __init__(self, code): self.code =",
"globals=globals()) # print(be) print('::BangBang::') bb = BangBang('''#!/bin/bash ls *.py''') print(bb)",
"'No operands left!' if arg.op == '|': cmd |= self.eval_command(mut_args)",
"BangTokenType(Enum): OPAQUE = 'OPAQUE' GLOB = 'GLOB' LOCAL = 'LOCAL'",
"to find {}'.format(arg)) while mut_args: if isinstance(mut_args[0], BangOp): break arg",
"needed if token != 'OP' and last_token and last_token ==",
"exprs.popleft() if isinstance(expr, BangGlob): if exprs: raise RuntimeError('Globbing can only",
"#TODO: Detect $ident to expose them on env when evaluated",
"yield BangToken(BangTokenType.ENV, value, pos) else: yield BangToken(BangTokenType.LOCAL, value, pos) else:",
"== '|': cmd |= self.eval_command(mut_args) elif arg.op == '^': cmd",
"tokenize.generate_tokens(code.readline) bangexpr = [] # type: List[str] bangcont = False",
"else: yield BangToken(BangTokenType.LOCAL, value, pos) else: assert token == 'EXPR'",
"len(bangexpr) if lines and prebang: lines[0] = prebang + lines[0]",
"to continuations we can't rely on NEWLINE tokens, instead we",
"(s.match.start(), s.match.end())) return cb @lru_cache() # it's intended for this",
"Deque[Any] = deque(seq.items) accum = '' while exprs: expr =",
"expr expr<' ls foo${bar} ' !! #!/bin/fish ls .* '''.strip()",
"quoted strings into parts \"\"\" for tkn, val, pos in",
"a terminating token so we can simplify the parsing tokens.append(('END',",
"('glob',) def __init__(self, glob): self.glob = glob def __repr__(self): return",
"PathWrapper(accum).glob(expr.glob) accum += self.eval_expr(expr) return accum def eval(self): mut_args =",
"> indent: bang_indent = -100 # due to continuations we",
"import re import tokenize import os from collections import deque,",
"better solved with: # locals are solved with inspect.frame.f_locals sh",
"in transform(StringIO(code), transformer): print(line.rstrip('\\n')) from pysh.command import command ls =",
"if tkn == 'DQS': yield from self.scan_dqs(val, offset=pos[0]+1) else: yield",
"line = ctkn.line.rstrip('\\r\\n') bangexpr.append(line) bangcont = line.endswith('\\\\') last_bang_line = ctkn.start[0]",
"__slots__ = ('code',) def __init__(self, code): self.code = code def",
"token, value, pos in self.demux_dqs(tokens): assert token != 'DQS' #",
"lambda v: v[2:-1])), (r'[^\\\\\\$]+', t('SQS')) # handle as single quoted",
"re.sub(r'\\\\(.)', r'\\1', value) yield BangToken(BangTokenType.EXPR, value, pos) else: assert False,",
"with inspect.frame.f_locals sh << r''' # << means with variables",
"StringIO import re import tokenize import os from collections import",
"= r''' foo = ! ls foo${bar}.* \\ | grep",
"Iterator[str]] # runtime symbols __all__ = ['BangExpr', 'BangOp', 'BangSeq', 'BangGlob',",
"BangToken(BangTokenType.OPAQUE, value, pos) elif token in ('ESCAPE', 'SQS'): #TODO: handle",
"exprs = [] while True: tkn = next(lexer, None) if",
"in ('ESCAPE', 'SQS'): #TODO: handle special escapes \\n value =",
"expr: Any) -> Union[str, Iterator[Path]]: if isinstance(expr, BangSeq): return self.eval_seq(expr)",
"occur at the end of a seq') return PathWrapper(accum).glob(expr.glob) accum",
"seq: if len(seq) > 1: exprs.append('pysh.BangSeq({})'.format(', '.join(seq))) else: exprs.append(seq[0]) seq",
"len(mut_args) > 0, 'No operands left!' if arg.op == '|':",
"class BangOp: __slots__ = ('op',) def __init__(self, op): self.op =",
"\\t').rstrip('\\r\\n') bangexpr.append(line.rstrip('\\\\')) bangcont = line.endswith('\\\\') last_bang_line = ctkn.start[0] assert not",
"= value.strip() yield BangToken(BangTokenType.OP, value, pos) else: if token ==",
"from typing import List, Callable, Iterator, Tuple, NamedTuple, Deque, Union,",
"env when evaluated lines[0] = lines[0][1:] code = '\\n'.join(lines) code",
"result.stderr: print(result.stderr, file=sys.stderr) if result.returncode > 0: if result.stdout: print(result.stdout)",
"= \"pysh.BangBang('{}')\".format(code) lines = code.split('\\n') for line in lines: yield",
"BangToken(BangTokenType.OP, value, pos) else: if token == 'OPAQUE': if re.search(r'(?!<\\\\)[~*?{]',",
"pysh.ExitStatusError(result.returncode) return result.stdout def __str__(self): return str(self.eval()) def __repr__(self): return",
"str) -> str: as_str = lambda s: \"'{}'\".format(s.replace(\"\\\\\", \"\\\\\\\\\").replace(\"'\", \"\\\\'\"))",
"self._tokener return re.Scanner([ (r'\\\\.', t('ESCAPE')), (r'\\$[A-Za-z_][A-Za-z0-9_]*', t('VAR', lambda v: v[1:])),",
"if isinstance(expr, BangSeq): return self.eval_seq(expr) elif isinstance(expr, BangEnv): return os.environ[expr.name]",
"pos in tokens: yield tkn, val, (offset+pos[0], offset+pos[1]) def demux_dqs(self,",
"(r'\"( \\\\. | [^\\\\\"]+ )+\"', t('DQS', lambda v: v[1:-1])), (r'\\$[A-Za-z_][A-Za-z0-9_]*',",
"print(result.stderr, file=sys.stderr) if result.returncode > 0: if result.stdout: print(result.stdout) raise",
"#TODO: handle special escapes \\n value = re.sub(r'\\\\(.)', r'\\1', value)",
"so we can resolve commands to variables return 'pysh.BangExpr({}, locals=locals(),",
"= prebang + lines[0] yield from lines bangexpr = []",
"1 if bang_indent > indent: bang_indent = -100 # due",
"arg = mut_args.popleft() cmd = self.vars.get(str(arg)) if cmd is None:",
"str, Tuple[int,int]] class BangLexer: def _tokener(self, token, transformer=lambda x: x,",
"locals/globals so we can resolve commands to variables return 'pysh.BangExpr({},",
"elif isinstance(expr, BangEnv): return os.environ[expr.name] elif isinstance(expr, BangGlob): return PathWrapper().glob(expr.glob)",
"os from collections import deque, ChainMap from functools import lru_cache",
"OP = 'OP' class BangToken(NamedTuple): type: BangTokenType value: str span:",
"'.join(exprs)) def transform(code: StringIO, transformer: TBangTransformer) -> Iterator[str]: \"\"\" Scans",
"if ctkn.string == '!': col = ctkn.start[1] prebang = ctkn.line[0:col]",
"!! is probably better solved with: # locals are solved",
"in (BangTokenType.LOCAL, BangTokenType.EXPR): seq.append(tkn.value) elif tkn.type == BangTokenType.ENV: seq.append('pysh.BangEnv({})'.format(as_str(tkn.value))) elif",
"'BangEnv', 'BangBang'] class BangTokenType(Enum): OPAQUE = 'OPAQUE' GLOB = 'GLOB'",
"ls .* ''' for line in transform(StringIO(code), transformer): print(line.rstrip('\\n')) from",
"lambda v: v[2:-1])), (r'[|<>^]+', t('OP')), (r'[A-Za-z0-9_%*+:.,=/@~\\[\\]{}-]+', t('OPAQUE')), (r'\\s+', t('WS')), ],",
"bangexpr, bangexpr def transformer(lines: List[str]) -> Iterator[str]: if lines[0].startswith('!'): #TODO:",
"yield BangToken(BangTokenType.OPAQUE, value, pos) elif token in ('VAR', 'EXPR'): value",
"self.eval_expr(mut_args.popleft()) else: raise RuntimeError('Unsupported operator {}'.format(arg.op)) return cmd def __str__(self):",
"exprs.append(seq[0]) seq = [] if not tkn: break assert tkn.type",
"on a new line #TODO: Support indent/dedent for multiline if",
"if lines[0].startswith('!'): #TODO: Detect $ident to expose them on env",
"value, pos) elif token in ('VAR', 'EXPR'): value = value.strip()",
"== 'DQS': yield from self.scan_dqs(val, offset=pos[0]+1) else: yield tkn, val,",
"SyntaxError('BangExpr continuation at program end') line = ctkn.line.rstrip('\\r\\n') bangexpr.append(line) bangcont",
"locals=None, globals=None): assert locals is not None assert globals is",
"if remaining: raise SyntaxError('Unexpected char <{}> at position {}'.format(remaining[0], len(code)-len(remaining)))",
"pos) else: assert False, 'unexpected {}, what happened?'.format(token) last_token, last_pos",
"on env when evaluated lines[0] = lines[0][1:] code = '\\n'.join(lines)",
"= command('ls') grep = command('grep') bar = 10 print('::BangExpr::') be",
"| [^\\\\}]+ )+}', t('EXPR', lambda v: v[2:-1])), (r'[|<>^]+', t('OP')), (r'[A-Za-z0-9_%*+:.,=/@~\\[\\]{}-]+',",
"t = self._tokener return re.Scanner([ (r'\\#.+', t('COMMENT', lambda v: v[1:])),",
"bang expressions. Given some python code it will extract bang",
"TBangLexerToken = Tuple[str, str, Tuple[int,int]] class BangLexer: def _tokener(self, token,",
"Iterator[str]: \"\"\" Scans python code to transform bang expressions. Given",
"if lines and prebang: lines[0] = prebang + lines[0] yield",
"<< r''' # << means with variables interpolated # <",
"= [] while True: tkn = next(lexer, None) if tkn",
"= Tuple[str, str, Tuple[int,int]] class BangLexer: def _tokener(self, token, transformer=lambda",
"raise SyntaxError('BangExpr continuation at program end') line = ctkn.line.rstrip('\\r\\n') bangexpr.append(line)",
"isinstance(mut_args[0], BangOp): break arg = mut_args.popleft() cmd = cmd(self.eval_expr(arg)) return",
"__slots__ = ('op',) def __init__(self, op): self.op = op def",
"= mut_args.popleft() assert isinstance(arg, BangOp), 'Expected OP but found: {}'.format(arg)",
"elif token in ('VAR', 'EXPR'): value = value.strip() if value.isalnum()",
"it instead of default shell import sys, subprocess result =",
"= ['BangExpr', 'BangOp', 'BangSeq', 'BangGlob', 'BangEnv', 'BangBang'] class BangTokenType(Enum): OPAQUE",
"at position {}'.format(len(code)-len(remaining))) # Add a terminating token so we",
"('code',) def __init__(self, code): self.code = code def eval(self): #TODO:",
"bangcont = line.endswith('\\\\') last_bang_line = ctkn.start[0] elif bangexpr: lines =",
"prebang = None ptkn = None indent = 0 bang_indent",
"['bash', '-c', self.code], encoding='utf-8', stdout=subprocess.PIPE, stderr=subprocess.PIPE) if result.stderr: print(result.stderr, file=sys.stderr)",
"file=sys.stderr) if result.returncode > 0: if result.stdout: print(result.stdout) raise pysh.ExitStatusError(result.returncode)",
"PathWrapper().glob(expr.glob) else: return str(expr) def eval_seq(self, seq: BangSeq) -> Union[str,",
"(r\"'( \\\\. | [^\\\\']+ )+'\", t('SQS', lambda v: v[1:-1])), (r'\"(",
"when evaluated lines[0] = lines[0][1:] code = '\\n'.join(lines) code =",
"cmd > self.eval_expr(mut_args.popleft()) elif arg.op == '>>': cmd = cmd",
"return cmd def eval_expr(self, expr: Any) -> Union[str, Iterator[Path]]: if",
"(r'[|<>^]+', t('OP')), (r'[A-Za-z0-9_%*+:.,=/@~\\[\\]{}-]+', t('OPAQUE')), (r'\\s+', t('WS')), ], flags=re.X) @lru_cache() def",
"print(line.rstrip('\\n')) from pysh.command import command ls = command('ls') grep =",
"value, pos) else: if token == 'OPAQUE': if re.search(r'(?!<\\\\)[~*?{]', value):",
"# runtime symbols __all__ = ['BangExpr', 'BangOp', 'BangSeq', 'BangGlob', 'BangEnv',",
"sys, subprocess result = subprocess.run( ['bash', '-c', self.code], encoding='utf-8', stdout=subprocess.PIPE,",
"flags=re.X) def scan_dqs(self, code: str, offset=0) -> Iterator[TBangLexerToken]: tokens, remaining",
"\\n value = re.sub(r'\\\\(.)', r'\\1', value) yield BangToken(BangTokenType.OPAQUE, value, pos)",
"mut_args = deque(self.args) cmd = self.eval_command(mut_args) while mut_args: arg =",
"a callback that can report back the transformation. Returns a",
"else: assert False, 'Unexpected token {}'.format(tkn.type) continue if seq: if",
"items def __repr__(self): return 'BangSeq<{!r}>'.format(self.items) class BangOp: __slots__ = ('op',)",
"cmd ^= self.eval_command(mut_args) elif arg.op == '>': cmd = cmd",
"if value.isalnum() and not value.isdigit(): if value.isupper(): yield BangToken(BangTokenType.ENV, value,",
"self.eval_command(mut_args) elif arg.op == '>': cmd = cmd > self.eval_expr(mut_args.popleft())",
"0: if result.stdout: print(result.stdout) raise pysh.ExitStatusError(result.returncode) return result.stdout def __str__(self):",
"__str__(self): return str(self.eval()) def __repr__(self): return 'BangExpr<{!r}>'.format(self.args) class BangBang: __slots__",
"def parse_bangexpr(code: str) -> str: as_str = lambda s: \"'{}'\".format(s.replace(\"\\\\\",",
"while True: tkn = next(lexer, None) if tkn and tkn.type",
"value) yield BangToken(BangTokenType.OPAQUE, value, pos) elif token in ('VAR', 'EXPR'):",
"can only occur at the end of a seq') return",
"command ls = command('ls') grep = command('grep') bar = 10",
"indent/dedent for multiline if ptkn and ctkn.start[0] > ptkn.start[0]: if",
"tokens: if ctkn.type == tokenize.INDENT: indent += 1 if last_bang_line",
"pysh from pysh.path import PathWrapper, Path from typing import List,",
"== '>': cmd = cmd > self.eval_expr(mut_args.popleft()) elif arg.op ==",
"seq: BangSeq) -> Union[str, Iterator[Path]]: exprs: Deque[Any] = deque(seq.items) accum",
"exprs: Deque[Any] = deque(seq.items) accum = '' while exprs: expr",
"__init__(self, code): self.code = code def eval(self): #TODO: Detect shebang",
"foo${bar} ' >> expr expr<' ls foo${bar} ' !! #!/bin/fish",
"isinstance(expr, BangEnv): return os.environ[expr.name] elif isinstance(expr, BangGlob): return PathWrapper().glob(expr.glob) else:",
"('items',) def __init__(self, *items): self.items = items def __repr__(self): return",
"pos) elif token in ('VAR', 'EXPR'): value = value.strip() if",
"if not tkn: break assert tkn.type == BangTokenType.OP if tkn.value",
"= Callable[ [List[str]], Iterator[str]] # runtime symbols __all__ = ['BangExpr',",
"bang_indent = -100 # due to continuations we can't rely",
"(len(code),len(code)))) last_token = last_pos = None for token, value, pos",
"is not None self.args = args self.vars = ChainMap(locals, globals)",
"Deque, Union, Any TBangTransformer = Callable[ [List[str]], Iterator[str]] # runtime",
"eval_expr(self, expr: Any) -> Union[str, Iterator[Path]]: if isinstance(expr, BangSeq): return",
"BangTokenType.GLOB: seq.append('pysh.BangGlob({})'.format(as_str(tkn.value))) else: assert False, 'Unexpected token {}'.format(tkn.type) continue if",
"> 0, 'No operands left!' if arg.op == '|': cmd",
"#TODO: Support indent/dedent for multiline if ptkn and ctkn.start[0] >",
"= next(lexer, None) if tkn and tkn.type != BangTokenType.OP: if",
"code = '\\n'.join(lines) code = code.strip().replace(\"'\", \"\\\\'\").replace(\"\\\\\", \"\\\\\\\\\") code =",
"cmd = cmd > self.eval_expr(mut_args.popleft()) elif arg.op == '>>': cmd",
"find {}'.format(arg)) while mut_args: if isinstance(mut_args[0], BangOp): break arg =",
"= 'ENV' EXPR = 'EXPR' OP = 'OP' class BangToken(NamedTuple):",
"str) -> Iterator[BangToken]: tokens, remaining = self.build_scanner().scan(code) if remaining: raise",
"are demuxed # Inject whitespace operator if needed if token",
"yield ptkn.line ptkn = ctkn if bangexpr: continue if ctkn.string",
"code: str, offset=0) -> Iterator[TBangLexerToken]: tokens, remaining = self.build_scanner().scan(code) if",
"elif token == 'OP': value = value.strip() yield BangToken(BangTokenType.OP, value,",
">> self.eval_expr(mut_args.popleft()) else: raise RuntimeError('Unsupported operator {}'.format(arg.op)) return cmd def",
"ctkn.start[0] elif bangexpr: lines = list(transformer(bangexpr)) assert len(lines) <= len(bangexpr)",
"\"pysh.BangBang('{}')\".format(code) lines = code.split('\\n') for line in lines: yield line",
"at the end of a seq') return PathWrapper(accum).glob(expr.glob) accum +=",
"yield BangToken(BangTokenType.LOCAL, value, pos) else: assert token == 'EXPR' value",
"else: yield BangToken(BangTokenType.OPAQUE, value, pos) elif token in ('ESCAPE', 'SQS'):",
"'.join(seq))) else: exprs.append(seq[0]) seq = [] if not tkn: break",
"cmd(self.eval_expr(arg)) return cmd def eval_expr(self, expr: Any) -> Union[str, Iterator[Path]]:",
"'Unexpected token {}'.format(tkn.type) continue if seq: if len(seq) > 1:",
"import deque, ChainMap from functools import lru_cache from enum import",
"True: tkn = next(lexer, None) if tkn and tkn.type !=",
"char at position {}'.format(len(code)-len(remaining))) # Add a terminating token so",
"if ptkn and ctkn.start[0] > ptkn.start[0]: if bangcont or bang_indent",
"subprocess result = subprocess.run( ['bash', '-c', self.code], encoding='utf-8', stdout=subprocess.PIPE, stderr=subprocess.PIPE)",
"__init__(self, *items): self.items = items def __repr__(self): return 'BangSeq<{!r}>'.format(self.items) class",
"BangOp): break arg = mut_args.popleft() cmd = cmd(self.eval_expr(arg)) return cmd",
"for tkn, val, pos in tokens: yield tkn, val, (offset+pos[0],",
"Iterator[Path]]: exprs: Deque[Any] = deque(seq.items) accum = '' while exprs:",
"if arg.op == '|': cmd |= self.eval_command(mut_args) elif arg.op ==",
"== tokenize.INDENT: indent += 1 if last_bang_line + 1 ==",
"we're on a new line #TODO: Support indent/dedent for multiline",
"t('ESCAPE')), (r'\\$[A-Za-z_][A-Za-z0-9_]*', t('VAR', lambda v: v[1:])), (r'\\${( \\\\. | [^\\\\}]+",
"token != 'OP' and last_token and last_token == 'WS': yield",
"= ('args', 'vars') def __init__(self, *args, locals=None, globals=None): assert locals",
"> ptkn.start[0]: if bangcont or bang_indent == indent: if ctkn.type",
"offset+pos[1]) def demux_dqs(self, tokens: Iterator[TBangLexerToken]) -> Iterator[TBangLexerToken]: \"\"\" Split double",
"line = ctkn.line[col+1:].lstrip(' \\t').rstrip('\\r\\n') bangexpr.append(line.rstrip('\\\\')) bangcont = line.endswith('\\\\') last_bang_line =",
"it's intended for this to be global def build_scanner(self): t",
"-> Iterator[TBangLexerToken]: \"\"\" Split double quoted strings into parts \"\"\"",
"last_bang_line = -100 for ctkn in tokens: if ctkn.type ==",
"isinstance(expr, BangGlob): return PathWrapper().glob(expr.glob) else: return str(expr) def eval_seq(self, seq:",
"r'\\1', value) yield BangToken(BangTokenType.EXPR, value, pos) else: assert False, 'unexpected",
"else: assert False, 'unexpected {}, what happened?'.format(token) last_token, last_pos =",
"= re.sub(r'\\\\(.)', r'\\1', value) yield BangToken(BangTokenType.EXPR, value, pos) else: assert",
"bangcont = line.endswith('\\\\') last_bang_line = ctkn.start[0] assert not bangexpr, bangexpr",
"self.vars.get(str(arg)) if cmd is None: raise RuntimeError('Unable to find {}'.format(arg))",
"# << means with variables interpolated # < is plain",
"_tokener(self, token, transformer=lambda x: x, **kwargs): def cb(s, v): v",
"RuntimeError('Globbing can only occur at the end of a seq')",
"when we're on a new line #TODO: Support indent/dedent for",
"with: # locals are solved with inspect.frame.f_locals sh << r'''",
"line in lines: yield line else: yield from parse_bangexpr(' '.join(lines)).split('\\n')",
"lines[0] = lines[0][1:] code = '\\n'.join(lines) code = code.strip().replace(\"'\", \"\\\\'\").replace(\"\\\\\",",
"last_pos = token, pos class BangEnv: __slots__ = ('name',) def",
"Detect shebang and use it instead of default shell import",
"= None indent = 0 bang_indent = -100 last_bang_line =",
"BangBang: __slots__ = ('code',) def __init__(self, code): self.code = code",
"isinstance(arg, BangOp), 'Expected OP but found: {}'.format(arg) assert len(mut_args) >",
"left!' if arg.op == '|': cmd |= self.eval_command(mut_args) elif arg.op",
"elif tkn.type == BangTokenType.ENV: seq.append('pysh.BangEnv({})'.format(as_str(tkn.value))) elif tkn.type == BangTokenType.OPAQUE: seq.append('{}'.format(as_str(tkn.value)))",
"offset=pos[0]+1) else: yield tkn, val, pos def scan(self, code: str)",
"the parsing tokens.append(('END', '', (len(code),len(code)))) last_token = last_pos = None",
"('args', 'vars') def __init__(self, *args, locals=None, globals=None): assert locals is",
"and not value.isdigit(): if value.isupper(): yield BangToken(BangTokenType.ENV, value, pos) else:",
"continue elif token == 'WS': pass elif token == 'OP':",
"__repr__(self): return 'BangSeq<{!r}>'.format(self.items) class BangOp: __slots__ = ('op',) def __init__(self,",
"-100 # due to continuations we can't rely on NEWLINE",
"lines: yield line else: yield from parse_bangexpr(' '.join(lines)).split('\\n') from io",
"if exprs: raise RuntimeError('Globbing can only occur at the end",
"expr = exprs.popleft() if isinstance(expr, BangGlob): if exprs: raise RuntimeError('Globbing",
"def __init__(self, op): self.op = op def __repr__(self): return 'BangOp<{}>'.format(self.op)",
"token in ('VAR', 'EXPR'): value = value.strip() if value.isalnum() and",
"*args, locals=None, globals=None): assert locals is not None assert globals",
"continuations we can't rely on NEWLINE tokens, instead we have",
"Inject whitespace operator if needed if token != 'OP' and",
"sh << r''' # << means with variables interpolated #",
"'DQS' # double quoted are demuxed # Inject whitespace operator",
"('COMMENT', 'END'): continue elif token == 'WS': pass elif token",
"= '' while exprs: expr = exprs.popleft() if isinstance(expr, BangGlob):",
"'unexpected {}, what happened?'.format(token) last_token, last_pos = token, pos class",
"class BangSeq: __slots__ = ('items',) def __init__(self, *items): self.items =",
"-100 for ctkn in tokens: if ctkn.type == tokenize.INDENT: indent",
"terminating token so we can simplify the parsing tokens.append(('END', '',",
"= BangLexer().scan(code) seq = [] exprs = [] while True:",
"return accum def eval(self): mut_args = deque(self.args) cmd = self.eval_command(mut_args)",
"is not None assert globals is not None self.args =",
"handle as single quoted ], flags=re.X) def scan_dqs(self, code: str,",
"not tkn: break assert tkn.type == BangTokenType.OP if tkn.value ==",
"yield BangToken(BangTokenType.OP, ' ', last_pos) if token in ('COMMENT', 'END'):",
"span: Tuple[int, int] TBangLexerToken = Tuple[str, str, Tuple[int,int]] class BangLexer:",
"= glob def __repr__(self): return 'BangGlob<{}>'.format(self.glob) class BangExpr: __slots__ =",
"def demux_dqs(self, tokens: Iterator[TBangLexerToken]) -> Iterator[TBangLexerToken]: \"\"\" Split double quoted",
"'\\n'.join(lines) code = code.strip().replace(\"'\", \"\\\\'\").replace(\"\\\\\", \"\\\\\\\\\") code = \"pysh.BangBang('{}')\".format(code) lines",
"the transformation. Returns a generator that allows to consume the",
"for line in transform(StringIO(code), transformer): print(line.rstrip('\\n')) from pysh.command import command",
"== 'WS': pass elif token == 'OP': value = value.strip()",
"= ('glob',) def __init__(self, glob): self.glob = glob def __repr__(self):",
"(r'\\\\.', t('ESCAPE')), (r\"'( \\\\. | [^\\\\']+ )+'\", t('SQS', lambda v:",
"t('OP')), (r'[A-Za-z0-9_%*+:.,=/@~\\[\\]{}-]+', t('OPAQUE')), (r'\\s+', t('WS')), ], flags=re.X) @lru_cache() def build_dqs_scanner(self):",
"'GLOB' LOCAL = 'LOCAL' ENV = 'ENV' EXPR = 'EXPR'",
"grep foo > /dev/null foo = r' ls foo${bar} '",
"for line in lines: yield line else: yield from parse_bangexpr('",
"= ! ls foo${bar}.* \\ | grep foo > /dev/null",
"import List, Callable, Iterator, Tuple, NamedTuple, Deque, Union, Any TBangTransformer",
"def __str__(self): return str(self.eval()) def __repr__(self): return 'BangExpr<{!r}>'.format(self.args) class BangBang:",
"raise SyntaxError('Unexpected char <{}> at position {}'.format(remaining[0], len(code)-len(remaining))) for tkn,",
"arg.op == '|': cmd |= self.eval_command(mut_args) elif arg.op == '^':",
"self.scan_dqs(val, offset=pos[0]+1) else: yield tkn, val, pos def scan(self, code:",
"= -100 for ctkn in tokens: if ctkn.type == tokenize.INDENT:",
"last_pos = None for token, value, pos in self.demux_dqs(tokens): assert",
"[] if not tkn: break assert tkn.type == BangTokenType.OP if",
"Iterator[TBangLexerToken]: tokens, remaining = self.build_scanner().scan(code) if remaining: raise SyntaxError('Unexpected char",
"BangTokenType.OP: if tkn.type in (BangTokenType.LOCAL, BangTokenType.EXPR): seq.append(tkn.value) elif tkn.type ==",
"else (token, v, (s.match.start(), s.match.end())) return cb @lru_cache() # it's",
"have # use the lexical information to detect when we're",
"Returns a generator that allows to consume the transformed code",
"in ('COMMENT', 'END'): continue elif token == 'WS': pass elif",
"re.Scanner([ (r'\\#.+', t('COMMENT', lambda v: v[1:])), (r'\\\\.', t('ESCAPE')), (r\"'( \\\\.",
"token == 'OP': value = value.strip() yield BangToken(BangTokenType.OP, value, pos)",
">> expr expr<' ls foo${bar} ' !! #!/bin/fish ls .*",
"= re.sub(r'\\\\(.)', r'\\1', value) yield BangToken(BangTokenType.OPAQUE, value, pos) elif token",
"token, transformer=lambda x: x, **kwargs): def cb(s, v): v =",
"= items def __repr__(self): return 'BangSeq<{!r}>'.format(self.items) class BangOp: __slots__ =",
"demuxed # Inject whitespace operator if needed if token !=",
"lines and prebang: lines[0] = prebang + lines[0] yield from",
"= 'OPAQUE' GLOB = 'GLOB' LOCAL = 'LOCAL' ENV =",
")+'\", t('SQS', lambda v: v[1:-1])), (r'\"( \\\\. | [^\\\\\"]+ )+\"',",
"ls foo${bar} ' !! #!/bin/fish ls .* '''.strip() #TODO: !!",
"-> Iterator[BangToken]: tokens, remaining = self.build_scanner().scan(code) if remaining: raise SyntaxError('Unexpected",
"#TODO: !! is probably better solved with: # locals are",
"!= 'DQS' # double quoted are demuxed # Inject whitespace",
"from lines bangexpr = [] last_bang_line = ptkn.start[0] else: yield",
"BangGlob): return PathWrapper().glob(expr.glob) else: return str(expr) def eval_seq(self, seq: BangSeq)",
"scan_dqs(self, code: str, offset=0) -> Iterator[TBangLexerToken]: tokens, remaining = self.build_scanner().scan(code)",
"BangLexer().scan(code) seq = [] exprs = [] while True: tkn",
"assert False, 'Unexpected token {}'.format(tkn.type) continue if seq: if len(seq)",
"= indent elif ctkn.type == tokenize.DEDENT: indent -= 1 if",
"[^\\\\']+ )+'\", t('SQS', lambda v: v[1:-1])), (r'\"( \\\\. | [^\\\\\"]+",
"cmd is None: raise RuntimeError('Unable to find {}'.format(arg)) while mut_args:",
"'BangBang'] class BangTokenType(Enum): OPAQUE = 'OPAQUE' GLOB = 'GLOB' LOCAL",
"return 'BangOp<{}>'.format(self.op) class BangGlob: __slots__ = ('glob',) def __init__(self, glob):",
"-100 last_bang_line = -100 for ctkn in tokens: if ctkn.type",
"= cmd >> self.eval_expr(mut_args.popleft()) else: raise RuntimeError('Unsupported operator {}'.format(arg.op)) return",
"prebang = ctkn.line[0:col] line = ctkn.line[col+1:].lstrip(' \\t').rstrip('\\r\\n') bangexpr.append(line.rstrip('\\\\')) bangcont =",
"yield BangToken(BangTokenType.GLOB, value, pos) else: yield BangToken(BangTokenType.OPAQUE, value, pos) elif",
"elif arg.op == '>>': cmd = cmd >> self.eval_expr(mut_args.popleft()) else:",
"-> Union[str, Iterator[Path]]: exprs: Deque[Any] = deque(seq.items) accum = ''",
"remaining = self.build_scanner().scan(code) if remaining: raise SyntaxError('Unexpected char <{}> at",
"tkn.value == ' ': continue exprs.append('pysh.BangOp(\"{}\")'.format(tkn.value)) # We need to",
"if last_bang_line + 1 == ctkn.start[0]: bang_indent = indent elif",
"python code to transform bang expressions. Given some python code",
"= ctkn.start[0] elif bangexpr: lines = list(transformer(bangexpr)) assert len(lines) <=",
"= BangExpr('ls', BangSeq('foo', bar, BangGlob('.*')), BangOp(\"|\"), 'grep', 'foo', 'baz', BangOp(\">\"),",
"= op def __repr__(self): return 'BangOp<{}>'.format(self.op) class BangGlob: __slots__ =",
"eval_seq(self, seq: BangSeq) -> Union[str, Iterator[Path]]: exprs: Deque[Any] = deque(seq.items)",
"None assert globals is not None self.args = args self.vars",
"return 'BangBang<{}>'.format(self.code) def parse_bangexpr(code: str) -> str: as_str = lambda",
"'''.strip() #TODO: !! is probably better solved with: # locals",
"only occur at the end of a seq') return PathWrapper(accum).glob(expr.glob)",
"self.eval_command(mut_args) while mut_args: arg = mut_args.popleft() assert isinstance(arg, BangOp), 'Expected",
"ctkn.start[0] > ptkn.start[0]: if bangcont or bang_indent == indent: if",
"line in transform(StringIO(code), transformer): print(line.rstrip('\\n')) from pysh.command import command ls",
"class BangToken(NamedTuple): type: BangTokenType value: str span: Tuple[int, int] TBangLexerToken",
"BangTokenType.OPAQUE: seq.append('{}'.format(as_str(tkn.value))) elif tkn.type == BangTokenType.GLOB: seq.append('pysh.BangGlob({})'.format(as_str(tkn.value))) else: assert False,",
"NEWLINE tokens, instead we have # use the lexical information",
"bar, BangGlob('.*')), BangOp(\"|\"), 'grep', 'foo', 'baz', BangOp(\">\"), '/dev/null', locals=locals(), globals=globals())",
"v[2:-1])), (r'[^\\\\\\$]+', t('SQS')) # handle as single quoted ], flags=re.X)",
"('VAR', 'EXPR'): value = value.strip() if value.isalnum() and not value.isdigit():",
"None) if tkn and tkn.type != BangTokenType.OP: if tkn.type in",
"ctkn.start[1] prebang = ctkn.line[0:col] line = ctkn.line[col+1:].lstrip(' \\t').rstrip('\\r\\n') bangexpr.append(line.rstrip('\\\\')) bangcont",
"= command('grep') bar = 10 print('::BangExpr::') be = BangExpr('ls', BangSeq('foo',",
"= tokenize.generate_tokens(code.readline) bangexpr = [] # type: List[str] bangcont =",
"tkn.type == BangTokenType.OPAQUE: seq.append('{}'.format(as_str(tkn.value))) elif tkn.type == BangTokenType.GLOB: seq.append('pysh.BangGlob({})'.format(as_str(tkn.value))) else:",
"pos) else: assert token == 'EXPR' value = re.sub(r'\\\\(.)', r'\\1',",
"None else (token, v, (s.match.start(), s.match.end())) return cb @lru_cache() #",
"<reponame>drslump/pysh from io import StringIO import re import tokenize import",
"if seq: if len(seq) > 1: exprs.append('pysh.BangSeq({})'.format(', '.join(seq))) else: exprs.append(seq[0])",
"v[1:])), (r'\\${( \\\\. | [^\\\\}]+ )+}', t('EXPR', lambda v: v[2:-1])),",
"transformer(lines: List[str]) -> Iterator[str]: if lines[0].startswith('!'): #TODO: Detect $ident to",
"BangEnv: __slots__ = ('name',) def __init__(self, name): self.name = name",
"report back the transformation. Returns a generator that allows to",
"BangSeq) -> Union[str, Iterator[Path]]: exprs: Deque[Any] = deque(seq.items) accum =",
"multiline if ptkn and ctkn.start[0] > ptkn.start[0]: if bangcont or",
"bangcont = False prebang = None ptkn = None indent",
"def __init__(self, code): self.code = code def eval(self): #TODO: Detect",
"BangToken(BangTokenType.OPAQUE, value, pos) elif token in ('VAR', 'EXPR'): value =",
"code it will extract bang expressions and process them with",
"tokens, remaining = self.build_scanner().scan(code) if remaining: raise SyntaxError('Unexpected char at",
"transform bang expressions. Given some python code it will extract",
"to provide locals/globals so we can resolve commands to variables",
"0 bang_indent = -100 last_bang_line = -100 for ctkn in",
"ENV = 'ENV' EXPR = 'EXPR' OP = 'OP' class",
"symbols __all__ = ['BangExpr', 'BangOp', 'BangSeq', 'BangGlob', 'BangEnv', 'BangBang'] class",
"str: as_str = lambda s: \"'{}'\".format(s.replace(\"\\\\\", \"\\\\\\\\\").replace(\"'\", \"\\\\'\")) lexer =",
"__repr__(self): return 'BangGlob<{}>'.format(self.glob) class BangExpr: __slots__ = ('args', 'vars') def",
"shebang and use it instead of default shell import sys,",
"t('ESCAPE')), (r\"'( \\\\. | [^\\\\']+ )+'\", t('SQS', lambda v: v[1:-1])),",
"False, 'Unexpected token {}'.format(tkn.type) continue if seq: if len(seq) >",
"t('OPAQUE')), (r'\\s+', t('WS')), ], flags=re.X) @lru_cache() def build_dqs_scanner(self): t =",
"assert not bangexpr, bangexpr def transformer(lines: List[str]) -> Iterator[str]: if",
"<< means with variables interpolated # < is plain text",
"'OP': value = value.strip() yield BangToken(BangTokenType.OP, value, pos) else: if",
"== BangTokenType.OPAQUE: seq.append('{}'.format(as_str(tkn.value))) elif tkn.type == BangTokenType.GLOB: seq.append('pysh.BangGlob({})'.format(as_str(tkn.value))) else: assert",
"r''' # << means with variables interpolated # < is",
"'DQS': yield from self.scan_dqs(val, offset=pos[0]+1) else: yield tkn, val, pos",
"code = code.strip().replace(\"'\", \"\\\\'\").replace(\"\\\\\", \"\\\\\\\\\") code = \"pysh.BangBang('{}')\".format(code) lines =",
"expressions. Given some python code it will extract bang expressions",
"Iterator[str]: if lines[0].startswith('!'): #TODO: Detect $ident to expose them on",
"lexer = BangLexer().scan(code) seq = [] exprs = [] while",
"import PathWrapper, Path from typing import List, Callable, Iterator, Tuple,",
"last_pos) if token in ('COMMENT', 'END'): continue elif token ==",
"pos class BangEnv: __slots__ = ('name',) def __init__(self, name): self.name",
"= mut_args.popleft() cmd = cmd(self.eval_expr(arg)) return cmd def eval_expr(self, expr:",
"assert isinstance(arg, BangOp), 'Expected OP but found: {}'.format(arg) assert len(mut_args)",
"flags=re.X) @lru_cache() def build_dqs_scanner(self): t = self._tokener return re.Scanner([ (r'\\\\.',",
"parsing tokens.append(('END', '', (len(code),len(code)))) last_token = last_pos = None for",
"lambda v: v[1:-1])), (r'\\$[A-Za-z_][A-Za-z0-9_]*', t('VAR', lambda v: v[1:])), (r'\\${( \\\\.",
"\\\\. | [^\\\\\"]+ )+\"', t('DQS', lambda v: v[1:-1])), (r'\\$[A-Za-z_][A-Za-z0-9_]*', t('VAR',",
"= '\\n'.join(lines) code = code.strip().replace(\"'\", \"\\\\'\").replace(\"\\\\\", \"\\\\\\\\\") code = \"pysh.BangBang('{}')\".format(code)",
"them with a callback that can report back the transformation.",
"'ENV' EXPR = 'EXPR' OP = 'OP' class BangToken(NamedTuple): type:",
"class BangExpr: __slots__ = ('args', 'vars') def __init__(self, *args, locals=None,",
"s: \"'{}'\".format(s.replace(\"\\\\\", \"\\\\\\\\\").replace(\"'\", \"\\\\'\")) lexer = BangLexer().scan(code) seq = []",
"-> Iterator[str]: \"\"\" Scans python code to transform bang expressions.",
"r''' foo = ! ls foo${bar}.* \\ | grep foo",
"lambda s: \"'{}'\".format(s.replace(\"\\\\\", \"\\\\\\\\\").replace(\"'\", \"\\\\'\")) lexer = BangLexer().scan(code) seq =",
"tokens = tokenize.generate_tokens(code.readline) bangexpr = [] # type: List[str] bangcont",
"assert globals is not None self.args = args self.vars =",
"We need to provide locals/globals so we can resolve commands",
"value, pos in self.demux_dqs(tokens): assert token != 'DQS' # double",
"> self.eval_expr(mut_args.popleft()) elif arg.op == '>>': cmd = cmd >>",
"def __init__(self, glob): self.glob = glob def __repr__(self): return 'BangGlob<{}>'.format(self.glob)",
"= args self.vars = ChainMap(locals, globals) def eval_command(self, mut_args): arg",
"(token, v, (s.match.start(), s.match.end())) return cb @lru_cache() # it's intended",
"{}'.format(tkn.type) continue if seq: if len(seq) > 1: exprs.append('pysh.BangSeq({})'.format(', '.join(seq)))",
"pos) else: yield BangToken(BangTokenType.LOCAL, value, pos) else: assert token ==",
"elif token == 'WS': pass elif token == 'OP': value",
"[] exprs = [] while True: tkn = next(lexer, None)",
"self._tokener return re.Scanner([ (r'\\#.+', t('COMMENT', lambda v: v[1:])), (r'\\\\.', t('ESCAPE')),",
"indent += 1 if last_bang_line + 1 == ctkn.start[0]: bang_indent",
"yield line else: yield from parse_bangexpr(' '.join(lines)).split('\\n') from io import",
"< is plain text ls .* ''' for line in",
"t('EXPR', lambda v: v[2:-1])), (r'[^\\\\\\$]+', t('SQS')) # handle as single",
"' >> expr expr<' ls foo${bar} ' !! #!/bin/fish ls",
"prebang + lines[0] yield from lines bangexpr = [] last_bang_line",
"pysh.command import command ls = command('ls') grep = command('grep') bar",
"TBangTransformer) -> Iterator[str]: \"\"\" Scans python code to transform bang",
"ChainMap(locals, globals) def eval_command(self, mut_args): arg = mut_args.popleft() cmd =",
"OP but found: {}'.format(arg) assert len(mut_args) > 0, 'No operands",
"= subprocess.run( ['bash', '-c', self.code], encoding='utf-8', stdout=subprocess.PIPE, stderr=subprocess.PIPE) if result.stderr:",
"+= 1 if last_bang_line + 1 == ctkn.start[0]: bang_indent =",
"code.split('\\n') for line in lines: yield line else: yield from",
"{}'.format(arg.op)) return cmd def __str__(self): return str(self.eval()) def __repr__(self): return",
"at position {}'.format(remaining[0], len(code)-len(remaining))) for tkn, val, pos in tokens:",
"BangOp(\"|\"), 'grep', 'foo', 'baz', BangOp(\">\"), '/dev/null', locals=locals(), globals=globals()) # print(be)",
"yield tkn, val, pos def scan(self, code: str) -> Iterator[BangToken]:",
"indent = 0 bang_indent = -100 last_bang_line = -100 for",
"return result.stdout def __str__(self): return str(self.eval()) def __repr__(self): return 'BangBang<{}>'.format(self.code)",
"list(transformer(bangexpr)) assert len(lines) <= len(bangexpr) if lines and prebang: lines[0]",
"def __repr__(self): return 'BangOp<{}>'.format(self.op) class BangGlob: __slots__ = ('glob',) def",
"transformation. Returns a generator that allows to consume the transformed",
"cmd = self.eval_command(mut_args) while mut_args: arg = mut_args.popleft() assert isinstance(arg,",
"not None self.args = args self.vars = ChainMap(locals, globals) def",
"return re.Scanner([ (r'\\#.+', t('COMMENT', lambda v: v[1:])), (r'\\\\.', t('ESCAPE')), (r\"'(",
"ls foo${bar} ' >> expr expr<' ls foo${bar} ' !!",
"is probably better solved with: # locals are solved with",
"result.stdout: print(result.stdout) raise pysh.ExitStatusError(result.returncode) return result.stdout def __str__(self): return str(self.eval())",
"= ('items',) def __init__(self, *items): self.items = items def __repr__(self):",
"elif tkn.type == BangTokenType.GLOB: seq.append('pysh.BangGlob({})'.format(as_str(tkn.value))) else: assert False, 'Unexpected token",
"code line by line. \"\"\" tokens = tokenize.generate_tokens(code.readline) bangexpr =",
"solved with: # locals are solved with inspect.frame.f_locals sh <<",
"1 if last_bang_line + 1 == ctkn.start[0]: bang_indent = indent",
"Path from typing import List, Callable, Iterator, Tuple, NamedTuple, Deque,",
"# use the lexical information to detect when we're on",
"= -100 last_bang_line = -100 for ctkn in tokens: if",
"if token == 'OPAQUE': if re.search(r'(?!<\\\\)[~*?{]', value): yield BangToken(BangTokenType.GLOB, value,",
"else: yield from parse_bangexpr(' '.join(lines)).split('\\n') from io import StringIO code",
"v: v[1:])), (r'\\\\.', t('ESCAPE')), (r\"'( \\\\. | [^\\\\']+ )+'\", t('SQS',",
"happened?'.format(token) last_token, last_pos = token, pos class BangEnv: __slots__ =",
"x: x, **kwargs): def cb(s, v): v = transformer(v, **kwargs)",
"], flags=re.X) def scan_dqs(self, code: str, offset=0) -> Iterator[TBangLexerToken]: tokens,",
"cmd >> self.eval_expr(mut_args.popleft()) else: raise RuntimeError('Unsupported operator {}'.format(arg.op)) return cmd",
"return 'BangSeq<{!r}>'.format(self.items) class BangOp: __slots__ = ('op',) def __init__(self, op):",
"some python code it will extract bang expressions and process",
"assert len(mut_args) > 0, 'No operands left!' if arg.op ==",
"'BangExpr<{!r}>'.format(self.args) class BangBang: __slots__ = ('code',) def __init__(self, code): self.code",
"__repr__(self): return 'BangOp<{}>'.format(self.op) class BangGlob: __slots__ = ('glob',) def __init__(self,",
"isinstance(expr, BangGlob): if exprs: raise RuntimeError('Globbing can only occur at",
"build_dqs_scanner(self): t = self._tokener return re.Scanner([ (r'\\\\.', t('ESCAPE')), (r'\\$[A-Za-z_][A-Za-z0-9_]*', t('VAR',",
"stdout=subprocess.PIPE, stderr=subprocess.PIPE) if result.stderr: print(result.stderr, file=sys.stderr) if result.returncode > 0:",
"is plain text ls .* ''' for line in transform(StringIO(code),",
"!! #!/bin/fish ls .* '''.strip() #TODO: !! is probably better",
"tkn == 'DQS': yield from self.scan_dqs(val, offset=pos[0]+1) else: yield tkn,",
"can't rely on NEWLINE tokens, instead we have # use",
"import StringIO import re import tokenize import os from collections",
"Iterator[BangToken]: tokens, remaining = self.build_scanner().scan(code) if remaining: raise SyntaxError('Unexpected char",
"value) yield BangToken(BangTokenType.EXPR, value, pos) else: assert False, 'unexpected {},",
"__slots__ = ('glob',) def __init__(self, glob): self.glob = glob def",
"raise RuntimeError('Globbing can only occur at the end of a",
"class BangTokenType(Enum): OPAQUE = 'OPAQUE' GLOB = 'GLOB' LOCAL =",
"op): self.op = op def __repr__(self): return 'BangOp<{}>'.format(self.op) class BangGlob:",
"': continue exprs.append('pysh.BangOp(\"{}\")'.format(tkn.value)) # We need to provide locals/globals so",
"will extract bang expressions and process them with a callback",
"'BangOp<{}>'.format(self.op) class BangGlob: __slots__ = ('glob',) def __init__(self, glob): self.glob",
"int] TBangLexerToken = Tuple[str, str, Tuple[int,int]] class BangLexer: def _tokener(self,",
"for this to be global def build_scanner(self): t = self._tokener",
"def build_scanner(self): t = self._tokener return re.Scanner([ (r'\\#.+', t('COMMENT', lambda",
"ptkn and ctkn.start[0] > ptkn.start[0]: if bangcont or bang_indent ==",
"quoted ], flags=re.X) def scan_dqs(self, code: str, offset=0) -> Iterator[TBangLexerToken]:",
"resolve commands to variables return 'pysh.BangExpr({}, locals=locals(), globals=globals())'.format(', '.join(exprs)) def",
"(r'\\${( \\\\. | [^\\\\}]+ )+}', t('EXPR', lambda v: v[2:-1])), (r'[^\\\\\\$]+',",
"'Expected OP but found: {}'.format(arg) assert len(mut_args) > 0, 'No",
"-> Union[str, Iterator[Path]]: if isinstance(expr, BangSeq): return self.eval_seq(expr) elif isinstance(expr,",
"PathWrapper, Path from typing import List, Callable, Iterator, Tuple, NamedTuple,",
"yield BangToken(BangTokenType.EXPR, value, pos) else: assert False, 'unexpected {}, what",
"lexical information to detect when we're on a new line",
"# locals are solved with inspect.frame.f_locals sh << r''' #",
"is None else (token, v, (s.match.start(), s.match.end())) return cb @lru_cache()",
"[] last_bang_line = ptkn.start[0] else: yield ptkn.line ptkn = ctkn",
"value = value.strip() yield BangToken(BangTokenType.OP, value, pos) else: if token",
"for token, value, pos in self.demux_dqs(tokens): assert token != 'DQS'",
"position {}'.format(len(code)-len(remaining))) # Add a terminating token so we can",
"__slots__ = ('items',) def __init__(self, *items): self.items = items def",
"if tkn and tkn.type != BangTokenType.OP: if tkn.type in (BangTokenType.LOCAL,",
"== ' ': continue exprs.append('pysh.BangOp(\"{}\")'.format(tkn.value)) # We need to provide",
"from functools import lru_cache from enum import Enum import pysh",
"ctkn if bangexpr: continue if ctkn.string == '!': col =",
"'BangGlob', 'BangEnv', 'BangBang'] class BangTokenType(Enum): OPAQUE = 'OPAQUE' GLOB =",
"from io import StringIO code = r''' foo = !",
"we have # use the lexical information to detect when",
"col = ctkn.start[1] prebang = ctkn.line[0:col] line = ctkn.line[col+1:].lstrip(' \\t').rstrip('\\r\\n')",
"encoding='utf-8', stdout=subprocess.PIPE, stderr=subprocess.PIPE) if result.stderr: print(result.stderr, file=sys.stderr) if result.returncode >",
"OPAQUE = 'OPAQUE' GLOB = 'GLOB' LOCAL = 'LOCAL' ENV",
"and use it instead of default shell import sys, subprocess",
"], flags=re.X) @lru_cache() def build_dqs_scanner(self): t = self._tokener return re.Scanner([",
"back the transformation. Returns a generator that allows to consume",
"lines[0] yield from lines bangexpr = [] last_bang_line = ptkn.start[0]",
"isinstance(expr, BangSeq): return self.eval_seq(expr) elif isinstance(expr, BangEnv): return os.environ[expr.name] elif",
"BangToken(BangTokenType.GLOB, value, pos) else: yield BangToken(BangTokenType.OPAQUE, value, pos) elif token",
"| [^\\\\']+ )+'\", t('SQS', lambda v: v[1:-1])), (r'\"( \\\\. |",
"{}, what happened?'.format(token) last_token, last_pos = token, pos class BangEnv:",
"self.glob = glob def __repr__(self): return 'BangGlob<{}>'.format(self.glob) class BangExpr: __slots__",
"\\\\. | [^\\\\}]+ )+}', t('EXPR', lambda v: v[2:-1])), (r'[|<>^]+', t('OP')),",
"'foo', 'baz', BangOp(\">\"), '/dev/null', locals=locals(), globals=globals()) # print(be) print('::BangBang::') bb",
"if bang_indent > indent: bang_indent = -100 # due to",
"value = re.sub(r'\\\\(.)', r'\\1', value) yield BangToken(BangTokenType.OPAQUE, value, pos) elif",
"== 'WS': yield BangToken(BangTokenType.OP, ' ', last_pos) if token in",
"need to provide locals/globals so we can resolve commands to",
"ptkn = None indent = 0 bang_indent = -100 last_bang_line",
"= self._tokener return re.Scanner([ (r'\\#.+', t('COMMENT', lambda v: v[1:])), (r'\\\\.',",
"code: str) -> Iterator[BangToken]: tokens, remaining = self.build_scanner().scan(code) if remaining:",
"| [^\\\\}]+ )+}', t('EXPR', lambda v: v[2:-1])), (r'[^\\\\\\$]+', t('SQS')) #",
"position {}'.format(remaining[0], len(code)-len(remaining))) for tkn, val, pos in tokens: yield",
"operator {}'.format(arg.op)) return cmd def __str__(self): return str(self.eval()) def __repr__(self):",
"\"\\\\\\\\\") code = \"pysh.BangBang('{}')\".format(code) lines = code.split('\\n') for line in",
"cb(s, v): v = transformer(v, **kwargs) return None if v",
"# We need to provide locals/globals so we can resolve",
"double quoted are demuxed # Inject whitespace operator if needed",
"else: if token == 'OPAQUE': if re.search(r'(?!<\\\\)[~*?{]', value): yield BangToken(BangTokenType.GLOB,",
"== ctkn.start[0]: bang_indent = indent elif ctkn.type == tokenize.DEDENT: indent",
"allows to consume the transformed code line by line. \"\"\"",
"elif bangexpr: lines = list(transformer(bangexpr)) assert len(lines) <= len(bangexpr) if",
".* ''' for line in transform(StringIO(code), transformer): print(line.rstrip('\\n')) from pysh.command",
"assert token == 'EXPR' value = re.sub(r'\\\\(.)', r'\\1', value) yield",
"collections import deque, ChainMap from functools import lru_cache from enum",
"List[str]) -> Iterator[str]: if lines[0].startswith('!'): #TODO: Detect $ident to expose",
"{}'.format(remaining[0], len(code)-len(remaining))) for tkn, val, pos in tokens: yield tkn,",
"if needed if token != 'OP' and last_token and last_token",
"RuntimeError('Unsupported operator {}'.format(arg.op)) return cmd def __str__(self): return str(self.eval()) def",
"value: str span: Tuple[int, int] TBangLexerToken = Tuple[str, str, Tuple[int,int]]",
"'LOCAL' ENV = 'ENV' EXPR = 'EXPR' OP = 'OP'",
"\\\\. | [^\\\\}]+ )+}', t('EXPR', lambda v: v[2:-1])), (r'[^\\\\\\$]+', t('SQS'))",
"BangOp: __slots__ = ('op',) def __init__(self, op): self.op = op",
"tkn, val, pos def scan(self, code: str) -> Iterator[BangToken]: tokens,",
"be = BangExpr('ls', BangSeq('foo', bar, BangGlob('.*')), BangOp(\"|\"), 'grep', 'foo', 'baz',",
"else: assert token == 'EXPR' value = re.sub(r'\\\\(.)', r'\\1', value)",
"' !! #!/bin/fish ls .* '''.strip() #TODO: !! is probably",
"tokens, instead we have # use the lexical information to",
"to consume the transformed code line by line. \"\"\" tokens",
"escapes \\n value = re.sub(r'\\\\(.)', r'\\1', value) yield BangToken(BangTokenType.OPAQUE, value,",
"def eval(self): mut_args = deque(self.args) cmd = self.eval_command(mut_args) while mut_args:"
] |
[
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"= testing_data[:, 1].reshape((testing_data.shape[0], 1)) return X, Y, X_test, Y_test def",
"num=20): flag = numpy.random.randint(0, 2, (num,)) X = flag *",
"Y_test def load_synthetic(theta1, theta2, sigmax, num=20): flag = numpy.random.randint(0, 2,",
"OF ANY # KIND, either express or implied. See the",
"X_test, Y_test def load_toy(): training_data = numpy.loadtxt('toy_data_train.txt') testing_data = numpy.loadtxt('toy_data_test_whole.txt')",
"(1.0 - flag) * numpy.random.normal(theta1 + theta2, sigmax, (num,)) return",
"Software Foundation (ASF) under one # or more contributor license",
"more contributor license agreements. See the NOTICE file # distributed",
"Unless required by applicable law or agreed to in writing,",
"= ( 'https://github.com/sxjscience/mxnet/raw/master/example/bayesian-methods/mnist.npz' ) print('Downloading data from %s to %s'",
"Y_test = dat['Y_test'] Y = Y.reshape((Y.shape[0],)) Y_test = Y_test.reshape((Y_test.shape[0],)) return",
"= numpy.loadtxt('toy_data_test_whole.txt') X = training_data[:, 0].reshape((training_data.shape[0], 1)) Y = training_data[:,",
"theta2, sigmax, num=20): flag = numpy.random.randint(0, 2, (num,)) X =",
"0].reshape((training_data.shape[0], 1)) Y = training_data[:, 1].reshape((training_data.shape[0], 1)) X_test = testing_data[:,",
"an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF",
"- flag) * numpy.random.normal(theta1 + theta2, sigmax, (num,)) return X",
"# regarding copyright ownership. The ASF licenses this file #",
"= (dat['X_test'] / 126.0).astype('float32') Y_test = dat['Y_test'] Y = Y.reshape((Y.shape[0],))",
"Apache Software Foundation (ASF) under one # or more contributor",
"ssl def load_mnist(training_num=50000): data_path = os.path.join(os.path.dirname(os.path.realpath('__file__')), 'mnist.npz') if not os.path.isfile(data_path):",
"1].reshape((testing_data.shape[0], 1)) return X, Y, X_test, Y_test def load_synthetic(theta1, theta2,",
"in compliance # with the License. You may obtain a",
"# to you under the Apache License, Version 2.0 (the",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express",
"License for the # specific language governing permissions and limitations",
"WARRANTIES OR CONDITIONS OF ANY # KIND, either express or",
"1)) Y_test = testing_data[:, 1].reshape((testing_data.shape[0], 1)) return X, Y, X_test,",
"with this work for additional information # regarding copyright ownership.",
"1)) X_test = testing_data[:, 0].reshape((testing_data.shape[0], 1)) Y_test = testing_data[:, 1].reshape((testing_data.shape[0],",
"(ASF) under one # or more contributor license agreements. See",
"2.0 (the # \"License\"); you may not use this file",
"OR CONDITIONS OF ANY # KIND, either express or implied.",
"126.0).astype('float32') Y_test = dat['Y_test'] Y = Y.reshape((Y.shape[0],)) Y_test = Y_test.reshape((Y_test.shape[0],))",
"# or more contributor license agreements. See the NOTICE file",
"numpy.loadtxt('toy_data_test_whole.txt') X = training_data[:, 0].reshape((training_data.shape[0], 1)) Y = training_data[:, 1].reshape((training_data.shape[0],",
"agreed to in writing, # software distributed under the License",
"def load_synthetic(theta1, theta2, sigmax, num=20): flag = numpy.random.randint(0, 2, (num,))",
"from __future__ import print_function import numpy import os import ssl",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"work for additional information # regarding copyright ownership. The ASF",
"specific language governing permissions and limitations # under the License.",
"limitations # under the License. from __future__ import print_function import",
"Y.reshape((Y.shape[0],)) Y_test = Y_test.reshape((Y_test.shape[0],)) return X, Y, X_test, Y_test def",
"under the License is distributed on an # \"AS IS\"",
"this file # to you under the Apache License, Version",
"distributed under the License is distributed on an # \"AS",
"return X, Y, X_test, Y_test def load_synthetic(theta1, theta2, sigmax, num=20):",
"X_test, Y_test def load_synthetic(theta1, theta2, sigmax, num=20): flag = numpy.random.randint(0,",
"BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either",
"copyright ownership. The ASF licenses this file # to you",
"# software distributed under the License is distributed on an",
"= (dat['X'][:training_num] / 126.0).astype('float32') Y = dat['Y'][:training_num] X_test = (dat['X_test']",
"\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY #",
"data_path)) ctx = ssl._create_unverified_context() with urllib.request.urlopen(origin, context=ctx) as u, open(data_path,",
"1].reshape((training_data.shape[0], 1)) X_test = testing_data[:, 0].reshape((testing_data.shape[0], 1)) Y_test = testing_data[:,",
"(the # \"License\"); you may not use this file except",
"the License. You may obtain a copy of the License",
"testing_data[:, 1].reshape((testing_data.shape[0], 1)) return X, Y, X_test, Y_test def load_synthetic(theta1,",
"in writing, # software distributed under the License is distributed",
"load_mnist(training_num=50000): data_path = os.path.join(os.path.dirname(os.path.realpath('__file__')), 'mnist.npz') if not os.path.isfile(data_path): from six.moves",
"'https://github.com/sxjscience/mxnet/raw/master/example/bayesian-methods/mnist.npz' ) print('Downloading data from %s to %s' % (origin,",
"dat['Y_test'] Y = Y.reshape((Y.shape[0],)) Y_test = Y_test.reshape((Y_test.shape[0],)) return X, Y,",
"distributed with this work for additional information # regarding copyright",
"training_data[:, 0].reshape((training_data.shape[0], 1)) Y = training_data[:, 1].reshape((training_data.shape[0], 1)) X_test =",
"* numpy.random.normal(theta1, sigmax, (num,)) \\ + (1.0 - flag) *",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"under the License. from __future__ import print_function import numpy import",
"License is distributed on an # \"AS IS\" BASIS, WITHOUT",
"ASF licenses this file # to you under the Apache",
"sigmax, (num,)) \\ + (1.0 - flag) * numpy.random.normal(theta1 +",
"= numpy.loadtxt('toy_data_train.txt') testing_data = numpy.loadtxt('toy_data_test_whole.txt') X = training_data[:, 0].reshape((training_data.shape[0], 1))",
"under the Apache License, Version 2.0 (the # \"License\"); you",
"for the # specific language governing permissions and limitations #",
"(dat['X'][:training_num] / 126.0).astype('float32') Y = dat['Y'][:training_num] X_test = (dat['X_test'] /",
"from %s to %s' % (origin, data_path)) ctx = ssl._create_unverified_context()",
"training_data[:, 1].reshape((training_data.shape[0], 1)) X_test = testing_data[:, 0].reshape((testing_data.shape[0], 1)) Y_test =",
"distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR",
"on an # \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS",
"regarding copyright ownership. The ASF licenses this file # to",
"See the License for the # specific language governing permissions",
"to in writing, # software distributed under the License is",
"or agreed to in writing, # software distributed under the",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"open(data_path, 'wb') as f: f.write(u.read()) print('Done!') dat = numpy.load(data_path) X",
"Y = Y.reshape((Y.shape[0],)) Y_test = Y_test.reshape((Y_test.shape[0],)) return X, Y, X_test,",
"ownership. The ASF licenses this file # to you under",
"Y = training_data[:, 1].reshape((training_data.shape[0], 1)) X_test = testing_data[:, 0].reshape((testing_data.shape[0], 1))",
"= training_data[:, 0].reshape((training_data.shape[0], 1)) Y = training_data[:, 1].reshape((training_data.shape[0], 1)) X_test",
"X = (dat['X'][:training_num] / 126.0).astype('float32') Y = dat['Y'][:training_num] X_test =",
"# \"License\"); you may not use this file except in",
"# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"X, Y, X_test, Y_test def load_toy(): training_data = numpy.loadtxt('toy_data_train.txt') testing_data",
"to the Apache Software Foundation (ASF) under one # or",
"\"License\"); you may not use this file except in compliance",
"file # distributed with this work for additional information #",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"origin = ( 'https://github.com/sxjscience/mxnet/raw/master/example/bayesian-methods/mnist.npz' ) print('Downloading data from %s to",
"= numpy.load(data_path) X = (dat['X'][:training_num] / 126.0).astype('float32') Y = dat['Y'][:training_num]",
"+ (1.0 - flag) * numpy.random.normal(theta1 + theta2, sigmax, (num,))",
"with the License. You may obtain a copy of the",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"to %s' % (origin, data_path)) ctx = ssl._create_unverified_context() with urllib.request.urlopen(origin,",
"= dat['Y_test'] Y = Y.reshape((Y.shape[0],)) Y_test = Y_test.reshape((Y_test.shape[0],)) return X,",
"or more contributor license agreements. See the NOTICE file #",
"import os import ssl def load_mnist(training_num=50000): data_path = os.path.join(os.path.dirname(os.path.realpath('__file__')), 'mnist.npz')",
"applicable law or agreed to in writing, # software distributed",
"# distributed with this work for additional information # regarding",
"this work for additional information # regarding copyright ownership. The",
"urllib origin = ( 'https://github.com/sxjscience/mxnet/raw/master/example/bayesian-methods/mnist.npz' ) print('Downloading data from %s",
"print_function import numpy import os import ssl def load_mnist(training_num=50000): data_path",
"writing, # software distributed under the License is distributed on",
"(dat['X_test'] / 126.0).astype('float32') Y_test = dat['Y_test'] Y = Y.reshape((Y.shape[0],)) Y_test",
"/ 126.0).astype('float32') Y_test = dat['Y_test'] Y = Y.reshape((Y.shape[0],)) Y_test =",
"the NOTICE file # distributed with this work for additional",
"Y = dat['Y'][:training_num] X_test = (dat['X_test'] / 126.0).astype('float32') Y_test =",
"126.0).astype('float32') Y = dat['Y'][:training_num] X_test = (dat['X_test'] / 126.0).astype('float32') Y_test",
"import numpy import os import ssl def load_mnist(training_num=50000): data_path =",
"language governing permissions and limitations # under the License. from",
"Y, X_test, Y_test def load_synthetic(theta1, theta2, sigmax, num=20): flag =",
"is distributed on an # \"AS IS\" BASIS, WITHOUT WARRANTIES",
"testing_data = numpy.loadtxt('toy_data_test_whole.txt') X = training_data[:, 0].reshape((training_data.shape[0], 1)) Y =",
"implied. See the License for the # specific language governing",
"file # to you under the Apache License, Version 2.0",
"Y_test.reshape((Y_test.shape[0],)) return X, Y, X_test, Y_test def load_toy(): training_data =",
"to you under the Apache License, Version 2.0 (the #",
"load_synthetic(theta1, theta2, sigmax, num=20): flag = numpy.random.randint(0, 2, (num,)) X",
"CONDITIONS OF ANY # KIND, either express or implied. See",
"# with the License. You may obtain a copy of",
"governing permissions and limitations # under the License. from __future__",
"os import ssl def load_mnist(training_num=50000): data_path = os.path.join(os.path.dirname(os.path.realpath('__file__')), 'mnist.npz') if",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"= Y.reshape((Y.shape[0],)) Y_test = Y_test.reshape((Y_test.shape[0],)) return X, Y, X_test, Y_test",
"\\ + (1.0 - flag) * numpy.random.normal(theta1 + theta2, sigmax,",
"testing_data[:, 0].reshape((testing_data.shape[0], 1)) Y_test = testing_data[:, 1].reshape((testing_data.shape[0], 1)) return X,",
"may not use this file except in compliance # with",
"print('Done!') dat = numpy.load(data_path) X = (dat['X'][:training_num] / 126.0).astype('float32') Y",
"os.path.join(os.path.dirname(os.path.realpath('__file__')), 'mnist.npz') if not os.path.isfile(data_path): from six.moves import urllib origin",
"software distributed under the License is distributed on an #",
"Licensed to the Apache Software Foundation (ASF) under one #",
"= training_data[:, 1].reshape((training_data.shape[0], 1)) X_test = testing_data[:, 0].reshape((testing_data.shape[0], 1)) Y_test",
"for additional information # regarding copyright ownership. The ASF licenses",
"0].reshape((testing_data.shape[0], 1)) Y_test = testing_data[:, 1].reshape((testing_data.shape[0], 1)) return X, Y,",
"the Apache Software Foundation (ASF) under one # or more",
"( 'https://github.com/sxjscience/mxnet/raw/master/example/bayesian-methods/mnist.npz' ) print('Downloading data from %s to %s' %",
"Y_test = testing_data[:, 1].reshape((testing_data.shape[0], 1)) return X, Y, X_test, Y_test",
"(origin, data_path)) ctx = ssl._create_unverified_context() with urllib.request.urlopen(origin, context=ctx) as u,",
"f: f.write(u.read()) print('Done!') dat = numpy.load(data_path) X = (dat['X'][:training_num] /",
"# # Unless required by applicable law or agreed to",
"Version 2.0 (the # \"License\"); you may not use this",
"%s to %s' % (origin, data_path)) ctx = ssl._create_unverified_context() with",
"under one # or more contributor license agreements. See the",
"not os.path.isfile(data_path): from six.moves import urllib origin = ( 'https://github.com/sxjscience/mxnet/raw/master/example/bayesian-methods/mnist.npz'",
"one # or more contributor license agreements. See the NOTICE",
"License, Version 2.0 (the # \"License\"); you may not use",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"context=ctx) as u, open(data_path, 'wb') as f: f.write(u.read()) print('Done!') dat",
"either express or implied. See the License for the #",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"X_test = testing_data[:, 0].reshape((testing_data.shape[0], 1)) Y_test = testing_data[:, 1].reshape((testing_data.shape[0], 1))",
"the License. from __future__ import print_function import numpy import os",
"= numpy.random.randint(0, 2, (num,)) X = flag * numpy.random.normal(theta1, sigmax,",
"KIND, either express or implied. See the License for the",
"information # regarding copyright ownership. The ASF licenses this file",
"% (origin, data_path)) ctx = ssl._create_unverified_context() with urllib.request.urlopen(origin, context=ctx) as",
"Y, X_test, Y_test def load_toy(): training_data = numpy.loadtxt('toy_data_train.txt') testing_data =",
"as f: f.write(u.read()) print('Done!') dat = numpy.load(data_path) X = (dat['X'][:training_num]",
"the Apache License, Version 2.0 (the # \"License\"); you may",
"(num,)) X = flag * numpy.random.normal(theta1, sigmax, (num,)) \\ +",
"= flag * numpy.random.normal(theta1, sigmax, (num,)) \\ + (1.0 -",
"f.write(u.read()) print('Done!') dat = numpy.load(data_path) X = (dat['X'][:training_num] / 126.0).astype('float32')",
"import ssl def load_mnist(training_num=50000): data_path = os.path.join(os.path.dirname(os.path.realpath('__file__')), 'mnist.npz') if not",
") print('Downloading data from %s to %s' % (origin, data_path))",
"print('Downloading data from %s to %s' % (origin, data_path)) ctx",
"import urllib origin = ( 'https://github.com/sxjscience/mxnet/raw/master/example/bayesian-methods/mnist.npz' ) print('Downloading data from",
"def load_toy(): training_data = numpy.loadtxt('toy_data_train.txt') testing_data = numpy.loadtxt('toy_data_test_whole.txt') X =",
"except in compliance # with the License. You may obtain",
"additional information # regarding copyright ownership. The ASF licenses this",
"'wb') as f: f.write(u.read()) print('Done!') dat = numpy.load(data_path) X =",
"%s' % (origin, data_path)) ctx = ssl._create_unverified_context() with urllib.request.urlopen(origin, context=ctx)",
"urllib.request.urlopen(origin, context=ctx) as u, open(data_path, 'wb') as f: f.write(u.read()) print('Done!')",
"Y_test def load_toy(): training_data = numpy.loadtxt('toy_data_train.txt') testing_data = numpy.loadtxt('toy_data_test_whole.txt') X",
"flag * numpy.random.normal(theta1, sigmax, (num,)) \\ + (1.0 - flag)",
"__future__ import print_function import numpy import os import ssl def",
"you under the Apache License, Version 2.0 (the # \"License\");",
"or implied. See the License for the # specific language",
"def load_mnist(training_num=50000): data_path = os.path.join(os.path.dirname(os.path.realpath('__file__')), 'mnist.npz') if not os.path.isfile(data_path): from",
"See the NOTICE file # distributed with this work for",
"# KIND, either express or implied. See the License for",
"express or implied. See the License for the # specific",
"Y_test = Y_test.reshape((Y_test.shape[0],)) return X, Y, X_test, Y_test def load_toy():",
"NOTICE file # distributed with this work for additional information",
"permissions and limitations # under the License. from __future__ import",
"sigmax, num=20): flag = numpy.random.randint(0, 2, (num,)) X = flag",
"= os.path.join(os.path.dirname(os.path.realpath('__file__')), 'mnist.npz') if not os.path.isfile(data_path): from six.moves import urllib",
"dat = numpy.load(data_path) X = (dat['X'][:training_num] / 126.0).astype('float32') Y =",
"this file except in compliance # with the License. You",
"agreements. See the NOTICE file # distributed with this work",
"= Y_test.reshape((Y_test.shape[0],)) return X, Y, X_test, Y_test def load_toy(): training_data",
"Apache License, Version 2.0 (the # \"License\"); you may not",
"from six.moves import urllib origin = ( 'https://github.com/sxjscience/mxnet/raw/master/example/bayesian-methods/mnist.npz' ) print('Downloading",
"the # specific language governing permissions and limitations # under",
"licenses this file # to you under the Apache License,",
"= ssl._create_unverified_context() with urllib.request.urlopen(origin, context=ctx) as u, open(data_path, 'wb') as",
"1)) return X, Y, X_test, Y_test def load_synthetic(theta1, theta2, sigmax,",
"license agreements. See the NOTICE file # distributed with this",
"numpy.load(data_path) X = (dat['X'][:training_num] / 126.0).astype('float32') Y = dat['Y'][:training_num] X_test",
"1)) Y = training_data[:, 1].reshape((training_data.shape[0], 1)) X_test = testing_data[:, 0].reshape((testing_data.shape[0],",
"X, Y, X_test, Y_test def load_synthetic(theta1, theta2, sigmax, num=20): flag",
"dat['Y'][:training_num] X_test = (dat['X_test'] / 126.0).astype('float32') Y_test = dat['Y_test'] Y",
"required by applicable law or agreed to in writing, #",
"flag = numpy.random.randint(0, 2, (num,)) X = flag * numpy.random.normal(theta1,",
"by applicable law or agreed to in writing, # software",
"may obtain a copy of the License at # #",
"# Unless required by applicable law or agreed to in",
"u, open(data_path, 'wb') as f: f.write(u.read()) print('Done!') dat = numpy.load(data_path)",
"six.moves import urllib origin = ( 'https://github.com/sxjscience/mxnet/raw/master/example/bayesian-methods/mnist.npz' ) print('Downloading data",
"as u, open(data_path, 'wb') as f: f.write(u.read()) print('Done!') dat =",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"The ASF licenses this file # to you under the",
"training_data = numpy.loadtxt('toy_data_train.txt') testing_data = numpy.loadtxt('toy_data_test_whole.txt') X = training_data[:, 0].reshape((training_data.shape[0],",
"file except in compliance # with the License. You may",
"2, (num,)) X = flag * numpy.random.normal(theta1, sigmax, (num,)) \\",
"IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND,",
"'mnist.npz') if not os.path.isfile(data_path): from six.moves import urllib origin =",
"# specific language governing permissions and limitations # under the",
"ssl._create_unverified_context() with urllib.request.urlopen(origin, context=ctx) as u, open(data_path, 'wb') as f:",
"the License for the # specific language governing permissions and",
"X_test = (dat['X_test'] / 126.0).astype('float32') Y_test = dat['Y_test'] Y =",
"if not os.path.isfile(data_path): from six.moves import urllib origin = (",
"License. You may obtain a copy of the License at",
"X = flag * numpy.random.normal(theta1, sigmax, (num,)) \\ + (1.0",
"numpy import os import ssl def load_mnist(training_num=50000): data_path = os.path.join(os.path.dirname(os.path.realpath('__file__')),",
"and limitations # under the License. from __future__ import print_function",
"= testing_data[:, 0].reshape((testing_data.shape[0], 1)) Y_test = testing_data[:, 1].reshape((testing_data.shape[0], 1)) return",
"You may obtain a copy of the License at #",
"ANY # KIND, either express or implied. See the License",
"X = training_data[:, 0].reshape((training_data.shape[0], 1)) Y = training_data[:, 1].reshape((training_data.shape[0], 1))",
"# under the License. from __future__ import print_function import numpy",
"<gh_stars>10-100 # Licensed to the Apache Software Foundation (ASF) under",
"# Licensed to the Apache Software Foundation (ASF) under one",
"the License is distributed on an # \"AS IS\" BASIS,",
"you may not use this file except in compliance #",
"data from %s to %s' % (origin, data_path)) ctx =",
"License. from __future__ import print_function import numpy import os import",
"load_toy(): training_data = numpy.loadtxt('toy_data_train.txt') testing_data = numpy.loadtxt('toy_data_test_whole.txt') X = training_data[:,",
"return X, Y, X_test, Y_test def load_toy(): training_data = numpy.loadtxt('toy_data_train.txt')",
"use this file except in compliance # with the License.",
"compliance # with the License. You may obtain a copy",
"numpy.random.normal(theta1, sigmax, (num,)) \\ + (1.0 - flag) * numpy.random.normal(theta1",
"import print_function import numpy import os import ssl def load_mnist(training_num=50000):",
"numpy.random.randint(0, 2, (num,)) X = flag * numpy.random.normal(theta1, sigmax, (num,))",
"os.path.isfile(data_path): from six.moves import urllib origin = ( 'https://github.com/sxjscience/mxnet/raw/master/example/bayesian-methods/mnist.npz' )",
"law or agreed to in writing, # software distributed under",
"/ 126.0).astype('float32') Y = dat['Y'][:training_num] X_test = (dat['X_test'] / 126.0).astype('float32')",
"contributor license agreements. See the NOTICE file # distributed with",
"ctx = ssl._create_unverified_context() with urllib.request.urlopen(origin, context=ctx) as u, open(data_path, 'wb')",
"with urllib.request.urlopen(origin, context=ctx) as u, open(data_path, 'wb') as f: f.write(u.read())",
"= dat['Y'][:training_num] X_test = (dat['X_test'] / 126.0).astype('float32') Y_test = dat['Y_test']",
"Foundation (ASF) under one # or more contributor license agreements.",
"numpy.loadtxt('toy_data_train.txt') testing_data = numpy.loadtxt('toy_data_test_whole.txt') X = training_data[:, 0].reshape((training_data.shape[0], 1)) Y",
"not use this file except in compliance # with the",
"data_path = os.path.join(os.path.dirname(os.path.realpath('__file__')), 'mnist.npz') if not os.path.isfile(data_path): from six.moves import",
"(num,)) \\ + (1.0 - flag) * numpy.random.normal(theta1 + theta2,"
] |
[
"tmdb.Movies(movie_id) # Retrieve Image URL minfo = m.info() poster_image_url =",
"m.info() poster_image_url = image_base_url + image_width + minfo['poster_path'] # Retrieve",
"# Olympus olympus = media.Movie(\"Olympus Has Fallen\") olympus.storyline = (\"Disgraced",
"\"en/3/32/Ghostbusters_2016_film_poster.png\") ghostbusters.trailer_url = \"https://www.youtube.com/watch?v=w3ugHP-yZXw\" # Olympus olympus = media.Movie(\"Olympus Has",
"armor to fight evil.\") ironman.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/7/70/\" \"Ironmanposter.JPG\") ironman.trailer_url =",
"of \" \"humor is subjected to a rogue experiment that",
"Chuck \" \"and Bomb - to figure out what the",
"birds \" \"is visited by mysterious green piggies, it's \"",
"following \" \"his orders and protecting the world he feels",
"for movie_id in movie_ids: m = tmdb.Movies(movie_id) # Retrieve Image",
"unique mission becomes torn between following \" \"his orders and",
"= \"w500\" for movie_id in movie_ids: m = tmdb.Movies(movie_id) #",
"= image_base_url + image_width + minfo['poster_path'] # Retrieve Youtube Video",
"moon Pandora \" \"on a unique mission becomes torn between",
"image_width = \"w500\" for movie_id in movie_ids: m = tmdb.Movies(movie_id)",
"olympus.trailer_url = \"https://www.youtube.com/watch?v=vwx1f0kyNwI\" # Angry Birds angry_birds = media.Movie(\"The Angry",
"(\"https://upload.wikimedia.org/wikipedia/en/4/46/\" \"Deadpool_poster.jpg\") deadpool.trailer_url = \"https://www.youtube.com/watch?v=gtTfd6tISfw\" # Ghostbusters ghostbusters = media.Movie(\"Ghostbusters\")",
"\" \"weaponized suit of armor to fight evil.\") ironman.poster_url =",
"birds are so angry. When an \" \"island populated by",
"+ minfo['poster_path'] # Retrieve Youtube Video URL videos = m.videos()",
"\"paranormal enthusiasts <NAME> and Abby \" \"Yates, nuclear engineer <NAME>,",
"= (\"https://upload.wikimedia.org/wikipedia/en/f/\" \"f9/The_Angry_Birds_Movie_poster.png\") angry_birds.trailer_url = \"https://www.youtube.com/watch?v=1U2DKKqxHgE\" # Ironman ironman =",
"happy, flightless birds \" \"is visited by mysterious green piggies,",
"= (\"https://upload.wikimedia.org/wikipedia/en/b/bf/\" \"Olympus_Has_Fallen_poster.jpg\") olympus.trailer_url = \"https://www.youtube.com/watch?v=vwx1f0kyNwI\" # Angry Birds angry_birds",
"by happy, flightless birds \" \"is visited by mysterious green",
"os import tmdbsimple as tmdb import media import fresh_tomatoes as",
"band together \" \"to stop the otherworldly threat.\") ghostbusters.poster_url =",
"\"the President from his kidnappers.\") olympus.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/b/bf/\" \"Olympus_Has_Fallen_poster.jpg\") olympus.trailer_url",
"(\"Following a ghost invasion of Manhattan, \" \"paranormal enthusiasts <NAME>",
"Afghan cave, \" \"billionaire engineer <NAME> creates a unique \"",
"movie_ids = [271110, 297761, 246655, 278154, 135397, 188927] # Get",
"\"to stop the otherworldly threat.\") ghostbusters.poster_url = (\"https://upload.wikimedia.org/wikipedia/\" \"en/3/32/Ghostbusters_2016_film_poster.png\") ghostbusters.trailer_url",
"home.\") avatar.poster_url = (\"https://upload.wikimedia.org/wikipedia/\" \"en/b/b0/Avatar-Teaser-Poster.jpg\") avatar.trailer_url = \"https://www.youtube.com/watch?v=-9ceBgWV8io\" # Deadpool",
"angry_birds.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/f/\" \"f9/The_Angry_Birds_Movie_poster.png\") angry_birds.trailer_url = \"https://www.youtube.com/watch?v=1U2DKKqxHgE\" # Ironman ironman",
"Angry Birds angry_birds = media.Movie(\"The Angry Birds Movie\") angry_birds.storyline =",
"ft movies = [] if os.environ.get('TMDB_API', False): # Retrieve API",
"Olympus olympus = media.Movie(\"Olympus Has Fallen\") olympus.storyline = (\"Disgraced Secret",
"feels is \" \"his home.\") avatar.poster_url = (\"https://upload.wikimedia.org/wikipedia/\" \"en/b/b0/Avatar-Teaser-Poster.jpg\") avatar.trailer_url",
"a unique mission becomes torn between following \" \"his orders",
"deadpool.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/4/46/\" \"Deadpool_poster.jpg\") deadpool.trailer_url = \"https://www.youtube.com/watch?v=gtTfd6tISfw\" # Ghostbusters ghostbusters",
"threat.\") ghostbusters.poster_url = (\"https://upload.wikimedia.org/wikipedia/\" \"en/3/32/Ghostbusters_2016_film_poster.png\") ghostbusters.trailer_url = \"https://www.youtube.com/watch?v=w3ugHP-yZXw\" # Olympus",
"youtube_url = 'https://youtube.com/watch?v=' + video['key'] # Append Movie object movie",
"# Ironman ironman = media.Movie(\"Iron Man\") ironman.storyline = (\"After being",
"to rescue \" \"the President from his kidnappers.\") olympus.poster_url =",
"= m.videos() video = videos['results'][0] youtube_url = 'https://youtube.com/watch?v=' + video['key']",
"\"on a unique mission becomes torn between following \" \"his",
"powers and a \" \"quest for revenge.\") deadpool.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/4/46/\"",
"\"his orders and protecting the world he feels is \"",
"the moon Pandora \" \"on a unique mission becomes torn",
"morbid sense of \" \"humor is subjected to a rogue",
"ghostbusters.poster_url = (\"https://upload.wikimedia.org/wikipedia/\" \"en/3/32/Ghostbusters_2016_film_poster.png\") ghostbusters.trailer_url = \"https://www.youtube.com/watch?v=w3ugHP-yZXw\" # Olympus olympus",
"subway worker <NAME> band together \" \"to stop the otherworldly",
"\" \"quest for revenge.\") deadpool.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/4/46/\" \"Deadpool_poster.jpg\") deadpool.trailer_url =",
"\"leaves him with accelerated healing powers and a \" \"quest",
"fight evil.\") ironman.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/7/70/\" \"Ironmanposter.JPG\") ironman.trailer_url = \"https://www.youtube.com/watch?v=8hYlB38asDY\" movies",
"\"f9/The_Angry_Birds_Movie_poster.png\") angry_birds.trailer_url = \"https://www.youtube.com/watch?v=1U2DKKqxHgE\" # Ironman ironman = media.Movie(\"Iron Man\")",
"False): # Retrieve API KEY tmdb.API_KEY = os.environ['TMDB_API'] # TMDB",
"held captive in an Afghan cave, \" \"billionaire engineer <NAME>",
"ironman = media.Movie(\"Iron Man\") ironman.storyline = (\"After being held captive",
"# Avatar avatar = media.Movie(\"Avatar\") avatar.storyline = (\"A paraplegic marine",
"\"weaponized suit of armor to fight evil.\") ironman.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/7/70/\"",
"= (\"https://upload.wikimedia.org/wikipedia/\" \"en/3/32/Ghostbusters_2016_film_poster.png\") ghostbusters.trailer_url = \"https://www.youtube.com/watch?v=w3ugHP-yZXw\" # Olympus olympus =",
"# Retrieve Youtube Video URL videos = m.videos() video =",
"\"Yates, nuclear engineer <NAME>, \" \"and subway worker <NAME> band",
"\" \"up to three unlikely outcasts - Red, Chuck \"",
"to the moon Pandora \" \"on a unique mission becomes",
"\"Banning works with national security to rescue \" \"the President",
"between following \" \"his orders and protecting the world he",
"out what the pigs are up \" \"to.\") angry_birds.poster_url =",
"his kidnappers.\") olympus.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/b/bf/\" \"Olympus_Has_Fallen_poster.jpg\") olympus.trailer_url = \"https://www.youtube.com/watch?v=vwx1f0kyNwI\" #",
"it's \" \"up to three unlikely outcasts - Red, Chuck",
"= videos['results'][0] youtube_url = 'https://youtube.com/watch?v=' + video['key'] # Append Movie",
"sense of \" \"humor is subjected to a rogue experiment",
"Avatar avatar = media.Movie(\"Avatar\") avatar.storyline = (\"A paraplegic marine dispatched",
"import media import fresh_tomatoes as ft movies = [] if",
"m.videos() video = videos['results'][0] youtube_url = 'https://youtube.com/watch?v=' + video['key'] #",
"as ft movies = [] if os.environ.get('TMDB_API', False): # Retrieve",
"object movie = media.Movie(m.title) movie.storyline = m.overview movie.poster_url = poster_image_url",
"\"https://www.youtube.com/watch?v=-9ceBgWV8io\" # Deadpool deadpool = media.Movie(\"Deadpool\") deadpool.storyline = (\"A fast-talking",
"him with accelerated healing powers and a \" \"quest for",
"Red, Chuck \" \"and Bomb - to figure out what",
"Manhattan, \" \"paranormal enthusiasts <NAME> and Abby \" \"Yates, nuclear",
"(and former \" \"presidential guard) <NAME> finds himself \" \"trapped",
"Secret Service agent (and former \" \"presidential guard) <NAME> finds",
"the White House in the wake of a \" \"terrorist",
"# Angry Birds angry_birds = media.Movie(\"The Angry Birds Movie\") angry_birds.storyline",
"tmdb.API_KEY = os.environ['TMDB_API'] # TMDB Movie Ids movie_ids = [271110,",
"to figure out what the pigs are up \" \"to.\")",
"\"https://www.youtube.com/watch?v=1U2DKKqxHgE\" # Ironman ironman = media.Movie(\"Iron Man\") ironman.storyline = (\"After",
"avatar = media.Movie(\"Avatar\") avatar.storyline = (\"A paraplegic marine dispatched to",
"finds himself \" \"trapped inside the White House in the",
"invasion of Manhattan, \" \"paranormal enthusiasts <NAME> and Abby \"",
"# TMDB Movie Ids movie_ids = [271110, 297761, 246655, 278154,",
"ironman.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/7/70/\" \"Ironmanposter.JPG\") ironman.trailer_url = \"https://www.youtube.com/watch?v=8hYlB38asDY\" movies = [avatar,",
"to fight evil.\") ironman.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/7/70/\" \"Ironmanposter.JPG\") ironman.trailer_url = \"https://www.youtube.com/watch?v=8hYlB38asDY\"",
"Pandora \" \"on a unique mission becomes torn between following",
"using his inside knowledge, \" \"Banning works with national security",
"paraplegic marine dispatched to the moon Pandora \" \"on a",
"captive in an Afghan cave, \" \"billionaire engineer <NAME> creates",
"that \" \"leaves him with accelerated healing powers and a",
"import tmdbsimple as tmdb import media import fresh_tomatoes as ft",
"\"quest for revenge.\") deadpool.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/4/46/\" \"Deadpool_poster.jpg\") deadpool.trailer_url = \"https://www.youtube.com/watch?v=gtTfd6tISfw\"",
"= [271110, 297761, 246655, 278154, 135397, 188927] # Get Configuration",
"in movie_ids: m = tmdb.Movies(movie_id) # Retrieve Image URL minfo",
"image_width + minfo['poster_path'] # Retrieve Youtube Video URL videos =",
"Movie object movie = media.Movie(m.title) movie.storyline = m.overview movie.poster_url =",
"\"https://www.youtube.com/watch?v=8hYlB38asDY\" movies = [avatar, deadpool, ghostbusters, olympus, angry_birds, ironman] ft.open_movies_page(movies)",
"security to rescue \" \"the President from his kidnappers.\") olympus.poster_url",
"olympus.storyline = (\"Disgraced Secret Service agent (and former \" \"presidential",
"a rogue experiment that \" \"leaves him with accelerated healing",
"movie.poster_url = poster_image_url movie.trailer_url = youtube_url movies.append(movie) else: # Avatar",
"\"Deadpool_poster.jpg\") deadpool.trailer_url = \"https://www.youtube.com/watch?v=gtTfd6tISfw\" # Ghostbusters ghostbusters = media.Movie(\"Ghostbusters\") ghostbusters.storyline",
"Ghostbusters ghostbusters = media.Movie(\"Ghostbusters\") ghostbusters.storyline = (\"Following a ghost invasion",
"\"island populated by happy, flightless birds \" \"is visited by",
"a \" \"terrorist attack; using his inside knowledge, \" \"Banning",
"angry_birds = media.Movie(\"The Angry Birds Movie\") angry_birds.storyline = (\"Find out",
"minfo['poster_path'] # Retrieve Youtube Video URL videos = m.videos() video",
"Youtube Video URL videos = m.videos() video = videos['results'][0] youtube_url",
"nuclear engineer <NAME>, \" \"and subway worker <NAME> band together",
"subjected to a rogue experiment that \" \"leaves him with",
"\" \"his orders and protecting the world he feels is",
"the birds are so angry. When an \" \"island populated",
"inside the White House in the wake of a \"",
"an Afghan cave, \" \"billionaire engineer <NAME> creates a unique",
"= (\"A paraplegic marine dispatched to the moon Pandora \"",
"video['key'] # Append Movie object movie = media.Movie(m.title) movie.storyline =",
"# Retrieve Image URL minfo = m.info() poster_image_url = image_base_url",
"(\"Disgraced Secret Service agent (and former \" \"presidential guard) <NAME>",
"videos = m.videos() video = videos['results'][0] youtube_url = 'https://youtube.com/watch?v=' +",
"tmdb.Configuration().info() image_base_url = configuration['images']['secure_base_url'] image_width = \"w500\" for movie_id in",
"an \" \"island populated by happy, flightless birds \" \"is",
"os.environ['TMDB_API'] # TMDB Movie Ids movie_ids = [271110, 297761, 246655,",
"Man\") ironman.storyline = (\"After being held captive in an Afghan",
"image_base_url = configuration['images']['secure_base_url'] image_width = \"w500\" for movie_id in movie_ids:",
"\"en/b/b0/Avatar-Teaser-Poster.jpg\") avatar.trailer_url = \"https://www.youtube.com/watch?v=-9ceBgWV8io\" # Deadpool deadpool = media.Movie(\"Deadpool\") deadpool.storyline",
"unlikely outcasts - Red, Chuck \" \"and Bomb - to",
"\" \"his home.\") avatar.poster_url = (\"https://upload.wikimedia.org/wikipedia/\" \"en/b/b0/Avatar-Teaser-Poster.jpg\") avatar.trailer_url = \"https://www.youtube.com/watch?v=-9ceBgWV8io\"",
"= media.Movie(m.title) movie.storyline = m.overview movie.poster_url = poster_image_url movie.trailer_url =",
"as tmdb import media import fresh_tomatoes as ft movies =",
"mission becomes torn between following \" \"his orders and protecting",
"video = videos['results'][0] youtube_url = 'https://youtube.com/watch?v=' + video['key'] # Append",
"os.environ.get('TMDB_API', False): # Retrieve API KEY tmdb.API_KEY = os.environ['TMDB_API'] #",
"<NAME>, \" \"and subway worker <NAME> band together \" \"to",
"\" \"is visited by mysterious green piggies, it's \" \"up",
"= (\"A fast-talking mercenary with a morbid sense of \"",
"experiment that \" \"leaves him with accelerated healing powers and",
"\" \"leaves him with accelerated healing powers and a \"",
"Retrieve Youtube Video URL videos = m.videos() video = videos['results'][0]",
"\"https://www.youtube.com/watch?v=vwx1f0kyNwI\" # Angry Birds angry_birds = media.Movie(\"The Angry Birds Movie\")",
"avatar.trailer_url = \"https://www.youtube.com/watch?v=-9ceBgWV8io\" # Deadpool deadpool = media.Movie(\"Deadpool\") deadpool.storyline =",
"(\"https://upload.wikimedia.org/wikipedia/\" \"en/b/b0/Avatar-Teaser-Poster.jpg\") avatar.trailer_url = \"https://www.youtube.com/watch?v=-9ceBgWV8io\" # Deadpool deadpool = media.Movie(\"Deadpool\")",
"of armor to fight evil.\") ironman.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/7/70/\" \"Ironmanposter.JPG\") ironman.trailer_url",
"what the pigs are up \" \"to.\") angry_birds.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/f/\"",
"\"his home.\") avatar.poster_url = (\"https://upload.wikimedia.org/wikipedia/\" \"en/b/b0/Avatar-Teaser-Poster.jpg\") avatar.trailer_url = \"https://www.youtube.com/watch?v=-9ceBgWV8io\" #",
"deadpool.trailer_url = \"https://www.youtube.com/watch?v=gtTfd6tISfw\" # Ghostbusters ghostbusters = media.Movie(\"Ghostbusters\") ghostbusters.storyline =",
"so angry. When an \" \"island populated by happy, flightless",
"= media.Movie(\"Olympus Has Fallen\") olympus.storyline = (\"Disgraced Secret Service agent",
"(\"After being held captive in an Afghan cave, \" \"billionaire",
"minfo = m.info() poster_image_url = image_base_url + image_width + minfo['poster_path']",
"Ids movie_ids = [271110, 297761, 246655, 278154, 135397, 188927] #",
"Fallen\") olympus.storyline = (\"Disgraced Secret Service agent (and former \"",
"URL minfo = m.info() poster_image_url = image_base_url + image_width +",
"import fresh_tomatoes as ft movies = [] if os.environ.get('TMDB_API', False):",
"Birds Movie\") angry_birds.storyline = (\"Find out why the birds are",
"out why the birds are so angry. When an \"",
"mysterious green piggies, it's \" \"up to three unlikely outcasts",
"poster_image_url movie.trailer_url = youtube_url movies.append(movie) else: # Avatar avatar =",
"= m.info() poster_image_url = image_base_url + image_width + minfo['poster_path'] #",
"\"https://www.youtube.com/watch?v=gtTfd6tISfw\" # Ghostbusters ghostbusters = media.Movie(\"Ghostbusters\") ghostbusters.storyline = (\"Following a",
"Append Movie object movie = media.Movie(m.title) movie.storyline = m.overview movie.poster_url",
"up \" \"to.\") angry_birds.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/f/\" \"f9/The_Angry_Birds_Movie_poster.png\") angry_birds.trailer_url = \"https://www.youtube.com/watch?v=1U2DKKqxHgE\"",
"evil.\") ironman.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/7/70/\" \"Ironmanposter.JPG\") ironman.trailer_url = \"https://www.youtube.com/watch?v=8hYlB38asDY\" movies =",
"<NAME> finds himself \" \"trapped inside the White House in",
"suit of armor to fight evil.\") ironman.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/7/70/\" \"Ironmanposter.JPG\")",
"+ video['key'] # Append Movie object movie = media.Movie(m.title) movie.storyline",
"(\"A paraplegic marine dispatched to the moon Pandora \" \"on",
"Service agent (and former \" \"presidential guard) <NAME> finds himself",
"figure out what the pigs are up \" \"to.\") angry_birds.poster_url",
"image_base_url + image_width + minfo['poster_path'] # Retrieve Youtube Video URL",
"\"https://www.youtube.com/watch?v=w3ugHP-yZXw\" # Olympus olympus = media.Movie(\"Olympus Has Fallen\") olympus.storyline =",
"former \" \"presidential guard) <NAME> finds himself \" \"trapped inside",
"being held captive in an Afghan cave, \" \"billionaire engineer",
"ironman.storyline = (\"After being held captive in an Afghan cave,",
"= tmdb.Movies(movie_id) # Retrieve Image URL minfo = m.info() poster_image_url",
"\"up to three unlikely outcasts - Red, Chuck \" \"and",
"angry_birds.storyline = (\"Find out why the birds are so angry.",
"\" \"humor is subjected to a rogue experiment that \"",
"pigs are up \" \"to.\") angry_birds.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/f/\" \"f9/The_Angry_Birds_Movie_poster.png\") angry_birds.trailer_url",
"a morbid sense of \" \"humor is subjected to a",
"protecting the world he feels is \" \"his home.\") avatar.poster_url",
"= media.Movie(\"Avatar\") avatar.storyline = (\"A paraplegic marine dispatched to the",
"outcasts - Red, Chuck \" \"and Bomb - to figure",
"cave, \" \"billionaire engineer <NAME> creates a unique \" \"weaponized",
"media.Movie(m.title) movie.storyline = m.overview movie.poster_url = poster_image_url movie.trailer_url = youtube_url",
"are up \" \"to.\") angry_birds.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/f/\" \"f9/The_Angry_Birds_Movie_poster.png\") angry_birds.trailer_url =",
"marine dispatched to the moon Pandora \" \"on a unique",
"Ironman ironman = media.Movie(\"Iron Man\") ironman.storyline = (\"After being held",
"[271110, 297761, 246655, 278154, 135397, 188927] # Get Configuration configuration",
"+ image_width + minfo['poster_path'] # Retrieve Youtube Video URL videos",
"<NAME> creates a unique \" \"weaponized suit of armor to",
"three unlikely outcasts - Red, Chuck \" \"and Bomb -",
"\" \"Yates, nuclear engineer <NAME>, \" \"and subway worker <NAME>",
"angry. When an \" \"island populated by happy, flightless birds",
"torn between following \" \"his orders and protecting the world",
"m = tmdb.Movies(movie_id) # Retrieve Image URL minfo = m.info()",
"media.Movie(\"Deadpool\") deadpool.storyline = (\"A fast-talking mercenary with a morbid sense",
"media.Movie(\"Iron Man\") ironman.storyline = (\"After being held captive in an",
"\"Ironmanposter.JPG\") ironman.trailer_url = \"https://www.youtube.com/watch?v=8hYlB38asDY\" movies = [avatar, deadpool, ghostbusters, olympus,",
"media.Movie(\"Olympus Has Fallen\") olympus.storyline = (\"Disgraced Secret Service agent (and",
"= configuration['images']['secure_base_url'] image_width = \"w500\" for movie_id in movie_ids: m",
"= media.Movie(\"Deadpool\") deadpool.storyline = (\"A fast-talking mercenary with a morbid",
"Get Configuration configuration = tmdb.Configuration().info() image_base_url = configuration['images']['secure_base_url'] image_width =",
"\" \"Banning works with national security to rescue \" \"the",
"himself \" \"trapped inside the White House in the wake",
"deadpool = media.Movie(\"Deadpool\") deadpool.storyline = (\"A fast-talking mercenary with a",
"= media.Movie(\"Ghostbusters\") ghostbusters.storyline = (\"Following a ghost invasion of Manhattan,",
"<NAME> and Abby \" \"Yates, nuclear engineer <NAME>, \" \"and",
"URL videos = m.videos() video = videos['results'][0] youtube_url = 'https://youtube.com/watch?v='",
"\"and Bomb - to figure out what the pigs are",
"# Ghostbusters ghostbusters = media.Movie(\"Ghostbusters\") ghostbusters.storyline = (\"Following a ghost",
"\" \"the President from his kidnappers.\") olympus.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/b/bf/\" \"Olympus_Has_Fallen_poster.jpg\")",
"movie_id in movie_ids: m = tmdb.Movies(movie_id) # Retrieve Image URL",
"= (\"https://upload.wikimedia.org/wikipedia/en/4/46/\" \"Deadpool_poster.jpg\") deadpool.trailer_url = \"https://www.youtube.com/watch?v=gtTfd6tISfw\" # Ghostbusters ghostbusters =",
"in the wake of a \" \"terrorist attack; using his",
"= 'https://youtube.com/watch?v=' + video['key'] # Append Movie object movie =",
"national security to rescue \" \"the President from his kidnappers.\")",
"the otherworldly threat.\") ghostbusters.poster_url = (\"https://upload.wikimedia.org/wikipedia/\" \"en/3/32/Ghostbusters_2016_film_poster.png\") ghostbusters.trailer_url = \"https://www.youtube.com/watch?v=w3ugHP-yZXw\"",
"m.overview movie.poster_url = poster_image_url movie.trailer_url = youtube_url movies.append(movie) else: #",
"\"to.\") angry_birds.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/f/\" \"f9/The_Angry_Birds_Movie_poster.png\") angry_birds.trailer_url = \"https://www.youtube.com/watch?v=1U2DKKqxHgE\" # Ironman",
"with accelerated healing powers and a \" \"quest for revenge.\")",
"avatar.poster_url = (\"https://upload.wikimedia.org/wikipedia/\" \"en/b/b0/Avatar-Teaser-Poster.jpg\") avatar.trailer_url = \"https://www.youtube.com/watch?v=-9ceBgWV8io\" # Deadpool deadpool",
"297761, 246655, 278154, 135397, 188927] # Get Configuration configuration =",
"tmdb import media import fresh_tomatoes as ft movies = []",
"healing powers and a \" \"quest for revenge.\") deadpool.poster_url =",
"revenge.\") deadpool.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/4/46/\" \"Deadpool_poster.jpg\") deadpool.trailer_url = \"https://www.youtube.com/watch?v=gtTfd6tISfw\" # Ghostbusters",
"KEY tmdb.API_KEY = os.environ['TMDB_API'] # TMDB Movie Ids movie_ids =",
"mercenary with a morbid sense of \" \"humor is subjected",
"Retrieve API KEY tmdb.API_KEY = os.environ['TMDB_API'] # TMDB Movie Ids",
"= m.overview movie.poster_url = poster_image_url movie.trailer_url = youtube_url movies.append(movie) else:",
"green piggies, it's \" \"up to three unlikely outcasts -",
"configuration['images']['secure_base_url'] image_width = \"w500\" for movie_id in movie_ids: m =",
"knowledge, \" \"Banning works with national security to rescue \"",
"(\"https://upload.wikimedia.org/wikipedia/\" \"en/3/32/Ghostbusters_2016_film_poster.png\") ghostbusters.trailer_url = \"https://www.youtube.com/watch?v=w3ugHP-yZXw\" # Olympus olympus = media.Movie(\"Olympus",
"media import fresh_tomatoes as ft movies = [] if os.environ.get('TMDB_API',",
"attack; using his inside knowledge, \" \"Banning works with national",
"with national security to rescue \" \"the President from his",
"if os.environ.get('TMDB_API', False): # Retrieve API KEY tmdb.API_KEY = os.environ['TMDB_API']",
"becomes torn between following \" \"his orders and protecting the",
"\"billionaire engineer <NAME> creates a unique \" \"weaponized suit of",
"\" \"terrorist attack; using his inside knowledge, \" \"Banning works",
"tmdbsimple as tmdb import media import fresh_tomatoes as ft movies",
"ghost invasion of Manhattan, \" \"paranormal enthusiasts <NAME> and Abby",
"= (\"After being held captive in an Afghan cave, \"",
"deadpool.storyline = (\"A fast-talking mercenary with a morbid sense of",
"movies.append(movie) else: # Avatar avatar = media.Movie(\"Avatar\") avatar.storyline = (\"A",
"ghostbusters.storyline = (\"Following a ghost invasion of Manhattan, \" \"paranormal",
"= poster_image_url movie.trailer_url = youtube_url movies.append(movie) else: # Avatar avatar",
"youtube_url movies.append(movie) else: # Avatar avatar = media.Movie(\"Avatar\") avatar.storyline =",
"Bomb - to figure out what the pigs are up",
"flightless birds \" \"is visited by mysterious green piggies, it's",
"wake of a \" \"terrorist attack; using his inside knowledge,",
"House in the wake of a \" \"terrorist attack; using",
"movies = [] if os.environ.get('TMDB_API', False): # Retrieve API KEY",
"Has Fallen\") olympus.storyline = (\"Disgraced Secret Service agent (and former",
"278154, 135397, 188927] # Get Configuration configuration = tmdb.Configuration().info() image_base_url",
"together \" \"to stop the otherworldly threat.\") ghostbusters.poster_url = (\"https://upload.wikimedia.org/wikipedia/\"",
"inside knowledge, \" \"Banning works with national security to rescue",
"movie = media.Movie(m.title) movie.storyline = m.overview movie.poster_url = poster_image_url movie.trailer_url",
"worker <NAME> band together \" \"to stop the otherworldly threat.\")",
"ghostbusters.trailer_url = \"https://www.youtube.com/watch?v=w3ugHP-yZXw\" # Olympus olympus = media.Movie(\"Olympus Has Fallen\")",
"the wake of a \" \"terrorist attack; using his inside",
"enthusiasts <NAME> and Abby \" \"Yates, nuclear engineer <NAME>, \"",
"he feels is \" \"his home.\") avatar.poster_url = (\"https://upload.wikimedia.org/wikipedia/\" \"en/b/b0/Avatar-Teaser-Poster.jpg\")",
"dispatched to the moon Pandora \" \"on a unique mission",
"movie.trailer_url = youtube_url movies.append(movie) else: # Avatar avatar = media.Movie(\"Avatar\")",
"angry_birds.trailer_url = \"https://www.youtube.com/watch?v=1U2DKKqxHgE\" # Ironman ironman = media.Movie(\"Iron Man\") ironman.storyline",
"\" \"and Bomb - to figure out what the pigs",
"\" \"paranormal enthusiasts <NAME> and Abby \" \"Yates, nuclear engineer",
"to three unlikely outcasts - Red, Chuck \" \"and Bomb",
"= os.environ['TMDB_API'] # TMDB Movie Ids movie_ids = [271110, 297761,",
"= \"https://www.youtube.com/watch?v=gtTfd6tISfw\" # Ghostbusters ghostbusters = media.Movie(\"Ghostbusters\") ghostbusters.storyline = (\"Following",
"= [] if os.environ.get('TMDB_API', False): # Retrieve API KEY tmdb.API_KEY",
"\" \"and subway worker <NAME> band together \" \"to stop",
"\"presidential guard) <NAME> finds himself \" \"trapped inside the White",
"the pigs are up \" \"to.\") angry_birds.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/f/\" \"f9/The_Angry_Birds_Movie_poster.png\")",
"is \" \"his home.\") avatar.poster_url = (\"https://upload.wikimedia.org/wikipedia/\" \"en/b/b0/Avatar-Teaser-Poster.jpg\") avatar.trailer_url =",
"fast-talking mercenary with a morbid sense of \" \"humor is",
"\" \"to.\") angry_birds.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/f/\" \"f9/The_Angry_Birds_Movie_poster.png\") angry_birds.trailer_url = \"https://www.youtube.com/watch?v=1U2DKKqxHgE\" #",
"piggies, it's \" \"up to three unlikely outcasts - Red,",
"to a rogue experiment that \" \"leaves him with accelerated",
"(\"A fast-talking mercenary with a morbid sense of \" \"humor",
"movie.storyline = m.overview movie.poster_url = poster_image_url movie.trailer_url = youtube_url movies.append(movie)",
"\" \"trapped inside the White House in the wake of",
"\"trapped inside the White House in the wake of a",
"movie_ids: m = tmdb.Movies(movie_id) # Retrieve Image URL minfo =",
"(\"Find out why the birds are so angry. When an",
"and protecting the world he feels is \" \"his home.\")",
"246655, 278154, 135397, 188927] # Get Configuration configuration = tmdb.Configuration().info()",
"works with national security to rescue \" \"the President from",
"of a \" \"terrorist attack; using his inside knowledge, \"",
"# Get Configuration configuration = tmdb.Configuration().info() image_base_url = configuration['images']['secure_base_url'] image_width",
"with a morbid sense of \" \"humor is subjected to",
"= media.Movie(\"The Angry Birds Movie\") angry_birds.storyline = (\"Find out why",
"= \"https://www.youtube.com/watch?v=1U2DKKqxHgE\" # Ironman ironman = media.Movie(\"Iron Man\") ironman.storyline =",
"a unique \" \"weaponized suit of armor to fight evil.\")",
"his inside knowledge, \" \"Banning works with national security to",
"= (\"Disgraced Secret Service agent (and former \" \"presidential guard)",
"agent (and former \" \"presidential guard) <NAME> finds himself \"",
"of Manhattan, \" \"paranormal enthusiasts <NAME> and Abby \" \"Yates,",
"Deadpool deadpool = media.Movie(\"Deadpool\") deadpool.storyline = (\"A fast-talking mercenary with",
"= \"https://www.youtube.com/watch?v=8hYlB38asDY\" movies = [avatar, deadpool, ghostbusters, olympus, angry_birds, ironman]",
"API KEY tmdb.API_KEY = os.environ['TMDB_API'] # TMDB Movie Ids movie_ids",
"- to figure out what the pigs are up \"",
"stop the otherworldly threat.\") ghostbusters.poster_url = (\"https://upload.wikimedia.org/wikipedia/\" \"en/3/32/Ghostbusters_2016_film_poster.png\") ghostbusters.trailer_url =",
"olympus.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/b/bf/\" \"Olympus_Has_Fallen_poster.jpg\") olympus.trailer_url = \"https://www.youtube.com/watch?v=vwx1f0kyNwI\" # Angry Birds",
"why the birds are so angry. When an \" \"island",
"unique \" \"weaponized suit of armor to fight evil.\") ironman.poster_url",
"\" \"on a unique mission becomes torn between following \"",
"= media.Movie(\"Iron Man\") ironman.storyline = (\"After being held captive in",
"creates a unique \" \"weaponized suit of armor to fight",
"engineer <NAME> creates a unique \" \"weaponized suit of armor",
"is subjected to a rogue experiment that \" \"leaves him",
"\"w500\" for movie_id in movie_ids: m = tmdb.Movies(movie_id) # Retrieve",
"\"humor is subjected to a rogue experiment that \" \"leaves",
"media.Movie(\"The Angry Birds Movie\") angry_birds.storyline = (\"Find out why the",
"import os import tmdbsimple as tmdb import media import fresh_tomatoes",
"= (\"Find out why the birds are so angry. When",
"media.Movie(\"Avatar\") avatar.storyline = (\"A paraplegic marine dispatched to the moon",
"fresh_tomatoes as ft movies = [] if os.environ.get('TMDB_API', False): #",
"are so angry. When an \" \"island populated by happy,",
"poster_image_url = image_base_url + image_width + minfo['poster_path'] # Retrieve Youtube",
"and Abby \" \"Yates, nuclear engineer <NAME>, \" \"and subway",
"from his kidnappers.\") olympus.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/b/bf/\" \"Olympus_Has_Fallen_poster.jpg\") olympus.trailer_url = \"https://www.youtube.com/watch?v=vwx1f0kyNwI\"",
"else: # Avatar avatar = media.Movie(\"Avatar\") avatar.storyline = (\"A paraplegic",
"visited by mysterious green piggies, it's \" \"up to three",
"configuration = tmdb.Configuration().info() image_base_url = configuration['images']['secure_base_url'] image_width = \"w500\" for",
"Birds angry_birds = media.Movie(\"The Angry Birds Movie\") angry_birds.storyline = (\"Find",
"TMDB Movie Ids movie_ids = [271110, 297761, 246655, 278154, 135397,",
"(\"https://upload.wikimedia.org/wikipedia/en/f/\" \"f9/The_Angry_Birds_Movie_poster.png\") angry_birds.trailer_url = \"https://www.youtube.com/watch?v=1U2DKKqxHgE\" # Ironman ironman = media.Movie(\"Iron",
"orders and protecting the world he feels is \" \"his",
"olympus = media.Movie(\"Olympus Has Fallen\") olympus.storyline = (\"Disgraced Secret Service",
"President from his kidnappers.\") olympus.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/b/bf/\" \"Olympus_Has_Fallen_poster.jpg\") olympus.trailer_url =",
"= tmdb.Configuration().info() image_base_url = configuration['images']['secure_base_url'] image_width = \"w500\" for movie_id",
"ironman.trailer_url = \"https://www.youtube.com/watch?v=8hYlB38asDY\" movies = [avatar, deadpool, ghostbusters, olympus, angry_birds,",
"Video URL videos = m.videos() video = videos['results'][0] youtube_url =",
"accelerated healing powers and a \" \"quest for revenge.\") deadpool.poster_url",
"# Retrieve API KEY tmdb.API_KEY = os.environ['TMDB_API'] # TMDB Movie",
"avatar.storyline = (\"A paraplegic marine dispatched to the moon Pandora",
"otherworldly threat.\") ghostbusters.poster_url = (\"https://upload.wikimedia.org/wikipedia/\" \"en/3/32/Ghostbusters_2016_film_poster.png\") ghostbusters.trailer_url = \"https://www.youtube.com/watch?v=w3ugHP-yZXw\" #",
"Configuration configuration = tmdb.Configuration().info() image_base_url = configuration['images']['secure_base_url'] image_width = \"w500\"",
"- Red, Chuck \" \"and Bomb - to figure out",
"White House in the wake of a \" \"terrorist attack;",
"135397, 188927] # Get Configuration configuration = tmdb.Configuration().info() image_base_url =",
"rogue experiment that \" \"leaves him with accelerated healing powers",
"\"and subway worker <NAME> band together \" \"to stop the",
"media.Movie(\"Ghostbusters\") ghostbusters.storyline = (\"Following a ghost invasion of Manhattan, \"",
"engineer <NAME>, \" \"and subway worker <NAME> band together \"",
"= \"https://www.youtube.com/watch?v=w3ugHP-yZXw\" # Olympus olympus = media.Movie(\"Olympus Has Fallen\") olympus.storyline",
"(\"https://upload.wikimedia.org/wikipedia/en/7/70/\" \"Ironmanposter.JPG\") ironman.trailer_url = \"https://www.youtube.com/watch?v=8hYlB38asDY\" movies = [avatar, deadpool, ghostbusters,",
"a \" \"quest for revenge.\") deadpool.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/4/46/\" \"Deadpool_poster.jpg\") deadpool.trailer_url",
"= youtube_url movies.append(movie) else: # Avatar avatar = media.Movie(\"Avatar\") avatar.storyline",
"\" \"presidential guard) <NAME> finds himself \" \"trapped inside the",
"188927] # Get Configuration configuration = tmdb.Configuration().info() image_base_url = configuration['images']['secure_base_url']",
"\" \"island populated by happy, flightless birds \" \"is visited",
"Abby \" \"Yates, nuclear engineer <NAME>, \" \"and subway worker",
"When an \" \"island populated by happy, flightless birds \"",
"kidnappers.\") olympus.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/b/bf/\" \"Olympus_Has_Fallen_poster.jpg\") olympus.trailer_url = \"https://www.youtube.com/watch?v=vwx1f0kyNwI\" # Angry",
"by mysterious green piggies, it's \" \"up to three unlikely",
"# Deadpool deadpool = media.Movie(\"Deadpool\") deadpool.storyline = (\"A fast-talking mercenary",
"Image URL minfo = m.info() poster_image_url = image_base_url + image_width",
"a ghost invasion of Manhattan, \" \"paranormal enthusiasts <NAME> and",
"populated by happy, flightless birds \" \"is visited by mysterious",
"(\"https://upload.wikimedia.org/wikipedia/en/b/bf/\" \"Olympus_Has_Fallen_poster.jpg\") olympus.trailer_url = \"https://www.youtube.com/watch?v=vwx1f0kyNwI\" # Angry Birds angry_birds =",
"Movie Ids movie_ids = [271110, 297761, 246655, 278154, 135397, 188927]",
"and a \" \"quest for revenge.\") deadpool.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/4/46/\" \"Deadpool_poster.jpg\")",
"= \"https://www.youtube.com/watch?v=-9ceBgWV8io\" # Deadpool deadpool = media.Movie(\"Deadpool\") deadpool.storyline = (\"A",
"guard) <NAME> finds himself \" \"trapped inside the White House",
"Retrieve Image URL minfo = m.info() poster_image_url = image_base_url +",
"for revenge.\") deadpool.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/4/46/\" \"Deadpool_poster.jpg\") deadpool.trailer_url = \"https://www.youtube.com/watch?v=gtTfd6tISfw\" #",
"# Append Movie object movie = media.Movie(m.title) movie.storyline = m.overview",
"<NAME> band together \" \"to stop the otherworldly threat.\") ghostbusters.poster_url",
"videos['results'][0] youtube_url = 'https://youtube.com/watch?v=' + video['key'] # Append Movie object",
"[] if os.environ.get('TMDB_API', False): # Retrieve API KEY tmdb.API_KEY =",
"\"terrorist attack; using his inside knowledge, \" \"Banning works with",
"= (\"Following a ghost invasion of Manhattan, \" \"paranormal enthusiasts",
"= \"https://www.youtube.com/watch?v=vwx1f0kyNwI\" # Angry Birds angry_birds = media.Movie(\"The Angry Birds",
"world he feels is \" \"his home.\") avatar.poster_url = (\"https://upload.wikimedia.org/wikipedia/\"",
"= (\"https://upload.wikimedia.org/wikipedia/en/7/70/\" \"Ironmanposter.JPG\") ironman.trailer_url = \"https://www.youtube.com/watch?v=8hYlB38asDY\" movies = [avatar, deadpool,",
"the world he feels is \" \"his home.\") avatar.poster_url =",
"ghostbusters = media.Movie(\"Ghostbusters\") ghostbusters.storyline = (\"Following a ghost invasion of",
"\" \"billionaire engineer <NAME> creates a unique \" \"weaponized suit",
"in an Afghan cave, \" \"billionaire engineer <NAME> creates a",
"\" \"to stop the otherworldly threat.\") ghostbusters.poster_url = (\"https://upload.wikimedia.org/wikipedia/\" \"en/3/32/Ghostbusters_2016_film_poster.png\")",
"\"Olympus_Has_Fallen_poster.jpg\") olympus.trailer_url = \"https://www.youtube.com/watch?v=vwx1f0kyNwI\" # Angry Birds angry_birds = media.Movie(\"The",
"Movie\") angry_birds.storyline = (\"Find out why the birds are so",
"rescue \" \"the President from his kidnappers.\") olympus.poster_url = (\"https://upload.wikimedia.org/wikipedia/en/b/bf/\"",
"Angry Birds Movie\") angry_birds.storyline = (\"Find out why the birds",
"\"is visited by mysterious green piggies, it's \" \"up to",
"= (\"https://upload.wikimedia.org/wikipedia/\" \"en/b/b0/Avatar-Teaser-Poster.jpg\") avatar.trailer_url = \"https://www.youtube.com/watch?v=-9ceBgWV8io\" # Deadpool deadpool =",
"'https://youtube.com/watch?v=' + video['key'] # Append Movie object movie = media.Movie(m.title)"
] |
[
"= QtWidgets.QLabel(self.centralwidget) self.label_4.setObjectName(\"label_4\") self.horizontalLayout.addWidget(self.label_4) self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit_2.setObjectName(\"lineEdit_2\") self.horizontalLayout.addWidget(self.lineEdit_2) self.line_2",
"self.horizontalLayout.addWidget(self.combo_element_type) self.line = QtWidgets.QFrame(self.centralwidget) self.line.setFrameShape(QtWidgets.QFrame.VLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName(\"line\") self.horizontalLayout.addWidget(self.line) self.label_3 =",
"self.lineEdit_2.setObjectName(\"lineEdit_2\") self.horizontalLayout.addWidget(self.lineEdit_2) self.line_2 = QtWidgets.QFrame(self.centralwidget) self.line_2.setFrameShape(QtWidgets.QFrame.VLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName(\"line_2\") self.horizontalLayout.addWidget(self.line_2) self.verticalLayout.addLayout(self.horizontalLayout)",
"def retranslateUi(self, ElementsWindow): ElementsWindow.setWindowTitle( QtWidgets.QApplication.translate(\"ElementsWindow\", \"MainWindow\", None, -1)) self.btn_refresh.setToolTip( QtWidgets.QApplication.translate(\"ElementsWindow\",",
"self.menubar.setObjectName(\"menubar\") ElementsWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(ElementsWindow) self.statusbar.setEnabled(True) self.statusbar.setObjectName(\"statusbar\") ElementsWindow.setStatusBar(self.statusbar) self.retranslateUi(ElementsWindow) QtCore.QObject.connect(self.combo_element_type,",
"\", None, -1)) self.label.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Element type: \", None, -1))",
"self.verticalLayout.addWidget(self.tableElements) self.verticalLayout_2.addLayout(self.verticalLayout) ElementsWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar() self.menubar.setGeometry(QtCore.QRect(0, 0, 841, 22))",
"self.line_2 = QtWidgets.QFrame(self.centralwidget) self.line_2.setFrameShape(QtWidgets.QFrame.VLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName(\"line_2\") self.horizontalLayout.addWidget(self.line_2) self.verticalLayout.addLayout(self.horizontalLayout) self.tableElements =",
"= QtWidgets.QLabel(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.label.sizePolicy().hasHeightForWidth())",
"\", None, -1)) self.label_2.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Component: \", None, -1)) self.label_4.setText(",
"utf-8 -*- # Form implementation generated from reading ui file",
"QtCore.QObject.connect(self.combo_element_type, QtCore.SIGNAL(\"currentIndexChanged(QString)\"), ElementsWindow.combo_element_type) QtCore.QObject.connect(self.btn_refresh, QtCore.SIGNAL(\"clicked()\"), ElementsWindow.force_refresh) QtCore.QMetaObject.connectSlotsByName(ElementsWindow) def retranslateUi(self, ElementsWindow):",
"self.horizontalLayout.addWidget(self.btn_refresh) self.label = QtWidgets.QLabel(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"-1)) self.label_2.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Component: \", None, -1)) self.label_4.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \"",
"QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the table \", None, -1)) self.btn_refresh.setWhatsThis( QtWidgets.QApplication.translate(\"ElementsWindow\",",
"QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName(\"horizontalLayout\") self.btn_refresh = QtWidgets.QPushButton(self.centralwidget) self.btn_refresh.setCursor(QtCore.Qt.ClosedHandCursor) self.btn_refresh.setText(\"\") icon = QtGui.QIcon()",
"self.horizontalLayout.addWidget(self.line) self.label_3 = QtWidgets.QLabel(self.centralwidget) font = QtGui.QFont() font.setWeight(75) font.setBold(True) self.label_3.setFont(font)",
"= QtGui.QFont() font.setWeight(75) font.setBold(True) self.label.setFont(font) self.label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)",
"Wed Jun 16 14:29:03 2021 # by: pyside2-uic running on",
"self.combo_element_type.setSizeAdjustPolicy( QtWidgets.QComboBox.AdjustToContents) self.combo_element_type.setObjectName(\"combo_element_type\") self.horizontalLayout.addWidget(self.combo_element_type) self.line = QtWidgets.QFrame(self.centralwidget) self.line.setFrameShape(QtWidgets.QFrame.VLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName(\"line\")",
"self.horizontalLayout.addWidget(self.label_2) self.lineEdit = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit.setObjectName(\"lineEdit\") self.horizontalLayout.addWidget(self.lineEdit) self.label_4 = QtWidgets.QLabel(self.centralwidget) self.label_4.setObjectName(\"label_4\")",
"setupUi(self, ElementsWindow): ElementsWindow.setObjectName(\"ElementsWindow\") ElementsWindow.resize(841, 623) self.centralwidget = QtWidgets.QWidget(ElementsWindow) self.centralwidget.setObjectName(\"centralwidget\") self.verticalLayout_2",
"QtWidgets.QLabel(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.label.sizePolicy().hasHeightForWidth()) self.label.setSizePolicy(sizePolicy)",
"'./elements_ui.ui' applies. # # Created: Wed Jun 16 14:29:03 2021",
"\", None, -1)) self.combo_element_type.setToolTip( QtWidgets.QApplication.translate( \"ElementsWindow\", \"<html><head/><body><p>Select the element table",
"= QtWidgets.QLineEdit(self.centralwidget) self.lineEdit_2.setObjectName(\"lineEdit_2\") self.horizontalLayout.addWidget(self.lineEdit_2) self.line_2 = QtWidgets.QFrame(self.centralwidget) self.line_2.setFrameShape(QtWidgets.QFrame.VLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName(\"line_2\")",
"you wish to view</p></body></html>\", None, -1)) self.label_3.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \" Filter:",
"self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit_2.setObjectName(\"lineEdit_2\") self.horizontalLayout.addWidget(self.lineEdit_2) self.line_2 = QtWidgets.QFrame(self.centralwidget) self.line_2.setFrameShape(QtWidgets.QFrame.VLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken)",
"ui file './elements_ui.ui', # licensing of './elements_ui.ui' applies. # #",
"# Form implementation generated from reading ui file './elements_ui.ui', #",
"self.verticalLayout_2.addLayout(self.verticalLayout) ElementsWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar() self.menubar.setGeometry(QtCore.QRect(0, 0, 841, 22)) self.menubar.setObjectName(\"menubar\")",
"type: \", None, -1)) self.combo_element_type.setToolTip( QtWidgets.QApplication.translate( \"ElementsWindow\", \"<html><head/><body><p>Select the element",
"element table you wish to view</p></body></html>\", None, -1)) self.label_3.setText( QtWidgets.QApplication.translate(\"ElementsWindow\",",
"Ui_ElementsWindow(object): def setupUi(self, ElementsWindow): ElementsWindow.setObjectName(\"ElementsWindow\") ElementsWindow.resize(841, 623) self.centralwidget = QtWidgets.QWidget(ElementsWindow)",
"icon.addPixmap(QtGui.QPixmap(\":/refresh\"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.btn_refresh.setIcon(icon) self.btn_refresh.setIconSize(QtCore.QSize(20, 20)) self.btn_refresh.setAutoDefault(False) self.btn_refresh.setDefault(False) self.btn_refresh.setFlat(True) self.btn_refresh.setObjectName(\"btn_refresh\")",
"22)) self.menubar.setObjectName(\"menubar\") ElementsWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(ElementsWindow) self.statusbar.setEnabled(True) self.statusbar.setObjectName(\"statusbar\") ElementsWindow.setStatusBar(self.statusbar) self.retranslateUi(ElementsWindow)",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.label.sizePolicy().hasHeightForWidth()) self.label.setSizePolicy(sizePolicy) font",
"font.setWeight(75) font.setBold(True) self.label_3.setFont(font) self.label_3.setObjectName(\"label_3\") self.horizontalLayout.addWidget(self.label_3) self.label_2 = QtWidgets.QLabel(self.centralwidget) self.label_2.setObjectName(\"label_2\") self.horizontalLayout.addWidget(self.label_2)",
"self.label_3 = QtWidgets.QLabel(self.centralwidget) font = QtGui.QFont() font.setWeight(75) font.setBold(True) self.label_3.setFont(font) self.label_3.setObjectName(\"label_3\")",
"623) self.centralwidget = QtWidgets.QWidget(ElementsWindow) self.centralwidget.setObjectName(\"centralwidget\") self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.centralwidget) self.verticalLayout_2.setSpacing(0) self.verticalLayout_2.setContentsMargins(0,",
"reading ui file './elements_ui.ui', # licensing of './elements_ui.ui' applies. #",
"generated from reading ui file './elements_ui.ui', # licensing of './elements_ui.ui'",
"None, -1)) self.btn_refresh.setAccessibleDescription( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the table \", None,",
"self.btn_refresh.setToolTip( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the table \", None, -1)) self.btn_refresh.setStatusTip(",
"refresh the table \", None, -1)) self.label.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Element type:",
"self.tableElements.setObjectName(\"tableElements\") self.verticalLayout.addWidget(self.tableElements) self.verticalLayout_2.addLayout(self.verticalLayout) ElementsWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar() self.menubar.setGeometry(QtCore.QRect(0, 0, 841,",
"QtWidgets.QApplication.translate(\"ElementsWindow\", \"MainWindow\", None, -1)) self.btn_refresh.setToolTip( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the table",
"the element table you wish to view</p></body></html>\", None, -1)) self.label_3.setText(",
"PySide2 import QtCore, QtGui, QtWidgets class Ui_ElementsWindow(object): def setupUi(self, ElementsWindow):",
"= QtWidgets.QLineEdit(self.centralwidget) self.lineEdit.setObjectName(\"lineEdit\") self.horizontalLayout.addWidget(self.lineEdit) self.label_4 = QtWidgets.QLabel(self.centralwidget) self.label_4.setObjectName(\"label_4\") self.horizontalLayout.addWidget(self.label_4) self.lineEdit_2",
"self.label.setObjectName(\"label\") self.horizontalLayout.addWidget(self.label) self.combo_element_type = QtWidgets.QComboBox(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0)",
"QtCore.QMetaObject.connectSlotsByName(ElementsWindow) def retranslateUi(self, ElementsWindow): ElementsWindow.setWindowTitle( QtWidgets.QApplication.translate(\"ElementsWindow\", \"MainWindow\", None, -1)) self.btn_refresh.setToolTip(",
"0) self.verticalLayout_2.setObjectName(\"verticalLayout_2\") self.verticalLayout = QtWidgets.QVBoxLayout() self.verticalLayout.setSizeConstraint( QtWidgets.QLayout.SetDefaultConstraint) self.verticalLayout.setObjectName(\"verticalLayout\") self.horizontalLayout =",
"QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.label.sizePolicy().hasHeightForWidth()) self.label.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setWeight(75)",
"font.setBold(True) self.label_3.setFont(font) self.label_3.setObjectName(\"label_3\") self.horizontalLayout.addWidget(self.label_3) self.label_2 = QtWidgets.QLabel(self.centralwidget) self.label_2.setObjectName(\"label_2\") self.horizontalLayout.addWidget(self.label_2) self.lineEdit",
"None, -1)) self.label_2.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Component: \", None, -1)) self.label_4.setText( QtWidgets.QApplication.translate(\"ElementsWindow\",",
"\"Component: \", None, -1)) self.label_4.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \" Layer: \", None,",
"changes made in this file will be lost! from PySide2",
"QtCore.SIGNAL(\"currentIndexChanged(QString)\"), ElementsWindow.combo_element_type) QtCore.QObject.connect(self.btn_refresh, QtCore.SIGNAL(\"clicked()\"), ElementsWindow.force_refresh) QtCore.QMetaObject.connectSlotsByName(ElementsWindow) def retranslateUi(self, ElementsWindow): ElementsWindow.setWindowTitle(",
"self.tableElements.setSortingEnabled(False) self.tableElements.setObjectName(\"tableElements\") self.verticalLayout.addWidget(self.tableElements) self.verticalLayout_2.addLayout(self.verticalLayout) ElementsWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar() self.menubar.setGeometry(QtCore.QRect(0, 0,",
"QtGui.QIcon.Normal, QtGui.QIcon.Off) self.btn_refresh.setIcon(icon) self.btn_refresh.setIconSize(QtCore.QSize(20, 20)) self.btn_refresh.setAutoDefault(False) self.btn_refresh.setDefault(False) self.btn_refresh.setFlat(True) self.btn_refresh.setObjectName(\"btn_refresh\") self.horizontalLayout.addWidget(self.btn_refresh)",
"-1)) self.btn_refresh.setWhatsThis( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the table \", None, -1))",
"self.tableElements.sizePolicy().hasHeightForWidth()) self.tableElements.setSizePolicy(sizePolicy) self.tableElements.setProperty(\"showDropIndicator\", False) self.tableElements.setDragDropOverwriteMode(False) self.tableElements.setAlternatingRowColors(True) self.tableElements.setSortingEnabled(False) self.tableElements.setObjectName(\"tableElements\") self.verticalLayout.addWidget(self.tableElements) self.verticalLayout_2.addLayout(self.verticalLayout)",
"self.label_4.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \" Layer: \", None, -1)) from . import",
"of './elements_ui.ui' applies. # # Created: Wed Jun 16 14:29:03",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.label.sizePolicy().hasHeightForWidth()) self.label.setSizePolicy(sizePolicy) font =",
"wish to view</p></body></html>\", None, -1)) self.label_3.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \" Filter: \",",
"self.label = QtWidgets.QLabel(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(",
"QtCore.SIGNAL(\"clicked()\"), ElementsWindow.force_refresh) QtCore.QMetaObject.connectSlotsByName(ElementsWindow) def retranslateUi(self, ElementsWindow): ElementsWindow.setWindowTitle( QtWidgets.QApplication.translate(\"ElementsWindow\", \"MainWindow\", None,",
"# by: pyside2-uic running on PySide2 5.13.2 # # WARNING!",
"-1)) self.label_3.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \" Filter: \", None, -1)) self.label_2.setText( QtWidgets.QApplication.translate(\"ElementsWindow\",",
"sizePolicy.setHeightForWidth( self.tableElements.sizePolicy().hasHeightForWidth()) self.tableElements.setSizePolicy(sizePolicy) self.tableElements.setProperty(\"showDropIndicator\", False) self.tableElements.setDragDropOverwriteMode(False) self.tableElements.setAlternatingRowColors(True) self.tableElements.setSortingEnabled(False) self.tableElements.setObjectName(\"tableElements\") self.verticalLayout.addWidget(self.tableElements)",
"None, -1)) self.label.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Element type: \", None, -1)) self.combo_element_type.setToolTip(",
"self.btn_refresh.setCursor(QtCore.Qt.ClosedHandCursor) self.btn_refresh.setText(\"\") icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(\":/refresh\"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.btn_refresh.setIcon(icon) self.btn_refresh.setIconSize(QtCore.QSize(20,",
"coding: utf-8 -*- # Form implementation generated from reading ui",
"self.line_2.setFrameShape(QtWidgets.QFrame.VLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName(\"line_2\") self.horizontalLayout.addWidget(self.line_2) self.verticalLayout.addLayout(self.horizontalLayout) self.tableElements = QtWidgets.QTableView(self.centralwidget) sizePolicy =",
"self.tableElements.setDragDropOverwriteMode(False) self.tableElements.setAlternatingRowColors(True) self.tableElements.setSortingEnabled(False) self.tableElements.setObjectName(\"tableElements\") self.verticalLayout.addWidget(self.tableElements) self.verticalLayout_2.addLayout(self.verticalLayout) ElementsWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar()",
"self.btn_refresh.setFlat(True) self.btn_refresh.setObjectName(\"btn_refresh\") self.horizontalLayout.addWidget(self.btn_refresh) self.label = QtWidgets.QLabel(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)",
"QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter) self.label.setObjectName(\"label\") self.horizontalLayout.addWidget(self.label) self.combo_element_type = QtWidgets.QComboBox(self.centralwidget) sizePolicy =",
"self.label.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Element type: \", None, -1)) self.combo_element_type.setToolTip( QtWidgets.QApplication.translate( \"ElementsWindow\",",
"self.line_2.setObjectName(\"line_2\") self.horizontalLayout.addWidget(self.line_2) self.verticalLayout.addLayout(self.horizontalLayout) self.tableElements = QtWidgets.QTableView(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)",
"-*- coding: utf-8 -*- # Form implementation generated from reading",
"self.horizontalLayout.addWidget(self.label_3) self.label_2 = QtWidgets.QLabel(self.centralwidget) self.label_2.setObjectName(\"label_2\") self.horizontalLayout.addWidget(self.label_2) self.lineEdit = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit.setObjectName(\"lineEdit\")",
"WARNING! All changes made in this file will be lost!",
"self.line = QtWidgets.QFrame(self.centralwidget) self.line.setFrameShape(QtWidgets.QFrame.VLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName(\"line\") self.horizontalLayout.addWidget(self.line) self.label_3 = QtWidgets.QLabel(self.centralwidget)",
"self.tableElements.setSizePolicy(sizePolicy) self.tableElements.setProperty(\"showDropIndicator\", False) self.tableElements.setDragDropOverwriteMode(False) self.tableElements.setAlternatingRowColors(True) self.tableElements.setSortingEnabled(False) self.tableElements.setObjectName(\"tableElements\") self.verticalLayout.addWidget(self.tableElements) self.verticalLayout_2.addLayout(self.verticalLayout) ElementsWindow.setCentralWidget(self.centralwidget)",
"ElementsWindow.combo_element_type) QtCore.QObject.connect(self.btn_refresh, QtCore.SIGNAL(\"clicked()\"), ElementsWindow.force_refresh) QtCore.QMetaObject.connectSlotsByName(ElementsWindow) def retranslateUi(self, ElementsWindow): ElementsWindow.setWindowTitle( QtWidgets.QApplication.translate(\"ElementsWindow\",",
"self.btn_refresh.setIconSize(QtCore.QSize(20, 20)) self.btn_refresh.setAutoDefault(False) self.btn_refresh.setDefault(False) self.btn_refresh.setFlat(True) self.btn_refresh.setObjectName(\"btn_refresh\") self.horizontalLayout.addWidget(self.btn_refresh) self.label = QtWidgets.QLabel(self.centralwidget)",
"from PySide2 import QtCore, QtGui, QtWidgets class Ui_ElementsWindow(object): def setupUi(self,",
"Form implementation generated from reading ui file './elements_ui.ui', # licensing",
"the table \", None, -1)) self.btn_refresh.setWhatsThis( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the",
"table \", None, -1)) self.btn_refresh.setWhatsThis( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the table",
"0, 841, 22)) self.menubar.setObjectName(\"menubar\") ElementsWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(ElementsWindow) self.statusbar.setEnabled(True) self.statusbar.setObjectName(\"statusbar\")",
"QtWidgets.QApplication.translate(\"ElementsWindow\", \" Layer: \", None, -1)) from . import main_window_rc_rc",
"self.combo_element_type.setSizePolicy(sizePolicy) self.combo_element_type.setCurrentText(\"\") self.combo_element_type.setSizeAdjustPolicy( QtWidgets.QComboBox.AdjustToContents) self.combo_element_type.setObjectName(\"combo_element_type\") self.horizontalLayout.addWidget(self.combo_element_type) self.line = QtWidgets.QFrame(self.centralwidget) self.line.setFrameShape(QtWidgets.QFrame.VLine)",
"= QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(\":/refresh\"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.btn_refresh.setIcon(icon) self.btn_refresh.setIconSize(QtCore.QSize(20, 20)) self.btn_refresh.setAutoDefault(False) self.btn_refresh.setDefault(False)",
"5.13.2 # # WARNING! All changes made in this file",
"font = QtGui.QFont() font.setWeight(75) font.setBold(True) self.label.setFont(font) self.label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing |",
"ElementsWindow.setObjectName(\"ElementsWindow\") ElementsWindow.resize(841, 623) self.centralwidget = QtWidgets.QWidget(ElementsWindow) self.centralwidget.setObjectName(\"centralwidget\") self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.centralwidget)",
"\", None, -1)) self.btn_refresh.setWhatsThis( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the table \",",
"self.tableElements.setAlternatingRowColors(True) self.tableElements.setSortingEnabled(False) self.tableElements.setObjectName(\"tableElements\") self.verticalLayout.addWidget(self.tableElements) self.verticalLayout_2.addLayout(self.verticalLayout) ElementsWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar() self.menubar.setGeometry(QtCore.QRect(0,",
"made in this file will be lost! from PySide2 import",
"self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName(\"line_2\") self.horizontalLayout.addWidget(self.line_2) self.verticalLayout.addLayout(self.horizontalLayout) self.tableElements = QtWidgets.QTableView(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,",
"QtWidgets.QComboBox(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.combo_element_type.sizePolicy().hasHeightForWidth()) self.combo_element_type.setSizePolicy(sizePolicy)",
"font.setBold(True) self.label.setFont(font) self.label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter) self.label.setObjectName(\"label\") self.horizontalLayout.addWidget(self.label) self.combo_element_type",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.tableElements.sizePolicy().hasHeightForWidth()) self.tableElements.setSizePolicy(sizePolicy) self.tableElements.setProperty(\"showDropIndicator\", False) self.tableElements.setDragDropOverwriteMode(False)",
"QtWidgets.QVBoxLayout(self.centralwidget) self.verticalLayout_2.setSpacing(0) self.verticalLayout_2.setContentsMargins(0, 0, 0, 0) self.verticalLayout_2.setObjectName(\"verticalLayout_2\") self.verticalLayout = QtWidgets.QVBoxLayout()",
"ElementsWindow): ElementsWindow.setObjectName(\"ElementsWindow\") ElementsWindow.resize(841, 623) self.centralwidget = QtWidgets.QWidget(ElementsWindow) self.centralwidget.setObjectName(\"centralwidget\") self.verticalLayout_2 =",
"\"ElementsWindow\", \"<html><head/><body><p>Select the element table you wish to view</p></body></html>\", None,",
"self.label.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setWeight(75) font.setBold(True) self.label.setFont(font) self.label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing",
"self.centralwidget = QtWidgets.QWidget(ElementsWindow) self.centralwidget.setObjectName(\"centralwidget\") self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.centralwidget) self.verticalLayout_2.setSpacing(0) self.verticalLayout_2.setContentsMargins(0, 0,",
"841, 22)) self.menubar.setObjectName(\"menubar\") ElementsWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(ElementsWindow) self.statusbar.setEnabled(True) self.statusbar.setObjectName(\"statusbar\") ElementsWindow.setStatusBar(self.statusbar)",
"self.label_2.setObjectName(\"label_2\") self.horizontalLayout.addWidget(self.label_2) self.lineEdit = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit.setObjectName(\"lineEdit\") self.horizontalLayout.addWidget(self.lineEdit) self.label_4 = QtWidgets.QLabel(self.centralwidget)",
"\" Filter: \", None, -1)) self.label_2.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Component: \", None,",
"# # Created: Wed Jun 16 14:29:03 2021 # by:",
"QtWidgets.QPushButton(self.centralwidget) self.btn_refresh.setCursor(QtCore.Qt.ClosedHandCursor) self.btn_refresh.setText(\"\") icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(\":/refresh\"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.btn_refresh.setIcon(icon)",
"= QtWidgets.QWidget(ElementsWindow) self.centralwidget.setObjectName(\"centralwidget\") self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.centralwidget) self.verticalLayout_2.setSpacing(0) self.verticalLayout_2.setContentsMargins(0, 0, 0,",
"= QtWidgets.QStatusBar(ElementsWindow) self.statusbar.setEnabled(True) self.statusbar.setObjectName(\"statusbar\") ElementsWindow.setStatusBar(self.statusbar) self.retranslateUi(ElementsWindow) QtCore.QObject.connect(self.combo_element_type, QtCore.SIGNAL(\"currentIndexChanged(QString)\"), ElementsWindow.combo_element_type) QtCore.QObject.connect(self.btn_refresh,",
"| QtCore.Qt.AlignVCenter) self.label.setObjectName(\"label\") self.horizontalLayout.addWidget(self.label) self.combo_element_type = QtWidgets.QComboBox(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,",
"Created: Wed Jun 16 14:29:03 2021 # by: pyside2-uic running",
"QtWidgets.QFrame(self.centralwidget) self.line.setFrameShape(QtWidgets.QFrame.VLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName(\"line\") self.horizontalLayout.addWidget(self.line) self.label_3 = QtWidgets.QLabel(self.centralwidget) font =",
"ElementsWindow.setStatusBar(self.statusbar) self.retranslateUi(ElementsWindow) QtCore.QObject.connect(self.combo_element_type, QtCore.SIGNAL(\"currentIndexChanged(QString)\"), ElementsWindow.combo_element_type) QtCore.QObject.connect(self.btn_refresh, QtCore.SIGNAL(\"clicked()\"), ElementsWindow.force_refresh) QtCore.QMetaObject.connectSlotsByName(ElementsWindow) def",
"table \", None, -1)) self.btn_refresh.setAccessibleDescription( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the table",
"file will be lost! from PySide2 import QtCore, QtGui, QtWidgets",
"self.btn_refresh.setText(\"\") icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(\":/refresh\"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.btn_refresh.setIcon(icon) self.btn_refresh.setIconSize(QtCore.QSize(20, 20))",
"QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.combo_element_type.sizePolicy().hasHeightForWidth()) self.combo_element_type.setSizePolicy(sizePolicy) self.combo_element_type.setCurrentText(\"\") self.combo_element_type.setSizeAdjustPolicy( QtWidgets.QComboBox.AdjustToContents) self.combo_element_type.setObjectName(\"combo_element_type\")",
"self.btn_refresh.setStatusTip( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the table \", None, -1)) self.btn_refresh.setWhatsThis(",
"file './elements_ui.ui', # licensing of './elements_ui.ui' applies. # # Created:",
"self.horizontalLayout.addWidget(self.lineEdit) self.label_4 = QtWidgets.QLabel(self.centralwidget) self.label_4.setObjectName(\"label_4\") self.horizontalLayout.addWidget(self.label_4) self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit_2.setObjectName(\"lineEdit_2\")",
"# # WARNING! All changes made in this file will",
"self.btn_refresh.setDefault(False) self.btn_refresh.setFlat(True) self.btn_refresh.setObjectName(\"btn_refresh\") self.horizontalLayout.addWidget(self.btn_refresh) self.label = QtWidgets.QLabel(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum,",
"14:29:03 2021 # by: pyside2-uic running on PySide2 5.13.2 #",
"self.btn_refresh.setObjectName(\"btn_refresh\") self.horizontalLayout.addWidget(self.btn_refresh) self.label = QtWidgets.QLabel(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0)",
"= QtGui.QFont() font.setWeight(75) font.setBold(True) self.label_3.setFont(font) self.label_3.setObjectName(\"label_3\") self.horizontalLayout.addWidget(self.label_3) self.label_2 = QtWidgets.QLabel(self.centralwidget)",
"\"Element type: \", None, -1)) self.combo_element_type.setToolTip( QtWidgets.QApplication.translate( \"ElementsWindow\", \"<html><head/><body><p>Select the",
"in this file will be lost! from PySide2 import QtCore,",
"QtGui.QFont() font.setWeight(75) font.setBold(True) self.label_3.setFont(font) self.label_3.setObjectName(\"label_3\") self.horizontalLayout.addWidget(self.label_3) self.label_2 = QtWidgets.QLabel(self.centralwidget) self.label_2.setObjectName(\"label_2\")",
"None, -1)) self.label_3.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \" Filter: \", None, -1)) self.label_2.setText(",
"self.label_2 = QtWidgets.QLabel(self.centralwidget) self.label_2.setObjectName(\"label_2\") self.horizontalLayout.addWidget(self.label_2) self.lineEdit = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit.setObjectName(\"lineEdit\") self.horizontalLayout.addWidget(self.lineEdit)",
"= QtWidgets.QTableView(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.tableElements.sizePolicy().hasHeightForWidth())",
"self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.centralwidget) self.verticalLayout_2.setSpacing(0) self.verticalLayout_2.setContentsMargins(0, 0, 0, 0) self.verticalLayout_2.setObjectName(\"verticalLayout_2\") self.verticalLayout",
"QtWidgets.QVBoxLayout() self.verticalLayout.setSizeConstraint( QtWidgets.QLayout.SetDefaultConstraint) self.verticalLayout.setObjectName(\"verticalLayout\") self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName(\"horizontalLayout\") self.btn_refresh =",
"pyside2-uic running on PySide2 5.13.2 # # WARNING! All changes",
"= QtWidgets.QLabel(self.centralwidget) self.label_2.setObjectName(\"label_2\") self.horizontalLayout.addWidget(self.label_2) self.lineEdit = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit.setObjectName(\"lineEdit\") self.horizontalLayout.addWidget(self.lineEdit) self.label_4",
"def setupUi(self, ElementsWindow): ElementsWindow.setObjectName(\"ElementsWindow\") ElementsWindow.resize(841, 623) self.centralwidget = QtWidgets.QWidget(ElementsWindow) self.centralwidget.setObjectName(\"centralwidget\")",
"self.centralwidget.setObjectName(\"centralwidget\") self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.centralwidget) self.verticalLayout_2.setSpacing(0) self.verticalLayout_2.setContentsMargins(0, 0, 0, 0) self.verticalLayout_2.setObjectName(\"verticalLayout_2\")",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.tableElements.sizePolicy().hasHeightForWidth()) self.tableElements.setSizePolicy(sizePolicy) self.tableElements.setProperty(\"showDropIndicator\", False)",
"QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the table \", None, -1)) self.label.setText( QtWidgets.QApplication.translate(\"ElementsWindow\",",
"refresh the table \", None, -1)) self.btn_refresh.setWhatsThis( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh",
"= QtWidgets.QFrame(self.centralwidget) self.line_2.setFrameShape(QtWidgets.QFrame.VLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName(\"line_2\") self.horizontalLayout.addWidget(self.line_2) self.verticalLayout.addLayout(self.horizontalLayout) self.tableElements = QtWidgets.QTableView(self.centralwidget)",
"will be lost! from PySide2 import QtCore, QtGui, QtWidgets class",
"self.horizontalLayout.addWidget(self.label_4) self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit_2.setObjectName(\"lineEdit_2\") self.horizontalLayout.addWidget(self.lineEdit_2) self.line_2 = QtWidgets.QFrame(self.centralwidget) self.line_2.setFrameShape(QtWidgets.QFrame.VLine)",
"All changes made in this file will be lost! from",
"= QtWidgets.QFrame(self.centralwidget) self.line.setFrameShape(QtWidgets.QFrame.VLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName(\"line\") self.horizontalLayout.addWidget(self.line) self.label_3 = QtWidgets.QLabel(self.centralwidget) font",
"# licensing of './elements_ui.ui' applies. # # Created: Wed Jun",
"QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.tableElements.sizePolicy().hasHeightForWidth()) self.tableElements.setSizePolicy(sizePolicy) self.tableElements.setProperty(\"showDropIndicator\", False) self.tableElements.setDragDropOverwriteMode(False) self.tableElements.setAlternatingRowColors(True)",
"table \", None, -1)) self.btn_refresh.setStatusTip( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the table",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.tableElements.sizePolicy().hasHeightForWidth()) self.tableElements.setSizePolicy(sizePolicy) self.tableElements.setProperty(\"showDropIndicator\", False) self.tableElements.setDragDropOverwriteMode(False) self.tableElements.setAlternatingRowColors(True) self.tableElements.setSortingEnabled(False) self.tableElements.setObjectName(\"tableElements\")",
"be lost! from PySide2 import QtCore, QtGui, QtWidgets class Ui_ElementsWindow(object):",
"to view</p></body></html>\", None, -1)) self.label_3.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \" Filter: \", None,",
"self.verticalLayout_2.setObjectName(\"verticalLayout_2\") self.verticalLayout = QtWidgets.QVBoxLayout() self.verticalLayout.setSizeConstraint( QtWidgets.QLayout.SetDefaultConstraint) self.verticalLayout.setObjectName(\"verticalLayout\") self.horizontalLayout = QtWidgets.QHBoxLayout()",
"self.statusbar.setEnabled(True) self.statusbar.setObjectName(\"statusbar\") ElementsWindow.setStatusBar(self.statusbar) self.retranslateUi(ElementsWindow) QtCore.QObject.connect(self.combo_element_type, QtCore.SIGNAL(\"currentIndexChanged(QString)\"), ElementsWindow.combo_element_type) QtCore.QObject.connect(self.btn_refresh, QtCore.SIGNAL(\"clicked()\"), ElementsWindow.force_refresh)",
"= QtWidgets.QVBoxLayout() self.verticalLayout.setSizeConstraint( QtWidgets.QLayout.SetDefaultConstraint) self.verticalLayout.setObjectName(\"verticalLayout\") self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName(\"horizontalLayout\") self.btn_refresh",
"self.tableElements.setProperty(\"showDropIndicator\", False) self.tableElements.setDragDropOverwriteMode(False) self.tableElements.setAlternatingRowColors(True) self.tableElements.setSortingEnabled(False) self.tableElements.setObjectName(\"tableElements\") self.verticalLayout.addWidget(self.tableElements) self.verticalLayout_2.addLayout(self.verticalLayout) ElementsWindow.setCentralWidget(self.centralwidget) self.menubar",
"QtWidgets.QLineEdit(self.centralwidget) self.lineEdit_2.setObjectName(\"lineEdit_2\") self.horizontalLayout.addWidget(self.lineEdit_2) self.line_2 = QtWidgets.QFrame(self.centralwidget) self.line_2.setFrameShape(QtWidgets.QFrame.VLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName(\"line_2\") self.horizontalLayout.addWidget(self.line_2)",
"\", None, -1)) self.btn_refresh.setStatusTip( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the table \",",
"self.label.sizePolicy().hasHeightForWidth()) self.label.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setWeight(75) font.setBold(True) self.label.setFont(font) self.label.setAlignment(QtCore.Qt.AlignRight |",
"self.statusbar = QtWidgets.QStatusBar(ElementsWindow) self.statusbar.setEnabled(True) self.statusbar.setObjectName(\"statusbar\") ElementsWindow.setStatusBar(self.statusbar) self.retranslateUi(ElementsWindow) QtCore.QObject.connect(self.combo_element_type, QtCore.SIGNAL(\"currentIndexChanged(QString)\"), ElementsWindow.combo_element_type)",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.tableElements.sizePolicy().hasHeightForWidth()) self.tableElements.setSizePolicy(sizePolicy) self.tableElements.setProperty(\"showDropIndicator\",",
"= QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName(\"horizontalLayout\") self.btn_refresh = QtWidgets.QPushButton(self.centralwidget) self.btn_refresh.setCursor(QtCore.Qt.ClosedHandCursor) self.btn_refresh.setText(\"\") icon =",
"self.menubar = QtWidgets.QMenuBar() self.menubar.setGeometry(QtCore.QRect(0, 0, 841, 22)) self.menubar.setObjectName(\"menubar\") ElementsWindow.setMenuBar(self.menubar) self.statusbar",
"0, 0) self.verticalLayout_2.setObjectName(\"verticalLayout_2\") self.verticalLayout = QtWidgets.QVBoxLayout() self.verticalLayout.setSizeConstraint( QtWidgets.QLayout.SetDefaultConstraint) self.verticalLayout.setObjectName(\"verticalLayout\") self.horizontalLayout",
"None, -1)) self.label_4.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \" Layer: \", None, -1)) from",
"self.horizontalLayout.addWidget(self.label) self.combo_element_type = QtWidgets.QComboBox(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"\"Force refresh the table \", None, -1)) self.label.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Element",
"QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the table \", None, -1)) self.btn_refresh.setAccessibleDescription( QtWidgets.QApplication.translate(\"ElementsWindow\",",
"ElementsWindow.force_refresh) QtCore.QMetaObject.connectSlotsByName(ElementsWindow) def retranslateUi(self, ElementsWindow): ElementsWindow.setWindowTitle( QtWidgets.QApplication.translate(\"ElementsWindow\", \"MainWindow\", None, -1))",
"QtWidgets.QLabel(self.centralwidget) self.label_4.setObjectName(\"label_4\") self.horizontalLayout.addWidget(self.label_4) self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit_2.setObjectName(\"lineEdit_2\") self.horizontalLayout.addWidget(self.lineEdit_2) self.line_2 =",
"QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(\":/refresh\"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.btn_refresh.setIcon(icon) self.btn_refresh.setIconSize(QtCore.QSize(20, 20)) self.btn_refresh.setAutoDefault(False) self.btn_refresh.setDefault(False) self.btn_refresh.setFlat(True)",
"self.label_2.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Component: \", None, -1)) self.label_4.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \" Layer:",
"refresh the table \", None, -1)) self.btn_refresh.setStatusTip( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh",
"icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(\":/refresh\"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.btn_refresh.setIcon(icon) self.btn_refresh.setIconSize(QtCore.QSize(20, 20)) self.btn_refresh.setAutoDefault(False)",
"QtGui, QtWidgets class Ui_ElementsWindow(object): def setupUi(self, ElementsWindow): ElementsWindow.setObjectName(\"ElementsWindow\") ElementsWindow.resize(841, 623)",
"20)) self.btn_refresh.setAutoDefault(False) self.btn_refresh.setDefault(False) self.btn_refresh.setFlat(True) self.btn_refresh.setObjectName(\"btn_refresh\") self.horizontalLayout.addWidget(self.btn_refresh) self.label = QtWidgets.QLabel(self.centralwidget) sizePolicy",
"| QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter) self.label.setObjectName(\"label\") self.horizontalLayout.addWidget(self.label) self.combo_element_type = QtWidgets.QComboBox(self.centralwidget) sizePolicy",
"self.verticalLayout.setObjectName(\"verticalLayout\") self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName(\"horizontalLayout\") self.btn_refresh = QtWidgets.QPushButton(self.centralwidget) self.btn_refresh.setCursor(QtCore.Qt.ClosedHandCursor) self.btn_refresh.setText(\"\")",
"# WARNING! All changes made in this file will be",
"\"Force refresh the table \", None, -1)) self.btn_refresh.setAccessibleDescription( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force",
"licensing of './elements_ui.ui' applies. # # Created: Wed Jun 16",
"self.label_3.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \" Filter: \", None, -1)) self.label_2.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Component:",
"= QtWidgets.QPushButton(self.centralwidget) self.btn_refresh.setCursor(QtCore.Qt.ClosedHandCursor) self.btn_refresh.setText(\"\") icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(\":/refresh\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.tableElements.sizePolicy().hasHeightForWidth()) self.tableElements.setSizePolicy(sizePolicy) self.tableElements.setProperty(\"showDropIndicator\", False) self.tableElements.setDragDropOverwriteMode(False) self.tableElements.setAlternatingRowColors(True) self.tableElements.setSortingEnabled(False)",
"QtWidgets.QLineEdit(self.centralwidget) self.lineEdit.setObjectName(\"lineEdit\") self.horizontalLayout.addWidget(self.lineEdit) self.label_4 = QtWidgets.QLabel(self.centralwidget) self.label_4.setObjectName(\"label_4\") self.horizontalLayout.addWidget(self.label_4) self.lineEdit_2 =",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.label.sizePolicy().hasHeightForWidth()) self.label.setSizePolicy(sizePolicy) font = QtGui.QFont()",
"QtWidgets.QApplication.translate( \"ElementsWindow\", \"<html><head/><body><p>Select the element table you wish to view</p></body></html>\",",
"False) self.tableElements.setDragDropOverwriteMode(False) self.tableElements.setAlternatingRowColors(True) self.tableElements.setSortingEnabled(False) self.tableElements.setObjectName(\"tableElements\") self.verticalLayout.addWidget(self.tableElements) self.verticalLayout_2.addLayout(self.verticalLayout) ElementsWindow.setCentralWidget(self.centralwidget) self.menubar =",
"self.verticalLayout_2.setContentsMargins(0, 0, 0, 0) self.verticalLayout_2.setObjectName(\"verticalLayout_2\") self.verticalLayout = QtWidgets.QVBoxLayout() self.verticalLayout.setSizeConstraint( QtWidgets.QLayout.SetDefaultConstraint)",
"\"Force refresh the table \", None, -1)) self.btn_refresh.setStatusTip( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force",
"16 14:29:03 2021 # by: pyside2-uic running on PySide2 5.13.2",
"self.combo_element_type.setObjectName(\"combo_element_type\") self.horizontalLayout.addWidget(self.combo_element_type) self.line = QtWidgets.QFrame(self.centralwidget) self.line.setFrameShape(QtWidgets.QFrame.VLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName(\"line\") self.horizontalLayout.addWidget(self.line) self.label_3",
"2021 # by: pyside2-uic running on PySide2 5.13.2 # #",
"sizePolicy.setHeightForWidth( self.label.sizePolicy().hasHeightForWidth()) self.label.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setWeight(75) font.setBold(True) self.label.setFont(font) self.label.setAlignment(QtCore.Qt.AlignRight",
"QtWidgets.QStatusBar(ElementsWindow) self.statusbar.setEnabled(True) self.statusbar.setObjectName(\"statusbar\") ElementsWindow.setStatusBar(self.statusbar) self.retranslateUi(ElementsWindow) QtCore.QObject.connect(self.combo_element_type, QtCore.SIGNAL(\"currentIndexChanged(QString)\"), ElementsWindow.combo_element_type) QtCore.QObject.connect(self.btn_refresh, QtCore.SIGNAL(\"clicked()\"),",
"QtCore.QObject.connect(self.btn_refresh, QtCore.SIGNAL(\"clicked()\"), ElementsWindow.force_refresh) QtCore.QMetaObject.connectSlotsByName(ElementsWindow) def retranslateUi(self, ElementsWindow): ElementsWindow.setWindowTitle( QtWidgets.QApplication.translate(\"ElementsWindow\", \"MainWindow\",",
"from reading ui file './elements_ui.ui', # licensing of './elements_ui.ui' applies.",
"-*- # Form implementation generated from reading ui file './elements_ui.ui',",
"running on PySide2 5.13.2 # # WARNING! All changes made",
"class Ui_ElementsWindow(object): def setupUi(self, ElementsWindow): ElementsWindow.setObjectName(\"ElementsWindow\") ElementsWindow.resize(841, 623) self.centralwidget =",
"self.btn_refresh.setAutoDefault(False) self.btn_refresh.setDefault(False) self.btn_refresh.setFlat(True) self.btn_refresh.setObjectName(\"btn_refresh\") self.horizontalLayout.addWidget(self.btn_refresh) self.label = QtWidgets.QLabel(self.centralwidget) sizePolicy =",
"ElementsWindow.resize(841, 623) self.centralwidget = QtWidgets.QWidget(ElementsWindow) self.centralwidget.setObjectName(\"centralwidget\") self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.centralwidget) self.verticalLayout_2.setSpacing(0)",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.label.sizePolicy().hasHeightForWidth()) self.label.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setWeight(75) font.setBold(True) self.label.setFont(font)",
"self.retranslateUi(ElementsWindow) QtCore.QObject.connect(self.combo_element_type, QtCore.SIGNAL(\"currentIndexChanged(QString)\"), ElementsWindow.combo_element_type) QtCore.QObject.connect(self.btn_refresh, QtCore.SIGNAL(\"clicked()\"), ElementsWindow.force_refresh) QtCore.QMetaObject.connectSlotsByName(ElementsWindow) def retranslateUi(self,",
"self.horizontalLayout.addWidget(self.lineEdit_2) self.line_2 = QtWidgets.QFrame(self.centralwidget) self.line_2.setFrameShape(QtWidgets.QFrame.VLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName(\"line_2\") self.horizontalLayout.addWidget(self.line_2) self.verticalLayout.addLayout(self.horizontalLayout) self.tableElements",
"\"Force refresh the table \", None, -1)) self.btn_refresh.setWhatsThis( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force",
"QtCore.Qt.AlignVCenter) self.label.setObjectName(\"label\") self.horizontalLayout.addWidget(self.label) self.combo_element_type = QtWidgets.QComboBox(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)",
"None, -1)) self.btn_refresh.setToolTip( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the table \", None,",
"self.menubar.setGeometry(QtCore.QRect(0, 0, 841, 22)) self.menubar.setObjectName(\"menubar\") ElementsWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(ElementsWindow) self.statusbar.setEnabled(True)",
"the table \", None, -1)) self.label.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Element type: \",",
"refresh the table \", None, -1)) self.btn_refresh.setAccessibleDescription( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh",
"# -*- coding: utf-8 -*- # Form implementation generated from",
"sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.combo_element_type.sizePolicy().hasHeightForWidth()) self.combo_element_type.setSizePolicy(sizePolicy) self.combo_element_type.setCurrentText(\"\") self.combo_element_type.setSizeAdjustPolicy( QtWidgets.QComboBox.AdjustToContents) self.combo_element_type.setObjectName(\"combo_element_type\") self.horizontalLayout.addWidget(self.combo_element_type) self.line",
"= QtWidgets.QVBoxLayout(self.centralwidget) self.verticalLayout_2.setSpacing(0) self.verticalLayout_2.setContentsMargins(0, 0, 0, 0) self.verticalLayout_2.setObjectName(\"verticalLayout_2\") self.verticalLayout =",
"= QtWidgets.QMenuBar() self.menubar.setGeometry(QtCore.QRect(0, 0, 841, 22)) self.menubar.setObjectName(\"menubar\") ElementsWindow.setMenuBar(self.menubar) self.statusbar =",
"QtWidgets.QMenuBar() self.menubar.setGeometry(QtCore.QRect(0, 0, 841, 22)) self.menubar.setObjectName(\"menubar\") ElementsWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(ElementsWindow)",
"table \", None, -1)) self.label.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Element type: \", None,",
"None, -1)) self.btn_refresh.setStatusTip( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the table \", None,",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.combo_element_type.sizePolicy().hasHeightForWidth()) self.combo_element_type.setSizePolicy(sizePolicy) self.combo_element_type.setCurrentText(\"\") self.combo_element_type.setSizeAdjustPolicy( QtWidgets.QComboBox.AdjustToContents) self.combo_element_type.setObjectName(\"combo_element_type\") self.horizontalLayout.addWidget(self.combo_element_type)",
"self.lineEdit.setObjectName(\"lineEdit\") self.horizontalLayout.addWidget(self.lineEdit) self.label_4 = QtWidgets.QLabel(self.centralwidget) self.label_4.setObjectName(\"label_4\") self.horizontalLayout.addWidget(self.label_4) self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)",
"self.horizontalLayout.addWidget(self.line_2) self.verticalLayout.addLayout(self.horizontalLayout) self.tableElements = QtWidgets.QTableView(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0)",
"= QtWidgets.QComboBox(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.combo_element_type.sizePolicy().hasHeightForWidth())",
"ElementsWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(ElementsWindow) self.statusbar.setEnabled(True) self.statusbar.setObjectName(\"statusbar\") ElementsWindow.setStatusBar(self.statusbar) self.retranslateUi(ElementsWindow) QtCore.QObject.connect(self.combo_element_type, QtCore.SIGNAL(\"currentIndexChanged(QString)\"),",
"sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.combo_element_type.sizePolicy().hasHeightForWidth()) self.combo_element_type.setSizePolicy(sizePolicy) self.combo_element_type.setCurrentText(\"\")",
"self.tableElements = QtWidgets.QTableView(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(",
"self.btn_refresh.setAccessibleDescription( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the table \", None, -1)) self.label.setText(",
"QtWidgets.QApplication.translate(\"ElementsWindow\", \" Filter: \", None, -1)) self.label_2.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Component: \",",
"\", None, -1)) self.label_4.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \" Layer: \", None, -1))",
"-1)) self.combo_element_type.setToolTip( QtWidgets.QApplication.translate( \"ElementsWindow\", \"<html><head/><body><p>Select the element table you wish",
"QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the table \", None, -1)) self.btn_refresh.setStatusTip( QtWidgets.QApplication.translate(\"ElementsWindow\",",
"QtWidgets.QLabel(self.centralwidget) font = QtGui.QFont() font.setWeight(75) font.setBold(True) self.label_3.setFont(font) self.label_3.setObjectName(\"label_3\") self.horizontalLayout.addWidget(self.label_3) self.label_2",
"sizePolicy.setHeightForWidth( self.combo_element_type.sizePolicy().hasHeightForWidth()) self.combo_element_type.setSizePolicy(sizePolicy) self.combo_element_type.setCurrentText(\"\") self.combo_element_type.setSizeAdjustPolicy( QtWidgets.QComboBox.AdjustToContents) self.combo_element_type.setObjectName(\"combo_element_type\") self.horizontalLayout.addWidget(self.combo_element_type) self.line =",
"-1)) self.btn_refresh.setStatusTip( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the table \", None, -1))",
"sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.label.sizePolicy().hasHeightForWidth()) self.label.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setWeight(75) font.setBold(True)",
"self.line.setFrameShape(QtWidgets.QFrame.VLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName(\"line\") self.horizontalLayout.addWidget(self.line) self.label_3 = QtWidgets.QLabel(self.centralwidget) font = QtGui.QFont()",
"= QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.combo_element_type.sizePolicy().hasHeightForWidth()) self.combo_element_type.setSizePolicy(sizePolicy) self.combo_element_type.setCurrentText(\"\") self.combo_element_type.setSizeAdjustPolicy(",
"lost! from PySide2 import QtCore, QtGui, QtWidgets class Ui_ElementsWindow(object): def",
"self.combo_element_type.setCurrentText(\"\") self.combo_element_type.setSizeAdjustPolicy( QtWidgets.QComboBox.AdjustToContents) self.combo_element_type.setObjectName(\"combo_element_type\") self.horizontalLayout.addWidget(self.combo_element_type) self.line = QtWidgets.QFrame(self.centralwidget) self.line.setFrameShape(QtWidgets.QFrame.VLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken)",
"self.horizontalLayout.setObjectName(\"horizontalLayout\") self.btn_refresh = QtWidgets.QPushButton(self.centralwidget) self.btn_refresh.setCursor(QtCore.Qt.ClosedHandCursor) self.btn_refresh.setText(\"\") icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(\":/refresh\"),",
"ElementsWindow.setWindowTitle( QtWidgets.QApplication.translate(\"ElementsWindow\", \"MainWindow\", None, -1)) self.btn_refresh.setToolTip( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the",
"self.line.setObjectName(\"line\") self.horizontalLayout.addWidget(self.line) self.label_3 = QtWidgets.QLabel(self.centralwidget) font = QtGui.QFont() font.setWeight(75) font.setBold(True)",
"QtWidgets.QApplication.translate(\"ElementsWindow\", \"Element type: \", None, -1)) self.combo_element_type.setToolTip( QtWidgets.QApplication.translate( \"ElementsWindow\", \"<html><head/><body><p>Select",
"\"<html><head/><body><p>Select the element table you wish to view</p></body></html>\", None, -1))",
"self.label_4.setObjectName(\"label_4\") self.horizontalLayout.addWidget(self.label_4) self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit_2.setObjectName(\"lineEdit_2\") self.horizontalLayout.addWidget(self.lineEdit_2) self.line_2 = QtWidgets.QFrame(self.centralwidget)",
"self.label.setFont(font) self.label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter) self.label.setObjectName(\"label\") self.horizontalLayout.addWidget(self.label) self.combo_element_type =",
"None, -1)) self.combo_element_type.setToolTip( QtWidgets.QApplication.translate( \"ElementsWindow\", \"<html><head/><body><p>Select the element table you",
"-1)) self.label_4.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \" Layer: \", None, -1)) from .",
"-1)) self.label.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Element type: \", None, -1)) self.combo_element_type.setToolTip( QtWidgets.QApplication.translate(",
"self.combo_element_type = QtWidgets.QComboBox(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(",
"view</p></body></html>\", None, -1)) self.label_3.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \" Filter: \", None, -1))",
"implementation generated from reading ui file './elements_ui.ui', # licensing of",
"QtWidgets.QLayout.SetDefaultConstraint) self.verticalLayout.setObjectName(\"verticalLayout\") self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName(\"horizontalLayout\") self.btn_refresh = QtWidgets.QPushButton(self.centralwidget) self.btn_refresh.setCursor(QtCore.Qt.ClosedHandCursor)",
"self.label_3.setFont(font) self.label_3.setObjectName(\"label_3\") self.horizontalLayout.addWidget(self.label_3) self.label_2 = QtWidgets.QLabel(self.centralwidget) self.label_2.setObjectName(\"label_2\") self.horizontalLayout.addWidget(self.label_2) self.lineEdit =",
"Jun 16 14:29:03 2021 # by: pyside2-uic running on PySide2",
"self.verticalLayout.addLayout(self.horizontalLayout) self.tableElements = QtWidgets.QTableView(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0)",
"the table \", None, -1)) self.btn_refresh.setStatusTip( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the",
"QtWidgets class Ui_ElementsWindow(object): def setupUi(self, ElementsWindow): ElementsWindow.setObjectName(\"ElementsWindow\") ElementsWindow.resize(841, 623) self.centralwidget",
"self.btn_refresh = QtWidgets.QPushButton(self.centralwidget) self.btn_refresh.setCursor(QtCore.Qt.ClosedHandCursor) self.btn_refresh.setText(\"\") icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(\":/refresh\"), QtGui.QIcon.Normal,",
"retranslateUi(self, ElementsWindow): ElementsWindow.setWindowTitle( QtWidgets.QApplication.translate(\"ElementsWindow\", \"MainWindow\", None, -1)) self.btn_refresh.setToolTip( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force",
"table you wish to view</p></body></html>\", None, -1)) self.label_3.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \"",
"self.verticalLayout.setSizeConstraint( QtWidgets.QLayout.SetDefaultConstraint) self.verticalLayout.setObjectName(\"verticalLayout\") self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName(\"horizontalLayout\") self.btn_refresh = QtWidgets.QPushButton(self.centralwidget)",
"Filter: \", None, -1)) self.label_2.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Component: \", None, -1))",
"QtWidgets.QApplication.translate(\"ElementsWindow\", \"Component: \", None, -1)) self.label_4.setText( QtWidgets.QApplication.translate(\"ElementsWindow\", \" Layer: \",",
"QtGui.QFont() font.setWeight(75) font.setBold(True) self.label.setFont(font) self.label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter) self.label.setObjectName(\"label\")",
"QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.combo_element_type.sizePolicy().hasHeightForWidth()) self.combo_element_type.setSizePolicy(sizePolicy) self.combo_element_type.setCurrentText(\"\") self.combo_element_type.setSizeAdjustPolicy( QtWidgets.QComboBox.AdjustToContents)",
"QtWidgets.QComboBox.AdjustToContents) self.combo_element_type.setObjectName(\"combo_element_type\") self.horizontalLayout.addWidget(self.combo_element_type) self.line = QtWidgets.QFrame(self.centralwidget) self.line.setFrameShape(QtWidgets.QFrame.VLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName(\"line\") self.horizontalLayout.addWidget(self.line)",
"QtGui.QIcon.Off) self.btn_refresh.setIcon(icon) self.btn_refresh.setIconSize(QtCore.QSize(20, 20)) self.btn_refresh.setAutoDefault(False) self.btn_refresh.setDefault(False) self.btn_refresh.setFlat(True) self.btn_refresh.setObjectName(\"btn_refresh\") self.horizontalLayout.addWidget(self.btn_refresh) self.label",
"0, 0, 0) self.verticalLayout_2.setObjectName(\"verticalLayout_2\") self.verticalLayout = QtWidgets.QVBoxLayout() self.verticalLayout.setSizeConstraint( QtWidgets.QLayout.SetDefaultConstraint) self.verticalLayout.setObjectName(\"verticalLayout\")",
"self.lineEdit = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit.setObjectName(\"lineEdit\") self.horizontalLayout.addWidget(self.lineEdit) self.label_4 = QtWidgets.QLabel(self.centralwidget) self.label_4.setObjectName(\"label_4\") self.horizontalLayout.addWidget(self.label_4)",
"= QtWidgets.QLabel(self.centralwidget) font = QtGui.QFont() font.setWeight(75) font.setBold(True) self.label_3.setFont(font) self.label_3.setObjectName(\"label_3\") self.horizontalLayout.addWidget(self.label_3)",
"\"MainWindow\", None, -1)) self.btn_refresh.setToolTip( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the table \",",
"-1)) self.btn_refresh.setToolTip( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the table \", None, -1))",
"QtCore, QtGui, QtWidgets class Ui_ElementsWindow(object): def setupUi(self, ElementsWindow): ElementsWindow.setObjectName(\"ElementsWindow\") ElementsWindow.resize(841,",
"self.label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter) self.label.setObjectName(\"label\") self.horizontalLayout.addWidget(self.label) self.combo_element_type = QtWidgets.QComboBox(self.centralwidget)",
"on PySide2 5.13.2 # # WARNING! All changes made in",
"self.combo_element_type.setToolTip( QtWidgets.QApplication.translate( \"ElementsWindow\", \"<html><head/><body><p>Select the element table you wish to",
"applies. # # Created: Wed Jun 16 14:29:03 2021 #",
"font.setWeight(75) font.setBold(True) self.label.setFont(font) self.label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter) self.label.setObjectName(\"label\") self.horizontalLayout.addWidget(self.label)",
"import QtCore, QtGui, QtWidgets class Ui_ElementsWindow(object): def setupUi(self, ElementsWindow): ElementsWindow.setObjectName(\"ElementsWindow\")",
"by: pyside2-uic running on PySide2 5.13.2 # # WARNING! All",
"self.label_4 = QtWidgets.QLabel(self.centralwidget) self.label_4.setObjectName(\"label_4\") self.horizontalLayout.addWidget(self.label_4) self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit_2.setObjectName(\"lineEdit_2\") self.horizontalLayout.addWidget(self.lineEdit_2)",
"QtWidgets.QTableView(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.tableElements.sizePolicy().hasHeightForWidth()) self.tableElements.setSizePolicy(sizePolicy)",
"'./elements_ui.ui', # licensing of './elements_ui.ui' applies. # # Created: Wed",
"QtWidgets.QLabel(self.centralwidget) self.label_2.setObjectName(\"label_2\") self.horizontalLayout.addWidget(self.label_2) self.lineEdit = QtWidgets.QLineEdit(self.centralwidget) self.lineEdit.setObjectName(\"lineEdit\") self.horizontalLayout.addWidget(self.lineEdit) self.label_4 =",
"self.verticalLayout_2.setSpacing(0) self.verticalLayout_2.setContentsMargins(0, 0, 0, 0) self.verticalLayout_2.setObjectName(\"verticalLayout_2\") self.verticalLayout = QtWidgets.QVBoxLayout() self.verticalLayout.setSizeConstraint(",
"self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName(\"horizontalLayout\") self.btn_refresh = QtWidgets.QPushButton(self.centralwidget) self.btn_refresh.setCursor(QtCore.Qt.ClosedHandCursor) self.btn_refresh.setText(\"\") icon",
"self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName(\"line\") self.horizontalLayout.addWidget(self.line) self.label_3 = QtWidgets.QLabel(self.centralwidget) font = QtGui.QFont() font.setWeight(75)",
"ElementsWindow): ElementsWindow.setWindowTitle( QtWidgets.QApplication.translate(\"ElementsWindow\", \"MainWindow\", None, -1)) self.btn_refresh.setToolTip( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh",
"-1)) self.btn_refresh.setAccessibleDescription( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the table \", None, -1))",
"QtWidgets.QWidget(ElementsWindow) self.centralwidget.setObjectName(\"centralwidget\") self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.centralwidget) self.verticalLayout_2.setSpacing(0) self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)",
"ElementsWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar() self.menubar.setGeometry(QtCore.QRect(0, 0, 841, 22)) self.menubar.setObjectName(\"menubar\") ElementsWindow.setMenuBar(self.menubar)",
"font = QtGui.QFont() font.setWeight(75) font.setBold(True) self.label_3.setFont(font) self.label_3.setObjectName(\"label_3\") self.horizontalLayout.addWidget(self.label_3) self.label_2 =",
"self.label_3.setObjectName(\"label_3\") self.horizontalLayout.addWidget(self.label_3) self.label_2 = QtWidgets.QLabel(self.centralwidget) self.label_2.setObjectName(\"label_2\") self.horizontalLayout.addWidget(self.label_2) self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)",
"self.btn_refresh.setWhatsThis( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the table \", None, -1)) self.btn_refresh.setAccessibleDescription(",
"\", None, -1)) self.btn_refresh.setAccessibleDescription( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the table \",",
"self.verticalLayout = QtWidgets.QVBoxLayout() self.verticalLayout.setSizeConstraint( QtWidgets.QLayout.SetDefaultConstraint) self.verticalLayout.setObjectName(\"verticalLayout\") self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName(\"horizontalLayout\")",
"QtWidgets.QFrame(self.centralwidget) self.line_2.setFrameShape(QtWidgets.QFrame.VLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName(\"line_2\") self.horizontalLayout.addWidget(self.line_2) self.verticalLayout.addLayout(self.horizontalLayout) self.tableElements = QtWidgets.QTableView(self.centralwidget) sizePolicy",
"self.statusbar.setObjectName(\"statusbar\") ElementsWindow.setStatusBar(self.statusbar) self.retranslateUi(ElementsWindow) QtCore.QObject.connect(self.combo_element_type, QtCore.SIGNAL(\"currentIndexChanged(QString)\"), ElementsWindow.combo_element_type) QtCore.QObject.connect(self.btn_refresh, QtCore.SIGNAL(\"clicked()\"), ElementsWindow.force_refresh) QtCore.QMetaObject.connectSlotsByName(ElementsWindow)",
"# Created: Wed Jun 16 14:29:03 2021 # by: pyside2-uic",
"None, -1)) self.btn_refresh.setWhatsThis( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the table \", None,",
"this file will be lost! from PySide2 import QtCore, QtGui,",
"self.btn_refresh.setIcon(icon) self.btn_refresh.setIconSize(QtCore.QSize(20, 20)) self.btn_refresh.setAutoDefault(False) self.btn_refresh.setDefault(False) self.btn_refresh.setFlat(True) self.btn_refresh.setObjectName(\"btn_refresh\") self.horizontalLayout.addWidget(self.btn_refresh) self.label =",
"PySide2 5.13.2 # # WARNING! All changes made in this",
"self.combo_element_type.sizePolicy().hasHeightForWidth()) self.combo_element_type.setSizePolicy(sizePolicy) self.combo_element_type.setCurrentText(\"\") self.combo_element_type.setSizeAdjustPolicy( QtWidgets.QComboBox.AdjustToContents) self.combo_element_type.setObjectName(\"combo_element_type\") self.horizontalLayout.addWidget(self.combo_element_type) self.line = QtWidgets.QFrame(self.centralwidget)",
"the table \", None, -1)) self.btn_refresh.setAccessibleDescription( QtWidgets.QApplication.translate(\"ElementsWindow\", \"Force refresh the"
] |
[
"cube(number): return number*number*number digit = input(\" the cube of which",
"def cube(number): return number*number*number digit = input(\" the cube of",
"digit = input(\" the cube of which digit do you",
"of which digit do you want >\") result = cube(int(digit))",
"return number*number*number digit = input(\" the cube of which digit",
"input(\" the cube of which digit do you want >\")",
"the cube of which digit do you want >\") result",
"number*number*number digit = input(\" the cube of which digit do",
"cube of which digit do you want >\") result =",
"which digit do you want >\") result = cube(int(digit)) print(result)",
"= input(\" the cube of which digit do you want"
] |
[
"def test_it_will_return_1_exit_code_on_failure(bad_py_file): try: run(targets=[bad_py_file.strpath]) except SystemExit as exception: assert exception.code",
"mock_popen: mock_popen.returncode = 0 result = _run_command('dummy_cmd', [''], ['']) assert",
"== 1 def test_it_will_return_zero_exit_code_on_success(good_py_file): try: run(targets=[good_py_file.strpath]) except SystemExit as exception:",
"from unittest.mock import patch except ImportError: # pragma: no cover",
"try: run(targets=[good_py_file.strpath], check_licenses=True) except SystemExit as exception: assert exception.code ==",
"exception.code == 0 def test_run_command_will_return_a_bool(): with patch('proofreader.runner.Popen') as mock_popen: mock_popen.returncode",
"def test_it_will_return_zero_exit_code_on_success(good_py_file): try: run(targets=[good_py_file.strpath]) except SystemExit as exception: assert exception.code",
"as exception: assert exception.code == 0 def test_run_command_will_return_a_bool(): with patch('proofreader.runner.Popen')",
"mock import patch from proofreader.runner import run, _run_command def test_it_will_return_1_exit_code_on_failure(bad_py_file):",
"except SystemExit as exception: assert exception.code == 0 def test_run_command_will_return_a_bool():",
"exception.code == 1 def test_it_will_return_zero_exit_code_on_success(good_py_file): try: run(targets=[good_py_file.strpath]) except SystemExit as",
"with patch('proofreader.runner.Popen') as mock_popen: mock_popen.returncode = 0 result = _run_command('dummy_cmd',",
"_run_command def test_it_will_return_1_exit_code_on_failure(bad_py_file): try: run(targets=[bad_py_file.strpath]) except SystemExit as exception: assert",
"no cover from mock import patch from proofreader.runner import run,",
"exception: assert exception.code == 0 def test_run_command_will_return_a_bool(): with patch('proofreader.runner.Popen') as",
"try: run(targets=[bad_py_file.strpath]) except SystemExit as exception: assert exception.code == 1",
"assert exception.code == 1 def test_it_will_return_zero_exit_code_on_success(good_py_file): try: run(targets=[good_py_file.strpath]) except SystemExit",
"def test_run_command_will_return_a_bool(): with patch('proofreader.runner.Popen') as mock_popen: mock_popen.returncode = 0 result",
"proofreader.runner import run, _run_command def test_it_will_return_1_exit_code_on_failure(bad_py_file): try: run(targets=[bad_py_file.strpath]) except SystemExit",
"SystemExit as exception: assert exception.code == 0 def test_run_command_will_return_a_bool(): with",
"pragma: no cover from mock import patch from proofreader.runner import",
"isinstance(result, bool) def test_will_return_zero_on_success_with_license_check(good_py_file): try: run(targets=[good_py_file.strpath], check_licenses=True) except SystemExit as",
"SystemExit as exception: assert exception.code == 1 def test_it_will_return_zero_exit_code_on_success(good_py_file): try:",
"ImportError: # pragma: no cover from mock import patch from",
"patch from proofreader.runner import run, _run_command def test_it_will_return_1_exit_code_on_failure(bad_py_file): try: run(targets=[bad_py_file.strpath])",
"test_it_returns_zero_exit_code_on_builtin_shadowing_fail(builtin_fail_py_file): try: run(targets=[builtin_fail_py_file.strpath]) except SystemExit as exception: assert exception.code ==",
"def test_it_returns_zero_exit_code_on_builtin_shadowing_fail(builtin_fail_py_file): try: run(targets=[builtin_fail_py_file.strpath]) except SystemExit as exception: assert exception.code",
"assert exception.code == 0 def test_it_returns_zero_exit_code_on_builtin_shadowing_fail(builtin_fail_py_file): try: run(targets=[builtin_fail_py_file.strpath]) except SystemExit",
"# pragma: no cover from mock import patch from proofreader.runner",
"assert exception.code == 0 def test_run_command_will_return_a_bool(): with patch('proofreader.runner.Popen') as mock_popen:",
"exception: assert exception.code == 1 def test_it_will_return_zero_exit_code_on_success(good_py_file): try: run(targets=[good_py_file.strpath]) except",
"== 0 def test_it_returns_zero_exit_code_on_builtin_shadowing_fail(builtin_fail_py_file): try: run(targets=[builtin_fail_py_file.strpath]) except SystemExit as exception:",
"run(targets=[good_py_file.strpath], check_licenses=True) except SystemExit as exception: assert exception.code == 0",
"1 def test_it_will_return_zero_exit_code_on_success(good_py_file): try: run(targets=[good_py_file.strpath]) except SystemExit as exception: assert",
"['']) assert isinstance(result, bool) def test_will_return_zero_on_success_with_license_check(good_py_file): try: run(targets=[good_py_file.strpath], check_licenses=True) except",
"test_it_will_return_1_exit_code_on_failure(bad_py_file): try: run(targets=[bad_py_file.strpath]) except SystemExit as exception: assert exception.code ==",
"test_run_command_will_return_a_bool(): with patch('proofreader.runner.Popen') as mock_popen: mock_popen.returncode = 0 result =",
"run(targets=[bad_py_file.strpath]) except SystemExit as exception: assert exception.code == 1 def",
"== 0 def test_run_command_will_return_a_bool(): with patch('proofreader.runner.Popen') as mock_popen: mock_popen.returncode =",
"unittest.mock import patch except ImportError: # pragma: no cover from",
"try: from unittest.mock import patch except ImportError: # pragma: no",
"run(targets=[good_py_file.strpath]) except SystemExit as exception: assert exception.code == 0 def",
"0 def test_it_returns_zero_exit_code_on_builtin_shadowing_fail(builtin_fail_py_file): try: run(targets=[builtin_fail_py_file.strpath]) except SystemExit as exception: assert",
"try: run(targets=[good_py_file.strpath]) except SystemExit as exception: assert exception.code == 0",
"def test_will_return_zero_on_success_with_license_check(good_py_file): try: run(targets=[good_py_file.strpath], check_licenses=True) except SystemExit as exception: assert",
"0 result = _run_command('dummy_cmd', [''], ['']) assert isinstance(result, bool) def",
"exception.code == 0 def test_it_returns_zero_exit_code_on_builtin_shadowing_fail(builtin_fail_py_file): try: run(targets=[builtin_fail_py_file.strpath]) except SystemExit as",
"from mock import patch from proofreader.runner import run, _run_command def",
"except ImportError: # pragma: no cover from mock import patch",
"as exception: assert exception.code == 1 def test_it_will_return_zero_exit_code_on_success(good_py_file): try: run(targets=[good_py_file.strpath])",
"mock_popen.returncode = 0 result = _run_command('dummy_cmd', [''], ['']) assert isinstance(result,",
"as exception: assert exception.code == 0 def test_it_returns_zero_exit_code_on_builtin_shadowing_fail(builtin_fail_py_file): try: run(targets=[builtin_fail_py_file.strpath])",
"run, _run_command def test_it_will_return_1_exit_code_on_failure(bad_py_file): try: run(targets=[bad_py_file.strpath]) except SystemExit as exception:",
"[''], ['']) assert isinstance(result, bool) def test_will_return_zero_on_success_with_license_check(good_py_file): try: run(targets=[good_py_file.strpath], check_licenses=True)",
"from proofreader.runner import run, _run_command def test_it_will_return_1_exit_code_on_failure(bad_py_file): try: run(targets=[bad_py_file.strpath]) except",
"patch except ImportError: # pragma: no cover from mock import",
"assert isinstance(result, bool) def test_will_return_zero_on_success_with_license_check(good_py_file): try: run(targets=[good_py_file.strpath], check_licenses=True) except SystemExit",
"<reponame>elifesciences/proofreader-python<gh_stars>1-10 try: from unittest.mock import patch except ImportError: # pragma:",
"cover from mock import patch from proofreader.runner import run, _run_command",
"try: run(targets=[builtin_fail_py_file.strpath]) except SystemExit as exception: assert exception.code == 0",
"as mock_popen: mock_popen.returncode = 0 result = _run_command('dummy_cmd', [''], [''])",
"= _run_command('dummy_cmd', [''], ['']) assert isinstance(result, bool) def test_will_return_zero_on_success_with_license_check(good_py_file): try:",
"= 0 result = _run_command('dummy_cmd', [''], ['']) assert isinstance(result, bool)",
"SystemExit as exception: assert exception.code == 0 def test_it_returns_zero_exit_code_on_builtin_shadowing_fail(builtin_fail_py_file): try:",
"except SystemExit as exception: assert exception.code == 0 def test_it_returns_zero_exit_code_on_builtin_shadowing_fail(builtin_fail_py_file):",
"0 def test_run_command_will_return_a_bool(): with patch('proofreader.runner.Popen') as mock_popen: mock_popen.returncode = 0",
"test_it_will_return_zero_exit_code_on_success(good_py_file): try: run(targets=[good_py_file.strpath]) except SystemExit as exception: assert exception.code ==",
"import run, _run_command def test_it_will_return_1_exit_code_on_failure(bad_py_file): try: run(targets=[bad_py_file.strpath]) except SystemExit as",
"patch('proofreader.runner.Popen') as mock_popen: mock_popen.returncode = 0 result = _run_command('dummy_cmd', [''],",
"except SystemExit as exception: assert exception.code == 1 def test_it_will_return_zero_exit_code_on_success(good_py_file):",
"import patch from proofreader.runner import run, _run_command def test_it_will_return_1_exit_code_on_failure(bad_py_file): try:",
"run(targets=[builtin_fail_py_file.strpath]) except SystemExit as exception: assert exception.code == 0 def",
"import patch except ImportError: # pragma: no cover from mock",
"_run_command('dummy_cmd', [''], ['']) assert isinstance(result, bool) def test_will_return_zero_on_success_with_license_check(good_py_file): try: run(targets=[good_py_file.strpath],",
"result = _run_command('dummy_cmd', [''], ['']) assert isinstance(result, bool) def test_will_return_zero_on_success_with_license_check(good_py_file):",
"bool) def test_will_return_zero_on_success_with_license_check(good_py_file): try: run(targets=[good_py_file.strpath], check_licenses=True) except SystemExit as exception:",
"test_will_return_zero_on_success_with_license_check(good_py_file): try: run(targets=[good_py_file.strpath], check_licenses=True) except SystemExit as exception: assert exception.code",
"exception: assert exception.code == 0 def test_it_returns_zero_exit_code_on_builtin_shadowing_fail(builtin_fail_py_file): try: run(targets=[builtin_fail_py_file.strpath]) except"
] |
[
"be handled by derived classes for now. class Container(object): def",
"for mobject in mobjects: for submod in self.submobjects: if isinstance(submod,",
"albeit purely nominally. # All actual implementation has to be",
"list(mobjects) + self.submobjects return self def remove(self, *mobjects, ): for",
"Mobject. # Still, we abstract its functionality here, albeit purely",
"really better to name it submobjects? def add(self, *mobjects): if",
"Exception(\"Mobject cannot contain self\") self.submobjects = list_update(self.submobjects, mobjects) return self",
"contain self\") self.submobjects = list_update(self.submobjects, mobjects) return self def add_to_back(self,",
"# Still, we abstract its functionality here, albeit purely nominally.",
"= list(mobjects) + self.submobjects return self def remove(self, *mobjects, ):",
"to name it submobjects? def add(self, *mobjects): if self in",
"submobjects? def add(self, *mobjects): if self in mobjects: raise Exception(\"Mobject",
"Currently, this is only used by both Scene and Mobject.",
"if self in mobjects: raise Exception(\"Mobject cannot contain self\") self.submobjects",
"tanim.utils.config_ops import digest_config from tanim.utils.iterables import list_update # Currently, this",
"digest_config(self, kwargs) self.submobjects = [] # Is it really better",
"import digest_config from tanim.utils.iterables import list_update # Currently, this is",
"[] # Is it really better to name it submobjects?",
"add_to_back(self, *mobjects): self.remove(*mobjects) self.submobjects = list(mobjects) + self.submobjects return self",
"# All actual implementation has to be handled by derived",
"mobject in mobjects: for submod in self.submobjects: if isinstance(submod, GroupContainer):",
"# Is it really better to name it submobjects? def",
"return self def remove(self, *mobjects, ): for mobject in mobjects:",
"): for mobject in mobjects: for submod in self.submobjects: if",
"its functionality here, albeit purely nominally. # All actual implementation",
"by both Scene and Mobject. # Still, we abstract its",
"remove(self, *mobjects, ): for mobject in mobjects: for submod in",
"def __init__(self, **kwargs): digest_config(self, kwargs) self.submobjects = [] # Is",
"now. class Container(object): def __init__(self, **kwargs): digest_config(self, kwargs) self.submobjects =",
"GroupContainer): submod.remove(mobject) elif mobject == submod: self.submobjects.remove(mobject) return self class",
"return self def add_to_back(self, *mobjects): self.remove(*mobjects) self.submobjects = list(mobjects) +",
"has to be handled by derived classes for now. class",
"import list_update # Currently, this is only used by both",
"tanim.utils.iterables import list_update # Currently, this is only used by",
"both Scene and Mobject. # Still, we abstract its functionality",
"it submobjects? def add(self, *mobjects): if self in mobjects: raise",
"mobjects: raise Exception(\"Mobject cannot contain self\") self.submobjects = list_update(self.submobjects, mobjects)",
"self.submobjects.remove(mobject) return self class GroupContainer(Container): def __init__(self, *containers, **kwargs): self.add(*containers)",
"submod in self.submobjects: if isinstance(submod, GroupContainer): submod.remove(mobject) elif mobject ==",
"self.submobjects = [] # Is it really better to name",
"self.submobjects = list(mobjects) + self.submobjects return self def remove(self, *mobjects,",
"classes for now. class Container(object): def __init__(self, **kwargs): digest_config(self, kwargs)",
"add(self, *mobjects): if self in mobjects: raise Exception(\"Mobject cannot contain",
"submod: self.submobjects.remove(mobject) return self class GroupContainer(Container): def __init__(self, *containers, **kwargs):",
"All actual implementation has to be handled by derived classes",
"kwargs) self.submobjects = [] # Is it really better to",
"self def add_to_back(self, *mobjects): self.remove(*mobjects) self.submobjects = list(mobjects) + self.submobjects",
"submod.remove(mobject) elif mobject == submod: self.submobjects.remove(mobject) return self class GroupContainer(Container):",
"def remove(self, *mobjects, ): for mobject in mobjects: for submod",
"for submod in self.submobjects: if isinstance(submod, GroupContainer): submod.remove(mobject) elif mobject",
"nominally. # All actual implementation has to be handled by",
"implementation has to be handled by derived classes for now.",
"*mobjects, ): for mobject in mobjects: for submod in self.submobjects:",
"we abstract its functionality here, albeit purely nominally. # All",
"derived classes for now. class Container(object): def __init__(self, **kwargs): digest_config(self,",
"is only used by both Scene and Mobject. # Still,",
"here, albeit purely nominally. # All actual implementation has to",
"Scene and Mobject. # Still, we abstract its functionality here,",
"this is only used by both Scene and Mobject. #",
"class Container(object): def __init__(self, **kwargs): digest_config(self, kwargs) self.submobjects = []",
"Is it really better to name it submobjects? def add(self,",
"*mobjects): if self in mobjects: raise Exception(\"Mobject cannot contain self\")",
"only used by both Scene and Mobject. # Still, we",
"for now. class Container(object): def __init__(self, **kwargs): digest_config(self, kwargs) self.submobjects",
"purely nominally. # All actual implementation has to be handled",
"mobjects: for submod in self.submobjects: if isinstance(submod, GroupContainer): submod.remove(mobject) elif",
"it really better to name it submobjects? def add(self, *mobjects):",
"if isinstance(submod, GroupContainer): submod.remove(mobject) elif mobject == submod: self.submobjects.remove(mobject) return",
"Still, we abstract its functionality here, albeit purely nominally. #",
"isinstance(submod, GroupContainer): submod.remove(mobject) elif mobject == submod: self.submobjects.remove(mobject) return self",
"= [] # Is it really better to name it",
"Container(object): def __init__(self, **kwargs): digest_config(self, kwargs) self.submobjects = [] #",
"to be handled by derived classes for now. class Container(object):",
"used by both Scene and Mobject. # Still, we abstract",
"actual implementation has to be handled by derived classes for",
"*mobjects): self.remove(*mobjects) self.submobjects = list(mobjects) + self.submobjects return self def",
"functionality here, albeit purely nominally. # All actual implementation has",
"== submod: self.submobjects.remove(mobject) return self class GroupContainer(Container): def __init__(self, *containers,",
"**kwargs): digest_config(self, kwargs) self.submobjects = [] # Is it really",
"handled by derived classes for now. class Container(object): def __init__(self,",
"__init__(self, **kwargs): digest_config(self, kwargs) self.submobjects = [] # Is it",
"abstract its functionality here, albeit purely nominally. # All actual",
"name it submobjects? def add(self, *mobjects): if self in mobjects:",
"self def remove(self, *mobjects, ): for mobject in mobjects: for",
"list_update # Currently, this is only used by both Scene",
"def add(self, *mobjects): if self in mobjects: raise Exception(\"Mobject cannot",
"self.submobjects: if isinstance(submod, GroupContainer): submod.remove(mobject) elif mobject == submod: self.submobjects.remove(mobject)",
"raise Exception(\"Mobject cannot contain self\") self.submobjects = list_update(self.submobjects, mobjects) return",
"in mobjects: raise Exception(\"Mobject cannot contain self\") self.submobjects = list_update(self.submobjects,",
"better to name it submobjects? def add(self, *mobjects): if self",
"mobject == submod: self.submobjects.remove(mobject) return self class GroupContainer(Container): def __init__(self,",
"self in mobjects: raise Exception(\"Mobject cannot contain self\") self.submobjects =",
"list_update(self.submobjects, mobjects) return self def add_to_back(self, *mobjects): self.remove(*mobjects) self.submobjects =",
"by derived classes for now. class Container(object): def __init__(self, **kwargs):",
"self.submobjects = list_update(self.submobjects, mobjects) return self def add_to_back(self, *mobjects): self.remove(*mobjects)",
"self.submobjects return self def remove(self, *mobjects, ): for mobject in",
"from tanim.utils.iterables import list_update # Currently, this is only used",
"and Mobject. # Still, we abstract its functionality here, albeit",
"cannot contain self\") self.submobjects = list_update(self.submobjects, mobjects) return self def",
"mobjects) return self def add_to_back(self, *mobjects): self.remove(*mobjects) self.submobjects = list(mobjects)",
"digest_config from tanim.utils.iterables import list_update # Currently, this is only",
"def add_to_back(self, *mobjects): self.remove(*mobjects) self.submobjects = list(mobjects) + self.submobjects return",
"elif mobject == submod: self.submobjects.remove(mobject) return self class GroupContainer(Container): def",
"in mobjects: for submod in self.submobjects: if isinstance(submod, GroupContainer): submod.remove(mobject)",
"from tanim.utils.config_ops import digest_config from tanim.utils.iterables import list_update # Currently,",
"+ self.submobjects return self def remove(self, *mobjects, ): for mobject",
"self\") self.submobjects = list_update(self.submobjects, mobjects) return self def add_to_back(self, *mobjects):",
"= list_update(self.submobjects, mobjects) return self def add_to_back(self, *mobjects): self.remove(*mobjects) self.submobjects",
"in self.submobjects: if isinstance(submod, GroupContainer): submod.remove(mobject) elif mobject == submod:",
"# Currently, this is only used by both Scene and",
"self.remove(*mobjects) self.submobjects = list(mobjects) + self.submobjects return self def remove(self,"
] |
[
"finish_task_in_db(task, article, type): update_task_status(task) update_finish_status(type, article) def count_person_performance(type, email): try:",
"email): try: cur = db.cursor() sql = \"SELECT * FROM",
"result except Exception as e: print(e) def get_works_list(articles): res =",
"type, article_id, work_due, staff) db.ping(reconnect=True) cur.execute(sql) db.commit() cur.close() except Exception",
"try: cur = db.cursor() sql = \"SELECT Name FROM user",
"sql = '' if type == 1: sql = \"UPDATE",
"cur.fetchall() db.commit() cur.close() return res except Exception as e: print(e)",
"email db.ping(reconnect=True) cur.execute(sql) result = cur.fetchone() db.commit() cur.close() return result",
"Exception as e: print(e) def get_task_list(email, articles): res = {}",
"% (email, type) db.ping(reconnect=True) cur.execute(sql) res = cur.fetchall() db.commit() cur.close()",
"works_type=%s AND is_finished='Y'\" % (email, type) db.ping(reconnect=True) cur.execute(sql) res =",
"result except Exception as e: print(e) def get_user_name(email): try: cur",
"in articles: id = a[0] tasks = get_your_task_with_article(email, id) res[id]",
"works_type\" % id db.ping(reconnect=True) cur.execute(sql) result = cur.fetchall() db.commit() cur.close()",
"get_user_name(w[5])[0]] work.append(my_list) res[id] = work return res def get_your_task_with_article(email, id):",
"cur.execute(sql) result = cur.fetchall() db.commit() cur.close() return result except Exception",
"result except Exception as e: print(e) def add_works_to_db(article_id, type, staff,",
"in works: my_list = [w[0], w[1], w[3], get_user_name(w[5])[0]] work.append(my_list) res[id]",
"print(e) def get_works_list(articles): res = {} for i in range(0,",
"= db.cursor() sql = \"SELECT Name FROM user WHERE email='%s'\"",
"cur.execute(sql) db.commit() cur.close() except Exception as e: print(e) def update_task_status(id):",
"1: sql = \"UPDATE article SET banner_status='Y' WHERE article_id=%s\" %",
"type == 1: sql = \"UPDATE article SET banner_status='Y' WHERE",
"in all_staff: email = s[1] banner = count_person_performance(1, email) text",
"as e: print(e) def get_article_s_work(id): try: cur = db.cursor() sql",
"article_id=%s\" % id db.ping(reconnect=True) cur.execute(sql) db.commit() cur.close() except Exception as",
"= db.cursor() sql = \"SELECT * FROM article WHERE article_status='N'\"",
"\"UPDATE article SET banner_status='Y' WHERE article_id=%s\" % id elif type",
"id = articles[i][0] work = [] works = get_article_s_work(id) for",
"2: sql = \"UPDATE article SET text_status='Y' WHERE article_id=%s\" %",
"(email, type) db.ping(reconnect=True) cur.execute(sql) res = cur.fetchall() db.commit() cur.close() return",
"Exception as e: print(e) def get_article_s_work(id): try: cur = db.cursor()",
"% id db.ping(reconnect=True) cur.execute(sql) db.commit() cur.close() except Exception as e:",
"db.cursor() sql = \"SELECT * FROM article_works WHERE works_staff='%s' AND",
"( type, article_id, work_due, staff) db.ping(reconnect=True) cur.execute(sql) db.commit() cur.close() except",
"work return res def get_your_task_with_article(email, id): try: cur = db.cursor()",
"AND works_type=%s AND is_finished='Y'\" % (email, type) db.ping(reconnect=True) cur.execute(sql) res",
"= \"UPDATE article SET text_status='Y' WHERE article_id=%s\" % id elif",
"sql = \"UPDATE article_works SET is_finished='Y' WHERE works_num=%s\" % id",
"try: cur = db.cursor() sql = \"SELECT Name,email FROM user",
"db.cursor() sql = \"INSERT INTO article_works(works_type,works_article,works_dueday,works_staff)VALUES (%s,%s,'%s','%s');\" % ( type,",
"except Exception as e: print(e) def finish_task_in_db(task, article, type): update_task_status(task)",
"cur = db.cursor() sql = \"SELECT Name,email FROM user WHERE",
"print(e) def add_works_to_db(article_id, type, staff, work_due): try: cur = db.cursor()",
"db.cursor() sql = \"SELECT Name,email FROM user WHERE type=5\" db.ping(reconnect=True)",
"as e: print(e) def finish_task_in_db(task, article, type): update_task_status(task) update_finish_status(type, article)",
"print(e) def count_performance(): all_staff = fetch_all_mkt_staff() performance_list = [] for",
"Name FROM user WHERE email='%s'\" % email db.ping(reconnect=True) cur.execute(sql) result",
"work.append(my_list) res[id] = work return res def get_your_task_with_article(email, id): try:",
"print(e) def update_task_status(id): try: cur = db.cursor() sql = \"UPDATE",
"Exception as e: print(e) def add_works_to_db(article_id, type, staff, work_due): try:",
"e: print(e) def get_article_id(title): try: cur = db.cursor() sql =",
"INTO article(article_title,article_dueday)VALUES ('%s','%s')\" % (title, due) db.ping(reconnect=True) cur.execute(sql) db.commit() cur.close()",
"e: print(e) def get_user_name(email): try: cur = db.cursor() sql =",
"id db.ping(reconnect=True) cur.execute(sql) db.commit() cur.close() except Exception as e: print(e)",
"= db.cursor() sql = \"INSERT INTO article(article_title,article_dueday)VALUES ('%s','%s')\" % (title,",
"cur.close() return result except Exception as e: print(e) def get_task_list(email,",
"FROM article WHERE article_title='%s' AND article_status='N'\" % title db.ping(reconnect=True) cur.execute(sql)",
"tasks return res def update_finish_status(type, id): try: type = int(type)",
"works_article=%s\" % (email, id) db.ping(reconnect=True) cur.execute(sql) result = cur.fetchall() db.commit()",
"= db.cursor() sql = '' if type == 1: sql",
"cur.execute(sql) res = cur.fetchall() db.commit() cur.close() return res except Exception",
"WHERE article_id=%s\" % id db.ping(reconnect=True) cur.execute(sql) db.commit() cur.close() except Exception",
"cur.fetchone() db.commit() cur.close() return result except Exception as e: print(e)",
"sql = \"INSERT INTO article(article_title,article_dueday)VALUES ('%s','%s')\" % (title, due) db.ping(reconnect=True)",
"from config import * def fetch_all_article(): try: cur = db.cursor()",
"print(e) def get_article_s_work(id): try: cur = db.cursor() sql = \"SELECT",
"as e: print(e) def get_user_name(email): try: cur = db.cursor() sql",
"sql = \"SELECT * FROM article_works WHERE works_staff='%s' AND works_article=%s\"",
"type == 3: sql = \"UPDATE article SET style_status='Y' WHERE",
"'' if type == 1: sql = \"UPDATE article SET",
"= db.cursor() sql = \"SELECT * FROM article_works WHERE works_article=%s",
"db.commit() cur.close() return result except Exception as e: print(e) def",
"db.cursor() sql = '' if type == 1: sql =",
"res except Exception as e: print(e) def count_performance(): all_staff =",
"except Exception as e: print(e) def get_article_s_work(id): try: cur =",
"article, type): update_task_status(task) update_finish_status(type, article) def count_person_performance(type, email): try: cur",
"res = {} for i in range(0, len(articles)): id =",
"articles[i][0] work = [] works = get_article_s_work(id) for w in",
"add_article_to_db(title, due): try: cur = db.cursor() sql = \"INSERT INTO",
"style_status='Y' WHERE article_id=%s\" % id db.ping(reconnect=True) cur.execute(sql) db.commit() cur.close() except",
"SET text_status='Y' WHERE article_id=%s\" % id elif type == 3:",
"= db.cursor() sql = \"SELECT * FROM article_works WHERE works_staff='%s'",
"cur.close() except Exception as e: print(e) def update_task_status(id): try: cur",
"db.commit() cur.close() except Exception as e: print(e) def finish_task_in_db(task, article,",
"= {} for a in articles: id = a[0] tasks",
"update_finish_status(type, article) def count_person_performance(type, email): try: cur = db.cursor() sql",
"db.cursor() sql = \"SELECT * FROM article WHERE article_status='N'\" db.ping(reconnect=True)",
"result = cur.fetchone() db.commit() cur.close() return result except Exception as",
"for s in all_staff: email = s[1] banner = count_person_performance(1,",
"e: print(e) def finish_task_in_db(task, article, type): update_task_status(task) update_finish_status(type, article) def",
"s[1] banner = count_person_performance(1, email) text = count_person_performance(2, email) style",
"def count_person_performance(type, email): try: cur = db.cursor() sql = \"SELECT",
"elif type == 2: sql = \"UPDATE article SET text_status='Y'",
"return result except Exception as e: print(e) def get_user_name(email): try:",
"= {} for i in range(0, len(articles)): id = articles[i][0]",
"db.cursor() sql = \"SELECT * FROM article_works WHERE works_article=%s ORDER",
"= tasks return res def update_finish_status(type, id): try: type =",
"if type == 1: sql = \"UPDATE article SET banner_status='Y'",
"article_works SET is_finished='Y' WHERE works_num=%s\" % id db.ping(reconnect=True) cur.execute(sql) db.commit()",
"% (title, due) db.ping(reconnect=True) cur.execute(sql) db.commit() cur.close() except Exception as",
"WHERE works_article=%s ORDER BY works_type\" % id db.ping(reconnect=True) cur.execute(sql) result",
"id) db.ping(reconnect=True) cur.execute(sql) result = cur.fetchall() db.commit() cur.close() return result",
"article_id=%s\" % id elif type == 3: sql = \"UPDATE",
"= count_person_performance(2, email) style = count_person_performance(3, email) p_list = [s[0],",
"% title db.ping(reconnect=True) cur.execute(sql) result = cur.fetchone() db.commit() cur.close() return",
"config import * def fetch_all_article(): try: cur = db.cursor() sql",
"(%s,%s,'%s','%s');\" % ( type, article_id, work_due, staff) db.ping(reconnect=True) cur.execute(sql) db.commit()",
"db.cursor() sql = \"SELECT Name FROM user WHERE email='%s'\" %",
"count_performance(): all_staff = fetch_all_mkt_staff() performance_list = [] for s in",
"(email, id) db.ping(reconnect=True) cur.execute(sql) result = cur.fetchall() db.commit() cur.close() return",
"works_staff='%s' AND works_article=%s\" % (email, id) db.ping(reconnect=True) cur.execute(sql) result =",
"works_article=%s ORDER BY works_type\" % id db.ping(reconnect=True) cur.execute(sql) result =",
"text_status='Y' WHERE article_id=%s\" % id elif type == 3: sql",
"article SET style_status='Y' WHERE article_id=%s\" % id db.ping(reconnect=True) cur.execute(sql) db.commit()",
"article_status='N'\" db.ping(reconnect=True) cur.execute(sql) result = cur.fetchall() db.commit() cur.close() return result",
"article WHERE article_title='%s' AND article_status='N'\" % title db.ping(reconnect=True) cur.execute(sql) result",
"update_finish_status(type, id): try: type = int(type) cur = db.cursor() sql",
"except Exception as e: print(e) def get_task_list(email, articles): res =",
"= work return res def get_your_task_with_article(email, id): try: cur =",
"type = int(type) cur = db.cursor() sql = '' if",
"banner_status='Y' WHERE article_id=%s\" % id elif type == 2: sql",
"id): try: cur = db.cursor() sql = \"SELECT * FROM",
"Exception as e: print(e) def finish_task_in_db(task, article, type): update_task_status(task) update_finish_status(type,",
"return result except Exception as e: print(e) def get_works_list(articles): res",
"= [w[0], w[1], w[3], get_user_name(w[5])[0]] work.append(my_list) res[id] = work return",
"e: print(e) def add_article_to_db(title, due): try: cur = db.cursor() sql",
"articles): res = {} for a in articles: id =",
"works_staff='%s' AND works_type=%s AND is_finished='Y'\" % (email, type) db.ping(reconnect=True) cur.execute(sql)",
"cur.execute(sql) db.commit() cur.close() except Exception as e: print(e) def fetch_all_mkt_staff():",
"Exception as e: print(e) def update_task_status(id): try: cur = db.cursor()",
"fetch_all_mkt_staff(): try: cur = db.cursor() sql = \"SELECT Name,email FROM",
"def get_user_name(email): try: cur = db.cursor() sql = \"SELECT Name",
"db.ping(reconnect=True) cur.execute(sql) result = cur.fetchall() db.commit() cur.close() return result except",
"e: print(e) def count_performance(): all_staff = fetch_all_mkt_staff() performance_list = []",
"article_works WHERE works_staff='%s' AND works_article=%s\" % (email, id) db.ping(reconnect=True) cur.execute(sql)",
"WHERE works_num=%s\" % id db.ping(reconnect=True) cur.execute(sql) db.commit() cur.close() except Exception",
"= cur.fetchone() db.commit() cur.close() return result except Exception as e:",
"e: print(e) def fetch_all_mkt_staff(): try: cur = db.cursor() sql =",
"\"SELECT Name FROM user WHERE email='%s'\" % email db.ping(reconnect=True) cur.execute(sql)",
"try: cur = db.cursor() sql = \"SELECT article_id FROM article",
"id elif type == 3: sql = \"UPDATE article SET",
"return result except Exception as e: print(e) def get_task_list(email, articles):",
"banner = count_person_performance(1, email) text = count_person_performance(2, email) style =",
"performance_list = [] for s in all_staff: email = s[1]",
"all_staff: email = s[1] banner = count_person_performance(1, email) text =",
"email) p_list = [s[0], len(banner), len(text), len(style)] performance_list.append(p_list) return performance_list",
"fetch_all_mkt_staff() performance_list = [] for s in all_staff: email =",
"as e: print(e) def get_article_id(title): try: cur = db.cursor() sql",
"res = cur.fetchall() db.commit() cur.close() return res except Exception as",
"SET banner_status='Y' WHERE article_id=%s\" % id elif type == 2:",
"= get_your_task_with_article(email, id) res[id] = tasks return res def update_finish_status(type,",
"elif type == 3: sql = \"UPDATE article SET style_status='Y'",
"count_person_performance(type, email): try: cur = db.cursor() sql = \"SELECT *",
"count_person_performance(2, email) style = count_person_performance(3, email) p_list = [s[0], len(banner),",
"db.commit() cur.close() except Exception as e: print(e) def update_task_status(id): try:",
"return result except Exception as e: print(e) def get_article_id(title): try:",
"= \"UPDATE article_works SET is_finished='Y' WHERE works_num=%s\" % id db.ping(reconnect=True)",
"WHERE works_staff='%s' AND works_type=%s AND is_finished='Y'\" % (email, type) db.ping(reconnect=True)",
"def get_article_s_work(id): try: cur = db.cursor() sql = \"SELECT *",
"type == 2: sql = \"UPDATE article SET text_status='Y' WHERE",
"WHERE article_title='%s' AND article_status='N'\" % title db.ping(reconnect=True) cur.execute(sql) result =",
"[] for s in all_staff: email = s[1] banner =",
"[w[0], w[1], w[3], get_user_name(w[5])[0]] work.append(my_list) res[id] = work return res",
"print(e) def get_user_name(email): try: cur = db.cursor() sql = \"SELECT",
"sql = \"SELECT Name,email FROM user WHERE type=5\" db.ping(reconnect=True) cur.execute(sql)",
"len(articles)): id = articles[i][0] work = [] works = get_article_s_work(id)",
"cur.close() return result except Exception as e: print(e) def get_user_name(email):",
"try: type = int(type) cur = db.cursor() sql = ''",
"res = {} for a in articles: id = a[0]",
"cur = db.cursor() sql = '' if type == 1:",
"sql = \"UPDATE article SET text_status='Y' WHERE article_id=%s\" % id",
"get_user_name(email): try: cur = db.cursor() sql = \"SELECT Name FROM",
"cur = db.cursor() sql = \"INSERT INTO article_works(works_type,works_article,works_dueday,works_staff)VALUES (%s,%s,'%s','%s');\" %",
"e: print(e) def update_task_status(id): try: cur = db.cursor() sql =",
"article_works WHERE works_staff='%s' AND works_type=%s AND is_finished='Y'\" % (email, type)",
"except Exception as e: print(e) def get_user_name(email): try: cur =",
"works: my_list = [w[0], w[1], w[3], get_user_name(w[5])[0]] work.append(my_list) res[id] =",
"due) db.ping(reconnect=True) cur.execute(sql) db.commit() cur.close() except Exception as e: print(e)",
"try: cur = db.cursor() sql = \"INSERT INTO article_works(works_type,works_article,works_dueday,works_staff)VALUES (%s,%s,'%s','%s');\"",
"WHERE article_id=%s\" % id elif type == 3: sql =",
"= \"SELECT Name FROM user WHERE email='%s'\" % email db.ping(reconnect=True)",
"e: print(e) def get_article_s_work(id): try: cur = db.cursor() sql =",
"= fetch_all_mkt_staff() performance_list = [] for s in all_staff: email",
"cur.close() return result except Exception as e: print(e) def add_works_to_db(article_id,",
"print(e) def finish_task_in_db(task, article, type): update_task_status(task) update_finish_status(type, article) def count_person_performance(type,",
"as e: print(e) def get_task_list(email, articles): res = {} for",
"3: sql = \"UPDATE article SET style_status='Y' WHERE article_id=%s\" %",
"def get_article_id(title): try: cur = db.cursor() sql = \"SELECT article_id",
"AND is_finished='Y'\" % (email, type) db.ping(reconnect=True) cur.execute(sql) res = cur.fetchall()",
"article_status='N'\" % title db.ping(reconnect=True) cur.execute(sql) result = cur.fetchone() db.commit() cur.close()",
"\"SELECT * FROM article_works WHERE works_article=%s ORDER BY works_type\" %",
"return res def update_finish_status(type, id): try: type = int(type) cur",
"article WHERE article_status='N'\" db.ping(reconnect=True) cur.execute(sql) result = cur.fetchall() db.commit() cur.close()",
"cur = db.cursor() sql = \"SELECT article_id FROM article WHERE",
"s in all_staff: email = s[1] banner = count_person_performance(1, email)",
"SET is_finished='Y' WHERE works_num=%s\" % id db.ping(reconnect=True) cur.execute(sql) db.commit() cur.close()",
"FROM article_works WHERE works_staff='%s' AND works_type=%s AND is_finished='Y'\" % (email,",
"cur.close() return result except Exception as e: print(e) def get_works_list(articles):",
"article_id, work_due, staff) db.ping(reconnect=True) cur.execute(sql) db.commit() cur.close() except Exception as",
"cur.fetchall() db.commit() cur.close() return result except Exception as e: print(e)",
"staff, work_due): try: cur = db.cursor() sql = \"INSERT INTO",
"article_works WHERE works_article=%s ORDER BY works_type\" % id db.ping(reconnect=True) cur.execute(sql)",
"import * def fetch_all_article(): try: cur = db.cursor() sql =",
"[] works = get_article_s_work(id) for w in works: my_list =",
"res def update_finish_status(type, id): try: type = int(type) cur =",
"* FROM article_works WHERE works_article=%s ORDER BY works_type\" % id",
"all_staff = fetch_all_mkt_staff() performance_list = [] for s in all_staff:",
"= [] for s in all_staff: email = s[1] banner",
"% id elif type == 2: sql = \"UPDATE article",
"= s[1] banner = count_person_performance(1, email) text = count_person_performance(2, email)",
"sql = \"SELECT * FROM article_works WHERE works_article=%s ORDER BY",
"db.commit() cur.close() except Exception as e: print(e) def get_article_s_work(id): try:",
"== 3: sql = \"UPDATE article SET style_status='Y' WHERE article_id=%s\"",
"as e: print(e) def update_task_status(id): try: cur = db.cursor() sql",
"articles: id = a[0] tasks = get_your_task_with_article(email, id) res[id] =",
"print(e) def get_task_list(email, articles): res = {} for a in",
"work_due): try: cur = db.cursor() sql = \"INSERT INTO article_works(works_type,works_article,works_dueday,works_staff)VALUES",
"sql = \"SELECT Name FROM user WHERE email='%s'\" % email",
"work = [] works = get_article_s_work(id) for w in works:",
"WHERE type=5\" db.ping(reconnect=True) cur.execute(sql) result = cur.fetchall() db.commit() cur.close() return",
"def get_task_list(email, articles): res = {} for a in articles:",
"as e: print(e) def add_article_to_db(title, due): try: cur = db.cursor()",
"for i in range(0, len(articles)): id = articles[i][0] work =",
"Exception as e: print(e) def get_user_name(email): try: cur = db.cursor()",
"print(e) def fetch_all_mkt_staff(): try: cur = db.cursor() sql = \"SELECT",
"= db.cursor() sql = \"SELECT Name,email FROM user WHERE type=5\"",
"cur = db.cursor() sql = \"SELECT * FROM article WHERE",
"id) res[id] = tasks return res def update_finish_status(type, id): try:",
"\"SELECT * FROM article_works WHERE works_staff='%s' AND works_type=%s AND is_finished='Y'\"",
"result = cur.fetchall() db.commit() cur.close() return result except Exception as",
"def add_works_to_db(article_id, type, staff, work_due): try: cur = db.cursor() sql",
"= \"SELECT * FROM article WHERE article_status='N'\" db.ping(reconnect=True) cur.execute(sql) result",
"% email db.ping(reconnect=True) cur.execute(sql) result = cur.fetchone() db.commit() cur.close() return",
"email='%s'\" % email db.ping(reconnect=True) cur.execute(sql) result = cur.fetchone() db.commit() cur.close()",
"= [] works = get_article_s_work(id) for w in works: my_list",
"= db.cursor() sql = \"SELECT article_id FROM article WHERE article_title='%s'",
"FROM article WHERE article_status='N'\" db.ping(reconnect=True) cur.execute(sql) result = cur.fetchall() db.commit()",
"id db.ping(reconnect=True) cur.execute(sql) result = cur.fetchall() db.commit() cur.close() return result",
"tasks = get_your_task_with_article(email, id) res[id] = tasks return res def",
"def count_performance(): all_staff = fetch_all_mkt_staff() performance_list = [] for s",
"print(e) def add_article_to_db(title, due): try: cur = db.cursor() sql =",
"type, staff, work_due): try: cur = db.cursor() sql = \"INSERT",
"ORDER BY works_type\" % id db.ping(reconnect=True) cur.execute(sql) result = cur.fetchall()",
"article(article_title,article_dueday)VALUES ('%s','%s')\" % (title, due) db.ping(reconnect=True) cur.execute(sql) db.commit() cur.close() except",
"return res except Exception as e: print(e) def count_performance(): all_staff",
"= count_person_performance(3, email) p_list = [s[0], len(banner), len(text), len(style)] performance_list.append(p_list)",
"result except Exception as e: print(e) def add_article_to_db(title, due): try:",
"int(type) cur = db.cursor() sql = '' if type ==",
"= cur.fetchall() db.commit() cur.close() return result except Exception as e:",
"fetch_all_article(): try: cur = db.cursor() sql = \"SELECT * FROM",
"Name,email FROM user WHERE type=5\" db.ping(reconnect=True) cur.execute(sql) result = cur.fetchall()",
"type) db.ping(reconnect=True) cur.execute(sql) res = cur.fetchall() db.commit() cur.close() return res",
"sql = \"SELECT * FROM article_works WHERE works_staff='%s' AND works_type=%s",
"WHERE article_id=%s\" % id elif type == 2: sql =",
"BY works_type\" % id db.ping(reconnect=True) cur.execute(sql) result = cur.fetchall() db.commit()",
"* FROM article WHERE article_status='N'\" db.ping(reconnect=True) cur.execute(sql) result = cur.fetchall()",
"\"UPDATE article SET text_status='Y' WHERE article_id=%s\" % id elif type",
"db.ping(reconnect=True) cur.execute(sql) res = cur.fetchall() db.commit() cur.close() return res except",
"email = s[1] banner = count_person_performance(1, email) text = count_person_performance(2,",
"FROM user WHERE email='%s'\" % email db.ping(reconnect=True) cur.execute(sql) result =",
"FROM article_works WHERE works_staff='%s' AND works_article=%s\" % (email, id) db.ping(reconnect=True)",
"article SET banner_status='Y' WHERE article_id=%s\" % id elif type ==",
"for a in articles: id = a[0] tasks = get_your_task_with_article(email,",
"e: print(e) def get_task_list(email, articles): res = {} for a",
"title db.ping(reconnect=True) cur.execute(sql) result = cur.fetchone() db.commit() cur.close() return result",
"= a[0] tasks = get_your_task_with_article(email, id) res[id] = tasks return",
"(title, due) db.ping(reconnect=True) cur.execute(sql) db.commit() cur.close() except Exception as e:",
"w in works: my_list = [w[0], w[1], w[3], get_user_name(w[5])[0]] work.append(my_list)",
"e: print(e) def get_works_list(articles): res = {} for i in",
"res def get_your_task_with_article(email, id): try: cur = db.cursor() sql =",
"def fetch_all_article(): try: cur = db.cursor() sql = \"SELECT *",
"get_article_s_work(id) for w in works: my_list = [w[0], w[1], w[3],",
"FROM article_works WHERE works_article=%s ORDER BY works_type\" % id db.ping(reconnect=True)",
"= \"UPDATE article SET style_status='Y' WHERE article_id=%s\" % id db.ping(reconnect=True)",
"\"UPDATE article SET style_status='Y' WHERE article_id=%s\" % id db.ping(reconnect=True) cur.execute(sql)",
"type): update_task_status(task) update_finish_status(type, article) def count_person_performance(type, email): try: cur =",
"result except Exception as e: print(e) def get_task_list(email, articles): res",
"user WHERE type=5\" db.ping(reconnect=True) cur.execute(sql) result = cur.fetchall() db.commit() cur.close()",
"* def fetch_all_article(): try: cur = db.cursor() sql = \"SELECT",
"SET style_status='Y' WHERE article_id=%s\" % id db.ping(reconnect=True) cur.execute(sql) db.commit() cur.close()",
"cur.execute(sql) result = cur.fetchone() db.commit() cur.close() return result except Exception",
"WHERE article_status='N'\" db.ping(reconnect=True) cur.execute(sql) result = cur.fetchall() db.commit() cur.close() return",
"= \"SELECT * FROM article_works WHERE works_staff='%s' AND works_article=%s\" %",
"= \"UPDATE article SET banner_status='Y' WHERE article_id=%s\" % id elif",
"def update_task_status(id): try: cur = db.cursor() sql = \"UPDATE article_works",
"except Exception as e: print(e) def add_article_to_db(title, due): try: cur",
"article_title='%s' AND article_status='N'\" % title db.ping(reconnect=True) cur.execute(sql) result = cur.fetchone()",
"= \"SELECT article_id FROM article WHERE article_title='%s' AND article_status='N'\" %",
"% id elif type == 3: sql = \"UPDATE article",
"add_works_to_db(article_id, type, staff, work_due): try: cur = db.cursor() sql =",
"except Exception as e: print(e) def add_works_to_db(article_id, type, staff, work_due):",
"print(e) def get_article_id(title): try: cur = db.cursor() sql = \"SELECT",
"% id db.ping(reconnect=True) cur.execute(sql) result = cur.fetchall() db.commit() cur.close() return",
"cur.execute(sql) db.commit() cur.close() except Exception as e: print(e) def finish_task_in_db(task,",
"result except Exception as e: print(e) def get_article_id(title): try: cur",
"staff) db.ping(reconnect=True) cur.execute(sql) db.commit() cur.close() except Exception as e: print(e)",
"def get_works_list(articles): res = {} for i in range(0, len(articles)):",
"is_finished='Y' WHERE works_num=%s\" % id db.ping(reconnect=True) cur.execute(sql) db.commit() cur.close() except",
"except Exception as e: print(e) def get_article_id(title): try: cur =",
"db.commit() cur.close() return res except Exception as e: print(e) def",
"def finish_task_in_db(task, article, type): update_task_status(task) update_finish_status(type, article) def count_person_performance(type, email):",
"= '' if type == 1: sql = \"UPDATE article",
"= \"SELECT Name,email FROM user WHERE type=5\" db.ping(reconnect=True) cur.execute(sql) result",
"id): try: type = int(type) cur = db.cursor() sql =",
"i in range(0, len(articles)): id = articles[i][0] work = []",
"due): try: cur = db.cursor() sql = \"INSERT INTO article(article_title,article_dueday)VALUES",
"get_article_s_work(id): try: cur = db.cursor() sql = \"SELECT * FROM",
"Exception as e: print(e) def fetch_all_mkt_staff(): try: cur = db.cursor()",
"except Exception as e: print(e) def get_works_list(articles): res = {}",
"except Exception as e: print(e) def count_performance(): all_staff = fetch_all_mkt_staff()",
"= db.cursor() sql = \"UPDATE article_works SET is_finished='Y' WHERE works_num=%s\"",
"db.ping(reconnect=True) cur.execute(sql) result = cur.fetchone() db.commit() cur.close() return result except",
"a[0] tasks = get_your_task_with_article(email, id) res[id] = tasks return res",
"WHERE works_staff='%s' AND works_article=%s\" % (email, id) db.ping(reconnect=True) cur.execute(sql) result",
"text = count_person_performance(2, email) style = count_person_performance(3, email) p_list =",
"email) style = count_person_performance(3, email) p_list = [s[0], len(banner), len(text),",
"article_works(works_type,works_article,works_dueday,works_staff)VALUES (%s,%s,'%s','%s');\" % ( type, article_id, work_due, staff) db.ping(reconnect=True) cur.execute(sql)",
"cur = db.cursor() sql = \"INSERT INTO article(article_title,article_dueday)VALUES ('%s','%s')\" %",
"cur.close() return res except Exception as e: print(e) def count_performance():",
"db.cursor() sql = \"INSERT INTO article(article_title,article_dueday)VALUES ('%s','%s')\" % (title, due)",
"% ( type, article_id, work_due, staff) db.ping(reconnect=True) cur.execute(sql) db.commit() cur.close()",
"\"SELECT * FROM article WHERE article_status='N'\" db.ping(reconnect=True) cur.execute(sql) result =",
"email) text = count_person_performance(2, email) style = count_person_performance(3, email) p_list",
"sql = \"SELECT * FROM article WHERE article_status='N'\" db.ping(reconnect=True) cur.execute(sql)",
"= cur.fetchall() db.commit() cur.close() return res except Exception as e:",
"def get_your_task_with_article(email, id): try: cur = db.cursor() sql = \"SELECT",
"== 2: sql = \"UPDATE article SET text_status='Y' WHERE article_id=%s\"",
"sql = \"INSERT INTO article_works(works_type,works_article,works_dueday,works_staff)VALUES (%s,%s,'%s','%s');\" % ( type, article_id,",
"Exception as e: print(e) def count_performance(): all_staff = fetch_all_mkt_staff() performance_list",
"Exception as e: print(e) def get_article_id(title): try: cur = db.cursor()",
"get_your_task_with_article(email, id): try: cur = db.cursor() sql = \"SELECT *",
"\"SELECT * FROM article_works WHERE works_staff='%s' AND works_article=%s\" % (email,",
"* FROM article_works WHERE works_staff='%s' AND works_article=%s\" % (email, id)",
"as e: print(e) def fetch_all_mkt_staff(): try: cur = db.cursor() sql",
"AND article_status='N'\" % title db.ping(reconnect=True) cur.execute(sql) result = cur.fetchone() db.commit()",
"as e: print(e) def get_works_list(articles): res = {} for i",
"range(0, len(articles)): id = articles[i][0] work = [] works =",
"works = get_article_s_work(id) for w in works: my_list = [w[0],",
"for w in works: my_list = [w[0], w[1], w[3], get_user_name(w[5])[0]]",
"Exception as e: print(e) def get_works_list(articles): res = {} for",
"work_due, staff) db.ping(reconnect=True) cur.execute(sql) db.commit() cur.close() except Exception as e:",
"\"UPDATE article_works SET is_finished='Y' WHERE works_num=%s\" % id db.ping(reconnect=True) cur.execute(sql)",
"article_id FROM article WHERE article_title='%s' AND article_status='N'\" % title db.ping(reconnect=True)",
"update_task_status(task) update_finish_status(type, article) def count_person_performance(type, email): try: cur = db.cursor()",
"= \"INSERT INTO article(article_title,article_dueday)VALUES ('%s','%s')\" % (title, due) db.ping(reconnect=True) cur.execute(sql)",
"get_your_task_with_article(email, id) res[id] = tasks return res def update_finish_status(type, id):",
"count_person_performance(3, email) p_list = [s[0], len(banner), len(text), len(style)] performance_list.append(p_list) return",
"count_person_performance(1, email) text = count_person_performance(2, email) style = count_person_performance(3, email)",
"update_task_status(id): try: cur = db.cursor() sql = \"UPDATE article_works SET",
"= articles[i][0] work = [] works = get_article_s_work(id) for w",
"def update_finish_status(type, id): try: type = int(type) cur = db.cursor()",
"cur.execute(sql) db.commit() cur.close() except Exception as e: print(e) def get_article_s_work(id):",
"cur.close() except Exception as e: print(e) def fetch_all_mkt_staff(): try: cur",
"is_finished='Y'\" % (email, type) db.ping(reconnect=True) cur.execute(sql) res = cur.fetchall() db.commit()",
"sql = \"UPDATE article SET style_status='Y' WHERE article_id=%s\" % id",
"in range(0, len(articles)): id = articles[i][0] work = [] works",
"FROM user WHERE type=5\" db.ping(reconnect=True) cur.execute(sql) result = cur.fetchall() db.commit()",
"WHERE email='%s'\" % email db.ping(reconnect=True) cur.execute(sql) result = cur.fetchone() db.commit()",
"as e: print(e) def add_works_to_db(article_id, type, staff, work_due): try: cur",
"= \"INSERT INTO article_works(works_type,works_article,works_dueday,works_staff)VALUES (%s,%s,'%s','%s');\" % ( type, article_id, work_due,",
"= count_person_performance(1, email) text = count_person_performance(2, email) style = count_person_performance(3,",
"works_num=%s\" % id db.ping(reconnect=True) cur.execute(sql) db.commit() cur.close() except Exception as",
"get_article_id(title): try: cur = db.cursor() sql = \"SELECT article_id FROM",
"type=5\" db.ping(reconnect=True) cur.execute(sql) result = cur.fetchall() db.commit() cur.close() return result",
"try: cur = db.cursor() sql = \"UPDATE article_works SET is_finished='Y'",
"e: print(e) def add_works_to_db(article_id, type, staff, work_due): try: cur =",
"sql = \"UPDATE article SET banner_status='Y' WHERE article_id=%s\" % id",
"{} for i in range(0, len(articles)): id = articles[i][0] work",
"get_task_list(email, articles): res = {} for a in articles: id",
"article) def count_person_performance(type, email): try: cur = db.cursor() sql =",
"cur = db.cursor() sql = \"SELECT * FROM article_works WHERE",
"db.cursor() sql = \"UPDATE article_works SET is_finished='Y' WHERE works_num=%s\" %",
"= \"SELECT * FROM article_works WHERE works_article=%s ORDER BY works_type\"",
"db.ping(reconnect=True) cur.execute(sql) db.commit() cur.close() except Exception as e: print(e) def",
"return result except Exception as e: print(e) def add_article_to_db(title, due):",
"except Exception as e: print(e) def update_task_status(id): try: cur =",
"id = a[0] tasks = get_your_task_with_article(email, id) res[id] = tasks",
"% (email, id) db.ping(reconnect=True) cur.execute(sql) result = cur.fetchall() db.commit() cur.close()",
"\"INSERT INTO article_works(works_type,works_article,works_dueday,works_staff)VALUES (%s,%s,'%s','%s');\" % ( type, article_id, work_due, staff)",
"w[1], w[3], get_user_name(w[5])[0]] work.append(my_list) res[id] = work return res def",
"db.cursor() sql = \"SELECT article_id FROM article WHERE article_title='%s' AND",
"as e: print(e) def count_performance(): all_staff = fetch_all_mkt_staff() performance_list =",
"= db.cursor() sql = \"INSERT INTO article_works(works_type,works_article,works_dueday,works_staff)VALUES (%s,%s,'%s','%s');\" % (",
"('%s','%s')\" % (title, due) db.ping(reconnect=True) cur.execute(sql) db.commit() cur.close() except Exception",
"id elif type == 2: sql = \"UPDATE article SET",
"user WHERE email='%s'\" % email db.ping(reconnect=True) cur.execute(sql) result = cur.fetchone()",
"\"INSERT INTO article(article_title,article_dueday)VALUES ('%s','%s')\" % (title, due) db.ping(reconnect=True) cur.execute(sql) db.commit()",
"except Exception as e: print(e) def fetch_all_mkt_staff(): try: cur =",
"\"SELECT Name,email FROM user WHERE type=5\" db.ping(reconnect=True) cur.execute(sql) result =",
"def add_article_to_db(title, due): try: cur = db.cursor() sql = \"INSERT",
"INTO article_works(works_type,works_article,works_dueday,works_staff)VALUES (%s,%s,'%s','%s');\" % ( type, article_id, work_due, staff) db.ping(reconnect=True)",
"== 1: sql = \"UPDATE article SET banner_status='Y' WHERE article_id=%s\"",
"article SET text_status='Y' WHERE article_id=%s\" % id elif type ==",
"{} for a in articles: id = a[0] tasks =",
"Exception as e: print(e) def add_article_to_db(title, due): try: cur =",
"db.commit() cur.close() except Exception as e: print(e) def fetch_all_mkt_staff(): try:",
"= get_article_s_work(id) for w in works: my_list = [w[0], w[1],",
"w[3], get_user_name(w[5])[0]] work.append(my_list) res[id] = work return res def get_your_task_with_article(email,",
"= \"SELECT * FROM article_works WHERE works_staff='%s' AND works_type=%s AND",
"cur.close() except Exception as e: print(e) def get_article_s_work(id): try: cur",
"\"SELECT article_id FROM article WHERE article_title='%s' AND article_status='N'\" % title",
"cur = db.cursor() sql = \"UPDATE article_works SET is_finished='Y' WHERE",
"res[id] = work return res def get_your_task_with_article(email, id): try: cur",
"AND works_article=%s\" % (email, id) db.ping(reconnect=True) cur.execute(sql) result = cur.fetchall()",
"try: cur = db.cursor() sql = \"SELECT * FROM article_works",
"= int(type) cur = db.cursor() sql = '' if type",
"try: cur = db.cursor() sql = \"INSERT INTO article(article_title,article_dueday)VALUES ('%s','%s')\"",
"return res def get_your_task_with_article(email, id): try: cur = db.cursor() sql",
"* FROM article_works WHERE works_staff='%s' AND works_type=%s AND is_finished='Y'\" %",
"get_works_list(articles): res = {} for i in range(0, len(articles)): id",
"res[id] = tasks return res def update_finish_status(type, id): try: type",
"try: cur = db.cursor() sql = \"SELECT * FROM article",
"cur.close() except Exception as e: print(e) def finish_task_in_db(task, article, type):",
"cur.close() return result except Exception as e: print(e) def get_article_id(title):",
"style = count_person_performance(3, email) p_list = [s[0], len(banner), len(text), len(style)]",
"cur.close() return result except Exception as e: print(e) def add_article_to_db(title,",
"article_id=%s\" % id elif type == 2: sql = \"UPDATE",
"my_list = [w[0], w[1], w[3], get_user_name(w[5])[0]] work.append(my_list) res[id] = work",
"sql = \"SELECT article_id FROM article WHERE article_title='%s' AND article_status='N'\"",
"a in articles: id = a[0] tasks = get_your_task_with_article(email, id)",
"return result except Exception as e: print(e) def add_works_to_db(article_id, type,",
"cur = db.cursor() sql = \"SELECT Name FROM user WHERE",
"def fetch_all_mkt_staff(): try: cur = db.cursor() sql = \"SELECT Name,email"
] |
[
"purchase_events = raw_events \\ .select(raw_events.value.cast('string').alias('raw'), raw_events.timestamp.cast('string')) \\ .filter(is_purchase('raw')) extracted_purchase_events =",
"== 'purchase_sword': return True return False def main(): \"\"\"main \"\"\"",
".option(\"startingOffsets\", \"earliest\") \\ .option(\"endingOffsets\", \"latest\") \\ .load() purchase_events = raw_events",
"write them to hdfs \"\"\" import json from pyspark.sql import",
"python \"\"\"Extract events from kafka and write them to hdfs",
"\"events\") \\ .option(\"startingOffsets\", \"earliest\") \\ .option(\"endingOffsets\", \"latest\") \\ .load() purchase_events",
".option(\"kafka.bootstrap.servers\", \"kafka:29092\") \\ .option(\"subscribe\", \"events\") \\ .option(\"startingOffsets\", \"earliest\") \\ .option(\"endingOffsets\",",
".filter(is_purchase('raw')) extracted_purchase_events = purchase_events \\ .rdd \\ .map(lambda r: Row(timestamp=r.timestamp,",
"\\ .format(\"kafka\") \\ .option(\"kafka.bootstrap.servers\", \"kafka:29092\") \\ .option(\"subscribe\", \"events\") \\ .option(\"startingOffsets\",",
".rdd \\ .map(lambda r: Row(timestamp=r.timestamp, **json.loads(r.raw))) \\ .toDF() extracted_purchase_events.printSchema() extracted_purchase_events.show()",
"\"\"\"Extract events from kafka and write them to hdfs \"\"\"",
"**json.loads(r.raw))) \\ .toDF() extracted_purchase_events.printSchema() extracted_purchase_events.show() if __name__ == \"__main__\": main()",
"event = json.loads(event_as_json) if event['event_type'] == 'purchase_sword': return True return",
"= spark \\ .read \\ .format(\"kafka\") \\ .option(\"kafka.bootstrap.servers\", \"kafka:29092\") \\",
"\\ .option(\"endingOffsets\", \"latest\") \\ .load() purchase_events = raw_events \\ .select(raw_events.value.cast('string').alias('raw'),",
".appName(\"ExtractEventsJob\") \\ .getOrCreate() raw_events = spark \\ .read \\ .format(\"kafka\")",
"json.loads(event_as_json) if event['event_type'] == 'purchase_sword': return True return False def",
"False def main(): \"\"\"main \"\"\" spark = SparkSession \\ .builder",
".option(\"endingOffsets\", \"latest\") \\ .load() purchase_events = raw_events \\ .select(raw_events.value.cast('string').alias('raw'), raw_events.timestamp.cast('string'))",
"\\ .option(\"subscribe\", \"events\") \\ .option(\"startingOffsets\", \"earliest\") \\ .option(\"endingOffsets\", \"latest\") \\",
"from pyspark.sql import SparkSession, Row from pyspark.sql.functions import udf @udf('boolean')",
"def main(): \"\"\"main \"\"\" spark = SparkSession \\ .builder \\",
".format(\"kafka\") \\ .option(\"kafka.bootstrap.servers\", \"kafka:29092\") \\ .option(\"subscribe\", \"events\") \\ .option(\"startingOffsets\", \"earliest\")",
"True return False def main(): \"\"\"main \"\"\" spark = SparkSession",
"@udf('boolean') def is_purchase(event_as_json): event = json.loads(event_as_json) if event['event_type'] == 'purchase_sword':",
"them to hdfs \"\"\" import json from pyspark.sql import SparkSession,",
"\\ .select(raw_events.value.cast('string').alias('raw'), raw_events.timestamp.cast('string')) \\ .filter(is_purchase('raw')) extracted_purchase_events = purchase_events \\ .rdd",
"spark \\ .read \\ .format(\"kafka\") \\ .option(\"kafka.bootstrap.servers\", \"kafka:29092\") \\ .option(\"subscribe\",",
"raw_events.timestamp.cast('string')) \\ .filter(is_purchase('raw')) extracted_purchase_events = purchase_events \\ .rdd \\ .map(lambda",
"\"\"\" spark = SparkSession \\ .builder \\ .appName(\"ExtractEventsJob\") \\ .getOrCreate()",
"is_purchase(event_as_json): event = json.loads(event_as_json) if event['event_type'] == 'purchase_sword': return True",
"\"\"\"main \"\"\" spark = SparkSession \\ .builder \\ .appName(\"ExtractEventsJob\") \\",
"import SparkSession, Row from pyspark.sql.functions import udf @udf('boolean') def is_purchase(event_as_json):",
"r: Row(timestamp=r.timestamp, **json.loads(r.raw))) \\ .toDF() extracted_purchase_events.printSchema() extracted_purchase_events.show() if __name__ ==",
"raw_events = spark \\ .read \\ .format(\"kafka\") \\ .option(\"kafka.bootstrap.servers\", \"kafka:29092\")",
"json from pyspark.sql import SparkSession, Row from pyspark.sql.functions import udf",
"pyspark.sql.functions import udf @udf('boolean') def is_purchase(event_as_json): event = json.loads(event_as_json) if",
"\"kafka:29092\") \\ .option(\"subscribe\", \"events\") \\ .option(\"startingOffsets\", \"earliest\") \\ .option(\"endingOffsets\", \"latest\")",
"\"\"\" import json from pyspark.sql import SparkSession, Row from pyspark.sql.functions",
".select(raw_events.value.cast('string').alias('raw'), raw_events.timestamp.cast('string')) \\ .filter(is_purchase('raw')) extracted_purchase_events = purchase_events \\ .rdd \\",
"= SparkSession \\ .builder \\ .appName(\"ExtractEventsJob\") \\ .getOrCreate() raw_events =",
"#!/usr/bin/env python \"\"\"Extract events from kafka and write them to",
"\\ .appName(\"ExtractEventsJob\") \\ .getOrCreate() raw_events = spark \\ .read \\",
"\\ .rdd \\ .map(lambda r: Row(timestamp=r.timestamp, **json.loads(r.raw))) \\ .toDF() extracted_purchase_events.printSchema()",
"to hdfs \"\"\" import json from pyspark.sql import SparkSession, Row",
"\\ .map(lambda r: Row(timestamp=r.timestamp, **json.loads(r.raw))) \\ .toDF() extracted_purchase_events.printSchema() extracted_purchase_events.show() if",
"\\ .load() purchase_events = raw_events \\ .select(raw_events.value.cast('string').alias('raw'), raw_events.timestamp.cast('string')) \\ .filter(is_purchase('raw'))",
"raw_events \\ .select(raw_events.value.cast('string').alias('raw'), raw_events.timestamp.cast('string')) \\ .filter(is_purchase('raw')) extracted_purchase_events = purchase_events \\",
"import udf @udf('boolean') def is_purchase(event_as_json): event = json.loads(event_as_json) if event['event_type']",
".read \\ .format(\"kafka\") \\ .option(\"kafka.bootstrap.servers\", \"kafka:29092\") \\ .option(\"subscribe\", \"events\") \\",
"pyspark.sql import SparkSession, Row from pyspark.sql.functions import udf @udf('boolean') def",
"import json from pyspark.sql import SparkSession, Row from pyspark.sql.functions import",
"\\ .builder \\ .appName(\"ExtractEventsJob\") \\ .getOrCreate() raw_events = spark \\",
"= purchase_events \\ .rdd \\ .map(lambda r: Row(timestamp=r.timestamp, **json.loads(r.raw))) \\",
"\\ .filter(is_purchase('raw')) extracted_purchase_events = purchase_events \\ .rdd \\ .map(lambda r:",
"extracted_purchase_events = purchase_events \\ .rdd \\ .map(lambda r: Row(timestamp=r.timestamp, **json.loads(r.raw)))",
"\\ .getOrCreate() raw_events = spark \\ .read \\ .format(\"kafka\") \\",
"<reponame>dwang-ischool/w205<gh_stars>10-100 #!/usr/bin/env python \"\"\"Extract events from kafka and write them",
"and write them to hdfs \"\"\" import json from pyspark.sql",
"SparkSession, Row from pyspark.sql.functions import udf @udf('boolean') def is_purchase(event_as_json): event",
"def is_purchase(event_as_json): event = json.loads(event_as_json) if event['event_type'] == 'purchase_sword': return",
".getOrCreate() raw_events = spark \\ .read \\ .format(\"kafka\") \\ .option(\"kafka.bootstrap.servers\",",
"spark = SparkSession \\ .builder \\ .appName(\"ExtractEventsJob\") \\ .getOrCreate() raw_events",
"hdfs \"\"\" import json from pyspark.sql import SparkSession, Row from",
"\\ .option(\"startingOffsets\", \"earliest\") \\ .option(\"endingOffsets\", \"latest\") \\ .load() purchase_events =",
"\\ .read \\ .format(\"kafka\") \\ .option(\"kafka.bootstrap.servers\", \"kafka:29092\") \\ .option(\"subscribe\", \"events\")",
"if event['event_type'] == 'purchase_sword': return True return False def main():",
"udf @udf('boolean') def is_purchase(event_as_json): event = json.loads(event_as_json) if event['event_type'] ==",
"main(): \"\"\"main \"\"\" spark = SparkSession \\ .builder \\ .appName(\"ExtractEventsJob\")",
"'purchase_sword': return True return False def main(): \"\"\"main \"\"\" spark",
".load() purchase_events = raw_events \\ .select(raw_events.value.cast('string').alias('raw'), raw_events.timestamp.cast('string')) \\ .filter(is_purchase('raw')) extracted_purchase_events",
"from kafka and write them to hdfs \"\"\" import json",
"\"latest\") \\ .load() purchase_events = raw_events \\ .select(raw_events.value.cast('string').alias('raw'), raw_events.timestamp.cast('string')) \\",
"Row from pyspark.sql.functions import udf @udf('boolean') def is_purchase(event_as_json): event =",
"event['event_type'] == 'purchase_sword': return True return False def main(): \"\"\"main",
"= json.loads(event_as_json) if event['event_type'] == 'purchase_sword': return True return False",
".map(lambda r: Row(timestamp=r.timestamp, **json.loads(r.raw))) \\ .toDF() extracted_purchase_events.printSchema() extracted_purchase_events.show() if __name__",
"return False def main(): \"\"\"main \"\"\" spark = SparkSession \\",
"purchase_events \\ .rdd \\ .map(lambda r: Row(timestamp=r.timestamp, **json.loads(r.raw))) \\ .toDF()",
"\"earliest\") \\ .option(\"endingOffsets\", \"latest\") \\ .load() purchase_events = raw_events \\",
"return True return False def main(): \"\"\"main \"\"\" spark =",
".option(\"subscribe\", \"events\") \\ .option(\"startingOffsets\", \"earliest\") \\ .option(\"endingOffsets\", \"latest\") \\ .load()",
"= raw_events \\ .select(raw_events.value.cast('string').alias('raw'), raw_events.timestamp.cast('string')) \\ .filter(is_purchase('raw')) extracted_purchase_events = purchase_events",
"Row(timestamp=r.timestamp, **json.loads(r.raw))) \\ .toDF() extracted_purchase_events.printSchema() extracted_purchase_events.show() if __name__ == \"__main__\":",
"events from kafka and write them to hdfs \"\"\" import",
"SparkSession \\ .builder \\ .appName(\"ExtractEventsJob\") \\ .getOrCreate() raw_events = spark",
"from pyspark.sql.functions import udf @udf('boolean') def is_purchase(event_as_json): event = json.loads(event_as_json)",
".builder \\ .appName(\"ExtractEventsJob\") \\ .getOrCreate() raw_events = spark \\ .read",
"kafka and write them to hdfs \"\"\" import json from",
"\\ .option(\"kafka.bootstrap.servers\", \"kafka:29092\") \\ .option(\"subscribe\", \"events\") \\ .option(\"startingOffsets\", \"earliest\") \\"
] |
[
"100)).astype(np.float32) tolerance = 0.0001 compressed = compress(a, tolerance=tolerance) recovered =",
"100, 100)).astype(np.float32) tolerance = 0.0001 compressed = compress(a, tolerance=tolerance) recovered",
"= 0.0001 compressed = compress(a, tolerance=tolerance) recovered = decompress(compressed, a.shape,",
"import numpy as np from pysz import compress, decompress def",
"0.0001 compressed = compress(a, tolerance=tolerance) recovered = decompress(compressed, a.shape, a.dtype)",
"np.linspace(0, 100, num=1000000).reshape((100, 100, 100)).astype(np.float32) tolerance = 0.0001 compressed =",
"test_compress_decompress(): a = np.linspace(0, 100, num=1000000).reshape((100, 100, 100)).astype(np.float32) tolerance =",
"a = np.linspace(0, 100, num=1000000).reshape((100, 100, 100)).astype(np.float32) tolerance = 0.0001",
"compress, decompress def test_compress_decompress(): a = np.linspace(0, 100, num=1000000).reshape((100, 100,",
"np from pysz import compress, decompress def test_compress_decompress(): a =",
"pysz import compress, decompress def test_compress_decompress(): a = np.linspace(0, 100,",
"import compress, decompress def test_compress_decompress(): a = np.linspace(0, 100, num=1000000).reshape((100,",
"= decompress(compressed, a.shape, a.dtype) assert(a.shape == recovered.shape) assert(np.allclose(a, recovered, atol=tolerance))",
"as np from pysz import compress, decompress def test_compress_decompress(): a",
"tolerance=tolerance) recovered = decompress(compressed, a.shape, a.dtype) assert(a.shape == recovered.shape) assert(np.allclose(a,",
"def test_compress_decompress(): a = np.linspace(0, 100, num=1000000).reshape((100, 100, 100)).astype(np.float32) tolerance",
"decompress(compressed, a.shape, a.dtype) assert(a.shape == recovered.shape) assert(np.allclose(a, recovered, atol=tolerance)) test_compress_decompress()",
"decompress def test_compress_decompress(): a = np.linspace(0, 100, num=1000000).reshape((100, 100, 100)).astype(np.float32)",
"= compress(a, tolerance=tolerance) recovered = decompress(compressed, a.shape, a.dtype) assert(a.shape ==",
"recovered = decompress(compressed, a.shape, a.dtype) assert(a.shape == recovered.shape) assert(np.allclose(a, recovered,",
"compress(a, tolerance=tolerance) recovered = decompress(compressed, a.shape, a.dtype) assert(a.shape == recovered.shape)",
"numpy as np from pysz import compress, decompress def test_compress_decompress():",
"100, num=1000000).reshape((100, 100, 100)).astype(np.float32) tolerance = 0.0001 compressed = compress(a,",
"= np.linspace(0, 100, num=1000000).reshape((100, 100, 100)).astype(np.float32) tolerance = 0.0001 compressed",
"num=1000000).reshape((100, 100, 100)).astype(np.float32) tolerance = 0.0001 compressed = compress(a, tolerance=tolerance)",
"from pysz import compress, decompress def test_compress_decompress(): a = np.linspace(0,",
"tolerance = 0.0001 compressed = compress(a, tolerance=tolerance) recovered = decompress(compressed,",
"compressed = compress(a, tolerance=tolerance) recovered = decompress(compressed, a.shape, a.dtype) assert(a.shape"
] |
[
"__init__(self, deviation=1.5): self.deviation = deviation def model(self): return OutlierSolver.kSigma @staticmethod",
"class KSigmaParams(OutlierSolverParams): def __init__(self, deviation=1.5): self.deviation = deviation def model(self):",
"model(self): return OutlierSolver.kSigma @staticmethod def from_json(json_str): d = json.loads(json_str) return",
"def model(self): return OutlierSolver.kSigma @staticmethod def from_json(json_str): d = json.loads(json_str)",
"import json from sparkdq.outliers.params.OutlierSolverParams import OutlierSolverParams from sparkdq.outliers.OutlierSolver import OutlierSolver",
"OutlierSolver class KSigmaParams(OutlierSolverParams): def __init__(self, deviation=1.5): self.deviation = deviation def",
"self.deviation = deviation def model(self): return OutlierSolver.kSigma @staticmethod def from_json(json_str):",
"return OutlierSolver.kSigma @staticmethod def from_json(json_str): d = json.loads(json_str) return KSigmaParams(d[\"deviation\"])",
"sparkdq.outliers.params.OutlierSolverParams import OutlierSolverParams from sparkdq.outliers.OutlierSolver import OutlierSolver class KSigmaParams(OutlierSolverParams): def",
"OutlierSolverParams from sparkdq.outliers.OutlierSolver import OutlierSolver class KSigmaParams(OutlierSolverParams): def __init__(self, deviation=1.5):",
"def __init__(self, deviation=1.5): self.deviation = deviation def model(self): return OutlierSolver.kSigma",
"import OutlierSolver class KSigmaParams(OutlierSolverParams): def __init__(self, deviation=1.5): self.deviation = deviation",
"import OutlierSolverParams from sparkdq.outliers.OutlierSolver import OutlierSolver class KSigmaParams(OutlierSolverParams): def __init__(self,",
"deviation def model(self): return OutlierSolver.kSigma @staticmethod def from_json(json_str): d =",
"KSigmaParams(OutlierSolverParams): def __init__(self, deviation=1.5): self.deviation = deviation def model(self): return",
"deviation=1.5): self.deviation = deviation def model(self): return OutlierSolver.kSigma @staticmethod def",
"sparkdq.outliers.OutlierSolver import OutlierSolver class KSigmaParams(OutlierSolverParams): def __init__(self, deviation=1.5): self.deviation =",
"= deviation def model(self): return OutlierSolver.kSigma @staticmethod def from_json(json_str): d",
"from sparkdq.outliers.OutlierSolver import OutlierSolver class KSigmaParams(OutlierSolverParams): def __init__(self, deviation=1.5): self.deviation",
"json from sparkdq.outliers.params.OutlierSolverParams import OutlierSolverParams from sparkdq.outliers.OutlierSolver import OutlierSolver class",
"from sparkdq.outliers.params.OutlierSolverParams import OutlierSolverParams from sparkdq.outliers.OutlierSolver import OutlierSolver class KSigmaParams(OutlierSolverParams):"
] |
[
"'request' in payload.get('event'): key = 'request' else: key = 'sentry.interfaces.Http'",
"payload.get('event')[key]['env'].get('ENV', 'prod') == 'prod': environment = 'Production' else: environment =",
"== 'prod': environment = 'Production' else: environment = 'Development' if",
"Alert( resource=payload['culprit'], event=payload['event']['event_id'], environment=environment, severity=severity, service=[payload['project']], group='Application', value=payload['level'], text='{}\\n{}\\n{}'.format(payload['message'], payload['event'].get('title',",
"WebhookBase class SentryWebhook(WebhookBase): def incoming(self, query_string, payload): # For Sentry",
"'error': severity = 'critical' else: severity = 'ok' return Alert(",
"attributes={'modules': ['{}=={}'.format(k, v) for k, v in payload['event']['modules'].items()]}, origin='sentry.io', raw_data=str(payload)",
"SentryWebhook(WebhookBase): def incoming(self, query_string, payload): # For Sentry v9 #",
"else: key = 'sentry.interfaces.Http' if payload.get('event')[key]['env'].get('ENV', 'prod') == 'prod': environment",
"value=payload['level'], text='{}\\n{}\\n{}'.format(payload['message'], payload['event'].get('title', ''), payload['url']), tags=['{}={}'.format(k, v) for k, v",
"in payload.get('event'): key = 'request' else: key = 'sentry.interfaces.Http' if",
"# For Sentry v9 # Defaults to value before Sentry",
"value before Sentry v9 if 'request' in payload.get('event'): key =",
"key = 'request' else: key = 'sentry.interfaces.Http' if payload.get('event')[key]['env'].get('ENV', 'prod')",
"= 'request' else: key = 'sentry.interfaces.Http' if payload.get('event')[key]['env'].get('ENV', 'prod') ==",
"k, v in payload['event']['tags']], attributes={'modules': ['{}=={}'.format(k, v) for k, v",
"for k, v in payload['event']['tags']], attributes={'modules': ['{}=={}'.format(k, v) for k,",
"= 'Development' if payload['level'] == 'error': severity = 'critical' else:",
"before Sentry v9 if 'request' in payload.get('event'): key = 'request'",
"= 'sentry.interfaces.Http' if payload.get('event')[key]['env'].get('ENV', 'prod') == 'prod': environment = 'Production'",
"import Alert from alerta.webhooks import WebhookBase class SentryWebhook(WebhookBase): def incoming(self,",
"'request' else: key = 'sentry.interfaces.Http' if payload.get('event')[key]['env'].get('ENV', 'prod') == 'prod':",
"tags=['{}={}'.format(k, v) for k, v in payload['event']['tags']], attributes={'modules': ['{}=={}'.format(k, v)",
"if payload['level'] == 'error': severity = 'critical' else: severity =",
"= 'ok' return Alert( resource=payload['culprit'], event=payload['event']['event_id'], environment=environment, severity=severity, service=[payload['project']], group='Application',",
"'Development' if payload['level'] == 'error': severity = 'critical' else: severity",
"severity=severity, service=[payload['project']], group='Application', value=payload['level'], text='{}\\n{}\\n{}'.format(payload['message'], payload['event'].get('title', ''), payload['url']), tags=['{}={}'.format(k, v)",
"v9 if 'request' in payload.get('event'): key = 'request' else: key",
"if payload.get('event')[key]['env'].get('ENV', 'prod') == 'prod': environment = 'Production' else: environment",
"= 'critical' else: severity = 'ok' return Alert( resource=payload['culprit'], event=payload['event']['event_id'],",
"'sentry.interfaces.Http' if payload.get('event')[key]['env'].get('ENV', 'prod') == 'prod': environment = 'Production' else:",
"in payload['event']['tags']], attributes={'modules': ['{}=={}'.format(k, v) for k, v in payload['event']['modules'].items()]},",
"return Alert( resource=payload['culprit'], event=payload['event']['event_id'], environment=environment, severity=severity, service=[payload['project']], group='Application', value=payload['level'], text='{}\\n{}\\n{}'.format(payload['message'],",
"= 'Production' else: environment = 'Development' if payload['level'] == 'error':",
"payload['event']['tags']], attributes={'modules': ['{}=={}'.format(k, v) for k, v in payload['event']['modules'].items()]}, origin='sentry.io',",
"alerta.webhooks import WebhookBase class SentryWebhook(WebhookBase): def incoming(self, query_string, payload): #",
"group='Application', value=payload['level'], text='{}\\n{}\\n{}'.format(payload['message'], payload['event'].get('title', ''), payload['url']), tags=['{}={}'.format(k, v) for k,",
"else: severity = 'ok' return Alert( resource=payload['culprit'], event=payload['event']['event_id'], environment=environment, severity=severity,",
"Defaults to value before Sentry v9 if 'request' in payload.get('event'):",
"if 'request' in payload.get('event'): key = 'request' else: key =",
"['{}=={}'.format(k, v) for k, v in payload['event']['modules'].items()]}, origin='sentry.io', raw_data=str(payload) )",
"severity = 'critical' else: severity = 'ok' return Alert( resource=payload['culprit'],",
"payload['url']), tags=['{}={}'.format(k, v) for k, v in payload['event']['tags']], attributes={'modules': ['{}=={}'.format(k,",
"incoming(self, query_string, payload): # For Sentry v9 # Defaults to",
"event=payload['event']['event_id'], environment=environment, severity=severity, service=[payload['project']], group='Application', value=payload['level'], text='{}\\n{}\\n{}'.format(payload['message'], payload['event'].get('title', ''), payload['url']),",
"''), payload['url']), tags=['{}={}'.format(k, v) for k, v in payload['event']['tags']], attributes={'modules':",
"Alert from alerta.webhooks import WebhookBase class SentryWebhook(WebhookBase): def incoming(self, query_string,",
"import WebhookBase class SentryWebhook(WebhookBase): def incoming(self, query_string, payload): # For",
"environment = 'Development' if payload['level'] == 'error': severity = 'critical'",
"resource=payload['culprit'], event=payload['event']['event_id'], environment=environment, severity=severity, service=[payload['project']], group='Application', value=payload['level'], text='{}\\n{}\\n{}'.format(payload['message'], payload['event'].get('title', ''),",
"class SentryWebhook(WebhookBase): def incoming(self, query_string, payload): # For Sentry v9",
"payload): # For Sentry v9 # Defaults to value before",
"to value before Sentry v9 if 'request' in payload.get('event'): key",
"environment=environment, severity=severity, service=[payload['project']], group='Application', value=payload['level'], text='{}\\n{}\\n{}'.format(payload['message'], payload['event'].get('title', ''), payload['url']), tags=['{}={}'.format(k,",
"severity = 'ok' return Alert( resource=payload['culprit'], event=payload['event']['event_id'], environment=environment, severity=severity, service=[payload['project']],",
"from alerta.models.alert import Alert from alerta.webhooks import WebhookBase class SentryWebhook(WebhookBase):",
"def incoming(self, query_string, payload): # For Sentry v9 # Defaults",
"alerta.models.alert import Alert from alerta.webhooks import WebhookBase class SentryWebhook(WebhookBase): def",
"'prod': environment = 'Production' else: environment = 'Development' if payload['level']",
"query_string, payload): # For Sentry v9 # Defaults to value",
"service=[payload['project']], group='Application', value=payload['level'], text='{}\\n{}\\n{}'.format(payload['message'], payload['event'].get('title', ''), payload['url']), tags=['{}={}'.format(k, v) for",
"'prod') == 'prod': environment = 'Production' else: environment = 'Development'",
"v) for k, v in payload['event']['tags']], attributes={'modules': ['{}=={}'.format(k, v) for",
"environment = 'Production' else: environment = 'Development' if payload['level'] ==",
"else: environment = 'Development' if payload['level'] == 'error': severity =",
"'ok' return Alert( resource=payload['culprit'], event=payload['event']['event_id'], environment=environment, severity=severity, service=[payload['project']], group='Application', value=payload['level'],",
"payload['event'].get('title', ''), payload['url']), tags=['{}={}'.format(k, v) for k, v in payload['event']['tags']],",
"# Defaults to value before Sentry v9 if 'request' in",
"payload['level'] == 'error': severity = 'critical' else: severity = 'ok'",
"'Production' else: environment = 'Development' if payload['level'] == 'error': severity",
"Sentry v9 if 'request' in payload.get('event'): key = 'request' else:",
"== 'error': severity = 'critical' else: severity = 'ok' return",
"<reponame>dunzoit/alerta-contrib from alerta.models.alert import Alert from alerta.webhooks import WebhookBase class",
"For Sentry v9 # Defaults to value before Sentry v9",
"payload.get('event'): key = 'request' else: key = 'sentry.interfaces.Http' if payload.get('event')[key]['env'].get('ENV',",
"v in payload['event']['tags']], attributes={'modules': ['{}=={}'.format(k, v) for k, v in",
"text='{}\\n{}\\n{}'.format(payload['message'], payload['event'].get('title', ''), payload['url']), tags=['{}={}'.format(k, v) for k, v in",
"Sentry v9 # Defaults to value before Sentry v9 if",
"key = 'sentry.interfaces.Http' if payload.get('event')[key]['env'].get('ENV', 'prod') == 'prod': environment =",
"v9 # Defaults to value before Sentry v9 if 'request'",
"'critical' else: severity = 'ok' return Alert( resource=payload['culprit'], event=payload['event']['event_id'], environment=environment,",
"from alerta.webhooks import WebhookBase class SentryWebhook(WebhookBase): def incoming(self, query_string, payload):"
] |
[
"content = chr(0x83) + chr(0x65) + chr(0x83) + chr(0x58) +",
"+ chr(0x83) + chr(0x58) + chr(0x83) + chr(0x67); return headers,",
"= [(\"Content-type\", \"text/html;charset=shift-jis\")] # Shift-JIS bytes for katakana TE SU",
"\"text/html;charset=shift-jis\")] # Shift-JIS bytes for katakana TE SU TO ('test')",
"chr(0x83) + chr(0x58) + chr(0x83) + chr(0x67); return headers, content",
"TE SU TO ('test') content = chr(0x83) + chr(0x65) +",
"TO ('test') content = chr(0x83) + chr(0x65) + chr(0x83) +",
"headers = [(\"Content-type\", \"text/html;charset=shift-jis\")] # Shift-JIS bytes for katakana TE",
"bytes for katakana TE SU TO ('test') content = chr(0x83)",
"for katakana TE SU TO ('test') content = chr(0x83) +",
"main(request, response): headers = [(\"Content-type\", \"text/html;charset=shift-jis\")] # Shift-JIS bytes for",
"[(\"Content-type\", \"text/html;charset=shift-jis\")] # Shift-JIS bytes for katakana TE SU TO",
"('test') content = chr(0x83) + chr(0x65) + chr(0x83) + chr(0x58)",
"chr(0x83) + chr(0x65) + chr(0x83) + chr(0x58) + chr(0x83) +",
"response): headers = [(\"Content-type\", \"text/html;charset=shift-jis\")] # Shift-JIS bytes for katakana",
"+ chr(0x65) + chr(0x83) + chr(0x58) + chr(0x83) + chr(0x67);",
"katakana TE SU TO ('test') content = chr(0x83) + chr(0x65)",
"# Shift-JIS bytes for katakana TE SU TO ('test') content",
"SU TO ('test') content = chr(0x83) + chr(0x65) + chr(0x83)",
"chr(0x65) + chr(0x83) + chr(0x58) + chr(0x83) + chr(0x67); return",
"= chr(0x83) + chr(0x65) + chr(0x83) + chr(0x58) + chr(0x83)",
"Shift-JIS bytes for katakana TE SU TO ('test') content =",
"def main(request, response): headers = [(\"Content-type\", \"text/html;charset=shift-jis\")] # Shift-JIS bytes"
] |
[
"author_email=\"<EMAIL>\", license=\"Apache License 2.0\", entry_points={ 'console_scripts': [ 'gmail_oauth2 = gmailapi_backend.bin.gmail_oauth2:main',",
"as f: MATCH_EXPR = \"__version__[^'\\\"]+(['\\\"])([^'\\\"]+)\" VERSION = re.search(MATCH_EXPR, f.read()).group(2).strip() setup(",
":: MacOS :: MacOS X', 'Operating System :: Microsoft ::",
"2.0\", entry_points={ 'console_scripts': [ 'gmail_oauth2 = gmailapi_backend.bin.gmail_oauth2:main', ] }, install_requires=[",
":: Communications :: Email', 'Development Status :: 4 - Beta'",
"MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows',",
"'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX',",
":: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language",
"Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming",
":: Python :: 3.6', 'Programming Language :: Python :: 3.7',",
"3', 'Programming Language :: Python :: 3.5', 'Programming Language ::",
"'Framework :: Django', 'Topic :: Communications :: Email', 'Development Status",
"'Topic :: Communications :: Email', 'Development Status :: 4 -",
"'Operating System :: MacOS :: MacOS X', 'Operating System ::",
"Audience :: Developers', 'License :: OSI Approved :: Apache Software",
"gmailapi_backend.bin.gmail_oauth2:main', ] }, install_requires=[ 'google-api-python-client~=2.0', 'google-auth>=1.16.0,<3.0.0dev', ], url=\"https://github.com/dolfim/django-gmailapi-backend\", long_description_content_type='text/markdown', long_description=open('README.md').read(),",
"OSI Approved :: Apache Software License', 'Operating System :: MacOS",
"'gmail_oauth2 = gmailapi_backend.bin.gmail_oauth2:main', ] }, install_requires=[ 'google-api-python-client~=2.0', 'google-auth>=1.16.0,<3.0.0dev', ], url=\"https://github.com/dolfim/django-gmailapi-backend\",",
"import re from setuptools import setup, find_packages import sys if",
":: Apache Software License', 'Operating System :: MacOS :: MacOS",
"setup, find_packages import sys if sys.version_info < (3, 5): raise",
"f.read()).group(2).strip() setup( name='django-gmailapi-backend', version=VERSION, packages=find_packages(), author=\"<NAME>\", author_email=\"<EMAIL>\", license=\"Apache License 2.0\",",
"MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating System",
"3.5', 'Programming Language :: Python :: 3.6', 'Programming Language ::",
"Microsoft :: Windows', 'Operating System :: POSIX', 'Programming Language ::",
"Language :: Python :: 3', 'Programming Language :: Python ::",
"(3, 5): raise 'must use Python version 3.5 or higher'",
":: Python :: 3.5', 'Programming Language :: Python :: 3.6',",
":: Microsoft :: Windows', 'Operating System :: POSIX', 'Programming Language",
"License 2.0\", entry_points={ 'console_scripts': [ 'gmail_oauth2 = gmailapi_backend.bin.gmail_oauth2:main', ] },",
":: POSIX', 'Programming Language :: Python', 'Programming Language :: Python",
"3.5 or higher' with open('./gmailapi_backend/__init__.py', 'r') as f: MATCH_EXPR =",
"Communications :: Email', 'Development Status :: 4 - Beta' ],",
"'License :: OSI Approved :: Apache Software License', 'Operating System",
":: MacOS X', 'Operating System :: Microsoft :: Windows', 'Operating",
"import sys if sys.version_info < (3, 5): raise 'must use",
"Gmail API', classifiers=[ 'Intended Audience :: Developers', 'License :: OSI",
"VERSION = re.search(MATCH_EXPR, f.read()).group(2).strip() setup( name='django-gmailapi-backend', version=VERSION, packages=find_packages(), author=\"<NAME>\", author_email=\"<EMAIL>\",",
"packages=find_packages(), author=\"<NAME>\", author_email=\"<EMAIL>\", license=\"Apache License 2.0\", entry_points={ 'console_scripts': [ 'gmail_oauth2",
"], url=\"https://github.com/dolfim/django-gmailapi-backend\", long_description_content_type='text/markdown', long_description=open('README.md').read(), description='Email backend for Django which sends",
"'console_scripts': [ 'gmail_oauth2 = gmailapi_backend.bin.gmail_oauth2:main', ] }, install_requires=[ 'google-api-python-client~=2.0', 'google-auth>=1.16.0,<3.0.0dev',",
"[ 'gmail_oauth2 = gmailapi_backend.bin.gmail_oauth2:main', ] }, install_requires=[ 'google-api-python-client~=2.0', 'google-auth>=1.16.0,<3.0.0dev', ],",
"Python :: 3.8', 'Framework :: Django', 'Topic :: Communications ::",
"backend for Django which sends email via the Gmail API',",
"higher' with open('./gmailapi_backend/__init__.py', 'r') as f: MATCH_EXPR = \"__version__[^'\\\"]+(['\\\"])([^'\\\"]+)\" VERSION",
"Software License', 'Operating System :: MacOS :: MacOS X', 'Operating",
"with open('./gmailapi_backend/__init__.py', 'r') as f: MATCH_EXPR = \"__version__[^'\\\"]+(['\\\"])([^'\\\"]+)\" VERSION =",
"email via the Gmail API', classifiers=[ 'Intended Audience :: Developers',",
"Language :: Python :: 3.6', 'Programming Language :: Python ::",
":: Python :: 3.8', 'Framework :: Django', 'Topic :: Communications",
":: Email', 'Development Status :: 4 - Beta' ], )",
":: OSI Approved :: Apache Software License', 'Operating System ::",
"'must use Python version 3.5 or higher' with open('./gmailapi_backend/__init__.py', 'r')",
"version=VERSION, packages=find_packages(), author=\"<NAME>\", author_email=\"<EMAIL>\", license=\"Apache License 2.0\", entry_points={ 'console_scripts': [",
"find_packages import sys if sys.version_info < (3, 5): raise 'must",
"Django which sends email via the Gmail API', classifiers=[ 'Intended",
":: Python :: 3.7', 'Programming Language :: Python :: 3.8',",
"setup( name='django-gmailapi-backend', version=VERSION, packages=find_packages(), author=\"<NAME>\", author_email=\"<EMAIL>\", license=\"Apache License 2.0\", entry_points={",
"open('./gmailapi_backend/__init__.py', 'r') as f: MATCH_EXPR = \"__version__[^'\\\"]+(['\\\"])([^'\\\"]+)\" VERSION = re.search(MATCH_EXPR,",
"Language :: Python :: 3.5', 'Programming Language :: Python ::",
"raise 'must use Python version 3.5 or higher' with open('./gmailapi_backend/__init__.py',",
"License', 'Operating System :: MacOS :: MacOS X', 'Operating System",
"'Intended Audience :: Developers', 'License :: OSI Approved :: Apache",
"'Programming Language :: Python :: 3.6', 'Programming Language :: Python",
":: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language",
":: 3', 'Programming Language :: Python :: 3.5', 'Programming Language",
"Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Framework",
"sys.version_info < (3, 5): raise 'must use Python version 3.5",
"import setup, find_packages import sys if sys.version_info < (3, 5):",
"System :: POSIX', 'Programming Language :: Python', 'Programming Language ::",
"'Programming Language :: Python :: 3', 'Programming Language :: Python",
"= gmailapi_backend.bin.gmail_oauth2:main', ] }, install_requires=[ 'google-api-python-client~=2.0', 'google-auth>=1.16.0,<3.0.0dev', ], url=\"https://github.com/dolfim/django-gmailapi-backend\", long_description_content_type='text/markdown',",
"for Django which sends email via the Gmail API', classifiers=[",
"version 3.5 or higher' with open('./gmailapi_backend/__init__.py', 'r') as f: MATCH_EXPR",
"Windows', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming",
"Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming",
"description='Email backend for Django which sends email via the Gmail",
"Language :: Python :: 3.8', 'Framework :: Django', 'Topic ::",
"3.8', 'Framework :: Django', 'Topic :: Communications :: Email', 'Development",
"long_description_content_type='text/markdown', long_description=open('README.md').read(), description='Email backend for Django which sends email via",
"Python', 'Programming Language :: Python :: 3', 'Programming Language ::",
"Language :: Python', 'Programming Language :: Python :: 3', 'Programming",
"= re.search(MATCH_EXPR, f.read()).group(2).strip() setup( name='django-gmailapi-backend', version=VERSION, packages=find_packages(), author=\"<NAME>\", author_email=\"<EMAIL>\", license=\"Apache",
"classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved ::",
"3.6', 'Programming Language :: Python :: 3.7', 'Programming Language ::",
"5): raise 'must use Python version 3.5 or higher' with",
"'Programming Language :: Python', 'Programming Language :: Python :: 3',",
"or higher' with open('./gmailapi_backend/__init__.py', 'r') as f: MATCH_EXPR = \"__version__[^'\\\"]+(['\\\"])([^'\\\"]+)\"",
"'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language",
"Django', 'Topic :: Communications :: Email', 'Development Status :: 4",
":: 3.8', 'Framework :: Django', 'Topic :: Communications :: Email',",
"re.search(MATCH_EXPR, f.read()).group(2).strip() setup( name='django-gmailapi-backend', version=VERSION, packages=find_packages(), author=\"<NAME>\", author_email=\"<EMAIL>\", license=\"Apache License",
"url=\"https://github.com/dolfim/django-gmailapi-backend\", long_description_content_type='text/markdown', long_description=open('README.md').read(), description='Email backend for Django which sends email",
"license=\"Apache License 2.0\", entry_points={ 'console_scripts': [ 'gmail_oauth2 = gmailapi_backend.bin.gmail_oauth2:main', ]",
"via the Gmail API', classifiers=[ 'Intended Audience :: Developers', 'License",
"'Programming Language :: Python :: 3.8', 'Framework :: Django', 'Topic",
"setuptools import setup, find_packages import sys if sys.version_info < (3,",
"= \"__version__[^'\\\"]+(['\\\"])([^'\\\"]+)\" VERSION = re.search(MATCH_EXPR, f.read()).group(2).strip() setup( name='django-gmailapi-backend', version=VERSION, packages=find_packages(),",
"entry_points={ 'console_scripts': [ 'gmail_oauth2 = gmailapi_backend.bin.gmail_oauth2:main', ] }, install_requires=[ 'google-api-python-client~=2.0',",
":: Developers', 'License :: OSI Approved :: Apache Software License',",
"\"__version__[^'\\\"]+(['\\\"])([^'\\\"]+)\" VERSION = re.search(MATCH_EXPR, f.read()).group(2).strip() setup( name='django-gmailapi-backend', version=VERSION, packages=find_packages(), author=\"<NAME>\",",
":: Windows', 'Operating System :: POSIX', 'Programming Language :: Python',",
"which sends email via the Gmail API', classifiers=[ 'Intended Audience",
"3.7', 'Programming Language :: Python :: 3.8', 'Framework :: Django',",
"'Programming Language :: Python :: 3.7', 'Programming Language :: Python",
"re from setuptools import setup, find_packages import sys if sys.version_info",
"Language :: Python :: 3.7', 'Programming Language :: Python ::",
":: Python', 'Programming Language :: Python :: 3', 'Programming Language",
":: 3.7', 'Programming Language :: Python :: 3.8', 'Framework ::",
"'Programming Language :: Python :: 3.5', 'Programming Language :: Python",
"the Gmail API', classifiers=[ 'Intended Audience :: Developers', 'License ::",
"'google-auth>=1.16.0,<3.0.0dev', ], url=\"https://github.com/dolfim/django-gmailapi-backend\", long_description_content_type='text/markdown', long_description=open('README.md').read(), description='Email backend for Django which",
"}, install_requires=[ 'google-api-python-client~=2.0', 'google-auth>=1.16.0,<3.0.0dev', ], url=\"https://github.com/dolfim/django-gmailapi-backend\", long_description_content_type='text/markdown', long_description=open('README.md').read(), description='Email backend",
"'r') as f: MATCH_EXPR = \"__version__[^'\\\"]+(['\\\"])([^'\\\"]+)\" VERSION = re.search(MATCH_EXPR, f.read()).group(2).strip()",
"] }, install_requires=[ 'google-api-python-client~=2.0', 'google-auth>=1.16.0,<3.0.0dev', ], url=\"https://github.com/dolfim/django-gmailapi-backend\", long_description_content_type='text/markdown', long_description=open('README.md').read(), description='Email",
"f: MATCH_EXPR = \"__version__[^'\\\"]+(['\\\"])([^'\\\"]+)\" VERSION = re.search(MATCH_EXPR, f.read()).group(2).strip() setup( name='django-gmailapi-backend',",
"API', classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved",
"POSIX', 'Programming Language :: Python', 'Programming Language :: Python ::",
"install_requires=[ 'google-api-python-client~=2.0', 'google-auth>=1.16.0,<3.0.0dev', ], url=\"https://github.com/dolfim/django-gmailapi-backend\", long_description_content_type='text/markdown', long_description=open('README.md').read(), description='Email backend for",
"Developers', 'License :: OSI Approved :: Apache Software License', 'Operating",
"from setuptools import setup, find_packages import sys if sys.version_info <",
"use Python version 3.5 or higher' with open('./gmailapi_backend/__init__.py', 'r') as",
"MATCH_EXPR = \"__version__[^'\\\"]+(['\\\"])([^'\\\"]+)\" VERSION = re.search(MATCH_EXPR, f.read()).group(2).strip() setup( name='django-gmailapi-backend', version=VERSION,",
"Approved :: Apache Software License', 'Operating System :: MacOS ::",
"Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming",
"name='django-gmailapi-backend', version=VERSION, packages=find_packages(), author=\"<NAME>\", author_email=\"<EMAIL>\", license=\"Apache License 2.0\", entry_points={ 'console_scripts':",
"System :: MacOS :: MacOS X', 'Operating System :: Microsoft",
"'google-api-python-client~=2.0', 'google-auth>=1.16.0,<3.0.0dev', ], url=\"https://github.com/dolfim/django-gmailapi-backend\", long_description_content_type='text/markdown', long_description=open('README.md').read(), description='Email backend for Django",
"< (3, 5): raise 'must use Python version 3.5 or",
"author=\"<NAME>\", author_email=\"<EMAIL>\", license=\"Apache License 2.0\", entry_points={ 'console_scripts': [ 'gmail_oauth2 =",
"System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Programming",
"X', 'Operating System :: Microsoft :: Windows', 'Operating System ::",
"sends email via the Gmail API', classifiers=[ 'Intended Audience ::",
"Apache Software License', 'Operating System :: MacOS :: MacOS X',",
"sys if sys.version_info < (3, 5): raise 'must use Python",
":: Python :: 3', 'Programming Language :: Python :: 3.5',",
":: Django', 'Topic :: Communications :: Email', 'Development Status ::",
"if sys.version_info < (3, 5): raise 'must use Python version",
"long_description=open('README.md').read(), description='Email backend for Django which sends email via the",
"Python version 3.5 or higher' with open('./gmailapi_backend/__init__.py', 'r') as f:"
] |
[
"\"\"\"Make sure config exists.\"\"\" path = await config_util.async_ensure_config_exists(opp) await opp.async_stop(force=True)",
"print(\"Configuration file:\", config_path) return 0 async def async_run(opp): \"\"\"Make sure",
"configuration directory exists if not os.path.isdir(config_dir): print(\"Creating directory\", config_dir) os.makedirs(config_dir)",
"opp.config.config_dir = config_dir config_path = opp.loop.run_until_complete(async_run(opp)) print(\"Configuration file:\", config_path) return",
"configuration file exists.\"\"\" import argparse import os import openpeerpower.config as",
"a Open Peer Power config exists, creates one if necessary.\"",
"ensure a configuration file exists.\"\"\" import argparse import os import",
"\"\"\"Handle ensure config commandline script.\"\"\" parser = argparse.ArgumentParser( description=( \"Ensure",
"not os.path.isdir(config_dir): print(\"Creating directory\", config_dir) os.makedirs(config_dir) opp = OpenPeerPower() opp.config.config_dir",
"script.\"\"\" parser = argparse.ArgumentParser( description=( \"Ensure a Open Peer Power",
"Open Peer Power configuration\", ) parser.add_argument(\"--script\", choices=[\"ensure_config\"]) args = parser.parse_args()",
"= OpenPeerPower() opp.config.config_dir = config_dir config_path = opp.loop.run_until_complete(async_run(opp)) print(\"Configuration file:\",",
"Peer Power config exists, creates one if necessary.\" ) )",
"= os.path.join(os.getcwd(), args.config) # Test if configuration directory exists if",
"Peer Power configuration\", ) parser.add_argument(\"--script\", choices=[\"ensure_config\"]) args = parser.parse_args() config_dir",
"a configuration file exists.\"\"\" import argparse import os import openpeerpower.config",
"file:\", config_path) return 0 async def async_run(opp): \"\"\"Make sure config",
"help=\"Directory that contains the Open Peer Power configuration\", ) parser.add_argument(\"--script\",",
"parser = argparse.ArgumentParser( description=( \"Ensure a Open Peer Power config",
"async_run(opp): \"\"\"Make sure config exists.\"\"\" path = await config_util.async_ensure_config_exists(opp) await",
"directory exists if not os.path.isdir(config_dir): print(\"Creating directory\", config_dir) os.makedirs(config_dir) opp",
"ensure config commandline script.\"\"\" parser = argparse.ArgumentParser( description=( \"Ensure a",
"default=config_util.get_default_config_dir(), help=\"Directory that contains the Open Peer Power configuration\", )",
"# mypy: allow-untyped-calls, allow-untyped-defs def run(args): \"\"\"Handle ensure config commandline",
"sure config exists.\"\"\" path = await config_util.async_ensure_config_exists(opp) await opp.async_stop(force=True) return",
"import openpeerpower.config as config_util from openpeerpower.core import OpenPeerPower # mypy:",
"run(args): \"\"\"Handle ensure config commandline script.\"\"\" parser = argparse.ArgumentParser( description=(",
"Open Peer Power config exists, creates one if necessary.\" )",
"exists, creates one if necessary.\" ) ) parser.add_argument( \"-c\", \"--config\",",
"Test if configuration directory exists if not os.path.isdir(config_dir): print(\"Creating directory\",",
"OpenPeerPower() opp.config.config_dir = config_dir config_path = opp.loop.run_until_complete(async_run(opp)) print(\"Configuration file:\", config_path)",
"argparse import os import openpeerpower.config as config_util from openpeerpower.core import",
"if configuration directory exists if not os.path.isdir(config_dir): print(\"Creating directory\", config_dir)",
"return 0 async def async_run(opp): \"\"\"Make sure config exists.\"\"\" path",
"allow-untyped-calls, allow-untyped-defs def run(args): \"\"\"Handle ensure config commandline script.\"\"\" parser",
"from openpeerpower.core import OpenPeerPower # mypy: allow-untyped-calls, allow-untyped-defs def run(args):",
"OpenPeerPower # mypy: allow-untyped-calls, allow-untyped-defs def run(args): \"\"\"Handle ensure config",
"config_dir config_path = opp.loop.run_until_complete(async_run(opp)) print(\"Configuration file:\", config_path) return 0 async",
"contains the Open Peer Power configuration\", ) parser.add_argument(\"--script\", choices=[\"ensure_config\"]) args",
"openpeerpower.config as config_util from openpeerpower.core import OpenPeerPower # mypy: allow-untyped-calls,",
"os.makedirs(config_dir) opp = OpenPeerPower() opp.config.config_dir = config_dir config_path = opp.loop.run_until_complete(async_run(opp))",
"import os import openpeerpower.config as config_util from openpeerpower.core import OpenPeerPower",
"allow-untyped-defs def run(args): \"\"\"Handle ensure config commandline script.\"\"\" parser =",
"0 async def async_run(opp): \"\"\"Make sure config exists.\"\"\" path =",
"def async_run(opp): \"\"\"Make sure config exists.\"\"\" path = await config_util.async_ensure_config_exists(opp)",
"config_dir = os.path.join(os.getcwd(), args.config) # Test if configuration directory exists",
"that contains the Open Peer Power configuration\", ) parser.add_argument(\"--script\", choices=[\"ensure_config\"])",
"configuration\", ) parser.add_argument(\"--script\", choices=[\"ensure_config\"]) args = parser.parse_args() config_dir = os.path.join(os.getcwd(),",
"config commandline script.\"\"\" parser = argparse.ArgumentParser( description=( \"Ensure a Open",
"config_path) return 0 async def async_run(opp): \"\"\"Make sure config exists.\"\"\"",
"if necessary.\" ) ) parser.add_argument( \"-c\", \"--config\", metavar=\"path_to_config_dir\", default=config_util.get_default_config_dir(), help=\"Directory",
"args = parser.parse_args() config_dir = os.path.join(os.getcwd(), args.config) # Test if",
"parser.add_argument( \"-c\", \"--config\", metavar=\"path_to_config_dir\", default=config_util.get_default_config_dir(), help=\"Directory that contains the Open",
"Power configuration\", ) parser.add_argument(\"--script\", choices=[\"ensure_config\"]) args = parser.parse_args() config_dir =",
"necessary.\" ) ) parser.add_argument( \"-c\", \"--config\", metavar=\"path_to_config_dir\", default=config_util.get_default_config_dir(), help=\"Directory that",
"creates one if necessary.\" ) ) parser.add_argument( \"-c\", \"--config\", metavar=\"path_to_config_dir\",",
"= argparse.ArgumentParser( description=( \"Ensure a Open Peer Power config exists,",
"= parser.parse_args() config_dir = os.path.join(os.getcwd(), args.config) # Test if configuration",
"as config_util from openpeerpower.core import OpenPeerPower # mypy: allow-untyped-calls, allow-untyped-defs",
") parser.add_argument( \"-c\", \"--config\", metavar=\"path_to_config_dir\", default=config_util.get_default_config_dir(), help=\"Directory that contains the",
"opp.loop.run_until_complete(async_run(opp)) print(\"Configuration file:\", config_path) return 0 async def async_run(opp): \"\"\"Make",
"file exists.\"\"\" import argparse import os import openpeerpower.config as config_util",
"commandline script.\"\"\" parser = argparse.ArgumentParser( description=( \"Ensure a Open Peer",
"description=( \"Ensure a Open Peer Power config exists, creates one",
"os import openpeerpower.config as config_util from openpeerpower.core import OpenPeerPower #",
"config exists, creates one if necessary.\" ) ) parser.add_argument( \"-c\",",
"parser.parse_args() config_dir = os.path.join(os.getcwd(), args.config) # Test if configuration directory",
"choices=[\"ensure_config\"]) args = parser.parse_args() config_dir = os.path.join(os.getcwd(), args.config) # Test",
"Power config exists, creates one if necessary.\" ) ) parser.add_argument(",
"metavar=\"path_to_config_dir\", default=config_util.get_default_config_dir(), help=\"Directory that contains the Open Peer Power configuration\",",
") ) parser.add_argument( \"-c\", \"--config\", metavar=\"path_to_config_dir\", default=config_util.get_default_config_dir(), help=\"Directory that contains",
"to ensure a configuration file exists.\"\"\" import argparse import os",
"opp = OpenPeerPower() opp.config.config_dir = config_dir config_path = opp.loop.run_until_complete(async_run(opp)) print(\"Configuration",
"os.path.join(os.getcwd(), args.config) # Test if configuration directory exists if not",
"# Test if configuration directory exists if not os.path.isdir(config_dir): print(\"Creating",
"os.path.isdir(config_dir): print(\"Creating directory\", config_dir) os.makedirs(config_dir) opp = OpenPeerPower() opp.config.config_dir =",
"\"--config\", metavar=\"path_to_config_dir\", default=config_util.get_default_config_dir(), help=\"Directory that contains the Open Peer Power",
"= config_dir config_path = opp.loop.run_until_complete(async_run(opp)) print(\"Configuration file:\", config_path) return 0",
"def run(args): \"\"\"Handle ensure config commandline script.\"\"\" parser = argparse.ArgumentParser(",
"config_util from openpeerpower.core import OpenPeerPower # mypy: allow-untyped-calls, allow-untyped-defs def",
") parser.add_argument(\"--script\", choices=[\"ensure_config\"]) args = parser.parse_args() config_dir = os.path.join(os.getcwd(), args.config)",
"config_dir) os.makedirs(config_dir) opp = OpenPeerPower() opp.config.config_dir = config_dir config_path =",
"import argparse import os import openpeerpower.config as config_util from openpeerpower.core",
"= opp.loop.run_until_complete(async_run(opp)) print(\"Configuration file:\", config_path) return 0 async def async_run(opp):",
"async def async_run(opp): \"\"\"Make sure config exists.\"\"\" path = await",
"parser.add_argument(\"--script\", choices=[\"ensure_config\"]) args = parser.parse_args() config_dir = os.path.join(os.getcwd(), args.config) #",
"openpeerpower.core import OpenPeerPower # mypy: allow-untyped-calls, allow-untyped-defs def run(args): \"\"\"Handle",
"exists if not os.path.isdir(config_dir): print(\"Creating directory\", config_dir) os.makedirs(config_dir) opp =",
"import OpenPeerPower # mypy: allow-untyped-calls, allow-untyped-defs def run(args): \"\"\"Handle ensure",
"\"Ensure a Open Peer Power config exists, creates one if",
"exists.\"\"\" import argparse import os import openpeerpower.config as config_util from",
"argparse.ArgumentParser( description=( \"Ensure a Open Peer Power config exists, creates",
"one if necessary.\" ) ) parser.add_argument( \"-c\", \"--config\", metavar=\"path_to_config_dir\", default=config_util.get_default_config_dir(),",
"config exists.\"\"\" path = await config_util.async_ensure_config_exists(opp) await opp.async_stop(force=True) return path",
"\"\"\"Script to ensure a configuration file exists.\"\"\" import argparse import",
"args.config) # Test if configuration directory exists if not os.path.isdir(config_dir):",
"mypy: allow-untyped-calls, allow-untyped-defs def run(args): \"\"\"Handle ensure config commandline script.\"\"\"",
"directory\", config_dir) os.makedirs(config_dir) opp = OpenPeerPower() opp.config.config_dir = config_dir config_path",
"if not os.path.isdir(config_dir): print(\"Creating directory\", config_dir) os.makedirs(config_dir) opp = OpenPeerPower()",
"\"-c\", \"--config\", metavar=\"path_to_config_dir\", default=config_util.get_default_config_dir(), help=\"Directory that contains the Open Peer",
"config_path = opp.loop.run_until_complete(async_run(opp)) print(\"Configuration file:\", config_path) return 0 async def",
"the Open Peer Power configuration\", ) parser.add_argument(\"--script\", choices=[\"ensure_config\"]) args =",
"print(\"Creating directory\", config_dir) os.makedirs(config_dir) opp = OpenPeerPower() opp.config.config_dir = config_dir"
] |
[
"# implementation S = list(input()) if len(set(S)) == 2: if",
"implementation S = list(input()) if len(set(S)) == 2: if S.count(S[0])",
"if len(set(S)) == 2: if S.count(S[0]) == 2: print(\"Yes\") quit()",
"= list(input()) if len(set(S)) == 2: if S.count(S[0]) == 2:",
"S = list(input()) if len(set(S)) == 2: if S.count(S[0]) ==",
"# Vicfred # https://atcoder.jp/contests/abc132/tasks/abc132_a # implementation S = list(input()) if",
"# https://atcoder.jp/contests/abc132/tasks/abc132_a # implementation S = list(input()) if len(set(S)) ==",
"list(input()) if len(set(S)) == 2: if S.count(S[0]) == 2: print(\"Yes\")",
"https://atcoder.jp/contests/abc132/tasks/abc132_a # implementation S = list(input()) if len(set(S)) == 2:",
"len(set(S)) == 2: if S.count(S[0]) == 2: print(\"Yes\") quit() print(\"No\")",
"Vicfred # https://atcoder.jp/contests/abc132/tasks/abc132_a # implementation S = list(input()) if len(set(S))"
] |
[
"regression labels = ax.get_ylabel() + ax.get_xlabel() assert ('target' in labels)",
"assert len(axes) == 4 # known result assert axes[0].get_xlabel() ==",
"(detect_types(data).T.idxmax() == ['low_card_int', 'categorical']).all() assert guess_ordinal(data[0]) # smoke test plot(data,",
"= plt.gcf()._suptitle.get_text() assert feature_type.capitalize() in text ax = plt.gca() #",
"are bound between 50 and 100 \"target\": np.random.randint(low=50, high=100, size=200)",
"n_samples=n_samples, n_features=continuous_features, n_informative=min(continuous_features, 2)) X_cat, y_cat = make_regression( n_samples=n_samples, n_features=categorical_features,",
"guess_ordinal(data[0]) # smoke test plot(data, target_col=1) def test_large_ordinal(): # check",
"between 50 and 100 \"target\": np.random.randint(low=50, high=100, size=200) } )",
"pd.DataFrame(X) y[::50] = np.NaN X['target_col'] = y with pytest.warns(UserWarning, match=\"Missing",
"axes = figures[0].get_axes() assert len(axes) == 10 # known result",
"diagonal has twin axes assert len(figures[0].get_axes()) == 5 * 5",
"def test_plot_regression_continuous_with_target_outliers(): df = pd.DataFrame( data={ \"feature\": np.random.randint(low=1, high=100, size=200),",
"from dabl.preprocessing import clean, detect_types, guess_ordinal from dabl.plot.supervised import (",
"\" \"been removed for regression\"): plot_regression_continuous(X, 'target_col') with pytest.warns(UserWarning, match=\"Missing",
"= y with pytest.raises(ValueError, match=\"need continuous\"): plot_regression_categorical(X, 'target') with pytest.raises(ValueError,",
"pytest.raises(ValueError, match=\"Less than two classes\"): plot_classification_categorical(X, 'target') with pytest.raises(ValueError, match=\"Less",
"= X[0] with pytest.raises(ValueError, match=\"need categorical\"): plot_classification_categorical(X, 'target') with pytest.raises(ValueError,",
"= pd.Series(y) y[y == 0] = 'a' y[y == 1]",
"def test_plots_smoke(continuous_features, categorical_features, task): # simple smoke test # should",
"figures = plot_classification_continuous(df.iloc[:, -7:], target_col='target', plot_pairwise=False) assert len(figures) == 1",
"X, y = load_diabetes(return_X_y=True) X = pd.DataFrame(X) y[::50] = np.NaN",
"column_types[-1] == 'categorical' else: assert column_types[-1] == 'continuous' plot(X_clean, target_col='target')",
"target.\" ): plot_regression_continuous(df, 'target') def test_plot_regression_categorical_missing_value(): df = pd.DataFrame({'y': np.random.normal(size=300)})",
"# top 10 axes assert len(figures[0].get_axes()) == 10 # six",
"= detect_types(X_clean) column_types = types.T.idxmax() assert np.all(column_types[:continuous_features] == 'continuous') assert",
"@pytest.mark.parametrize(\"add, feature_type, target_type\", itertools.product([0, .1], ['continuous', 'categorical'], ['continuous', 'categorical'])) def",
"plot_classification_continuous(X, 'target') def test_plot_target_low_card_int(): data = load_digits() df = data_df_from_bunch(data)",
"assert axes[0].get_xlabel() == \"PCA 1\" assert axes[0].get_ylabel() == 'PCA 5'",
"axes = figures[3].get_axes() assert len(axes) == 4 # known result",
"don't bring us down (bincount memory error) # here some",
"df = df.append({\"feature\": 50, \"target\": 0}, ignore_index=True) with pytest.warns( UserWarning,",
"X = pd.DataFrame(X) X[3] = y plot(X, target_col=3) def test_negative_ordinal():",
"0 with pytest.raises(ValueError, match=\"Less than two classes\"): plot_classification_categorical(X, 'target') with",
"= pd.DataFrame(X) data['target'] = y.astype(np.float) types = detect_types(data) assert types.categorical['target']",
"we do classification with a float target X, y =",
"axes[0].get_ylabel() == 'S6_N' # PCA axes = figures[2].get_axes() assert len(axes)",
"np.NaN res = plot(df, target_col='y') assert len(res[1][0, 0].get_yticklabels()) == 3",
"is 'target' iif regression labels = ax.get_ylabel() + ax.get_xlabel() assert",
"assert res[0, 0].get_ylabel() == 'the_target_that_h...' assert res[0, 0].get_xlabel() == 'a_really_long_nam...'",
"target_col='target', type_hints={'target': 'categorical'}) plt.close(\"all\") @pytest.mark.filterwarnings('ignore:Discarding near-constant') def test_plot_classification_n_classes(): X, y",
"test_plot_regression_categorical_missing_value(): df = pd.DataFrame({'y': np.random.normal(size=300)}) df.loc[100:200, 'y'] += 1 df.loc[200:300,",
"cont_columns = [\"asdf_%d_cont\" % i for i in range(continuous_features)] df_cont",
"y but a column name @pytest.mark.filterwarnings('ignore:the matrix subclass') @pytest.mark.parametrize(\"continuous_features, categorical_features,",
"smoke test # should be parametrized n_samples = 100 X_cont,",
"= 0 with pytest.raises(ValueError, match=\"Less than two classes\"): plot_classification_categorical(X, 'target')",
"figures[0].get_axes() assert len(axes) == 10 # known result assert axes[0].get_xlabel()",
"2] = 'c' data['target'] = y plot(data, target_col='target') def test_na_vals_reg_plot_raise_warning():",
"'a_really_long_nam...' set_config(truncate_labels=False) res = plot_regression_continuous(df, target_col=b) assert res[0, 0].get_ylabel() ==",
"== \"classification\": assert column_types[-1] == 'categorical' else: assert column_types[-1] ==",
"six is the minimum number of features for histograms #",
"univariate_plot='kde') def test_plot_int_column_name(): X, y = make_blobs() X = pd.DataFrame(X)",
"+ ax.get_xlabel() assert ('target' in labels) == (target_type == 'continuous')",
"= make_blobs() X = pd.DataFrame(X) X[3] = y plot(X, target_col=3)",
"res = plot(df, target_col='y') assert len(res[1][0, 0].get_yticklabels()) == 3 assert",
"# known result assert axes[0].get_xlabel() == \"LDA 0\" assert axes[0].get_ylabel()",
"import itertools from sklearn.datasets import (make_regression, make_blobs, load_digits, fetch_openml, load_diabetes)",
"df.append({\"feature\": 50, \"target\": 0}, ignore_index=True) with pytest.warns( UserWarning, match=\"Dropped 1",
"pd.DataFrame(np.random.randint(4, size=100)) + add X['target'] = np.random.uniform(size=100) plot(X, type_hints={0: feature_type,",
"'S6_N' # PCA axes = figures[2].get_axes() assert len(axes) == 4",
"target) figures = plot_classification_continuous(df.iloc[:, -7:], target_col='target', plot_pairwise=False) assert len(figures) ==",
"is target) figures = plot_classification_continuous(df.iloc[:, -7:], target_col='target', plot_pairwise=False) assert len(figures)",
"y = pd.Series(y) y[y == 0] = 'a' y[y ==",
"negative values is plotted correctly data = pd.DataFrame([np.random.randint(0, 10, size=1000)",
"parametrized n_samples = 100 X_cont, y_cont = make_regression( n_samples=n_samples, n_features=continuous_features,",
"should be parametrized n_samples = 100 X_cont, y_cont = make_regression(",
"df = data_df_from_bunch(data) # only univariate plots figures = plot_classification_continuous(df,",
"'target') with pytest.raises(ValueError, match=\"Less than two classes\"): plot_classification_continuous(X, 'target') def",
"pd.DataFrame({a: np.random.uniform(0, 1, 1000)}) df[b] = df[a] + np.random.uniform(0, 0.1,",
"i in range(continuous_features)] df_cont = pd.DataFrame(X_cont, columns=cont_columns) if categorical_features >",
"plot, plot_classification_categorical, plot_classification_continuous, plot_regression_categorical, plot_regression_continuous) from dabl.utils import data_df_from_bunch from",
"y = load_diabetes(return_X_y=True) X = pd.DataFrame(X) y[::50] = np.NaN X['target_col']",
"df_cat.astype(\"category\") X_df = pd.concat([df_cont, df_cat], axis=1) else: X_df = df_cont",
"def test_plot_classification_n_classes(): X, y = make_blobs() X = pd.DataFrame(X) X['target']",
"# FIXME: check that target is not y but a",
"axes[0].get_ylabel() == 'PCA 5' # LDA axes = figures[3].get_axes() assert",
"= data_df_from_bunch(data) # only univariate plots figures = plot_classification_continuous(df, target_col='target',",
"def test_plot_regression_numpy(): X, y = make_regression() plot(X, y) def test_plot_lda_binary():",
"categorical\"): plot_classification_continuous(X, 'target') def test_plot_target_low_card_int(): data = load_digits() df =",
"labels) == (target_type == 'continuous') plt.close(\"all\") def test_float_classification_target(): # check",
"= np.NaN res = plot(df, target_col='y') assert len(res[1][0, 0].get_yticklabels()) ==",
"== 'S6_N' # PCA axes = figures[2].get_axes() assert len(axes) ==",
"figure text = plt.gcf()._suptitle.get_text() assert feature_type.capitalize() in text ax =",
"'target') X['target'] = X[0] with pytest.raises(ValueError, match=\"need categorical\"): plot_classification_categorical(X, 'target')",
"\" \"been removed for regression\"): plot(X, 'target_col') with pytest.warns(UserWarning, match=\"Missing",
"n_features=continuous_features, n_informative=min(continuous_features, 2)) X_cat, y_cat = make_regression( n_samples=n_samples, n_features=categorical_features, n_informative=min(categorical_features,",
"'_by_just_being_very_long') b = ('the_target_that_has_an_equally_long_name_which_would_' 'mess_up_everything_as_well_but_in_different_places') df = pd.DataFrame({a: np.random.uniform(0, 1,",
"= plot_classification_continuous(df.iloc[:, -6:], target_col='target', plot_pairwise=False) assert len(figures) == 1 #",
"= make_blobs(n_samples=30) data = pd.DataFrame(X) y = pd.Series(y) y[y ==",
"'target') def test_plot_wrong_target_type(): X, y = make_blobs() X = pd.DataFrame(X)",
"y = make_blobs() X = pd.DataFrame(X) plot(X, y) def test_plot_regression_numpy():",
"data_df_from_bunch from dabl import set_config # FIXME: check that target",
"dabl.preprocessing import clean, detect_types, guess_ordinal from dabl.plot.supervised import ( plot,",
".1], ['continuous', 'categorical'], ['continuous', 'categorical'])) def test_type_hints(add, feature_type, target_type): X",
"plot(X, y, univariate_plot='kde') def test_plot_int_column_name(): X, y = make_blobs() X",
"make_blobs, load_digits, fetch_openml, load_diabetes) from sklearn.preprocessing import KBinsDiscretizer from dabl.preprocessing",
"ensure first column is low_card_int assert (detect_types(data).T.idxmax() == ['low_card_int', 'categorical']).all()",
"'target') with pytest.raises(ValueError, match=\"need continuous\"): plot_regression_continuous(X, 'target') X['target'] = X[0]",
"plt import itertools from sklearn.datasets import (make_regression, make_blobs, load_digits, fetch_openml,",
"iif regression labels = ax.get_ylabel() + ax.get_xlabel() assert ('target' in",
"than two classes\"): plot_classification_categorical(X, 'target') with pytest.raises(ValueError, match=\"Less than two",
"= pd.DataFrame(np.random.randint(4, size=100)) + add X['target'] = np.random.uniform(size=100) plot(X, type_hints={0:",
"assert len(figures[0].get_axes()) == 10 # six is the minimum number",
"plot_pairwise=False) assert len(figures) == 1 # top 10 axes assert",
"assert len(figures) == 1 assert len(figures[0].get_axes()) == 6 # for",
"== 4 # known result assert axes[0].get_xlabel() == \"SOD1_N\" assert",
"\"been removed for regression\"): plot_regression_continuous(X, 'target_col') with pytest.warns(UserWarning, match=\"Missing values",
"plot_regression_categorical(X, 'target') with pytest.raises(ValueError, match=\"need continuous\"): plot_regression_continuous(X, 'target') X['target'] =",
"with target value 0 df = df.append({\"feature\": 50, \"target\": 0},",
"== 5 * 5 + 5 # also do pairwise",
"plot_classification_categorical(X, 'target') with pytest.raises(ValueError, match=\"Less than two classes\"): plot_classification_continuous(X, 'target')",
"= y with pytest.warns(UserWarning, match=\"Missing values in target_col have \"",
"plot(X, 'target_col') with pytest.warns(UserWarning, match=\"Missing values in target_col have \"",
"np.random.uniform(size=100) plot(X, type_hints={0: feature_type, 'target': target_type}, target_col='target') # get title",
"def test_plot_int_column_name(): X, y = make_blobs() X = pd.DataFrame(X) X[3]",
"classes\"): plot_classification_categorical(X, 'target') with pytest.raises(ValueError, match=\"Less than two classes\"): plot_classification_continuous(X,",
"# only univariate plots figures = plot_classification_continuous(df, target_col='target', plot_pairwise=False) assert",
"for i in range(categorical_features)] df_cat = pd.DataFrame(X_cat, columns=cat_columns).astype('int') df_cat =",
"X = pd.DataFrame(X) plot(X, y) def test_plot_regression_numpy(): X, y =",
"assert len(figures) == 1 # top 10 axes assert len(figures[0].get_axes())",
"plot(data, target_col='target') # same with \"actual float\" - we need",
"% i for i in range(categorical_features)] df_cat = pd.DataFrame(X_cat, columns=cat_columns).astype('int')",
"= pd.DataFrame(X_cont, columns=cont_columns) if categorical_features > 0: cat_columns = [\"asdf_%d_cat\"",
"4 # known result assert axes[0].get_xlabel() == \"LDA 0\" assert",
"plot even if we do classification with a float target",
"to specify classification for that :-/ data['target'] = y.astype(np.float) +",
"'target_col') def test_plot_regression_continuous_with_target_outliers(): df = pd.DataFrame( data={ \"feature\": np.random.randint(low=1, high=100,",
"y with pytest.raises(ValueError, match=\"need continuous\"): plot_regression_categorical(X, 'target') with pytest.raises(ValueError, match=\"need",
"10, 60, 85])) X_clean['target'] = y if task == \"classification\":",
"in column target.\" ): plot_regression_continuous(df, 'target') def test_plot_regression_categorical_missing_value(): df =",
"data['target'] = y plot(data, target_col='target') def test_na_vals_reg_plot_raise_warning(): X, y =",
"PCA axes = figures[2].get_axes() assert len(axes) == 4 # known",
"== 3 assert res[1][0, 0].get_yticklabels()[2].get_text() == 'dabl_mi...' def test_label_truncation(): a",
"'the_target_that_h...' assert res[0, 0].get_xlabel() == 'a_really_long_nam...' set_config(truncate_labels=False) res = plot_regression_continuous(df,",
"only univariate plots figures = plot_classification_continuous(df, target_col='target', plot_pairwise=False) assert len(figures)",
"len(figures) == 1 # diagonal has twin axes assert len(figures[0].get_axes())",
"\"SOD1_N\" # bar plot never has ylabel assert axes[0].get_ylabel() ==",
"'PCA 5' # LDA axes = figures[3].get_axes() assert len(axes) ==",
".2 plot(data, target_col='target', type_hints={'target': 'categorical'}) plt.close(\"all\") @pytest.mark.filterwarnings('ignore:Discarding near-constant') def test_plot_classification_n_classes():",
"# simple smoke test # should be parametrized n_samples =",
"10 axes assert len(figures[0].get_axes()) == 10 # six is the",
"assert len(figures[0].get_axes()) == 5 * 5 + 5 # also",
"+ .2 plot(data, target_col='target', type_hints={'target': 'categorical'}) plt.close(\"all\") @pytest.mark.filterwarnings('ignore:Discarding near-constant') def",
"figures = plot_classification_continuous(df, target_col='target', plot_pairwise=False) assert len(figures) == 1 #",
"np.random.randint(0, 2, size=1000)]).T # ensure first column is low_card_int assert",
"1000)}) df[b] = df[a] + np.random.uniform(0, 0.1, 1000) res =",
"== continuous_features + categorical_features) X_clean = clean(X_df.copy()) y = y_cont",
"# also do pairwise plots figures = plot_classification_continuous(df, target_col='target', random_state=42)",
"= pd.DataFrame( data={ \"feature\": np.random.randint(low=1, high=100, size=200), # target values",
"# LDA axes = figures[3].get_axes() assert len(axes) == 4 #",
"axis=1) else: X_df = df_cont assert(X_df.shape[1] == continuous_features + categorical_features)",
"5 + 5 # also do pairwise plots figures =",
"type_hints={'target': 'categorical'}) plt.close(\"all\") @pytest.mark.filterwarnings('ignore:Discarding near-constant') def test_plot_classification_n_classes(): X, y =",
"== 6 # for 5 features, do full pairplot figures",
"+ categorical_features) X_clean = clean(X_df.copy()) y = y_cont + y_cat",
"'categorical') if task == \"classification\": assert column_types[-1] == 'categorical' else:",
"= load_diabetes(return_X_y=True) X = pd.DataFrame(X) y[::50] = np.NaN X['target_col'] =",
"clean, detect_types, guess_ordinal from dabl.plot.supervised import ( plot, plot_classification_categorical, plot_classification_continuous,",
"( plot, plot_classification_categorical, plot_classification_continuous, plot_regression_categorical, plot_regression_continuous) from dabl.utils import data_df_from_bunch",
"have \" \"been removed for regression\"): plot(X, 'target_col') with pytest.warns(UserWarning,",
"plot_classification_categorical, plot_classification_continuous, plot_regression_categorical, plot_regression_continuous) from dabl.utils import data_df_from_bunch from dabl",
"1, 3, 100], ['classification', 'regression'])) def test_plots_smoke(continuous_features, categorical_features, task): #",
"load_digits, fetch_openml, load_diabetes) from sklearn.preprocessing import KBinsDiscretizer from dabl.preprocessing import",
"with pytest.raises(ValueError, match=\"need continuous\"): plot_regression_categorical(X, 'target') with pytest.raises(ValueError, match=\"need continuous\"):",
"import KBinsDiscretizer from dabl.preprocessing import clean, detect_types, guess_ordinal from dabl.plot.supervised",
"KBinsDiscretizer(encode='ordinal').fit_transform(X_cat) cont_columns = [\"asdf_%d_cont\" % i for i in range(continuous_features)]",
"plt.close(\"all\") @pytest.mark.parametrize(\"add, feature_type, target_type\", itertools.product([0, .1], ['continuous', 'categorical'], ['continuous', 'categorical']))",
"as np import pandas as pd import matplotlib.pyplot as plt",
"10 # known result assert axes[0].get_xlabel() == \"SOD1_N\" # bar",
"assert axes[0].get_ylabel() == 'LDA 1' def test_plot_string_target(): X, y =",
"plot(X, y) def test_plot_regression_numpy(): X, y = make_regression() plot(X, y)",
"res[0, 0].get_ylabel() == b assert res[0, 0].get_xlabel() == a set_config(truncate_labels=True)",
"len(figures) == 1 assert len(figures[0].get_axes()) == 6 # for 5",
"dabl.utils import data_df_from_bunch from dabl import set_config # FIXME: check",
"test # should be parametrized n_samples = 100 X_cont, y_cont",
"as pd import matplotlib.pyplot as plt import itertools from sklearn.datasets",
"X['target'] = y with pytest.raises(ValueError, match=\"need continuous\"): plot_regression_categorical(X, 'target') with",
"= make_blobs() X = pd.DataFrame(X) plot(X, y) def test_plot_regression_numpy(): X,",
"= plot_classification_continuous(df.iloc[:, -7:], target_col='target', plot_pairwise=False) assert len(figures) == 1 assert",
"# known result assert axes[0].get_xlabel() == \"SOD1_N\" assert axes[0].get_ylabel() ==",
"X_clean['target'] = X_clean['target'].astype('category') types = detect_types(X_clean) column_types = types.T.idxmax() assert",
"axes[0].get_xlabel() == \"PCA 1\" assert axes[0].get_ylabel() == 'PCA 5' #",
"data={ \"feature\": np.random.randint(low=1, high=100, size=200), # target values are bound",
"y = np.digitize(y, np.percentile(y, [5, 10, 60, 85])) X_clean['target'] =",
"but a column name @pytest.mark.filterwarnings('ignore:the matrix subclass') @pytest.mark.parametrize(\"continuous_features, categorical_features, task\",",
"'categorical' else: assert column_types[-1] == 'continuous' plot(X_clean, target_col='target') plt.close(\"all\") @pytest.mark.parametrize(\"add,",
"0}, ignore_index=True) with pytest.warns( UserWarning, match=\"Dropped 1 outliers in column",
"not guess_ordinal(pd.Series([6786930208, 2142878625, 9106275431])) def test_plot_classification_continuous(): data = fetch_openml('MiceProtein') df",
"= df.append({\"feature\": 50, \"target\": 0}, ignore_index=True) with pytest.warns( UserWarning, match=\"Dropped",
"a column name @pytest.mark.filterwarnings('ignore:the matrix subclass') @pytest.mark.parametrize(\"continuous_features, categorical_features, task\", itertools.product([0,",
"simple smoke test # should be parametrized n_samples = 100",
"== \"classification\": y = np.digitize(y, np.percentile(y, [5, 10, 60, 85]))",
"np.digitize(y, np.percentile(y, [5, 10, 60, 85])) X_clean['target'] = y if",
"np.all(column_types[continuous_features:-1] == 'categorical') if task == \"classification\": assert column_types[-1] ==",
"also do pairwise plots figures = plot_classification_continuous(df, target_col='target', random_state=42) #",
"== \"SOD1_N\" # bar plot never has ylabel assert axes[0].get_ylabel()",
"data = pd.DataFrame(X) y = pd.Series(y) y[y == 0] =",
"y = make_blobs() X = pd.DataFrame(X) X['target'] = y with",
"detect_types(data) assert types.categorical['target'] plot(data, target_col='target') # same with \"actual float\"",
"low card int with negative values is plotted correctly data",
"of figure text = plt.gcf()._suptitle.get_text() assert feature_type.capitalize() in text ax",
"size=1000) - 5, np.random.randint(0, 2, size=1000)]).T # ensure first column",
"assert len(figures[0].get_axes()) == 6 # for 5 features, do full",
"feature_type, 'target': target_type}, target_col='target') # get title of figure text",
"\"classification\": X_clean['target'] = X_clean['target'].astype('category') types = detect_types(X_clean) column_types = types.T.idxmax()",
"test plot(data, target_col=1) def test_large_ordinal(): # check that large integers",
"= pd.DataFrame(X) plot(X, y, univariate_plot='kde') def test_plot_int_column_name(): X, y =",
"test_plot_regression_numpy(): X, y = make_regression() plot(X, y) def test_plot_lda_binary(): X,",
"regression\"): plot(X, 'target_col') with pytest.warns(UserWarning, match=\"Missing values in target_col have",
"> 0: cat_columns = [\"asdf_%d_cat\" % i for i in",
"data = load_digits() df = data_df_from_bunch(data) plot(df[::10], target_col='target') def test_plot_X_y():",
"== 10 # known result assert axes[0].get_xlabel() == \"SOD1_N\" #",
"text ax = plt.gca() # one of the labels is",
"itertools from sklearn.datasets import (make_regression, make_blobs, load_digits, fetch_openml, load_diabetes) from",
"y_cont = make_regression( n_samples=n_samples, n_features=continuous_features, n_informative=min(continuous_features, 2)) X_cat, y_cat =",
"matrix subclass') @pytest.mark.parametrize(\"continuous_features, categorical_features, task\", itertools.product([0, 1, 3, 100], [0,",
"1, 3, 100], [0, 1, 3, 100], ['classification', 'regression'])) def",
"\"\" # pairwise axes = figures[1].get_axes() assert len(axes) == 4",
"pairwise plots figures = plot_classification_continuous(df, target_col='target', random_state=42) # univariate, pairwise,",
"random phone numbers assert not guess_ordinal(pd.Series([6786930208, 2142878625, 9106275431])) def test_plot_classification_continuous():",
"types.categorical['target'] plot(data, target_col='target') # same with \"actual float\" - we",
") # append single outlier record with target value 0",
"in range(continuous_features)] df_cont = pd.DataFrame(X_cont, columns=cont_columns) if categorical_features > 0:",
"never has ylabel assert axes[0].get_ylabel() == \"\" # pairwise axes",
"res = plot_regression_continuous(df, target_col=b) assert res[0, 0].get_ylabel() == b assert",
"y = y_cont + y_cat if X_df.shape[1] == 0: y",
"3 assert res[1][0, 0].get_yticklabels()[2].get_text() == 'dabl_mi...' def test_label_truncation(): a =",
"import matplotlib.pyplot as plt import itertools from sklearn.datasets import (make_regression,",
"name @pytest.mark.filterwarnings('ignore:the matrix subclass') @pytest.mark.parametrize(\"continuous_features, categorical_features, task\", itertools.product([0, 1, 3,",
"pd.DataFrame(X) y = pd.Series(y) y[y == 0] = 'a' y[y",
"== 'PCA 5' # LDA axes = figures[3].get_axes() assert len(axes)",
"4 # univariate axes = figures[0].get_axes() assert len(axes) == 10",
"\"PCA 1\" assert axes[0].get_ylabel() == 'PCA 5' # LDA axes",
"assert res[0, 0].get_ylabel() == b assert res[0, 0].get_xlabel() == a",
"('target' in labels) == (target_type == 'continuous') plt.close(\"all\") def test_float_classification_target():",
"plt.close(\"all\") @pytest.mark.filterwarnings('ignore:Discarding near-constant') def test_plot_classification_n_classes(): X, y = make_blobs() X",
"len(axes) == 4 # known result assert axes[0].get_xlabel() == \"LDA",
"+= 2 df['x'] = 'a' df.loc[100:200, 'x'] = 'b' df.loc[200:300,",
"plot_classification_continuous(df.iloc[:, -6:], target_col='target', plot_pairwise=False) assert len(figures) == 1 # diagonal",
"load_diabetes) from sklearn.preprocessing import KBinsDiscretizer from dabl.preprocessing import clean, detect_types,",
"df_cont = pd.DataFrame(X_cont, columns=cont_columns) if categorical_features > 0: cat_columns =",
"100], [0, 1, 3, 100], ['classification', 'regression'])) def test_plots_smoke(continuous_features, categorical_features,",
"plot_classification_continuous(X, 'target') def test_plot_wrong_target_type(): X, y = make_blobs() X =",
"0 df = df.append({\"feature\": 50, \"target\": 0}, ignore_index=True) with pytest.warns(",
"assert axes[0].get_xlabel() == \"LDA 0\" assert axes[0].get_ylabel() == 'LDA 1'",
"regression\"): plot_regression_continuous(X, 'target_col') with pytest.warns(UserWarning, match=\"Missing values in target_col have",
"itertools.product([0, 1, 3, 100], [0, 1, 3, 100], ['classification', 'regression']))",
"with pytest.warns(UserWarning, match=\"Missing values in target_col have \" \"been removed",
"match=\"Less than two classes\"): plot_classification_continuous(X, 'target') def test_plot_wrong_target_type(): X, y",
"y_cat = make_regression( n_samples=n_samples, n_features=categorical_features, n_informative=min(categorical_features, 2)) if X_cat.shape[1] >",
"} ) # append single outlier record with target value",
"make_blobs(n_samples=30) data = pd.DataFrame(X) y = pd.Series(y) y[y == 0]",
"categorical_features, task\", itertools.product([0, 1, 3, 100], [0, 1, 3, 100],",
"we need to specify classification for that :-/ data['target'] =",
"= figures[0].get_axes() assert len(axes) == 10 # known result assert",
"X_cat.shape[1] > 0: X_cat = KBinsDiscretizer(encode='ordinal').fit_transform(X_cat) cont_columns = [\"asdf_%d_cont\" %",
"y) def test_plot_lda_binary(): X, y = make_blobs(centers=2) X = pd.DataFrame(X)",
"numpy as np import pandas as pd import matplotlib.pyplot as",
"guess_ordinal(pd.Series([6786930208, 2142878625, 9106275431])) def test_plot_classification_continuous(): data = fetch_openml('MiceProtein') df =",
"= df[a] + np.random.uniform(0, 0.1, 1000) res = plot_regression_continuous(df, target_col=b)",
"= np.random.uniform(size=n_samples) if task == \"classification\": y = np.digitize(y, np.percentile(y,",
"fetch_openml('MiceProtein') df = data_df_from_bunch(data) # only univariate plots figures =",
"import clean, detect_types, guess_ordinal from dabl.plot.supervised import ( plot, plot_classification_categorical,",
"near-constant') def test_plot_classification_n_classes(): X, y = make_blobs() X = pd.DataFrame(X)",
"5 features, do full pairplot figures = plot_classification_continuous(df.iloc[:, -6:], target_col='target',",
"value 0 df = df.append({\"feature\": 50, \"target\": 0}, ignore_index=True) with",
"size=100)) + add X['target'] = np.random.uniform(size=100) plot(X, type_hints={0: feature_type, 'target':",
"('the_target_that_has_an_equally_long_name_which_would_' 'mess_up_everything_as_well_but_in_different_places') df = pd.DataFrame({a: np.random.uniform(0, 1, 1000)}) df[b] =",
"categorical\"): plot_classification_categorical(X, 'target') with pytest.raises(ValueError, match=\"need categorical\"): plot_classification_continuous(X, 'target') def",
"even if we do classification with a float target X,",
"make_regression() plot(X, y) def test_plot_lda_binary(): X, y = make_blobs(centers=2) X",
"'regression'])) def test_plots_smoke(continuous_features, categorical_features, task): # simple smoke test #",
"= fetch_openml('MiceProtein') df = data_df_from_bunch(data) # only univariate plots figures",
"['classification', 'regression'])) def test_plots_smoke(continuous_features, categorical_features, task): # simple smoke test",
"X_clean['target'] = y if task == \"classification\": X_clean['target'] = X_clean['target'].astype('category')",
"can plot even if we do classification with a float",
"features, do full pairplot figures = plot_classification_continuous(df.iloc[:, -6:], target_col='target', plot_pairwise=False)",
"KBinsDiscretizer from dabl.preprocessing import clean, detect_types, guess_ordinal from dabl.plot.supervised import",
"= 'b' df.loc[200:300, 'x'] = np.NaN res = plot(df, target_col='y')",
"2 df['x'] = 'a' df.loc[100:200, 'x'] = 'b' df.loc[200:300, 'x']",
"that large integers don't bring us down (bincount memory error)",
"down (bincount memory error) # here some random phone numbers",
"in target_col have \" \"been removed for regression\"): plot_regression_continuous(X, 'target_col')",
"from sklearn.preprocessing import KBinsDiscretizer from dabl.preprocessing import clean, detect_types, guess_ordinal",
"check we can plot even if we do classification with",
"test_plot_X_y(): X, y = make_blobs() X = pd.DataFrame(X) plot(X, y)",
"= make_regression() plot(X, y) def test_plot_lda_binary(): X, y = make_blobs(centers=2)",
"if we do classification with a float target X, y",
"1 # top 10 axes assert len(figures[0].get_axes()) == 10 #",
"+= 1 df.loc[200:300, 'y'] += 2 df['x'] = 'a' df.loc[100:200,",
"histograms # (last column is target) figures = plot_classification_continuous(df.iloc[:, -7:],",
"text = plt.gcf()._suptitle.get_text() assert feature_type.capitalize() in text ax = plt.gca()",
"# target values are bound between 50 and 100 \"target\":",
"pytest.raises(ValueError, match=\"need continuous\"): plot_regression_continuous(X, 'target') X['target'] = X[0] with pytest.raises(ValueError,",
"'target') def test_plot_target_low_card_int(): data = load_digits() df = data_df_from_bunch(data) plot(df[::10],",
"1\" assert axes[0].get_ylabel() == 'PCA 5' # LDA axes =",
"X_cont, y_cont = make_regression( n_samples=n_samples, n_features=continuous_features, n_informative=min(continuous_features, 2)) X_cat, y_cat",
"classification for that :-/ data['target'] = y.astype(np.float) + .2 plot(data,",
"continuous\"): plot_regression_categorical(X, 'target') with pytest.raises(ValueError, match=\"need continuous\"): plot_regression_continuous(X, 'target') X['target']",
"85])) X_clean['target'] = y if task == \"classification\": X_clean['target'] =",
"plot_pairwise=False) assert len(figures) == 1 assert len(figures[0].get_axes()) == 6 #",
"if X_cat.shape[1] > 0: X_cat = KBinsDiscretizer(encode='ordinal').fit_transform(X_cat) cont_columns = [\"asdf_%d_cont\"",
"df = pd.DataFrame({a: np.random.uniform(0, 1, 1000)}) df[b] = df[a] +",
"plot_regression_continuous) from dabl.utils import data_df_from_bunch from dabl import set_config #",
"0\" assert axes[0].get_ylabel() == 'LDA 1' def test_plot_string_target(): X, y",
"twin axes assert len(figures[0].get_axes()) == 5 * 5 + 5",
"check that target is not y but a column name",
"= pd.DataFrame(X) X[3] = y plot(X, target_col=3) def test_negative_ordinal(): #",
"from sklearn.datasets import (make_regression, make_blobs, load_digits, fetch_openml, load_diabetes) from sklearn.preprocessing",
"plot_regression_continuous(X, 'target_col') with pytest.warns(UserWarning, match=\"Missing values in target_col have \"",
"df['x'] = 'a' df.loc[100:200, 'x'] = 'b' df.loc[200:300, 'x'] =",
"task): # simple smoke test # should be parametrized n_samples",
"categorical_features > 0: cat_columns = [\"asdf_%d_cat\" % i for i",
"make_blobs() X = pd.DataFrame(X) X['target'] = y with pytest.raises(ValueError, match=\"need",
"res[1][0, 0].get_yticklabels()[2].get_text() == 'dabl_mi...' def test_label_truncation(): a = ('a_really_long_name_that_would_mess_up_the_layout_a_lot' '_by_just_being_very_long')",
"test_plot_string_target(): X, y = make_blobs(n_samples=30) data = pd.DataFrame(X) y =",
"(bincount memory error) # here some random phone numbers assert",
"match=\"Dropped 1 outliers in column target.\" ): plot_regression_continuous(df, 'target') def",
"100 X_cont, y_cont = make_regression( n_samples=n_samples, n_features=continuous_features, n_informative=min(continuous_features, 2)) X_cat,",
"univariate, pairwise, pca, lda assert len(figures) == 4 # univariate",
"= make_blobs(centers=2) X = pd.DataFrame(X) plot(X, y, univariate_plot='kde') def test_plot_int_column_name():",
"# bar plot never has ylabel assert axes[0].get_ylabel() == \"\"",
"in target_col have \" \"been removed for regression\"): plot_regression_categorical(X, 'target_col')",
"df_cat = pd.DataFrame(X_cat, columns=cat_columns).astype('int') df_cat = df_cat.astype(\"category\") X_df = pd.concat([df_cont,",
"column name @pytest.mark.filterwarnings('ignore:the matrix subclass') @pytest.mark.parametrize(\"continuous_features, categorical_features, task\", itertools.product([0, 1,",
"pd.DataFrame(X_cat, columns=cat_columns).astype('int') df_cat = df_cat.astype(\"category\") X_df = pd.concat([df_cont, df_cat], axis=1)",
"result assert axes[0].get_xlabel() == \"SOD1_N\" assert axes[0].get_ylabel() == 'S6_N' #",
"task == \"classification\": assert column_types[-1] == 'categorical' else: assert column_types[-1]",
"y = make_blobs() X = pd.DataFrame(X) X[3] = y plot(X,",
"== 'continuous') assert np.all(column_types[continuous_features:-1] == 'categorical') if task == \"classification\":",
"as plt import itertools from sklearn.datasets import (make_regression, make_blobs, load_digits,",
"pd.Series(y) y[y == 0] = 'a' y[y == 1] =",
"itertools.product([0, .1], ['continuous', 'categorical'], ['continuous', 'categorical'])) def test_type_hints(add, feature_type, target_type):",
"= [\"asdf_%d_cont\" % i for i in range(continuous_features)] df_cont =",
"\"SOD1_N\" assert axes[0].get_ylabel() == 'S6_N' # PCA axes = figures[2].get_axes()",
"plot(X, y) def test_plot_lda_binary(): X, y = make_blobs(centers=2) X =",
"np.random.randint(low=50, high=100, size=200) } ) # append single outlier record",
"is low_card_int assert (detect_types(data).T.idxmax() == ['low_card_int', 'categorical']).all() assert guess_ordinal(data[0]) #",
"pytest.raises(ValueError, match=\"need categorical\"): plot_classification_continuous(X, 'target') def test_plot_target_low_card_int(): data = load_digits()",
"make_blobs() X = pd.DataFrame(X) X[3] = y plot(X, target_col=3) def",
"X, y = make_blobs() X = pd.DataFrame(X) X[3] = y",
"assert ('target' in labels) == (target_type == 'continuous') plt.close(\"all\") def",
"test_plot_int_column_name(): X, y = make_blobs() X = pd.DataFrame(X) X[3] =",
"data_df_from_bunch(data) plot(df[::10], target_col='target') def test_plot_X_y(): X, y = make_blobs() X",
"match=\"need categorical\"): plot_classification_categorical(X, 'target') with pytest.raises(ValueError, match=\"need categorical\"): plot_classification_continuous(X, 'target')",
"import numpy as np import pandas as pd import matplotlib.pyplot",
"ax.get_ylabel() + ax.get_xlabel() assert ('target' in labels) == (target_type ==",
"than two classes\"): plot_classification_continuous(X, 'target') def test_plot_wrong_target_type(): X, y =",
"plot(df, target_col='y') assert len(res[1][0, 0].get_yticklabels()) == 3 assert res[1][0, 0].get_yticklabels()[2].get_text()",
"figures[2].get_axes() assert len(axes) == 4 # known result assert axes[0].get_xlabel()",
"assert res[0, 0].get_xlabel() == 'a_really_long_nam...' set_config(truncate_labels=False) res = plot_regression_continuous(df, target_col=b)",
"size=1000)]).T # ensure first column is low_card_int assert (detect_types(data).T.idxmax() ==",
"some random phone numbers assert not guess_ordinal(pd.Series([6786930208, 2142878625, 9106275431])) def",
"ax.get_xlabel() assert ('target' in labels) == (target_type == 'continuous') plt.close(\"all\")",
"do classification with a float target X, y = make_blobs()",
"1 assert len(figures[0].get_axes()) == 6 # for 5 features, do",
"values are bound between 50 and 100 \"target\": np.random.randint(low=50, high=100,",
"y = make_regression() plot(X, y) def test_plot_lda_binary(): X, y =",
"match=\"Missing values in target_col have \" \"been removed for regression\"):",
"data['target'] = y.astype(np.float) + .2 plot(data, target_col='target', type_hints={'target': 'categorical'}) plt.close(\"all\")",
"assert len(figures) == 1 # diagonal has twin axes assert",
"do full pairplot figures = plot_classification_continuous(df.iloc[:, -6:], target_col='target', plot_pairwise=False) assert",
"4 # known result assert axes[0].get_xlabel() == \"SOD1_N\" assert axes[0].get_ylabel()",
"X, y = make_regression() plot(X, y) def test_plot_lda_binary(): X, y",
"feature_type, target_type\", itertools.product([0, .1], ['continuous', 'categorical'], ['continuous', 'categorical'])) def test_type_hints(add,",
"# here some random phone numbers assert not guess_ordinal(pd.Series([6786930208, 2142878625,",
"plot_regression_categorical, plot_regression_continuous) from dabl.utils import data_df_from_bunch from dabl import set_config",
"test_plot_classification_continuous(): data = fetch_openml('MiceProtein') df = data_df_from_bunch(data) # only univariate",
"== 1 # diagonal has twin axes assert len(figures[0].get_axes()) ==",
"# append single outlier record with target value 0 df",
"target_col='target') # same with \"actual float\" - we need to",
"classes\"): plot_classification_continuous(X, 'target') def test_plot_wrong_target_type(): X, y = make_blobs() X",
"else: X_df = df_cont assert(X_df.shape[1] == continuous_features + categorical_features) X_clean",
"target_col='target', plot_pairwise=False) assert len(figures) == 1 # diagonal has twin",
"columns=cont_columns) if categorical_features > 0: cat_columns = [\"asdf_%d_cat\" % i",
"= 'a' y[y == 1] = 'b' y[y == 2]",
"= ax.get_ylabel() + ax.get_xlabel() assert ('target' in labels) == (target_type",
"n_samples = 100 X_cont, y_cont = make_regression( n_samples=n_samples, n_features=continuous_features, n_informative=min(continuous_features,",
"# smoke test plot(data, target_col=1) def test_large_ordinal(): # check that",
"= y_cont + y_cat if X_df.shape[1] == 0: y =",
"[0, 1, 3, 100], ['classification', 'regression'])) def test_plots_smoke(continuous_features, categorical_features, task):",
"assert not guess_ordinal(pd.Series([6786930208, 2142878625, 9106275431])) def test_plot_classification_continuous(): data = fetch_openml('MiceProtein')",
"int with negative values is plotted correctly data = pd.DataFrame([np.random.randint(0,",
"= pd.DataFrame([np.random.randint(0, 10, size=1000) - 5, np.random.randint(0, 2, size=1000)]).T #",
"that :-/ data['target'] = y.astype(np.float) + .2 plot(data, target_col='target', type_hints={'target':",
"values in target_col have \" \"been removed for regression\"): plot(X,",
"UserWarning, match=\"Dropped 1 outliers in column target.\" ): plot_regression_continuous(df, 'target')",
"target_col='y') assert len(res[1][0, 0].get_yticklabels()) == 3 assert res[1][0, 0].get_yticklabels()[2].get_text() ==",
"= pd.DataFrame({'y': np.random.normal(size=300)}) df.loc[100:200, 'y'] += 1 df.loc[200:300, 'y'] +=",
"= ('the_target_that_has_an_equally_long_name_which_would_' 'mess_up_everything_as_well_but_in_different_places') df = pd.DataFrame({a: np.random.uniform(0, 1, 1000)}) df[b]",
"= pd.DataFrame(X) X['target'] = y with pytest.raises(ValueError, match=\"need continuous\"): plot_regression_categorical(X,",
"-6:], target_col='target', plot_pairwise=False) assert len(figures) == 1 # diagonal has",
"plot(X, target_col=3) def test_negative_ordinal(): # check that a low card",
"3, 100], [0, 1, 3, 100], ['classification', 'regression'])) def test_plots_smoke(continuous_features,",
"0: y = np.random.uniform(size=n_samples) if task == \"classification\": y =",
"'target_col') with pytest.warns(UserWarning, match=\"Missing values in target_col have \" \"been",
"X, y = make_blobs() X = pd.DataFrame(X) plot(X, y) def",
"== \"PCA 1\" assert axes[0].get_ylabel() == 'PCA 5' # LDA",
"= y.astype(np.float) types = detect_types(data) assert types.categorical['target'] plot(data, target_col='target') #",
"lda assert len(figures) == 4 # univariate axes = figures[0].get_axes()",
"data = fetch_openml('MiceProtein') df = data_df_from_bunch(data) # only univariate plots",
"np.random.normal(size=300)}) df.loc[100:200, 'y'] += 1 df.loc[200:300, 'y'] += 2 df['x']",
"pytest.raises(ValueError, match=\"Less than two classes\"): plot_classification_continuous(X, 'target') def test_plot_wrong_target_type(): X,",
"X = pd.DataFrame(X) y[::50] = np.NaN X['target_col'] = y with",
"== 1 assert len(figures[0].get_axes()) == 6 # for 5 features,",
"dabl import set_config # FIXME: check that target is not",
"with pytest.warns( UserWarning, match=\"Dropped 1 outliers in column target.\" ):",
"pd.DataFrame(X) data['target'] = y.astype(np.float) types = detect_types(data) assert types.categorical['target'] plot(data,",
"match=\"Less than two classes\"): plot_classification_categorical(X, 'target') with pytest.raises(ValueError, match=\"Less than",
"two classes\"): plot_classification_continuous(X, 'target') def test_plot_wrong_target_type(): X, y = make_blobs()",
"np.random.uniform(0, 1, 1000)}) df[b] = df[a] + np.random.uniform(0, 0.1, 1000)",
"df.loc[200:300, 'y'] += 2 df['x'] = 'a' df.loc[100:200, 'x'] =",
"continuous\"): plot_regression_continuous(X, 'target') X['target'] = X[0] with pytest.raises(ValueError, match=\"need categorical\"):",
"target_col have \" \"been removed for regression\"): plot(X, 'target_col') with",
"@pytest.mark.parametrize(\"continuous_features, categorical_features, task\", itertools.product([0, 1, 3, 100], [0, 1, 3,",
"res = plot_regression_continuous(df, target_col=b) assert res[0, 0].get_ylabel() == 'the_target_that_h...' assert",
"def test_plot_target_low_card_int(): data = load_digits() df = data_df_from_bunch(data) plot(df[::10], target_col='target')",
"\"feature\": np.random.randint(low=1, high=100, size=200), # target values are bound between",
"pd.concat([df_cont, df_cat], axis=1) else: X_df = df_cont assert(X_df.shape[1] == continuous_features",
"y_cat if X_df.shape[1] == 0: y = np.random.uniform(size=n_samples) if task",
"if categorical_features > 0: cat_columns = [\"asdf_%d_cat\" % i for",
"def test_large_ordinal(): # check that large integers don't bring us",
"with negative values is plotted correctly data = pd.DataFrame([np.random.randint(0, 10,",
"target_col='target') def test_na_vals_reg_plot_raise_warning(): X, y = load_diabetes(return_X_y=True) X = pd.DataFrame(X)",
"categorical_features) X_clean = clean(X_df.copy()) y = y_cont + y_cat if",
"known result assert axes[0].get_xlabel() == \"LDA 0\" assert axes[0].get_ylabel() ==",
"0: X_cat = KBinsDiscretizer(encode='ordinal').fit_transform(X_cat) cont_columns = [\"asdf_%d_cont\" % i for",
"one of the labels is 'target' iif regression labels =",
"y.astype(np.float) types = detect_types(data) assert types.categorical['target'] plot(data, target_col='target') # same",
"sklearn.preprocessing import KBinsDiscretizer from dabl.preprocessing import clean, detect_types, guess_ordinal from",
"dabl.plot.supervised import ( plot, plot_classification_categorical, plot_classification_continuous, plot_regression_categorical, plot_regression_continuous) from dabl.utils",
"make_regression( n_samples=n_samples, n_features=continuous_features, n_informative=min(continuous_features, 2)) X_cat, y_cat = make_regression( n_samples=n_samples,",
"np import pandas as pd import matplotlib.pyplot as plt import",
"assert(X_df.shape[1] == continuous_features + categorical_features) X_clean = clean(X_df.copy()) y =",
"target X, y = make_blobs() data = pd.DataFrame(X) data['target'] =",
"def test_plot_X_y(): X, y = make_blobs() X = pd.DataFrame(X) plot(X,",
"a low card int with negative values is plotted correctly",
"= df_cat.astype(\"category\") X_df = pd.concat([df_cont, df_cat], axis=1) else: X_df =",
"# ensure first column is low_card_int assert (detect_types(data).T.idxmax() == ['low_card_int',",
"def test_plot_classification_continuous(): data = fetch_openml('MiceProtein') df = data_df_from_bunch(data) # only",
"X['target_col'] = y with pytest.warns(UserWarning, match=\"Missing values in target_col have",
"== \"\" # pairwise axes = figures[1].get_axes() assert len(axes) ==",
"== 'categorical') if task == \"classification\": assert column_types[-1] == 'categorical'",
"(last column is target) figures = plot_classification_continuous(df.iloc[:, -7:], target_col='target', plot_pairwise=False)",
"y = make_blobs() X = pd.DataFrame(X) X['target'] = 0 with",
"import pandas as pd import matplotlib.pyplot as plt import itertools",
"us down (bincount memory error) # here some random phone",
"df_cat = df_cat.astype(\"category\") X_df = pd.concat([df_cont, df_cat], axis=1) else: X_df",
"4 # known result assert axes[0].get_xlabel() == \"PCA 1\" assert",
"def test_plot_string_target(): X, y = make_blobs(n_samples=30) data = pd.DataFrame(X) y",
"['low_card_int', 'categorical']).all() assert guess_ordinal(data[0]) # smoke test plot(data, target_col=1) def",
"matplotlib.pyplot as plt import itertools from sklearn.datasets import (make_regression, make_blobs,",
"np.random.uniform(size=n_samples) if task == \"classification\": y = np.digitize(y, np.percentile(y, [5,",
"a float target X, y = make_blobs() data = pd.DataFrame(X)",
"test_plot_target_low_card_int(): data = load_digits() df = data_df_from_bunch(data) plot(df[::10], target_col='target') def",
"size=200) } ) # append single outlier record with target",
"X, y = make_blobs() data = pd.DataFrame(X) data['target'] = y.astype(np.float)",
"# PCA axes = figures[2].get_axes() assert len(axes) == 4 #",
"df[a] + np.random.uniform(0, 0.1, 1000) res = plot_regression_continuous(df, target_col=b) assert",
"target_col='target', random_state=42) # univariate, pairwise, pca, lda assert len(figures) ==",
"* 5 + 5 # also do pairwise plots figures",
"# check that large integers don't bring us down (bincount",
"task == \"classification\": y = np.digitize(y, np.percentile(y, [5, 10, 60,",
"len(axes) == 4 # known result assert axes[0].get_xlabel() == \"SOD1_N\"",
"removed for regression\"): plot_regression_categorical(X, 'target_col') def test_plot_regression_continuous_with_target_outliers(): df = pd.DataFrame(",
"plot_classification_continuous, plot_regression_categorical, plot_regression_continuous) from dabl.utils import data_df_from_bunch from dabl import",
"regression\"): plot_regression_categorical(X, 'target_col') def test_plot_regression_continuous_with_target_outliers(): df = pd.DataFrame( data={ \"feature\":",
"'categorical'], ['continuous', 'categorical'])) def test_type_hints(add, feature_type, target_type): X = pd.DataFrame(np.random.randint(4,",
"X[3] = y plot(X, target_col=3) def test_negative_ordinal(): # check that",
"assert axes[0].get_ylabel() == 'PCA 5' # LDA axes = figures[3].get_axes()",
"X[0] with pytest.raises(ValueError, match=\"need categorical\"): plot_classification_categorical(X, 'target') with pytest.raises(ValueError, match=\"need",
"single outlier record with target value 0 df = df.append({\"feature\":",
"add X['target'] = np.random.uniform(size=100) plot(X, type_hints={0: feature_type, 'target': target_type}, target_col='target')",
"data['target'] = y.astype(np.float) types = detect_types(data) assert types.categorical['target'] plot(data, target_col='target')",
"assert (detect_types(data).T.idxmax() == ['low_card_int', 'categorical']).all() assert guess_ordinal(data[0]) # smoke test",
"df.loc[100:200, 'x'] = 'b' df.loc[200:300, 'x'] = np.NaN res =",
"1, 1000)}) df[b] = df[a] + np.random.uniform(0, 0.1, 1000) res",
"'x'] = 'b' df.loc[200:300, 'x'] = np.NaN res = plot(df,",
"-7:], target_col='target', plot_pairwise=False) assert len(figures) == 1 assert len(figures[0].get_axes()) ==",
"= pd.concat([df_cont, df_cat], axis=1) else: X_df = df_cont assert(X_df.shape[1] ==",
"# for 5 features, do full pairplot figures = plot_classification_continuous(df.iloc[:,",
"> 0: X_cat = KBinsDiscretizer(encode='ordinal').fit_transform(X_cat) cont_columns = [\"asdf_%d_cont\" % i",
"types = detect_types(data) assert types.categorical['target'] plot(data, target_col='target') # same with",
"plot(data, target_col='target') def test_na_vals_reg_plot_raise_warning(): X, y = load_diabetes(return_X_y=True) X =",
"data_df_from_bunch(data) # only univariate plots figures = plot_classification_continuous(df, target_col='target', plot_pairwise=False)",
"# same with \"actual float\" - we need to specify",
"columns=cat_columns).astype('int') df_cat = df_cat.astype(\"category\") X_df = pd.concat([df_cont, df_cat], axis=1) else:",
"figures = plot_classification_continuous(df.iloc[:, -6:], target_col='target', plot_pairwise=False) assert len(figures) == 1",
"'categorical']).all() assert guess_ordinal(data[0]) # smoke test plot(data, target_col=1) def test_large_ordinal():",
"test_label_truncation(): a = ('a_really_long_name_that_would_mess_up_the_layout_a_lot' '_by_just_being_very_long') b = ('the_target_that_has_an_equally_long_name_which_would_' 'mess_up_everything_as_well_but_in_different_places') df",
"number of features for histograms # (last column is target)",
"y_cont + y_cat if X_df.shape[1] == 0: y = np.random.uniform(size=n_samples)",
"- we need to specify classification for that :-/ data['target']",
"for that :-/ data['target'] = y.astype(np.float) + .2 plot(data, target_col='target',",
"def test_negative_ordinal(): # check that a low card int with",
"assert axes[0].get_xlabel() == \"SOD1_N\" assert axes[0].get_ylabel() == 'S6_N' # PCA",
"== 'LDA 1' def test_plot_string_target(): X, y = make_blobs(n_samples=30) data",
"target_col=b) assert res[0, 0].get_ylabel() == b assert res[0, 0].get_xlabel() ==",
"bring us down (bincount memory error) # here some random",
"removed for regression\"): plot_regression_continuous(X, 'target_col') with pytest.warns(UserWarning, match=\"Missing values in",
"0].get_yticklabels()) == 3 assert res[1][0, 0].get_yticklabels()[2].get_text() == 'dabl_mi...' def test_label_truncation():",
"pd.DataFrame( data={ \"feature\": np.random.randint(low=1, high=100, size=200), # target values are",
"append single outlier record with target value 0 df =",
"classification with a float target X, y = make_blobs() data",
"== 2] = 'c' data['target'] = y plot(data, target_col='target') def",
"10, size=1000) - 5, np.random.randint(0, 2, size=1000)]).T # ensure first",
"'target') def test_plot_regression_categorical_missing_value(): df = pd.DataFrame({'y': np.random.normal(size=300)}) df.loc[100:200, 'y'] +=",
"with a float target X, y = make_blobs() data =",
"6 # for 5 features, do full pairplot figures =",
"np.percentile(y, [5, 10, 60, 85])) X_clean['target'] = y if task",
"target_type}, target_col='target') # get title of figure text = plt.gcf()._suptitle.get_text()",
"pd.DataFrame(X) X['target'] = y with pytest.raises(ValueError, match=\"need continuous\"): plot_regression_categorical(X, 'target')",
"plot_classification_continuous(df, target_col='target', random_state=42) # univariate, pairwise, pca, lda assert len(figures)",
"assert res[1][0, 0].get_yticklabels()[2].get_text() == 'dabl_mi...' def test_label_truncation(): a = ('a_really_long_name_that_would_mess_up_the_layout_a_lot'",
"i for i in range(continuous_features)] df_cont = pd.DataFrame(X_cont, columns=cont_columns) if",
"== 'continuous' plot(X_clean, target_col='target') plt.close(\"all\") @pytest.mark.parametrize(\"add, feature_type, target_type\", itertools.product([0, .1],",
"pairwise axes = figures[1].get_axes() assert len(axes) == 4 # known",
"make_regression( n_samples=n_samples, n_features=categorical_features, n_informative=min(categorical_features, 2)) if X_cat.shape[1] > 0: X_cat",
"first column is low_card_int assert (detect_types(data).T.idxmax() == ['low_card_int', 'categorical']).all() assert",
"target is not y but a column name @pytest.mark.filterwarnings('ignore:the matrix",
"high=100, size=200) } ) # append single outlier record with",
"% i for i in range(continuous_features)] df_cont = pd.DataFrame(X_cont, columns=cont_columns)",
"\"classification\": assert column_types[-1] == 'categorical' else: assert column_types[-1] == 'continuous'",
"50 and 100 \"target\": np.random.randint(low=50, high=100, size=200) } ) #",
"assert types.categorical['target'] plot(data, target_col='target') # same with \"actual float\" -",
"column is low_card_int assert (detect_types(data).T.idxmax() == ['low_card_int', 'categorical']).all() assert guess_ordinal(data[0])",
"np.random.randint(low=1, high=100, size=200), # target values are bound between 50",
"X, y = make_blobs() X = pd.DataFrame(X) X['target'] = 0",
"= pd.DataFrame(X) X['target'] = 0 with pytest.raises(ValueError, match=\"Less than two",
"'categorical'])) def test_type_hints(add, feature_type, target_type): X = pd.DataFrame(np.random.randint(4, size=100)) +",
"with pytest.raises(ValueError, match=\"need continuous\"): plot_regression_continuous(X, 'target') X['target'] = X[0] with",
"== 'a_really_long_nam...' set_config(truncate_labels=False) res = plot_regression_continuous(df, target_col=b) assert res[0, 0].get_ylabel()",
"X, y = make_blobs() X = pd.DataFrame(X) X['target'] = y",
"make_blobs() data = pd.DataFrame(X) data['target'] = y.astype(np.float) types = detect_types(data)",
"test_plot_wrong_target_type(): X, y = make_blobs() X = pd.DataFrame(X) X['target'] =",
"target_col='target') # get title of figure text = plt.gcf()._suptitle.get_text() assert",
"1] = 'b' y[y == 2] = 'c' data['target'] =",
"df.loc[100:200, 'y'] += 1 df.loc[200:300, 'y'] += 2 df['x'] =",
"with pytest.raises(ValueError, match=\"need categorical\"): plot_classification_categorical(X, 'target') with pytest.raises(ValueError, match=\"need categorical\"):",
"test_plots_smoke(continuous_features, categorical_features, task): # simple smoke test # should be",
"labels = ax.get_ylabel() + ax.get_xlabel() assert ('target' in labels) ==",
"card int with negative values is plotted correctly data =",
"random_state=42) # univariate, pairwise, pca, lda assert len(figures) == 4",
"100 \"target\": np.random.randint(low=50, high=100, size=200) } ) # append single",
"plt.gca() # one of the labels is 'target' iif regression",
"= plt.gca() # one of the labels is 'target' iif",
"= np.random.uniform(size=100) plot(X, type_hints={0: feature_type, 'target': target_type}, target_col='target') # get",
"target_col=b) assert res[0, 0].get_ylabel() == 'the_target_that_h...' assert res[0, 0].get_xlabel() ==",
"'continuous') assert np.all(column_types[continuous_features:-1] == 'categorical') if task == \"classification\": assert",
"5 # also do pairwise plots figures = plot_classification_continuous(df, target_col='target',",
"ylabel assert axes[0].get_ylabel() == \"\" # pairwise axes = figures[1].get_axes()",
"== (target_type == 'continuous') plt.close(\"all\") def test_float_classification_target(): # check we",
"assert len(res[1][0, 0].get_yticklabels()) == 3 assert res[1][0, 0].get_yticklabels()[2].get_text() == 'dabl_mi...'",
"sklearn.datasets import (make_regression, make_blobs, load_digits, fetch_openml, load_diabetes) from sklearn.preprocessing import",
"for regression\"): plot(X, 'target_col') with pytest.warns(UserWarning, match=\"Missing values in target_col",
"X_cat, y_cat = make_regression( n_samples=n_samples, n_features=categorical_features, n_informative=min(categorical_features, 2)) if X_cat.shape[1]",
"[\"asdf_%d_cat\" % i for i in range(categorical_features)] df_cat = pd.DataFrame(X_cat,",
"assert column_types[-1] == 'categorical' else: assert column_types[-1] == 'continuous' plot(X_clean,",
"y.astype(np.float) + .2 plot(data, target_col='target', type_hints={'target': 'categorical'}) plt.close(\"all\") @pytest.mark.filterwarnings('ignore:Discarding near-constant')",
"= 'a' df.loc[100:200, 'x'] = 'b' df.loc[200:300, 'x'] = np.NaN",
"X['target'] = 0 with pytest.raises(ValueError, match=\"Less than two classes\"): plot_classification_categorical(X,",
"for regression\"): plot_regression_continuous(X, 'target_col') with pytest.warns(UserWarning, match=\"Missing values in target_col",
"plots figures = plot_classification_continuous(df, target_col='target', plot_pairwise=False) assert len(figures) == 1",
"axes assert len(figures[0].get_axes()) == 5 * 5 + 5 #",
"[5, 10, 60, 85])) X_clean['target'] = y if task ==",
"n_informative=min(continuous_features, 2)) X_cat, y_cat = make_regression( n_samples=n_samples, n_features=categorical_features, n_informative=min(categorical_features, 2))",
"assert axes[0].get_ylabel() == 'S6_N' # PCA axes = figures[2].get_axes() assert",
"100], ['classification', 'regression'])) def test_plots_smoke(continuous_features, categorical_features, task): # simple smoke",
"size=200), # target values are bound between 50 and 100",
"in range(categorical_features)] df_cat = pd.DataFrame(X_cat, columns=cat_columns).astype('int') df_cat = df_cat.astype(\"category\") X_df",
"pd.DataFrame([np.random.randint(0, 10, size=1000) - 5, np.random.randint(0, 2, size=1000)]).T # ensure",
"np.all(column_types[:continuous_features] == 'continuous') assert np.all(column_types[continuous_features:-1] == 'categorical') if task ==",
"values in target_col have \" \"been removed for regression\"): plot_regression_categorical(X,",
"(make_regression, make_blobs, load_digits, fetch_openml, load_diabetes) from sklearn.preprocessing import KBinsDiscretizer from",
"top 10 axes assert len(figures[0].get_axes()) == 10 # six is",
"have \" \"been removed for regression\"): plot_regression_continuous(X, 'target_col') with pytest.warns(UserWarning,",
"the labels is 'target' iif regression labels = ax.get_ylabel() +",
"df[b] = df[a] + np.random.uniform(0, 0.1, 1000) res = plot_regression_continuous(df,",
"column_types = types.T.idxmax() assert np.all(column_types[:continuous_features] == 'continuous') assert np.all(column_types[continuous_features:-1] ==",
"X['target'] = X[0] with pytest.raises(ValueError, match=\"need categorical\"): plot_classification_categorical(X, 'target') with",
"'c' data['target'] = y plot(data, target_col='target') def test_na_vals_reg_plot_raise_warning(): X, y",
"0].get_yticklabels()[2].get_text() == 'dabl_mi...' def test_label_truncation(): a = ('a_really_long_name_that_would_mess_up_the_layout_a_lot' '_by_just_being_very_long') b",
"\"LDA 0\" assert axes[0].get_ylabel() == 'LDA 1' def test_plot_string_target(): X,",
"error) # here some random phone numbers assert not guess_ordinal(pd.Series([6786930208,",
"with \"actual float\" - we need to specify classification for",
"'target') with pytest.raises(ValueError, match=\"need categorical\"): plot_classification_continuous(X, 'target') def test_plot_target_low_card_int(): data",
"np.random.uniform(0, 0.1, 1000) res = plot_regression_continuous(df, target_col=b) assert res[0, 0].get_ylabel()",
"# six is the minimum number of features for histograms",
"def test_na_vals_reg_plot_raise_warning(): X, y = load_diabetes(return_X_y=True) X = pd.DataFrame(X) y[::50]",
"'LDA 1' def test_plot_string_target(): X, y = make_blobs(n_samples=30) data =",
"2)) X_cat, y_cat = make_regression( n_samples=n_samples, n_features=categorical_features, n_informative=min(categorical_features, 2)) if",
"+ np.random.uniform(0, 0.1, 1000) res = plot_regression_continuous(df, target_col=b) assert res[0,",
"and 100 \"target\": np.random.randint(low=50, high=100, size=200) } ) # append",
"= plot_classification_continuous(df, target_col='target', random_state=42) # univariate, pairwise, pca, lda assert",
"pytest.warns(UserWarning, match=\"Missing values in target_col have \" \"been removed for",
"'dabl_mi...' def test_label_truncation(): a = ('a_really_long_name_that_would_mess_up_the_layout_a_lot' '_by_just_being_very_long') b = ('the_target_that_has_an_equally_long_name_which_would_'",
"b = ('the_target_that_has_an_equally_long_name_which_would_' 'mess_up_everything_as_well_but_in_different_places') df = pd.DataFrame({a: np.random.uniform(0, 1, 1000)})",
"load_digits() df = data_df_from_bunch(data) plot(df[::10], target_col='target') def test_plot_X_y(): X, y",
"y) def test_plot_regression_numpy(): X, y = make_regression() plot(X, y) def",
"from dabl.utils import data_df_from_bunch from dabl import set_config # FIXME:",
"X = pd.DataFrame(X) plot(X, y, univariate_plot='kde') def test_plot_int_column_name(): X, y",
"2)) if X_cat.shape[1] > 0: X_cat = KBinsDiscretizer(encode='ordinal').fit_transform(X_cat) cont_columns =",
"figures[3].get_axes() assert len(axes) == 4 # known result assert axes[0].get_xlabel()",
"plt.close(\"all\") def test_float_classification_target(): # check we can plot even if",
"known result assert axes[0].get_xlabel() == \"SOD1_N\" assert axes[0].get_ylabel() == 'S6_N'",
"type_hints={0: feature_type, 'target': target_type}, target_col='target') # get title of figure",
"# (last column is target) figures = plot_classification_continuous(df.iloc[:, -7:], target_col='target',",
"y = np.random.uniform(size=n_samples) if task == \"classification\": y = np.digitize(y,",
"axes[0].get_ylabel() == \"\" # pairwise axes = figures[1].get_axes() assert len(axes)",
"= figures[2].get_axes() assert len(axes) == 4 # known result assert",
"y = make_blobs(n_samples=30) data = pd.DataFrame(X) y = pd.Series(y) y[y",
"assert guess_ordinal(data[0]) # smoke test plot(data, target_col=1) def test_large_ordinal(): #",
"y, univariate_plot='kde') def test_plot_int_column_name(): X, y = make_blobs() X =",
"smoke test plot(data, target_col=1) def test_large_ordinal(): # check that large",
"50, \"target\": 0}, ignore_index=True) with pytest.warns( UserWarning, match=\"Dropped 1 outliers",
"= pd.DataFrame(X) plot(X, y) def test_plot_regression_numpy(): X, y = make_regression()",
"= np.digitize(y, np.percentile(y, [5, 10, 60, 85])) X_clean['target'] = y",
"test_plot_classification_n_classes(): X, y = make_blobs() X = pd.DataFrame(X) X['target'] =",
"- 5, np.random.randint(0, 2, size=1000)]).T # ensure first column is",
"types = detect_types(X_clean) column_types = types.T.idxmax() assert np.all(column_types[:continuous_features] == 'continuous')",
"i in range(categorical_features)] df_cat = pd.DataFrame(X_cat, columns=cat_columns).astype('int') df_cat = df_cat.astype(\"category\")",
"'a' df.loc[100:200, 'x'] = 'b' df.loc[200:300, 'x'] = np.NaN res",
"plot(data, target_col='target', type_hints={'target': 'categorical'}) plt.close(\"all\") @pytest.mark.filterwarnings('ignore:Discarding near-constant') def test_plot_classification_n_classes(): X,",
"phone numbers assert not guess_ordinal(pd.Series([6786930208, 2142878625, 9106275431])) def test_plot_classification_continuous(): data",
"== 'dabl_mi...' def test_label_truncation(): a = ('a_really_long_name_that_would_mess_up_the_layout_a_lot' '_by_just_being_very_long') b =",
"# get title of figure text = plt.gcf()._suptitle.get_text() assert feature_type.capitalize()",
"in labels) == (target_type == 'continuous') plt.close(\"all\") def test_float_classification_target(): #",
"len(figures) == 1 # top 10 axes assert len(figures[0].get_axes()) ==",
"two classes\"): plot_classification_categorical(X, 'target') with pytest.raises(ValueError, match=\"Less than two classes\"):",
"result assert axes[0].get_xlabel() == \"PCA 1\" assert axes[0].get_ylabel() == 'PCA",
"target_type): X = pd.DataFrame(np.random.randint(4, size=100)) + add X['target'] = np.random.uniform(size=100)",
"# one of the labels is 'target' iif regression labels",
"5, np.random.randint(0, 2, size=1000)]).T # ensure first column is low_card_int",
"pytest import numpy as np import pandas as pd import",
"= 'b' y[y == 2] = 'c' data['target'] = y",
"= figures[3].get_axes() assert len(axes) == 4 # known result assert",
"column is target) figures = plot_classification_continuous(df.iloc[:, -7:], target_col='target', plot_pairwise=False) assert",
"if task == \"classification\": y = np.digitize(y, np.percentile(y, [5, 10,",
"@pytest.mark.filterwarnings('ignore:Discarding near-constant') def test_plot_classification_n_classes(): X, y = make_blobs() X =",
"= make_regression( n_samples=n_samples, n_features=categorical_features, n_informative=min(categorical_features, 2)) if X_cat.shape[1] > 0:",
"in target_col have \" \"been removed for regression\"): plot(X, 'target_col')",
"plot_regression_continuous(df, target_col=b) assert res[0, 0].get_ylabel() == b assert res[0, 0].get_xlabel()",
"= pd.DataFrame({a: np.random.uniform(0, 1, 1000)}) df[b] = df[a] + np.random.uniform(0,",
"# should be parametrized n_samples = 100 X_cont, y_cont =",
"axes[0].get_xlabel() == \"LDA 0\" assert axes[0].get_ylabel() == 'LDA 1' def",
"else: assert column_types[-1] == 'continuous' plot(X_clean, target_col='target') plt.close(\"all\") @pytest.mark.parametrize(\"add, feature_type,",
"y[y == 2] = 'c' data['target'] = y plot(data, target_col='target')",
"\" \"been removed for regression\"): plot_regression_categorical(X, 'target_col') def test_plot_regression_continuous_with_target_outliers(): df",
"not y but a column name @pytest.mark.filterwarnings('ignore:the matrix subclass') @pytest.mark.parametrize(\"continuous_features,",
"X_df.shape[1] == 0: y = np.random.uniform(size=n_samples) if task == \"classification\":",
"pytest.raises(ValueError, match=\"need continuous\"): plot_regression_categorical(X, 'target') with pytest.raises(ValueError, match=\"need continuous\"): plot_regression_continuous(X,",
"detect_types, guess_ordinal from dabl.plot.supervised import ( plot, plot_classification_categorical, plot_classification_continuous, plot_regression_categorical,",
"be parametrized n_samples = 100 X_cont, y_cont = make_regression( n_samples=n_samples,",
"if task == \"classification\": X_clean['target'] = X_clean['target'].astype('category') types = detect_types(X_clean)",
"(target_type == 'continuous') plt.close(\"all\") def test_float_classification_target(): # check we can",
"len(axes) == 4 # known result assert axes[0].get_xlabel() == \"PCA",
"import set_config # FIXME: check that target is not y",
"set_config # FIXME: check that target is not y but",
"def test_plot_lda_binary(): X, y = make_blobs(centers=2) X = pd.DataFrame(X) plot(X,",
"figures[1].get_axes() assert len(axes) == 4 # known result assert axes[0].get_xlabel()",
"5' # LDA axes = figures[3].get_axes() assert len(axes) == 4",
"1' def test_plot_string_target(): X, y = make_blobs(n_samples=30) data = pd.DataFrame(X)",
"that target is not y but a column name @pytest.mark.filterwarnings('ignore:the",
"assert np.all(column_types[continuous_features:-1] == 'categorical') if task == \"classification\": assert column_types[-1]",
"ignore_index=True) with pytest.warns( UserWarning, match=\"Dropped 1 outliers in column target.\"",
"data = pd.DataFrame([np.random.randint(0, 10, size=1000) - 5, np.random.randint(0, 2, size=1000)]).T",
"['continuous', 'categorical'], ['continuous', 'categorical'])) def test_type_hints(add, feature_type, target_type): X =",
"feature_type.capitalize() in text ax = plt.gca() # one of the",
"axes[0].get_ylabel() == 'LDA 1' def test_plot_string_target(): X, y = make_blobs(n_samples=30)",
"full pairplot figures = plot_classification_continuous(df.iloc[:, -6:], target_col='target', plot_pairwise=False) assert len(figures)",
"len(axes) == 10 # known result assert axes[0].get_xlabel() == \"SOD1_N\"",
"= make_blobs() data = pd.DataFrame(X) data['target'] = y.astype(np.float) types =",
"1 # diagonal has twin axes assert len(figures[0].get_axes()) == 5",
"# known result assert axes[0].get_xlabel() == \"PCA 1\" assert axes[0].get_ylabel()",
"test_type_hints(add, feature_type, target_type): X = pd.DataFrame(np.random.randint(4, size=100)) + add X['target']",
"'b' df.loc[200:300, 'x'] = np.NaN res = plot(df, target_col='y') assert",
"removed for regression\"): plot(X, 'target_col') with pytest.warns(UserWarning, match=\"Missing values in",
"\"target\": 0}, ignore_index=True) with pytest.warns( UserWarning, match=\"Dropped 1 outliers in",
"= df_cont assert(X_df.shape[1] == continuous_features + categorical_features) X_clean = clean(X_df.copy())",
"== 0] = 'a' y[y == 1] = 'b' y[y",
"of features for histograms # (last column is target) figures",
"= pd.DataFrame(X_cat, columns=cat_columns).astype('int') df_cat = df_cat.astype(\"category\") X_df = pd.concat([df_cont, df_cat],",
"target_col=3) def test_negative_ordinal(): # check that a low card int",
"correctly data = pd.DataFrame([np.random.randint(0, 10, size=1000) - 5, np.random.randint(0, 2,",
"== \"SOD1_N\" assert axes[0].get_ylabel() == 'S6_N' # PCA axes =",
"X_cat = KBinsDiscretizer(encode='ordinal').fit_transform(X_cat) cont_columns = [\"asdf_%d_cont\" % i for i",
"assert column_types[-1] == 'continuous' plot(X_clean, target_col='target') plt.close(\"all\") @pytest.mark.parametrize(\"add, feature_type, target_type\",",
"0] = 'a' y[y == 1] = 'b' y[y ==",
"\"actual float\" - we need to specify classification for that",
"df.loc[200:300, 'x'] = np.NaN res = plot(df, target_col='y') assert len(res[1][0,",
"= y if task == \"classification\": X_clean['target'] = X_clean['target'].astype('category') types",
"y[y == 1] = 'b' y[y == 2] = 'c'",
"= [\"asdf_%d_cat\" % i for i in range(categorical_features)] df_cat =",
"from dabl import set_config # FIXME: check that target is",
"known result assert axes[0].get_xlabel() == \"SOD1_N\" # bar plot never",
"X_df = df_cont assert(X_df.shape[1] == continuous_features + categorical_features) X_clean =",
"task == \"classification\": X_clean['target'] = X_clean['target'].astype('category') types = detect_types(X_clean) column_types",
"assert np.all(column_types[:continuous_features] == 'continuous') assert np.all(column_types[continuous_features:-1] == 'categorical') if task",
"== 10 # six is the minimum number of features",
"+ 5 # also do pairwise plots figures = plot_classification_continuous(df,",
"= 'c' data['target'] = y plot(data, target_col='target') def test_na_vals_reg_plot_raise_warning(): X,",
"X = pd.DataFrame(np.random.randint(4, size=100)) + add X['target'] = np.random.uniform(size=100) plot(X,",
"X, y = make_blobs(n_samples=30) data = pd.DataFrame(X) y = pd.Series(y)",
"figures = plot_classification_continuous(df, target_col='target', random_state=42) # univariate, pairwise, pca, lda",
":-/ data['target'] = y.astype(np.float) + .2 plot(data, target_col='target', type_hints={'target': 'categorical'})",
"0: cat_columns = [\"asdf_%d_cat\" % i for i in range(categorical_features)]",
"target_col='target', plot_pairwise=False) assert len(figures) == 1 # top 10 axes",
"plot_regression_continuous(X, 'target') X['target'] = X[0] with pytest.raises(ValueError, match=\"need categorical\"): plot_classification_categorical(X,",
"X = pd.DataFrame(X) X['target'] = y with pytest.raises(ValueError, match=\"need continuous\"):",
"== 4 # known result assert axes[0].get_xlabel() == \"LDA 0\"",
"'continuous' plot(X_clean, target_col='target') plt.close(\"all\") @pytest.mark.parametrize(\"add, feature_type, target_type\", itertools.product([0, .1], ['continuous',",
"values in target_col have \" \"been removed for regression\"): plot_regression_continuous(X,",
"clean(X_df.copy()) y = y_cont + y_cat if X_df.shape[1] == 0:",
"i for i in range(categorical_features)] df_cat = pd.DataFrame(X_cat, columns=cat_columns).astype('int') df_cat",
"axes assert len(figures[0].get_axes()) == 10 # six is the minimum",
"for histograms # (last column is target) figures = plot_classification_continuous(df.iloc[:,",
"if task == \"classification\": assert column_types[-1] == 'categorical' else: assert",
"target_type\", itertools.product([0, .1], ['continuous', 'categorical'], ['continuous', 'categorical'])) def test_type_hints(add, feature_type,",
"low_card_int assert (detect_types(data).T.idxmax() == ['low_card_int', 'categorical']).all() assert guess_ordinal(data[0]) # smoke",
"n_features=categorical_features, n_informative=min(categorical_features, 2)) if X_cat.shape[1] > 0: X_cat = KBinsDiscretizer(encode='ordinal').fit_transform(X_cat)",
"univariate axes = figures[0].get_axes() assert len(axes) == 10 # known",
"+ add X['target'] = np.random.uniform(size=100) plot(X, type_hints={0: feature_type, 'target': target_type},",
"2, size=1000)]).T # ensure first column is low_card_int assert (detect_types(data).T.idxmax()",
"categorical_features, task): # simple smoke test # should be parametrized",
"make_blobs() X = pd.DataFrame(X) X['target'] = 0 with pytest.raises(ValueError, match=\"Less",
"labels is 'target' iif regression labels = ax.get_ylabel() + ax.get_xlabel()",
"pd.DataFrame(X) plot(X, y) def test_plot_regression_numpy(): X, y = make_regression() plot(X,",
"outlier record with target value 0 df = df.append({\"feature\": 50,",
"pd.DataFrame({'y': np.random.normal(size=300)}) df.loc[100:200, 'y'] += 1 df.loc[200:300, 'y'] += 2",
"target_col=1) def test_large_ordinal(): # check that large integers don't bring",
"res[0, 0].get_xlabel() == 'a_really_long_nam...' set_config(truncate_labels=False) res = plot_regression_continuous(df, target_col=b) assert",
"# known result assert axes[0].get_xlabel() == \"SOD1_N\" # bar plot",
"= plot_regression_continuous(df, target_col=b) assert res[0, 0].get_ylabel() == 'the_target_that_h...' assert res[0,",
"('a_really_long_name_that_would_mess_up_the_layout_a_lot' '_by_just_being_very_long') b = ('the_target_that_has_an_equally_long_name_which_would_' 'mess_up_everything_as_well_but_in_different_places') df = pd.DataFrame({a: np.random.uniform(0,",
"pd.DataFrame(X) plot(X, y, univariate_plot='kde') def test_plot_int_column_name(): X, y = make_blobs()",
"with pytest.raises(ValueError, match=\"Less than two classes\"): plot_classification_continuous(X, 'target') def test_plot_wrong_target_type():",
"types.T.idxmax() assert np.all(column_types[:continuous_features] == 'continuous') assert np.all(column_types[continuous_features:-1] == 'categorical') if",
"in text ax = plt.gca() # one of the labels",
"y = make_blobs() data = pd.DataFrame(X) data['target'] = y.astype(np.float) types",
"float\" - we need to specify classification for that :-/",
"+ y_cat if X_df.shape[1] == 0: y = np.random.uniform(size=n_samples) if",
"match=\"need categorical\"): plot_classification_continuous(X, 'target') def test_plot_target_low_card_int(): data = load_digits() df",
"column_types[-1] == 'continuous' plot(X_clean, target_col='target') plt.close(\"all\") @pytest.mark.parametrize(\"add, feature_type, target_type\", itertools.product([0,",
"y with pytest.warns(UserWarning, match=\"Missing values in target_col have \" \"been",
"from dabl.plot.supervised import ( plot, plot_classification_categorical, plot_classification_continuous, plot_regression_categorical, plot_regression_continuous) from",
"'a' y[y == 1] = 'b' y[y == 2] =",
"need to specify classification for that :-/ data['target'] = y.astype(np.float)",
"FIXME: check that target is not y but a column",
"'continuous') plt.close(\"all\") def test_float_classification_target(): # check we can plot even",
"= make_regression( n_samples=n_samples, n_features=continuous_features, n_informative=min(continuous_features, 2)) X_cat, y_cat = make_regression(",
"len(res[1][0, 0].get_yticklabels()) == 3 assert res[1][0, 0].get_yticklabels()[2].get_text() == 'dabl_mi...' def",
"target_col have \" \"been removed for regression\"): plot_regression_categorical(X, 'target_col') def",
"y = make_blobs(centers=2) X = pd.DataFrame(X) plot(X, y, univariate_plot='kde') def",
"assert len(figures) == 4 # univariate axes = figures[0].get_axes() assert",
"y[y == 0] = 'a' y[y == 1] = 'b'",
"'y'] += 2 df['x'] = 'a' df.loc[100:200, 'x'] = 'b'",
"1000) res = plot_regression_continuous(df, target_col=b) assert res[0, 0].get_ylabel() == 'the_target_that_h...'",
"X_df = pd.concat([df_cont, df_cat], axis=1) else: X_df = df_cont assert(X_df.shape[1]",
"pandas as pd import matplotlib.pyplot as plt import itertools from",
"is plotted correctly data = pd.DataFrame([np.random.randint(0, 10, size=1000) - 5,",
"\"classification\": y = np.digitize(y, np.percentile(y, [5, 10, 60, 85])) X_clean['target']",
"result assert axes[0].get_xlabel() == \"LDA 0\" assert axes[0].get_ylabel() == 'LDA",
"high=100, size=200), # target values are bound between 50 and",
"y plot(data, target_col='target') def test_na_vals_reg_plot_raise_warning(): X, y = load_diabetes(return_X_y=True) X",
"assert feature_type.capitalize() in text ax = plt.gca() # one of",
"is the minimum number of features for histograms # (last",
"n_samples=n_samples, n_features=categorical_features, n_informative=min(categorical_features, 2)) if X_cat.shape[1] > 0: X_cat =",
"'mess_up_everything_as_well_but_in_different_places') df = pd.DataFrame({a: np.random.uniform(0, 1, 1000)}) df[b] = df[a]",
"# pairwise axes = figures[1].get_axes() assert len(axes) == 4 #",
"= figures[1].get_axes() assert len(axes) == 4 # known result assert",
"= make_blobs() X = pd.DataFrame(X) X['target'] = y with pytest.raises(ValueError,",
"a = ('a_really_long_name_that_would_mess_up_the_layout_a_lot' '_by_just_being_very_long') b = ('the_target_that_has_an_equally_long_name_which_would_' 'mess_up_everything_as_well_but_in_different_places') df =",
"= make_blobs() X = pd.DataFrame(X) X['target'] = 0 with pytest.raises(ValueError,",
"# check that a low card int with negative values",
"\"been removed for regression\"): plot(X, 'target_col') with pytest.warns(UserWarning, match=\"Missing values",
"= y plot(X, target_col=3) def test_negative_ordinal(): # check that a",
"plot never has ylabel assert axes[0].get_ylabel() == \"\" # pairwise",
"= pd.DataFrame(X) y = pd.Series(y) y[y == 0] = 'a'",
"df_cont assert(X_df.shape[1] == continuous_features + categorical_features) X_clean = clean(X_df.copy()) y",
"[\"asdf_%d_cont\" % i for i in range(continuous_features)] df_cont = pd.DataFrame(X_cont,",
"detect_types(X_clean) column_types = types.T.idxmax() assert np.all(column_types[:continuous_features] == 'continuous') assert np.all(column_types[continuous_features:-1]",
"== 'categorical' else: assert column_types[-1] == 'continuous' plot(X_clean, target_col='target') plt.close(\"all\")",
"plot_classification_categorical(X, 'target') with pytest.raises(ValueError, match=\"need categorical\"): plot_classification_continuous(X, 'target') def test_plot_target_low_card_int():",
"fetch_openml, load_diabetes) from sklearn.preprocessing import KBinsDiscretizer from dabl.preprocessing import clean,",
"match=\"need continuous\"): plot_regression_categorical(X, 'target') with pytest.raises(ValueError, match=\"need continuous\"): plot_regression_continuous(X, 'target')",
"5 * 5 + 5 # also do pairwise plots",
"['continuous', 'categorical'])) def test_type_hints(add, feature_type, target_type): X = pd.DataFrame(np.random.randint(4, size=100))",
"memory error) # here some random phone numbers assert not",
"0.1, 1000) res = plot_regression_continuous(df, target_col=b) assert res[0, 0].get_ylabel() ==",
"import ( plot, plot_classification_categorical, plot_classification_continuous, plot_regression_categorical, plot_regression_continuous) from dabl.utils import",
"): plot_regression_continuous(df, 'target') def test_plot_regression_categorical_missing_value(): df = pd.DataFrame({'y': np.random.normal(size=300)}) df.loc[100:200,",
"have \" \"been removed for regression\"): plot_regression_categorical(X, 'target_col') def test_plot_regression_continuous_with_target_outliers():",
"here some random phone numbers assert not guess_ordinal(pd.Series([6786930208, 2142878625, 9106275431]))",
"= load_digits() df = data_df_from_bunch(data) plot(df[::10], target_col='target') def test_plot_X_y(): X,",
"cat_columns = [\"asdf_%d_cat\" % i for i in range(categorical_features)] df_cat",
"axes = figures[2].get_axes() assert len(axes) == 4 # known result",
"assert len(axes) == 10 # known result assert axes[0].get_xlabel() ==",
"import pytest import numpy as np import pandas as pd",
"load_diabetes(return_X_y=True) X = pd.DataFrame(X) y[::50] = np.NaN X['target_col'] = y",
"test_plot_regression_continuous_with_target_outliers(): df = pd.DataFrame( data={ \"feature\": np.random.randint(low=1, high=100, size=200), #",
"float target X, y = make_blobs() data = pd.DataFrame(X) data['target']",
"pd.DataFrame(X_cont, columns=cont_columns) if categorical_features > 0: cat_columns = [\"asdf_%d_cat\" %",
"plot_classification_continuous(df.iloc[:, -7:], target_col='target', plot_pairwise=False) assert len(figures) == 1 assert len(figures[0].get_axes())",
"bar plot never has ylabel assert axes[0].get_ylabel() == \"\" #",
"== 1] = 'b' y[y == 2] = 'c' data['target']",
"for 5 features, do full pairplot figures = plot_classification_continuous(df.iloc[:, -6:],",
"of the labels is 'target' iif regression labels = ax.get_ylabel()",
"y plot(X, target_col=3) def test_negative_ordinal(): # check that a low",
"= data_df_from_bunch(data) plot(df[::10], target_col='target') def test_plot_X_y(): X, y = make_blobs()",
"== \"classification\": X_clean['target'] = X_clean['target'].astype('category') types = detect_types(X_clean) column_types =",
"== 'continuous') plt.close(\"all\") def test_float_classification_target(): # check we can plot",
"ax = plt.gca() # one of the labels is 'target'",
"np.NaN X['target_col'] = y with pytest.warns(UserWarning, match=\"Missing values in target_col",
"y if task == \"classification\": X_clean['target'] = X_clean['target'].astype('category') types =",
"check that large integers don't bring us down (bincount memory",
"range(continuous_features)] df_cont = pd.DataFrame(X_cont, columns=cont_columns) if categorical_features > 0: cat_columns",
"len(figures[0].get_axes()) == 6 # for 5 features, do full pairplot",
"= X_clean['target'].astype('category') types = detect_types(X_clean) column_types = types.T.idxmax() assert np.all(column_types[:continuous_features]",
"column target.\" ): plot_regression_continuous(df, 'target') def test_plot_regression_categorical_missing_value(): df = pd.DataFrame({'y':",
"== 0: y = np.random.uniform(size=n_samples) if task == \"classification\": y",
"result assert axes[0].get_xlabel() == \"SOD1_N\" # bar plot never has",
"has ylabel assert axes[0].get_ylabel() == \"\" # pairwise axes =",
"X['target'] = np.random.uniform(size=100) plot(X, type_hints={0: feature_type, 'target': target_type}, target_col='target') #",
"pd.DataFrame(X) X['target'] = 0 with pytest.raises(ValueError, match=\"Less than two classes\"):",
"plot_regression_continuous(df, target_col=b) assert res[0, 0].get_ylabel() == 'the_target_that_h...' assert res[0, 0].get_xlabel()",
"for i in range(continuous_features)] df_cont = pd.DataFrame(X_cont, columns=cont_columns) if categorical_features",
"guess_ordinal from dabl.plot.supervised import ( plot, plot_classification_categorical, plot_classification_continuous, plot_regression_categorical, plot_regression_continuous)",
"= clean(X_df.copy()) y = y_cont + y_cat if X_df.shape[1] ==",
"def test_plot_wrong_target_type(): X, y = make_blobs() X = pd.DataFrame(X) X['target']",
"'categorical'}) plt.close(\"all\") @pytest.mark.filterwarnings('ignore:Discarding near-constant') def test_plot_classification_n_classes(): X, y = make_blobs()",
"pytest.raises(ValueError, match=\"need categorical\"): plot_classification_categorical(X, 'target') with pytest.raises(ValueError, match=\"need categorical\"): plot_classification_continuous(X,",
"title of figure text = plt.gcf()._suptitle.get_text() assert feature_type.capitalize() in text",
"2142878625, 9106275431])) def test_plot_classification_continuous(): data = fetch_openml('MiceProtein') df = data_df_from_bunch(data)",
"= np.NaN X['target_col'] = y with pytest.warns(UserWarning, match=\"Missing values in",
"= 100 X_cont, y_cont = make_regression( n_samples=n_samples, n_features=continuous_features, n_informative=min(continuous_features, 2))",
"= y plot(data, target_col='target') def test_na_vals_reg_plot_raise_warning(): X, y = load_diabetes(return_X_y=True)",
"target_col have \" \"been removed for regression\"): plot_regression_continuous(X, 'target_col') with",
"<reponame>nrohan09-cloud/dabl<gh_stars>100-1000 import pytest import numpy as np import pandas as",
"outliers in column target.\" ): plot_regression_continuous(df, 'target') def test_plot_regression_categorical_missing_value(): df",
"df_cat], axis=1) else: X_df = df_cont assert(X_df.shape[1] == continuous_features +",
"def test_label_truncation(): a = ('a_really_long_name_that_would_mess_up_the_layout_a_lot' '_by_just_being_very_long') b = ('the_target_that_has_an_equally_long_name_which_would_' 'mess_up_everything_as_well_but_in_different_places')",
"plotted correctly data = pd.DataFrame([np.random.randint(0, 10, size=1000) - 5, np.random.randint(0,",
"test_plot_lda_binary(): X, y = make_blobs(centers=2) X = pd.DataFrame(X) plot(X, y,",
"10 # six is the minimum number of features for",
"range(categorical_features)] df_cat = pd.DataFrame(X_cat, columns=cat_columns).astype('int') df_cat = df_cat.astype(\"category\") X_df =",
"== 4 # known result assert axes[0].get_xlabel() == \"PCA 1\"",
"values is plotted correctly data = pd.DataFrame([np.random.randint(0, 10, size=1000) -",
"plot(data, target_col=1) def test_large_ordinal(): # check that large integers don't",
"y[::50] = np.NaN X['target_col'] = y with pytest.warns(UserWarning, match=\"Missing values",
"pytest.warns( UserWarning, match=\"Dropped 1 outliers in column target.\" ): plot_regression_continuous(df,",
"continuous_features + categorical_features) X_clean = clean(X_df.copy()) y = y_cont +",
"plot_classification_continuous(df, target_col='target', plot_pairwise=False) assert len(figures) == 1 # top 10",
"== 4 # univariate axes = figures[0].get_axes() assert len(axes) ==",
"pd.DataFrame(X) X[3] = y plot(X, target_col=3) def test_negative_ordinal(): # check",
"1 outliers in column target.\" ): plot_regression_continuous(df, 'target') def test_plot_regression_categorical_missing_value():",
"1 df.loc[200:300, 'y'] += 2 df['x'] = 'a' df.loc[100:200, 'x']",
"== 'the_target_that_h...' assert res[0, 0].get_xlabel() == 'a_really_long_nam...' set_config(truncate_labels=False) res =",
"pca, lda assert len(figures) == 4 # univariate axes =",
"make_blobs() X = pd.DataFrame(X) plot(X, y) def test_plot_regression_numpy(): X, y",
"subclass') @pytest.mark.parametrize(\"continuous_features, categorical_features, task\", itertools.product([0, 1, 3, 100], [0, 1,",
"import data_df_from_bunch from dabl import set_config # FIXME: check that",
"X_clean['target'].astype('category') types = detect_types(X_clean) column_types = types.T.idxmax() assert np.all(column_types[:continuous_features] ==",
"'x'] = np.NaN res = plot(df, target_col='y') assert len(res[1][0, 0].get_yticklabels())",
"'target': target_type}, target_col='target') # get title of figure text =",
"== 1 # top 10 axes assert len(figures[0].get_axes()) == 10",
"with pytest.raises(ValueError, match=\"need categorical\"): plot_classification_continuous(X, 'target') def test_plot_target_low_card_int(): data =",
"'b' y[y == 2] = 'c' data['target'] = y plot(data,",
"test_negative_ordinal(): # check that a low card int with negative",
"len(figures[0].get_axes()) == 5 * 5 + 5 # also do",
"axes = figures[1].get_axes() assert len(axes) == 4 # known result",
"same with \"actual float\" - we need to specify classification",
"has twin axes assert len(figures[0].get_axes()) == 5 * 5 +",
"# univariate, pairwise, pca, lda assert len(figures) == 4 #",
"= plot(df, target_col='y') assert len(res[1][0, 0].get_yticklabels()) == 3 assert res[1][0,",
"df = data_df_from_bunch(data) plot(df[::10], target_col='target') def test_plot_X_y(): X, y =",
"\"target\": np.random.randint(low=50, high=100, size=200) } ) # append single outlier",
"@pytest.mark.filterwarnings('ignore:the matrix subclass') @pytest.mark.parametrize(\"continuous_features, categorical_features, task\", itertools.product([0, 1, 3, 100],",
"n_informative=min(categorical_features, 2)) if X_cat.shape[1] > 0: X_cat = KBinsDiscretizer(encode='ordinal').fit_transform(X_cat) cont_columns",
"known result assert axes[0].get_xlabel() == \"PCA 1\" assert axes[0].get_ylabel() ==",
"= types.T.idxmax() assert np.all(column_types[:continuous_features] == 'continuous') assert np.all(column_types[continuous_features:-1] == 'categorical')",
"pairplot figures = plot_classification_continuous(df.iloc[:, -6:], target_col='target', plot_pairwise=False) assert len(figures) ==",
"0].get_ylabel() == 'the_target_that_h...' assert res[0, 0].get_xlabel() == 'a_really_long_nam...' set_config(truncate_labels=False) res",
"the minimum number of features for histograms # (last column",
"# diagonal has twin axes assert len(figures[0].get_axes()) == 5 *",
"minimum number of features for histograms # (last column is",
"= detect_types(data) assert types.categorical['target'] plot(data, target_col='target') # same with \"actual",
"make_blobs(centers=2) X = pd.DataFrame(X) plot(X, y, univariate_plot='kde') def test_plot_int_column_name(): X,",
"def test_plot_regression_categorical_missing_value(): df = pd.DataFrame({'y': np.random.normal(size=300)}) df.loc[100:200, 'y'] += 1",
"target value 0 df = df.append({\"feature\": 50, \"target\": 0}, ignore_index=True)",
"import (make_regression, make_blobs, load_digits, fetch_openml, load_diabetes) from sklearn.preprocessing import KBinsDiscretizer",
"target_col='target') def test_plot_X_y(): X, y = make_blobs() X = pd.DataFrame(X)",
"X = pd.DataFrame(X) X['target'] = 0 with pytest.raises(ValueError, match=\"Less than",
"target_col='target', plot_pairwise=False) assert len(figures) == 1 assert len(figures[0].get_axes()) == 6",
"# check we can plot even if we do classification",
"'y'] += 1 df.loc[200:300, 'y'] += 2 df['x'] = 'a'",
"plot_regression_continuous(df, 'target') def test_plot_regression_categorical_missing_value(): df = pd.DataFrame({'y': np.random.normal(size=300)}) df.loc[100:200, 'y']",
"target_col='target') plt.close(\"all\") @pytest.mark.parametrize(\"add, feature_type, target_type\", itertools.product([0, .1], ['continuous', 'categorical'], ['continuous',",
"target values are bound between 50 and 100 \"target\": np.random.randint(low=50,",
"== \"LDA 0\" assert axes[0].get_ylabel() == 'LDA 1' def test_plot_string_target():",
"specify classification for that :-/ data['target'] = y.astype(np.float) + .2",
"df = pd.DataFrame( data={ \"feature\": np.random.randint(low=1, high=100, size=200), # target",
"features for histograms # (last column is target) figures =",
"= KBinsDiscretizer(encode='ordinal').fit_transform(X_cat) cont_columns = [\"asdf_%d_cont\" % i for i in",
"'target' iif regression labels = ax.get_ylabel() + ax.get_xlabel() assert ('target'",
"we can plot even if we do classification with a",
"axes[0].get_xlabel() == \"SOD1_N\" assert axes[0].get_ylabel() == 'S6_N' # PCA axes",
"pd import matplotlib.pyplot as plt import itertools from sklearn.datasets import",
"axes[0].get_xlabel() == \"SOD1_N\" # bar plot never has ylabel assert",
"res[0, 0].get_ylabel() == 'the_target_that_h...' assert res[0, 0].get_xlabel() == 'a_really_long_nam...' set_config(truncate_labels=False)",
"len(figures[0].get_axes()) == 10 # six is the minimum number of",
"that a low card int with negative values is plotted",
"test_na_vals_reg_plot_raise_warning(): X, y = load_diabetes(return_X_y=True) X = pd.DataFrame(X) y[::50] =",
"test_large_ordinal(): # check that large integers don't bring us down",
"task\", itertools.product([0, 1, 3, 100], [0, 1, 3, 100], ['classification',",
"plot(df[::10], target_col='target') def test_plot_X_y(): X, y = make_blobs() X =",
"plot(X_clean, target_col='target') plt.close(\"all\") @pytest.mark.parametrize(\"add, feature_type, target_type\", itertools.product([0, .1], ['continuous', 'categorical'],",
"df = pd.DataFrame({'y': np.random.normal(size=300)}) df.loc[100:200, 'y'] += 1 df.loc[200:300, 'y']",
"numbers assert not guess_ordinal(pd.Series([6786930208, 2142878625, 9106275431])) def test_plot_classification_continuous(): data =",
"integers don't bring us down (bincount memory error) # here",
"len(figures) == 4 # univariate axes = figures[0].get_axes() assert len(axes)",
"= plot_regression_continuous(df, target_col=b) assert res[0, 0].get_ylabel() == b assert res[0,",
"match=\"need continuous\"): plot_regression_continuous(X, 'target') X['target'] = X[0] with pytest.raises(ValueError, match=\"need",
"for regression\"): plot_regression_categorical(X, 'target_col') def test_plot_regression_continuous_with_target_outliers(): df = pd.DataFrame( data={",
"= plot_classification_continuous(df, target_col='target', plot_pairwise=False) assert len(figures) == 1 # top",
"test_float_classification_target(): # check we can plot even if we do",
"data = pd.DataFrame(X) data['target'] = y.astype(np.float) types = detect_types(data) assert",
"= y.astype(np.float) + .2 plot(data, target_col='target', type_hints={'target': 'categorical'}) plt.close(\"all\") @pytest.mark.filterwarnings('ignore:Discarding",
"9106275431])) def test_plot_classification_continuous(): data = fetch_openml('MiceProtein') df = data_df_from_bunch(data) #",
"plt.gcf()._suptitle.get_text() assert feature_type.capitalize() in text ax = plt.gca() # one",
"univariate plots figures = plot_classification_continuous(df, target_col='target', plot_pairwise=False) assert len(figures) ==",
"def test_float_classification_target(): # check we can plot even if we",
"plot_pairwise=False) assert len(figures) == 1 # diagonal has twin axes",
"is not y but a column name @pytest.mark.filterwarnings('ignore:the matrix subclass')",
"== ['low_card_int', 'categorical']).all() assert guess_ordinal(data[0]) # smoke test plot(data, target_col=1)",
"60, 85])) X_clean['target'] = y if task == \"classification\": X_clean['target']",
"X_clean = clean(X_df.copy()) y = y_cont + y_cat if X_df.shape[1]",
"def test_type_hints(add, feature_type, target_type): X = pd.DataFrame(np.random.randint(4, size=100)) + add",
"do pairwise plots figures = plot_classification_continuous(df, target_col='target', random_state=42) # univariate,",
"# univariate axes = figures[0].get_axes() assert len(axes) == 10 #",
"X, y = make_blobs(centers=2) X = pd.DataFrame(X) plot(X, y, univariate_plot='kde')",
"\"been removed for regression\"): plot_regression_categorical(X, 'target_col') def test_plot_regression_continuous_with_target_outliers(): df =",
"= pd.DataFrame(X) y[::50] = np.NaN X['target_col'] = y with pytest.warns(UserWarning,",
"plot_regression_categorical(X, 'target_col') def test_plot_regression_continuous_with_target_outliers(): df = pd.DataFrame( data={ \"feature\": np.random.randint(low=1,",
"assert axes[0].get_xlabel() == \"SOD1_N\" # bar plot never has ylabel",
"set_config(truncate_labels=False) res = plot_regression_continuous(df, target_col=b) assert res[0, 0].get_ylabel() == b",
"bound between 50 and 100 \"target\": np.random.randint(low=50, high=100, size=200) }",
"= ('a_really_long_name_that_would_mess_up_the_layout_a_lot' '_by_just_being_very_long') b = ('the_target_that_has_an_equally_long_name_which_would_' 'mess_up_everything_as_well_but_in_different_places') df = pd.DataFrame({a:",
"get title of figure text = plt.gcf()._suptitle.get_text() assert feature_type.capitalize() in",
"check that a low card int with negative values is",
"assert axes[0].get_ylabel() == \"\" # pairwise axes = figures[1].get_axes() assert",
"feature_type, target_type): X = pd.DataFrame(np.random.randint(4, size=100)) + add X['target'] =",
"if X_df.shape[1] == 0: y = np.random.uniform(size=n_samples) if task ==",
"plot(X, type_hints={0: feature_type, 'target': target_type}, target_col='target') # get title of",
"pairwise, pca, lda assert len(figures) == 4 # univariate axes",
"3, 100], ['classification', 'regression'])) def test_plots_smoke(continuous_features, categorical_features, task): # simple",
"with pytest.raises(ValueError, match=\"Less than two classes\"): plot_classification_categorical(X, 'target') with pytest.raises(ValueError,",
"record with target value 0 df = df.append({\"feature\": 50, \"target\":",
"LDA axes = figures[3].get_axes() assert len(axes) == 4 # known",
"large integers don't bring us down (bincount memory error) #",
"plots figures = plot_classification_continuous(df, target_col='target', random_state=42) # univariate, pairwise, pca,",
"0].get_xlabel() == 'a_really_long_nam...' set_config(truncate_labels=False) res = plot_regression_continuous(df, target_col=b) assert res[0,"
] |
[
"# Put the tie broken ones in a list paretto_optimal_tie_break",
"print(it[i]['mapping']) # print(it[i]['q_value']) # For each environment. get the rank",
"LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A",
"there for i in range(len(it2)): env = it2[i]['mapping'] if environment",
"each environment. get the rank in the other experiments and",
"in dict_list: # Find its rank there for i in",
"in dict_list[0]: for it2 in dict_list[0]: if len([i for i,",
"it up for each victim(experiment) for it2 in dict_list: #",
"import sys import json from pprint import pprint class CalculateRank(object):",
"was no tie breaking\") if __name__ == \"__main__\": if len(sys.argv)",
"# print() # for i in range(len(it)): # print(it[i]['mapping']) #",
"no tie breaking\") if __name__ == \"__main__\": if len(sys.argv) !=",
"If there are ties, try to break them at fewer",
"= rank_list # Identify the ones that are not Pareto",
"for it in dict_list: # print() # print() # for",
"TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR",
"broken ones in a list paretto_optimal_tie_break = list() for it",
"= json.load(data_file) # Sort all the configurations in a list",
"i > j]) == len(it1['rank']): rank_list_bad.append(it1) # Put the Pareto",
"a list paretto_optimal = list() for it in dict_list[0]: if",
"rights # to use, copy, modify, merge, publish, distribute, sublicense,",
"print() # print() # for i in range(len(it)): # print(it[i]['mapping'])",
"in paretto_optimal: if not (it in rank_list_bad): paretto_optimal_tie_break.append(it) print(\"With no",
"<NAME>, <NAME>, <NAME> # Permission is hereby granted, free of",
"= list(sorted(ranked_list.values(), key=lambda x:x['q_value'], reverse=True)) dict_list.append(od) # for it in",
"it['rank'] = rank_list # Identify the ones that are not",
"environment. get the rank in the other experiments and store",
"# Find its rank there for i in range(len(it2)): env",
"= list() for it1 in paretto_optimal: for it2 in paretto_optimal:",
"and store in 'rank' for it in dict_list[0]: environment =",
"if environment == env: rank_here = i break rank_list.append(rank_here) it['rank']",
"list() # Look it up for each victim(experiment) for it2",
"for it2 in dict_list[0]: if len([i for i, j in",
"store in 'rank' for it in dict_list[0]: environment = it['mapping']",
"and associated documentation files (the \"Software\"), to deal # in",
"Software without restriction, including without limitation the rights # to",
"and to permit persons to whom the Software is #",
"copies of the Software, and to permit persons to whom",
"hereby granted, free of charge, to any person obtaining a",
"file with open(self._input_file) as data_file: experiments_object = json.load(data_file) # Sort",
"# Put the Pareto Optimal in a list paretto_optimal =",
"in all #copies or substantial portions of the Software. #",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE",
"distribute, sublicense, and/or sell # copies of the Software, and",
"print(it[i]['q_value']) # For each environment. get the rank in the",
"list() for it1 in dict_list[0]: for it2 in dict_list[0]: if",
"rank_list_bad): paretto_optimal_tie_break.append(it) print(\"With no tie breaking\") for i in range(len(paretto_optimal)):",
"fewer comparisons if len(paretto_optimal) > 1: rank_list_bad = list() for",
"OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"the rank in the other experiments and store in 'rank'",
"HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #",
"paretto_optimal_tie_break = list() for it in paretto_optimal: if not (it",
"env = it2[i]['mapping'] if environment == env: rank_here = i",
"tie breaking\") if __name__ == \"__main__\": if len(sys.argv) != 2:",
"the JSON file with open(self._input_file) as data_file: experiments_object = json.load(data_file)",
"rank_here = i break rank_list.append(rank_here) it['rank'] = rank_list # Identify",
"experiments_object[experiment][\"it\"] od = list(sorted(ranked_list.values(), key=lambda x:x['q_value'], reverse=True)) dict_list.append(od) # for",
"rank_list_bad = list() for it1 in dict_list[0]: for it2 in",
"for it in dict_list[0]: if not (it in rank_list_bad): paretto_optimal.append(it)",
"OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH",
"rank_list_bad.append(it1) # Put the tie broken ones in a list",
"\" + sys.argv[0] + \" <ranked_environments>.json\\n\") exit(1) rank = CalculateRank(sys.argv[1])",
"deal # in the Software without restriction, including without limitation",
"use, copy, modify, merge, publish, distribute, sublicense, and/or sell #",
"optimal rank_list_bad = list() for it1 in dict_list[0]: for it2",
"# SOFTWARE. ################################################################################ import sys import json from pprint import",
"environment = it['mapping'] rank_list = list() # Look it up",
"tie breaking\") for i in range(len(paretto_optimal_tie_break)): print(paretto_optimal_tie_break[i]['mapping']) else: print(paretto_optimal[0]['mapping']) print(\"There",
"copy, modify, merge, publish, distribute, sublicense, and/or sell # copies",
"# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR",
"IN THE # SOFTWARE. ################################################################################ import sys import json from",
"= list() # Look it up for each victim(experiment) for",
"software and associated documentation files (the \"Software\"), to deal #",
"in range(len(paretto_optimal_tie_break)): print(paretto_optimal_tie_break[i]['mapping']) else: print(paretto_optimal[0]['mapping']) print(\"There was no tie breaking\")",
"get the rank in the other experiments and store in",
"if len(sys.argv) != 2: print(\"usage: \" + sys.argv[0] + \"",
"it2 in paretto_optimal: if len([i for i, j in zip(it1['rank'],",
"# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF",
"AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR",
"the Software without restriction, including without limitation the rights #",
"# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"in the JSON file with open(self._input_file) as data_file: experiments_object =",
"try to break them at fewer comparisons if len(paretto_optimal) >",
"\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #",
"it2['rank']) if i > j]) == len(it1['rank']) - 1: rank_list_bad.append(it1)",
"ranked_list = experiments_object[experiment][\"it\"] od = list(sorted(ranked_list.values(), key=lambda x:x['q_value'], reverse=True)) dict_list.append(od)",
"it in paretto_optimal: if not (it in rank_list_bad): paretto_optimal_tie_break.append(it) print(\"With",
"# print(it[i]['mapping']) # print(it[i]['q_value']) # For each environment. get the",
"For each environment. get the rank in the other experiments",
"if len([i for i, j in zip(it1['rank'], it2['rank']) if i",
"dict_list: # print() # print() # for i in range(len(it)):",
"i break rank_list.append(rank_here) it['rank'] = rank_list # Identify the ones",
"# of this software and associated documentation files (the \"Software\"),",
"furnished to do so, subject to the following conditions: #",
"# The above copyright notice and this permission notice shall",
"SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR",
"a copy # of this software and associated documentation files",
"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF",
"if i > j]) == len(it1['rank']) - 1: rank_list_bad.append(it1) #",
"not (it in rank_list_bad): paretto_optimal_tie_break.append(it) print(\"With no tie breaking\") for",
"input_file): self._input_file = input_file def get_rank(self): # Read the configuration",
"# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO",
"dict_list = list() for experiment in experiments_object: ranked_list = experiments_object[experiment][\"it\"]",
"> j]) == len(it1['rank']) - 1: rank_list_bad.append(it1) # Put the",
"IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"import pprint class CalculateRank(object): def __init__(self, input_file): self._input_file = input_file",
"it2 in dict_list[0]: if len([i for i, j in zip(it1['rank'],",
"rank_list_bad = list() for it1 in paretto_optimal: for it2 in",
"__init__(self, input_file): self._input_file = input_file def get_rank(self): # Read the",
"for i in range(len(paretto_optimal_tie_break)): print(paretto_optimal_tie_break[i]['mapping']) else: print(paretto_optimal[0]['mapping']) print(\"There was no",
"experiment in experiments_object: ranked_list = experiments_object[experiment][\"it\"] od = list(sorted(ranked_list.values(), key=lambda",
"NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE",
"paretto_optimal = list() for it in dict_list[0]: if not (it",
"# Read the configuration in the JSON file with open(self._input_file)",
"to deal # in the Software without restriction, including without",
"rank_list_bad.append(it1) # Put the Pareto Optimal in a list paretto_optimal",
"SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #",
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
"IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS",
"paretto_optimal: if not (it in rank_list_bad): paretto_optimal_tie_break.append(it) print(\"With no tie",
"dict_list[0]: if len([i for i, j in zip(it1['rank'], it2['rank']) if",
"FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN",
"len([i for i, j in zip(it1['rank'], it2['rank']) if i >",
"1: rank_list_bad.append(it1) # Put the tie broken ones in a",
"\"__main__\": if len(sys.argv) != 2: print(\"usage: \" + sys.argv[0] +",
"it1 in paretto_optimal: for it2 in paretto_optimal: if len([i for",
"range(len(it)): # print(it[i]['mapping']) # print(it[i]['q_value']) # For each environment. get",
"################################################################################ # Copyright (c) 2017 <NAME>, <NAME>, <NAME> # Permission",
"range(len(paretto_optimal)): print(paretto_optimal[i]['mapping']) print(\"With tie breaking\") for i in range(len(paretto_optimal_tie_break)): print(paretto_optimal_tie_break[i]['mapping'])",
"in the other experiments and store in 'rank' for it",
"the Pareto Optimal in a list paretto_optimal = list() for",
"Pareto Optimal in a list paretto_optimal = list() for it",
"i in range(len(paretto_optimal)): print(paretto_optimal[i]['mapping']) print(\"With tie breaking\") for i in",
"list paretto_optimal_tie_break = list() for it in paretto_optimal: if not",
"and/or sell # copies of the Software, and to permit",
"the rights # to use, copy, modify, merge, publish, distribute,",
"all the configurations in a list dict_list = list() for",
"for it2 in paretto_optimal: if len([i for i, j in",
"# for i in range(len(it)): # print(it[i]['mapping']) # print(it[i]['q_value']) #",
"conditions: # The above copyright notice and this permission notice",
"notice and this permission notice shall be included in all",
"Software. # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY",
"is hereby granted, free of charge, to any person obtaining",
"range(len(paretto_optimal_tie_break)): print(paretto_optimal_tie_break[i]['mapping']) else: print(paretto_optimal[0]['mapping']) print(\"There was no tie breaking\") if",
"else: print(paretto_optimal[0]['mapping']) print(\"There was no tie breaking\") if __name__ ==",
"= list() for it in dict_list[0]: if not (it in",
"no tie breaking\") for i in range(len(paretto_optimal)): print(paretto_optimal[i]['mapping']) print(\"With tie",
"as data_file: experiments_object = json.load(data_file) # Sort all the configurations",
"def __init__(self, input_file): self._input_file = input_file def get_rank(self): # Read",
"ties, try to break them at fewer comparisons if len(paretto_optimal)",
"CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR",
"person obtaining a copy # of this software and associated",
"without restriction, including without limitation the rights # to use,",
"for it1 in dict_list[0]: for it2 in dict_list[0]: if len([i",
"so, subject to the following conditions: # The above copyright",
"'rank' for it in dict_list[0]: environment = it['mapping'] rank_list =",
"OR OTHER DEALINGS IN THE # SOFTWARE. ################################################################################ import sys",
"env: rank_here = i break rank_list.append(rank_here) it['rank'] = rank_list #",
"in range(len(it)): # print(it[i]['mapping']) # print(it[i]['q_value']) # For each environment.",
"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN",
"environment == env: rank_here = i break rank_list.append(rank_here) it['rank'] =",
"THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE",
"dict_list[0]: for it2 in dict_list[0]: if len([i for i, j",
"+ sys.argv[0] + \" <ranked_environments>.json\\n\") exit(1) rank = CalculateRank(sys.argv[1]) rank.get_rank()",
"JSON file with open(self._input_file) as data_file: experiments_object = json.load(data_file) #",
"BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL",
"DEALINGS IN THE # SOFTWARE. ################################################################################ import sys import json",
"OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR",
"experiments and store in 'rank' for it in dict_list[0]: environment",
"break rank_list.append(rank_here) it['rank'] = rank_list # Identify the ones that",
"permission notice shall be included in all #copies or substantial",
"key=lambda x:x['q_value'], reverse=True)) dict_list.append(od) # for it in dict_list: #",
"CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS",
"IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER",
"CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION",
"in rank_list_bad): paretto_optimal.append(it) # If there are ties, try to",
"# Permission is hereby granted, free of charge, to any",
"of charge, to any person obtaining a copy # of",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #",
"merge, publish, distribute, sublicense, and/or sell # copies of the",
"it2 in dict_list: # Find its rank there for i",
"len(sys.argv) != 2: print(\"usage: \" + sys.argv[0] + \" <ranked_environments>.json\\n\")",
"list dict_list = list() for experiment in experiments_object: ranked_list =",
"experiments_object: ranked_list = experiments_object[experiment][\"it\"] od = list(sorted(ranked_list.values(), key=lambda x:x['q_value'], reverse=True))",
"tie breaking\") for i in range(len(paretto_optimal)): print(paretto_optimal[i]['mapping']) print(\"With tie breaking\")",
"== env: rank_here = i break rank_list.append(rank_here) it['rank'] = rank_list",
"NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT",
"configuration in the JSON file with open(self._input_file) as data_file: experiments_object",
"i in range(len(it2)): env = it2[i]['mapping'] if environment == env:",
"of the Software. # THE SOFTWARE IS PROVIDED \"AS IS\",",
"victim(experiment) for it2 in dict_list: # Find its rank there",
"NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR",
"breaking\") for i in range(len(paretto_optimal_tie_break)): print(paretto_optimal_tie_break[i]['mapping']) else: print(paretto_optimal[0]['mapping']) print(\"There was",
"or substantial portions of the Software. # THE SOFTWARE IS",
"be included in all #copies or substantial portions of the",
"# For each environment. get the rank in the other",
"<NAME>, <NAME> # Permission is hereby granted, free of charge,",
"list() for it1 in paretto_optimal: for it2 in paretto_optimal: if",
"Look it up for each victim(experiment) for it2 in dict_list:",
"for i in range(len(paretto_optimal)): print(paretto_optimal[i]['mapping']) print(\"With tie breaking\") for i",
"CalculateRank(object): def __init__(self, input_file): self._input_file = input_file def get_rank(self): #",
"__name__ == \"__main__\": if len(sys.argv) != 2: print(\"usage: \" +",
"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER",
"dict_list[0]: if not (it in rank_list_bad): paretto_optimal.append(it) # If there",
"== \"__main__\": if len(sys.argv) != 2: print(\"usage: \" + sys.argv[0]",
"!= 2: print(\"usage: \" + sys.argv[0] + \" <ranked_environments>.json\\n\") exit(1)",
"print(\"usage: \" + sys.argv[0] + \" <ranked_environments>.json\\n\") exit(1) rank =",
"i in range(len(it)): # print(it[i]['mapping']) # print(it[i]['q_value']) # For each",
"other experiments and store in 'rank' for it in dict_list[0]:",
"configurations in a list dict_list = list() for experiment in",
"AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #",
"Optimal in a list paretto_optimal = list() for it in",
"paretto_optimal: for it2 in paretto_optimal: if len([i for i, j",
"DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF",
"for it1 in paretto_optimal: for it2 in paretto_optimal: if len([i",
"to break them at fewer comparisons if len(paretto_optimal) > 1:",
"USE OR OTHER DEALINGS IN THE # SOFTWARE. ################################################################################ import",
"FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE",
"= i break rank_list.append(rank_here) it['rank'] = rank_list # Identify the",
"the tie broken ones in a list paretto_optimal_tie_break = list()",
"pprint class CalculateRank(object): def __init__(self, input_file): self._input_file = input_file def",
"od = list(sorted(ranked_list.values(), key=lambda x:x['q_value'], reverse=True)) dict_list.append(od) # for it",
"substantial portions of the Software. # THE SOFTWARE IS PROVIDED",
"for it2 in dict_list: # Find its rank there for",
"Read the configuration in the JSON file with open(self._input_file) as",
"the Software, and to permit persons to whom the Software",
"- 1: rank_list_bad.append(it1) # Put the tie broken ones in",
"i in range(len(paretto_optimal_tie_break)): print(paretto_optimal_tie_break[i]['mapping']) else: print(paretto_optimal[0]['mapping']) print(\"There was no tie",
"break them at fewer comparisons if len(paretto_optimal) > 1: rank_list_bad",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT",
"persons to whom the Software is # furnished to do",
"following conditions: # The above copyright notice and this permission",
"associated documentation files (the \"Software\"), to deal # in the",
"the following conditions: # The above copyright notice and this",
"MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN",
"j in zip(it1['rank'], it2['rank']) if i > j]) == len(it1['rank']):",
"print(paretto_optimal[0]['mapping']) print(\"There was no tie breaking\") if __name__ == \"__main__\":",
"1: rank_list_bad = list() for it1 in paretto_optimal: for it2",
"to any person obtaining a copy # of this software",
"each victim(experiment) for it2 in dict_list: # Find its rank",
"print() # for i in range(len(it)): # print(it[i]['mapping']) # print(it[i]['q_value'])",
"2: print(\"usage: \" + sys.argv[0] + \" <ranked_environments>.json\\n\") exit(1) rank",
"ones in a list paretto_optimal_tie_break = list() for it in",
"# print(it[i]['q_value']) # For each environment. get the rank in",
"dict_list[0]: environment = it['mapping'] rank_list = list() # Look it",
"in range(len(it2)): env = it2[i]['mapping'] if environment == env: rank_here",
"in dict_list[0]: if not (it in rank_list_bad): paretto_optimal.append(it) # If",
"of the Software, and to permit persons to whom the",
"this software and associated documentation files (the \"Software\"), to deal",
"ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN",
"in zip(it1['rank'], it2['rank']) if i > j]) == len(it1['rank']): rank_list_bad.append(it1)",
"BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY,",
"SOFTWARE. ################################################################################ import sys import json from pprint import pprint",
"= list() for experiment in experiments_object: ranked_list = experiments_object[experiment][\"it\"] od",
"= it2[i]['mapping'] if environment == env: rank_here = i break",
"Software is # furnished to do so, subject to the",
"rank there for i in range(len(it2)): env = it2[i]['mapping'] if",
"open(self._input_file) as data_file: experiments_object = json.load(data_file) # Sort all the",
"PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
"== len(it1['rank']): rank_list_bad.append(it1) # Put the Pareto Optimal in a",
"to do so, subject to the following conditions: # The",
"whom the Software is # furnished to do so, subject",
"ones that are not Pareto optimal rank_list_bad = list() for",
"sublicense, and/or sell # copies of the Software, and to",
"if len(paretto_optimal) > 1: rank_list_bad = list() for it1 in",
"print(\"With tie breaking\") for i in range(len(paretto_optimal_tie_break)): print(paretto_optimal_tie_break[i]['mapping']) else: print(paretto_optimal[0]['mapping'])",
"paretto_optimal: if len([i for i, j in zip(it1['rank'], it2['rank']) if",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY",
"zip(it1['rank'], it2['rank']) if i > j]) == len(it1['rank']): rank_list_bad.append(it1) #",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING",
"in the Software without restriction, including without limitation the rights",
"for i in range(len(it)): # print(it[i]['mapping']) # print(it[i]['q_value']) # For",
"# furnished to do so, subject to the following conditions:",
"any person obtaining a copy # of this software and",
"the Software. # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT",
"ARISING FROM, # OUT OF OR IN CONNECTION WITH THE",
"pprint import pprint class CalculateRank(object): def __init__(self, input_file): self._input_file =",
"SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
"in experiments_object: ranked_list = experiments_object[experiment][\"it\"] od = list(sorted(ranked_list.values(), key=lambda x:x['q_value'],",
"KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO",
"list() for it in paretto_optimal: if not (it in rank_list_bad):",
"json from pprint import pprint class CalculateRank(object): def __init__(self, input_file):",
"OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"2017 <NAME>, <NAME>, <NAME> # Permission is hereby granted, free",
"restriction, including without limitation the rights # to use, copy,",
"<NAME> # Permission is hereby granted, free of charge, to",
"from pprint import pprint class CalculateRank(object): def __init__(self, input_file): self._input_file",
"len(it1['rank']): rank_list_bad.append(it1) # Put the Pareto Optimal in a list",
"including without limitation the rights # to use, copy, modify,",
"# If there are ties, try to break them at",
"copyright notice and this permission notice shall be included in",
"= it['mapping'] rank_list = list() # Look it up for",
"ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED",
"free of charge, to any person obtaining a copy #",
"files (the \"Software\"), to deal # in the Software without",
"json.load(data_file) # Sort all the configurations in a list dict_list",
"<reponame>daniel-theis/multicore-test-harness ################################################################################ # Copyright (c) 2017 <NAME>, <NAME>, <NAME> #",
"the configuration in the JSON file with open(self._input_file) as data_file:",
"= list() for it1 in dict_list[0]: for it2 in dict_list[0]:",
"in paretto_optimal: for it2 in paretto_optimal: if len([i for i,",
"in zip(it1['rank'], it2['rank']) if i > j]) == len(it1['rank']) -",
"included in all #copies or substantial portions of the Software.",
"for each victim(experiment) for it2 in dict_list: # Find its",
"the configurations in a list dict_list = list() for experiment",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
"input_file def get_rank(self): # Read the configuration in the JSON",
"Pareto optimal rank_list_bad = list() for it1 in dict_list[0]: for",
"get_rank(self): # Read the configuration in the JSON file with",
"rank_list.append(rank_here) it['rank'] = rank_list # Identify the ones that are",
"def get_rank(self): # Read the configuration in the JSON file",
"in a list paretto_optimal_tie_break = list() for it in paretto_optimal:",
"breaking\") if __name__ == \"__main__\": if len(sys.argv) != 2: print(\"usage:",
"print(\"With no tie breaking\") for i in range(len(paretto_optimal)): print(paretto_optimal[i]['mapping']) print(\"With",
"rank_list # Identify the ones that are not Pareto optimal",
"# for it in dict_list: # print() # print() #",
"> j]) == len(it1['rank']): rank_list_bad.append(it1) # Put the Pareto Optimal",
"at fewer comparisons if len(paretto_optimal) > 1: rank_list_bad = list()",
"for it in paretto_optimal: if not (it in rank_list_bad): paretto_optimal_tie_break.append(it)",
"of this software and associated documentation files (the \"Software\"), to",
"OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR",
"OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE",
"# Sort all the configurations in a list dict_list =",
"for experiment in experiments_object: ranked_list = experiments_object[experiment][\"it\"] od = list(sorted(ranked_list.values(),",
"if not (it in rank_list_bad): paretto_optimal_tie_break.append(it) print(\"With no tie breaking\")",
"THE USE OR OTHER DEALINGS IN THE # SOFTWARE. ################################################################################",
"EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE",
"print(paretto_optimal_tie_break[i]['mapping']) else: print(paretto_optimal[0]['mapping']) print(\"There was no tie breaking\") if __name__",
"paretto_optimal_tie_break.append(it) print(\"With no tie breaking\") for i in range(len(paretto_optimal)): print(paretto_optimal[i]['mapping'])",
"# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,",
"not Pareto optimal rank_list_bad = list() for it1 in dict_list[0]:",
"PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS",
"list paretto_optimal = list() for it in dict_list[0]: if not",
"a list paretto_optimal_tie_break = list() for it in paretto_optimal: if",
"for it in dict_list[0]: environment = it['mapping'] rank_list = list()",
"breaking\") for i in range(len(paretto_optimal)): print(paretto_optimal[i]['mapping']) print(\"With tie breaking\") for",
"(the \"Software\"), to deal # in the Software without restriction,",
"print(paretto_optimal[i]['mapping']) print(\"With tie breaking\") for i in range(len(paretto_optimal_tie_break)): print(paretto_optimal_tie_break[i]['mapping']) else:",
"that are not Pareto optimal rank_list_bad = list() for it1",
"there are ties, try to break them at fewer comparisons",
"#copies or substantial portions of the Software. # THE SOFTWARE",
"WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND",
"if i > j]) == len(it1['rank']): rank_list_bad.append(it1) # Put the",
"j in zip(it1['rank'], it2['rank']) if i > j]) == len(it1['rank'])",
"charge, to any person obtaining a copy # of this",
"permit persons to whom the Software is # furnished to",
"to the following conditions: # The above copyright notice and",
"THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE",
"the Software is # furnished to do so, subject to",
"do so, subject to the following conditions: # The above",
"in a list paretto_optimal = list() for it in dict_list[0]:",
"above copyright notice and this permission notice shall be included",
"IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED,",
"len(paretto_optimal) > 1: rank_list_bad = list() for it1 in paretto_optimal:",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",
"limitation the rights # to use, copy, modify, merge, publish,",
"it1 in dict_list[0]: for it2 in dict_list[0]: if len([i for",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #",
"in dict_list[0]: if len([i for i, j in zip(it1['rank'], it2['rank'])",
"list(sorted(ranked_list.values(), key=lambda x:x['q_value'], reverse=True)) dict_list.append(od) # for it in dict_list:",
"without limitation the rights # to use, copy, modify, merge,",
"== len(it1['rank']) - 1: rank_list_bad.append(it1) # Put the tie broken",
"portions of the Software. # THE SOFTWARE IS PROVIDED \"AS",
"if not (it in rank_list_bad): paretto_optimal.append(it) # If there are",
"len(it1['rank']) - 1: rank_list_bad.append(it1) # Put the tie broken ones",
"EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE",
"sys import json from pprint import pprint class CalculateRank(object): def",
"# in the Software without restriction, including without limitation the",
"documentation files (the \"Software\"), to deal # in the Software",
"and this permission notice shall be included in all #copies",
"in dict_list[0]: environment = it['mapping'] rank_list = list() # Look",
"them at fewer comparisons if len(paretto_optimal) > 1: rank_list_bad =",
"it in dict_list[0]: if not (it in rank_list_bad): paretto_optimal.append(it) #",
"reverse=True)) dict_list.append(od) # for it in dict_list: # print() #",
"(it in rank_list_bad): paretto_optimal_tie_break.append(it) print(\"With no tie breaking\") for i",
"all #copies or substantial portions of the Software. # THE",
"ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT",
"sell # copies of the Software, and to permit persons",
"OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT",
"Identify the ones that are not Pareto optimal rank_list_bad =",
"= experiments_object[experiment][\"it\"] od = list(sorted(ranked_list.values(), key=lambda x:x['q_value'], reverse=True)) dict_list.append(od) #",
"OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT,",
"tie broken ones in a list paretto_optimal_tie_break = list() for",
"this permission notice shall be included in all #copies or",
"publish, distribute, sublicense, and/or sell # copies of the Software,",
"range(len(it2)): env = it2[i]['mapping'] if environment == env: rank_here =",
"import json from pprint import pprint class CalculateRank(object): def __init__(self,",
"in a list dict_list = list() for experiment in experiments_object:",
"Find its rank there for i in range(len(it2)): env =",
"experiments_object = json.load(data_file) # Sort all the configurations in a",
"list() for experiment in experiments_object: ranked_list = experiments_object[experiment][\"it\"] od =",
"modify, merge, publish, distribute, sublicense, and/or sell # copies of",
"notice shall be included in all #copies or substantial portions",
"OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION",
"are ties, try to break them at fewer comparisons if",
"it2['rank']) if i > j]) == len(it1['rank']): rank_list_bad.append(it1) # Put",
"IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"Software, and to permit persons to whom the Software is",
"for i in range(len(it2)): env = it2[i]['mapping'] if environment ==",
"# to use, copy, modify, merge, publish, distribute, sublicense, and/or",
"in rank_list_bad): paretto_optimal_tie_break.append(it) print(\"With no tie breaking\") for i in",
"rank in the other experiments and store in 'rank' for",
"# Look it up for each victim(experiment) for it2 in",
"OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT",
"= input_file def get_rank(self): # Read the configuration in the",
"i, j in zip(it1['rank'], it2['rank']) if i > j]) ==",
"rank_list_bad): paretto_optimal.append(it) # If there are ties, try to break",
"Put the tie broken ones in a list paretto_optimal_tie_break =",
"in range(len(paretto_optimal)): print(paretto_optimal[i]['mapping']) print(\"With tie breaking\") for i in range(len(paretto_optimal_tie_break)):",
"zip(it1['rank'], it2['rank']) if i > j]) == len(it1['rank']) - 1:",
"\"Software\"), to deal # in the Software without restriction, including",
"data_file: experiments_object = json.load(data_file) # Sort all the configurations in",
"Copyright (c) 2017 <NAME>, <NAME>, <NAME> # Permission is hereby",
"it in dict_list[0]: environment = it['mapping'] rank_list = list() #",
"list() for it in dict_list[0]: if not (it in rank_list_bad):",
"> 1: rank_list_bad = list() for it1 in paretto_optimal: for",
"dict_list: # Find its rank there for i in range(len(it2)):",
"# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR",
"Put the Pareto Optimal in a list paretto_optimal = list()",
"j]) == len(it1['rank']) - 1: rank_list_bad.append(it1) # Put the tie",
"# Copyright (c) 2017 <NAME>, <NAME>, <NAME> # Permission is",
"(it in rank_list_bad): paretto_optimal.append(it) # If there are ties, try",
"a list dict_list = list() for experiment in experiments_object: ranked_list",
"(c) 2017 <NAME>, <NAME>, <NAME> # Permission is hereby granted,",
"COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"j]) == len(it1['rank']): rank_list_bad.append(it1) # Put the Pareto Optimal in",
"dict_list.append(od) # for it in dict_list: # print() # print()",
"= list() for it in paretto_optimal: if not (it in",
"################################################################################ import sys import json from pprint import pprint class",
"with open(self._input_file) as data_file: experiments_object = json.load(data_file) # Sort all",
"# copies of the Software, and to permit persons to",
"print(\"There was no tie breaking\") if __name__ == \"__main__\": if",
"it['mapping'] rank_list = list() # Look it up for each",
"granted, free of charge, to any person obtaining a copy",
"in dict_list: # print() # print() # for i in",
"obtaining a copy # of this software and associated documentation",
"the ones that are not Pareto optimal rank_list_bad = list()",
"for i, j in zip(it1['rank'], it2['rank']) if i > j])",
"TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN",
"is # furnished to do so, subject to the following",
"to whom the Software is # furnished to do so,",
"copy # of this software and associated documentation files (the",
"it2[i]['mapping'] if environment == env: rank_here = i break rank_list.append(rank_here)",
"not (it in rank_list_bad): paretto_optimal.append(it) # If there are ties,",
"THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY",
"OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE.",
"Permission is hereby granted, free of charge, to any person",
"up for each victim(experiment) for it2 in dict_list: # Find",
"paretto_optimal.append(it) # If there are ties, try to break them",
"x:x['q_value'], reverse=True)) dict_list.append(od) # for it in dict_list: # print()",
"class CalculateRank(object): def __init__(self, input_file): self._input_file = input_file def get_rank(self):",
"THE # SOFTWARE. ################################################################################ import sys import json from pprint",
"self._input_file = input_file def get_rank(self): # Read the configuration in",
"# Identify the ones that are not Pareto optimal rank_list_bad",
"if __name__ == \"__main__\": if len(sys.argv) != 2: print(\"usage: \"",
"The above copyright notice and this permission notice shall be",
"i > j]) == len(it1['rank']) - 1: rank_list_bad.append(it1) # Put",
"# print() # print() # for i in range(len(it)): #",
"it in dict_list: # print() # print() # for i",
"its rank there for i in range(len(it2)): env = it2[i]['mapping']",
"in paretto_optimal: if len([i for i, j in zip(it1['rank'], it2['rank'])",
"rank_list = list() # Look it up for each victim(experiment)",
"subject to the following conditions: # The above copyright notice",
"the other experiments and store in 'rank' for it in",
"Sort all the configurations in a list dict_list = list()",
"WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT",
"OTHER DEALINGS IN THE # SOFTWARE. ################################################################################ import sys import",
"are not Pareto optimal rank_list_bad = list() for it1 in",
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES",
"shall be included in all #copies or substantial portions of",
"to permit persons to whom the Software is # furnished",
"comparisons if len(paretto_optimal) > 1: rank_list_bad = list() for it1",
"WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING",
"in 'rank' for it in dict_list[0]: environment = it['mapping'] rank_list"
] |
[
"1 and parts[0][-1] == ':': section = parts[0][:-1] test_cases.setdefault(section, [])",
"'') start = 0 last_pos = None parts = []",
"if __name__ == '__main__': if len(sys.argv) == 1: sys.argv.insert(1, \"StandardLuceneGrammar\")",
"line in fi: l = line.strip() if not l or",
"index_fo.close() print 'HTML charts generated into:', index_fo.name os.chdir(old_dir) def load_gunit_file(gunit_file):",
"sub import os \"\"\" Simple utility script to generate HTML",
"'// %s/%s :: %s' % (i, total, query) #generate graph",
"% grammar_name) out_lines = [] i = 0 cmds =",
"= 0 cmds = generate_ast_command.split() cmds_svg = generate_svg_command.split() total =",
"is None: last_pos = p else: parts.append(line[last_pos+1:p]) parts.append(line[p+1:].strip()) last_pos =",
"+ '.gunit') generate_ast_command = '%s -cp %s org.apache.lucene.queryparser.flexible.aqp.parser.BuildAST %s \"%%s\"'",
"/>') for section,values in test_cases.items(): output = tree = svg",
"os \"\"\" Simple utility script to generate HTML charts of",
"toc.append('The rule: <a href=\"#anchor%s\"><pre>%s</pre></a><br/>' % (section, section)) # generate AST",
"section,values in test_cases.items(): output = tree = svg = ''",
"= split_line(l) if len(parts) == 1 and parts[0][-1] == ':':",
"query print errors if 'java.lang.ClassNotFoundException' in errors: raise Exception('Please fix",
"cp='.:/dvt/antlr-142/lib/antlr-3.4-complete.jar:/x/dev/antlr-34/lib/antlr-3.4-complete.jar', grammardir='', java_executable='java', dot_executable='dot' ): if not basedir: basedir =",
"-> \\\"%s\\\"\" % (q, t) else: print 'Error generating AST",
"%s\\nclasspath: %s\\nparserdir: %s\" % (grammar_name, basedir, cp, thisdir) grammar_file =",
"sub.Popen(cmds,stdout=sub.PIPE,stderr=sub.PIPE) tree, errors = p.communicate() if tree: q = query.replace('\\\\',",
"len(x), test_cases.values())) toc = [] data = [] toc.append('<a name=\"toc\"",
"e: print \"The following command failed:\" print ' '.join(cmds_svg) raise",
"= os.path.abspath('../../../../../../../../../../bin') old_dir = os.getcwd() thisdir = grammardir if not",
"[] i = 0 cmds = generate_ast_command.split() cmds_svg = generate_svg_command.split()",
"' + query print errors tree = errors cmds.pop() cmds.pop()",
"fo = open(tmp_dot, 'w') fo.write(output) fo.close() else: print 'Error generating",
"= sub.Popen(cmds,stdout=sub.PIPE,stderr=sub.PIPE) tree, errors = p.communicate() if tree: q =",
"os.path.exists(tmp_dot): os.remove(tmp_dot) toc.append('%s. <a href=\"#anchor%s\"><pre>%s</pre></a><br/>' % (i, i, query)) print",
"</head> </body> ''') index_fo.write('\\n'.join(toc)) index_fo.write('\\n'.join(data)) index_fo.write(''' </body> </html> ''') index_fo.close()",
"while line.find('\"', start) > -1: p = line.index('\"', start) start",
"not exist in classpath: %s' % (grammar_file, cp)) tmp_file =",
"tree, errors = p.communicate() if tree: q = query.replace('\\\\', '\\\\\\\\').replace('\"',",
"does not exist in classpath: %s' % (grammar_file, cp)) tmp_file",
"parts if __name__ == '__main__': if len(sys.argv) == 1: sys.argv.insert(1,",
"if output: fo = open(tmp_dot, 'w') fo.write(output) fo.close() else: print",
"= os.getcwd() thisdir = grammardir if not thisdir: thisdir =",
"-cp %s org.apache.lucene.queryparser.flexible.aqp.parser.BuildAST %s \"%%s\"' % (java_executable, cp, grammar_name) generate_svg_command",
"%s' % (i, total, query) #generate graph p = sub.Popen(cmds,stdout=sub.PIPE,stderr=sub.PIPE)",
"cases generated from grammar: %s</h1>\\n' % grammar_name) out_lines = []",
"generate_svg_command = '%s -Tsvg %s' % (dot_executable, tmp_file) test_cases =",
"output, errors = p.communicate() data.append(' <a name=\"anchor%s\"/><h3>%s. <pre\">%s</pre> <a href=\"#toc\">^</a>",
"= tree = svg = '' toc.append('The rule: <a href=\"#anchor%s\"><pre>%s</pre></a><br/>'",
"%s</h1>\\n' % grammar_name) out_lines = [] i = 0 cmds",
"if tree: q = query.replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"').replace('\\'', '\\\\\\'') t =",
"or l[:2] == '//': continue parts = split_line(l) if len(parts)",
"l[:2] == '//': continue parts = split_line(l) if len(parts) ==",
"parts = split_line(l) if len(parts) == 1 and parts[0][-1] ==",
"'\\\\\"').replace(\"'\", \"\\\\'\") print \"\\\"%s\\\" -> \\\"%s\\\"\" % (q, t) else:",
"\"\\\\'\") print \"\\\"%s\\\" -> \\\"%s\\\"\" % (q, t) else: print",
"values: i += 1 cmds[-1] = query #tmp_dot = os.path.join(basedir,",
"= line.index('\"', start) start = p+1 if line[p-1] != '\\\\':",
"resulting AST. \"\"\" def run(grammar_name, basedir='', cp='.:/dvt/antlr-142/lib/antlr-3.4-complete.jar:/x/dev/antlr-34/lib/antlr-3.4-complete.jar', grammardir='', java_executable='java', dot_executable='dot'",
"!= 'fails': query = parts[0] query = query.replace('\\\\\\\"', '\"').replace('\\\\\\'', '\\'').replace('\\\\\\\\',",
"output, errors = p.communicate() if output: fo = open(tmp_dot, 'w')",
"not parts: parts.append(line.strip()) return parts if __name__ == '__main__': if",
"p = sub.Popen(cmds_svg,stdout=sub.PIPE,stderr=sub.PIPE) except Exception, e: print \"The following command",
"# generate AST tree for query in values: i +=",
"os.path.abspath('../../../../../../../../../../bin') old_dir = os.getcwd() thisdir = grammardir if not thisdir:",
"%s' % (dot_executable, tmp_file) test_cases = load_gunit_file(gunit_file) index_fo = open(index_file,",
"= open(index_file, 'w') index_fo.write('<h1>Test cases generated from grammar: %s</h1>\\n' %",
"% i) tmp_dot = tmp_file if os.path.exists(tmp_dot): os.remove(tmp_dot) toc.append('%s. <a",
"open(tmp_dot, 'w') fo.write(output) fo.close() else: print 'Error generating AST for:",
"test_cases.setdefault(section, []) elif len(parts) > 1 and parts[1].lower() != 'fails':",
"'\\\\') test_cases[section].append(query) fi.close() return test_cases def split_line(line): line = line.replace('->',",
"line.index('\"', start) start = p+1 if line[p-1] != '\\\\': if",
"line.find('\"', start) > -1: p = line.index('\"', start) start =",
"<pre\">%s</pre> <a href=\"#toc\">^</a> </h3>' % (i, i, query)) data.append(output) data.append('<br/><pre>'",
"= p+1 if line[p-1] != '\\\\': if last_pos is None:",
"is the resulting AST. \"\"\" def run(grammar_name, basedir='', cp='.:/dvt/antlr-142/lib/antlr-3.4-complete.jar:/x/dev/antlr-34/lib/antlr-3.4-complete.jar', grammardir='',",
"'//': continue parts = split_line(l) if len(parts) == 1 and",
"graph p = sub.Popen(cmds,stdout=sub.PIPE,stderr=sub.PIPE) output, errors = p.communicate() if output:",
"e output, errors = p.communicate() data.append(' <a name=\"anchor%s\"/><h3>%s. <pre\">%s</pre> <a",
"not os.path.exists(grammar_file): raise Exception('Grammar %s does not exist in classpath:",
"None for line in fi: l = line.strip() if not",
"fi.close() return test_cases def split_line(line): line = line.replace('->', '') start",
"t) else: print 'Error generating AST for: ' + query",
"> -1: p = line.index('\"', start) start = p+1 if",
"+ tree + '</pre>') data.append('<br/>') index_fo.write(''' <html> <head> <meta http-equiv=\"Content-Type\"",
"classpath: %s' % (grammar_file, cp)) tmp_file = os.path.join(basedir, 'ast-tree.dot') index_file",
"of how ANTLR parses every query and what is the",
"in classpath: %s' % (grammar_file, cp)) tmp_file = os.path.join(basedir, 'ast-tree.dot')",
"for: ' + query print errors tree = errors cmds.pop()",
"%s \"%%s\"' % (java_executable, cp, grammar_name) generate_svg_command = '%s -Tsvg",
"== 1 and parts[0][-1] == ':': section = parts[0][:-1] test_cases.setdefault(section,",
"p = sub.Popen(cmds,stdout=sub.PIPE,stderr=sub.PIPE) tree, errors = p.communicate() if tree: q",
"cmds = generate_ast_command.split() cmds_svg = generate_svg_command.split() total = sum(map(lambda x:",
"not basedir: basedir = os.path.abspath('../../../../../../../../../../bin') old_dir = os.getcwd() thisdir =",
"= sub.Popen(cmds,stdout=sub.PIPE,stderr=sub.PIPE) output, errors = p.communicate() if output: fo =",
"AST tree for query in values: i += 1 cmds[-1]",
"test_cases.items(): output = tree = svg = '' toc.append('The rule:",
"start) start = p+1 if line[p-1] != '\\\\': if last_pos",
"pre {display:inline;} </style> </head> </body> ''') index_fo.write('\\n'.join(toc)) index_fo.write('\\n'.join(data)) index_fo.write(''' </body>",
"errors if 'java.lang.ClassNotFoundException' in errors: raise Exception('Please fix your classpath')",
"\"\\\"%s\\\" -> \\\"%s\\\"\" % (q, t) else: print 'Error generating",
"1 and parts[1].lower() != 'fails': query = parts[0] query =",
"old_dir = os.getcwd() thisdir = grammardir if not thisdir: thisdir",
"<head> <meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" /> <style type=\"text/css\"> pre {display:inline;} </style>",
"= open(gunit_file, 'r') test_cases = {} section = None for",
"basedir #print \"We'll generate ANTLR graphs\\ngramar: %s\\nbasedir: %s\\nclasspath: %s\\nparserdir: %s\"",
"errors = p.communicate() if output: fo = open(tmp_dot, 'w') fo.write(output)",
"http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" /> <style type=\"text/css\"> pre {display:inline;} </style> </head> </body>",
"'Error generating AST for: ' + query print errors if",
"+= 1 cmds[-1] = query #tmp_dot = os.path.join(basedir, 'tmp-%s.dot' %",
"start) > -1: p = line.index('\"', start) start = p+1",
"\"\"\" def run(grammar_name, basedir='', cp='.:/dvt/antlr-142/lib/antlr-3.4-complete.jar:/x/dev/antlr-34/lib/antlr-3.4-complete.jar', grammardir='', java_executable='java', dot_executable='dot' ): if",
"print '// %s/%s :: %s' % (i, total, query) #generate",
"grammardir='', java_executable='java', dot_executable='dot' ): if not basedir: basedir = os.path.abspath('../../../../../../../../../../bin')",
"tmp_file) test_cases = load_gunit_file(gunit_file) index_fo = open(index_file, 'w') index_fo.write('<h1>Test cases",
"(grammar_name, basedir, cp, thisdir) grammar_file = os.path.join(thisdir, grammar_name + '.g')",
"\"\"\" Simple utility script to generate HTML charts of how",
"generate_svg_command.split() total = sum(map(lambda x: len(x), test_cases.values())) toc = []",
"cmds.pop() cmds.pop() cmds_svg[-1] = tmp_dot try: p = sub.Popen(cmds_svg,stdout=sub.PIPE,stderr=sub.PIPE) except",
"continue parts = split_line(l) if len(parts) == 1 and parts[0][-1]",
"generating AST for: ' + query print errors if 'java.lang.ClassNotFoundException'",
"if last_pos is None: last_pos = p else: parts.append(line[last_pos+1:p]) parts.append(line[p+1:].strip())",
"% (grammar_file, cp)) tmp_file = os.path.join(basedir, 'ast-tree.dot') index_file = os.path.join(basedir,",
"+= os.pathsep + basedir #print \"We'll generate ANTLR graphs\\ngramar: %s\\nbasedir:",
"return test_cases def split_line(line): line = line.replace('->', '') start =",
"'w') index_fo.write('<h1>Test cases generated from grammar: %s</h1>\\n' % grammar_name) out_lines",
"query in values: i += 1 cmds[-1] = query #tmp_dot",
"generate_ast_command.split() cmds_svg = generate_svg_command.split() total = sum(map(lambda x: len(x), test_cases.values()))",
"None: last_pos = p else: parts.append(line[last_pos+1:p]) parts.append(line[p+1:].strip()) last_pos = None",
"{} section = None for line in fi: l =",
"thisdir) grammar_file = os.path.join(thisdir, grammar_name + '.g') if not os.path.exists(grammar_file):",
"raise Exception('Please fix your classpath') continue #generate tree cmds.append(section) cmds.append(\"tree\")",
"test_cases def split_line(line): line = line.replace('->', '') start = 0",
"x: len(x), test_cases.values())) toc = [] data = [] toc.append('<a",
"'fails': query = parts[0] query = query.replace('\\\\\\\"', '\"').replace('\\\\\\'', '\\'').replace('\\\\\\\\', '\\\\')",
"/> <style type=\"text/css\"> pre {display:inline;} </style> </head> </body> ''') index_fo.write('\\n'.join(toc))",
"script to generate HTML charts of how ANTLR parses every",
"<style type=\"text/css\"> pre {display:inline;} </style> </head> </body> ''') index_fo.write('\\n'.join(toc)) index_fo.write('\\n'.join(data))",
"start = 0 last_pos = None parts = [] while",
"\"%%s\"' % (java_executable, cp, grammar_name) generate_svg_command = '%s -Tsvg %s'",
"errors = p.communicate() data.append(' <a name=\"anchor%s\"/><h3>%s. <pre\">%s</pre> <a href=\"#toc\">^</a> </h3>'",
"__name__ == '__main__': if len(sys.argv) == 1: sys.argv.insert(1, \"StandardLuceneGrammar\") run(*sys.argv[1:])",
"= generate_ast_command.split() cmds_svg = generate_svg_command.split() total = sum(map(lambda x: len(x),",
"(i, i, query)) print '// %s/%s :: %s' % (i,",
"output: fo = open(tmp_dot, 'w') fo.write(output) fo.close() else: print 'Error",
"= p.communicate() if tree: q = query.replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"').replace('\\'', '\\\\\\'')",
"import subprocess as sub import os \"\"\" Simple utility script",
"= '%s -cp %s org.apache.lucene.queryparser.flexible.aqp.parser.BuildAST %s \"%%s\"' % (java_executable, cp,",
"= query.replace('\\\\\\\"', '\"').replace('\\\\\\'', '\\'').replace('\\\\\\\\', '\\\\') test_cases[section].append(query) fi.close() return test_cases def",
"print \"\\\"%s\\\" -> \\\"%s\\\"\" % (q, t) else: print 'Error",
"href=\"#toc\">^</a> </h3>' % (i, i, query)) data.append(output) data.append('<br/><pre>' + tree",
"svg = '' toc.append('The rule: <a href=\"#anchor%s\"><pre>%s</pre></a><br/>' % (section, section))",
"[]) elif len(parts) > 1 and parts[1].lower() != 'fails': query",
"last_pos = None break if not parts: parts.append(line.strip()) return parts",
"%s does not exist in classpath: %s' % (grammar_file, cp))",
"cmds.append(\"tree\") p = sub.Popen(cmds,stdout=sub.PIPE,stderr=sub.PIPE) tree, errors = p.communicate() if tree:",
"= sub.Popen(cmds_svg,stdout=sub.PIPE,stderr=sub.PIPE) except Exception, e: print \"The following command failed:\"",
"(i, total, query) #generate graph p = sub.Popen(cmds,stdout=sub.PIPE,stderr=sub.PIPE) output, errors",
"= os.path.dirname(os.path.abspath(__file__)) os.chdir(thisdir) cp += os.pathsep + basedir #print \"We'll",
"= svg = '' toc.append('The rule: <a href=\"#anchor%s\"><pre>%s</pre></a><br/>' % (section,",
"in errors: raise Exception('Please fix your classpath') continue #generate tree",
"%s\\nparserdir: %s\" % (grammar_name, basedir, cp, thisdir) grammar_file = os.path.join(thisdir,",
"try: p = sub.Popen(cmds_svg,stdout=sub.PIPE,stderr=sub.PIPE) except Exception, e: print \"The following",
"cp)) tmp_file = os.path.join(basedir, 'ast-tree.dot') index_file = os.path.join(basedir, '%s.html' %",
"grammar_name) out_lines = [] i = 0 cmds = generate_ast_command.split()",
"basedir, cp, thisdir) grammar_file = os.path.join(thisdir, grammar_name + '.g') if",
"dot_executable='dot' ): if not basedir: basedir = os.path.abspath('../../../../../../../../../../bin') old_dir =",
"org.apache.lucene.queryparser.flexible.aqp.parser.BuildAST %s \"%%s\"' % (java_executable, cp, grammar_name) generate_svg_command = '%s",
"'%s -Tsvg %s' % (dot_executable, tmp_file) test_cases = load_gunit_file(gunit_file) index_fo",
"l = line.strip() if not l or l[:2] == '//':",
"ANTLR parses every query and what is the resulting AST.",
"''') index_fo.write('\\n'.join(toc)) index_fo.write('\\n'.join(data)) index_fo.write(''' </body> </html> ''') index_fo.close() print 'HTML",
"'.g') if not os.path.exists(grammar_file): raise Exception('Grammar %s does not exist",
"cmds_svg[-1] = tmp_dot try: p = sub.Popen(cmds_svg,stdout=sub.PIPE,stderr=sub.PIPE) except Exception, e:",
"run(grammar_name, basedir='', cp='.:/dvt/antlr-142/lib/antlr-3.4-complete.jar:/x/dev/antlr-34/lib/antlr-3.4-complete.jar', grammardir='', java_executable='java', dot_executable='dot' ): if not basedir:",
"parts[0] query = query.replace('\\\\\\\"', '\"').replace('\\\\\\'', '\\'').replace('\\\\\\\\', '\\\\') test_cases[section].append(query) fi.close() return",
"= os.path.join(thisdir, grammar_name + '.gunit') generate_ast_command = '%s -cp %s",
"every query and what is the resulting AST. \"\"\" def",
"def split_line(line): line = line.replace('->', '') start = 0 last_pos",
"= p.communicate() data.append(' <a name=\"anchor%s\"/><h3>%s. <pre\">%s</pre> <a href=\"#toc\">^</a> </h3>' %",
"(i, i, query)) data.append(output) data.append('<br/><pre>' + tree + '</pre>') data.append('<br/>')",
"query = parts[0] query = query.replace('\\\\\\\"', '\"').replace('\\\\\\'', '\\'').replace('\\\\\\\\', '\\\\') test_cases[section].append(query)",
"for query in values: i += 1 cmds[-1] = query",
"> 1 and parts[1].lower() != 'fails': query = parts[0] query",
"href=\"#anchor%s\"><pre>%s</pre></a><br/>' % (i, i, query)) print '// %s/%s :: %s'",
"last_pos = None parts = [] while line.find('\"', start) >",
"graphs\\ngramar: %s\\nbasedir: %s\\nclasspath: %s\\nparserdir: %s\" % (grammar_name, basedir, cp, thisdir)",
"section = None for line in fi: l = line.strip()",
"'\\\\\\'') t = tree.strip().replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"').replace(\"'\", \"\\\\'\") print \"\\\"%s\\\" ->",
"total = sum(map(lambda x: len(x), test_cases.values())) toc = [] data",
"% (i, total, query) #generate graph p = sub.Popen(cmds,stdout=sub.PIPE,stderr=sub.PIPE) output,",
"index_fo.write(''' <html> <head> <meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" /> <style type=\"text/css\"> pre",
"content=\"text/html;charset=utf-8\" /> <style type=\"text/css\"> pre {display:inline;} </style> </head> </body> ''')",
"basedir = os.path.abspath('../../../../../../../../../../bin') old_dir = os.getcwd() thisdir = grammardir if",
"= parts[0][:-1] test_cases.setdefault(section, []) elif len(parts) > 1 and parts[1].lower()",
"tree: q = query.replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"').replace('\\'', '\\\\\\'') t = tree.strip().replace('\\\\',",
"href=\"#anchor%s\"><pre>%s</pre></a><br/>' % (section, section)) # generate AST tree for query",
"java_executable='java', dot_executable='dot' ): if not basedir: basedir = os.path.abspath('../../../../../../../../../../bin') old_dir",
"% (java_executable, cp, grammar_name) generate_svg_command = '%s -Tsvg %s' %",
"generated from grammar: %s</h1>\\n' % grammar_name) out_lines = [] i",
"= query.replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"').replace('\\'', '\\\\\\'') t = tree.strip().replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"').replace(\"'\",",
"grammar_file = os.path.join(thisdir, grammar_name + '.g') if not os.path.exists(grammar_file): raise",
"AST for: ' + query print errors tree = errors",
"len(parts) == 1 and parts[0][-1] == ':': section = parts[0][:-1]",
"None parts = [] while line.find('\"', start) > -1: p",
"not thisdir: thisdir = os.path.dirname(os.path.abspath(__file__)) os.chdir(thisdir) cp += os.pathsep +",
"'java.lang.ClassNotFoundException' in errors: raise Exception('Please fix your classpath') continue #generate",
"query print errors tree = errors cmds.pop() cmds.pop() cmds_svg[-1] =",
"parts: parts.append(line.strip()) return parts if __name__ == '__main__': if len(sys.argv)",
"index_file = os.path.join(basedir, '%s.html' % grammar_name) gunit_file = os.path.join(thisdir, grammar_name",
"grammar_name) generate_svg_command = '%s -Tsvg %s' % (dot_executable, tmp_file) test_cases",
"print ' '.join(cmds_svg) raise e output, errors = p.communicate() data.append('",
"= open(tmp_dot, 'w') fo.write(output) fo.close() else: print 'Error generating AST",
"= tree.strip().replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"').replace(\"'\", \"\\\\'\") print \"\\\"%s\\\" -> \\\"%s\\\"\" %",
"%s' % (grammar_file, cp)) tmp_file = os.path.join(basedir, 'ast-tree.dot') index_file =",
"query and what is the resulting AST. \"\"\" def run(grammar_name,",
"q = query.replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"').replace('\\'', '\\\\\\'') t = tree.strip().replace('\\\\', '\\\\\\\\').replace('\"',",
"<html> <head> <meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" /> <style type=\"text/css\"> pre {display:inline;}",
"'.gunit') generate_ast_command = '%s -cp %s org.apache.lucene.queryparser.flexible.aqp.parser.BuildAST %s \"%%s\"' %",
"thisdir = grammardir if not thisdir: thisdir = os.path.dirname(os.path.abspath(__file__)) os.chdir(thisdir)",
"index_fo = open(index_file, 'w') index_fo.write('<h1>Test cases generated from grammar: %s</h1>\\n'",
"generating AST for: ' + query print errors tree =",
"last_pos is None: last_pos = p else: parts.append(line[last_pos+1:p]) parts.append(line[p+1:].strip()) last_pos",
"parts[0][-1] == ':': section = parts[0][:-1] test_cases.setdefault(section, []) elif len(parts)",
"'' toc.append('The rule: <a href=\"#anchor%s\"><pre>%s</pre></a><br/>' % (section, section)) # generate",
"% (i, i, query)) print '// %s/%s :: %s' %",
"cp, grammar_name) generate_svg_command = '%s -Tsvg %s' % (dot_executable, tmp_file)",
"</body> ''') index_fo.write('\\n'.join(toc)) index_fo.write('\\n'.join(data)) index_fo.write(''' </body> </html> ''') index_fo.close() print",
"tree + '</pre>') data.append('<br/>') index_fo.write(''' <html> <head> <meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\"",
"index_fo.name os.chdir(old_dir) def load_gunit_file(gunit_file): fi = open(gunit_file, 'r') test_cases =",
"%s/%s :: %s' % (i, total, query) #generate graph p",
"index_fo.write('\\n'.join(toc)) index_fo.write('\\n'.join(data)) index_fo.write(''' </body> </html> ''') index_fo.close() print 'HTML charts",
"<a href=\"#anchor%s\"><pre>%s</pre></a><br/>' % (section, section)) # generate AST tree for",
"name=\"toc\" />') for section,values in test_cases.items(): output = tree =",
"len(parts) > 1 and parts[1].lower() != 'fails': query = parts[0]",
"query = query.replace('\\\\\\\"', '\"').replace('\\\\\\'', '\\'').replace('\\\\\\\\', '\\\\') test_cases[section].append(query) fi.close() return test_cases",
"p = sub.Popen(cmds,stdout=sub.PIPE,stderr=sub.PIPE) output, errors = p.communicate() if output: fo",
"fi = open(gunit_file, 'r') test_cases = {} section = None",
"if not parts: parts.append(line.strip()) return parts if __name__ == '__main__':",
"os.path.join(basedir, 'tmp-%s.dot' % i) tmp_dot = tmp_file if os.path.exists(tmp_dot): os.remove(tmp_dot)",
"line.strip() if not l or l[:2] == '//': continue parts",
"= tmp_file if os.path.exists(tmp_dot): os.remove(tmp_dot) toc.append('%s. <a href=\"#anchor%s\"><pre>%s</pre></a><br/>' % (i,",
"os.getcwd() thisdir = grammardir if not thisdir: thisdir = os.path.dirname(os.path.abspath(__file__))",
"%s\" % (grammar_name, basedir, cp, thisdir) grammar_file = os.path.join(thisdir, grammar_name",
"command failed:\" print ' '.join(cmds_svg) raise e output, errors =",
"<a href=\"#toc\">^</a> </h3>' % (i, i, query)) data.append(output) data.append('<br/><pre>' +",
"+ '</pre>') data.append('<br/>') index_fo.write(''' <html> <head> <meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" />",
"break if not parts: parts.append(line.strip()) return parts if __name__ ==",
"grammar: %s</h1>\\n' % grammar_name) out_lines = [] i = 0",
"% (q, t) else: print 'Error generating AST for: '",
"section = parts[0][:-1] test_cases.setdefault(section, []) elif len(parts) > 1 and",
"raise Exception('Grammar %s does not exist in classpath: %s' %",
"os.remove(tmp_dot) toc.append('%s. <a href=\"#anchor%s\"><pre>%s</pre></a><br/>' % (i, i, query)) print '//",
"+ '.g') if not os.path.exists(grammar_file): raise Exception('Grammar %s does not",
"<a name=\"anchor%s\"/><h3>%s. <pre\">%s</pre> <a href=\"#toc\">^</a> </h3>' % (i, i, query))",
"+ query print errors if 'java.lang.ClassNotFoundException' in errors: raise Exception('Please",
"parts[1].lower() != 'fails': query = parts[0] query = query.replace('\\\\\\\"', '\"').replace('\\\\\\'',",
"(java_executable, cp, grammar_name) generate_svg_command = '%s -Tsvg %s' % (dot_executable,",
"continue #generate tree cmds.append(section) cmds.append(\"tree\") p = sub.Popen(cmds,stdout=sub.PIPE,stderr=sub.PIPE) tree, errors",
"'%s.html' % grammar_name) gunit_file = os.path.join(thisdir, grammar_name + '.gunit') generate_ast_command",
"index_fo.write(''' </body> </html> ''') index_fo.close() print 'HTML charts generated into:',",
"query.replace('\\\\\\\"', '\"').replace('\\\\\\'', '\\'').replace('\\\\\\\\', '\\\\') test_cases[section].append(query) fi.close() return test_cases def split_line(line):",
"% (grammar_name, basedir, cp, thisdir) grammar_file = os.path.join(thisdir, grammar_name +",
"grammardir if not thisdir: thisdir = os.path.dirname(os.path.abspath(__file__)) os.chdir(thisdir) cp +=",
"</h3>' % (i, i, query)) data.append(output) data.append('<br/><pre>' + tree +",
"'ast-tree.dot') index_file = os.path.join(basedir, '%s.html' % grammar_name) gunit_file = os.path.join(thisdir,",
"rule: <a href=\"#anchor%s\"><pre>%s</pre></a><br/>' % (section, section)) # generate AST tree",
"cmds.pop() cmds_svg[-1] = tmp_dot try: p = sub.Popen(cmds_svg,stdout=sub.PIPE,stderr=sub.PIPE) except Exception,",
"line = line.replace('->', '') start = 0 last_pos = None",
"AST. \"\"\" def run(grammar_name, basedir='', cp='.:/dvt/antlr-142/lib/antlr-3.4-complete.jar:/x/dev/antlr-34/lib/antlr-3.4-complete.jar', grammardir='', java_executable='java', dot_executable='dot' ):",
"l or l[:2] == '//': continue parts = split_line(l) if",
"= None for line in fi: l = line.strip() if",
"parts = [] while line.find('\"', start) > -1: p =",
"else: print 'Error generating AST for: ' + query print",
"#generate tree cmds.append(section) cmds.append(\"tree\") p = sub.Popen(cmds,stdout=sub.PIPE,stderr=sub.PIPE) tree, errors =",
"into:', index_fo.name os.chdir(old_dir) def load_gunit_file(gunit_file): fi = open(gunit_file, 'r') test_cases",
"AST for: ' + query print errors if 'java.lang.ClassNotFoundException' in",
"out_lines = [] i = 0 cmds = generate_ast_command.split() cmds_svg",
"import os \"\"\" Simple utility script to generate HTML charts",
"following command failed:\" print ' '.join(cmds_svg) raise e output, errors",
"t = tree.strip().replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"').replace(\"'\", \"\\\\'\") print \"\\\"%s\\\" -> \\\"%s\\\"\"",
"= line.replace('->', '') start = 0 last_pos = None parts",
"p else: parts.append(line[last_pos+1:p]) parts.append(line[p+1:].strip()) last_pos = None break if not",
"in values: i += 1 cmds[-1] = query #tmp_dot =",
"':': section = parts[0][:-1] test_cases.setdefault(section, []) elif len(parts) > 1",
"test_cases = {} section = None for line in fi:",
"'\\\\': if last_pos is None: last_pos = p else: parts.append(line[last_pos+1:p])",
"from grammar: %s</h1>\\n' % grammar_name) out_lines = [] i =",
"= '%s -Tsvg %s' % (dot_executable, tmp_file) test_cases = load_gunit_file(gunit_file)",
"0 cmds = generate_ast_command.split() cmds_svg = generate_svg_command.split() total = sum(map(lambda",
"Simple utility script to generate HTML charts of how ANTLR",
"errors = p.communicate() if tree: q = query.replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"').replace('\\'',",
"charts of how ANTLR parses every query and what is",
"data.append('<br/><pre>' + tree + '</pre>') data.append('<br/>') index_fo.write(''' <html> <head> <meta",
"generated into:', index_fo.name os.chdir(old_dir) def load_gunit_file(gunit_file): fi = open(gunit_file, 'r')",
"' '.join(cmds_svg) raise e output, errors = p.communicate() data.append(' <a",
"0 last_pos = None parts = [] while line.find('\"', start)",
"p.communicate() if tree: q = query.replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"').replace('\\'', '\\\\\\'') t",
"sum(map(lambda x: len(x), test_cases.values())) toc = [] data = []",
":: %s' % (i, total, query) #generate graph p =",
"raise e output, errors = p.communicate() data.append(' <a name=\"anchor%s\"/><h3>%s. <pre\">%s</pre> ",
"= line.strip() if not l or l[:2] == '//': continue",
"cmds_svg = generate_svg_command.split() total = sum(map(lambda x: len(x), test_cases.values())) toc",
"== ':': section = parts[0][:-1] test_cases.setdefault(section, []) elif len(parts) >",
"' + query print errors if 'java.lang.ClassNotFoundException' in errors: raise",
"if 'java.lang.ClassNotFoundException' in errors: raise Exception('Please fix your classpath') continue",
"% grammar_name) gunit_file = os.path.join(thisdir, grammar_name + '.gunit') generate_ast_command =",
"index_fo.write('<h1>Test cases generated from grammar: %s</h1>\\n' % grammar_name) out_lines =",
"grammar_name + '.g') if not os.path.exists(grammar_file): raise Exception('Grammar %s does",
"p.communicate() if output: fo = open(tmp_dot, 'w') fo.write(output) fo.close() else:",
"data.append(output) data.append('<br/><pre>' + tree + '</pre>') data.append('<br/>') index_fo.write(''' <html> <head>",
"test_cases = load_gunit_file(gunit_file) index_fo = open(index_file, 'w') index_fo.write('<h1>Test cases generated",
"for line in fi: l = line.strip() if not l",
"\"The following command failed:\" print ' '.join(cmds_svg) raise e output,",
"section)) # generate AST tree for query in values: i",
"os.path.join(thisdir, grammar_name + '.g') if not os.path.exists(grammar_file): raise Exception('Grammar %s",
"query)) data.append(output) data.append('<br/><pre>' + tree + '</pre>') data.append('<br/>') index_fo.write(''' <html>",
"= None parts = [] while line.find('\"', start) > -1:",
"split_line(line): line = line.replace('->', '') start = 0 last_pos =",
"'r') test_cases = {} section = None for line in",
"output = tree = svg = '' toc.append('The rule: <a",
"in test_cases.items(): output = tree = svg = '' toc.append('The",
"os.path.join(basedir, 'ast-tree.dot') index_file = os.path.join(basedir, '%s.html' % grammar_name) gunit_file =",
"line[p-1] != '\\\\': if last_pos is None: last_pos = p",
"gunit_file = os.path.join(thisdir, grammar_name + '.gunit') generate_ast_command = '%s -cp",
"and parts[1].lower() != 'fails': query = parts[0] query = query.replace('\\\\\\\"',",
"else: parts.append(line[last_pos+1:p]) parts.append(line[p+1:].strip()) last_pos = None break if not parts:",
"'%s -cp %s org.apache.lucene.queryparser.flexible.aqp.parser.BuildAST %s \"%%s\"' % (java_executable, cp, grammar_name)",
"split_line(l) if len(parts) == 1 and parts[0][-1] == ':': section",
"ANTLR graphs\\ngramar: %s\\nbasedir: %s\\nclasspath: %s\\nparserdir: %s\" % (grammar_name, basedir, cp,",
"if not os.path.exists(grammar_file): raise Exception('Grammar %s does not exist in",
"test_cases.values())) toc = [] data = [] toc.append('<a name=\"toc\" />')",
"-Tsvg %s' % (dot_executable, tmp_file) test_cases = load_gunit_file(gunit_file) index_fo =",
"'\\\\\\\\').replace('\"', '\\\\\"').replace(\"'\", \"\\\\'\") print \"\\\"%s\\\" -> \\\"%s\\\"\" % (q, t)",
"= tmp_dot try: p = sub.Popen(cmds_svg,stdout=sub.PIPE,stderr=sub.PIPE) except Exception, e: print",
"</html> ''') index_fo.close() print 'HTML charts generated into:', index_fo.name os.chdir(old_dir)",
"toc = [] data = [] toc.append('<a name=\"toc\" />') for",
"how ANTLR parses every query and what is the resulting",
"basedir: basedir = os.path.abspath('../../../../../../../../../../bin') old_dir = os.getcwd() thisdir = grammardir",
"%s org.apache.lucene.queryparser.flexible.aqp.parser.BuildAST %s \"%%s\"' % (java_executable, cp, grammar_name) generate_svg_command =",
"'\\\\\\\\').replace('\"', '\\\\\"').replace('\\'', '\\\\\\'') t = tree.strip().replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"').replace(\"'\", \"\\\\'\") print",
"fix your classpath') continue #generate tree cmds.append(section) cmds.append(\"tree\") p =",
"'HTML charts generated into:', index_fo.name os.chdir(old_dir) def load_gunit_file(gunit_file): fi =",
"(dot_executable, tmp_file) test_cases = load_gunit_file(gunit_file) index_fo = open(index_file, 'w') index_fo.write('<h1>Test",
"sys import subprocess as sub import os \"\"\" Simple utility",
"exist in classpath: %s' % (grammar_file, cp)) tmp_file = os.path.join(basedir,",
"tmp_dot = tmp_file if os.path.exists(tmp_dot): os.remove(tmp_dot) toc.append('%s. <a href=\"#anchor%s\"><pre>%s</pre></a><br/>' %",
"fo.write(output) fo.close() else: print 'Error generating AST for: ' +",
"load_gunit_file(gunit_file): fi = open(gunit_file, 'r') test_cases = {} section =",
"os.chdir(old_dir) def load_gunit_file(gunit_file): fi = open(gunit_file, 'r') test_cases = {}",
"(q, t) else: print 'Error generating AST for: ' +",
"\\\"%s\\\"\" % (q, t) else: print 'Error generating AST for:",
"!= '\\\\': if last_pos is None: last_pos = p else:",
"grammar_name + '.gunit') generate_ast_command = '%s -cp %s org.apache.lucene.queryparser.flexible.aqp.parser.BuildAST %s",
"tree.strip().replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"').replace(\"'\", \"\\\\'\") print \"\\\"%s\\\" -> \\\"%s\\\"\" % (q,",
"): if not basedir: basedir = os.path.abspath('../../../../../../../../../../bin') old_dir = os.getcwd()",
"what is the resulting AST. \"\"\" def run(grammar_name, basedir='', cp='.:/dvt/antlr-142/lib/antlr-3.4-complete.jar:/x/dev/antlr-34/lib/antlr-3.4-complete.jar',",
"def load_gunit_file(gunit_file): fi = open(gunit_file, 'r') test_cases = {} section",
"os.path.exists(grammar_file): raise Exception('Grammar %s does not exist in classpath: %s'",
"= os.path.join(basedir, 'tmp-%s.dot' % i) tmp_dot = tmp_file if os.path.exists(tmp_dot):",
"%s\\nbasedir: %s\\nclasspath: %s\\nparserdir: %s\" % (grammar_name, basedir, cp, thisdir) grammar_file",
"query) #generate graph p = sub.Popen(cmds,stdout=sub.PIPE,stderr=sub.PIPE) output, errors = p.communicate()",
"None break if not parts: parts.append(line.strip()) return parts if __name__",
"generate HTML charts of how ANTLR parses every query and",
"fo.close() else: print 'Error generating AST for: ' + query",
"= p else: parts.append(line[last_pos+1:p]) parts.append(line[p+1:].strip()) last_pos = None break if",
"import sys import subprocess as sub import os \"\"\" Simple",
"#tmp_dot = os.path.join(basedir, 'tmp-%s.dot' % i) tmp_dot = tmp_file if",
"line.replace('->', '') start = 0 last_pos = None parts =",
"test_cases[section].append(query) fi.close() return test_cases def split_line(line): line = line.replace('->', '')",
"'\"').replace('\\\\\\'', '\\'').replace('\\\\\\\\', '\\\\') test_cases[section].append(query) fi.close() return test_cases def split_line(line): line",
"'</pre>') data.append('<br/>') index_fo.write(''' <html> <head> <meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" /> <style",
"generate AST tree for query in values: i += 1",
"= {} section = None for line in fi: l",
"print errors tree = errors cmds.pop() cmds.pop() cmds_svg[-1] = tmp_dot",
"to generate HTML charts of how ANTLR parses every query",
"\"We'll generate ANTLR graphs\\ngramar: %s\\nbasedir: %s\\nclasspath: %s\\nparserdir: %s\" % (grammar_name,",
"the resulting AST. \"\"\" def run(grammar_name, basedir='', cp='.:/dvt/antlr-142/lib/antlr-3.4-complete.jar:/x/dev/antlr-34/lib/antlr-3.4-complete.jar', grammardir='', java_executable='java',",
"failed:\" print ' '.join(cmds_svg) raise e output, errors = p.communicate()",
"data.append(' <a name=\"anchor%s\"/><h3>%s. <pre\">%s</pre> <a href=\"#toc\">^</a> </h3>' % (i, i,",
"cmds[-1] = query #tmp_dot = os.path.join(basedir, 'tmp-%s.dot' % i) tmp_dot",
"= grammardir if not thisdir: thisdir = os.path.dirname(os.path.abspath(__file__)) os.chdir(thisdir) cp",
"(section, section)) # generate AST tree for query in values:",
"parses every query and what is the resulting AST. \"\"\"",
"if not basedir: basedir = os.path.abspath('../../../../../../../../../../bin') old_dir = os.getcwd() thisdir",
"tmp_file = os.path.join(basedir, 'ast-tree.dot') index_file = os.path.join(basedir, '%s.html' % grammar_name)",
"query.replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"').replace('\\'', '\\\\\\'') t = tree.strip().replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"').replace(\"'\", \"\\\\'\")",
"print errors if 'java.lang.ClassNotFoundException' in errors: raise Exception('Please fix your",
"load_gunit_file(gunit_file) index_fo = open(index_file, 'w') index_fo.write('<h1>Test cases generated from grammar:",
"'tmp-%s.dot' % i) tmp_dot = tmp_file if os.path.exists(tmp_dot): os.remove(tmp_dot) toc.append('%s.",
"errors cmds.pop() cmds.pop() cmds_svg[-1] = tmp_dot try: p = sub.Popen(cmds_svg,stdout=sub.PIPE,stderr=sub.PIPE)",
"= [] data = [] toc.append('<a name=\"toc\" />') for section,values",
"p = line.index('\"', start) start = p+1 if line[p-1] !=",
"open(index_file, 'w') index_fo.write('<h1>Test cases generated from grammar: %s</h1>\\n' % grammar_name)",
"errors: raise Exception('Please fix your classpath') continue #generate tree cmds.append(section)",
"<a href=\"#anchor%s\"><pre>%s</pre></a><br/>' % (i, i, query)) print '// %s/%s ::",
"Exception('Grammar %s does not exist in classpath: %s' % (grammar_file,",
"open(gunit_file, 'r') test_cases = {} section = None for line",
"fi: l = line.strip() if not l or l[:2] ==",
"(grammar_file, cp)) tmp_file = os.path.join(basedir, 'ast-tree.dot') index_file = os.path.join(basedir, '%s.html'",
"parts[0][:-1] test_cases.setdefault(section, []) elif len(parts) > 1 and parts[1].lower() !=",
"'Error generating AST for: ' + query print errors tree",
"and parts[0][-1] == ':': section = parts[0][:-1] test_cases.setdefault(section, []) elif",
"data = [] toc.append('<a name=\"toc\" />') for section,values in test_cases.items():",
"#print \"We'll generate ANTLR graphs\\ngramar: %s\\nbasedir: %s\\nclasspath: %s\\nparserdir: %s\" %",
"errors tree = errors cmds.pop() cmds.pop() cmds_svg[-1] = tmp_dot try:",
"sub.Popen(cmds_svg,stdout=sub.PIPE,stderr=sub.PIPE) except Exception, e: print \"The following command failed:\" print",
"if not l or l[:2] == '//': continue parts =",
"last_pos = p else: parts.append(line[last_pos+1:p]) parts.append(line[p+1:].strip()) last_pos = None break",
"if not thisdir: thisdir = os.path.dirname(os.path.abspath(__file__)) os.chdir(thisdir) cp += os.pathsep",
"print 'Error generating AST for: ' + query print errors",
"classpath') continue #generate tree cmds.append(section) cmds.append(\"tree\") p = sub.Popen(cmds,stdout=sub.PIPE,stderr=sub.PIPE) tree,",
"cp, thisdir) grammar_file = os.path.join(thisdir, grammar_name + '.g') if not",
"index_fo.write('\\n'.join(data)) index_fo.write(''' </body> </html> ''') index_fo.close() print 'HTML charts generated",
"toc.append('%s. <a href=\"#anchor%s\"><pre>%s</pre></a><br/>' % (i, i, query)) print '// %s/%s",
"print 'HTML charts generated into:', index_fo.name os.chdir(old_dir) def load_gunit_file(gunit_file): fi",
"as sub import os \"\"\" Simple utility script to generate",
"tree = errors cmds.pop() cmds.pop() cmds_svg[-1] = tmp_dot try: p",
"= os.path.join(basedir, '%s.html' % grammar_name) gunit_file = os.path.join(thisdir, grammar_name +",
"i += 1 cmds[-1] = query #tmp_dot = os.path.join(basedir, 'tmp-%s.dot'",
"charts generated into:', index_fo.name os.chdir(old_dir) def load_gunit_file(gunit_file): fi = open(gunit_file,",
"<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" /> <style type=\"text/css\"> pre {display:inline;} </style> </head>",
"type=\"text/css\"> pre {display:inline;} </style> </head> </body> ''') index_fo.write('\\n'.join(toc)) index_fo.write('\\n'.join(data)) index_fo.write('''",
"p.communicate() data.append(' <a name=\"anchor%s\"/><h3>%s. <pre\">%s</pre> <a href=\"#toc\">^</a> </h3>' % (i,",
"#generate graph p = sub.Popen(cmds,stdout=sub.PIPE,stderr=sub.PIPE) output, errors = p.communicate() if",
"[] while line.find('\"', start) > -1: p = line.index('\"', start)",
"1 cmds[-1] = query #tmp_dot = os.path.join(basedir, 'tmp-%s.dot' % i)",
"sub.Popen(cmds,stdout=sub.PIPE,stderr=sub.PIPE) output, errors = p.communicate() if output: fo = open(tmp_dot,",
"HTML charts of how ANTLR parses every query and what",
"= load_gunit_file(gunit_file) index_fo = open(index_file, 'w') index_fo.write('<h1>Test cases generated from",
"generate ANTLR graphs\\ngramar: %s\\nbasedir: %s\\nclasspath: %s\\nparserdir: %s\" % (grammar_name, basedir,",
"tmp_dot try: p = sub.Popen(cmds_svg,stdout=sub.PIPE,stderr=sub.PIPE) except Exception, e: print \"The",
"= generate_svg_command.split() total = sum(map(lambda x: len(x), test_cases.values())) toc =",
"i) tmp_dot = tmp_file if os.path.exists(tmp_dot): os.remove(tmp_dot) toc.append('%s. <a href=\"#anchor%s\"><pre>%s</pre></a><br/>'",
"Exception('Please fix your classpath') continue #generate tree cmds.append(section) cmds.append(\"tree\") p",
"</style> </head> </body> ''') index_fo.write('\\n'.join(toc)) index_fo.write('\\n'.join(data)) index_fo.write(''' </body> </html> ''')",
"not l or l[:2] == '//': continue parts = split_line(l)",
"if line[p-1] != '\\\\': if last_pos is None: last_pos =",
"p+1 if line[p-1] != '\\\\': if last_pos is None: last_pos",
"cp += os.pathsep + basedir #print \"We'll generate ANTLR graphs\\ngramar:",
"'w') fo.write(output) fo.close() else: print 'Error generating AST for: '",
"= [] i = 0 cmds = generate_ast_command.split() cmds_svg =",
"= errors cmds.pop() cmds.pop() cmds_svg[-1] = tmp_dot try: p =",
"grammar_name) gunit_file = os.path.join(thisdir, grammar_name + '.gunit') generate_ast_command = '%s",
"= 0 last_pos = None parts = [] while line.find('\"',",
"parts.append(line[last_pos+1:p]) parts.append(line[p+1:].strip()) last_pos = None break if not parts: parts.append(line.strip())",
"'.join(cmds_svg) raise e output, errors = p.communicate() data.append(' <a name=\"anchor%s\"/><h3>%s.",
"i = 0 cmds = generate_ast_command.split() cmds_svg = generate_svg_command.split() total",
"os.chdir(thisdir) cp += os.pathsep + basedir #print \"We'll generate ANTLR",
"basedir='', cp='.:/dvt/antlr-142/lib/antlr-3.4-complete.jar:/x/dev/antlr-34/lib/antlr-3.4-complete.jar', grammardir='', java_executable='java', dot_executable='dot' ): if not basedir: basedir",
"query #tmp_dot = os.path.join(basedir, 'tmp-%s.dot' % i) tmp_dot = tmp_file",
"elif len(parts) > 1 and parts[1].lower() != 'fails': query =",
"os.path.dirname(os.path.abspath(__file__)) os.chdir(thisdir) cp += os.pathsep + basedir #print \"We'll generate",
"+ basedir #print \"We'll generate ANTLR graphs\\ngramar: %s\\nbasedir: %s\\nclasspath: %s\\nparserdir:",
"i, query)) print '// %s/%s :: %s' % (i, total,",
"generate_ast_command = '%s -cp %s org.apache.lucene.queryparser.flexible.aqp.parser.BuildAST %s \"%%s\"' % (java_executable,",
"os.path.join(basedir, '%s.html' % grammar_name) gunit_file = os.path.join(thisdir, grammar_name + '.gunit')",
"if len(parts) == 1 and parts[0][-1] == ':': section =",
"your classpath') continue #generate tree cmds.append(section) cmds.append(\"tree\") p = sub.Popen(cmds,stdout=sub.PIPE,stderr=sub.PIPE)",
"parts.append(line.strip()) return parts if __name__ == '__main__': if len(sys.argv) ==",
"for section,values in test_cases.items(): output = tree = svg =",
"[] toc.append('<a name=\"toc\" />') for section,values in test_cases.items(): output =",
"</body> </html> ''') index_fo.close() print 'HTML charts generated into:', index_fo.name",
"''') index_fo.close() print 'HTML charts generated into:', index_fo.name os.chdir(old_dir) def",
"start = p+1 if line[p-1] != '\\\\': if last_pos is",
"'\\'').replace('\\\\\\\\', '\\\\') test_cases[section].append(query) fi.close() return test_cases def split_line(line): line =",
"{display:inline;} </style> </head> </body> ''') index_fo.write('\\n'.join(toc)) index_fo.write('\\n'.join(data)) index_fo.write(''' </body> </html>",
"tree cmds.append(section) cmds.append(\"tree\") p = sub.Popen(cmds,stdout=sub.PIPE,stderr=sub.PIPE) tree, errors = p.communicate()",
"cmds.append(section) cmds.append(\"tree\") p = sub.Popen(cmds,stdout=sub.PIPE,stderr=sub.PIPE) tree, errors = p.communicate() if",
"os.path.join(thisdir, grammar_name + '.gunit') generate_ast_command = '%s -cp %s org.apache.lucene.queryparser.flexible.aqp.parser.BuildAST",
"-1: p = line.index('\"', start) start = p+1 if line[p-1]",
"toc.append('<a name=\"toc\" />') for section,values in test_cases.items(): output = tree",
"% (section, section)) # generate AST tree for query in",
"total, query) #generate graph p = sub.Popen(cmds,stdout=sub.PIPE,stderr=sub.PIPE) output, errors =",
"= [] while line.find('\"', start) > -1: p = line.index('\"',",
"utility script to generate HTML charts of how ANTLR parses",
"= None break if not parts: parts.append(line.strip()) return parts if",
"+ query print errors tree = errors cmds.pop() cmds.pop() cmds_svg[-1]",
"% (i, i, query)) data.append(output) data.append('<br/><pre>' + tree + '</pre>')",
"% (dot_executable, tmp_file) test_cases = load_gunit_file(gunit_file) index_fo = open(index_file, 'w')",
"[] data = [] toc.append('<a name=\"toc\" />') for section,values in",
"'\\\\\"').replace('\\'', '\\\\\\'') t = tree.strip().replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"').replace(\"'\", \"\\\\'\") print \"\\\"%s\\\"",
"for: ' + query print errors if 'java.lang.ClassNotFoundException' in errors:",
"and what is the resulting AST. \"\"\" def run(grammar_name, basedir='',",
"= query #tmp_dot = os.path.join(basedir, 'tmp-%s.dot' % i) tmp_dot =",
"except Exception, e: print \"The following command failed:\" print '",
"tree = svg = '' toc.append('The rule: <a href=\"#anchor%s\"><pre>%s</pre></a><br/>' %",
"i, query)) data.append(output) data.append('<br/><pre>' + tree + '</pre>') data.append('<br/>') index_fo.write('''",
"= parts[0] query = query.replace('\\\\\\\"', '\"').replace('\\\\\\'', '\\'').replace('\\\\\\\\', '\\\\') test_cases[section].append(query) fi.close()",
"return parts if __name__ == '__main__': if len(sys.argv) == 1:",
"= os.path.join(basedir, 'ast-tree.dot') index_file = os.path.join(basedir, '%s.html' % grammar_name) gunit_file",
"Exception, e: print \"The following command failed:\" print ' '.join(cmds_svg)",
"subprocess as sub import os \"\"\" Simple utility script to",
"def run(grammar_name, basedir='', cp='.:/dvt/antlr-142/lib/antlr-3.4-complete.jar:/x/dev/antlr-34/lib/antlr-3.4-complete.jar', grammardir='', java_executable='java', dot_executable='dot' ): if not",
"os.pathsep + basedir #print \"We'll generate ANTLR graphs\\ngramar: %s\\nbasedir: %s\\nclasspath:",
"tmp_file if os.path.exists(tmp_dot): os.remove(tmp_dot) toc.append('%s. <a href=\"#anchor%s\"><pre>%s</pre></a><br/>' % (i, i,",
"print \"The following command failed:\" print ' '.join(cmds_svg) raise e",
"= p.communicate() if output: fo = open(tmp_dot, 'w') fo.write(output) fo.close()",
"name=\"anchor%s\"/><h3>%s. <pre\">%s</pre> <a href=\"#toc\">^</a> </h3>' % (i, i, query)) data.append(output)",
"thisdir = os.path.dirname(os.path.abspath(__file__)) os.chdir(thisdir) cp += os.pathsep + basedir #print",
"== '//': continue parts = split_line(l) if len(parts) == 1",
"if os.path.exists(tmp_dot): os.remove(tmp_dot) toc.append('%s. <a href=\"#anchor%s\"><pre>%s</pre></a><br/>' % (i, i, query))",
"parts.append(line[p+1:].strip()) last_pos = None break if not parts: parts.append(line.strip()) return",
"data.append('<br/>') index_fo.write(''' <html> <head> <meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" /> <style type=\"text/css\">",
"= os.path.join(thisdir, grammar_name + '.g') if not os.path.exists(grammar_file): raise Exception('Grammar",
"= [] toc.append('<a name=\"toc\" />') for section,values in test_cases.items(): output",
"tree for query in values: i += 1 cmds[-1] =",
"in fi: l = line.strip() if not l or l[:2]",
"thisdir: thisdir = os.path.dirname(os.path.abspath(__file__)) os.chdir(thisdir) cp += os.pathsep + basedir",
"= sum(map(lambda x: len(x), test_cases.values())) toc = [] data =",
"query)) print '// %s/%s :: %s' % (i, total, query)",
"= '' toc.append('The rule: <a href=\"#anchor%s\"><pre>%s</pre></a><br/>' % (section, section)) #"
] |
[
"'train', 7: 'truck', 8: 'boat', 9: 'traffic light', 10: 'fire",
"= None, classes_path:str = None, input_shape:int = 608): if (weights_path",
"MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO",
"1: 'bicycle', 2: 'car', 3: 'motorcycle', 4: 'airplane', 5: 'bus',",
"'banana', 47: 'apple', 48: 'sandwich', 49: 'orange', 50: 'broccoli', 51:",
"should not be None.') self.yolo_classes = classes_path self.weights_path = weights_path",
"i in range(len(pred_bboxes)): check_name = labels[pred_bboxes[i][4]] check = custom_objects.get(check_name, 'invalid')",
"as yolo_main import numpy as np import cv2 labels =",
"substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS",
"notice shall be included in all copies or substantial portions",
"68: 'microwave', 69: 'oven', 70: 'toaster', 71: 'sink', 72: 'refrigerator',",
"54: 'donut', 55: 'cake', 56: 'chair', 57: 'couch', 58: 'potted",
"res) else: res = self.model.draw_bboxes(img, pred_bboxes) if debug: cv2.imwrite(self.output_path, res)",
"12: 'parking meter', 13: 'bench', 14: 'bird', 15: 'cat', 16:",
"= classes_path self.weights_path = weights_path self.input_shape = input_shape self.model =",
"self.input_shape) self.model.classes = self.yolo_classes self.model.make_model() self.model.load_weights(self.weights_path, weights_type = 'yolo') def",
"0.4, score = 0.07, custom_objects:dict = None, debug=True): self.output_path =",
"11: 'stop sign', 12: 'parking meter', 13: 'bench', 14: 'bird',",
"4: 'airplane', 5: 'bus', 6: 'train', 7: 'truck', 8: 'boat',",
"self.yolo_classes self.model.make_model() self.model.load_weights(self.weights_path, weights_type = 'yolo') def predict(self, img:np.ndarray, output_path:str,",
"cv2 labels = {0: 'person', 1: 'bicycle', 2: 'car', 3:",
"= None, input_shape:int = 0): if (weights_path is None) or",
"= self.yolo_classes self.model.make_model() self.model.load_weights(self.weights_path, weights_type = 'yolo') def predict(self, img:np.ndarray,",
"== 'valid': boxes.append(list(pred_bboxes[i])) boxes = np.array(boxes) res = self.model.draw_bboxes(img, boxes)",
"51: 'carrot', 52: 'hot dog', 53: 'pizza', 54: 'donut', 55:",
"iou_threshold = self.iou, score_threshold = self.score) boxes = [] if",
"continue elif check == 'valid': boxes.append(list(pred_bboxes[i])) boxes = np.array(boxes) res",
"classes_path:str = None, input_shape:int = 0): if (weights_path is None)",
"yolo_main(tiny = True, shape = self.input_shape) self.model.classes = self.yolo_classes self.model.make_model()",
"= None, debug=True): self.output_path = output_path self.iou = iou self.score",
"classes_path:str = None, input_shape:int = 608): if (weights_path is None)",
"48: 'sandwich', 49: 'orange', 50: 'broccoli', 51: 'carrot', 52: 'hot",
"'bus', 6: 'train', 7: 'truck', 8: 'boat', 9: 'traffic light',",
"'hair drier', 79: 'toothbrush'} class YOLOv4: def __init__(self): self.weights_path =",
"def predict(self, img:np.ndarray, output_path:str, iou = 0.4, score = 0.07,",
"Software without restriction, including without limitation the rights to use,",
"'bird', 15: 'cat', 16: 'dog', 17: 'horse', 18: 'sheep', 19:",
"self.yolo_classes = classes_path self.weights_path = weights_path self.input_shape = input_shape self.model",
"= \"\" self.iou = 0 self.score = 0 self.input_shape =",
"NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS",
"copies of the Software, and to permit persons to whom",
"46: 'banana', 47: 'apple', 48: 'sandwich', 49: 'orange', 50: 'broccoli',",
"hereby granted, free of charge, to any person obtaining a",
"custom_objects:dict = None, debug=True): self.output_path = output_path self.iou = iou",
"if (custom_objects != None): for i in range(len(pred_bboxes)): check_name =",
"to deal in the Software without restriction, including without limitation",
"res = self.model.draw_bboxes(img, pred_bboxes) if debug: cv2.imwrite(self.output_path, res) return res",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE",
"yolo_main(shape = self.input_shape) self.model.classes = self.yolo_classes self.model.make_model() self.model.load_weights(self.weights_path, weights_type =",
"'bicycle', 2: 'car', 3: 'motorcycle', 4: 'airplane', 5: 'bus', 6:",
"None): raise RuntimeError ('weights_path AND classes_path should not be None.')",
"'potted plant', 59: 'bed', 60: 'dining table', 61: 'toilet', 62:",
"boxes = np.array(boxes) res = self.model.draw_bboxes(img, boxes) if debug: cv2.imwrite(self.output_path,",
"range(len(pred_bboxes)): check_name = labels[pred_bboxes[i][4]] check = custom_objects.get(check_name, 'invalid') if check",
"78: 'hair drier', 79: 'toothbrush'} class YOLOv4: def __init__(self): self.weights_path",
"9: 'traffic light', 10: 'fire hydrant', 11: 'stop sign', 12:",
"= self.model.predict(img, iou_threshold = self.iou, score_threshold = self.score) boxes =",
"self.iou = iou self.score = score #img = np.array(Image.open(img))[..., ::-1]",
"6: 'train', 7: 'truck', 8: 'boat', 9: 'traffic light', 10:",
"portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\",",
"'frisbee', 30: 'skis', 31: 'snowboard', 32: 'sports ball', 33: 'kite',",
"'book', 74: 'clock', 75: 'vase', 76: 'scissors', 77: 'teddy bear',",
"\"\"\" MIT License Copyright (c) 2020 <NAME> <<EMAIL>> Permission is",
"boxes) if debug: cv2.imwrite(self.output_path, res) else: res = self.model.draw_bboxes(img, pred_bboxes)",
"labels[pred_bboxes[i][4]] check = custom_objects.get(check_name, 'invalid') if check == 'invalid': continue",
"20: 'elephant', 21: 'bear', 22: 'zebra', 23: 'giraffe', 24: 'backpack',",
"17: 'horse', 18: 'sheep', 19: 'cow', 20: 'elephant', 21: 'bear',",
"= score #img = np.array(Image.open(img))[..., ::-1] pred_bboxes = self.model.predict(img, iou_threshold",
"DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,",
"'apple', 48: 'sandwich', 49: 'orange', 50: 'broccoli', 51: 'carrot', 52:",
"FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR",
"22: 'zebra', 23: 'giraffe', 24: 'backpack', 25: 'umbrella', 26: 'handbag',",
"modify, merge, publish, distribute, sublicense, and/or sell copies of the",
"'scissors', 77: 'teddy bear', 78: 'hair drier', 79: 'toothbrush'} class",
"weights_path self.input_shape = input_shape self.model = yolo_main(tiny = True, shape",
"ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE",
"= input_shape self.model = yolo_main(tiny = True, shape = self.input_shape)",
"persons to whom the Software is furnished to do so,",
"'knife', 44: 'spoon', 45: 'bowl', 46: 'banana', 47: 'apple', 48:",
"limitation the rights to use, copy, modify, merge, publish, distribute,",
"subject to the following conditions: The above copyright notice and",
"OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH",
"'giraffe', 24: 'backpack', 25: 'umbrella', 26: 'handbag', 27: 'tie', 28:",
"raise RuntimeError ('weights_path AND classes_path should not be None.') self.yolo_classes",
"'bowl', 46: 'banana', 47: 'apple', 48: 'sandwich', 49: 'orange', 50:",
"of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT",
"= output_path self.iou = iou self.score = score #img =",
"glass', 41: 'cup', 42: 'fork', 43: 'knife', 44: 'spoon', 45:",
"'airplane', 5: 'bus', 6: 'train', 7: 'truck', 8: 'boat', 9:",
"'toothbrush'} class YOLOv4: def __init__(self): self.weights_path = \"\" self.model =",
"not be None.') self.yolo_classes = classes_path self.weights_path = weights_path self.input_shape",
"NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A",
"'traffic light', 10: 'fire hydrant', 11: 'stop sign', 12: 'parking",
"Software is furnished to do so, subject to the following",
"drier', 79: 'toothbrush'} class YOLOv4: def __init__(self): self.weights_path = \"\"",
"Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF",
"'tennis racket', 39: 'bottle', 40: 'wine glass', 41: 'cup', 42:",
"is None): raise RuntimeError ('weights_path AND classes_path should not be",
"sell copies of the Software, and to permit persons to",
"64: 'mouse', 65: 'remote', 66: 'keyboard', 67: 'cell phone', 68:",
"'snowboard', 32: 'sports ball', 33: 'kite', 34: 'baseball bat', 35:",
"included in all copies or substantial portions of the Software.",
"weights_path:str = None, classes_path:str = None, input_shape:int = 0): if",
"(weights_path is None) or (classes_path is None): raise RuntimeError ('weights_path",
"58: 'potted plant', 59: 'bed', 60: 'dining table', 61: 'toilet',",
"input_shape:int = 608): if (weights_path is None) or (classes_path is",
"copy, modify, merge, publish, distribute, sublicense, and/or sell copies of",
"'spoon', 45: 'bowl', 46: 'banana', 47: 'apple', 48: 'sandwich', 49:",
"'keyboard', 67: 'cell phone', 68: 'microwave', 69: 'oven', 70: 'toaster',",
"= np.array(boxes) res = self.model.draw_bboxes(img, boxes) if debug: cv2.imwrite(self.output_path, res)",
"'fork', 43: 'knife', 44: 'spoon', 45: 'bowl', 46: 'banana', 47:",
"classes_path self.weights_path = weights_path self.input_shape = input_shape self.model = yolo_main(tiny",
"weights_path:str = None, classes_path:str = None, input_shape:int = 608): if",
"furnished to do so, subject to the following conditions: The",
"or substantial portions of the Software. THE SOFTWARE IS PROVIDED",
"EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR",
"37: 'surfboard', 38: 'tennis racket', 39: 'bottle', 40: 'wine glass',",
"None, input_shape:int = 608): if (weights_path is None) or (classes_path",
"plant', 59: 'bed', 60: 'dining table', 61: 'toilet', 62: 'tv',",
"EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"def predict(self, img:np.ndarray, output_path:str, iou = 0.45, score = 0.25,",
"publish, distribute, sublicense, and/or sell copies of the Software, and",
"56: 'chair', 57: 'couch', 58: 'potted plant', 59: 'bed', 60:",
"= self.model.draw_bboxes(img, pred_bboxes) if debug: cv2.imwrite(self.output_path, res) return res class",
"\"Software\"), to deal in the Software without restriction, including without",
"'hot dog', 53: 'pizza', 54: 'donut', 55: 'cake', 56: 'chair',",
"self.input_shape = input_shape self.model = yolo_main(shape = self.input_shape) self.model.classes =",
"IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"'skis', 31: 'snowboard', 32: 'sports ball', 33: 'kite', 34: 'baseball",
"= \"\" def load_model(self, weights_path:str = None, classes_path:str = None,",
"79: 'toothbrush'} class YOLOv4: def __init__(self): self.weights_path = \"\" self.model",
"classes_path should not be None.') self.yolo_classes = classes_path self.weights_path =",
"TinyYOLOv4: def __init__(self): self.weights_path = \"\" self.model = None self.yolo_classes",
"be included in all copies or substantial portions of the",
"load_model(self, weights_path:str = None, classes_path:str = None, input_shape:int = 608):",
"output_path:str, iou = 0.4, score = 0.07, custom_objects:dict = None,",
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
"= None self.yolo_classes = \"\" self.iou = 0 self.score =",
"39: 'bottle', 40: 'wine glass', 41: 'cup', 42: 'fork', 43:",
"self.model.classes = self.yolo_classes self.model.make_model() self.model.load_weights(self.weights_path, weights_type = 'yolo') def predict(self,",
"score #img = np.array(Image.open(img))[..., ::-1] pred_bboxes = self.model.predict(img, iou_threshold =",
"if debug: cv2.imwrite(self.output_path, res) else: res = self.model.draw_bboxes(img, pred_bboxes) if",
"31: 'snowboard', 32: 'sports ball', 33: 'kite', 34: 'baseball bat',",
"(custom_objects != None): for i in range(len(pred_bboxes)): check_name = labels[pred_bboxes[i][4]]",
"'truck', 8: 'boat', 9: 'traffic light', 10: 'fire hydrant', 11:",
"labels = {0: 'person', 1: 'bicycle', 2: 'car', 3: 'motorcycle',",
"return res class TinyYOLOv4: def __init__(self): self.weights_path = \"\" self.model",
"(c) 2020 <NAME> <<EMAIL>> Permission is hereby granted, free of",
"'yolo') def predict(self, img:np.ndarray, output_path:str, iou = 0.45, score =",
"predict(self, img:np.ndarray, output_path:str, iou = 0.45, score = 0.25, custom_objects:dict",
"'chair', 57: 'couch', 58: 'potted plant', 59: 'bed', 60: 'dining",
"the following conditions: The above copyright notice and this permission",
"files (the \"Software\"), to deal in the Software without restriction,",
"'sandwich', 49: 'orange', 50: 'broccoli', 51: 'carrot', 52: 'hot dog',",
"28: 'suitcase', 29: 'frisbee', 30: 'skis', 31: 'snowboard', 32: 'sports",
"50: 'broccoli', 51: 'carrot', 52: 'hot dog', 53: 'pizza', 54:",
"== 'invalid': continue elif check == 'valid': boxes.append(list(pred_bboxes[i])) boxes =",
"if check == 'invalid': continue elif check == 'valid': boxes.append(list(pred_bboxes[i]))",
"AND classes_path should not be None.') self.yolo_classes = classes_path self.weights_path",
"ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF",
"'bear', 22: 'zebra', 23: 'giraffe', 24: 'backpack', 25: 'umbrella', 26:",
"None, input_shape:int = 0): if (weights_path is None) or (classes_path",
"the rights to use, copy, modify, merge, publish, distribute, sublicense,",
"self.model = None self.yolo_classes = \"\" self.iou = 0 self.score",
"16: 'dog', 17: 'horse', 18: 'sheep', 19: 'cow', 20: 'elephant',",
"'horse', 18: 'sheep', 19: 'cow', 20: 'elephant', 21: 'bear', 22:",
"40: 'wine glass', 41: 'cup', 42: 'fork', 43: 'knife', 44:",
"software and associated documentation files (the \"Software\"), to deal in",
"15: 'cat', 16: 'dog', 17: 'horse', 18: 'sheep', 19: 'cow',",
"47: 'apple', 48: 'sandwich', 49: 'orange', 50: 'broccoli', 51: 'carrot',",
"= 0 self.input_shape = 0 self.output_path = \"\" def load_model(self,",
"notice and this permission notice shall be included in all",
"'couch', 58: 'potted plant', 59: 'bed', 60: 'dining table', 61:",
"is hereby granted, free of charge, to any person obtaining",
"59: 'bed', 60: 'dining table', 61: 'toilet', 62: 'tv', 63:",
"= True, shape = self.input_shape) self.model.classes = self.yolo_classes self.model.make_model() self.model.load_weights(self.weights_path,",
"check = custom_objects.get(check_name, 'invalid') if check == 'invalid': continue elif",
"= self.model.draw_bboxes(img, boxes) if debug: cv2.imwrite(self.output_path, res) else: res =",
"for i in range(len(pred_bboxes)): check_name = labels[pred_bboxes[i][4]] check = custom_objects.get(check_name,",
"{0: 'person', 1: 'bicycle', 2: 'car', 3: 'motorcycle', 4: 'airplane',",
"table', 61: 'toilet', 62: 'tv', 63: 'laptop', 64: 'mouse', 65:",
"('weights_path AND classes_path should not be None.') self.yolo_classes = classes_path",
"input_shape:int = 0): if (weights_path is None) or (classes_path is",
"is None) or (classes_path is None): raise RuntimeError ('weights_path AND",
"self.input_shape = 0 self.output_path = \"\" def load_model(self, weights_path:str =",
"elif check == 'valid': boxes.append(list(pred_bboxes[i])) boxes = np.array(boxes) res =",
"'handbag', 27: 'tie', 28: 'suitcase', 29: 'frisbee', 30: 'skis', 31:",
"= 0.45, score = 0.25, custom_objects:dict = None, debug=True): self.output_path",
"= 608): if (weights_path is None) or (classes_path is None):",
"dog', 53: 'pizza', 54: 'donut', 55: 'cake', 56: 'chair', 57:",
"to the following conditions: The above copyright notice and this",
"conditions: The above copyright notice and this permission notice shall",
"boxes = [] if (custom_objects != None): for i in",
"the Software without restriction, including without limitation the rights to",
"'suitcase', 29: 'frisbee', 30: 'skis', 31: 'snowboard', 32: 'sports ball',",
"= [] if (custom_objects != None): for i in range(len(pred_bboxes)):",
"= 'yolo') def predict(self, img:np.ndarray, output_path:str, iou = 0.4, score",
"'motorcycle', 4: 'airplane', 5: 'bus', 6: 'train', 7: 'truck', 8:",
"THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND",
"and/or sell copies of the Software, and to permit persons",
"score_threshold = self.score) boxes = [] if (custom_objects != None):",
"permit persons to whom the Software is furnished to do",
"self.iou = 0 self.score = 0 self.input_shape = 0 self.output_path",
"35: 'baseball glove', 36: 'skateboard', 37: 'surfboard', 38: 'tennis racket',",
"None, classes_path:str = None, input_shape:int = 608): if (weights_path is",
"38: 'tennis racket', 39: 'bottle', 40: 'wine glass', 41: 'cup',",
"do so, subject to the following conditions: The above copyright",
"26: 'handbag', 27: 'tie', 28: 'suitcase', 29: 'frisbee', 30: 'skis',",
"'dog', 17: 'horse', 18: 'sheep', 19: 'cow', 20: 'elephant', 21:",
"self.model.load_weights(self.weights_path, weights_type = 'yolo') def predict(self, img:np.ndarray, output_path:str, iou =",
"any person obtaining a copy of this software and associated",
"13: 'bench', 14: 'bird', 15: 'cat', 16: 'dog', 17: 'horse',",
"self.output_path = \"\" def load_model(self, weights_path:str = None, classes_path:str =",
"np.array(Image.open(img))[..., ::-1] pred_bboxes = self.model.predict(img, iou_threshold = self.iou, score_threshold =",
"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN",
"hydrant', 11: 'stop sign', 12: 'parking meter', 13: 'bench', 14:",
"32: 'sports ball', 33: 'kite', 34: 'baseball bat', 35: 'baseball",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT",
"THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE",
"check == 'invalid': continue elif check == 'valid': boxes.append(list(pred_bboxes[i])) boxes",
"THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,",
"None.') self.yolo_classes = classes_path self.weights_path = weights_path self.input_shape = input_shape",
"as np import cv2 labels = {0: 'person', 1: 'bicycle',",
"0 self.output_path = \"\" def load_model(self, weights_path:str = None, classes_path:str",
"meter', 13: 'bench', 14: 'bird', 15: 'cat', 16: 'dog', 17:",
"'teddy bear', 78: 'hair drier', 79: 'toothbrush'} class YOLOv4: def",
"copy of this software and associated documentation files (the \"Software\"),",
"classes_path self.weights_path = weights_path self.input_shape = input_shape self.model = yolo_main(shape",
"or (classes_path is None): raise RuntimeError ('weights_path AND classes_path should",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL",
"including without limitation the rights to use, copy, modify, merge,",
"OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR",
"0 self.input_shape = 0 self.output_path = \"\" def load_model(self, weights_path:str",
"SOFTWARE. \"\"\" from visual_perception.Detection.yolov4.tf import YOLOv4 as yolo_main import numpy",
"CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS",
"IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER",
"'carrot', 52: 'hot dog', 53: 'pizza', 54: 'donut', 55: 'cake',",
"img:np.ndarray, output_path:str, iou = 0.45, score = 0.25, custom_objects:dict =",
"class TinyYOLOv4: def __init__(self): self.weights_path = \"\" self.model = None",
"'cow', 20: 'elephant', 21: 'bear', 22: 'zebra', 23: 'giraffe', 24:",
"'cake', 56: 'chair', 57: 'couch', 58: 'potted plant', 59: 'bed',",
"IN THE SOFTWARE. \"\"\" from visual_perception.Detection.yolov4.tf import YOLOv4 as yolo_main",
"without limitation the rights to use, copy, modify, merge, publish,",
"18: 'sheep', 19: 'cow', 20: 'elephant', 21: 'bear', 22: 'zebra',",
"= None, input_shape:int = 608): if (weights_path is None) or",
"self.yolo_classes = \"\" self.iou = 0 self.score = 0 self.input_shape",
"weights_type = 'yolo') def predict(self, img:np.ndarray, output_path:str, iou = 0.4,",
"debug=True): self.output_path = output_path self.iou = iou self.score = score",
"'dining table', 61: 'toilet', 62: 'tv', 63: 'laptop', 64: 'mouse',",
"'valid': boxes.append(list(pred_bboxes[i])) boxes = np.array(boxes) res = self.model.draw_bboxes(img, boxes) if",
"'zebra', 23: 'giraffe', 24: 'backpack', 25: 'umbrella', 26: 'handbag', 27:",
"restriction, including without limitation the rights to use, copy, modify,",
"61: 'toilet', 62: 'tv', 63: 'laptop', 64: 'mouse', 65: 'remote',",
"74: 'clock', 75: 'vase', 76: 'scissors', 77: 'teddy bear', 78:",
"load_model(self, weights_path:str = None, classes_path:str = None, input_shape:int = 0):",
"to permit persons to whom the Software is furnished to",
"None): for i in range(len(pred_bboxes)): check_name = labels[pred_bboxes[i][4]] check =",
"weights_type = 'yolo') def predict(self, img:np.ndarray, output_path:str, iou = 0.45,",
"<reponame>SSusantAchary/Visual-Perception \"\"\" MIT License Copyright (c) 2020 <NAME> <<EMAIL>> Permission",
"OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"sign', 12: 'parking meter', 13: 'bench', 14: 'bird', 15: 'cat',",
"= 0.07, custom_objects:dict = None, debug=True): self.output_path = output_path self.iou",
"'wine glass', 41: 'cup', 42: 'fork', 43: 'knife', 44: 'spoon',",
"OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR",
"Copyright (c) 2020 <NAME> <<EMAIL>> Permission is hereby granted, free",
"deal in the Software without restriction, including without limitation the",
"29: 'frisbee', 30: 'skis', 31: 'snowboard', 32: 'sports ball', 33:",
"self.model = yolo_main(shape = self.input_shape) self.model.classes = self.yolo_classes self.model.make_model() self.model.load_weights(self.weights_path,",
"BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR",
"res class TinyYOLOv4: def __init__(self): self.weights_path = \"\" self.model =",
"'microwave', 69: 'oven', 70: 'toaster', 71: 'sink', 72: 'refrigerator', 73:",
"0.07, custom_objects:dict = None, debug=True): self.output_path = output_path self.iou =",
"self.score) boxes = [] if (custom_objects != None): for i",
"ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO",
"distribute, sublicense, and/or sell copies of the Software, and to",
"'bed', 60: 'dining table', 61: 'toilet', 62: 'tv', 63: 'laptop',",
"73: 'book', 74: 'clock', 75: 'vase', 76: 'scissors', 77: 'teddy",
"iou = 0.45, score = 0.25, custom_objects:dict = None, debug=True):",
"if debug: cv2.imwrite(self.output_path, res) return res class TinyYOLOv4: def __init__(self):",
"0): if (weights_path is None) or (classes_path is None): raise",
"OTHER DEALINGS IN THE SOFTWARE. \"\"\" from visual_perception.Detection.yolov4.tf import YOLOv4",
"36: 'skateboard', 37: 'surfboard', 38: 'tennis racket', 39: 'bottle', 40:",
"PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR",
"'tie', 28: 'suitcase', 29: 'frisbee', 30: 'skis', 31: 'snowboard', 32:",
"= input_shape self.model = yolo_main(shape = self.input_shape) self.model.classes = self.yolo_classes",
"8: 'boat', 9: 'traffic light', 10: 'fire hydrant', 11: 'stop",
"weights_path self.input_shape = input_shape self.model = yolo_main(shape = self.input_shape) self.model.classes",
"the Software, and to permit persons to whom the Software",
"53: 'pizza', 54: 'donut', 55: 'cake', 56: 'chair', 57: 'couch',",
"and associated documentation files (the \"Software\"), to deal in the",
"21: 'bear', 22: 'zebra', 23: 'giraffe', 24: 'backpack', 25: 'umbrella',",
"3: 'motorcycle', 4: 'airplane', 5: 'bus', 6: 'train', 7: 'truck',",
"2: 'car', 3: 'motorcycle', 4: 'airplane', 5: 'bus', 6: 'train',",
"glove', 36: 'skateboard', 37: 'surfboard', 38: 'tennis racket', 39: 'bottle',",
"the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY",
"to whom the Software is furnished to do so, subject",
"self.model.draw_bboxes(img, boxes) if debug: cv2.imwrite(self.output_path, res) else: res = self.model.draw_bboxes(img,",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT",
"<<EMAIL>> Permission is hereby granted, free of charge, to any",
"YOLOv4 as yolo_main import numpy as np import cv2 labels",
"self.input_shape = input_shape self.model = yolo_main(tiny = True, shape =",
"True, shape = self.input_shape) self.model.classes = self.yolo_classes self.model.make_model() self.model.load_weights(self.weights_path, weights_type",
"'bench', 14: 'bird', 15: 'cat', 16: 'dog', 17: 'horse', 18:",
"def __init__(self): self.weights_path = \"\" self.model = None self.yolo_classes =",
"'baseball bat', 35: 'baseball glove', 36: 'skateboard', 37: 'surfboard', 38:",
"self.model = yolo_main(tiny = True, shape = self.input_shape) self.model.classes =",
"44: 'spoon', 45: 'bowl', 46: 'banana', 47: 'apple', 48: 'sandwich',",
"WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT",
"def load_model(self, weights_path:str = None, classes_path:str = None, input_shape:int =",
"42: 'fork', 43: 'knife', 44: 'spoon', 45: 'bowl', 46: 'banana',",
"import cv2 labels = {0: 'person', 1: 'bicycle', 2: 'car',",
"phone', 68: 'microwave', 69: 'oven', 70: 'toaster', 71: 'sink', 72:",
"14: 'bird', 15: 'cat', 16: 'dog', 17: 'horse', 18: 'sheep',",
"TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE",
"= labels[pred_bboxes[i][4]] check = custom_objects.get(check_name, 'invalid') if check == 'invalid':",
"70: 'toaster', 71: 'sink', 72: 'refrigerator', 73: 'book', 74: 'clock',",
"input_shape self.model = yolo_main(tiny = True, shape = self.input_shape) self.model.classes",
"'cell phone', 68: 'microwave', 69: 'oven', 70: 'toaster', 71: 'sink',",
"of the Software, and to permit persons to whom the",
"this software and associated documentation files (the \"Software\"), to deal",
"'refrigerator', 73: 'book', 74: 'clock', 75: 'vase', 76: 'scissors', 77:",
"34: 'baseball bat', 35: 'baseball glove', 36: 'skateboard', 37: 'surfboard',",
"self.weights_path = \"\" self.model = None self.yolo_classes = \"\" self.iou",
"all copies or substantial portions of the Software. THE SOFTWARE",
"49: 'orange', 50: 'broccoli', 51: 'carrot', 52: 'hot dog', 53:",
"'toaster', 71: 'sink', 72: 'refrigerator', 73: 'book', 74: 'clock', 75:",
"(the \"Software\"), to deal in the Software without restriction, including",
"merge, publish, distribute, sublicense, and/or sell copies of the Software,",
"'cat', 16: 'dog', 17: 'horse', 18: 'sheep', 19: 'cow', 20:",
"5: 'bus', 6: 'train', 7: 'truck', 8: 'boat', 9: 'traffic",
"in range(len(pred_bboxes)): check_name = labels[pred_bboxes[i][4]] check = custom_objects.get(check_name, 'invalid') if",
"yolo_main import numpy as np import cv2 labels = {0:",
"'remote', 66: 'keyboard', 67: 'cell phone', 68: 'microwave', 69: 'oven',",
"so, subject to the following conditions: The above copyright notice",
"PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
"\"\" self.iou = 0 self.score = 0 self.input_shape = 0",
"charge, to any person obtaining a copy of this software",
"to do so, subject to the following conditions: The above",
"'boat', 9: 'traffic light', 10: 'fire hydrant', 11: 'stop sign',",
"WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"7: 'truck', 8: 'boat', 9: 'traffic light', 10: 'fire hydrant',",
"ball', 33: 'kite', 34: 'baseball bat', 35: 'baseball glove', 36:",
"'mouse', 65: 'remote', 66: 'keyboard', 67: 'cell phone', 68: 'microwave',",
"following conditions: The above copyright notice and this permission notice",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY",
"= None, classes_path:str = None, input_shape:int = 0): if (weights_path",
"'skateboard', 37: 'surfboard', 38: 'tennis racket', 39: 'bottle', 40: 'wine",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,",
"'cup', 42: 'fork', 43: 'knife', 44: 'spoon', 45: 'bowl', 46:",
"in the Software without restriction, including without limitation the rights",
"permission notice shall be included in all copies or substantial",
"if (weights_path is None) or (classes_path is None): raise RuntimeError",
"import numpy as np import cv2 labels = {0: 'person',",
"0.45, score = 0.25, custom_objects:dict = None, debug=True): self.output_path =",
"25: 'umbrella', 26: 'handbag', 27: 'tie', 28: 'suitcase', 29: 'frisbee',",
"self.output_path = output_path self.iou = iou self.score = score #img",
"SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
"BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER",
"'elephant', 21: 'bear', 22: 'zebra', 23: 'giraffe', 24: 'backpack', 25:",
"self.iou, score_threshold = self.score) boxes = [] if (custom_objects !=",
"None, classes_path:str = None, input_shape:int = 0): if (weights_path is",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS",
"class YOLOv4: def __init__(self): self.weights_path = \"\" self.model = None",
"debug: cv2.imwrite(self.output_path, res) return res class TinyYOLOv4: def __init__(self): self.weights_path",
"HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,",
"= \"\" self.model = None self.yolo_classes = \"\" self.iou =",
"self.score = 0 self.input_shape = 0 self.output_path = \"\" def",
"copyright notice and this permission notice shall be included in",
"= weights_path self.input_shape = input_shape self.model = yolo_main(tiny = True,",
"predict(self, img:np.ndarray, output_path:str, iou = 0.4, score = 0.07, custom_objects:dict",
"'tv', 63: 'laptop', 64: 'mouse', 65: 'remote', 66: 'keyboard', 67:",
"be None.') self.yolo_classes = classes_path self.weights_path = weights_path self.input_shape =",
"OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\"",
"0 self.score = 0 self.input_shape = 0 self.output_path = \"\"",
"self.weights_path = weights_path self.input_shape = input_shape self.model = yolo_main(shape =",
"and to permit persons to whom the Software is furnished",
"copies or substantial portions of the Software. THE SOFTWARE IS",
"License Copyright (c) 2020 <NAME> <<EMAIL>> Permission is hereby granted,",
"OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED",
"score = 0.07, custom_objects:dict = None, debug=True): self.output_path = output_path",
"30: 'skis', 31: 'snowboard', 32: 'sports ball', 33: 'kite', 34:",
"DEALINGS IN THE SOFTWARE. \"\"\" from visual_perception.Detection.yolov4.tf import YOLOv4 as",
"52: 'hot dog', 53: 'pizza', 54: 'donut', 55: 'cake', 56:",
"light', 10: 'fire hydrant', 11: 'stop sign', 12: 'parking meter',",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
"SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY",
"'laptop', 64: 'mouse', 65: 'remote', 66: 'keyboard', 67: 'cell phone',",
"'orange', 50: 'broccoli', 51: 'carrot', 52: 'hot dog', 53: 'pizza',",
"output_path self.iou = iou self.score = score #img = np.array(Image.open(img))[...,",
"= yolo_main(tiny = True, shape = self.input_shape) self.model.classes = self.yolo_classes",
"67: 'cell phone', 68: 'microwave', 69: 'oven', 70: 'toaster', 71:",
"whom the Software is furnished to do so, subject to",
"'fire hydrant', 11: 'stop sign', 12: 'parking meter', 13: 'bench',",
"'kite', 34: 'baseball bat', 35: 'baseball glove', 36: 'skateboard', 37:",
"55: 'cake', 56: 'chair', 57: 'couch', 58: 'potted plant', 59:",
"0.25, custom_objects:dict = None, debug=True): self.output_path = output_path self.iou =",
"np import cv2 labels = {0: 'person', 1: 'bicycle', 2:",
"AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT",
"YOLOv4: def __init__(self): self.weights_path = \"\" self.model = None self.yolo_classes",
"boxes.append(list(pred_bboxes[i])) boxes = np.array(boxes) res = self.model.draw_bboxes(img, boxes) if debug:",
"'umbrella', 26: 'handbag', 27: 'tie', 28: 'suitcase', 29: 'frisbee', 30:",
"in all copies or substantial portions of the Software. THE",
"obtaining a copy of this software and associated documentation files",
"'person', 1: 'bicycle', 2: 'car', 3: 'motorcycle', 4: 'airplane', 5:",
"input_shape self.model = yolo_main(shape = self.input_shape) self.model.classes = self.yolo_classes self.model.make_model()",
"None self.yolo_classes = \"\" self.iou = 0 self.score = 0",
"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN",
"\"\" def load_model(self, weights_path:str = None, classes_path:str = None, input_shape:int",
"score = 0.25, custom_objects:dict = None, debug=True): self.output_path = output_path",
"USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" from visual_perception.Detection.yolov4.tf",
"of this software and associated documentation files (the \"Software\"), to",
"OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR",
"a copy of this software and associated documentation files (the",
"OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE",
"= np.array(Image.open(img))[..., ::-1] pred_bboxes = self.model.predict(img, iou_threshold = self.iou, score_threshold",
"custom_objects.get(check_name, 'invalid') if check == 'invalid': continue elif check ==",
"sublicense, and/or sell copies of the Software, and to permit",
"pred_bboxes) if debug: cv2.imwrite(self.output_path, res) return res class TinyYOLOv4: def",
"racket', 39: 'bottle', 40: 'wine glass', 41: 'cup', 42: 'fork',",
"2020 <NAME> <<EMAIL>> Permission is hereby granted, free of charge,",
"LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR",
"iou = 0.4, score = 0.07, custom_objects:dict = None, debug=True):",
"self.model.predict(img, iou_threshold = self.iou, score_threshold = self.score) boxes = []",
"76: 'scissors', 77: 'teddy bear', 78: 'hair drier', 79: 'toothbrush'}",
"= custom_objects.get(check_name, 'invalid') if check == 'invalid': continue elif check",
"27: 'tie', 28: 'suitcase', 29: 'frisbee', 30: 'skis', 31: 'snowboard',",
"__init__(self): self.weights_path = \"\" self.model = None self.yolo_classes = \"\"",
"OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN",
"self.model.make_model() self.model.load_weights(self.weights_path, weights_type = 'yolo') def predict(self, img:np.ndarray, output_path:str, iou",
"'baseball glove', 36: 'skateboard', 37: 'surfboard', 38: 'tennis racket', 39:",
"= iou self.score = score #img = np.array(Image.open(img))[..., ::-1] pred_bboxes",
"'backpack', 25: 'umbrella', 26: 'handbag', 27: 'tie', 28: 'suitcase', 29:",
"'pizza', 54: 'donut', 55: 'cake', 56: 'chair', 57: 'couch', 58:",
"CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF",
"np.array(boxes) res = self.model.draw_bboxes(img, boxes) if debug: cv2.imwrite(self.output_path, res) else:",
"this permission notice shall be included in all copies or",
"69: 'oven', 70: 'toaster', 71: 'sink', 72: 'refrigerator', 73: 'book',",
"::-1] pred_bboxes = self.model.predict(img, iou_threshold = self.iou, score_threshold = self.score)",
"= 0 self.score = 0 self.input_shape = 0 self.output_path =",
"CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN",
"above copyright notice and this permission notice shall be included",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",
"numpy as np import cv2 labels = {0: 'person', 1:",
"'bottle', 40: 'wine glass', 41: 'cup', 42: 'fork', 43: 'knife',",
"= {0: 'person', 1: 'bicycle', 2: 'car', 3: 'motorcycle', 4:",
"'oven', 70: 'toaster', 71: 'sink', 72: 'refrigerator', 73: 'book', 74:",
"'surfboard', 38: 'tennis racket', 39: 'bottle', 40: 'wine glass', 41:",
"pred_bboxes = self.model.predict(img, iou_threshold = self.iou, score_threshold = self.score) boxes",
"75: 'vase', 76: 'scissors', 77: 'teddy bear', 78: 'hair drier',",
"'car', 3: 'motorcycle', 4: 'airplane', 5: 'bus', 6: 'train', 7:",
"check == 'valid': boxes.append(list(pred_bboxes[i])) boxes = np.array(boxes) res = self.model.draw_bboxes(img,",
"= 0.25, custom_objects:dict = None, debug=True): self.output_path = output_path self.iou",
"\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,",
"OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" from visual_perception.Detection.yolov4.tf import",
"self.model.draw_bboxes(img, pred_bboxes) if debug: cv2.imwrite(self.output_path, res) return res class TinyYOLOv4:",
"IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING",
"THE SOFTWARE. \"\"\" from visual_perception.Detection.yolov4.tf import YOLOv4 as yolo_main import",
"KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE",
"is furnished to do so, subject to the following conditions:",
"= 0): if (weights_path is None) or (classes_path is None):",
"self.score = score #img = np.array(Image.open(img))[..., ::-1] pred_bboxes = self.model.predict(img,",
"= 0 self.output_path = \"\" def load_model(self, weights_path:str = None,",
"33: 'kite', 34: 'baseball bat', 35: 'baseball glove', 36: 'skateboard',",
"None) or (classes_path is None): raise RuntimeError ('weights_path AND classes_path",
"= 0.4, score = 0.07, custom_objects:dict = None, debug=True): self.output_path",
"to any person obtaining a copy of this software and",
"= 'yolo') def predict(self, img:np.ndarray, output_path:str, iou = 0.45, score",
"'sports ball', 33: 'kite', 34: 'baseball bat', 35: 'baseball glove',",
"shall be included in all copies or substantial portions of",
"person obtaining a copy of this software and associated documentation",
"MIT License Copyright (c) 2020 <NAME> <<EMAIL>> Permission is hereby",
"FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN",
"shape = self.input_shape) self.model.classes = self.yolo_classes self.model.make_model() self.model.load_weights(self.weights_path, weights_type =",
"None, debug=True): self.output_path = output_path self.iou = iou self.score =",
"output_path:str, iou = 0.45, score = 0.25, custom_objects:dict = None,",
"and this permission notice shall be included in all copies",
"72: 'refrigerator', 73: 'book', 74: 'clock', 75: 'vase', 76: 'scissors',",
"= self.iou, score_threshold = self.score) boxes = [] if (custom_objects",
"debug: cv2.imwrite(self.output_path, res) else: res = self.model.draw_bboxes(img, pred_bboxes) if debug:",
"10: 'fire hydrant', 11: 'stop sign', 12: 'parking meter', 13:",
"(classes_path is None): raise RuntimeError ('weights_path AND classes_path should not",
"'yolo') def predict(self, img:np.ndarray, output_path:str, iou = 0.4, score =",
"AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT",
"iou self.score = score #img = np.array(Image.open(img))[..., ::-1] pred_bboxes =",
"'invalid') if check == 'invalid': continue elif check == 'valid':",
"= weights_path self.input_shape = input_shape self.model = yolo_main(shape = self.input_shape)",
"'stop sign', 12: 'parking meter', 13: 'bench', 14: 'bird', 15:",
"res = self.model.draw_bboxes(img, boxes) if debug: cv2.imwrite(self.output_path, res) else: res",
"<NAME> <<EMAIL>> Permission is hereby granted, free of charge, to",
"OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE",
"free of charge, to any person obtaining a copy of",
"'sink', 72: 'refrigerator', 73: 'book', 74: 'clock', 75: 'vase', 76:",
"IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE",
"\"\"\" from visual_perception.Detection.yolov4.tf import YOLOv4 as yolo_main import numpy as",
"'clock', 75: 'vase', 76: 'scissors', 77: 'teddy bear', 78: 'hair",
"IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT",
"the Software is furnished to do so, subject to the",
"Software, and to permit persons to whom the Software is",
"71: 'sink', 72: 'refrigerator', 73: 'book', 74: 'clock', 75: 'vase',",
"SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.",
"visual_perception.Detection.yolov4.tf import YOLOv4 as yolo_main import numpy as np import",
"45: 'bowl', 46: 'banana', 47: 'apple', 48: 'sandwich', 49: 'orange',",
"rights to use, copy, modify, merge, publish, distribute, sublicense, and/or",
"63: 'laptop', 64: 'mouse', 65: 'remote', 66: 'keyboard', 67: 'cell",
"60: 'dining table', 61: 'toilet', 62: 'tv', 63: 'laptop', 64:",
"23: 'giraffe', 24: 'backpack', 25: 'umbrella', 26: 'handbag', 27: 'tie',",
"documentation files (the \"Software\"), to deal in the Software without",
"= yolo_main(shape = self.input_shape) self.model.classes = self.yolo_classes self.model.make_model() self.model.load_weights(self.weights_path, weights_type",
"'donut', 55: 'cake', 56: 'chair', 57: 'couch', 58: 'potted plant',",
"\"\" self.model = None self.yolo_classes = \"\" self.iou = 0",
"without restriction, including without limitation the rights to use, copy,",
"57: 'couch', 58: 'potted plant', 59: 'bed', 60: 'dining table',",
"41: 'cup', 42: 'fork', 43: 'knife', 44: 'spoon', 45: 'bowl',",
"TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION",
"[] if (custom_objects != None): for i in range(len(pred_bboxes)): check_name",
"= self.input_shape) self.model.classes = self.yolo_classes self.model.make_model() self.model.load_weights(self.weights_path, weights_type = 'yolo')",
"COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"RuntimeError ('weights_path AND classes_path should not be None.') self.yolo_classes =",
"43: 'knife', 44: 'spoon', 45: 'bowl', 46: 'banana', 47: 'apple',",
"check_name = labels[pred_bboxes[i][4]] check = custom_objects.get(check_name, 'invalid') if check ==",
"608): if (weights_path is None) or (classes_path is None): raise",
"'invalid': continue elif check == 'valid': boxes.append(list(pred_bboxes[i])) boxes = np.array(boxes)",
"19: 'cow', 20: 'elephant', 21: 'bear', 22: 'zebra', 23: 'giraffe',",
"77: 'teddy bear', 78: 'hair drier', 79: 'toothbrush'} class YOLOv4:",
"62: 'tv', 63: 'laptop', 64: 'mouse', 65: 'remote', 66: 'keyboard',",
"65: 'remote', 66: 'keyboard', 67: 'cell phone', 68: 'microwave', 69:",
"NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE",
"img:np.ndarray, output_path:str, iou = 0.4, score = 0.07, custom_objects:dict =",
"use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies",
"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR",
"'sheep', 19: 'cow', 20: 'elephant', 21: 'bear', 22: 'zebra', 23:",
"import YOLOv4 as yolo_main import numpy as np import cv2",
"'parking meter', 13: 'bench', 14: 'bird', 15: 'cat', 16: 'dog',",
"granted, free of charge, to any person obtaining a copy",
"self.weights_path = weights_path self.input_shape = input_shape self.model = yolo_main(tiny =",
"bat', 35: 'baseball glove', 36: 'skateboard', 37: 'surfboard', 38: 'tennis",
"else: res = self.model.draw_bboxes(img, pred_bboxes) if debug: cv2.imwrite(self.output_path, res) return",
"= self.score) boxes = [] if (custom_objects != None): for",
"'vase', 76: 'scissors', 77: 'teddy bear', 78: 'hair drier', 79:",
"24: 'backpack', 25: 'umbrella', 26: 'handbag', 27: 'tie', 28: 'suitcase',",
"of charge, to any person obtaining a copy of this",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS",
"#img = np.array(Image.open(img))[..., ::-1] pred_bboxes = self.model.predict(img, iou_threshold = self.iou,",
"cv2.imwrite(self.output_path, res) return res class TinyYOLOv4: def __init__(self): self.weights_path =",
"from visual_perception.Detection.yolov4.tf import YOLOv4 as yolo_main import numpy as np",
"Permission is hereby granted, free of charge, to any person",
"!= None): for i in range(len(pred_bboxes)): check_name = labels[pred_bboxes[i][4]] check",
"res) return res class TinyYOLOv4: def __init__(self): self.weights_path = \"\"",
"The above copyright notice and this permission notice shall be",
"cv2.imwrite(self.output_path, res) else: res = self.model.draw_bboxes(img, pred_bboxes) if debug: cv2.imwrite(self.output_path,",
"'toilet', 62: 'tv', 63: 'laptop', 64: 'mouse', 65: 'remote', 66:",
"'broccoli', 51: 'carrot', 52: 'hot dog', 53: 'pizza', 54: 'donut',",
"bear', 78: 'hair drier', 79: 'toothbrush'} class YOLOv4: def __init__(self):",
"associated documentation files (the \"Software\"), to deal in the Software",
"ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION",
"66: 'keyboard', 67: 'cell phone', 68: 'microwave', 69: 'oven', 70:",
"THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" from",
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES",
"WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING"
] |
[
"host, port): host = host port = port client =",
"= host port = port client = mqtt.Client() def connect():",
"= 'localhost' PORT = 1883 class MQTTConnector: def __init__(self, host,",
"client = mqtt.Client() def connect(): self.client.connect(self.host, self.port, 60) def run(self):",
"def connect(): self.client.connect(self.host, self.port, 60) def run(self): self.client.loop_forever() class MQTTSubscriber:",
"def run(self): self.client.loop_forever() class MQTTSubscriber: def __init__(self, *args, **kwargs): super(MQTTSubscriber,",
"def __init__(self, *args, **kwargs): super(MQTTSubscriber, self).__init__(*args, **kwargs) class MQTTPublisher: def",
"<reponame>rishab-rb/MyIOTMap import paho.client as mqtt HOST = 'localhost' PORT =",
"paho.client as mqtt HOST = 'localhost' PORT = 1883 class",
"host = host port = port client = mqtt.Client() def",
"class MQTTSubscriber: def __init__(self, *args, **kwargs): super(MQTTSubscriber, self).__init__(*args, **kwargs) class",
"MQTTSubscriber: def __init__(self, *args, **kwargs): super(MQTTSubscriber, self).__init__(*args, **kwargs) class MQTTPublisher:",
"mqtt HOST = 'localhost' PORT = 1883 class MQTTConnector: def",
"host port = port client = mqtt.Client() def connect(): self.client.connect(self.host,",
"self.port, 60) def run(self): self.client.loop_forever() class MQTTSubscriber: def __init__(self, *args,",
"= mqtt.Client() def connect(): self.client.connect(self.host, self.port, 60) def run(self): self.client.loop_forever()",
"= port client = mqtt.Client() def connect(): self.client.connect(self.host, self.port, 60)",
"60) def run(self): self.client.loop_forever() class MQTTSubscriber: def __init__(self, *args, **kwargs):",
"1883 class MQTTConnector: def __init__(self, host, port): host = host",
"__init__(self, *args, **kwargs): super(MQTTSubscriber, self).__init__(*args, **kwargs) class MQTTPublisher: def __init__(self,",
"MQTTConnector: def __init__(self, host, port): host = host port =",
"as mqtt HOST = 'localhost' PORT = 1883 class MQTTConnector:",
"port = port client = mqtt.Client() def connect(): self.client.connect(self.host, self.port,",
"run(self): self.client.loop_forever() class MQTTSubscriber: def __init__(self, *args, **kwargs): super(MQTTSubscriber, self).__init__(*args,",
"'localhost' PORT = 1883 class MQTTConnector: def __init__(self, host, port):",
"port client = mqtt.Client() def connect(): self.client.connect(self.host, self.port, 60) def",
"PORT = 1883 class MQTTConnector: def __init__(self, host, port): host",
"self.client.connect(self.host, self.port, 60) def run(self): self.client.loop_forever() class MQTTSubscriber: def __init__(self,",
"*args, **kwargs): super(MQTTSubscriber, self).__init__(*args, **kwargs) class MQTTPublisher: def __init__(self, host)",
"import paho.client as mqtt HOST = 'localhost' PORT = 1883",
"HOST = 'localhost' PORT = 1883 class MQTTConnector: def __init__(self,",
"self.client.loop_forever() class MQTTSubscriber: def __init__(self, *args, **kwargs): super(MQTTSubscriber, self).__init__(*args, **kwargs)",
"port): host = host port = port client = mqtt.Client()",
"= 1883 class MQTTConnector: def __init__(self, host, port): host =",
"connect(): self.client.connect(self.host, self.port, 60) def run(self): self.client.loop_forever() class MQTTSubscriber: def",
"mqtt.Client() def connect(): self.client.connect(self.host, self.port, 60) def run(self): self.client.loop_forever() class",
"class MQTTConnector: def __init__(self, host, port): host = host port",
"def __init__(self, host, port): host = host port = port",
"__init__(self, host, port): host = host port = port client"
] |
[
"[item for sublist in temp_list for item in sublist] #",
"de Enfermería\" text2 = \"ESCUELA DE ENFERMERIA\" file = open(\"scripts/spacy_files/data/escuelas.json\",",
"unaccented_schools.append(unidecode.unidecode(sch).lower()) return unaccented_schools def set_school_to_unaccent(escuelas): escuelas = unaccent_list(escuelas) return escuelas",
"= \"scripts/spacy_files/data/thesis_200_with_school.csv\" df = pd.read_csv(csv_source) df = df[df['isScan']==False] df =",
"import displacy import unidecode import pandas as pd import numpy",
"text1_u.lower() text2_l_u = unidecode.unidecode(text2).lower() print(text1_l_u, \"<-->\", text2_l_u) if text1_l_u ==",
"json.load(file) temp_list = [] for facultad in file: temp_list.append(facultad['escuela']) #print(facultad['escuela'])",
"= json.load(file) temp_list = [] for facultad in file: temp_list.append(facultad['escuela'])",
"main import spacy import json from spacy import displacy import",
"print(text1_l_u, \"<-->\", text2_l_u) if text1_l_u == text2_l_u: print(text1, \" is",
"dict((e,i) for i,e in enumerate(schools)) return myDict def set_schools_accents(row, dict,",
"list flat #print(escuelas) text1_u = unidecode.unidecode(text1) text1_l_u = text1_u.lower() text2_l_u",
"u_escuelas = set_school_to_unaccent(escuelas) u_escuelas_dict = create_dictionary(u_escuelas) escuelas_dict = create_dictionary(escuelas) print(u_escuelas_dict)",
"for facultad in file: temp_list.append(facultad['escuela']) #print(facultad['escuela']) escuelas = [item for",
"file = open(\"scripts/spacy_files/data/escuelas.json\", \"r\") file = json.load(file) temp_list = []",
"df[df['isScan']==False] df = df.sort_values('isScan', ascending=False) text1= \"Escuela de Enfermería\" text2",
"\"ESCUELA DE ENFERMERIA\" file = open(\"scripts/spacy_files/data/escuelas.json\", \"r\") file = json.load(file)",
"DE ENFERMERIA\" file = open(\"scripts/spacy_files/data/escuelas.json\", \"r\") file = json.load(file) temp_list",
"text2_l_u) if text1_l_u == text2_l_u: print(text1, \" is correct.\") def",
"accent_list: unaccented_schools.append(unidecode.unidecode(sch).lower()) return unaccented_schools def set_school_to_unaccent(escuelas): escuelas = unaccent_list(escuelas) return",
"#!/bin/env python from black import main import spacy import json",
"[] for sch in accent_list: unaccented_schools.append(unidecode.unidecode(sch).lower()) return unaccented_schools def set_school_to_unaccent(escuelas):",
"pandas as pd import numpy as np import os csv_source",
"in sublist] # make the list flat #print(escuelas) text1_u =",
"text2_l_u: print(text1, \" is correct.\") def unaccent_list(accent_list): unaccented_schools = []",
"open(\"scripts/spacy_files/data/escuelas.json\", \"r\") file = json.load(file) temp_list = [] for facultad",
"escuelas = unaccent_list(escuelas) return escuelas def create_dictionary(schools): myDict = dict((e,i)",
"spacy import json from spacy import displacy import unidecode import",
"displacy import unidecode import pandas as pd import numpy as",
"myDict def set_schools_accents(row, dict, dict_c): index = dict.get(row.lower()) key_list =",
"file = json.load(file) temp_list = [] for facultad in file:",
"\"<-->\", text2_l_u) if text1_l_u == text2_l_u: print(text1, \" is correct.\")",
"print(text1, \" is correct.\") def unaccent_list(accent_list): unaccented_schools = [] for",
"the list flat #print(escuelas) text1_u = unidecode.unidecode(text1) text1_l_u = text1_u.lower()",
"= list(dict_c.values()) try: position = val_list.index(index) key_list[position] except: return None",
"create_dictionary(u_escuelas) escuelas_dict = create_dictionary(escuelas) print(u_escuelas_dict) print(escuelas_dict) print(set_schools_accents(\"No school\", u_escuelas_dict, escuelas_dict))",
"\"__main__\": u_escuelas = set_school_to_unaccent(escuelas) u_escuelas_dict = create_dictionary(u_escuelas) escuelas_dict = create_dictionary(escuelas)",
"return None if __name__ == \"__main__\": u_escuelas = set_school_to_unaccent(escuelas) u_escuelas_dict",
"def set_school_to_unaccent(escuelas): escuelas = unaccent_list(escuelas) return escuelas def create_dictionary(schools): myDict",
"list(dict_c.values()) try: position = val_list.index(index) key_list[position] except: return None if",
"return escuelas def create_dictionary(schools): myDict = dict((e,i) for i,e in",
"position = val_list.index(index) key_list[position] except: return None if __name__ ==",
"in temp_list for item in sublist] # make the list",
"csv_source = \"scripts/spacy_files/data/thesis_200_with_school.csv\" df = pd.read_csv(csv_source) df = df[df['isScan']==False] df",
"except: return None if __name__ == \"__main__\": u_escuelas = set_school_to_unaccent(escuelas)",
"unaccent_list(escuelas) return escuelas def create_dictionary(schools): myDict = dict((e,i) for i,e",
"key_list[position] except: return None if __name__ == \"__main__\": u_escuelas =",
"= pd.read_csv(csv_source) df = df[df['isScan']==False] df = df.sort_values('isScan', ascending=False) text1=",
"return unaccented_schools def set_school_to_unaccent(escuelas): escuelas = unaccent_list(escuelas) return escuelas def",
"myDict = dict((e,i) for i,e in enumerate(schools)) return myDict def",
"set_school_to_unaccent(escuelas) u_escuelas_dict = create_dictionary(u_escuelas) escuelas_dict = create_dictionary(escuelas) print(u_escuelas_dict) print(escuelas_dict) print(set_schools_accents(\"No",
"temp_list.append(facultad['escuela']) #print(facultad['escuela']) escuelas = [item for sublist in temp_list for",
"= unidecode.unidecode(text1) text1_l_u = text1_u.lower() text2_l_u = unidecode.unidecode(text2).lower() print(text1_l_u, \"<-->\",",
"os csv_source = \"scripts/spacy_files/data/thesis_200_with_school.csv\" df = pd.read_csv(csv_source) df = df[df['isScan']==False]",
"= df[df['isScan']==False] df = df.sort_values('isScan', ascending=False) text1= \"Escuela de Enfermería\"",
"= \"ESCUELA DE ENFERMERIA\" file = open(\"scripts/spacy_files/data/escuelas.json\", \"r\") file =",
"unidecode import pandas as pd import numpy as np import",
"df.sort_values('isScan', ascending=False) text1= \"Escuela de Enfermería\" text2 = \"ESCUELA DE",
"i,e in enumerate(schools)) return myDict def set_schools_accents(row, dict, dict_c): index",
"escuelas = [item for sublist in temp_list for item in",
"dict.get(row.lower()) key_list = list(dict_c.keys()) val_list = list(dict_c.values()) try: position =",
"in accent_list: unaccented_schools.append(unidecode.unidecode(sch).lower()) return unaccented_schools def set_school_to_unaccent(escuelas): escuelas = unaccent_list(escuelas)",
"as pd import numpy as np import os csv_source =",
"= dict.get(row.lower()) key_list = list(dict_c.keys()) val_list = list(dict_c.values()) try: position",
"\"scripts/spacy_files/data/thesis_200_with_school.csv\" df = pd.read_csv(csv_source) df = df[df['isScan']==False] df = df.sort_values('isScan',",
"pd import numpy as np import os csv_source = \"scripts/spacy_files/data/thesis_200_with_school.csv\"",
"pd.read_csv(csv_source) df = df[df['isScan']==False] df = df.sort_values('isScan', ascending=False) text1= \"Escuela",
"= text1_u.lower() text2_l_u = unidecode.unidecode(text2).lower() print(text1_l_u, \"<-->\", text2_l_u) if text1_l_u",
"val_list.index(index) key_list[position] except: return None if __name__ == \"__main__\": u_escuelas",
"set_school_to_unaccent(escuelas): escuelas = unaccent_list(escuelas) return escuelas def create_dictionary(schools): myDict =",
"import os csv_source = \"scripts/spacy_files/data/thesis_200_with_school.csv\" df = pd.read_csv(csv_source) df =",
"= create_dictionary(u_escuelas) escuelas_dict = create_dictionary(escuelas) print(u_escuelas_dict) print(escuelas_dict) print(set_schools_accents(\"No school\", u_escuelas_dict,",
"if text1_l_u == text2_l_u: print(text1, \" is correct.\") def unaccent_list(accent_list):",
"ENFERMERIA\" file = open(\"scripts/spacy_files/data/escuelas.json\", \"r\") file = json.load(file) temp_list =",
"text2 = \"ESCUELA DE ENFERMERIA\" file = open(\"scripts/spacy_files/data/escuelas.json\", \"r\") file",
"val_list = list(dict_c.values()) try: position = val_list.index(index) key_list[position] except: return",
"make the list flat #print(escuelas) text1_u = unidecode.unidecode(text1) text1_l_u =",
"#print(escuelas) text1_u = unidecode.unidecode(text1) text1_l_u = text1_u.lower() text2_l_u = unidecode.unidecode(text2).lower()",
"= [] for sch in accent_list: unaccented_schools.append(unidecode.unidecode(sch).lower()) return unaccented_schools def",
"= val_list.index(index) key_list[position] except: return None if __name__ == \"__main__\":",
"file: temp_list.append(facultad['escuela']) #print(facultad['escuela']) escuelas = [item for sublist in temp_list",
"sublist in temp_list for item in sublist] # make the",
"black import main import spacy import json from spacy import",
"def unaccent_list(accent_list): unaccented_schools = [] for sch in accent_list: unaccented_schools.append(unidecode.unidecode(sch).lower())",
"import pandas as pd import numpy as np import os",
"python from black import main import spacy import json from",
"for i,e in enumerate(schools)) return myDict def set_schools_accents(row, dict, dict_c):",
"index = dict.get(row.lower()) key_list = list(dict_c.keys()) val_list = list(dict_c.values()) try:",
"df = df.sort_values('isScan', ascending=False) text1= \"Escuela de Enfermería\" text2 =",
"unidecode.unidecode(text1) text1_l_u = text1_u.lower() text2_l_u = unidecode.unidecode(text2).lower() print(text1_l_u, \"<-->\", text2_l_u)",
"temp_list for item in sublist] # make the list flat",
"unidecode.unidecode(text2).lower() print(text1_l_u, \"<-->\", text2_l_u) if text1_l_u == text2_l_u: print(text1, \"",
"df = pd.read_csv(csv_source) df = df[df['isScan']==False] df = df.sort_values('isScan', ascending=False)",
"in enumerate(schools)) return myDict def set_schools_accents(row, dict, dict_c): index =",
"= df.sort_values('isScan', ascending=False) text1= \"Escuela de Enfermería\" text2 = \"ESCUELA",
"numpy as np import os csv_source = \"scripts/spacy_files/data/thesis_200_with_school.csv\" df =",
"set_schools_accents(row, dict, dict_c): index = dict.get(row.lower()) key_list = list(dict_c.keys()) val_list",
"ascending=False) text1= \"Escuela de Enfermería\" text2 = \"ESCUELA DE ENFERMERIA\"",
"== \"__main__\": u_escuelas = set_school_to_unaccent(escuelas) u_escuelas_dict = create_dictionary(u_escuelas) escuelas_dict =",
"= open(\"scripts/spacy_files/data/escuelas.json\", \"r\") file = json.load(file) temp_list = [] for",
"list(dict_c.keys()) val_list = list(dict_c.values()) try: position = val_list.index(index) key_list[position] except:",
"u_escuelas_dict = create_dictionary(u_escuelas) escuelas_dict = create_dictionary(escuelas) print(u_escuelas_dict) print(escuelas_dict) print(set_schools_accents(\"No school\",",
"def set_schools_accents(row, dict, dict_c): index = dict.get(row.lower()) key_list = list(dict_c.keys())",
"None if __name__ == \"__main__\": u_escuelas = set_school_to_unaccent(escuelas) u_escuelas_dict =",
"= unaccent_list(escuelas) return escuelas def create_dictionary(schools): myDict = dict((e,i) for",
"= list(dict_c.keys()) val_list = list(dict_c.values()) try: position = val_list.index(index) key_list[position]",
"df = df[df['isScan']==False] df = df.sort_values('isScan', ascending=False) text1= \"Escuela de",
"__name__ == \"__main__\": u_escuelas = set_school_to_unaccent(escuelas) u_escuelas_dict = create_dictionary(u_escuelas) escuelas_dict",
"== text2_l_u: print(text1, \" is correct.\") def unaccent_list(accent_list): unaccented_schools =",
"spacy import displacy import unidecode import pandas as pd import",
"from spacy import displacy import unidecode import pandas as pd",
"#print(facultad['escuela']) escuelas = [item for sublist in temp_list for item",
"\" is correct.\") def unaccent_list(accent_list): unaccented_schools = [] for sch",
"unaccented_schools = [] for sch in accent_list: unaccented_schools.append(unidecode.unidecode(sch).lower()) return unaccented_schools",
"import json from spacy import displacy import unidecode import pandas",
"import unidecode import pandas as pd import numpy as np",
"sch in accent_list: unaccented_schools.append(unidecode.unidecode(sch).lower()) return unaccented_schools def set_school_to_unaccent(escuelas): escuelas =",
"facultad in file: temp_list.append(facultad['escuela']) #print(facultad['escuela']) escuelas = [item for sublist",
"import spacy import json from spacy import displacy import unidecode",
"return myDict def set_schools_accents(row, dict, dict_c): index = dict.get(row.lower()) key_list",
"escuelas def create_dictionary(schools): myDict = dict((e,i) for i,e in enumerate(schools))",
"\"r\") file = json.load(file) temp_list = [] for facultad in",
"unaccented_schools def set_school_to_unaccent(escuelas): escuelas = unaccent_list(escuelas) return escuelas def create_dictionary(schools):",
"np import os csv_source = \"scripts/spacy_files/data/thesis_200_with_school.csv\" df = pd.read_csv(csv_source) df",
"# make the list flat #print(escuelas) text1_u = unidecode.unidecode(text1) text1_l_u",
"key_list = list(dict_c.keys()) val_list = list(dict_c.values()) try: position = val_list.index(index)",
"json from spacy import displacy import unidecode import pandas as",
"text1_l_u = text1_u.lower() text2_l_u = unidecode.unidecode(text2).lower() print(text1_l_u, \"<-->\", text2_l_u) if",
"dict_c): index = dict.get(row.lower()) key_list = list(dict_c.keys()) val_list = list(dict_c.values())",
"correct.\") def unaccent_list(accent_list): unaccented_schools = [] for sch in accent_list:",
"text1= \"Escuela de Enfermería\" text2 = \"ESCUELA DE ENFERMERIA\" file",
"text1_l_u == text2_l_u: print(text1, \" is correct.\") def unaccent_list(accent_list): unaccented_schools",
"def create_dictionary(schools): myDict = dict((e,i) for i,e in enumerate(schools)) return",
"dict, dict_c): index = dict.get(row.lower()) key_list = list(dict_c.keys()) val_list =",
"temp_list = [] for facultad in file: temp_list.append(facultad['escuela']) #print(facultad['escuela']) escuelas",
"= [item for sublist in temp_list for item in sublist]",
"unaccent_list(accent_list): unaccented_schools = [] for sch in accent_list: unaccented_schools.append(unidecode.unidecode(sch).lower()) return",
"create_dictionary(schools): myDict = dict((e,i) for i,e in enumerate(schools)) return myDict",
"= [] for facultad in file: temp_list.append(facultad['escuela']) #print(facultad['escuela']) escuelas =",
"for sublist in temp_list for item in sublist] # make",
"flat #print(escuelas) text1_u = unidecode.unidecode(text1) text1_l_u = text1_u.lower() text2_l_u =",
"for item in sublist] # make the list flat #print(escuelas)",
"import numpy as np import os csv_source = \"scripts/spacy_files/data/thesis_200_with_school.csv\" df",
"= dict((e,i) for i,e in enumerate(schools)) return myDict def set_schools_accents(row,",
"item in sublist] # make the list flat #print(escuelas) text1_u",
"\"Escuela de Enfermería\" text2 = \"ESCUELA DE ENFERMERIA\" file =",
"= unidecode.unidecode(text2).lower() print(text1_l_u, \"<-->\", text2_l_u) if text1_l_u == text2_l_u: print(text1,",
"for sch in accent_list: unaccented_schools.append(unidecode.unidecode(sch).lower()) return unaccented_schools def set_school_to_unaccent(escuelas): escuelas",
"text2_l_u = unidecode.unidecode(text2).lower() print(text1_l_u, \"<-->\", text2_l_u) if text1_l_u == text2_l_u:",
"try: position = val_list.index(index) key_list[position] except: return None if __name__",
"Enfermería\" text2 = \"ESCUELA DE ENFERMERIA\" file = open(\"scripts/spacy_files/data/escuelas.json\", \"r\")",
"import main import spacy import json from spacy import displacy",
"if __name__ == \"__main__\": u_escuelas = set_school_to_unaccent(escuelas) u_escuelas_dict = create_dictionary(u_escuelas)",
"sublist] # make the list flat #print(escuelas) text1_u = unidecode.unidecode(text1)",
"enumerate(schools)) return myDict def set_schools_accents(row, dict, dict_c): index = dict.get(row.lower())",
"in file: temp_list.append(facultad['escuela']) #print(facultad['escuela']) escuelas = [item for sublist in",
"as np import os csv_source = \"scripts/spacy_files/data/thesis_200_with_school.csv\" df = pd.read_csv(csv_source)",
"from black import main import spacy import json from spacy",
"= set_school_to_unaccent(escuelas) u_escuelas_dict = create_dictionary(u_escuelas) escuelas_dict = create_dictionary(escuelas) print(u_escuelas_dict) print(escuelas_dict)",
"text1_u = unidecode.unidecode(text1) text1_l_u = text1_u.lower() text2_l_u = unidecode.unidecode(text2).lower() print(text1_l_u,",
"is correct.\") def unaccent_list(accent_list): unaccented_schools = [] for sch in",
"[] for facultad in file: temp_list.append(facultad['escuela']) #print(facultad['escuela']) escuelas = [item"
] |
[
"unit-test. \"\"\" agent, environment = self.prepare( environment=environment, min_timesteps=min_timesteps, states=states, actions=actions,",
"<filename>test/unittest_base.py # Copyright 2018 Tensorforce Team. All Rights Reserved. #",
"None: assertion = True else: self.assertTrue(expr=assertion) if assertion: sys.stdout.write('.') sys.stdout.flush()",
"num_values=4), float_state=dict(type='float', shape=(1, 1, 2)), bounded_state=dict(type='float', shape=(), min_value=-0.5, max_value=0.5) )",
"2.0 (the \"License\"); # you may not use this file",
"and num_episodes is None and num_timesteps is None: num_updates =",
"): \"\"\" Generic unit-test. \"\"\" agent, environment = self.prepare( environment=environment,",
"in self.__class__.agent.items(): if key not in agent: agent[key] = value",
"shape' ) def start_tests(self, name=None): \"\"\" Start unit-test method. \"\"\"",
"(num_timesteps is not None) == 1 evaluation = not any([",
"Tensorforce Team. All Rights Reserved. # # Licensed under the",
"from test.unittest_environment import UnittestEnvironment os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' class UnittestBase(object): \"\"\"",
"+ \\ (num_timesteps is not None) == 1 evaluation =",
"self.runner.run( num_episodes=num_episodes, num_timesteps=num_timesteps, num_updates=num_updates, use_tqdm=False, evaluation=evaluation ) self.runner.close() agent.close() environment.close()",
"if min_timesteps is None: min_timesteps = self.__class__.min_timesteps environment = UnittestEnvironment(",
"UnittestBase(object): \"\"\" Unit-test base class. \"\"\" # Unittest num_updates =",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"name is None: sys.stdout.write('\\n{} {}: '.format( datetime.now().strftime('%H:%M:%S'), self.__class__.__name__[4:] )) else:",
"from datetime import datetime import os import sys import warnings",
")) else: sys.stdout.write('\\n{} {} ({}): '.format( datetime.now().strftime('%H:%M:%S'), self.__class__.__name__[4:], name ))",
"{} ({}): '.format( datetime.now().strftime('%H:%M:%S'), self.__class__.__name__[4:], name )) sys.stdout.flush() def finished_test(self,",
"self.__class__.__name__[4:], name )) sys.stdout.flush() def finished_test(self, assertion=None): \"\"\" Finished unit-test.",
"exclude_int_action=False, exclude_float_action=False, exclude_bounded_action=False, require_observe=False, require_all=False, **agent ): \"\"\" Generic unit-test",
"sys.stdout.write('\\n{} {}: '.format( datetime.now().strftime('%H:%M:%S'), self.__class__.__name__[4:] )) else: sys.stdout.write('\\n{} {} ({}):",
"shape=(1,)), int_action=dict(type='int', shape=(2,), num_values=4), float_action=dict(type='float', shape=(1, 1)), bounded_action=dict(type='float', shape=(2,), min_value=-0.5,",
"start_tests(self, name=None): \"\"\" Start unit-test method. \"\"\" if name is",
"# limitations under the License. # ============================================================================== from copy import",
"from tensorforce.environments import Environment from tensorforce.execution import Runner from test.unittest_environment",
"<= 1 if num_updates is None and num_episodes is None",
"self.__class__.num_updates num_episodes = self.__class__.num_episodes num_timesteps = self.__class__.num_timesteps if num_updates is",
"is None: states = deepcopy(self.__class__.states) if actions is None: actions",
"\"\"\" Unit-test base class. \"\"\" # Unittest num_updates = None",
"True else: self.assertTrue(expr=assertion) if assertion: sys.stdout.write('.') sys.stdout.flush() def prepare( self,",
"is None: num_updates = 2 assert (num_updates is not None)",
"num_episodes = self.__class__.num_episodes num_timesteps = self.__class__.num_timesteps if num_updates is None",
"\"\"\" if assertion is None: assertion = True else: self.assertTrue(expr=assertion)",
"False exclude_int_action = False exclude_float_action = False exclude_bounded_action = False",
"states=None, actions=None, exclude_bool_action=False, exclude_int_action=False, exclude_float_action=False, exclude_bounded_action=False, require_observe=False, require_all=False, **agent ):",
"exclude_float_action=exclude_float_action, exclude_bounded_action=exclude_bounded_action, require_observe=require_observe, require_all=require_all, **agent ) self.runner = Runner(agent=agent, environment=environment)",
"use this file except in compliance with the License. #",
"= 2 assert (num_updates is not None) + (num_episodes is",
"tensorforce.agents import Agent from tensorforce.core.layers import Layer from tensorforce.environments import",
"not None) + \\ (num_timesteps is not None) <= 1",
"tensorforce.environments import Environment from tensorforce.execution import Runner from test.unittest_environment import",
"Copyright 2018 Tensorforce Team. All Rights Reserved. # # Licensed",
"= self.__class__.min_timesteps environment = UnittestEnvironment( states=states, actions=actions, min_timesteps=min_timesteps ) elif",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"evaluation = not any([ require_all, require_observe, self.__class__.require_all, self.__class__.require_observe ]) self.runner.run(",
"None: states = deepcopy(self.__class__.states) if actions is None: actions =",
"agent[key] = value if self.__class__.require_all or require_all: config = None",
"Layer from tensorforce.environments import Environment from tensorforce.execution import Runner from",
"License. # You may obtain a copy of the License",
"num_values=4), float_action=dict(type='float', shape=(1, 1)), bounded_action=dict(type='float', shape=(2,), min_value=-0.5, max_value=0.5) ) #",
"num_updates=None, num_episodes=None, num_timesteps=None, environment=None, min_timesteps=None, states=None, actions=None, exclude_bool_action=False, exclude_int_action=False, exclude_float_action=False,",
"is not None) + \\ (num_timesteps is not None) ==",
"= False # Agent agent = dict( update=4, policy=dict(network=dict(type='auto', size=8,",
"under the License is distributed on an \"AS IS\" BASIS,",
"License for the specific language governing permissions and # limitations",
"not None) + \\ (num_timesteps is not None) == 1",
"name )) sys.stdout.flush() def finished_test(self, assertion=None): \"\"\" Finished unit-test. \"\"\"",
"= self.__class__.num_updates num_episodes = self.__class__.num_episodes num_timesteps = self.__class__.num_timesteps if num_updates",
"Reserved. # # Licensed under the Apache License, Version 2.0",
"'.format( datetime.now().strftime('%H:%M:%S'), self.__class__.__name__[4:], name )) sys.stdout.flush() def finished_test(self, assertion=None): \"\"\"",
"self.__class__.agent.items(): if key not in agent: agent[key] = value if",
"{}: '.format( datetime.now().strftime('%H:%M:%S'), self.__class__.__name__[4:] )) else: sys.stdout.write('\\n{} {} ({}): '.format(",
"= None elif self.__class__.require_observe or require_observe: config = dict(api_functions=['reset', 'act',",
"self.__class__.require_all or require_all: config = None elif self.__class__.require_observe or require_observe:",
"= dict( update=4, policy=dict(network=dict(type='auto', size=8, depth=1, internal_rnn=2)), objective='policy_gradient', reward_estimation=dict(horizon=3) )",
"governing permissions and # limitations under the License. # ==============================================================================",
"self.__class__.exclude_bool_action: actions.pop('bool_action') if exclude_int_action or self.__class__.exclude_int_action: actions.pop('int_action') if exclude_float_action or",
"Environment.create(environment=environment, max_episode_timesteps=5) for key, value in self.__class__.agent.items(): if key not",
"not any([ require_all, require_observe, self.__class__.require_all, self.__class__.require_observe ]) self.runner.run( num_episodes=num_episodes, num_timesteps=num_timesteps,",
"if states is None: states = deepcopy(self.__class__.states) if actions is",
"= None num_episodes = None num_timesteps = None # Environment",
"actions=actions, exclude_bool_action=exclude_bool_action, exclude_int_action=exclude_int_action, exclude_float_action=exclude_float_action, exclude_bounded_action=exclude_bounded_action, require_observe=require_observe, require_all=require_all, **agent ) self.runner",
"if name is None: sys.stdout.write('\\n{} {}: '.format( datetime.now().strftime('%H:%M:%S'), self.__class__.__name__[4:] ))",
"Exclude action types exclude_bool_action = False exclude_int_action = False exclude_float_action",
"in compliance with the License. # You may obtain a",
"a dense Tensor of unknown shape' ) def start_tests(self, name=None):",
"software # distributed under the License is distributed on an",
"exclude_bounded_action=False, require_observe=False, require_all=False, **agent ): \"\"\" Generic unit-test preparation. \"\"\"",
") # Tensorforce config require_observe = False require_all = False",
"not None) == 1 evaluation = not any([ require_all, require_observe,",
"require_all=False, **agent ): \"\"\" Generic unit-test. \"\"\" agent, environment =",
"for key, value in self.__class__.agent.items(): if key not in agent:",
"under the License. # ============================================================================== from copy import deepcopy from",
"in agent: agent[key] = value if self.__class__.require_all or require_all: config",
"2 assert (num_updates is not None) + (num_episodes is not",
"2018 Tensorforce Team. All Rights Reserved. # # Licensed under",
"and # limitations under the License. # ============================================================================== from copy",
"\"\"\" Start unit-test method. \"\"\" if name is None: sys.stdout.write('\\n{}",
"name=None): \"\"\" Start unit-test method. \"\"\" if name is None:",
"self.__class__.num_timesteps if num_updates is None and num_episodes is None and",
"import datetime import os import sys import warnings from tensorforce",
"bounded_action=dict(type='float', shape=(2,), min_value=-0.5, max_value=0.5) ) # Exclude action types exclude_bool_action",
"): \"\"\" Generic unit-test preparation. \"\"\" Layer.layers = None if",
"False exclude_bounded_action = False # Agent agent = dict( update=4,",
"environment=environment, min_timesteps=min_timesteps, states=states, actions=actions, exclude_bool_action=exclude_bool_action, exclude_int_action=exclude_int_action, exclude_float_action=exclude_float_action, exclude_bounded_action=exclude_bounded_action, require_observe=require_observe, require_all=require_all,",
"depth=1, internal_rnn=2)), objective='policy_gradient', reward_estimation=dict(horizon=3) ) # Tensorforce config require_observe =",
"num_timesteps is None: num_updates = self.__class__.num_updates num_episodes = self.__class__.num_episodes num_timesteps",
"agent = dict( update=4, policy=dict(network=dict(type='auto', size=8, depth=1, internal_rnn=2)), objective='policy_gradient', reward_estimation=dict(horizon=3)",
"OF ANY KIND, either express or implied. # See the",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"None) + \\ (num_timesteps is not None) <= 1 if",
"max_value=0.5) ) # Exclude action types exclude_bool_action = False exclude_int_action",
"ANY KIND, either express or implied. # See the License",
"See the License for the specific language governing permissions and",
"the License. # You may obtain a copy of the",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"for the specific language governing permissions and # limitations under",
"exclude_bounded_action = False # Agent agent = dict( update=4, policy=dict(network=dict(type='auto',",
"False exclude_float_action = False exclude_bounded_action = False # Agent agent",
"to in writing, software # distributed under the License is",
"assertion: sys.stdout.write('.') sys.stdout.flush() def prepare( self, environment=None, min_timesteps=None, states=None, actions=None,",
"else: self.assertTrue(expr=assertion) if assertion: sys.stdout.write('.') sys.stdout.flush() def prepare( self, environment=None,",
"# See the License for the specific language governing permissions",
"states is None: states = deepcopy(self.__class__.states) if actions is None:",
"os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' class UnittestBase(object): \"\"\" Unit-test base class. \"\"\"",
"language governing permissions and # limitations under the License. #",
"or agreed to in writing, software # distributed under the",
"required by applicable law or agreed to in writing, software",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"def finished_test(self, assertion=None): \"\"\" Finished unit-test. \"\"\" if assertion is",
"min_timesteps = self.__class__.min_timesteps environment = UnittestEnvironment( states=states, actions=actions, min_timesteps=min_timesteps )",
"self.runner = Runner(agent=agent, environment=environment) assert (num_updates is not None) +",
"action='ignore', message='Converting sparse IndexedSlices to a dense Tensor of unknown",
"with the License. # You may obtain a copy of",
"from tensorforce.execution import Runner from test.unittest_environment import UnittestEnvironment os.environ['TF_CPP_MIN_LOG_LEVEL'] =",
"elif min_timesteps is not None: raise TensorforceError.unexpected() environment = Environment.create(environment=environment,",
"or require_observe: config = dict(api_functions=['reset', 'act', 'observe']) else: config =",
"max_episode_timesteps=5) for key, value in self.__class__.agent.items(): if key not in",
"(num_timesteps is not None) <= 1 if num_updates is None",
"**agent ): \"\"\" Generic unit-test. \"\"\" agent, environment = self.prepare(",
"= dict( bool_state=dict(type='bool', shape=(1,)), int_state=dict(type='int', shape=(2,), num_values=4), float_state=dict(type='float', shape=(1, 1,",
"compliance with the License. # You may obtain a copy",
"All Rights Reserved. # # Licensed under the Apache License,",
"agreed to in writing, software # distributed under the License",
"\"\"\" # Unittest num_updates = None num_episodes = None num_timesteps",
"exclude_bool_action=False, exclude_int_action=False, exclude_float_action=False, exclude_bounded_action=False, require_observe=False, require_all=False, **agent ): \"\"\" Generic",
"update=4, policy=dict(network=dict(type='auto', size=8, depth=1, internal_rnn=2)), objective='policy_gradient', reward_estimation=dict(horizon=3) ) # Tensorforce",
"if actions is None: actions = deepcopy(self.__class__.actions) if exclude_bool_action or",
"= None num_timesteps = None # Environment min_timesteps = 1",
"distributed under the License is distributed on an \"AS IS\"",
"permissions and # limitations under the License. # ============================================================================== from",
"method. \"\"\" if name is None: sys.stdout.write('\\n{} {}: '.format( datetime.now().strftime('%H:%M:%S'),",
"self.__class__.exclude_int_action: actions.pop('int_action') if exclude_float_action or self.__class__.exclude_float_action: actions.pop('float_action') if exclude_bounded_action or",
"Agent from tensorforce.core.layers import Layer from tensorforce.environments import Environment from",
"from tensorforce.agents import Agent from tensorforce.core.layers import Layer from tensorforce.environments",
"== 1 evaluation = not any([ require_all, require_observe, self.__class__.require_all, self.__class__.require_observe",
"is None: min_timesteps = self.__class__.min_timesteps environment = UnittestEnvironment( states=states, actions=actions,",
"= False exclude_bounded_action = False # Agent agent = dict(",
"exclude_int_action or self.__class__.exclude_int_action: actions.pop('int_action') if exclude_float_action or self.__class__.exclude_float_action: actions.pop('float_action') if",
"num_updates is None and num_episodes is None and num_timesteps is",
"shape=(), min_value=-0.5, max_value=0.5) ) actions = dict( bool_action=dict(type='bool', shape=(1,)), int_action=dict(type='int',",
"is None and num_timesteps is None: num_updates = self.__class__.num_updates num_episodes",
"copy import deepcopy from datetime import datetime import os import",
"import Environment from tensorforce.execution import Runner from test.unittest_environment import UnittestEnvironment",
"express or implied. # See the License for the specific",
"require_observe, self.__class__.require_all, self.__class__.require_observe ]) self.runner.run( num_episodes=num_episodes, num_timesteps=num_timesteps, num_updates=num_updates, use_tqdm=False, evaluation=evaluation",
"except in compliance with the License. # You may obtain",
"config = dict(api_functions=['reset', 'act', 'observe']) else: config = dict(api_functions=['reset', 'act'])",
"import Agent from tensorforce.core.layers import Layer from tensorforce.environments import Environment",
"None and num_timesteps is None: num_updates = 2 assert (num_updates",
"min_value=-0.5, max_value=0.5) ) actions = dict( bool_action=dict(type='bool', shape=(1,)), int_action=dict(type='int', shape=(2,),",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"= dict(api_functions=['reset', 'act']) agent = Agent.create(agent=agent, environment=environment, config=config) return agent,",
"self.__class__.require_observe ]) self.runner.run( num_episodes=num_episodes, num_timesteps=num_timesteps, num_updates=num_updates, use_tqdm=False, evaluation=evaluation ) self.runner.close()",
"not use this file except in compliance with the License.",
"Start unit-test method. \"\"\" if name is None: sys.stdout.write('\\n{} {}:",
"and num_timesteps is None: num_updates = self.__class__.num_updates num_episodes = self.__class__.num_episodes",
"writing, software # distributed under the License is distributed on",
"and num_timesteps is None: num_updates = 2 assert (num_updates is",
"raise TensorforceError.unexpected() environment = Environment.create(environment=environment, max_episode_timesteps=5) for key, value in",
"you may not use this file except in compliance with",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"agent: agent[key] = value if self.__class__.require_all or require_all: config =",
"= 1 states = dict( bool_state=dict(type='bool', shape=(1,)), int_state=dict(type='int', shape=(2,), num_values=4),",
"= value if self.__class__.require_all or require_all: config = None elif",
"reward_estimation=dict(horizon=3) ) # Tensorforce config require_observe = False require_all =",
"unit-test preparation. \"\"\" Layer.layers = None if environment is None:",
"exclude_bool_action=exclude_bool_action, exclude_int_action=exclude_int_action, exclude_float_action=exclude_float_action, exclude_bounded_action=exclude_bounded_action, require_observe=require_observe, require_all=require_all, **agent ) self.runner =",
"None) == 1 evaluation = not any([ require_all, require_observe, self.__class__.require_all,",
"exclude_float_action or self.__class__.exclude_float_action: actions.pop('float_action') if exclude_bounded_action or self.__class__.exclude_bounded_action: actions.pop('bounded_action') if",
"def setUp(self): warnings.filterwarnings( action='ignore', message='Converting sparse IndexedSlices to a dense",
"bounded_state=dict(type='float', shape=(), min_value=-0.5, max_value=0.5) ) actions = dict( bool_action=dict(type='bool', shape=(1,)),",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"actions.pop('bool_action') if exclude_int_action or self.__class__.exclude_int_action: actions.pop('int_action') if exclude_float_action or self.__class__.exclude_float_action:",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"limitations under the License. # ============================================================================== from copy import deepcopy",
"key not in agent: agent[key] = value if self.__class__.require_all or",
"if exclude_bool_action or self.__class__.exclude_bool_action: actions.pop('bool_action') if exclude_int_action or self.__class__.exclude_int_action: actions.pop('int_action')",
"import UnittestEnvironment os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' class UnittestBase(object): \"\"\" Unit-test base",
"warnings.filterwarnings( action='ignore', message='Converting sparse IndexedSlices to a dense Tensor of",
"actions.pop('float_action') if exclude_bounded_action or self.__class__.exclude_bounded_action: actions.pop('bounded_action') if min_timesteps is None:",
"= self.__class__.num_timesteps if num_updates is None and num_episodes is None",
"1 evaluation = not any([ require_all, require_observe, self.__class__.require_all, self.__class__.require_observe ])",
"unit-test. \"\"\" if assertion is None: assertion = True else:",
"if environment is None: if states is None: states =",
"internal_rnn=2)), objective='policy_gradient', reward_estimation=dict(horizon=3) ) # Tensorforce config require_observe = False",
"deepcopy(self.__class__.actions) if exclude_bool_action or self.__class__.exclude_bool_action: actions.pop('bool_action') if exclude_int_action or self.__class__.exclude_int_action:",
"exclude_bounded_action or self.__class__.exclude_bounded_action: actions.pop('bounded_action') if min_timesteps is None: min_timesteps =",
"None: raise TensorforceError.unexpected() environment = Environment.create(environment=environment, max_episode_timesteps=5) for key, value",
"import warnings from tensorforce import TensorforceError from tensorforce.agents import Agent",
"is not None: raise TensorforceError.unexpected() environment = Environment.create(environment=environment, max_episode_timesteps=5) for",
"num_episodes=num_episodes, num_timesteps=num_timesteps, num_updates=num_updates, use_tqdm=False, evaluation=evaluation ) self.runner.close() agent.close() environment.close() self.finished_test()",
"exclude_bool_action = False exclude_int_action = False exclude_float_action = False exclude_bounded_action",
"actions = deepcopy(self.__class__.actions) if exclude_bool_action or self.__class__.exclude_bool_action: actions.pop('bool_action') if exclude_int_action",
"action types exclude_bool_action = False exclude_int_action = False exclude_float_action =",
"\"\"\" Finished unit-test. \"\"\" if assertion is None: assertion =",
"require_all=require_all, **agent ) self.runner = Runner(agent=agent, environment=environment) assert (num_updates is",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"import sys import warnings from tensorforce import TensorforceError from tensorforce.agents",
"import deepcopy from datetime import datetime import os import sys",
"Tensor of unknown shape' ) def start_tests(self, name=None): \"\"\" Start",
"the License is distributed on an \"AS IS\" BASIS, #",
"# Environment min_timesteps = 1 states = dict( bool_state=dict(type='bool', shape=(1,)),",
"if exclude_int_action or self.__class__.exclude_int_action: actions.pop('int_action') if exclude_float_action or self.__class__.exclude_float_action: actions.pop('float_action')",
"+ \\ (num_timesteps is not None) <= 1 if num_updates",
"Agent agent = dict( update=4, policy=dict(network=dict(type='auto', size=8, depth=1, internal_rnn=2)), objective='policy_gradient',",
"the License. # ============================================================================== from copy import deepcopy from datetime",
"# Tensorforce config require_observe = False require_all = False def",
"not None) + (num_episodes is not None) + \\ (num_timesteps",
"states=states, actions=actions, exclude_bool_action=exclude_bool_action, exclude_int_action=exclude_int_action, exclude_float_action=exclude_float_action, exclude_bounded_action=exclude_bounded_action, require_observe=require_observe, require_all=require_all, **agent )",
"]) self.runner.run( num_episodes=num_episodes, num_timesteps=num_timesteps, num_updates=num_updates, use_tqdm=False, evaluation=evaluation ) self.runner.close() agent.close()",
"License. # ============================================================================== from copy import deepcopy from datetime import",
"is None: sys.stdout.write('\\n{} {}: '.format( datetime.now().strftime('%H:%M:%S'), self.__class__.__name__[4:] )) else: sys.stdout.write('\\n{}",
"config = None elif self.__class__.require_observe or require_observe: config = dict(api_functions=['reset',",
"dict(api_functions=['reset', 'act', 'observe']) else: config = dict(api_functions=['reset', 'act']) agent =",
"law or agreed to in writing, software # distributed under",
"num_updates = self.__class__.num_updates num_episodes = self.__class__.num_episodes num_timesteps = self.__class__.num_timesteps if",
"num_episodes is None and num_timesteps is None: num_updates = 2",
"dense Tensor of unknown shape' ) def start_tests(self, name=None): \"\"\"",
"return agent, environment def unittest( self, num_updates=None, num_episodes=None, num_timesteps=None, environment=None,",
"is None: if states is None: states = deepcopy(self.__class__.states) if",
"to a dense Tensor of unknown shape' ) def start_tests(self,",
"class UnittestBase(object): \"\"\" Unit-test base class. \"\"\" # Unittest num_updates",
"if key not in agent: agent[key] = value if self.__class__.require_all",
"may obtain a copy of the License at # #",
"agent, environment = self.prepare( environment=environment, min_timesteps=min_timesteps, states=states, actions=actions, exclude_bool_action=exclude_bool_action, exclude_int_action=exclude_int_action,",
"datetime.now().strftime('%H:%M:%S'), self.__class__.__name__[4:], name )) sys.stdout.flush() def finished_test(self, assertion=None): \"\"\" Finished",
"'act']) agent = Agent.create(agent=agent, environment=environment, config=config) return agent, environment def",
"= Runner(agent=agent, environment=environment) assert (num_updates is not None) + (num_episodes",
"num_timesteps is None: num_updates = 2 assert (num_updates is not",
"exclude_bounded_action=exclude_bounded_action, require_observe=require_observe, require_all=require_all, **agent ) self.runner = Runner(agent=agent, environment=environment) assert",
"min_timesteps is None: min_timesteps = self.__class__.min_timesteps environment = UnittestEnvironment( states=states,",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"message='Converting sparse IndexedSlices to a dense Tensor of unknown shape'",
"may not use this file except in compliance with the",
"environment = UnittestEnvironment( states=states, actions=actions, min_timesteps=min_timesteps ) elif min_timesteps is",
"if exclude_float_action or self.__class__.exclude_float_action: actions.pop('float_action') if exclude_bounded_action or self.__class__.exclude_bounded_action: actions.pop('bounded_action')",
"Agent.create(agent=agent, environment=environment, config=config) return agent, environment def unittest( self, num_updates=None,",
"not None) <= 1 if num_updates is None and num_episodes",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"or self.__class__.exclude_int_action: actions.pop('int_action') if exclude_float_action or self.__class__.exclude_float_action: actions.pop('float_action') if exclude_bounded_action",
"require_observe=require_observe, require_all=require_all, **agent ) self.runner = Runner(agent=agent, environment=environment) assert (num_updates",
"this file except in compliance with the License. # You",
"actions=None, exclude_bool_action=False, exclude_int_action=False, exclude_float_action=False, exclude_bounded_action=False, require_observe=False, require_all=False, **agent ): \"\"\"",
"num_updates = None num_episodes = None num_timesteps = None #",
"# Exclude action types exclude_bool_action = False exclude_int_action = False",
"environment is None: if states is None: states = deepcopy(self.__class__.states)",
"None: if states is None: states = deepcopy(self.__class__.states) if actions",
"False require_all = False def setUp(self): warnings.filterwarnings( action='ignore', message='Converting sparse",
"'3' class UnittestBase(object): \"\"\" Unit-test base class. \"\"\" # Unittest",
"exclude_int_action=exclude_int_action, exclude_float_action=exclude_float_action, exclude_bounded_action=exclude_bounded_action, require_observe=require_observe, require_all=require_all, **agent ) self.runner = Runner(agent=agent,",
"= Environment.create(environment=environment, max_episode_timesteps=5) for key, value in self.__class__.agent.items(): if key",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"is not None) <= 1 if num_updates is None and",
"config=config) return agent, environment def unittest( self, num_updates=None, num_episodes=None, num_timesteps=None,",
"# # Licensed under the Apache License, Version 2.0 (the",
"file except in compliance with the License. # You may",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"warnings from tensorforce import TensorforceError from tensorforce.agents import Agent from",
"actions.pop('int_action') if exclude_float_action or self.__class__.exclude_float_action: actions.pop('float_action') if exclude_bounded_action or self.__class__.exclude_bounded_action:",
"states = deepcopy(self.__class__.states) if actions is None: actions = deepcopy(self.__class__.actions)",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"class. \"\"\" # Unittest num_updates = None num_episodes = None",
"require_observe: config = dict(api_functions=['reset', 'act', 'observe']) else: config = dict(api_functions=['reset',",
"actions=actions, min_timesteps=min_timesteps ) elif min_timesteps is not None: raise TensorforceError.unexpected()",
"from tensorforce.core.layers import Layer from tensorforce.environments import Environment from tensorforce.execution",
"agent, environment def unittest( self, num_updates=None, num_episodes=None, num_timesteps=None, environment=None, min_timesteps=None,",
"assertion=None): \"\"\" Finished unit-test. \"\"\" if assertion is None: assertion",
"# ============================================================================== from copy import deepcopy from datetime import datetime",
"= dict(api_functions=['reset', 'act', 'observe']) else: config = dict(api_functions=['reset', 'act']) agent",
"objective='policy_gradient', reward_estimation=dict(horizon=3) ) # Tensorforce config require_observe = False require_all",
"if self.__class__.require_all or require_all: config = None elif self.__class__.require_observe or",
"not None: raise TensorforceError.unexpected() environment = Environment.create(environment=environment, max_episode_timesteps=5) for key,",
"= self.prepare( environment=environment, min_timesteps=min_timesteps, states=states, actions=actions, exclude_bool_action=exclude_bool_action, exclude_int_action=exclude_int_action, exclude_float_action=exclude_float_action, exclude_bounded_action=exclude_bounded_action,",
"bool_state=dict(type='bool', shape=(1,)), int_state=dict(type='int', shape=(2,), num_values=4), float_state=dict(type='float', shape=(1, 1, 2)), bounded_state=dict(type='float',",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"shape=(2,), min_value=-0.5, max_value=0.5) ) # Exclude action types exclude_bool_action =",
"self.__class__.exclude_bounded_action: actions.pop('bounded_action') if min_timesteps is None: min_timesteps = self.__class__.min_timesteps environment",
"= not any([ require_all, require_observe, self.__class__.require_all, self.__class__.require_observe ]) self.runner.run( num_episodes=num_episodes,",
"or implied. # See the License for the specific language",
"Rights Reserved. # # Licensed under the Apache License, Version",
"None and num_timesteps is None: num_updates = self.__class__.num_updates num_episodes =",
"deepcopy(self.__class__.states) if actions is None: actions = deepcopy(self.__class__.actions) if exclude_bool_action",
"if exclude_bounded_action or self.__class__.exclude_bounded_action: actions.pop('bounded_action') if min_timesteps is None: min_timesteps",
"= self.__class__.num_episodes num_timesteps = self.__class__.num_timesteps if num_updates is None and",
"KIND, either express or implied. # See the License for",
"specific language governing permissions and # limitations under the License.",
"\"\"\" Generic unit-test. \"\"\" agent, environment = self.prepare( environment=environment, min_timesteps=min_timesteps,",
"sys.stdout.write('\\n{} {} ({}): '.format( datetime.now().strftime('%H:%M:%S'), self.__class__.__name__[4:], name )) sys.stdout.flush() def",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"None num_timesteps = None # Environment min_timesteps = 1 states",
"is None: assertion = True else: self.assertTrue(expr=assertion) if assertion: sys.stdout.write('.')",
"None # Environment min_timesteps = 1 states = dict( bool_state=dict(type='bool',",
"states=states, actions=actions, min_timesteps=min_timesteps ) elif min_timesteps is not None: raise",
"environment=environment, config=config) return agent, environment def unittest( self, num_updates=None, num_episodes=None,",
"size=8, depth=1, internal_rnn=2)), objective='policy_gradient', reward_estimation=dict(horizon=3) ) # Tensorforce config require_observe",
"'observe']) else: config = dict(api_functions=['reset', 'act']) agent = Agent.create(agent=agent, environment=environment,",
"============================================================================== from copy import deepcopy from datetime import datetime import",
"shape=(1, 1, 2)), bounded_state=dict(type='float', shape=(), min_value=-0.5, max_value=0.5) ) actions =",
"num_episodes is None and num_timesteps is None: num_updates = self.__class__.num_updates",
"({}): '.format( datetime.now().strftime('%H:%M:%S'), self.__class__.__name__[4:], name )) sys.stdout.flush() def finished_test(self, assertion=None):",
"(the \"License\"); # you may not use this file except",
"1 states = dict( bool_state=dict(type='bool', shape=(1,)), int_state=dict(type='int', shape=(2,), num_values=4), float_state=dict(type='float',",
"self.__class__.min_timesteps environment = UnittestEnvironment( states=states, actions=actions, min_timesteps=min_timesteps ) elif min_timesteps",
"states = dict( bool_state=dict(type='bool', shape=(1,)), int_state=dict(type='int', shape=(2,), num_values=4), float_state=dict(type='float', shape=(1,",
"# you may not use this file except in compliance",
"= False def setUp(self): warnings.filterwarnings( action='ignore', message='Converting sparse IndexedSlices to",
"self.prepare( environment=environment, min_timesteps=min_timesteps, states=states, actions=actions, exclude_bool_action=exclude_bool_action, exclude_int_action=exclude_int_action, exclude_float_action=exclude_float_action, exclude_bounded_action=exclude_bounded_action, require_observe=require_observe,",
"self.__class__.__name__[4:] )) else: sys.stdout.write('\\n{} {} ({}): '.format( datetime.now().strftime('%H:%M:%S'), self.__class__.__name__[4:], name",
"sparse IndexedSlices to a dense Tensor of unknown shape' )",
"None: min_timesteps = self.__class__.min_timesteps environment = UnittestEnvironment( states=states, actions=actions, min_timesteps=min_timesteps",
"num_episodes=None, num_timesteps=None, environment=None, min_timesteps=None, states=None, actions=None, exclude_bool_action=False, exclude_int_action=False, exclude_float_action=False, exclude_bounded_action=False,",
"assertion is None: assertion = True else: self.assertTrue(expr=assertion) if assertion:",
"value in self.__class__.agent.items(): if key not in agent: agent[key] =",
"Unittest num_updates = None num_episodes = None num_timesteps = None",
"num_updates = 2 assert (num_updates is not None) + (num_episodes",
"exclude_bool_action or self.__class__.exclude_bool_action: actions.pop('bool_action') if exclude_int_action or self.__class__.exclude_int_action: actions.pop('int_action') if",
"actions is None: actions = deepcopy(self.__class__.actions) if exclude_bool_action or self.__class__.exclude_bool_action:",
"min_timesteps = 1 states = dict( bool_state=dict(type='bool', shape=(1,)), int_state=dict(type='int', shape=(2,),",
"# # Unless required by applicable law or agreed to",
"float_state=dict(type='float', shape=(1, 1, 2)), bounded_state=dict(type='float', shape=(), min_value=-0.5, max_value=0.5) ) actions",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"tensorforce.core.layers import Layer from tensorforce.environments import Environment from tensorforce.execution import",
"Version 2.0 (the \"License\"); # you may not use this",
"num_timesteps=None, environment=None, min_timesteps=None, states=None, actions=None, exclude_bool_action=False, exclude_int_action=False, exclude_float_action=False, exclude_bounded_action=False, require_observe=False,",
") self.runner = Runner(agent=agent, environment=environment) assert (num_updates is not None)",
"require_all = False def setUp(self): warnings.filterwarnings( action='ignore', message='Converting sparse IndexedSlices",
"prepare( self, environment=None, min_timesteps=None, states=None, actions=None, exclude_bool_action=False, exclude_int_action=False, exclude_float_action=False, exclude_bounded_action=False,",
"self, environment=None, min_timesteps=None, states=None, actions=None, exclude_bool_action=False, exclude_int_action=False, exclude_float_action=False, exclude_bounded_action=False, require_observe=False,",
"\\ (num_timesteps is not None) == 1 evaluation = not",
"Generic unit-test preparation. \"\"\" Layer.layers = None if environment is",
"\"\"\" Generic unit-test preparation. \"\"\" Layer.layers = None if environment",
"None: num_updates = self.__class__.num_updates num_episodes = self.__class__.num_episodes num_timesteps = self.__class__.num_timesteps",
"not in agent: agent[key] = value if self.__class__.require_all or require_all:",
"implied. # See the License for the specific language governing",
"def start_tests(self, name=None): \"\"\" Start unit-test method. \"\"\" if name",
")) sys.stdout.flush() def finished_test(self, assertion=None): \"\"\" Finished unit-test. \"\"\" if",
"environment def unittest( self, num_updates=None, num_episodes=None, num_timesteps=None, environment=None, min_timesteps=None, states=None,",
"Team. All Rights Reserved. # # Licensed under the Apache",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"None num_episodes = None num_timesteps = None # Environment min_timesteps",
"= deepcopy(self.__class__.actions) if exclude_bool_action or self.__class__.exclude_bool_action: actions.pop('bool_action') if exclude_int_action or",
"environment=environment) assert (num_updates is not None) + (num_episodes is not",
"Generic unit-test. \"\"\" agent, environment = self.prepare( environment=environment, min_timesteps=min_timesteps, states=states,",
"min_timesteps=None, states=None, actions=None, exclude_bool_action=False, exclude_int_action=False, exclude_float_action=False, exclude_bounded_action=False, require_observe=False, require_all=False, **agent",
"None: actions = deepcopy(self.__class__.actions) if exclude_bool_action or self.__class__.exclude_bool_action: actions.pop('bool_action') if",
"if num_updates is None and num_episodes is None and num_timesteps",
"test.unittest_environment import UnittestEnvironment os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' class UnittestBase(object): \"\"\" Unit-test",
"= deepcopy(self.__class__.states) if actions is None: actions = deepcopy(self.__class__.actions) if",
"None) + (num_episodes is not None) + \\ (num_timesteps is",
"by applicable law or agreed to in writing, software #",
"or self.__class__.exclude_bool_action: actions.pop('bool_action') if exclude_int_action or self.__class__.exclude_int_action: actions.pop('int_action') if exclude_float_action",
"**agent ) self.runner = Runner(agent=agent, environment=environment) assert (num_updates is not",
"unittest( self, num_updates=None, num_episodes=None, num_timesteps=None, environment=None, min_timesteps=None, states=None, actions=None, exclude_bool_action=False,",
"require_observe=False, require_all=False, **agent ): \"\"\" Generic unit-test. \"\"\" agent, environment",
"= False exclude_float_action = False exclude_bounded_action = False # Agent",
"1)), bounded_action=dict(type='float', shape=(2,), min_value=-0.5, max_value=0.5) ) # Exclude action types",
"types exclude_bool_action = False exclude_int_action = False exclude_float_action = False",
"(num_episodes is not None) + \\ (num_timesteps is not None)",
"max_value=0.5) ) actions = dict( bool_action=dict(type='bool', shape=(1,)), int_action=dict(type='int', shape=(2,), num_values=4),",
"= None # Environment min_timesteps = 1 states = dict(",
"dict( update=4, policy=dict(network=dict(type='auto', size=8, depth=1, internal_rnn=2)), objective='policy_gradient', reward_estimation=dict(horizon=3) ) #",
"unit-test method. \"\"\" if name is None: sys.stdout.write('\\n{} {}: '.format(",
"exclude_int_action=False, exclude_float_action=False, exclude_bounded_action=False, require_observe=False, require_all=False, **agent ): \"\"\" Generic unit-test.",
"None elif self.__class__.require_observe or require_observe: config = dict(api_functions=['reset', 'act', 'observe'])",
"None) <= 1 if num_updates is None and num_episodes is",
"dict( bool_state=dict(type='bool', shape=(1,)), int_state=dict(type='int', shape=(2,), num_values=4), float_state=dict(type='float', shape=(1, 1, 2)),",
"import Runner from test.unittest_environment import UnittestEnvironment os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' class",
") elif min_timesteps is not None: raise TensorforceError.unexpected() environment =",
"self, num_updates=None, num_episodes=None, num_timesteps=None, environment=None, min_timesteps=None, states=None, actions=None, exclude_bool_action=False, exclude_int_action=False,",
"if assertion is None: assertion = True else: self.assertTrue(expr=assertion) if",
"actions.pop('bounded_action') if min_timesteps is None: min_timesteps = self.__class__.min_timesteps environment =",
"is not None) == 1 evaluation = not any([ require_all,",
"min_timesteps=min_timesteps, states=states, actions=actions, exclude_bool_action=exclude_bool_action, exclude_int_action=exclude_int_action, exclude_float_action=exclude_float_action, exclude_bounded_action=exclude_bounded_action, require_observe=require_observe, require_all=require_all, **agent",
"'.format( datetime.now().strftime('%H:%M:%S'), self.__class__.__name__[4:] )) else: sys.stdout.write('\\n{} {} ({}): '.format( datetime.now().strftime('%H:%M:%S'),",
"import os import sys import warnings from tensorforce import TensorforceError",
"None) + \\ (num_timesteps is not None) == 1 evaluation",
"base class. \"\"\" # Unittest num_updates = None num_episodes =",
"= True else: self.assertTrue(expr=assertion) if assertion: sys.stdout.write('.') sys.stdout.flush() def prepare(",
"require_all=False, **agent ): \"\"\" Generic unit-test preparation. \"\"\" Layer.layers =",
") actions = dict( bool_action=dict(type='bool', shape=(1,)), int_action=dict(type='int', shape=(2,), num_values=4), float_action=dict(type='float',",
"is None: actions = deepcopy(self.__class__.actions) if exclude_bool_action or self.__class__.exclude_bool_action: actions.pop('bool_action')",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"is None: num_updates = self.__class__.num_updates num_episodes = self.__class__.num_episodes num_timesteps =",
"num_episodes = None num_timesteps = None # Environment min_timesteps =",
"Unless required by applicable law or agreed to in writing,",
"= None if environment is None: if states is None:",
"unknown shape' ) def start_tests(self, name=None): \"\"\" Start unit-test method.",
"TensorforceError.unexpected() environment = Environment.create(environment=environment, max_episode_timesteps=5) for key, value in self.__class__.agent.items():",
"min_value=-0.5, max_value=0.5) ) # Exclude action types exclude_bool_action = False",
"finished_test(self, assertion=None): \"\"\" Finished unit-test. \"\"\" if assertion is None:",
"datetime import os import sys import warnings from tensorforce import",
"environment=None, min_timesteps=None, states=None, actions=None, exclude_bool_action=False, exclude_int_action=False, exclude_float_action=False, exclude_bounded_action=False, require_observe=False, require_all=False,",
"exclude_float_action=False, exclude_bounded_action=False, require_observe=False, require_all=False, **agent ): \"\"\" Generic unit-test. \"\"\"",
"2)), bounded_state=dict(type='float', shape=(), min_value=-0.5, max_value=0.5) ) actions = dict( bool_action=dict(type='bool',",
"the specific language governing permissions and # limitations under the",
"def prepare( self, environment=None, min_timesteps=None, states=None, actions=None, exclude_bool_action=False, exclude_int_action=False, exclude_float_action=False,",
"is not None) + \\ (num_timesteps is not None) <=",
"1, 2)), bounded_state=dict(type='float', shape=(), min_value=-0.5, max_value=0.5) ) actions = dict(",
"or self.__class__.exclude_bounded_action: actions.pop('bounded_action') if min_timesteps is None: min_timesteps = self.__class__.min_timesteps",
"applicable law or agreed to in writing, software # distributed",
"(num_updates is not None) + (num_episodes is not None) +",
"UnittestEnvironment os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' class UnittestBase(object): \"\"\" Unit-test base class.",
"shape=(2,), num_values=4), float_state=dict(type='float', shape=(1, 1, 2)), bounded_state=dict(type='float', shape=(), min_value=-0.5, max_value=0.5)",
"shape=(2,), num_values=4), float_action=dict(type='float', shape=(1, 1)), bounded_action=dict(type='float', shape=(2,), min_value=-0.5, max_value=0.5) )",
"environment = Environment.create(environment=environment, max_episode_timesteps=5) for key, value in self.__class__.agent.items(): if",
"require_all, require_observe, self.__class__.require_all, self.__class__.require_observe ]) self.runner.run( num_episodes=num_episodes, num_timesteps=num_timesteps, num_updates=num_updates, use_tqdm=False,",
"or self.__class__.exclude_float_action: actions.pop('float_action') if exclude_bounded_action or self.__class__.exclude_bounded_action: actions.pop('bounded_action') if min_timesteps",
"False def setUp(self): warnings.filterwarnings( action='ignore', message='Converting sparse IndexedSlices to a",
"'act', 'observe']) else: config = dict(api_functions=['reset', 'act']) agent = Agent.create(agent=agent,",
"in writing, software # distributed under the License is distributed",
"any([ require_all, require_observe, self.__class__.require_all, self.__class__.require_observe ]) self.runner.run( num_episodes=num_episodes, num_timesteps=num_timesteps, num_updates=num_updates,",
"self.__class__.exclude_float_action: actions.pop('float_action') if exclude_bounded_action or self.__class__.exclude_bounded_action: actions.pop('bounded_action') if min_timesteps is",
"tensorforce.execution import Runner from test.unittest_environment import UnittestEnvironment os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'",
"Runner(agent=agent, environment=environment) assert (num_updates is not None) + (num_episodes is",
"assertion = True else: self.assertTrue(expr=assertion) if assertion: sys.stdout.write('.') sys.stdout.flush() def",
"Environment from tensorforce.execution import Runner from test.unittest_environment import UnittestEnvironment os.environ['TF_CPP_MIN_LOG_LEVEL']",
"Runner from test.unittest_environment import UnittestEnvironment os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' class UnittestBase(object):",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"is None and num_timesteps is None: num_updates = 2 assert",
"License, Version 2.0 (the \"License\"); # you may not use",
"of unknown shape' ) def start_tests(self, name=None): \"\"\" Start unit-test",
"value if self.__class__.require_all or require_all: config = None elif self.__class__.require_observe",
"# You may obtain a copy of the License at",
"Unit-test base class. \"\"\" # Unittest num_updates = None num_episodes",
"\"\"\" if name is None: sys.stdout.write('\\n{} {}: '.format( datetime.now().strftime('%H:%M:%S'), self.__class__.__name__[4:]",
"else: config = dict(api_functions=['reset', 'act']) agent = Agent.create(agent=agent, environment=environment, config=config)",
"None: num_updates = 2 assert (num_updates is not None) +",
"require_all: config = None elif self.__class__.require_observe or require_observe: config =",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"require_observe=False, require_all=False, **agent ): \"\"\" Generic unit-test preparation. \"\"\" Layer.layers",
"exclude_bounded_action=False, require_observe=False, require_all=False, **agent ): \"\"\" Generic unit-test. \"\"\" agent,",
"datetime import datetime import os import sys import warnings from",
"sys.stdout.flush() def finished_test(self, assertion=None): \"\"\" Finished unit-test. \"\"\" if assertion",
"\"\"\" agent, environment = self.prepare( environment=environment, min_timesteps=min_timesteps, states=states, actions=actions, exclude_bool_action=exclude_bool_action,",
"sys.stdout.flush() def prepare( self, environment=None, min_timesteps=None, states=None, actions=None, exclude_bool_action=False, exclude_int_action=False,",
"Finished unit-test. \"\"\" if assertion is None: assertion = True",
"setUp(self): warnings.filterwarnings( action='ignore', message='Converting sparse IndexedSlices to a dense Tensor",
"policy=dict(network=dict(type='auto', size=8, depth=1, internal_rnn=2)), objective='policy_gradient', reward_estimation=dict(horizon=3) ) # Tensorforce config",
"is not None) + (num_episodes is not None) + \\",
"# Agent agent = dict( update=4, policy=dict(network=dict(type='auto', size=8, depth=1, internal_rnn=2)),",
"shape=(1, 1)), bounded_action=dict(type='float', shape=(2,), min_value=-0.5, max_value=0.5) ) # Exclude action",
"\\ (num_timesteps is not None) <= 1 if num_updates is",
"the License for the specific language governing permissions and #",
"= Agent.create(agent=agent, environment=environment, config=config) return agent, environment def unittest( self,",
"None and num_episodes is None and num_timesteps is None: num_updates",
"config require_observe = False require_all = False def setUp(self): warnings.filterwarnings(",
"import Layer from tensorforce.environments import Environment from tensorforce.execution import Runner",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"either express or implied. # See the License for the",
"Environment min_timesteps = 1 states = dict( bool_state=dict(type='bool', shape=(1,)), int_state=dict(type='int',",
"os import sys import warnings from tensorforce import TensorforceError from",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"import TensorforceError from tensorforce.agents import Agent from tensorforce.core.layers import Layer",
"= False require_all = False def setUp(self): warnings.filterwarnings( action='ignore', message='Converting",
"or require_all: config = None elif self.__class__.require_observe or require_observe: config",
"self.__class__.require_observe or require_observe: config = dict(api_functions=['reset', 'act', 'observe']) else: config",
"None: sys.stdout.write('\\n{} {}: '.format( datetime.now().strftime('%H:%M:%S'), self.__class__.__name__[4:] )) else: sys.stdout.write('\\n{} {}",
"sys.stdout.write('.') sys.stdout.flush() def prepare( self, environment=None, min_timesteps=None, states=None, actions=None, exclude_bool_action=False,",
"config = dict(api_functions=['reset', 'act']) agent = Agent.create(agent=agent, environment=environment, config=config) return",
"IndexedSlices to a dense Tensor of unknown shape' ) def",
"UnittestEnvironment( states=states, actions=actions, min_timesteps=min_timesteps ) elif min_timesteps is not None:",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"int_action=dict(type='int', shape=(2,), num_values=4), float_action=dict(type='float', shape=(1, 1)), bounded_action=dict(type='float', shape=(2,), min_value=-0.5, max_value=0.5)",
"Tensorforce config require_observe = False require_all = False def setUp(self):",
"# Copyright 2018 Tensorforce Team. All Rights Reserved. # #",
"= UnittestEnvironment( states=states, actions=actions, min_timesteps=min_timesteps ) elif min_timesteps is not",
"dict( bool_action=dict(type='bool', shape=(1,)), int_action=dict(type='int', shape=(2,), num_values=4), float_action=dict(type='float', shape=(1, 1)), bounded_action=dict(type='float',",
"float_action=dict(type='float', shape=(1, 1)), bounded_action=dict(type='float', shape=(2,), min_value=-0.5, max_value=0.5) ) # Exclude",
"agent = Agent.create(agent=agent, environment=environment, config=config) return agent, environment def unittest(",
"None if environment is None: if states is None: states",
"exclude_float_action=False, exclude_bounded_action=False, require_observe=False, require_all=False, **agent ): \"\"\" Generic unit-test preparation.",
"if assertion: sys.stdout.write('.') sys.stdout.flush() def prepare( self, environment=None, min_timesteps=None, states=None,",
"min_timesteps is not None: raise TensorforceError.unexpected() environment = Environment.create(environment=environment, max_episode_timesteps=5)",
"actions = dict( bool_action=dict(type='bool', shape=(1,)), int_action=dict(type='int', shape=(2,), num_values=4), float_action=dict(type='float', shape=(1,",
"\"License\"); # you may not use this file except in",
"require_observe = False require_all = False def setUp(self): warnings.filterwarnings( action='ignore',",
"elif self.__class__.require_observe or require_observe: config = dict(api_functions=['reset', 'act', 'observe']) else:",
"int_state=dict(type='int', shape=(2,), num_values=4), float_state=dict(type='float', shape=(1, 1, 2)), bounded_state=dict(type='float', shape=(), min_value=-0.5,",
"bool_action=dict(type='bool', shape=(1,)), int_action=dict(type='int', shape=(2,), num_values=4), float_action=dict(type='float', shape=(1, 1)), bounded_action=dict(type='float', shape=(2,),",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"Layer.layers = None if environment is None: if states is",
"datetime.now().strftime('%H:%M:%S'), self.__class__.__name__[4:] )) else: sys.stdout.write('\\n{} {} ({}): '.format( datetime.now().strftime('%H:%M:%S'), self.__class__.__name__[4:],",
"exclude_int_action = False exclude_float_action = False exclude_bounded_action = False #",
"min_timesteps=min_timesteps ) elif min_timesteps is not None: raise TensorforceError.unexpected() environment",
"shape=(1,)), int_state=dict(type='int', shape=(2,), num_values=4), float_state=dict(type='float', shape=(1, 1, 2)), bounded_state=dict(type='float', shape=(),",
"+ (num_episodes is not None) + \\ (num_timesteps is not",
"# distributed under the License is distributed on an \"AS",
"environment = self.prepare( environment=environment, min_timesteps=min_timesteps, states=states, actions=actions, exclude_bool_action=exclude_bool_action, exclude_int_action=exclude_int_action, exclude_float_action=exclude_float_action,",
"# Unless required by applicable law or agreed to in",
"else: sys.stdout.write('\\n{} {} ({}): '.format( datetime.now().strftime('%H:%M:%S'), self.__class__.__name__[4:], name )) sys.stdout.flush()",
"from copy import deepcopy from datetime import datetime import os",
"= dict( bool_action=dict(type='bool', shape=(1,)), int_action=dict(type='int', shape=(2,), num_values=4), float_action=dict(type='float', shape=(1, 1)),",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"\"\"\" Layer.layers = None if environment is None: if states",
"1 if num_updates is None and num_episodes is None and",
") def start_tests(self, name=None): \"\"\" Start unit-test method. \"\"\" if",
"num_timesteps = None # Environment min_timesteps = 1 states =",
"exclude_float_action = False exclude_bounded_action = False # Agent agent =",
"You may obtain a copy of the License at #",
"self.assertTrue(expr=assertion) if assertion: sys.stdout.write('.') sys.stdout.flush() def prepare( self, environment=None, min_timesteps=None,",
"preparation. \"\"\" Layer.layers = None if environment is None: if",
"TensorforceError from tensorforce.agents import Agent from tensorforce.core.layers import Layer from",
"= False exclude_int_action = False exclude_float_action = False exclude_bounded_action =",
"tensorforce import TensorforceError from tensorforce.agents import Agent from tensorforce.core.layers import",
"**agent ): \"\"\" Generic unit-test preparation. \"\"\" Layer.layers = None",
"from tensorforce import TensorforceError from tensorforce.agents import Agent from tensorforce.core.layers",
"= '3' class UnittestBase(object): \"\"\" Unit-test base class. \"\"\" #",
"key, value in self.__class__.agent.items(): if key not in agent: agent[key]",
"is None and num_episodes is None and num_timesteps is None:",
"the Apache License, Version 2.0 (the \"License\"); # you may",
") # Exclude action types exclude_bool_action = False exclude_int_action =",
"self.__class__.num_episodes num_timesteps = self.__class__.num_timesteps if num_updates is None and num_episodes",
"dict(api_functions=['reset', 'act']) agent = Agent.create(agent=agent, environment=environment, config=config) return agent, environment",
"False # Agent agent = dict( update=4, policy=dict(network=dict(type='auto', size=8, depth=1,",
"assert (num_updates is not None) + (num_episodes is not None)",
"sys import warnings from tensorforce import TensorforceError from tensorforce.agents import",
"deepcopy from datetime import datetime import os import sys import",
"# Unittest num_updates = None num_episodes = None num_timesteps =",
"def unittest( self, num_updates=None, num_episodes=None, num_timesteps=None, environment=None, min_timesteps=None, states=None, actions=None,",
"num_timesteps = self.__class__.num_timesteps if num_updates is None and num_episodes is",
"self.__class__.require_all, self.__class__.require_observe ]) self.runner.run( num_episodes=num_episodes, num_timesteps=num_timesteps, num_updates=num_updates, use_tqdm=False, evaluation=evaluation )"
] |
[
"for reveal app\"\"\" # pylint: disable=invalid-name default_app_config = \"mspray.apps.reveal.apps.RevealConfig\" #",
"\"\"\"init module for reveal app\"\"\" # pylint: disable=invalid-name default_app_config =",
"module for reveal app\"\"\" # pylint: disable=invalid-name default_app_config = \"mspray.apps.reveal.apps.RevealConfig\"",
"reveal app\"\"\" # pylint: disable=invalid-name default_app_config = \"mspray.apps.reveal.apps.RevealConfig\" # noqa"
] |
[
"django.db import models from django import forms from audit_log.models.managers import",
"django import forms from audit_log.models.managers import AuditLog # Create your",
"blank=True) def __str__(self): return self.name class FormPort(forms.ModelForm): pass class Meta:",
"def __str__(self): return self.name class FormPort(forms.ModelForm): pass class Meta: model",
"= AuditLog() #icon = models.ImageField(upload_to='images', blank=True) def __str__(self): return self.name",
"models here. class Port(models.Model): name = models.CharField(max_length=250) port = models.CharField(max_length=250)",
"import AuditLog # Create your models here. class Port(models.Model): name",
"models.CharField(max_length=250) description = models.TextField(blank=True) audit_log = AuditLog() #icon = models.ImageField(upload_to='images',",
"here. class Port(models.Model): name = models.CharField(max_length=250) port = models.CharField(max_length=250) description",
"description = models.TextField(blank=True) audit_log = AuditLog() #icon = models.ImageField(upload_to='images', blank=True)",
"__str__(self): return self.name class FormPort(forms.ModelForm): pass class Meta: model =",
"models.ImageField(upload_to='images', blank=True) def __str__(self): return self.name class FormPort(forms.ModelForm): pass class",
"# Create your models here. class Port(models.Model): name = models.CharField(max_length=250)",
"name = models.CharField(max_length=250) port = models.CharField(max_length=250) description = models.TextField(blank=True) audit_log",
"class Port(models.Model): name = models.CharField(max_length=250) port = models.CharField(max_length=250) description =",
"= models.CharField(max_length=250) description = models.TextField(blank=True) audit_log = AuditLog() #icon =",
"return self.name class FormPort(forms.ModelForm): pass class Meta: model = Port",
"AuditLog() #icon = models.ImageField(upload_to='images', blank=True) def __str__(self): return self.name class",
"models.CharField(max_length=250) port = models.CharField(max_length=250) description = models.TextField(blank=True) audit_log = AuditLog()",
"= models.ImageField(upload_to='images', blank=True) def __str__(self): return self.name class FormPort(forms.ModelForm): pass",
"AuditLog # Create your models here. class Port(models.Model): name =",
"= models.TextField(blank=True) audit_log = AuditLog() #icon = models.ImageField(upload_to='images', blank=True) def",
"import forms from audit_log.models.managers import AuditLog # Create your models",
"from audit_log.models.managers import AuditLog # Create your models here. class",
"Create your models here. class Port(models.Model): name = models.CharField(max_length=250) port",
"forms from audit_log.models.managers import AuditLog # Create your models here.",
"audit_log = AuditLog() #icon = models.ImageField(upload_to='images', blank=True) def __str__(self): return",
"#icon = models.ImageField(upload_to='images', blank=True) def __str__(self): return self.name class FormPort(forms.ModelForm):",
"from django import forms from audit_log.models.managers import AuditLog # Create",
"= models.CharField(max_length=250) port = models.CharField(max_length=250) description = models.TextField(blank=True) audit_log =",
"models from django import forms from audit_log.models.managers import AuditLog #",
"audit_log.models.managers import AuditLog # Create your models here. class Port(models.Model):",
"from django.db import models from django import forms from audit_log.models.managers",
"import models from django import forms from audit_log.models.managers import AuditLog",
"models.TextField(blank=True) audit_log = AuditLog() #icon = models.ImageField(upload_to='images', blank=True) def __str__(self):",
"your models here. class Port(models.Model): name = models.CharField(max_length=250) port =",
"Port(models.Model): name = models.CharField(max_length=250) port = models.CharField(max_length=250) description = models.TextField(blank=True)",
"port = models.CharField(max_length=250) description = models.TextField(blank=True) audit_log = AuditLog() #icon"
] |
[
"2.2.5 on 2019-09-25 00:12 from django.db import migrations class Migration(migrations.Migration):",
"migrations class Migration(migrations.Migration): dependencies = [ ('arm', '0001_initial'), ] operations",
"operations = [ migrations.DeleteModel( name='CautionMessage', ), migrations.DeleteModel( name='RiskRatingValue', ), ]",
"from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('arm',",
"] operations = [ migrations.DeleteModel( name='CautionMessage', ), migrations.DeleteModel( name='RiskRatingValue', ),",
"class Migration(migrations.Migration): dependencies = [ ('arm', '0001_initial'), ] operations =",
"by Django 2.2.5 on 2019-09-25 00:12 from django.db import migrations",
"Migration(migrations.Migration): dependencies = [ ('arm', '0001_initial'), ] operations = [",
"# Generated by Django 2.2.5 on 2019-09-25 00:12 from django.db",
"import migrations class Migration(migrations.Migration): dependencies = [ ('arm', '0001_initial'), ]",
"on 2019-09-25 00:12 from django.db import migrations class Migration(migrations.Migration): dependencies",
"<reponame>karstenv/nmp-arm # Generated by Django 2.2.5 on 2019-09-25 00:12 from",
"00:12 from django.db import migrations class Migration(migrations.Migration): dependencies = [",
"django.db import migrations class Migration(migrations.Migration): dependencies = [ ('arm', '0001_initial'),",
"('arm', '0001_initial'), ] operations = [ migrations.DeleteModel( name='CautionMessage', ), migrations.DeleteModel(",
"dependencies = [ ('arm', '0001_initial'), ] operations = [ migrations.DeleteModel(",
"2019-09-25 00:12 from django.db import migrations class Migration(migrations.Migration): dependencies =",
"Django 2.2.5 on 2019-09-25 00:12 from django.db import migrations class",
"Generated by Django 2.2.5 on 2019-09-25 00:12 from django.db import",
"'0001_initial'), ] operations = [ migrations.DeleteModel( name='CautionMessage', ), migrations.DeleteModel( name='RiskRatingValue',",
"[ ('arm', '0001_initial'), ] operations = [ migrations.DeleteModel( name='CautionMessage', ),",
"= [ ('arm', '0001_initial'), ] operations = [ migrations.DeleteModel( name='CautionMessage',"
] |
[
"# tf.config.threading.set_inter_op_parallelism_threads(0) # tf.config.threading.set_intra_op_parallelism_threads(0) # print(tf.config.threading.get_inter_op_parallelism_threads()) # print(tf.config.threading.get_intra_op_parallelism_threads()) with tf.compat.v1.Session()",
"blur = cv2.GaussianBlur(gray,(15,15),0) # _, thresh = cv2.threshold(blur,20,255,cv2.THRESH_BINARY) # dilated",
"keypoint_coords = posenet.decode_multi.decode_multiple_poses( heatmaps_result.squeeze(axis=0), offsets_result.squeeze(axis=0), displacement_fwd_result.squeeze(axis=0), displacement_bwd_result.squeeze(axis=0), output_stride=output_stride, max_pose_detections=1, min_pose_score=0.15)",
"keyboard.is_pressed('q'): print('you pressed q - quitting!') cv2.destroyAllWindows() break print('Average FPS:",
"if(cv2.contourArea(contour)>400): # continue # cv2.rectangle(frame1,(x,y),(x+w,y+h),(0,255,0),2) # # cv2.drawContours(frame1,contours, -1,(0,255,0),2) #",
"args=(str(path+filename),str(file_content))) x.start() x.join() file_content = [] if cv2.waitKey(1) & keyboard.is_pressed('a'):",
"recording = True # ret,frame1 = cap.read() # ret,frame2 =",
"# cv2.drawContours(frame1,contours, -1,(0,255,0),2) # cv2.imshow(\"feed\",frame1) # frame1 = frame2 #",
"video file instead of a live camera\") args = parser.parse_args()",
"= [] if cv2.waitKey(1) & keyboard.is_pressed('a'): print('you pressed a -",
"min_pose_score=0.15) keypoint_coords *= output_scale # TODO this isn't particularly fast,",
"= cv2.absdiff(frame1,frame2) # gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) # blur =",
"model_outputs, feed_dict={'image:0': input_image} ) pose_scores, keypoint_scores, keypoint_coords = posenet.decode_multi.decode_multiple_poses( heatmaps_result.squeeze(axis=0),",
"if cv2.waitKey(1) & keyboard.is_pressed('w'): print('you pressed w - service it",
"_ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # # if(len(contours)>0): # #",
"output_scale # TODO this isn't particularly fast, use GL for",
"= (left[0]+right[0])/2.0 y = (left[1]+right[1])/2.0 return [x,y] def find_distance(pointA,pointB): dist",
"leftHipCords = poses[0][11] rightHipCords = poses[0][12] middleHipPoint = find_middle(leftHipCords,rightHipCords) armHipDistance",
"& keyboard.is_pressed('d'): print('you pressed d - forehand it was!') time.sleep(0.5)",
"model_outputs = posenet.load_model(args.model, sess) output_stride = model_cfg['output_stride'] if args.file is",
"ret, frame2 = cap.read() input_image, display_image, output_scale = posenet.read_cap(cap, scale_factor=args.scale_factor,",
"of a live camera\") args = parser.parse_args() def main(): #",
"def my_function(toPrint): print(toPrint) def save_to_file(filename,data): file = open(filename,'w') file.write(data) file.close()",
"= posenet.draw_skel_and_kp( display_image, pose_scores, keypoint_scores, keypoint_coords, min_pose_score=0.15, min_part_score=0.15) cv2.imshow('posenet', img)",
"type=int, default=101) parser.add_argument('--cam_id', type=int, default=0) parser.add_argument('--cam_width', type=int, default=1280) parser.add_argument('--cam_height', type=int,",
"path = \"collected/forehand/\" filename = str(slugify(\"f-\"+str(time.time()))+\".txt\") x = Thread(target=save_to_file, args=(str(path+filename),str(file_content)))",
"print(tf.config.threading.get_intra_op_parallelism_threads()) with tf.compat.v1.Session() as sess: model_cfg, model_outputs = posenet.load_model(args.model, sess)",
"= find_middle(leftHipCords,rightHipCords) armHipDistance = find_distance(middleHipPoint,middleShoulderPoint); normalized = [] for pose",
"ret,frame1 = cap.read() # ret,frame2 = cap.read() file_content = []",
"a - backhand it was!') time.sleep(0.5) path = \"collected/backhand/\" filename",
"displacement_fwd_result.squeeze(axis=0), displacement_bwd_result.squeeze(axis=0), output_stride=output_stride, max_pose_detections=1, min_pose_score=0.15) keypoint_coords *= output_scale # TODO",
"= argparse.ArgumentParser() parser.add_argument('--model', type=int, default=101) parser.add_argument('--cam_id', type=int, default=0) parser.add_argument('--cam_width', type=int,",
"default=0) parser.add_argument('--cam_width', type=int, default=1280) parser.add_argument('--cam_height', type=int, default=720) parser.add_argument('--scale_factor', type=float, default=0.7125)",
"displacement_fwd_result, displacement_bwd_result = sess.run( model_outputs, feed_dict={'image:0': input_image} ) pose_scores, keypoint_scores,",
"for drawing and display someday... # print(\"\\n ===================================== \\n\") img",
"pose_scores, keypoint_scores, keypoint_coords = posenet.decode_multi.decode_multiple_poses( heatmaps_result.squeeze(axis=0), offsets_result.squeeze(axis=0), displacement_fwd_result.squeeze(axis=0), displacement_bwd_result.squeeze(axis=0), output_stride=output_stride,",
"d - forehand it was!') time.sleep(0.5) path = \"collected/forehand/\" filename",
"tf import json import math import cv2 import time import",
"img) frame_count += 1 if(recording): normalize_poses(keypoint_coords) results = json.dumps({ \"timestamp\":time.time()",
"filename = str(slugify(\"b-\"+str(time.time()))+\".txt\") x = Thread(target=save_to_file, args=(str(path+filename),str(file_content))) x.start() x.join() file_content",
"+ (pointB[1] - pointA[1])**2) return dist def normalize_poses(poses): leftShoulderCords =",
"posenet.decode_multi.decode_multiple_poses( heatmaps_result.squeeze(axis=0), offsets_result.squeeze(axis=0), displacement_fwd_result.squeeze(axis=0), displacement_bwd_result.squeeze(axis=0), output_stride=output_stride, max_pose_detections=1, min_pose_score=0.15) keypoint_coords *=",
"normalize_poses(keypoint_coords) results = json.dumps({ \"timestamp\":time.time() - start, \"pose_scores\":pose_scores.tolist(), \"keypoint_scores\":keypoint_scores.tolist(), \"scores\":",
"rightShoulderCords = poses[0][6] middleShoulderPoint = find_middle(leftShoulderCords,rightShoulderCords) leftHipCords = poses[0][11] rightHipCords",
"if(len(contours)>0): # # print(\"One:\") # # print(dir(contours[0])) # # print(\"One",
"= math.sqrt((pointB[0] - pointA[0])**2 + (pointB[1] - pointA[1])**2) return dist",
"cv2.waitKey(1) & keyboard.is_pressed('a'): print('you pressed a - backhand it was!')",
"= cap.read() file_content = [] while True: # diff =",
"this isn't particularly fast, use GL for drawing and display",
"cap.set(3, args.cam_width) cap.set(4, args.cam_height) start = time.time() frame_count = 0",
"= str(slugify(\"s-\"+str(time.time()))+\".txt\") x = Thread(target=save_to_file, args=(str(path+filename),str(file_content))) x.start() x.join() file_content =",
"= str(slugify(\"f-\"+str(time.time()))+\".txt\") x = Thread(target=save_to_file, args=(str(path+filename),str(file_content))) x.start() x.join() file_content =",
"if(recording): normalize_poses(keypoint_coords) results = json.dumps({ \"timestamp\":time.time() - start, \"pose_scores\":pose_scores.tolist(), \"keypoint_scores\":keypoint_scores.tolist(),",
"= find_middle(leftShoulderCords,rightShoulderCords) leftHipCords = poses[0][11] rightHipCords = poses[0][12] middleHipPoint =",
"poses[0][6] middleShoulderPoint = find_middle(leftShoulderCords,rightShoulderCords) leftHipCords = poses[0][11] rightHipCords = poses[0][12]",
"= time.time() frame_count = 0 recording = True # ret,frame1",
"w - service it was!') time.sleep(0.5) path = \"collected/serves/\" filename",
"keyboard import sys import numpy as np from threading import",
"import keyboard import sys import numpy as np from threading",
"slugify parser = argparse.ArgumentParser() parser.add_argument('--model', type=int, default=101) parser.add_argument('--cam_id', type=int, default=0)",
"\"scores\": keypoint_scores.size, \"keypoint_coords\":normalize_poses(keypoint_coords), \"coords\": keypoint_coords.size }) file_content.append(results) file_content = file_content[-30:]",
"pointA[1])**2) return dist def normalize_poses(poses): leftShoulderCords = poses[0][5] rightShoulderCords =",
"particularly fast, use GL for drawing and display someday... #",
"isn't particularly fast, use GL for drawing and display someday...",
"default=101) parser.add_argument('--cam_id', type=int, default=0) parser.add_argument('--cam_width', type=int, default=1280) parser.add_argument('--cam_height', type=int, default=720)",
"pressed w - service it was!') time.sleep(0.5) path = \"collected/serves/\"",
"x.join() file_content = [] if cv2.waitKey(1) & keyboard.is_pressed('d'): print('you pressed",
"print('you pressed q - quitting!') cv2.destroyAllWindows() break print('Average FPS: ',",
"print('you pressed d - forehand it was!') time.sleep(0.5) path =",
"\"collected/backhand/\" filename = str(slugify(\"b-\"+str(time.time()))+\".txt\") x = Thread(target=save_to_file, args=(str(path+filename),str(file_content))) x.start() x.join()",
"help=\"Optionally use a video file instead of a live camera\")",
"# print(\"\\n ===================================== \\n\") img = posenet.draw_skel_and_kp( display_image, pose_scores, keypoint_scores,",
"= model_cfg['output_stride'] if args.file is not None: cap = cv2.VideoCapture(args.file)",
"# blur = cv2.GaussianBlur(gray,(15,15),0) # _, thresh = cv2.threshold(blur,20,255,cv2.THRESH_BINARY) #",
"print(toPrint) def save_to_file(filename,data): file = open(filename,'w') file.write(data) file.close() def find_middle(left,right):",
"json.dumps({ \"timestamp\":time.time() - start, \"pose_scores\":pose_scores.tolist(), \"keypoint_scores\":keypoint_scores.tolist(), \"scores\": keypoint_scores.size, \"keypoint_coords\":normalize_poses(keypoint_coords), \"coords\":",
"print(tf.config.threading.get_inter_op_parallelism_threads()) # print(tf.config.threading.get_intra_op_parallelism_threads()) with tf.compat.v1.Session() as sess: model_cfg, model_outputs =",
"it was!') time.sleep(0.5) path = \"collected/forehand/\" filename = str(slugify(\"f-\"+str(time.time()))+\".txt\") x",
"file_content[-30:] if cv2.waitKey(1) & keyboard.is_pressed('w'): print('you pressed w - service",
"\"keypoint_coords\":normalize_poses(keypoint_coords), \"coords\": keypoint_coords.size }) file_content.append(results) file_content = file_content[-30:] if cv2.waitKey(1)",
"# # print(\"One it is.\") # for contour in contours:",
"rightHipCords = poses[0][12] middleHipPoint = find_middle(leftHipCords,rightHipCords) armHipDistance = find_distance(middleHipPoint,middleShoulderPoint); normalized",
"x.start() x.join() file_content = [] if cv2.waitKey(1) & keyboard.is_pressed('d'): print('you",
"save_to_file(filename,data): file = open(filename,'w') file.write(data) file.close() def find_middle(left,right): x =",
"normalized.append( [(pose[0]-middleHipPoint[0])/armHipDistance, (pose[1]-middleHipPoint[1])/armHipDistance] ) return normalized if __name__ == \"__main__\":",
"args = parser.parse_args() def main(): # tf.config.threading.set_inter_op_parallelism_threads(0) # tf.config.threading.set_intra_op_parallelism_threads(0) #",
"main(): # tf.config.threading.set_inter_op_parallelism_threads(0) # tf.config.threading.set_intra_op_parallelism_threads(0) # print(tf.config.threading.get_inter_op_parallelism_threads()) # print(tf.config.threading.get_intra_op_parallelism_threads()) with",
"find_middle(left,right): x = (left[0]+right[0])/2.0 y = (left[1]+right[1])/2.0 return [x,y] def",
"print(\"\\n ===================================== \\n\") img = posenet.draw_skel_and_kp( display_image, pose_scores, keypoint_scores, keypoint_coords,",
"===================================== \\n\") img = posenet.draw_skel_and_kp( display_image, pose_scores, keypoint_scores, keypoint_coords, min_pose_score=0.15,",
"keyboard.is_pressed('a'): print('you pressed a - backhand it was!') time.sleep(0.5) path",
"default=None, help=\"Optionally use a video file instead of a live",
"sess.run( model_outputs, feed_dict={'image:0': input_image} ) pose_scores, keypoint_scores, keypoint_coords = posenet.decode_multi.decode_multiple_poses(",
"diff = cv2.absdiff(frame1,frame2) # gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) # blur",
"cv2.dilate(thresh,None, iterations=3) # contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) #",
"import posenet import keyboard import sys import numpy as np",
"# ret,frame1 = cap.read() # ret,frame2 = cap.read() file_content =",
"parser.add_argument('--cam_id', type=int, default=0) parser.add_argument('--cam_width', type=int, default=1280) parser.add_argument('--cam_height', type=int, default=720) parser.add_argument('--scale_factor',",
"= str(slugify(\"b-\"+str(time.time()))+\".txt\") x = Thread(target=save_to_file, args=(str(path+filename),str(file_content))) x.start() x.join() file_content =",
"print(dir(contours[0])) # # print(\"One it is.\") # for contour in",
"= cv2.dilate(thresh,None, iterations=3) # contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)",
"= poses[0][5] rightShoulderCords = poses[0][6] middleShoulderPoint = find_middle(leftShoulderCords,rightShoulderCords) leftHipCords =",
"= cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) # blur = cv2.GaussianBlur(gray,(15,15),0) # _, thresh",
"cap.read() file_content = [] while True: # diff = cv2.absdiff(frame1,frame2)",
"[] while True: # diff = cv2.absdiff(frame1,frame2) # gray =",
"= \"collected/forehand/\" filename = str(slugify(\"f-\"+str(time.time()))+\".txt\") x = Thread(target=save_to_file, args=(str(path+filename),str(file_content))) x.start()",
"is.\") # for contour in contours: # (x,y,w,h) = cv2.boundingRect(contour)",
"cv2.imshow('posenet', img) frame_count += 1 if(recording): normalize_poses(keypoint_coords) results = json.dumps({",
"return [x,y] def find_distance(pointA,pointB): dist = math.sqrt((pointB[0] - pointA[0])**2 +",
"type=float, default=0.7125) parser.add_argument('--file', type=str, default=None, help=\"Optionally use a video file",
"concurrent.futures import posenet import keyboard import sys import numpy as",
"(left[1]+right[1])/2.0 return [x,y] def find_distance(pointA,pointB): dist = math.sqrt((pointB[0] - pointA[0])**2",
"offsets_result, displacement_fwd_result, displacement_bwd_result = sess.run( model_outputs, feed_dict={'image:0': input_image} ) pose_scores,",
"\"timestamp\":time.time() - start, \"pose_scores\":pose_scores.tolist(), \"keypoint_scores\":keypoint_scores.tolist(), \"scores\": keypoint_scores.size, \"keypoint_coords\":normalize_poses(keypoint_coords), \"coords\": keypoint_coords.size",
"my_function(toPrint): print(toPrint) def save_to_file(filename,data): file = open(filename,'w') file.write(data) file.close() def",
"find_distance(middleHipPoint,middleShoulderPoint); normalized = [] for pose in poses[0]: normalized.append( [(pose[0]-middleHipPoint[0])/armHipDistance,",
"forehand it was!') time.sleep(0.5) path = \"collected/forehand/\" filename = str(slugify(\"f-\"+str(time.time()))+\".txt\")",
"path = \"collected/serves/\" filename = str(slugify(\"s-\"+str(time.time()))+\".txt\") x = Thread(target=save_to_file, args=(str(path+filename),str(file_content)))",
"parser.add_argument('--file', type=str, default=None, help=\"Optionally use a video file instead of",
"use a video file instead of a live camera\") args",
"(left[0]+right[0])/2.0 y = (left[1]+right[1])/2.0 return [x,y] def find_distance(pointA,pointB): dist =",
"0 recording = True # ret,frame1 = cap.read() # ret,frame2",
"import json import math import cv2 import time import argparse",
"x.start() x.join() file_content = [] if cv2.waitKey(1) & keyboard.is_pressed('a'): print('you",
"cap = cv2.VideoCapture(args.cam_id) cap.set(3, args.cam_width) cap.set(4, args.cam_height) start = time.time()",
"# _, thresh = cv2.threshold(blur,20,255,cv2.THRESH_BINARY) # dilated = cv2.dilate(thresh,None, iterations=3)",
"cv2.rectangle(frame1,(x,y),(x+w,y+h),(0,255,0),2) # # cv2.drawContours(frame1,contours, -1,(0,255,0),2) # cv2.imshow(\"feed\",frame1) # frame1 =",
"[x,y] def find_distance(pointA,pointB): dist = math.sqrt((pointB[0] - pointA[0])**2 + (pointB[1]",
"was!') time.sleep(0.5) path = \"collected/forehand/\" filename = str(slugify(\"f-\"+str(time.time()))+\".txt\") x =",
"/ (time.time() - start)) return 0 def my_function(toPrint): print(toPrint) def",
"import math import cv2 import time import argparse import concurrent.futures",
"# contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # # if(len(contours)>0):",
"# for contour in contours: # (x,y,w,h) = cv2.boundingRect(contour) #",
"[] if cv2.waitKey(1) & keyboard.is_pressed('a'): print('you pressed a - backhand",
"[] if cv2.waitKey(1) & keyboard.is_pressed('q'): print('you pressed q - quitting!')",
"Thread(target=save_to_file, args=(str(path+filename),str(file_content))) x.start() x.join() file_content = [] if cv2.waitKey(1) &",
"contour in contours: # (x,y,w,h) = cv2.boundingRect(contour) # if(cv2.contourArea(contour)>400): #",
"print('you pressed a - backhand it was!') time.sleep(0.5) path =",
"output_stride = model_cfg['output_stride'] if args.file is not None: cap =",
"[] for pose in poses[0]: normalized.append( [(pose[0]-middleHipPoint[0])/armHipDistance, (pose[1]-middleHipPoint[1])/armHipDistance] ) return",
"# (x,y,w,h) = cv2.boundingRect(contour) # if(cv2.contourArea(contour)>400): # continue # cv2.rectangle(frame1,(x,y),(x+w,y+h),(0,255,0),2)",
"file_content.append(results) file_content = file_content[-30:] if cv2.waitKey(1) & keyboard.is_pressed('w'): print('you pressed",
"keypoint_coords, min_pose_score=0.15, min_part_score=0.15) cv2.imshow('posenet', img) frame_count += 1 if(recording): normalize_poses(keypoint_coords)",
"tf.config.threading.set_intra_op_parallelism_threads(0) # print(tf.config.threading.get_inter_op_parallelism_threads()) # print(tf.config.threading.get_intra_op_parallelism_threads()) with tf.compat.v1.Session() as sess: model_cfg,",
"if args.file is not None: cap = cv2.VideoCapture(args.file) else: cap",
"True: # diff = cv2.absdiff(frame1,frame2) # gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)",
"= cap.read() input_image, display_image, output_scale = posenet.read_cap(cap, scale_factor=args.scale_factor, output_stride=output_stride) heatmaps_result,",
"as sess: model_cfg, model_outputs = posenet.load_model(args.model, sess) output_stride = model_cfg['output_stride']",
"file_content = [] if cv2.waitKey(1) & keyboard.is_pressed('d'): print('you pressed d",
"time.sleep(0.5) path = \"collected/forehand/\" filename = str(slugify(\"f-\"+str(time.time()))+\".txt\") x = Thread(target=save_to_file,",
"[(pose[0]-middleHipPoint[0])/armHipDistance, (pose[1]-middleHipPoint[1])/armHipDistance] ) return normalized if __name__ == \"__main__\": main()",
"# ret,frame2 = cap.read() file_content = [] while True: #",
"= [] if cv2.waitKey(1) & keyboard.is_pressed('q'): print('you pressed q -",
"for pose in poses[0]: normalized.append( [(pose[0]-middleHipPoint[0])/armHipDistance, (pose[1]-middleHipPoint[1])/armHipDistance] ) return normalized",
"posenet.draw_skel_and_kp( display_image, pose_scores, keypoint_scores, keypoint_coords, min_pose_score=0.15, min_part_score=0.15) cv2.imshow('posenet', img) frame_count",
"cv2.waitKey(1) & keyboard.is_pressed('q'): print('you pressed q - quitting!') cv2.destroyAllWindows() break",
"type=int, default=1280) parser.add_argument('--cam_height', type=int, default=720) parser.add_argument('--scale_factor', type=float, default=0.7125) parser.add_argument('--file', type=str,",
"is not None: cap = cv2.VideoCapture(args.file) else: cap = cv2.VideoCapture(args.cam_id)",
"- start)) return 0 def my_function(toPrint): print(toPrint) def save_to_file(filename,data): file",
"= cv2.boundingRect(contour) # if(cv2.contourArea(contour)>400): # continue # cv2.rectangle(frame1,(x,y),(x+w,y+h),(0,255,0),2) # #",
"parser.parse_args() def main(): # tf.config.threading.set_inter_op_parallelism_threads(0) # tf.config.threading.set_intra_op_parallelism_threads(0) # print(tf.config.threading.get_inter_op_parallelism_threads()) #",
"cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) # blur = cv2.GaussianBlur(gray,(15,15),0) # _, thresh =",
"cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # # if(len(contours)>0): # # print(\"One:\") #",
"input_image} ) pose_scores, keypoint_scores, keypoint_coords = posenet.decode_multi.decode_multiple_poses( heatmaps_result.squeeze(axis=0), offsets_result.squeeze(axis=0), displacement_fwd_result.squeeze(axis=0),",
"1 if(recording): normalize_poses(keypoint_coords) results = json.dumps({ \"timestamp\":time.time() - start, \"pose_scores\":pose_scores.tolist(),",
"default=720) parser.add_argument('--scale_factor', type=float, default=0.7125) parser.add_argument('--file', type=str, default=None, help=\"Optionally use a",
"\"coords\": keypoint_coords.size }) file_content.append(results) file_content = file_content[-30:] if cv2.waitKey(1) &",
"', frame_count / (time.time() - start)) return 0 def my_function(toPrint):",
"def find_distance(pointA,pointB): dist = math.sqrt((pointB[0] - pointA[0])**2 + (pointB[1] -",
"# print(tf.config.threading.get_inter_op_parallelism_threads()) # print(tf.config.threading.get_intra_op_parallelism_threads()) with tf.compat.v1.Session() as sess: model_cfg, model_outputs",
"# dilated = cv2.dilate(thresh,None, iterations=3) # contours, _ = cv2.findContours(dilated,",
"was!') time.sleep(0.5) path = \"collected/backhand/\" filename = str(slugify(\"b-\"+str(time.time()))+\".txt\") x =",
"# ret, frame2 = cap.read() input_image, display_image, output_scale = posenet.read_cap(cap,",
"cv2 import time import argparse import concurrent.futures import posenet import",
"offsets_result.squeeze(axis=0), displacement_fwd_result.squeeze(axis=0), displacement_bwd_result.squeeze(axis=0), output_stride=output_stride, max_pose_detections=1, min_pose_score=0.15) keypoint_coords *= output_scale #",
"display someday... # print(\"\\n ===================================== \\n\") img = posenet.draw_skel_and_kp( display_image,",
"as tf import json import math import cv2 import time",
"frame_count / (time.time() - start)) return 0 def my_function(toPrint): print(toPrint)",
"a video file instead of a live camera\") args =",
"default=1280) parser.add_argument('--cam_height', type=int, default=720) parser.add_argument('--scale_factor', type=float, default=0.7125) parser.add_argument('--file', type=str, default=None,",
"str(slugify(\"s-\"+str(time.time()))+\".txt\") x = Thread(target=save_to_file, args=(str(path+filename),str(file_content))) x.start() x.join() file_content = []",
"cap = cv2.VideoCapture(args.file) else: cap = cv2.VideoCapture(args.cam_id) cap.set(3, args.cam_width) cap.set(4,",
"find_middle(leftShoulderCords,rightShoulderCords) leftHipCords = poses[0][11] rightHipCords = poses[0][12] middleHipPoint = find_middle(leftHipCords,rightHipCords)",
"y = (left[1]+right[1])/2.0 return [x,y] def find_distance(pointA,pointB): dist = math.sqrt((pointB[0]",
"poses[0][5] rightShoulderCords = poses[0][6] middleShoulderPoint = find_middle(leftShoulderCords,rightShoulderCords) leftHipCords = poses[0][11]",
"thresh = cv2.threshold(blur,20,255,cv2.THRESH_BINARY) # dilated = cv2.dilate(thresh,None, iterations=3) # contours,",
"args.cam_height) start = time.time() frame_count = 0 recording = True",
"keypoint_coords *= output_scale # TODO this isn't particularly fast, use",
"poses[0][11] rightHipCords = poses[0][12] middleHipPoint = find_middle(leftHipCords,rightHipCords) armHipDistance = find_distance(middleHipPoint,middleShoulderPoint);",
"# print(tf.config.threading.get_intra_op_parallelism_threads()) with tf.compat.v1.Session() as sess: model_cfg, model_outputs = posenet.load_model(args.model,",
"args=(str(path+filename),str(file_content))) x.start() x.join() file_content = [] if cv2.waitKey(1) & keyboard.is_pressed('q'):",
"= Thread(target=save_to_file, args=(str(path+filename),str(file_content))) x.start() x.join() file_content = [] if cv2.waitKey(1)",
"args=(str(path+filename),str(file_content))) x.start() x.join() file_content = [] if cv2.waitKey(1) & keyboard.is_pressed('d'):",
"it was!') time.sleep(0.5) path = \"collected/serves/\" filename = str(slugify(\"s-\"+str(time.time()))+\".txt\") x",
"min_part_score=0.15) cv2.imshow('posenet', img) frame_count += 1 if(recording): normalize_poses(keypoint_coords) results =",
"json import math import cv2 import time import argparse import",
"& keyboard.is_pressed('w'): print('you pressed w - service it was!') time.sleep(0.5)",
"frame2 # ret, frame2 = cap.read() input_image, display_image, output_scale =",
"cap.read() # ret,frame2 = cap.read() file_content = [] while True:",
"it was!') time.sleep(0.5) path = \"collected/backhand/\" filename = str(slugify(\"b-\"+str(time.time()))+\".txt\") x",
"= cv2.VideoCapture(args.file) else: cap = cv2.VideoCapture(args.cam_id) cap.set(3, args.cam_width) cap.set(4, args.cam_height)",
"math import cv2 import time import argparse import concurrent.futures import",
"= [] while True: # diff = cv2.absdiff(frame1,frame2) # gray",
"start, \"pose_scores\":pose_scores.tolist(), \"keypoint_scores\":keypoint_scores.tolist(), \"scores\": keypoint_scores.size, \"keypoint_coords\":normalize_poses(keypoint_coords), \"coords\": keypoint_coords.size }) file_content.append(results)",
"cv2.COLOR_BGR2GRAY) # blur = cv2.GaussianBlur(gray,(15,15),0) # _, thresh = cv2.threshold(blur,20,255,cv2.THRESH_BINARY)",
"# # print(dir(contours[0])) # # print(\"One it is.\") # for",
"in contours: # (x,y,w,h) = cv2.boundingRect(contour) # if(cv2.contourArea(contour)>400): # continue",
"use GL for drawing and display someday... # print(\"\\n =====================================",
"posenet.load_model(args.model, sess) output_stride = model_cfg['output_stride'] if args.file is not None:",
"backhand it was!') time.sleep(0.5) path = \"collected/backhand/\" filename = str(slugify(\"b-\"+str(time.time()))+\".txt\")",
"poses[0]: normalized.append( [(pose[0]-middleHipPoint[0])/armHipDistance, (pose[1]-middleHipPoint[1])/armHipDistance] ) return normalized if __name__ ==",
"keypoint_scores.size, \"keypoint_coords\":normalize_poses(keypoint_coords), \"coords\": keypoint_coords.size }) file_content.append(results) file_content = file_content[-30:] if",
"display_image, output_scale = posenet.read_cap(cap, scale_factor=args.scale_factor, output_stride=output_stride) heatmaps_result, offsets_result, displacement_fwd_result, displacement_bwd_result",
"True # ret,frame1 = cap.read() # ret,frame2 = cap.read() file_content",
"sys import numpy as np from threading import Thread from",
"# tf.config.threading.set_intra_op_parallelism_threads(0) # print(tf.config.threading.get_inter_op_parallelism_threads()) # print(tf.config.threading.get_intra_op_parallelism_threads()) with tf.compat.v1.Session() as sess:",
"numpy as np from threading import Thread from slugify import",
"output_stride=output_stride, max_pose_detections=1, min_pose_score=0.15) keypoint_coords *= output_scale # TODO this isn't",
"args.cam_width) cap.set(4, args.cam_height) start = time.time() frame_count = 0 recording",
"pose in poses[0]: normalized.append( [(pose[0]-middleHipPoint[0])/armHipDistance, (pose[1]-middleHipPoint[1])/armHipDistance] ) return normalized if",
"= posenet.load_model(args.model, sess) output_stride = model_cfg['output_stride'] if args.file is not",
"live camera\") args = parser.parse_args() def main(): # tf.config.threading.set_inter_op_parallelism_threads(0) #",
"q - quitting!') cv2.destroyAllWindows() break print('Average FPS: ', frame_count /",
"while True: # diff = cv2.absdiff(frame1,frame2) # gray = cv2.cvtColor(diff,",
"min_pose_score=0.15, min_part_score=0.15) cv2.imshow('posenet', img) frame_count += 1 if(recording): normalize_poses(keypoint_coords) results",
"tensorflow as tf import json import math import cv2 import",
"a live camera\") args = parser.parse_args() def main(): # tf.config.threading.set_inter_op_parallelism_threads(0)",
"(time.time() - start)) return 0 def my_function(toPrint): print(toPrint) def save_to_file(filename,data):",
"if cv2.waitKey(1) & keyboard.is_pressed('q'): print('you pressed q - quitting!') cv2.destroyAllWindows()",
"= poses[0][6] middleShoulderPoint = find_middle(leftShoulderCords,rightShoulderCords) leftHipCords = poses[0][11] rightHipCords =",
"# continue # cv2.rectangle(frame1,(x,y),(x+w,y+h),(0,255,0),2) # # cv2.drawContours(frame1,contours, -1,(0,255,0),2) # cv2.imshow(\"feed\",frame1)",
"cap.read() input_image, display_image, output_scale = posenet.read_cap(cap, scale_factor=args.scale_factor, output_stride=output_stride) heatmaps_result, offsets_result,",
"file_content = [] while True: # diff = cv2.absdiff(frame1,frame2) #",
"frame_count += 1 if(recording): normalize_poses(keypoint_coords) results = json.dumps({ \"timestamp\":time.time() -",
"default=0.7125) parser.add_argument('--file', type=str, default=None, help=\"Optionally use a video file instead",
"# print(\"One:\") # # print(dir(contours[0])) # # print(\"One it is.\")",
"import time import argparse import concurrent.futures import posenet import keyboard",
"posenet import keyboard import sys import numpy as np from",
"x.join() file_content = [] if cv2.waitKey(1) & keyboard.is_pressed('q'): print('you pressed",
"open(filename,'w') file.write(data) file.close() def find_middle(left,right): x = (left[0]+right[0])/2.0 y =",
"scale_factor=args.scale_factor, output_stride=output_stride) heatmaps_result, offsets_result, displacement_fwd_result, displacement_bwd_result = sess.run( model_outputs, feed_dict={'image:0':",
"cv2.CHAIN_APPROX_SIMPLE) # # if(len(contours)>0): # # print(\"One:\") # # print(dir(contours[0]))",
"parser = argparse.ArgumentParser() parser.add_argument('--model', type=int, default=101) parser.add_argument('--cam_id', type=int, default=0) parser.add_argument('--cam_width',",
"cv2.imshow(\"feed\",frame1) # frame1 = frame2 # ret, frame2 = cap.read()",
"= find_distance(middleHipPoint,middleShoulderPoint); normalized = [] for pose in poses[0]: normalized.append(",
"= json.dumps({ \"timestamp\":time.time() - start, \"pose_scores\":pose_scores.tolist(), \"keypoint_scores\":keypoint_scores.tolist(), \"scores\": keypoint_scores.size, \"keypoint_coords\":normalize_poses(keypoint_coords),",
"service it was!') time.sleep(0.5) path = \"collected/serves/\" filename = str(slugify(\"s-\"+str(time.time()))+\".txt\")",
"import slugify parser = argparse.ArgumentParser() parser.add_argument('--model', type=int, default=101) parser.add_argument('--cam_id', type=int,",
"- quitting!') cv2.destroyAllWindows() break print('Average FPS: ', frame_count / (time.time()",
"pose_scores, keypoint_scores, keypoint_coords, min_pose_score=0.15, min_part_score=0.15) cv2.imshow('posenet', img) frame_count += 1",
"keyboard.is_pressed('d'): print('you pressed d - forehand it was!') time.sleep(0.5) path",
"= \"collected/serves/\" filename = str(slugify(\"s-\"+str(time.time()))+\".txt\") x = Thread(target=save_to_file, args=(str(path+filename),str(file_content))) x.start()",
"parser.add_argument('--model', type=int, default=101) parser.add_argument('--cam_id', type=int, default=0) parser.add_argument('--cam_width', type=int, default=1280) parser.add_argument('--cam_height',",
"filename = str(slugify(\"s-\"+str(time.time()))+\".txt\") x = Thread(target=save_to_file, args=(str(path+filename),str(file_content))) x.start() x.join() file_content",
"continue # cv2.rectangle(frame1,(x,y),(x+w,y+h),(0,255,0),2) # # cv2.drawContours(frame1,contours, -1,(0,255,0),2) # cv2.imshow(\"feed\",frame1) #",
"middleShoulderPoint = find_middle(leftShoulderCords,rightShoulderCords) leftHipCords = poses[0][11] rightHipCords = poses[0][12] middleHipPoint",
"time.sleep(0.5) path = \"collected/serves/\" filename = str(slugify(\"s-\"+str(time.time()))+\".txt\") x = Thread(target=save_to_file,",
"dilated = cv2.dilate(thresh,None, iterations=3) # contours, _ = cv2.findContours(dilated, cv2.RETR_TREE,",
"heatmaps_result, offsets_result, displacement_fwd_result, displacement_bwd_result = sess.run( model_outputs, feed_dict={'image:0': input_image} )",
"model_cfg['output_stride'] if args.file is not None: cap = cv2.VideoCapture(args.file) else:",
"args.file is not None: cap = cv2.VideoCapture(args.file) else: cap =",
"gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) # blur = cv2.GaussianBlur(gray,(15,15),0) # _,",
"# TODO this isn't particularly fast, use GL for drawing",
"= parser.parse_args() def main(): # tf.config.threading.set_inter_op_parallelism_threads(0) # tf.config.threading.set_intra_op_parallelism_threads(0) # print(tf.config.threading.get_inter_op_parallelism_threads())",
"results = json.dumps({ \"timestamp\":time.time() - start, \"pose_scores\":pose_scores.tolist(), \"keypoint_scores\":keypoint_scores.tolist(), \"scores\": keypoint_scores.size,",
"x = Thread(target=save_to_file, args=(str(path+filename),str(file_content))) x.start() x.join() file_content = [] if",
"import argparse import concurrent.futures import posenet import keyboard import sys",
"find_distance(pointA,pointB): dist = math.sqrt((pointB[0] - pointA[0])**2 + (pointB[1] - pointA[1])**2)",
"# print(\"One it is.\") # for contour in contours: #",
"instead of a live camera\") args = parser.parse_args() def main():",
"= \"collected/backhand/\" filename = str(slugify(\"b-\"+str(time.time()))+\".txt\") x = Thread(target=save_to_file, args=(str(path+filename),str(file_content))) x.start()",
"camera\") args = parser.parse_args() def main(): # tf.config.threading.set_inter_op_parallelism_threads(0) # tf.config.threading.set_intra_op_parallelism_threads(0)",
"from slugify import slugify parser = argparse.ArgumentParser() parser.add_argument('--model', type=int, default=101)",
"import concurrent.futures import posenet import keyboard import sys import numpy",
"def main(): # tf.config.threading.set_inter_op_parallelism_threads(0) # tf.config.threading.set_intra_op_parallelism_threads(0) # print(tf.config.threading.get_inter_op_parallelism_threads()) # print(tf.config.threading.get_intra_op_parallelism_threads())",
"break print('Average FPS: ', frame_count / (time.time() - start)) return",
"\"collected/serves/\" filename = str(slugify(\"s-\"+str(time.time()))+\".txt\") x = Thread(target=save_to_file, args=(str(path+filename),str(file_content))) x.start() x.join()",
"math.sqrt((pointB[0] - pointA[0])**2 + (pointB[1] - pointA[1])**2) return dist def",
"# if(len(contours)>0): # # print(\"One:\") # # print(dir(contours[0])) # #",
"not None: cap = cv2.VideoCapture(args.file) else: cap = cv2.VideoCapture(args.cam_id) cap.set(3,",
"\"collected/forehand/\" filename = str(slugify(\"f-\"+str(time.time()))+\".txt\") x = Thread(target=save_to_file, args=(str(path+filename),str(file_content))) x.start() x.join()",
"= 0 recording = True # ret,frame1 = cap.read() #",
"# # cv2.drawContours(frame1,contours, -1,(0,255,0),2) # cv2.imshow(\"feed\",frame1) # frame1 = frame2",
"parser.add_argument('--cam_height', type=int, default=720) parser.add_argument('--scale_factor', type=float, default=0.7125) parser.add_argument('--file', type=str, default=None, help=\"Optionally",
"was!') time.sleep(0.5) path = \"collected/serves/\" filename = str(slugify(\"s-\"+str(time.time()))+\".txt\") x =",
"poses[0][12] middleHipPoint = find_middle(leftHipCords,rightHipCords) armHipDistance = find_distance(middleHipPoint,middleShoulderPoint); normalized = []",
"= open(filename,'w') file.write(data) file.close() def find_middle(left,right): x = (left[0]+right[0])/2.0 y",
"ret,frame2 = cap.read() file_content = [] while True: # diff",
"posenet.read_cap(cap, scale_factor=args.scale_factor, output_stride=output_stride) heatmaps_result, offsets_result, displacement_fwd_result, displacement_bwd_result = sess.run( model_outputs,",
"pressed q - quitting!') cv2.destroyAllWindows() break print('Average FPS: ', frame_count",
"_, thresh = cv2.threshold(blur,20,255,cv2.THRESH_BINARY) # dilated = cv2.dilate(thresh,None, iterations=3) #",
"max_pose_detections=1, min_pose_score=0.15) keypoint_coords *= output_scale # TODO this isn't particularly",
"x.join() file_content = [] if cv2.waitKey(1) & keyboard.is_pressed('a'): print('you pressed",
"argparse import concurrent.futures import posenet import keyboard import sys import",
"quitting!') cv2.destroyAllWindows() break print('Average FPS: ', frame_count / (time.time() -",
"cap.set(4, args.cam_height) start = time.time() frame_count = 0 recording =",
") pose_scores, keypoint_scores, keypoint_coords = posenet.decode_multi.decode_multiple_poses( heatmaps_result.squeeze(axis=0), offsets_result.squeeze(axis=0), displacement_fwd_result.squeeze(axis=0), displacement_bwd_result.squeeze(axis=0),",
"file = open(filename,'w') file.write(data) file.close() def find_middle(left,right): x = (left[0]+right[0])/2.0",
"keypoint_scores, keypoint_coords, min_pose_score=0.15, min_part_score=0.15) cv2.imshow('posenet', img) frame_count += 1 if(recording):",
"return dist def normalize_poses(poses): leftShoulderCords = poses[0][5] rightShoulderCords = poses[0][6]",
"= poses[0][12] middleHipPoint = find_middle(leftHipCords,rightHipCords) armHipDistance = find_distance(middleHipPoint,middleShoulderPoint); normalized =",
"displacement_bwd_result.squeeze(axis=0), output_stride=output_stride, max_pose_detections=1, min_pose_score=0.15) keypoint_coords *= output_scale # TODO this",
"slugify import slugify parser = argparse.ArgumentParser() parser.add_argument('--model', type=int, default=101) parser.add_argument('--cam_id',",
"dist = math.sqrt((pointB[0] - pointA[0])**2 + (pointB[1] - pointA[1])**2) return",
"else: cap = cv2.VideoCapture(args.cam_id) cap.set(3, args.cam_width) cap.set(4, args.cam_height) start =",
"pressed a - backhand it was!') time.sleep(0.5) path = \"collected/backhand/\"",
"import cv2 import time import argparse import concurrent.futures import posenet",
"output_scale = posenet.read_cap(cap, scale_factor=args.scale_factor, output_stride=output_stride) heatmaps_result, offsets_result, displacement_fwd_result, displacement_bwd_result =",
"if cv2.waitKey(1) & keyboard.is_pressed('a'): print('you pressed a - backhand it",
"iterations=3) # contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # #",
"dist def normalize_poses(poses): leftShoulderCords = poses[0][5] rightShoulderCords = poses[0][6] middleShoulderPoint",
"normalized = [] for pose in poses[0]: normalized.append( [(pose[0]-middleHipPoint[0])/armHipDistance, (pose[1]-middleHipPoint[1])/armHipDistance]",
"def normalize_poses(poses): leftShoulderCords = poses[0][5] rightShoulderCords = poses[0][6] middleShoulderPoint =",
"contours: # (x,y,w,h) = cv2.boundingRect(contour) # if(cv2.contourArea(contour)>400): # continue #",
"= file_content[-30:] if cv2.waitKey(1) & keyboard.is_pressed('w'): print('you pressed w -",
"cv2.boundingRect(contour) # if(cv2.contourArea(contour)>400): # continue # cv2.rectangle(frame1,(x,y),(x+w,y+h),(0,255,0),2) # # cv2.drawContours(frame1,contours,",
"start)) return 0 def my_function(toPrint): print(toPrint) def save_to_file(filename,data): file =",
"- service it was!') time.sleep(0.5) path = \"collected/serves/\" filename =",
"\"pose_scores\":pose_scores.tolist(), \"keypoint_scores\":keypoint_scores.tolist(), \"scores\": keypoint_scores.size, \"keypoint_coords\":normalize_poses(keypoint_coords), \"coords\": keypoint_coords.size }) file_content.append(results) file_content",
"heatmaps_result.squeeze(axis=0), offsets_result.squeeze(axis=0), displacement_fwd_result.squeeze(axis=0), displacement_bwd_result.squeeze(axis=0), output_stride=output_stride, max_pose_detections=1, min_pose_score=0.15) keypoint_coords *= output_scale",
"cv2.waitKey(1) & keyboard.is_pressed('d'): print('you pressed d - forehand it was!')",
"- pointA[1])**2) return dist def normalize_poses(poses): leftShoulderCords = poses[0][5] rightShoulderCords",
"time.sleep(0.5) path = \"collected/backhand/\" filename = str(slugify(\"b-\"+str(time.time()))+\".txt\") x = Thread(target=save_to_file,",
"= frame2 # ret, frame2 = cap.read() input_image, display_image, output_scale",
"argparse.ArgumentParser() parser.add_argument('--model', type=int, default=101) parser.add_argument('--cam_id', type=int, default=0) parser.add_argument('--cam_width', type=int, default=1280)",
"cv2.absdiff(frame1,frame2) # gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) # blur = cv2.GaussianBlur(gray,(15,15),0)",
"import Thread from slugify import slugify parser = argparse.ArgumentParser() parser.add_argument('--model',",
"cv2.VideoCapture(args.cam_id) cap.set(3, args.cam_width) cap.set(4, args.cam_height) start = time.time() frame_count =",
"start = time.time() frame_count = 0 recording = True #",
"import numpy as np from threading import Thread from slugify",
"= cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # # if(len(contours)>0): # # print(\"One:\")",
"cv2.destroyAllWindows() break print('Average FPS: ', frame_count / (time.time() - start))",
"time import argparse import concurrent.futures import posenet import keyboard import",
"feed_dict={'image:0': input_image} ) pose_scores, keypoint_scores, keypoint_coords = posenet.decode_multi.decode_multiple_poses( heatmaps_result.squeeze(axis=0), offsets_result.squeeze(axis=0),",
"file_content = file_content[-30:] if cv2.waitKey(1) & keyboard.is_pressed('w'): print('you pressed w",
"= sess.run( model_outputs, feed_dict={'image:0': input_image} ) pose_scores, keypoint_scores, keypoint_coords =",
"frame1 = frame2 # ret, frame2 = cap.read() input_image, display_image,",
"type=str, default=None, help=\"Optionally use a video file instead of a",
"parser.add_argument('--cam_width', type=int, default=1280) parser.add_argument('--cam_height', type=int, default=720) parser.add_argument('--scale_factor', type=float, default=0.7125) parser.add_argument('--file',",
"= cv2.GaussianBlur(gray,(15,15),0) # _, thresh = cv2.threshold(blur,20,255,cv2.THRESH_BINARY) # dilated =",
"= cv2.VideoCapture(args.cam_id) cap.set(3, args.cam_width) cap.set(4, args.cam_height) start = time.time() frame_count",
"[] if cv2.waitKey(1) & keyboard.is_pressed('d'): print('you pressed d - forehand",
"cv2.VideoCapture(args.file) else: cap = cv2.VideoCapture(args.cam_id) cap.set(3, args.cam_width) cap.set(4, args.cam_height) start",
"str(slugify(\"b-\"+str(time.time()))+\".txt\") x = Thread(target=save_to_file, args=(str(path+filename),str(file_content))) x.start() x.join() file_content = []",
"*= output_scale # TODO this isn't particularly fast, use GL",
"pressed d - forehand it was!') time.sleep(0.5) path = \"collected/forehand/\"",
"middleHipPoint = find_middle(leftHipCords,rightHipCords) armHipDistance = find_distance(middleHipPoint,middleShoulderPoint); normalized = [] for",
"it is.\") # for contour in contours: # (x,y,w,h) =",
"\\n\") img = posenet.draw_skel_and_kp( display_image, pose_scores, keypoint_scores, keypoint_coords, min_pose_score=0.15, min_part_score=0.15)",
"- pointA[0])**2 + (pointB[1] - pointA[1])**2) return dist def normalize_poses(poses):",
"# frame1 = frame2 # ret, frame2 = cap.read() input_image,",
"file.close() def find_middle(left,right): x = (left[0]+right[0])/2.0 y = (left[1]+right[1])/2.0 return",
"frame2 = cap.read() input_image, display_image, output_scale = posenet.read_cap(cap, scale_factor=args.scale_factor, output_stride=output_stride)",
"= True # ret,frame1 = cap.read() # ret,frame2 = cap.read()",
"display_image, pose_scores, keypoint_scores, keypoint_coords, min_pose_score=0.15, min_part_score=0.15) cv2.imshow('posenet', img) frame_count +=",
"keypoint_coords.size }) file_content.append(results) file_content = file_content[-30:] if cv2.waitKey(1) & keyboard.is_pressed('w'):",
"None: cap = cv2.VideoCapture(args.file) else: cap = cv2.VideoCapture(args.cam_id) cap.set(3, args.cam_width)",
"drawing and display someday... # print(\"\\n ===================================== \\n\") img =",
"file_content = [] if cv2.waitKey(1) & keyboard.is_pressed('a'): print('you pressed a",
"parser.add_argument('--scale_factor', type=float, default=0.7125) parser.add_argument('--file', type=str, default=None, help=\"Optionally use a video",
"sess: model_cfg, model_outputs = posenet.load_model(args.model, sess) output_stride = model_cfg['output_stride'] if",
"tf.compat.v1.Session() as sess: model_cfg, model_outputs = posenet.load_model(args.model, sess) output_stride =",
"with tf.compat.v1.Session() as sess: model_cfg, model_outputs = posenet.load_model(args.model, sess) output_stride",
"}) file_content.append(results) file_content = file_content[-30:] if cv2.waitKey(1) & keyboard.is_pressed('w'): print('you",
"- start, \"pose_scores\":pose_scores.tolist(), \"keypoint_scores\":keypoint_scores.tolist(), \"scores\": keypoint_scores.size, \"keypoint_coords\":normalize_poses(keypoint_coords), \"coords\": keypoint_coords.size })",
"pointA[0])**2 + (pointB[1] - pointA[1])**2) return dist def normalize_poses(poses): leftShoulderCords",
"# # print(\"One:\") # # print(dir(contours[0])) # # print(\"One it",
"= [] for pose in poses[0]: normalized.append( [(pose[0]-middleHipPoint[0])/armHipDistance, (pose[1]-middleHipPoint[1])/armHipDistance] )",
"import sys import numpy as np from threading import Thread",
"FPS: ', frame_count / (time.time() - start)) return 0 def",
"(pointB[1] - pointA[1])**2) return dist def normalize_poses(poses): leftShoulderCords = poses[0][5]",
"& keyboard.is_pressed('q'): print('you pressed q - quitting!') cv2.destroyAllWindows() break print('Average",
"def save_to_file(filename,data): file = open(filename,'w') file.write(data) file.close() def find_middle(left,right): x",
"= cv2.threshold(blur,20,255,cv2.THRESH_BINARY) # dilated = cv2.dilate(thresh,None, iterations=3) # contours, _",
"keyboard.is_pressed('w'): print('you pressed w - service it was!') time.sleep(0.5) path",
"str(slugify(\"f-\"+str(time.time()))+\".txt\") x = Thread(target=save_to_file, args=(str(path+filename),str(file_content))) x.start() x.join() file_content = []",
"print(\"One it is.\") # for contour in contours: # (x,y,w,h)",
"input_image, display_image, output_scale = posenet.read_cap(cap, scale_factor=args.scale_factor, output_stride=output_stride) heatmaps_result, offsets_result, displacement_fwd_result,",
"# cv2.rectangle(frame1,(x,y),(x+w,y+h),(0,255,0),2) # # cv2.drawContours(frame1,contours, -1,(0,255,0),2) # cv2.imshow(\"feed\",frame1) # frame1",
"normalize_poses(poses): leftShoulderCords = poses[0][5] rightShoulderCords = poses[0][6] middleShoulderPoint = find_middle(leftShoulderCords,rightShoulderCords)",
"np from threading import Thread from slugify import slugify parser",
"armHipDistance = find_distance(middleHipPoint,middleShoulderPoint); normalized = [] for pose in poses[0]:",
"threading import Thread from slugify import slugify parser = argparse.ArgumentParser()",
"print('Average FPS: ', frame_count / (time.time() - start)) return 0",
"if cv2.waitKey(1) & keyboard.is_pressed('d'): print('you pressed d - forehand it",
"file instead of a live camera\") args = parser.parse_args() def",
"path = \"collected/backhand/\" filename = str(slugify(\"b-\"+str(time.time()))+\".txt\") x = Thread(target=save_to_file, args=(str(path+filename),str(file_content)))",
"contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # # if(len(contours)>0): #",
"file.write(data) file.close() def find_middle(left,right): x = (left[0]+right[0])/2.0 y = (left[1]+right[1])/2.0",
"model_cfg, model_outputs = posenet.load_model(args.model, sess) output_stride = model_cfg['output_stride'] if args.file",
"someday... # print(\"\\n ===================================== \\n\") img = posenet.draw_skel_and_kp( display_image, pose_scores,",
"for contour in contours: # (x,y,w,h) = cv2.boundingRect(contour) # if(cv2.contourArea(contour)>400):",
"Thread from slugify import slugify parser = argparse.ArgumentParser() parser.add_argument('--model', type=int,",
"file_content = [] if cv2.waitKey(1) & keyboard.is_pressed('q'): print('you pressed q",
"and display someday... # print(\"\\n ===================================== \\n\") img = posenet.draw_skel_and_kp(",
"# # if(len(contours)>0): # # print(\"One:\") # # print(dir(contours[0])) #",
"keypoint_scores, keypoint_coords = posenet.decode_multi.decode_multiple_poses( heatmaps_result.squeeze(axis=0), offsets_result.squeeze(axis=0), displacement_fwd_result.squeeze(axis=0), displacement_bwd_result.squeeze(axis=0), output_stride=output_stride, max_pose_detections=1,",
"cv2.GaussianBlur(gray,(15,15),0) # _, thresh = cv2.threshold(blur,20,255,cv2.THRESH_BINARY) # dilated = cv2.dilate(thresh,None,",
"cv2.drawContours(frame1,contours, -1,(0,255,0),2) # cv2.imshow(\"feed\",frame1) # frame1 = frame2 # ret,",
"type=int, default=720) parser.add_argument('--scale_factor', type=float, default=0.7125) parser.add_argument('--file', type=str, default=None, help=\"Optionally use",
"= poses[0][11] rightHipCords = poses[0][12] middleHipPoint = find_middle(leftHipCords,rightHipCords) armHipDistance =",
"cv2.waitKey(1) & keyboard.is_pressed('w'): print('you pressed w - service it was!')",
"leftShoulderCords = poses[0][5] rightShoulderCords = poses[0][6] middleShoulderPoint = find_middle(leftShoulderCords,rightShoulderCords) leftHipCords",
"# diff = cv2.absdiff(frame1,frame2) # gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) #",
"frame_count = 0 recording = True # ret,frame1 = cap.read()",
"cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # # if(len(contours)>0): # # print(\"One:\") # #",
"(x,y,w,h) = cv2.boundingRect(contour) # if(cv2.contourArea(contour)>400): # continue # cv2.rectangle(frame1,(x,y),(x+w,y+h),(0,255,0),2) #",
"from threading import Thread from slugify import slugify parser =",
"= [] if cv2.waitKey(1) & keyboard.is_pressed('d'): print('you pressed d -",
"= (left[1]+right[1])/2.0 return [x,y] def find_distance(pointA,pointB): dist = math.sqrt((pointB[0] -",
"& keyboard.is_pressed('a'): print('you pressed a - backhand it was!') time.sleep(0.5)",
"fast, use GL for drawing and display someday... # print(\"\\n",
"0 def my_function(toPrint): print(toPrint) def save_to_file(filename,data): file = open(filename,'w') file.write(data)",
"img = posenet.draw_skel_and_kp( display_image, pose_scores, keypoint_scores, keypoint_coords, min_pose_score=0.15, min_part_score=0.15) cv2.imshow('posenet',",
"in poses[0]: normalized.append( [(pose[0]-middleHipPoint[0])/armHipDistance, (pose[1]-middleHipPoint[1])/armHipDistance] ) return normalized if __name__",
"x.start() x.join() file_content = [] if cv2.waitKey(1) & keyboard.is_pressed('q'): print('you",
"import tensorflow as tf import json import math import cv2",
"print(\"One:\") # # print(dir(contours[0])) # # print(\"One it is.\") #",
"as np from threading import Thread from slugify import slugify",
"find_middle(leftHipCords,rightHipCords) armHipDistance = find_distance(middleHipPoint,middleShoulderPoint); normalized = [] for pose in",
"tf.config.threading.set_inter_op_parallelism_threads(0) # tf.config.threading.set_intra_op_parallelism_threads(0) # print(tf.config.threading.get_inter_op_parallelism_threads()) # print(tf.config.threading.get_intra_op_parallelism_threads()) with tf.compat.v1.Session() as",
"-1,(0,255,0),2) # cv2.imshow(\"feed\",frame1) # frame1 = frame2 # ret, frame2",
"= posenet.decode_multi.decode_multiple_poses( heatmaps_result.squeeze(axis=0), offsets_result.squeeze(axis=0), displacement_fwd_result.squeeze(axis=0), displacement_bwd_result.squeeze(axis=0), output_stride=output_stride, max_pose_detections=1, min_pose_score=0.15) keypoint_coords",
"displacement_bwd_result = sess.run( model_outputs, feed_dict={'image:0': input_image} ) pose_scores, keypoint_scores, keypoint_coords",
"filename = str(slugify(\"f-\"+str(time.time()))+\".txt\") x = Thread(target=save_to_file, args=(str(path+filename),str(file_content))) x.start() x.join() file_content",
"print('you pressed w - service it was!') time.sleep(0.5) path =",
"sess) output_stride = model_cfg['output_stride'] if args.file is not None: cap",
"time.time() frame_count = 0 recording = True # ret,frame1 =",
"\"keypoint_scores\":keypoint_scores.tolist(), \"scores\": keypoint_scores.size, \"keypoint_coords\":normalize_poses(keypoint_coords), \"coords\": keypoint_coords.size }) file_content.append(results) file_content =",
"x = (left[0]+right[0])/2.0 y = (left[1]+right[1])/2.0 return [x,y] def find_distance(pointA,pointB):",
"cv2.threshold(blur,20,255,cv2.THRESH_BINARY) # dilated = cv2.dilate(thresh,None, iterations=3) # contours, _ =",
"# gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) # blur = cv2.GaussianBlur(gray,(15,15),0) #",
"= posenet.read_cap(cap, scale_factor=args.scale_factor, output_stride=output_stride) heatmaps_result, offsets_result, displacement_fwd_result, displacement_bwd_result = sess.run(",
"# print(dir(contours[0])) # # print(\"One it is.\") # for contour",
"# cv2.imshow(\"feed\",frame1) # frame1 = frame2 # ret, frame2 =",
"type=int, default=0) parser.add_argument('--cam_width', type=int, default=1280) parser.add_argument('--cam_height', type=int, default=720) parser.add_argument('--scale_factor', type=float,",
"output_stride=output_stride) heatmaps_result, offsets_result, displacement_fwd_result, displacement_bwd_result = sess.run( model_outputs, feed_dict={'image:0': input_image}",
"+= 1 if(recording): normalize_poses(keypoint_coords) results = json.dumps({ \"timestamp\":time.time() - start,",
"TODO this isn't particularly fast, use GL for drawing and",
"def find_middle(left,right): x = (left[0]+right[0])/2.0 y = (left[1]+right[1])/2.0 return [x,y]",
"= cap.read() # ret,frame2 = cap.read() file_content = [] while",
"GL for drawing and display someday... # print(\"\\n ===================================== \\n\")",
"- forehand it was!') time.sleep(0.5) path = \"collected/forehand/\" filename =",
"# if(cv2.contourArea(contour)>400): # continue # cv2.rectangle(frame1,(x,y),(x+w,y+h),(0,255,0),2) # # cv2.drawContours(frame1,contours, -1,(0,255,0),2)",
"return 0 def my_function(toPrint): print(toPrint) def save_to_file(filename,data): file = open(filename,'w')",
"- backhand it was!') time.sleep(0.5) path = \"collected/backhand/\" filename ="
] |
[
"uuid.uuid4().hex, 'security_group_name': uuid.uuid4().hex, 'created_at': uuid.uuid4().hex, 'error_code': uuid.uuid4().hex, 'product_id': random.choice(['OTC_DCS_SINGLE', 'OTC_DCS_MS',",
"'value': uuid.uuid4().hex, 'value_type': uuid.uuid4().hex, 'value_range': uuid.uuid4().hex, 'default_value': uuid.uuid4().hex, 'description': uuid.uuid4().hex",
"random.choice(['OTC_DCS_SINGLE', 'OTC_DCS_MS', 'OTC_DCS_CL']), 'available_zones': uuid.uuid4().hex, 'max_memory': random.randint(0, 10), 'used_memory': random.randint(0,",
"object_info = { 'name': 'group-' + uuid.uuid4().hex, 'id': 'id-' +",
"random import uuid import mock from openstackclient.tests.unit import utils from",
"description', 'status': random.choice(['CREATING', 'CREATEFILED', 'RUNNING', 'ERROR', 'STARTING', 'RESTARTING', 'CLOSING', 'CLOSED',",
"mock.Mock() self.client = self.app.client_manager.dcs self.client.get_instance = mock.Mock() self.client.find_instance = mock.Mock()",
"generate(cls): object_info = { 'instance_id': 'instance_id-' + uuid.uuid4().hex, 'id': 'id-'",
"uuid.uuid4().hex, 'vpc_name': uuid.uuid4().hex, 'subnet_id': uuid.uuid4().hex, 'subnet_name': uuid.uuid4().hex, 'subnet_cidr': uuid.uuid4().hex, 'security_group_id':",
"'dcs.master_standby', 'dcs.cluster' ]), 'engine_version': uuid.uuid4().hex, 'internal_version': uuid.uuid4().hex, 'charging_mode': random.randint(0, 10),",
"uuid.uuid4().hex, 'id': 'id-' + uuid.uuid4().hex, 'size': random.randint(1, 65535), 'period': uuid.uuid4().hex,",
"'default_value': uuid.uuid4().hex, 'description': uuid.uuid4().hex } obj = config.Config.existing(**object_info) return obj",
"class FakeConfig(test_base.Fake): \"\"\"Fake one or more Config\"\"\" @classmethod def generate(cls):",
"10), 'vpc_id': uuid.uuid4().hex, 'vpc_name': uuid.uuid4().hex, 'subnet_id': uuid.uuid4().hex, 'subnet_name': uuid.uuid4().hex, 'subnet_cidr':",
"'RESTARTING', 'CLOSING', 'CLOSED', 'EXTENDING']), 'engine': uuid.uuid4().hex, 'capacity': random.randint(1, 100), 'ip':",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"backup from otcextensions.sdk.dcs.v1 import config from otcextensions.sdk.dcs.v1 import instance from",
"specific language governing permissions and limitations # under the License.",
"# not use this file except in compliance with the",
"obj = statistic.Statistic.existing(**object_info) return obj class FakeBackup(test_base.Fake): \"\"\"Fake one or",
"= { 'name': 'group-' + uuid.uuid4().hex, 'id': 'id-' + uuid.uuid4().hex,",
"in compliance with the License. You may obtain # a",
"one or more Backup\"\"\" @classmethod def generate(cls): object_info = {",
"You may obtain # a copy of the License at",
"'id': 'id-' + uuid.uuid4().hex, 'size': random.randint(1, 65535), 'period': uuid.uuid4().hex, 'description':",
"uuid.uuid4().hex, 'size': random.randint(1, 65535), 'period': uuid.uuid4().hex, 'description': uuid.uuid4().hex, 'progress': uuid.uuid4().hex,",
"self).setUp() self.app.client_manager.dcs = mock.Mock() self.client = self.app.client_manager.dcs self.client.get_instance = mock.Mock()",
"\"\"\"Fake one or more Config\"\"\" @classmethod def generate(cls): object_info =",
"# under the License. # import datetime import random import",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"otcextensions.sdk.dcs.v1 import statistic class TestDCS(utils.TestCommand): def setUp(self): super(TestDCS, self).setUp() self.app.client_manager.dcs",
"import instance from otcextensions.sdk.dcs.v1 import restore from otcextensions.sdk.dcs.v1 import statistic",
"config from otcextensions.sdk.dcs.v1 import instance from otcextensions.sdk.dcs.v1 import restore from",
"+ uuid.uuid4().hex, 'input_kbps': 'input-' + uuid.uuid4().hex, 'output_kbps': 'output-' + uuid.uuid4().hex,",
"under the License is distributed on an \"AS IS\" BASIS,",
"or more Statistic\"\"\" @classmethod def generate(cls): object_info = { 'instance_id':",
"backup.Backup.existing(**object_info) return obj class FakeRestore(test_base.Fake): \"\"\"Fake one or more Restore\"\"\"",
"random.randint(1, 65535), 'used_memory': random.randint(1, 65535), 'cmd_get_count': random.randint(1, 65535), 'cmd_set_count': random.randint(1,",
"'progress': uuid.uuid4().hex, 'created_at': uuid.uuid4().hex, 'updated_at': uuid.uuid4().hex, 'type': uuid.uuid4().hex, 'name': uuid.uuid4().hex,",
"uuid.uuid4().hex, 'max_memory': random.randint(0, 10), 'used_memory': random.randint(0, 10), 'user_id': uuid.uuid4().hex, 'user_name':",
"'id-' + uuid.uuid4().hex, 'size': random.randint(1, 65535), 'period': uuid.uuid4().hex, 'description': uuid.uuid4().hex,",
"= { 'instance_id': 'instance_id-' + uuid.uuid4().hex, 'id': uuid.uuid4().hex, 'name': uuid.uuid4().hex,",
"'cmd_set_count': random.randint(1, 65535), 'used_cpu': 'cpu-' + uuid.uuid4().hex, 'input_kbps': 'input-' +",
"uuid.uuid4().hex, 'capacity': random.randint(1, 100), 'ip': uuid.uuid4().hex, 'port': random.randint(1, 65535), 'resource_spec_code':",
"uuid.uuid4().hex, 'id': 'id-' + uuid.uuid4().hex, 'description': 'SOME description', 'status': random.choice(['CREATING',",
"uuid.uuid4().hex, 'subnet_name': uuid.uuid4().hex, 'subnet_cidr': uuid.uuid4().hex, 'security_group_id': uuid.uuid4().hex, 'security_group_name': uuid.uuid4().hex, 'created_at':",
"this file except in compliance with the License. You may",
"obj class FakeConfig(test_base.Fake): \"\"\"Fake one or more Config\"\"\" @classmethod def",
"'updated_at': uuid.uuid4().hex, 'type': uuid.uuid4().hex, 'name': uuid.uuid4().hex, 'error_code': uuid.uuid4().hex, 'is_restorable': True,",
"random.choice(['CREATING', 'CREATEFILED', 'RUNNING', 'ERROR', 'STARTING', 'RESTARTING', 'CLOSING', 'CLOSED', 'EXTENDING']), 'engine':",
"uuid.uuid4().hex, 'error_code': uuid.uuid4().hex, 'product_id': random.choice(['OTC_DCS_SINGLE', 'OTC_DCS_MS', 'OTC_DCS_CL']), 'available_zones': uuid.uuid4().hex, 'max_memory':",
"'value_type': uuid.uuid4().hex, 'value_range': uuid.uuid4().hex, 'default_value': uuid.uuid4().hex, 'description': uuid.uuid4().hex } obj",
"10), 'used_memory': random.randint(0, 10), 'user_id': uuid.uuid4().hex, 'user_name': uuid.uuid4().hex, 'order_id': uuid.uuid4().hex,",
"software # distributed under the License is distributed on an",
"(the \"License\"); you may # not use this file except",
"utils from otcextensions.tests.unit.osclient import test_base from otcextensions.sdk.dcs.v1 import backup from",
"from otcextensions.sdk.dcs.v1 import instance from otcextensions.sdk.dcs.v1 import restore from otcextensions.sdk.dcs.v1",
"= mock.Mock() self.client.update_instance = mock.Mock() self.client.create_instance = mock.Mock() self.client.extend_instance =",
"'internal_version': uuid.uuid4().hex, 'charging_mode': random.randint(0, 10), 'vpc_id': uuid.uuid4().hex, 'vpc_name': uuid.uuid4().hex, 'subnet_id':",
"uuid.uuid4().hex, 'subnet_id': uuid.uuid4().hex, 'subnet_name': uuid.uuid4().hex, 'subnet_cidr': uuid.uuid4().hex, 'security_group_id': uuid.uuid4().hex, 'security_group_name':",
"uuid.uuid4().hex, 'updated_at': uuid.uuid4().hex, 'type': uuid.uuid4().hex, 'name': uuid.uuid4().hex, 'error_code': uuid.uuid4().hex, 'is_restorable':",
"'output-' + uuid.uuid4().hex, } obj = statistic.Statistic.existing(**object_info) return obj class",
"from otcextensions.sdk.dcs.v1 import statistic class TestDCS(utils.TestCommand): def setUp(self): super(TestDCS, self).setUp()",
"file except in compliance with the License. You may obtain",
"uuid.uuid4().hex, 'max_memory': random.randint(1, 65535), 'used_memory': random.randint(1, 65535), 'cmd_get_count': random.randint(1, 65535),",
"\"\"\"Fake one or more Backup\"\"\" @classmethod def generate(cls): object_info =",
"FakeBackup(test_base.Fake): \"\"\"Fake one or more Backup\"\"\" @classmethod def generate(cls): object_info",
"OR CONDITIONS OF ANY KIND, either express or implied. See",
"the specific language governing permissions and limitations # under the",
"= mock.Mock() self.client.instances = mock.Mock() self.client.delete_instance = mock.Mock() self.client.update_instance =",
"datetime import random import uuid import mock from openstackclient.tests.unit import",
"} obj = backup.Backup.existing(**object_info) return obj class FakeRestore(test_base.Fake): \"\"\"Fake one",
"obj class FakeRestore(test_base.Fake): \"\"\"Fake one or more Restore\"\"\" @classmethod def",
"'engine': uuid.uuid4().hex, 'capacity': random.randint(1, 100), 'ip': uuid.uuid4().hex, 'port': random.randint(1, 65535),",
"under the Apache License, Version 2.0 (the \"License\"); you may",
"return obj class FakeStatistic(test_base.Fake): \"\"\"Fake one or more Statistic\"\"\" @classmethod",
"FakeInstance(test_base.Fake): \"\"\"Fake one or more Instance\"\"\" @classmethod def generate(cls): object_info",
"generate(cls): object_info = { 'instance_id': 'instance_id-' + uuid.uuid4().hex, 'max_memory': random.randint(1,",
"{ 'instance_id': 'instance_id-' + uuid.uuid4().hex, 'max_memory': random.randint(1, 65535), 'used_memory': random.randint(1,",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY",
"otcextensions.sdk.dcs.v1 import instance from otcextensions.sdk.dcs.v1 import restore from otcextensions.sdk.dcs.v1 import",
"self.client.create_instance = mock.Mock() self.client.extend_instance = mock.Mock() class FakeInstance(test_base.Fake): \"\"\"Fake one",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"the License. # import datetime import random import uuid import",
"to in writing, software # distributed under the License is",
"one or more Config\"\"\" @classmethod def generate(cls): object_info = {",
"65535), 'used_memory': random.randint(1, 65535), 'cmd_get_count': random.randint(1, 65535), 'cmd_set_count': random.randint(1, 65535),",
"'output_kbps': 'output-' + uuid.uuid4().hex } obj = restore.Restore.existing(**object_info) return obj",
"random.randint(1, 65535), 'resource_spec_code': random.choice(['dcs.single_node', 'dcs.master_standby', 'dcs.cluster' ]), 'engine_version': uuid.uuid4().hex, 'internal_version':",
"statistic class TestDCS(utils.TestCommand): def setUp(self): super(TestDCS, self).setUp() self.app.client_manager.dcs = mock.Mock()",
"or agreed to in writing, software # distributed under the",
"uuid.uuid4().hex, 'product_id': random.choice(['OTC_DCS_SINGLE', 'OTC_DCS_MS', 'OTC_DCS_CL']), 'available_zones': uuid.uuid4().hex, 'max_memory': random.randint(0, 10),",
"= instance.Instance.existing(**object_info) return obj class FakeStatistic(test_base.Fake): \"\"\"Fake one or more",
"required by applicable law or agreed to in writing, software",
"uuid.uuid4().hex, 'maintain_begin': uuid.uuid4().hex, 'maintain_end': uuid.uuid4().hex, } obj = instance.Instance.existing(**object_info) return",
"class FakeStatistic(test_base.Fake): \"\"\"Fake one or more Statistic\"\"\" @classmethod def generate(cls):",
"more Instance\"\"\" @classmethod def generate(cls): object_info = { 'name': 'group-'",
"setUp(self): super(TestDCS, self).setUp() self.app.client_manager.dcs = mock.Mock() self.client = self.app.client_manager.dcs self.client.get_instance",
"mock.Mock() self.client.extend_instance = mock.Mock() class FakeInstance(test_base.Fake): \"\"\"Fake one or more",
"'name': uuid.uuid4().hex, 'value': uuid.uuid4().hex, 'value_type': uuid.uuid4().hex, 'value_range': uuid.uuid4().hex, 'default_value': uuid.uuid4().hex,",
"= statistic.Statistic.existing(**object_info) return obj class FakeBackup(test_base.Fake): \"\"\"Fake one or more",
"import random import uuid import mock from openstackclient.tests.unit import utils",
"'charging_mode': random.randint(0, 10), 'vpc_id': uuid.uuid4().hex, 'vpc_name': uuid.uuid4().hex, 'subnet_id': uuid.uuid4().hex, 'subnet_name':",
"uuid.uuid4().hex, 'output_kbps': 'output-' + uuid.uuid4().hex } obj = restore.Restore.existing(**object_info) return",
"uuid.uuid4().hex, 'name': uuid.uuid4().hex, 'value': uuid.uuid4().hex, 'value_type': uuid.uuid4().hex, 'value_range': uuid.uuid4().hex, 'default_value':",
"Apache License, Version 2.0 (the \"License\"); you may # not",
"class FakeBackup(test_base.Fake): \"\"\"Fake one or more Backup\"\"\" @classmethod def generate(cls):",
"agreed to in writing, software # distributed under the License",
"or more Backup\"\"\" @classmethod def generate(cls): object_info = { 'instance_id':",
"or more Config\"\"\" @classmethod def generate(cls): object_info = { 'instance_id':",
"'cpu-' + uuid.uuid4().hex, 'input_kbps': 'input-' + uuid.uuid4().hex, 'output_kbps': 'output-' +",
"from otcextensions.sdk.dcs.v1 import config from otcextensions.sdk.dcs.v1 import instance from otcextensions.sdk.dcs.v1",
"distributed under the License is distributed on an \"AS IS\"",
"self.app.client_manager.dcs self.client.get_instance = mock.Mock() self.client.find_instance = mock.Mock() self.client.instances = mock.Mock()",
"License, Version 2.0 (the \"License\"); you may # not use",
"CONDITIONS OF ANY KIND, either express or implied. See the",
"def generate(cls): object_info = { 'instance_id': 'instance_id-' + uuid.uuid4().hex, 'max_memory':",
"uuid.uuid4().hex, 'output_kbps': 'output-' + uuid.uuid4().hex, } obj = statistic.Statistic.existing(**object_info) return",
"'max_memory': random.randint(0, 10), 'used_memory': random.randint(0, 10), 'user_id': uuid.uuid4().hex, 'user_name': uuid.uuid4().hex,",
"= { 'instance_id': 'instance_id-' + uuid.uuid4().hex, 'id': 'id-' + uuid.uuid4().hex,",
"not use this file except in compliance with the License.",
"+ uuid.uuid4().hex } obj = restore.Restore.existing(**object_info) return obj class FakeConfig(test_base.Fake):",
"'used_memory': random.randint(0, 10), 'user_id': uuid.uuid4().hex, 'user_name': uuid.uuid4().hex, 'order_id': uuid.uuid4().hex, 'maintain_begin':",
"writing, software # distributed under the License is distributed on",
"self.client.delete_instance = mock.Mock() self.client.update_instance = mock.Mock() self.client.create_instance = mock.Mock() self.client.extend_instance",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"'id-' + uuid.uuid4().hex, 'description': 'SOME description', 'status': random.choice(['CREATING', 'CREATEFILED', 'RUNNING',",
"# import datetime import random import uuid import mock from",
"more Backup\"\"\" @classmethod def generate(cls): object_info = { 'instance_id': 'instance_id-'",
"the License. You may obtain # a copy of the",
"an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF",
"mock.Mock() self.client.find_instance = mock.Mock() self.client.instances = mock.Mock() self.client.delete_instance = mock.Mock()",
"use this file except in compliance with the License. You",
"'instance_id-' + uuid.uuid4().hex, 'id': 'id-' + uuid.uuid4().hex, 'size': random.randint(1, 65535),",
"'type': uuid.uuid4().hex, 'name': uuid.uuid4().hex, 'error_code': uuid.uuid4().hex, 'is_restorable': True, } obj",
"or more Instance\"\"\" @classmethod def generate(cls): object_info = { 'name':",
"random.randint(0, 10), 'vpc_id': uuid.uuid4().hex, 'vpc_name': uuid.uuid4().hex, 'subnet_id': uuid.uuid4().hex, 'subnet_name': uuid.uuid4().hex,",
"random.randint(1, 100), 'ip': uuid.uuid4().hex, 'port': random.randint(1, 65535), 'resource_spec_code': random.choice(['dcs.single_node', 'dcs.master_standby',",
"= backup.Backup.existing(**object_info) return obj class FakeRestore(test_base.Fake): \"\"\"Fake one or more",
"{ 'instance_id': 'instance_id-' + uuid.uuid4().hex, 'id': uuid.uuid4().hex, 'name': uuid.uuid4().hex, 'value':",
"uuid.uuid4().hex, 'description': uuid.uuid4().hex, 'progress': uuid.uuid4().hex, 'created_at': uuid.uuid4().hex, 'updated_at': uuid.uuid4().hex, 'type':",
"generate(cls): object_info = { 'instance_id': 'instance_id-' + uuid.uuid4().hex, 'id': uuid.uuid4().hex,",
"uuid.uuid4().hex, 'value_range': uuid.uuid4().hex, 'default_value': uuid.uuid4().hex, 'description': uuid.uuid4().hex } obj =",
"from openstackclient.tests.unit import utils from otcextensions.tests.unit.osclient import test_base from otcextensions.sdk.dcs.v1",
"uuid.uuid4().hex, } obj = instance.Instance.existing(**object_info) return obj class FakeStatistic(test_base.Fake): \"\"\"Fake",
"self.client.instances = mock.Mock() self.client.delete_instance = mock.Mock() self.client.update_instance = mock.Mock() self.client.create_instance",
"License is distributed on an \"AS IS\" BASIS, WITHOUT #",
"KIND, either express or implied. See the # License for",
"Instance\"\"\" @classmethod def generate(cls): object_info = { 'name': 'group-' +",
"uuid.uuid4().hex, 'charging_mode': random.randint(0, 10), 'vpc_id': uuid.uuid4().hex, 'vpc_name': uuid.uuid4().hex, 'subnet_id': uuid.uuid4().hex,",
"'input_kbps': 'input-' + uuid.uuid4().hex, 'output_kbps': 'output-' + uuid.uuid4().hex } obj",
"'CLOSED', 'EXTENDING']), 'engine': uuid.uuid4().hex, 'capacity': random.randint(1, 100), 'ip': uuid.uuid4().hex, 'port':",
"object_info = { 'instance_id': 'instance_id-' + uuid.uuid4().hex, 'max_memory': random.randint(1, 65535),",
"\"License\"); you may # not use this file except in",
"IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,",
"} obj = instance.Instance.existing(**object_info) return obj class FakeStatistic(test_base.Fake): \"\"\"Fake one",
"Config\"\"\" @classmethod def generate(cls): object_info = { 'instance_id': 'instance_id-' +",
"express or implied. See the # License for the specific",
"True, } obj = backup.Backup.existing(**object_info) return obj class FakeRestore(test_base.Fake): \"\"\"Fake",
"def setUp(self): super(TestDCS, self).setUp() self.app.client_manager.dcs = mock.Mock() self.client = self.app.client_manager.dcs",
"= mock.Mock() self.client = self.app.client_manager.dcs self.client.get_instance = mock.Mock() self.client.find_instance =",
"the Apache License, Version 2.0 (the \"License\"); you may #",
"uuid.uuid4().hex, 'is_restorable': True, } obj = backup.Backup.existing(**object_info) return obj class",
"'value_range': uuid.uuid4().hex, 'default_value': uuid.uuid4().hex, 'description': uuid.uuid4().hex } obj = config.Config.existing(**object_info)",
"'output-' + uuid.uuid4().hex } obj = restore.Restore.existing(**object_info) return obj class",
"} obj = restore.Restore.existing(**object_info) return obj class FakeConfig(test_base.Fake): \"\"\"Fake one",
"65535), 'used_cpu': 'cpu-' + uuid.uuid4().hex, 'input_kbps': 'input-' + uuid.uuid4().hex, 'output_kbps':",
"See the # License for the specific language governing permissions",
"from otcextensions.sdk.dcs.v1 import backup from otcextensions.sdk.dcs.v1 import config from otcextensions.sdk.dcs.v1",
"uuid.uuid4().hex, 'created_at': uuid.uuid4().hex, 'updated_at': uuid.uuid4().hex, 'type': uuid.uuid4().hex, 'name': uuid.uuid4().hex, 'error_code':",
"'maintain_end': uuid.uuid4().hex, } obj = instance.Instance.existing(**object_info) return obj class FakeStatistic(test_base.Fake):",
"# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"one or more Statistic\"\"\" @classmethod def generate(cls): object_info = {",
"statistic.Statistic.existing(**object_info) return obj class FakeBackup(test_base.Fake): \"\"\"Fake one or more Backup\"\"\"",
"self.client = self.app.client_manager.dcs self.client.get_instance = mock.Mock() self.client.find_instance = mock.Mock() self.client.instances",
"uuid.uuid4().hex, 'internal_version': uuid.uuid4().hex, 'charging_mode': random.randint(0, 10), 'vpc_id': uuid.uuid4().hex, 'vpc_name': uuid.uuid4().hex,",
"uuid.uuid4().hex, 'id': uuid.uuid4().hex, 'name': uuid.uuid4().hex, 'value': uuid.uuid4().hex, 'value_type': uuid.uuid4().hex, 'value_range':",
"law or agreed to in writing, software # distributed under",
"'ERROR', 'STARTING', 'RESTARTING', 'CLOSING', 'CLOSED', 'EXTENDING']), 'engine': uuid.uuid4().hex, 'capacity': random.randint(1,",
"implied. See the # License for the specific language governing",
"uuid.uuid4().hex, 'user_name': uuid.uuid4().hex, 'order_id': uuid.uuid4().hex, 'maintain_begin': uuid.uuid4().hex, 'maintain_end': uuid.uuid4().hex, }",
"'input-' + uuid.uuid4().hex, 'output_kbps': 'output-' + uuid.uuid4().hex, } obj =",
"mock from openstackclient.tests.unit import utils from otcextensions.tests.unit.osclient import test_base from",
"'user_id': uuid.uuid4().hex, 'user_name': uuid.uuid4().hex, 'order_id': uuid.uuid4().hex, 'maintain_begin': uuid.uuid4().hex, 'maintain_end': uuid.uuid4().hex,",
"{ 'instance_id': 'instance_id-' + uuid.uuid4().hex, 'id': 'id-' + uuid.uuid4().hex, 'size':",
"mock.Mock() self.client.update_instance = mock.Mock() self.client.create_instance = mock.Mock() self.client.extend_instance = mock.Mock()",
"return obj class FakeBackup(test_base.Fake): \"\"\"Fake one or more Backup\"\"\" @classmethod",
"and limitations # under the License. # import datetime import",
"import statistic class TestDCS(utils.TestCommand): def setUp(self): super(TestDCS, self).setUp() self.app.client_manager.dcs =",
"class FakeRestore(test_base.Fake): \"\"\"Fake one or more Restore\"\"\" @classmethod def generate(cls):",
"uuid.uuid4().hex, 'order_id': uuid.uuid4().hex, 'maintain_begin': uuid.uuid4().hex, 'maintain_end': uuid.uuid4().hex, } obj =",
"Restore\"\"\" @classmethod def generate(cls): object_info = { 'instance_id': 'instance_id-' +",
"object_info = { 'instance_id': 'instance_id-' + uuid.uuid4().hex, 'id': 'id-' +",
"self.client.extend_instance = mock.Mock() class FakeInstance(test_base.Fake): \"\"\"Fake one or more Instance\"\"\"",
"restore.Restore.existing(**object_info) return obj class FakeConfig(test_base.Fake): \"\"\"Fake one or more Config\"\"\"",
"self.client.get_instance = mock.Mock() self.client.find_instance = mock.Mock() self.client.instances = mock.Mock() self.client.delete_instance",
"'capacity': random.randint(1, 100), 'ip': uuid.uuid4().hex, 'port': random.randint(1, 65535), 'resource_spec_code': random.choice(['dcs.single_node',",
"+ uuid.uuid4().hex, 'id': 'id-' + uuid.uuid4().hex, 'size': random.randint(1, 65535), 'period':",
"self.app.client_manager.dcs = mock.Mock() self.client = self.app.client_manager.dcs self.client.get_instance = mock.Mock() self.client.find_instance",
"'instance_id': 'instance_id-' + uuid.uuid4().hex, 'id': 'id-' + uuid.uuid4().hex, 'size': random.randint(1,",
"+ uuid.uuid4().hex, 'id': uuid.uuid4().hex, 'name': uuid.uuid4().hex, 'value': uuid.uuid4().hex, 'value_type': uuid.uuid4().hex,",
"+ uuid.uuid4().hex, 'output_kbps': 'output-' + uuid.uuid4().hex } obj = restore.Restore.existing(**object_info)",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR",
"'name': 'group-' + uuid.uuid4().hex, 'id': 'id-' + uuid.uuid4().hex, 'description': 'SOME",
"'maintain_begin': uuid.uuid4().hex, 'maintain_end': uuid.uuid4().hex, } obj = instance.Instance.existing(**object_info) return obj",
"= mock.Mock() self.client.create_instance = mock.Mock() self.client.extend_instance = mock.Mock() class FakeInstance(test_base.Fake):",
"'error_code': uuid.uuid4().hex, 'is_restorable': True, } obj = backup.Backup.existing(**object_info) return obj",
"random.randint(0, 10), 'used_memory': random.randint(0, 10), 'user_id': uuid.uuid4().hex, 'user_name': uuid.uuid4().hex, 'order_id':",
"random.choice(['dcs.single_node', 'dcs.master_standby', 'dcs.cluster' ]), 'engine_version': uuid.uuid4().hex, 'internal_version': uuid.uuid4().hex, 'charging_mode': random.randint(0,",
"uuid.uuid4().hex, 'port': random.randint(1, 65535), 'resource_spec_code': random.choice(['dcs.single_node', 'dcs.master_standby', 'dcs.cluster' ]), 'engine_version':",
"obj class FakeStatistic(test_base.Fake): \"\"\"Fake one or more Statistic\"\"\" @classmethod def",
"Backup\"\"\" @classmethod def generate(cls): object_info = { 'instance_id': 'instance_id-' +",
"'size': random.randint(1, 65535), 'period': uuid.uuid4().hex, 'description': uuid.uuid4().hex, 'progress': uuid.uuid4().hex, 'created_at':",
"obtain # a copy of the License at # #",
"TestDCS(utils.TestCommand): def setUp(self): super(TestDCS, self).setUp() self.app.client_manager.dcs = mock.Mock() self.client =",
"super(TestDCS, self).setUp() self.app.client_manager.dcs = mock.Mock() self.client = self.app.client_manager.dcs self.client.get_instance =",
"Version 2.0 (the \"License\"); you may # not use this",
"'engine_version': uuid.uuid4().hex, 'internal_version': uuid.uuid4().hex, 'charging_mode': random.randint(0, 10), 'vpc_id': uuid.uuid4().hex, 'vpc_name':",
"'output_kbps': 'output-' + uuid.uuid4().hex, } obj = statistic.Statistic.existing(**object_info) return obj",
"'dcs.cluster' ]), 'engine_version': uuid.uuid4().hex, 'internal_version': uuid.uuid4().hex, 'charging_mode': random.randint(0, 10), 'vpc_id':",
"import restore from otcextensions.sdk.dcs.v1 import statistic class TestDCS(utils.TestCommand): def setUp(self):",
"return obj class FakeRestore(test_base.Fake): \"\"\"Fake one or more Restore\"\"\" @classmethod",
"uuid.uuid4().hex, 'input_kbps': 'input-' + uuid.uuid4().hex, 'output_kbps': 'output-' + uuid.uuid4().hex }",
"License for the specific language governing permissions and limitations #",
"uuid.uuid4().hex, 'input_kbps': 'input-' + uuid.uuid4().hex, 'output_kbps': 'output-' + uuid.uuid4().hex, }",
"'description': 'SOME description', 'status': random.choice(['CREATING', 'CREATEFILED', 'RUNNING', 'ERROR', 'STARTING', 'RESTARTING',",
"'subnet_name': uuid.uuid4().hex, 'subnet_cidr': uuid.uuid4().hex, 'security_group_id': uuid.uuid4().hex, 'security_group_name': uuid.uuid4().hex, 'created_at': uuid.uuid4().hex,",
"on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS",
"import test_base from otcextensions.sdk.dcs.v1 import backup from otcextensions.sdk.dcs.v1 import config",
"'user_name': uuid.uuid4().hex, 'order_id': uuid.uuid4().hex, 'maintain_begin': uuid.uuid4().hex, 'maintain_end': uuid.uuid4().hex, } obj",
"'CREATEFILED', 'RUNNING', 'ERROR', 'STARTING', 'RESTARTING', 'CLOSING', 'CLOSED', 'EXTENDING']), 'engine': uuid.uuid4().hex,",
"'instance_id-' + uuid.uuid4().hex, 'max_memory': random.randint(1, 65535), 'used_memory': random.randint(1, 65535), 'cmd_get_count':",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"10), 'user_id': uuid.uuid4().hex, 'user_name': uuid.uuid4().hex, 'order_id': uuid.uuid4().hex, 'maintain_begin': uuid.uuid4().hex, 'maintain_end':",
"FakeRestore(test_base.Fake): \"\"\"Fake one or more Restore\"\"\" @classmethod def generate(cls): object_info",
"uuid.uuid4().hex, 'progress': uuid.uuid4().hex, 'created_at': uuid.uuid4().hex, 'updated_at': uuid.uuid4().hex, 'type': uuid.uuid4().hex, 'name':",
"'instance_id-' + uuid.uuid4().hex, 'id': uuid.uuid4().hex, 'name': uuid.uuid4().hex, 'value': uuid.uuid4().hex, 'value_type':",
"Licensed under the Apache License, Version 2.0 (the \"License\"); you",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"return obj class FakeConfig(test_base.Fake): \"\"\"Fake one or more Config\"\"\" @classmethod",
"random.randint(1, 65535), 'period': uuid.uuid4().hex, 'description': uuid.uuid4().hex, 'progress': uuid.uuid4().hex, 'created_at': uuid.uuid4().hex,",
"uuid.uuid4().hex, 'type': uuid.uuid4().hex, 'name': uuid.uuid4().hex, 'error_code': uuid.uuid4().hex, 'is_restorable': True, }",
"more Statistic\"\"\" @classmethod def generate(cls): object_info = { 'instance_id': 'instance_id-'",
"compliance with the License. You may obtain # a copy",
"uuid.uuid4().hex, 'value': uuid.uuid4().hex, 'value_type': uuid.uuid4().hex, 'value_range': uuid.uuid4().hex, 'default_value': uuid.uuid4().hex, 'description':",
"more Config\"\"\" @classmethod def generate(cls): object_info = { 'instance_id': 'instance_id-'",
"@classmethod def generate(cls): object_info = { 'name': 'group-' + uuid.uuid4().hex,",
"+ uuid.uuid4().hex, 'output_kbps': 'output-' + uuid.uuid4().hex, } obj = statistic.Statistic.existing(**object_info)",
"the # License for the specific language governing permissions and",
"= { 'instance_id': 'instance_id-' + uuid.uuid4().hex, 'max_memory': random.randint(1, 65535), 'used_memory':",
"instance.Instance.existing(**object_info) return obj class FakeStatistic(test_base.Fake): \"\"\"Fake one or more Statistic\"\"\"",
"+ uuid.uuid4().hex, 'max_memory': random.randint(1, 65535), 'used_memory': random.randint(1, 65535), 'cmd_get_count': random.randint(1,",
"'security_group_id': uuid.uuid4().hex, 'security_group_name': uuid.uuid4().hex, 'created_at': uuid.uuid4().hex, 'error_code': uuid.uuid4().hex, 'product_id': random.choice(['OTC_DCS_SINGLE',",
"'resource_spec_code': random.choice(['dcs.single_node', 'dcs.master_standby', 'dcs.cluster' ]), 'engine_version': uuid.uuid4().hex, 'internal_version': uuid.uuid4().hex, 'charging_mode':",
"# # Unless required by applicable law or agreed to",
"= self.app.client_manager.dcs self.client.get_instance = mock.Mock() self.client.find_instance = mock.Mock() self.client.instances =",
"License. # import datetime import random import uuid import mock",
"'instance_id': 'instance_id-' + uuid.uuid4().hex, 'id': uuid.uuid4().hex, 'name': uuid.uuid4().hex, 'value': uuid.uuid4().hex,",
"'is_restorable': True, } obj = backup.Backup.existing(**object_info) return obj class FakeRestore(test_base.Fake):",
"2.0 (the \"License\"); you may # not use this file",
"random.randint(1, 65535), 'cmd_set_count': random.randint(1, 65535), 'used_cpu': 'cpu-' + uuid.uuid4().hex, 'input_kbps':",
"'instance_id': 'instance_id-' + uuid.uuid4().hex, 'max_memory': random.randint(1, 65535), 'used_memory': random.randint(1, 65535),",
"'vpc_name': uuid.uuid4().hex, 'subnet_id': uuid.uuid4().hex, 'subnet_name': uuid.uuid4().hex, 'subnet_cidr': uuid.uuid4().hex, 'security_group_id': uuid.uuid4().hex,",
"mock.Mock() self.client.instances = mock.Mock() self.client.delete_instance = mock.Mock() self.client.update_instance = mock.Mock()",
"openstackclient.tests.unit import utils from otcextensions.tests.unit.osclient import test_base from otcextensions.sdk.dcs.v1 import",
"\"\"\"Fake one or more Statistic\"\"\" @classmethod def generate(cls): object_info =",
"limitations # under the License. # import datetime import random",
"by applicable law or agreed to in writing, software #",
"'cmd_get_count': random.randint(1, 65535), 'cmd_set_count': random.randint(1, 65535), 'used_cpu': 'cpu-' + uuid.uuid4().hex,",
"one or more Restore\"\"\" @classmethod def generate(cls): object_info = {",
"'security_group_name': uuid.uuid4().hex, 'created_at': uuid.uuid4().hex, 'error_code': uuid.uuid4().hex, 'product_id': random.choice(['OTC_DCS_SINGLE', 'OTC_DCS_MS', 'OTC_DCS_CL']),",
"+ uuid.uuid4().hex, 'input_kbps': 'input-' + uuid.uuid4().hex, 'output_kbps': 'output-' + uuid.uuid4().hex",
"otcextensions.sdk.dcs.v1 import config from otcextensions.sdk.dcs.v1 import instance from otcextensions.sdk.dcs.v1 import",
"otcextensions.tests.unit.osclient import test_base from otcextensions.sdk.dcs.v1 import backup from otcextensions.sdk.dcs.v1 import",
"otcextensions.sdk.dcs.v1 import restore from otcextensions.sdk.dcs.v1 import statistic class TestDCS(utils.TestCommand): def",
"BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either",
"+ uuid.uuid4().hex, 'size': random.randint(1, 65535), 'period': uuid.uuid4().hex, 'description': uuid.uuid4().hex, 'progress':",
"'ip': uuid.uuid4().hex, 'port': random.randint(1, 65535), 'resource_spec_code': random.choice(['dcs.single_node', 'dcs.master_standby', 'dcs.cluster' ]),",
"'subnet_cidr': uuid.uuid4().hex, 'security_group_id': uuid.uuid4().hex, 'security_group_name': uuid.uuid4().hex, 'created_at': uuid.uuid4().hex, 'error_code': uuid.uuid4().hex,",
"'name': uuid.uuid4().hex, 'error_code': uuid.uuid4().hex, 'is_restorable': True, } obj = backup.Backup.existing(**object_info)",
"]), 'engine_version': uuid.uuid4().hex, 'internal_version': uuid.uuid4().hex, 'charging_mode': random.randint(0, 10), 'vpc_id': uuid.uuid4().hex,",
"obj = backup.Backup.existing(**object_info) return obj class FakeRestore(test_base.Fake): \"\"\"Fake one or",
"100), 'ip': uuid.uuid4().hex, 'port': random.randint(1, 65535), 'resource_spec_code': random.choice(['dcs.single_node', 'dcs.master_standby', 'dcs.cluster'",
"may obtain # a copy of the License at #",
"65535), 'cmd_get_count': random.randint(1, 65535), 'cmd_set_count': random.randint(1, 65535), 'used_cpu': 'cpu-' +",
"'available_zones': uuid.uuid4().hex, 'max_memory': random.randint(0, 10), 'used_memory': random.randint(0, 10), 'user_id': uuid.uuid4().hex,",
"Unless required by applicable law or agreed to in writing,",
"= restore.Restore.existing(**object_info) return obj class FakeConfig(test_base.Fake): \"\"\"Fake one or more",
"import backup from otcextensions.sdk.dcs.v1 import config from otcextensions.sdk.dcs.v1 import instance",
"'input_kbps': 'input-' + uuid.uuid4().hex, 'output_kbps': 'output-' + uuid.uuid4().hex, } obj",
"applicable law or agreed to in writing, software # distributed",
"= mock.Mock() self.client.find_instance = mock.Mock() self.client.instances = mock.Mock() self.client.delete_instance =",
"OF ANY KIND, either express or implied. See the #",
"uuid.uuid4().hex, 'description': 'SOME description', 'status': random.choice(['CREATING', 'CREATEFILED', 'RUNNING', 'ERROR', 'STARTING',",
"'OTC_DCS_CL']), 'available_zones': uuid.uuid4().hex, 'max_memory': random.randint(0, 10), 'used_memory': random.randint(0, 10), 'user_id':",
"uuid.uuid4().hex, 'name': uuid.uuid4().hex, 'error_code': uuid.uuid4().hex, 'is_restorable': True, } obj =",
"WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"in writing, software # distributed under the License is distributed",
"'id': uuid.uuid4().hex, 'name': uuid.uuid4().hex, 'value': uuid.uuid4().hex, 'value_type': uuid.uuid4().hex, 'value_range': uuid.uuid4().hex,",
"} obj = statistic.Statistic.existing(**object_info) return obj class FakeBackup(test_base.Fake): \"\"\"Fake one",
"@classmethod def generate(cls): object_info = { 'instance_id': 'instance_id-' + uuid.uuid4().hex,",
"'input-' + uuid.uuid4().hex, 'output_kbps': 'output-' + uuid.uuid4().hex } obj =",
"random.randint(1, 65535), 'cmd_get_count': random.randint(1, 65535), 'cmd_set_count': random.randint(1, 65535), 'used_cpu': 'cpu-'",
"uuid.uuid4().hex } obj = restore.Restore.existing(**object_info) return obj class FakeConfig(test_base.Fake): \"\"\"Fake",
"otcextensions.sdk.dcs.v1 import backup from otcextensions.sdk.dcs.v1 import config from otcextensions.sdk.dcs.v1 import",
"uuid.uuid4().hex, 'subnet_cidr': uuid.uuid4().hex, 'security_group_id': uuid.uuid4().hex, 'security_group_name': uuid.uuid4().hex, 'created_at': uuid.uuid4().hex, 'error_code':",
"'error_code': uuid.uuid4().hex, 'product_id': random.choice(['OTC_DCS_SINGLE', 'OTC_DCS_MS', 'OTC_DCS_CL']), 'available_zones': uuid.uuid4().hex, 'max_memory': random.randint(0,",
"uuid.uuid4().hex, } obj = statistic.Statistic.existing(**object_info) return obj class FakeBackup(test_base.Fake): \"\"\"Fake",
"self.client.update_instance = mock.Mock() self.client.create_instance = mock.Mock() self.client.extend_instance = mock.Mock() class",
"65535), 'resource_spec_code': random.choice(['dcs.single_node', 'dcs.master_standby', 'dcs.cluster' ]), 'engine_version': uuid.uuid4().hex, 'internal_version': uuid.uuid4().hex,",
"'CLOSING', 'CLOSED', 'EXTENDING']), 'engine': uuid.uuid4().hex, 'capacity': random.randint(1, 100), 'ip': uuid.uuid4().hex,",
"one or more Instance\"\"\" @classmethod def generate(cls): object_info = {",
"+ uuid.uuid4().hex, 'id': 'id-' + uuid.uuid4().hex, 'description': 'SOME description', 'status':",
"class FakeInstance(test_base.Fake): \"\"\"Fake one or more Instance\"\"\" @classmethod def generate(cls):",
"FakeConfig(test_base.Fake): \"\"\"Fake one or more Config\"\"\" @classmethod def generate(cls): object_info",
"= mock.Mock() class FakeInstance(test_base.Fake): \"\"\"Fake one or more Instance\"\"\" @classmethod",
"'order_id': uuid.uuid4().hex, 'maintain_begin': uuid.uuid4().hex, 'maintain_end': uuid.uuid4().hex, } obj = instance.Instance.existing(**object_info)",
"test_base from otcextensions.sdk.dcs.v1 import backup from otcextensions.sdk.dcs.v1 import config from",
"def generate(cls): object_info = { 'instance_id': 'instance_id-' + uuid.uuid4().hex, 'id':",
"instance from otcextensions.sdk.dcs.v1 import restore from otcextensions.sdk.dcs.v1 import statistic class",
"either express or implied. See the # License for the",
"'created_at': uuid.uuid4().hex, 'error_code': uuid.uuid4().hex, 'product_id': random.choice(['OTC_DCS_SINGLE', 'OTC_DCS_MS', 'OTC_DCS_CL']), 'available_zones': uuid.uuid4().hex,",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"'product_id': random.choice(['OTC_DCS_SINGLE', 'OTC_DCS_MS', 'OTC_DCS_CL']), 'available_zones': uuid.uuid4().hex, 'max_memory': random.randint(0, 10), 'used_memory':",
"random.randint(1, 65535), 'used_cpu': 'cpu-' + uuid.uuid4().hex, 'input_kbps': 'input-' + uuid.uuid4().hex,",
"uuid.uuid4().hex, 'error_code': uuid.uuid4().hex, 'is_restorable': True, } obj = backup.Backup.existing(**object_info) return",
"may # not use this file except in compliance with",
"'group-' + uuid.uuid4().hex, 'id': 'id-' + uuid.uuid4().hex, 'description': 'SOME description',",
"uuid import mock from openstackclient.tests.unit import utils from otcextensions.tests.unit.osclient import",
"# License for the specific language governing permissions and limitations",
"with the License. You may obtain # a copy of",
"+ uuid.uuid4().hex, 'description': 'SOME description', 'status': random.choice(['CREATING', 'CREATEFILED', 'RUNNING', 'ERROR',",
"you may # not use this file except in compliance",
"governing permissions and limitations # under the License. # import",
"self.client.find_instance = mock.Mock() self.client.instances = mock.Mock() self.client.delete_instance = mock.Mock() self.client.update_instance",
"obj = instance.Instance.existing(**object_info) return obj class FakeStatistic(test_base.Fake): \"\"\"Fake one or",
"'period': uuid.uuid4().hex, 'description': uuid.uuid4().hex, 'progress': uuid.uuid4().hex, 'created_at': uuid.uuid4().hex, 'updated_at': uuid.uuid4().hex,",
"'RUNNING', 'ERROR', 'STARTING', 'RESTARTING', 'CLOSING', 'CLOSED', 'EXTENDING']), 'engine': uuid.uuid4().hex, 'capacity':",
"import utils from otcextensions.tests.unit.osclient import test_base from otcextensions.sdk.dcs.v1 import backup",
"under the License. # import datetime import random import uuid",
"'max_memory': random.randint(1, 65535), 'used_memory': random.randint(1, 65535), 'cmd_get_count': random.randint(1, 65535), 'cmd_set_count':",
"= mock.Mock() self.client.extend_instance = mock.Mock() class FakeInstance(test_base.Fake): \"\"\"Fake one or",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"{ 'name': 'group-' + uuid.uuid4().hex, 'id': 'id-' + uuid.uuid4().hex, 'description':",
"language governing permissions and limitations # under the License. #",
"obj class FakeBackup(test_base.Fake): \"\"\"Fake one or more Backup\"\"\" @classmethod def",
"# WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"'EXTENDING']), 'engine': uuid.uuid4().hex, 'capacity': random.randint(1, 100), 'ip': uuid.uuid4().hex, 'port': random.randint(1,",
"'description': uuid.uuid4().hex, 'progress': uuid.uuid4().hex, 'created_at': uuid.uuid4().hex, 'updated_at': uuid.uuid4().hex, 'type': uuid.uuid4().hex,",
"+ uuid.uuid4().hex, } obj = statistic.Statistic.existing(**object_info) return obj class FakeBackup(test_base.Fake):",
"from otcextensions.tests.unit.osclient import test_base from otcextensions.sdk.dcs.v1 import backup from otcextensions.sdk.dcs.v1",
"the License is distributed on an \"AS IS\" BASIS, WITHOUT",
"generate(cls): object_info = { 'name': 'group-' + uuid.uuid4().hex, 'id': 'id-'",
"Statistic\"\"\" @classmethod def generate(cls): object_info = { 'instance_id': 'instance_id-' +",
"'OTC_DCS_MS', 'OTC_DCS_CL']), 'available_zones': uuid.uuid4().hex, 'max_memory': random.randint(0, 10), 'used_memory': random.randint(0, 10),",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"mock.Mock() class FakeInstance(test_base.Fake): \"\"\"Fake one or more Instance\"\"\" @classmethod def",
"mock.Mock() self.client.delete_instance = mock.Mock() self.client.update_instance = mock.Mock() self.client.create_instance = mock.Mock()",
"'STARTING', 'RESTARTING', 'CLOSING', 'CLOSED', 'EXTENDING']), 'engine': uuid.uuid4().hex, 'capacity': random.randint(1, 100),",
"FakeStatistic(test_base.Fake): \"\"\"Fake one or more Statistic\"\"\" @classmethod def generate(cls): object_info",
"'id': 'id-' + uuid.uuid4().hex, 'description': 'SOME description', 'status': random.choice(['CREATING', 'CREATEFILED',",
"for the specific language governing permissions and limitations # under",
"'SOME description', 'status': random.choice(['CREATING', 'CREATEFILED', 'RUNNING', 'ERROR', 'STARTING', 'RESTARTING', 'CLOSING',",
"import datetime import random import uuid import mock from openstackclient.tests.unit",
"uuid.uuid4().hex, 'value_type': uuid.uuid4().hex, 'value_range': uuid.uuid4().hex, 'default_value': uuid.uuid4().hex, 'description': uuid.uuid4().hex }",
"'created_at': uuid.uuid4().hex, 'updated_at': uuid.uuid4().hex, 'type': uuid.uuid4().hex, 'name': uuid.uuid4().hex, 'error_code': uuid.uuid4().hex,",
"\"\"\"Fake one or more Restore\"\"\" @classmethod def generate(cls): object_info =",
"65535), 'cmd_set_count': random.randint(1, 65535), 'used_cpu': 'cpu-' + uuid.uuid4().hex, 'input_kbps': 'input-'",
"from otcextensions.sdk.dcs.v1 import restore from otcextensions.sdk.dcs.v1 import statistic class TestDCS(utils.TestCommand):",
"restore from otcextensions.sdk.dcs.v1 import statistic class TestDCS(utils.TestCommand): def setUp(self): super(TestDCS,",
"except in compliance with the License. You may obtain #",
"object_info = { 'instance_id': 'instance_id-' + uuid.uuid4().hex, 'id': uuid.uuid4().hex, 'name':",
"'vpc_id': uuid.uuid4().hex, 'vpc_name': uuid.uuid4().hex, 'subnet_id': uuid.uuid4().hex, 'subnet_name': uuid.uuid4().hex, 'subnet_cidr': uuid.uuid4().hex,",
"or more Restore\"\"\" @classmethod def generate(cls): object_info = { 'instance_id':",
"random.randint(0, 10), 'user_id': uuid.uuid4().hex, 'user_name': uuid.uuid4().hex, 'order_id': uuid.uuid4().hex, 'maintain_begin': uuid.uuid4().hex,",
"uuid.uuid4().hex, 'created_at': uuid.uuid4().hex, 'error_code': uuid.uuid4().hex, 'product_id': random.choice(['OTC_DCS_SINGLE', 'OTC_DCS_MS', 'OTC_DCS_CL']), 'available_zones':",
"import mock from openstackclient.tests.unit import utils from otcextensions.tests.unit.osclient import test_base",
"License. You may obtain # a copy of the License",
"65535), 'period': uuid.uuid4().hex, 'description': uuid.uuid4().hex, 'progress': uuid.uuid4().hex, 'created_at': uuid.uuid4().hex, 'updated_at':",
"uuid.uuid4().hex, 'default_value': uuid.uuid4().hex, 'description': uuid.uuid4().hex } obj = config.Config.existing(**object_info) return",
"import uuid import mock from openstackclient.tests.unit import utils from otcextensions.tests.unit.osclient",
"class TestDCS(utils.TestCommand): def setUp(self): super(TestDCS, self).setUp() self.app.client_manager.dcs = mock.Mock() self.client",
"uuid.uuid4().hex, 'security_group_id': uuid.uuid4().hex, 'security_group_name': uuid.uuid4().hex, 'created_at': uuid.uuid4().hex, 'error_code': uuid.uuid4().hex, 'product_id':",
"ANY KIND, either express or implied. See the # License",
"# distributed under the License is distributed on an \"AS",
"# Unless required by applicable law or agreed to in",
"'status': random.choice(['CREATING', 'CREATEFILED', 'RUNNING', 'ERROR', 'STARTING', 'RESTARTING', 'CLOSING', 'CLOSED', 'EXTENDING']),",
"\"\"\"Fake one or more Instance\"\"\" @classmethod def generate(cls): object_info =",
"def generate(cls): object_info = { 'name': 'group-' + uuid.uuid4().hex, 'id':",
"is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES",
"permissions and limitations # under the License. # import datetime",
"mock.Mock() self.client.create_instance = mock.Mock() self.client.extend_instance = mock.Mock() class FakeInstance(test_base.Fake): \"\"\"Fake",
"'port': random.randint(1, 65535), 'resource_spec_code': random.choice(['dcs.single_node', 'dcs.master_standby', 'dcs.cluster' ]), 'engine_version': uuid.uuid4().hex,",
"= mock.Mock() self.client.delete_instance = mock.Mock() self.client.update_instance = mock.Mock() self.client.create_instance =",
"more Restore\"\"\" @classmethod def generate(cls): object_info = { 'instance_id': 'instance_id-'",
"'used_cpu': 'cpu-' + uuid.uuid4().hex, 'input_kbps': 'input-' + uuid.uuid4().hex, 'output_kbps': 'output-'",
"uuid.uuid4().hex, 'maintain_end': uuid.uuid4().hex, } obj = instance.Instance.existing(**object_info) return obj class",
"'used_memory': random.randint(1, 65535), 'cmd_get_count': random.randint(1, 65535), 'cmd_set_count': random.randint(1, 65535), 'used_cpu':",
"'subnet_id': uuid.uuid4().hex, 'subnet_name': uuid.uuid4().hex, 'subnet_cidr': uuid.uuid4().hex, 'security_group_id': uuid.uuid4().hex, 'security_group_name': uuid.uuid4().hex,",
"obj = restore.Restore.existing(**object_info) return obj class FakeConfig(test_base.Fake): \"\"\"Fake one or",
"or implied. See the # License for the specific language",
"import config from otcextensions.sdk.dcs.v1 import instance from otcextensions.sdk.dcs.v1 import restore"
] |
[
"_make from . import expr as _expr from . import",
"_tag int8 = \"int8\" int32 = \"int32\" float32 = \"float32\"",
"._ffi.node import register_node, NodeBase from ._ffi.node import convert_to_node as _convert_to_node",
"from ._ffi.node import convert_to_node as _convert_to_node from ._ffi.node_generic import _scalar_type_inference",
"from . import schedule as _schedule from . import container",
"_convert_tvm_func from ._ffi.runtime_ctypes import TVMType from . import _api_internal from",
"from . import expr as _expr from . import tensor",
"import convert_to_node as _convert_to_node from ._ffi.node_generic import _scalar_type_inference from ._ffi.function",
"from ._ffi.function import convert_to_tvm_func as _convert_tvm_func from ._ffi.runtime_ctypes import TVMType",
"import TVMType from . import _api_internal from . import make",
"float32 = \"float32\" handle = \"handle\" def min_value(dtype): return _api_internal._min_value(dtype)",
"container as _container from . import tag as _tag int8",
"int8 = \"int8\" int32 = \"int32\" float32 = \"float32\" handle",
"from . import tag as _tag int8 = \"int8\" int32",
"._ffi.function import convert_to_tvm_func as _convert_tvm_func from ._ffi.runtime_ctypes import TVMType from",
"string_types from ._ffi.object import register_object, Object from ._ffi.node import register_node,",
"_scalar_type_inference from ._ffi.function import Function from ._ffi.function import _init_api, register_func,",
"import convert_to_tvm_func as _convert_tvm_func from ._ffi.runtime_ctypes import TVMType from .",
"_tensor from . import schedule as _schedule from . import",
"_schedule from . import container as _container from . import",
"tag as _tag int8 = \"int8\" int32 = \"int32\" float32",
"_container from . import tag as _tag int8 = \"int8\"",
"import register_node, NodeBase from ._ffi.node import convert_to_node as _convert_to_node from",
"TVMType from . import _api_internal from . import make as",
". import expr as _expr from . import tensor as",
"\"int32\" float32 = \"float32\" handle = \"handle\" def min_value(dtype): return",
"Object from ._ffi.node import register_node, NodeBase from ._ffi.node import convert_to_node",
"import Function from ._ffi.function import _init_api, register_func, get_global_func, extract_ext_funcs from",
"= \"int8\" int32 = \"int32\" float32 = \"float32\" handle =",
"make as _make from . import expr as _expr from",
"from . import tensor as _tensor from . import schedule",
"import schedule as _schedule from . import container as _container",
"as _convert_tvm_func from ._ffi.runtime_ctypes import TVMType from . import _api_internal",
". import tensor as _tensor from . import schedule as",
"from ._ffi.node import register_node, NodeBase from ._ffi.node import convert_to_node as",
"._ffi.object import register_object, Object from ._ffi.node import register_node, NodeBase from",
"schedule as _schedule from . import container as _container from",
"import make as _make from . import expr as _expr",
"import tag as _tag int8 = \"int8\" int32 = \"int32\"",
". import container as _container from . import tag as",
"as _container from . import tag as _tag int8 =",
"from ._ffi.base import string_types from ._ffi.object import register_object, Object from",
"from ._ffi.function import _init_api, register_func, get_global_func, extract_ext_funcs from ._ffi.function import",
"as _make from . import expr as _expr from .",
"as _schedule from . import container as _container from .",
"._ffi.node_generic import _scalar_type_inference from ._ffi.function import Function from ._ffi.function import",
"import container as _container from . import tag as _tag",
"NodeBase from ._ffi.node import convert_to_node as _convert_to_node from ._ffi.node_generic import",
"convert_to_node as _convert_to_node from ._ffi.node_generic import _scalar_type_inference from ._ffi.function import",
". import schedule as _schedule from . import container as",
"as _tag int8 = \"int8\" int32 = \"int32\" float32 =",
"from . import container as _container from . import tag",
"import expr as _expr from . import tensor as _tensor",
"from ._ffi.runtime_ctypes import TVMType from . import _api_internal from .",
". import make as _make from . import expr as",
"register_node, NodeBase from ._ffi.node import convert_to_node as _convert_to_node from ._ffi.node_generic",
"= \"int32\" float32 = \"float32\" handle = \"handle\" def min_value(dtype):",
"from . import _api_internal from . import make as _make",
"._ffi.runtime_ctypes import TVMType from . import _api_internal from . import",
"as _convert_to_node from ._ffi.node_generic import _scalar_type_inference from ._ffi.function import Function",
"Function from ._ffi.function import _init_api, register_func, get_global_func, extract_ext_funcs from ._ffi.function",
"expr as _expr from . import tensor as _tensor from",
"get_global_func, extract_ext_funcs from ._ffi.function import convert_to_tvm_func as _convert_tvm_func from ._ffi.runtime_ctypes",
"_expr from . import tensor as _tensor from . import",
"._ffi.node import convert_to_node as _convert_to_node from ._ffi.node_generic import _scalar_type_inference from",
"as _expr from . import tensor as _tensor from .",
"convert_to_tvm_func as _convert_tvm_func from ._ffi.runtime_ctypes import TVMType from . import",
"import register_object, Object from ._ffi.node import register_node, NodeBase from ._ffi.node",
"\"int8\" int32 = \"int32\" float32 = \"float32\" handle = \"handle\"",
"from ._ffi.object import register_object, Object from ._ffi.node import register_node, NodeBase",
"import _api_internal from . import make as _make from .",
"._ffi.base import string_types from ._ffi.object import register_object, Object from ._ffi.node",
"register_func, get_global_func, extract_ext_funcs from ._ffi.function import convert_to_tvm_func as _convert_tvm_func from",
"._ffi.function import Function from ._ffi.function import _init_api, register_func, get_global_func, extract_ext_funcs",
"import string_types from ._ffi.object import register_object, Object from ._ffi.node import",
"_init_api, register_func, get_global_func, extract_ext_funcs from ._ffi.function import convert_to_tvm_func as _convert_tvm_func",
"from . import make as _make from . import expr",
"import _init_api, register_func, get_global_func, extract_ext_funcs from ._ffi.function import convert_to_tvm_func as",
". import _api_internal from . import make as _make from",
"int32 = \"int32\" float32 = \"float32\" handle = \"handle\" def",
"extract_ext_funcs from ._ffi.function import convert_to_tvm_func as _convert_tvm_func from ._ffi.runtime_ctypes import",
"from ._ffi.node_generic import _scalar_type_inference from ._ffi.function import Function from ._ffi.function",
". import tag as _tag int8 = \"int8\" int32 =",
"._ffi.function import _init_api, register_func, get_global_func, extract_ext_funcs from ._ffi.function import convert_to_tvm_func",
"tensor as _tensor from . import schedule as _schedule from",
"from ._ffi.function import Function from ._ffi.function import _init_api, register_func, get_global_func,",
"import _scalar_type_inference from ._ffi.function import Function from ._ffi.function import _init_api,",
"register_object, Object from ._ffi.node import register_node, NodeBase from ._ffi.node import",
"_convert_to_node from ._ffi.node_generic import _scalar_type_inference from ._ffi.function import Function from",
"_api_internal from . import make as _make from . import",
"as _tensor from . import schedule as _schedule from .",
"import tensor as _tensor from . import schedule as _schedule"
] |
[
"validity ids = [] for attack in attacks: ids.append(id(attack.model)) if",
"data_loader, save_path=None, verbose=True, return_verbose=False): r\"\"\" Overridden. \"\"\" self._clear_multi_atk_records() verbose =",
"if self.verbose: print(self._return_sr_record(multi_atk_records)) if self._accumulate_multi_atk_records: self._update_multi_atk_records(multi_atk_records) return final_images def _clear_multi_atk_records(self):",
"final_images[succeeds] = adv_images[succeeds_of_fails] fails = torch.masked_select(fails, corrects) multi_atk_records.append(len(fails)) if len(fails)",
"= labels.clone().detach().to(self.device) multi_atk_records = [batch_size] for _, attack in enumerate(self.attacks):",
"iters=40, random_start=True) >>> atk2 = torchattacks.PGD(model, eps=8/255, alpha=2/255, iters=40, random_start=True)",
"sr]) def _update_multi_atk_records(self, multi_atk_records): for i, item in enumerate(multi_atk_records): self._multi_atk_records[i]",
"if return_verbose: return rob_acc, sr, l2, elapsed_time def _save_print(self, progress,",
"rob_acc)+\\ \" / \"+self._return_sr_record(self._multi_atk_records)+\\ ' / L2: %1.5f (%2.3f it/s)",
"%%\"%item for item in sr]) def _update_multi_atk_records(self, multi_atk_records): for i,",
"self.verbose = False self._accumulate_multi_atk_records = True for i, attack in",
"rob_acc, l2, elapsed_time, end): r\"\"\" Overridden. \"\"\" print(\"- Save progress:",
"return final_images def _clear_multi_atk_records(self): self._multi_atk_records = [0.0] def _covert_to_success_rates(self, multi_atk_records):",
"Save progress: %2.2f %% / Robust accuracy: %2.2f %%\"%(progress, rob_acc)+\\",
"super().save(data_loader, save_path, verbose, return_verbose) sr = self._covert_to_success_rates(self._multi_atk_records) self._clear_multi_atk_records() self._accumulate_multi_atk_records =",
"iters=40, random_start=True) >>> atk = torchattacks.MultiAttack([atk1, atk2]) >>> adv_images =",
"= attacks self.verbose = verbose self._accumulate_multi_atk_records = False self._multi_atk_records =",
"attacks (list): list of attacks. Examples:: >>> atk1 = torchattacks.PGD(model,",
"[((1-multi_atk_records[i]/multi_atk_records[0])*100) for i in range(1, len(multi_atk_records))] return sr def _return_sr_record(self,",
"self._multi_atk_records.append(0.0) rob_acc, l2, elapsed_time = super().save(data_loader, save_path, verbose, return_verbose) sr",
"MultiAttack is a class to attack a model with various",
"torchattacks.MultiAttack([atk1, atk2]) >>> adv_images = attack(images, labels) \"\"\" def __init__(self,",
"model (nn.Module): model to attack. attacks (list): list of attacks.",
"1: raise ValueError(\"At least one of attacks is referencing a",
"attack a model with various attacks agains same images and",
"wrongs) succeeds_of_fails = torch.masked_select(torch.arange(fails.shape[0]).to(self.device), wrongs) final_images[succeeds] = adv_images[succeeds_of_fails] fails =",
"self.verbose self.verbose = False self._accumulate_multi_atk_records = True for i, attack",
"pre = torch.max(outputs.data, 1) corrects = (pre == labels[fails]) wrongs",
"class to attack a model with various attacks agains same",
"return rob_acc, sr, l2, elapsed_time def _save_print(self, progress, rob_acc, l2,",
"random_start=True) >>> atk = torchattacks.MultiAttack([atk1, atk2]) >>> adv_images = attack(images,",
"def _clear_multi_atk_records(self): self._multi_atk_records = [0.0] def _covert_to_success_rates(self, multi_atk_records): sr =",
"verbose if return_verbose: return rob_acc, sr, l2, elapsed_time def _save_print(self,",
"in enumerate(self.attacks): adv_images = attack(images[fails], labels[fails]) outputs = self.model(adv_images) _,",
"def __init__(self, attacks, verbose=False): # Check validity ids = []",
"one of attacks is referencing a different model.\") super().__init__(\"MultiAttack\", attack.model)",
"torch.max(outputs.data, 1) corrects = (pre == labels[fails]) wrongs = ~corrects",
"atk = torchattacks.MultiAttack([atk1, atk2]) >>> adv_images = attack(images, labels) \"\"\"",
"for i, item in enumerate(multi_atk_records): self._multi_atk_records[i] += item def save(self,",
"attack in enumerate(self.attacks): adv_images = attack(images[fails], labels[fails]) outputs = self.model(adv_images)",
"attack(images, labels) \"\"\" def __init__(self, attacks, verbose=False): # Check validity",
"elapsed_time = super().save(data_loader, save_path, verbose, return_verbose) sr = self._covert_to_success_rates(self._multi_atk_records) self._clear_multi_atk_records()",
"= torch.max(outputs.data, 1) corrects = (pre == labels[fails]) wrongs =",
"= [0.0] self._supported_mode = ['default'] def forward(self, images, labels): r\"\"\"",
"enumerate(self.attacks): adv_images = attack(images[fails], labels[fails]) outputs = self.model(adv_images) _, pre",
"# Check validity ids = [] for attack in attacks:",
"= [((1-multi_atk_records[i]/multi_atk_records[0])*100) for i in range(1, len(multi_atk_records))] return sr def",
"i, attack in enumerate(self.attacks): self._multi_atk_records.append(0.0) rob_acc, l2, elapsed_time = super().save(data_loader,",
"False self._multi_atk_records = [0.0] self._supported_mode = ['default'] def forward(self, images,",
"\"\"\" self._clear_multi_atk_records() verbose = self.verbose self.verbose = False self._accumulate_multi_atk_records =",
"torchattacks.PGD(model, eps=8/255, alpha=2/255, iters=40, random_start=True) >>> atk2 = torchattacks.PGD(model, eps=8/255,",
"torchattacks.PGD(model, eps=8/255, alpha=2/255, iters=40, random_start=True) >>> atk = torchattacks.MultiAttack([atk1, atk2])",
"labels. Arguments: model (nn.Module): model to attack. attacks (list): list",
"item in sr]) def _update_multi_atk_records(self, multi_atk_records): for i, item in",
"eps=8/255, alpha=2/255, iters=40, random_start=True) >>> atk2 = torchattacks.PGD(model, eps=8/255, alpha=2/255,",
"Arguments: model (nn.Module): model to attack. attacks (list): list of",
"%%\"%(progress, rob_acc)+\\ \" / \"+self._return_sr_record(self._multi_atk_records)+\\ ' / L2: %1.5f (%2.3f",
"attacks: ids.append(id(attack.model)) if len(set(ids)) != 1: raise ValueError(\"At least one",
"sr, l2, elapsed_time def _save_print(self, progress, rob_acc, l2, elapsed_time, end):",
"progress: %2.2f %% / Robust accuracy: %2.2f %%\"%(progress, rob_acc)+\\ \"",
"attack.model) self.attacks = attacks self.verbose = verbose self._accumulate_multi_atk_records = False",
"from ..attack import Attack class MultiAttack(Attack): r\"\"\" MultiAttack is a",
"l2, elapsed_time, end): r\"\"\" Overridden. \"\"\" print(\"- Save progress: %2.2f",
"ids.append(id(attack.model)) if len(set(ids)) != 1: raise ValueError(\"At least one of",
"def forward(self, images, labels): r\"\"\" Overridden. \"\"\" batch_size = images.shape[0]",
"labels.clone().detach().to(self.device) multi_atk_records = [batch_size] for _, attack in enumerate(self.attacks): adv_images",
"_update_multi_atk_records(self, multi_atk_records): for i, item in enumerate(multi_atk_records): self._multi_atk_records[i] += item",
"r\"\"\" Overridden. \"\"\" batch_size = images.shape[0] fails = torch.arange(batch_size).to(self.device) final_images",
">>> atk1 = torchattacks.PGD(model, eps=8/255, alpha=2/255, iters=40, random_start=True) >>> atk2",
"least one of attacks is referencing a different model.\") super().__init__(\"MultiAttack\",",
"= verbose self._accumulate_multi_atk_records = False self._multi_atk_records = [0.0] self._supported_mode =",
"if len(set(ids)) != 1: raise ValueError(\"At least one of attacks",
"_save_print(self, progress, rob_acc, l2, elapsed_time, end): r\"\"\" Overridden. \"\"\" print(\"-",
"= torchattacks.PGD(model, eps=8/255, alpha=2/255, iters=40, random_start=True) >>> atk = torchattacks.MultiAttack([atk1,",
"and labels. Arguments: model (nn.Module): model to attack. attacks (list):",
"= False self.verbose = verbose if return_verbose: return rob_acc, sr,",
"images.clone().detach().to(self.device) labels = labels.clone().detach().to(self.device) multi_atk_records = [batch_size] for _, attack",
"self._covert_to_success_rates(multi_atk_records) return \"Attack success rate: \"+\" | \".join([\"%2.2f %%\"%item for",
"labels) \"\"\" def __init__(self, attacks, verbose=False): # Check validity ids",
"alpha=2/255, iters=40, random_start=True) >>> atk2 = torchattacks.PGD(model, eps=8/255, alpha=2/255, iters=40,",
"self.attacks = attacks self.verbose = verbose self._accumulate_multi_atk_records = False self._multi_atk_records",
"self.verbose = verbose self._accumulate_multi_atk_records = False self._multi_atk_records = [0.0] self._supported_mode",
"self._covert_to_success_rates(self._multi_atk_records) self._clear_multi_atk_records() self._accumulate_multi_atk_records = False self.verbose = verbose if return_verbose:",
"== labels[fails]) wrongs = ~corrects succeeds = torch.masked_select(fails, wrongs) succeeds_of_fails",
"eps=8/255, alpha=2/255, iters=40, random_start=True) >>> atk = torchattacks.MultiAttack([atk1, atk2]) >>>",
"rob_acc, sr, l2, elapsed_time def _save_print(self, progress, rob_acc, l2, elapsed_time,",
"r\"\"\" MultiAttack is a class to attack a model with",
"\"Attack success rate: \"+\" | \".join([\"%2.2f %%\"%item for item in",
"forward(self, images, labels): r\"\"\" Overridden. \"\"\" batch_size = images.shape[0] fails",
"in enumerate(multi_atk_records): self._multi_atk_records[i] += item def save(self, data_loader, save_path=None, verbose=True,",
"/ \"+self._return_sr_record(self._multi_atk_records)+\\ ' / L2: %1.5f (%2.3f it/s) \\t'%(l2, elapsed_time),",
"Overridden. \"\"\" batch_size = images.shape[0] fails = torch.arange(batch_size).to(self.device) final_images =",
"[0.0] def _covert_to_success_rates(self, multi_atk_records): sr = [((1-multi_atk_records[i]/multi_atk_records[0])*100) for i in",
"<filename>torchattacks/attacks/multiattack.py import copy import torch from ..attack import Attack class",
"/ Robust accuracy: %2.2f %%\"%(progress, rob_acc)+\\ \" / \"+self._return_sr_record(self._multi_atk_records)+\\ '",
"in attacks: ids.append(id(attack.model)) if len(set(ids)) != 1: raise ValueError(\"At least",
"attacks agains same images and labels. Arguments: model (nn.Module): model",
"r\"\"\" Overridden. \"\"\" self._clear_multi_atk_records() verbose = self.verbose self.verbose = False",
"model.\") super().__init__(\"MultiAttack\", attack.model) self.attacks = attacks self.verbose = verbose self._accumulate_multi_atk_records",
"self.verbose: print(self._return_sr_record(multi_atk_records)) if self._accumulate_multi_atk_records: self._update_multi_atk_records(multi_atk_records) return final_images def _clear_multi_atk_records(self): self._multi_atk_records",
"enumerate(self.attacks): self._multi_atk_records.append(0.0) rob_acc, l2, elapsed_time = super().save(data_loader, save_path, verbose, return_verbose)",
"i, item in enumerate(multi_atk_records): self._multi_atk_records[i] += item def save(self, data_loader,",
"Check validity ids = [] for attack in attacks: ids.append(id(attack.model))",
"= False self._multi_atk_records = [0.0] self._supported_mode = ['default'] def forward(self,",
"_, attack in enumerate(self.attacks): adv_images = attack(images[fails], labels[fails]) outputs =",
"a model with various attacks agains same images and labels.",
"print(self._return_sr_record(multi_atk_records)) if self._accumulate_multi_atk_records: self._update_multi_atk_records(multi_atk_records) return final_images def _clear_multi_atk_records(self): self._multi_atk_records =",
">>> atk2 = torchattacks.PGD(model, eps=8/255, alpha=2/255, iters=40, random_start=True) >>> atk",
"model to attack. attacks (list): list of attacks. Examples:: >>>",
"[] for attack in attacks: ids.append(id(attack.model)) if len(set(ids)) != 1:",
"0: break if self.verbose: print(self._return_sr_record(multi_atk_records)) if self._accumulate_multi_atk_records: self._update_multi_atk_records(multi_atk_records) return final_images",
"Examples:: >>> atk1 = torchattacks.PGD(model, eps=8/255, alpha=2/255, iters=40, random_start=True) >>>",
"l2, elapsed_time def _save_print(self, progress, rob_acc, l2, elapsed_time, end): r\"\"\"",
"= attack(images, labels) \"\"\" def __init__(self, attacks, verbose=False): # Check",
"adv_images[succeeds_of_fails] fails = torch.masked_select(fails, corrects) multi_atk_records.append(len(fails)) if len(fails) == 0:",
"+= item def save(self, data_loader, save_path=None, verbose=True, return_verbose=False): r\"\"\" Overridden.",
"= images.shape[0] fails = torch.arange(batch_size).to(self.device) final_images = images.clone().detach().to(self.device) labels =",
"\"\"\" def __init__(self, attacks, verbose=False): # Check validity ids =",
"%2.2f %%\"%(progress, rob_acc)+\\ \" / \"+self._return_sr_record(self._multi_atk_records)+\\ ' / L2: %1.5f",
"of attacks. Examples:: >>> atk1 = torchattacks.PGD(model, eps=8/255, alpha=2/255, iters=40,",
">>> atk = torchattacks.MultiAttack([atk1, atk2]) >>> adv_images = attack(images, labels)",
"return_verbose) sr = self._covert_to_success_rates(self._multi_atk_records) self._clear_multi_atk_records() self._accumulate_multi_atk_records = False self.verbose =",
"for attack in attacks: ids.append(id(attack.model)) if len(set(ids)) != 1: raise",
"r\"\"\" Overridden. \"\"\" print(\"- Save progress: %2.2f %% / Robust",
"sr = self._covert_to_success_rates(multi_atk_records) return \"Attack success rate: \"+\" | \".join([\"%2.2f",
"self._supported_mode = ['default'] def forward(self, images, labels): r\"\"\" Overridden. \"\"\"",
"elapsed_time, end): r\"\"\" Overridden. \"\"\" print(\"- Save progress: %2.2f %%",
"l2, elapsed_time = super().save(data_loader, save_path, verbose, return_verbose) sr = self._covert_to_success_rates(self._multi_atk_records)",
"def _save_print(self, progress, rob_acc, l2, elapsed_time, end): r\"\"\" Overridden. \"\"\"",
"print(\"- Save progress: %2.2f %% / Robust accuracy: %2.2f %%\"%(progress,",
"attacks self.verbose = verbose self._accumulate_multi_atk_records = False self._multi_atk_records = [0.0]",
"\"+self._return_sr_record(self._multi_atk_records)+\\ ' / L2: %1.5f (%2.3f it/s) \\t'%(l2, elapsed_time), end=end)",
"same images and labels. Arguments: model (nn.Module): model to attack.",
"['default'] def forward(self, images, labels): r\"\"\" Overridden. \"\"\" batch_size =",
"class MultiAttack(Attack): r\"\"\" MultiAttack is a class to attack a",
"succeeds = torch.masked_select(fails, wrongs) succeeds_of_fails = torch.masked_select(torch.arange(fails.shape[0]).to(self.device), wrongs) final_images[succeeds] =",
"~corrects succeeds = torch.masked_select(fails, wrongs) succeeds_of_fails = torch.masked_select(torch.arange(fails.shape[0]).to(self.device), wrongs) final_images[succeeds]",
"len(multi_atk_records))] return sr def _return_sr_record(self, multi_atk_records): sr = self._covert_to_success_rates(multi_atk_records) return",
"alpha=2/255, iters=40, random_start=True) >>> atk = torchattacks.MultiAttack([atk1, atk2]) >>> adv_images",
"break if self.verbose: print(self._return_sr_record(multi_atk_records)) if self._accumulate_multi_atk_records: self._update_multi_atk_records(multi_atk_records) return final_images def",
"torch.masked_select(fails, wrongs) succeeds_of_fails = torch.masked_select(torch.arange(fails.shape[0]).to(self.device), wrongs) final_images[succeeds] = adv_images[succeeds_of_fails] fails",
"!= 1: raise ValueError(\"At least one of attacks is referencing",
"= ['default'] def forward(self, images, labels): r\"\"\" Overridden. \"\"\" batch_size",
"images, labels): r\"\"\" Overridden. \"\"\" batch_size = images.shape[0] fails =",
"in range(1, len(multi_atk_records))] return sr def _return_sr_record(self, multi_atk_records): sr =",
"verbose = self.verbose self.verbose = False self._accumulate_multi_atk_records = True for",
"sr = self._covert_to_success_rates(self._multi_atk_records) self._clear_multi_atk_records() self._accumulate_multi_atk_records = False self.verbose = verbose",
"referencing a different model.\") super().__init__(\"MultiAttack\", attack.model) self.attacks = attacks self.verbose",
"to attack. attacks (list): list of attacks. Examples:: >>> atk1",
"atk2]) >>> adv_images = attack(images, labels) \"\"\" def __init__(self, attacks,",
"| \".join([\"%2.2f %%\"%item for item in sr]) def _update_multi_atk_records(self, multi_atk_records):",
"adv_images = attack(images[fails], labels[fails]) outputs = self.model(adv_images) _, pre =",
"agains same images and labels. Arguments: model (nn.Module): model to",
"= self.model(adv_images) _, pre = torch.max(outputs.data, 1) corrects = (pre",
"final_images = images.clone().detach().to(self.device) labels = labels.clone().detach().to(self.device) multi_atk_records = [batch_size] for",
"self._accumulate_multi_atk_records = True for i, attack in enumerate(self.attacks): self._multi_atk_records.append(0.0) rob_acc,",
"multi_atk_records.append(len(fails)) if len(fails) == 0: break if self.verbose: print(self._return_sr_record(multi_atk_records)) if",
"enumerate(multi_atk_records): self._multi_atk_records[i] += item def save(self, data_loader, save_path=None, verbose=True, return_verbose=False):",
"attack in enumerate(self.attacks): self._multi_atk_records.append(0.0) rob_acc, l2, elapsed_time = super().save(data_loader, save_path,",
"i in range(1, len(multi_atk_records))] return sr def _return_sr_record(self, multi_atk_records): sr",
"False self.verbose = verbose if return_verbose: return rob_acc, sr, l2,",
">>> adv_images = attack(images, labels) \"\"\" def __init__(self, attacks, verbose=False):",
"_, pre = torch.max(outputs.data, 1) corrects = (pre == labels[fails])",
"to attack a model with various attacks agains same images",
"of attacks is referencing a different model.\") super().__init__(\"MultiAttack\", attack.model) self.attacks",
"\" / \"+self._return_sr_record(self._multi_atk_records)+\\ ' / L2: %1.5f (%2.3f it/s) \\t'%(l2,",
"corrects = (pre == labels[fails]) wrongs = ~corrects succeeds =",
"images.shape[0] fails = torch.arange(batch_size).to(self.device) final_images = images.clone().detach().to(self.device) labels = labels.clone().detach().to(self.device)",
"torch.arange(batch_size).to(self.device) final_images = images.clone().detach().to(self.device) labels = labels.clone().detach().to(self.device) multi_atk_records = [batch_size]",
"succeeds_of_fails = torch.masked_select(torch.arange(fails.shape[0]).to(self.device), wrongs) final_images[succeeds] = adv_images[succeeds_of_fails] fails = torch.masked_select(fails,",
"def save(self, data_loader, save_path=None, verbose=True, return_verbose=False): r\"\"\" Overridden. \"\"\" self._clear_multi_atk_records()",
"atk1 = torchattacks.PGD(model, eps=8/255, alpha=2/255, iters=40, random_start=True) >>> atk2 =",
"len(fails) == 0: break if self.verbose: print(self._return_sr_record(multi_atk_records)) if self._accumulate_multi_atk_records: self._update_multi_atk_records(multi_atk_records)",
"progress, rob_acc, l2, elapsed_time, end): r\"\"\" Overridden. \"\"\" print(\"- Save",
"[batch_size] for _, attack in enumerate(self.attacks): adv_images = attack(images[fails], labels[fails])",
"= [batch_size] for _, attack in enumerate(self.attacks): adv_images = attack(images[fails],",
"labels[fails]) wrongs = ~corrects succeeds = torch.masked_select(fails, wrongs) succeeds_of_fails =",
"corrects) multi_atk_records.append(len(fails)) if len(fails) == 0: break if self.verbose: print(self._return_sr_record(multi_atk_records))",
"(list): list of attacks. Examples:: >>> atk1 = torchattacks.PGD(model, eps=8/255,",
"if len(fails) == 0: break if self.verbose: print(self._return_sr_record(multi_atk_records)) if self._accumulate_multi_atk_records:",
"attack(images[fails], labels[fails]) outputs = self.model(adv_images) _, pre = torch.max(outputs.data, 1)",
"outputs = self.model(adv_images) _, pre = torch.max(outputs.data, 1) corrects =",
"fails = torch.masked_select(fails, corrects) multi_atk_records.append(len(fails)) if len(fails) == 0: break",
"self.verbose = verbose if return_verbose: return rob_acc, sr, l2, elapsed_time",
"self._accumulate_multi_atk_records = False self.verbose = verbose if return_verbose: return rob_acc,",
"verbose, return_verbose) sr = self._covert_to_success_rates(self._multi_atk_records) self._clear_multi_atk_records() self._accumulate_multi_atk_records = False self.verbose",
"self.model(adv_images) _, pre = torch.max(outputs.data, 1) corrects = (pre ==",
"self._multi_atk_records[i] += item def save(self, data_loader, save_path=None, verbose=True, return_verbose=False): r\"\"\"",
"accuracy: %2.2f %%\"%(progress, rob_acc)+\\ \" / \"+self._return_sr_record(self._multi_atk_records)+\\ ' / L2:",
"rate: \"+\" | \".join([\"%2.2f %%\"%item for item in sr]) def",
"wrongs) final_images[succeeds] = adv_images[succeeds_of_fails] fails = torch.masked_select(fails, corrects) multi_atk_records.append(len(fails)) if",
"random_start=True) >>> atk2 = torchattacks.PGD(model, eps=8/255, alpha=2/255, iters=40, random_start=True) >>>",
"= ~corrects succeeds = torch.masked_select(fails, wrongs) succeeds_of_fails = torch.masked_select(torch.arange(fails.shape[0]).to(self.device), wrongs)",
"in sr]) def _update_multi_atk_records(self, multi_atk_records): for i, item in enumerate(multi_atk_records):",
"self._update_multi_atk_records(multi_atk_records) return final_images def _clear_multi_atk_records(self): self._multi_atk_records = [0.0] def _covert_to_success_rates(self,",
"atk2 = torchattacks.PGD(model, eps=8/255, alpha=2/255, iters=40, random_start=True) >>> atk =",
"== 0: break if self.verbose: print(self._return_sr_record(multi_atk_records)) if self._accumulate_multi_atk_records: self._update_multi_atk_records(multi_atk_records) return",
"_clear_multi_atk_records(self): self._multi_atk_records = [0.0] def _covert_to_success_rates(self, multi_atk_records): sr = [((1-multi_atk_records[i]/multi_atk_records[0])*100)",
"with various attacks agains same images and labels. Arguments: model",
"def _return_sr_record(self, multi_atk_records): sr = self._covert_to_success_rates(multi_atk_records) return \"Attack success rate:",
"import torch from ..attack import Attack class MultiAttack(Attack): r\"\"\" MultiAttack",
"multi_atk_records): sr = [((1-multi_atk_records[i]/multi_atk_records[0])*100) for i in range(1, len(multi_atk_records))] return",
"= torchattacks.MultiAttack([atk1, atk2]) >>> adv_images = attack(images, labels) \"\"\" def",
"for i, attack in enumerate(self.attacks): self._multi_atk_records.append(0.0) rob_acc, l2, elapsed_time =",
"save_path=None, verbose=True, return_verbose=False): r\"\"\" Overridden. \"\"\" self._clear_multi_atk_records() verbose = self.verbose",
"self._multi_atk_records = [0.0] def _covert_to_success_rates(self, multi_atk_records): sr = [((1-multi_atk_records[i]/multi_atk_records[0])*100) for",
"def _update_multi_atk_records(self, multi_atk_records): for i, item in enumerate(multi_atk_records): self._multi_atk_records[i] +=",
"torch.masked_select(fails, corrects) multi_atk_records.append(len(fails)) if len(fails) == 0: break if self.verbose:",
"= verbose if return_verbose: return rob_acc, sr, l2, elapsed_time def",
"raise ValueError(\"At least one of attacks is referencing a different",
"model with various attacks agains same images and labels. Arguments:",
"\"\"\" batch_size = images.shape[0] fails = torch.arange(batch_size).to(self.device) final_images = images.clone().detach().to(self.device)",
"multi_atk_records): for i, item in enumerate(multi_atk_records): self._multi_atk_records[i] += item def",
"= self.verbose self.verbose = False self._accumulate_multi_atk_records = True for i,",
"elapsed_time def _save_print(self, progress, rob_acc, l2, elapsed_time, end): r\"\"\" Overridden.",
"attack in attacks: ids.append(id(attack.model)) if len(set(ids)) != 1: raise ValueError(\"At",
"\"+\" | \".join([\"%2.2f %%\"%item for item in sr]) def _update_multi_atk_records(self,",
"(nn.Module): model to attack. attacks (list): list of attacks. Examples::",
"images and labels. Arguments: model (nn.Module): model to attack. attacks",
"ids = [] for attack in attacks: ids.append(id(attack.model)) if len(set(ids))",
"[0.0] self._supported_mode = ['default'] def forward(self, images, labels): r\"\"\" Overridden.",
"attacks. Examples:: >>> atk1 = torchattacks.PGD(model, eps=8/255, alpha=2/255, iters=40, random_start=True)",
"attacks is referencing a different model.\") super().__init__(\"MultiAttack\", attack.model) self.attacks =",
"= self._covert_to_success_rates(multi_atk_records) return \"Attack success rate: \"+\" | \".join([\"%2.2f %%\"%item",
"= False self._accumulate_multi_atk_records = True for i, attack in enumerate(self.attacks):",
"%2.2f %% / Robust accuracy: %2.2f %%\"%(progress, rob_acc)+\\ \" /",
"return \"Attack success rate: \"+\" | \".join([\"%2.2f %%\"%item for item",
"Attack class MultiAttack(Attack): r\"\"\" MultiAttack is a class to attack",
"super().__init__(\"MultiAttack\", attack.model) self.attacks = attacks self.verbose = verbose self._accumulate_multi_atk_records =",
"a class to attack a model with various attacks agains",
"item in enumerate(multi_atk_records): self._multi_atk_records[i] += item def save(self, data_loader, save_path=None,",
"for i in range(1, len(multi_atk_records))] return sr def _return_sr_record(self, multi_atk_records):",
"attack. attacks (list): list of attacks. Examples:: >>> atk1 =",
"self._accumulate_multi_atk_records = False self._multi_atk_records = [0.0] self._supported_mode = ['default'] def",
"= attack(images[fails], labels[fails]) outputs = self.model(adv_images) _, pre = torch.max(outputs.data,",
"save(self, data_loader, save_path=None, verbose=True, return_verbose=False): r\"\"\" Overridden. \"\"\" self._clear_multi_atk_records() verbose",
"copy import torch from ..attack import Attack class MultiAttack(Attack): r\"\"\"",
"ValueError(\"At least one of attacks is referencing a different model.\")",
"torch from ..attack import Attack class MultiAttack(Attack): r\"\"\" MultiAttack is",
"True for i, attack in enumerate(self.attacks): self._multi_atk_records.append(0.0) rob_acc, l2, elapsed_time",
"= adv_images[succeeds_of_fails] fails = torch.masked_select(fails, corrects) multi_atk_records.append(len(fails)) if len(fails) ==",
"= super().save(data_loader, save_path, verbose, return_verbose) sr = self._covert_to_success_rates(self._multi_atk_records) self._clear_multi_atk_records() self._accumulate_multi_atk_records",
"end): r\"\"\" Overridden. \"\"\" print(\"- Save progress: %2.2f %% /",
"is a class to attack a model with various attacks",
"_return_sr_record(self, multi_atk_records): sr = self._covert_to_success_rates(multi_atk_records) return \"Attack success rate: \"+\"",
"import Attack class MultiAttack(Attack): r\"\"\" MultiAttack is a class to",
"return_verbose=False): r\"\"\" Overridden. \"\"\" self._clear_multi_atk_records() verbose = self.verbose self.verbose =",
"success rate: \"+\" | \".join([\"%2.2f %%\"%item for item in sr])",
"= [] for attack in attacks: ids.append(id(attack.model)) if len(set(ids)) !=",
"Overridden. \"\"\" self._clear_multi_atk_records() verbose = self.verbose self.verbose = False self._accumulate_multi_atk_records",
"item def save(self, data_loader, save_path=None, verbose=True, return_verbose=False): r\"\"\" Overridden. \"\"\"",
"in enumerate(self.attacks): self._multi_atk_records.append(0.0) rob_acc, l2, elapsed_time = super().save(data_loader, save_path, verbose,",
"verbose=True, return_verbose=False): r\"\"\" Overridden. \"\"\" self._clear_multi_atk_records() verbose = self.verbose self.verbose",
"(pre == labels[fails]) wrongs = ~corrects succeeds = torch.masked_select(fails, wrongs)",
"sr = [((1-multi_atk_records[i]/multi_atk_records[0])*100) for i in range(1, len(multi_atk_records))] return sr",
"a different model.\") super().__init__(\"MultiAttack\", attack.model) self.attacks = attacks self.verbose =",
"range(1, len(multi_atk_records))] return sr def _return_sr_record(self, multi_atk_records): sr = self._covert_to_success_rates(multi_atk_records)",
"= torch.masked_select(fails, corrects) multi_atk_records.append(len(fails)) if len(fails) == 0: break if",
"labels[fails]) outputs = self.model(adv_images) _, pre = torch.max(outputs.data, 1) corrects",
"sr def _return_sr_record(self, multi_atk_records): sr = self._covert_to_success_rates(multi_atk_records) return \"Attack success",
"batch_size = images.shape[0] fails = torch.arange(batch_size).to(self.device) final_images = images.clone().detach().to(self.device) labels",
"False self._accumulate_multi_atk_records = True for i, attack in enumerate(self.attacks): self._multi_atk_records.append(0.0)",
"different model.\") super().__init__(\"MultiAttack\", attack.model) self.attacks = attacks self.verbose = verbose",
"torch.masked_select(torch.arange(fails.shape[0]).to(self.device), wrongs) final_images[succeeds] = adv_images[succeeds_of_fails] fails = torch.masked_select(fails, corrects) multi_atk_records.append(len(fails))",
"= torchattacks.PGD(model, eps=8/255, alpha=2/255, iters=40, random_start=True) >>> atk2 = torchattacks.PGD(model,",
"multi_atk_records): sr = self._covert_to_success_rates(multi_atk_records) return \"Attack success rate: \"+\" |",
"def _covert_to_success_rates(self, multi_atk_records): sr = [((1-multi_atk_records[i]/multi_atk_records[0])*100) for i in range(1,",
"import copy import torch from ..attack import Attack class MultiAttack(Attack):",
"fails = torch.arange(batch_size).to(self.device) final_images = images.clone().detach().to(self.device) labels = labels.clone().detach().to(self.device) multi_atk_records",
"\"\"\" print(\"- Save progress: %2.2f %% / Robust accuracy: %2.2f",
"various attacks agains same images and labels. Arguments: model (nn.Module):",
"list of attacks. Examples:: >>> atk1 = torchattacks.PGD(model, eps=8/255, alpha=2/255,",
"return sr def _return_sr_record(self, multi_atk_records): sr = self._covert_to_success_rates(multi_atk_records) return \"Attack",
"return_verbose: return rob_acc, sr, l2, elapsed_time def _save_print(self, progress, rob_acc,",
"..attack import Attack class MultiAttack(Attack): r\"\"\" MultiAttack is a class",
"rob_acc, l2, elapsed_time = super().save(data_loader, save_path, verbose, return_verbose) sr =",
"= (pre == labels[fails]) wrongs = ~corrects succeeds = torch.masked_select(fails,",
"= images.clone().detach().to(self.device) labels = labels.clone().detach().to(self.device) multi_atk_records = [batch_size] for _,",
"attacks, verbose=False): # Check validity ids = [] for attack",
"= self._covert_to_success_rates(self._multi_atk_records) self._clear_multi_atk_records() self._accumulate_multi_atk_records = False self.verbose = verbose if",
"Robust accuracy: %2.2f %%\"%(progress, rob_acc)+\\ \" / \"+self._return_sr_record(self._multi_atk_records)+\\ ' /",
"MultiAttack(Attack): r\"\"\" MultiAttack is a class to attack a model",
"if self._accumulate_multi_atk_records: self._update_multi_atk_records(multi_atk_records) return final_images def _clear_multi_atk_records(self): self._multi_atk_records = [0.0]",
"Overridden. \"\"\" print(\"- Save progress: %2.2f %% / Robust accuracy:",
"self._multi_atk_records = [0.0] self._supported_mode = ['default'] def forward(self, images, labels):",
"__init__(self, attacks, verbose=False): # Check validity ids = [] for",
"self._clear_multi_atk_records() verbose = self.verbose self.verbose = False self._accumulate_multi_atk_records = True",
"1) corrects = (pre == labels[fails]) wrongs = ~corrects succeeds",
"multi_atk_records = [batch_size] for _, attack in enumerate(self.attacks): adv_images =",
"len(set(ids)) != 1: raise ValueError(\"At least one of attacks is",
"verbose self._accumulate_multi_atk_records = False self._multi_atk_records = [0.0] self._supported_mode = ['default']",
"is referencing a different model.\") super().__init__(\"MultiAttack\", attack.model) self.attacks = attacks",
"self._accumulate_multi_atk_records: self._update_multi_atk_records(multi_atk_records) return final_images def _clear_multi_atk_records(self): self._multi_atk_records = [0.0] def",
"= torch.arange(batch_size).to(self.device) final_images = images.clone().detach().to(self.device) labels = labels.clone().detach().to(self.device) multi_atk_records =",
"%% / Robust accuracy: %2.2f %%\"%(progress, rob_acc)+\\ \" / \"+self._return_sr_record(self._multi_atk_records)+\\",
"= [0.0] def _covert_to_success_rates(self, multi_atk_records): sr = [((1-multi_atk_records[i]/multi_atk_records[0])*100) for i",
"for _, attack in enumerate(self.attacks): adv_images = attack(images[fails], labels[fails]) outputs",
"wrongs = ~corrects succeeds = torch.masked_select(fails, wrongs) succeeds_of_fails = torch.masked_select(torch.arange(fails.shape[0]).to(self.device),",
"_covert_to_success_rates(self, multi_atk_records): sr = [((1-multi_atk_records[i]/multi_atk_records[0])*100) for i in range(1, len(multi_atk_records))]",
"\".join([\"%2.2f %%\"%item for item in sr]) def _update_multi_atk_records(self, multi_atk_records): for",
"= torch.masked_select(fails, wrongs) succeeds_of_fails = torch.masked_select(torch.arange(fails.shape[0]).to(self.device), wrongs) final_images[succeeds] = adv_images[succeeds_of_fails]",
"labels): r\"\"\" Overridden. \"\"\" batch_size = images.shape[0] fails = torch.arange(batch_size).to(self.device)",
"adv_images = attack(images, labels) \"\"\" def __init__(self, attacks, verbose=False): #",
"final_images def _clear_multi_atk_records(self): self._multi_atk_records = [0.0] def _covert_to_success_rates(self, multi_atk_records): sr",
"save_path, verbose, return_verbose) sr = self._covert_to_success_rates(self._multi_atk_records) self._clear_multi_atk_records() self._accumulate_multi_atk_records = False",
"verbose=False): # Check validity ids = [] for attack in",
"= torch.masked_select(torch.arange(fails.shape[0]).to(self.device), wrongs) final_images[succeeds] = adv_images[succeeds_of_fails] fails = torch.masked_select(fails, corrects)",
"self._clear_multi_atk_records() self._accumulate_multi_atk_records = False self.verbose = verbose if return_verbose: return",
"for item in sr]) def _update_multi_atk_records(self, multi_atk_records): for i, item",
"= True for i, attack in enumerate(self.attacks): self._multi_atk_records.append(0.0) rob_acc, l2,",
"labels = labels.clone().detach().to(self.device) multi_atk_records = [batch_size] for _, attack in"
] |
[
"NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A",
"cmd = \"kill -9\" for pid in pidList: cmd +=",
"ON AN \"AS IS\" BASIS, # WITHOUT WARRANTIES OF ANY",
"~ /25[0-9][0-9][0-9]/'\" \\ \"| awk '{print $NF}'\" (status, output) =",
"self.result.val += \"The cmd is %s \" % cmd else:",
"+= \"The cmd is %s \" % cmd else: self.result.val",
"0 and output != \"\"): for line in output.split('\\n'): if",
"AN \"AS IS\" BASIS, # WITHOUT WARRANTIES OF ANY KIND,",
"commands: %s\\noutput:%s \" % ( cmd, output) else: if (output.strip()",
"for more details. # ---------------------------------------------------------------------------- import subprocess from gspylib.inspection.common.CheckItem import",
"WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING",
"\\ \"| awk '{print $NF}'\" (status, output) = subprocess.getstatusoutput(cmd) if",
"OR FIT FOR A PARTICULAR PURPOSE. # See the Mulan",
"\"ports is normal\" else: self.result.rst = ResultStatus.NG self.result.val = output",
"normal\" else: self.result.rst = ResultStatus.NG self.result.val = output self.result.raw =",
"def doSet(self): pidList = [] cmd = \"netstat -apn| grep",
"if (status == 0 and output != \"\"): for line",
"under Mulan PSL v2. # You can use this software",
"more details. # ---------------------------------------------------------------------------- import subprocess from gspylib.inspection.common.CheckItem import BaseItem",
"---------------------------------------------------------------------------- import subprocess from gspylib.inspection.common.CheckItem import BaseItem from gspylib.inspection.common.CheckResult import",
"'LISTEN'| awk -F ' ' '$4 ~ /25[0-9][0-9][0-9]/'\" \\ \"|",
"pid (status, output) = subprocess.getstatusoutput(cmd) if (status != \"\"): self.result.val",
"grep 'LISTEN'| awk -F ' ' '$4 ~ /25[0-9][0-9][0-9]/'\" \\",
"(c) 2020 Huawei Technologies Co.,Ltd. # # openGauss is licensed",
"= output self.result.raw = \"checked ports: (25000-26000)\\n\" + output def",
"cmd = \"netstat -apn| grep 'tcp'\" \\ \"| grep 'LISTEN'|",
"coding:utf-8 -*- # Copyright (c) 2020 Huawei Technologies Co.,Ltd. #",
"Mulan PSL v2. # You can use this software according",
"for line in output.split('\\n'): if (line.find('/') > 0): pid =",
"'tcp' \" \\ \"| grep 'LISTEN'| awk -F ' '",
"~ /25[0-9][0-9][0-9]/'\" (status, output) = subprocess.getstatusoutput(cmd) if (status != 0):",
"\"Failed to excuted commands: %s\\noutput:%s \" % ( cmd, output)",
"SOFTWARE IS PROVIDED ON AN \"AS IS\" BASIS, # WITHOUT",
"-9\" for pid in pidList: cmd += \" %s\" %",
"'{print $NF}'\" (status, output) = subprocess.getstatusoutput(cmd) if (status == 0",
"v2. # You may obtain a copy of Mulan PSL",
"-F ' ' '$4 ~ /25[0-9][0-9][0-9]/'\" (status, output) = subprocess.getstatusoutput(cmd)",
"# THIS SOFTWARE IS PROVIDED ON AN \"AS IS\" BASIS,",
"self.result.val = \"Failed to kill process.Error:%s\\n\" % output self.result.val +=",
"conditions of the Mulan PSL v2. # You may obtain",
"\"\"): self.result.rst = ResultStatus.OK self.result.val = \"ports is normal\" else:",
"# # THIS SOFTWARE IS PROVIDED ON AN \"AS IS\"",
"# WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR",
"doCheck(self): cmd = \"netstat -apn | grep 'tcp' \" \\",
"doSet(self): pidList = [] cmd = \"netstat -apn| grep 'tcp'\"",
"\" %s\" % pid (status, output) = subprocess.getstatusoutput(cmd) if (status",
"cmd else: self.result.val = \\ \"Successfully killed the process with",
"= subprocess.getstatusoutput(cmd) if (status != \"\"): self.result.val = \"Failed to",
"a copy of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2",
"-apn| grep 'tcp'\" \\ \"| grep 'LISTEN'| awk -F '",
"output def doSet(self): pidList = [] cmd = \"netstat -apn|",
"in pidList: cmd += \" %s\" % pid (status, output)",
"= \"checked ports: (25000-26000)\\n\" + output def doSet(self): pidList =",
"IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR",
"!= 0): self.result.rst = ResultStatus.NG self.result.val = \"Failed to excuted",
"== \"\"): self.result.rst = ResultStatus.OK self.result.val = \"ports is normal\"",
"output) = subprocess.getstatusoutput(cmd) if (status == 0 and output !=",
"output) = subprocess.getstatusoutput(cmd) if (status != \"\"): self.result.val = \"Failed",
"THIS SOFTWARE IS PROVIDED ON AN \"AS IS\" BASIS, #",
"import BaseItem from gspylib.inspection.common.CheckResult import ResultStatus class CheckPortConflict(BaseItem): def __init__(self):",
"to the terms # and conditions of the Mulan PSL",
"(pid.isdigit()): pidList.append(pid) if (pidList): cmd = \"kill -9\" for pid",
"pidList: cmd += \" %s\" % pid (status, output) =",
"IS PROVIDED ON AN \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"# You may obtain a copy of Mulan PSL v2",
"openGauss is licensed under Mulan PSL v2. # You can",
"is licensed under Mulan PSL v2. # You can use",
"import subprocess from gspylib.inspection.common.CheckItem import BaseItem from gspylib.inspection.common.CheckResult import ResultStatus",
"gspylib.inspection.common.CheckResult import ResultStatus class CheckPortConflict(BaseItem): def __init__(self): super(CheckPortConflict, self).__init__(self.__class__.__name__) def",
"'tcp'\" \\ \"| grep 'LISTEN'| awk -F ' ' '$4",
"= subprocess.getstatusoutput(cmd) if (status == 0 and output != \"\"):",
"copy of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 #",
"(line.find('/') > 0): pid = line.split('/')[0].strip() if (pid.isdigit()): pidList.append(pid) if",
"/25[0-9][0-9][0-9]/'\" (status, output) = subprocess.getstatusoutput(cmd) if (status != 0): self.result.rst",
"0): pid = line.split('/')[0].strip() if (pid.isdigit()): pidList.append(pid) if (pidList): cmd",
"for pid in pidList: cmd += \" %s\" % pid",
"pid in pidList: cmd += \" %s\" % pid (status,",
"% cmd else: self.result.val = \\ \"Successfully killed the process",
"\" % cmd else: self.result.val = \\ \"Successfully killed the",
"\"kill -9\" for pid in pidList: cmd += \" %s\"",
"-F ' ' '$4 ~ /25[0-9][0-9][0-9]/'\" \\ \"| awk '{print",
"!= \"\"): self.result.val = \"Failed to kill process.Error:%s\\n\" % output",
"of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # #",
"kill process.Error:%s\\n\" % output self.result.val += \"The cmd is %s",
"A PARTICULAR PURPOSE. # See the Mulan PSL v2 for",
"cmd is %s \" % cmd else: self.result.val = \\",
"OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT",
"gspylib.inspection.common.CheckItem import BaseItem from gspylib.inspection.common.CheckResult import ResultStatus class CheckPortConflict(BaseItem): def",
"# See the Mulan PSL v2 for more details. #",
"\"checked ports: (25000-26000)\\n\" + output def doSet(self): pidList = []",
"(status == 0 and output != \"\"): for line in",
"from gspylib.inspection.common.CheckResult import ResultStatus class CheckPortConflict(BaseItem): def __init__(self): super(CheckPortConflict, self).__init__(self.__class__.__name__)",
"Mulan PSL v2 for more details. # ---------------------------------------------------------------------------- import subprocess",
"else: self.result.val = \\ \"Successfully killed the process with occupies",
"[] cmd = \"netstat -apn| grep 'tcp'\" \\ \"| grep",
"if (status != \"\"): self.result.val = \"Failed to kill process.Error:%s\\n\"",
"\\ \"| grep 'LISTEN'| awk -F ' ' '$4 ~",
"of the Mulan PSL v2. # You may obtain a",
"obtain a copy of Mulan PSL v2 at: # #",
"'$4 ~ /25[0-9][0-9][0-9]/'\" (status, output) = subprocess.getstatusoutput(cmd) if (status !=",
"self.result.val = \"ports is normal\" else: self.result.rst = ResultStatus.NG self.result.val",
"!= \"\"): for line in output.split('\\n'): if (line.find('/') > 0):",
"super(CheckPortConflict, self).__init__(self.__class__.__name__) def doCheck(self): cmd = \"netstat -apn | grep",
"-apn | grep 'tcp' \" \\ \"| grep 'LISTEN'| awk",
"grep 'tcp' \" \\ \"| grep 'LISTEN'| awk -F '",
"= \"ports is normal\" else: self.result.rst = ResultStatus.NG self.result.val =",
"awk -F ' ' '$4 ~ /25[0-9][0-9][0-9]/'\" (status, output) =",
"pidList.append(pid) if (pidList): cmd = \"kill -9\" for pid in",
"is normal\" else: self.result.rst = ResultStatus.NG self.result.val = output self.result.raw",
"licensed under Mulan PSL v2. # You can use this",
"CheckPortConflict(BaseItem): def __init__(self): super(CheckPortConflict, self).__init__(self.__class__.__name__) def doCheck(self): cmd = \"netstat",
"line in output.split('\\n'): if (line.find('/') > 0): pid = line.split('/')[0].strip()",
"ResultStatus class CheckPortConflict(BaseItem): def __init__(self): super(CheckPortConflict, self).__init__(self.__class__.__name__) def doCheck(self): cmd",
"You can use this software according to the terms #",
"INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT",
"'LISTEN'| awk -F ' ' '$4 ~ /25[0-9][0-9][0-9]/'\" (status, output)",
"# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See",
"+= \" %s\" % pid (status, output) = subprocess.getstatusoutput(cmd) if",
"may obtain a copy of Mulan PSL v2 at: #",
"'$4 ~ /25[0-9][0-9][0-9]/'\" \\ \"| awk '{print $NF}'\" (status, output)",
"excuted commands: %s\\noutput:%s \" % ( cmd, output) else: if",
"# http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON AN",
"0): self.result.rst = ResultStatus.NG self.result.val = \"Failed to excuted commands:",
"EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, #",
"Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS",
"You may obtain a copy of Mulan PSL v2 at:",
"( cmd, output) else: if (output.strip() == \"\"): self.result.rst =",
"ResultStatus.OK self.result.val = \"ports is normal\" else: self.result.rst = ResultStatus.NG",
"IS\" BASIS, # WITHOUT WARRANTIES OF ANY KIND, # EITHER",
"FIT FOR A PARTICULAR PURPOSE. # See the Mulan PSL",
"PARTICULAR PURPOSE. # See the Mulan PSL v2 for more",
"NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. #",
"# openGauss is licensed under Mulan PSL v2. # You",
"\"| awk '{print $NF}'\" (status, output) = subprocess.getstatusoutput(cmd) if (status",
"# Copyright (c) 2020 Huawei Technologies Co.,Ltd. # # openGauss",
"# and conditions of the Mulan PSL v2. # You",
"PSL v2. # You can use this software according to",
"' ' '$4 ~ /25[0-9][0-9][0-9]/'\" (status, output) = subprocess.getstatusoutput(cmd) if",
"v2. # You can use this software according to the",
"% pid (status, output) = subprocess.getstatusoutput(cmd) if (status != \"\"):",
"output self.result.val += \"The cmd is %s \" % cmd",
"grep 'LISTEN'| awk -F ' ' '$4 ~ /25[0-9][0-9][0-9]/'\" (status,",
"KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED",
"OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY",
"\"netstat -apn| grep 'tcp'\" \\ \"| grep 'LISTEN'| awk -F",
"v2 for more details. # ---------------------------------------------------------------------------- import subprocess from gspylib.inspection.common.CheckItem",
"(pidList): cmd = \"kill -9\" for pid in pidList: cmd",
"the Mulan PSL v2 for more details. # ---------------------------------------------------------------------------- import",
"__init__(self): super(CheckPortConflict, self).__init__(self.__class__.__name__) def doCheck(self): cmd = \"netstat -apn |",
"' '$4 ~ /25[0-9][0-9][0-9]/'\" (status, output) = subprocess.getstatusoutput(cmd) if (status",
"TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.",
"= [] cmd = \"netstat -apn| grep 'tcp'\" \\ \"|",
"= \"Failed to kill process.Error:%s\\n\" % output self.result.val += \"The",
"import ResultStatus class CheckPortConflict(BaseItem): def __init__(self): super(CheckPortConflict, self).__init__(self.__class__.__name__) def doCheck(self):",
"http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON AN \"AS",
"ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT",
"awk '{print $NF}'\" (status, output) = subprocess.getstatusoutput(cmd) if (status ==",
"\"\"): for line in output.split('\\n'): if (line.find('/') > 0): pid",
"\" \\ \"| grep 'LISTEN'| awk -F ' ' '$4",
"%s \" % cmd else: self.result.val = \\ \"Successfully killed",
"# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO",
"line.split('/')[0].strip() if (pid.isdigit()): pidList.append(pid) if (pidList): cmd = \"kill -9\"",
"%s\" % pid (status, output) = subprocess.getstatusoutput(cmd) if (status !=",
"self.result.rst = ResultStatus.NG self.result.val = \"Failed to excuted commands: %s\\noutput:%s",
"self.result.val = \\ \"Successfully killed the process with occupies the",
"= ResultStatus.NG self.result.val = \"Failed to excuted commands: %s\\noutput:%s \"",
"the terms # and conditions of the Mulan PSL v2.",
"and output != \"\"): for line in output.split('\\n'): if (line.find('/')",
"grep 'tcp'\" \\ \"| grep 'LISTEN'| awk -F ' '",
"ports: (25000-26000)\\n\" + output def doSet(self): pidList = [] cmd",
"self).__init__(self.__class__.__name__) def doCheck(self): cmd = \"netstat -apn | grep 'tcp'",
"if (output.strip() == \"\"): self.result.rst = ResultStatus.OK self.result.val = \"ports",
"output.split('\\n'): if (line.find('/') > 0): pid = line.split('/')[0].strip() if (pid.isdigit()):",
"self.result.raw = \"checked ports: (25000-26000)\\n\" + output def doSet(self): pidList",
"-*- coding:utf-8 -*- # Copyright (c) 2020 Huawei Technologies Co.,Ltd.",
"Huawei Technologies Co.,Ltd. # # openGauss is licensed under Mulan",
"\"| grep 'LISTEN'| awk -F ' ' '$4 ~ /25[0-9][0-9][0-9]/'\"",
"= \"netstat -apn | grep 'tcp' \" \\ \"| grep",
"and conditions of the Mulan PSL v2. # You may",
"Mulan PSL v2. # You may obtain a copy of",
"BaseItem from gspylib.inspection.common.CheckResult import ResultStatus class CheckPortConflict(BaseItem): def __init__(self): super(CheckPortConflict,",
"self.result.val = \"Failed to excuted commands: %s\\noutput:%s \" % (",
"Copyright (c) 2020 Huawei Technologies Co.,Ltd. # # openGauss is",
"# -*- coding:utf-8 -*- # Copyright (c) 2020 Huawei Technologies",
"def doCheck(self): cmd = \"netstat -apn | grep 'tcp' \"",
"% ( cmd, output) else: if (output.strip() == \"\"): self.result.rst",
"else: if (output.strip() == \"\"): self.result.rst = ResultStatus.OK self.result.val =",
"if (line.find('/') > 0): pid = line.split('/')[0].strip() if (pid.isdigit()): pidList.append(pid)",
"> 0): pid = line.split('/')[0].strip() if (pid.isdigit()): pidList.append(pid) if (pidList):",
"terms # and conditions of the Mulan PSL v2. #",
"= subprocess.getstatusoutput(cmd) if (status != 0): self.result.rst = ResultStatus.NG self.result.val",
"WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED,",
"can use this software according to the terms # and",
"the Mulan PSL v2. # You may obtain a copy",
"pidList = [] cmd = \"netstat -apn| grep 'tcp'\" \\",
"cmd, output) else: if (output.strip() == \"\"): self.result.rst = ResultStatus.OK",
"= ResultStatus.NG self.result.val = output self.result.raw = \"checked ports: (25000-26000)\\n\"",
"+ output def doSet(self): pidList = [] cmd = \"netstat",
"\"netstat -apn | grep 'tcp' \" \\ \"| grep 'LISTEN'|",
"EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,",
"PURPOSE. # See the Mulan PSL v2 for more details.",
"if (status != 0): self.result.rst = ResultStatus.NG self.result.val = \"Failed",
"= \"kill -9\" for pid in pidList: cmd += \"",
"= \"Failed to excuted commands: %s\\noutput:%s \" % ( cmd,",
"is %s \" % cmd else: self.result.val = \\ \"Successfully",
"$NF}'\" (status, output) = subprocess.getstatusoutput(cmd) if (status == 0 and",
"output self.result.raw = \"checked ports: (25000-26000)\\n\" + output def doSet(self):",
"subprocess.getstatusoutput(cmd) if (status != 0): self.result.rst = ResultStatus.NG self.result.val =",
"\" % ( cmd, output) else: if (output.strip() == \"\"):",
"output) = subprocess.getstatusoutput(cmd) if (status != 0): self.result.rst = ResultStatus.NG",
"v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS",
"= ResultStatus.OK self.result.val = \"ports is normal\" else: self.result.rst =",
"' ' '$4 ~ /25[0-9][0-9][0-9]/'\" \\ \"| awk '{print $NF}'\"",
"in output.split('\\n'): if (line.find('/') > 0): pid = line.split('/')[0].strip() if",
"pid = line.split('/')[0].strip() if (pid.isdigit()): pidList.append(pid) if (pidList): cmd =",
"to kill process.Error:%s\\n\" % output self.result.val += \"The cmd is",
"self.result.val = output self.result.raw = \"checked ports: (25000-26000)\\n\" + output",
"(status, output) = subprocess.getstatusoutput(cmd) if (status == 0 and output",
"= \\ \"Successfully killed the process with occupies the port.\\n\"",
"PSL v2. # You may obtain a copy of Mulan",
"PSL v2 for more details. # ---------------------------------------------------------------------------- import subprocess from",
"ResultStatus.NG self.result.val = \"Failed to excuted commands: %s\\noutput:%s \" %",
"BASIS, # WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS",
"(status != \"\"): self.result.val = \"Failed to kill process.Error:%s\\n\" %",
"# You can use this software according to the terms",
"if (pid.isdigit()): pidList.append(pid) if (pidList): cmd = \"kill -9\" for",
"(status != 0): self.result.rst = ResultStatus.NG self.result.val = \"Failed to",
"FOR A PARTICULAR PURPOSE. # See the Mulan PSL v2",
"cmd += \" %s\" % pid (status, output) = subprocess.getstatusoutput(cmd)",
"at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED",
"self.result.rst = ResultStatus.OK self.result.val = \"ports is normal\" else: self.result.rst",
"== 0 and output != \"\"): for line in output.split('\\n'):",
"cmd = \"netstat -apn | grep 'tcp' \" \\ \"|",
"(status, output) = subprocess.getstatusoutput(cmd) if (status != 0): self.result.rst =",
"(25000-26000)\\n\" + output def doSet(self): pidList = [] cmd =",
"Technologies Co.,Ltd. # # openGauss is licensed under Mulan PSL",
"-*- # Copyright (c) 2020 Huawei Technologies Co.,Ltd. # #",
"output != \"\"): for line in output.split('\\n'): if (line.find('/') >",
"PROVIDED ON AN \"AS IS\" BASIS, # WITHOUT WARRANTIES OF",
"LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR",
"= line.split('/')[0].strip() if (pid.isdigit()): pidList.append(pid) if (pidList): cmd = \"kill",
"from gspylib.inspection.common.CheckItem import BaseItem from gspylib.inspection.common.CheckResult import ResultStatus class CheckPortConflict(BaseItem):",
"details. # ---------------------------------------------------------------------------- import subprocess from gspylib.inspection.common.CheckItem import BaseItem from",
"this software according to the terms # and conditions of",
"MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the",
"def __init__(self): super(CheckPortConflict, self).__init__(self.__class__.__name__) def doCheck(self): cmd = \"netstat -apn",
"# # openGauss is licensed under Mulan PSL v2. #",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OF ANY KIND, #",
"2020 Huawei Technologies Co.,Ltd. # # openGauss is licensed under",
"%s\\noutput:%s \" % ( cmd, output) else: if (output.strip() ==",
"= \"netstat -apn| grep 'tcp'\" \\ \"| grep 'LISTEN'| awk",
"BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR",
"awk -F ' ' '$4 ~ /25[0-9][0-9][0-9]/'\" \\ \"| awk",
"software according to the terms # and conditions of the",
"# # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON",
"subprocess from gspylib.inspection.common.CheckItem import BaseItem from gspylib.inspection.common.CheckResult import ResultStatus class",
"| grep 'tcp' \" \\ \"| grep 'LISTEN'| awk -F",
"output) else: if (output.strip() == \"\"): self.result.rst = ResultStatus.OK self.result.val",
"subprocess.getstatusoutput(cmd) if (status == 0 and output != \"\"): for",
"/25[0-9][0-9][0-9]/'\" \\ \"| awk '{print $NF}'\" (status, output) = subprocess.getstatusoutput(cmd)",
"See the Mulan PSL v2 for more details. # ----------------------------------------------------------------------------",
"to excuted commands: %s\\noutput:%s \" % ( cmd, output) else:",
"if (pidList): cmd = \"kill -9\" for pid in pidList:",
"ResultStatus.NG self.result.val = output self.result.raw = \"checked ports: (25000-26000)\\n\" +",
"class CheckPortConflict(BaseItem): def __init__(self): super(CheckPortConflict, self).__init__(self.__class__.__name__) def doCheck(self): cmd =",
"\"Failed to kill process.Error:%s\\n\" % output self.result.val += \"The cmd",
"process.Error:%s\\n\" % output self.result.val += \"The cmd is %s \"",
"\"The cmd is %s \" % cmd else: self.result.val =",
"(status, output) = subprocess.getstatusoutput(cmd) if (status != \"\"): self.result.val =",
"else: self.result.rst = ResultStatus.NG self.result.val = output self.result.raw = \"checked",
"% output self.result.val += \"The cmd is %s \" %",
"PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE",
"self.result.rst = ResultStatus.NG self.result.val = output self.result.raw = \"checked ports:",
"# ---------------------------------------------------------------------------- import subprocess from gspylib.inspection.common.CheckItem import BaseItem from gspylib.inspection.common.CheckResult",
"(output.strip() == \"\"): self.result.rst = ResultStatus.OK self.result.val = \"ports is",
"' '$4 ~ /25[0-9][0-9][0-9]/'\" \\ \"| awk '{print $NF}'\" (status,",
"subprocess.getstatusoutput(cmd) if (status != \"\"): self.result.val = \"Failed to kill",
"\"\"): self.result.val = \"Failed to kill process.Error:%s\\n\" % output self.result.val",
"Co.,Ltd. # # openGauss is licensed under Mulan PSL v2.",
"according to the terms # and conditions of the Mulan",
"use this software according to the terms # and conditions"
] |
[
"subprocess import sys from . import ROOT, PY_SRC, _run, PY,",
"\"--output-folder\", DIST / \"conda-bld\", ] if __name__ == \"__main__\": for",
"_run([*CONDA_BUILD_ARGS, \"--skip-existing\", \".\"], cwd=ROOT / \"recipes\") except: for pkg in",
"for pkg in PY_SRC.glob(\"wxyz_*\"): _run([PY, \"setup.py\", \"sdist\", \"--dist-dir\", DIST /",
"\"--skip-existing\", \".\"], cwd=ROOT / \"recipes\") except: for pkg in CONDA_ORDER:",
"import ROOT, PY_SRC, _run, PY, DIST CONDA_ORDER = [ \"core\",",
"\"svg\", \"tpl-jjinja\" \"yaml\" ] CONDA_BUILD_ARGS = [ \"conda-build\", \"-c\", \"conda-forge\",",
"PY, DIST CONDA_ORDER = [ \"core\", \"html\", \"lab\", \"datagrid\", \"svg\",",
"\"--dist-dir\", DIST / \"sdist\"], cwd=str(pkg)) try: _run([*CONDA_BUILD_ARGS, \"--skip-existing\", \".\"], cwd=ROOT",
"/ \"recipes\") except: for pkg in CONDA_ORDER: _run([*CONDA_BUILD_ARGS, f\"wxyz-{pkg}\"], cwd=ROOT",
"\"datagrid\", \"svg\", \"tpl-jjinja\" \"yaml\" ] CONDA_BUILD_ARGS = [ \"conda-build\", \"-c\",",
"DIST CONDA_ORDER = [ \"core\", \"html\", \"lab\", \"datagrid\", \"svg\", \"tpl-jjinja\"",
"\"yaml\" ] CONDA_BUILD_ARGS = [ \"conda-build\", \"-c\", \"conda-forge\", \"--output-folder\", DIST",
"DIST / \"sdist\"], cwd=str(pkg)) try: _run([*CONDA_BUILD_ARGS, \"--skip-existing\", \".\"], cwd=ROOT /",
"CONDA_ORDER = [ \"core\", \"html\", \"lab\", \"datagrid\", \"svg\", \"tpl-jjinja\" \"yaml\"",
"\"lab\", \"datagrid\", \"svg\", \"tpl-jjinja\" \"yaml\" ] CONDA_BUILD_ARGS = [ \"conda-build\",",
"_run([PY, \"setup.py\", \"sdist\", \"--dist-dir\", DIST / \"sdist\"], cwd=str(pkg)) try: _run([*CONDA_BUILD_ARGS,",
"sys from . import ROOT, PY_SRC, _run, PY, DIST CONDA_ORDER",
"from . import ROOT, PY_SRC, _run, PY, DIST CONDA_ORDER =",
"[ \"core\", \"html\", \"lab\", \"datagrid\", \"svg\", \"tpl-jjinja\" \"yaml\" ] CONDA_BUILD_ARGS",
"in PY_SRC.glob(\"wxyz_*\"): _run([PY, \"setup.py\", \"sdist\", \"--dist-dir\", DIST / \"sdist\"], cwd=str(pkg))",
"try: _run([*CONDA_BUILD_ARGS, \"--skip-existing\", \".\"], cwd=ROOT / \"recipes\") except: for pkg",
"CONDA_BUILD_ARGS = [ \"conda-build\", \"-c\", \"conda-forge\", \"--output-folder\", DIST / \"conda-bld\",",
"import sys from . import ROOT, PY_SRC, _run, PY, DIST",
"] CONDA_BUILD_ARGS = [ \"conda-build\", \"-c\", \"conda-forge\", \"--output-folder\", DIST /",
"\"html\", \"lab\", \"datagrid\", \"svg\", \"tpl-jjinja\" \"yaml\" ] CONDA_BUILD_ARGS = [",
"\"recipes\") except: for pkg in CONDA_ORDER: _run([*CONDA_BUILD_ARGS, f\"wxyz-{pkg}\"], cwd=ROOT /",
"/ \"sdist\"], cwd=str(pkg)) try: _run([*CONDA_BUILD_ARGS, \"--skip-existing\", \".\"], cwd=ROOT / \"recipes\")",
"= [ \"core\", \"html\", \"lab\", \"datagrid\", \"svg\", \"tpl-jjinja\" \"yaml\" ]",
"\".\"], cwd=ROOT / \"recipes\") except: for pkg in CONDA_ORDER: _run([*CONDA_BUILD_ARGS,",
"\"setup.py\", \"sdist\", \"--dist-dir\", DIST / \"sdist\"], cwd=str(pkg)) try: _run([*CONDA_BUILD_ARGS, \"--skip-existing\",",
"\"tpl-jjinja\" \"yaml\" ] CONDA_BUILD_ARGS = [ \"conda-build\", \"-c\", \"conda-forge\", \"--output-folder\",",
"\"__main__\": for pkg in PY_SRC.glob(\"wxyz_*\"): _run([PY, \"setup.py\", \"sdist\", \"--dist-dir\", DIST",
"pkg in PY_SRC.glob(\"wxyz_*\"): _run([PY, \"setup.py\", \"sdist\", \"--dist-dir\", DIST / \"sdist\"],",
"cwd=str(pkg)) try: _run([*CONDA_BUILD_ARGS, \"--skip-existing\", \".\"], cwd=ROOT / \"recipes\") except: for",
"cwd=ROOT / \"recipes\") except: for pkg in CONDA_ORDER: _run([*CONDA_BUILD_ARGS, f\"wxyz-{pkg}\"],",
"except: for pkg in CONDA_ORDER: _run([*CONDA_BUILD_ARGS, f\"wxyz-{pkg}\"], cwd=ROOT / \"recipes\")",
"PY_SRC, _run, PY, DIST CONDA_ORDER = [ \"core\", \"html\", \"lab\",",
"_run, PY, DIST CONDA_ORDER = [ \"core\", \"html\", \"lab\", \"datagrid\",",
"\"core\", \"html\", \"lab\", \"datagrid\", \"svg\", \"tpl-jjinja\" \"yaml\" ] CONDA_BUILD_ARGS =",
"[ \"conda-build\", \"-c\", \"conda-forge\", \"--output-folder\", DIST / \"conda-bld\", ] if",
"\"sdist\"], cwd=str(pkg)) try: _run([*CONDA_BUILD_ARGS, \"--skip-existing\", \".\"], cwd=ROOT / \"recipes\") except:",
"\"conda-build\", \"-c\", \"conda-forge\", \"--output-folder\", DIST / \"conda-bld\", ] if __name__",
"== \"__main__\": for pkg in PY_SRC.glob(\"wxyz_*\"): _run([PY, \"setup.py\", \"sdist\", \"--dist-dir\",",
"DIST / \"conda-bld\", ] if __name__ == \"__main__\": for pkg",
"\"sdist\", \"--dist-dir\", DIST / \"sdist\"], cwd=str(pkg)) try: _run([*CONDA_BUILD_ARGS, \"--skip-existing\", \".\"],",
". import ROOT, PY_SRC, _run, PY, DIST CONDA_ORDER = [",
"] if __name__ == \"__main__\": for pkg in PY_SRC.glob(\"wxyz_*\"): _run([PY,",
"\"-c\", \"conda-forge\", \"--output-folder\", DIST / \"conda-bld\", ] if __name__ ==",
"ROOT, PY_SRC, _run, PY, DIST CONDA_ORDER = [ \"core\", \"html\",",
"PY_SRC.glob(\"wxyz_*\"): _run([PY, \"setup.py\", \"sdist\", \"--dist-dir\", DIST / \"sdist\"], cwd=str(pkg)) try:",
"\"conda-forge\", \"--output-folder\", DIST / \"conda-bld\", ] if __name__ == \"__main__\":",
"__name__ == \"__main__\": for pkg in PY_SRC.glob(\"wxyz_*\"): _run([PY, \"setup.py\", \"sdist\",",
"import subprocess import sys from . import ROOT, PY_SRC, _run,",
"= [ \"conda-build\", \"-c\", \"conda-forge\", \"--output-folder\", DIST / \"conda-bld\", ]",
"if __name__ == \"__main__\": for pkg in PY_SRC.glob(\"wxyz_*\"): _run([PY, \"setup.py\",",
"\"conda-bld\", ] if __name__ == \"__main__\": for pkg in PY_SRC.glob(\"wxyz_*\"):",
"/ \"conda-bld\", ] if __name__ == \"__main__\": for pkg in"
] |
[
"j_rsakey = re.findall(r'j_rsaKey\" value=\"(\\S+)\"', r.text, re.M)[0] s.headers.update({\"lt\": lt}) username =",
"r = s.get(redirect_url) return s if __name__ == \"__main__\": main()",
"d += int2char(c << 2 | v >> 4) d",
"\"m.cloud.189.cn\", \"Accept-Encoding\" : \"gzip, deflate\", } response = s.get(url,headers=headers) try:",
"try: response2 = s.get(url2,headers=headers) if (\"errorCode\" in response2.text): print(response.json()['errorCode']) elif",
"+= int2char(c << 2 | v >> 4) d +=",
"for i in range(len(a)): if list(a)[i] != \"=\": v =",
"= rsa_encode(j_rsakey, username) password = rsa_encode(j_rsakey, password) url = \"https://open.e.189.cn/api/logbox/oauth2/loginSubmit.do\"",
"(response2.json().has_key('description')): description = response2.json()['description'] print(f\"抽奖2获得{description}\") except: print(f\"抽奖2完成,解析时失败\") BI_RM = list(\"0123456789abcdefghijklmnopqrstuvwxyz\")",
"print(f\"抽奖获得{description}\") except: print(f\"抽奖1完成,解析时失败\") try: response2 = s.get(url2,headers=headers) if (\"errorCode\" in",
"like Gecko) Version/4.0 Chrome/74.0.3729.136 Mobile Safari/537.36 Ecloud/8.6.3 Android/22 clientId/355325117317828 clientModel/SM-G930K",
"\"Host\" : \"m.cloud.189.cn\", \"Accept-Encoding\" : \"gzip, deflate\", } response =",
"= \"(.+?)\"', r.text)[0] j_rsakey = re.findall(r'j_rsaKey\" value=\"(\\S+)\"', r.text, re.M)[0] s.headers.update({\"lt\":",
"re.findall(r\"returnUrl = '(.+?)'\", r.text)[0] paramId = re.findall(r'paramId = \"(.+?)\"', r.text)[0]",
"\"\" if(username == \"\" or password == \"\"): username =",
"= \"\" password = \"\" if(username == \"\" or password",
"password = input(\"密码:\") def main(): login(username, password) rand = str(round(time.time()*1000))",
"re.findall(r\"captchaToken' value='(.+?)'\", r.text)[0] lt = re.findall(r'lt = \"(.+?)\"', r.text)[0] returnUrl",
"else: e = 0 d += int2char(c << 2 |",
"4) d += int2char(15 & v) if e == 1:",
"d = \"\" e = 0 c = 0 for",
"= 15 & v elif 2 == e: e =",
"int2char(c << 2) return d def rsa_encode(j_rsakey, string): rsa_key =",
"deflate\", } response = s.get(surl,headers=headers) netdiskBonus = response.json()['netdiskBonus'] if(response.json()['isSign'] ==",
"except: print(f\"抽奖2完成,解析时失败\") BI_RM = list(\"0123456789abcdefghijklmnopqrstuvwxyz\") def int2char(a): return BI_RM[a] b64map",
"f\"{{<PASSWORD>}\", \"validateCode\": \"\", \"captchaToken\": captchaToken, \"returnUrl\": returnUrl, \"mailSuffix\": \"@189.cn\", \"paramId\":",
"e: e = 1 d += int2char(v >> 2) c",
"PUBLIC KEY-----\" pubkey = rsa.PublicKey.load_pkcs1_openssl_pem(rsa_key.encode()) result = b64tohex((base64.b64encode(rsa.encrypt(f'{string}'.encode(), pubkey))).decode()) return",
"\"(.+?)\"', r.text)[0] j_rsakey = re.findall(r'j_rsaKey\" value=\"(\\S+)\"', r.text, re.M)[0] s.headers.update({\"lt\": lt})",
"if(response.json()['isSign'] == \"false\"): print(f\"未签到,签到获得{netdiskBonus}M空间\") else: print(f\"已经签到过了,签到获得{netdiskBonus}M空间\") headers = { 'User-Agent':'Mozilla/5.0",
"= 3 & v else: e = 0 d +=",
"\"returnUrl\": returnUrl, \"mailSuffix\": \"@189.cn\", \"paramId\": paramId } r = s.post(url,",
"+= int2char(c << 2) return d def rsa_encode(j_rsakey, string): rsa_key",
"e = 3 d += int2char(c) d += int2char(v >>",
"Firefox/76.0', 'Referer': 'https://open.e.189.cn/', } data = { \"appKey\": \"cloud\", \"accountType\":",
"int2char(c << 2 | v >> 4) c = 15",
"15 & v elif 2 == e: e = 3",
"= r.json()['toUrl'] r = s.get(redirect_url) return s if __name__ ==",
"\"validateCode\": \"\", \"captchaToken\": captchaToken, \"returnUrl\": returnUrl, \"mailSuffix\": \"@189.cn\", \"paramId\": paramId",
"0 for i in range(len(a)): if list(a)[i] != \"=\": v",
"description = response.json()['description'] print(f\"抽奖获得{description}\") except: print(f\"抽奖1完成,解析时失败\") try: response2 = s.get(url2,headers=headers)",
"deflate\", } response = s.get(url,headers=headers) try: if (\"errorCode\" in response.text):",
"in response2.text): print(response.json()['errorCode']) elif (response2.json().has_key('description')): description = response2.json()['description'] print(f\"抽奖2获得{description}\") except:",
"return d def rsa_encode(j_rsakey, string): rsa_key = f\"-----BEGIN PUBLIC KEY-----\\n{j_rsakey}\\n-----END",
"if list(a)[i] != \"=\": v = b64map.index(list(a)[i]) if 0 ==",
": \"gzip, deflate\", } response = s.get(url,headers=headers) try: if (\"errorCode\"",
"Gecko/20100101 Firefox/76.0', 'Referer': 'https://open.e.189.cn/', } data = { \"appKey\": \"cloud\",",
"& v elif 2 == e: e = 3 d",
"pubkey = rsa.PublicKey.load_pkcs1_openssl_pem(rsa_key.encode()) result = b64tohex((base64.b64encode(rsa.encrypt(f'{string}'.encode(), pubkey))).decode()) return result def",
"s = requests.Session() username = \"\" password = \"\" if(username",
"v) if e == 1: d += int2char(c << 2)",
"| v >> 4) c = 15 & v elif",
"print(f\"抽奖2获得{description}\") except: print(f\"抽奖2完成,解析时失败\") BI_RM = list(\"0123456789abcdefghijklmnopqrstuvwxyz\") def int2char(a): return BI_RM[a]",
"\"Accept-Encoding\" : \"gzip, deflate\", } response = s.get(surl,headers=headers) netdiskBonus =",
"f\"{{RSA}}{username}\", \"password\": f\"{{<PASSWORD>}\", \"validateCode\": \"\", \"captchaToken\": captchaToken, \"returnUrl\": returnUrl, \"mailSuffix\":",
"s.get(url,headers=headers) try: if (\"errorCode\" in response.text): print(response.json()['errorCode']) elif (response.json().has_key('description')): description",
"0 == e: e = 1 d += int2char(v >>",
"re.M)[0] s.headers.update({\"lt\": lt}) username = rsa_encode(j_rsakey, username) password = rsa_encode(j_rsakey,",
"= \"https://open.e.189.cn/api/logbox/oauth2/loginSubmit.do\" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0;",
"s.get(url2,headers=headers) if (\"errorCode\" in response2.text): print(response.json()['errorCode']) elif (response2.json().has_key('description')): description =",
"PUBLIC KEY-----\\n{j_rsakey}\\n-----END PUBLIC KEY-----\" pubkey = rsa.PublicKey.load_pkcs1_openssl_pem(rsa_key.encode()) result = b64tohex((base64.b64encode(rsa.encrypt(f'{string}'.encode(),",
"list(\"0123456789abcdefghijklmnopqrstuvwxyz\") def int2char(a): return BI_RM[a] b64map = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\" def b64tohex(a):",
"if (\"errorCode\" in response.text): print(response.json()['errorCode']) elif (response.json().has_key('description')): description = response.json()['description']",
"v else: e = 0 d += int2char(c << 2",
"urllib import parse s = requests.Session() username = \"\" password",
"2) c = 3 & v else: e = 0",
"value=\"(\\S+)\"', r.text, re.M)[0] s.headers.update({\"lt\": lt}) username = rsa_encode(j_rsakey, username) password",
"= list(\"0123456789abcdefghijklmnopqrstuvwxyz\") def int2char(a): return BI_RM[a] b64map = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\" def",
"= response2.json()['description'] print(f\"抽奖2获得{description}\") except: print(f\"抽奖2完成,解析时失败\") BI_RM = list(\"0123456789abcdefghijklmnopqrstuvwxyz\") def int2char(a):",
"Android 5.1.1; SM-G930K Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0",
"= s.get(url) captchaToken = re.findall(r\"captchaToken' value='(.+?)'\", r.text)[0] lt = re.findall(r'lt",
"(\"errorCode\" in response2.text): print(response.json()['errorCode']) elif (response2.json().has_key('description')): description = response2.json()['description'] print(f\"抽奖2获得{description}\")",
"r.text)[0] returnUrl = re.findall(r\"returnUrl = '(.+?)'\", r.text)[0] paramId = re.findall(r'paramId",
"def login(username, password): url = \"https://cloud.189.cn/udb/udb_login.jsp?pageId=1&redirectURL=/main.action\" r = s.get(url) captchaToken",
"v >> 4) c = 15 & v elif 2",
"2) c = 3 & v elif 1 == e:",
"password) url = \"https://open.e.189.cn/api/logbox/oauth2/loginSubmit.do\" headers = { 'User-Agent': 'Mozilla/5.0 (Windows",
"re.findall(r'paramId = \"(.+?)\"', r.text)[0] j_rsakey = re.findall(r'j_rsaKey\" value=\"(\\S+)\"', r.text, re.M)[0]",
"print(r.json()['msg']) redirect_url = r.json()['toUrl'] r = s.get(redirect_url) return s if",
"\"Accept-Encoding\" : \"gzip, deflate\", } response = s.get(url,headers=headers) try: if",
"list(a)[i] != \"=\": v = b64map.index(list(a)[i]) if 0 == e:",
"rsa_encode(j_rsakey, username) password = rsa_encode(j_rsakey, password) url = \"https://open.e.189.cn/api/logbox/oauth2/loginSubmit.do\" headers",
"headers=headers, timeout=5) if(r.json()['result'] == 0): print(r.json()['msg']) else: print(r.json()['msg']) redirect_url =",
"from urllib import parse s = requests.Session() username = \"\"",
"r.text)[0] j_rsakey = re.findall(r'j_rsaKey\" value=\"(\\S+)\"', r.text, re.M)[0] s.headers.update({\"lt\": lt}) username",
"\"\" password = \"\" if(username == \"\" or password ==",
"+= int2char(v >> 2) c = 3 & v elif",
"e = 0 c = 0 for i in range(len(a)):",
"0 c = 0 for i in range(len(a)): if list(a)[i]",
"clientId/355325117317828 clientModel/SM-G930K imsi/460071114317824 clientChannelId/qq proVersion/1.0.6', \"Referer\" : \"https://m.cloud.189.cn/zhuanti/2016/sign/index.jsp?albumBackupOpened=1\", \"Host\" :",
">> 4) d += int2char(15 & v) if e ==",
"rsa_encode(j_rsakey, password) url = \"https://open.e.189.cn/api/logbox/oauth2/loginSubmit.do\" headers = { 'User-Agent': 'Mozilla/5.0",
"<< 2 | v >> 4) d += int2char(15 &",
"Version/4.0 Chrome/74.0.3729.136 Mobile Safari/537.36 Ecloud/8.6.3 Android/22 clientId/355325117317828 clientModel/SM-G930K imsi/460071114317824 clientChannelId/qq",
"e = 1 d += int2char(v >> 2) c =",
"parse s = requests.Session() username = \"\" password = \"\"",
"r = s.post(url, data=data, headers=headers, timeout=5) if(r.json()['result'] == 0): print(r.json()['msg'])",
"| v >> 4) d += int2char(15 & v) if",
"d += int2char(v >> 2) c = 3 & v",
"url2 = f'https://m.cloud.189.cn/v2/drawPrizeMarketDetails.action?taskId=TASK_SIGNIN_PHOTOS&activityId=ACT_SIGNIN' headers = { 'User-Agent':'Mozilla/5.0 (Linux; Android 5.1.1;",
"returnUrl, \"mailSuffix\": \"@189.cn\", \"paramId\": paramId } r = s.post(url, data=data,",
"v = b64map.index(list(a)[i]) if 0 == e: e = 1",
"captchaToken, \"returnUrl\": returnUrl, \"mailSuffix\": \"@189.cn\", \"paramId\": paramId } r =",
"= rsa.PublicKey.load_pkcs1_openssl_pem(rsa_key.encode()) result = b64tohex((base64.b64encode(rsa.encrypt(f'{string}'.encode(), pubkey))).decode()) return result def calculate_md5_sign(params):",
"1 d += int2char(v >> 2) c = 3 &",
"result = b64tohex((base64.b64encode(rsa.encrypt(f'{string}'.encode(), pubkey))).decode()) return result def calculate_md5_sign(params): return hashlib.md5('&'.join(sorted(params.split('&'))).encode('utf-8')).hexdigest()",
"= str(round(time.time()*1000)) surl = f'https://api.cloud.189.cn/mkt/userSign.action?rand={rand}&clientType=TELEANDROID&version=8.6.3&model=SM-G930K' url = f'https://m.cloud.189.cn/v2/drawPrizeMarketDetails.action?taskId=TASK_SIGNIN&activityId=ACT_SIGNIN' url2 =",
"+= int2char(v >> 2) c = 3 & v else:",
"b64map.index(list(a)[i]) if 0 == e: e = 1 d +=",
"(KHTML, like Gecko) Version/4.0 Chrome/74.0.3729.136 Mobile Safari/537.36 Ecloud/8.6.3 Android/22 clientId/355325117317828",
"int2char(v >> 2) c = 3 & v elif 1",
"def calculate_md5_sign(params): return hashlib.md5('&'.join(sorted(params.split('&'))).encode('utf-8')).hexdigest() def login(username, password): url = \"https://cloud.189.cn/udb/udb_login.jsp?pageId=1&redirectURL=/main.action\"",
"BI_RM = list(\"0123456789abcdefghijklmnopqrstuvwxyz\") def int2char(a): return BI_RM[a] b64map = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"",
"requests, time, re, rsa, json, base64 from urllib import parse",
"2 d += int2char(c << 2 | v >> 4)",
"+= int2char(c) d += int2char(v >> 2) c = 3",
"= b64tohex((base64.b64encode(rsa.encrypt(f'{string}'.encode(), pubkey))).decode()) return result def calculate_md5_sign(params): return hashlib.md5('&'.join(sorted(params.split('&'))).encode('utf-8')).hexdigest() def",
"2 == e: e = 3 d += int2char(c) d",
"returnUrl = re.findall(r\"returnUrl = '(.+?)'\", r.text)[0] paramId = re.findall(r'paramId =",
"or password == \"\"): username = input(\"账号:\") password = input(\"密码:\")",
"paramId = re.findall(r'paramId = \"(.+?)\"', r.text)[0] j_rsakey = re.findall(r'j_rsaKey\" value=\"(\\S+)\"',",
"response = s.get(url,headers=headers) try: if (\"errorCode\" in response.text): print(response.json()['errorCode']) elif",
"= b64map.index(list(a)[i]) if 0 == e: e = 1 d",
"int2char(15 & v) if e == 1: d += int2char(c",
"} data = { \"appKey\": \"cloud\", \"accountType\": '01', \"userName\": f\"{{RSA}}{username}\",",
"print(f\"已经签到过了,签到获得{netdiskBonus}M空间\") headers = { 'User-Agent':'Mozilla/5.0 (Linux; Android 5.1.1; SM-G930K Build/NRD90M;",
"\"https://m.cloud.189.cn/zhuanti/2016/sign/index.jsp?albumBackupOpened=1\", \"Host\" : \"m.cloud.189.cn\", \"Accept-Encoding\" : \"gzip, deflate\", } response",
"!= \"=\": v = b64map.index(list(a)[i]) if 0 == e: e",
"\"\", \"captchaToken\": captchaToken, \"returnUrl\": returnUrl, \"mailSuffix\": \"@189.cn\", \"paramId\": paramId }",
"(response.json().has_key('description')): description = response.json()['description'] print(f\"抽奖获得{description}\") except: print(f\"抽奖1完成,解析时失败\") try: response2 =",
"proVersion/1.0.6', \"Referer\" : \"https://m.cloud.189.cn/zhuanti/2016/sign/index.jsp?albumBackupOpened=1\", \"Host\" : \"m.cloud.189.cn\", \"Accept-Encoding\" : \"gzip,",
"import requests, time, re, rsa, json, base64 from urllib import",
"s.get(surl,headers=headers) netdiskBonus = response.json()['netdiskBonus'] if(response.json()['isSign'] == \"false\"): print(f\"未签到,签到获得{netdiskBonus}M空间\") else: print(f\"已经签到过了,签到获得{netdiskBonus}M空间\")",
"response.text): print(response.json()['errorCode']) elif (response.json().has_key('description')): description = response.json()['description'] print(f\"抽奖获得{description}\") except: print(f\"抽奖1完成,解析时失败\")",
"rand = str(round(time.time()*1000)) surl = f'https://api.cloud.189.cn/mkt/userSign.action?rand={rand}&clientType=TELEANDROID&version=8.6.3&model=SM-G930K' url = f'https://m.cloud.189.cn/v2/drawPrizeMarketDetails.action?taskId=TASK_SIGNIN&activityId=ACT_SIGNIN' url2",
"= re.findall(r'paramId = \"(.+?)\"', r.text)[0] j_rsakey = re.findall(r'j_rsaKey\" value=\"(\\S+)\"', r.text,",
"input(\"账号:\") password = input(\"密码:\") def main(): login(username, password) rand =",
"username = \"\" password = \"\" if(username == \"\" or",
"r.text)[0] paramId = re.findall(r'paramId = \"(.+?)\"', r.text)[0] j_rsakey = re.findall(r'j_rsaKey\"",
"= response.json()['description'] print(f\"抽奖获得{description}\") except: print(f\"抽奖1完成,解析时失败\") try: response2 = s.get(url2,headers=headers) if",
"password = \"\" if(username == \"\" or password == \"\"):",
"surl = f'https://api.cloud.189.cn/mkt/userSign.action?rand={rand}&clientType=TELEANDROID&version=8.6.3&model=SM-G930K' url = f'https://m.cloud.189.cn/v2/drawPrizeMarketDetails.action?taskId=TASK_SIGNIN&activityId=ACT_SIGNIN' url2 = f'https://m.cloud.189.cn/v2/drawPrizeMarketDetails.action?taskId=TASK_SIGNIN_PHOTOS&activityId=ACT_SIGNIN' headers",
"= 0 for i in range(len(a)): if list(a)[i] != \"=\":",
"username = input(\"账号:\") password = input(\"密码:\") def main(): login(username, password)",
"f'https://api.cloud.189.cn/mkt/userSign.action?rand={rand}&clientType=TELEANDROID&version=8.6.3&model=SM-G930K' url = f'https://m.cloud.189.cn/v2/drawPrizeMarketDetails.action?taskId=TASK_SIGNIN&activityId=ACT_SIGNIN' url2 = f'https://m.cloud.189.cn/v2/drawPrizeMarketDetails.action?taskId=TASK_SIGNIN_PHOTOS&activityId=ACT_SIGNIN' headers = {",
"= response.json()['netdiskBonus'] if(response.json()['isSign'] == \"false\"): print(f\"未签到,签到获得{netdiskBonus}M空间\") else: print(f\"已经签到过了,签到获得{netdiskBonus}M空间\") headers =",
"= input(\"账号:\") password = input(\"密码:\") def main(): login(username, password) rand",
"s.headers.update({\"lt\": lt}) username = rsa_encode(j_rsakey, username) password = rsa_encode(j_rsakey, password)",
"login(username, password) rand = str(round(time.time()*1000)) surl = f'https://api.cloud.189.cn/mkt/userSign.action?rand={rand}&clientType=TELEANDROID&version=8.6.3&model=SM-G930K' url =",
"= { 'User-Agent':'Mozilla/5.0 (Linux; Android 5.1.1; SM-G930K Build/NRD90M; wv) AppleWebKit/537.36",
"== \"false\"): print(f\"未签到,签到获得{netdiskBonus}M空间\") else: print(f\"已经签到过了,签到获得{netdiskBonus}M空间\") headers = { 'User-Agent':'Mozilla/5.0 (Linux;",
"\"mailSuffix\": \"@189.cn\", \"paramId\": paramId } r = s.post(url, data=data, headers=headers,",
"rv:74.0) Gecko/20100101 Firefox/76.0', 'Referer': 'https://open.e.189.cn/', } data = { \"appKey\":",
">> 2) c = 3 & v elif 1 ==",
"'https://open.e.189.cn/', } data = { \"appKey\": \"cloud\", \"accountType\": '01', \"userName\":",
"if(r.json()['result'] == 0): print(r.json()['msg']) else: print(r.json()['msg']) redirect_url = r.json()['toUrl'] r",
"v >> 4) d += int2char(15 & v) if e",
"response.json()['description'] print(f\"抽奖获得{description}\") except: print(f\"抽奖1完成,解析时失败\") try: response2 = s.get(url2,headers=headers) if (\"errorCode\"",
"e == 1: d += int2char(c << 2) return d",
"base64 from urllib import parse s = requests.Session() username =",
"= f'https://m.cloud.189.cn/v2/drawPrizeMarketDetails.action?taskId=TASK_SIGNIN_PHOTOS&activityId=ACT_SIGNIN' headers = { 'User-Agent':'Mozilla/5.0 (Linux; Android 5.1.1; SM-G930K",
"d += int2char(c << 2) return d def rsa_encode(j_rsakey, string):",
"\"\"): username = input(\"账号:\") password = input(\"密码:\") def main(): login(username,",
"rsa_key = f\"-----BEGIN PUBLIC KEY-----\\n{j_rsakey}\\n-----END PUBLIC KEY-----\" pubkey = rsa.PublicKey.load_pkcs1_openssl_pem(rsa_key.encode())",
"= re.findall(r'lt = \"(.+?)\"', r.text)[0] returnUrl = re.findall(r\"returnUrl = '(.+?)'\",",
"= re.findall(r\"captchaToken' value='(.+?)'\", r.text)[0] lt = re.findall(r'lt = \"(.+?)\"', r.text)[0]",
"username) password = rsa_encode(j_rsakey, password) url = \"https://open.e.189.cn/api/logbox/oauth2/loginSubmit.do\" headers =",
"\"\" e = 0 c = 0 for i in",
"f\"-----BEGIN PUBLIC KEY-----\\n{j_rsakey}\\n-----END PUBLIC KEY-----\" pubkey = rsa.PublicKey.load_pkcs1_openssl_pem(rsa_key.encode()) result =",
"= \"\" e = 0 c = 0 for i",
"(Linux; Android 5.1.1; SM-G930K Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko)",
"lt}) username = rsa_encode(j_rsakey, username) password = rsa_encode(j_rsakey, password) url",
"re.findall(r'j_rsaKey\" value=\"(\\S+)\"', r.text, re.M)[0] s.headers.update({\"lt\": lt}) username = rsa_encode(j_rsakey, username)",
"clientChannelId/qq proVersion/1.0.6', \"Referer\" : \"https://m.cloud.189.cn/zhuanti/2016/sign/index.jsp?albumBackupOpened=1\", \"Host\" : \"m.cloud.189.cn\", \"Accept-Encoding\" :",
"= 3 d += int2char(c) d += int2char(v >> 2)",
"\"appKey\": \"cloud\", \"accountType\": '01', \"userName\": f\"{{RSA}}{username}\", \"password\": f\"{{<PASSWORD>}\", \"validateCode\": \"\",",
"s.get(url) captchaToken = re.findall(r\"captchaToken' value='(.+?)'\", r.text)[0] lt = re.findall(r'lt =",
"netdiskBonus = response.json()['netdiskBonus'] if(response.json()['isSign'] == \"false\"): print(f\"未签到,签到获得{netdiskBonus}M空间\") else: print(f\"已经签到过了,签到获得{netdiskBonus}M空间\") headers",
"} r = s.post(url, data=data, headers=headers, timeout=5) if(r.json()['result'] == 0):",
"= 0 c = 0 for i in range(len(a)): if",
">> 2) c = 3 & v else: e =",
"rsa.PublicKey.load_pkcs1_openssl_pem(rsa_key.encode()) result = b64tohex((base64.b64encode(rsa.encrypt(f'{string}'.encode(), pubkey))).decode()) return result def calculate_md5_sign(params): return",
"= input(\"密码:\") def main(): login(username, password) rand = str(round(time.time()*1000)) surl",
"== \"\"): username = input(\"账号:\") password = input(\"密码:\") def main():",
"def main(): login(username, password) rand = str(round(time.time()*1000)) surl = f'https://api.cloud.189.cn/mkt/userSign.action?rand={rand}&clientType=TELEANDROID&version=8.6.3&model=SM-G930K'",
"= \"https://cloud.189.cn/udb/udb_login.jsp?pageId=1&redirectURL=/main.action\" r = s.get(url) captchaToken = re.findall(r\"captchaToken' value='(.+?)'\", r.text)[0]",
"d += int2char(c) d += int2char(v >> 2) c =",
"re, rsa, json, base64 from urllib import parse s =",
"= s.get(url,headers=headers) try: if (\"errorCode\" in response.text): print(response.json()['errorCode']) elif (response.json().has_key('description')):",
"0): print(r.json()['msg']) else: print(r.json()['msg']) redirect_url = r.json()['toUrl'] r = s.get(redirect_url)",
"requests.Session() username = \"\" password = \"\" if(username == \"\"",
"\"\" or password == \"\"): username = input(\"账号:\") password =",
"b64tohex((base64.b64encode(rsa.encrypt(f'{string}'.encode(), pubkey))).decode()) return result def calculate_md5_sign(params): return hashlib.md5('&'.join(sorted(params.split('&'))).encode('utf-8')).hexdigest() def login(username,",
"response = s.get(surl,headers=headers) netdiskBonus = response.json()['netdiskBonus'] if(response.json()['isSign'] == \"false\"): print(f\"未签到,签到获得{netdiskBonus}M空间\")",
"(Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/76.0', 'Referer': 'https://open.e.189.cn/',",
"= 3 & v elif 1 == e: e =",
"value='(.+?)'\", r.text)[0] lt = re.findall(r'lt = \"(.+?)\"', r.text)[0] returnUrl =",
"\"paramId\": paramId } r = s.post(url, data=data, headers=headers, timeout=5) if(r.json()['result']",
"= \"(.+?)\"', r.text)[0] returnUrl = re.findall(r\"returnUrl = '(.+?)'\", r.text)[0] paramId",
"if 0 == e: e = 1 d += int2char(v",
"\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\" def b64tohex(a): d = \"\" e = 0 c",
"in response.text): print(response.json()['errorCode']) elif (response.json().has_key('description')): description = response.json()['description'] print(f\"抽奖获得{description}\") except:",
"b64map = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\" def b64tohex(a): d = \"\" e =",
"2 | v >> 4) d += int2char(15 & v)",
"= f'https://api.cloud.189.cn/mkt/userSign.action?rand={rand}&clientType=TELEANDROID&version=8.6.3&model=SM-G930K' url = f'https://m.cloud.189.cn/v2/drawPrizeMarketDetails.action?taskId=TASK_SIGNIN&activityId=ACT_SIGNIN' url2 = f'https://m.cloud.189.cn/v2/drawPrizeMarketDetails.action?taskId=TASK_SIGNIN_PHOTOS&activityId=ACT_SIGNIN' headers =",
"BI_RM[a] b64map = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\" def b64tohex(a): d = \"\" e",
"2 | v >> 4) c = 15 & v",
"result def calculate_md5_sign(params): return hashlib.md5('&'.join(sorted(params.split('&'))).encode('utf-8')).hexdigest() def login(username, password): url =",
"json, base64 from urllib import parse s = requests.Session() username",
"captchaToken = re.findall(r\"captchaToken' value='(.+?)'\", r.text)[0] lt = re.findall(r'lt = \"(.+?)\"',",
"rsa, json, base64 from urllib import parse s = requests.Session()",
"range(len(a)): if list(a)[i] != \"=\": v = b64map.index(list(a)[i]) if 0",
"re.findall(r'lt = \"(.+?)\"', r.text)[0] returnUrl = re.findall(r\"returnUrl = '(.+?)'\", r.text)[0]",
"description = response2.json()['description'] print(f\"抽奖2获得{description}\") except: print(f\"抽奖2完成,解析时失败\") BI_RM = list(\"0123456789abcdefghijklmnopqrstuvwxyz\") def",
"r = s.get(url) captchaToken = re.findall(r\"captchaToken' value='(.+?)'\", r.text)[0] lt =",
"password): url = \"https://cloud.189.cn/udb/udb_login.jsp?pageId=1&redirectURL=/main.action\" r = s.get(url) captchaToken = re.findall(r\"captchaToken'",
"response.json()['netdiskBonus'] if(response.json()['isSign'] == \"false\"): print(f\"未签到,签到获得{netdiskBonus}M空间\") else: print(f\"已经签到过了,签到获得{netdiskBonus}M空间\") headers = {",
"Chrome/74.0.3729.136 Mobile Safari/537.36 Ecloud/8.6.3 Android/22 clientId/355325117317828 clientModel/SM-G930K imsi/460071114317824 clientChannelId/qq proVersion/1.0.6',",
"10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/76.0', 'Referer': 'https://open.e.189.cn/', } data",
"{ 'User-Agent':'Mozilla/5.0 (Linux; Android 5.1.1; SM-G930K Build/NRD90M; wv) AppleWebKit/537.36 (KHTML,",
"5.1.1; SM-G930K Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/74.0.3729.136",
"\"m.cloud.189.cn\", \"Accept-Encoding\" : \"gzip, deflate\", } response = s.get(surl,headers=headers) netdiskBonus",
"int2char(v >> 2) c = 3 & v else: e",
"\"https://open.e.189.cn/api/logbox/oauth2/loginSubmit.do\" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64;",
"== e: e = 1 d += int2char(v >> 2)",
"elif 1 == e: e = 2 d += int2char(c",
"rsa_encode(j_rsakey, string): rsa_key = f\"-----BEGIN PUBLIC KEY-----\\n{j_rsakey}\\n-----END PUBLIC KEY-----\" pubkey",
"imsi/460071114317824 clientChannelId/qq proVersion/1.0.6', \"Referer\" : \"https://m.cloud.189.cn/zhuanti/2016/sign/index.jsp?albumBackupOpened=1\", \"Host\" : \"m.cloud.189.cn\", \"Accept-Encoding\"",
"\"=\": v = b64map.index(list(a)[i]) if 0 == e: e =",
"1 == e: e = 2 d += int2char(c <<",
"Gecko) Version/4.0 Chrome/74.0.3729.136 Mobile Safari/537.36 Ecloud/8.6.3 Android/22 clientId/355325117317828 clientModel/SM-G930K imsi/460071114317824",
"d def rsa_encode(j_rsakey, string): rsa_key = f\"-----BEGIN PUBLIC KEY-----\\n{j_rsakey}\\n-----END PUBLIC",
"if(username == \"\" or password == \"\"): username = input(\"账号:\")",
"wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/74.0.3729.136 Mobile Safari/537.36 Ecloud/8.6.3",
"input(\"密码:\") def main(): login(username, password) rand = str(round(time.time()*1000)) surl =",
"i in range(len(a)): if list(a)[i] != \"=\": v = b64map.index(list(a)[i])",
"username = rsa_encode(j_rsakey, username) password = rsa_encode(j_rsakey, password) url =",
"== \"\" or password == \"\"): username = input(\"账号:\") password",
"print(r.json()['msg']) else: print(r.json()['msg']) redirect_url = r.json()['toUrl'] r = s.get(redirect_url) return",
"elif 2 == e: e = 3 d += int2char(c)",
"main(): login(username, password) rand = str(round(time.time()*1000)) surl = f'https://api.cloud.189.cn/mkt/userSign.action?rand={rand}&clientType=TELEANDROID&version=8.6.3&model=SM-G930K' url",
"= 1 d += int2char(v >> 2) c = 3",
"return BI_RM[a] b64map = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\" def b64tohex(a): d = \"\"",
"elif (response2.json().has_key('description')): description = response2.json()['description'] print(f\"抽奖2获得{description}\") except: print(f\"抽奖2完成,解析时失败\") BI_RM =",
"= requests.Session() username = \"\" password = \"\" if(username ==",
"f'https://m.cloud.189.cn/v2/drawPrizeMarketDetails.action?taskId=TASK_SIGNIN_PHOTOS&activityId=ACT_SIGNIN' headers = { 'User-Agent':'Mozilla/5.0 (Linux; Android 5.1.1; SM-G930K Build/NRD90M;",
"+= int2char(15 & v) if e == 1: d +=",
"(\"errorCode\" in response.text): print(response.json()['errorCode']) elif (response.json().has_key('description')): description = response.json()['description'] print(f\"抽奖获得{description}\")",
"& v else: e = 0 d += int2char(c <<",
": \"gzip, deflate\", } response = s.get(surl,headers=headers) netdiskBonus = response.json()['netdiskBonus']",
"def rsa_encode(j_rsakey, string): rsa_key = f\"-----BEGIN PUBLIC KEY-----\\n{j_rsakey}\\n-----END PUBLIC KEY-----\"",
"1: d += int2char(c << 2) return d def rsa_encode(j_rsakey,",
"f'https://m.cloud.189.cn/v2/drawPrizeMarketDetails.action?taskId=TASK_SIGNIN&activityId=ACT_SIGNIN' url2 = f'https://m.cloud.189.cn/v2/drawPrizeMarketDetails.action?taskId=TASK_SIGNIN_PHOTOS&activityId=ACT_SIGNIN' headers = { 'User-Agent':'Mozilla/5.0 (Linux; Android",
"except: print(f\"抽奖1完成,解析时失败\") try: response2 = s.get(url2,headers=headers) if (\"errorCode\" in response2.text):",
"\"password\": f\"{{<PASSWORD>}\", \"validateCode\": \"\", \"captchaToken\": captchaToken, \"returnUrl\": returnUrl, \"mailSuffix\": \"@189.cn\",",
"'(.+?)'\", r.text)[0] paramId = re.findall(r'paramId = \"(.+?)\"', r.text)[0] j_rsakey =",
"x64; rv:74.0) Gecko/20100101 Firefox/76.0', 'Referer': 'https://open.e.189.cn/', } data = {",
"'01', \"userName\": f\"{{RSA}}{username}\", \"password\": f\"{{<PASSWORD>}\", \"validateCode\": \"\", \"captchaToken\": captchaToken, \"returnUrl\":",
"import parse s = requests.Session() username = \"\" password =",
"str(round(time.time()*1000)) surl = f'https://api.cloud.189.cn/mkt/userSign.action?rand={rand}&clientType=TELEANDROID&version=8.6.3&model=SM-G930K' url = f'https://m.cloud.189.cn/v2/drawPrizeMarketDetails.action?taskId=TASK_SIGNIN&activityId=ACT_SIGNIN' url2 = f'https://m.cloud.189.cn/v2/drawPrizeMarketDetails.action?taskId=TASK_SIGNIN_PHOTOS&activityId=ACT_SIGNIN'",
"SM-G930K Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/74.0.3729.136 Mobile",
"print(f\"抽奖1完成,解析时失败\") try: response2 = s.get(url2,headers=headers) if (\"errorCode\" in response2.text): print(response.json()['errorCode'])",
"3 & v elif 1 == e: e = 2",
"if e == 1: d += int2char(c << 2) return",
"== 1: d += int2char(c << 2) return d def",
"\"gzip, deflate\", } response = s.get(url,headers=headers) try: if (\"errorCode\" in",
"headers = { 'User-Agent':'Mozilla/5.0 (Linux; Android 5.1.1; SM-G930K Build/NRD90M; wv)",
"KEY-----\\n{j_rsakey}\\n-----END PUBLIC KEY-----\" pubkey = rsa.PublicKey.load_pkcs1_openssl_pem(rsa_key.encode()) result = b64tohex((base64.b64encode(rsa.encrypt(f'{string}'.encode(), pubkey))).decode())",
"data = { \"appKey\": \"cloud\", \"accountType\": '01', \"userName\": f\"{{RSA}}{username}\", \"password\":",
"3 d += int2char(c) d += int2char(v >> 2) c",
"return result def calculate_md5_sign(params): return hashlib.md5('&'.join(sorted(params.split('&'))).encode('utf-8')).hexdigest() def login(username, password): url",
"pubkey))).decode()) return result def calculate_md5_sign(params): return hashlib.md5('&'.join(sorted(params.split('&'))).encode('utf-8')).hexdigest() def login(username, password):",
"def b64tohex(a): d = \"\" e = 0 c =",
"\"accountType\": '01', \"userName\": f\"{{RSA}}{username}\", \"password\": f\"{{<PASSWORD>}\", \"validateCode\": \"\", \"captchaToken\": captchaToken,",
"e = 2 d += int2char(c << 2 | v",
"\"https://cloud.189.cn/udb/udb_login.jsp?pageId=1&redirectURL=/main.action\" r = s.get(url) captchaToken = re.findall(r\"captchaToken' value='(.+?)'\", r.text)[0] lt",
"calculate_md5_sign(params): return hashlib.md5('&'.join(sorted(params.split('&'))).encode('utf-8')).hexdigest() def login(username, password): url = \"https://cloud.189.cn/udb/udb_login.jsp?pageId=1&redirectURL=/main.action\" r",
"headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64;",
"& v elif 1 == e: e = 2 d",
"AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/74.0.3729.136 Mobile Safari/537.36 Ecloud/8.6.3 Android/22",
"= \"\" if(username == \"\" or password == \"\"): username",
"\"gzip, deflate\", } response = s.get(surl,headers=headers) netdiskBonus = response.json()['netdiskBonus'] if(response.json()['isSign']",
"c = 3 & v else: e = 0 d",
"<< 2 | v >> 4) c = 15 &",
"r.json()['toUrl'] r = s.get(redirect_url) return s if __name__ == \"__main__\":",
"<gh_stars>1-10 import requests, time, re, rsa, json, base64 from urllib",
">> 4) c = 15 & v elif 2 ==",
"= re.findall(r\"returnUrl = '(.+?)'\", r.text)[0] paramId = re.findall(r'paramId = \"(.+?)\"',",
"else: print(r.json()['msg']) redirect_url = r.json()['toUrl'] r = s.get(redirect_url) return s",
": \"m.cloud.189.cn\", \"Accept-Encoding\" : \"gzip, deflate\", } response = s.get(url,headers=headers)",
"login(username, password): url = \"https://cloud.189.cn/udb/udb_login.jsp?pageId=1&redirectURL=/main.action\" r = s.get(url) captchaToken =",
"== 0): print(r.json()['msg']) else: print(r.json()['msg']) redirect_url = r.json()['toUrl'] r =",
"{ \"appKey\": \"cloud\", \"accountType\": '01', \"userName\": f\"{{RSA}}{username}\", \"password\": f\"{{<PASSWORD>}\", \"validateCode\":",
"{ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101",
"b64tohex(a): d = \"\" e = 0 c = 0",
"r.text, re.M)[0] s.headers.update({\"lt\": lt}) username = rsa_encode(j_rsakey, username) password =",
"Safari/537.36 Ecloud/8.6.3 Android/22 clientId/355325117317828 clientModel/SM-G930K imsi/460071114317824 clientChannelId/qq proVersion/1.0.6', \"Referer\" :",
"\"userName\": f\"{{RSA}}{username}\", \"password\": f\"{{<PASSWORD>}\", \"validateCode\": \"\", \"captchaToken\": captchaToken, \"returnUrl\": returnUrl,",
"c = 15 & v elif 2 == e: e",
"paramId } r = s.post(url, data=data, headers=headers, timeout=5) if(r.json()['result'] ==",
"clientModel/SM-G930K imsi/460071114317824 clientChannelId/qq proVersion/1.0.6', \"Referer\" : \"https://m.cloud.189.cn/zhuanti/2016/sign/index.jsp?albumBackupOpened=1\", \"Host\" : \"m.cloud.189.cn\",",
"print(response.json()['errorCode']) elif (response.json().has_key('description')): description = response.json()['description'] print(f\"抽奖获得{description}\") except: print(f\"抽奖1完成,解析时失败\") try:",
"s.post(url, data=data, headers=headers, timeout=5) if(r.json()['result'] == 0): print(r.json()['msg']) else: print(r.json()['msg'])",
"= { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0)",
"Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/74.0.3729.136 Mobile Safari/537.36",
"= s.get(url2,headers=headers) if (\"errorCode\" in response2.text): print(response.json()['errorCode']) elif (response2.json().has_key('description')): description",
"= s.post(url, data=data, headers=headers, timeout=5) if(r.json()['result'] == 0): print(r.json()['msg']) else:",
"'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/76.0', 'Referer':",
"in range(len(a)): if list(a)[i] != \"=\": v = b64map.index(list(a)[i]) if",
"= f\"-----BEGIN PUBLIC KEY-----\\n{j_rsakey}\\n-----END PUBLIC KEY-----\" pubkey = rsa.PublicKey.load_pkcs1_openssl_pem(rsa_key.encode()) result",
"= s.get(surl,headers=headers) netdiskBonus = response.json()['netdiskBonus'] if(response.json()['isSign'] == \"false\"): print(f\"未签到,签到获得{netdiskBonus}M空间\") else:",
"= 0 d += int2char(c << 2 | v >>",
"KEY-----\" pubkey = rsa.PublicKey.load_pkcs1_openssl_pem(rsa_key.encode()) result = b64tohex((base64.b64encode(rsa.encrypt(f'{string}'.encode(), pubkey))).decode()) return result",
"url = \"https://open.e.189.cn/api/logbox/oauth2/loginSubmit.do\" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT",
"int2char(c << 2 | v >> 4) d += int2char(15",
"r.text)[0] lt = re.findall(r'lt = \"(.+?)\"', r.text)[0] returnUrl = re.findall(r\"returnUrl",
"== e: e = 3 d += int2char(c) d +=",
"c = 0 for i in range(len(a)): if list(a)[i] !=",
"e: e = 3 d += int2char(c) d += int2char(v",
"= f'https://m.cloud.189.cn/v2/drawPrizeMarketDetails.action?taskId=TASK_SIGNIN&activityId=ACT_SIGNIN' url2 = f'https://m.cloud.189.cn/v2/drawPrizeMarketDetails.action?taskId=TASK_SIGNIN_PHOTOS&activityId=ACT_SIGNIN' headers = { 'User-Agent':'Mozilla/5.0 (Linux;",
"'User-Agent':'Mozilla/5.0 (Linux; Android 5.1.1; SM-G930K Build/NRD90M; wv) AppleWebKit/537.36 (KHTML, like",
"time, re, rsa, json, base64 from urllib import parse s",
"lt = re.findall(r'lt = \"(.+?)\"', r.text)[0] returnUrl = re.findall(r\"returnUrl =",
"e = 0 d += int2char(c << 2 | v",
"= 2 d += int2char(c << 2 | v >>",
": \"m.cloud.189.cn\", \"Accept-Encoding\" : \"gzip, deflate\", } response = s.get(surl,headers=headers)",
": \"https://m.cloud.189.cn/zhuanti/2016/sign/index.jsp?albumBackupOpened=1\", \"Host\" : \"m.cloud.189.cn\", \"Accept-Encoding\" : \"gzip, deflate\", }",
"string): rsa_key = f\"-----BEGIN PUBLIC KEY-----\\n{j_rsakey}\\n-----END PUBLIC KEY-----\" pubkey =",
"& v) if e == 1: d += int2char(c <<",
"\"(.+?)\"', r.text)[0] returnUrl = re.findall(r\"returnUrl = '(.+?)'\", r.text)[0] paramId =",
"3 & v else: e = 0 d += int2char(c",
"= \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\" def b64tohex(a): d = \"\" e = 0",
"print(response.json()['errorCode']) elif (response2.json().has_key('description')): description = response2.json()['description'] print(f\"抽奖2获得{description}\") except: print(f\"抽奖2完成,解析时失败\") BI_RM",
"print(f\"抽奖2完成,解析时失败\") BI_RM = list(\"0123456789abcdefghijklmnopqrstuvwxyz\") def int2char(a): return BI_RM[a] b64map =",
"if (\"errorCode\" in response2.text): print(response.json()['errorCode']) elif (response2.json().has_key('description')): description = response2.json()['description']",
"timeout=5) if(r.json()['result'] == 0): print(r.json()['msg']) else: print(r.json()['msg']) redirect_url = r.json()['toUrl']",
"'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/76.0',",
"= { \"appKey\": \"cloud\", \"accountType\": '01', \"userName\": f\"{{RSA}}{username}\", \"password\": f\"{{<PASSWORD>}\",",
"d += int2char(c << 2 | v >> 4) c",
"v elif 2 == e: e = 3 d +=",
"} response = s.get(surl,headers=headers) netdiskBonus = response.json()['netdiskBonus'] if(response.json()['isSign'] == \"false\"):",
"hashlib.md5('&'.join(sorted(params.split('&'))).encode('utf-8')).hexdigest() def login(username, password): url = \"https://cloud.189.cn/udb/udb_login.jsp?pageId=1&redirectURL=/main.action\" r = s.get(url)",
"Mobile Safari/537.36 Ecloud/8.6.3 Android/22 clientId/355325117317828 clientModel/SM-G930K imsi/460071114317824 clientChannelId/qq proVersion/1.0.6', \"Referer\"",
"url = f'https://m.cloud.189.cn/v2/drawPrizeMarketDetails.action?taskId=TASK_SIGNIN&activityId=ACT_SIGNIN' url2 = f'https://m.cloud.189.cn/v2/drawPrizeMarketDetails.action?taskId=TASK_SIGNIN_PHOTOS&activityId=ACT_SIGNIN' headers = { 'User-Agent':'Mozilla/5.0",
"\"false\"): print(f\"未签到,签到获得{netdiskBonus}M空间\") else: print(f\"已经签到过了,签到获得{netdiskBonus}M空间\") headers = { 'User-Agent':'Mozilla/5.0 (Linux; Android",
"0 d += int2char(c << 2 | v >> 4)",
"d += int2char(15 & v) if e == 1: d",
"= rsa_encode(j_rsakey, password) url = \"https://open.e.189.cn/api/logbox/oauth2/loginSubmit.do\" headers = { 'User-Agent':",
"else: print(f\"已经签到过了,签到获得{netdiskBonus}M空间\") headers = { 'User-Agent':'Mozilla/5.0 (Linux; Android 5.1.1; SM-G930K",
"NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/76.0', 'Referer': 'https://open.e.189.cn/', }",
"Android/22 clientId/355325117317828 clientModel/SM-G930K imsi/460071114317824 clientChannelId/qq proVersion/1.0.6', \"Referer\" : \"https://m.cloud.189.cn/zhuanti/2016/sign/index.jsp?albumBackupOpened=1\", \"Host\"",
"try: if (\"errorCode\" in response.text): print(response.json()['errorCode']) elif (response.json().has_key('description')): description =",
"Ecloud/8.6.3 Android/22 clientId/355325117317828 clientModel/SM-G930K imsi/460071114317824 clientChannelId/qq proVersion/1.0.6', \"Referer\" : \"https://m.cloud.189.cn/zhuanti/2016/sign/index.jsp?albumBackupOpened=1\",",
"Win64; x64; rv:74.0) Gecko/20100101 Firefox/76.0', 'Referer': 'https://open.e.189.cn/', } data =",
"password == \"\"): username = input(\"账号:\") password = input(\"密码:\") def",
"response2.json()['description'] print(f\"抽奖2获得{description}\") except: print(f\"抽奖2完成,解析时失败\") BI_RM = list(\"0123456789abcdefghijklmnopqrstuvwxyz\") def int2char(a): return",
"elif (response.json().has_key('description')): description = response.json()['description'] print(f\"抽奖获得{description}\") except: print(f\"抽奖1完成,解析时失败\") try: response2",
"e: e = 2 d += int2char(c << 2 |",
"int2char(a): return BI_RM[a] b64map = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\" def b64tohex(a): d =",
"4) c = 15 & v elif 2 == e:",
"'Referer': 'https://open.e.189.cn/', } data = { \"appKey\": \"cloud\", \"accountType\": '01',",
"+= int2char(c << 2 | v >> 4) c =",
"redirect_url = r.json()['toUrl'] r = s.get(redirect_url) return s if __name__",
"return hashlib.md5('&'.join(sorted(params.split('&'))).encode('utf-8')).hexdigest() def login(username, password): url = \"https://cloud.189.cn/udb/udb_login.jsp?pageId=1&redirectURL=/main.action\" r =",
"<< 2) return d def rsa_encode(j_rsakey, string): rsa_key = f\"-----BEGIN",
"response2 = s.get(url2,headers=headers) if (\"errorCode\" in response2.text): print(response.json()['errorCode']) elif (response2.json().has_key('description')):",
"\"cloud\", \"accountType\": '01', \"userName\": f\"{{RSA}}{username}\", \"password\": f\"{{<PASSWORD>}\", \"validateCode\": \"\", \"captchaToken\":",
"c = 3 & v elif 1 == e: e",
"== e: e = 2 d += int2char(c << 2",
"password) rand = str(round(time.time()*1000)) surl = f'https://api.cloud.189.cn/mkt/userSign.action?rand={rand}&clientType=TELEANDROID&version=8.6.3&model=SM-G930K' url = f'https://m.cloud.189.cn/v2/drawPrizeMarketDetails.action?taskId=TASK_SIGNIN&activityId=ACT_SIGNIN'",
"2) return d def rsa_encode(j_rsakey, string): rsa_key = f\"-----BEGIN PUBLIC",
"response2.text): print(response.json()['errorCode']) elif (response2.json().has_key('description')): description = response2.json()['description'] print(f\"抽奖2获得{description}\") except: print(f\"抽奖2完成,解析时失败\")",
"\"@189.cn\", \"paramId\": paramId } r = s.post(url, data=data, headers=headers, timeout=5)",
"print(f\"未签到,签到获得{netdiskBonus}M空间\") else: print(f\"已经签到过了,签到获得{netdiskBonus}M空间\") headers = { 'User-Agent':'Mozilla/5.0 (Linux; Android 5.1.1;",
"= re.findall(r'j_rsaKey\" value=\"(\\S+)\"', r.text, re.M)[0] s.headers.update({\"lt\": lt}) username = rsa_encode(j_rsakey,",
"\"Referer\" : \"https://m.cloud.189.cn/zhuanti/2016/sign/index.jsp?albumBackupOpened=1\", \"Host\" : \"m.cloud.189.cn\", \"Accept-Encoding\" : \"gzip, deflate\",",
"= '(.+?)'\", r.text)[0] paramId = re.findall(r'paramId = \"(.+?)\"', r.text)[0] j_rsakey",
"} response = s.get(url,headers=headers) try: if (\"errorCode\" in response.text): print(response.json()['errorCode'])",
"int2char(c) d += int2char(v >> 2) c = 3 &",
"password = rsa_encode(j_rsakey, password) url = \"https://open.e.189.cn/api/logbox/oauth2/loginSubmit.do\" headers = {",
"url = \"https://cloud.189.cn/udb/udb_login.jsp?pageId=1&redirectURL=/main.action\" r = s.get(url) captchaToken = re.findall(r\"captchaToken' value='(.+?)'\",",
"v elif 1 == e: e = 2 d +=",
"def int2char(a): return BI_RM[a] b64map = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\" def b64tohex(a): d",
"\"captchaToken\": captchaToken, \"returnUrl\": returnUrl, \"mailSuffix\": \"@189.cn\", \"paramId\": paramId } r",
"data=data, headers=headers, timeout=5) if(r.json()['result'] == 0): print(r.json()['msg']) else: print(r.json()['msg']) redirect_url"
] |
[
"pyplot as plt import numpy as np import pysam def",
"= line.reference_name#t[0] start= line.reference_start end= line.reference_end strand= not line.is_reverse #",
"to consider strand specific situation. #'+' strand we have CG",
"# if 'G'==r2 or 'g'==r2: # if 'C'==r1: cg[0]+=1 #",
"r1=read[i-1] # if 'G'==r2 or 'g'==r2: # if 'C'==r1: cg[0]+=1",
"#print cg cgnum_per_read.append(sum(cg)) if cg[0]>0 and cg[1]>0: reads_cg_num[2]+=1 continue if",
"plt.axis('equal') #plt.legend(loc=2,bbox_to_anchor=(0, 0)) ax=plt.subplot(212) t=np.zeros(20) for num in cgnum_per_read: t[min(num-1,19)]+=1",
"if __name__==\"__main__\": import argparse parser = argparse.ArgumentParser() parser.add_argument('-b','--bamfile',help=\"bam file name\",",
"-strand if not chr in chrs: continue end=min(end+1,l[chr]) reads_num+=1 if",
"labels = ['noCG','NonRepeat CG','Repeat cg','CGcg mix'] colors = ['r','b','g','y'] explode=(0.05,0,0,0)",
"False -strand if not chr in chrs: continue end=min(end+1,l[chr]) reads_num+=1",
"parser.add_argument('-b','--bamfile',help=\"bam file name\", metavar=\"FILE\") parser.add_argument('-g','--genome',help=\"Genome fasta file path\") parser.add_argument('-o','--output',help=\"pie figure's",
"situation. #'+' strand we have CG but '-' we should",
"start= line.reference_start end= line.reference_end strand= not line.is_reverse # True +strand;",
"in cgnum_per_read: t[min(num-1,19)]+=1 labels = list(map(str,np.arange(1,20)))+['20+'] #print(t) t = (np.array(t).astype(float)/sum(reads_cg_num))*100",
"chr in chrs: continue end=min(end+1,l[chr]) reads_num+=1 if strand:#=='+': cg=[bases[chr].count('CG',start,end)+bases[chr].count('Cg',start,end),bases[chr].count('cG',start,end)+bases[chr].count('cg',start,end)] else:",
"True +strand; False -strand if not chr in chrs: continue",
"in chrs: continue end=min(end+1,l[chr]) reads_num+=1 if strand:#=='+': cg=[bases[chr].count('CG',start,end)+bases[chr].count('Cg',start,end),bases[chr].count('cG',start,end)+bases[chr].count('cg',start,end)] else: cg=[bases[chr].count('GC',start,end)+bases[chr].count('gC',start,end),bases[chr].count('Gc',start,end)+bases[chr].count('gc',start,end)]",
"patches,l_text,p_text = plt.pie(sizes,explode=explode,labels=labels,colors=colors, labeldistance = 1.1,autopct = '%3.1f%%',shadow = False,",
"#print(t) t = (np.array(t).astype(float)/sum(reads_cg_num))*100 plt.bar(np.arange(20),t) ax.set_xticks(np.arange(20)) ax.set_xticklabels(labels) ax.set_ylabel('Percentage of reads",
"'G'==r2 or 'g'==r2: # if 'C'==r1: cg[0]+=1 # if 'c'==r1:",
"cg','CGcg mix'] colors = ['r','b','g','y'] explode=(0.05,0,0,0) sizes=[reads_num-sum(reads_cg_num)]+reads_cg_num patches,l_text,p_text = plt.pie(sizes,explode=explode,labels=labels,colors=colors,",
"line.reference_start end= line.reference_end strand= not line.is_reverse # True +strand; False",
"ax.set_xticks(np.arange(20)) ax.set_xticklabels(labels) ax.set_ylabel('Percentage of reads including CG') ax.set_xlabel('CG number per",
"matplotlib import pyplot as plt import numpy as np import",
"t = (np.array(t).astype(float)/sum(reads_cg_num))*100 plt.bar(np.arange(20),t) ax.set_xticks(np.arange(20)) ax.set_xticklabels(labels) ax.set_ylabel('Percentage of reads including",
"if 'G'==r2 or 'g'==r2: # if 'C'==r1: cg[0]+=1 # if",
"list(map(str,np.arange(1,20)))+['20+'] #print(t) t = (np.array(t).astype(float)/sum(reads_cg_num))*100 plt.bar(np.arange(20),t) ax.set_xticks(np.arange(20)) ax.set_xticklabels(labels) ax.set_ylabel('Percentage of",
"should count 'GC'. #print cg # for i in range(1,ls):",
"cg[0]>0: reads_cg_num[0]+=1 else: reads_cg_num[1]+=1 #print reads_cg_num #print reads_num plt.figure() plt.subplot(211)",
"from .Genome_fasta import get_fasta import matplotlib matplotlib.use('Agg') from matplotlib import",
"parser = argparse.ArgumentParser() parser.add_argument('-b','--bamfile',help=\"bam file name\", metavar=\"FILE\") parser.add_argument('-g','--genome',help=\"Genome fasta file",
"t=np.zeros(20) for num in cgnum_per_read: t[min(num-1,19)]+=1 labels = list(map(str,np.arange(1,20)))+['20+'] #print(t)",
"import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt import",
"or 'g'==r2: # if 'C'==r1: cg[0]+=1 # if 'c'==r1: cg[1]+=1",
"= set(chrs) #p = subprocess.Popen('bamToBed -i '+args.bamfile,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) reads_num=0 reads_cg_num=[0,0,0] #CG,cg,Cg",
"continue #print cg cgnum_per_read.append(sum(cg)) if cg[0]>0 and cg[1]>0: reads_cg_num[2]+=1 continue",
"1.1,autopct = '%3.1f%%',shadow = False, startangle = 90,pctdistance = 0.6)",
"cgnum_per_read.append(sum(cg)) if cg[0]>0 and cg[1]>0: reads_cg_num[2]+=1 continue if cg[0]>0: reads_cg_num[0]+=1",
"np import pysam def run(parser): args = parser.parse_args() bases,chrs =",
"strand specific situation. #'+' strand we have CG but '-'",
"= '%3.1f%%',shadow = False, startangle = 90,pctdistance = 0.6) plt.axis('equal')",
"CG','Repeat cg','CGcg mix'] colors = ['r','b','g','y'] explode=(0.05,0,0,0) sizes=[reads_num-sum(reads_cg_num)]+reads_cg_num patches,l_text,p_text =",
"matplotlib.use('Agg') from matplotlib import pyplot as plt import numpy as",
"cg[0]>0 and cg[1]>0: reads_cg_num[2]+=1 continue if cg[0]>0: reads_cg_num[0]+=1 else: reads_cg_num[1]+=1",
"#print reads_cg_num #print reads_num plt.figure() plt.subplot(211) labels = ['noCG','NonRepeat CG','Repeat",
"= subprocess.Popen('bamToBed -i '+args.bamfile,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) reads_num=0 reads_cg_num=[0,0,0] #CG,cg,Cg cgnum_per_read=[] with pysam.AlignmentFile(args.bamfile)",
"end=min(end+1,l[chr]) reads_num+=1 if strand:#=='+': cg=[bases[chr].count('CG',start,end)+bases[chr].count('Cg',start,end),bases[chr].count('cG',start,end)+bases[chr].count('cg',start,end)] else: cg=[bases[chr].count('GC',start,end)+bases[chr].count('gC',start,end),bases[chr].count('Gc',start,end)+bases[chr].count('gc',start,end)] #We need to",
"plt.text(4,max(t)+4,'All reads including CG site: '+str(sum(reads_cg_num))) #print args.output+'.pdf' plt.savefig(args.output+'.pdf') if",
"= parser.parse_args() bases,chrs = get_fasta(args.genome) l={} for c in chrs:",
"not line.is_reverse # True +strand; False -strand if not chr",
"import get_fasta import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as",
"cg=[bases[chr].count('GC',start,end)+bases[chr].count('gC',start,end),bases[chr].count('Gc',start,end)+bases[chr].count('gc',start,end)] #We need to consider strand specific situation. #'+' strand",
"labeldistance = 1.1,autopct = '%3.1f%%',shadow = False, startangle = 90,pctdistance",
"run(parser): args = parser.parse_args() bases,chrs = get_fasta(args.genome) l={} for c",
"and cg[1]>0: reads_cg_num[2]+=1 continue if cg[0]>0: reads_cg_num[0]+=1 else: reads_cg_num[1]+=1 #print",
"in chrs: l[c]=len(bases[c]) chrs = set(chrs) #p = subprocess.Popen('bamToBed -i",
"int(cg[0]>0)+int(cg[1]>0) if cg[0]+cg[1]==0: continue #print cg cgnum_per_read.append(sum(cg)) if cg[0]>0 and",
"get_fasta(args.genome) l={} for c in chrs: l[c]=len(bases[c]) chrs = set(chrs)",
"of reads including CG') ax.set_xlabel('CG number per read') plt.text(4,max(t)+4,'All reads",
"CG') ax.set_xlabel('CG number per read') plt.text(4,max(t)+4,'All reads including CG site:",
"get_fasta import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt",
"# if 'C'==r1: cg[0]+=1 # if 'c'==r1: cg[1]+=1 #count =",
"chrs = set(chrs) #p = subprocess.Popen('bamToBed -i '+args.bamfile,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) reads_num=0 reads_cg_num=[0,0,0]",
"import pyplot as plt import numpy as np import pysam",
"pysam def run(parser): args = parser.parse_args() bases,chrs = get_fasta(args.genome) l={}",
"#p = subprocess.Popen('bamToBed -i '+args.bamfile,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) reads_num=0 reads_cg_num=[0,0,0] #CG,cg,Cg cgnum_per_read=[] with",
"strand= not line.is_reverse # True +strand; False -strand if not",
"continue end=min(end+1,l[chr]) reads_num+=1 if strand:#=='+': cg=[bases[chr].count('CG',start,end)+bases[chr].count('Cg',start,end),bases[chr].count('cG',start,end)+bases[chr].count('cg',start,end)] else: cg=[bases[chr].count('GC',start,end)+bases[chr].count('gC',start,end),bases[chr].count('Gc',start,end)+bases[chr].count('gc',start,end)] #We need",
"count 'GC'. #print cg # for i in range(1,ls): #",
"chr = line.reference_name#t[0] start= line.reference_start end= line.reference_end strand= not line.is_reverse",
"False, startangle = 90,pctdistance = 0.6) plt.axis('equal') #plt.legend(loc=2,bbox_to_anchor=(0, 0)) ax=plt.subplot(212)",
"line.reference_end strand= not line.is_reverse # True +strand; False -strand if",
"['noCG','NonRepeat CG','Repeat cg','CGcg mix'] colors = ['r','b','g','y'] explode=(0.05,0,0,0) sizes=[reads_num-sum(reads_cg_num)]+reads_cg_num patches,l_text,p_text",
"from matplotlib import pyplot as plt import numpy as np",
"ax=plt.subplot(212) t=np.zeros(20) for num in cgnum_per_read: t[min(num-1,19)]+=1 labels = list(map(str,np.arange(1,20)))+['20+']",
"ax.set_ylabel('Percentage of reads including CG') ax.set_xlabel('CG number per read') plt.text(4,max(t)+4,'All",
"90,pctdistance = 0.6) plt.axis('equal') #plt.legend(loc=2,bbox_to_anchor=(0, 0)) ax=plt.subplot(212) t=np.zeros(20) for num",
"= line.decode('utf-8').strip().split() chr = line.reference_name#t[0] start= line.reference_start end= line.reference_end strand=",
"chrs: l[c]=len(bases[c]) chrs = set(chrs) #p = subprocess.Popen('bamToBed -i '+args.bamfile,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)",
"if cg[0]>0 and cg[1]>0: reads_cg_num[2]+=1 continue if cg[0]>0: reads_cg_num[0]+=1 else:",
"sizes=[reads_num-sum(reads_cg_num)]+reads_cg_num patches,l_text,p_text = plt.pie(sizes,explode=explode,labels=labels,colors=colors, labeldistance = 1.1,autopct = '%3.1f%%',shadow =",
"CG site: '+str(sum(reads_cg_num))) #print args.output+'.pdf' plt.savefig(args.output+'.pdf') if __name__==\"__main__\": import argparse",
"cg[1]+=1 #count = int(cg[0]>0)+int(cg[1]>0) if cg[0]+cg[1]==0: continue #print cg cgnum_per_read.append(sum(cg))",
"#print reads_num plt.figure() plt.subplot(211) labels = ['noCG','NonRepeat CG','Repeat cg','CGcg mix']",
"with pysam.AlignmentFile(args.bamfile) as f: for line in f: #t =",
"else: reads_cg_num[1]+=1 #print reads_cg_num #print reads_num plt.figure() plt.subplot(211) labels =",
"numpy as np import pysam def run(parser): args = parser.parse_args()",
"including CG') ax.set_xlabel('CG number per read') plt.text(4,max(t)+4,'All reads including CG",
"consider strand specific situation. #'+' strand we have CG but",
"# if 'c'==r1: cg[1]+=1 #count = int(cg[0]>0)+int(cg[1]>0) if cg[0]+cg[1]==0: continue",
"name\", metavar=\"FILE\") parser.add_argument('-g','--genome',help=\"Genome fasta file path\") parser.add_argument('-o','--output',help=\"pie figure's filename\") run(parser)",
"# True +strand; False -strand if not chr in chrs:",
"= ['noCG','NonRepeat CG','Repeat cg','CGcg mix'] colors = ['r','b','g','y'] explode=(0.05,0,0,0) sizes=[reads_num-sum(reads_cg_num)]+reads_cg_num",
"reads_num plt.figure() plt.subplot(211) labels = ['noCG','NonRepeat CG','Repeat cg','CGcg mix'] colors",
"(np.array(t).astype(float)/sum(reads_cg_num))*100 plt.bar(np.arange(20),t) ax.set_xticks(np.arange(20)) ax.set_xticklabels(labels) ax.set_ylabel('Percentage of reads including CG') ax.set_xlabel('CG",
"for i in range(1,ls): # r2=read[i] # r1=read[i-1] # if",
"plt.savefig(args.output+'.pdf') if __name__==\"__main__\": import argparse parser = argparse.ArgumentParser() parser.add_argument('-b','--bamfile',help=\"bam file",
"'GC'. #print cg # for i in range(1,ls): # r2=read[i]",
"['r','b','g','y'] explode=(0.05,0,0,0) sizes=[reads_num-sum(reads_cg_num)]+reads_cg_num patches,l_text,p_text = plt.pie(sizes,explode=explode,labels=labels,colors=colors, labeldistance = 1.1,autopct =",
"mix'] colors = ['r','b','g','y'] explode=(0.05,0,0,0) sizes=[reads_num-sum(reads_cg_num)]+reads_cg_num patches,l_text,p_text = plt.pie(sizes,explode=explode,labels=labels,colors=colors, labeldistance",
"but '-' we should count 'GC'. #print cg # for",
"cg[0]+cg[1]==0: continue #print cg cgnum_per_read.append(sum(cg)) if cg[0]>0 and cg[1]>0: reads_cg_num[2]+=1",
"+strand; False -strand if not chr in chrs: continue end=min(end+1,l[chr])",
"argparse parser = argparse.ArgumentParser() parser.add_argument('-b','--bamfile',help=\"bam file name\", metavar=\"FILE\") parser.add_argument('-g','--genome',help=\"Genome fasta",
"#'+' strand we have CG but '-' we should count",
"bases,chrs = get_fasta(args.genome) l={} for c in chrs: l[c]=len(bases[c]) chrs",
"chrs: continue end=min(end+1,l[chr]) reads_num+=1 if strand:#=='+': cg=[bases[chr].count('CG',start,end)+bases[chr].count('Cg',start,end),bases[chr].count('cG',start,end)+bases[chr].count('cg',start,end)] else: cg=[bases[chr].count('GC',start,end)+bases[chr].count('gC',start,end),bases[chr].count('Gc',start,end)+bases[chr].count('gc',start,end)] #We",
"as f: for line in f: #t = line.decode('utf-8').strip().split() chr",
"num in cgnum_per_read: t[min(num-1,19)]+=1 labels = list(map(str,np.arange(1,20)))+['20+'] #print(t) t =",
"= list(map(str,np.arange(1,20)))+['20+'] #print(t) t = (np.array(t).astype(float)/sum(reads_cg_num))*100 plt.bar(np.arange(20),t) ax.set_xticks(np.arange(20)) ax.set_xticklabels(labels) ax.set_ylabel('Percentage",
"line.is_reverse # True +strand; False -strand if not chr in",
"ax.set_xlabel('CG number per read') plt.text(4,max(t)+4,'All reads including CG site: '+str(sum(reads_cg_num)))",
"pysam.AlignmentFile(args.bamfile) as f: for line in f: #t = line.decode('utf-8').strip().split()",
"cgnum_per_read: t[min(num-1,19)]+=1 labels = list(map(str,np.arange(1,20)))+['20+'] #print(t) t = (np.array(t).astype(float)/sum(reads_cg_num))*100 plt.bar(np.arange(20),t)",
"= get_fasta(args.genome) l={} for c in chrs: l[c]=len(bases[c]) chrs =",
"else: cg=[bases[chr].count('GC',start,end)+bases[chr].count('gC',start,end),bases[chr].count('Gc',start,end)+bases[chr].count('gc',start,end)] #We need to consider strand specific situation. #'+'",
"args = parser.parse_args() bases,chrs = get_fasta(args.genome) l={} for c in",
"parser.parse_args() bases,chrs = get_fasta(args.genome) l={} for c in chrs: l[c]=len(bases[c])",
"0)) ax=plt.subplot(212) t=np.zeros(20) for num in cgnum_per_read: t[min(num-1,19)]+=1 labels =",
"in range(1,ls): # r2=read[i] # r1=read[i-1] # if 'G'==r2 or",
"# r2=read[i] # r1=read[i-1] # if 'G'==r2 or 'g'==r2: #",
"for num in cgnum_per_read: t[min(num-1,19)]+=1 labels = list(map(str,np.arange(1,20)))+['20+'] #print(t) t",
"for line in f: #t = line.decode('utf-8').strip().split() chr = line.reference_name#t[0]",
"CG but '-' we should count 'GC'. #print cg #",
"#We need to consider strand specific situation. #'+' strand we",
"reads including CG site: '+str(sum(reads_cg_num))) #print args.output+'.pdf' plt.savefig(args.output+'.pdf') if __name__==\"__main__\":",
"as np import pysam def run(parser): args = parser.parse_args() bases,chrs",
"if 'C'==r1: cg[0]+=1 # if 'c'==r1: cg[1]+=1 #count = int(cg[0]>0)+int(cg[1]>0)",
"plt import numpy as np import pysam def run(parser): args",
"i in range(1,ls): # r2=read[i] # r1=read[i-1] # if 'G'==r2",
"= int(cg[0]>0)+int(cg[1]>0) if cg[0]+cg[1]==0: continue #print cg cgnum_per_read.append(sum(cg)) if cg[0]>0",
"plt.pie(sizes,explode=explode,labels=labels,colors=colors, labeldistance = 1.1,autopct = '%3.1f%%',shadow = False, startangle =",
"as plt import numpy as np import pysam def run(parser):",
"-i '+args.bamfile,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) reads_num=0 reads_cg_num=[0,0,0] #CG,cg,Cg cgnum_per_read=[] with pysam.AlignmentFile(args.bamfile) as f:",
"number per read') plt.text(4,max(t)+4,'All reads including CG site: '+str(sum(reads_cg_num))) #print",
"= 90,pctdistance = 0.6) plt.axis('equal') #plt.legend(loc=2,bbox_to_anchor=(0, 0)) ax=plt.subplot(212) t=np.zeros(20) for",
"f: #t = line.decode('utf-8').strip().split() chr = line.reference_name#t[0] start= line.reference_start end=",
"'%3.1f%%',shadow = False, startangle = 90,pctdistance = 0.6) plt.axis('equal') #plt.legend(loc=2,bbox_to_anchor=(0,",
".Genome_fasta import get_fasta import matplotlib matplotlib.use('Agg') from matplotlib import pyplot",
"l[c]=len(bases[c]) chrs = set(chrs) #p = subprocess.Popen('bamToBed -i '+args.bamfile,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) reads_num=0",
"subprocess from .Genome_fasta import get_fasta import matplotlib matplotlib.use('Agg') from matplotlib",
"if 'c'==r1: cg[1]+=1 #count = int(cg[0]>0)+int(cg[1]>0) if cg[0]+cg[1]==0: continue #print",
"import argparse parser = argparse.ArgumentParser() parser.add_argument('-b','--bamfile',help=\"bam file name\", metavar=\"FILE\") parser.add_argument('-g','--genome',help=\"Genome",
"have CG but '-' we should count 'GC'. #print cg",
"#t = line.decode('utf-8').strip().split() chr = line.reference_name#t[0] start= line.reference_start end= line.reference_end",
"# r1=read[i-1] # if 'G'==r2 or 'g'==r2: # if 'C'==r1:",
"#plt.legend(loc=2,bbox_to_anchor=(0, 0)) ax=plt.subplot(212) t=np.zeros(20) for num in cgnum_per_read: t[min(num-1,19)]+=1 labels",
"line.reference_name#t[0] start= line.reference_start end= line.reference_end strand= not line.is_reverse # True",
"ax.set_xticklabels(labels) ax.set_ylabel('Percentage of reads including CG') ax.set_xlabel('CG number per read')",
"cg[1]>0: reads_cg_num[2]+=1 continue if cg[0]>0: reads_cg_num[0]+=1 else: reads_cg_num[1]+=1 #print reads_cg_num",
"reads_cg_num[0]+=1 else: reads_cg_num[1]+=1 #print reads_cg_num #print reads_num plt.figure() plt.subplot(211) labels",
"= False, startangle = 90,pctdistance = 0.6) plt.axis('equal') #plt.legend(loc=2,bbox_to_anchor=(0, 0))",
"range(1,ls): # r2=read[i] # r1=read[i-1] # if 'G'==r2 or 'g'==r2:",
"colors = ['r','b','g','y'] explode=(0.05,0,0,0) sizes=[reads_num-sum(reads_cg_num)]+reads_cg_num patches,l_text,p_text = plt.pie(sizes,explode=explode,labels=labels,colors=colors, labeldistance =",
"explode=(0.05,0,0,0) sizes=[reads_num-sum(reads_cg_num)]+reads_cg_num patches,l_text,p_text = plt.pie(sizes,explode=explode,labels=labels,colors=colors, labeldistance = 1.1,autopct = '%3.1f%%',shadow",
"including CG site: '+str(sum(reads_cg_num))) #print args.output+'.pdf' plt.savefig(args.output+'.pdf') if __name__==\"__main__\": import",
"reads_num=0 reads_cg_num=[0,0,0] #CG,cg,Cg cgnum_per_read=[] with pysam.AlignmentFile(args.bamfile) as f: for line",
"reads including CG') ax.set_xlabel('CG number per read') plt.text(4,max(t)+4,'All reads including",
"read') plt.text(4,max(t)+4,'All reads including CG site: '+str(sum(reads_cg_num))) #print args.output+'.pdf' plt.savefig(args.output+'.pdf')",
"we should count 'GC'. #print cg # for i in",
"0.6) plt.axis('equal') #plt.legend(loc=2,bbox_to_anchor=(0, 0)) ax=plt.subplot(212) t=np.zeros(20) for num in cgnum_per_read:",
"line in f: #t = line.decode('utf-8').strip().split() chr = line.reference_name#t[0] start=",
"plt.figure() plt.subplot(211) labels = ['noCG','NonRepeat CG','Repeat cg','CGcg mix'] colors =",
"set(chrs) #p = subprocess.Popen('bamToBed -i '+args.bamfile,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) reads_num=0 reads_cg_num=[0,0,0] #CG,cg,Cg cgnum_per_read=[]",
"strand:#=='+': cg=[bases[chr].count('CG',start,end)+bases[chr].count('Cg',start,end),bases[chr].count('cG',start,end)+bases[chr].count('cg',start,end)] else: cg=[bases[chr].count('GC',start,end)+bases[chr].count('gC',start,end),bases[chr].count('Gc',start,end)+bases[chr].count('gc',start,end)] #We need to consider strand specific",
"__name__==\"__main__\": import argparse parser = argparse.ArgumentParser() parser.add_argument('-b','--bamfile',help=\"bam file name\", metavar=\"FILE\")",
"def run(parser): args = parser.parse_args() bases,chrs = get_fasta(args.genome) l={} for",
"we have CG but '-' we should count 'GC'. #print",
"reads_num+=1 if strand:#=='+': cg=[bases[chr].count('CG',start,end)+bases[chr].count('Cg',start,end),bases[chr].count('cG',start,end)+bases[chr].count('cg',start,end)] else: cg=[bases[chr].count('GC',start,end)+bases[chr].count('gC',start,end),bases[chr].count('Gc',start,end)+bases[chr].count('gc',start,end)] #We need to consider",
"import pysam def run(parser): args = parser.parse_args() bases,chrs = get_fasta(args.genome)",
"in f: #t = line.decode('utf-8').strip().split() chr = line.reference_name#t[0] start= line.reference_start",
"startangle = 90,pctdistance = 0.6) plt.axis('equal') #plt.legend(loc=2,bbox_to_anchor=(0, 0)) ax=plt.subplot(212) t=np.zeros(20)",
"site: '+str(sum(reads_cg_num))) #print args.output+'.pdf' plt.savefig(args.output+'.pdf') if __name__==\"__main__\": import argparse parser",
"cg=[bases[chr].count('CG',start,end)+bases[chr].count('Cg',start,end),bases[chr].count('cG',start,end)+bases[chr].count('cg',start,end)] else: cg=[bases[chr].count('GC',start,end)+bases[chr].count('gC',start,end),bases[chr].count('Gc',start,end)+bases[chr].count('gc',start,end)] #We need to consider strand specific situation.",
"matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt import numpy",
"'-' we should count 'GC'. #print cg # for i",
"#count = int(cg[0]>0)+int(cg[1]>0) if cg[0]+cg[1]==0: continue #print cg cgnum_per_read.append(sum(cg)) if",
"import numpy as np import pysam def run(parser): args =",
"cgnum_per_read=[] with pysam.AlignmentFile(args.bamfile) as f: for line in f: #t",
"need to consider strand specific situation. #'+' strand we have",
"reads_cg_num[2]+=1 continue if cg[0]>0: reads_cg_num[0]+=1 else: reads_cg_num[1]+=1 #print reads_cg_num #print",
"reads_cg_num[1]+=1 #print reads_cg_num #print reads_num plt.figure() plt.subplot(211) labels = ['noCG','NonRepeat",
"args.output+'.pdf' plt.savefig(args.output+'.pdf') if __name__==\"__main__\": import argparse parser = argparse.ArgumentParser() parser.add_argument('-b','--bamfile',help=\"bam",
"cg cgnum_per_read.append(sum(cg)) if cg[0]>0 and cg[1]>0: reads_cg_num[2]+=1 continue if cg[0]>0:",
"for c in chrs: l[c]=len(bases[c]) chrs = set(chrs) #p =",
"if cg[0]+cg[1]==0: continue #print cg cgnum_per_read.append(sum(cg)) if cg[0]>0 and cg[1]>0:",
"reads_cg_num=[0,0,0] #CG,cg,Cg cgnum_per_read=[] with pysam.AlignmentFile(args.bamfile) as f: for line in",
"r2=read[i] # r1=read[i-1] # if 'G'==r2 or 'g'==r2: # if",
"= plt.pie(sizes,explode=explode,labels=labels,colors=colors, labeldistance = 1.1,autopct = '%3.1f%%',shadow = False, startangle",
"if not chr in chrs: continue end=min(end+1,l[chr]) reads_num+=1 if strand:#=='+':",
"strand we have CG but '-' we should count 'GC'.",
"= 1.1,autopct = '%3.1f%%',shadow = False, startangle = 90,pctdistance =",
"= 0.6) plt.axis('equal') #plt.legend(loc=2,bbox_to_anchor=(0, 0)) ax=plt.subplot(212) t=np.zeros(20) for num in",
"t[min(num-1,19)]+=1 labels = list(map(str,np.arange(1,20)))+['20+'] #print(t) t = (np.array(t).astype(float)/sum(reads_cg_num))*100 plt.bar(np.arange(20),t) ax.set_xticks(np.arange(20))",
"not chr in chrs: continue end=min(end+1,l[chr]) reads_num+=1 if strand:#=='+': cg=[bases[chr].count('CG',start,end)+bases[chr].count('Cg',start,end),bases[chr].count('cG',start,end)+bases[chr].count('cg',start,end)]",
"#print cg # for i in range(1,ls): # r2=read[i] #",
"labels = list(map(str,np.arange(1,20)))+['20+'] #print(t) t = (np.array(t).astype(float)/sum(reads_cg_num))*100 plt.bar(np.arange(20),t) ax.set_xticks(np.arange(20)) ax.set_xticklabels(labels)",
"specific situation. #'+' strand we have CG but '-' we",
"plt.subplot(211) labels = ['noCG','NonRepeat CG','Repeat cg','CGcg mix'] colors = ['r','b','g','y']",
"'+args.bamfile,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) reads_num=0 reads_cg_num=[0,0,0] #CG,cg,Cg cgnum_per_read=[] with pysam.AlignmentFile(args.bamfile) as f: for",
"per read') plt.text(4,max(t)+4,'All reads including CG site: '+str(sum(reads_cg_num))) #print args.output+'.pdf'",
"'g'==r2: # if 'C'==r1: cg[0]+=1 # if 'c'==r1: cg[1]+=1 #count",
"subprocess.Popen('bamToBed -i '+args.bamfile,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) reads_num=0 reads_cg_num=[0,0,0] #CG,cg,Cg cgnum_per_read=[] with pysam.AlignmentFile(args.bamfile) as",
"= (np.array(t).astype(float)/sum(reads_cg_num))*100 plt.bar(np.arange(20),t) ax.set_xticks(np.arange(20)) ax.set_xticklabels(labels) ax.set_ylabel('Percentage of reads including CG')",
"file name\", metavar=\"FILE\") parser.add_argument('-g','--genome',help=\"Genome fasta file path\") parser.add_argument('-o','--output',help=\"pie figure's filename\")",
"# for i in range(1,ls): # r2=read[i] # r1=read[i-1] #",
"cg[0]+=1 # if 'c'==r1: cg[1]+=1 #count = int(cg[0]>0)+int(cg[1]>0) if cg[0]+cg[1]==0:",
"if cg[0]>0: reads_cg_num[0]+=1 else: reads_cg_num[1]+=1 #print reads_cg_num #print reads_num plt.figure()",
"l={} for c in chrs: l[c]=len(bases[c]) chrs = set(chrs) #p",
"f: for line in f: #t = line.decode('utf-8').strip().split() chr =",
"= ['r','b','g','y'] explode=(0.05,0,0,0) sizes=[reads_num-sum(reads_cg_num)]+reads_cg_num patches,l_text,p_text = plt.pie(sizes,explode=explode,labels=labels,colors=colors, labeldistance = 1.1,autopct",
"line.decode('utf-8').strip().split() chr = line.reference_name#t[0] start= line.reference_start end= line.reference_end strand= not",
"plt.bar(np.arange(20),t) ax.set_xticks(np.arange(20)) ax.set_xticklabels(labels) ax.set_ylabel('Percentage of reads including CG') ax.set_xlabel('CG number",
"'+str(sum(reads_cg_num))) #print args.output+'.pdf' plt.savefig(args.output+'.pdf') if __name__==\"__main__\": import argparse parser =",
"'C'==r1: cg[0]+=1 # if 'c'==r1: cg[1]+=1 #count = int(cg[0]>0)+int(cg[1]>0) if",
"cg # for i in range(1,ls): # r2=read[i] # r1=read[i-1]",
"continue if cg[0]>0: reads_cg_num[0]+=1 else: reads_cg_num[1]+=1 #print reads_cg_num #print reads_num",
"import subprocess from .Genome_fasta import get_fasta import matplotlib matplotlib.use('Agg') from",
"c in chrs: l[c]=len(bases[c]) chrs = set(chrs) #p = subprocess.Popen('bamToBed",
"'c'==r1: cg[1]+=1 #count = int(cg[0]>0)+int(cg[1]>0) if cg[0]+cg[1]==0: continue #print cg",
"end= line.reference_end strand= not line.is_reverse # True +strand; False -strand",
"reads_cg_num #print reads_num plt.figure() plt.subplot(211) labels = ['noCG','NonRepeat CG','Repeat cg','CGcg",
"#print args.output+'.pdf' plt.savefig(args.output+'.pdf') if __name__==\"__main__\": import argparse parser = argparse.ArgumentParser()",
"#CG,cg,Cg cgnum_per_read=[] with pysam.AlignmentFile(args.bamfile) as f: for line in f:",
"if strand:#=='+': cg=[bases[chr].count('CG',start,end)+bases[chr].count('Cg',start,end),bases[chr].count('cG',start,end)+bases[chr].count('cg',start,end)] else: cg=[bases[chr].count('GC',start,end)+bases[chr].count('gC',start,end),bases[chr].count('Gc',start,end)+bases[chr].count('gc',start,end)] #We need to consider strand",
"= argparse.ArgumentParser() parser.add_argument('-b','--bamfile',help=\"bam file name\", metavar=\"FILE\") parser.add_argument('-g','--genome',help=\"Genome fasta file path\")",
"argparse.ArgumentParser() parser.add_argument('-b','--bamfile',help=\"bam file name\", metavar=\"FILE\") parser.add_argument('-g','--genome',help=\"Genome fasta file path\") parser.add_argument('-o','--output',help=\"pie"
] |
[
"wrap_tables(context[\"body\"]) def setup(app): \"\"\"Entry point for sphinx theming.\"\"\" theme_path =",
"pagename, templatename, context, doctree): if app.config.html_theme != \"furo\": return #",
"= toctree( collapse=False, titles_only=True, maxdepth=-1, includehidden=True ) context[\"furo_navigation_tree\"] = get_navigation_tree(toctree_html)",
"context[\"furo_pygments\"] = colors # Patch the content if \"body\" in",
"should_hide_toc def _html_page_context(app, pagename, templatename, context, doctree): if app.config.html_theme !=",
"if \"body\" in context: context[\"body\"] = wrap_tables(context[\"body\"]) def setup(app): \"\"\"Entry",
"\"furo\": return # Custom Navigation Tree (adds checkboxes and labels)",
"or {}): context[\"furo_hide_toc\"] = True # Inject information about styles",
"Custom Navigation Tree (adds checkboxes and labels) toctree = context.get(\"toctree\",",
"return # Custom Navigation Tree (adds checkboxes and labels) toctree",
"Custom \"should hide ToC\" logic context[\"furo_hide_toc\"] = should_hide_toc(context.get(\"toc\", \"\")) #",
"styles colors = get_pygments_style_colors( app.builder.highlighter.formatter_args[\"style\"], fallbacks={\"foreground\": \"#000000\", \"background\": \"#FFFFFF\"}, )",
"ToC\" logic context[\"furo_hide_toc\"] = should_hide_toc(context.get(\"toc\", \"\")) # Allow for hiding",
"context[\"body\"] = wrap_tables(context[\"body\"]) def setup(app): \"\"\"Entry point for sphinx theming.\"\"\"",
"for sphinx theming.\"\"\" theme_path = (Path(__file__).parent / \"theme\").resolve() app.add_html_theme(\"furo\", str(theme_path))",
"labels) toctree = context.get(\"toctree\", lambda **kwargs: \"\") toctree_html = toctree(",
"\"#FFFFFF\"}, ) context[\"furo_pygments\"] = colors # Patch the content if",
"if \"hide-toc\" in (context.get(\"meta\", None) or {}): context[\"furo_hide_toc\"] = True",
"\"#000000\", \"background\": \"#FFFFFF\"}, ) context[\"furo_pygments\"] = colors # Patch the",
"# Allow for hiding toc via ToC in page-wide metadata.",
"Path from .body import wrap_tables from .code import get_pygments_style_colors from",
"in context: context[\"body\"] = wrap_tables(context[\"body\"]) def setup(app): \"\"\"Entry point for",
"Tree (adds checkboxes and labels) toctree = context.get(\"toctree\", lambda **kwargs:",
"\"background\": \"#FFFFFF\"}, ) context[\"furo_pygments\"] = colors # Patch the content",
"and labels) toctree = context.get(\"toctree\", lambda **kwargs: \"\") toctree_html =",
"toctree_html = toctree( collapse=False, titles_only=True, maxdepth=-1, includehidden=True ) context[\"furo_navigation_tree\"] =",
"= True # Inject information about styles colors = get_pygments_style_colors(",
"checkboxes and labels) toctree = context.get(\"toctree\", lambda **kwargs: \"\") toctree_html",
"= get_pygments_style_colors( app.builder.highlighter.formatter_args[\"style\"], fallbacks={\"foreground\": \"#000000\", \"background\": \"#FFFFFF\"}, ) context[\"furo_pygments\"] =",
".toc import should_hide_toc def _html_page_context(app, pagename, templatename, context, doctree): if",
"!= \"furo\": return # Custom Navigation Tree (adds checkboxes and",
"includehidden=True ) context[\"furo_navigation_tree\"] = get_navigation_tree(toctree_html) # Custom \"should hide ToC\"",
"theming.\"\"\" theme_path = (Path(__file__).parent / \"theme\").resolve() app.add_html_theme(\"furo\", str(theme_path)) app.connect(\"html-page-context\", _html_page_context)",
"context, doctree): if app.config.html_theme != \"furo\": return # Custom Navigation",
") context[\"furo_pygments\"] = colors # Patch the content if \"body\"",
"= should_hide_toc(context.get(\"toc\", \"\")) # Allow for hiding toc via ToC",
"# Inject information about styles colors = get_pygments_style_colors( app.builder.highlighter.formatter_args[\"style\"], fallbacks={\"foreground\":",
"\"body\" in context: context[\"body\"] = wrap_tables(context[\"body\"]) def setup(app): \"\"\"Entry point",
"get_navigation_tree(toctree_html) # Custom \"should hide ToC\" logic context[\"furo_hide_toc\"] = should_hide_toc(context.get(\"toc\",",
"\"2020.9.8.beta2\" from pathlib import Path from .body import wrap_tables from",
"import Path from .body import wrap_tables from .code import get_pygments_style_colors",
"**kwargs: \"\") toctree_html = toctree( collapse=False, titles_only=True, maxdepth=-1, includehidden=True )",
"Patch the content if \"body\" in context: context[\"body\"] = wrap_tables(context[\"body\"])",
"doctree): if app.config.html_theme != \"furo\": return # Custom Navigation Tree",
".navigation import get_navigation_tree from .toc import should_hide_toc def _html_page_context(app, pagename,",
"clean customisable Sphinx documentation theme.\"\"\" __version__ = \"2020.9.8.beta2\" from pathlib",
"\"should hide ToC\" logic context[\"furo_hide_toc\"] = should_hide_toc(context.get(\"toc\", \"\")) # Allow",
"toctree = context.get(\"toctree\", lambda **kwargs: \"\") toctree_html = toctree( collapse=False,",
"import should_hide_toc def _html_page_context(app, pagename, templatename, context, doctree): if app.config.html_theme",
"from .navigation import get_navigation_tree from .toc import should_hide_toc def _html_page_context(app,",
"content if \"body\" in context: context[\"body\"] = wrap_tables(context[\"body\"]) def setup(app):",
"(adds checkboxes and labels) toctree = context.get(\"toctree\", lambda **kwargs: \"\")",
"= wrap_tables(context[\"body\"]) def setup(app): \"\"\"Entry point for sphinx theming.\"\"\" theme_path",
"collapse=False, titles_only=True, maxdepth=-1, includehidden=True ) context[\"furo_navigation_tree\"] = get_navigation_tree(toctree_html) # Custom",
"hide ToC\" logic context[\"furo_hide_toc\"] = should_hide_toc(context.get(\"toc\", \"\")) # Allow for",
"__version__ = \"2020.9.8.beta2\" from pathlib import Path from .body import",
".body import wrap_tables from .code import get_pygments_style_colors from .navigation import",
"\"\") toctree_html = toctree( collapse=False, titles_only=True, maxdepth=-1, includehidden=True ) context[\"furo_navigation_tree\"]",
"<reponame>sethmlarson/furo<filename>src/furo/__init__.py \"\"\"A clean customisable Sphinx documentation theme.\"\"\" __version__ = \"2020.9.8.beta2\"",
"= context.get(\"toctree\", lambda **kwargs: \"\") toctree_html = toctree( collapse=False, titles_only=True,",
"toctree( collapse=False, titles_only=True, maxdepth=-1, includehidden=True ) context[\"furo_navigation_tree\"] = get_navigation_tree(toctree_html) #",
"\"\"\"A clean customisable Sphinx documentation theme.\"\"\" __version__ = \"2020.9.8.beta2\" from",
"app.config.html_theme != \"furo\": return # Custom Navigation Tree (adds checkboxes",
"wrap_tables from .code import get_pygments_style_colors from .navigation import get_navigation_tree from",
"from .body import wrap_tables from .code import get_pygments_style_colors from .navigation",
"templatename, context, doctree): if app.config.html_theme != \"furo\": return # Custom",
"in (context.get(\"meta\", None) or {}): context[\"furo_hide_toc\"] = True # Inject",
"Allow for hiding toc via ToC in page-wide metadata. if",
"(context.get(\"meta\", None) or {}): context[\"furo_hide_toc\"] = True # Inject information",
"the content if \"body\" in context: context[\"body\"] = wrap_tables(context[\"body\"]) def",
"get_navigation_tree from .toc import should_hide_toc def _html_page_context(app, pagename, templatename, context,",
"= \"2020.9.8.beta2\" from pathlib import Path from .body import wrap_tables",
"import get_pygments_style_colors from .navigation import get_navigation_tree from .toc import should_hide_toc",
"point for sphinx theming.\"\"\" theme_path = (Path(__file__).parent / \"theme\").resolve() app.add_html_theme(\"furo\",",
"information about styles colors = get_pygments_style_colors( app.builder.highlighter.formatter_args[\"style\"], fallbacks={\"foreground\": \"#000000\", \"background\":",
"Inject information about styles colors = get_pygments_style_colors( app.builder.highlighter.formatter_args[\"style\"], fallbacks={\"foreground\": \"#000000\",",
"get_pygments_style_colors from .navigation import get_navigation_tree from .toc import should_hide_toc def",
"_html_page_context(app, pagename, templatename, context, doctree): if app.config.html_theme != \"furo\": return",
"pathlib import Path from .body import wrap_tables from .code import",
"maxdepth=-1, includehidden=True ) context[\"furo_navigation_tree\"] = get_navigation_tree(toctree_html) # Custom \"should hide",
"context[\"furo_navigation_tree\"] = get_navigation_tree(toctree_html) # Custom \"should hide ToC\" logic context[\"furo_hide_toc\"]",
"import wrap_tables from .code import get_pygments_style_colors from .navigation import get_navigation_tree",
"context.get(\"toctree\", lambda **kwargs: \"\") toctree_html = toctree( collapse=False, titles_only=True, maxdepth=-1,",
"context[\"furo_hide_toc\"] = True # Inject information about styles colors =",
"for hiding toc via ToC in page-wide metadata. if \"hide-toc\"",
"get_pygments_style_colors( app.builder.highlighter.formatter_args[\"style\"], fallbacks={\"foreground\": \"#000000\", \"background\": \"#FFFFFF\"}, ) context[\"furo_pygments\"] = colors",
"# Custom \"should hide ToC\" logic context[\"furo_hide_toc\"] = should_hide_toc(context.get(\"toc\", \"\"))",
"from pathlib import Path from .body import wrap_tables from .code",
"logic context[\"furo_hide_toc\"] = should_hide_toc(context.get(\"toc\", \"\")) # Allow for hiding toc",
"from .toc import should_hide_toc def _html_page_context(app, pagename, templatename, context, doctree):",
"page-wide metadata. if \"hide-toc\" in (context.get(\"meta\", None) or {}): context[\"furo_hide_toc\"]",
"hiding toc via ToC in page-wide metadata. if \"hide-toc\" in",
"sphinx theming.\"\"\" theme_path = (Path(__file__).parent / \"theme\").resolve() app.add_html_theme(\"furo\", str(theme_path)) app.connect(\"html-page-context\",",
"customisable Sphinx documentation theme.\"\"\" __version__ = \"2020.9.8.beta2\" from pathlib import",
"\"\"\"Entry point for sphinx theming.\"\"\" theme_path = (Path(__file__).parent / \"theme\").resolve()",
"documentation theme.\"\"\" __version__ = \"2020.9.8.beta2\" from pathlib import Path from",
"titles_only=True, maxdepth=-1, includehidden=True ) context[\"furo_navigation_tree\"] = get_navigation_tree(toctree_html) # Custom \"should",
"about styles colors = get_pygments_style_colors( app.builder.highlighter.formatter_args[\"style\"], fallbacks={\"foreground\": \"#000000\", \"background\": \"#FFFFFF\"},",
"in page-wide metadata. if \"hide-toc\" in (context.get(\"meta\", None) or {}):",
"\"hide-toc\" in (context.get(\"meta\", None) or {}): context[\"furo_hide_toc\"] = True #",
"\"\")) # Allow for hiding toc via ToC in page-wide",
".code import get_pygments_style_colors from .navigation import get_navigation_tree from .toc import",
"if app.config.html_theme != \"furo\": return # Custom Navigation Tree (adds",
"# Custom Navigation Tree (adds checkboxes and labels) toctree =",
"fallbacks={\"foreground\": \"#000000\", \"background\": \"#FFFFFF\"}, ) context[\"furo_pygments\"] = colors # Patch",
"from .code import get_pygments_style_colors from .navigation import get_navigation_tree from .toc",
"lambda **kwargs: \"\") toctree_html = toctree( collapse=False, titles_only=True, maxdepth=-1, includehidden=True",
"# Patch the content if \"body\" in context: context[\"body\"] =",
"context: context[\"body\"] = wrap_tables(context[\"body\"]) def setup(app): \"\"\"Entry point for sphinx",
"def _html_page_context(app, pagename, templatename, context, doctree): if app.config.html_theme != \"furo\":",
"def setup(app): \"\"\"Entry point for sphinx theming.\"\"\" theme_path = (Path(__file__).parent",
"ToC in page-wide metadata. if \"hide-toc\" in (context.get(\"meta\", None) or",
"should_hide_toc(context.get(\"toc\", \"\")) # Allow for hiding toc via ToC in",
"toc via ToC in page-wide metadata. if \"hide-toc\" in (context.get(\"meta\",",
") context[\"furo_navigation_tree\"] = get_navigation_tree(toctree_html) # Custom \"should hide ToC\" logic",
"metadata. if \"hide-toc\" in (context.get(\"meta\", None) or {}): context[\"furo_hide_toc\"] =",
"theme.\"\"\" __version__ = \"2020.9.8.beta2\" from pathlib import Path from .body",
"= get_navigation_tree(toctree_html) # Custom \"should hide ToC\" logic context[\"furo_hide_toc\"] =",
"import get_navigation_tree from .toc import should_hide_toc def _html_page_context(app, pagename, templatename,",
"colors = get_pygments_style_colors( app.builder.highlighter.formatter_args[\"style\"], fallbacks={\"foreground\": \"#000000\", \"background\": \"#FFFFFF\"}, ) context[\"furo_pygments\"]",
"app.builder.highlighter.formatter_args[\"style\"], fallbacks={\"foreground\": \"#000000\", \"background\": \"#FFFFFF\"}, ) context[\"furo_pygments\"] = colors #",
"Navigation Tree (adds checkboxes and labels) toctree = context.get(\"toctree\", lambda",
"setup(app): \"\"\"Entry point for sphinx theming.\"\"\" theme_path = (Path(__file__).parent /",
"colors # Patch the content if \"body\" in context: context[\"body\"]",
"{}): context[\"furo_hide_toc\"] = True # Inject information about styles colors",
"context[\"furo_hide_toc\"] = should_hide_toc(context.get(\"toc\", \"\")) # Allow for hiding toc via",
"True # Inject information about styles colors = get_pygments_style_colors( app.builder.highlighter.formatter_args[\"style\"],",
"via ToC in page-wide metadata. if \"hide-toc\" in (context.get(\"meta\", None)",
"None) or {}): context[\"furo_hide_toc\"] = True # Inject information about",
"Sphinx documentation theme.\"\"\" __version__ = \"2020.9.8.beta2\" from pathlib import Path",
"= colors # Patch the content if \"body\" in context:"
] |
[
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"and # limitations under the License. \"\"\"A test for what",
"= mix_down(powerchord, min_third) with wav_file_context(args.filename) as fout: fout.write_frames(powerchord.frames) fout.write_frames(maj_triad.frames) fout.write_frames(min_triad.frames)",
"common from potty_oh.wav_file import wav_file_context from potty_oh.waveform import mix_down from",
"# # Licensed under the Apache License, Version 2.0 (the",
"compliance with the License. # You may obtain a copy",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"2.0 (the \"License\"); # you may not use this file",
"agreed to in writing, software # distributed under the License",
"file except in compliance with the License. # You may",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"Unless required by applicable law or agreed to in writing,",
"common.ParserArguments.length(parser) common.ParserArguments.framerate(parser) common.ParserArguments.set_defaults(parser, type='constant', length=2.0) args = parser.parse_args() common.defaults.framerate =",
"length=2.0) args = parser.parse_args() common.defaults.framerate = args.framerate sg = Generator(length=args.length,",
"distributed under the License is distributed on an \"AS IS\"",
"#!/usr/bin/env python3 # Copyright 2016 <NAME> # # Licensed under",
"the specific language governing permissions and # limitations under the",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"express or implied. # See the License for the specific",
"applicable law or agreed to in writing, software # distributed",
"from potty_oh.music.pitch import Key from potty_oh.music.interval import Interval def main():",
"common.defaults.framerate = args.framerate sg = Generator(length=args.length, verbose=args.debug) key = Key()",
"except in compliance with the License. # You may obtain",
"Generator(length=args.length, verbose=args.debug) key = Key() unison = sg.sin_constant(key.interval(Interval.unison)) maj_third =",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"potty_oh.signal_generator import Generator from potty_oh.music.pitch import Key from potty_oh.music.interval import",
"import Generator from potty_oh.music.pitch import Key from potty_oh.music.interval import Interval",
"powerchord.mix_down(maj_third) min_triad = mix_down(powerchord, min_third) with wav_file_context(args.filename) as fout: fout.write_frames(powerchord.frames)",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"def main(): parser = common.get_cmd_line_parser(description=__doc__) common.ParserArguments.filename(parser) common.ParserArguments.length(parser) common.ParserArguments.framerate(parser) common.ParserArguments.set_defaults(parser, type='constant',",
"not use this file except in compliance with the License.",
"Copyright 2016 <NAME> # # Licensed under the Apache License,",
"with wav_file_context(args.filename) as fout: fout.write_frames(powerchord.frames) fout.write_frames(maj_triad.frames) fout.write_frames(min_triad.frames) return 0 if",
"\"\"\"A test for what happens when two waveforms are averaged",
"are averaged together.\"\"\" from potty_oh import common from potty_oh.wav_file import",
"writing, software # distributed under the License is distributed on",
"in writing, software # distributed under the License is distributed",
"potty_oh.music.interval import Interval def main(): parser = common.get_cmd_line_parser(description=__doc__) common.ParserArguments.filename(parser) common.ParserArguments.length(parser)",
"permissions and # limitations under the License. \"\"\"A test for",
"you may not use this file except in compliance with",
"common.ParserArguments.set_defaults(parser, type='constant', length=2.0) args = parser.parse_args() common.defaults.framerate = args.framerate sg",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"args.framerate sg = Generator(length=args.length, verbose=args.debug) key = Key() unison =",
"use this file except in compliance with the License. #",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"= parser.parse_args() common.defaults.framerate = args.framerate sg = Generator(length=args.length, verbose=args.debug) key",
"limitations under the License. \"\"\"A test for what happens when",
"language governing permissions and # limitations under the License. \"\"\"A",
"wav_file_context(args.filename) as fout: fout.write_frames(powerchord.frames) fout.write_frames(maj_triad.frames) fout.write_frames(min_triad.frames) return 0 if __name__",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"or implied. # See the License for the specific language",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"governing permissions and # limitations under the License. \"\"\"A test",
"from potty_oh.wav_file import wav_file_context from potty_oh.waveform import mix_down from potty_oh.signal_generator",
"License. # You may obtain a copy of the License",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"License, Version 2.0 (the \"License\"); # you may not use",
"= common.get_cmd_line_parser(description=__doc__) common.ParserArguments.filename(parser) common.ParserArguments.length(parser) common.ParserArguments.framerate(parser) common.ParserArguments.set_defaults(parser, type='constant', length=2.0) args =",
"# You may obtain a copy of the License at",
"KIND, either express or implied. # See the License for",
"specific language governing permissions and # limitations under the License.",
"from potty_oh.waveform import mix_down from potty_oh.signal_generator import Generator from potty_oh.music.pitch",
"common.ParserArguments.filename(parser) common.ParserArguments.length(parser) common.ParserArguments.framerate(parser) common.ParserArguments.set_defaults(parser, type='constant', length=2.0) args = parser.parse_args() common.defaults.framerate",
"import common from potty_oh.wav_file import wav_file_context from potty_oh.waveform import mix_down",
"sg = Generator(length=args.length, verbose=args.debug) key = Key() unison = sg.sin_constant(key.interval(Interval.unison))",
"under the License is distributed on an \"AS IS\" BASIS,",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"License for the specific language governing permissions and # limitations",
"min_third = sg.sin_constant(key.interval(Interval.minor_third)) fifth = sg.sin_constant(key.interval(Interval.fifth)) powerchord = unison.mix_down(fifth) maj_triad",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"fout.write_frames(powerchord.frames) fout.write_frames(maj_triad.frames) fout.write_frames(min_triad.frames) return 0 if __name__ == \"__main__\": common.call_main(main)",
"Generator from potty_oh.music.pitch import Key from potty_oh.music.interval import Interval def",
"2016 <NAME> # # Licensed under the Apache License, Version",
"parser = common.get_cmd_line_parser(description=__doc__) common.ParserArguments.filename(parser) common.ParserArguments.length(parser) common.ParserArguments.framerate(parser) common.ParserArguments.set_defaults(parser, type='constant', length=2.0) args",
"key = Key() unison = sg.sin_constant(key.interval(Interval.unison)) maj_third = sg.sin_constant(key.interval(Interval.major_third)) min_third",
"= Generator(length=args.length, verbose=args.debug) key = Key() unison = sg.sin_constant(key.interval(Interval.unison)) maj_third",
"averaged together.\"\"\" from potty_oh import common from potty_oh.wav_file import wav_file_context",
"the License. \"\"\"A test for what happens when two waveforms",
"when two waveforms are averaged together.\"\"\" from potty_oh import common",
"from potty_oh.signal_generator import Generator from potty_oh.music.pitch import Key from potty_oh.music.interval",
"common.get_cmd_line_parser(description=__doc__) common.ParserArguments.filename(parser) common.ParserArguments.length(parser) common.ParserArguments.framerate(parser) common.ParserArguments.set_defaults(parser, type='constant', length=2.0) args = parser.parse_args()",
"= Key() unison = sg.sin_constant(key.interval(Interval.unison)) maj_third = sg.sin_constant(key.interval(Interval.major_third)) min_third =",
"the License for the specific language governing permissions and #",
"(the \"License\"); # you may not use this file except",
"sg.sin_constant(key.interval(Interval.fifth)) powerchord = unison.mix_down(fifth) maj_triad = powerchord.mix_down(maj_third) min_triad = mix_down(powerchord,",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"# you may not use this file except in compliance",
"sg.sin_constant(key.interval(Interval.major_third)) min_third = sg.sin_constant(key.interval(Interval.minor_third)) fifth = sg.sin_constant(key.interval(Interval.fifth)) powerchord = unison.mix_down(fifth)",
"either express or implied. # See the License for the",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"= args.framerate sg = Generator(length=args.length, verbose=args.debug) key = Key() unison",
"python3 # Copyright 2016 <NAME> # # Licensed under the",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"the License is distributed on an \"AS IS\" BASIS, #",
"# Copyright 2016 <NAME> # # Licensed under the Apache",
"in compliance with the License. # You may obtain a",
"Key from potty_oh.music.interval import Interval def main(): parser = common.get_cmd_line_parser(description=__doc__)",
"software # distributed under the License is distributed on an",
"Key() unison = sg.sin_constant(key.interval(Interval.unison)) maj_third = sg.sin_constant(key.interval(Interval.major_third)) min_third = sg.sin_constant(key.interval(Interval.minor_third))",
"from potty_oh.music.interval import Interval def main(): parser = common.get_cmd_line_parser(description=__doc__) common.ParserArguments.filename(parser)",
"import Key from potty_oh.music.interval import Interval def main(): parser =",
"what happens when two waveforms are averaged together.\"\"\" from potty_oh",
"fifth = sg.sin_constant(key.interval(Interval.fifth)) powerchord = unison.mix_down(fifth) maj_triad = powerchord.mix_down(maj_third) min_triad",
"# # Unless required by applicable law or agreed to",
"together.\"\"\" from potty_oh import common from potty_oh.wav_file import wav_file_context from",
"= sg.sin_constant(key.interval(Interval.unison)) maj_third = sg.sin_constant(key.interval(Interval.major_third)) min_third = sg.sin_constant(key.interval(Interval.minor_third)) fifth =",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"main(): parser = common.get_cmd_line_parser(description=__doc__) common.ParserArguments.filename(parser) common.ParserArguments.length(parser) common.ParserArguments.framerate(parser) common.ParserArguments.set_defaults(parser, type='constant', length=2.0)",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"sg.sin_constant(key.interval(Interval.unison)) maj_third = sg.sin_constant(key.interval(Interval.major_third)) min_third = sg.sin_constant(key.interval(Interval.minor_third)) fifth = sg.sin_constant(key.interval(Interval.fifth))",
"Version 2.0 (the \"License\"); # you may not use this",
"under the License. \"\"\"A test for what happens when two",
"import wav_file_context from potty_oh.waveform import mix_down from potty_oh.signal_generator import Generator",
"law or agreed to in writing, software # distributed under",
"= powerchord.mix_down(maj_third) min_triad = mix_down(powerchord, min_third) with wav_file_context(args.filename) as fout:",
"import mix_down from potty_oh.signal_generator import Generator from potty_oh.music.pitch import Key",
"parser.parse_args() common.defaults.framerate = args.framerate sg = Generator(length=args.length, verbose=args.debug) key =",
"unison = sg.sin_constant(key.interval(Interval.unison)) maj_third = sg.sin_constant(key.interval(Interval.major_third)) min_third = sg.sin_constant(key.interval(Interval.minor_third)) fifth",
"from potty_oh import common from potty_oh.wav_file import wav_file_context from potty_oh.waveform",
"import Interval def main(): parser = common.get_cmd_line_parser(description=__doc__) common.ParserArguments.filename(parser) common.ParserArguments.length(parser) common.ParserArguments.framerate(parser)",
"implied. # See the License for the specific language governing",
"args = parser.parse_args() common.defaults.framerate = args.framerate sg = Generator(length=args.length, verbose=args.debug)",
"as fout: fout.write_frames(powerchord.frames) fout.write_frames(maj_triad.frames) fout.write_frames(min_triad.frames) return 0 if __name__ ==",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"\"License\"); # you may not use this file except in",
"mix_down(powerchord, min_third) with wav_file_context(args.filename) as fout: fout.write_frames(powerchord.frames) fout.write_frames(maj_triad.frames) fout.write_frames(min_triad.frames) return",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"common.ParserArguments.framerate(parser) common.ParserArguments.set_defaults(parser, type='constant', length=2.0) args = parser.parse_args() common.defaults.framerate = args.framerate",
"type='constant', length=2.0) args = parser.parse_args() common.defaults.framerate = args.framerate sg =",
"potty_oh.wav_file import wav_file_context from potty_oh.waveform import mix_down from potty_oh.signal_generator import",
"powerchord = unison.mix_down(fifth) maj_triad = powerchord.mix_down(maj_third) min_triad = mix_down(powerchord, min_third)",
"by applicable law or agreed to in writing, software #",
"# distributed under the License is distributed on an \"AS",
"OF ANY KIND, either express or implied. # See the",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"happens when two waveforms are averaged together.\"\"\" from potty_oh import",
"unison.mix_down(fifth) maj_triad = powerchord.mix_down(maj_third) min_triad = mix_down(powerchord, min_third) with wav_file_context(args.filename)",
"may obtain a copy of the License at # #",
"# Unless required by applicable law or agreed to in",
"ANY KIND, either express or implied. # See the License",
"See the License for the specific language governing permissions and",
"= sg.sin_constant(key.interval(Interval.fifth)) powerchord = unison.mix_down(fifth) maj_triad = powerchord.mix_down(maj_third) min_triad =",
"mix_down from potty_oh.signal_generator import Generator from potty_oh.music.pitch import Key from",
"maj_third = sg.sin_constant(key.interval(Interval.major_third)) min_third = sg.sin_constant(key.interval(Interval.minor_third)) fifth = sg.sin_constant(key.interval(Interval.fifth)) powerchord",
"potty_oh import common from potty_oh.wav_file import wav_file_context from potty_oh.waveform import",
"the License. # You may obtain a copy of the",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"for the specific language governing permissions and # limitations under",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"maj_triad = powerchord.mix_down(maj_third) min_triad = mix_down(powerchord, min_third) with wav_file_context(args.filename) as",
"to in writing, software # distributed under the License is",
"Interval def main(): parser = common.get_cmd_line_parser(description=__doc__) common.ParserArguments.filename(parser) common.ParserArguments.length(parser) common.ParserArguments.framerate(parser) common.ParserArguments.set_defaults(parser,",
"= unison.mix_down(fifth) maj_triad = powerchord.mix_down(maj_third) min_triad = mix_down(powerchord, min_third) with",
"= sg.sin_constant(key.interval(Interval.major_third)) min_third = sg.sin_constant(key.interval(Interval.minor_third)) fifth = sg.sin_constant(key.interval(Interval.fifth)) powerchord =",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"# See the License for the specific language governing permissions",
"= sg.sin_constant(key.interval(Interval.minor_third)) fifth = sg.sin_constant(key.interval(Interval.fifth)) powerchord = unison.mix_down(fifth) maj_triad =",
"You may obtain a copy of the License at #",
"wav_file_context from potty_oh.waveform import mix_down from potty_oh.signal_generator import Generator from",
"may not use this file except in compliance with the",
"or agreed to in writing, software # distributed under the",
"required by applicable law or agreed to in writing, software",
"potty_oh.waveform import mix_down from potty_oh.signal_generator import Generator from potty_oh.music.pitch import",
"waveforms are averaged together.\"\"\" from potty_oh import common from potty_oh.wav_file",
"test for what happens when two waveforms are averaged together.\"\"\"",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"potty_oh.music.pitch import Key from potty_oh.music.interval import Interval def main(): parser",
"sg.sin_constant(key.interval(Interval.minor_third)) fifth = sg.sin_constant(key.interval(Interval.fifth)) powerchord = unison.mix_down(fifth) maj_triad = powerchord.mix_down(maj_third)",
"min_third) with wav_file_context(args.filename) as fout: fout.write_frames(powerchord.frames) fout.write_frames(maj_triad.frames) fout.write_frames(min_triad.frames) return 0",
"with the License. # You may obtain a copy of",
"fout: fout.write_frames(powerchord.frames) fout.write_frames(maj_triad.frames) fout.write_frames(min_triad.frames) return 0 if __name__ == \"__main__\":",
"this file except in compliance with the License. # You",
"# limitations under the License. \"\"\"A test for what happens",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"for what happens when two waveforms are averaged together.\"\"\" from",
"verbose=args.debug) key = Key() unison = sg.sin_constant(key.interval(Interval.unison)) maj_third = sg.sin_constant(key.interval(Interval.major_third))",
"min_triad = mix_down(powerchord, min_third) with wav_file_context(args.filename) as fout: fout.write_frames(powerchord.frames) fout.write_frames(maj_triad.frames)",
"two waveforms are averaged together.\"\"\" from potty_oh import common from",
"<NAME> # # Licensed under the Apache License, Version 2.0",
"License. \"\"\"A test for what happens when two waveforms are"
] |