def json_read(self, config): self.reset() j = json.loads(config) # load img config if j["imgpath"] is not None: self.map_load(j["imgpath"]) else: self.map_unset() # walk speed if "walk_speed" in j: self.walk_speed = j["walk_speed"] # load reference points if j["A"] is not None: la, lo = GPS.sex2dec(j["A"]["coord"]) self.set_ref("A", j["A"]["xy"][0], j["A"]["xy"][1], la, lo) else: self.unset_ref("A") if j["H"] is not None: la, lo = GPS.sex2dec(j["H"]["coord"]) self.set_ref("H", j["H"]["xy"][0], j["H"]["xy"][1], la, lo) else: self.unset_ref("H") if j["V"] is not None: la, lo = GPS.sex2dec(j["V"]["coord"]) self.set_ref("V", j["V"]["xy"][0], j["V"]["xy"][1], la, lo) else: self.unset_ref("V") # load last route self.route = j["route"]
def on_exit(status): """ Called when gnatname exited. Reload the project view if it succeed. """ if not status: GPS.execute_action("reload project")
def do_exit(timeout): """ Force an exit of GPS right now, logging as an error the contents of the Messages window. This is useful for capturing more traces for stalled tests that are about to get killed by rlimit. """ timeout.remove() simple_error(GPS.Console("Messages").get_text()) GPS.exit(force=1)
def __init__(self): # Whether we trust that there are no links in the project hierarchy self.trusted_mode = True cross_ref_runtime.create( "Cross references in runtime files", 'boolean', "Index files in the runtime for cross references queries", False) # When we support python, we add support for the --runtime attribute. # This is not supported in GNAT Bench though xml = self.xml xml = xml.replace( "<!-- Runtime_switch support -->", "<arg>%python(cross_references.runtime_switch())</arg>") GPS.parse_xml(xml) GPS.Hook("project_view_changed").add(self.on_project_view_changed) GPS.Hook("compilation_finished").add(self.on_compilation_finished) GPS.Hook("preferences_changed").add(self.on_preferences_changed) GPS.Hook("rsync_finished").add(self.on_rsync_finished) self.gnatinspect_launch_registered = False self.gnatinspect_already_running = False # Initialize self.trusted_mode and other preferences self.on_preferences_changed(None) # An action for the menu item /Build/Recompute Xref Info gps_utils.make_interactive( lambda *args: self.recompute_xref(quiet=False), name="recompute xref info")
def register_doc(): GPS.parse_xml (""" <documentation_file> <name>http://www.python.org/doc/2.4.2/tut/tut.html</name> <descr>Python tutorial</descr> <menu>/Python/Python Tutorial</menu> <category>Scripts</category> </documentation_file> <documentation_file> <shell lang="python">python_support.show_python_library()</shell> <descr>Python Library</descr> <menu>/Python/Python Library</menu> <category>Scripts</category> </documentation_file>""") if has_pygtk: GPS.parse_xml (""" <documentation_file> <name>http://www.pygtk.org/pygtk2tutorial/index.html</name> <descr>PyGTK tutorial</descr> <menu>/Python/PyGTK Tutorial</menu> <category>Scripts</category> </documentation_file> <documentation_file> <name>http://www.pygtk.org/pygtk2reference/index.html</name> <descr>PyGTK Reference Manual</descr> <menu>/Python/PyGTK Reference Manual</menu> <category>Scripts</category> </documentation_file>""")
def reload_file (menu): """Reload the currently edited file in python. If the file has not been imported yet, import it initially. Otherwise, reload the current version of the file.""" try: file = GPS.current_context().file() module=os.path.splitext (os.path.basename (file.name()))[0] ## The actual import and reload must be done in the context of the ## GPS console so that they are visible there. The current function ## executes in a different context, and would not impact the GPS ## console as a result otherwise. ## We cannot use execfile(...), since that would be the equivalent ## of "from ... import *", not of "import ..." if sys.modules.has_key (module): GPS.exec_in_console ("reload (sys.modules[\"" + module + "\"])") else: try: sys.path.index (os.path.dirname (file.name())) except: sys.path = [os.path.dirname (file.name())] + sys.path mod = __import__ (module) # This would import in the current context, not what we want # exec (compile ("import " + module, "<cmdline>", "exec")) ## The proper solution is to execute in the context of the GPS console GPS.exec_in_console ("import " + module) except: pass ## Current context is not a file
def goto_declaration_body(): """ Jump to the declaration of the current entity. If the cursor is already on the declaration, jump to the body/implementation of the entity instead. """ current_file = GPS.current_context().file() current_line = GPS.current_context().location().line() try: entity = GPS.current_context().entity() decl = entity.declaration().file() decl_line = entity.declaration().line() GPS.Editor.mark_current_location() if current_file == decl and current_line == decl_line: body = entity.body().file() body_line = entity.body().line() GPS.Editor.edit(body.name(), line=body_line, column=entity.body().column()) else: GPS.Editor.edit(decl.name(), line=decl_line, column=entity.declaration().column()) GPS.Editor.mark_current_location() except: print "Not found %s:%s:%s" % (name, current_file.path, line) GPS.Editor.edit(current_file.other_file().path)
def __init__(self, tool_name, default_args): """ Initializes a new instance of the class :class:`TargetConnector` by creating a build target associated to ``tool_name``, with ``default_args`` used as default arguments. """ xml = r""" <target model="target connector" category="Bareboard" name="%s"> <launch-mode>MANUALLY_WITH_NO_DIALOG</launch-mode> <command-line> <arg>%s</arg>""" % (tool_name, tool_name) for arg in default_args: xml += r"""<arg>%s</arg>\n""" % (arg) xml += """</command-line> </target>""" try: super(TargetConnector, self).__init__(tool_name) except GPS.Exception: GPS.parse_xml(xml) super(TargetConnector, self).__init__(tool_name)
def go_to_spec(prj = XReqProject()): context = GPS.current_context() file = context.file() line_no = context.location().line() buffer = GPS.EditorBuffer.get(file) #GPS.Console().write ("%s line %d\n" % (file.name(), line_no)) if not buffer.is_modified(): filename = file.name() delete = False else: filename = GPS.dump(buffer.get_chars()) delete = True args = ["xreq", "--partial", "--step-matching", "--step", prj.steps_dir(), filename] p = subprocess.Popen(args, stdout=subprocess.PIPE) step_file = None step_line = None for line in p.stdout.readlines(): m = re.match('^Step Matching: "(.*):([0-9]+)" matches "(.*):([0-9]+)" procedure (.*)$', line) if m: l = int(m.group(2)) if l > line_no: break else: #GPS.Console().write ("line %d match %s (%s:%d)\n" % ( # int(m.group(2)), m.group(5), m.group(3), int(m.group(4)))); step_file = m.group(3) step_line = int(m.group(4)) p.stdout.close() if delete: os.remove(filename) if step_file: open_file(step_file, step_line)
def close_editors(): """ Save and close all source editors. """ GPS.execute_action("/File/Save More/All") for ed in GPS.EditorBuffer.list(): ed.close(True)
def setup(self): GPS.parse_xml(targets) GPS.Hook("compilation_finished").add(self.on_compilation_finished) GPS.Hook("preferences_changed").add(self.on_preferences_changed) # Initialize trusted_mode and other preferences self.on_preferences_changed(None)
def attempt_up(count=1): line = GPS.current_context().location().line() if line - count > 0: file = GPS.current_context().file().name() GPS.Editor.cursor_set_position(file, line - count) return True else: return False
def gps_fatal_error(msg): """Unconditional error""" global exit_status exit_status = FAILURE GPS.Logger('TESTSUITE').log(msg) GPS.exit(force=1) raise Exception("Fatal Error: %s" % msg)
def internalSpawn(self, filestr, project, recursive=False): if GPS.Preference('General-Auto-Save').get(): # Force, since otherwise we get a modal dialog while within # a GPS action, which gtk+ doesn't like modified = GPS.Project.root().is_modified(recursive=True) GPS.MDI.save_all(force=True) if modified: GPS.Project.root().recompute() self.full_output = "" opts_project = project opts = opts_project.get_attribute_as_list( "switches", package="check", index="ada") if len(opts) == 0: opts = opts_project.get_attribute_as_list( "default_switches", package="check", index="ada") if len(opts) == 0: opts_project = GPS.Project.root() opts = opts_project.get_attribute_as_list( "switches", package="check", index="ada") if len(opts) == 0: opts = opts_project.get_attribute_as_list( "default_switches", package="check", index="ada") # We need a rules file if none was specified in the project. need_rules_file = True if len(opts) != 0: for opt in opts: res = re.split("^\-from\=(.*)$", opt) if len(res) > 1: # we cd to the project's dir before creating the file, # as this will then correctly resolve if the file is # relative to the project's dir olddir = GPS.pwd() GPS.cd(opts_project.file().directory()) self.rules_file = GPS.File(res[1]) GPS.cd(olddir) need_rules_file = False if need_rules_file: # Display a dialog, but without using run(), since we are # running a GPS action in the task manager and that would # crash GPS on some platforms selector = rulesSelector(project.name(), self.rules_file) def on_response(dialog, response_id): if response_id == Gtk.ResponseType.OK: self.rules_file = selector.get_file() dialog.destroy() self.on_spawn(filestr, project, recursive) else: dialog.destroy() selector.connect('response', on_response) selector.show_all() else: self.on_spawn(filestr, project, recursive)
def reload_gnatcov_data(): """ Clean the coverage report and reload it from the files. """ # Switch to gcov mode if GPS.Preference("Coverage-Toolchain").get() != 'Gnatcov': GPS.Preference("Coverage-Toolchain").set('Gnatcov') GPS.execute_action("/Tools/Coverage/Clear coverage from memory") GPS.execute_action("/Tools/Coverage/Load data for all projects")
def close_editors_except_current(): """ Save and close all source editors, except the curret one. """ buffer = GPS.EditorBuffer.get(open=False) GPS.execute_action("/File/Save More/All") for ed in GPS.EditorBuffer.list(): if ed != buffer: ed.close(True)
def on_gps_started(hook_name): t = GPS.Toolbar() cut = GPS.ToolButton("gtk-cut", "Cut", lambda x: GPS.execute_action("/Edit/Cut")) copy = GPS.ToolButton("gtk-copy", "Copy", lambda x: GPS.execute_action("/Edit/Copy")) paste = GPS.ToolButton("gtk-paste", "Paste", lambda x: GPS.execute_action("/Edit/Paste")) t.insert(cut, 3, "Cut to Clipboard") t.insert(copy, 4, "Copy to Clipboard") t.insert(paste, 5, "Paste from Clipboard")
def __init__(self): """ Various initializations done before the gps_started hook """ self.port_pref = GPS.Preference("Plugins/python_support/port") self.port_pref.create( "Pydoc port", "integer", """Port that should be used when spawning the pydoc daemon. This is a small local server to which your web browser connects to display the documentation for the standard python library. It is accessed through the /Python menu when editing a python file""", 9432) # Add the language definition before the gps_started hook, so that # python files are correctly found GPS.Language.register(PythonLanguage(), "Python", ".py", "", ".pyc") XML = """ <filter_and name="Python file"> <filter id="Source editor" /> <filter language="Python" /> </filter_and> <documentation_file> <name>http://docs.python.org/2/tutorial/</name> <descr>Python tutorial</descr> <menu>/Help/Python/Python Tutorial</menu> <category>Scripts</category> </documentation_file> <documentation_file> <shell lang="python">""" XML += """GPS.execute_action('display python library help')</shell> <descr>Python Library</descr> <menu>/Help/Python/Python Library</menu> <category>Scripts</category> </documentation_file> """ if Gtk: XML += """ <documentation_file> <name>http://www.pygtk.org/pygtk2tutorial/index.html</name> <descr>PyGTK tutorial</descr> <menu>/Help/Python/PyGTK Tutorial</menu> <category>Scripts</category> </documentation_file> <documentation_file> <name>http://www.pygtk.org/pygtk2reference/index.html</name> <descr>PyGTK Reference Manual</descr> <menu>/Help/Python/PyGTK Reference Manual</menu> <category>Scripts</category> </documentation_file> """ GPS.parse_xml(XML)
def get_response_content(fs): # read the lat-lon points from the input lines = Util.get_stripped_lines(fs.datalines.splitlines()) rows = parse_lines(lines) latlon_points = [] city_names = [] for city, latd, latm, lond, lonm in rows: lat = math.radians(GPS.degrees_minutes_to_degrees(latd, latm)) lon = math.radians(GPS.degrees_minutes_to_degrees(lond, lonm)) latlon_points.append((lat, lon)) city_names.append(city) npoints = len(latlon_points) # start writing the response np.set_printoptions(linewidth=200) out = StringIO() radius = GPS.g_earth_radius_miles for dfunc, name in ( (GPS.get_arc_distance, 'great arc'), (GPS.get_euclidean_distance, 'euclidean')): # define the edm whose elements are squared euclidean-like distances edm = np.zeros((npoints, npoints)) D = np.zeros((npoints, npoints)) for i, pointa in enumerate(latlon_points): for j, pointb in enumerate(latlon_points): D[i, j] = dfunc(pointa, pointb, radius) edm[i, j] = D[i, j]**2 print >> out, name, 'distances:' print >> out, D print >> out print >> out, name, 'EDM:' print >> out, edm print >> out G = Euclid.edm_to_dccov(edm) print >> out, name, 'Gower centered matrix:' print >> out, G print >> out spectrum = np.array(list(reversed(sorted(np.linalg.eigvals(G))))) print >> out, name, 'spectrum of Gower centered matrix:' for x in spectrum: print >> out, x print >> out print >> out, name, 'rounded spectrum:' for x in spectrum: print >> out, '%.1f' % x print >> out mds_points = Euclid.edm_to_points(edm) print >> out, '2D MDS coordinates:' for name, mds_point in zip(city_names, mds_points): x = mds_point[0] y = mds_point[1] print >> out, '\t'.join(str(x) for x in [name, x, y]) print >> out # break between distance methods print >> out # return the response return out.getvalue()
def wait_doc(timeout): txt = GPS.Console("Messages").get_text() if txt.find("Documentation generated") == -1: return True else: # Log the output in log.txt f=open("log.txt", "w") f.write(GPS.Console ("Messages").get_text()) f.close() GPS.exit()
def apply_action(self): cur = self.cursor() if self.before: insert_loc = cur.forward_line(-1).end_of_line() else: insert_loc = cur.end_of_line() self.vim_state.view.goto(insert_loc) self.vim_state.buffer.insert(insert_loc, "\n") GPS.execute_action("/Edit/Format Selection") switch_state(self.vim_state, InsertState)
def before_exit(hook): """ Print error messages to stderr and exit GPS """ global before_exit_has_run if before_exit_has_run == 0: before_exit_has_run = 1 # We can force now, since any handling for not force has already been # handled GPS.exit(force=1, status=exit_status) return True
def on_gps_started(hook_name): "Initializes this module." init = """<action name='%(action)s' category='Editor'> <description> End the current Ada block, by providing the appropriate "end" statement </description> <filter language="ada" error='%(action)s requires an Ada file' /> <shell lang="python" output="none">block_completion.block_complete("%%F");</shell> </action>""" % {"action": action_name} GPS.parse_xml(init)
def __init__(self): # Create all custom things that do not require GPS' GUI to be ready # (i.e.: all but menus and hooks). for xml_nodes in ( self.PROJECT_ATTRIBUTES, self.BUILD_MODES, self.GNATCOV_DOCUMENTATION, self.GNATEMU_DOCUMENTATION, ): GPS.parse_xml(list_to_xml(xml_nodes)) # Defer further initialization to when GPS is completely ready. GPS.Hook('gps_started').add(self.on_gps_started)
def __find_subprogram_decl(): """ Return the subprogram declaration closest to the cursor. This returns a (MatchObject, line) tuple for the regexp subprograms_re """ f = GPS.current_context().file().path line = GPS.current_context().location().line() while line > 0: match = re.search(subprograms_re, GPS.Editor.get_chars(f, line, 1)) if match is not None: return (match, line) line = line - 1 return (None, 0)
def process_all_events(): """ Process all pending events. This is often needed in the testsuite, where we need to wait for events to be processed to make sure that a view is refreshed for instance. Using this function is not recommended in the general case, but is sometimes unavoidable. In general, it is better to use idle callbacks through GObject.idle_add, to avoid blocking the whole GPS interface. """ GPS.process_all_events()
def create_default_shell(): """Spawns the user's shell as read from the environment variable SHELL""" try: context = GPS.current_context() GPS.cd(context.directory()) except: pass if os.getenv("SHELL") and os.getenv("TERM"): Unix_Shell(os.getenv("SHELL"), "-i") elif os.getenv("COMSPEC"): Win32_Shell(os.getenv("COMSPEC"), "/Q")
def json_write(self): return json.dumps({ "imgpath": self.imgpath, "A": { "coord": GPS.dec2sex(self.A[1][1], self.A[1][0]), "xy": self.A[0] } if self.A is not None else None, "H": { "coord": GPS.dec2sex(self.H[1][1], self.H[1][0]), "xy": self.H[0] } if self.H is not None else None, "V": { "coord": GPS.dec2sex(self.V[1][1], self.V[1][0]), "xy": self.V[0] } if self.V is not None else None, "route": self.route, "walk_speed": self.walk_speed, }, indent = 4)
def on_gps_started (hook_name): """ Called once, when GPS is starting. """ global gnatcov_menu_separator if os_utils.locate_exec_on_path ("gnatcov") != "": GPS.Hook("compilation_finished").add(on_compilation_finished) menu = "/Tools/GNATcov/" ref = "Coverage" gnatcov_menu = GPS.Menu.create(menu + '-', ref=ref, add_before=False) GPS.parse_xml(xml.replace("@MENU@", 'menu="%s"' % menu))
def open_and_yield(self): """ Compatible with run_test_driver, to be used in a yield statement view = Variables_View() yield view.open_and_yield() ... """ yield self._open_and_yield("open debugger variables window") GPS.execute_action("open debugger variables window") self.view = GPS.MDI.get("Debugger Variables") gps_not_null(self.view, "Variables view not found") self.tree = get_widgets_by_type(Gtk.TreeView, self.view.pywidget()) self.tree = self.tree[0]
Other.saveLog(phaseLog, '9', 'Goal Detection Phase Started', time.time() - t_start) t_GoalDetection_start = time.time() print('Goal Detection Phase Started {}'.format(time.time() - t_start)) try: # --- calculate the distance to the goal --- # direction = Calibration.calculate_direction(lon2,lat2) goal_distance = direction["distance"] print('goal_distance = ', goal_distance) # --- if the distance to the goal is within 5 meters --- # while goal_distance <= 5: goal_value[0] = 1 # --- until the goal decision --- # while goal_value[0] != 0: goal_value = goaldetection.GoalDetection("/home/pi/photo/photo",200 ,20, 80, 7000) print("goalflug", goal_value[0], "goalarea",goal_value[1], "goalGAP", goal_value[2], "name", goal_value[3]) Other.saveLog(goalDetectionLog, time.time() - t_start, goal_value, GPS.readGPS()) if goal_value[0] != -1: # --- if the pixcel error is -30 or less, rotate left --- # if goal_value[2] <= -30.0: print('Turn left') run = pwm_control.Run() run.turn_left_l() time.sleep(0.5) # --- if the pixcel error is 30 or more, rotate right --- # elif 30 <= goal_value[2]: print('Turn right') run = pwm_control.Run() run.turn_right_l() time.sleep(0.5) # --- if the pixcel error is greater than -30 and less than 30, go straight --- # else:
luxjudge = Release.luxjudge() pressjudge = Release.pressjudge() if luxjudge == 1 or pressjudge == 1: break else: print("now in rocket ,taking photo") time.sleep(2) tx2 = time.time() else: print("RELEASE TIMEOUT") print("THE ROVER HAS RELEASED") pi.write(22, 1) # ------------------- Landing Fhase ------------------- # ty1 = time.time() ty2 = ty1 gpsData = GPS.readGPS() bme280Data = BME280.bme280_read() PRESS[0] = bme280Data[1] while (ty2 - ty1 <= y): pressjudge = Land.pressjudge() gpsjudge = Land.gpsjudge() if pressjudge == 1 and gpsjudge == 1: break elif pressjudge == 0 and gpsjudge == 0: print("Descend now taking photo") elif pressjudge == 1 or gpsjudge == 1: print("landjudgementnow") time.sleep(3) ty2 = time.time() else: print("RELEASE TIMEOUT")
to_write += [ AFE_data["temperature"], AFE_data["temperature raw"], AFE_data["NO2 ppm"], AFE_data["NO2 main"], AFE_data["NO2 aux"], AFE_data["OX ppm"], AFE_data["OX main"], AFE_data["OX aux"], AFE_data["SO2 ppm"], AFE_data["SO2 main"], AFE_data["SO2 aux"], AFE_data["CO ppm"], AFE_data["CO main"], AFE_data["CO aux"] ] pump_stop() if GPS_activation: # print("Wait switching from SPI to UART...", end='\r') # time.sleep(1) # avoid too close communication between SPI of OPC and UART of GPS # Get GPS information print("********************** GPS **********************") GPS_data = GPS.get_position() to_write += [ GPS_data["current time"], GPS_data["fix date and time"], GPS_data["latitude"], GPS_data["longitude"], GPS_data["SOG"], GPS_data["COG"], GPS_data["horizontal precision"], GPS_data["accuracy"], GPS_data["altitude"], GPS_data["WGS84 correction"], GPS_data["fix status"], GPS_data["status"] ] # Store everything in the csv file append_data_to_csv(now, *to_write) # Time at which the sampling finishes finish = time.time( ) # as previously, expressed in seconds since reference date
def on_terminate(status): out = "".join(output) if show_if_error and status != 0: GPS.Console().write("%s\n" % (" ".join(self.__command, ))) GPS.Console().write(out) p.resolve((status, "".join(output)))
def register_tool(): """Register the QGENC tool and its switches""" GPS.parse_xml("""<?xml version='1.0' ?> <GNAT_Studio> <project_attribute package="QGen" name="Output_Dir" editor_page="QGen" editor_section="Default Arguments" label="Output directory" description="The default location for QGen generated files" hide_in="wizard library_wizard"> <string type="directory"/> </project_attribute> <project_attribute package="QGen" name="Target" editor_page="QGen" list="true" label="Target" hide_in="wizard library_wizard"> <index attribute="main"> <string type="file" filter="project" default="(Simulink model file(s))"/> </index> </project_attribute> <project_attribute package="QGen" name="Debug_Args" editor_page="QGen" editor_section="Default Arguments" label="Debug arguments" description="Arguments to supply to gdb `run` when starting the QGen debugger" hide_in="wizard library_wizard"> <string /> </project_attribute> <target-model name="QGenc" category=""> <description>Generic launch of QGen</description> <iconname>gps-build-all-symbolic</iconname> <switches> </switches> </target-model> <target model="QGenc" category="_File_" name="QGen for file"> <in-toolbar>FALSE</in-toolbar> <in-menu>FALSE</in-menu> <launch-mode>MANUALLY_WITH_NO_DIALOG</launch-mode> <read-only>TRUE</read-only> <command-line> <arg>qgenc</arg> </command-line> </target> <tool name="QGen" package="QGen" index="QGen"> <language>QGen</language> <switches> <title line="1">Input Files</title> <title line="2">Generation Configuration</title> <title line="3">Output</title> <field line="1" label="Matlab file" switch="-m" separator=" " as-file="true" tip="Provides variable declarations of the Matlab workspace"/> <field line="1" label="Arithmetic operations configuration file" switch="--arith-conf" separator=" " as-file="true" tip="Specify a file containing the configuration for \ arithmetic operations"/> <field line="1" label="Custom block implementations configuration file" switch="--block-conf" separator=" " as-file="true" tip="Specify a file containing the configuration for \ custom block implementations"/> <field line="1" label="Library directory" switch="-b" separator=" " as-directory="true" tip=""/> <combo line="2" label="Target language" switch="-l" separator=" " tip="The language used by QGENC to produce the generated files"> <combo-entry label="Ada" value="ada"/> <combo-entry label="C" value="c"/> </combo> <check line="2" label="Generate unoptimized code" switch="--debug" tip=""/> <check line="2" label="Generate traceability infos for model debugging" switch="--trace" tip=""/> <radio line="2" label="MISRA violations" tip="The behavior when detecting MISRA Simulink violations"> <radio-entry label="Detect as errors" switch = ""/> <radio-entry label="Detect as warnings" switch="--wmisra"/> <radio-entry label="Accept" switch="--no-misra"/> </radio> <check line="2" label="Generate code for all model variants" switch="--all-variants" tip=""/> <check line="2" label="Generate entry point source file" switch="--gen-entrypoint" tip=""/> <check line="2" label="Always generate system variables as variables" switch="--consts-as-vars" tip=""/> <check line="2" label="Remove code for assertions blocks" switch="--remove-assertions" tip=""/> <check line="2" label="Remove goto statements" switch="--no-jump" tip=""/> <check line="2" label="Generate main subsystem's IO as global variables" switch="--global-io" tip=""/> <radio line = "2" label="Flattening strategy" tip="Controls the way source files are generated"> <radio-entry label="No flattening" switch=""/> <radio-entry label="Full flattening" switch="--full-flattening" /> <radio-entry label="Flattening by reference" switch="--ref-flattening"/> <radio-entry label="Flatten non reusable functions" switch="--noreuse-flattening" /> </radio> <field line="3" label="Output Directory" switch="-o" separator=" " as-directory="true" tip="Specify the output directory"/> <radio line="3" label="Output directory cleaning policy"> <radio-entry label="Ensure non existent" switch="" tip="Only generates code if the output directory does not exist"/> <radio-entry label="Delete" switch="-c" tip="Delete contents of output directory between compilations"/> <radio-entry label="Preserve" switch="-i" tip="Preserve contents of output directory between compilations"/> </radio> </switches> </tool> </GNAT_Studio>""")
def run_test(): # Open main.adb and check that 'copy_base_file_name' works buf = GPS.EditorBuffer.get(GPS.File("main.adb")) GPS.execute_action("copy_base_file_name") clipboard_contents = GPS.Clipboard().contents() gps_assert(clipboard_contents[GPS.Clipboard().current()], "main.adb", "copy_base_file_name not working on focused editors") # Close the editor and select main.adb in the Project view # and check that 'copy_file_name' works explorer = get_widget_by_name("Project Explorer Tree") windows = Gtk.Window.list_toplevels() explorer.grab_focus() select_in_tree(explorer, column=1, key="main.adb") GPS.execute_action("copy_file_name") clipboard_contents = GPS.Clipboard().contents() gps_assert(clipboard_contents[GPS.Clipboard().current()], GPS.File(os.path.join(GPS.pwd(), "main.adb")).path, "copy_file_name not working on files in the Project view") # Check that 'copy_file_name' works on directories from the # Project view select_in_tree(explorer, column=1, key=".") GPS.execute_action("copy_file_name") clipboard_contents = GPS.Clipboard().contents() gps_assert(clipboard_contents[GPS.Clipboard().current()], GPS.File(os.path.join(GPS.pwd())).path, "copy_file_name not working on dirs in the Project view")
visual_actions = dict( list(basic_actions.items()) + list({ "d": (VisualDeletion, ), "D": (VisualDeletion, ), "y": (VisualYank, ), "Y": (VisualYank, ) }.items())) modes_keymaps = defaultdict( dict, { NormalState: basic_actions, VisualState: visual_actions, VisualStateLine: visual_actions, VisualStateBox: visual_actions }) def on_file_edited(hn, f): def key_pressed_proxy(view, event): return view.vim_state.on_key_pressed(view, event) buffer = GPS.EditorBuffer.get(f) view = buffer.current_view() gtk_view = get_widgets_by_type(Gtk.TextView, view.pywidget())[0] gtk_view.vim_state = VimState(view, gtk_view) buffer.vim_state = gtk_view.vim_state gtk_view.connect("key-press-event", key_pressed_proxy) GPS.Hook("file_edited").add(on_file_edited)
def __enter__(self): GPS.freeze_prefs()
def __init__(self, f, reuse_existing=True, remote_target='', remote_protocol=''): """ Initialize a manager, begin a debugger on the given file with no timers, no promises, no command. The optional ``remote_target`` and ``remote_protocol`` parameters are used to initialize a remote debugging session when spawning the debugger. When not specified, the ``IDE'Program_Host`` and ``IDE'Communication_Protocol`` are used if present in the .gpr project file. """ if reuse_existing: try: # handler for debugger self.__debugger = GPS.Debugger.get() # Raise the debugger's console if we are reusing an existing # one. GPS.MDI.get_by_child( self.__debugger.get_console()).raise_window() # if we reach this, a debugger is running: interrupt it GPS.execute_action("debug interrupt") # Try to reconnect to the previous remote connection, if any GPS.execute_action("debug connect to board") except Exception: self.__debugger = GPS.Debugger.spawn( executable=f, remote_target=remote_target, remote_protocol=remote_protocol, load_executable=GPS.Preference( "Debugger-Load-On-Init").get()) if self.__debugger: pass else: raise Exception("Could not launch the debugger") else: self.__debugger = GPS.Debugger.spawn( executable=f, remote_target=remote_target, remote_protocol=remote_protocol, load_executable=GPS.Preference("Debugger-Load-On-Init").get()) if not self.__debugger: raise Exception("Could not launch the debugger") # current on waiting promise self.__this_promise = None # the command to be sent self.__next_cmd = None # the output returned after send __next_cmd self.__output = None # regular checker that checks if debugger is busy self.__timer = None # deadline for __next_cmd and __this_promise self.__deadline = None
def __init__(self, cmdargs=[], spawn_console=False, directory=None, regexp='.+', single_line_regexp=True, block_exit=True, give_focus_on_create=False): """ Initialize and run a process with no promises, no user-defined pattern to match, but a omnipotent regexp that catches everything. The process has empty output and two flags saying that the process is unfinished and no pattern has matched yet. If spawn_console is True, a console is spawned to display the process output. This console also allows the user to relaunch the associated process with a "Relaunch" button in the console toolbar. :param bool|str spawn_console: whether to display the process and its output to a console. If this is a boolean, then a new console named like the process is opened. If it is a string, it is the name of the console to use (the empty string reused GPS's Messages window). :param bool single_line_regexp: if True, then '.' in the regexp will also match '\n'. This is useful to capture larger parts of the output at once. :param bool block_exit: whether the user should be asked when GPS exits and this process is still running. :param bool give_focus_on_create: set it to True to give the focus to the spawned console, if any. """ # __current_promise = about on waiting wish for match something self.__current_promise = None # the stream that includes all output from the process self.__stream = None # __current_pattern = regexp that user waiting for in the output self.__current_pattern = None # __output = a buffer for current output of self.__process self.__output = "" # __whether process has finished self.finished = False # Used to know when the attached process is being relaunched via # th relaunch button. self.__relaunched = False # handler of process will be created -> start running # Remove empty command line arguments self.__command = [c for c in cmdargs if c] # The console associated with the process. # Created only if spawn_console is set to True. self.__console = None # Launch the command try: self.__process = GPS.Process(command=self.__command, directory=directory, regexp=regexp, single_line_regexp=single_line_regexp, block_exit=block_exit, on_match=self.__on_match, on_exit=self.__on_exit) except Exception: GPS.Logger("PROMISES").log("Failed to spawn %s" % (self.__command, )) self.__process = None return # Save the start time self.__start_time = time.time() # If requested, spawn a console to display the process output if spawn_console is not False: if isinstance(spawn_console, str): console_name = spawn_console else: console_name = cmdargs[0] toolbar_name = cmdargs[0] + '_toolbar' self.__console = GPS.Console( name=console_name, accept_input=False, on_destroy=self.__on_console_destroy, toolbar_name=toolbar_name, give_focus_on_create=give_focus_on_create) self.__action = GPS.Action('launch ' + cmdargs[0]) self.__console.write_with_links("%s\n" % ' '.join(self.__command)) # Create the associated action and relaunch button if it # does not exist yet. if not self.__action.exists(): self.__action.create( on_activate=self.__relaunch, description='relaunch the spawned process', icon='gps-refresh-symbolic') self.__action.button(toolbar=toolbar_name, label='Relaunch') def __show_console_on_exit(status): end_time = time.time() output = "\n" + TimeDisplay.get_timestamp(end_time) if not status: output += " process terminated successfully" else: output += " process exited with status " + str(status) output += ", elapsed time: " + TimeDisplay.get_elapsed( self.__start_time, end_time) + "\n" if self.__console: self.__console.write_with_links(output) def __display_output(out): if self.__console: self.__console.write_with_links("%s\n" % out) self.stream.subscribe(__display_output, oncompleted=__show_console_on_exit)
def __list_global_vars(): """List all non local variables referenced by the subprogram.""" list_vars(GPS.current_context().entity(), False)
def __list_local_vars(): """List all variables referenced by the subprogram.""" list_vars(GPS.current_context().entity(), True)
import GPS import RPi.GPIO as GPIO import time gps = GPS.GPS() #gps.turnOn() GPSdata = GPS.GPSData() print("start GPS read") while True: gps.readGPS()
def close(): pi.write(22,0) pi.write(24,0) GPS.closeGPS()
def __init__(self): GPS.execute_action("open breakpoints editor") self.view = GPS.MDI.get("Breakpoints") self.list = get_widgets_by_type(Gtk.TreeView, self.view.pywidget()) gps_not_null(self.list, 'List of breakpoints not found') self.list = self.list[0]
def __exit__(self, exc_type, exc_value, traceback): GPS.thaw_prefs()
x_end1, y_end1 = 100., -20.0 ''' # Coords start_coord = np.array([0., 0.]) end_coord = np.array([30., 0.]) start_coord1 = np.array([0, 0]) end_coord1 = np.array([30., 10]) start_coord2 = np.array([0, 0]) end_coord2 = np.array([30., 0]) steer = Steering(start_coord, end_coord) # Create object data = data_processing.Data() GPS = GPS.GPS() data.open_list("wheel_odometry.txt") steer.motor.stop_motors() # Set initial steering angle and calculate servo value ''' THIS LOOP IS ONLY FOR ONE COORDINATE, NOT FOR MULTIPLE '''
def __init__(self, ispell): """Create a new static contextual menu for spell checking""" GPS.Action('spell check word').contextual(self._label)
2 - BOOST 3 - COAST 4 - APOGEE 5 - UNDER DROGUE 6 - UNDER MAIN 7 - BALLISTIC """ State = 0 initializations = [] print("\n~~~~~~~~~~~INITIALIZING SUB-SYSTEMS~~~~~~~~~~~\n") filehandle.write("\n~~~~~~~~~~~INITIALIZING SUB-SYSTEMS~~~~~~~~~~~\n") try: GPS1 = GPS.GPS() except: print("COULD NOT CONNECT TO GPS") filehandle.write('COULD NOT CONNECT TO GPS\n') Initialization_Error = True try: ADC1 = ADS1x15.ADS1115() except: print("COULD NOT CONNECT TO ADC") filehandle.write('COULD NOT CONNECT TO ADC\n') Initialization_Error = True try: BARO1 = mpl3115a2.Barometer() except:
but it is sometimes more convenient to edit them by hand. You need to reload your project file (/Project/Reload Project) to force GPS to take into account your changes. """ import GPS XML = r"""<?xml version="1.0"?> <GPS> <Language> <Name>Project File</Name> <Parent>Ada</Parent> <Body_Suffix>.gpr</Body_Suffix> <Keywords>(a(bstract|t|ll)|case|e(nd|xte(nds|rnal))|for|is|li(brary|mited)|null|</Keywords> <Keywords>others|p(ackage|roject)|renames|type|use|w(hen|ith)|(aggregate|aggregate library|abstract|standard|configuration) project)\b</Keywords> <Context> <New_Line_Comment_Start>--</New_Line_Comment_Start> <String_Delimiter>"</String_Delimiter> <Constant_Character>'</Constant_Character> <Can_Indent>True</Can_Indent> <Syntax_Highlighting>True</Syntax_Highlighting> <Case_Sensitive>False</Case_Sensitive> </Context> </Language> </GPS> """ GPS.parse_xml(XML)
def up(count=1): file = GPS.current_context().file().name() line = GPS.current_context().location().line() GPS.Editor.cursor_set_position(file, line - count)
import binascii import signal import platform import pigpio from time import sleep portnumber = '/dev/ttyAMA0' import IM920 import GPS pi = pigpio.pi() if __name__ == '__main__': try: GPS.openGPS() pi = pigpio.pi() pi.set_mode(22, pigpio.OUTPUT) print('IM920 poweron') pi.write(22, 1) print('Send Start') while 1: gpsdata = GPS.readGPS() #IM920.Srid(19200,'3156') #ペアリング #IM920.Erid(19200) #削除 #IM920.Send('Hello') #文字列送信 IM920.Send(str(gpsdata)) #print(IM920.Reception(19200)) #文字列受信 #IM920.Repeater(19200) #中継機化 #IM920.Rdid(19200) #固有ID #IM920.Stch(19200, '01') #無線通信チャンネルの設定
def hook_handler(hook, *args): GPS.Hook(hook_name).remove(hook_handler) p.resolve(*args)
def get_line(): file = GPS.current_context().file().name() line_num = GPS.current_context().location().line() str = GPS.Editor.get_chars(file, line_num, 0) return str[:-1] # omit the '\n'
project_attributes = """ <project_attribute package="emulator" name="Debug_Port" label="Debug port" editor_page="GNATemulator" hide_in="wizard library_wizard" description="Port used by GNATemulator to debug." > <string/> </project_attribute> """ # This has to be done at GPS start, before the project is actually loaded. GPS.parse_xml(project_attributes) def log(msg): GPS.Logger("GNATemulator").log(msg) class GNATemulator(Module): # List of targets # These are created lazily the first time we find the necessary tools on # the command line. This is done so that we do not have to toggle the # visibility of these build targets too often, since that also trigger # the reparsing of Makefiles, for instance, and a refresh of all GUI # elements related to any build target. __buildTargets = []
def with_col(loc, col): return GPS.EditorLocation(loc.buffer(), loc.line(), col)
def __error_exit(self, msg=""): """ Emit an error and reset the workflows """ GPS.Console("Messages").write(msg + " [workflow stopped]", mode="error")
def log(msg): GPS.Logger("GNATemulator").log(msg)
def my_action(): target = GPS.BuildTarget("my_command") target.execute(synchronous=False)
def close(): GPS.closeGPS()