@Test public void testPrefWidthNegativeTreatedAsZero() { Region region = new Region(); region.setPrefWidth(-10); assertEquals(0, region.prefWidth(-1), 0); assertEquals(0, region.prefWidth(5), 0); }
@Test public void testMaxHeightNaNTreatedAsZero() { Region region = new Region(); region.setMaxHeight(Double.NaN); assertEquals(0, region.maxHeight(-1), 0); assertEquals(0, region.maxHeight(5), 0); }
// Test for RT-13820 @Test public void changingShapeElementsShouldResultInRender() { Region r = new Region(); r.setPrefWidth(640); r.setPrefHeight(480); LineTo lineTo; Path p = new Path( new MoveTo(0, 0), lineTo = new LineTo(100, 0), new LineTo(50, 100), new ClosePath()); r.setBackground(new Background(new BackgroundFill(Color.BLUE, null, null))); r.setCenterShape(true); r.setScaleShape(true); r.setShape(p); r.impl_syncPeer(); NGRegion peer = r.impl_getPeer(); assertFalse(peer.isClean()); peer.clearDirtyTree(); assertTrue(peer.isClean()); lineTo.setX(200); p.impl_syncPeer(); r.impl_syncPeer(); assertFalse(peer.isClean()); }
@Test public void testPrefWidthNaNTreatedAsZero() { Region region = new Region(); region.setPrefWidth(Double.NaN); assertEquals(0, region.prefWidth(-1), 0); assertEquals(0, region.prefWidth(5), 0); }
@Override public boolean onTouchEvent(MotionEvent event) { Point point = new Point(); point.x = (int) event.getX(); point.y = (int) event.getY(); int count = 0; for (PieSlice slice : slices) { Region r = new Region(); r.setPath(slice.getPath(), slice.getRegion()); if (r.contains(point.x, point.y) && event.getAction() == MotionEvent.ACTION_DOWN) { indexSelected = count; } else if (event.getAction() == MotionEvent.ACTION_UP) { if (r.contains(point.x, point.y) && listener != null) { if (indexSelected > -1) { listener.onClick(indexSelected); } indexSelected = -1; } } count++; } if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_UP) { postInvalidate(); } return true; }
public static Region fromJSON(final JSONObject json) throws JSONException { final JSONObject r = json.getJSONObject("rect"); final Rect rect = new Rect(r.getInt("left"), r.getInt("top"), r.getInt("right"), r.getInt("bottom")); final Region region = new Region(rect); final JSONArray actions = json.getJSONArray("actions"); for (int aIndex = 0; aIndex < actions.length(); aIndex++) { try { final JSONObject a = actions.getJSONObject(aIndex); final Touch type = Touch.valueOf(a.getString("type")); final String name = a.getString("name"); final Integer id = ActionEx.getActionId(name); if (id != null) { region.setAction(type, id, a.getBoolean("enabled")); } else { LCTX.e("Unknown action name: " + name); } } catch (final JSONException ex) { throw new JSONException( "Old perssitent format found. Touch action are returned to default ones: " + ex.getMessage()); } } return region; }
public Region unmarshall(StaxUnmarshallerContext context) throws Exception { Region region = new Region(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) targetDepth += 1; while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return region; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { if (context.testExpression("regionName", targetDepth)) { region.setRegionName(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("regionEndpoint", targetDepth)) { region.setEndpoint(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return region; } } } }
@Test public void testMaxHeightNegativeTreatedAsZero() { Region region = new Region(); region.setMaxHeight(-10); assertEquals(0, region.maxHeight(-1), 0); assertEquals(0, region.maxHeight(5), 0); }
public Polygonal2DRegionSelector(RegionSelector oldSelector, int maxPoints) { this(oldSelector.getIncompleteRegion().getWorld(), maxPoints); if (oldSelector instanceof Polygonal2DRegionSelector) { final Polygonal2DRegionSelector polygonal2DRegionSelector = (Polygonal2DRegionSelector) oldSelector; pos1 = polygonal2DRegionSelector.pos1; region = new Polygonal2DRegion(polygonal2DRegionSelector.region); } else { final Region oldRegion; try { oldRegion = oldSelector.getRegion(); } catch (IncompleteRegionException e) { return; } final int minY = oldRegion.getMinimumPoint().getBlockY(); final int maxY = oldRegion.getMaximumPoint().getBlockY(); List<BlockVector2D> points = oldRegion.polygonize(maxPoints); pos1 = points.get(0).toVector(minY).toBlockVector(); region = new Polygonal2DRegion(oldRegion.getWorld(), points, minY, maxY); } }
public Region getSelection(String player) { Region v = this.selections.get(player); if (v != null && v.getFirst() != null && v.getEnd() != null) return v; return null; }
/** * Get a random key from the given region that is within this instance's range. If no keys qualify * in the region, return null. * * @param aRegion - The region to get the key from. * @param excludeKey - The region to get the key from. * @returns A key from aRegion, or null. */ public Object getRandomKey(Region aRegion, Object excludeKey) { long start = System.currentTimeMillis(); int lower = ((Integer) (lowerKeyRange.get())).intValue(); int upper = ((Integer) (upperKeyRange.get())).intValue(); long randomKeyIndex = TestConfig.tab().getRandGen().nextLong(lower, upper); long startKeyIndex = randomKeyIndex; Object key = NameFactory.getObjectNameForCounter(randomKeyIndex); do { boolean done = false; if ((!(key.equals(excludeKey))) && (aRegion.containsKey(key))) done = true; if (done) break; randomKeyIndex++; // go to the next key if (randomKeyIndex > upper) randomKeyIndex = lower; if (randomKeyIndex == startKeyIndex) { // considered all keys key = null; break; } key = NameFactory.getObjectNameForCounter(randomKeyIndex); } while (true); long end = System.currentTimeMillis(); Log.getLogWriter() .info( "Done in TxUtilKeyRange:getRandomKey, key is " + key + " " + aRegion.getFullPath() + " getRandomKey took " + (end - start) + " millis"); return key; }
/** * This sequence is used to split the buffer between the given positions. It returns the positions * of the different parts. The positions of the separators can be kept. * * @param buffer is the buffer * @param posBegin is the beginning index * @param posEnd is the ending index * @param keepSeparator indicates if the positions of the separators are kept * @param spec is the escape character * @param inhibs are the ignored blocks * @return the positions of the different parts */ public List<Region> split( final StringBuffer buffer, int posBegin, int posEnd, boolean keepSeparator, Sequence spec, SequenceBlock[] inhibs) { List<Region> result = new ArrayList<Region>(); if (buffer != null && buffer.length() > 0 && posEnd > 0 && posEnd > posBegin) { int currentPos; if (posBegin < 0) { currentPos = 0; } else { currentPos = posBegin; } while (currentPos > -1 && currentPos < posEnd) { Region index = search(buffer, currentPos, posEnd, spec, inhibs); if (index.b() == -1) { if (posEnd > currentPos) { result.add(new Region(currentPos, posEnd, this)); } break; } if (index.b() > currentPos) { result.add(new Region(currentPos, index.b(), this)); } if (keepSeparator) { result.add(index); } currentPos = index.e(); } } return result; }
private void queuePlaceArmies(PlaceArmiesMove plm) { // should not ever happen if (plm == null) { System.err.println("Error on place_armies input."); return; } Region region = plm.getRegion(); Player player = getPlayer(plm.getPlayerName()); int armies = plm.getArmies(); // check legality if (region.ownedByPlayer(player.getName())) { if (armies < 1) { plm.setIllegalMove(" place-armies " + "cannot place less than 1 army"); } else { if (armies > player.getArmiesLeft()) // player wants to place more armies than he has left plm.setArmies(player.getArmiesLeft()); // place all armies he has left if (player.getArmiesLeft() <= 0) plm.setIllegalMove(" place-armies " + "no armies left to place"); player.setArmiesLeft(player.getArmiesLeft() - plm.getArmies()); } } else plm.setIllegalMove(plm.getRegion().getId() + " place-armies " + " not owned"); moveQueue.addMove(plm); }
protected void configureMessage( final Message message, final AOObject obj, final Region region, final String action) { Map<String, Serializable> messageMap = null; if (message instanceof PropertyMessage) { messageMap = ((PropertyMessage) message).getPropertyMapRef(); } else if (message instanceof WorldManagerClient.TargetedPropertyMessage) { messageMap = ((WorldManagerClient.TargetedPropertyMessage) message).getPropertyMapRef(); } if (messageMap != null) { if (action != null) { messageMap.put("regionAction", action); } if (this.messageProperties != null) { messageMap.putAll(this.messageProperties); } } final String messageRegionProperties = (String) region.getProperty("messageRegionProperties"); if (messageRegionProperties != null && messageMap != null) { this.copyProperties(messageRegionProperties, region.getPropertyMapRef(), messageMap); } final String objectProperties = (String) region.getProperty("messageObjectProperties"); if (objectProperties != null && messageMap != null) { this.copyProperties(objectProperties, obj.getPropertyMap(), messageMap); } if (Log.loggingDebug && messageMap != null) { Log.debug("MessageRegionTrigger: properties=" + DebugUtils.mapToString(messageMap)); } }
/** loads the weather-data from the internet and stores it in the shared preferences. */ private void reloadWeatherInfo(final MenuItem item) { // start refresh-icon-spinner item.setActionView(R.layout.action_progressbar); item.expandActionView(); int numberOfActiveRegions = 0; for (final Region region : regions) { if (region.isActive()) { numberOfActiveRegions++; } } final AsyncTaskCounter counter = new AsyncTaskCounter( numberOfActiveRegions, new AsyncTaskCounterCallback() { @Override public void onFinishedAllTasks() { // stop refresh-icon-spinner item.collapseActionView(); item.setActionView(null); } }); // refresh weather data for all active regions for (final Region region : regions) { if (region.isActive()) { final DownloadWeatherDataAsyncTask task = new DownloadWeatherDataAsyncTask(this, sharedPrefs, region, counter); task.execute(new URL[] {}); } } }
public final void debugRenderRegions(float landscape_x, float landscape_y) { int RADIUS = 30; int center_x = toGridCoordinate(landscape_x); int center_y = toGridCoordinate(landscape_y); int start_x = StrictMath.max(0, center_x - RADIUS); int end_x = StrictMath.min(occupants.length - 0, center_x + RADIUS); int start_y = StrictMath.max(0, center_y - RADIUS); int end_y = StrictMath.min(occupants.length - 0, center_y + RADIUS); GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glPointSize(3f); GL11.glBegin(GL11.GL_POINTS); Region last_region = null; for (int y = start_y; y < end_y; y++) for (int x = start_x; x < end_x; x++) { float xf = coordinateFromGrid(x); float yf = coordinateFromGrid(y); Region region = getRegion(x, y); if (region == null) { GL11.glColor3f(1f, 0f, 0f); } else { last_region = region; DebugRender.setColor(region.hashCode()); } GL11.glVertex3f(xf, yf, heightmap.getNearestHeight(xf, yf) + 2f); } GL11.glEnd(); GL11.glBegin(GL11.GL_LINES); GL11.glColor3f(1f, 0f, 0f); if (last_region != null) { last_region.debugRenderConnections(heightmap); last_region.debugRenderConnectionsReset(); } GL11.glEnd(); GL11.glEnable(GL11.GL_TEXTURE_2D); }
protected Point getRegionDimension(BoardState origState, int cellregion) { Vector<CellLocation> cells; CellLocation tempcell; int rheight = 0; int rwidth = 0; int xmin, xmax, ymin, ymax; xmin = ymin = 1000000; xmax = ymax = -1000000; Region region = ((Region[]) origState.getExtraData().get(0))[cellregion]; cells = region.getCells(); for (int c = 0; c < cells.size(); ++c) { if (origState.getCellContents(cells.get(c).getX(), cells.get(c).getY()) == Heyawake.CELL_WHITE) { continue; } if (cells.get(c).getX() < xmin) xmin = cells.get(c).getX(); if (cells.get(c).getY() < ymin) ymin = cells.get(c).getY(); if (cells.get(c).getX() > xmax) xmax = cells.get(c).getX(); if (cells.get(c).getY() > ymax) ymax = cells.get(c).getY(); } rwidth = xmax - xmin; rheight = ymax - ymin; return new Point(rwidth, rheight); }
@EventHandler(priority = EventPriority.HIGHEST) public void onPlayerInteract(PlayerInteractEvent e) { if (e.getItem() != null && e.getItem().getType() == selectionTools && e.getClickedBlock() != null && e.getPlayer().isOp()) { Region v = this.selections.get(e.getPlayer().getName()); if (v == null) { v = new Region(null, null); this.selections.put(e.getPlayer().getName(), v); } Location l = e.getClickedBlock().getLocation(); if (e.getAction() == Action.RIGHT_CLICK_BLOCK) { v.setEnd(l); if (plugin.portalRegionSelectionMessage) e.getPlayer().sendMessage("[BungeeSuiteBukkit] Second point set"); } else if (e.getAction() == Action.LEFT_CLICK_BLOCK) { v.setFirst(l); if (plugin.portalRegionSelectionMessage) e.getPlayer().sendMessage("[BungeeSuiteBukkit] First point set"); } } }
public List<String> getRegionsAsString() { List<String> reg = new ArrayList<String>(); for (Region r : this.regions) { reg.add(r.toString()); } return reg; }
public boolean doesRegionBorder(Region r) { for (Region re : this.regions) { if (re.doesRegionBorder(r)) return true; } return false; }
private void updateRegions(XY xy, ScribeMark mark) { List<Region> regionsContainingNewSquare = new ArrayList<Region>(); for (Region region : this.regions) { for (XY neighbor : xy.neighbors()) { if (this.get(neighbor) == mark && region.contains(neighbor)) { region.add(xy); regionsContainingNewSquare.add(region); break; } } } switch (regionsContainingNewSquare.size()) { case 0: Region newRegion = new Region(xy, mark); this.regions.add(newRegion); break; default: /* * merge all the regions into one */ Region mergedRegion = regionsContainingNewSquare.remove(0); for (Region region : regionsContainingNewSquare) { this.regions.remove(region); mergedRegion.addAll(region); } break; } }
public Region getOverlappingRegion(Region region) { for (Region r : this.regions) { if (!r.compare(region)) continue; return r; } return null; }
/** {@inheritDoc} */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // after user closed the settings: regionFragments = new ArrayList<RegionFragment>(numberOfRegions); for (final String selectionKey : selectionKeys) { final boolean selection = sharedPrefs.getBoolean(selectionKey, false); for (final Region region : regions) { if (region.getPreferencesKeySelection().equals(selectionKey)) { region.setActive(selection); if (selection) { regionFragments.add(region.getFragment()); } } } } // TODO something is still wrong about this regionsPageAdapter.updateData(regionFragments); regionsPageAdapter.notifyDataSetChanged(); reloadWeatherInfo(); }
public void testInstallAtLocation() throws BundleException, MalformedURLException, IOException { // create disconnected test regions Region r1 = digraph.createRegion(getName() + ".1"); Region r2 = digraph.createRegion(getName() + ".2"); String location = bundleInstaller.getBundleLocation(PP1); Bundle b1 = null; Bundle b2 = null; String l1 = null; String l2 = null; try { URL url = new URL(location); b1 = r1.installBundle(location + ".1", url.openStream()); l1 = b1.getLocation(); b2 = r2.installBundleAtLocation(location + ".2", url.openStream()); l2 = b2.getLocation(); } finally { if (b1 != null) { try { b1.uninstall(); } catch (BundleException e) { // ignore } } if (b2 != null) { try { b2.uninstall(); } catch (BundleException e) { // ignore } } } assertEquals("Wrong location found.", location + ".1#" + r1.getName(), l1); assertEquals("Wrong location found.", location + ".2", l2); }
/** * Возвращает подмножество регионов которые включают в себя указанную ячейку данной области * отчета. Подробная информация по заданной ячейке может быть получена при помощи вызова * * <pre> final Cell cell = this.getRows().get(row).getCells().get(col); </pre> * * @param colnum номер колонки в которой находится заданная ячейка. * @param rownum номер строки в которой находится заданная ячейка. Отсчет номеров строк начинается * с первой строки данной области строк. * @return список всех регионов определенных в данной области которые включают в себя указанную * ячейку области. */ public Collection<Region> getRegionsWithCell(final int colnum, final int rownum) { final ArrayList<Region> result = new ArrayList<Region>(); for (Region region : regions) { if (region.contains(colnum, rownum)) result.add(region); } return result; }
private void setScreenOrRegion(Object reg) { Region r = (Region) reg; MaxTimePerScan = (int) (1000.0 / r.getWaitScanRate()); offX = r.x; offY = r.y; log(3, "search in: \n%s", r); }
private Region generateClosedDoorPane(int n, int e, int s, int w) { Region closedDoor = new Region(); closedDoor.setPrefHeight(CELL_SIZE); closedDoor.setPrefWidth(CELL_SIZE); int north_gap = BORDER_WIDTH, east_gap = BORDER_WIDTH, south_gap = BORDER_WIDTH, west_gap = BORDER_WIDTH; if (n == 3) { north_gap = 0; } if (e == 3) { east_gap = 0; } if (s == 3) { south_gap = 0; } if (w == 3) { west_gap = 0; } Insets gap = new Insets(north_gap, east_gap, south_gap, west_gap); closedDoor.setBackground( new Background(new BackgroundFill(CLOSED_DOOR_COLOR, CornerRadii.EMPTY, gap))); return closedDoor; }
/** * Update an existing key in region REGION_NAME. The keys to update are specified in keyIntervals. * * @return true if all keys to be updated have been completed. */ protected boolean updateExistingKey() { long nextKey = CQUtilBB.getBB().getSharedCounters().incrementAndRead(CQUtilBB.LASTKEY_UPDATE_EXISTING_KEY); if (!keyIntervals.keyInRange(KeyIntervals.UPDATE_EXISTING_KEY, nextKey)) { Log.getLogWriter().info("All existing keys updated; returning from updateExistingKey"); return true; } Object key = NameFactory.getObjectNameForCounter(nextKey); QueryObject existingValue = (QueryObject) aRegion.get(key); if (existingValue == null) throw new TestException("Get of key " + key + " returned unexpected " + existingValue); QueryObject newValue = existingValue.modifyWithNewInstance(QueryObject.NEGATE, 0, true); newValue.extra = key; // encode the key in the object for later validation if (existingValue.aPrimitiveLong < 0) throw new TestException( "Trying to update a key which was already updated: " + existingValue.toStringFull()); Log.getLogWriter() .info("Updating existing key " + key + " with value " + TestHelper.toString(newValue)); aRegion.put(key, newValue); Log.getLogWriter() .info( "Done updating existing key " + key + " with value " + TestHelper.toString(newValue) + ", num remaining: " + (keyIntervals.getLastKey(KeyIntervals.UPDATE_EXISTING_KEY) - nextKey)); return (nextKey >= keyIntervals.getLastKey(KeyIntervals.UPDATE_EXISTING_KEY)); }
public void save() { // Sort list, add country to top, save types, put ids into type map List<RegionType> regionTypeList = new ArrayList(typeHashMap.values()); Collections.sort( regionTypeList, (object1, object2) -> object1.getShortName().compareTo(object2.getShortName())); regionTypeList.add(0, new RegionType(COUNTRY_ID, COUNTRY_TYPE)); // Add country to list after sort. typeHashMap.put(COUNTRY_TYPE, new RegionType(COUNTRY_ID, COUNTRY_TYPE)); // Save for (RegionType regionType : regionTypeList) { regionType.identity = insertRegionType(regionType); } // Save countries put ids into country map List<Country> countryList = new ArrayList(countryHashMap.values()); Collections.sort( countryList, (object1, object2) -> object1.getShortName().compareTo(object2.getShortName())); for (Country country : countryList) { country.identity = insertCountry(country); } // Save parent regions put ids into region map List<Region> regionList = new ArrayList(regionHashMap.values()); Collections.sort( regionList, (object1, object2) -> object1.getShortName().compareTo(object2.getShortName())); for (Region region : regionList) { if (region.parentCode == null || region.parentCode.isEmpty()) { region.identity = insertRegion(region); } } // Save child regions for (Region region : regionList) { if (region.parentCode != null && !region.parentCode.isEmpty()) { region.identity = insertRegion(region); } } // Save Region path to root, TODO really brute force, this could be SO better. regionList = new ArrayList(regionHashMap.values()); Collections.sort( regionList, (object1, object2) -> object1.getShortName().compareTo(object2.getShortName())); for (Region region : regionList) { if (!region.categoryName.equals(COUNTRY_TYPE)) { // region is not a country and so has a parent list. Country is the current top of the list. if (region.parentCode == null || region.parentCode.isEmpty()) { // if region has no parent, record country as parent node @ level 1 and leaf region as 2 insertNodePath(region.identity, countryHashMap.get(region.countryCode).identity, 1); insertNodePath(region.identity, region.identity, 2); } else { // if region has a parent, record country as parent node @ level 1, parent region as 2 and // leaf region as 3 insertNodePath(region.identity, countryHashMap.get(region.countryCode).identity, 1); insertNodePath(region.identity, regionHashMap.get(region.parentCode).identity, 2); insertNodePath(region.identity, region.identity, 3); } } } }
@Test public void testMaxHeightOverrideSetToPref() { Region region = new MockRegion(10, 20, 100, 200, 500, 600); assertEquals(600, region.maxHeight(-1), 1e-100); region.setMaxHeight(Region.USE_PREF_SIZE); assertEquals(Region.USE_PREF_SIZE, region.getMaxHeight(), 0); assertEquals(200, region.maxHeight(-1), 1e-100); }