/** * Getting All notes * * @param checkNavigation Tells if navigation status (notes, archived) must be kept in * consideration or if all notes have to be retrieved * @return Notes list */ public List<Note> getAllNotes(Boolean checkNavigation) { String whereCondition = ""; if (checkNavigation) { int navigation = Navigation.getNavigation(); switch (navigation) { case Navigation.NOTES: return getNotesActive(); case Navigation.ARCHIVE: return getNotesArchived(); case Navigation.REMINDERS: return getNotesWithReminder( prefs.getBoolean(Constants.PREF_FILTER_PAST_REMINDERS, false)); case Navigation.TRASH: return getNotesTrashed(); case Navigation.UNCATEGORIZED: return getNotesUncategorized(); case Navigation.CATEGORY: return getNotesByCategory(Navigation.getCategory()); default: return getNotes(whereCondition, true); } } else { return getNotes(whereCondition, true); } }
@Test public void testRequestForPrices() throws Exception { Navigation navigation = navigation(); Navigation.Markets markets = navigation.findMarkets( EventTypeName.SOCCER, between(now(), now().plusHours(6)), "Match Odds"); Iterable<MarketId> marketIds = limit(markets.marketsIds(), 5); PriceProjection priceProjection = new PriceProjection( newHashSet(PriceData.EX_BEST_OFFERS), new ExBestOfferOverRides(4, RollupModel.STAKE, null, null, null), true, false); httpAccess.listMarketBook( fileWriter(LIST_MARKET_BOOK_FILE), new ListMarketBook(marketIds, priceProjection, null, null, null, Locale.EN_US)); MarketBook[] marketBooks = JsonSerialization.parse( readFileToString(LIST_MARKET_BOOK_FILE.toFile()), MarketBook[].class); for (MarketBook marketBook : marketBooks) { System.out.println(marketBook); } }
/** 숫자값을 입력하면, 숫자값에 해당하는 방향이 스트링으로 나오겠끔 [동쪽으로 이동합니다] */ public static void main(String[] args) { System.out.println("가고자 하는 방향을 정하세요 동 : 1 서 : 2 남 : 3 북 : 4"); Scanner scanner = new Scanner(System.in); Navigation n = new Navigation(); n.setDirection(scanner.nextInt()); System.out.println(n.getDirection()); }
@Test @InSequence(2) public void adminCreateApplicationTest() { driver.get(contextRoot.toExternalForm()); loginPage.waitForPage(); loginPage.login(ADMIN_USERNAME, PASSWORD); if (passwordChangePage.isPagePresent()) { passwordChangePage.changePassword(PASSWORD); } navigation.goToApplications(); pushAppsPage.waitForPage(); navigation.goToApplications(); // initially there shouldn't exist any push applications while (!pushAppsPage.getApplicationList().isEmpty()) { Application application = pushAppsPage.getApplicationList().get(0); application.remove(); modal.waitForDialog(); modal.confirmName(application.getName()); modal.remove(); } pushAppsPage.pressCreateButton(); pushAppEditPage.registerNewPushApp(ADMIN_APPLICATION, ""); header.logout(); }
@Test public void creatingANavigationShouldLinkNavigationAndNode() { Id<Portal> classic = gateIn.siteId(Site.Type.PORTAL, "classic"); Portal portal = gateIn.get(classic); assert portal.equals(gateIn.getPortal(classic)); Page page = portal.getPageRegistry().get(classic.getIdforChild("page")); Id<Page> pageId = page.getId(); assert page.equals(gateIn.get(pageId)); Navigation nav = portal.getNavigation().get("page"); assert page.equals(nav.getTargetPage()); Page sub = portal.getPageRegistry().get("sub"); assert sub.equals(gateIn.get(pageId.getIdforChild("sub"))); Navigation navigation = portal.createNavigationTo(sub, portal.getNavigation()); assert sub.equals(navigation.getTargetPage()); assert sub.getInboundNavigations().contains(navigation.getId()); assert portal.getNavigation().contains(navigation.getName()); Navigation inboundNavigation = sub.createInboundNavigationIn(portal, portal.getNavigation()); assert sub.equals(inboundNavigation.getTargetPage()); assert sub.getInboundNavigations().contains(inboundNavigation.getId()); assert portal.getNavigation().contains(inboundNavigation.getName()); }
public void play() throws GameActionException { MapLocation dest = Abilities.ClosestPastr(rc, rc.getLocation(), ENEMY); if (dest != null) { Deque<Move> path = Navigation.pathAStar(rc, dest); while (Navigation.attackMoveOnPath(rc, path, INFO.type.attackRadiusMaxSquared, ENEMY)) { Tactics.killNearbyEnemies(rc, INFO); } } Tactics.killNearbyEnemies(rc, INFO); if (rc.isActive()) { wanderingDirection = Navigation.wonder(rc, rand, wanderingDirection); } else { rc.yield(); } }
/** Retrieves all notes with specified tags */ public List<Note> getNotesByTag(String[] tags) { // Select All Query StringBuilder whereCondition = new StringBuilder(); whereCondition.append(" WHERE "); for (int i = 0; i < tags.length; i++) { if (i != 0) { whereCondition.append(" AND "); } whereCondition .append("(" + KEY_CONTENT + " LIKE '%") .append(tags[i]) .append("%' OR ") .append(KEY_TITLE) .append(" LIKE '%") .append(tags[i]) .append("%')"); } // Trashed notes must be included in search results only if search if performed from trash whereCondition .append(" AND " + KEY_TRASHED + " IS ") .append(Navigation.checkNavigation(Navigation.TRASH) ? "" : "" + " NOT ") .append(" 1"); return getNotes(whereCondition.toString(), true); }
public static void main(String[] args) { Navigation n = new Navigation(128, 128); int[] start = new int[] {121, 126}; int[] end = new int[] {123, 132}; Node pathStart = n.getPath(start, end); n.map.mapX = TestMaps.getXMap(); n.map.mapY = TestMaps.getYMap(); for (int i = 119; i < 137; i++) { for (int j = 119; j < 137; j++) { if ((((n.map.mapX[i][(j) / 64] >>> (64 - (j % 64)) - 1) & 1L) == 1) && (((n.map.mapY[j][(i) / 64] >>> (64 - (i % 64)) - 1) & 1L) == 1)) { System.out.print(1 + " "); } else { boolean notVisited = true; if (pathStart != null) { Node path = new Node(pathStart); while (path != null) { if (path.location[0] == j && path.location[1] == i) { if (path.direction == 0) { System.out.print("F "); } else if (path.mapLast == null) { System.out.print("S "); } else { System.out.print("X "); } notVisited = false; break; } else { path = path.mapNext; } } } if (notVisited) { System.out.print(0 + " "); } } } System.out.println(); } }
@Test @InSequence(3) public void newUserCreateApplicationTest() { driver.get(contextRoot.toExternalForm()); loginPage.waitForPage(); loginPage.login(NEW_USER_USERNAME, NEW_USER_PASSWORD); if (passwordChangePage.isPagePresent()) { passwordChangePage.changePassword(NEW_USER_PASSWORD); } navigation.goToApplications(); pushAppsPage.waitForPage(); navigation.goToApplications(); pushAppsPage.pressCreateButton(); pushAppEditPage.registerNewPushApp(NEW_USER_APPLICATION, ""); header.logout(); }
/** * {@inheritDoc} * * <p>When the ghosts are not patrolling their home corners, Pinky wants to go to the place that * is four grid spaces ahead of Pac-Man in the direction that Pac-Man is facing. If Pac-Man is * facing down, Pinky wants to go to the location exactly four spaces below Pac-Man. Moving * towards this place uses the same logic that Blinky uses to find Pac-Man's exact location. Pinky * is affected by a targeting bug if Pac-Man is facing up - when he moves or faces up, Pinky tries * moving towards a point up, and left, four spaces. */ @Override public Direction nextMove() { Unit player = Navigation.findNearest(Player.class, getSquare()); if (player == null) { return randomMove(); } Direction targetDirection = player.getDirection(); Square destination = player.getSquare(); for (int i = 0; i < SQUARES_AHEAD; i++) { destination = destination.getSquareAt(targetDirection); } List<Direction> path = Navigation.shortestPath(getSquare(), destination, this); if (path != null && !path.isEmpty()) { return path.get(0); } return randomMove(); }
/** Checks for any login errors on the page. */ public void detectErrorsWay1() { // Are there any errors? if (!isElementExists(sXpath_LoginError)) return; // Get the error message String sErrorMessage = getText(findElement(driver, sXpath_LoginError)); if (sErrorMessage == null) sErrorMessage = "null"; // Construct the error message for the log String sError = "Login failed due to following reason: " + sErrorMessage + getNewLine(); Logs.log.error(sError); // Get current language to check error message Languages currentLanguage = Navigation.getCurrentLanguage(driver); /* * Based on error message throw corresponding exception */ // User Name blank? if (sErrorMessage.contains( Translations.voc .getWord(Keywords.sError_Login_UserName_Blank) .getTranscription(currentLanguage))) { throw new LoginUserNameBlankException(sError); } // Password blank? if (sErrorMessage.contains( Translations.voc .getWord(Keywords.sError_Login_Password_Blank) .getTranscription(currentLanguage))) { throw new LoginPasswordBlankException(sError); } // Credentials incorrect? if (sErrorMessage.contains( Translations.voc .getWord(Keywords.sError_Login_CredentialsWrong) .getTranscription(currentLanguage))) { throw new LoginCredentialsWrongException(sError); } // Password cannot be reused yet? if (sErrorMessage.contains( Translations.voc .getWord(Keywords.sError_Login_CannotUseSamePassword) .getTranscription(currentLanguage))) { throw new LoginCannotUseSamePasswordException(sError); } // Unknown error message throw new GenericUnexpectedException(sError); }
@Test public void test() throws Exception { Navigation navigation = navigation(); Navigation.Markets markets = navigation.findMarkets( EventTypeName.SOCCER, between(now(), now().plusHours(6)), "Match Odds"); PriceProjection priceProjection = new PriceProjection( newHashSet(PriceData.EX_BEST_OFFERS), new ExBestOfferOverRides(4, RollupModel.STAKE, null, null, null), true, false); MarketBook marketBook = new HttpExchangeOperations(httpAccess) .marketBook(markets.marketsIds().iterator().next(), priceProjection); System.out.println("marketBook = " + marketBook); }
/** * Gets notes matching pattern with title or content text * * @param pattern String to match with * @return Notes list */ public List<Note> getNotesByPattern(String pattern) { int navigation = Navigation.getNavigation(); String whereCondition = " WHERE " + KEY_TRASHED + (navigation == Navigation.TRASH ? " IS 1" : " IS NOT 1") + (navigation == Navigation.ARCHIVE ? " AND " + KEY_ARCHIVED + " IS 1" : "") + (navigation == Navigation.CATEGORY ? " AND " + KEY_CATEGORY + " = " + Navigation.getCategory() : "") + (navigation == Navigation.UNCATEGORIZED ? " AND (" + KEY_CATEGORY + " IS NULL OR " + KEY_CATEGORY_ID + " == 0) " : "") + (Navigation.checkNavigation(Navigation.REMINDERS) ? " AND " + KEY_REMINDER + " IS NOT NULL" : "") + " AND (" + " ( " + KEY_LOCKED + " IS NOT 1 AND (" + KEY_TITLE + " LIKE '%" + pattern + "%' " + " OR " + KEY_CONTENT + " LIKE '%" + pattern + "%' ))" + " OR ( " + KEY_LOCKED + " = 1 AND " + KEY_TITLE + " LIKE '%" + pattern + "%' )" + ")"; return getNotes(whereCondition, true); }
@Test @InSequence(4) public void developerApplicationListTest() { driver.get(contextRoot.toExternalForm()); loginPage.login(DEVELOPER_USERNAME, DEVELOPER_PASSWORD); if (passwordChangePage.isPagePresent()) { passwordChangePage.changePassword(DEVELOPER_PASSWORD); } navigation.goToApplications(); pushAppsPage.waitForPage(); assertEquals(0, pushAppsPage.countApplications()); assertFalse(pushAppsPage.applicationExists(ADMIN_APPLICATION, "")); }
@Test public void testRequestForResult() throws Exception { Navigation navigation = Navigation.parse( GenerateTestData.GetNavigation.getNavigationJson(LocalDate.parse("2014-08-08"))); Navigation.Markets markets = navigation.findMarkets( EventTypeName.SOCCER, between(now().minusDays(1), now()), "Match Odds"); Iterable<MarketId> marketIds = limit(markets.marketsIds(), 5); httpAccess.listMarketBook( fileWriter(LIST_MARKET_BOOK_FILE), new ListMarketBook(marketIds, null, null, null, null, Locale.EN_US)); MarketBook[] marketBooks = JsonSerialization.parse( readFileToString(LIST_MARKET_BOOK_FILE.toFile()), MarketBook[].class); for (MarketBook marketBook : marketBooks) { System.out.println(marketBook.prettyPrint()); } }
@Test @InSequence(7) public void newUserApplicationListTest() { driver.get(contextRoot.toExternalForm()); loginPage.waitForPage(); loginPage.login(NEW_USER_USERNAME, NEW_USER_PASSWORD); if (passwordChangePage.isPagePresent()) { passwordChangePage.changePassword(NEW_USER_PASSWORD); } navigation.goToApplications(); pushAppsPage.waitForPage(); assertEquals(1, pushAppsPage.countApplications()); assertTrue(pushAppsPage.applicationExists(NEW_USER_APPLICATION, "")); }
@Test @InSequence(6) public void adminApplicationListTest() { driver.get(contextRoot.toExternalForm()); loginPage.login(ADMIN_USERNAME, PASSWORD); if (passwordChangePage.isPagePresent()) { passwordChangePage.changePassword(PASSWORD); } navigation.goToApplications(); pushAppsPage.waitForPage(); assertEquals(3, pushAppsPage.countApplications()); assertTrue(pushAppsPage.applicationExists(ADMIN_APPLICATION, "")); assertTrue(pushAppsPage.applicationExists(DEVELOPER_APPLICATION, "")); assertTrue(pushAppsPage.applicationExists(NEW_USER_APPLICATION, "")); header.logout(); loginPage.waitForPage(); }
/** * Loads a set of tabs in the browser specified by the given session. * * @param session Session to load */ protected void loadSessionTabs(Session session) { // Verify initial about:home tab verifyTabCount(1); verifyUrl(StringHelper.ABOUT_HOME_URL); SessionTab[] tabs = session.getItems(); for (int i = 0; i < tabs.length; i++) { final SessionTab tab = tabs[i]; final PageInfo[] pages = tab.getItems(); // New tabs always start with about:home, so make sure about:home // is always the first entry. mAsserter.is( pages[0].url, StringHelper.ABOUT_HOME_URL, "first page in tab is " + StringHelper.ABOUT_HOME_URL); // If this is the first tab, the tab already exists, so no need to // create a new one. Otherwise, create a new tab if we're loading // the first the first page in the set. if (i > 0) { addTab(); } for (int j = 1; j < pages.length; j++) { Actions.EventExpecter pageShowExpecter = mActions.expectGoannaEvent("Content:PageShow"); loadUrl(pages[j].url); pageShowExpecter.blockForEvent(); pageShowExpecter.unregisterListener(); } final int index = tab.getIndex(); for (int j = pages.length - 1; j > index; j--) { mNavigation.back(); } } selectTabAt(session.getIndex()); }
public void doBoardSearch() { this.nav.travelTo(30, 30); this.nav.turnTo(2, false); nav.setSpeeds(-1 * ROTATION_SPEED, ROTATION_SPEED); while (!objectSeen()) {} nav.setSpeeds(0, 0); counter++; Double rightAngle = odo.getAng(); nav.setSpeeds(-1 * ROTATION_SPEED, ROTATION_SPEED); while (objectSeen()) {} nav.setSpeeds(0, 0); Double leftAngle = odo.getAng(); this.nav.turnTo(odo.getAng() - 5 - (0.5 * this.getAngleDistance(leftAngle, rightAngle)), false); this.nav.setSpeeds(0, 0); while (usPoller.getDistance() > 0.065) { this.nav.setSpeeds(50, 50); } this.nav.setSpeeds(0, 0); // go find another block this.nav.travelTo(30, 30); this.nav.turnTo(leftAngle + 20, false); nav.setSpeeds(-1 * ROTATION_SPEED, ROTATION_SPEED); while (!objectSeen()) {} nav.setSpeeds(0, 0); counter++; rightAngle = odo.getAng(); nav.setSpeeds(-1 * ROTATION_SPEED, ROTATION_SPEED); while (objectSeen()) {} nav.setSpeeds(0, 0); leftAngle = odo.getAng(); this.nav.turnTo(odo.getAng() - 5 - (0.5 * this.getAngleDistance(leftAngle, rightAngle)), false); this.nav.setSpeeds(0, 0); while (usPoller.getDistance() > 0.065) { this.nav.setSpeeds(50, 50); } this.nav.setSpeeds(0, 0); }
/** Retrieves all tags of a specified note */ public List<Tag> getTags(Note note) { List<Tag> tags = new ArrayList<>(); HashMap<String, Integer> tagsMap = new HashMap<>(); String whereCondition = " WHERE " + (note != null ? KEY_ID + " = " + note.get_id() + " AND " : "") + "(" + KEY_CONTENT + " LIKE '%#%' OR " + KEY_TITLE + " LIKE '%#%' " + ")" + " AND " + KEY_TRASHED + " IS " + (Navigation.checkNavigation(Navigation.TRASH) ? "" : " NOT ") + " 1"; List<Note> notesRetrieved = getNotes(whereCondition, true); for (Note noteRetrieved : notesRetrieved) { HashMap<String, Integer> tagsRetrieved = TagsHelper.retrieveTags(noteRetrieved); for (String s : tagsRetrieved.keySet()) { int count = tagsMap.get(s) == null ? 0 : tagsMap.get(s); tagsMap.put(s, ++count); } } for (String s : tagsMap.keySet()) { Tag tag = new Tag(s, tagsMap.get(s)); tags.add(tag); } Collections.sort(tags, (tag1, tag2) -> tag1.getText().compareToIgnoreCase(tag2.getText())); return tags; }
public void update(java.util.Observable observable, java.lang.Object obj) { Navigation navigation_ = null; try { navigation_ = (Navigation) obj; } catch (Exception excp) { System.out.println(excp); System.out.println("Visualization Component received wrong data type!"); } if (navigation_ != null) { // make sure all the values are in the proper range. navigation_.roll = (navigation_.roll > 180 || navigation_.roll < -180) ? 0 : navigation_.roll; navigation_.pitch = (navigation_.pitch > 90 || navigation_.pitch < -90) ? 0 : navigation_.pitch; // update the artificial horizon alt_hor_.update_display(navigation_.roll, navigation_.pitch); navigation_.pitch = (navigation_.position_latitude > 90 || navigation_.position_latitude < -90) ? 0 : navigation_.position_latitude; navigation_.pitch = (navigation_.position_longitude > 100 || navigation_.position_longitude < 00) ? 0 : navigation_.position_longitude; navigation_.pitch = (navigation_.altitude > 90 || navigation_.altitude < -90) ? 0 : navigation_.altitude; navigation_.pitch = (navigation_.heading > 180 || navigation_.heading < -180) ? 0 : navigation_.heading; // update the position display pos_.update_display( navigation_.position_latitude, navigation_.position_longitude, navigation_.altitude, navigation_.heading); } }
/** * This recursive method is responsible for finding the blue styrofoam block and returning it to * the green/red zone. The search and detect process will begin when the robot has reached the * green/red zone. * * @param x The x position of where the robot will start the search for the blue styrofoam block * @param y The y position of where the robot will start search for the blue styrofoam block */ public void doSearchAndDetect(double x, double y) { // Searching inside the green/red zone if (firstTry) { odox = odometer.getX(); odoy = odometer.getY(); odotheta = odometer.getTheta(); dashboard.turnLeft(40); try { Thread.sleep(750); } catch (Exception e) { } } else if (Math.abs(odox - odometer.getX()) > 15 && Math.abs(odoy - odometer.getY()) > 15) { odox = odometer.getX(); odoy = odometer.getY(); odotheta = odometer.getTheta(); dashboard.turnLeft(40); try { Thread.sleep(750); } catch (Exception e) { } } firstTry = false; // Initializing the heading angle when a robot detects something 35 cm away detectionAngle = odometer.getTheta(); Point greenZone = new Point((int) x, (int) y); // Remembering green zone dashboard.turnLeft(70); // Beginning the 360 degrees scan boolean clawIsDown = false; // The boolean found never becomes true so the robot will keep spinning until // it finds something then moves to a different zone or it will complete 1 full // revolution from its starting angle then move to a different zone. while (!found) { // Condition for the robot to move to a different area to search since it has // completed one full revolution if (Math.abs(odox - odometer.getX()) < 10 && Math.abs(odoy - odometer.getY()) < 10 && Math.abs(odotheta - odometer.getTheta()) < 5) { // Case where no objects in search radius if (directionCounter == 1) { // First time around, go to a point 15 cm south west of the green zone bottom // left corner directionCounter++; navigation.travelTo(greenZone.getX() - 15, greenZone.getY() - 15, false); } else if (directionCounter == 2) { // Second time around, go below the middle of the green zone directionCounter++; navigation.travelTo(greenZone.getX() + 30, greenZone.getY() - 15, false); } else if (directionCounter == 3) { // Third time, go north easy of of the green zone directionCounter++; navigation.travelTo(greenZone.getX() + 30, greenZone.getY() + 45, false); } else if (directionCounter == 4) { // Last time around, go to the middle of the playing field directionCounter = 1; navigation.travelTo(180, 180, false); } // After traveling to the new scan zone, perform the search and scan doSearchAndDetect(greenZone.getX(), greenZone.getY()); } else { // If the ultrasonic sensor senses something within 35 centimeters, go to the object if (usLow.getFilteredDistance() <= 35 && Math.abs(odometer.getTheta() - badHeading) > 30) { // Range to go check out object detectionAngle = odometer.getTheta(); // Saving heading angle when the object is detected blockAngle = odometer.getTheta(); previousDistance = usLow.getFilteredDistance(); navigation.turnTo( detectionAngle - 30.0); // Turning to past where object was detected so it can analyze the full // block Stopwatch stopwatch = new Stopwatch(); // Scanning whole object for 3 seconds to find shortest point of the object to robot while (stopwatch.elapsed() < (3 * Math.pow(10, 3))) { dashboard.turnRight( 70); // Turning to the right to analyze object since it overturned initially if (usLow.getFilteredDistance() < previousDistance) { dashboard.stop(); previousDistance = usLow.getFilteredDistance(); blockAngle = odometer.getTheta(); } } dashboard.stop(); navigation.turnTo(blockAngle); // Turn to block // Remembering tacho count in case object is a wooden block // so it will back up to exactly the same spot originalTacho = dashboard.getRightTacho(); Stopwatch watch = new Stopwatch(); while (usLow.getFilteredDistance() >= 10) { // If robot hasn't reached object in 8 seconds, most likely nothing there and false // positive if (watch.elapsed() > 9 * Math.pow(10, 3)) { badHeading = odometer.getTheta(); newTacho = dashboard.getRightTacho(); dashboard.rotateMotor(-(newTacho - originalTacho), -(newTacho - originalTacho), 200); dashboard.stop(); doSearchAndDetect(greenZone.getX(), greenZone.getY()); } // Travel to the object by going forward dashboard.goForward(200); } // Making a check for a wooden block by using the top ultrasonic sensor if (usHigh.getFilteredDistance() < 25) { // Brown Block so back up distance traveled to the block dashboard.stop(); badHeading = odometer .getTheta(); // Saving the angle of the wooden block so it doesn't go back when // it sees it again newTacho = dashboard.getRightTacho(); dashboard.rotateMotor(-(newTacho - originalTacho), -(newTacho - originalTacho), 200); dashboard.stop(); doSearchAndDetect(greenZone.getX(), greenZone.getY()); } else { // Go forward a bit more to get closer to the styrofoam block for (int i = 0; i < 200; i++) { dashboard.goForward(70); } } // 2nd check for brown block to make sure when closer to object if (usHigh.getFilteredDistance() < 25) { dashboard.stop(); badHeading = odometer.getTheta(); newTacho = dashboard.getRightTacho(); dashboard.rotateMotor(-(newTacho - originalTacho), -(newTacho - originalTacho), 200); dashboard.stop(); doSearchAndDetect(greenZone.getX(), greenZone.getY()); } else { // Return to dropzone then drop off and re-do scan newTacho = dashboard.getRightTacho(); // If doing search but the block is in the green/red zone, don't pick it up again if ((odometer.getX() > greenZone.getX() && odometer.getY() > greenZone.getY()) && (odometer.getX() < greenZone.getX() + 30 && odometer.getY() < greenZone.getY() + 30)) { badHeading = odometer.getTheta(); dashboard.rotateMotor(-(newTacho - originalTacho), -(newTacho - originalTacho), 200); dashboard.stop(); doSearchAndDetect(greenZone.getX(), greenZone.getY()); } dashboard.stop(); // Reached a good distance from the styrofoam block so back up // and get ready for the juggle. Stopwatch secondWatch = new Stopwatch(); while (secondWatch.elapsed() < 3 * Math.pow(10, 3)) { dashboard.goBackward(100); } dashboard.stop(); if (!clawIsDown) { // Arms are currently up so drop them since the block is // detected and close by lifter.dropClaw(); clawIsDown = true; } // Driving forward until the block is within 7 cm while (usLow.getFilteredDistance() >= 7) { dashboard.goForward(100); } juggle(); // Juggle to reposition the block so it is easier to pick dashboard.stop(); // Drive forward 8 cm so the block will be picked up perfectly dashboard.goForward(8, false); // Remember where the block was picked up so the robot // will return here after dropping off in the designated zone previousPickUp.setLocation(odometer.getX(), odometer.getY()); dashboard.stop(); lifter.lift(); // Picking up the block isCarrying = true; // Driving back to the green zone (a bit further to account) for the arms // and at this distance, the block is dropped off in the middle of the zone navigation.travelTo(greenZone.getX() + 45, greenZone.getY() + 45, false); // If it is the nth*2 time, robot will stack. if (!firstIteration) { lifter.stackLift(); } navigation.turnTo(180); // Turning so the block will end up in the middle of the zone dashboard.goForward( 2, false); // Going forward 2 cm so even closer to block (used for stacking purposes) lifter.dropBlock(); Stopwatch secondStop = new Stopwatch(); // After dropping it off, back up then lift arms while (secondStop.elapsed() < 3.5 * Math.pow(10, 3)) { dashboard.goBackward(100); } dashboard.stop(); lifter.postLift(); firstIteration = !firstIteration; // Only making stacks of 2 so reverse boolean navigation.travelTo( greenZone.getX() - 15, greenZone.getY(), false); // Travel to side of green zone so blocks are not touched when navigating // out of the zone navigation.travelTo( previousPickUp.getX(), previousPickUp.getY(), false); // Return to previous position of where styrofoam block was found doSearchAndDetect( greenZone.getX(), greenZone.getY()); // Do search and detect at the new position } } } } }
/** * Common method for notes retrieval. It accepts a query to perform and returns matching records. */ public List<Note> getNotes(String whereCondition, boolean order) { List<Note> noteList = new ArrayList<>(); String sort_column, sort_order = ""; // Getting sorting criteria from preferences. Reminder screen forces sorting. if (Navigation.checkNavigation(Navigation.REMINDERS)) { sort_column = KEY_REMINDER; } else { sort_column = prefs.getString(Constants.PREF_SORTING_COLUMN, KEY_TITLE); } if (order) { sort_order = KEY_TITLE.equals(sort_column) || KEY_REMINDER.equals(sort_column) ? " ASC " : " DESC "; } // In case of title sorting criteria it must be handled empty title by concatenating content sort_column = KEY_TITLE.equals(sort_column) ? KEY_TITLE + "||" + KEY_CONTENT : sort_column; // In case of reminder sorting criteria the empty reminder notes must be moved on bottom of // results sort_column = KEY_REMINDER.equals(sort_column) ? "IFNULL(" + KEY_REMINDER + ", " + "" + Constants.TIMESTAMP_UNIX_EPOCH + ")" : sort_column; // Generic query to be specialized with conditions passed as parameter String query = "SELECT " + KEY_CREATION + "," + KEY_LAST_MODIFICATION + "," + KEY_TITLE + "," + KEY_CONTENT + "," + KEY_ARCHIVED + "," + KEY_TRASHED + "," + KEY_REMINDER + "," + KEY_REMINDER_FIRED + "," + KEY_RECURRENCE_RULE + "," + KEY_LATITUDE + "," + KEY_LONGITUDE + "," + KEY_ADDRESS + "," + KEY_LOCKED + "," + KEY_CHECKLIST + "," + KEY_CATEGORY + "," + KEY_CATEGORY_NAME + "," + KEY_CATEGORY_DESCRIPTION + "," + KEY_CATEGORY_COLOR + " FROM " + TABLE_NOTES + " LEFT JOIN " + TABLE_CATEGORY + " USING( " + KEY_CATEGORY + ") " + whereCondition + (order ? " ORDER BY " + sort_column + sort_order : ""); Log.v(Constants.TAG, "Query: " + query); Cursor cursor = null; try { cursor = getDatabase().rawQuery(query, null); // Looping through all rows and adding to list if (cursor.moveToFirst()) { do { int i = 0; Note note = new Note(); note.setCreation(cursor.getLong(i++)); note.setLastModification(cursor.getLong(i++)); note.setTitle(cursor.getString(i++)); note.setContent(cursor.getString(i++)); note.setArchived("1".equals(cursor.getString(i++))); note.setTrashed("1".equals(cursor.getString(i++))); note.setAlarm(cursor.getString(i++)); note.setReminderFired(cursor.getInt(i++)); note.setRecurrenceRule(cursor.getString(i++)); note.setLatitude(cursor.getString(i++)); note.setLongitude(cursor.getString(i++)); note.setAddress(cursor.getString(i++)); note.setLocked("1".equals(cursor.getString(i++))); note.setChecklist("1".equals(cursor.getString(i++))); // Eventual decryption of content if (note.isLocked()) { note.setContent( Security.decrypt(note.getContent(), prefs.getString(Constants.PREF_PASSWORD, ""))); } // Set category long categoryId = cursor.getLong(i++); if (categoryId != 0) { Category category = new Category( categoryId, cursor.getString(i++), cursor.getString(i++), cursor.getString(i++)); note.setCategory(category); } // Add eventual attachments uri note.setAttachmentsList(getNoteAttachments(note)); // Adding note to list noteList.add(note); } while (cursor.moveToNext()); } } finally { if (cursor != null) cursor.close(); } Log.v(Constants.TAG, "Query: Retrieval finished!"); return noteList; }
public synchronized void update(RtecEventComm.Event event) { // System.out.println ("in NavWeapDataHandler.update"); Any any_value; PersianRecursion.Data persian_recursion_data; any_value = event.data.any_value; if (any_value.type().equal(PersianRecursion.DataHelper.type())) { // System.out.println ("type matched PersianRecursion.Data"); try { persian_recursion_data = PersianRecursion.DataHelper.extract(any_value); } catch (Exception e) { System.err.println(e.getMessage() + "\nThe stack trace is:\n"); e.printStackTrace(); return; } // System.out.println ("extracted any"); if (persian_recursion_data.criticality_level.equals( RtecScheduler.Criticality_t.HIGH_CRITICALITY) || persian_recursion_data.criticality_level.equals( RtecScheduler.Criticality_t.VERY_HIGH_CRITICALITY)) { // System.out.println ("obtaining high priority persian recursion observable"); PersianObservable pobs_hi = (PersianObservable) ObservablesTable.get("High Consumer Persian Recursion"); // System.out.println ("updating high priority persian recursion observable"); pobs_hi.updatePersianData(persian_recursion_data); // LatencyObservable lobs_hi = // (LatencyObservable) ObservablesTable.get ("High Consumer Execution Time (100 ns)"); // lobs_hi.updateLatency (persian_recursion_data.computation_time); } else { // System.out.println ("obtaining low priority persian recursion observable"); PersianObservable pobs_lo = (PersianObservable) ObservablesTable.get("Low Consumer Persian Recursion"); // System.out.println ("obtained low priority persian recursion observable"); // System.out.println ("updating low priority persian recursion observable"); pobs_lo.updatePersianData(persian_recursion_data); // System.out.println ("updated low priority persian recursion observable"); // LatencyObservable lobs_lo = // (LatencyObservable) ObservablesTable.get ("Low Consumer Execution Time (100 ns)"); // lobs_lo.updateLatency (persian_recursion_data.computation_time); } // System.out.println ("done updating PersianObservables"); received_events_++; // System.out.println ("total events received: " + received_events_); } else if (any_value.type().equal(NavigationHelper.type())) { Navigation navigation_ = NavigationHelper.extract(any_value); // if the navigation data structure's update data flag is set, // update its scheduling data with actual values from the EC if (navigation_.update_data > 0) { navigation_.arrival_time = event.header.creation_time; navigation_.completion_time = event.header.ec_send_time; navigation_.deadline_time += event.header.creation_time; } NavigationObservable nobs = (NavigationObservable) ObservablesTable.get("Navigation"); nobs.updateNavigation(navigation_); Cpu_UsageObservable cobs = (Cpu_UsageObservable) ObservablesTable.get("CPU Usage"); cobs.updateCpu_Usage(navigation_.utilization); OverheadObservable oobs = (OverheadObservable) ObservablesTable.get("Overhead"); oobs.updateOverhead(navigation_.overhead); JitterObservable jobs = (JitterObservable) ObservablesTable.get("Latency Jitter (100 ns)"); jobs.updateJitter( navigation_.completion_time, navigation_.computation_time, navigation_.arrival_time); JitterObservable njobs = (JitterObservable) ObservablesTable.get("Navigation Latency Jitter (100 ns)"); njobs.updateJitter( navigation_.completion_time, navigation_.computation_time, navigation_.arrival_time); DeadlinesObservable dobs = (DeadlinesObservable) ObservablesTable.get("Missed Deadlines"); dobs.updateDeadlines(navigation_.deadline_time, navigation_.completion_time); CriticalDeadlinesObservable cdobs = (CriticalDeadlinesObservable) ObservablesTable.get("Missed Critical Deadlines"); cdobs.updateDeadlines( navigation_.deadline_time, navigation_.completion_time, navigation_.criticality); LatencyObservable lobs = (LatencyObservable) ObservablesTable.get("Latency (100 ns)"); lobs.updateLatency( navigation_.completion_time, navigation_.computation_time, navigation_.arrival_time); LatencyObservable nlobs = (LatencyObservable) ObservablesTable.get("Navigation Latency (100 ns)"); nlobs.updateLatency( navigation_.completion_time, navigation_.computation_time, navigation_.arrival_time); received_events_++; } else if (any_value.type().equal(WeaponsHelper.type())) { Weapons weapons_ = WeaponsHelper.extract(any_value); // if the weapons structure's update data flag is set, update // itss scheduling data with actual values from the EC if (weapons_.update_data > 0) { weapons_.arrival_time = event.header.creation_time; weapons_.completion_time = event.header.ec_send_time; weapons_.deadline_time += event.header.creation_time; } WeaponsObservable wobs = (WeaponsObservable) ObservablesTable.get("Weapons"); ; wobs.updateWeapons(weapons_); Cpu_UsageObservable cobs = (Cpu_UsageObservable) ObservablesTable.get("CPU Usage"); cobs.updateCpu_Usage(weapons_.utilization); OverheadObservable oobs = (OverheadObservable) ObservablesTable.get("Overhead"); oobs.updateOverhead(weapons_.overhead); JitterObservable jobs = (JitterObservable) ObservablesTable.get("Latency Jitter (100 ns)"); jobs.updateJitter(weapons_.completion_time, weapons_.computation_time, weapons_.arrival_time); JitterObservable wjobs = (JitterObservable) ObservablesTable.get("Weapons Latency Jitter (100 ns)"); wjobs.updateJitter( weapons_.completion_time, weapons_.computation_time, weapons_.arrival_time); DeadlinesObservable dobs = (DeadlinesObservable) ObservablesTable.get("Missed Deadlines"); dobs.updateDeadlines(weapons_.deadline_time, weapons_.completion_time); CriticalDeadlinesObservable cdobs = (CriticalDeadlinesObservable) ObservablesTable.get("Missed Critical Deadlines"); cdobs.updateDeadlines(weapons_.deadline_time, weapons_.completion_time, weapons_.criticality); LatencyObservable lobs = (LatencyObservable) ObservablesTable.get("Latency (100 ns)"); lobs.updateLatency( weapons_.completion_time, weapons_.computation_time, weapons_.arrival_time); LatencyObservable wlobs = (LatencyObservable) ObservablesTable.get("Weapons Latency (100 ns)"); wlobs.updateLatency( weapons_.completion_time, weapons_.computation_time, weapons_.arrival_time); received_events_++; } else { System.out.println("Received wrong type information"); System.out.println("Received any_value.type (): [" + any_value.type() + "]"); System.out.println("Expected NavigationHelper.type (): [" + NavigationHelper.type() + "]"); System.out.println("OR WeaponsHelper.type (): [" + WeaponsHelper.type() + "]"); System.out.println( "OR PersianRecursion.DataHelper.type (): [" + PersianRecursion.DataHelper.type() + "]"); } }
/** * Logins into application.<br> * <B>Note:</B> I am <B>NOT</B> returning a page object because the user can change which page is * displayed on login. * * @param details - variables need to login */ public void loginAs(LoginDetails details) { // Switch languages if necessary Navigation.switchToUserLanguage(driver, details.lang); // Click the Change Password link if necessary if (details.bChangePassword) { clickChangePassword(); } // Enter UserName & Password enterUserName(details.sUserName); enterPassword(details.sPassword); // If necessary enter New Password & Confirm Password if (details.bChangePassword) { enterNewPassword(details.sNewPassword); enterConfirmPassword(details.sConfirmPassword); } // Click Login if (details.bChangePassword && !details.sNewPassword.equals(details.sConfirmPassword)) clickLogin(); else clickLoginAndWait(); // Handle possible alert boolean bAlertAccepted = false; String sAlertMessage = null; try { sAlertMessage = acceptAlert(driver); bAlertAccepted = true; } catch (Exception ex) { bAlertAccepted = false; } finally { // Assume that no exception will need to be thrown boolean bThrowException = false; // Alert appeared but no alert was expected as change password not done if (bAlertAccepted && !details.bChangePassword) { bThrowException = true; } // Alert appeared but no alert was expected as new password & confirm password were the same if (bAlertAccepted && details.bChangePassword) { if (details.sNewPassword.equals(details.sConfirmPassword)) bThrowException = true; } // No Alert appeared but expected an alert as new password & confirm password were different if (!bAlertAccepted && details.bChangePassword) { if (!details.sNewPassword.equals(details.sConfirmPassword)) bThrowException = true; } // Throw exception if necessary if (bThrowException) { String sError; if (bAlertAccepted) sError = "Alert with text '" + sAlertMessage + "' appeared but no alert was expected" + getNewLine(); else sError = "Alert did not appear but an alert was expected" + getNewLine(); Logs.log.error(sError); throw new GenericUnexpectedException(sError); } } // Did an expected alert appear? if (sAlertMessage != null) { // Construct error to write to log String sError = "Alert appeared with the text: " + sAlertMessage + getNewLine(); Logs.log.error(sError); // New Password & Confirm Password mismatch? if (sAlertMessage.contains( Translations.voc .getWord(Keywords.sError_Login_NewPasswordMismatch) .getTranscription(details.lang))) { throw new LoginChangePasswordException(sError); } // Unknown alert appeared throw new GenericUnexpectedException(sError); } // Detect inline errors // Custom way which uses similar code detectErrorsWay1(); // Using abstract class to reduce amount of duplicate code detectErrorsWay2(); // Close Last Login Popup if it appears closeLoginPopup(); }
public static void main(String[] args) { UltrasonicPoller frontPoller = new UltrasonicPoller("S4"); UltrasonicPoller sidePoller = new UltrasonicPoller("S1"); ColorSensorPoller blockPoller = new ColorSensorPoller("S2"); ColorSensorPoller groundPoller = new ColorSensorPoller("S3"); groundPoller.setMode(1); // start the block detector thread, which will be constantly checking with the light sensor // to see if there is a block. boolean wifiWorked = true; // *********************************WiFi module************************************// // Set up WiFi connection, require data from server, parse data and disconnect from server. WifiConnection conn = null; Transmission t = null; try { conn = new WifiConnection(SERVER_IP, TEAM_NUMBER); } catch (IOException e) { LCD.drawString("Connection failed", 0, 1); wifiWorked = false; } if (conn == null) { LCD.drawString("Unable to find Server", 0, 5); wifiWorked = false; } else { // Data received from the server is saved in "t". // Pass the data saved in t to the relevant class t = conn.getTransmission(); // Display the data in t if (t == null) { LCD.drawString("Failed to read transmission", 0, 5); wifiWorked = false; } else { conn.printTransmission(); } // Button.waitForAnyPress(); LCD.clear(); } // ********************************WiFi module ends******************************// if (wifiWorked) { // variables from WIFI int flagType = t.flagType; StartCorner startingCorner = t.startingCorner; int bottomLeftX = t.opponentHomeZoneBL_X; int bottomLeftY = t.opponentHomeZoneBL_Y; int topRightX = t.opponentHomeZoneTR_X; int topRightY = t.opponentHomeZoneTR_Y; int capturePointX = t.dropZone_X; int capturePointY = t.dropZone_Y; // variables HARDCODED // int flagType = 1; // StartCorner startingCorner = StartCorner.TOP_RIGHT; // int bottomLeftX = 3; // int bottomLeftY = 3; // int topRightX = 5; // int topRightY = 5; // int capturePointX = 1; // int capturePointY = 1; // ***********************Initialization Module******************************// // setup the odometer Odometer odo = new Odometer(leftMotor, rightMotor, 30, true); OdometerCorrector odoCorr = new OdometerCorrector(odo, groundPoller); // setup the wall avoider WallAvoider avoider = new WallAvoider(odo, frontPoller, sidePoller); // set up the navigator Navigation navi = new Navigation(odo, avoider, frontPoller, WHEEL_RADIUS, TRACK); // set up the detector BlockDetector blockDetector = new BlockDetector( blockPoller, navi, odo, frontPoller, verticalArmMotor, horizontalArmMotor, flagType); blockDetector.start(); // set up the searcher BlockZoneSearcher flagSearcher = new BlockZoneSearcher(sidePoller, frontPoller, navi, odo, blockDetector); // set up the LCD LCDDisplay lcd = new LCDDisplay(odo, frontPoller, sidePoller, blockPoller, blockDetector); lcd.start(); // set up the localization LightLocalizer lsl = new LightLocalizer( odo, groundPoller, navi, ROBOT_CENTRE_TO_LIGHTLOCALIZATION_SENSOR, startingCorner); USLocalizer usl = new USLocalizer(odo, navi, frontPoller, USLocalizer.LocalizationType.FULL_CIRCLE); // ***********************End of Initialization******************************// double angleForSearch; String searchDirection = ""; int searchStartX; int searchStartY; int firstCornerX; int firstCornerY; double zoneBuffer; // we use our starting corner to determine where we want to travel to in order to search. if (startingCorner == StartCorner.BOTTOM_LEFT || startingCorner == StartCorner.BOTTOM_RIGHT) { searchDirection = "down"; searchStartX = bottomLeftX; searchStartY = topRightY; firstCornerX = bottomLeftX; firstCornerY = bottomLeftY; zoneBuffer = -1 * TILE_WIDTH / 3.0; angleForSearch = 270; } else { // it is the top left or top right searchDirection = "up"; searchStartX = topRightX; searchStartY = bottomLeftY; firstCornerX = topRightX; firstCornerY = topRightY; zoneBuffer = TILE_WIDTH / 3.0; angleForSearch = 90; } /* * Step 1: Ultrasonic Localization * Figure out where we are, roughly */ // disable the side sensor for localization so that it doesn't interfere sidePoller.disableSensor(); // set the errors on the navigation to be large for US localization navi.setCmError(0.5); navi.setDegreeError(4.0); // perform ultra-sonic localization usl.doLocalization(); /* * Step 2: Light Localization * Figure out where we are, precisely */ // set the errors back to smaller values navi.setCmError(0.5); navi.setDegreeError(2.0); // perform light-sensor localization lsl.doLocalization(); /* * Step 3: Travel to first corner * Travel to the corner of the block zone in which we are going to relocalize */ // enable the side poller for navigating sidePoller.enableSensor(); // speed up the robot for navigation navi.setSlowSpeed(90); navi.setFastSpeed(160); // start odometry correction odoCorr.start(); // navigation navi.travelToAndAvoid(TILE_WIDTH * firstCornerX, TILE_WIDTH * firstCornerY); /* * Step 4: Relocalize * Use the lines to relocalize (figure out where we are, again) */ // perform second localization lsl.doRelocalization(TILE_WIDTH * firstCornerX, TILE_WIDTH * firstCornerY); /* * Step 5: Travel to second corner & rotate * Travel to the top (or bottom) corner of the block zone, and turn to searching position */ // we first travel a bit away from the zone navi.travelTo(TILE_WIDTH * firstCornerX + zoneBuffer, TILE_WIDTH * firstCornerY + zoneBuffer); // we travel to the second corner with no avoidance (there can't be any blocks there, anyway) navi.travelTo(TILE_WIDTH * searchStartX + zoneBuffer, TILE_WIDTH * searchStartY); navi.turnTo(angleForSearch, true); /* * Step 6: Search for block * Start to search around the perimeter for the block */ // lower errors navi.setCmError(0.4); navi.setDegreeError(3); // find dimensions of place to search int zoneWidth = topRightX - bottomLeftX; int zoneHeight = topRightY - bottomLeftY; // run searcher flagSearcher.searchZone(searchStartX, searchStartY, zoneWidth, zoneHeight, searchDirection); /* * Step 7: Drive to end position * We now have the block. Drive to the final position */ if (blockDetector.isFlag()) { // we want to travel to the center of the blocks. navi.travelToAndAvoid( capturePointX * TILE_WIDTH + TILE_WIDTH / 2, capturePointY * TILE_WIDTH + TILE_WIDTH / 2); // wifi } while (Button.waitForAnyPress() != Button.ID_ESCAPE) ; System.exit(0); } }
/** * Localizes the robot using the ultrasonic sensor. Clocks the angle at which the sensor detects * each wall and calculates 0 degrees */ public void doLocalization() { angleA = 0; angleB = 0; int UCdistance, expmtDistance; expmtDistance = 38; int count = 0; boolean facingToWall = true; // rotate the robot until it sees no wall nav.rotate(165, -165); facingToWall = true; while (facingToWall) { UCdistance = getFilteredData(); if (UCdistance > expmtDistance) { count++; } if (UCdistance > expmtDistance && count >= 3) { facingToWall = false; count = 0; } } sleep(3000); // keep rotating until the robot sees a wall, then latch the angle while (!facingToWall) { UCdistance = getFilteredData(); if (UCdistance < expmtDistance) { count++; } if (UCdistance < expmtDistance && count >= 3) { facingToWall = true; angleA = odo.getTheta(); Sound.beep(); nav.stopMotor(); count = 0; } } // switch direction and wait until it sees no wall nav.rotate(-165, 165); while (facingToWall) { UCdistance = getFilteredData(); if (UCdistance > expmtDistance) { count++; } if (UCdistance > expmtDistance && count >= 3) { facingToWall = false; count = 0; } } // keep rotating until the robot sees a wall, then latch the angle sleep(3000); while (!facingToWall) { UCdistance = getFilteredData(); if (UCdistance < expmtDistance) { count++; } if (UCdistance < expmtDistance && count >= 3) { facingToWall = true; angleB = odo.getTheta(); Sound.beep(); nav.stopMotor(); } } // angleA is clockwise from angleB, so assume the average of the // angles to the right of angleB is 45 degrees past 'north' // we slightly correct the angle '45' to '44' based on the error we measured angle = 45 - (angleA - angleB) / 2; // update the odometer position (example to follow:) odo.setTheta(angle); nav.turnTo(0); }