def generic_translate_python(src, lib, lang_import, highlight): ''' Translate Python code into Javascript and execute src: source code in editor lib: language specific lib (e.g. my_lib in English, biblio in French) already imported in html file lang_import: something like "from reeborg_en import *" ''' # save initial state of lib initial_lib_dict = {} for key in lib.__dict__: initial_lib_dict[key] = lib.__dict__[key] exec(library.getValue(), lib.__dict__) exec(lang_import) if highlight: temp_src, success = insert_highlight_info(src) if success: src = temp_src else: exec("RUR.ui.highlight()") window.jQuery("#highlight-impossible").show() exec(src) # remove added definitions new_keys = [] for key in lib.__dict__: if key not in initial_lib_dict: new_keys.append(key) else: lib.__dict__[key] = initial_lib_dict[key] for key in new_keys: del lib.__dict__[key]
def generic_translate_python(src, lib, lang_import, highlight, pre_code='', post_code=''): ''' Translate Python code into Javascript and execute src: source code in editor lib: string - language specific lib (e.g. "library" in English, "biblio" in French) already imported in html file lang_import: something like "from reeborg_en import *" ''' globals_ = {} exec(lang_import, globals_) if highlight: temp_src, problem = insert_highlight_info(src) if hasattr(window.RUR, "__debug"): window.console.log(temp_src) if not problem: src = temp_src else: exec("RUR.ui.highlight('{}')".format(problem), globals_) window.jQuery("#highlight-impossible").show() src = pre_code + "\n" + src + "\n" + post_code exec(src, globals_) if lib in sys.modules: del sys.modules[lib]
def generic_translate_python(src, lib, lang_import, highlight, pre_code='', post_code=''): ''' Translate Python code into Javascript and execute src: source code in editor lib: string - language specific lib (e.g. "library" in English, "biblio" in French) already imported in html file lang_import: something like "from reeborg_en import *" ''' if lib in sys.modules: del sys.modules[lib] globals_ = {} globals_.update(globals()) globals_['dir_py'] = dir_py globals_['Help'] = Help src = transform(src) exec(lang_import, globals_) if highlight: temp_src, problem = insert_highlight_info(src) if not problem: src = temp_src else: exec("RUR.ui.highlight('{}')".format(problem), globals_) window.jQuery("#highlight-impossible").show() if hasattr(window.RUR, "__debug"): window.console.log("processed source:") window.console.log(src) src = "help=Help\n" + pre_code + "\n" + src + "\n" + post_code exec(src, globals_)
def generic_translate_python(src, lib, lang_import, highlight, var_watch, pre_code='', post_code=''): ''' Translate Python code into Javascript and execute src: source code in editor lib: string - language specific lib (e.g. "library" in English, "biblio" in French) already imported in html file lang_import: something like "from reeborg_en import *" ''' sys.stdout.write = __write sys.stderr.write = __write_err if lib in sys.modules: del sys.modules[lib] globals_ = {} globals_.update(globals()) globals_['dir_py'] = dir_py globals_['Help'] = Help globals_['_watch_'] = _watch_ globals_['_v_'] = None globals_['previous_watch_values'] = {} src = transform(src) exec(lang_import, globals_) # globals_['system_default_vars'] = set([key for key in globals_]) if highlight or var_watch: try: temp_src, problem = insert_highlight_info(src, highlight=highlight, var_watch=var_watch) if not problem: src = temp_src else: window.RUR.ui.highlight() window.jQuery("#highlight-impossible").show() except Exception as e: window.RUR.__python_error = e window.console.log("problem with hightlight:", e) return if hasattr(window.RUR, "__debug"): window.console.log("processed source:") window.console.log(src) # include v again to reset its value _v_ = "system_default_vars = set(locals().keys())\n" src = "help=Help\n" + pre_code + "\n" + _v_ + src + "\n" + post_code try: exec(src, globals_) except Exception as e: window.RUR.__python_error = e
def generic_translate_python(src, highlight, var_watch, pre_code='', post_code=''): ''' RUR.translate Python code into Javascript and execute src: source code in editor highlight: determines if the code will be highlighted as it is run var_watch: determines if some variable watch will take place pre_code: code included with world definition and prepended to user code post_code: code included with world definition and appended to user code ''' # lib: string - language specific lib # (e.g. "library" in English, "biblio" in French) # already imported in html file lib = window.RUR.library_name # lang_import: something like "from reeborg_en import *" lang_import = window.RUR.from_import sys.stdout.write = __write sys.stderr.write = __write_err if lib in sys.modules: del sys.modules[lib] globals_ = {} globals_.update(globals()) globals_['dir_py'] = dir_py globals_['Help'] = Help globals_['_watch_'] = _watch_ globals_['_v_'] = None globals_['previous_watch_values'] = {} src = transform(src) exec(lang_import, globals_) # globals_['system_default_vars'] = set([key for key in globals_]) if highlight or var_watch: try: temp_src, problem = insert_highlight_info(src, highlight=highlight, var_watch=var_watch) if not problem: src = temp_src else: window.RUR.toggle_highlight() window.jQuery("#highlight-impossible").show() except Exception as e: window.RUR.__python_error = e window.console.log("problem with hightlight:", e) return if hasattr(window.RUR, "__debug"): window.console.log("processed source:") window.console.log(src) # include v again to reset its value _v_ = "system_default_vars = set(locals().keys())\n" src = "help=Help\n" + pre_code + "\n" + _v_ + src + "\n" + post_code try: exec(src, globals_) except Exception as e: window.RUR.__python_error = e
def json_view(self): _info = json.dumps({ 'places': net.INSTANCE.place_defs, 'transitions': net.INSTANCE.transition_defs, 'arcs': net.INSTANCE.arc_defs, 'place_names': net.INSTANCE.place_names, 'token_ledger': net.INSTANCE.token_ledger }) window.jQuery('#json').JSONView(_info)
def form_task_add(self) -> None: """ Handler that will be fired on form submit :return: None """ self.controller.task_add( html.escape(window.jQuery('.input-todo-task')[0].value), int(window.jQuery('.select-todo-priority')[0].value), html.escape("")) window.jQuery('.input-todo-task')[0].value = ''
def json_view(self): _info = json.dumps({ 'places': self.instance.place_defs, 'transitions': self.instance.transition_defs, 'arcs': self.instance.arc_defs, 'place_names': self.instance.place_names, 'token_ledger': self.instance.token_ledger }) window.jQuery('#json').JSONView(_info, {'collapsed': True})
def __onload(ctx): """ use snap to begin creating an SVG """ global CTL CTL = Editor() window.jQuery('#net').on('click', CTL.on_insert) window.jQuery('.select').on('click', CTL.select) window.jQuery('.symbol').on('click', CTL.symbol) window.jQuery('.tool').on('click', CTL.tool) window.jQuery('.simulator').on('click', CTL.simulator) global CTX CTX = ctx CTX.machine('empty', callback=CTL.load)
def generic_translate_python(src, lib, lang_import, highlight, pre_code='', post_code=''): ''' Translate Python code into Javascript and execute src: source code in editor lib: string - language specific lib (e.g. "library" in English, "biblio" in French) already imported in html file lang_import: something like "from reeborg_en import *" ''' sys.stdout.write = __write sys.stderr.write = __write_err if lib in sys.modules: del sys.modules[lib] globals_ = {} globals_.update(globals()) globals_['dir_py'] = dir_py globals_['Help'] = Help globals_['__watch'] = __watch globals_['__v'] = None globals_['previous_watch_values'] = {} src = transform(src) exec(lang_import, globals_) # globals_['system_default_vars'] = set([key for key in globals_]) if highlight: try: temp_src, problem = insert_highlight_info(src) if not problem: src = temp_src else: window.RUR.ui.highlight() window.jQuery("#highlight-impossible").show() except Exception as e: window.RUR.__python_error = e window.console.log("problem with hightlight:", e) return if hasattr(window.RUR, "__debug"): window.console.log("processed source:") window.console.log(src) # include v again to reset its value __v = "system_default_vars = set(locals().keys())\n" src = "help=Help\n" + pre_code + "\n" + __v + src + "\n" + post_code try: exec(src, globals_) except Exception as e: window.RUR.__python_error = e
def inicia_visualizacao(ev): mapa = browser.document['mapa'].value robo = tuple([int(i) for i in browser.document['robo'].value.split(',')]) mapa = mapa.split('\n') particulas = simple_particle.cria_particulas(mapa) simple_particle.mostra_mapa(mapa, robo, particulas) window.jQuery('ul.tabs').tabs('select_tab', 'viz') cria_tabela(mapa, 'mapa_viz') cria_tabela(mapa, 'mapa_probs') atualiza_tabela(mapa, robo, (0, 0), particulas) atualiza_tabela_prob(mapa, particulas) simulacao_atual['mapa'] = mapa simulacao_atual['robo'] = robo simulacao_atual['particulas'] = particulas
def __init__(self, controller): """ :param controller: TodoApp controller """ self.controller = controller register_submit('form-todo-add', self.form_task_add) self.controller.event_task_add.subscribe(self.task_on_add) self.todo_list_elm = window.jQuery('.todo-list')
def register_submit(class_name, fire) -> None: """ Register on a form a handler :param class_name: class name of the form :param fire: function that will be fire on form submit :return: None """ def submit_handler(event) -> None: """ Handle form submit and fire handler :param event: Default html form object :return: None """ event.preventDefault() fire() if window.jQuery('.' + class_name).length == 1: return window.jQuery('.' + class_name).on('submit', submit_handler)
def elm(elm_type: object, attr=None) -> any: """ Create an HTML element with given type and attribute :param elm_type: type of the element :param attr: attributes that will given to the element :return: jQuery HTML element """ jquery_elm = window.jQuery(document.createElement(elm_type)) if attr is not None: jquery_elm.attr(attr) return jquery_elm
def load_saved_nets(self, req): """ load known schemata from server """ nets = json.loads(req.text)['schemata'] options = [] for net in nets: if self.selected_net == net: options.append('<option selected="selected">%s</option>' % net) else: options.append('<option>%s</option>' % net) el = window.jQuery('#netselect') el.html(''.join(options)) el.change(lambda event: self.view(event.target.value))
def generic_translate_python(src, lib, lang_import, highlight, pre_code='', post_code=''): ''' Translate Python code into Javascript and execute src: source code in editor lib: language specific lib (e.g. my_lib in English, biblio in French) already imported in html file lang_import: something like "from reeborg_en import *" ''' globals_ = {} # save initial state of lib initial_lib_dict = {} for key in lib.__dict__: initial_lib_dict[key] = lib.__dict__[key] exec(library.getValue(), lib.__dict__) exec(lang_import, globals_) if highlight: temp_src, success = insert_highlight_info(src) if success: src = temp_src else: exec("RUR.ui.highlight()", globals_) window.jQuery("#highlight-impossible").show() src = pre_code + "\n" + src + "\n" + post_code exec(src, globals_) # remove added definitions new_keys = [] for key in lib.__dict__: if key not in initial_lib_dict: new_keys.append(key) else: lib.__dict__[key] = initial_lib_dict[key] for key in new_keys: del lib.__dict__[key]
def render_div(self, div): css_selector = f"#{self.div_id}" # Not sure the right way to erase the children of a node # Just replace with an identical node with the same ID. window.jQuery(css_selector).replaceWith(f"<div id='{self.div_id}'/>") document[self.div_id] <= div
def start(e): try: window.loader_dialog.open() for i in range(int(document.getElementById("num-cases").value)): window.linearProgress.progress = i/int(document.getElementById("num-cases").value) try: exec(window.test_case_editor.getValue(), {}, locals()) except Exception: window.jQuery("#comment-error").html( "テストケース生成コードの実行中にエラーが発生しました。プログラムを確認してください。確認しても治らない場合はお手数ですが、バグ報告を行ってください。") window.jQuery("#genbun").text(traceback.format_exc()) window.generate_error_dialog.open() else: tmp = [] try: for j in window.hensuu: tmp.append(eval(j[0])) except NameError: window.jQuery("#comment-error").html("変数の定義が間違っている可能性があります。確認してください。<br>" "<span class='text-info'>テストケース生成時に定義されていない変数{}が存在します。</span>". format(str(e).split("'")[1])) window.jQuery("#genbun").text(traceback.format_exc()) window.generate_error_dialog.open() except Exception: window.jQuery("#comment-error").html("処理できないエラーが発生しました。お手数ですが、バグ報告を行ってください。") window.jQuery("#genbun").text(traceback.format_exc()) window.generate_error_dialog.open() else: ok_list = [] global_list = {} for j, k in enumerate(window.hensuu): global_list[k[0]] = tmp[j] global_ = {} s = "A" + ''.join(random.choices(string.ascii_letters + string.digits, k=64)) try: for j in window.answer_editor.getValue().splitlines(): if j.find("print(") != -1: exec(j.replace("print(", s + "=("), global_) else: exec(j, global_) for k in global_list: if k in global_ and k not in ok_list: ok_list.append(k) global_[k] = global_list[k] except Exception: window.jQuery("#comment-error").html( "テストケース生成コードの実行中にエラーが発生しました。プログラムを確認してください。確認しても治らない場合はお手数ですが、バグ報告を行ってください。") window.jQuery("#genbun").text(traceback.format_exc()) window.generate_error_dialog.open() else: tmp.append(str(global_[s])) tmp.append(False) html = '<tr class="mdc-data-table__row" id="random_case-' + str(len(window.random_case)) + '">' for j in tmp[:-1]: html += '<th class="mdc-data-table__cell">' + str(j) + '</th>' html += '<td class="mdc-data-table__cell"><div class="mdc-touch-target-wrapper"><div ' \ 'class="mdc-checkbox ' \ 'mdc-checkbox--touch"><input class="mdc-checkbox__native-control case-list-checkbox" ' \ 'type="checkbox"/><div class="mdc-checkbox__background"><svg ' \ 'class="mdc-checkbox__checkmark" ' \ 'viewBox="0 0 24 24"><path class="mdc-checkbox__checkmark-path" d="M1.73,12.91 8.1,' \ '19.28 22.79,' \ '4.59" fill="none"/></svg><div class="mdc-checkbox__mixedmark"></div></div><div ' \ 'class="mdc-checkbox__ripple"></div></div></div></td><td ' \ 'class="mdc-data-table__cell"><button ' \ 'class="mdc-button mdc-button--raised w-100 random-case-change-btn"><span ' \ 'class="mdc-button__label">変更</span></button></td><td ' \ 'class="mdc-data-table__cell"><button ' \ 'class="mdc-button mdc-button--outlined w-100 random-case-remove-btn"><span ' \ 'class="mdc-button__ripple"></span><span ' \ 'class="mdc-button__label">削除</span></button></td> ' window.jQuery("#random_case-list").append(html) window.random_case.append(tmp) except Exception: window.jQuery("#comment-error").html("処理できないエラーが発生しました。お手数ですが、バグ報告を行ってください。") window.jQuery("#genbun").text(traceback.format_exc()) window.generate_error_dialog.open() finally: print("exited.") window.loader_dialog.close()
def j(self, *args): return window.jQuery(*args)
def generic_translate_python(src, highlight=False, var_watch=False, pre_code='', post_code=''): ''' RUR.translate Python code into Javascript and execute src: source code in editor highlight: determines if the code will be highlighted as it is run var_watch: determines if some variable watch will take place pre_code: code included with world definition and prepended to user code post_code: code included with world definition and appended to user code ''' # lib: string - language specific lib # (e.g. "library" in English, "biblio" in French) # already imported in html file lib = window.RUR.library_name # lang_import: something like "from reeborg_en import *" lang_import = window.RUR.from_import sys.stdout.write = __write sys.stderr.write = __write_err if lib in sys.modules: del sys.modules[lib] globals_ = {} globals_.update(globals()) globals_['dir_py'] = dir_py globals_['Help'] = Help globals_['_watch_'] = _watch_ globals_['_v_'] = None globals_['previous_watch_values'] = {} src = transform(src) # sometimes, when copying from documentation displayed in the browsers # some nonbreaking spaces are inserted instead of regular spaces. # We make the assumption that nonbreaking spaces should never appear # in source code - which is not necessarily valid... if '\xa0' in src: src = src.replace('\xa0', ' ') window.console.warn("Some nonbreaking spaces were replaced in the Python code.") exec(lang_import, globals_) # globals_['system_default_vars'] = set([key for key in globals_]) if highlight or var_watch: try: temp_src, problem = insert_highlight_info(src, highlight=highlight, var_watch=var_watch) if not problem: src = temp_src else: window.RUR.toggle_highlight() window.jQuery("#highlight-impossible").show() except Exception as e: window.RUR.__python_error = e window.console.log("problem with hightlight:", e) return if hasattr(window.RUR, "__debug"): window.console.log("processed source:") window.console.log(src) # include v again to reset its value _v_ = "system_default_vars = set(locals().keys())\n" src = "help=Help\n" + pre_code + "\n" + _v_ + src + "\n" + post_code try: exec(src, globals_) except Exception as e: window.RUR.__python_error = e
def bind_controls(self): """ control editor instance """ window.jQuery('#netreload').on('click', lambda _: self.view()) window.jQuery('#netsave').on('click', lambda _: self.save()) window.jQuery('#dbreload').on('click', lambda _: self.install_db())
def __generic_translate_python(src, highlight=False, var_watch=False, pre_code='', post_code=''): ''' RUR.translate Python code into Javascript and execute src: source code in editor highlight: determines if the code will be highlighted as it is run var_watch: determines if some variable watch will take place pre_code: code included with world definition and prepended to user code post_code: code included with world definition and appended to user code ''' from preprocess import transform # keeping out of global namespace from highlight import insert_highlight_info sys.stdout.write = __write sys.stderr.write = __write # reeborg_en and reeborg_fr define some attributes to window; these # could have been redefined when importing a different language version - # or, perhas even when running a Javascript version; so it # is important to ensure that they have their proper definition by forcing # a fresh import each time such a request is made via something like # from reeborg_en import * # Similarly, library or biblio's content might have changed by the user # since the program was run last time for mod in ["reeborg_en", "reeborg_fr", "library", "biblio", "extra"]: if mod in sys.modules: del sys.modules[mod] globals_ = {} globals_['__help'] = __help globals_['__watch'] = __watch globals_['__previous_watch_values'] = {} globals_['window'] = window globals_['console'] = console globals_['print_dir'] = print_dir src = transform(src) # sometimes, when copying from documentation displayed in the browsers # some nonbreaking spaces are inserted instead of regular spaces. # We make the assumption that nonbreaking spaces should never appear # in source code - which is not necessarily valid... if '\xa0' in src: src = src.replace('\xa0', ' ') window.console.warn( "Some nonbreaking spaces were replaced in the Python code.") # Notwithstanding what is writte above regarding fresh imports, # we simulate this here by doing a dict update, thus effectively using a # cached version of a previous import while ensuring that and # global ("window") definition is done properly. if window.RUR.from_import == "from reeborg_en import *": globals_.update(__REEBORG_EN) elif window.RUR.from_import == "from reeborg_fr import *": globals_.update(__REEBORG_FR) else: raise Exception("unknown import %s" % window.RUR.from_import) if highlight or var_watch: try: temp_src, problem = insert_highlight_info(src, highlight=highlight, var_watch=var_watch) if not problem: src = temp_src else: window.RUR.toggle_highlight() window.jQuery("#highlight-impossible").show() except Exception as e: window.RUR.__python_error = e window.console.log("problem with hightlight:", e) return if hasattr(window.RUR, "__debug"): window.console.log("processed source:") window.console.log(src) if var_watch: system_vars = "system_default_vars = set(locals().keys())\n" else: system_vars = "\n" src = "help=__help\n" + pre_code + "\n" + system_vars + src + "\n" + post_code try: exec(src, globals_) except Exception as e: window.RUR.__python_error = e
def bind_controls(self): window.jQuery('#net').on('click', self.on_insert) window.jQuery('.select').on('click', self.select) window.jQuery('.symbol').on('click', self.symbol) window.jQuery('.tool').on('click', self.tool) window.jQuery('.simulator').on('click', self.simulator)
1: 'background-color:red;', 2: 'background-color:green;' } }, 'recid': 9, 'c1': 'C', 'c2': 'C#', }, #{ 'recid': 3, 'c1': 'CMaj7', }, #{ 'recid': 4, 'c1': 'CSus4', }, #{ 'recid': 5, 'c1': 'C', }, ] } # attach the lay0out to the HTML div window.jQuery('#main').w2layout(w2layoutDefinition) # jstree_container is defined in the style tag of the left-hand panel tree = window.jQuery('#jstree_container').jstree(treeDefinition) # create the grid grid = window.jQuery().w2grid(gridDefinition) # and insert the grid into the w2ui layout window.w2ui.layout.content('main', grid) # set up the global application instance document.pyapp = Application("wss://echo.websocket.org", window.w2ui, grid, tree) # ensure grid and friends are refreshed grid.refresh() # r5 = grid.get(5) # getGlobal().js_dump(r5)