input
stringlengths
20
285k
output
stringlengths
20
285k
public static void beforeClass() throws Exception { server = new DummyServer("localhost", 6999); server.start(); server.register("my-app", "my-module", null, EchoBean.class.getSimpleName(), new EchoBean()); final Endpoint endpoint = Remoting.createEndpoint("endpoint", Executors.newSingleThreadExecutor(), OptionMap.EMPTY); final Xnio xnio = Xnio.getInstance(); final Registration registration = endpoint.addConnectionProvider("remote", new RemoteConnectionProviderFactory(xnio), OptionMap.create(Options.SSL_ENABLED, false)); final IoFuture<Connection> futureConnection = endpoint.connect(new URI("remote://localhost:6999"), OptionMap.create(Options.SASL_POLICY_NOANONYMOUS, Boolean.FALSE), new AnonymousCallbackHandler()); connection = get(futureConnection, 5, TimeUnit.SECONDS); }
public static void beforeClass() throws Exception { server = new DummyServer("localhost", 6999); server.start(); server.register("my-app", "my-module", "", EchoBean.class.getSimpleName(), new EchoBean()); final Endpoint endpoint = Remoting.createEndpoint("endpoint", Executors.newSingleThreadExecutor(), OptionMap.EMPTY); final Xnio xnio = Xnio.getInstance(); final Registration registration = endpoint.addConnectionProvider("remote", new RemoteConnectionProviderFactory(xnio), OptionMap.create(Options.SSL_ENABLED, false)); final IoFuture<Connection> futureConnection = endpoint.connect(new URI("remote://localhost:6999"), OptionMap.create(Options.SASL_POLICY_NOANONYMOUS, Boolean.FALSE), new AnonymousCallbackHandler()); connection = get(futureConnection, 5, TimeUnit.SECONDS); }
public void testShades() throws IOException { String mvn = System.getProperty("path.to.mvn", "mvn"); String version = BPMLocalTest.getBonitaVersion(); String thePom = getPom(version); File file = new File("shadeTester"); file.mkdir(); String outputOfMaven; try { File file2 = new File(file, "pom.xml"); IOUtil.write(file2, thePom); System.out.println("building " + file2.getAbsolutePath()); System.out.println("Run mvn in " + file.getAbsolutePath()); Process exec = Runtime.getRuntime().exec(mvn + " dependency:tree", new String[] {}, file); InputStream inputStream = exec.getInputStream(); exec.getOutputStream().close(); exec.getErrorStream().close(); outputOfMaven = IOUtil.read(inputStream); System.out.println(outputOfMaven); } finally { IOUtil.deleteDir(file); } assertTrue("build was not successfull", outputOfMaven.contains("BUILD SUCCESS")); outputOfMaven = outputOfMaven.replaceAll("bonitasoft.engine:bonita-server", ""); outputOfMaven = outputOfMaven.replaceAll("bonitasoft.engine:bonita-client", ""); outputOfMaven = outputOfMaven.replaceAll("bonitasoft.engine:bonita-common", ""); if (outputOfMaven.contains("bonitasoft")) { String str = "bonitasoft"; int indexOf = outputOfMaven.indexOf(str); String part1 = outputOfMaven.substring(indexOf - 50, indexOf - 1); String part2 = outputOfMaven.substring(indexOf - 1, indexOf + str.length()); String part3 = outputOfMaven.substring(indexOf + str.length(), indexOf + str.length() + 50); fail("the dependency tree contains other modules than server/client/common: \"" + part1 + " =====>>>>>" + part2 + " <<<<<=====" + part3); } }
public void testShades() throws IOException { String mvn = System.getProperty("path.to.mvn", "mvn"); String version = BPMLocalTest.getBonitaVersion(); String thePom = getPom(version); File file = new File("shadeTester"); file.mkdir(); String outputOfMaven; try { File file2 = new File(file, "pom.xml"); IOUtil.write(file2, thePom); System.out.println("building " + file2.getAbsolutePath()); System.out.println("Run mvn in " + file.getAbsolutePath()); Process exec = Runtime.getRuntime().exec(mvn + " dependency:tree", null, file); InputStream inputStream = exec.getInputStream(); exec.getOutputStream().close(); exec.getErrorStream().close(); outputOfMaven = IOUtil.read(inputStream); System.out.println(outputOfMaven); } finally { IOUtil.deleteDir(file); } assertTrue("build was not successfull", outputOfMaven.contains("BUILD SUCCESS")); outputOfMaven = outputOfMaven.replaceAll("bonitasoft.engine:bonita-server", ""); outputOfMaven = outputOfMaven.replaceAll("bonitasoft.engine:bonita-client", ""); outputOfMaven = outputOfMaven.replaceAll("bonitasoft.engine:bonita-common", ""); if (outputOfMaven.contains("bonitasoft")) { String str = "bonitasoft"; int indexOf = outputOfMaven.indexOf(str); String part1 = outputOfMaven.substring(indexOf - 50, indexOf - 1); String part2 = outputOfMaven.substring(indexOf - 1, indexOf + str.length()); String part3 = outputOfMaven.substring(indexOf + str.length(), indexOf + str.length() + 50); fail("the dependency tree contains other modules than server/client/common: \"" + part1 + " =====>>>>>" + part2 + " <<<<<=====" + part3); } }
public boolean use(Hero hero, LivingEntity target, String[] args) { Player player = hero.getPlayer(); if (target instanceof Player) { Player tPlayer = (Player) target; if (!(player.getItemInHand().getType() == Material.PAPER)) { Messaging.send(player, "You need paper to perform this."); return false; } if (playerSchedulers.containsKey(tPlayer.getEntityId())) { Messaging.send(player, "$1 is already being bandaged.", tPlayer.getName()); return false; } if (tPlayer.getHealth() >= 20) { Messaging.send(player, "$1 is already at full health.", tPlayer.getName()); return false; } tickHealth = config.getInt("tick-health", 1); ticks = config.getInt("ticks", 10); playerSchedulers.put(tPlayer.getEntityId(), plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new BandageTask(plugin, tPlayer), 20L, 20L)); notifyNearbyPlayers(player.getLocation().toVector(), "$1 is bandaging $2.", player.getName(), tPlayer == player ? "himself" : tPlayer.getName()); int firstSlot = player.getInventory().first(Material.PAPER); int num = player.getInventory().getItem(firstSlot).getAmount(); if (num == 1) { player.getInventory().clear(firstSlot); } else if (num > 1) { player.getInventory().getItem(firstSlot).setAmount(num - 1); } return true; } return false; }
public boolean use(Hero hero, LivingEntity target, String[] args) { Player player = hero.getPlayer(); if (target instanceof Player) { Player tPlayer = (Player) target; if (!(player.getItemInHand().getType() == Material.PAPER)) { Messaging.send(player, "You need paper to perform this."); return false; } if (playerSchedulers.containsKey(tPlayer.getEntityId())) { Messaging.send(player, "$1 is already being bandaged.", tPlayer.getName()); return false; } if (tPlayer.getHealth() >= 20) { Messaging.send(player, "$1 is already at full health.", tPlayer.getName()); return false; } tickHealth = config.getInt("tick-health", 1); ticks = config.getInt("ticks", 10); playerSchedulers.put(tPlayer.getEntityId(), plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new BandageTask(plugin, tPlayer), 20L, 20L)); notifyNearbyPlayers(player.getLocation().toVector(), "$1 is bandaging $2.", player.getName(), tPlayer == player ? "himself" : tPlayer.getName()); int firstSlot = player.getInventory().first(Material.PAPER); int num = player.getInventory().getItem(firstSlot).getAmount(); if (num == 1) { player.getInventory().clear(firstSlot); } else if (num > 1) { player.getInventory().getItem(firstSlot).setAmount(num - 1); } return true; } return false; }
private RubyTime createTime(IRubyObject[] args, boolean gmt) { int len = 6; if (args.length == 10) { args = new IRubyObject[] { args[5], args[4], args[3], args[2], args[1], args[0] }; } else { len = checkArgumentCount(args, 1, 7); } ThreadContext tc = getRuntime().getCurrentContext(); if(!(args[0] instanceof RubyNumeric)) { args[0] = args[0].callMethod(tc,"to_i"); } int year = (int)RubyNumeric.num2long(args[0]); int month = 0; if (len > 1) { if (!args[1].isNil()) { if (args[1] instanceof RubyString) { month = -1; for (int i = 0; i < 12; i++) { if (months[i].equalsIgnoreCase(args[1].toString())) { month = i; } } if (month == -1) { try { month = Integer.parseInt(args[1].toString()) - 1; } catch (NumberFormatException nfExcptn) { throw getRuntime().newArgumentError("Argument out of range."); } } } else { month = (int)RubyNumeric.num2long(args[1]) - 1; } } if (0 > month || month > 11) { throw getRuntime().newArgumentError("Argument out of range."); } } int[] int_args = { 1, 0, 0, 0, 0 }; for (int i = 0; len > i + 2; i++) { if (!args[i + 2].isNil()) { if(!(args[i+2] instanceof RubyNumeric)) { args[i+2] = args[i+2].callMethod(tc,"to_i"); } int_args[i] = (int)RubyNumeric.num2long(args[i + 2]); if (time_min[i] > int_args[i] || int_args[i] > time_max[i]) { throw getRuntime().newArgumentError("Argument out of range."); } } } Calendar cal = gmt ? Calendar.getInstance(TimeZone.getTimeZone(RubyTime.UTC)) : Calendar.getInstance(); RubyTime time = new RubyTime(getRuntime(), (RubyClass) this, cal); cal.set(year, month, int_args[0], int_args[1], int_args[2], int_args[3]); cal.set(Calendar.MILLISECOND, int_args[4] / 1000); time.setUSec(int_args[4] % 1000); time.callInit(args, Block.NULL_BLOCK); return time; }
private RubyTime createTime(IRubyObject[] args, boolean gmt) { int len = 6; if (args.length == 10) { args = new IRubyObject[] { args[5], args[4], args[3], args[2], args[1], args[0] }; } else { len = checkArgumentCount(args, 1, 7); } ThreadContext tc = getRuntime().getCurrentContext(); if(!(args[0] instanceof RubyNumeric)) { args[0] = args[0].callMethod(tc,"to_i"); } int year = (int)RubyNumeric.num2long(args[0]); int month = 0; if (len > 1) { if (!args[1].isNil()) { if (args[1] instanceof RubyString) { month = -1; for (int i = 0; i < 12; i++) { if (months[i].equalsIgnoreCase(args[1].toString())) { month = i; } } if (month == -1) { try { month = Integer.parseInt(args[1].toString()) - 1; } catch (NumberFormatException nfExcptn) { throw getRuntime().newArgumentError("Argument out of range."); } } } else { month = (int)RubyNumeric.num2long(args[1]) - 1; } } if (0 > month || month > 11) { throw getRuntime().newArgumentError("Argument out of range."); } } int[] int_args = { 1, 0, 0, 0, 0 }; for (int i = 0; len > i + 2; i++) { if (!args[i + 2].isNil()) { if(!(args[i+2] instanceof RubyNumeric)) { args[i+2] = args[i+2].callMethod(tc,"to_i"); } int_args[i] = (int)RubyNumeric.num2long(args[i + 2]); if (time_min[i] > int_args[i] || int_args[i] > time_max[i]) { throw getRuntime().newArgumentError("Argument out of range."); } } } Calendar cal = gmt ? Calendar.getInstance(TimeZone.getTimeZone(RubyTime.UTC)) : Calendar.getInstance(); cal.set(year, month, int_args[0], int_args[1], int_args[2], int_args[3]); cal.set(Calendar.MILLISECOND, int_args[4] / 1000); if (cal.getTimeInMillis() < 0) { throw getRuntime().newArgumentError("time out of range"); } RubyTime time = new RubyTime(getRuntime(), (RubyClass) this, cal); time.setUSec(int_args[4] % 1000); time.callInit(args, Block.NULL_BLOCK); return time; }
private void generateASCII() { System.out.println("Converting image into ASCII..."); this.output = ""; int width = this.output_image.getWidth(); int height = this.output_image.getHeight(); int last_percent = 0; for(int i = 0; i < height; ++i) { for(int j = 0; j < width; ++j) { String character = " "; int pixel = this.output_image.getRGB(j, i); int red = (pixel >> 16) & 0xff; int green = (pixel >> 8) & 0xff; int blue = (pixel) & 0xff; int grey = (int)(0.299 * red + 0.587 * green + 0.114 * blue); if(grey <= 100) { character = "+"; } else if(grey > 100 && grey <= 150) { character = "@"; } else if(grey > 150 && grey <= 240) { character = "*"; } this.output += character; } this.output += "\n\r"; int percent = (i / height) * 100; if(percent != last_percent) { last_percent = percent; System.out.println(String.format("Progress: %d%%", percent)); } } System.out.println("Image converted into ASCII!"); }
private void generateASCII() { System.out.println("Converting image into ASCII..."); this.output = ""; int width = this.output_image.getWidth(); int height = this.output_image.getHeight(); int last_percent = 0; for(int i = 0; i < height; ++i) { for(int j = 0; j < width; ++j) { String character = " "; int pixel = this.output_image.getRGB(j, i); int red = (pixel >> 16) & 0xff; int green = (pixel >> 8) & 0xff; int blue = (pixel) & 0xff; int grey = (int)(0.299 * red + 0.587 * green + 0.114 * blue); if(grey <= 100) { character = "+"; } else if(grey > 100 && grey <= 150) { character = "@"; } else if(grey > 150 && grey <= 240) { character = "*"; } this.output += character; } this.output += "\n"; int percent = (i / height) * 100; if(percent != last_percent) { last_percent = percent; System.out.println(String.format("Progress: %d%%", percent)); } } System.out.println("Image converted into ASCII!"); }
public void testProjectNameValue() throws Exception { final DistributedMasterBuilder masterBuilder = new DistributedMasterBuilder(); final Builder nestedBuilder = new MockBuilder(); masterBuilder.add(nestedBuilder); masterBuilder.setModule("deprecatedModule"); try { masterBuilder.build(new HashMap()); fail("Missing projectname property should have failed."); } catch (CruiseControlException e) { assertEquals(DistributedMasterBuilder.MSG_MISSING_PROJECT_NAME, e.getMessage()); } final Map projectProperties = new HashMap(); projectProperties.put(PropertiesHelper.PROJECT_NAME, "testProjectName"); masterBuilder.setFailFast(); try { masterBuilder.build(projectProperties); fail("Null agent should have failed."); } catch (CruiseControlException e) { assertEquals("Distributed build runtime exception", e.getMessage()); } }
public void testProjectNameValue() throws Exception { final DistributedMasterBuilder masterBuilder = DistributedMasterBuilderTest.getMasterBuilder_LocalhostONLY(); final Builder nestedBuilder = new MockBuilder(); masterBuilder.add(nestedBuilder); masterBuilder.setModule("deprecatedModule"); try { masterBuilder.build(new HashMap()); fail("Missing projectname property should have failed."); } catch (CruiseControlException e) { assertEquals(DistributedMasterBuilder.MSG_MISSING_PROJECT_NAME, e.getMessage()); } final Map projectProperties = new HashMap(); projectProperties.put(PropertiesHelper.PROJECT_NAME, "testProjectName"); masterBuilder.setFailFast(); try { masterBuilder.build(projectProperties); fail("Null agent should have failed."); } catch (CruiseControlException e) { assertEquals("Distributed build runtime exception", e.getMessage()); } }
public LinkedList<MIDPrimerCombo> loadMIDS() throws MIDFormatException { LinkedList <MIDPrimerCombo> MIDTags = new LinkedList <MIDPrimerCombo>(); int midCount = 0; try { String line = input.readLine(); while (line != null) { if(line.trim().length() == 0) { continue; } String[] columns = line.split(","); if(columns.length != 3) { columns = line.split("\t"); if(columns.length != 3) throw new MIDFormatException("Incorrect number of columns in " + inputLocation); } String descriptor = columns[0].trim(); String midTag = columns[1].trim(); String primerSeq = columns[2].trim(); for(int i = 0; i < midTag.length();i++) { char curr = midTag.charAt(i); if(! AcaciaEngine.getEngine().isIUPAC(curr)) { throw new MIDFormatException("Invalid MID sequence: " + midTag); } } midTag = midTag.replace("\"", ""); descriptor = descriptor.replace("\"", ""); MIDTags.add(new MIDPrimerCombo(midTag.toUpperCase(), primerSeq.toUpperCase(), descriptor)); line = input.readLine(); midCount++; } } catch (IOException ie) { System.out.println("An input exception occurred from " + inputLocation); } return MIDTags; }
public LinkedList<MIDPrimerCombo> loadMIDS() throws MIDFormatException { LinkedList <MIDPrimerCombo> MIDTags = new LinkedList <MIDPrimerCombo>(); int midCount = 0; try { String line = input.readLine(); while (line != null) { if(line.trim().length() == 0) { line = input.readLine(); continue; } String[] columns = line.split(","); if(columns.length != 3) { columns = line.split("\t"); if(columns.length != 3) throw new MIDFormatException("Incorrect number of columns in " + inputLocation); } String descriptor = columns[0].trim(); String midTag = columns[1].trim(); String primerSeq = columns[2].trim(); for(int i = 0; i < midTag.length();i++) { char curr = midTag.charAt(i); if(! AcaciaEngine.getEngine().isIUPAC(curr)) { throw new MIDFormatException("Invalid MID sequence: " + midTag); } } midTag = midTag.replace("\"", ""); descriptor = descriptor.replace("\"", ""); MIDTags.add(new MIDPrimerCombo(midTag.toUpperCase(), primerSeq.toUpperCase(), descriptor)); line = input.readLine(); midCount++; } } catch (IOException ie) { System.out.println("An input exception occurred from " + inputLocation); } return MIDTags; }
public Map pageListToMap(HttpServletRequest req, boolean loggedIn, Site site, SitePage page, String toolContextPath, String portalPrefix, boolean doPages, boolean resetTools, boolean includeSummary) { Map<String, Object> theMap = new HashMap<String, Object>(); String pageUrl = Web.returnUrl(req, "/" + portalPrefix + "/" + Web.escapeUrl(getSiteEffectiveId(site)) + "/page/"); String toolUrl = Web.returnUrl(req, "/" + portalPrefix + "/" + Web.escapeUrl(getSiteEffectiveId(site))); if (resetTools) { toolUrl = toolUrl + "/tool-reset/"; } else { toolUrl = toolUrl + "/tool/"; } String pagePopupUrl = Web.returnUrl(req, "/page/"); boolean showHelp = ServerConfigurationService.getBoolean("display.help.menu", true); String iconUrl = site.getIconUrlFull(); boolean published = site.isPublished(); String type = site.getType(); theMap.put("pageNavPublished", Boolean.valueOf(published)); theMap.put("pageNavType", type); theMap.put("pageNavIconUrl", iconUrl); List pages = getPermittedPagesInOrder(site); List<Map> l = new ArrayList<Map>(); for (Iterator i = pages.iterator(); i.hasNext();) { SitePage p = (SitePage) i.next(); List pTools = p.getTools(); ToolConfiguration firstTool = null; if (pTools != null && pTools.size() > 0) { firstTool = (ToolConfiguration) pTools.get(0); } String toolsOnPage = null; boolean current = (page != null && p.getId().equals(page.getId()) && !p .isPopUp()); String alias = lookupPageToAlias(site.getId(), p); String pagerefUrl = pageUrl + Web.escapeUrl((alias != null)?alias:p.getId()); if (doPages || p.isPopUp()) { Map<String, Object> m = new HashMap<String, Object>(); m.put("isPage", Boolean.valueOf(true)); m.put("current", Boolean.valueOf(current)); m.put("ispopup", Boolean.valueOf(p.isPopUp())); m.put("pagePopupUrl", pagePopupUrl); m.put("pageTitle", Web.escapeHtml(p.getTitle())); m.put("jsPageTitle", Web.escapeJavascript(p.getTitle())); m.put("pageId", Web.escapeUrl(p.getId())); m.put("jsPageId", Web.escapeJavascript(p.getId())); m.put("pageRefUrl", pagerefUrl); Iterator tools = pTools.iterator(); StringBuffer desc = new StringBuffer(); int tCount = 0; while(tools.hasNext()){ ToolConfiguration t = (ToolConfiguration)tools.next(); if (tCount > 0){ desc.append(" | "); } desc.append(t.getTool().getDescription()); tCount++; } String description = desc.toString().replace('"','-'); m.put("description", desc.toString()); if (toolsOnPage != null) m.put("toolsOnPage", toolsOnPage); if (includeSummary) summarizePage(m, site, p); if (firstTool != null) { String menuClass = firstTool.getToolId(); menuClass = "icon-" + menuClass.replace('.', '-'); m.put("menuClass", menuClass); } else { m.put("menuClass", "icon-default-tool"); } m.put("pageProps", createPageProps(p)); m.put("_sitePage", p); l.add(m); continue; } Iterator iPt = pTools.iterator(); while (iPt.hasNext()) { ToolConfiguration placement = (ToolConfiguration) iPt.next(); String toolrefUrl = toolUrl + Web.escapeUrl(placement.getId()); Map<String, Object> m = new HashMap<String, Object>(); m.put("isPage", Boolean.valueOf(false)); m.put("toolId", Web.escapeUrl(placement.getId())); m.put("jsToolId", Web.escapeJavascript(placement.getId())); m.put("toolRegistryId", placement.getToolId()); m.put("toolTitle", Web.escapeHtml(placement.getTitle())); m.put("jsToolTitle", Web.escapeJavascript(placement.getTitle())); m.put("toolrefUrl", toolrefUrl); String menuClass = placement.getToolId(); menuClass = "icon-" + menuClass.replace('.', '-'); m.put("menuClass", menuClass); m.put("_placement", placement); l.add(m); } } PageFilter pageFilter = portal.getPageFilter(); if (pageFilter != null) { l = pageFilter.filterPlacements(l, site); } theMap.put("pageNavTools", l); theMap.put("pageMaxIfSingle", ServerConfigurationService.getBoolean( "portal.experimental.maximizesinglepage", false)); theMap.put("pageNavToolsCount", Integer.valueOf(l.size())); String helpUrl = ServerConfigurationService.getHelpUrl(null); theMap.put("pageNavShowHelp", Boolean.valueOf(showHelp)); theMap.put("pageNavHelpUrl", helpUrl); theMap.put("helpMenuClass", "icon-sakai-help"); theMap.put("subsiteClass", "icon-sakai-subsite"); boolean showPresence; String globalShowPresence = ServerConfigurationService.getString("display.users.present"); if ("never".equals(globalShowPresence)) { showPresence = false; } else if ("always".equals(globalShowPresence)) { showPresence = true; } else { String showPresenceSite = site.getProperties().getProperty("display-users-present"); if (showPresenceSite == null) { showPresence = Boolean.valueOf(globalShowPresence).booleanValue(); } else { showPresence = Boolean.valueOf(showPresenceSite).booleanValue(); } } String presenceUrl = Web.returnUrl(req, "/presence/" + Web.escapeUrl(site.getId())); theMap.put("pageNavShowPresenceLoggedIn", Boolean.valueOf(showPresence && loggedIn)); theMap.put("pageNavPresenceUrl", presenceUrl); return theMap; }
public Map pageListToMap(HttpServletRequest req, boolean loggedIn, Site site, SitePage page, String toolContextPath, String portalPrefix, boolean doPages, boolean resetTools, boolean includeSummary) { Map<String, Object> theMap = new HashMap<String, Object>(); String pageUrl = Web.returnUrl(req, "/" + portalPrefix + "/" + Web.escapeUrl(getSiteEffectiveId(site)) + "/page/"); String toolUrl = Web.returnUrl(req, "/" + portalPrefix + "/" + Web.escapeUrl(getSiteEffectiveId(site))); if (resetTools) { toolUrl = toolUrl + "/tool-reset/"; } else { toolUrl = toolUrl + "/tool/"; } String pagePopupUrl = Web.returnUrl(req, "/page/"); boolean showHelp = ServerConfigurationService.getBoolean("display.help.menu", true); String iconUrl = site.getIconUrlFull(); boolean published = site.isPublished(); String type = site.getType(); theMap.put("pageNavPublished", Boolean.valueOf(published)); theMap.put("pageNavType", type); theMap.put("pageNavIconUrl", iconUrl); List pages = getPermittedPagesInOrder(site); List<Map> l = new ArrayList<Map>(); for (Iterator i = pages.iterator(); i.hasNext();) { SitePage p = (SitePage) i.next(); List pTools = p.getTools(); ToolConfiguration firstTool = null; if (pTools != null && pTools.size() > 0) { firstTool = (ToolConfiguration) pTools.get(0); } String toolsOnPage = null; boolean current = (page != null && p.getId().equals(page.getId()) && !p .isPopUp()); String alias = lookupPageToAlias(site.getId(), p); String pagerefUrl = pageUrl + Web.escapeUrl((alias != null)?alias:p.getId()); if (doPages || p.isPopUp()) { Map<String, Object> m = new HashMap<String, Object>(); m.put("isPage", Boolean.valueOf(true)); m.put("current", Boolean.valueOf(current)); m.put("ispopup", Boolean.valueOf(p.isPopUp())); m.put("pagePopupUrl", pagePopupUrl); m.put("pageTitle", Web.escapeHtml(p.getTitle())); m.put("jsPageTitle", Web.escapeJavascript(p.getTitle())); m.put("pageId", Web.escapeUrl(p.getId())); m.put("jsPageId", Web.escapeJavascript(p.getId())); m.put("pageRefUrl", pagerefUrl); Iterator tools = pTools.iterator(); StringBuffer desc = new StringBuffer(); int tCount = 0; while(tools.hasNext()){ ToolConfiguration t = (ToolConfiguration)tools.next(); if (tCount > 0){ desc.append(" | "); } if ( t.getTool() == null ) continue; desc.append(t.getTool().getDescription()); tCount++; } String description = desc.toString().replace('"','-'); m.put("description", desc.toString()); if (toolsOnPage != null) m.put("toolsOnPage", toolsOnPage); if (includeSummary) summarizePage(m, site, p); if (firstTool != null) { String menuClass = firstTool.getToolId(); menuClass = "icon-" + menuClass.replace('.', '-'); m.put("menuClass", menuClass); } else { m.put("menuClass", "icon-default-tool"); } m.put("pageProps", createPageProps(p)); m.put("_sitePage", p); l.add(m); continue; } Iterator iPt = pTools.iterator(); while (iPt.hasNext()) { ToolConfiguration placement = (ToolConfiguration) iPt.next(); String toolrefUrl = toolUrl + Web.escapeUrl(placement.getId()); Map<String, Object> m = new HashMap<String, Object>(); m.put("isPage", Boolean.valueOf(false)); m.put("toolId", Web.escapeUrl(placement.getId())); m.put("jsToolId", Web.escapeJavascript(placement.getId())); m.put("toolRegistryId", placement.getToolId()); m.put("toolTitle", Web.escapeHtml(placement.getTitle())); m.put("jsToolTitle", Web.escapeJavascript(placement.getTitle())); m.put("toolrefUrl", toolrefUrl); String menuClass = placement.getToolId(); menuClass = "icon-" + menuClass.replace('.', '-'); m.put("menuClass", menuClass); m.put("_placement", placement); l.add(m); } } PageFilter pageFilter = portal.getPageFilter(); if (pageFilter != null) { l = pageFilter.filterPlacements(l, site); } theMap.put("pageNavTools", l); theMap.put("pageMaxIfSingle", ServerConfigurationService.getBoolean( "portal.experimental.maximizesinglepage", false)); theMap.put("pageNavToolsCount", Integer.valueOf(l.size())); String helpUrl = ServerConfigurationService.getHelpUrl(null); theMap.put("pageNavShowHelp", Boolean.valueOf(showHelp)); theMap.put("pageNavHelpUrl", helpUrl); theMap.put("helpMenuClass", "icon-sakai-help"); theMap.put("subsiteClass", "icon-sakai-subsite"); boolean showPresence; String globalShowPresence = ServerConfigurationService.getString("display.users.present"); if ("never".equals(globalShowPresence)) { showPresence = false; } else if ("always".equals(globalShowPresence)) { showPresence = true; } else { String showPresenceSite = site.getProperties().getProperty("display-users-present"); if (showPresenceSite == null) { showPresence = Boolean.valueOf(globalShowPresence).booleanValue(); } else { showPresence = Boolean.valueOf(showPresenceSite).booleanValue(); } } String presenceUrl = Web.returnUrl(req, "/presence/" + Web.escapeUrl(site.getId())); theMap.put("pageNavShowPresenceLoggedIn", Boolean.valueOf(showPresence && loggedIn)); theMap.put("pageNavPresenceUrl", presenceUrl); return theMap; }
protected void onRowPopulated(final WebMarkupContainer rowComponent) { if (disableRowClickNotifications()) return; rowComponent.add(new AjaxFormSubmitBehavior(getForm(), "onclick") { private static final long serialVersionUID = 1L; @Override protected void onSubmit(AjaxRequestTarget target) { } @Override protected void onError(AjaxRequestTarget target) { } @Override protected void onEvent(AjaxRequestTarget target) { Form form = getForm(); form.visitFormComponentsPostOrder(new FormComponent.AbstractVisitor() { public void onFormComponent(final FormComponent formComponent) { if (formComponent.isVisibleInHierarchy()) { formComponent.inputChanged(); } } }); String column = getRequest().getParameter("column"); lastClickedColumn = column; IModel model = rowComponent.getModel(); IGridColumn lastClickedColumn = getLastClickedColumn(); if (lastClickedColumn != null && lastClickedColumn.cellClicked(model) == true) { return; } onRowClicked(target, model); } @Override public CharSequence getCallbackUrl() { return super.getCallbackUrl() + "&column='+col+'"; } @Override protected IAjaxCallDecorator getAjaxCallDecorator() { return new AjaxCallDecorator() { private static final long serialVersionUID = 1L; @Override public CharSequence decorateScript(CharSequence script) { return super.decorateScript("if (InMethod.XTable.canSelectRow(event)) { " + "var col=(this.imxtClickedColumn || ''); this.imxtClickedColumn='';" + script + " } else return false;"); } }; } }); }
protected void onRowPopulated(final WebMarkupContainer rowComponent) { if (disableRowClickNotifications()) return; rowComponent.add(new AjaxFormSubmitBehavior(getForm(), "onclick") { private static final long serialVersionUID = 1L; @Override protected void onSubmit(AjaxRequestTarget target) { } @Override protected void onError(AjaxRequestTarget target) { } @Override protected void onEvent(AjaxRequestTarget target) { Form form = getForm(); form.visitFormComponentsPostOrder(new FormComponent.AbstractVisitor() { public void onFormComponent(final FormComponent formComponent) { if (formComponent.isVisibleInHierarchy()) { formComponent.inputChanged(); } } }); String column = getRequest().getParameter("column"); lastClickedColumn = column; IModel model = rowComponent.getModel(); IGridColumn lastClickedColumn = getLastClickedColumn(); if (lastClickedColumn != null && lastClickedColumn.cellClicked(model) == true) { return; } onRowClicked(target, model); } @Override public CharSequence getCallbackUrl() { return super.getCallbackUrl() + "&column='+col+'"; } @Override protected IAjaxCallDecorator getAjaxCallDecorator() { return new AjaxCallDecorator() { private static final long serialVersionUID = 1L; @Override public CharSequence decorateScript(CharSequence script) { return super.decorateScript("if (InMethod.XTable.canSelectRow(event)) { " + "var col=(this.imxtClickedColumn || ''); this.imxtClickedColumn='';" + script + " }"); } }; } }); }
private void editResource (AppleResponse res, AppleRequest req, String type, String messages) { boolean validated = true; boolean insertSuccess = false; boolean updateDate = false; String dctPublisher; String dctIdentifier; String dateAccepted; String committer; String allTopics = adminService.getAllTopics(); String allLanguages = adminService.getAllLanguages(); String allMediatypes = adminService.getAllMediaTypes(); String allAudiences = adminService.getAllAudiences(); String allStatuses = adminService.getAllStatuses(); StringBuffer messageBuffer = new StringBuffer(); messageBuffer.append("<c:messages xmlns:c=\"http://xmlns.computas.com/cocoon\" xmlns:i18n=\"http://apache.org/cocoon/i18n/2.1\">\n"); messageBuffer.append(messages); Map<String, Object> bizData = new HashMap<String, Object>(); bizData.put("topics", allTopics); bizData.put("languages", allLanguages); bizData.put("mediatypes", allMediatypes); bizData.put("audience", allAudiences); bizData.put("status", allStatuses); bizData.put("userprivileges", userPrivileges); if (req.getCocoonRequest().getMethod().equalsIgnoreCase("GET")) { bizData.put("tempvalues", "<empty></empty>"); if ("ny".equalsIgnoreCase(type)) { registerNewResourceURL(req, res); return; } else { bizData.put("resource", adminService.getResourceByURI(req.getCocoonRequest().getParameter("uri"))); bizData.put("publishers", adminService.getAllPublishers()); bizData.put("mode", "edit"); bizData.put("messages", "<empty></empty>"); res.sendPage("xml2/ressurs", bizData); } } else if (req.getCocoonRequest().getMethod().equalsIgnoreCase("POST")) { if ("Slett ressurs".equalsIgnoreCase(req.getCocoonRequest().getParameter("actionbutton")) || "Delete resource".equalsIgnoreCase(req.getCocoonRequest().getParameter("actionbutton"))) { String deleteString = "DELETE {\n" + "<" + req.getCocoonRequest().getParameter("uri") + "> ?a ?o.\n" + "} WHERE {\n" + "<" + req.getCocoonRequest().getParameter("uri") + "> ?a ?o. }"; boolean deleteResourceSuccess = sparulDispatcher.query(deleteString); logger.trace("ResourceController.editResource --> DELETE RESOURCE QUERY:\n" + deleteString); logger.trace("ResourceController.editResource --> DELETE RESOURCE QUERY RESULT: " + deleteResourceSuccess); if (deleteResourceSuccess) { messageBuffer.append("<c:message>Ressursen slettet!</c:message>\n"); bizData.put("resource", "<empty></empty>"); bizData.put("tempvalues", "<empty></empty>"); bizData.put("mode", "edit"); } else { messageBuffer.append("<c:message>Feil ved sletting av ressurs</c:message>\n"); bizData.put("tempvalues", "<empty></empty>"); bizData.put("resource", adminService.getResourceByURI(req.getCocoonRequest().getParameter("sub:url"))); bizData.put("mode", "edit"); } } else { Map<String, String[]> parameterMap = new TreeMap<String, String[]>(createParametersMap(req.getCocoonRequest())); String tempPrefixes = "<c:tempvalues \n" + "xmlns:topic=\"" + getProperty("sublima.base.url") + "topic/\"\n" + "xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\"\n" + "xmlns:wdr=\"http://www.w3.org/2007/05/powder#\"\n" + "xmlns:lingvoj=\"http://www.lingvoj.org/ontology#\"\n" + "xmlns:sioc=\"http://rdfs.org/sioc/ns#\"\n" + "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n" + "xmlns:foaf=\"http://xmlns.com/foaf/0.1/\"\n" + "xmlns:owl=\"http://www.w3.org/2002/07/owl#\"\n" + "xmlns:dct=\"http://purl.org/dc/terms/\"\n" + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"\n" + "xmlns:dcmitype=\"http://purl.org/dc/dcmitype/\"\n" + "xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"\n" + "xmlns:c=\"http://xmlns.computas.com/cocoon\"\n" + "xmlns:i18n=\"http://apache.org/cocoon/i18n/2.1\"\n" + "xmlns:sub=\"http://xmlns.computas.com/sublima#\">\n"; Date date = new Date(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dateAccepted = dateFormat.format(date); if (parameterMap.containsKey("markasnew")) { updateDate = true; parameterMap.remove("markasnew"); } parameterMap.put("sub:committer", new String[]{user.getId()}); if ("".equalsIgnoreCase(req.getCocoonRequest().getParameter("dct:identifier")) || req.getCocoonRequest().getParameter("dct:identifier") == null) { updateDate = true; dctIdentifier = req.getCocoonRequest().getParameter("dct:title-1").replace(" ", "_"); dctIdentifier = dctIdentifier.replace(",", "_"); dctIdentifier = dctIdentifier.replace(".", "_"); dctIdentifier = getProperty("sublima.base.url") + "resource/" + dctIdentifier + parameterMap.get("the-resource").hashCode(); } else { dctIdentifier = req.getCocoonRequest().getParameter("dct:identifier"); } if (updateDate) { parameterMap.put("dct:dateAccepted", new String[]{dateAccepted}); } Form2SparqlService form2SparqlService = new Form2SparqlService(parameterMap.get("prefix")); parameterMap.put("sub:url", parameterMap.get("the-resource")); parameterMap.remove("dct:identifier"); parameterMap.put("dct:identifier", new String[] {dctIdentifier}); parameterMap.remove("prefix"); parameterMap.remove("actionbutton"); if (parameterMap.get("subjecturi-prefix") != null) { parameterMap.put("subjecturi-prefix", new String[]{getProperty("sublima.base.url") + parameterMap.get("subjecturi-prefix")[0]}); } String sparqlQuery = null; try { sparqlQuery = form2SparqlService.convertForm2Sparul(parameterMap); } catch (IOException e) { messageBuffer.append("<c:message>Feil ved lagring av emne</c:message>\n"); } insertSuccess = sparulDispatcher.query(sparqlQuery); logger.trace("AdminController.editResource --> INSERT QUERY RESULT: " + insertSuccess); if (insertSuccess) { messageBuffer.append("<c:message>Ny ressurs lagt til!</c:message>\n"); } else { messageBuffer.append("<c:message>Feil ved lagring av ny ressurs</c:message>\n"); bizData.put("resource", "<empty></empty>"); } } if (insertSuccess) { bizData.put("resource", adminService.getResourceByURI(req.getCocoonRequest().getParameter("the-resource"))); bizData.put("tempvalues", "<empty></empty>"); bizData.put("mode", "edit"); } else { bizData.put("resource", "<empty></empty>"); bizData.put("tempvalues", "<empty/>"); bizData.put("mode", "temp"); } messageBuffer.append("</c:messages>\n"); bizData.put("messages", messageBuffer.toString()); bizData.put("userprivileges", userPrivileges); bizData.put("publishers", adminService.getAllPublishers()); res.sendPage("xml2/ressurs", bizData); }
private void editResource (AppleResponse res, AppleRequest req, String type, String messages) { boolean validated = true; boolean insertSuccess = false; boolean updateDate = false; String dctPublisher; String dctIdentifier; String dateAccepted; String committer; String allTopics = adminService.getAllTopics(); String allLanguages = adminService.getAllLanguages(); String allMediatypes = adminService.getAllMediaTypes(); String allAudiences = adminService.getAllAudiences(); String allStatuses = adminService.getAllStatuses(); StringBuffer messageBuffer = new StringBuffer(); messageBuffer.append("<c:messages xmlns:c=\"http://xmlns.computas.com/cocoon\" xmlns:i18n=\"http://apache.org/cocoon/i18n/2.1\">\n"); messageBuffer.append(messages); Map<String, Object> bizData = new HashMap<String, Object>(); bizData.put("topics", allTopics); bizData.put("languages", allLanguages); bizData.put("mediatypes", allMediatypes); bizData.put("audience", allAudiences); bizData.put("status", allStatuses); bizData.put("userprivileges", userPrivileges); if (req.getCocoonRequest().getMethod().equalsIgnoreCase("GET")) { bizData.put("tempvalues", "<empty></empty>"); if ("ny".equalsIgnoreCase(type)) { registerNewResourceURL(req, res); return; } else { bizData.put("resource", adminService.getResourceByURI(req.getCocoonRequest().getParameter("uri"))); bizData.put("publishers", adminService.getAllPublishers()); bizData.put("mode", "edit"); bizData.put("messages", "<empty></empty>"); res.sendPage("xml2/ressurs", bizData); } } else if (req.getCocoonRequest().getMethod().equalsIgnoreCase("POST")) { if ("Slett ressurs".equalsIgnoreCase(req.getCocoonRequest().getParameter("actionbutton")) || "Delete resource".equalsIgnoreCase(req.getCocoonRequest().getParameter("actionbutton"))) { String deleteString = "DELETE {\n" + "<" + req.getCocoonRequest().getParameter("uri") + "> ?a ?o.\n" + "} WHERE {\n" + "<" + req.getCocoonRequest().getParameter("uri") + "> ?a ?o. }"; boolean deleteResourceSuccess = sparulDispatcher.query(deleteString); logger.trace("ResourceController.editResource --> DELETE RESOURCE QUERY:\n" + deleteString); logger.trace("ResourceController.editResource --> DELETE RESOURCE QUERY RESULT: " + deleteResourceSuccess); if (deleteResourceSuccess) { messageBuffer.append("<c:message>Ressursen slettet!</c:message>\n"); bizData.put("resource", "<empty></empty>"); bizData.put("tempvalues", "<empty></empty>"); bizData.put("mode", "edit"); } else { messageBuffer.append("<c:message>Feil ved sletting av ressurs</c:message>\n"); bizData.put("tempvalues", "<empty></empty>"); bizData.put("resource", adminService.getResourceByURI(req.getCocoonRequest().getParameter("sub:url"))); bizData.put("mode", "edit"); } } else { Map<String, String[]> parameterMap = new TreeMap<String, String[]>(createParametersMap(req.getCocoonRequest())); String tempPrefixes = "<c:tempvalues \n" + "xmlns:topic=\"" + getProperty("sublima.base.url") + "topic/\"\n" + "xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\"\n" + "xmlns:wdr=\"http://www.w3.org/2007/05/powder#\"\n" + "xmlns:lingvoj=\"http://www.lingvoj.org/ontology#\"\n" + "xmlns:sioc=\"http://rdfs.org/sioc/ns#\"\n" + "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n" + "xmlns:foaf=\"http://xmlns.com/foaf/0.1/\"\n" + "xmlns:owl=\"http://www.w3.org/2002/07/owl#\"\n" + "xmlns:dct=\"http://purl.org/dc/terms/\"\n" + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"\n" + "xmlns:dcmitype=\"http://purl.org/dc/dcmitype/\"\n" + "xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"\n" + "xmlns:c=\"http://xmlns.computas.com/cocoon\"\n" + "xmlns:i18n=\"http://apache.org/cocoon/i18n/2.1\"\n" + "xmlns:sub=\"http://xmlns.computas.com/sublima#\">\n"; Date date = new Date(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dateAccepted = dateFormat.format(date); if (parameterMap.containsKey("markasnew")) { updateDate = true; parameterMap.remove("markasnew"); } parameterMap.put("sub:committer", new String[]{user.getId()}); if ("".equalsIgnoreCase(req.getCocoonRequest().getParameter("dct:identifier")) || req.getCocoonRequest().getParameter("dct:identifier") == null) { updateDate = true; dctIdentifier = req.getCocoonRequest().getParameter("dct:title-1").replace(" ", "_"); dctIdentifier = dctIdentifier.replace(",", "_"); dctIdentifier = dctIdentifier.replace(".", "_"); dctIdentifier = getProperty("sublima.base.url") + "resource/" + dctIdentifier + parameterMap.get("the-resource").hashCode(); } else { dctIdentifier = req.getCocoonRequest().getParameter("dct:identifier"); } if (updateDate) { parameterMap.put("dct:dateAccepted", new String[]{dateAccepted}); } Form2SparqlService form2SparqlService = new Form2SparqlService(parameterMap.get("prefix")); parameterMap.put("sub:url", parameterMap.get("the-resource")); parameterMap.remove("dct:identifier"); parameterMap.put("dct:identifier", new String[] {dctIdentifier}); parameterMap.remove("prefix"); parameterMap.remove("actionbutton"); if (parameterMap.get("subjecturi-prefix") != null) { parameterMap.put("subjecturi-prefix", new String[]{getProperty("sublima.base.url") + parameterMap.get("subjecturi-prefix")[0]}); } String sparqlQuery = null; try { sparqlQuery = form2SparqlService.convertForm2Sparul(parameterMap); } catch (IOException e) { messageBuffer.append("<c:message>Feil ved lagring av emne</c:message>\n"); } insertSuccess = sparulDispatcher.query(sparqlQuery); logger.trace("AdminController.editResource --> INSERT QUERY RESULT: " + insertSuccess); if (insertSuccess) { messageBuffer.append("<c:message>Ny ressurs lagt til!</c:message>\n"); } else { messageBuffer.append("<c:message>Feil ved lagring av ny ressurs</c:message>\n"); } } if (insertSuccess) { bizData.put("resource", adminService.getResourceByURI(req.getCocoonRequest().getParameter("the-resource"))); bizData.put("tempvalues", "<empty></empty>"); bizData.put("mode", "edit"); } else { bizData.put("resource", "<empty></empty>"); bizData.put("tempvalues", "<empty/>"); bizData.put("mode", "edit"); } messageBuffer.append("</c:messages>\n"); bizData.put("messages", messageBuffer.toString()); bizData.put("userprivileges", userPrivileges); bizData.put("publishers", adminService.getAllPublishers()); res.sendPage("xml2/ressurs", bizData); }
public void run() { try { socket = new DatagramSocket(port); } catch (Exception e) { System.out.println("Unable to start UDP server on port " + port + ". Ignoring ..."); return ; } System.out.println("UDP server started on port " + port); while (true) { try { if (isInterrupted()) break; byte[] buf = new byte[256]; DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); msgList.add(packet); } catch (IOException e) { if (e.getMessage().equals("socket closed")) { } else { System.out.println("ERROR in UDP server. Stack trace:"); e.printStackTrace(); } } } socket.close(); System.out.println("UDP NAT server closed."); }
public void run() { try { socket = new DatagramSocket(port); } catch (Exception e) { System.out.println("Unable to start UDP server on port " + port + ". Ignoring ..."); return ; } System.out.println("UDP server started on port " + port); while (true) { try { if (isInterrupted()) break; byte[] buf = new byte[256]; DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); msgList.add(packet); } catch (IOException e) { if (e.getMessage().equalsIgnoreCase("socket closed")) { } else { System.out.println("ERROR in UDP server. Stack trace:"); e.printStackTrace(); } } } socket.close(); System.out.println("UDP NAT server closed."); }
ChartsPanel(RemoteCollector remoteCollector) { super(remoteCollector); final JLabel throbberLabel = new JLabel(THROBBER_ICON); add(throbberLabel, BorderLayout.NORTH); add(createButtonsPanel(), BorderLayout.CENTER); final SwingWorker<Map<String, byte[]>, Object> swingWorker = new SwingWorker<Map<String, byte[]>, Object>() { @Override protected Map<String, byte[]> doInBackground() throws IOException { return getRemoteCollector().collectJRobins(CHART_WIDTH, CHART_HEIGHT); } @Override protected void done() { try { final Map<String, byte[]> jrobins = get(); final JPanel mainJRobinsPanel = createJRobinPanel(jrobins); remove(throbberLabel); add(mainJRobinsPanel, BorderLayout.NORTH); revalidate(); } catch (final Exception e) { MSwingUtilities.showException(e); } } }; swingWorker.execute(); }
ChartsPanel(RemoteCollector remoteCollector) { super(remoteCollector); final JLabel throbberLabel = new JLabel(THROBBER_ICON); add(throbberLabel, BorderLayout.NORTH); add(createButtonsPanel(), BorderLayout.CENTER); final SwingWorker<Map<String, byte[]>, Object> swingWorker = new SwingWorker<Map<String, byte[]>, Object>() { @Override protected Map<String, byte[]> doInBackground() throws IOException { return getRemoteCollector().collectJRobins(CHART_WIDTH, CHART_HEIGHT); } @Override protected void done() { try { final Map<String, byte[]> jrobins = get(); final JPanel mainJRobinsPanel = createJRobinPanel(jrobins); remove(throbberLabel); add(mainJRobinsPanel, BorderLayout.NORTH); revalidate(); } catch (final Exception e) { MSwingUtilities.showException(e); remove(throbberLabel); } } }; swingWorker.execute(); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.main); service = new TrollServiceSqlLite(getBaseContext()); String levelId = getIntent().getExtras().getString(HomeScreenActiity.LEVEL_ID); level = service.getLevel(levelId); loadComponents(); initGraphics(); moveToCity(service.getCity(level.getStartCityId())); City goal = service.getCity(level.getGoalCityId()); goalView.setText("Goal: " + goal.getName()); mapView.setGoalCity(goal); counter = new CountDown(10000,1000, timeLeftView); counter.start(); counter.setOnFinishListener(new CountDown.OnCounterFinishListener() { public void finished() { failDialog.show(); } }); successDialog = new SuccessDialog(this); Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/fixed.ttf"); button1.setTypeface(tf); button2.setTypeface(tf); button3.setTypeface(tf); button4.setTypeface(tf); goalView.setTypeface(tf); timeLeftView.setTypeface(tf); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.main); service = new TrollServiceSqlLite(getBaseContext()); String levelId = getIntent().getExtras().getString(HomeScreenActiity.LEVEL_ID); level = service.getLevel(levelId); loadComponents(); initGraphics(); moveToCity(service.getCity(level.getStartCityId())); City goal = service.getCity(level.getGoalCityId()); goalView.setText("Goal: " + goal.getName()); mapView.setGoalCity(goal); counter = new CountDown(10000,1000, timeLeftView); counter.start(); counter.setOnFinishListener(new CountDown.OnCounterFinishListener() { public void finished() { failDialog.show(); } }); successDialog = new SuccessDialog(this, levelId); Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/fixed.ttf"); button1.setTypeface(tf); button2.setTypeface(tf); button3.setTypeface(tf); button4.setTypeface(tf); goalView.setTypeface(tf); timeLeftView.setTypeface(tf); }
private final TextElement parseText(String currentText, String tag, String arg) { TextElement result = new TextElement(tag); if(result.mType == TextElementType.Quote) result.mContent = arg; if (currentText.substring(0,1).equals("\n")) { result.mConsumedLength++; } Pattern tagPattern = Pattern.compile("\\[(.+?)(?:=\"?(.+?)\"?)?\\]", Pattern.MULTILINE|Pattern.DOTALL); Matcher tagMatcher = tagPattern.matcher(currentText); String keyRegex = "(CH|SS|US|KS)K@[%,~" + URLEncoder.getSafeURLCharacters() + "]+"; Pattern keyPattern = Pattern.compile(keyRegex, Pattern.MULTILINE|Pattern.DOTALL); Matcher keyMatcher = keyPattern.matcher(currentText); Pattern oldQuotePattern = Pattern.compile("^(\\S+@\\S+?.freetalk) wrote:\n", Pattern.MULTILINE|Pattern.DOTALL); Matcher oldQuoteMatcher = oldQuotePattern.matcher(currentText); while (result.mConsumedLength < currentText.length()) { int tagPos = currentText.length(); if (tagMatcher.find(result.mConsumedLength)) tagPos = tagMatcher.start(); int keyPos = currentText.length(); if (keyMatcher.find(result.mConsumedLength)) keyPos = keyMatcher.start(); int oldQuotePos = currentText.length(); if (oldQuoteMatcher.find(result.mConsumedLength)) oldQuotePos = oldQuoteMatcher.start(); int textEndPos = Math.min(Math.min(tagPos, keyPos),oldQuotePos); if (textEndPos > result.mConsumedLength) { TextElement newElement = new TextElement(TextElementType.PlainText); newElement.mContent = currentText.substring(result.mConsumedLength, textEndPos); newElement.mConsumedLength = textEndPos-result.mConsumedLength; result.mChildren.add(newElement); result.mConsumedLength += newElement.mConsumedLength; } if (textEndPos == currentText.length()) { break; } if (textEndPos == tagPos) { result.mConsumedLength += tagMatcher.group().length(); String t = tagMatcher.group(1); String a = tagMatcher.group(2); if (t.equals("/"+tag)) return result; if (t.substring(0,1).equals("/")) { TextElement newElement = new TextElement(TextElementType.Error); newElement.mContent = tagMatcher.group(); newElement.mConsumedLength = newElement.mContent.length(); result.mChildren.add(newElement); } else { TextElement subElement = parseText(currentText.substring(tagMatcher.end()), t, a); result.mChildren.add(subElement); result.mConsumedLength += subElement.mConsumedLength; } } else if (textEndPos == keyPos) { TextElement newElement = new TextElement(TextElementType.Key); newElement.mContent = keyMatcher.group(); newElement.mConsumedLength = newElement.mContent.length(); result.mChildren.add(newElement); result.mConsumedLength += newElement.mConsumedLength; } else if (textEndPos == oldQuotePos) { String author = oldQuoteMatcher.group(1); result.mConsumedLength += oldQuoteMatcher.group().length(); Pattern endOfOldQuotePattern = Pattern.compile("^[^>]", Pattern.MULTILINE|Pattern.DOTALL); Matcher endOfOldQuoteMatcher = endOfOldQuotePattern.matcher(currentText); int endOfOldQuotePos = currentText.length(); if (endOfOldQuoteMatcher.find(result.mConsumedLength)) endOfOldQuotePos = endOfOldQuoteMatcher.start(); String quoted = currentText.substring(result.mConsumedLength, endOfOldQuotePos); result.mConsumedLength += quoted.length(); Pattern quotePartPattern = Pattern.compile("^>\\s*", Pattern.MULTILINE|Pattern.DOTALL); Matcher quotePartMatcher = quotePartPattern.matcher(quoted); String unquoted = quotePartMatcher.replaceAll(""); TextElement subElement = parseText(unquoted, "quote", author); result.mChildren.add(subElement); } } return result; }
private final TextElement parseText(String currentText, String tag, String arg) { TextElement result = new TextElement(tag); if(result.mType == TextElementType.Quote) result.mContent = arg; if (currentText.length() > 0) { if (currentText.substring(0,1).equals("\n")) { result.mConsumedLength++; } } Pattern tagPattern = Pattern.compile("\\[(.+?)(?:=\"?(.+?)\"?)?\\]", Pattern.MULTILINE|Pattern.DOTALL); Matcher tagMatcher = tagPattern.matcher(currentText); String keyRegex = "(CH|SS|US|KS)K@[%,~" + URLEncoder.getSafeURLCharacters() + "]+"; Pattern keyPattern = Pattern.compile(keyRegex, Pattern.MULTILINE|Pattern.DOTALL); Matcher keyMatcher = keyPattern.matcher(currentText); Pattern oldQuotePattern = Pattern.compile("^(\\S+@\\S+?.freetalk) wrote:\n", Pattern.MULTILINE|Pattern.DOTALL); Matcher oldQuoteMatcher = oldQuotePattern.matcher(currentText); while (result.mConsumedLength < currentText.length()) { int tagPos = currentText.length(); if (tagMatcher.find(result.mConsumedLength)) tagPos = tagMatcher.start(); int keyPos = currentText.length(); if (keyMatcher.find(result.mConsumedLength)) keyPos = keyMatcher.start(); int oldQuotePos = currentText.length(); if (oldQuoteMatcher.find(result.mConsumedLength)) oldQuotePos = oldQuoteMatcher.start(); int textEndPos = Math.min(Math.min(tagPos, keyPos),oldQuotePos); if (textEndPos > result.mConsumedLength) { TextElement newElement = new TextElement(TextElementType.PlainText); newElement.mContent = currentText.substring(result.mConsumedLength, textEndPos); newElement.mConsumedLength = textEndPos-result.mConsumedLength; result.mChildren.add(newElement); result.mConsumedLength += newElement.mConsumedLength; } if (textEndPos == currentText.length()) { break; } if (textEndPos == tagPos) { result.mConsumedLength += tagMatcher.group().length(); String t = tagMatcher.group(1); String a = tagMatcher.group(2); if (t.equals("/"+tag)) return result; if (t.substring(0,1).equals("/")) { TextElement newElement = new TextElement(TextElementType.Error); newElement.mContent = tagMatcher.group(); newElement.mConsumedLength = newElement.mContent.length(); result.mChildren.add(newElement); } else { TextElement subElement = parseText(currentText.substring(tagMatcher.end()), t, a); result.mChildren.add(subElement); result.mConsumedLength += subElement.mConsumedLength; } } else if (textEndPos == keyPos) { TextElement newElement = new TextElement(TextElementType.Key); newElement.mContent = keyMatcher.group(); newElement.mConsumedLength = newElement.mContent.length(); result.mChildren.add(newElement); result.mConsumedLength += newElement.mConsumedLength; } else if (textEndPos == oldQuotePos) { String author = oldQuoteMatcher.group(1); result.mConsumedLength += oldQuoteMatcher.group().length(); Pattern endOfOldQuotePattern = Pattern.compile("^[^>]", Pattern.MULTILINE|Pattern.DOTALL); Matcher endOfOldQuoteMatcher = endOfOldQuotePattern.matcher(currentText); int endOfOldQuotePos = currentText.length(); if (endOfOldQuoteMatcher.find(result.mConsumedLength)) endOfOldQuotePos = endOfOldQuoteMatcher.start(); String quoted = currentText.substring(result.mConsumedLength, endOfOldQuotePos); result.mConsumedLength += quoted.length(); Pattern quotePartPattern = Pattern.compile("^>\\s*", Pattern.MULTILINE|Pattern.DOTALL); Matcher quotePartMatcher = quotePartPattern.matcher(quoted); String unquoted = quotePartMatcher.replaceAll(""); TextElement subElement = parseText(unquoted, "quote", author); result.mChildren.add(subElement); } } return result; }
public void testRegistration() { Page page = tester.startPage(RegisterPage.class); tester.assertRenderedPage(RegisterPage.class); PortalSession.get().getRights().add(new Right("captcha.disabled")); FormTester ft = tester.newFormTester("form"); ft.setValue("username", "peterpan"); ft.setValue("firstname", "mike"); ft.setValue("lastname", "jack"); ft.setValue("email", "mike.jack@email.tld"); ft.setValue("birthday", "1981-10-13"); ft.setValue("password1", "testing"); ft.setValue("password2", "testing"); ft.setValue("termsOfUse", true); tester.executeAjaxEvent("form:registerButton", "onclick"); tester.assertNoErrorMessage(); tester.assertRenderedPage(MessagePage.class); tester.assertContains(page.getString("confirm.email")); }
public void testRegistration() { Page page = tester.startPage(RegisterPage.class); tester.assertRenderedPage(RegisterPage.class); PortalSession.get().getRights().add(new Right("captcha.disabled")); FormTester ft = tester.newFormTester("form"); ft.setValue("username", "peterpan123"); ft.setValue("firstname", "mike"); ft.setValue("lastname", "jack"); ft.setValue("email", "mike.jack@email.tld"); ft.setValue("birthday", "1981-10-13"); ft.setValue("password1", "testing"); ft.setValue("password2", "testing"); ft.setValue("termsOfUse", true); tester.executeAjaxEvent("form:registerButton", "onclick"); tester.assertNoErrorMessage(); tester.assertRenderedPage(MessagePage.class); tester.assertContains(page.getString("confirm.email")); }
public void draw(Canvas canvas) { if (mViews != null) { final int n = mViews.size(); for (int i = 0; i < mCurrent; i++) { drawView(mViews.get(i), canvas); } for (int i = n - 1; i > mCurrent; i--) { drawView(mViews.get(i), canvas); } drawView(mViews.get(mCurrent), canvas); } }
public void draw(Canvas canvas) { if ((mViews != null) && (mCurrent > -1)) { final int n = mViews.size(); for (int i = 0; i < mCurrent; i++) { drawView(mViews.get(i), canvas); } for (int i = n - 1; i > mCurrent; i--) { drawView(mViews.get(i), canvas); } drawView(mViews.get(mCurrent), canvas); } }
public void init(FMLInitializationEvent event) { System.out.println("Initilizing Sustainable Resources Mod (SMR)"); System.out.println("You are using a pre-alpha build! And peter fails :P"); }
public void init(FMLInitializationEvent event) { System.out.println("Initilizing Sustainable Resources Mod (SMR)"); System.out.println("You are using a pre-alpha build!"); }
public static void main (String [] args) { assert args.length > 5; int NUM_READERS = 5; int NUM_WRITERS = 1; final int N = Integer.parseInt(args[0]); final int R = Integer.parseInt(args[1]); int W = Integer.parseInt(args[2]); int K = Integer.parseInt(args[3]); assert K >= 1; int ITERATIONS = Integer.parseInt(args[4]); DelayModel delaymodel = null; if(args[5].equals("FILE")) { String sendDelayFile = args[6]; String ackDelayFile = args[7]; delaymodel = new EmpiricalDelayModel(sendDelayFile, ackDelayFile); } else if(args[5].equals("PARETO")) { delaymodel = new ParetoDelayModel(Double.parseDouble(args[6]), Double.parseDouble(args[7]), Double.parseDouble(args[8]), Double.parseDouble(args[9])); } else if(args[5].equals("MULTIDC")) { delaymodel = new MultiDCDelayModel(Double.parseDouble(args[6]), Double.parseDouble(args[7]), Double.parseDouble(args[8]), Double.parseDouble(args[9]), Double.parseDouble(args[10]), N); } else if(args[5].equals("EXPONENTIAL")) { delaymodel = new ExponentialDelayModel(Double.parseDouble(args[6]), Double.parseDouble(args[7])); } else { System.err.println( "Usage: Simulator <N> <R> <W> <k> <iters> FILE <sendF> <ackF> OPT\n" + "Usage: Simulator <N> <R> <W> <iters> PARETO <W-min> <W-alpha> <ARS-min> <ARS-alpha> OPT\n" + "Usage: Simulator <N> <R> <W> <iters> EXPONENTIAL <W-lambda> <ARS-lambda> OPT\n +" + "Usage: Simulator <N> <R> <W> <iters> MULTIDC <W-min> <W-alpha> <ARS-min> <ARS-alpha> <DC-delay> OPT\n +" + "OPT= O <SWEEP|LATS>"); System.exit(1); } final DelayModel delay = delaymodel; String optsinput = ""; for(int i = 0; i < args.length; ++i) { if(args[i].equals("O")) { optsinput = args[i+1]; assert optsinput.equals("SWEEP") || optsinput.equals("LATS"); break; } } final String opts = optsinput; final Vector<KVServer> replicas = new Vector<KVServer>(); for(int i = 0; i < N; ++i) { replicas.add(new KVServer()); } Vector<Double> writelats = new Vector<Double>(); final ConcurrentLinkedQueue<Double> readlats = new ConcurrentLinkedQueue<Double>(); HashMap<Integer, Double> commitTimes = new HashMap<Integer, Double>(); Vector<WriteInstance> writes = new Vector<WriteInstance>(); final CommitTimes commits = new CommitTimes(); final ConcurrentLinkedQueue<ReadPlot> readPlotConcurrent = new ConcurrentLinkedQueue<ReadPlot>(); double ltime = 0; double ftime = 1000; for(int wid = 0; wid < NUM_WRITERS; wid++) { double time = 0; for(int i = 0; i < ITERATIONS; ++i) { Vector<Double> oneways = new Vector<Double>(); Vector<Double> rtts = new Vector<Double>(); for(int w = 0; w < N; ++w) { double oneway = delay.getWriteSendDelay(); double ack = delay.getWriteAckDelay(); oneways.add(time + oneway); rtts.add(oneway + ack); } Collections.sort(rtts); double wlat = rtts.get(W-1); if(opts.equals("LATS")) { writelats.add(wlat); } double committime = time+wlat; writes.add(new WriteInstance(oneways, time, committime)); time = committime; } if(time > ltime) ltime = time; if(time < ftime) ftime = time; } final double maxtime = ltime; final double firsttime = ftime; Collections.sort(writes); for(int wno = 0; wno < writes.size(); ++wno) { WriteInstance curWrite = writes.get(wno); for(int sno = 0; sno < N; ++sno) { replicas.get(sno).write(curWrite.getOneway().get(sno), wno); } commits.record(curWrite.getCommittime(), wno); } final CountDownLatch latch = new CountDownLatch(NUM_READERS); for(int rid = 0; rid < NUM_READERS; ++rid) { Thread t = new Thread(new Runnable () { public void run() { double time = firsttime*2; while(time < maxtime) { Vector<ReadInstance> readRound = new Vector<ReadInstance>(); for(int sno = 0; sno < N; ++sno) { double onewaytime = delay.getReadSendDelay(); int version = replicas.get(sno).read(time+onewaytime); double rtt = onewaytime+delay.getReadAckDelay(); readRound.add(new ReadInstance(version, rtt)); } Collections.sort(readRound); double endtime = readRound.get(R-1).getFinishtime(); if(opts.equals("LATS")) { readlats.add(endtime); } int maxversion = -1; for(int rno = 0; rno < R; ++rno) { int readVersion = readRound.get(rno).getVersion(); if(readVersion > maxversion) maxversion = readVersion; } readPlotConcurrent.add(new ReadPlot( new ReadOutput(commits.last_committed_version(time), maxversion, time), commits.get_commit_time(commits.last_committed_version(time)))); int staleness = maxversion-commits.last_committed_version(time); time += endtime; } latch.countDown(); } }); t.start(); } try { latch.await(); } catch (Exception e) { System.out.println(e.getMessage()); } if(opts.equals("SWEEP")) { Vector<ReadPlot> readPlots = new Vector<ReadPlot>(readPlotConcurrent); Collections.sort(readPlots); Collections.reverse(readPlots); HashMap<Long, ReadPlot> manystalemap = new HashMap<Long, ReadPlot>(); long stale = 0; for(ReadPlot r : readPlots) { if(r.getRead().getVersion_read() < r.getRead().getVersion_at_start()-K-1) { stale += 1; manystalemap.put(stale, r); } } for(double p = .9; p < 1; p += .001) { double tstale = 0; long how_many_stale = (long)Math.ceil(readPlots.size()*p); ReadPlot r = manystalemap.get(how_many_stale); if(r == null) tstale = 0; else tstale = r.getRead().getStart_time() - r.getCommit_time_at_start(); System.out.println(p+" "+tstale); } } if(opts.equals("LATS")) { System.out.println("WRITE"); Collections.sort(writelats); for(double p = 0; p < 1; p += .01) { System.out.printf("%f %f\n", p, writelats.get((int) Math.round(p * writelats.size()))); } Vector<Double> readLatencies = new Vector<Double>(readlats); System.out.println("READ"); Collections.sort(readLatencies); for(double p = 0; p < 1; p += .01) { System.out.printf("%f %f\n", p, readLatencies.get((int)Math.round(p*readLatencies.size()))); } } }
public static void main (String [] args) { assert args.length > 5; int NUM_READERS = 5; int NUM_WRITERS = 1; final int N = Integer.parseInt(args[0]); final int R = Integer.parseInt(args[1]); int W = Integer.parseInt(args[2]); int K = Integer.parseInt(args[3]); assert K >= 1; int ITERATIONS = Integer.parseInt(args[4]); DelayModel delaymodel = null; if(args[5].equals("FILE")) { String sendDelayFile = args[6]; String ackDelayFile = args[7]; delaymodel = new EmpiricalDelayModel(sendDelayFile, ackDelayFile); } else if(args[5].equals("PARETO")) { delaymodel = new ParetoDelayModel(Double.parseDouble(args[6]), Double.parseDouble(args[7]), Double.parseDouble(args[8]), Double.parseDouble(args[9])); } else if(args[5].equals("MULTIDC")) { delaymodel = new MultiDCDelayModel(Double.parseDouble(args[6]), Double.parseDouble(args[7]), Double.parseDouble(args[8]), Double.parseDouble(args[9]), Double.parseDouble(args[10]), N); } else if(args[5].equals("EXPONENTIAL")) { delaymodel = new ExponentialDelayModel(Double.parseDouble(args[6]), Double.parseDouble(args[7])); } else { System.err.println( "Usage: Simulator <N> <R> <W> <k> <iters> FILE <sendF> <ackF> OPT\n" + "Usage: Simulator <N> <R> <W> <iters> PARETO <W-min> <W-alpha> <ARS-min> <ARS-alpha> OPT\n" + "Usage: Simulator <N> <R> <W> <iters> EXPONENTIAL <W-lambda> <ARS-lambda> OPT\n +" + "Usage: Simulator <N> <R> <W> <iters> MULTIDC <W-min> <W-alpha> <ARS-min> <ARS-alpha> <DC-delay> OPT\n +" + "OPT= O <SWEEP|LATS>"); System.exit(1); } final DelayModel delay = delaymodel; String optsinput = ""; for(int i = 0; i < args.length; ++i) { if(args[i].equals("O")) { optsinput = args[i+1]; assert optsinput.equals("SWEEP") || optsinput.equals("LATS"); break; } } final String opts = optsinput; final Vector<KVServer> replicas = new Vector<KVServer>(); for(int i = 0; i < N; ++i) { replicas.add(new KVServer()); } Vector<Double> writelats = new Vector<Double>(); final ConcurrentLinkedQueue<Double> readlats = new ConcurrentLinkedQueue<Double>(); HashMap<Integer, Double> commitTimes = new HashMap<Integer, Double>(); Vector<WriteInstance> writes = new Vector<WriteInstance>(); final CommitTimes commits = new CommitTimes(); final ConcurrentLinkedQueue<ReadPlot> readPlotConcurrent = new ConcurrentLinkedQueue<ReadPlot>(); double ltime = 0; double ftime = 1000; for(int wid = 0; wid < NUM_WRITERS; wid++) { double time = 0; for(int i = 0; i < ITERATIONS; ++i) { Vector<Double> oneways = new Vector<Double>(); Vector<Double> rtts = new Vector<Double>(); for(int w = 0; w < N; ++w) { double oneway = delay.getWriteSendDelay(); double ack = delay.getWriteAckDelay(); oneways.add(time + oneway); rtts.add(oneway + ack); } Collections.sort(rtts); double wlat = rtts.get(W-1); if(opts.equals("LATS")) { writelats.add(wlat); } double committime = time+wlat; writes.add(new WriteInstance(oneways, time, committime)); time = committime; } if(time > ltime) ltime = time; if(time < ftime) ftime = time; } final double maxtime = ltime; final double firsttime = ftime; Collections.sort(writes); for(int wno = 0; wno < writes.size(); ++wno) { WriteInstance curWrite = writes.get(wno); for(int sno = 0; sno < N; ++sno) { replicas.get(sno).write(curWrite.getOneway().get(sno), wno); } commits.record(curWrite.getCommittime(), wno); } final CountDownLatch latch = new CountDownLatch(NUM_READERS); for(int rid = 0; rid < NUM_READERS; ++rid) { Thread t = new Thread(new Runnable () { public void run() { double time = firsttime*2; while(time < maxtime) { Vector<ReadInstance> readRound = new Vector<ReadInstance>(); for(int sno = 0; sno < N; ++sno) { double onewaytime = delay.getReadSendDelay(); int version = replicas.get(sno).read(time+onewaytime); double rtt = onewaytime+delay.getReadAckDelay(); readRound.add(new ReadInstance(version, rtt)); } Collections.sort(readRound); double endtime = readRound.get(R-1).getFinishtime(); if(opts.equals("LATS")) { readlats.add(endtime); } int maxversion = -1; for(int rno = 0; rno < R; ++rno) { int readVersion = readRound.get(rno).getVersion(); if(readVersion > maxversion) maxversion = readVersion; } readPlotConcurrent.add(new ReadPlot( new ReadOutput(commits.last_committed_version(time), maxversion, time), commits.get_commit_time(commits.last_committed_version(time)))); int staleness = maxversion-commits.last_committed_version(time); time += endtime; } latch.countDown(); } }); t.start(); } try { latch.await(); } catch (Exception e) { System.out.println(e.getMessage()); } if(opts.equals("SWEEP")) { Vector<ReadPlot> readPlots = new Vector<ReadPlot>(readPlotConcurrent); Collections.sort(readPlots); Collections.reverse(readPlots); HashMap<Long, ReadPlot> manystalemap = new HashMap<Long, ReadPlot>(); long stale = 0; for(ReadPlot r : readPlots) { if(r.getRead().getVersion_read() < r.getRead().getVersion_at_start()-K-1) { stale += 1; manystalemap.put(stale, r); } } for(double p = .9; p < 1; p += .001) { double tstale = 0; long how_many_stale = (long)Math.ceil(readPlots.size()*(1-p)); ReadPlot r = manystalemap.get(how_many_stale); if(r == null) tstale = 0; else tstale = r.getRead().getStart_time() - r.getCommit_time_at_start(); System.out.println(p+" "+tstale); } } if(opts.equals("LATS")) { System.out.println("WRITE"); Collections.sort(writelats); for(double p = 0; p < 1; p += .01) { System.out.printf("%f %f\n", p, writelats.get((int) Math.round(p * writelats.size()))); } Vector<Double> readLatencies = new Vector<Double>(readlats); System.out.println("READ"); Collections.sort(readLatencies); for(double p = 0; p < 1; p += .01) { System.out.printf("%f %f\n", p, readLatencies.get((int)Math.round(p*readLatencies.size()))); } } }
public void execute(final ScheduledJob scheduledJob) { final SystemHelper systemHelper = SingletonS2Container .getComponent(SystemHelper.class); final JobLog jobLog = new JobLog(scheduledJob); final String scriptType = scheduledJob.getScriptType(); final String script = scheduledJob.getScriptData(); final Long id = scheduledJob.getId(); final String jobId = Constants.JOB_ID_PREFIX + id; final JobExecutor jobExecutor = SingletonS2Container .getComponent(scriptType + JOB_EXECUTOR_SUFFIX); if (jobExecutor == null) { throw new ScheduledJobException("No jobExecutor: " + scriptType + JOB_EXECUTOR_SUFFIX); } if (systemHelper.startJobExecutoer(id, jobExecutor) != null) { if (logger.isDebugEnabled()) { logger.debug(jobId + " is running."); } return; } try { if (scheduledJob.isLoggingEnabled()) { storeJobLog(jobLog); } if (logger.isDebugEnabled()) { logger.debug("Starting Job " + jobId + ". scriptType: " + scriptType + ", script: " + script); } else if (logger.isInfoEnabled()) { logger.info("Starting Job " + jobId + "."); } final Object ret = jobExecutor.execute(script); if (ret == null) { logger.info("Finished Job " + jobId + "."); } else { logger.info("Finished Job " + jobId + ". The return value is:\n" + ret); jobLog.setScriptResult(ret.toString()); } jobLog.setJobStatus(Constants.OK); } catch (final Throwable e) { logger.error("Failed to execute " + jobId + ": " + script, e); jobLog.setJobStatus(Constants.FAIL); jobLog.setScriptResult(systemHelper.abbreviateLongText(e .getLocalizedMessage())); } finally { systemHelper.finishJobExecutoer(id); jobLog.setEndTime(new Timestamp(System.currentTimeMillis())); if (logger.isDebugEnabled()) { logger.debug("jobLog: " + jobLog); } if (scheduledJob.isLoggingEnabled()) { storeJobLog(jobLog); } } }
public void execute(final ScheduledJob scheduledJob) { final SystemHelper systemHelper = SingletonS2Container .getComponent(SystemHelper.class); final JobLog jobLog = new JobLog(scheduledJob); final String scriptType = scheduledJob.getScriptType(); final String script = scheduledJob.getScriptData(); final Long id = scheduledJob.getId(); final String jobId = Constants.JOB_ID_PREFIX + id; final JobExecutor jobExecutor = SingletonS2Container .getComponent(scriptType + JOB_EXECUTOR_SUFFIX); if (jobExecutor == null) { throw new ScheduledJobException("No jobExecutor: " + scriptType + JOB_EXECUTOR_SUFFIX); } if (systemHelper.startJobExecutoer(id, jobExecutor) != null) { if (logger.isDebugEnabled()) { logger.debug(jobId + " is running."); } return; } try { if (scheduledJob.isLoggingEnabled()) { storeJobLog(jobLog); } if (logger.isDebugEnabled()) { logger.debug("Starting Job " + jobId + ". scriptType: " + scriptType + ", script: " + script); } else if (scheduledJob.isLoggingEnabled() && logger.isInfoEnabled()) { logger.info("Starting Job " + jobId + "."); } final Object ret = jobExecutor.execute(script); if (ret == null) { if (scheduledJob.isLoggingEnabled() && logger.isInfoEnabled()) { logger.info("Finished Job " + jobId + "."); } } else { if (scheduledJob.isLoggingEnabled() && logger.isInfoEnabled()) { logger.info("Finished Job " + jobId + ". The return value is:\n" + ret); } jobLog.setScriptResult(ret.toString()); } jobLog.setJobStatus(Constants.OK); } catch (final Throwable e) { logger.error("Failed to execute " + jobId + ": " + script, e); jobLog.setJobStatus(Constants.FAIL); jobLog.setScriptResult(systemHelper.abbreviateLongText(e .getLocalizedMessage())); } finally { systemHelper.finishJobExecutoer(id); jobLog.setEndTime(new Timestamp(System.currentTimeMillis())); if (logger.isDebugEnabled()) { logger.debug("jobLog: " + jobLog); } if (scheduledJob.isLoggingEnabled()) { storeJobLog(jobLog); } } }
public static void init() { oi = new OI(); SmartDashboard.putData(driveTrain); SmartDashboard.putData(shooter); SmartDashboard.putdata(feeder); }
public static void init() { oi = new OI(); SmartDashboard.putData(driveTrain); SmartDashboard.putData(shooter); SmartDashboard.putData(feeder); }
protected boolean processCharacters( HWPFDocumentCore document, int currentTableLevel, Range range, final Element block ) { if ( range == null ) return false; boolean haveAnyText = false; if ( document instanceof HWPFDocument ) { final HWPFDocument doc = (HWPFDocument) document; Map<Integer, List<Bookmark>> rangeBookmarks = doc.getBookmarks() .getBookmarksStartedBetween( range.getStartOffset(), range.getEndOffset() ); if ( rangeBookmarks != null && !rangeBookmarks.isEmpty() ) { boolean processedAny = processRangeBookmarks( doc, currentTableLevel, range, block, rangeBookmarks ); if ( processedAny ) return true; } } for ( int c = 0; c < range.numCharacterRuns(); c++ ) { CharacterRun characterRun = range.getCharacterRun( c ); if ( characterRun == null ) throw new AssertionError(); if ( document instanceof HWPFDocument && ( (HWPFDocument) document ).getPicturesTable() .hasPicture( characterRun ) ) { HWPFDocument newFormat = (HWPFDocument) document; Picture picture = newFormat.getPicturesTable().extractPicture( characterRun, true ); processImage( block, characterRun.text().charAt( 0 ) == 0x01, picture ); continue; } String text = characterRun.text(); if ( text.getBytes().length == 0 ) continue; if ( characterRun.isSpecialCharacter() ) { if ( text.charAt( 0 ) == SPECCHAR_AUTONUMBERED_FOOTNOTE_REFERENCE && ( document instanceof HWPFDocument ) ) { HWPFDocument doc = (HWPFDocument) document; processNoteAnchor( doc, characterRun, block ); continue; } } if ( text.getBytes()[0] == FIELD_BEGIN_MARK ) { if ( document instanceof HWPFDocument ) { Field aliveField = ( (HWPFDocument) document ) .getFieldsTables().lookupFieldByStartOffset( FieldsDocumentPart.MAIN, characterRun.getStartOffset() ); if ( aliveField != null ) { processField( ( (HWPFDocument) document ), range, currentTableLevel, aliveField, block ); int continueAfter = aliveField.getFieldEndOffset(); while ( c < range.numCharacterRuns() && range.getCharacterRun( c ).getEndOffset() <= continueAfter ) c++; if ( c < range.numCharacterRuns() ) c--; continue; } } int skipTo = tryDeadField( document, range, currentTableLevel, c, block ); if ( skipTo != c ) { c = skipTo; continue; } continue; } if ( text.getBytes()[0] == FIELD_SEPARATOR_MARK ) { continue; } if ( text.getBytes()[0] == FIELD_END_MARK ) { continue; } if ( characterRun.isSpecialCharacter() || characterRun.isObj() || characterRun.isOle2() ) { continue; } if ( text.endsWith( "\r" ) || ( text.charAt( text.length() - 1 ) == BEL_MARK && currentTableLevel != Integer.MIN_VALUE ) ) text = text.substring( 0, text.length() - 1 ); { StringBuilder stringBuilder = new StringBuilder(); for ( char charChar : text.toCharArray() ) { if ( charChar == 11 ) { if ( stringBuilder.length() > 0 ) { outputCharacters( block, characterRun, stringBuilder.toString() ); stringBuilder.setLength( 0 ); } processLineBreak( block, characterRun ); } else if ( charChar == 30 ) { stringBuilder.append( UNICODECHAR_NONBREAKING_HYPHEN ); } else if ( charChar == 31 ) { stringBuilder.append( UNICODECHAR_ZERO_WIDTH_SPACE ); } else if ( charChar > 0x20 || charChar == 0x09 || charChar == 0x0A || charChar == 0x0D ) { stringBuilder.append( charChar ); } } if ( stringBuilder.length() > 0 ) { outputCharacters( block, characterRun, stringBuilder.toString() ); stringBuilder.setLength( 0 ); } } haveAnyText |= text.trim().length() != 0; } return haveAnyText; }
protected boolean processCharacters( HWPFDocumentCore document, int currentTableLevel, Range range, final Element block ) { if ( range == null ) return false; boolean haveAnyText = false; if ( document instanceof HWPFDocument ) { final HWPFDocument doc = (HWPFDocument) document; Map<Integer, List<Bookmark>> rangeBookmarks = doc.getBookmarks() .getBookmarksStartedBetween( range.getStartOffset(), range.getEndOffset() ); if ( rangeBookmarks != null && !rangeBookmarks.isEmpty() ) { boolean processedAny = processRangeBookmarks( doc, currentTableLevel, range, block, rangeBookmarks ); if ( processedAny ) return true; } } for ( int c = 0; c < range.numCharacterRuns(); c++ ) { CharacterRun characterRun = range.getCharacterRun( c ); if ( characterRun == null ) throw new AssertionError(); if ( document instanceof HWPFDocument && ( (HWPFDocument) document ).getPicturesTable() .hasPicture( characterRun ) ) { HWPFDocument newFormat = (HWPFDocument) document; Picture picture = newFormat.getPicturesTable().extractPicture( characterRun, true ); processImage( block, characterRun.text().charAt( 0 ) == 0x01, picture ); continue; } String text = characterRun.text(); if ( text.getBytes().length == 0 ) continue; if ( characterRun.isSpecialCharacter() ) { if ( text.charAt( 0 ) == SPECCHAR_AUTONUMBERED_FOOTNOTE_REFERENCE && ( document instanceof HWPFDocument ) ) { HWPFDocument doc = (HWPFDocument) document; processNoteAnchor( doc, characterRun, block ); continue; } } if ( text.getBytes()[0] == FIELD_BEGIN_MARK ) { if ( document instanceof HWPFDocument ) { Field aliveField = ( (HWPFDocument) document ) .getFieldsTables().lookupFieldByStartOffset( FieldsDocumentPart.MAIN, characterRun.getStartOffset() ); if ( aliveField != null ) { processField( ( (HWPFDocument) document ), range, currentTableLevel, aliveField, block ); int continueAfter = aliveField.getFieldEndOffset(); while ( c < range.numCharacterRuns() && range.getCharacterRun( c ).getEndOffset() <= continueAfter ) c++; if ( c < range.numCharacterRuns() ) c--; continue; } } int skipTo = tryDeadField( document, range, currentTableLevel, c, block ); if ( skipTo != c ) { c = skipTo; continue; } continue; } if ( text.getBytes()[0] == FIELD_SEPARATOR_MARK ) { continue; } if ( text.getBytes()[0] == FIELD_END_MARK ) { continue; } if ( characterRun.isSpecialCharacter() || characterRun.isObj() || characterRun.isOle2() ) { continue; } if ( text.endsWith( "\r" ) || ( text.charAt( text.length() - 1 ) == BEL_MARK && currentTableLevel != Integer.MIN_VALUE ) ) text = text.substring( 0, text.length() - 1 ); { StringBuilder stringBuilder = new StringBuilder(); for ( char charChar : text.toCharArray() ) { if ( charChar == 11 ) { if ( stringBuilder.length() > 0 ) { outputCharacters( block, characterRun, stringBuilder.toString() ); stringBuilder.setLength( 0 ); } processLineBreak( block, characterRun ); } else if ( charChar == 30 ) { stringBuilder.append( UNICODECHAR_NONBREAKING_HYPHEN ); } else if ( charChar == 31 ) { stringBuilder.append( UNICODECHAR_ZERO_WIDTH_SPACE ); } else if ( charChar >= 0x20 || charChar == 0x09 || charChar == 0x0A || charChar == 0x0D ) { stringBuilder.append( charChar ); } } if ( stringBuilder.length() > 0 ) { outputCharacters( block, characterRun, stringBuilder.toString() ); stringBuilder.setLength( 0 ); } } haveAnyText |= text.trim().length() != 0; } return haveAnyText; }
public String getSelector() { buildEngineMap(); if (_engines.isEmpty()) return "<b>No search engines specified</b>"; String dflt = _context.getProperty(PROP_DEFAULT); if (dflt == null || !_engines.containsKey(dflt)) { int idx = _context.random().nextInt(_engines.size()); int i = 0; for (String name : _engines.keySet()) { dflt = name; if (i++ >= idx) { _context.router().saveConfig(PROP_DEFAULT, dflt); break; } } } StringBuilder buf = new StringBuilder(1024); buf.append("<select name=\"engine\">"); for (String name : _engines.keySet()) { buf.append("<option value=\"").append(name).append('\"'); if (name.equals(dflt)) buf.append(" selected=\"true\""); buf.append('>').append(name).append("</option>\n"); } buf.append("</select>\n"); return buf.toString(); }
public String getSelector() { buildEngineMap(); if (_engines.isEmpty()) return "<b>No search engines specified</b>"; String dflt = _context.getProperty(PROP_DEFAULT); if (dflt == null || !_engines.containsKey(dflt)) { int idx = _context.random().nextInt(_engines.size()); int i = 0; for (String name : _engines.keySet()) { dflt = name; if (i++ >= idx) { _context.router().saveConfig(PROP_DEFAULT, dflt); break; } } } StringBuilder buf = new StringBuilder(1024); buf.append("<select name=\"engine\">"); for (String name : _engines.keySet()) { buf.append("<option value=\"").append(name).append('\"'); if (name.equals(dflt)) buf.append(" selected=\"selected\""); buf.append('>').append(name).append("</option>\n"); } buf.append("</select>\n"); return buf.toString(); }
public void save(){ Iterator<SaveCommand> siter = saveCommands.iterator(); int previousCommand = -1; int count = 0; while(siter.hasNext()){ this.progress = (int)((double)count / (double)this.saveCommands.size() * 100); this.mapDel.setProgressBarValue(this.progress, "Saving Map"); count++; SaveCommand tempCo = siter.next(); if(tempCo.getCommand() == SaveCommand.COPY_COMMAND){ this.saveCurrentChunks(); this.mapChunksE = null; try { MapChunkExtended copyFrom = new MapChunkExtended(tempCo.getChunkA()); MapChunkExtended copyTo = new MapChunkExtended(tempCo.getChunkB()); copyTo.copy(copyFrom); copyTo.save(); } catch (IOException e) { e.printStackTrace(); } } if(tempCo.getCommand() == SaveCommand.DELETE_COMMAND){ System.out.println("Delete Command"); this.deleteCommands.add(tempCo); } if(tempCo.getCommand() != SaveCommand.ADD_BLOCKS_COMMAND || tempCo.getCommand() != SaveCommand.CHANGE_HEIGHT_COMMAND){ continue; } if(this.mapChunksE == null){ this.mapChunksE = new HashMap<String, LinkedList<SaveCommand>>(); } if(!this.mapChunksE.containsKey(tempCo.getChunkA())){ LinkedList<SaveCommand> tempList = new LinkedList<SaveCommand>(); tempList.add(tempCo); this.mapChunksE.put(tempCo.getChunkA(), tempList); } else{ this.mapChunksE.get(tempCo.getChunkA()).add(tempCo); } } this.saveCurrentChunks(); this.delete(); this.mapDel.progressBarComplete("Finished Saving"); }
public void save(){ Iterator<SaveCommand> siter = saveCommands.iterator(); int previousCommand = -1; int count = 0; while(siter.hasNext()){ this.progress = (int)((double)count / (double)this.saveCommands.size() * 100); this.mapDel.setProgressBarValue(this.progress, "Saving Map"); count++; SaveCommand tempCo = siter.next(); if(tempCo.getCommand() == SaveCommand.COPY_COMMAND){ this.saveCurrentChunks(); this.mapChunksE = null; try { MapChunkExtended copyFrom = new MapChunkExtended(tempCo.getChunkA()); MapChunkExtended copyTo = new MapChunkExtended(tempCo.getChunkB()); copyTo.copy(copyFrom); copyTo.save(); } catch (IOException e) { e.printStackTrace(); } } if(tempCo.getCommand() == SaveCommand.DELETE_COMMAND){ System.out.println("Delete Command"); this.deleteCommands.add(tempCo); } if(tempCo.getCommand() != SaveCommand.ADD_BLOCKS_COMMAND && tempCo.getCommand() != SaveCommand.CHANGE_HEIGHT_COMMAND){ continue; } if(this.mapChunksE == null){ this.mapChunksE = new HashMap<String, LinkedList<SaveCommand>>(); } if(!this.mapChunksE.containsKey(tempCo.getChunkA())){ LinkedList<SaveCommand> tempList = new LinkedList<SaveCommand>(); tempList.add(tempCo); this.mapChunksE.put(tempCo.getChunkA(), tempList); } else { this.mapChunksE.get(tempCo.getChunkA()).add(tempCo); } } this.saveCurrentChunks(); this.delete(); this.mapDel.progressBarComplete("Finished Saving"); }
public SessionProvider( Registry registry, MBeanService mBeanService, @SessionCache Cache<?, ?> cache, @BackgroundScheduler ScheduledExecutorService scheduler, @Named(IpcSessionConfig.EXPIRATION_TIME) long time, @Named(IpcSessionConfig.EXPIRATION_TIME_UNIT) TimeUnit timeUnit) { this.registry = Preconditions.checkNotNull(registry, "Registry"); this.mBeanService = Preconditions.checkNotNull(mBeanService, "MBeanService"); this.cache = (Cache<Session.Key, IpcSession>) Preconditions.checkNotNull(cache, "Cache"); this.scheduler = Preconditions.checkNotNull(scheduler, "Scheduler"); this.expirationTime = time; this.expirationTimeUnit = Preconditions.checkNotNull(timeUnit, "TimeUnit"); }
public SessionProvider( Registry registry, MBeanService mBeanService, @SuppressWarnings("rawtypes") @SessionCache Cache cache, @BackgroundScheduler ScheduledExecutorService scheduler, @Named(IpcSessionConfig.EXPIRATION_TIME) long time, @Named(IpcSessionConfig.EXPIRATION_TIME_UNIT) TimeUnit timeUnit) { this.registry = Preconditions.checkNotNull(registry, "Registry"); this.mBeanService = Preconditions.checkNotNull(mBeanService, "MBeanService"); this.cache = (Cache<Session.Key, IpcSession>) Preconditions.checkNotNull(cache, "Cache"); this.scheduler = Preconditions.checkNotNull(scheduler, "Scheduler"); this.expirationTime = time; this.expirationTimeUnit = Preconditions.checkNotNull(timeUnit, "TimeUnit"); }
private synchronized void broadcastTags(Intent intent) { TagCache cache = app.getTagCache(); synchronized(cache) { Integer currentNestId = Integer.valueOf(intent.getIntExtra(BUNDLE_NEST_ID, -1)); List<String> out = new ArrayList<String>(); Set<String> lt = cache.getLocalTags(currentNestId); if(lt != null) { out.addAll(lt); } String[] rt = cache.getRemoteTags(currentNestId); if(rt != null) { for(String tag : rt) { out.add(tag); } } Intent broadcastIntent = new Intent(ACTION_AUTOCOMPLETE_TAGS); broadcastIntent.putExtra(BUNDLE_NEST_ID, currentNestId); broadcastIntent.putExtra(BUNDLE_TAG_LIST, out.toArray(new String[out.size()])); mLocalBroadcastManager.sendBroadcast(broadcastIntent); broadcastIntent.putExtra(BUNDLE_NEST_ID, currentNestId); broadcastIntent = new Intent(ACTION_LAST_USED_TAGS); String[] tags = cache.getLastUsedTags(currentNestId); if(tags == null) { tags = new String[0]; } broadcastIntent.putExtra(BUNDLE_TAG_LIST, tags); mLocalBroadcastManager.sendBroadcast(broadcastIntent); } }
private synchronized void broadcastTags(Intent intent) { TagCache cache = app.getTagCache(); synchronized(cache) { Integer currentNestId = Integer.valueOf(intent.getIntExtra(BUNDLE_NEST_ID, -1)); Set<String> out; Set<String> lt = cache.getLocalTags(currentNestId); if(lt != null) { out = new HashSet<String>(lt); } else { out = new HashSet<String>(); } String[] rt = cache.getRemoteTags(currentNestId); if(rt != null) { for(String tag : rt) { out.add(tag); } } Intent broadcastIntent = new Intent(ACTION_AUTOCOMPLETE_TAGS); broadcastIntent.putExtra(BUNDLE_NEST_ID, currentNestId); broadcastIntent.putExtra(BUNDLE_TAG_LIST, out.toArray(new String[out.size()])); mLocalBroadcastManager.sendBroadcast(broadcastIntent); broadcastIntent.putExtra(BUNDLE_NEST_ID, currentNestId); broadcastIntent = new Intent(ACTION_LAST_USED_TAGS); String[] tags = cache.getLastUsedTags(currentNestId); if(tags == null) { tags = new String[0]; } broadcastIntent.putExtra(BUNDLE_TAG_LIST, tags); mLocalBroadcastManager.sendBroadcast(broadcastIntent); } }
protected void onHandleIntent(Intent intent) { long now = java.lang.System.currentTimeMillis(); SharedPreferences settings=PreferenceManager.getDefaultSharedPreferences(this); long last = settings.getLong("lastDataUpdate", 0); boolean updateNeeded = false; if (last == 0) { updateNeeded = true; Log.d("UPDATE","Yes, never updated before"); } else if (now > last) { Log.d("UPDATEDATENOW",Long.toString(now)); Log.d("UPDATEDATELAST",Long.toString(last)); Log.d("UPDATEDATEMINUS",Long.toString(now - last)); ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); long interval; if (mWifi.isConnected()) { Log.d("UPDATE","WiFi Connected so 1 week"); interval = 1000*60*60*24*7; } else { Log.d("UPDATE","No WiFi so 1 month"); interval = 1000*60*60*24*7; } if ((now - last) > interval) { updateNeeded = true; Log.d("UPDATE","Yes, to old"); } } else { updateNeeded = true; Log.d("UPDATE","Yes, clock has run backwards"); } if (updateNeeded) { startService(new Intent(this, LoadDataService.class)); } }
protected void onHandleIntent(Intent intent) { long now = java.lang.System.currentTimeMillis(); SharedPreferences settings=PreferenceManager.getDefaultSharedPreferences(this); long last = settings.getLong("lastDataUpdate", 0); boolean updateNeeded = false; if (last == 0) { updateNeeded = true; Log.d("UPDATE","Yes, never updated before"); } else if (now > last) { Log.d("UPDATEDATENOW",Long.toString(now)); Log.d("UPDATEDATELAST",Long.toString(last)); Log.d("UPDATEDATEMINUS",Long.toString(now - last)); ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); long interval; if (mWifi.isConnected()) { Log.d("UPDATE","WiFi Connected so 1 week"); interval = 1000*60*60*24*7; } else { Log.d("UPDATE","No WiFi so 1 month"); interval = 1000*60*60*24*30; } if ((now - last) > interval) { updateNeeded = true; Log.d("UPDATE","Yes, to old"); } } else { updateNeeded = true; Log.d("UPDATE","Yes, clock has run backwards"); } if (updateNeeded) { startService(new Intent(this, LoadDataService.class)); } }
public static int processSum(ResultSet result, int sample_size, int db_size) throws SQLException { HashMap<Integer, Integer> frequencies = new HashMap<Integer, Integer>(); Integer k; Integer v; int sum = 0; int s = 0; while (result.next()) { k = new Integer(result.getInt("value")); if (frequencies.containsKey(k)) { v = frequencies.get(k); frequencies.put(k, new Integer(++v)); } else frequencies.put(k, new Integer(1)); s++; } System.out.println(s); Iterator<Map.Entry<Integer, Integer>> it = frequencies.entrySet().iterator(); while (it.hasNext()) { Entry<Integer, Integer> entry = (Entry<Integer, Integer>) it.next(); sum += entry.getKey() * (entry.getValue() / (double)sample_size) * db_size; } return sum; }
public static long processSum(ResultSet result, int sample_size, int db_size) throws SQLException { HashMap<Integer, Integer> frequencies = new HashMap<Integer, Integer>(); Integer k; Integer v; long sum = 0; int s = 0; while (result.next()) { k = new Integer(result.getInt("value")); if (frequencies.containsKey(k)) { v = frequencies.get(k); frequencies.put(k, new Integer(++v)); } else frequencies.put(k, new Integer(1)); s++; } System.out.println(s); Iterator<Map.Entry<Integer, Integer>> it = frequencies.entrySet().iterator(); while (it.hasNext()) { Entry<Integer, Integer> entry = (Entry<Integer, Integer>) it.next(); sum += entry.getKey() * (entry.getValue() / (double)sample_size) * db_size; } return sum; }
public User(String email_, String password_, String firstname_, String lastname_, String question_, String answer_) { this.email_ = email_; this.password_ = password_; this.firstname_ = firstname_; this.lastname_ = lastname_; this.question_ = question_; this.answer_ = answer_; if (User.count() == 0) { this.admin_ = true; } else { this.admin_ = true; } }
public User(String email_, String password_, String firstname_, String lastname_, String question_, String answer_) { this.email_ = email_; this.password_ = password_; this.firstname_ = firstname_; this.lastname_ = lastname_; this.question_ = question_; this.answer_ = answer_; if (User.count() == 0) { this.admin_ = true; } else { this.admin_ = false; } }
public void completeJoblet(int jobletId, JobletResult result, String logMessage) throws TransportException, InvalidApiKey, InvalidJobletId { log.trace("completeJoblet()"); Joblet joblet = readJoblet(jobletId); joblet.setStatus(result.getStatus()); dao.update(joblet); result.setJoblet(joblet); result.setTimeCreated(System.currentTimeMillis()); dao.create(result); if ((logMessage != null) && (logMessage.length() > 0)) { JobletLogEntry log = new JobletLogEntry(0, joblet, logMessage); dao.create(log); } Criteria crit = queryDAO.createCriteria(Joblet.class); crit.add(Restrictions.eq("jobId", joblet.getJobId())); crit.add(Restrictions.or( Restrictions.eq("status", JOB_STATUS.RECEIVED), Restrictions .or(Restrictions.eq("status", JOB_STATUS.QUEUED), Restrictions .eq("status", JOB_STATUS.PROCESSING)))); crit.setProjection(Projections.rowCount()); int active = ((Integer) crit.list().get(0)).intValue(); if (active == 0) { Query query = queryDAO .createQuery("update Joblet set status = ? where (jobId = ? and status = ?)"); query.setInteger(0, JOB_STATUS.RECEIVED); query.setInteger(1, joblet.getJobId()); query.setInteger(2, JOB_STATUS.SAVED); active = query.executeUpdate(); } if (active == 0) { Job job = (Job) dao.read(Job.class, joblet.getJobId()); Criteria failures = queryDAO.createCriteria(Joblet.class); failures.add(Restrictions.eq("jobId", job.getId())); failures.add(Restrictions.eq("status", JOB_STATUS.FAILED)); failures.setProjection(Projections.rowCount()); int failureCount = ((Integer) failures.list().get(0)).intValue(); int jobStatus = (failureCount == 0) ? JOB_STATUS.COMPLETED : JOB_STATUS.FAILED; job.setStatus(jobStatus); job = (Job) dao.update(job); if ((job.getCallbackType() != 0) && (job.getCallbackType() != JOB_CALLBACK_TYPES.NONE)) { Map<String, String> params = new HashMap<String, String>(); params.put("jobId", Integer.toString(job.getId())); params.put("jobStatus", jobStatusTypes[jobStatus]); params.put("callbackType", ApiCallbackTypes .getStringCallbackType(job.getCallbackType())); params.put("callbackAddress", job.getCallbackAddress()); Joblet callback = new Joblet(0, System.currentTimeMillis(), 0, 0, job.getSubmitter(), 2, Constants.CALLBACK_JOBLET, "Callback for job # ", params, null, JOB_STATUS.RECEIVED); try { self.submitJoblet(callback, 0, JOB_CALLBACK_TYPES.NONE, null, null); } catch (InvalidJobId e) { log.error("InvalidJobId called while submitting callback!", e); } } } }
public void completeJoblet(int jobletId, JobletResult result, String logMessage) throws TransportException, InvalidApiKey, InvalidJobletId { log.trace("completeJoblet()"); Joblet joblet = readJoblet(jobletId); joblet.setStatus(result.getStatus()); dao.update(joblet); result.setJoblet(joblet); result.setTimeCreated(System.currentTimeMillis()); dao.create(result); if ((logMessage != null) && (logMessage.length() > 0)) { JobletLogEntry log = new JobletLogEntry(0, joblet, logMessage); dao.create(log); } Criteria crit = queryDAO.createCriteria(Joblet.class); crit.add(Restrictions.eq("jobId", joblet.getJobId())); crit.add(Restrictions.or( Restrictions.eq("status", JOB_STATUS.RECEIVED), Restrictions .or(Restrictions.eq("status", JOB_STATUS.QUEUED), Restrictions .eq("status", JOB_STATUS.PROCESSING)))); crit.setProjection(Projections.rowCount()); int active = ((Integer) crit.list().get(0)).intValue(); if (active == 0) { Query query = queryDAO .createQuery("update Joblet set status = ? where (jobId = ? and status = ?)"); query.setInteger(0, JOB_STATUS.RECEIVED); query.setInteger(1, joblet.getJobId()); query.setInteger(2, JOB_STATUS.SAVED); active = query.executeUpdate(); } if (active == 0) { Job job = (Job) dao.read(Job.class, joblet.getJobId()); Criteria failures = queryDAO.createCriteria(Joblet.class); failures.add(Restrictions.eq("jobId", job.getId())); failures.add(Restrictions.eq("status", JOB_STATUS.FAILED)); failures.setProjection(Projections.rowCount()); int failureCount = ((Integer) failures.list().get(0)).intValue(); int jobStatus = (failureCount == 0) ? JOB_STATUS.COMPLETED : JOB_STATUS.FAILED; job.setStatus(jobStatus); job = (Job) dao.update(job); if ((job.getCallbackType() != 0) && (job.getCallbackType() != JOB_CALLBACK_TYPES.NONE)) { Map<String, String> params = new HashMap<String, String>(); params.put("jobId", Integer.toString(job.getId())); params.put("jobStatus", jobStatusTypes[jobStatus]); params.put("callbackType", ApiCallbackTypes .getStringCallbackType(job.getCallbackType())); params.put("callbackAddress", job.getCallbackAddress()); Joblet callback = new Joblet(0, System.currentTimeMillis(), 0, 0, job.getSubmitter(), 2, Constants.CALLBACK_JOBLET, "Callback for job # ", params, job.getCallbackContent(), JOB_STATUS.RECEIVED); try { self.submitJoblet(callback, 0, JOB_CALLBACK_TYPES.NONE, null, null); } catch (InvalidJobId e) { log.error("InvalidJobId called while submitting callback!", e); } } } }
public void shouldGetListOfUserSupportedProgramsForAFacilityForGivenRights() { Program program = new Program(); List<Program> programs = new ArrayList<>(Arrays.asList(program)); Long facilityId = 12345L; when(programService.getProgramsSupportedByUserHomeFacilityWithRights(facilityId, USER_ID, VIEW_REQUISITION)).thenReturn(programs); assertEquals(programs, controller.getProgramsToViewRequisitions(facilityId, httpServletRequest)); }
public void shouldGetListOfUserSupportedProgramsForAFacilityForGivenRights() { Program program = new Program(); List<Program> programs = new ArrayList<>(Arrays.asList(program)); Long facilityId = 12345L; when(programService.getProgramsForUserByFacilityAndRights(facilityId, USER_ID, VIEW_REQUISITION)).thenReturn(programs); assertEquals(programs, controller.getProgramsToViewRequisitions(facilityId, httpServletRequest)); }
private void _startScan( File folder ){ File[] files = folder.listFiles( new FileFilter() { @Override public boolean accept(File pathname) { if ( ! pathname.canRead() ) return false; if ( pathname.isHidden() && ! _hidden ) return false; if ( pathname.isDirectory() && ! _recursive ) return false; if ( _ff != null ){ return _ff.accept( pathname ); } else { for ( String ext : ALLOWED_MEDIA ) if ( pathname.getName().endsWith( ext ) ) return true; } return false; } }); for ( File file : files ){ if ( this.isStopped() ) return; if ( file.isDirectory() ){ this._startScan( file ); continue; } this.files.add( file ); this.getThreadListener().onProgress(this, 0, 0, 0, file); } }
private void _startScan( File folder ){ File[] files = folder.listFiles( new FileFilter() { @Override public boolean accept(File pathname) { if ( ! pathname.canRead() ) return false; if ( pathname.isHidden() && ! _hidden ) return false; if ( pathname.isDirectory() && ! _recursive ) return false; if ( _ff != null ){ return _ff.accept( pathname ); } else { for ( String ext : ALLOWED_MEDIA ) if ( pathname.getName().endsWith( "." + ext ) ) return true; } return false; } }); for ( File file : files ){ if ( this.isStopped() ) return; if ( file.isDirectory() ){ this._startScan( file ); continue; } this.files.add( file ); this.getThreadListener().onProgress(this, 0, 0, 0, file); } }
private boolean getLockInformation(ITransaction transaction, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Node lockInfoNode = null; DocumentBuilder documentBuilder = null; documentBuilder = getDocumentBuilder(); try { Document document = documentBuilder.parse(new InputSource(req .getInputStream())); Element rootElement = document.getDocumentElement(); lockInfoNode = rootElement; if (lockInfoNode != null) { NodeList childList = lockInfoNode.getChildNodes(); Node lockScopeNode = null; Node lockTypeNode = null; Node lockOwnerNode = null; Node currentNode = null; String nodeName = null; for (int i = 0; i < childList.getLength(); i++) { currentNode = childList.item(i); if (currentNode.getNodeType() == Node.ELEMENT_NODE || currentNode.getNodeType() == Node.TEXT_NODE) { nodeName = currentNode.getNodeName(); if (nodeName.endsWith("locktype")) { lockTypeNode = currentNode; } if (nodeName.endsWith("lockscope")) { lockScopeNode = currentNode; } if (nodeName.endsWith("owner")) { lockOwnerNode = currentNode; } } else { return false; } } if (lockScopeNode != null) { String scope = null; childList = lockScopeNode.getChildNodes(); for (int i = 0; i < childList.getLength(); i++) { currentNode = childList.item(i); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { scope = currentNode.getNodeName(); if (scope.endsWith("exclusive")) { _exclusive = true; } else if (scope.equals("shared")) { _exclusive = false; } } } if (scope == null) { return false; } } else { return false; } if (lockTypeNode != null) { childList = lockTypeNode.getChildNodes(); for (int i = 0; i < childList.getLength(); i++) { currentNode = childList.item(i); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { _type = currentNode.getNodeName(); if (_type.endsWith("write")) { _type = "write"; } else if (_type.equals("read")) { _type = "read"; } } } if (_type == null) { return false; } } else { return false; } if (lockOwnerNode != null) { childList = lockOwnerNode.getChildNodes(); for (int i = 0; i < childList.getLength(); i++) { currentNode = childList.item(i); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { _lockOwner = currentNode.getNodeValue(); } } } if (_lockOwner == null) { return false; } } else { return false; } } catch (DOMException e) { resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR); e.printStackTrace(); return false; } catch (SAXException e) { resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR); e.printStackTrace(); return false; } return true; }
private boolean getLockInformation(ITransaction transaction, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Node lockInfoNode = null; DocumentBuilder documentBuilder = null; documentBuilder = getDocumentBuilder(); try { Document document = documentBuilder.parse(new InputSource(req .getInputStream())); Element rootElement = document.getDocumentElement(); lockInfoNode = rootElement; if (lockInfoNode != null) { NodeList childList = lockInfoNode.getChildNodes(); Node lockScopeNode = null; Node lockTypeNode = null; Node lockOwnerNode = null; Node currentNode = null; String nodeName = null; for (int i = 0; i < childList.getLength(); i++) { currentNode = childList.item(i); if (currentNode.getNodeType() == Node.ELEMENT_NODE || currentNode.getNodeType() == Node.TEXT_NODE) { nodeName = currentNode.getNodeName(); if (nodeName.endsWith("locktype")) { lockTypeNode = currentNode; } if (nodeName.endsWith("lockscope")) { lockScopeNode = currentNode; } if (nodeName.endsWith("owner")) { lockOwnerNode = currentNode; } } else { return false; } } if (lockScopeNode != null) { String scope = null; childList = lockScopeNode.getChildNodes(); for (int i = 0; i < childList.getLength(); i++) { currentNode = childList.item(i); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { scope = currentNode.getNodeName(); if (scope.endsWith("exclusive")) { _exclusive = true; } else if (scope.equals("shared")) { _exclusive = false; } } } if (scope == null) { return false; } } else { return false; } if (lockTypeNode != null) { childList = lockTypeNode.getChildNodes(); for (int i = 0; i < childList.getLength(); i++) { currentNode = childList.item(i); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { _type = currentNode.getNodeName(); if (_type.endsWith("write")) { _type = "write"; } else if (_type.equals("read")) { _type = "read"; } } } if (_type == null) { return false; } } else { return false; } if (lockOwnerNode != null) { childList = lockOwnerNode.getChildNodes(); for (int i = 0; i < childList.getLength(); i++) { currentNode = childList.item(i); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { _lockOwner = currentNode.getFirstChild() .getNodeValue(); } } } if (_lockOwner == null) { return false; } } else { return false; } } catch (DOMException e) { resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR); e.printStackTrace(); return false; } catch (SAXException e) { resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR); e.printStackTrace(); return false; } return true; }
public static double[] getUniquedValuesFromMatrix(IMatrix data, IElementAdapter cellAdapter, int valueDimension, int maxUnique, IProgressMonitor monitor) { Double[] values = null; List<Double> valueList = new ArrayList<Double>(); MatrixUtils.DoubleCast cast = MatrixUtils.createDoubleCast( cellAdapter.getProperty(valueDimension).getValueClass()); Double min = Double.POSITIVE_INFINITY; Double max = Double.NEGATIVE_INFINITY; int colNb = data.getColumnCount(); int rowNb = data.getRowCount(); IProgressMonitor submonitor = monitor.subtask(); String valueDimensionName = data.getCellAttributes().get(valueDimension).getName(); submonitor.begin("Reading all values in data matrix for "+ valueDimensionName, rowNb); int randomRows = 50 > rowNb ? rowNb : 50; int[] randomRowsIdx = new int[randomRows]; for (int i = 0; i < randomRows; i++) randomRowsIdx[i] = (int)(Math.random() * ((rowNb) + 1)); int rr = 0; for (int r = 0; r<rowNb; r++) { monitor.worked(1); for (int c = 0; c < colNb; c++) { double d = cast.getDoubleValue( data.getCellValue(r, c, valueDimension)); if (!Double.isNaN(d)) { if (valueList.size() <= maxUnique && !valueList.contains(d) ) valueList.add(d); min = d < min ? d : min; max = d > max ? d : max; } } if (rr >= randomRows-1) break; else if (valueList.size() >= maxUnique) { r = randomRowsIdx[rr]; rr++; } } if (!valueList.contains(min)) valueList.add(min); if (!valueList.contains(max)) valueList.add(max); if (valueList.size() >= maxUnique) { valueList.clear(); double spectrum = max-min; double step = spectrum/maxUnique; for (int i = 0; i < maxUnique; i++) { valueList.add(i*step-(spectrum - max)); } } return ArrayUtils.toPrimitive(valueList.toArray(new Double[]{})); }
public static double[] getUniquedValuesFromMatrix(IMatrix data, IElementAdapter cellAdapter, int valueDimension, int maxUnique, IProgressMonitor monitor) { Double[] values = null; List<Double> valueList = new ArrayList<Double>(); MatrixUtils.DoubleCast cast = MatrixUtils.createDoubleCast( cellAdapter.getProperty(valueDimension).getValueClass()); Double min = Double.POSITIVE_INFINITY; Double max = Double.NEGATIVE_INFINITY; int colNb = data.getColumnCount(); int rowNb = data.getRowCount(); IProgressMonitor submonitor = monitor.subtask(); String valueDimensionName = data.getCellAttributes().get(valueDimension).getName(); submonitor.begin("Reading all values in data matrix for "+ valueDimensionName, rowNb); int randomRows = 50 > rowNb ? rowNb : 50; int[] randomRowsIdx = new int[randomRows]; for (int i = 0; i < randomRows; i++) randomRowsIdx[i] = (int)(Math.random() * ((rowNb) + 1)); int rr = 0; for (int r = 0; r<rowNb; r++) { monitor.worked(1); for (int c = 0; c < colNb; c++) { Object v = data.getCellValue(r, c, valueDimension); if (v == null) continue; double d = cast.getDoubleValue(v); if (!Double.isNaN(d)) { if (valueList.size() <= maxUnique && !valueList.contains(d) ) valueList.add(d); min = d < min ? d : min; max = d > max ? d : max; } } if (rr >= randomRows-1) break; else if (valueList.size() >= maxUnique) { r = randomRowsIdx[rr]; rr++; } } if (!valueList.contains(min)) valueList.add(min); if (!valueList.contains(max)) valueList.add(max); if (valueList.size() >= maxUnique) { valueList.clear(); double spectrum = max-min; double step = spectrum/maxUnique; for (int i = 0; i < maxUnique; i++) { valueList.add(i*step-(spectrum - max)); } } return ArrayUtils.toPrimitive(valueList.toArray(new Double[]{})); }
void startCleanup() { final long now = System.currentTimeMillis(); if (locallyOwnedMap != null) { locallyOwnedMap.evict(now); } if (mapNearCache != null) { mapNearCache.evict(now, false); } final Set<Record> recordsDirty = new HashSet<Record>(); final Set<Record> recordsUnknown = new HashSet<Record>(); final Set<Record> recordsToPurge = new HashSet<Record>(); final Set<Record> recordsToEvict = new HashSet<Record>(); final Set<Record> sortedRecords = new TreeSet<Record>(evictionComparator); final Collection<Record> records = mapRecords.values(); final int clusterMemberSize = node.getClusterImpl().getMembers().size(); final int memberCount = (clusterMemberSize == 0) ? 1 : clusterMemberSize; final int maxSizePerJVM = maxSize / memberCount; final boolean evictionAware = evictionComparator != null && maxSizePerJVM > 0; final PartitionServiceImpl partitionService = concurrentMapManager.partitionManager.partitionServiceImpl; int recordsStillOwned = 0; int backupPurgeCount = 0; for (Record record : records) { PartitionServiceImpl.PartitionProxy partition = partitionService.getPartition(record.getBlockId()); Member owner = partition.getOwner(); if (owner != null && !partition.isMigrating()) { boolean owned = owner.localMember(); if (owned) { if (store != null && record.isDirty()) { if (now > record.getWriteTime()) { recordsDirty.add(record); record.setDirty(false); } } else if (shouldPurgeRecord(record, now)) { recordsToPurge.add(record); } else if (record.isActive() && !record.isValid(now)) { recordsToEvict.add(record); } else if (evictionAware && record.isActive() && record.isEvictable()) { sortedRecords.add(record); recordsStillOwned++; } else { recordsStillOwned++; } } else { Member ownerEventual = partition.getEventualOwner(); boolean backup = false; if (ownerEventual != null && owner != null && !owner.localMember()) { int distance = node.getClusterImpl().getDistanceFrom(ownerEventual); backup = (distance != -1 && distance <= getBackupCount()); } if (backup) { if (shouldPurgeRecord(record, now)) { recordsToPurge.add(record); backupPurgeCount++; } } else { recordsUnknown.add(record); } } } } if (evictionAware && maxSizePerJVM < recordsStillOwned) { int numberOfRecordsToEvict = (int) (recordsStillOwned * evictionRate); int evictedCount = 0; for (Record record : sortedRecords) { if (record.isActive() && record.isEvictable()) { recordsToEvict.add(record); if (++evictedCount >= numberOfRecordsToEvict) { break; } } } } Level levelLog = (concurrentMapManager.LOG_STATE) ? Level.INFO : Level.FINEST; logger.log(levelLog, name + " Cleanup " + ", dirty:" + recordsDirty.size() + ", purge:" + recordsToPurge.size() + ", evict:" + recordsToEvict.size() + ", unknown:" + recordsUnknown.size() + ", stillOwned:" + recordsStillOwned + ", backupPurge:" + backupPurgeCount ); executeStoreUpdate(recordsDirty); executeEviction(recordsToEvict); executePurge(recordsToPurge); executePurgeUnknowns(recordsUnknown); }
void startCleanup() { final long now = System.currentTimeMillis(); if (locallyOwnedMap != null) { locallyOwnedMap.evict(now); } if (mapNearCache != null) { mapNearCache.evict(now, false); } final Set<Record> recordsDirty = new HashSet<Record>(); final Set<Record> recordsUnknown = new HashSet<Record>(); final Set<Record> recordsToPurge = new HashSet<Record>(); final Set<Record> recordsToEvict = new HashSet<Record>(); final Set<Record> sortedRecords = new TreeSet<Record>(evictionComparator); final Collection<Record> records = mapRecords.values(); final int clusterMemberSize = node.getClusterImpl().getMembers().size(); final int memberCount = (clusterMemberSize == 0) ? 1 : clusterMemberSize; final int maxSizePerJVM = maxSize / memberCount; final boolean evictionAware = evictionComparator != null && maxSizePerJVM > 0; final PartitionServiceImpl partitionService = concurrentMapManager.partitionManager.partitionServiceImpl; int recordsStillOwned = 0; int backupPurgeCount = 0; for (Record record : records) { PartitionServiceImpl.PartitionProxy partition = partitionService.getPartition(record.getBlockId()); Member owner = partition.getOwner(); if (owner != null && !partition.isMigrating()) { boolean owned = owner.localMember(); if (owned) { if (store != null && writeDelayMillis > 0 && record.isDirty()) { if (now > record.getWriteTime()) { recordsDirty.add(record); record.setDirty(false); } } else if (shouldPurgeRecord(record, now)) { recordsToPurge.add(record); } else if (record.isActive() && !record.isValid(now)) { recordsToEvict.add(record); } else if (evictionAware && record.isActive() && record.isEvictable()) { sortedRecords.add(record); recordsStillOwned++; } else { recordsStillOwned++; } } else { Member ownerEventual = partition.getEventualOwner(); boolean backup = false; if (ownerEventual != null && owner != null && !owner.localMember()) { int distance = node.getClusterImpl().getDistanceFrom(ownerEventual); backup = (distance != -1 && distance <= getBackupCount()); } if (backup) { if (shouldPurgeRecord(record, now)) { recordsToPurge.add(record); backupPurgeCount++; } } else { recordsUnknown.add(record); } } } } if (evictionAware && maxSizePerJVM < recordsStillOwned) { int numberOfRecordsToEvict = (int) (recordsStillOwned * evictionRate); int evictedCount = 0; for (Record record : sortedRecords) { if (record.isActive() && record.isEvictable()) { recordsToEvict.add(record); if (++evictedCount >= numberOfRecordsToEvict) { break; } } } } Level levelLog = (concurrentMapManager.LOG_STATE) ? Level.INFO : Level.FINEST; logger.log(levelLog, name + " Cleanup " + ", dirty:" + recordsDirty.size() + ", purge:" + recordsToPurge.size() + ", evict:" + recordsToEvict.size() + ", unknown:" + recordsUnknown.size() + ", stillOwned:" + recordsStillOwned + ", backupPurge:" + backupPurgeCount ); executeStoreUpdate(recordsDirty); executeEviction(recordsToEvict); executePurge(recordsToPurge); executePurgeUnknowns(recordsUnknown); }
protected void writeRatings(RatingDataAccessObject dao, Long2IntMap userSegments) throws MojoExecutionException, SQLException { Connection[] dbcs = new Connection[numFolds]; PreparedStatement[] insert = new PreparedStatement[numFolds]; PreparedStatement[] test = new PreparedStatement[numFolds]; try { for (int i = 0; i < numFolds; i++) { String fn = String.format(databaseFilePattern, i+1); getLog().debug("Opening database " + fn); dbcs[i] = DriverManager.getConnection("jdbc:sqlite:" + fn); JDBCUtils.execute(dbcs[i], "DROP TABLE IF EXISTS train;"); JDBCUtils.execute(dbcs[i], "DROP TABLE IF EXISTS test;"); String qmake = "CREATE TABLE %s (user INTEGER, item INTEGER, rating REAL"; if (useTimestamp) qmake += ", timestamp INTEGER"; qmake += ");"; JDBCUtils.execute(dbcs[i], String.format(qmake, "train")); JDBCUtils.execute(dbcs[i], String.format(qmake, "test")); qmake = "INSERT INTO %s (user, item, rating"; if (useTimestamp) qmake += ", timestamp"; qmake += ") VALUES (?, ?, ?"; if (useTimestamp) qmake += ", ?"; qmake += ");"; insert[i] = dbcs[i].prepareStatement(String.format(qmake, "train")); test[i] = dbcs[i].prepareStatement(String.format(qmake, "test")); dbcs[i].setAutoCommit(false); } Long2ObjectMap<List<Rating>> userRatings = new Long2ObjectOpenHashMap<List<Rating>>(userSegments.size()); LongIterator iter = userSegments.keySet().iterator(); while (iter.hasNext()) userRatings.put(iter.nextLong(), new ArrayList<Rating>()); getLog().info("Processing ratings"); Cursor<Rating> ratings = dao.getRatings(); try { int n = 0; for (Rating r: ratings) { long uid = r.getUserId(); int s = userSegments.get(uid); userRatings.get(uid).add(r); long ts = r.getTimestamp(); for (int i = 0; i < numFolds; i++) { if (i != s) { insert[i].setLong(1, uid); insert[i].setLong(2, r.getItemId()); insert[i].setDouble(3, r.getRating()); if (useTimestamp) { if (ts >= 0) insert[i].setLong(4, ts); else insert[i].setNull(4, Types.INTEGER); } insert[i].executeUpdate(); } } n++; if (n % 50 == 0 && getLog().isInfoEnabled()) System.out.format("%d\r", n); } if (getLog().isInfoEnabled()) System.out.format("%d\n", n); } finally { ratings.close(); } getLog().info("Writing test sets"); int n = 0; for (Long2ObjectMap.Entry<List<Rating>> e: userRatings.long2ObjectEntrySet()) { long uid = e.getLongKey(); int seg = userSegments.get(uid); PreparedStatement sTrain = insert[seg]; PreparedStatement sTest = test[seg]; sTrain.setLong(1, uid); sTest.setLong(1, uid); List<Rating> urs = e.getValue(); Collections.shuffle(urs); int midpt = urs.size() - holdoutCount; for (Rating r: urs.subList(0, midpt)) { long iid = r.getItemId(); double v = r.getRating(); long ts = r.getTimestamp(); sTrain.setLong(2, iid); sTrain.setDouble(3, v); if (useTimestamp) { if (ts >= 0) sTrain.setLong(4, ts); else sTrain.setNull(4, Types.INTEGER); } sTrain.executeUpdate(); } for (Rating r: urs.subList(0, midpt)) { long iid = r.getItemId(); double v = r.getRating(); long ts = r.getTimestamp(); sTest.setLong(2, iid); sTest.setDouble(3, v); if (useTimestamp) { if (ts >= 0) sTest.setLong(4, ts); else sTest.setNull(4, Types.INTEGER); } sTest.executeUpdate(); } urs.clear(); n++; if (n % 50 == 0 && getLog().isInfoEnabled()) System.out.format("%d\r", n); } if (getLog().isInfoEnabled()) System.out.format("%d\n", n); userRatings = null; getLog().info("Committing data"); for (int i = 0; i < numFolds; i++) { getLog().debug(String.format("Committing and indexing set %d", i+1)); dbcs[i].commit(); dbcs[i].setAutoCommit(true); JDBCUtils.execute(dbcs[i], "CREATE INDEX train_user_idx ON train (user);"); JDBCUtils.execute(dbcs[i], "CREATE INDEX train_item_idx ON train (item);"); JDBCUtils.execute(dbcs[i], "CREATE INDEX train_timestamp_idx ON train (timestamp);"); JDBCUtils.execute(dbcs[i], "CREATE INDEX test_user_idx ON test (user);"); JDBCUtils.execute(dbcs[i], "CREATE INDEX test_item_idx ON test (item);"); JDBCUtils.execute(dbcs[i], "ANALYZE;"); } } finally { boolean failed = false; for (int i = 0; i < dbcs.length; i++) { if (test[i] != null) { try { test[i].close(); } catch (SQLException e) { getLog().error(e); failed = true; } } if (insert[i] != null) { try { insert[i].close(); } catch (SQLException e) { getLog().error(e); failed = true; } } if (dbcs[i] != null) { try { dbcs[i].close(); } catch (SQLException e) { getLog().error(e); failed = true; } } if (failed) throw new MojoExecutionException("Failed to close database"); } } }
protected void writeRatings(RatingDataAccessObject dao, Long2IntMap userSegments) throws MojoExecutionException, SQLException { Connection[] dbcs = new Connection[numFolds]; PreparedStatement[] insert = new PreparedStatement[numFolds]; PreparedStatement[] test = new PreparedStatement[numFolds]; try { for (int i = 0; i < numFolds; i++) { String fn = String.format(databaseFilePattern, i+1); getLog().debug("Opening database " + fn); dbcs[i] = DriverManager.getConnection("jdbc:sqlite:" + fn); JDBCUtils.execute(dbcs[i], "DROP TABLE IF EXISTS train;"); JDBCUtils.execute(dbcs[i], "DROP TABLE IF EXISTS test;"); String qmake = "CREATE TABLE %s (user INTEGER, item INTEGER, rating REAL"; if (useTimestamp) qmake += ", timestamp INTEGER"; qmake += ");"; JDBCUtils.execute(dbcs[i], String.format(qmake, "train")); JDBCUtils.execute(dbcs[i], String.format(qmake, "test")); qmake = "INSERT INTO %s (user, item, rating"; if (useTimestamp) qmake += ", timestamp"; qmake += ") VALUES (?, ?, ?"; if (useTimestamp) qmake += ", ?"; qmake += ");"; insert[i] = dbcs[i].prepareStatement(String.format(qmake, "train")); test[i] = dbcs[i].prepareStatement(String.format(qmake, "test")); dbcs[i].setAutoCommit(false); } Long2ObjectMap<List<Rating>> userRatings = new Long2ObjectOpenHashMap<List<Rating>>(userSegments.size()); LongIterator iter = userSegments.keySet().iterator(); while (iter.hasNext()) userRatings.put(iter.nextLong(), new ArrayList<Rating>()); getLog().info("Processing ratings"); Cursor<Rating> ratings = dao.getRatings(); try { int n = 0; for (Rating r: ratings) { long uid = r.getUserId(); int s = userSegments.get(uid); userRatings.get(uid).add(r); long ts = r.getTimestamp(); for (int i = 0; i < numFolds; i++) { if (i != s) { insert[i].setLong(1, uid); insert[i].setLong(2, r.getItemId()); insert[i].setDouble(3, r.getRating()); if (useTimestamp) { if (ts >= 0) insert[i].setLong(4, ts); else insert[i].setNull(4, Types.INTEGER); } insert[i].executeUpdate(); } } n++; if (n % 50 == 0 && getLog().isInfoEnabled()) System.out.format("%d\r", n); } if (getLog().isInfoEnabled()) System.out.format("%d\n", n); } finally { ratings.close(); } getLog().info("Writing test sets"); int n = 0; for (Long2ObjectMap.Entry<List<Rating>> e: userRatings.long2ObjectEntrySet()) { long uid = e.getLongKey(); int seg = userSegments.get(uid); PreparedStatement sTrain = insert[seg]; PreparedStatement sTest = test[seg]; sTrain.setLong(1, uid); sTest.setLong(1, uid); List<Rating> urs = e.getValue(); Collections.shuffle(urs); int midpt = urs.size() - holdoutCount; for (Rating r: urs.subList(0, midpt)) { long iid = r.getItemId(); double v = r.getRating(); long ts = r.getTimestamp(); sTrain.setLong(2, iid); sTrain.setDouble(3, v); if (useTimestamp) { if (ts >= 0) sTrain.setLong(4, ts); else sTrain.setNull(4, Types.INTEGER); } sTrain.executeUpdate(); } for (Rating r: urs.subList(midpt, urs.size())) { long iid = r.getItemId(); double v = r.getRating(); long ts = r.getTimestamp(); sTest.setLong(2, iid); sTest.setDouble(3, v); if (useTimestamp) { if (ts >= 0) sTest.setLong(4, ts); else sTest.setNull(4, Types.INTEGER); } sTest.executeUpdate(); } urs.clear(); n++; if (n % 50 == 0 && getLog().isInfoEnabled()) System.out.format("%d\r", n); } if (getLog().isInfoEnabled()) System.out.format("%d\n", n); userRatings = null; getLog().info("Committing data"); for (int i = 0; i < numFolds; i++) { getLog().debug(String.format("Committing and indexing set %d", i+1)); dbcs[i].commit(); dbcs[i].setAutoCommit(true); JDBCUtils.execute(dbcs[i], "CREATE INDEX train_user_idx ON train (user);"); JDBCUtils.execute(dbcs[i], "CREATE INDEX train_item_idx ON train (item);"); JDBCUtils.execute(dbcs[i], "CREATE INDEX train_timestamp_idx ON train (timestamp);"); JDBCUtils.execute(dbcs[i], "CREATE INDEX test_user_idx ON test (user);"); JDBCUtils.execute(dbcs[i], "CREATE INDEX test_item_idx ON test (item);"); JDBCUtils.execute(dbcs[i], "ANALYZE;"); } } finally { boolean failed = false; for (int i = 0; i < dbcs.length; i++) { if (test[i] != null) { try { test[i].close(); } catch (SQLException e) { getLog().error(e); failed = true; } } if (insert[i] != null) { try { insert[i].close(); } catch (SQLException e) { getLog().error(e); failed = true; } } if (dbcs[i] != null) { try { dbcs[i].close(); } catch (SQLException e) { getLog().error(e); failed = true; } } if (failed) throw new MojoExecutionException("Failed to close database"); } } }

RepairLLaMA - Datasets

Contains the processed fine-tuning datasets for RepairLLaMA.

Instructions to explore the dataset

To load the dataset, you must define which revision (i.e., which input/output representation pair) you want to load.

from datasets import load_dataset

# Load ir1xor1
dataset = load_dataset("ASSERT-KTH/repairllama-datasets", "ir1xor1")
# Load irXxorY
dataset = load_dataset("ASSERT-KTH/repairllama-dataset", "irXxorY")

Citation

If you use RepairLLaMA in academic research, please cite "RepairLLaMA: Efficient Representations and Fine-Tuned Adapters for Program Repair", Technical report, arXiv 2312.15698, 2023.

@techreport{repairllama2023,
  title={RepairLLaMA: Efficient Representations and Fine-Tuned Adapters for Program Repair},
  author={Silva, Andr{\'e} and Fang, Sen and Monperrus, Martin},
  url = {http://arxiv.org/abs/2312.15698},
  number = {2312.15698},
  institution = {arXiv},
}
Downloads last month
3
Edit dataset card