id
int64
22
34.9k
original_code
stringlengths
31
107k
code_wo_comment
stringlengths
29
77.3k
cleancode
stringlengths
25
62.1k
repo
stringlengths
6
65
label
sequencelengths
4
4
30,822
public void checkBookmarks() throws IOException { for (Bookmark bookmark : bookmarksService.getBookmarks()) { bookmarksService.doCheck(bookmark); JavaFxUtils.getController(BookmarksController.class).bookmarksTableView.refresh(); } JavaFxUtils.getController(BookmarksController.class).tableView.setUserData(null); JavaFxUtils.getController(BookmarksController.class).webView.setUserData(null); //TODO refresh current bookmark if not SAME if (currentBookmark != null/* && JavaFxUtils.currentBookmark.getStatus() == BookmarkStatus.CHANGED*/) { JavaFxUtils.getController(BookmarksController.class).refresh(); } }
public void checkBookmarks() throws IOException { for (Bookmark bookmark : bookmarksService.getBookmarks()) { bookmarksService.doCheck(bookmark); JavaFxUtils.getController(BookmarksController.class).bookmarksTableView.refresh(); } JavaFxUtils.getController(BookmarksController.class).tableView.setUserData(null); JavaFxUtils.getController(BookmarksController.class).webView.setUserData(null); if (currentBookmark != nul) { JavaFxUtils.getController(BookmarksController.class).refresh(); } }
public void checkbookmarks() throws ioexception { for (bookmark bookmark : bookmarksservice.getbookmarks()) { bookmarksservice.docheck(bookmark); javafxutils.getcontroller(bookmarkscontroller.class).bookmarkstableview.refresh(); } javafxutils.getcontroller(bookmarkscontroller.class).tableview.setuserdata(null); javafxutils.getcontroller(bookmarkscontroller.class).webview.setuserdata(null); if (currentbookmark != nul) { javafxutils.getcontroller(bookmarkscontroller.class).refresh(); } }
LeonisX/jSite-Watcher
[ 0, 1, 0, 0 ]
22,752
public void remove( ) { // TODO Add remove operation support. }
public void remove( ) { }
public void remove( ) { }
JamesCao2048/BlizzardData
[ 0, 1, 0, 0 ]
30,989
public String longestPalindrome(String s) { // TODO:write your code here return ""; }
public String longestPalindrome(String s) { return ""; }
public string longestpalindrome(string s) { return ""; }
MessierObject111/algorithms-playground
[ 0, 1, 0, 0 ]
30,992
public File executeOptimization() throws IOException, InterruptedException { final String path = workingFile.getCanonicalPath(); // FIXME Handle the ImageFileOptimizationException in one of the optimizations so it does not impact the other optimizations. return executePngquant(executeOptipng(executePngout(executeAdvpng(executePngquant(executeOptipng(executePngout(executeAdvpng(workingFile, path), path), path), path), path), path), path), path); }
public File executeOptimization() throws IOException, InterruptedException { final String path = workingFile.getCanonicalPath(); return executePngquant(executeOptipng(executePngout(executeAdvpng(executePngquant(executeOptipng(executePngout(executeAdvpng(workingFile, path), path), path), path), path), path), path), path); }
public file executeoptimization() throws ioexception, interruptedexception { final string path = workingfile.getcanonicalpath(); return executepngquant(executeoptipng(executepngout(executeadvpng(executepngquant(executeoptipng(executepngout(executeadvpng(workingfile, path), path), path), path), path), path), path), path); }
MatthewJuliusScott/ImageOptimization
[ 1, 0, 0, 0 ]
23,231
@Test public void testValueOfJ() { // workaround to register this test as covering some part of the testee. // static variable access does not currently register as coverage . . . HasMutableStaticInitializer.noticeMe(); assertEquals(101, HasMutableStaticInitializer.j); }
@Test public void testValueOfJ() { HasMutableStaticInitializer.noticeMe(); assertEquals(101, HasMutableStaticInitializer.j); }
@test public void testvalueofj() { hasmutablestaticinitializer.noticeme(); assertequals(101, hasmutablestaticinitializer.j); }
Programming-Systems-Lab/pitest
[ 0, 1, 0, 0 ]
31,477
@Test public void testLineOfCaller() { assumeStackTraceDetailsAvailable(); DynamicConverter<ILoggingEvent> converter = new LineOfCallerConverter(); StringBuilder buf = new StringBuilder(); converter.write(buf, le); // the number below should be the line number of the previous line assertEquals("78", buf.toString()); // TODO: Refactor this test so that it does not depend on the actual line numbers of this file }
@Test public void testLineOfCaller() { assumeStackTraceDetailsAvailable(); DynamicConverter<ILoggingEvent> converter = new LineOfCallerConverter(); StringBuilder buf = new StringBuilder(); converter.write(buf, le); assertEquals("78", buf.toString()); }
@test public void testlineofcaller() { assumestacktracedetailsavailable(); dynamicconverter<iloggingevent> converter = new lineofcallerconverter(); stringbuilder buf = new stringbuilder(); converter.write(buf, le); assertequals("78", buf.tostring()); }
LinZong/logback-android
[ 0, 0, 0, 1 ]
23,314
@Override public void runOpMode() throws InterruptedException { /* Initialize the setDrivePowers system variables. The init() methods of our hardware class does all the work: */ FtcDashboard dashboard = FtcDashboard.getInstance(); Telemetry dashboardTelemetry = dashboard.getTelemetry(); robot.init(hardwareMap, this, true, false); /* Init Delay Option Select: */ // After init is pushed but before Start we can change the delay using dpad up/down // delayTimer.reset(); // Runs a loop to change certain settings while we wait to start while (!opModeIsActive()) { if (this.isStopRequested()) { // Leave the loop if STOP is pressed return; } if (gamepad1.dpad_up && (delayTimer.seconds() > 0.8)) { // Increases the amount of time we wait timeDelay += 1; delayTimer.reset(); } if (gamepad1.dpad_down && (delayTimer.seconds() > 0.8)) { // Decreases the amount of time we wait if (timeDelay > 0) { // No such thing as negative time timeDelay -= 1; } delayTimer.reset(); } if (((gamepad1.x) && delayTimer.seconds() > 0.8)) { // Changes Alliance Sides if (isRedAlliance) { isRedAlliance = false; robot.isRedAlliance = false; } else { isRedAlliance = true; robot.isRedAlliance = true; } delayTimer.reset(); } /** * LED code: */ if (robot.eyes.getNumRings() == CatHW_Vision.UltimateGoalPipeline.numRings.NONE) { robot.lights.setDefaultColor(RevBlinkinLedDriver.BlinkinPattern.RAINBOW_LAVA_PALETTE); } if (robot.eyes.getNumRings() == CatHW_Vision.UltimateGoalPipeline.numRings.ONE) { robot.lights.setDefaultColor(RevBlinkinLedDriver.BlinkinPattern.RAINBOW_OCEAN_PALETTE); } if (robot.eyes.getNumRings() == CatHW_Vision.UltimateGoalPipeline.numRings.FOUR) { robot.lights.setDefaultColor(RevBlinkinLedDriver.BlinkinPattern.RAINBOW_PARTY_PALETTE); } /** * Telemetry while waiting for PLAY: */ telemetry.addData("Delay Timer: ", timeDelay); if (isRedAlliance) { telemetry.addData("Alliance: ", "Red"); } else { telemetry.addData("Alliance: ", "Blue"); } telemetry.addData("Num of Rings", "%s",robot.eyes.getNumRings().toString()); dashboardTelemetry.addData("Num of Rings", "%s",robot.eyes.getNumRings().toString()); dashboardTelemetry.addData("Analysis", "%d", robot.eyes.pipeline.getAnalysis()); dashboardTelemetry.update(); telemetry.update(); /** * We don't need a "waitForStart()" since we've been running our own * loop all this time so that we can make some changes. */ } CatHW_Vision.UltimateGoalPipeline.numRings numRings = robot.eyes.getNumRings(); /** * Runs after hit start: * DO STUFF FOR the OPMODE!!! */ /** * Init the IMU after play so that it is not offset after * remaining idle for a minute or two... */ robot.driveClassic.IMU_Init(); // Time Delay: robot.robotWait(timeDelay); robot.driveOdo.quickDrive(-4,48,0.5, 0,3.0); for (int i = 0; i < 5; i++) { robot.robotWait(5); Log.d("catbot", String.format("Translate Time wait current %.2f %.2f %.1f ", robot.driveOdo.updatesThread.positionUpdate.returnXInches(), robot.driveOdo.updatesThread.positionUpdate.returnYInches(), robot.driveOdo.updatesThread.positionUpdate.returnOrientation() )); robot.driveOdo.quickDrive( -4,96,0.8, 0,5.0); robot.driveOdo.quickDrive(-52,96,0.8, 0,5.0); robot.driveOdo.quickDrive(-52,48,0.8, 0,5.0); robot.driveOdo.quickDrive( -4,48,0.8, 0,5.0); } /* for (int i = 0; i <= 5; i++) { robot.robotWait(5); robot.driveOdo.quickDrive( -4,96,0.3, -90,3.0); robot.driveOdo.quickDrive(-52,96,0.3, 0,3.0); robot.driveOdo.quickDrive(-52,48,0.3, 90,3.0); robot.driveOdo.quickDrive( -4,48,0.3, 0,3.0); } */ robot.driveOdo.updatesThread.stop(); }
@Override public void runOpMode() throws InterruptedException { FtcDashboard dashboard = FtcDashboard.getInstance(); Telemetry dashboardTelemetry = dashboard.getTelemetry(); robot.init(hardwareMap, this, true, false); delayTimer.reset(); while (!opModeIsActive()) { if (this.isStopRequested()) { return; } if (gamepad1.dpad_up && (delayTimer.seconds() > 0.8)) { timeDelay += 1; delayTimer.reset(); } if (gamepad1.dpad_down && (delayTimer.seconds() > 0.8)) { if (timeDelay > 0) { timeDelay -= 1; } delayTimer.reset(); } if (((gamepad1.x) && delayTimer.seconds() > 0.8)) { if (isRedAlliance) { isRedAlliance = false; robot.isRedAlliance = false; } else { isRedAlliance = true; robot.isRedAlliance = true; } delayTimer.reset(); } if (robot.eyes.getNumRings() == CatHW_Vision.UltimateGoalPipeline.numRings.NONE) { robot.lights.setDefaultColor(RevBlinkinLedDriver.BlinkinPattern.RAINBOW_LAVA_PALETTE); } if (robot.eyes.getNumRings() == CatHW_Vision.UltimateGoalPipeline.numRings.ONE) { robot.lights.setDefaultColor(RevBlinkinLedDriver.BlinkinPattern.RAINBOW_OCEAN_PALETTE); } if (robot.eyes.getNumRings() == CatHW_Vision.UltimateGoalPipeline.numRings.FOUR) { robot.lights.setDefaultColor(RevBlinkinLedDriver.BlinkinPattern.RAINBOW_PARTY_PALETTE); } telemetry.addData("Delay Timer: ", timeDelay); if (isRedAlliance) { telemetry.addData("Alliance: ", "Red"); } else { telemetry.addData("Alliance: ", "Blue"); } telemetry.addData("Num of Rings", "%s",robot.eyes.getNumRings().toString()); dashboardTelemetry.addData("Num of Rings", "%s",robot.eyes.getNumRings().toString()); dashboardTelemetry.addData("Analysis", "%d", robot.eyes.pipeline.getAnalysis()); dashboardTelemetry.update(); telemetry.update(); } CatHW_Vision.UltimateGoalPipeline.numRings numRings = robot.eyes.getNumRings(); robot.driveClassic.IMU_Init(); robot.robotWait(timeDelay); robot.driveOdo.quickDrive(-4,48,0.5, 0,3.0); for (int i = 0; i < 5; i++) { robot.robotWait(5); Log.d("catbot", String.format("Translate Time wait current %.2f %.2f %.1f ", robot.driveOdo.updatesThread.positionUpdate.returnXInches(), robot.driveOdo.updatesThread.positionUpdate.returnYInches(), robot.driveOdo.updatesThread.positionUpdate.returnOrientation() )); robot.driveOdo.quickDrive( -4,96,0.8, 0,5.0); robot.driveOdo.quickDrive(-52,96,0.8, 0,5.0); robot.driveOdo.quickDrive(-52,48,0.8, 0,5.0); robot.driveOdo.quickDrive( -4,48,0.8, 0,5.0); } robot.driveOdo.updatesThread.stop(); }
@override public void runopmode() throws interruptedexception { ftcdashboard dashboard = ftcdashboard.getinstance(); telemetry dashboardtelemetry = dashboard.gettelemetry(); robot.init(hardwaremap, this, true, false); delaytimer.reset(); while (!opmodeisactive()) { if (this.isstoprequested()) { return; } if (gamepad1.dpad_up && (delaytimer.seconds() > 0.8)) { timedelay += 1; delaytimer.reset(); } if (gamepad1.dpad_down && (delaytimer.seconds() > 0.8)) { if (timedelay > 0) { timedelay -= 1; } delaytimer.reset(); } if (((gamepad1.x) && delaytimer.seconds() > 0.8)) { if (isredalliance) { isredalliance = false; robot.isredalliance = false; } else { isredalliance = true; robot.isredalliance = true; } delaytimer.reset(); } if (robot.eyes.getnumrings() == cathw_vision.ultimategoalpipeline.numrings.none) { robot.lights.setdefaultcolor(revblinkinleddriver.blinkinpattern.rainbow_lava_palette); } if (robot.eyes.getnumrings() == cathw_vision.ultimategoalpipeline.numrings.one) { robot.lights.setdefaultcolor(revblinkinleddriver.blinkinpattern.rainbow_ocean_palette); } if (robot.eyes.getnumrings() == cathw_vision.ultimategoalpipeline.numrings.four) { robot.lights.setdefaultcolor(revblinkinleddriver.blinkinpattern.rainbow_party_palette); } telemetry.adddata("delay timer: ", timedelay); if (isredalliance) { telemetry.adddata("alliance: ", "red"); } else { telemetry.adddata("alliance: ", "blue"); } telemetry.adddata("num of rings", "%s",robot.eyes.getnumrings().tostring()); dashboardtelemetry.adddata("num of rings", "%s",robot.eyes.getnumrings().tostring()); dashboardtelemetry.adddata("analysis", "%d", robot.eyes.pipeline.getanalysis()); dashboardtelemetry.update(); telemetry.update(); } cathw_vision.ultimategoalpipeline.numrings numrings = robot.eyes.getnumrings(); robot.driveclassic.imu_init(); robot.robotwait(timedelay); robot.driveodo.quickdrive(-4,48,0.5, 0,3.0); for (int i = 0; i < 5; i++) { robot.robotwait(5); log.d("catbot", string.format("translate time wait current %.2f %.2f %.1f ", robot.driveodo.updatesthread.positionupdate.returnxinches(), robot.driveodo.updatesthread.positionupdate.returnyinches(), robot.driveodo.updatesthread.positionupdate.returnorientation() )); robot.driveodo.quickdrive( -4,96,0.8, 0,5.0); robot.driveodo.quickdrive(-52,96,0.8, 0,5.0); robot.driveodo.quickdrive(-52,48,0.8, 0,5.0); robot.driveodo.quickdrive( -4,48,0.8, 0,5.0); } robot.driveodo.updatesthread.stop(); }
PanzerSchnitter/UltimateGoal2020
[ 0, 0, 0, 0 ]
15,126
private void clanList(L2PcInstance activeChar, int index) { if (index < 1) { index = 1; } // header final StringBuilder html = StringUtil.startAppend(2000, "<html><body><br><br><center><br1><br1><table border=0 cellspacing=0 cellpadding=0><tr><td FIXWIDTH=15>&nbsp;</td><td width=610 height=30 align=left><a action=\"bypass _bbsclan_clanlist\"> CLAN COMMUNITY </a></td></tr></table><table border=0 cellspacing=0 cellpadding=0 width=610 bgcolor=434343><tr><td height=10></td></tr><tr><td fixWIDTH=5></td><td fixWIDTH=600><a action=\"bypass _bbsclan_clanhome;", String.valueOf((activeChar.getClan() != null) ? activeChar.getClan().getId() : 0), "\">[GO TO MY CLAN]</a>&nbsp;&nbsp;</td><td fixWIDTH=5></td></tr><tr><td height=10></td></tr></table><br><table border=0 cellspacing=0 cellpadding=2 bgcolor=5A5A5A width=610><tr><td FIXWIDTH=5></td><td FIXWIDTH=200 align=center>CLAN NAME</td><td FIXWIDTH=200 align=center>CLAN LEADER</td><td FIXWIDTH=100 align=center>CLAN LEVEL</td><td FIXWIDTH=100 align=center>CLAN MEMBERS</td><td FIXWIDTH=5></td></tr></table><img src=\"L2UI.Squareblank\" width=\"1\" height=\"5\">"); int i = 0; for (L2Clan cl : ClanTable.getInstance().getClans()) { if (i > ((index + 1) * 7)) { break; } if (i++ >= ((index - 1) * 7)) { StringUtil.append(html, "<img src=\"L2UI.SquareBlank\" width=\"610\" height=\"3\"><table border=0 cellspacing=0 cellpadding=0 width=610><tr> <td FIXWIDTH=5></td><td FIXWIDTH=200 align=center><a action=\"bypass _bbsclan_clanhome;", String.valueOf(cl.getId()), "\">", cl.getName(), "</a></td><td FIXWIDTH=200 align=center>", cl.getLeaderName(), "</td><td FIXWIDTH=100 align=center>", String.valueOf(cl.getLevel()), "</td><td FIXWIDTH=100 align=center>", String.valueOf(cl.getMembersCount()), "</td><td FIXWIDTH=5></td></tr><tr><td height=5></td></tr></table><img src=\"L2UI.SquareBlank\" width=\"610\" height=\"3\"><img src=\"L2UI.SquareGray\" width=\"610\" height=\"1\">"); } } html.append("<img src=\"L2UI.SquareBlank\" width=\"610\" height=\"2\"><table cellpadding=0 cellspacing=2 border=0><tr>"); if (index == 1) { html.append("<td><button action=\"\" back=\"l2ui_ch3.prev1_down\" fore=\"l2ui_ch3.prev1\" width=16 height=16 ></td>"); } else { StringUtil.append(html, "<td><button action=\"_bbsclan_clanlist;", String.valueOf(index - 1), "\" back=\"l2ui_ch3.prev1_down\" fore=\"l2ui_ch3.prev1\" width=16 height=16 ></td>"); } i = 0; int nbp = ClanTable.getInstance().getClanCount() / 8; if ((nbp * 8) != ClanTable.getInstance().getClanCount()) { nbp++; } for (i = 1; i <= nbp; i++) { if (i == index) { StringUtil.append(html, "<td> ", String.valueOf(i), " </td>"); } else { StringUtil.append(html, "<td><a action=\"bypass _bbsclan_clanlist;", String.valueOf(i), "\"> ", String.valueOf(i), " </a></td>"); } } if (index == nbp) { html.append("<td><button action=\"\" back=\"l2ui_ch3.next1_down\" fore=\"l2ui_ch3.next1\" width=16 height=16 ></td>"); } else { StringUtil.append(html, "<td><button action=\"bypass _bbsclan_clanlist;", String.valueOf(index + 1), "\" back=\"l2ui_ch3.next1_down\" fore=\"l2ui_ch3.next1\" width=16 height=16 ></td>"); } html.append("</tr></table><table border=0 cellspacing=0 cellpadding=0><tr><td width=610><img src=\"sek.cbui141\" width=\"610\" height=\"1\"></td></tr></table><table border=0><tr><td><combobox width=65 var=keyword list=\"Name;Ruler\"></td><td><edit var = \"Search\" width=130 height=11 length=\"16\"></td>" + // TODO: search (Write in BBS) "<td><button value=\"&$420;\" action=\"Write 5 -1 0 Search keyword keyword\" back=\"l2ui_ch3.smallbutton2_down\" width=65 height=20 fore=\"l2ui_ch3.smallbutton2\"> </td> </tr></table><br><br></center></body></html>"); CommunityBoardHandler.separateAndSend(html.toString(), activeChar); }
private void clanList(L2PcInstance activeChar, int index) { if (index < 1) { index = 1; } final StringBuilder html = StringUtil.startAppend(2000, "<html><body><br><br><center><br1><br1><table border=0 cellspacing=0 cellpadding=0><tr><td FIXWIDTH=15>&nbsp;</td><td width=610 height=30 align=left><a action=\"bypass _bbsclan_clanlist\"> CLAN COMMUNITY </a></td></tr></table><table border=0 cellspacing=0 cellpadding=0 width=610 bgcolor=434343><tr><td height=10></td></tr><tr><td fixWIDTH=5></td><td fixWIDTH=600><a action=\"bypass _bbsclan_clanhome;", String.valueOf((activeChar.getClan() != null) ? activeChar.getClan().getId() : 0), "\">[GO TO MY CLAN]</a>&nbsp;&nbsp;</td><td fixWIDTH=5></td></tr><tr><td height=10></td></tr></table><br><table border=0 cellspacing=0 cellpadding=2 bgcolor=5A5A5A width=610><tr><td FIXWIDTH=5></td><td FIXWIDTH=200 align=center>CLAN NAME</td><td FIXWIDTH=200 align=center>CLAN LEADER</td><td FIXWIDTH=100 align=center>CLAN LEVEL</td><td FIXWIDTH=100 align=center>CLAN MEMBERS</td><td FIXWIDTH=5></td></tr></table><img src=\"L2UI.Squareblank\" width=\"1\" height=\"5\">"); int i = 0; for (L2Clan cl : ClanTable.getInstance().getClans()) { if (i > ((index + 1) * 7)) { break; } if (i++ >= ((index - 1) * 7)) { StringUtil.append(html, "<img src=\"L2UI.SquareBlank\" width=\"610\" height=\"3\"><table border=0 cellspacing=0 cellpadding=0 width=610><tr> <td FIXWIDTH=5></td><td FIXWIDTH=200 align=center><a action=\"bypass _bbsclan_clanhome;", String.valueOf(cl.getId()), "\">", cl.getName(), "</a></td><td FIXWIDTH=200 align=center>", cl.getLeaderName(), "</td><td FIXWIDTH=100 align=center>", String.valueOf(cl.getLevel()), "</td><td FIXWIDTH=100 align=center>", String.valueOf(cl.getMembersCount()), "</td><td FIXWIDTH=5></td></tr><tr><td height=5></td></tr></table><img src=\"L2UI.SquareBlank\" width=\"610\" height=\"3\"><img src=\"L2UI.SquareGray\" width=\"610\" height=\"1\">"); } } html.append("<img src=\"L2UI.SquareBlank\" width=\"610\" height=\"2\"><table cellpadding=0 cellspacing=2 border=0><tr>"); if (index == 1) { html.append("<td><button action=\"\" back=\"l2ui_ch3.prev1_down\" fore=\"l2ui_ch3.prev1\" width=16 height=16 ></td>"); } else { StringUtil.append(html, "<td><button action=\"_bbsclan_clanlist;", String.valueOf(index - 1), "\" back=\"l2ui_ch3.prev1_down\" fore=\"l2ui_ch3.prev1\" width=16 height=16 ></td>"); } i = 0; int nbp = ClanTable.getInstance().getClanCount() / 8; if ((nbp * 8) != ClanTable.getInstance().getClanCount()) { nbp++; } for (i = 1; i <= nbp; i++) { if (i == index) { StringUtil.append(html, "<td> ", String.valueOf(i), " </td>"); } else { StringUtil.append(html, "<td><a action=\"bypass _bbsclan_clanlist;", String.valueOf(i), "\"> ", String.valueOf(i), " </a></td>"); } } if (index == nbp) { html.append("<td><button action=\"\" back=\"l2ui_ch3.next1_down\" fore=\"l2ui_ch3.next1\" width=16 height=16 ></td>"); } else { StringUtil.append(html, "<td><button action=\"bypass _bbsclan_clanlist;", String.valueOf(index + 1), "\" back=\"l2ui_ch3.next1_down\" fore=\"l2ui_ch3.next1\" width=16 height=16 ></td>"); } html.append("</tr></table><table border=0 cellspacing=0 cellpadding=0><tr><td width=610><img src=\"sek.cbui141\" width=\"610\" height=\"1\"></td></tr></table><table border=0><tr><td><combobox width=65 var=keyword list=\"Name;Ruler\"></td><td><edit var = \"Search\" width=130 height=11 length=\"16\"></td>" + "<td><button value=\"&$420;\" action=\"Write 5 -1 0 Search keyword keyword\" back=\"l2ui_ch3.smallbutton2_down\" width=65 height=20 fore=\"l2ui_ch3.smallbutton2\"> </td> </tr></table><br><br></center></body></html>"); CommunityBoardHandler.separateAndSend(html.toString(), activeChar); }
private void clanlist(l2pcinstance activechar, int index) { if (index < 1) { index = 1; } final stringbuilder html = stringutil.startappend(2000, "<html><body><br><br><center><br1><br1><table border=0 cellspacing=0 cellpadding=0><tr><td fixwidth=15>&nbsp;</td><td width=610 height=30 align=left><a action=\"bypass _bbsclan_clanlist\"> clan community </a></td></tr></table><table border=0 cellspacing=0 cellpadding=0 width=610 bgcolor=434343><tr><td height=10></td></tr><tr><td fixwidth=5></td><td fixwidth=600><a action=\"bypass _bbsclan_clanhome;", string.valueof((activechar.getclan() != null) ? activechar.getclan().getid() : 0), "\">[go to my clan]</a>&nbsp;&nbsp;</td><td fixwidth=5></td></tr><tr><td height=10></td></tr></table><br><table border=0 cellspacing=0 cellpadding=2 bgcolor=5a5a5a width=610><tr><td fixwidth=5></td><td fixwidth=200 align=center>clan name</td><td fixwidth=200 align=center>clan leader</td><td fixwidth=100 align=center>clan level</td><td fixwidth=100 align=center>clan members</td><td fixwidth=5></td></tr></table><img src=\"l2ui.squareblank\" width=\"1\" height=\"5\">"); int i = 0; for (l2clan cl : clantable.getinstance().getclans()) { if (i > ((index + 1) * 7)) { break; } if (i++ >= ((index - 1) * 7)) { stringutil.append(html, "<img src=\"l2ui.squareblank\" width=\"610\" height=\"3\"><table border=0 cellspacing=0 cellpadding=0 width=610><tr> <td fixwidth=5></td><td fixwidth=200 align=center><a action=\"bypass _bbsclan_clanhome;", string.valueof(cl.getid()), "\">", cl.getname(), "</a></td><td fixwidth=200 align=center>", cl.getleadername(), "</td><td fixwidth=100 align=center>", string.valueof(cl.getlevel()), "</td><td fixwidth=100 align=center>", string.valueof(cl.getmemberscount()), "</td><td fixwidth=5></td></tr><tr><td height=5></td></tr></table><img src=\"l2ui.squareblank\" width=\"610\" height=\"3\"><img src=\"l2ui.squaregray\" width=\"610\" height=\"1\">"); } } html.append("<img src=\"l2ui.squareblank\" width=\"610\" height=\"2\"><table cellpadding=0 cellspacing=2 border=0><tr>"); if (index == 1) { html.append("<td><button action=\"\" back=\"l2ui_ch3.prev1_down\" fore=\"l2ui_ch3.prev1\" width=16 height=16 ></td>"); } else { stringutil.append(html, "<td><button action=\"_bbsclan_clanlist;", string.valueof(index - 1), "\" back=\"l2ui_ch3.prev1_down\" fore=\"l2ui_ch3.prev1\" width=16 height=16 ></td>"); } i = 0; int nbp = clantable.getinstance().getclancount() / 8; if ((nbp * 8) != clantable.getinstance().getclancount()) { nbp++; } for (i = 1; i <= nbp; i++) { if (i == index) { stringutil.append(html, "<td> ", string.valueof(i), " </td>"); } else { stringutil.append(html, "<td><a action=\"bypass _bbsclan_clanlist;", string.valueof(i), "\"> ", string.valueof(i), " </a></td>"); } } if (index == nbp) { html.append("<td><button action=\"\" back=\"l2ui_ch3.next1_down\" fore=\"l2ui_ch3.next1\" width=16 height=16 ></td>"); } else { stringutil.append(html, "<td><button action=\"bypass _bbsclan_clanlist;", string.valueof(index + 1), "\" back=\"l2ui_ch3.next1_down\" fore=\"l2ui_ch3.next1\" width=16 height=16 ></td>"); } html.append("</tr></table><table border=0 cellspacing=0 cellpadding=0><tr><td width=610><img src=\"sek.cbui141\" width=\"610\" height=\"1\"></td></tr></table><table border=0><tr><td><combobox width=65 var=keyword list=\"name;ruler\"></td><td><edit var = \"search\" width=130 height=11 length=\"16\"></td>" + "<td><button value=\"&$420;\" action=\"write 5 -1 0 search keyword keyword\" back=\"l2ui_ch3.smallbutton2_down\" width=65 height=20 fore=\"l2ui_ch3.smallbutton2\"> </td> </tr></table><br><br></center></body></html>"); communityboardhandler.separateandsend(html.tostring(), activechar); }
RollingSoftware/L2J_HighFive_Hardcore
[ 0, 1, 0, 0 ]
23,375
public void sendErrorEmail(RequestCycle cycle, Exception ex, IRequestLogger logger) { try { String customer = Utils.getCustomer(); Url url = cycle.getRequest().getUrl(); Url clientUrl = cycle.getRequest().getClientUrl(); String exStr = ExceptionUtils.getStackTrace(ex); String fullUrl = cycle.getUrlRenderer().renderFullUrl(url); int currUserId = 0; RequestData currRd = logger.getCurrentRequest(); String currSessId = Session.get().getId(); SessionData sd = null; if(currSessId != null) { SessionData[] sessions = logger.getLiveSessions(); for(SessionData s : sessions) { if(s.getSessionId().equals(currSessId)) { sd = s; break; } } } String currReq = ((CustomRequestLogger)logger).createRequestData(currRd, sd); StringBuilder currSessStr = new StringBuilder(); if(sd != null) { currSessStr.append("id:").append(sd.getSessionId()).append('\n'); currSessStr.append("requestCount:").append(sd.getNumberOfRequests()).append('\n'); currSessStr.append("requestsTime:").append(sd.getTotalTimeTaken()).append('\n'); currSessStr.append("sessionSize:").append(Bytes.bytes(sd.getSessionSize())).append('\n'); currSessStr.append("sessionInfo:").append(sd.getSessionInfo()).append('\n'); currSessStr.append("startDate:").append(sd.getStartDate()).append('\n'); currSessStr.append("lastRequestTime:").append(sd.getLastActive()).append('\n'); currSessStr.append("numberOfRequests:").append(sd.getNumberOfRequests()).append('\n'); currSessStr.append("totalTimeTaken:").append(sd.getTotalTimeTaken()).append("\n\n\n"); } currSessStr.append("Requests: \n"); ((CustomRequestLogger)logger).getRequests(currSessStr); String template = "param1: %s \n url: %s \n client url: %s \n user: %s \n\n " + "curr req: %s \n\n\n curr session: %s \n\n\n stack trace: %s"; String body = String.format(template, customer, fullUrl, clientUrl.toString(), currUserId, currReq, currSessStr.toString(), exStr); String subject = customer + " error"; //TODO send email here } catch (Exception e) { //ignore } }
public void sendErrorEmail(RequestCycle cycle, Exception ex, IRequestLogger logger) { try { String customer = Utils.getCustomer(); Url url = cycle.getRequest().getUrl(); Url clientUrl = cycle.getRequest().getClientUrl(); String exStr = ExceptionUtils.getStackTrace(ex); String fullUrl = cycle.getUrlRenderer().renderFullUrl(url); int currUserId = 0; RequestData currRd = logger.getCurrentRequest(); String currSessId = Session.get().getId(); SessionData sd = null; if(currSessId != null) { SessionData[] sessions = logger.getLiveSessions(); for(SessionData s : sessions) { if(s.getSessionId().equals(currSessId)) { sd = s; break; } } } String currReq = ((CustomRequestLogger)logger).createRequestData(currRd, sd); StringBuilder currSessStr = new StringBuilder(); if(sd != null) { currSessStr.append("id:").append(sd.getSessionId()).append('\n'); currSessStr.append("requestCount:").append(sd.getNumberOfRequests()).append('\n'); currSessStr.append("requestsTime:").append(sd.getTotalTimeTaken()).append('\n'); currSessStr.append("sessionSize:").append(Bytes.bytes(sd.getSessionSize())).append('\n'); currSessStr.append("sessionInfo:").append(sd.getSessionInfo()).append('\n'); currSessStr.append("startDate:").append(sd.getStartDate()).append('\n'); currSessStr.append("lastRequestTime:").append(sd.getLastActive()).append('\n'); currSessStr.append("numberOfRequests:").append(sd.getNumberOfRequests()).append('\n'); currSessStr.append("totalTimeTaken:").append(sd.getTotalTimeTaken()).append("\n\n\n"); } currSessStr.append("Requests: \n"); ((CustomRequestLogger)logger).getRequests(currSessStr); String template = "param1: %s \n url: %s \n client url: %s \n user: %s \n\n " + "curr req: %s \n\n\n curr session: %s \n\n\n stack trace: %s"; String body = String.format(template, customer, fullUrl, clientUrl.toString(), currUserId, currReq, currSessStr.toString(), exStr); String subject = customer + " error"; } catch (Exception e) { } }
public void senderroremail(requestcycle cycle, exception ex, irequestlogger logger) { try { string customer = utils.getcustomer(); url url = cycle.getrequest().geturl(); url clienturl = cycle.getrequest().getclienturl(); string exstr = exceptionutils.getstacktrace(ex); string fullurl = cycle.geturlrenderer().renderfullurl(url); int curruserid = 0; requestdata currrd = logger.getcurrentrequest(); string currsessid = session.get().getid(); sessiondata sd = null; if(currsessid != null) { sessiondata[] sessions = logger.getlivesessions(); for(sessiondata s : sessions) { if(s.getsessionid().equals(currsessid)) { sd = s; break; } } } string currreq = ((customrequestlogger)logger).createrequestdata(currrd, sd); stringbuilder currsessstr = new stringbuilder(); if(sd != null) { currsessstr.append("id:").append(sd.getsessionid()).append('\n'); currsessstr.append("requestcount:").append(sd.getnumberofrequests()).append('\n'); currsessstr.append("requeststime:").append(sd.gettotaltimetaken()).append('\n'); currsessstr.append("sessionsize:").append(bytes.bytes(sd.getsessionsize())).append('\n'); currsessstr.append("sessioninfo:").append(sd.getsessioninfo()).append('\n'); currsessstr.append("startdate:").append(sd.getstartdate()).append('\n'); currsessstr.append("lastrequesttime:").append(sd.getlastactive()).append('\n'); currsessstr.append("numberofrequests:").append(sd.getnumberofrequests()).append('\n'); currsessstr.append("totaltimetaken:").append(sd.gettotaltimetaken()).append("\n\n\n"); } currsessstr.append("requests: \n"); ((customrequestlogger)logger).getrequests(currsessstr); string template = "param1: %s \n url: %s \n client url: %s \n user: %s \n\n " + "curr req: %s \n\n\n curr session: %s \n\n\n stack trace: %s"; string body = string.format(template, customer, fullurl, clienturl.tostring(), curruserid, currreq, currsessstr.tostring(), exstr); string subject = customer + " error"; } catch (exception e) { } }
RomanSery/codesnippets
[ 0, 1, 0, 0 ]
23,575
public static void main(String[] args) { // TODO Auto-generated method stub //Assuming stock of each sport is 2 Sports sp1=new IndoorSports(); System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock()); sp1=new Billiards(sp1); System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock()); sp1=new Carrom(sp1); System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock()); sp1=new Badminton(sp1); System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock()); Sports sp2=new OutdoorSports(); System.out.println("\nTotal Outdoor Sports Stock:"+sp2.getCurrentStock()); sp2=new Trekking(sp2); System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock()); sp2=new Cricket(sp2); System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock()); sp2=new HighJump(sp2); System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock()); sp2=new LongJump(sp2); System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock()); }
public static void main(String[] args) { Sports sp1=new IndoorSports(); System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock()); sp1=new Billiards(sp1); System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock()); sp1=new Carrom(sp1); System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock()); sp1=new Badminton(sp1); System.out.println("Total Indoor Sports Stock:"+sp1.getCurrentStock()); Sports sp2=new OutdoorSports(); System.out.println("\nTotal Outdoor Sports Stock:"+sp2.getCurrentStock()); sp2=new Trekking(sp2); System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock()); sp2=new Cricket(sp2); System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock()); sp2=new HighJump(sp2); System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock()); sp2=new LongJump(sp2); System.out.println("Total Outdoor Sports Stock:"+sp2.getCurrentStock()); }
public static void main(string[] args) { sports sp1=new indoorsports(); system.out.println("total indoor sports stock:"+sp1.getcurrentstock()); sp1=new billiards(sp1); system.out.println("total indoor sports stock:"+sp1.getcurrentstock()); sp1=new carrom(sp1); system.out.println("total indoor sports stock:"+sp1.getcurrentstock()); sp1=new badminton(sp1); system.out.println("total indoor sports stock:"+sp1.getcurrentstock()); sports sp2=new outdoorsports(); system.out.println("\ntotal outdoor sports stock:"+sp2.getcurrentstock()); sp2=new trekking(sp2); system.out.println("total outdoor sports stock:"+sp2.getcurrentstock()); sp2=new cricket(sp2); system.out.println("total outdoor sports stock:"+sp2.getcurrentstock()); sp2=new highjump(sp2); system.out.println("total outdoor sports stock:"+sp2.getcurrentstock()); sp2=new longjump(sp2); system.out.println("total outdoor sports stock:"+sp2.getcurrentstock()); }
Saba-d-coder/6thSemIse
[ 1, 0, 0, 0 ]
15,413
public void put(String name, Scriptable start, Object value) { try { ObjectLocation variable = this.extractFieldVariable(name); if (value instanceof NativeArray) { // FIXME this breaks referential equality, but maybe it's OK variable.set(this.sequenceFromArray((NativeArray)value, start)); return; } //System.err.println("variable " + variable + " new value " + value + " type " + variable.getClass().getName()); if (variable instanceof FloatLocation) { // FIXME FIXME super ad-hoc value = Context.jsToJava(value, Float.class); } else if (value instanceof ObjectLocation) { // here's a place where two locations could be bound to each other? value = ((ObjectLocation)value).get(); } else if (value instanceof Wrapper) { // FIXME is there a better way??? value = ((Wrapper)value).unwrap(); if (value instanceof ObjectLocation) { value = ((ObjectLocation)value).get(); } } variable.set(value); return; } catch (Exception e) { e.printStackTrace(System.err); } }
public void put(String name, Scriptable start, Object value) { try { ObjectLocation variable = this.extractFieldVariable(name); if (value instanceof NativeArray) { variable.set(this.sequenceFromArray((NativeArray)value, start)); return; } if (variable instanceof FloatLocation) { value = Context.jsToJava(value, Float.class); } else if (value instanceof ObjectLocation) { value = ((ObjectLocation)value).get(); } else if (value instanceof Wrapper) { value = ((Wrapper)value).unwrap(); if (value instanceof ObjectLocation) { value = ((ObjectLocation)value).get(); } } variable.set(value); return; } catch (Exception e) { e.printStackTrace(System.err); } }
public void put(string name, scriptable start, object value) { try { objectlocation variable = this.extractfieldvariable(name); if (value instanceof nativearray) { variable.set(this.sequencefromarray((nativearray)value, start)); return; } if (variable instanceof floatlocation) { value = context.jstojava(value, float.class); } else if (value instanceof objectlocation) { value = ((objectlocation)value).get(); } else if (value instanceof wrapper) { value = ((wrapper)value).unwrap(); if (value instanceof objectlocation) { value = ((objectlocation)value).get(); } } variable.set(value); return; } catch (exception e) { e.printstacktrace(system.err); } }
LivelyKernel/sunlabs-kernel
[ 1, 0, 1, 0 ]
15,430
private static Method getMethod() { return method.get(0); }
private static Method getMethod() { return method.get(0); }
private static method getmethod() { return method.get(0); }
Modify24x7/ApkStringDecryptor
[ 1, 0, 0, 0 ]
15,621
private boolean initCipher() { try { //Obtain a cipher instance and configure it with the properties required for fingerprint authentication// if(this.cipher == null) { this.cipher = Cipher.getInstance( KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7); } } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { e.printStackTrace(); return false; } try { if(this.secretKey == null) { this.secretKey = generateKey(); } if(this.keyStore != null) { if(!this.keystoreInitialized) { this.keyStore.load(null); this.keystoreInitialized = true; } } // key = (SecretKey) this.keyStore.getKey(keyName, null); todo needed? if(this.cipher != null) { if (!this.cipherInitialized) { this.cipher.init(Cipher.ENCRYPT_MODE, this.secretKey); this.cipherInitialized = true; } } //Return true if the cipher has been initialized successfully// return true; } catch (KeyPermanentlyInvalidatedException e) { //Return false if cipher initialization failed// return false; } catch (CertificateException //KeyStoreException | IOException //UnrecoverableKeyException | NullPointerException | NoSuchAlgorithmException | InvalidKeyException e) { e.printStackTrace(); return false; } }
private boolean initCipher() { try { if(this.cipher == null) { this.cipher = Cipher.getInstance( KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7); } } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { e.printStackTrace(); return false; } try { if(this.secretKey == null) { this.secretKey = generateKey(); } if(this.keyStore != null) { if(!this.keystoreInitialized) { this.keyStore.load(null); this.keystoreInitialized = true; } } if(this.cipher != null) { if (!this.cipherInitialized) { this.cipher.init(Cipher.ENCRYPT_MODE, this.secretKey); this.cipherInitialized = true; } } return true; } catch (KeyPermanentlyInvalidatedException e) { return false; } catch (CertificateException | IOException | NullPointerException | NoSuchAlgorithmException | InvalidKeyException e) { e.printStackTrace(); return false; } }
private boolean initcipher() { try { if(this.cipher == null) { this.cipher = cipher.getinstance( keyproperties.key_algorithm_aes + "/" + keyproperties.block_mode_cbc + "/" + keyproperties.encryption_padding_pkcs7); } } catch (nosuchalgorithmexception | nosuchpaddingexception e) { e.printstacktrace(); return false; } try { if(this.secretkey == null) { this.secretkey = generatekey(); } if(this.keystore != null) { if(!this.keystoreinitialized) { this.keystore.load(null); this.keystoreinitialized = true; } } if(this.cipher != null) { if (!this.cipherinitialized) { this.cipher.init(cipher.encrypt_mode, this.secretkey); this.cipherinitialized = true; } } return true; } catch (keypermanentlyinvalidatedexception e) { return false; } catch (certificateexception | ioexception | nullpointerexception | nosuchalgorithmexception | invalidkeyexception e) { e.printstacktrace(); return false; } }
PGMacDesign/PGMacTips
[ 1, 0, 0, 0 ]
23,837
private void writeRunnerProject() throws IOException, XmlException, ParseException { // TODO revise whole method // TODO now using a newer JAPA (suuports java 8), -> maybe ANTLR supports better PathUtils.createDir(getRunnerProjectSettings().getBaseDir().toPath()); // copy snippets PathUtils.copy(getSnippetProject().getSourceDir(), getRunnerProjectSettings().getSnippetSourceDirectory().toPath()); // create INFO file writeInfoFile(); // remove SETTE annotations and imports from file Collection<File> filesWritten = Files .walk(getRunnerProjectSettings().getSnippetSourceDirectory().toPath()) .filter(Files::isRegularFile).map(Path::toFile).sorted() .collect(Collectors.toList()); for (File file : filesWritten) { // parse source with JavaParser log.debug("Parsing with JavaParser: {}", file); CompilationUnit compilationUnit = JavaParser.parse(file); log.debug("Parsed with JavaParser: {}", file); // extract type List<TypeDeclaration> types = compilationUnit.getTypes(); if (types.size() != 1) { // NOTE better exception type throw new RuntimeException( "Java source files containing more that one types are not supported"); } TypeDeclaration type = types.get(0); // skip file if Java version is not supported by the tool (@SetteSnippetContainer) // NOTE it can be also done with snippet containers... (and also done in CATG // generator!) List<AnnotationExpr> classAnnotations = type.getAnnotations(); JavaVersion reqJavaVer = getRequiredJavaVersion(classAnnotations); if (reqJavaVer != null && !getTool().supportsJavaVersion(reqJavaVer)) { System.err.println( "Skipping file: " + file + " (required Java version: " + reqJavaVer + ")"); PathUtils.delete(file.toPath()); } else { // remove SETTE annotations from the class Predicate<AnnotationExpr> isSetteAnnotation = (a -> a.getName().getName() .startsWith("Sette")); classAnnotations.removeIf(isSetteAnnotation); // remove SETTE annotations from the members for (BodyDeclaration member : type.getMembers()) { member.getAnnotations().removeIf(isSetteAnnotation); } // TODO enhance List<String> toRemovePrefixes = new ArrayList<>(); toRemovePrefixes.add("hu.bme.mit.sette.snippets.inputs"); toRemovePrefixes.add("hu.bme.mit.sette.common"); // remove SETTE imports compilationUnit.getImports().removeIf(importDeclaration -> { String impDecl = importDeclaration.getName().toString(); for (String prefix : toRemovePrefixes) { if (impDecl.startsWith(prefix)) { return true; } } return false; }); // save edited source code String source = compilationUnit.toString(); if (type instanceof EnumDeclaration) { // FIXME remove after javaparser bug is fixed source = source.replaceFirst(type.getName() + "\\s+implements\\s*\\{", type.getName() + " {"); } PathUtils.write(file.toPath(), source.getBytes()); } } // copy libraries if (getSnippetProject().getLibDir().toFile().exists()) { PathUtils.copy(getSnippetProject().getLibDir(), getRunnerProjectSettings().getSnippetLibraryDirectory().toPath()); } // create project this.eclipseProject.save(getRunnerProjectSettings().getBaseDir().toPath()); }
private void writeRunnerProject() throws IOException, XmlException, ParseException { PathUtils.createDir(getRunnerProjectSettings().getBaseDir().toPath()); PathUtils.copy(getSnippetProject().getSourceDir(), getRunnerProjectSettings().getSnippetSourceDirectory().toPath()); writeInfoFile(); Collection<File> filesWritten = Files .walk(getRunnerProjectSettings().getSnippetSourceDirectory().toPath()) .filter(Files::isRegularFile).map(Path::toFile).sorted() .collect(Collectors.toList()); for (File file : filesWritten) { log.debug("Parsing with JavaParser: {}", file); CompilationUnit compilationUnit = JavaParser.parse(file); log.debug("Parsed with JavaParser: {}", file); List<TypeDeclaration> types = compilationUnit.getTypes(); if (types.size() != 1) { throw new RuntimeException( "Java source files containing more that one types are not supported"); } TypeDeclaration type = types.get(0); List<AnnotationExpr> classAnnotations = type.getAnnotations(); JavaVersion reqJavaVer = getRequiredJavaVersion(classAnnotations); if (reqJavaVer != null && !getTool().supportsJavaVersion(reqJavaVer)) { System.err.println( "Skipping file: " + file + " (required Java version: " + reqJavaVer + ")"); PathUtils.delete(file.toPath()); } else { Predicate<AnnotationExpr> isSetteAnnotation = (a -> a.getName().getName() .startsWith("Sette")); classAnnotations.removeIf(isSetteAnnotation); for (BodyDeclaration member : type.getMembers()) { member.getAnnotations().removeIf(isSetteAnnotation); } List<String> toRemovePrefixes = new ArrayList<>(); toRemovePrefixes.add("hu.bme.mit.sette.snippets.inputs"); toRemovePrefixes.add("hu.bme.mit.sette.common"); compilationUnit.getImports().removeIf(importDeclaration -> { String impDecl = importDeclaration.getName().toString(); for (String prefix : toRemovePrefixes) { if (impDecl.startsWith(prefix)) { return true; } } return false; }); String source = compilationUnit.toString(); if (type instanceof EnumDeclaration) { source = source.replaceFirst(type.getName() + "\\s+implements\\s*\\{", type.getName() + " {"); } PathUtils.write(file.toPath(), source.getBytes()); } } if (getSnippetProject().getLibDir().toFile().exists()) { PathUtils.copy(getSnippetProject().getLibDir(), getRunnerProjectSettings().getSnippetLibraryDirectory().toPath()); } this.eclipseProject.save(getRunnerProjectSettings().getBaseDir().toPath()); }
private void writerunnerproject() throws ioexception, xmlexception, parseexception { pathutils.createdir(getrunnerprojectsettings().getbasedir().topath()); pathutils.copy(getsnippetproject().getsourcedir(), getrunnerprojectsettings().getsnippetsourcedirectory().topath()); writeinfofile(); collection<file> fileswritten = files .walk(getrunnerprojectsettings().getsnippetsourcedirectory().topath()) .filter(files::isregularfile).map(path::tofile).sorted() .collect(collectors.tolist()); for (file file : fileswritten) { log.debug("parsing with javaparser: {}", file); compilationunit compilationunit = javaparser.parse(file); log.debug("parsed with javaparser: {}", file); list<typedeclaration> types = compilationunit.gettypes(); if (types.size() != 1) { throw new runtimeexception( "java source files containing more that one types are not supported"); } typedeclaration type = types.get(0); list<annotationexpr> classannotations = type.getannotations(); javaversion reqjavaver = getrequiredjavaversion(classannotations); if (reqjavaver != null && !gettool().supportsjavaversion(reqjavaver)) { system.err.println( "skipping file: " + file + " (required java version: " + reqjavaver + ")"); pathutils.delete(file.topath()); } else { predicate<annotationexpr> issetteannotation = (a -> a.getname().getname() .startswith("sette")); classannotations.removeif(issetteannotation); for (bodydeclaration member : type.getmembers()) { member.getannotations().removeif(issetteannotation); } list<string> toremoveprefixes = new arraylist<>(); toremoveprefixes.add("hu.bme.mit.sette.snippets.inputs"); toremoveprefixes.add("hu.bme.mit.sette.common"); compilationunit.getimports().removeif(importdeclaration -> { string impdecl = importdeclaration.getname().tostring(); for (string prefix : toremoveprefixes) { if (impdecl.startswith(prefix)) { return true; } } return false; }); string source = compilationunit.tostring(); if (type instanceof enumdeclaration) { source = source.replacefirst(type.getname() + "\\s+implements\\s*\\{", type.getname() + " {"); } pathutils.write(file.topath(), source.getbytes()); } } if (getsnippetproject().getlibdir().tofile().exists()) { pathutils.copy(getsnippetproject().getlibdir(), getrunnerprojectsettings().getsnippetlibrarydirectory().topath()); } this.eclipseproject.save(getrunnerprojectsettings().getbasedir().topath()); }
SETTE-Testing/sette-tool
[ 1, 0, 1, 0 ]
15,691
public boolean isSubjectEmpty() { return TextUtils.getTrimmedLength(mSubject.getText()) == 0; }
public boolean isSubjectEmpty() { return TextUtils.getTrimmedLength(mSubject.getText()) == 0; }
public boolean issubjectempty() { return textutils.gettrimmedlength(msubject.gettext()) == 0; }
Keneral/apackages
[ 1, 0, 0, 0 ]
23,891
public void buildOutAssignment(StringBuilder sb, PLSQLargument outArg, PLSQLStoredProcedureCall call) { String sql2PlName = call.getPl2SQLName(this); if (sql2PlName == null) { // TODO: Error. throw new NullPointerException("no Pl2SQL conversion routine for " + typeName); } String target = databaseTypeHelper.buildTarget(outArg); sb.append(" :"); sb.append(outArg.outIndex); sb.append(" := "); sb.append(sql2PlName); sb.append("("); sb.append(target); sb.append(");"); sb.append(NL); }
public void buildOutAssignment(StringBuilder sb, PLSQLargument outArg, PLSQLStoredProcedureCall call) { String sql2PlName = call.getPl2SQLName(this); if (sql2PlName == null) { throw new NullPointerException("no Pl2SQL conversion routine for " + typeName); } String target = databaseTypeHelper.buildTarget(outArg); sb.append(" :"); sb.append(outArg.outIndex); sb.append(" := "); sb.append(sql2PlName); sb.append("("); sb.append(target); sb.append(");"); sb.append(NL); }
public void buildoutassignment(stringbuilder sb, plsqlargument outarg, plsqlstoredprocedurecall call) { string sql2plname = call.getpl2sqlname(this); if (sql2plname == null) { throw new nullpointerexception("no pl2sql conversion routine for " + typename); } string target = databasetypehelper.buildtarget(outarg); sb.append(" :"); sb.append(outarg.outindex); sb.append(" := "); sb.append(sql2plname); sb.append("("); sb.append(target); sb.append(");"); sb.append(nl); }
Pandrex247/patched-src-eclipselink
[ 0, 0, 1, 0 ]
23,901
private void guestSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guestSearchActionPerformed // TODO add your handling code here: //Guestsearch guestsearch = new Guestsearch(jFrameInstance, email); //jFrameInstance.changePanelToSpecific(guestsearch); }
private void guestSearchActionPerformed(java.awt.event.ActionEvent evt) { }
private void guestsearchactionperformed(java.awt.event.actionevent evt) { }
Jed-g/property-booking-system
[ 0, 1, 0, 0 ]
32,148
@Override protected void setUp() throws Exception { super.setUp(); // TODO: This test will actually mess with contacts on your phone. // Ideally we would use a fake content provider to give us contact data... FakeFactory.registerWithoutFakeContext(getTestContext()); // add test contacts. addTestContact("John", "650-123-1233", "[email protected]", false); addTestContact("Joe", "(650)123-1233", "[email protected]", false); addTestContact("Jim", "650 123 1233", "[email protected]", false); addTestContact("Samantha", "650-123-1235", "[email protected]", true); addTestContact("Adrienne", "650-123-1236", "[email protected]", true); }
@Override protected void setUp() throws Exception { super.setUp(); FakeFactory.registerWithoutFakeContext(getTestContext()); addTestContact("John", "650-123-1233", "[email protected]", false); addTestContact("Joe", "(650)123-1233", "[email protected]", false); addTestContact("Jim", "650 123 1233", "[email protected]", false); addTestContact("Samantha", "650-123-1235", "[email protected]", true); addTestContact("Adrienne", "650-123-1236", "[email protected]", true); }
@override protected void setup() throws exception { super.setup(); fakefactory.registerwithoutfakecontext(gettestcontext()); addtestcontact("john", "650-123-1233", "[email protected]", false); addtestcontact("joe", "(650)123-1233", "[email protected]", false); addtestcontact("jim", "650 123 1233", "[email protected]", false); addtestcontact("samantha", "650-123-1235", "[email protected]", true); addtestcontact("adrienne", "650-123-1236", "[email protected]", true); }
Keneral/apackages
[ 0, 0, 0, 1 ]
15,785
@Override public ItemStack transferStackInSlot(EntityPlayer player, int slot) { // TODO: Try to come up with a generic way of implementing this return null; }
@Override public ItemStack transferStackInSlot(EntityPlayer player, int slot) { return null; }
@override public itemstack transferstackinslot(entityplayer player, int slot) { return null; }
PC-Logix/GregsLighting-Reloaded
[ 1, 0, 0, 0 ]
7,631
public JSONArray getProjectRevisions(ProjectEndpoint endpoint) { //TODO need to add paging somewhere (page, items) to handle long commit histories String json = restInterface.get(TeamworkCloudEndpoints.GET_PROJECT_REVISIONS.buildUrl(endpoint.getHost(), endpoint.getCollection(), endpoint.getProject(), "true"), endpoint.getToken(), String.class); return new JSONArray(json); }
public JSONArray getProjectRevisions(ProjectEndpoint endpoint) { String json = restInterface.get(TeamworkCloudEndpoints.GET_PROJECT_REVISIONS.buildUrl(endpoint.getHost(), endpoint.getCollection(), endpoint.getProject(), "true"), endpoint.getToken(), String.class); return new JSONArray(json); }
public jsonarray getprojectrevisions(projectendpoint endpoint) { string json = restinterface.get(teamworkcloudendpoints.get_project_revisions.buildurl(endpoint.gethost(), endpoint.getcollection(), endpoint.getproject(), "true"), endpoint.gettoken(), string.class); return new jsonarray(json); }
Open-MBEE/sync-service
[ 0, 1, 0, 0 ]
24,107
public void ClearScreenTest(){ press(R.id.btn_1); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.binary_number_2); press(R.id.btn_1); press(R.id.btn_0); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_divide); press(R.id.btn_all_clear); checkResult(""); checkBinary1(""); checkBinary2(""); }
public void ClearScreenTest(){ press(R.id.btn_1); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.binary_number_2); press(R.id.btn_1); press(R.id.btn_0); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_divide); press(R.id.btn_all_clear); checkResult(""); checkBinary1(""); checkBinary2(""); }
public void clearscreentest(){ press(r.id.btn_1); press(r.id.btn_0); press(r.id.btn_0); press(r.id.btn_0); press(r.id.btn_0); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.binary_number_2); press(r.id.btn_1); press(r.id.btn_0); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_divide); press(r.id.btn_all_clear); checkresult(""); checkbinary1(""); checkbinary2(""); }
ModestosV/Simple-Calculator
[ 0, 0, 0, 1 ]
24,108
public void DeleteTest(){ press(R.id.btn_1); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_del); checkBinary1("1000011111"); press(R.id.binary_number_2); press(R.id.btn_1); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_del); checkBinary2("10"); }
public void DeleteTest(){ press(R.id.btn_1); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_1); press(R.id.btn_del); checkBinary1("1000011111"); press(R.id.binary_number_2); press(R.id.btn_1); press(R.id.btn_0); press(R.id.btn_0); press(R.id.btn_del); checkBinary2("10"); }
public void deletetest(){ press(r.id.btn_1); press(r.id.btn_0); press(r.id.btn_0); press(r.id.btn_0); press(r.id.btn_0); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_1); press(r.id.btn_del); checkbinary1("1000011111"); press(r.id.binary_number_2); press(r.id.btn_1); press(r.id.btn_0); press(r.id.btn_0); press(r.id.btn_del); checkbinary2("10"); }
ModestosV/Simple-Calculator
[ 0, 0, 0, 1 ]
15,927
public int ExecuteGFXCommand(int cmd, int len, byte[] cmddata, int[] hasret) { len -= 4; // for the 4 byte header hasret[0] = 0; // Nothing to return by default // System.out.println("GFXCMD=" + cmd); // make sure the frame is still valid or we could crash on fullscreen mode switches if((cmd != GFXCMD_INIT) && (cmd != GFXCMD_DEINIT)) { if((f != null) ? (!f.isDisplayable() || !f.isValid() || !f.isShowing()) : true) { // System.out.println("GFXCMD while frame not displayable"); // spin until the frame is valid and displayable, if we don't we'll lose parts of the UI or crash while((f != null) ? (!f.isDisplayable() || !f.isValid() || !f.isShowing()) : true) { try { Thread.sleep(10); } catch(InterruptedException ex) {} } } } if (c != null) { switch(cmd) { case GFXCMD_INIT: case GFXCMD_DEINIT: case GFXCMD_STARTFRAME: case GFXCMD_FLIPBUFFER: c.setCursor(null); break; case GFXCMD_DRAWRECT: case GFXCMD_FILLRECT: case GFXCMD_CLEARRECT: case GFXCMD_DRAWOVAL: case GFXCMD_FILLOVAL: case GFXCMD_DRAWROUNDRECT: case GFXCMD_FILLROUNDRECT: case GFXCMD_DRAWTEXT: case GFXCMD_DRAWTEXTURED: case GFXCMD_DRAWLINE: case GFXCMD_LOADIMAGE: case GFXCMD_LOADIMAGETARGETED: case GFXCMD_UNLOADIMAGE: case GFXCMD_LOADFONT: case GFXCMD_UNLOADFONT: case GFXCMD_SETTARGETSURFACE: case GFXCMD_CREATESURFACE: break; case GFXCMD_PREPIMAGE: case GFXCMD_LOADIMAGELINE: case GFXCMD_LOADIMAGECOMPRESSED: case GFXCMD_XFMIMAGE: case GFXCMD_LOADCACHEDIMAGE: case GFXCMD_PREPIMAGETARGETED: if (!cursorHidden) c.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR)); break; } } switch(cmd) { case GFXCMD_INIT: hasret[0] = 1; // System.out.println("INIT"); // start up native renderer init0(); int windowTitleStyle = 0; try { windowTitleStyle = Integer.parseInt(MiniClient.myProperties.getProperty("window_title_style", "0")); } catch (NumberFormatException e){} if (!"true".equals(MiniClient.myProperties.getProperty("enable_custom_title_bar", MiniClient.MAC_OS_X ? "false" : "true"))) windowTitleStyle = 10; // platform default f = new MiniClientWindow(myConn.getWindowTitle(), windowTitleStyle); java.awt.LayoutManager layer = new java.awt.LayoutManager() { public void addLayoutComponent(String name, java.awt.Component comp) {} public java.awt.Dimension minimumLayoutSize(java.awt.Container parent) { return preferredLayoutSize(parent); } public java.awt.Dimension preferredLayoutSize(java.awt.Container parent) { return parent.getPreferredSize(); } public void removeLayoutComponent(java.awt.Component comp) {} public void layoutContainer(java.awt.Container parent) { c.setBounds(parent.getInsets().left, parent.getInsets().top, parent.getWidth() - parent.getInsets().left - parent.getInsets().right, parent.getHeight() - parent.getInsets().top - parent.getInsets().bottom); //System.out.println("LAYOUT frame bounds=" + f.getBounds() + " videoBounds=" + videoBounds + " parentBounds=" + parent.getBounds()); } }; f.getContentPane().setLayout(layer); try { bgImage = java.awt.Toolkit.getDefaultToolkit().createImage(getClass().getClassLoader().getResource("images/Background.jpg")); ensureImageIsLoaded(bgImage); logoImage = java.awt.Toolkit.getDefaultToolkit().createImage(getClass().getClassLoader().getResource("images/SageLogo256.png")); ensureImageIsLoaded(logoImage); } catch (Exception e) { System.out.println("ERROR:" + e); e.printStackTrace(); } f.setFocusTraversalKeysEnabled(false); /* if not connecting to localhost: - draw background to bounds (scaled) - draw logo to {{2% from left, 15% from top}{20% view width, 7% view height}}, no clipping, alpha = 0.85, adjust size to keep aspect ratio - load Arial 32 bold - draw the following text, double spaced using Arial 32 bold, white with black shadow (offset by (+2,+2)) "SageTV Placeshifter is connecting to" "the server: "+myConn.getServerName() "Please Wait..." text is centered in the view on the middle line, use font metrics to determine proper location g.setFont(pleaseWaitFont); g.setColor(java.awt.Color.black); y += 2; g.drawString(str1, 2 + (getWidth()/2) - (fm.stringWidth(str1)/2), y + fm.getAscent()); y += fm.getHeight(); g.drawString(str2, 2 + (getWidth()/2) - (fm.stringWidth(str2)/2), y + fm.getAscent()); y += 2*fm.getHeight(); g.drawString(str3, 2 + (getWidth()/2) - (fm.stringWidth(str3)/2), y + fm.getAscent()); g.setColor(java.awt.Color.white); y = (getHeight() / 2) - fh/2; g.drawString(str1, (getWidth()/2) - (fm.stringWidth(str1)/2), y + fm.getAscent()); y += fm.getHeight(); g.drawString(str2, (getWidth()/2) - (fm.stringWidth(str2)/2), y + fm.getAscent()); y += 2*fm.getHeight(); g.drawString(str3, (getWidth()/2) - (fm.stringWidth(str3)/2), y + fm.getAscent()); */ java.awt.Dimension panelSize = f.getContentPane().getSize(); c = new QuartzRendererView(); c.setSize(panelSize); c.setFocusTraversalKeysEnabled(false); f.getContentPane().add(c); try { java.awt.Image frameIcon = java.awt.Toolkit.getDefaultToolkit().createImage(getClass().getClassLoader().getResource("images/tvicon.gif")); ensureImageIsLoaded(frameIcon); f.setIconImage(frameIcon); } catch (Exception e) { System.out.println("ERROR:" + e); e.printStackTrace(); } f.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { if (!f.isFullScreen() || System.getProperty("os.name").toLowerCase().indexOf("windows") != -1) { MiniClient.myProperties.setProperty("main_window_width", Integer.toString(f.getWidth())); MiniClient.myProperties.setProperty("main_window_height", Integer.toString(f.getHeight())); MiniClient.myProperties.setProperty("main_window_x", Integer.toString(f.getX())); MiniClient.myProperties.setProperty("main_window_y", Integer.toString(f.getY())); } myConn.close(); /* try { if (myConn.getMediaCmd().getPlaya() != null) { myConn.getMediaCmd().getPlaya().stop(); myConn.getMediaCmd().getPlaya().free(); } }catch (Exception e){} System.exit(0);*/ close(); // f.dispose(); } }); c.addComponentListener(new java.awt.event.ComponentAdapter() { public void componentResized(java.awt.event.ComponentEvent evt) { myConn.postResizeEvent(new java.awt.Dimension(c.getWidth(), c.getHeight())); } }); f.addKeyListener(this); c.addKeyListener(this); //f.addMouseListener(this); f.addMouseWheelListener(this); c.addMouseListener(this); if (ENABLE_MOUSE_MOTION_EVENTS) { //f.addMouseMotionListener(this); c.addMouseMotionListener(this); } int frameX = 100; int frameY = 100; int frameW = 720; int frameH = 480; try { frameW = Integer.parseInt(MiniClient.myProperties.getProperty("main_window_width", "720")); frameH = Integer.parseInt(MiniClient.myProperties.getProperty("main_window_height", "480")); frameX = Integer.parseInt(MiniClient.myProperties.getProperty("main_window_x", "100")); frameY = Integer.parseInt(MiniClient.myProperties.getProperty("main_window_y", "100")); } catch (NumberFormatException e){} java.awt.Point newPos = new java.awt.Point(frameX, frameY); boolean foundScreen = sage.UIUtils.isPointOnAScreen(newPos); if (!foundScreen) { newPos.x = 150; newPos.y = 150; } f.setVisible(true); f.setSize(1,1); f.setSize(Math.max(frameW, 320), Math.max(frameH, 240)); f.setLocation(newPos); if (MiniClient.fsStartup) f.setFullScreen(true); MiniClient.hideSplash(); // f.setVisible(true); return 1; case GFXCMD_DEINIT: // System.out.println("DEINIT"); close(); break; case GFXCMD_DRAWRECT: if(len==36) { float x, y, width, height; int thickness, argbTL, argbTR, argbBR, argbBL; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); thickness=readInt(16, cmddata); argbTL=readInt(20, cmddata); argbTR=readInt(24, cmddata); argbBR=readInt(28, cmddata); argbBL=readInt(32, cmddata); // System.out.println("DRAWRECT: dest=("+x+","+y+" "+width+"x"+height+") thickness="+thickness+" argbTL="+Integer.toHexString(argbTL)+" argbTR="+Integer.toHexString(argbTR)+" argbBL="+Integer.toHexString(argbBL)+" argbBR="+Integer.toHexString(argbBR)); // FIXME: no gradients on framed rects yet... drawRect0(new java.awt.geom.Rectangle2D.Float(x, y, width, height), null, 0, new java.awt.Color(argbTL, true), thickness, null, 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } else { System.out.println("Invalid len for GFXCMD_DRAWRECT : " + len); } break; case GFXCMD_FILLRECT: // x, y, width, height, argbTL, argbTR, argbBR, argbBL if(len==32) { float x, y, width, height; int argbTL, argbTR, argbBR, argbBL; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); argbTL=readInt(16, cmddata); argbTR=readInt(20, cmddata); argbBR=readInt(24, cmddata); argbBL=readInt(28, cmddata); // System.out.println("FILLRECT: dest=("+x+","+y+" "+width+"x"+height+") argbTL="+Integer.toHexString(argbTL)+" argbTR="+Integer.toHexString(argbTR)+" argbBL="+Integer.toHexString(argbBL)+" argbBR="+Integer.toHexString(argbBR)); java.awt.GradientPaint gp = getGradient(x, y, width, height, argbTL, argbTR, argbBL, argbBR); java.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height); if(gp != null) { drawRect0(bounds, null, 0, null, 0, gp.getColor1(), (float)gp.getPoint1().getX(), (float)gp.getPoint1().getY(), gp.getColor2(), (float)gp.getPoint2().getX(), (float)gp.getPoint2().getY(), //(float)((argbTL>>24)&0xff)/255.0f); 1.0f); // alpha already supplied } else { drawRect0(bounds, null, 0, null, 0, new java.awt.Color(argbTL, true), 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } } else { System.out.println("Invalid len for GFXCMD_FILLRECT : " + len); } break; case GFXCMD_CLEARRECT: // x, y, width, height, argbTL, argbTR, argbBR, argbBL if(len==32) { int x, y, width, height, argbTL, argbTR, argbBR, argbBL; x=readInt(0, cmddata); y=readInt(4, cmddata); width=readInt(8, cmddata); height=readInt(12, cmddata); argbTL=readInt(16, cmddata); argbTR=readInt(20, cmddata); argbBR=readInt(24, cmddata); argbBL=readInt(28, cmddata); // System.out.println("CLEARRECT: dest=("+x+","+y+" "+width+"x"+height+") argbTL="+Integer.toHexString(argbTL)+" argbTR="+Integer.toHexString(argbTR)+" argbBL="+Integer.toHexString(argbBL)+" argbBR="+Integer.toHexString(argbBR)); java.awt.geom.Rectangle2D.Float destRect = new java.awt.geom.Rectangle2D.Float(x, y, width, height); clearRect0(destRect); } else { System.out.println("Invalid len for GFXCMD_CLEARRECT : " + len); } break; case GFXCMD_DRAWOVAL: // x, y, width, height, thickness, argbTL, argbTR, argbBR, argbBL, // clipX, clipY, clipW, clipH if(len==52) { float x, y, width, height, clipX, clipY, clipW, clipH; int thickness, argbTL, argbTR, argbBR, argbBL; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); thickness=readInt(16, cmddata); argbTL=readInt(20, cmddata); argbTR=readInt(24, cmddata); argbBR=readInt(28, cmddata); argbBL=readInt(32, cmddata); clipX=(float)readInt(36, cmddata); clipY=(float)readInt(40, cmddata); clipW=(float)readInt(44, cmddata); clipH=(float)readInt(48, cmddata); // System.out.println("DRAWOVAL: dest=("+x+","+y+" "+width+"x"+height+") clip=("+clipX+","+clipY+" "+clipW+"x"+clipH+") thickness="+thickness+" argbTL="+Integer.toHexString(argbTL)+" argbTR="+Integer.toHexString(argbTR)+" argbBL="+Integer.toHexString(argbBL)+" argbBR="+Integer.toHexString(argbBR)); // FIXME: no gradient for framed ovals java.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height); java.awt.geom.Rectangle2D.Float clipRect = new java.awt.geom.Rectangle2D.Float(clipX, clipY, clipW, clipH); drawOval0(bounds, clipRect, new java.awt.Color(argbTL, true), thickness, null, 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } else { System.out.println("Invalid len for GFXCMD_DRAWOVAL : " + len); } break; case GFXCMD_FILLOVAL: // x, y, width, height, argbTL, argbTR, argbBR, argbBL, // clipX, clipY, clipW, clipH if(len==48) { float x, y, width, height, clipX, clipY, clipW, clipH; int argbTL, argbTR, argbBR, argbBL; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); argbTL=readInt(16, cmddata); argbTR=readInt(20, cmddata); argbBR=readInt(24, cmddata); argbBL=readInt(28, cmddata); clipX=(float)readInt(32, cmddata); clipY=(float)readInt(36, cmddata); clipW=(float)readInt(40, cmddata); clipH=(float)readInt(44, cmddata); // System.out.println("FILLOVAL: dest=("+x+","+y+" "+width+"x"+height+") clip=("+clipX+","+clipY+" "+clipW+"x"+clipH+") argbTL="+Integer.toHexString(argbTL)+" argbTR="+Integer.toHexString(argbTR)+" argbBL="+Integer.toHexString(argbBL)+" argbBR="+Integer.toHexString(argbBR)); java.awt.GradientPaint gp = getGradient(x, y, width, height, argbTL, argbTR, argbBL, argbBR); java.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height); java.awt.geom.Rectangle2D.Float clipRect = new java.awt.geom.Rectangle2D.Float(clipX, clipY, clipW, clipH); if(gp != null) { drawOval0(bounds, clipRect, null, 0, gp.getColor1(), (float)gp.getPoint1().getX(), (float)gp.getPoint1().getY(), gp.getColor2(), (float)gp.getPoint2().getX(), (float)gp.getPoint2().getY(), 1.0f); } else { drawOval0(bounds, clipRect, null, 0, new java.awt.Color(argbTL, true), 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } } else { System.out.println("Invalid len for GFXCMD_FILLOVAL : " + len); } break; case GFXCMD_DRAWROUNDRECT: // x, y, width, height, thickness, arcRadius, argbTL, argbTR, argbBR, argbBL, // clipX, clipY, clipW, clipH if(len==56) { float x, y, width, height, clipX, clipY, clipW, clipH; int thickness, arcRadius, argbTL, argbTR, argbBR, argbBL; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); thickness=readInt(16, cmddata); arcRadius=readInt(20, cmddata); argbTL=readInt(24, cmddata); argbTR=readInt(28, cmddata); argbBR=readInt(32, cmddata); argbBL=readInt(36, cmddata); clipX=(float)readInt(40, cmddata); clipY=(float)readInt(44, cmddata); clipW=(float)readInt(48, cmddata); clipH=(float)readInt(52, cmddata); // System.out.println("DRAWROUNDRECT: dest=("+x+","+y+" "+width+"x"+height+") clip=("+clipX+","+clipY+" "+clipW+"x"+clipH+") thickness="+thickness+" arcRadius="+arcRadius+" argbTL="+Integer.toHexString(argbTL)+" argbTR="+Integer.toHexString(argbTR)+" argbBL="+Integer.toHexString(argbBL)+" argbBR="+Integer.toHexString(argbBR)); // FIXME: no gradients on stroked shapes java.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height); java.awt.geom.Rectangle2D.Float clipRect = new java.awt.geom.Rectangle2D.Float(clipX, clipY, clipW, clipH); drawRect0(bounds, clipRect, arcRadius, new java.awt.Color(argbTL, true), thickness, null, 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } else { System.out.println("Invalid len for GFXCMD_DRAWROUNDRECT : " + len); } break; case GFXCMD_FILLROUNDRECT: // x, y, width, height, arcRadius, argbTL, argbTR, argbBR, argbBL, // clipX, clipY, clipW, clipH if(len==52) { float x, y, width, height, clipX, clipY, clipW, clipH; int arcRadius, argbTL, argbTR, argbBR, argbBL; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); arcRadius=readInt(16, cmddata); argbTL=readInt(20, cmddata); argbTR=readInt(24, cmddata); argbBR=readInt(28, cmddata); argbBL=readInt(32, cmddata); clipX=(float)readInt(36, cmddata); clipY=(float)readInt(40, cmddata); clipW=(float)readInt(44, cmddata); clipH=(float)readInt(48, cmddata); // System.out.println("FILLROUNDRECT: dest=("+x+","+y+" "+width+"x"+height+") clip=("+clipX+","+clipY+" "+clipW+"x"+clipH+") arcRadius="+arcRadius+" argbTL="+Integer.toHexString(argbTL)+" argbTR="+Integer.toHexString(argbTR)+" argbBL="+Integer.toHexString(argbBL)+" argbBR="+Integer.toHexString(argbBR)); java.awt.GradientPaint gp = getGradient(x, y, width, height, argbTL, argbTR, argbBL, argbBR); java.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height); java.awt.geom.Rectangle2D.Float clipRect = new java.awt.geom.Rectangle2D.Float(clipX, clipY, clipW, clipH); if(gp != null) { drawRect0(bounds, clipRect, arcRadius, null, 0, gp.getColor1(), (float)gp.getPoint1().getX(), (float)gp.getPoint1().getY(), gp.getColor2(), (float)gp.getPoint2().getX(), (float)gp.getPoint2().getY(), //(float)((argbTL>>24)&0xff)/255.0f); 1.0f); } else { drawRect0(bounds, clipRect, arcRadius, null, 0, new java.awt.Color(argbTL, true), 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } } else { System.out.println("Invalid len for GFXCMD_FILLROUNDRECT : " + len); } break; case GFXCMD_DRAWTEXT: // x, y, len, text, handle, argb, clipX, clipY, clipW, clipH if(len>=36 && len>=(36+readInt(8, cmddata)*2)) { float x, y, clipX, clipY, clipW, clipH; int textlen, fontHandle, argb; StringBuffer text = new StringBuffer(); int i; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); textlen=readInt(8, cmddata); for(i=0;i<textlen;i++) { text.append((char)readShort(12+i*2, cmddata)); } fontHandle=readInt(textlen*2+12, cmddata); argb=readInt(textlen*2+16, cmddata); clipX=(float)readInt(textlen*2+20, cmddata); clipY=(float)readInt(textlen*2+24, cmddata); clipW=(float)readInt(textlen*2+28, cmddata); clipH=(float)readInt(textlen*2+32, cmddata); // TODO: check if this is needed // if (System.getProperty("java.version").startsWith("1.4")) // clipW = clipW * 5 / 4; // System.out.println("DRAWTEXT: dest=("+x+","+y+") clip=("+clipX+","+clipY+" "+clipW+"x"+clipH+") fontHandle="+fontHandle+" argb="+Integer.toHexString(argb)+" text="+text.toString()); McFont fontPtr = (McFont)fontMap.get(new Integer(fontHandle)); if(fontPtr != null) { // use AWT string bounds or we'll clip on occasion String theString = text.toString(); // java.awt.Dimension textSize = fontPtr.getStringSize(theString); float[] positions = fontPtr.getGlyphPositions(theString); // System.out.println("drawText: \""+theString+"\" loc=("+x+","+y+") num positions="+positions.length); drawTextWithPositions0(theString, fontPtr.nativeFont, x, y, positions, new java.awt.geom.Rectangle2D.Float(clipX,clipY,clipW,clipH), new java.awt.Color(argb, true)); } } else { System.out.println("Invalid len for GFXCMD_DRAWTEXT : " + len); } break; case GFXCMD_DRAWTEXTURED: // x, y, width, height, handle, srcx, srcy, srcwidth, srcheight, blend if(len==40) { float x, y, width, height, srcx, srcy, srcwidth, srcheight; int handle, blend; // blend is a color, use alpha component for blending x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); handle=readInt(16, cmddata); // either an image handle or layer handle (if not in imageMap) srcx=(float)readInt(20, cmddata); srcy=(float)readInt(24, cmddata); srcwidth=(float)readInt(28, cmddata); srcheight=(float)readInt(32, cmddata); blend=readInt(36, cmddata); /* if height < 0 disable blending if width < 0 (font mode, composite with background and blend with given color) blend with full RGBA color else blend with alpha only */ // System.out.println("DRAWTEXTURED: handle="+handle+" dest=("+x+","+y+" "+width+"x"+height+") src=("+srcx+","+srcy+" "+srcwidth+"x"+srcheight+") blend="+Integer.toHexString(blend)); boolean doBlend = true; if(height < 0) { doBlend = false; height *= -1; } if(width < 0) { width *= -1; } else { if(doBlend) blend |= 0x00ffffff; // only use alpha } Long imagePtr = (Long)imageMap.get(new Integer(handle)); java.awt.geom.Rectangle2D.Float destRect = new java.awt.geom.Rectangle2D.Float(x,y,width,height); java.awt.geom.Rectangle2D.Float srcRect = new java.awt.geom.Rectangle2D.Float(srcx,srcy,srcwidth,srcheight); if(imagePtr != null) { myConn.registerImageAccess(handle); // System.out.println(" (drawing image) imagePtr="+imagePtr); drawImage1(imagePtr.longValue(), destRect, srcRect, (doBlend) ? new java.awt.Color(blend, true) : null); } else { imagePtr = (Long)layerMap.get(new Integer(handle)); if(imagePtr != null) { myConn.registerImageAccess(handle); // System.out.println(" (compositing surface) layerPtr="+Long.toHexString(imagePtr.longValue())+" currentLayer="+currentLayer); float alpha = (doBlend ? (float)(((blend >> 24)&0xff))/255.0f : 1.0f); composite0(imagePtr.longValue(), currentLayer, srcRect, destRect, alpha, doBlend); } else { System.out.println("ERROR invalid handle passed for texture rendering of: " + handle); abortRenderCycle = true; } } } else { System.out.println("Invalid len for GFXCMD_DRAWTEXTURED : " + len); } break; case GFXCMD_DRAWLINE: // x1, y1, x2, y2, argb1, argb2 if(len==24) { float x1, y1, x2, y2; int argb1, argb2; x1=readInt(0, cmddata); y1=readInt(4, cmddata); x2=readInt(8, cmddata); y2=readInt(12, cmddata); argb1=readInt(16, cmddata); argb2=readInt(20, cmddata); // System.out.println("DRAWLINE: start=("+x1+","+y1+") end=("+x2+","+y2+") argb1="+Integer.toHexString(argb1)+" argb2="+Integer.toHexString(argb2)); drawLine0(x1, y1, x2, y2, 1, new java.awt.Color(argb1, true)); } else { System.out.println("Invalid len for GFXCMD_DRAWLINE : " + len); } break; case GFXCMD_LOADIMAGE: // width, height if(len>=8) { int width, height; int imghandle = 0; width=readInt(0, cmddata); height=readInt(4, cmddata); // System.out.println("LOADIMAGE: size=("+width+"x"+height+")"); if (width * height * 4 + imageCacheSize > imageCacheLimit) { imghandle = 0; } else { // creating a new image from bitmap data being sent over myConn, create a new empty image long imagePtr = createNewImage0(width, height); imghandle = handleCount++; // System.out.println(" imghandle="+imghandle+" imagePtr="+imagePtr); imageMap.put(new Integer(imghandle), new Long(imagePtr)); // actual value is filled in later when it's prepared imageCacheSize += width * height * 4; } hasret[0]=1; return imghandle; } else { System.out.println("Invalid len for GFXCMD_LOADIMAGE : " + len); } break; case GFXCMD_LOADIMAGETARGETED: // handle, width, height // Not used unless we do uncompressed images if(len>=12) { int width, height; int imghandle = readInt(0, cmddata); width=readInt(4, cmddata); height=readInt(8, cmddata); while (width * height * 4 + imageCacheSize > imageCacheLimit) { // Keep freeing the oldest image until we have enough memory to do this int oldestImage = myConn.getOldestImage(); if (oldestImage != 0) { System.out.println("Freeing image to make room in cache"); unloadImage(oldestImage); myConn.postImageUnload(oldestImage); } else { System.out.println("ERROR cannot free enough from the cache to support loading a new image!!!"); break; } } long imagePtr = createNewImage0(width, height); // System.out.println(" imghandle="+imghandle+" imagePtr="+imagePtr); imageMap.put(new Integer(imghandle), new Long(imagePtr)); // actual value is filled in later when it's prepared imageCacheSize += width * height * 4; myConn.registerImageAccess(imghandle); hasret[0]=0; } else { System.out.println("Invalid len for GFXCMD_LOADIMAGETARGETED : " + len); } break; case GFXCMD_CREATESURFACE: // width, height if(len>=8) { int width, height; int handle = handleCount++;; width=readInt(0, cmddata); height=readInt(4, cmddata); // width/height is managed here long layerPtr = createLayer0(c.getSize()); layerMap.put(new Integer(handle), new Long(layerPtr)); // System.out.println("CREATESURFACE: ("+width+","+height+") handle="+handle+" layerPtr="+layerPtr); hasret[0]=1; return handle; } else { System.out.println("Invalid len for GFXCMD_CREATESURFACE : " + len); } break; case GFXCMD_PREPIMAGE: // width, height if(len>=8) { int width, height; //int imghandle = handleCount++;; width=readInt(0, cmddata); height=readInt(4, cmddata); int imghandle = 1; // System.out.println("PREPIMAGE: size=("+width+"x"+height+")"); if (width * height * 4 + imageCacheSize > imageCacheLimit) imghandle = 0; else if (len >= 12) { // We've got enough room for it and there's a cache ID, check if we've got it cached locally int strlen = readInt(8, cmddata); if (strlen > 1) { String rezName = new String(cmddata, 16, strlen - 1); // System.out.println(" rezName="+rezName); lastImageResourceID = rezName; // We use this hashcode to match it up on the loadCompressedImage call so we know we're caching the right thing lastImageResourceIDHandle = imghandle = Math.abs(lastImageResourceID.hashCode()); java.io.File cachedFile = myConn.getCachedImageFile(rezName); if (cachedFile != null) { // We've got it locally in our cache! Read it from there. long imagePtr = createImageFromPath0(cachedFile.getAbsolutePath()); if(imagePtr != 0) { java.awt.Dimension imgSize = getImageDimensions0(imagePtr); if(imgSize != null) { if(imgSize.getWidth() == width && imgSize.getHeight() == height) { // valid image in cache, use it imghandle = handleCount++; // System.out.println(" loaded from cache, imagePtr="+imagePtr+" handle="+imghandle); imageMap.put(new Integer(imghandle), new Long(imagePtr)); imageCacheSize += getImageSize0(imagePtr); hasret[0] = 1; return -1 * imghandle; } else freeNativeImage0(imagePtr); } else freeNativeImage0(imagePtr); } } } } //imghandle=STBGFX.GFX_loadImage(width, height); hasret[0]=1; return imghandle; } else { System.out.println("Invalid len for GFXCMD_PREPIMAGE : " + len); } break; case GFXCMD_PREPIMAGETARGETED: // handle, width, height, [rezID] if(len>=12) { int imghandle, width, height; imghandle = readInt(0, cmddata); width=readInt(4, cmddata); height=readInt(8, cmddata); int strlen = readInt(12, cmddata); while (width * height * 4 + imageCacheSize > imageCacheLimit) { // Keep freeing the oldest image until we have enough memory to do this int oldestImage = myConn.getOldestImage(); if (oldestImage != 0) { System.out.println("Freeing image to make room in cache"); unloadImage(oldestImage); myConn.postImageUnload(oldestImage); } else { System.out.println("ERROR cannot free enough from the cache to support loading a new image!!!"); break; } } if (len >= 16) { // We will not have this cached locally...but setup our vars to track it String rezName = new String(cmddata, 20, strlen - 1); lastImageResourceID = rezName; lastImageResourceIDHandle = imghandle; System.out.println("Prepped targeted image with handle " + imghandle + " resource=" + rezName); } myConn.registerImageAccess(imghandle); hasret[0]=0; } else { System.out.println("Invalid len for GFXCMD_PREPIMAGE : " + len); } break; case GFXCMD_LOADCACHEDIMAGE: // width, height if(len>=18) { int width, height, imghandle; imghandle = readInt(0, cmddata); width = readInt(4, cmddata); height = readInt(8, cmddata); int strlen = readInt(12, cmddata); String rezName = new String(cmddata, 20, strlen - 1); System.out.println("imghandle=" + imghandle + " width=" + width + " height=" + height + " strlen=" + strlen + " rezName=" + rezName); while (width * height * 4 + imageCacheSize > imageCacheLimit) { // Keep freeing the oldest image until we have enough memory to do this int oldestImage = myConn.getOldestImage(); if (oldestImage != 0) { System.out.println("Freeing image to make room in cache"); unloadImage(oldestImage); myConn.postImageUnload(oldestImage); } else { System.out.println("ERROR cannot free enough from the cache to support loading a new image!!!"); break; } } myConn.registerImageAccess(imghandle); try { System.out.println("Loading resource from cache: " + rezName); java.io.File cachedFile = myConn.getCachedImageFile(rezName); if (cachedFile != null) { // We've got it locally in our cache! Read it from there. System.out.println("Image found in cache!"); // We've got it locally in our cache! Read it from there. long imagePtr = createImageFromPath0(cachedFile.getAbsolutePath()); if(imagePtr != 0) { java.awt.Dimension imgSize = getImageDimensions0(imagePtr); if(imgSize != null && imgSize.getWidth() == width && imgSize.getHeight() == height) { // valid image in cache, use it // System.out.println(" loaded from cache, imagePtr="+imagePtr+" handle="+imghandle); imageMap.put(new Integer(imghandle), new Long(imagePtr)); imageCacheSize += getImageSize0(imagePtr); } else { if (imgSize != null) { // It doesn't match the cache System.out.println("CACHE ID verification failed for rezName=" + rezName + " target=" + width + "x" + height + " actual=" + imgSize.getWidth() + "x" + imgSize.getHeight()); } else System.out.println("CACHE Load failed for rezName=" + rezName); cachedFile.delete(); freeNativeImage0(imagePtr); // This load failed but the server thought it would succeed, so we need to inform it that the image is no longer loaded. myConn.postImageUnload(imghandle); myConn.postOfflineCacheChange(false, rezName); } } else { cachedFile.delete(); // This load failed but the server thought it would succeed, so we need to inform it that the image is no longer loaded. myConn.postImageUnload(imghandle); myConn.postOfflineCacheChange(false, rezName); } } else { System.out.println("ERROR Image not found in cache that should be there! rezName=" + rezName); // This load failed but the server thought it would succeed, so we need to inform it that the image is no longer loaded. myConn.postImageUnload(imghandle); myConn.postOfflineCacheChange(false, rezName); } } catch (java.io.IOException e) { System.out.println("ERROR loading compressed image: " + e); } hasret[0]=0; } else { System.out.println("Invalid len for GFXCMD_PREPIMAGE : " + len); } break; case GFXCMD_UNLOADIMAGE: // handle if(len==4) { int handle; handle=readInt(0, cmddata); unloadImage(handle); myConn.clearImageAccess(handle); } else { System.out.println("Invalid len for GFXCMD_UNLOADIMAGE : " + len); } break; case GFXCMD_SETTARGETSURFACE: // handle if(len==4) { int handle; handle=readInt(0, cmddata); //STBGFX.GFX_unloadImage(handle); Long layerPtr = (Long)layerMap.get(new Integer(handle)); // System.out.println("SETTARGETSURFACE: handle="+handle+" layerPtr="+ (layerPtr == null ? "0" : Long.toHexString(layerPtr.longValue()))); currentLayer = (layerPtr != null) ? layerPtr.longValue() : 0; java.awt.Rectangle clipRect = new java.awt.Rectangle(0, 0, c.getWidth(), c.getHeight()); setLayer0(currentLayer, c.getSize(), clipRect); } else { System.out.println("Invalid len for GFXCMD_SETTARGETSURFACE : " + len); } break; case GFXCMD_LOADFONT: // namelen, name, style, size if(len>=12 && len>=(12+readInt(0, cmddata))) { int namelen, style, size; StringBuffer name = new StringBuffer(); int i; int fonthandle = handleCount++; namelen=readInt(0, cmddata); for(i=0;i<namelen-1;i++) // skip the terminating \0 character { name.append((char) cmddata[8 + i]); // an extra 4 for the header } style=readInt(namelen+4, cmddata); size=readInt(namelen+8, cmddata); // System.out.println("LOADFONT: handle="+fonthandle+" name="+name.toString()+" style="+Integer.toHexString(style)+" size="+size); McFont fontPtr = new McFont(name.toString(), style, size); // long fontPtr = loadFont0(name.toString(), style, size); if(fontPtr == null) { // FIXME: implement! // we don't have the font on this sytem (yet) see if it's cached and try to load it manually // String cacheName = name.toString() + "-" + style; // fontPtr = loadCachedFont0(cacheDir.getAbsolutePath(), name.toString() + "-" + myConn.getServerName(), style, size); // if (fontPtr == 0) { // Return that we don't have this font so it'll load it into our cache hasret[0] = 1; return 0; // } } // System.out.println(" fontPtr=" + fontPtr); fontMap.put(new Integer(fonthandle), fontPtr); hasret[0] = 1; return fonthandle; } else { System.out.println("Invalid len for GFXCMD_LOADFONT : " + len); } break; case GFXCMD_UNLOADFONT: // handle if(len==4) { int handle; handle=readInt(0, cmddata); //STBGFX.GFX_unloadFont(handle); McFont fontPtr = (McFont)fontMap.get(new Integer(handle)); // System.out.println("UNLOADFONT: handle="+handle+" fontPtr="+fontPtr); if(fontPtr != null) fontPtr.unload(); fontMap.remove(new Integer(handle)); } else { System.out.println("Invalid len for GFXCMD_UNLOADFONT : " + len); } break; case GFXCMD_LOADFONTSTREAM: // namelen, name, len, data if (len>=8) { StringBuffer name = new StringBuffer(); int namelen = readInt(0, cmddata); for(int i=0;i<namelen-1;i++) // skip the terminating \0 character { name.append((char) cmddata[8 + i]); // an extra 4 for the header } int datalen = readInt(4 + namelen, cmddata); if (len >= datalen + 8 + namelen) { // System.out.println("Saving font " + name.toString() + " to cache"); myConn.saveCacheData(name.toString() + "-" + myConn.getServerName(), cmddata, 12 + namelen, datalen); } } else { System.out.println("Invalid len for GFXCMD_LOADFONTSTREAM : " + len); } break; case GFXCMD_FLIPBUFFER: // System.out.println("FLIPBUFFER"); if (abortRenderCycle) { System.out.println("ERROR in painting cycle, ABORT was set...send full repaint command"); myConn.postRepaintEvent(0, 0, c.getWidth(), c.getHeight()); } else { present0(c.nativeView, new java.awt.Rectangle(0, 0, c.getWidth(), c.getHeight())); } hasret[0] = 1; //STBGFX.GFX_flipBuffer(); firstFrameDone = true; return 0; case GFXCMD_STARTFRAME: // System.out.println("STARTFRAME"); // prepare for a new frame to be rendered setTargetView0(c.nativeView); setLayer0(0, c.getSize(), null); // this makes sure the drawing surface gets resized properly abortRenderCycle = false; break; case GFXCMD_LOADIMAGELINE: // handle, line, len, data if(len>=12 && len>=(12+readInt(8, cmddata))) { int handle, line, len2; //unsigned char *data=&cmddata[12]; handle=readInt(0, cmddata); line=readInt(4, cmddata); len2=readInt(8, cmddata); // the last number is the offset into the data array to start reading from //STBGFX.GFX_loadImageLine(handle, line, len, data, 12); //int dataPos = 12; Long imagePtr = (Long)imageMap.get(new Integer(handle)); // System.out.println("LOADIMAGELINE: handle="+handle+" imagePtr="+imagePtr+" line="+line+" len2="+len2); if(imagePtr != null) loadImageLine0(imagePtr.longValue(), line, cmddata, 16/*12*/, len2); myConn.registerImageAccess(handle); } else { System.out.println("Invalid len for GFXCMD_LOADIMAGELINE : " + len); } break; case GFXCMD_LOADIMAGECOMPRESSED: // handle, line, len, data if(len>=8 && len>=(8+readInt(4, cmddata))) { int handle, len2; handle=readInt(0, cmddata); len2=readInt(4, cmddata); if (lastImageResourceID != null && lastImageResourceIDHandle == handle) { myConn.saveCacheData(lastImageResourceID, cmddata, 12, len2); myConn.postOfflineCacheChange(true, lastImageResourceID); } if (!myConn.doesUseAdvancedImageCaching()) { handle = handleCount++; hasret[0] = 1; } else hasret[0] = 0; myConn.registerImageAccess(handle); long imagePtr = createImageFromBytes0(cmddata, 12, len2, null); // FIXME: grab extension if possible // System.out.println("LOADIMAGECOMPRESSED: handle="+handle+" imagePtr="+imagePtr+" len2="+len2); imageMap.put(new Integer(handle), new Long(imagePtr)); imageCacheSize += getImageSize0(imagePtr); return handle; } else { System.out.println("Invalid len for GFXCMD_LOADIMAGECOMPRESSED : " + len); } break; case GFXCMD_XFMIMAGE: // srcHandle, destHandle, destWidth, destHeight, maskCornerArc if (len >= 20) { int srcHandle, destHandle, destWidth, destHeight, maskCornerArc; srcHandle = readInt(0, cmddata); destHandle = readInt(4, cmddata); // seems to be unused destWidth = readInt(8, cmddata); // scaled size (ignore?) destHeight = readInt(12, cmddata); maskCornerArc = readInt(16, cmddata); int rvHandle = destHandle; if (!myConn.doesUseAdvancedImageCaching()) { rvHandle = handleCount++; hasret[0] = 1; } else hasret[0] = 0; // we cheat and apply the transforms to a metaimage object without actually creating a new image (saves oodles of memory) Long srcImg = (Long)imageMap.get(new Integer(srcHandle)); // System.out.println("XFMIMAGE: srcHandle="+srcHandle+" srcImg="+srcImg+" destHandle="+destHandle+" destWidth="+destWidth+" destHeight="+destHeight+" maskCornerArc="+maskCornerArc); if(srcImg != null) { long newImage = transformImage0(srcImg.longValue(), destWidth, destHeight, maskCornerArc); if(newImage != 0) { // System.out.println(" newImage="+newImage); imageMap.put(new Integer(rvHandle), new Long(newImage)); } } return rvHandle; } else { System.out.println("Invalid len for GFXCMD_XFMIMAGE : " + len); } break; case GFXCMD_SETVIDEOPROP: if (len >= 40) { java.awt.Rectangle srcRect = new java.awt.Rectangle(readInt(4, cmddata), readInt(8, cmddata), readInt(12, cmddata), readInt(16, cmddata)); java.awt.Rectangle destRect = new java.awt.Rectangle(readInt(20, cmddata), readInt(24, cmddata), readInt(28, cmddata), readInt(32, cmddata)); System.out.println("SETVIDEOPROP: srcRect="+srcRect+" dstRect="+destRect); setVideoBounds(srcRect, destRect); } else { System.out.println("Invalid len for GFXCMD_SETVIDEOPROP: " + len); } break; default: return -1; } return 0; }
public int ExecuteGFXCommand(int cmd, int len, byte[] cmddata, int[] hasret) { len -= 4; hasret[0] = 0; if((cmd != GFXCMD_INIT) && (cmd != GFXCMD_DEINIT)) { if((f != null) ? (!f.isDisplayable() || !f.isValid() || !f.isShowing()) : true) { while((f != null) ? (!f.isDisplayable() || !f.isValid() || !f.isShowing()) : true) { try { Thread.sleep(10); } catch(InterruptedException ex) {} } } } if (c != null) { switch(cmd) { case GFXCMD_INIT: case GFXCMD_DEINIT: case GFXCMD_STARTFRAME: case GFXCMD_FLIPBUFFER: c.setCursor(null); break; case GFXCMD_DRAWRECT: case GFXCMD_FILLRECT: case GFXCMD_CLEARRECT: case GFXCMD_DRAWOVAL: case GFXCMD_FILLOVAL: case GFXCMD_DRAWROUNDRECT: case GFXCMD_FILLROUNDRECT: case GFXCMD_DRAWTEXT: case GFXCMD_DRAWTEXTURED: case GFXCMD_DRAWLINE: case GFXCMD_LOADIMAGE: case GFXCMD_LOADIMAGETARGETED: case GFXCMD_UNLOADIMAGE: case GFXCMD_LOADFONT: case GFXCMD_UNLOADFONT: case GFXCMD_SETTARGETSURFACE: case GFXCMD_CREATESURFACE: break; case GFXCMD_PREPIMAGE: case GFXCMD_LOADIMAGELINE: case GFXCMD_LOADIMAGECOMPRESSED: case GFXCMD_XFMIMAGE: case GFXCMD_LOADCACHEDIMAGE: case GFXCMD_PREPIMAGETARGETED: if (!cursorHidden) c.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR)); break; } } switch(cmd) { case GFXCMD_INIT: hasret[0] = 1; init0(); int windowTitleStyle = 0; try { windowTitleStyle = Integer.parseInt(MiniClient.myProperties.getProperty("window_title_style", "0")); } catch (NumberFormatException e){} if (!"true".equals(MiniClient.myProperties.getProperty("enable_custom_title_bar", MiniClient.MAC_OS_X ? "false" : "true"))) windowTitleStyle = 10; f = new MiniClientWindow(myConn.getWindowTitle(), windowTitleStyle); java.awt.LayoutManager layer = new java.awt.LayoutManager() { public void addLayoutComponent(String name, java.awt.Component comp) {} public java.awt.Dimension minimumLayoutSize(java.awt.Container parent) { return preferredLayoutSize(parent); } public java.awt.Dimension preferredLayoutSize(java.awt.Container parent) { return parent.getPreferredSize(); } public void removeLayoutComponent(java.awt.Component comp) {} public void layoutContainer(java.awt.Container parent) { c.setBounds(parent.getInsets().left, parent.getInsets().top, parent.getWidth() - parent.getInsets().left - parent.getInsets().right, parent.getHeight() - parent.getInsets().top - parent.getInsets().bottom); } }; f.getContentPane().setLayout(layer); try { bgImage = java.awt.Toolkit.getDefaultToolkit().createImage(getClass().getClassLoader().getResource("images/Background.jpg")); ensureImageIsLoaded(bgImage); logoImage = java.awt.Toolkit.getDefaultToolkit().createImage(getClass().getClassLoader().getResource("images/SageLogo256.png")); ensureImageIsLoaded(logoImage); } catch (Exception e) { System.out.println("ERROR:" + e); e.printStackTrace(); } f.setFocusTraversalKeysEnabled(false); java.awt.Dimension panelSize = f.getContentPane().getSize(); c = new QuartzRendererView(); c.setSize(panelSize); c.setFocusTraversalKeysEnabled(false); f.getContentPane().add(c); try { java.awt.Image frameIcon = java.awt.Toolkit.getDefaultToolkit().createImage(getClass().getClassLoader().getResource("images/tvicon.gif")); ensureImageIsLoaded(frameIcon); f.setIconImage(frameIcon); } catch (Exception e) { System.out.println("ERROR:" + e); e.printStackTrace(); } f.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { if (!f.isFullScreen() || System.getProperty("os.name").toLowerCase().indexOf("windows") != -1) { MiniClient.myProperties.setProperty("main_window_width", Integer.toString(f.getWidth())); MiniClient.myProperties.setProperty("main_window_height", Integer.toString(f.getHeight())); MiniClient.myProperties.setProperty("main_window_x", Integer.toString(f.getX())); MiniClient.myProperties.setProperty("main_window_y", Integer.toString(f.getY())); } myConn.close(); close(); } }); c.addComponentListener(new java.awt.event.ComponentAdapter() { public void componentResized(java.awt.event.ComponentEvent evt) { myConn.postResizeEvent(new java.awt.Dimension(c.getWidth(), c.getHeight())); } }); f.addKeyListener(this); c.addKeyListener(this); f.addMouseWheelListener(this); c.addMouseListener(this); if (ENABLE_MOUSE_MOTION_EVENTS) { c.addMouseMotionListener(this); } int frameX = 100; int frameY = 100; int frameW = 720; int frameH = 480; try { frameW = Integer.parseInt(MiniClient.myProperties.getProperty("main_window_width", "720")); frameH = Integer.parseInt(MiniClient.myProperties.getProperty("main_window_height", "480")); frameX = Integer.parseInt(MiniClient.myProperties.getProperty("main_window_x", "100")); frameY = Integer.parseInt(MiniClient.myProperties.getProperty("main_window_y", "100")); } catch (NumberFormatException e){} java.awt.Point newPos = new java.awt.Point(frameX, frameY); boolean foundScreen = sage.UIUtils.isPointOnAScreen(newPos); if (!foundScreen) { newPos.x = 150; newPos.y = 150; } f.setVisible(true); f.setSize(1,1); f.setSize(Math.max(frameW, 320), Math.max(frameH, 240)); f.setLocation(newPos); if (MiniClient.fsStartup) f.setFullScreen(true); MiniClient.hideSplash(); return 1; case GFXCMD_DEINIT: close(); break; case GFXCMD_DRAWRECT: if(len==36) { float x, y, width, height; int thickness, argbTL, argbTR, argbBR, argbBL; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); thickness=readInt(16, cmddata); argbTL=readInt(20, cmddata); argbTR=readInt(24, cmddata); argbBR=readInt(28, cmddata); argbBL=readInt(32, cmddata); drawRect0(new java.awt.geom.Rectangle2D.Float(x, y, width, height), null, 0, new java.awt.Color(argbTL, true), thickness, null, 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } else { System.out.println("Invalid len for GFXCMD_DRAWRECT : " + len); } break; case GFXCMD_FILLRECT: if(len==32) { float x, y, width, height; int argbTL, argbTR, argbBR, argbBL; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); argbTL=readInt(16, cmddata); argbTR=readInt(20, cmddata); argbBR=readInt(24, cmddata); argbBL=readInt(28, cmddata); java.awt.GradientPaint gp = getGradient(x, y, width, height, argbTL, argbTR, argbBL, argbBR); java.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height); if(gp != null) { drawRect0(bounds, null, 0, null, 0, gp.getColor1(), (float)gp.getPoint1().getX(), (float)gp.getPoint1().getY(), gp.getColor2(), (float)gp.getPoint2().getX(), (float)gp.getPoint2().getY(), 1.0f); } else { drawRect0(bounds, null, 0, null, 0, new java.awt.Color(argbTL, true), 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } } else { System.out.println("Invalid len for GFXCMD_FILLRECT : " + len); } break; case GFXCMD_CLEARRECT: if(len==32) { int x, y, width, height, argbTL, argbTR, argbBR, argbBL; x=readInt(0, cmddata); y=readInt(4, cmddata); width=readInt(8, cmddata); height=readInt(12, cmddata); argbTL=readInt(16, cmddata); argbTR=readInt(20, cmddata); argbBR=readInt(24, cmddata); argbBL=readInt(28, cmddata); java.awt.geom.Rectangle2D.Float destRect = new java.awt.geom.Rectangle2D.Float(x, y, width, height); clearRect0(destRect); } else { System.out.println("Invalid len for GFXCMD_CLEARRECT : " + len); } break; case GFXCMD_DRAWOVAL: if(len==52) { float x, y, width, height, clipX, clipY, clipW, clipH; int thickness, argbTL, argbTR, argbBR, argbBL; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); thickness=readInt(16, cmddata); argbTL=readInt(20, cmddata); argbTR=readInt(24, cmddata); argbBR=readInt(28, cmddata); argbBL=readInt(32, cmddata); clipX=(float)readInt(36, cmddata); clipY=(float)readInt(40, cmddata); clipW=(float)readInt(44, cmddata); clipH=(float)readInt(48, cmddata); java.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height); java.awt.geom.Rectangle2D.Float clipRect = new java.awt.geom.Rectangle2D.Float(clipX, clipY, clipW, clipH); drawOval0(bounds, clipRect, new java.awt.Color(argbTL, true), thickness, null, 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } else { System.out.println("Invalid len for GFXCMD_DRAWOVAL : " + len); } break; case GFXCMD_FILLOVAL: if(len==48) { float x, y, width, height, clipX, clipY, clipW, clipH; int argbTL, argbTR, argbBR, argbBL; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); argbTL=readInt(16, cmddata); argbTR=readInt(20, cmddata); argbBR=readInt(24, cmddata); argbBL=readInt(28, cmddata); clipX=(float)readInt(32, cmddata); clipY=(float)readInt(36, cmddata); clipW=(float)readInt(40, cmddata); clipH=(float)readInt(44, cmddata); java.awt.GradientPaint gp = getGradient(x, y, width, height, argbTL, argbTR, argbBL, argbBR); java.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height); java.awt.geom.Rectangle2D.Float clipRect = new java.awt.geom.Rectangle2D.Float(clipX, clipY, clipW, clipH); if(gp != null) { drawOval0(bounds, clipRect, null, 0, gp.getColor1(), (float)gp.getPoint1().getX(), (float)gp.getPoint1().getY(), gp.getColor2(), (float)gp.getPoint2().getX(), (float)gp.getPoint2().getY(), 1.0f); } else { drawOval0(bounds, clipRect, null, 0, new java.awt.Color(argbTL, true), 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } } else { System.out.println("Invalid len for GFXCMD_FILLOVAL : " + len); } break; case GFXCMD_DRAWROUNDRECT: if(len==56) { float x, y, width, height, clipX, clipY, clipW, clipH; int thickness, arcRadius, argbTL, argbTR, argbBR, argbBL; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); thickness=readInt(16, cmddata); arcRadius=readInt(20, cmddata); argbTL=readInt(24, cmddata); argbTR=readInt(28, cmddata); argbBR=readInt(32, cmddata); argbBL=readInt(36, cmddata); clipX=(float)readInt(40, cmddata); clipY=(float)readInt(44, cmddata); clipW=(float)readInt(48, cmddata); clipH=(float)readInt(52, cmddata); java.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height); java.awt.geom.Rectangle2D.Float clipRect = new java.awt.geom.Rectangle2D.Float(clipX, clipY, clipW, clipH); drawRect0(bounds, clipRect, arcRadius, new java.awt.Color(argbTL, true), thickness, null, 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } else { System.out.println("Invalid len for GFXCMD_DRAWROUNDRECT : " + len); } break; case GFXCMD_FILLROUNDRECT: if(len==52) { float x, y, width, height, clipX, clipY, clipW, clipH; int arcRadius, argbTL, argbTR, argbBR, argbBL; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); arcRadius=readInt(16, cmddata); argbTL=readInt(20, cmddata); argbTR=readInt(24, cmddata); argbBR=readInt(28, cmddata); argbBL=readInt(32, cmddata); clipX=(float)readInt(36, cmddata); clipY=(float)readInt(40, cmddata); clipW=(float)readInt(44, cmddata); clipH=(float)readInt(48, cmddata); java.awt.GradientPaint gp = getGradient(x, y, width, height, argbTL, argbTR, argbBL, argbBR); java.awt.geom.Rectangle2D.Float bounds = new java.awt.geom.Rectangle2D.Float(x, y, width, height); java.awt.geom.Rectangle2D.Float clipRect = new java.awt.geom.Rectangle2D.Float(clipX, clipY, clipW, clipH); if(gp != null) { drawRect0(bounds, clipRect, arcRadius, null, 0, gp.getColor1(), (float)gp.getPoint1().getX(), (float)gp.getPoint1().getY(), gp.getColor2(), (float)gp.getPoint2().getX(), (float)gp.getPoint2().getY(), 1.0f); } else { drawRect0(bounds, clipRect, arcRadius, null, 0, new java.awt.Color(argbTL, true), 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } } else { System.out.println("Invalid len for GFXCMD_FILLROUNDRECT : " + len); } break; case GFXCMD_DRAWTEXT: if(len>=36 && len>=(36+readInt(8, cmddata)*2)) { float x, y, clipX, clipY, clipW, clipH; int textlen, fontHandle, argb; StringBuffer text = new StringBuffer(); int i; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); textlen=readInt(8, cmddata); for(i=0;i<textlen;i++) { text.append((char)readShort(12+i*2, cmddata)); } fontHandle=readInt(textlen*2+12, cmddata); argb=readInt(textlen*2+16, cmddata); clipX=(float)readInt(textlen*2+20, cmddata); clipY=(float)readInt(textlen*2+24, cmddata); clipW=(float)readInt(textlen*2+28, cmddata); clipH=(float)readInt(textlen*2+32, cmddata); McFont fontPtr = (McFont)fontMap.get(new Integer(fontHandle)); if(fontPtr != null) { String theString = text.toString(); float[] positions = fontPtr.getGlyphPositions(theString); drawTextWithPositions0(theString, fontPtr.nativeFont, x, y, positions, new java.awt.geom.Rectangle2D.Float(clipX,clipY,clipW,clipH), new java.awt.Color(argb, true)); } } else { System.out.println("Invalid len for GFXCMD_DRAWTEXT : " + len); } break; case GFXCMD_DRAWTEXTURED: if(len==40) { float x, y, width, height, srcx, srcy, srcwidth, srcheight; int handle, blend; x=(float)readInt(0, cmddata); y=(float)readInt(4, cmddata); width=(float)readInt(8, cmddata); height=(float)readInt(12, cmddata); handle=readInt(16, cmddata); srcx=(float)readInt(20, cmddata); srcy=(float)readInt(24, cmddata); srcwidth=(float)readInt(28, cmddata); srcheight=(float)readInt(32, cmddata); blend=readInt(36, cmddata); boolean doBlend = true; if(height < 0) { doBlend = false; height *= -1; } if(width < 0) { width *= -1; } else { if(doBlend) blend |= 0x00ffffff; } Long imagePtr = (Long)imageMap.get(new Integer(handle)); java.awt.geom.Rectangle2D.Float destRect = new java.awt.geom.Rectangle2D.Float(x,y,width,height); java.awt.geom.Rectangle2D.Float srcRect = new java.awt.geom.Rectangle2D.Float(srcx,srcy,srcwidth,srcheight); if(imagePtr != null) { myConn.registerImageAccess(handle); drawImage1(imagePtr.longValue(), destRect, srcRect, (doBlend) ? new java.awt.Color(blend, true) : null); } else { imagePtr = (Long)layerMap.get(new Integer(handle)); if(imagePtr != null) { myConn.registerImageAccess(handle); float alpha = (doBlend ? (float)(((blend >> 24)&0xff))/255.0f : 1.0f); composite0(imagePtr.longValue(), currentLayer, srcRect, destRect, alpha, doBlend); } else { System.out.println("ERROR invalid handle passed for texture rendering of: " + handle); abortRenderCycle = true; } } } else { System.out.println("Invalid len for GFXCMD_DRAWTEXTURED : " + len); } break; case GFXCMD_DRAWLINE: if(len==24) { float x1, y1, x2, y2; int argb1, argb2; x1=readInt(0, cmddata); y1=readInt(4, cmddata); x2=readInt(8, cmddata); y2=readInt(12, cmddata); argb1=readInt(16, cmddata); argb2=readInt(20, cmddata); drawLine0(x1, y1, x2, y2, 1, new java.awt.Color(argb1, true)); } else { System.out.println("Invalid len for GFXCMD_DRAWLINE : " + len); } break; case GFXCMD_LOADIMAGE: if(len>=8) { int width, height; int imghandle = 0; width=readInt(0, cmddata); height=readInt(4, cmddata); if (width * height * 4 + imageCacheSize > imageCacheLimit) { imghandle = 0; } else { long imagePtr = createNewImage0(width, height); imghandle = handleCount++; imageMap.put(new Integer(imghandle), new Long(imagePtr)); imageCacheSize += width * height * 4; } hasret[0]=1; return imghandle; } else { System.out.println("Invalid len for GFXCMD_LOADIMAGE : " + len); } break; case GFXCMD_LOADIMAGETARGETED: if(len>=12) { int width, height; int imghandle = readInt(0, cmddata); width=readInt(4, cmddata); height=readInt(8, cmddata); while (width * height * 4 + imageCacheSize > imageCacheLimit) { int oldestImage = myConn.getOldestImage(); if (oldestImage != 0) { System.out.println("Freeing image to make room in cache"); unloadImage(oldestImage); myConn.postImageUnload(oldestImage); } else { System.out.println("ERROR cannot free enough from the cache to support loading a new image!!!"); break; } } long imagePtr = createNewImage0(width, height); imageMap.put(new Integer(imghandle), new Long(imagePtr)); imageCacheSize += width * height * 4; myConn.registerImageAccess(imghandle); hasret[0]=0; } else { System.out.println("Invalid len for GFXCMD_LOADIMAGETARGETED : " + len); } break; case GFXCMD_CREATESURFACE: if(len>=8) { int width, height; int handle = handleCount++;; width=readInt(0, cmddata); height=readInt(4, cmddata); long layerPtr = createLayer0(c.getSize()); layerMap.put(new Integer(handle), new Long(layerPtr)); hasret[0]=1; return handle; } else { System.out.println("Invalid len for GFXCMD_CREATESURFACE : " + len); } break; case GFXCMD_PREPIMAGE: if(len>=8) { int width, height; width=readInt(0, cmddata); height=readInt(4, cmddata); int imghandle = 1; if (width * height * 4 + imageCacheSize > imageCacheLimit) imghandle = 0; else if (len >= 12) { int strlen = readInt(8, cmddata); if (strlen > 1) { String rezName = new String(cmddata, 16, strlen - 1); lastImageResourceID = rezName; lastImageResourceIDHandle = imghandle = Math.abs(lastImageResourceID.hashCode()); java.io.File cachedFile = myConn.getCachedImageFile(rezName); if (cachedFile != null) { long imagePtr = createImageFromPath0(cachedFile.getAbsolutePath()); if(imagePtr != 0) { java.awt.Dimension imgSize = getImageDimensions0(imagePtr); if(imgSize != null) { if(imgSize.getWidth() == width && imgSize.getHeight() == height) { imghandle = handleCount++; imageMap.put(new Integer(imghandle), new Long(imagePtr)); imageCacheSize += getImageSize0(imagePtr); hasret[0] = 1; return -1 * imghandle; } else freeNativeImage0(imagePtr); } else freeNativeImage0(imagePtr); } } } } hasret[0]=1; return imghandle; } else { System.out.println("Invalid len for GFXCMD_PREPIMAGE : " + len); } break; case GFXCMD_PREPIMAGETARGETED: if(len>=12) { int imghandle, width, height; imghandle = readInt(0, cmddata); width=readInt(4, cmddata); height=readInt(8, cmddata); int strlen = readInt(12, cmddata); while (width * height * 4 + imageCacheSize > imageCacheLimit) { int oldestImage = myConn.getOldestImage(); if (oldestImage != 0) { System.out.println("Freeing image to make room in cache"); unloadImage(oldestImage); myConn.postImageUnload(oldestImage); } else { System.out.println("ERROR cannot free enough from the cache to support loading a new image!!!"); break; } } if (len >= 16) { String rezName = new String(cmddata, 20, strlen - 1); lastImageResourceID = rezName; lastImageResourceIDHandle = imghandle; System.out.println("Prepped targeted image with handle " + imghandle + " resource=" + rezName); } myConn.registerImageAccess(imghandle); hasret[0]=0; } else { System.out.println("Invalid len for GFXCMD_PREPIMAGE : " + len); } break; case GFXCMD_LOADCACHEDIMAGE: if(len>=18) { int width, height, imghandle; imghandle = readInt(0, cmddata); width = readInt(4, cmddata); height = readInt(8, cmddata); int strlen = readInt(12, cmddata); String rezName = new String(cmddata, 20, strlen - 1); System.out.println("imghandle=" + imghandle + " width=" + width + " height=" + height + " strlen=" + strlen + " rezName=" + rezName); while (width * height * 4 + imageCacheSize > imageCacheLimit) { int oldestImage = myConn.getOldestImage(); if (oldestImage != 0) { System.out.println("Freeing image to make room in cache"); unloadImage(oldestImage); myConn.postImageUnload(oldestImage); } else { System.out.println("ERROR cannot free enough from the cache to support loading a new image!!!"); break; } } myConn.registerImageAccess(imghandle); try { System.out.println("Loading resource from cache: " + rezName); java.io.File cachedFile = myConn.getCachedImageFile(rezName); if (cachedFile != null) { System.out.println("Image found in cache!"); long imagePtr = createImageFromPath0(cachedFile.getAbsolutePath()); if(imagePtr != 0) { java.awt.Dimension imgSize = getImageDimensions0(imagePtr); if(imgSize != null && imgSize.getWidth() == width && imgSize.getHeight() == height) { imageMap.put(new Integer(imghandle), new Long(imagePtr)); imageCacheSize += getImageSize0(imagePtr); } else { if (imgSize != null) { System.out.println("CACHE ID verification failed for rezName=" + rezName + " target=" + width + "x" + height + " actual=" + imgSize.getWidth() + "x" + imgSize.getHeight()); } else System.out.println("CACHE Load failed for rezName=" + rezName); cachedFile.delete(); freeNativeImage0(imagePtr); myConn.postImageUnload(imghandle); myConn.postOfflineCacheChange(false, rezName); } } else { cachedFile.delete(); myConn.postImageUnload(imghandle); myConn.postOfflineCacheChange(false, rezName); } } else { System.out.println("ERROR Image not found in cache that should be there! rezName=" + rezName); myConn.postImageUnload(imghandle); myConn.postOfflineCacheChange(false, rezName); } } catch (java.io.IOException e) { System.out.println("ERROR loading compressed image: " + e); } hasret[0]=0; } else { System.out.println("Invalid len for GFXCMD_PREPIMAGE : " + len); } break; case GFXCMD_UNLOADIMAGE: if(len==4) { int handle; handle=readInt(0, cmddata); unloadImage(handle); myConn.clearImageAccess(handle); } else { System.out.println("Invalid len for GFXCMD_UNLOADIMAGE : " + len); } break; case GFXCMD_SETTARGETSURFACE: if(len==4) { int handle; handle=readInt(0, cmddata); Long layerPtr = (Long)layerMap.get(new Integer(handle)); currentLayer = (layerPtr != null) ? layerPtr.longValue() : 0; java.awt.Rectangle clipRect = new java.awt.Rectangle(0, 0, c.getWidth(), c.getHeight()); setLayer0(currentLayer, c.getSize(), clipRect); } else { System.out.println("Invalid len for GFXCMD_SETTARGETSURFACE : " + len); } break; case GFXCMD_LOADFONT: if(len>=12 && len>=(12+readInt(0, cmddata))) { int namelen, style, size; StringBuffer name = new StringBuffer(); int i; int fonthandle = handleCount++; namelen=readInt(0, cmddata); for(i=0;i<namelen-1;i++) { name.append((char) cmddata[8 + i]); } style=readInt(namelen+4, cmddata); size=readInt(namelen+8, cmddata); McFont fontPtr = new McFont(name.toString(), style, size); if(fontPtr == null) { hasret[0] = 1; return 0; } fontMap.put(new Integer(fonthandle), fontPtr); hasret[0] = 1; return fonthandle; } else { System.out.println("Invalid len for GFXCMD_LOADFONT : " + len); } break; case GFXCMD_UNLOADFONT: if(len==4) { int handle; handle=readInt(0, cmddata); McFont fontPtr = (McFont)fontMap.get(new Integer(handle)); if(fontPtr != null) fontPtr.unload(); fontMap.remove(new Integer(handle)); } else { System.out.println("Invalid len for GFXCMD_UNLOADFONT : " + len); } break; case GFXCMD_LOADFONTSTREAM: if (len>=8) { StringBuffer name = new StringBuffer(); int namelen = readInt(0, cmddata); for(int i=0;i<namelen-1;i++) { name.append((char) cmddata[8 + i]); } int datalen = readInt(4 + namelen, cmddata); if (len >= datalen + 8 + namelen) { myConn.saveCacheData(name.toString() + "-" + myConn.getServerName(), cmddata, 12 + namelen, datalen); } } else { System.out.println("Invalid len for GFXCMD_LOADFONTSTREAM : " + len); } break; case GFXCMD_FLIPBUFFER: if (abortRenderCycle) { System.out.println("ERROR in painting cycle, ABORT was set...send full repaint command"); myConn.postRepaintEvent(0, 0, c.getWidth(), c.getHeight()); } else { present0(c.nativeView, new java.awt.Rectangle(0, 0, c.getWidth(), c.getHeight())); } hasret[0] = 1; firstFrameDone = true; return 0; case GFXCMD_STARTFRAME: setTargetView0(c.nativeView); setLayer0(0, c.getSize(), null); abortRenderCycle = false; break; case GFXCMD_LOADIMAGELINE: if(len>=12 && len>=(12+readInt(8, cmddata))) { int handle, line, len2; handle=readInt(0, cmddata); line=readInt(4, cmddata); len2=readInt(8, cmddata); Long imagePtr = (Long)imageMap.get(new Integer(handle)); if(imagePtr != null) loadImageLine0(imagePtr.longValue(), line, cmddata, 1, len2); myConn.registerImageAccess(handle); } else { System.out.println("Invalid len for GFXCMD_LOADIMAGELINE : " + len); } break; case GFXCMD_LOADIMAGECOMPRESSED: if(len>=8 && len>=(8+readInt(4, cmddata))) { int handle, len2; handle=readInt(0, cmddata); len2=readInt(4, cmddata); if (lastImageResourceID != null && lastImageResourceIDHandle == handle) { myConn.saveCacheData(lastImageResourceID, cmddata, 12, len2); myConn.postOfflineCacheChange(true, lastImageResourceID); } if (!myConn.doesUseAdvancedImageCaching()) { handle = handleCount++; hasret[0] = 1; } else hasret[0] = 0; myConn.registerImageAccess(handle); long imagePtr = createImageFromBytes0(cmddata, 12, len2, null); imageMap.put(new Integer(handle), new Long(imagePtr)); imageCacheSize += getImageSize0(imagePtr); return handle; } else { System.out.println("Invalid len for GFXCMD_LOADIMAGECOMPRESSED : " + len); } break; case GFXCMD_XFMIMAGE: if (len >= 20) { int srcHandle, destHandle, destWidth, destHeight, maskCornerArc; srcHandle = readInt(0, cmddata); destHandle = readInt(4, cmddata); destWidth = readInt(8, cmddata); destHeight = readInt(12, cmddata); maskCornerArc = readInt(16, cmddata); int rvHandle = destHandle; if (!myConn.doesUseAdvancedImageCaching()) { rvHandle = handleCount++; hasret[0] = 1; } else hasret[0] = 0; Long srcImg = (Long)imageMap.get(new Integer(srcHandle)); if(srcImg != null) { long newImage = transformImage0(srcImg.longValue(), destWidth, destHeight, maskCornerArc); if(newImage != 0) { imageMap.put(new Integer(rvHandle), new Long(newImage)); } } return rvHandle; } else { System.out.println("Invalid len for GFXCMD_XFMIMAGE : " + len); } break; case GFXCMD_SETVIDEOPROP: if (len >= 40) { java.awt.Rectangle srcRect = new java.awt.Rectangle(readInt(4, cmddata), readInt(8, cmddata), readInt(12, cmddata), readInt(16, cmddata)); java.awt.Rectangle destRect = new java.awt.Rectangle(readInt(20, cmddata), readInt(24, cmddata), readInt(28, cmddata), readInt(32, cmddata)); System.out.println("SETVIDEOPROP: srcRect="+srcRect+" dstRect="+destRect); setVideoBounds(srcRect, destRect); } else { System.out.println("Invalid len for GFXCMD_SETVIDEOPROP: " + len); } break; default: return -1; } return 0; }
public int executegfxcommand(int cmd, int len, byte[] cmddata, int[] hasret) { len -= 4; hasret[0] = 0; if((cmd != gfxcmd_init) && (cmd != gfxcmd_deinit)) { if((f != null) ? (!f.isdisplayable() || !f.isvalid() || !f.isshowing()) : true) { while((f != null) ? (!f.isdisplayable() || !f.isvalid() || !f.isshowing()) : true) { try { thread.sleep(10); } catch(interruptedexception ex) {} } } } if (c != null) { switch(cmd) { case gfxcmd_init: case gfxcmd_deinit: case gfxcmd_startframe: case gfxcmd_flipbuffer: c.setcursor(null); break; case gfxcmd_drawrect: case gfxcmd_fillrect: case gfxcmd_clearrect: case gfxcmd_drawoval: case gfxcmd_filloval: case gfxcmd_drawroundrect: case gfxcmd_fillroundrect: case gfxcmd_drawtext: case gfxcmd_drawtextured: case gfxcmd_drawline: case gfxcmd_loadimage: case gfxcmd_loadimagetargeted: case gfxcmd_unloadimage: case gfxcmd_loadfont: case gfxcmd_unloadfont: case gfxcmd_settargetsurface: case gfxcmd_createsurface: break; case gfxcmd_prepimage: case gfxcmd_loadimageline: case gfxcmd_loadimagecompressed: case gfxcmd_xfmimage: case gfxcmd_loadcachedimage: case gfxcmd_prepimagetargeted: if (!cursorhidden) c.setcursor(java.awt.cursor.getpredefinedcursor(java.awt.cursor.wait_cursor)); break; } } switch(cmd) { case gfxcmd_init: hasret[0] = 1; init0(); int windowtitlestyle = 0; try { windowtitlestyle = integer.parseint(miniclient.myproperties.getproperty("window_title_style", "0")); } catch (numberformatexception e){} if (!"true".equals(miniclient.myproperties.getproperty("enable_custom_title_bar", miniclient.mac_os_x ? "false" : "true"))) windowtitlestyle = 10; f = new miniclientwindow(myconn.getwindowtitle(), windowtitlestyle); java.awt.layoutmanager layer = new java.awt.layoutmanager() { public void addlayoutcomponent(string name, java.awt.component comp) {} public java.awt.dimension minimumlayoutsize(java.awt.container parent) { return preferredlayoutsize(parent); } public java.awt.dimension preferredlayoutsize(java.awt.container parent) { return parent.getpreferredsize(); } public void removelayoutcomponent(java.awt.component comp) {} public void layoutcontainer(java.awt.container parent) { c.setbounds(parent.getinsets().left, parent.getinsets().top, parent.getwidth() - parent.getinsets().left - parent.getinsets().right, parent.getheight() - parent.getinsets().top - parent.getinsets().bottom); } }; f.getcontentpane().setlayout(layer); try { bgimage = java.awt.toolkit.getdefaulttoolkit().createimage(getclass().getclassloader().getresource("images/background.jpg")); ensureimageisloaded(bgimage); logoimage = java.awt.toolkit.getdefaulttoolkit().createimage(getclass().getclassloader().getresource("images/sagelogo256.png")); ensureimageisloaded(logoimage); } catch (exception e) { system.out.println("error:" + e); e.printstacktrace(); } f.setfocustraversalkeysenabled(false); java.awt.dimension panelsize = f.getcontentpane().getsize(); c = new quartzrendererview(); c.setsize(panelsize); c.setfocustraversalkeysenabled(false); f.getcontentpane().add(c); try { java.awt.image frameicon = java.awt.toolkit.getdefaulttoolkit().createimage(getclass().getclassloader().getresource("images/tvicon.gif")); ensureimageisloaded(frameicon); f.seticonimage(frameicon); } catch (exception e) { system.out.println("error:" + e); e.printstacktrace(); } f.addwindowlistener(new java.awt.event.windowadapter() { public void windowclosing(java.awt.event.windowevent evt) { if (!f.isfullscreen() || system.getproperty("os.name").tolowercase().indexof("windows") != -1) { miniclient.myproperties.setproperty("main_window_width", integer.tostring(f.getwidth())); miniclient.myproperties.setproperty("main_window_height", integer.tostring(f.getheight())); miniclient.myproperties.setproperty("main_window_x", integer.tostring(f.getx())); miniclient.myproperties.setproperty("main_window_y", integer.tostring(f.gety())); } myconn.close(); close(); } }); c.addcomponentlistener(new java.awt.event.componentadapter() { public void componentresized(java.awt.event.componentevent evt) { myconn.postresizeevent(new java.awt.dimension(c.getwidth(), c.getheight())); } }); f.addkeylistener(this); c.addkeylistener(this); f.addmousewheellistener(this); c.addmouselistener(this); if (enable_mouse_motion_events) { c.addmousemotionlistener(this); } int framex = 100; int framey = 100; int framew = 720; int frameh = 480; try { framew = integer.parseint(miniclient.myproperties.getproperty("main_window_width", "720")); frameh = integer.parseint(miniclient.myproperties.getproperty("main_window_height", "480")); framex = integer.parseint(miniclient.myproperties.getproperty("main_window_x", "100")); framey = integer.parseint(miniclient.myproperties.getproperty("main_window_y", "100")); } catch (numberformatexception e){} java.awt.point newpos = new java.awt.point(framex, framey); boolean foundscreen = sage.uiutils.ispointonascreen(newpos); if (!foundscreen) { newpos.x = 150; newpos.y = 150; } f.setvisible(true); f.setsize(1,1); f.setsize(math.max(framew, 320), math.max(frameh, 240)); f.setlocation(newpos); if (miniclient.fsstartup) f.setfullscreen(true); miniclient.hidesplash(); return 1; case gfxcmd_deinit: close(); break; case gfxcmd_drawrect: if(len==36) { float x, y, width, height; int thickness, argbtl, argbtr, argbbr, argbbl; x=(float)readint(0, cmddata); y=(float)readint(4, cmddata); width=(float)readint(8, cmddata); height=(float)readint(12, cmddata); thickness=readint(16, cmddata); argbtl=readint(20, cmddata); argbtr=readint(24, cmddata); argbbr=readint(28, cmddata); argbbl=readint(32, cmddata); drawrect0(new java.awt.geom.rectangle2d.float(x, y, width, height), null, 0, new java.awt.color(argbtl, true), thickness, null, 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } else { system.out.println("invalid len for gfxcmd_drawrect : " + len); } break; case gfxcmd_fillrect: if(len==32) { float x, y, width, height; int argbtl, argbtr, argbbr, argbbl; x=(float)readint(0, cmddata); y=(float)readint(4, cmddata); width=(float)readint(8, cmddata); height=(float)readint(12, cmddata); argbtl=readint(16, cmddata); argbtr=readint(20, cmddata); argbbr=readint(24, cmddata); argbbl=readint(28, cmddata); java.awt.gradientpaint gp = getgradient(x, y, width, height, argbtl, argbtr, argbbl, argbbr); java.awt.geom.rectangle2d.float bounds = new java.awt.geom.rectangle2d.float(x, y, width, height); if(gp != null) { drawrect0(bounds, null, 0, null, 0, gp.getcolor1(), (float)gp.getpoint1().getx(), (float)gp.getpoint1().gety(), gp.getcolor2(), (float)gp.getpoint2().getx(), (float)gp.getpoint2().gety(), 1.0f); } else { drawrect0(bounds, null, 0, null, 0, new java.awt.color(argbtl, true), 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } } else { system.out.println("invalid len for gfxcmd_fillrect : " + len); } break; case gfxcmd_clearrect: if(len==32) { int x, y, width, height, argbtl, argbtr, argbbr, argbbl; x=readint(0, cmddata); y=readint(4, cmddata); width=readint(8, cmddata); height=readint(12, cmddata); argbtl=readint(16, cmddata); argbtr=readint(20, cmddata); argbbr=readint(24, cmddata); argbbl=readint(28, cmddata); java.awt.geom.rectangle2d.float destrect = new java.awt.geom.rectangle2d.float(x, y, width, height); clearrect0(destrect); } else { system.out.println("invalid len for gfxcmd_clearrect : " + len); } break; case gfxcmd_drawoval: if(len==52) { float x, y, width, height, clipx, clipy, clipw, cliph; int thickness, argbtl, argbtr, argbbr, argbbl; x=(float)readint(0, cmddata); y=(float)readint(4, cmddata); width=(float)readint(8, cmddata); height=(float)readint(12, cmddata); thickness=readint(16, cmddata); argbtl=readint(20, cmddata); argbtr=readint(24, cmddata); argbbr=readint(28, cmddata); argbbl=readint(32, cmddata); clipx=(float)readint(36, cmddata); clipy=(float)readint(40, cmddata); clipw=(float)readint(44, cmddata); cliph=(float)readint(48, cmddata); java.awt.geom.rectangle2d.float bounds = new java.awt.geom.rectangle2d.float(x, y, width, height); java.awt.geom.rectangle2d.float cliprect = new java.awt.geom.rectangle2d.float(clipx, clipy, clipw, cliph); drawoval0(bounds, cliprect, new java.awt.color(argbtl, true), thickness, null, 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } else { system.out.println("invalid len for gfxcmd_drawoval : " + len); } break; case gfxcmd_filloval: if(len==48) { float x, y, width, height, clipx, clipy, clipw, cliph; int argbtl, argbtr, argbbr, argbbl; x=(float)readint(0, cmddata); y=(float)readint(4, cmddata); width=(float)readint(8, cmddata); height=(float)readint(12, cmddata); argbtl=readint(16, cmddata); argbtr=readint(20, cmddata); argbbr=readint(24, cmddata); argbbl=readint(28, cmddata); clipx=(float)readint(32, cmddata); clipy=(float)readint(36, cmddata); clipw=(float)readint(40, cmddata); cliph=(float)readint(44, cmddata); java.awt.gradientpaint gp = getgradient(x, y, width, height, argbtl, argbtr, argbbl, argbbr); java.awt.geom.rectangle2d.float bounds = new java.awt.geom.rectangle2d.float(x, y, width, height); java.awt.geom.rectangle2d.float cliprect = new java.awt.geom.rectangle2d.float(clipx, clipy, clipw, cliph); if(gp != null) { drawoval0(bounds, cliprect, null, 0, gp.getcolor1(), (float)gp.getpoint1().getx(), (float)gp.getpoint1().gety(), gp.getcolor2(), (float)gp.getpoint2().getx(), (float)gp.getpoint2().gety(), 1.0f); } else { drawoval0(bounds, cliprect, null, 0, new java.awt.color(argbtl, true), 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } } else { system.out.println("invalid len for gfxcmd_filloval : " + len); } break; case gfxcmd_drawroundrect: if(len==56) { float x, y, width, height, clipx, clipy, clipw, cliph; int thickness, arcradius, argbtl, argbtr, argbbr, argbbl; x=(float)readint(0, cmddata); y=(float)readint(4, cmddata); width=(float)readint(8, cmddata); height=(float)readint(12, cmddata); thickness=readint(16, cmddata); arcradius=readint(20, cmddata); argbtl=readint(24, cmddata); argbtr=readint(28, cmddata); argbbr=readint(32, cmddata); argbbl=readint(36, cmddata); clipx=(float)readint(40, cmddata); clipy=(float)readint(44, cmddata); clipw=(float)readint(48, cmddata); cliph=(float)readint(52, cmddata); java.awt.geom.rectangle2d.float bounds = new java.awt.geom.rectangle2d.float(x, y, width, height); java.awt.geom.rectangle2d.float cliprect = new java.awt.geom.rectangle2d.float(clipx, clipy, clipw, cliph); drawrect0(bounds, cliprect, arcradius, new java.awt.color(argbtl, true), thickness, null, 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } else { system.out.println("invalid len for gfxcmd_drawroundrect : " + len); } break; case gfxcmd_fillroundrect: if(len==52) { float x, y, width, height, clipx, clipy, clipw, cliph; int arcradius, argbtl, argbtr, argbbr, argbbl; x=(float)readint(0, cmddata); y=(float)readint(4, cmddata); width=(float)readint(8, cmddata); height=(float)readint(12, cmddata); arcradius=readint(16, cmddata); argbtl=readint(20, cmddata); argbtr=readint(24, cmddata); argbbr=readint(28, cmddata); argbbl=readint(32, cmddata); clipx=(float)readint(36, cmddata); clipy=(float)readint(40, cmddata); clipw=(float)readint(44, cmddata); cliph=(float)readint(48, cmddata); java.awt.gradientpaint gp = getgradient(x, y, width, height, argbtl, argbtr, argbbl, argbbr); java.awt.geom.rectangle2d.float bounds = new java.awt.geom.rectangle2d.float(x, y, width, height); java.awt.geom.rectangle2d.float cliprect = new java.awt.geom.rectangle2d.float(clipx, clipy, clipw, cliph); if(gp != null) { drawrect0(bounds, cliprect, arcradius, null, 0, gp.getcolor1(), (float)gp.getpoint1().getx(), (float)gp.getpoint1().gety(), gp.getcolor2(), (float)gp.getpoint2().getx(), (float)gp.getpoint2().gety(), 1.0f); } else { drawrect0(bounds, cliprect, arcradius, null, 0, new java.awt.color(argbtl, true), 0.0f, 0.0f, null, 0.0f, 0.0f, 1.0f); } } else { system.out.println("invalid len for gfxcmd_fillroundrect : " + len); } break; case gfxcmd_drawtext: if(len>=36 && len>=(36+readint(8, cmddata)*2)) { float x, y, clipx, clipy, clipw, cliph; int textlen, fonthandle, argb; stringbuffer text = new stringbuffer(); int i; x=(float)readint(0, cmddata); y=(float)readint(4, cmddata); textlen=readint(8, cmddata); for(i=0;i<textlen;i++) { text.append((char)readshort(12+i*2, cmddata)); } fonthandle=readint(textlen*2+12, cmddata); argb=readint(textlen*2+16, cmddata); clipx=(float)readint(textlen*2+20, cmddata); clipy=(float)readint(textlen*2+24, cmddata); clipw=(float)readint(textlen*2+28, cmddata); cliph=(float)readint(textlen*2+32, cmddata); mcfont fontptr = (mcfont)fontmap.get(new integer(fonthandle)); if(fontptr != null) { string thestring = text.tostring(); float[] positions = fontptr.getglyphpositions(thestring); drawtextwithpositions0(thestring, fontptr.nativefont, x, y, positions, new java.awt.geom.rectangle2d.float(clipx,clipy,clipw,cliph), new java.awt.color(argb, true)); } } else { system.out.println("invalid len for gfxcmd_drawtext : " + len); } break; case gfxcmd_drawtextured: if(len==40) { float x, y, width, height, srcx, srcy, srcwidth, srcheight; int handle, blend; x=(float)readint(0, cmddata); y=(float)readint(4, cmddata); width=(float)readint(8, cmddata); height=(float)readint(12, cmddata); handle=readint(16, cmddata); srcx=(float)readint(20, cmddata); srcy=(float)readint(24, cmddata); srcwidth=(float)readint(28, cmddata); srcheight=(float)readint(32, cmddata); blend=readint(36, cmddata); boolean doblend = true; if(height < 0) { doblend = false; height *= -1; } if(width < 0) { width *= -1; } else { if(doblend) blend |= 0x00ffffff; } long imageptr = (long)imagemap.get(new integer(handle)); java.awt.geom.rectangle2d.float destrect = new java.awt.geom.rectangle2d.float(x,y,width,height); java.awt.geom.rectangle2d.float srcrect = new java.awt.geom.rectangle2d.float(srcx,srcy,srcwidth,srcheight); if(imageptr != null) { myconn.registerimageaccess(handle); drawimage1(imageptr.longvalue(), destrect, srcrect, (doblend) ? new java.awt.color(blend, true) : null); } else { imageptr = (long)layermap.get(new integer(handle)); if(imageptr != null) { myconn.registerimageaccess(handle); float alpha = (doblend ? (float)(((blend >> 24)&0xff))/255.0f : 1.0f); composite0(imageptr.longvalue(), currentlayer, srcrect, destrect, alpha, doblend); } else { system.out.println("error invalid handle passed for texture rendering of: " + handle); abortrendercycle = true; } } } else { system.out.println("invalid len for gfxcmd_drawtextured : " + len); } break; case gfxcmd_drawline: if(len==24) { float x1, y1, x2, y2; int argb1, argb2; x1=readint(0, cmddata); y1=readint(4, cmddata); x2=readint(8, cmddata); y2=readint(12, cmddata); argb1=readint(16, cmddata); argb2=readint(20, cmddata); drawline0(x1, y1, x2, y2, 1, new java.awt.color(argb1, true)); } else { system.out.println("invalid len for gfxcmd_drawline : " + len); } break; case gfxcmd_loadimage: if(len>=8) { int width, height; int imghandle = 0; width=readint(0, cmddata); height=readint(4, cmddata); if (width * height * 4 + imagecachesize > imagecachelimit) { imghandle = 0; } else { long imageptr = createnewimage0(width, height); imghandle = handlecount++; imagemap.put(new integer(imghandle), new long(imageptr)); imagecachesize += width * height * 4; } hasret[0]=1; return imghandle; } else { system.out.println("invalid len for gfxcmd_loadimage : " + len); } break; case gfxcmd_loadimagetargeted: if(len>=12) { int width, height; int imghandle = readint(0, cmddata); width=readint(4, cmddata); height=readint(8, cmddata); while (width * height * 4 + imagecachesize > imagecachelimit) { int oldestimage = myconn.getoldestimage(); if (oldestimage != 0) { system.out.println("freeing image to make room in cache"); unloadimage(oldestimage); myconn.postimageunload(oldestimage); } else { system.out.println("error cannot free enough from the cache to support loading a new image!!!"); break; } } long imageptr = createnewimage0(width, height); imagemap.put(new integer(imghandle), new long(imageptr)); imagecachesize += width * height * 4; myconn.registerimageaccess(imghandle); hasret[0]=0; } else { system.out.println("invalid len for gfxcmd_loadimagetargeted : " + len); } break; case gfxcmd_createsurface: if(len>=8) { int width, height; int handle = handlecount++;; width=readint(0, cmddata); height=readint(4, cmddata); long layerptr = createlayer0(c.getsize()); layermap.put(new integer(handle), new long(layerptr)); hasret[0]=1; return handle; } else { system.out.println("invalid len for gfxcmd_createsurface : " + len); } break; case gfxcmd_prepimage: if(len>=8) { int width, height; width=readint(0, cmddata); height=readint(4, cmddata); int imghandle = 1; if (width * height * 4 + imagecachesize > imagecachelimit) imghandle = 0; else if (len >= 12) { int strlen = readint(8, cmddata); if (strlen > 1) { string rezname = new string(cmddata, 16, strlen - 1); lastimageresourceid = rezname; lastimageresourceidhandle = imghandle = math.abs(lastimageresourceid.hashcode()); java.io.file cachedfile = myconn.getcachedimagefile(rezname); if (cachedfile != null) { long imageptr = createimagefrompath0(cachedfile.getabsolutepath()); if(imageptr != 0) { java.awt.dimension imgsize = getimagedimensions0(imageptr); if(imgsize != null) { if(imgsize.getwidth() == width && imgsize.getheight() == height) { imghandle = handlecount++; imagemap.put(new integer(imghandle), new long(imageptr)); imagecachesize += getimagesize0(imageptr); hasret[0] = 1; return -1 * imghandle; } else freenativeimage0(imageptr); } else freenativeimage0(imageptr); } } } } hasret[0]=1; return imghandle; } else { system.out.println("invalid len for gfxcmd_prepimage : " + len); } break; case gfxcmd_prepimagetargeted: if(len>=12) { int imghandle, width, height; imghandle = readint(0, cmddata); width=readint(4, cmddata); height=readint(8, cmddata); int strlen = readint(12, cmddata); while (width * height * 4 + imagecachesize > imagecachelimit) { int oldestimage = myconn.getoldestimage(); if (oldestimage != 0) { system.out.println("freeing image to make room in cache"); unloadimage(oldestimage); myconn.postimageunload(oldestimage); } else { system.out.println("error cannot free enough from the cache to support loading a new image!!!"); break; } } if (len >= 16) { string rezname = new string(cmddata, 20, strlen - 1); lastimageresourceid = rezname; lastimageresourceidhandle = imghandle; system.out.println("prepped targeted image with handle " + imghandle + " resource=" + rezname); } myconn.registerimageaccess(imghandle); hasret[0]=0; } else { system.out.println("invalid len for gfxcmd_prepimage : " + len); } break; case gfxcmd_loadcachedimage: if(len>=18) { int width, height, imghandle; imghandle = readint(0, cmddata); width = readint(4, cmddata); height = readint(8, cmddata); int strlen = readint(12, cmddata); string rezname = new string(cmddata, 20, strlen - 1); system.out.println("imghandle=" + imghandle + " width=" + width + " height=" + height + " strlen=" + strlen + " rezname=" + rezname); while (width * height * 4 + imagecachesize > imagecachelimit) { int oldestimage = myconn.getoldestimage(); if (oldestimage != 0) { system.out.println("freeing image to make room in cache"); unloadimage(oldestimage); myconn.postimageunload(oldestimage); } else { system.out.println("error cannot free enough from the cache to support loading a new image!!!"); break; } } myconn.registerimageaccess(imghandle); try { system.out.println("loading resource from cache: " + rezname); java.io.file cachedfile = myconn.getcachedimagefile(rezname); if (cachedfile != null) { system.out.println("image found in cache!"); long imageptr = createimagefrompath0(cachedfile.getabsolutepath()); if(imageptr != 0) { java.awt.dimension imgsize = getimagedimensions0(imageptr); if(imgsize != null && imgsize.getwidth() == width && imgsize.getheight() == height) { imagemap.put(new integer(imghandle), new long(imageptr)); imagecachesize += getimagesize0(imageptr); } else { if (imgsize != null) { system.out.println("cache id verification failed for rezname=" + rezname + " target=" + width + "x" + height + " actual=" + imgsize.getwidth() + "x" + imgsize.getheight()); } else system.out.println("cache load failed for rezname=" + rezname); cachedfile.delete(); freenativeimage0(imageptr); myconn.postimageunload(imghandle); myconn.postofflinecachechange(false, rezname); } } else { cachedfile.delete(); myconn.postimageunload(imghandle); myconn.postofflinecachechange(false, rezname); } } else { system.out.println("error image not found in cache that should be there! rezname=" + rezname); myconn.postimageunload(imghandle); myconn.postofflinecachechange(false, rezname); } } catch (java.io.ioexception e) { system.out.println("error loading compressed image: " + e); } hasret[0]=0; } else { system.out.println("invalid len for gfxcmd_prepimage : " + len); } break; case gfxcmd_unloadimage: if(len==4) { int handle; handle=readint(0, cmddata); unloadimage(handle); myconn.clearimageaccess(handle); } else { system.out.println("invalid len for gfxcmd_unloadimage : " + len); } break; case gfxcmd_settargetsurface: if(len==4) { int handle; handle=readint(0, cmddata); long layerptr = (long)layermap.get(new integer(handle)); currentlayer = (layerptr != null) ? layerptr.longvalue() : 0; java.awt.rectangle cliprect = new java.awt.rectangle(0, 0, c.getwidth(), c.getheight()); setlayer0(currentlayer, c.getsize(), cliprect); } else { system.out.println("invalid len for gfxcmd_settargetsurface : " + len); } break; case gfxcmd_loadfont: if(len>=12 && len>=(12+readint(0, cmddata))) { int namelen, style, size; stringbuffer name = new stringbuffer(); int i; int fonthandle = handlecount++; namelen=readint(0, cmddata); for(i=0;i<namelen-1;i++) { name.append((char) cmddata[8 + i]); } style=readint(namelen+4, cmddata); size=readint(namelen+8, cmddata); mcfont fontptr = new mcfont(name.tostring(), style, size); if(fontptr == null) { hasret[0] = 1; return 0; } fontmap.put(new integer(fonthandle), fontptr); hasret[0] = 1; return fonthandle; } else { system.out.println("invalid len for gfxcmd_loadfont : " + len); } break; case gfxcmd_unloadfont: if(len==4) { int handle; handle=readint(0, cmddata); mcfont fontptr = (mcfont)fontmap.get(new integer(handle)); if(fontptr != null) fontptr.unload(); fontmap.remove(new integer(handle)); } else { system.out.println("invalid len for gfxcmd_unloadfont : " + len); } break; case gfxcmd_loadfontstream: if (len>=8) { stringbuffer name = new stringbuffer(); int namelen = readint(0, cmddata); for(int i=0;i<namelen-1;i++) { name.append((char) cmddata[8 + i]); } int datalen = readint(4 + namelen, cmddata); if (len >= datalen + 8 + namelen) { myconn.savecachedata(name.tostring() + "-" + myconn.getservername(), cmddata, 12 + namelen, datalen); } } else { system.out.println("invalid len for gfxcmd_loadfontstream : " + len); } break; case gfxcmd_flipbuffer: if (abortrendercycle) { system.out.println("error in painting cycle, abort was set...send full repaint command"); myconn.postrepaintevent(0, 0, c.getwidth(), c.getheight()); } else { present0(c.nativeview, new java.awt.rectangle(0, 0, c.getwidth(), c.getheight())); } hasret[0] = 1; firstframedone = true; return 0; case gfxcmd_startframe: settargetview0(c.nativeview); setlayer0(0, c.getsize(), null); abortrendercycle = false; break; case gfxcmd_loadimageline: if(len>=12 && len>=(12+readint(8, cmddata))) { int handle, line, len2; handle=readint(0, cmddata); line=readint(4, cmddata); len2=readint(8, cmddata); long imageptr = (long)imagemap.get(new integer(handle)); if(imageptr != null) loadimageline0(imageptr.longvalue(), line, cmddata, 1, len2); myconn.registerimageaccess(handle); } else { system.out.println("invalid len for gfxcmd_loadimageline : " + len); } break; case gfxcmd_loadimagecompressed: if(len>=8 && len>=(8+readint(4, cmddata))) { int handle, len2; handle=readint(0, cmddata); len2=readint(4, cmddata); if (lastimageresourceid != null && lastimageresourceidhandle == handle) { myconn.savecachedata(lastimageresourceid, cmddata, 12, len2); myconn.postofflinecachechange(true, lastimageresourceid); } if (!myconn.doesuseadvancedimagecaching()) { handle = handlecount++; hasret[0] = 1; } else hasret[0] = 0; myconn.registerimageaccess(handle); long imageptr = createimagefrombytes0(cmddata, 12, len2, null); imagemap.put(new integer(handle), new long(imageptr)); imagecachesize += getimagesize0(imageptr); return handle; } else { system.out.println("invalid len for gfxcmd_loadimagecompressed : " + len); } break; case gfxcmd_xfmimage: if (len >= 20) { int srchandle, desthandle, destwidth, destheight, maskcornerarc; srchandle = readint(0, cmddata); desthandle = readint(4, cmddata); destwidth = readint(8, cmddata); destheight = readint(12, cmddata); maskcornerarc = readint(16, cmddata); int rvhandle = desthandle; if (!myconn.doesuseadvancedimagecaching()) { rvhandle = handlecount++; hasret[0] = 1; } else hasret[0] = 0; long srcimg = (long)imagemap.get(new integer(srchandle)); if(srcimg != null) { long newimage = transformimage0(srcimg.longvalue(), destwidth, destheight, maskcornerarc); if(newimage != 0) { imagemap.put(new integer(rvhandle), new long(newimage)); } } return rvhandle; } else { system.out.println("invalid len for gfxcmd_xfmimage : " + len); } break; case gfxcmd_setvideoprop: if (len >= 40) { java.awt.rectangle srcrect = new java.awt.rectangle(readint(4, cmddata), readint(8, cmddata), readint(12, cmddata), readint(16, cmddata)); java.awt.rectangle destrect = new java.awt.rectangle(readint(20, cmddata), readint(24, cmddata), readint(28, cmddata), readint(32, cmddata)); system.out.println("setvideoprop: srcrect="+srcrect+" dstrect="+destrect); setvideobounds(srcrect, destrect); } else { system.out.println("invalid len for gfxcmd_setvideoprop: " + len); } break; default: return -1; } return 0; }
Narflex/sagetv
[ 1, 0, 1, 0 ]
7,810
public boolean isOvertaking() { if (overtakeStage != OvertakeStage.NOT_OVERTAKING) { return true; } else { return false; } }
public boolean isOvertaking() { if (overtakeStage != OvertakeStage.NOT_OVERTAKING) { return true; } else { return false; } }
public boolean isovertaking() { if (overtakestage != overtakestage.not_overtaking) { return true; } else { return false; } }
RobAlexander/SCovSGen
[ 0, 1, 0, 0 ]
16,039
public static List<String> generateParenthesis1(int n) { Set<String>[] dp = new Set[n + 1]; Set<String> first = new HashSet<>(); first.add(""); dp[0] = first; for (int i = 1; i <= n; i++) { Set<String> set = new HashSet<>(); for (String pre : dp[i - 1]) { set.add("(" + pre + ")"); } for (int m = 1; m < i; m++) { for (String p1 : dp[m]) { for (String p2 : dp[i - m]) { set.add(p1 + p2); set.add(p2 + p1); } } } dp[i] = set; } return new ArrayList<>(dp[n]); }
public static List<String> generateParenthesis1(int n) { Set<String>[] dp = new Set[n + 1]; Set<String> first = new HashSet<>(); first.add(""); dp[0] = first; for (int i = 1; i <= n; i++) { Set<String> set = new HashSet<>(); for (String pre : dp[i - 1]) { set.add("(" + pre + ")"); } for (int m = 1; m < i; m++) { for (String p1 : dp[m]) { for (String p2 : dp[i - m]) { set.add(p1 + p2); set.add(p2 + p1); } } } dp[i] = set; } return new ArrayList<>(dp[n]); }
public static list<string> generateparenthesis1(int n) { set<string>[] dp = new set[n + 1]; set<string> first = new hashset<>(); first.add(""); dp[0] = first; for (int i = 1; i <= n; i++) { set<string> set = new hashset<>(); for (string pre : dp[i - 1]) { set.add("(" + pre + ")"); } for (int m = 1; m < i; m++) { for (string p1 : dp[m]) { for (string p2 : dp[i - m]) { set.add(p1 + p2); set.add(p2 + p1); } } } dp[i] = set; } return new arraylist<>(dp[n]); }
Joybeanx/leetcode
[ 1, 0, 0, 0 ]
24,717
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { Study study = ControllerUtil.findStudy(request, mStudyService); Submission submission = (Submission) study.getSubmission(); StudyCommand studyCommand = new StudyCommand(); // copy study information studyCommand.setStudy(study); // study from TBI do not contain submission_id if (submission != null) { studyCommand.setSubmission_id(submission.getId()); } List<Analysis> analysisList = study.getAnalyses(); List<AnalysisCommand> analysisCommandList = new ArrayList<AnalysisCommand>(); List<Analysis> changedAnalyses = new ArrayList<Analysis>(); StringBuilder errBuilder = new StringBuilder(); for (Analysis analysis : analysisList) { // FIXME: next if block needs to me moved to the onSumbit method when // we this controller will extend BaseFormController. if (!analysis.getValidated()) { ExecutionResult result = analysis.validate(); if (!result.isSuccessful()) { errBuilder.append(result.getErrorMessage()); } if (analysis.getValidated()) { // save to db if the validated flag is updated: changedAnalyses.add(analysis); } } //FIXME: display err message in GUI if (LOGGER.isDebugEnabled()) { LOGGER.debug(errBuilder.toString()); //$NON-NLS-1$ } // // Analysis AnalysisCommand analysisCommand = new AnalysisCommand(); BeanUtils.copyProperties(analysisCommand, analysis); // Analysis Steps for Analysis and add algorithm type List<AnalysisStep> analysisStepList = analysis.getAnalysisStepsReadOnly(); List<AnalysisStepCommand> analysisStepCommandList = new ArrayList<AnalysisStepCommand>(); for (AnalysisStep analysisStep : analysisStepList) { AnalysisStepCommand analysisStepCommand = new AnalysisStepCommand(); BeanUtils.copyProperties(analysisStepCommand, analysisStep); // analysisStepCommand.setId(analysisStep.getId()); // analysisStepCommand.setSoftwareInfo(analysisStep.getSoftwareInfo()); Algorithm algorithm = analysisStep.getAlgorithmInfo(); String algorithmType = new String(); if (algorithm instanceof LikelihoodAlgorithm) { algorithmType = Constants.ALGORITHM_LIKELIHOOD; } else if (algorithm instanceof ParsimonyAlgorithm) { algorithmType = Constants.ALGORITHM_PARSIMONY; } else if (algorithm instanceof OtherAlgorithm) { algorithmType = Constants.ALGORITHM_OTHER; }else if (algorithm instanceof BayesianAlgorithm) { algorithmType = Constants.ALGORITHM_Bayesian; } else if (algorithm instanceof EvolutionAlgorithm) { algorithmType = Constants.ALGORITHM_Evolution; } else if (algorithm instanceof JoiningAlgorithm) { algorithmType = Constants.ALGORITHM_Joining; } else if (algorithm instanceof UPGMAAlgorithm) { algorithmType = Constants.ALGORITHM_UPGMA; } // add algorithm type for analysisStepCommand analysisStepCommand.setAlgorithmType(algorithmType); // analyzed data for each analysis step List<AnalyzedData> analyzedDataSet = analysisStep.getDataSetReadOnly(); List<AnalyzedDataCommand> analyzedDataCommandList = new ArrayList<AnalyzedDataCommand>(); // Matrix or Tree? for (AnalyzedData analyzedData : analyzedDataSet) { AnalyzedDataCommand analyzedDataCommand = new AnalyzedDataCommand(); BeanUtils.copyProperties(analyzedDataCommand, analyzedData); String inputOutput = (analyzedData.isInputData()) ? ("Input") : ("Output"); analyzedDataCommand.setInputOutputType(inputOutput); if (analyzedData instanceof AnalyzedMatrix) { AnalyzedMatrix analyzedMatrix = (AnalyzedMatrix) analyzedData; analyzedDataCommand.setDataType(Constants.MATRIX_KEY); analyzedDataCommand.setDisplayName(analyzedMatrix.getMatrix().getTitle()); analyzedDataCommand.setId(analyzedMatrix.getId()); analyzedDataCommand.setDataId(analyzedMatrix.getMatrix().getId()); } else if (analyzedData instanceof AnalyzedTree) { AnalyzedTree analyzedTree = (AnalyzedTree) analyzedData; analyzedDataCommand.setDataType(Constants.TREE_KEY); analyzedDataCommand.setDisplayName(analyzedTree.getTree().getLabel()); analyzedDataCommand.setId(analyzedTree.getId()); analyzedDataCommand.setDataId(analyzedTree.getTree().getId()); } analyzedDataCommandList.add(analyzedDataCommand); } // end for // add analyzedData for analysisStepCommand Collections.sort(analyzedDataCommandList, new AnalyzedDataComparator()); analysisStepCommand.setAnalyzedDataCommandList(analyzedDataCommandList); analysisStepCommandList.add(analysisStepCommand); } analysisCommand.setAnalysisStepCommandList(analysisStepCommandList); analysisCommandList.add(analysisCommand); } getStudyService().updateCollection(changedAnalyses); studyCommand.setAnalysisCommandList(analysisCommandList); return new ModelAndView("analysisSection", Constants.STUDY_COMMAND_KEY, studyCommand); }
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { Study study = ControllerUtil.findStudy(request, mStudyService); Submission submission = (Submission) study.getSubmission(); StudyCommand studyCommand = new StudyCommand(); studyCommand.setStudy(study); if (submission != null) { studyCommand.setSubmission_id(submission.getId()); } List<Analysis> analysisList = study.getAnalyses(); List<AnalysisCommand> analysisCommandList = new ArrayList<AnalysisCommand>(); List<Analysis> changedAnalyses = new ArrayList<Analysis>(); StringBuilder errBuilder = new StringBuilder(); for (Analysis analysis : analysisList) { if (!analysis.getValidated()) { ExecutionResult result = analysis.validate(); if (!result.isSuccessful()) { errBuilder.append(result.getErrorMessage()); } if (analysis.getValidated()) { changedAnalyses.add(analysis); } } if (LOGGER.isDebugEnabled()) { LOGGER.debug(errBuilder.toString()); } AnalysisCommand analysisCommand = new AnalysisCommand(); BeanUtils.copyProperties(analysisCommand, analysis); List<AnalysisStep> analysisStepList = analysis.getAnalysisStepsReadOnly(); List<AnalysisStepCommand> analysisStepCommandList = new ArrayList<AnalysisStepCommand>(); for (AnalysisStep analysisStep : analysisStepList) { AnalysisStepCommand analysisStepCommand = new AnalysisStepCommand(); BeanUtils.copyProperties(analysisStepCommand, analysisStep); Algorithm algorithm = analysisStep.getAlgorithmInfo(); String algorithmType = new String(); if (algorithm instanceof LikelihoodAlgorithm) { algorithmType = Constants.ALGORITHM_LIKELIHOOD; } else if (algorithm instanceof ParsimonyAlgorithm) { algorithmType = Constants.ALGORITHM_PARSIMONY; } else if (algorithm instanceof OtherAlgorithm) { algorithmType = Constants.ALGORITHM_OTHER; }else if (algorithm instanceof BayesianAlgorithm) { algorithmType = Constants.ALGORITHM_Bayesian; } else if (algorithm instanceof EvolutionAlgorithm) { algorithmType = Constants.ALGORITHM_Evolution; } else if (algorithm instanceof JoiningAlgorithm) { algorithmType = Constants.ALGORITHM_Joining; } else if (algorithm instanceof UPGMAAlgorithm) { algorithmType = Constants.ALGORITHM_UPGMA; } analysisStepCommand.setAlgorithmType(algorithmType); List<AnalyzedData> analyzedDataSet = analysisStep.getDataSetReadOnly(); List<AnalyzedDataCommand> analyzedDataCommandList = new ArrayList<AnalyzedDataCommand>(); for (AnalyzedData analyzedData : analyzedDataSet) { AnalyzedDataCommand analyzedDataCommand = new AnalyzedDataCommand(); BeanUtils.copyProperties(analyzedDataCommand, analyzedData); String inputOutput = (analyzedData.isInputData()) ? ("Input") : ("Output"); analyzedDataCommand.setInputOutputType(inputOutput); if (analyzedData instanceof AnalyzedMatrix) { AnalyzedMatrix analyzedMatrix = (AnalyzedMatrix) analyzedData; analyzedDataCommand.setDataType(Constants.MATRIX_KEY); analyzedDataCommand.setDisplayName(analyzedMatrix.getMatrix().getTitle()); analyzedDataCommand.setId(analyzedMatrix.getId()); analyzedDataCommand.setDataId(analyzedMatrix.getMatrix().getId()); } else if (analyzedData instanceof AnalyzedTree) { AnalyzedTree analyzedTree = (AnalyzedTree) analyzedData; analyzedDataCommand.setDataType(Constants.TREE_KEY); analyzedDataCommand.setDisplayName(analyzedTree.getTree().getLabel()); analyzedDataCommand.setId(analyzedTree.getId()); analyzedDataCommand.setDataId(analyzedTree.getTree().getId()); } analyzedDataCommandList.add(analyzedDataCommand); } Collections.sort(analyzedDataCommandList, new AnalyzedDataComparator()); analysisStepCommand.setAnalyzedDataCommandList(analyzedDataCommandList); analysisStepCommandList.add(analysisStepCommand); } analysisCommand.setAnalysisStepCommandList(analysisStepCommandList); analysisCommandList.add(analysisCommand); } getStudyService().updateCollection(changedAnalyses); studyCommand.setAnalysisCommandList(analysisCommandList); return new ModelAndView("analysisSection", Constants.STUDY_COMMAND_KEY, studyCommand); }
public modelandview handlerequest(httpservletrequest request, httpservletresponse response) throws exception { study study = controllerutil.findstudy(request, mstudyservice); submission submission = (submission) study.getsubmission(); studycommand studycommand = new studycommand(); studycommand.setstudy(study); if (submission != null) { studycommand.setsubmission_id(submission.getid()); } list<analysis> analysislist = study.getanalyses(); list<analysiscommand> analysiscommandlist = new arraylist<analysiscommand>(); list<analysis> changedanalyses = new arraylist<analysis>(); stringbuilder errbuilder = new stringbuilder(); for (analysis analysis : analysislist) { if (!analysis.getvalidated()) { executionresult result = analysis.validate(); if (!result.issuccessful()) { errbuilder.append(result.geterrormessage()); } if (analysis.getvalidated()) { changedanalyses.add(analysis); } } if (logger.isdebugenabled()) { logger.debug(errbuilder.tostring()); } analysiscommand analysiscommand = new analysiscommand(); beanutils.copyproperties(analysiscommand, analysis); list<analysisstep> analysissteplist = analysis.getanalysisstepsreadonly(); list<analysisstepcommand> analysisstepcommandlist = new arraylist<analysisstepcommand>(); for (analysisstep analysisstep : analysissteplist) { analysisstepcommand analysisstepcommand = new analysisstepcommand(); beanutils.copyproperties(analysisstepcommand, analysisstep); algorithm algorithm = analysisstep.getalgorithminfo(); string algorithmtype = new string(); if (algorithm instanceof likelihoodalgorithm) { algorithmtype = constants.algorithm_likelihood; } else if (algorithm instanceof parsimonyalgorithm) { algorithmtype = constants.algorithm_parsimony; } else if (algorithm instanceof otheralgorithm) { algorithmtype = constants.algorithm_other; }else if (algorithm instanceof bayesianalgorithm) { algorithmtype = constants.algorithm_bayesian; } else if (algorithm instanceof evolutionalgorithm) { algorithmtype = constants.algorithm_evolution; } else if (algorithm instanceof joiningalgorithm) { algorithmtype = constants.algorithm_joining; } else if (algorithm instanceof upgmaalgorithm) { algorithmtype = constants.algorithm_upgma; } analysisstepcommand.setalgorithmtype(algorithmtype); list<analyzeddata> analyzeddataset = analysisstep.getdatasetreadonly(); list<analyzeddatacommand> analyzeddatacommandlist = new arraylist<analyzeddatacommand>(); for (analyzeddata analyzeddata : analyzeddataset) { analyzeddatacommand analyzeddatacommand = new analyzeddatacommand(); beanutils.copyproperties(analyzeddatacommand, analyzeddata); string inputoutput = (analyzeddata.isinputdata()) ? ("input") : ("output"); analyzeddatacommand.setinputoutputtype(inputoutput); if (analyzeddata instanceof analyzedmatrix) { analyzedmatrix analyzedmatrix = (analyzedmatrix) analyzeddata; analyzeddatacommand.setdatatype(constants.matrix_key); analyzeddatacommand.setdisplayname(analyzedmatrix.getmatrix().gettitle()); analyzeddatacommand.setid(analyzedmatrix.getid()); analyzeddatacommand.setdataid(analyzedmatrix.getmatrix().getid()); } else if (analyzeddata instanceof analyzedtree) { analyzedtree analyzedtree = (analyzedtree) analyzeddata; analyzeddatacommand.setdatatype(constants.tree_key); analyzeddatacommand.setdisplayname(analyzedtree.gettree().getlabel()); analyzeddatacommand.setid(analyzedtree.getid()); analyzeddatacommand.setdataid(analyzedtree.gettree().getid()); } analyzeddatacommandlist.add(analyzeddatacommand); } collections.sort(analyzeddatacommandlist, new analyzeddatacomparator()); analysisstepcommand.setanalyzeddatacommandlist(analyzeddatacommandlist); analysisstepcommandlist.add(analysisstepcommand); } analysiscommand.setanalysisstepcommandlist(analysisstepcommandlist); analysiscommandlist.add(analysiscommand); } getstudyservice().updatecollection(changedanalyses); studycommand.setanalysiscommandlist(analysiscommandlist); return new modelandview("analysissection", constants.study_command_key, studycommand); }
TreeBASE/treebasetest
[ 0, 1, 1, 0 ]
148
private void addVar(Varlet v){ long key=key(v.chromosome, v.beginLoc); ArrayList<Varlet> list=keymap.get(key); assert(list!=null) : "\nCan't find "+key+" in "+keymap.keySet()+"\n"; synchronized(list){ list.add(v); if(list.size()>=WRITE_BUFFER){ if(MERGE_EQUAL_VARLETS){ mergeEqualVarlets(list); }else{ Collections.sort(list); } writeList(list); list.clear(); } } }
private void addVar(Varlet v){ long key=key(v.chromosome, v.beginLoc); ArrayList<Varlet> list=keymap.get(key); assert(list!=null) : "\nCan't find "+key+" in "+keymap.keySet()+"\n"; synchronized(list){ list.add(v); if(list.size()>=WRITE_BUFFER){ if(MERGE_EQUAL_VARLETS){ mergeEqualVarlets(list); }else{ Collections.sort(list); } writeList(list); list.clear(); } } }
private void addvar(varlet v){ long key=key(v.chromosome, v.beginloc); arraylist<varlet> list=keymap.get(key); assert(list!=null) : "\ncan't find "+key+" in "+keymap.keyset()+"\n"; synchronized(list){ list.add(v); if(list.size()>=write_buffer){ if(merge_equal_varlets){ mergeequalvarlets(list); }else{ collections.sort(list); } writelist(list); list.clear(); } } }
SilasK/BBMap
[ 1, 0, 0, 0 ]
16,664
private NiceWebDriver getNiceWebDriverInstance(DriverType driverType, Object[] oArgs){ switch(driverType) { case Chrome: return new NiceChrome().UnderloadedNiceWebDriverConstructor(oArgs).getThisWithVerbositySetTo(outputIsVerbose); case Firefox: return null; //TODO: Make Firefox subclass case IE: return null; //TODO: Make IE subclass case Edge: return null; //TODO: Make Edge subclass case Opera: return null; //TODO: Make Opera subclass case Safari: return null; //TODO: Make Safari subclass case iOS_iPhone: return null; //TODO: Make iOS_iPhone subclass case iOS_iPad: return null; //TODO: Make iOS_iPad subclass case Android: return null; //TODO: Make Android subclass case HtmlUnit: return null; //TODO: Make HtmlUnit subclass default: return null; } }
private NiceWebDriver getNiceWebDriverInstance(DriverType driverType, Object[] oArgs){ switch(driverType) { case Chrome: return new NiceChrome().UnderloadedNiceWebDriverConstructor(oArgs).getThisWithVerbositySetTo(outputIsVerbose); case Firefox: return null; case IE: return null; case Edge: return null; case Opera: return null; case Safari: return null; case iOS_iPhone: return null; case iOS_iPad: return null; case Android: return null; case HtmlUnit: return null; default: return null; } }
private nicewebdriver getnicewebdriverinstance(drivertype drivertype, object[] oargs){ switch(drivertype) { case chrome: return new nicechrome().underloadednicewebdriverconstructor(oargs).getthiswithverbositysetto(outputisverbose); case firefox: return null; case ie: return null; case edge: return null; case opera: return null; case safari: return null; case ios_iphone: return null; case ios_ipad: return null; case android: return null; case htmlunit: return null; default: return null; } }
Skenvy/SeleniumNG
[ 0, 1, 0, 0 ]
33,149
private void tag() throws Exception { String[] asFilename = (String[])m_oCmdLineMap.get("filenames"); for (int i=0; i < asFilename.length; i++) { File oSourceFile = new File(asFilename[i]); MP3File oMP3File = new MP3File(oSourceFile); if (m_oCmdLineMap.containsKey("1")) { ID3V1_1Tag oID3V1_1Tag = new ID3V1_1Tag(); if (m_oCmdLineMap.containsKey("album")) { oID3V1_1Tag.setAlbum((String)m_oCmdLineMap.get("album")); } if (m_oCmdLineMap.containsKey("artist")) { oID3V1_1Tag.setArtist((String)m_oCmdLineMap.get("artist")); } if (m_oCmdLineMap.containsKey("comment")) { oID3V1_1Tag.setComment((String)m_oCmdLineMap.get("comment")); } if (m_oCmdLineMap.containsKey("genre")) { String sGenre = (String)m_oCmdLineMap.get("genre"); oID3V1_1Tag.setGenre(ID3V1Tag.Genre.lookupGenre(sGenre)); } if (m_oCmdLineMap.containsKey("title")) { oID3V1_1Tag.setTitle((String)m_oCmdLineMap.get("title")); } if (m_oCmdLineMap.containsKey("year")) { oID3V1_1Tag.setYear(((Integer)m_oCmdLineMap.get("year")).toString()); } if (m_oCmdLineMap.containsKey("track")) { oID3V1_1Tag.setAlbumTrack(((Integer)m_oCmdLineMap.get("track")).intValue()); } oMP3File.setID3Tag(oID3V1_1Tag); } if (m_oCmdLineMap.containsKey("2")) { ID3V2_3_0Tag oID3V2_3_0Tag = new ID3V2_3_0Tag(); //HACK: Need to have padding at the end of the tag, or Winamp won't see the last frame (at least 6 bytes seem to be required). oID3V2_3_0Tag.setPaddingLength(16); if (m_oCmdLineMap.containsKey("album")) { oID3V2_3_0Tag.setAlbum((String)m_oCmdLineMap.get("album")); } if (m_oCmdLineMap.containsKey("artist")) { oID3V2_3_0Tag.setArtist((String)m_oCmdLineMap.get("artist")); } if (m_oCmdLineMap.containsKey("comment")) { oID3V2_3_0Tag.setComment((String)m_oCmdLineMap.get("comment")); } if (m_oCmdLineMap.containsKey("genre")) { oID3V2_3_0Tag.setGenre((String)m_oCmdLineMap.get("genre")); } oMP3File.setID3Tag(oID3V2_3_0Tag); if (m_oCmdLineMap.containsKey("title")) { oID3V2_3_0Tag.setTitle((String)m_oCmdLineMap.get("title")); } if (m_oCmdLineMap.containsKey("year")) { oID3V2_3_0Tag.setYear(((Integer)m_oCmdLineMap.get("year")).intValue()); } if (m_oCmdLineMap.containsKey("track")) { if (m_oCmdLineMap.containsKey("total")) { oID3V2_3_0Tag.setTrackNumber(((Integer)m_oCmdLineMap.get("track")).intValue(), ((Integer)m_oCmdLineMap.get("total")).intValue()); } else { oID3V2_3_0Tag.setTrackNumber(((Integer)m_oCmdLineMap.get("track")).intValue()); } } } oMP3File.sync(); } }
private void tag() throws Exception { String[] asFilename = (String[])m_oCmdLineMap.get("filenames"); for (int i=0; i < asFilename.length; i++) { File oSourceFile = new File(asFilename[i]); MP3File oMP3File = new MP3File(oSourceFile); if (m_oCmdLineMap.containsKey("1")) { ID3V1_1Tag oID3V1_1Tag = new ID3V1_1Tag(); if (m_oCmdLineMap.containsKey("album")) { oID3V1_1Tag.setAlbum((String)m_oCmdLineMap.get("album")); } if (m_oCmdLineMap.containsKey("artist")) { oID3V1_1Tag.setArtist((String)m_oCmdLineMap.get("artist")); } if (m_oCmdLineMap.containsKey("comment")) { oID3V1_1Tag.setComment((String)m_oCmdLineMap.get("comment")); } if (m_oCmdLineMap.containsKey("genre")) { String sGenre = (String)m_oCmdLineMap.get("genre"); oID3V1_1Tag.setGenre(ID3V1Tag.Genre.lookupGenre(sGenre)); } if (m_oCmdLineMap.containsKey("title")) { oID3V1_1Tag.setTitle((String)m_oCmdLineMap.get("title")); } if (m_oCmdLineMap.containsKey("year")) { oID3V1_1Tag.setYear(((Integer)m_oCmdLineMap.get("year")).toString()); } if (m_oCmdLineMap.containsKey("track")) { oID3V1_1Tag.setAlbumTrack(((Integer)m_oCmdLineMap.get("track")).intValue()); } oMP3File.setID3Tag(oID3V1_1Tag); } if (m_oCmdLineMap.containsKey("2")) { ID3V2_3_0Tag oID3V2_3_0Tag = new ID3V2_3_0Tag(); oID3V2_3_0Tag.setPaddingLength(16); if (m_oCmdLineMap.containsKey("album")) { oID3V2_3_0Tag.setAlbum((String)m_oCmdLineMap.get("album")); } if (m_oCmdLineMap.containsKey("artist")) { oID3V2_3_0Tag.setArtist((String)m_oCmdLineMap.get("artist")); } if (m_oCmdLineMap.containsKey("comment")) { oID3V2_3_0Tag.setComment((String)m_oCmdLineMap.get("comment")); } if (m_oCmdLineMap.containsKey("genre")) { oID3V2_3_0Tag.setGenre((String)m_oCmdLineMap.get("genre")); } oMP3File.setID3Tag(oID3V2_3_0Tag); if (m_oCmdLineMap.containsKey("title")) { oID3V2_3_0Tag.setTitle((String)m_oCmdLineMap.get("title")); } if (m_oCmdLineMap.containsKey("year")) { oID3V2_3_0Tag.setYear(((Integer)m_oCmdLineMap.get("year")).intValue()); } if (m_oCmdLineMap.containsKey("track")) { if (m_oCmdLineMap.containsKey("total")) { oID3V2_3_0Tag.setTrackNumber(((Integer)m_oCmdLineMap.get("track")).intValue(), ((Integer)m_oCmdLineMap.get("total")).intValue()); } else { oID3V2_3_0Tag.setTrackNumber(((Integer)m_oCmdLineMap.get("track")).intValue()); } } } oMP3File.sync(); } }
private void tag() throws exception { string[] asfilename = (string[])m_ocmdlinemap.get("filenames"); for (int i=0; i < asfilename.length; i++) { file osourcefile = new file(asfilename[i]); mp3file omp3file = new mp3file(osourcefile); if (m_ocmdlinemap.containskey("1")) { id3v1_1tag oid3v1_1tag = new id3v1_1tag(); if (m_ocmdlinemap.containskey("album")) { oid3v1_1tag.setalbum((string)m_ocmdlinemap.get("album")); } if (m_ocmdlinemap.containskey("artist")) { oid3v1_1tag.setartist((string)m_ocmdlinemap.get("artist")); } if (m_ocmdlinemap.containskey("comment")) { oid3v1_1tag.setcomment((string)m_ocmdlinemap.get("comment")); } if (m_ocmdlinemap.containskey("genre")) { string sgenre = (string)m_ocmdlinemap.get("genre"); oid3v1_1tag.setgenre(id3v1tag.genre.lookupgenre(sgenre)); } if (m_ocmdlinemap.containskey("title")) { oid3v1_1tag.settitle((string)m_ocmdlinemap.get("title")); } if (m_ocmdlinemap.containskey("year")) { oid3v1_1tag.setyear(((integer)m_ocmdlinemap.get("year")).tostring()); } if (m_ocmdlinemap.containskey("track")) { oid3v1_1tag.setalbumtrack(((integer)m_ocmdlinemap.get("track")).intvalue()); } omp3file.setid3tag(oid3v1_1tag); } if (m_ocmdlinemap.containskey("2")) { id3v2_3_0tag oid3v2_3_0tag = new id3v2_3_0tag(); oid3v2_3_0tag.setpaddinglength(16); if (m_ocmdlinemap.containskey("album")) { oid3v2_3_0tag.setalbum((string)m_ocmdlinemap.get("album")); } if (m_ocmdlinemap.containskey("artist")) { oid3v2_3_0tag.setartist((string)m_ocmdlinemap.get("artist")); } if (m_ocmdlinemap.containskey("comment")) { oid3v2_3_0tag.setcomment((string)m_ocmdlinemap.get("comment")); } if (m_ocmdlinemap.containskey("genre")) { oid3v2_3_0tag.setgenre((string)m_ocmdlinemap.get("genre")); } omp3file.setid3tag(oid3v2_3_0tag); if (m_ocmdlinemap.containskey("title")) { oid3v2_3_0tag.settitle((string)m_ocmdlinemap.get("title")); } if (m_ocmdlinemap.containskey("year")) { oid3v2_3_0tag.setyear(((integer)m_ocmdlinemap.get("year")).intvalue()); } if (m_ocmdlinemap.containskey("track")) { if (m_ocmdlinemap.containskey("total")) { oid3v2_3_0tag.settracknumber(((integer)m_ocmdlinemap.get("track")).intvalue(), ((integer)m_ocmdlinemap.get("total")).intvalue()); } else { oid3v2_3_0tag.settracknumber(((integer)m_ocmdlinemap.get("track")).intvalue()); } } } omp3file.sync(); } }
ShahzaibAyyub/Music-Player-Library-Java-SQL
[ 1, 0, 0, 0 ]
8,611
@Override public void actionPerformed(ActionEvent e) { if(currSel!= null && currSel instanceof GroupTreeNode){ // differentiate clones in this group GroupTreeNode gtn = (GroupTreeNode)currSel; // if(gtn.getChildCount() == 2){ // TODO: currently we only support two way comparison CloneTreeNode ctn1 = (CloneTreeNode)gtn.getChildAt(0); CloneTreeNode ctn2 = (CloneTreeNode)gtn.getChildAt(1); String file1 = ctn1.getFile(); String file2 = ctn2.getFile(); CloneComparison comparison = new CloneComparison(panel, new File(file1), new File(file2), ctn1.start, ctn1.end, ctn2.start, ctn2.end); comparison.setOpenInBackground(false); comparison.execute(); // } } }
@Override public void actionPerformed(ActionEvent e) { if(currSel!= null && currSel instanceof GroupTreeNode){ GroupTreeNode gtn = (GroupTreeNode)currSel; CloneTreeNode ctn1 = (CloneTreeNode)gtn.getChildAt(0); CloneTreeNode ctn2 = (CloneTreeNode)gtn.getChildAt(1); String file1 = ctn1.getFile(); String file2 = ctn2.getFile(); CloneComparison comparison = new CloneComparison(panel, new File(file1), new File(file2), ctn1.start, ctn1.end, ctn2.start, ctn2.end); comparison.setOpenInBackground(false); comparison.execute(); } }
@override public void actionperformed(actionevent e) { if(currsel!= null && currsel instanceof grouptreenode){ grouptreenode gtn = (grouptreenode)currsel; clonetreenode ctn1 = (clonetreenode)gtn.getchildat(0); clonetreenode ctn2 = (clonetreenode)gtn.getchildat(1); string file1 = ctn1.getfile(); string file2 = ctn2.getfile(); clonecomparison comparison = new clonecomparison(panel, new file(file1), new file(file2), ctn1.start, ctn1.end, ctn2.start, ctn2.end); comparison.setopeninbackground(false); comparison.execute(); } }
UCLA-SEAL/Grafter
[ 1, 0, 0, 0 ]
25,018
private BaseQuery buildQueryNoAggregations(QueryFactory queryFactory, String queryString, Map<String, Object> namedParameters, long startOffset, int maxResults, IckleParsingResult<TypeMetadata> parsingResult) { if (parsingResult.hasGroupingOrAggregations()) { throw log.queryMustNotUseGroupingOrAggregation(); // may happen only due to internal programming error } boolean isFullTextQuery; if (parsingResult.getWhereClause() != null) { isFullTextQuery = parsingResult.getWhereClause().acceptVisitor(FullTextVisitor.INSTANCE); if (!isIndexed && isFullTextQuery) { throw new IllegalStateException("The cache must be indexed in order to use full-text queries."); } } if (parsingResult.getSortFields() != null) { for (SortField sortField : parsingResult.getSortFields()) { PropertyPath<?> p = sortField.getPath(); if (propertyHelper.isRepeatedProperty(parsingResult.getTargetEntityMetadata(), p.asArrayPath())) { throw log.multivaluedPropertyCannotBeUsedInOrderBy(p.toString()); } } } if (parsingResult.getProjectedPaths() != null) { for (PropertyPath<?> p : parsingResult.getProjectedPaths()) { if (propertyHelper.isRepeatedProperty(parsingResult.getTargetEntityMetadata(), p.asArrayPath())) { throw log.multivaluedPropertyCannotBeProjected(p.asStringPath()); } } } BooleanExpr normalizedWhereClause = booleanFilterNormalizer.normalize(parsingResult.getWhereClause()); if (normalizedWhereClause == ConstantBooleanExpr.FALSE) { // the query is a contradiction, there are no matches return new EmptyResultQuery(queryFactory, cache, queryString, namedParameters, startOffset, maxResults); } // if cache is indexed but there is no actual 'where' filter clause and we do have sorting or projections we should still use the index, otherwise just go for a non-indexed fetch-all if (!isIndexed || (normalizedWhereClause == null || normalizedWhereClause == ConstantBooleanExpr.TRUE) && parsingResult.getProjections() == null && parsingResult.getSortFields() == null) { // fully non-indexed execution because the filter matches everything or there is no indexing at all return new EmbeddedQuery(this, queryFactory, cache, queryString, namedParameters, parsingResult.getProjections(), startOffset, maxResults); } IndexedFieldProvider.FieldIndexingMetadata fieldIndexingMetadata = propertyHelper.getIndexedFieldProvider().get(parsingResult.getTargetEntityMetadata()); boolean allProjectionsAreStored = true; LinkedHashMap<PropertyPath, List<Integer>> projectionsMap = null; if (parsingResult.getProjectedPaths() != null) { projectionsMap = new LinkedHashMap<>(); for (int i = 0; i < parsingResult.getProjectedPaths().length; i++) { PropertyPath<?> p = parsingResult.getProjectedPaths()[i]; List<Integer> idx = projectionsMap.get(p); if (idx == null) { idx = new ArrayList<>(); projectionsMap.put(p, idx); if (!fieldIndexingMetadata.isStored(p.asArrayPath())) { allProjectionsAreStored = false; } } idx.add(i); } } boolean allSortFieldsAreStored = true; SortField[] sortFields = parsingResult.getSortFields(); if (sortFields != null) { // deduplicate sort fields LinkedHashMap<String, SortField> sortFieldMap = new LinkedHashMap<>(); for (SortField sf : sortFields) { PropertyPath<?> p = sf.getPath(); String asStringPath = p.asStringPath(); if (!sortFieldMap.containsKey(asStringPath)) { sortFieldMap.put(asStringPath, sf); if (!fieldIndexingMetadata.isStored(p.asArrayPath())) { allSortFieldsAreStored = false; } } } sortFields = sortFieldMap.values().toArray(new SortField[sortFieldMap.size()]); } //todo [anistor] do not allow hybrid queries with fulltext. exception, allow a fully indexed query followed by in-memory aggregation. the aggregated or 'having' field should not be analyzed //todo [anistor] do we allow aggregation in fulltext queries? //todo [anistor] do not allow hybrid fulltext queries. all 'where' fields must be indexed. all projections must be stored. BooleShannonExpansion bse = new BooleShannonExpansion(MAX_EXPANSION_COFACTORS, fieldIndexingMetadata); BooleanExpr expansion = bse.expand(normalizedWhereClause); if (expansion == normalizedWhereClause) { // identity comparison is intended here! // all involved fields are indexed, so go the Lucene way if (allSortFieldsAreStored) { if (allProjectionsAreStored) { // all projections are stored, so we can execute the query entirely against the index, and we can also sort using the index RowProcessor rowProcessor = null; if (parsingResult.getProjectedPaths() != null) { if (projectionsMap.size() != parsingResult.getProjectedPaths().length) { // but some projections are duplicated ... final Class<?>[] projectedTypes = new Class<?>[projectionsMap.size()]; final int[] map = new int[parsingResult.getProjectedPaths().length]; int j = 0; for (List<Integer> idx : projectionsMap.values()) { int i = idx.get(0); projectedTypes[j] = parsingResult.getProjectedTypes()[i]; for (int k : idx) { map[k] = j; } j++; } RowProcessor projectionProcessor = makeProjectionProcessor(projectedTypes); rowProcessor = inRow -> { if (projectionProcessor != null) { inRow = projectionProcessor.process(inRow); } Object[] outRow = new Object[map.length]; for (int i = 0; i < map.length; i++) { outRow[i] = inRow[map[i]]; } return outRow; }; PropertyPath[] deduplicatedProjection = projectionsMap.keySet().toArray(new PropertyPath[projectionsMap.size()]); IckleParsingResult<TypeMetadata> fpr = makeFilterParsingResult(parsingResult, normalizedWhereClause, deduplicatedProjection, projectedTypes, sortFields); return new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, fpr, parsingResult.getProjections(), makeResultProcessor(rowProcessor), startOffset, maxResults); } else { rowProcessor = makeProjectionProcessor(parsingResult.getProjectedTypes()); } } return new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, parsingResult, parsingResult.getProjections(), makeResultProcessor(rowProcessor), startOffset, maxResults); } else { IckleParsingResult<TypeMetadata> fpr = makeFilterParsingResult(parsingResult, normalizedWhereClause, null, null, sortFields); Query indexQuery = new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, fpr, null, makeResultProcessor(null), startOffset, maxResults); String projectionQueryStr = SyntaxTreePrinter.printTree(parsingResult.getTargetEntityName(), parsingResult.getProjectedPaths(), null, null); return new HybridQuery(queryFactory, cache, projectionQueryStr, null, getObjectFilter(matcher, projectionQueryStr, null, null), -1, -1, indexQuery); } } else { // projections may be stored but some sort fields are not so we need to query the index and then execute in-memory sorting and projecting in a second phase IckleParsingResult<TypeMetadata> fpr = makeFilterParsingResult(parsingResult, normalizedWhereClause, null, null, null); Query indexQuery = new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, fpr, null, makeResultProcessor(null), -1, -1); String projectionQueryStr = SyntaxTreePrinter.printTree(parsingResult.getTargetEntityName(), parsingResult.getProjectedPaths(), null, sortFields); return new HybridQuery(queryFactory, cache, projectionQueryStr, null, getObjectFilter(matcher, projectionQueryStr, null, null), startOffset, maxResults, indexQuery); } } if (expansion == ConstantBooleanExpr.TRUE) { // expansion leads to a full non-indexed query or the expansion is too long/complex return new EmbeddedQuery(this, queryFactory, cache, queryString, namedParameters, parsingResult.getProjections(), startOffset, maxResults); } // some fields are indexed, run a hybrid query IckleParsingResult<TypeMetadata> fpr = makeFilterParsingResult(parsingResult, expansion, null, null, null); Query expandedQuery = new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, fpr, null, makeResultProcessor(null), -1, -1); return new HybridQuery(queryFactory, cache, queryString, namedParameters, getObjectFilter(matcher, queryString, namedParameters, null), startOffset, maxResults, expandedQuery); }
private BaseQuery buildQueryNoAggregations(QueryFactory queryFactory, String queryString, Map<String, Object> namedParameters, long startOffset, int maxResults, IckleParsingResult<TypeMetadata> parsingResult) { if (parsingResult.hasGroupingOrAggregations()) { throw log.queryMustNotUseGroupingOrAggregation(); } boolean isFullTextQuery; if (parsingResult.getWhereClause() != null) { isFullTextQuery = parsingResult.getWhereClause().acceptVisitor(FullTextVisitor.INSTANCE); if (!isIndexed && isFullTextQuery) { throw new IllegalStateException("The cache must be indexed in order to use full-text queries."); } } if (parsingResult.getSortFields() != null) { for (SortField sortField : parsingResult.getSortFields()) { PropertyPath<?> p = sortField.getPath(); if (propertyHelper.isRepeatedProperty(parsingResult.getTargetEntityMetadata(), p.asArrayPath())) { throw log.multivaluedPropertyCannotBeUsedInOrderBy(p.toString()); } } } if (parsingResult.getProjectedPaths() != null) { for (PropertyPath<?> p : parsingResult.getProjectedPaths()) { if (propertyHelper.isRepeatedProperty(parsingResult.getTargetEntityMetadata(), p.asArrayPath())) { throw log.multivaluedPropertyCannotBeProjected(p.asStringPath()); } } } BooleanExpr normalizedWhereClause = booleanFilterNormalizer.normalize(parsingResult.getWhereClause()); if (normalizedWhereClause == ConstantBooleanExpr.FALSE) { return new EmptyResultQuery(queryFactory, cache, queryString, namedParameters, startOffset, maxResults); } if (!isIndexed || (normalizedWhereClause == null || normalizedWhereClause == ConstantBooleanExpr.TRUE) && parsingResult.getProjections() == null && parsingResult.getSortFields() == null) { return new EmbeddedQuery(this, queryFactory, cache, queryString, namedParameters, parsingResult.getProjections(), startOffset, maxResults); } IndexedFieldProvider.FieldIndexingMetadata fieldIndexingMetadata = propertyHelper.getIndexedFieldProvider().get(parsingResult.getTargetEntityMetadata()); boolean allProjectionsAreStored = true; LinkedHashMap<PropertyPath, List<Integer>> projectionsMap = null; if (parsingResult.getProjectedPaths() != null) { projectionsMap = new LinkedHashMap<>(); for (int i = 0; i < parsingResult.getProjectedPaths().length; i++) { PropertyPath<?> p = parsingResult.getProjectedPaths()[i]; List<Integer> idx = projectionsMap.get(p); if (idx == null) { idx = new ArrayList<>(); projectionsMap.put(p, idx); if (!fieldIndexingMetadata.isStored(p.asArrayPath())) { allProjectionsAreStored = false; } } idx.add(i); } } boolean allSortFieldsAreStored = true; SortField[] sortFields = parsingResult.getSortFields(); if (sortFields != null) { LinkedHashMap<String, SortField> sortFieldMap = new LinkedHashMap<>(); for (SortField sf : sortFields) { PropertyPath<?> p = sf.getPath(); String asStringPath = p.asStringPath(); if (!sortFieldMap.containsKey(asStringPath)) { sortFieldMap.put(asStringPath, sf); if (!fieldIndexingMetadata.isStored(p.asArrayPath())) { allSortFieldsAreStored = false; } } } sortFields = sortFieldMap.values().toArray(new SortField[sortFieldMap.size()]); } BooleShannonExpansion bse = new BooleShannonExpansion(MAX_EXPANSION_COFACTORS, fieldIndexingMetadata); BooleanExpr expansion = bse.expand(normalizedWhereClause); if (expansion == normalizedWhereClause) { if (allSortFieldsAreStored) { if (allProjectionsAreStored) { RowProcessor rowProcessor = null; if (parsingResult.getProjectedPaths() != null) { if (projectionsMap.size() != parsingResult.getProjectedPaths().length) { final Class<?>[] projectedTypes = new Class<?>[projectionsMap.size()]; final int[] map = new int[parsingResult.getProjectedPaths().length]; int j = 0; for (List<Integer> idx : projectionsMap.values()) { int i = idx.get(0); projectedTypes[j] = parsingResult.getProjectedTypes()[i]; for (int k : idx) { map[k] = j; } j++; } RowProcessor projectionProcessor = makeProjectionProcessor(projectedTypes); rowProcessor = inRow -> { if (projectionProcessor != null) { inRow = projectionProcessor.process(inRow); } Object[] outRow = new Object[map.length]; for (int i = 0; i < map.length; i++) { outRow[i] = inRow[map[i]]; } return outRow; }; PropertyPath[] deduplicatedProjection = projectionsMap.keySet().toArray(new PropertyPath[projectionsMap.size()]); IckleParsingResult<TypeMetadata> fpr = makeFilterParsingResult(parsingResult, normalizedWhereClause, deduplicatedProjection, projectedTypes, sortFields); return new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, fpr, parsingResult.getProjections(), makeResultProcessor(rowProcessor), startOffset, maxResults); } else { rowProcessor = makeProjectionProcessor(parsingResult.getProjectedTypes()); } } return new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, parsingResult, parsingResult.getProjections(), makeResultProcessor(rowProcessor), startOffset, maxResults); } else { IckleParsingResult<TypeMetadata> fpr = makeFilterParsingResult(parsingResult, normalizedWhereClause, null, null, sortFields); Query indexQuery = new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, fpr, null, makeResultProcessor(null), startOffset, maxResults); String projectionQueryStr = SyntaxTreePrinter.printTree(parsingResult.getTargetEntityName(), parsingResult.getProjectedPaths(), null, null); return new HybridQuery(queryFactory, cache, projectionQueryStr, null, getObjectFilter(matcher, projectionQueryStr, null, null), -1, -1, indexQuery); } } else { IckleParsingResult<TypeMetadata> fpr = makeFilterParsingResult(parsingResult, normalizedWhereClause, null, null, null); Query indexQuery = new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, fpr, null, makeResultProcessor(null), -1, -1); String projectionQueryStr = SyntaxTreePrinter.printTree(parsingResult.getTargetEntityName(), parsingResult.getProjectedPaths(), null, sortFields); return new HybridQuery(queryFactory, cache, projectionQueryStr, null, getObjectFilter(matcher, projectionQueryStr, null, null), startOffset, maxResults, indexQuery); } } if (expansion == ConstantBooleanExpr.TRUE) { return new EmbeddedQuery(this, queryFactory, cache, queryString, namedParameters, parsingResult.getProjections(), startOffset, maxResults); } IckleParsingResult<TypeMetadata> fpr = makeFilterParsingResult(parsingResult, expansion, null, null, null); Query expandedQuery = new EmbeddedLuceneQuery<>(this, queryFactory, namedParameters, fpr, null, makeResultProcessor(null), -1, -1); return new HybridQuery(queryFactory, cache, queryString, namedParameters, getObjectFilter(matcher, queryString, namedParameters, null), startOffset, maxResults, expandedQuery); }
private basequery buildquerynoaggregations(queryfactory queryfactory, string querystring, map<string, object> namedparameters, long startoffset, int maxresults, ickleparsingresult<typemetadata> parsingresult) { if (parsingresult.hasgroupingoraggregations()) { throw log.querymustnotusegroupingoraggregation(); } boolean isfulltextquery; if (parsingresult.getwhereclause() != null) { isfulltextquery = parsingresult.getwhereclause().acceptvisitor(fulltextvisitor.instance); if (!isindexed && isfulltextquery) { throw new illegalstateexception("the cache must be indexed in order to use full-text queries."); } } if (parsingresult.getsortfields() != null) { for (sortfield sortfield : parsingresult.getsortfields()) { propertypath<?> p = sortfield.getpath(); if (propertyhelper.isrepeatedproperty(parsingresult.gettargetentitymetadata(), p.asarraypath())) { throw log.multivaluedpropertycannotbeusedinorderby(p.tostring()); } } } if (parsingresult.getprojectedpaths() != null) { for (propertypath<?> p : parsingresult.getprojectedpaths()) { if (propertyhelper.isrepeatedproperty(parsingresult.gettargetentitymetadata(), p.asarraypath())) { throw log.multivaluedpropertycannotbeprojected(p.asstringpath()); } } } booleanexpr normalizedwhereclause = booleanfilternormalizer.normalize(parsingresult.getwhereclause()); if (normalizedwhereclause == constantbooleanexpr.false) { return new emptyresultquery(queryfactory, cache, querystring, namedparameters, startoffset, maxresults); } if (!isindexed || (normalizedwhereclause == null || normalizedwhereclause == constantbooleanexpr.true) && parsingresult.getprojections() == null && parsingresult.getsortfields() == null) { return new embeddedquery(this, queryfactory, cache, querystring, namedparameters, parsingresult.getprojections(), startoffset, maxresults); } indexedfieldprovider.fieldindexingmetadata fieldindexingmetadata = propertyhelper.getindexedfieldprovider().get(parsingresult.gettargetentitymetadata()); boolean allprojectionsarestored = true; linkedhashmap<propertypath, list<integer>> projectionsmap = null; if (parsingresult.getprojectedpaths() != null) { projectionsmap = new linkedhashmap<>(); for (int i = 0; i < parsingresult.getprojectedpaths().length; i++) { propertypath<?> p = parsingresult.getprojectedpaths()[i]; list<integer> idx = projectionsmap.get(p); if (idx == null) { idx = new arraylist<>(); projectionsmap.put(p, idx); if (!fieldindexingmetadata.isstored(p.asarraypath())) { allprojectionsarestored = false; } } idx.add(i); } } boolean allsortfieldsarestored = true; sortfield[] sortfields = parsingresult.getsortfields(); if (sortfields != null) { linkedhashmap<string, sortfield> sortfieldmap = new linkedhashmap<>(); for (sortfield sf : sortfields) { propertypath<?> p = sf.getpath(); string asstringpath = p.asstringpath(); if (!sortfieldmap.containskey(asstringpath)) { sortfieldmap.put(asstringpath, sf); if (!fieldindexingmetadata.isstored(p.asarraypath())) { allsortfieldsarestored = false; } } } sortfields = sortfieldmap.values().toarray(new sortfield[sortfieldmap.size()]); } booleshannonexpansion bse = new booleshannonexpansion(max_expansion_cofactors, fieldindexingmetadata); booleanexpr expansion = bse.expand(normalizedwhereclause); if (expansion == normalizedwhereclause) { if (allsortfieldsarestored) { if (allprojectionsarestored) { rowprocessor rowprocessor = null; if (parsingresult.getprojectedpaths() != null) { if (projectionsmap.size() != parsingresult.getprojectedpaths().length) { final class<?>[] projectedtypes = new class<?>[projectionsmap.size()]; final int[] map = new int[parsingresult.getprojectedpaths().length]; int j = 0; for (list<integer> idx : projectionsmap.values()) { int i = idx.get(0); projectedtypes[j] = parsingresult.getprojectedtypes()[i]; for (int k : idx) { map[k] = j; } j++; } rowprocessor projectionprocessor = makeprojectionprocessor(projectedtypes); rowprocessor = inrow -> { if (projectionprocessor != null) { inrow = projectionprocessor.process(inrow); } object[] outrow = new object[map.length]; for (int i = 0; i < map.length; i++) { outrow[i] = inrow[map[i]]; } return outrow; }; propertypath[] deduplicatedprojection = projectionsmap.keyset().toarray(new propertypath[projectionsmap.size()]); ickleparsingresult<typemetadata> fpr = makefilterparsingresult(parsingresult, normalizedwhereclause, deduplicatedprojection, projectedtypes, sortfields); return new embeddedlucenequery<>(this, queryfactory, namedparameters, fpr, parsingresult.getprojections(), makeresultprocessor(rowprocessor), startoffset, maxresults); } else { rowprocessor = makeprojectionprocessor(parsingresult.getprojectedtypes()); } } return new embeddedlucenequery<>(this, queryfactory, namedparameters, parsingresult, parsingresult.getprojections(), makeresultprocessor(rowprocessor), startoffset, maxresults); } else { ickleparsingresult<typemetadata> fpr = makefilterparsingresult(parsingresult, normalizedwhereclause, null, null, sortfields); query indexquery = new embeddedlucenequery<>(this, queryfactory, namedparameters, fpr, null, makeresultprocessor(null), startoffset, maxresults); string projectionquerystr = syntaxtreeprinter.printtree(parsingresult.gettargetentityname(), parsingresult.getprojectedpaths(), null, null); return new hybridquery(queryfactory, cache, projectionquerystr, null, getobjectfilter(matcher, projectionquerystr, null, null), -1, -1, indexquery); } } else { ickleparsingresult<typemetadata> fpr = makefilterparsingresult(parsingresult, normalizedwhereclause, null, null, null); query indexquery = new embeddedlucenequery<>(this, queryfactory, namedparameters, fpr, null, makeresultprocessor(null), -1, -1); string projectionquerystr = syntaxtreeprinter.printtree(parsingresult.gettargetentityname(), parsingresult.getprojectedpaths(), null, sortfields); return new hybridquery(queryfactory, cache, projectionquerystr, null, getobjectfilter(matcher, projectionquerystr, null, null), startoffset, maxresults, indexquery); } } if (expansion == constantbooleanexpr.true) { return new embeddedquery(this, queryfactory, cache, querystring, namedparameters, parsingresult.getprojections(), startoffset, maxresults); } ickleparsingresult<typemetadata> fpr = makefilterparsingresult(parsingresult, expansion, null, null, null); query expandedquery = new embeddedlucenequery<>(this, queryfactory, namedparameters, fpr, null, makeresultprocessor(null), -1, -1); return new hybridquery(queryfactory, cache, querystring, namedparameters, getobjectfilter(matcher, querystring, namedparameters, null), startoffset, maxresults, expandedquery); }
TomasHofman/infinispan
[ 1, 0, 0, 0 ]
448
public static char[][] fill(char contents, int width, int height) { char[][] next = new char[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static char[][] fill(char contents, int width, int height) { char[][] next = new char[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static char[][] fill(char contents, int width, int height) { char[][] next = new char[width][height]; for (int x = 0; x < width; x++) { arrays.fill(next[x], contents); } return next; }
SquidPony/SquidLib
[ 1, 0, 0, 0 ]
449
public static float[][] fill(float contents, int width, int height) { float[][] next = new float[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static float[][] fill(float contents, int width, int height) { float[][] next = new float[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static float[][] fill(float contents, int width, int height) { float[][] next = new float[width][height]; for (int x = 0; x < width; x++) { arrays.fill(next[x], contents); } return next; }
SquidPony/SquidLib
[ 1, 0, 0, 0 ]
450
public static double[][] fill(double contents, int width, int height) { double[][] next = new double[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static double[][] fill(double contents, int width, int height) { double[][] next = new double[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static double[][] fill(double contents, int width, int height) { double[][] next = new double[width][height]; for (int x = 0; x < width; x++) { arrays.fill(next[x], contents); } return next; }
SquidPony/SquidLib
[ 1, 0, 0, 0 ]
451
public static int[][] fill(int contents, int width, int height) { int[][] next = new int[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static int[][] fill(int contents, int width, int height) { int[][] next = new int[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static int[][] fill(int contents, int width, int height) { int[][] next = new int[width][height]; for (int x = 0; x < width; x++) { arrays.fill(next[x], contents); } return next; }
SquidPony/SquidLib
[ 1, 0, 0, 0 ]
452
public static byte[][] fill(byte contents, int width, int height) { byte[][] next = new byte[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static byte[][] fill(byte contents, int width, int height) { byte[][] next = new byte[width][height]; for (int x = 0; x < width; x++) { Arrays.fill(next[x], contents); } return next; }
public static byte[][] fill(byte contents, int width, int height) { byte[][] next = new byte[width][height]; for (int x = 0; x < width; x++) { arrays.fill(next[x], contents); } return next; }
SquidPony/SquidLib
[ 1, 0, 0, 0 ]
453
public static boolean[][] fill(boolean contents, int width, int height) { boolean[][] next = new boolean[width][height]; if (contents) { for (int x = 0; x < width; x++) { Arrays.fill(next[x], true); } } return next; }
public static boolean[][] fill(boolean contents, int width, int height) { boolean[][] next = new boolean[width][height]; if (contents) { for (int x = 0; x < width; x++) { Arrays.fill(next[x], true); } } return next; }
public static boolean[][] fill(boolean contents, int width, int height) { boolean[][] next = new boolean[width][height]; if (contents) { for (int x = 0; x < width; x++) { arrays.fill(next[x], true); } } return next; }
SquidPony/SquidLib
[ 1, 0, 0, 0 ]
16,885
@JsonGetter("limit") public String getLimit ( ) { return this.limit; }
@JsonGetter("limit") public String getLimit ( ) { return this.limit; }
@jsongetter("limit") public string getlimit ( ) { return this.limit; }
adams-okode/chirpstack-rest-sdk
[ 0, 0, 0, 0 ]
25,078
@Override protected void execute(CalculationMonitor monitor){ // import the image data into 1D arrays : TO DO ImageDataFloat layersImg = new ImageDataFloat(layersImage.getImageData()); ImageDataFloat intensImg = new ImageDataFloat(intensityImage.getImageData()); int nx = layersImg.getRows(); int ny = layersImg.getCols(); int nz = layersImg.getSlices(); int nlayers = layersImg.getComponents()-1; int nxyz = nx*ny*nz; float rx = layersImg.getHeader().getDimResolutions()[0]; float ry = layersImg.getHeader().getDimResolutions()[1]; float rz = layersImg.getHeader().getDimResolutions()[2]; float[][] layers = new float[nlayers+1][nxyz]; float[][][][] buffer4 = layersImg.toArray4d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) for (int l=0;l<=nlayers;l++) { int xyz = x+nx*y+nx*ny*z; layers[l][xyz] = buffer4[x][y][z][l]; } buffer4 = null; layersImg = null; float[] intensity = new float[nxyz]; float[][][] buffer3 = intensImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; intensity[xyz] = buffer3[x][y][z]; } buffer3 = null; intensImg = null; // create a mask for all the regions outside of the area where layer 1 is > 0 and layer 2 is < 0 boolean[] ctxmask = new boolean[nxyz]; if (maskImage.getImageData()!=null) { ImageDataUByte maskImg = new ImageDataUByte(maskImage.getImageData()); byte[][][] bufferbyte = maskImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0 && bufferbyte[x][y][z]>0); } bufferbyte = null; maskImg = null; } else { for (int xyz=0;xyz<nxyz;xyz++) { ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0); } } // main algorithm // 1. define partial voume for each layer, each voxel float[][] pvol = new float[nlayers+1][nxyz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { for (int l=0;l<=nlayers;l++) { pvol[l][xyz] = partialVolumeFromSurface(x, y, z, layers[l], nx, ny, nz); } } } // 2. build and invert the GLM for each profile / voxel? float delta = paramExtent.getValue().floatValue()/Numerics.min(rx,ry,rz); float stdev = paramStdev.getValue().floatValue()/Numerics.min(rx,ry,rz); CorticalProfile profile = new CorticalProfile(nlayers, nx, ny, nz, rx, ry, rz); float maskval = 1e13f; float[][][][] mapping = new float[nx][ny][nz][nlayers]; float[][][] residual = new float[nx][ny][nz]; BitSet sampled = new BitSet(nx*ny*nz); float[] profiledist = new float[nx*ny*nz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { findFastMarchingProfileNeighborhood(sampled, profiledist, x,y,z, delta, layers, profile, ctxmask, nx, ny, nz, nlayers); int nsample = sampled.size(); if (nsample>=nlayers) { double[][] glm = new double[nlayers][nsample]; double[][] data = new double[nsample][1]; int idx = 0; for (int n=0;n<nsample;n++) { // get the next non-zero value idx = sampled.nextSetBit(idx); // build a weighting function based on distance to the original location double weight = FastMath.exp(-0.5*Numerics.square(profiledist[idx]/stdev)); for (int l=0;l<nlayers;l++) { glm[l][n] = weight*(pvol[l+1][idx]-pvol[l][idx]); } data[n][0] = weight*intensity[idx]; } // invert the linear model Matrix mtx = new Matrix(glm); Matrix smp = new Matrix(data); Matrix val = mtx.solve(smp); for (int l=0;l<nlayers;l++) { mapping[x][y][z][l] = (float)val.get(l,0); } Matrix res = mtx.times(val).minus(smp); residual[x][y][z] = (float)res.normInf(); } } } // output String imgname = intensityImage.getImageData().getName(); ImageDataFloat mapData = new ImageDataFloat(mapping); mapData.setHeader(layersImage.getImageData().getHeader()); mapData.setName(imgname+"_glmprofiles"); mappedImage.setValue(mapData); mapData = null; mapping = null; ImageDataFloat resData = new ImageDataFloat(residual); resData.setHeader(layersImage.getImageData().getHeader()); resData.setName(imgname+"_glmresidual"); residualImage.setValue(resData); resData = null; residual = null; }
@Override protected void execute(CalculationMonitor monitor){ ImageDataFloat layersImg = new ImageDataFloat(layersImage.getImageData()); ImageDataFloat intensImg = new ImageDataFloat(intensityImage.getImageData()); int nx = layersImg.getRows(); int ny = layersImg.getCols(); int nz = layersImg.getSlices(); int nlayers = layersImg.getComponents()-1; int nxyz = nx*ny*nz; float rx = layersImg.getHeader().getDimResolutions()[0]; float ry = layersImg.getHeader().getDimResolutions()[1]; float rz = layersImg.getHeader().getDimResolutions()[2]; float[][] layers = new float[nlayers+1][nxyz]; float[][][][] buffer4 = layersImg.toArray4d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) for (int l=0;l<=nlayers;l++) { int xyz = x+nx*y+nx*ny*z; layers[l][xyz] = buffer4[x][y][z][l]; } buffer4 = null; layersImg = null; float[] intensity = new float[nxyz]; float[][][] buffer3 = intensImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; intensity[xyz] = buffer3[x][y][z]; } buffer3 = null; intensImg = null; boolean[] ctxmask = new boolean[nxyz]; if (maskImage.getImageData()!=null) { ImageDataUByte maskImg = new ImageDataUByte(maskImage.getImageData()); byte[][][] bufferbyte = maskImg.toArray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0 && bufferbyte[x][y][z]>0); } bufferbyte = null; maskImg = null; } else { for (int xyz=0;xyz<nxyz;xyz++) { ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0); } } float[][] pvol = new float[nlayers+1][nxyz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { for (int l=0;l<=nlayers;l++) { pvol[l][xyz] = partialVolumeFromSurface(x, y, z, layers[l], nx, ny, nz); } } } float delta = paramExtent.getValue().floatValue()/Numerics.min(rx,ry,rz); float stdev = paramStdev.getValue().floatValue()/Numerics.min(rx,ry,rz); CorticalProfile profile = new CorticalProfile(nlayers, nx, ny, nz, rx, ry, rz); float maskval = 1e13f; float[][][][] mapping = new float[nx][ny][nz][nlayers]; float[][][] residual = new float[nx][ny][nz]; BitSet sampled = new BitSet(nx*ny*nz); float[] profiledist = new float[nx*ny*nz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { findFastMarchingProfileNeighborhood(sampled, profiledist, x,y,z, delta, layers, profile, ctxmask, nx, ny, nz, nlayers); int nsample = sampled.size(); if (nsample>=nlayers) { double[][] glm = new double[nlayers][nsample]; double[][] data = new double[nsample][1]; int idx = 0; for (int n=0;n<nsample;n++) { idx = sampled.nextSetBit(idx); double weight = FastMath.exp(-0.5*Numerics.square(profiledist[idx]/stdev)); for (int l=0;l<nlayers;l++) { glm[l][n] = weight*(pvol[l+1][idx]-pvol[l][idx]); } data[n][0] = weight*intensity[idx]; } Matrix mtx = new Matrix(glm); Matrix smp = new Matrix(data); Matrix val = mtx.solve(smp); for (int l=0;l<nlayers;l++) { mapping[x][y][z][l] = (float)val.get(l,0); } Matrix res = mtx.times(val).minus(smp); residual[x][y][z] = (float)res.normInf(); } } } String imgname = intensityImage.getImageData().getName(); ImageDataFloat mapData = new ImageDataFloat(mapping); mapData.setHeader(layersImage.getImageData().getHeader()); mapData.setName(imgname+"_glmprofiles"); mappedImage.setValue(mapData); mapData = null; mapping = null; ImageDataFloat resData = new ImageDataFloat(residual); resData.setHeader(layersImage.getImageData().getHeader()); resData.setName(imgname+"_glmresidual"); residualImage.setValue(resData); resData = null; residual = null; }
@override protected void execute(calculationmonitor monitor){ imagedatafloat layersimg = new imagedatafloat(layersimage.getimagedata()); imagedatafloat intensimg = new imagedatafloat(intensityimage.getimagedata()); int nx = layersimg.getrows(); int ny = layersimg.getcols(); int nz = layersimg.getslices(); int nlayers = layersimg.getcomponents()-1; int nxyz = nx*ny*nz; float rx = layersimg.getheader().getdimresolutions()[0]; float ry = layersimg.getheader().getdimresolutions()[1]; float rz = layersimg.getheader().getdimresolutions()[2]; float[][] layers = new float[nlayers+1][nxyz]; float[][][][] buffer4 = layersimg.toarray4d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) for (int l=0;l<=nlayers;l++) { int xyz = x+nx*y+nx*ny*z; layers[l][xyz] = buffer4[x][y][z][l]; } buffer4 = null; layersimg = null; float[] intensity = new float[nxyz]; float[][][] buffer3 = intensimg.toarray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; intensity[xyz] = buffer3[x][y][z]; } buffer3 = null; intensimg = null; boolean[] ctxmask = new boolean[nxyz]; if (maskimage.getimagedata()!=null) { imagedataubyte maskimg = new imagedataubyte(maskimage.getimagedata()); byte[][][] bufferbyte = maskimg.toarray3d(); for (int x=0;x<nx;x++) for (int y=0;y<ny;y++) for (int z=0;z<nz;z++) { int xyz = x+nx*y+nx*ny*z; ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0 && bufferbyte[x][y][z]>0); } bufferbyte = null; maskimg = null; } else { for (int xyz=0;xyz<nxyz;xyz++) { ctxmask[xyz] = (layers[0][xyz]>=0.0 && layers[nlayers][xyz]<=0.0); } } float[][] pvol = new float[nlayers+1][nxyz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { for (int l=0;l<=nlayers;l++) { pvol[l][xyz] = partialvolumefromsurface(x, y, z, layers[l], nx, ny, nz); } } } float delta = paramextent.getvalue().floatvalue()/numerics.min(rx,ry,rz); float stdev = paramstdev.getvalue().floatvalue()/numerics.min(rx,ry,rz); corticalprofile profile = new corticalprofile(nlayers, nx, ny, nz, rx, ry, rz); float maskval = 1e13f; float[][][][] mapping = new float[nx][ny][nz][nlayers]; float[][][] residual = new float[nx][ny][nz]; bitset sampled = new bitset(nx*ny*nz); float[] profiledist = new float[nx*ny*nz]; for (int x=0; x<nx; x++) for (int y=0; y<ny; y++) for (int z = 0; z<nz; z++) { int xyz = x + nx*y + nx*ny*z; if (ctxmask[xyz]) { findfastmarchingprofileneighborhood(sampled, profiledist, x,y,z, delta, layers, profile, ctxmask, nx, ny, nz, nlayers); int nsample = sampled.size(); if (nsample>=nlayers) { double[][] glm = new double[nlayers][nsample]; double[][] data = new double[nsample][1]; int idx = 0; for (int n=0;n<nsample;n++) { idx = sampled.nextsetbit(idx); double weight = fastmath.exp(-0.5*numerics.square(profiledist[idx]/stdev)); for (int l=0;l<nlayers;l++) { glm[l][n] = weight*(pvol[l+1][idx]-pvol[l][idx]); } data[n][0] = weight*intensity[idx]; } matrix mtx = new matrix(glm); matrix smp = new matrix(data); matrix val = mtx.solve(smp); for (int l=0;l<nlayers;l++) { mapping[x][y][z][l] = (float)val.get(l,0); } matrix res = mtx.times(val).minus(smp); residual[x][y][z] = (float)res.norminf(); } } } string imgname = intensityimage.getimagedata().getname(); imagedatafloat mapdata = new imagedatafloat(mapping); mapdata.setheader(layersimage.getimagedata().getheader()); mapdata.setname(imgname+"_glmprofiles"); mappedimage.setvalue(mapdata); mapdata = null; mapping = null; imagedatafloat resdata = new imagedatafloat(residual); resdata.setheader(layersimage.getimagedata().getheader()); resdata.setname(imgname+"_glmresidual"); residualimage.setvalue(resdata); resdata = null; residual = null; }
alaurent4/nighres
[ 0, 1, 0, 0 ]
16,887
@JsonGetter("offset") public String getOffset ( ) { return this.offset; }
@JsonGetter("offset") public String getOffset ( ) { return this.offset; }
@jsongetter("offset") public string getoffset ( ) { return this.offset; }
adams-okode/chirpstack-rest-sdk
[ 0, 0, 0, 0 ]
16,886
@JsonSetter("limit") public void setLimit (String value) { this.limit = value; }
@JsonSetter("limit") public void setLimit (String value) { this.limit = value; }
@jsonsetter("limit") public void setlimit (string value) { this.limit = value; }
adams-okode/chirpstack-rest-sdk
[ 0, 0, 0, 0 ]
16,888
@JsonSetter("offset") public void setOffset (String value) { this.offset = value; }
@JsonSetter("offset") public void setOffset (String value) { this.offset = value; }
@jsonsetter("offset") public void setoffset (string value) { this.offset = value; }
adams-okode/chirpstack-rest-sdk
[ 0, 0, 0, 0 ]
25,180
public static int staticCompare(UUID u1, UUID u2) { // First: major sorting by types int type = u1.version(); int diff = type - u2.version(); if (diff != 0) { return diff; } // Second: for time-based variant, order by time stamp: if (type == UUIDType.TIME_BASED.raw()) { diff = compareULongs(u1.timestamp(), u2.timestamp()); if (diff == 0) { // or if that won't work, by other bits lexically diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } else { // note: java.util.UUIDs compares with sign extension, IMO that's wrong, so: diff = compareULongs(u1.getMostSignificantBits(), u2.getMostSignificantBits()); if (diff == 0) { diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } return diff; }
public static int staticCompare(UUID u1, UUID u2) { int type = u1.version(); int diff = type - u2.version(); if (diff != 0) { return diff; } if (type == UUIDType.TIME_BASED.raw()) { diff = compareULongs(u1.timestamp(), u2.timestamp()); if (diff == 0) { diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } else { diff = compareULongs(u1.getMostSignificantBits(), u2.getMostSignificantBits()); if (diff == 0) { diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } return diff; }
public static int staticcompare(uuid u1, uuid u2) { int type = u1.version(); int diff = type - u2.version(); if (diff != 0) { return diff; } if (type == uuidtype.time_based.raw()) { diff = compareulongs(u1.timestamp(), u2.timestamp()); if (diff == 0) { diff = compareulongs(u1.getleastsignificantbits(), u2.getleastsignificantbits()); } } else { diff = compareulongs(u1.getmostsignificantbits(), u2.getmostsignificantbits()); if (diff == 0) { diff = compareulongs(u1.getleastsignificantbits(), u2.getleastsignificantbits()); } } return diff; }
andrebrait/java-uuid-generator
[ 0, 0, 0, 0 ]
653
public PlayerPathData populateStats() { this.playerEntity = strongholdPath.getPlayerEntity(); StrongholdGenerator.Start start = this.strongholdPath.getStart(); StrongholdTreeAccessor treeAccessor = (StrongholdTreeAccessor) start; List<StrongholdPathEntry> history = this.strongholdPath.getHistory(); ArrayList<StructurePiece> solution = new ArrayList<>(); StrongholdGenerator.Piece current = this.strongholdPath.getHistory().get(strongholdPath.getHistory().size() - 1).getCurrentPiece(); while (current != null) { solution.add(current); current = (StrongholdGenerator.Piece) treeAccessor.getParents().get(current); } List<StrongholdPathEntry> validEntries = history.stream() .filter(entry -> validateEntryForLoss(strongholdPath, strongholdPath.getNextEntry(entry))) .filter(entry -> !solution.contains(strongholdPath.getNextEntry(entry).getCurrentPiece()) && solution.contains(entry.getCurrentPiece())) .collect(Collectors.toList()); List<Pair<StrongholdPathEntry, Double>> losses = new ArrayList<>(); validEntries.forEach(strongholdPathEntry -> losses.add(new Pair<>(strongholdPathEntry, loss(strongholdPath, strongholdPath.getNextEntry(strongholdPathEntry), solution)))); this.inaccuracies = losses.stream().filter(pair -> pair.getRight() >= INACCURACY_THRESHOLD).map(Pair::getLeft).map(StrongholdPathEntry::getCurrentPiece).collect(Collectors.toList()); this.mistakes = losses.stream().filter(pair -> pair.getRight() >= MISTAKE_THRESHOLD).map(Pair::getLeft).map(StrongholdPathEntry::getCurrentPiece).collect(Collectors.toList()); this.blunders = losses.stream().filter(pair -> pair.getRight() >= BLUNDER_THRESHOLD).map(Pair::getLeft).map(StrongholdPathEntry::getCurrentPiece).collect(Collectors.toList()); inaccuracies.removeAll(this.mistakes); mistakes.removeAll(this.blunders); ArrayList<Pair<StrongholdGenerator.Piece, Integer>> rooms = new ArrayList<>(); history.forEach(pathEntry -> { Pair<StrongholdGenerator.Piece, Integer> pair = new Pair<>(pathEntry.getCurrentPiece(), pathEntry.getTicksSpentInPiece().get()); rooms.add(pair); }); return new PlayerPathData( rooms, strongholdPath.getTotalTime(), computeDifficulty(solution), history.stream() .filter(pathEntry -> !solution.contains(pathEntry.getCurrentPiece())) .map(StrongholdPathEntry::getTicksSpentInPiece) .mapToInt(AtomicInteger::get) .sum(), // TODO: don't count entering the first Five-Way (int) history.stream() .map(strongholdPathEntry -> strongholdPath.getNextEntry(strongholdPathEntry)) .filter(Objects::nonNull) .map(StrongholdPathEntry::getCurrentPiece) .filter(solution::contains) .count(), this.inaccuracies.size(), this.mistakes.size(), this.blunders.size(), (int) history.stream() .filter(entry -> !(entry.getCurrentPiece() instanceof StrongholdGenerator.PortalRoom)) .filter(entry -> !areAdjacent(entry.getCurrentPiece(), strongholdPath.getNextEntry(entry).getCurrentPiece(), treeAccessor)) .count(), history.size() - 1, history.stream() .filter(entry -> FEINBERG_AVG_ROOM_TIMES.containsKey(entry.getCurrentPiece().getClass())) .mapToInt(value -> value.getTicksSpentInPiece().get() - FEINBERG_AVG_ROOM_TIMES.get(value.getCurrentPiece().getClass())) .sum() ); }
public PlayerPathData populateStats() { this.playerEntity = strongholdPath.getPlayerEntity(); StrongholdGenerator.Start start = this.strongholdPath.getStart(); StrongholdTreeAccessor treeAccessor = (StrongholdTreeAccessor) start; List<StrongholdPathEntry> history = this.strongholdPath.getHistory(); ArrayList<StructurePiece> solution = new ArrayList<>(); StrongholdGenerator.Piece current = this.strongholdPath.getHistory().get(strongholdPath.getHistory().size() - 1).getCurrentPiece(); while (current != null) { solution.add(current); current = (StrongholdGenerator.Piece) treeAccessor.getParents().get(current); } List<StrongholdPathEntry> validEntries = history.stream() .filter(entry -> validateEntryForLoss(strongholdPath, strongholdPath.getNextEntry(entry))) .filter(entry -> !solution.contains(strongholdPath.getNextEntry(entry).getCurrentPiece()) && solution.contains(entry.getCurrentPiece())) .collect(Collectors.toList()); List<Pair<StrongholdPathEntry, Double>> losses = new ArrayList<>(); validEntries.forEach(strongholdPathEntry -> losses.add(new Pair<>(strongholdPathEntry, loss(strongholdPath, strongholdPath.getNextEntry(strongholdPathEntry), solution)))); this.inaccuracies = losses.stream().filter(pair -> pair.getRight() >= INACCURACY_THRESHOLD).map(Pair::getLeft).map(StrongholdPathEntry::getCurrentPiece).collect(Collectors.toList()); this.mistakes = losses.stream().filter(pair -> pair.getRight() >= MISTAKE_THRESHOLD).map(Pair::getLeft).map(StrongholdPathEntry::getCurrentPiece).collect(Collectors.toList()); this.blunders = losses.stream().filter(pair -> pair.getRight() >= BLUNDER_THRESHOLD).map(Pair::getLeft).map(StrongholdPathEntry::getCurrentPiece).collect(Collectors.toList()); inaccuracies.removeAll(this.mistakes); mistakes.removeAll(this.blunders); ArrayList<Pair<StrongholdGenerator.Piece, Integer>> rooms = new ArrayList<>(); history.forEach(pathEntry -> { Pair<StrongholdGenerator.Piece, Integer> pair = new Pair<>(pathEntry.getCurrentPiece(), pathEntry.getTicksSpentInPiece().get()); rooms.add(pair); }); return new PlayerPathData( rooms, strongholdPath.getTotalTime(), computeDifficulty(solution), history.stream() .filter(pathEntry -> !solution.contains(pathEntry.getCurrentPiece())) .map(StrongholdPathEntry::getTicksSpentInPiece) .mapToInt(AtomicInteger::get) .sum(), (int) history.stream() .map(strongholdPathEntry -> strongholdPath.getNextEntry(strongholdPathEntry)) .filter(Objects::nonNull) .map(StrongholdPathEntry::getCurrentPiece) .filter(solution::contains) .count(), this.inaccuracies.size(), this.mistakes.size(), this.blunders.size(), (int) history.stream() .filter(entry -> !(entry.getCurrentPiece() instanceof StrongholdGenerator.PortalRoom)) .filter(entry -> !areAdjacent(entry.getCurrentPiece(), strongholdPath.getNextEntry(entry).getCurrentPiece(), treeAccessor)) .count(), history.size() - 1, history.stream() .filter(entry -> FEINBERG_AVG_ROOM_TIMES.containsKey(entry.getCurrentPiece().getClass())) .mapToInt(value -> value.getTicksSpentInPiece().get() - FEINBERG_AVG_ROOM_TIMES.get(value.getCurrentPiece().getClass())) .sum() ); }
public playerpathdata populatestats() { this.playerentity = strongholdpath.getplayerentity(); strongholdgenerator.start start = this.strongholdpath.getstart(); strongholdtreeaccessor treeaccessor = (strongholdtreeaccessor) start; list<strongholdpathentry> history = this.strongholdpath.gethistory(); arraylist<structurepiece> solution = new arraylist<>(); strongholdgenerator.piece current = this.strongholdpath.gethistory().get(strongholdpath.gethistory().size() - 1).getcurrentpiece(); while (current != null) { solution.add(current); current = (strongholdgenerator.piece) treeaccessor.getparents().get(current); } list<strongholdpathentry> validentries = history.stream() .filter(entry -> validateentryforloss(strongholdpath, strongholdpath.getnextentry(entry))) .filter(entry -> !solution.contains(strongholdpath.getnextentry(entry).getcurrentpiece()) && solution.contains(entry.getcurrentpiece())) .collect(collectors.tolist()); list<pair<strongholdpathentry, double>> losses = new arraylist<>(); validentries.foreach(strongholdpathentry -> losses.add(new pair<>(strongholdpathentry, loss(strongholdpath, strongholdpath.getnextentry(strongholdpathentry), solution)))); this.inaccuracies = losses.stream().filter(pair -> pair.getright() >= inaccuracy_threshold).map(pair::getleft).map(strongholdpathentry::getcurrentpiece).collect(collectors.tolist()); this.mistakes = losses.stream().filter(pair -> pair.getright() >= mistake_threshold).map(pair::getleft).map(strongholdpathentry::getcurrentpiece).collect(collectors.tolist()); this.blunders = losses.stream().filter(pair -> pair.getright() >= blunder_threshold).map(pair::getleft).map(strongholdpathentry::getcurrentpiece).collect(collectors.tolist()); inaccuracies.removeall(this.mistakes); mistakes.removeall(this.blunders); arraylist<pair<strongholdgenerator.piece, integer>> rooms = new arraylist<>(); history.foreach(pathentry -> { pair<strongholdgenerator.piece, integer> pair = new pair<>(pathentry.getcurrentpiece(), pathentry.getticksspentinpiece().get()); rooms.add(pair); }); return new playerpathdata( rooms, strongholdpath.gettotaltime(), computedifficulty(solution), history.stream() .filter(pathentry -> !solution.contains(pathentry.getcurrentpiece())) .map(strongholdpathentry::getticksspentinpiece) .maptoint(atomicinteger::get) .sum(), (int) history.stream() .map(strongholdpathentry -> strongholdpath.getnextentry(strongholdpathentry)) .filter(objects::nonnull) .map(strongholdpathentry::getcurrentpiece) .filter(solution::contains) .count(), this.inaccuracies.size(), this.mistakes.size(), this.blunders.size(), (int) history.stream() .filter(entry -> !(entry.getcurrentpiece() instanceof strongholdgenerator.portalroom)) .filter(entry -> !areadjacent(entry.getcurrentpiece(), strongholdpath.getnextentry(entry).getcurrentpiece(), treeaccessor)) .count(), history.size() - 1, history.stream() .filter(entry -> feinberg_avg_room_times.containskey(entry.getcurrentpiece().getclass())) .maptoint(value -> value.getticksspentinpiece().get() - feinberg_avg_room_times.get(value.getcurrentpiece().getclass())) .sum() ); }
ScribbleLP/StrongholdTrainer
[ 0, 1, 0, 0 ]
17,055
public void sendEmail(String userId1, String userId2, String asgmtName, double score, String recipientMail, String reportLink) throws Exception { MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message); String stud1 = userService.findById(userId1).getfName(); String stud2 = userService.findById(userId2).getfName(); helper.setTo("[email protected]"); helper.setText("Codesniffer found plagiarised submission with similarity score" + score + "Click the below link to view the full report+\n" + "https://s3.amazonaws.com/codesniffer-reports/" + reportLink+ "/match0.html"); // to do add link in email helper.setSubject("Plag detected in " + asgmtName + " between " + stud1 + " and " + stud2); sender.send(message); }
public void sendEmail(String userId1, String userId2, String asgmtName, double score, String recipientMail, String reportLink) throws Exception { MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message); String stud1 = userService.findById(userId1).getfName(); String stud2 = userService.findById(userId2).getfName(); helper.setTo("[email protected]"); helper.setText("Codesniffer found plagiarised submission with similarity score" + score + "Click the below link to view the full report+\n" + "https://s3.amazonaws.com/codesniffer-reports/" + reportLink+ "/match0.html"); helper.setSubject("Plag detected in " + asgmtName + " between " + stud1 + " and " + stud2); sender.send(message); }
public void sendemail(string userid1, string userid2, string asgmtname, double score, string recipientmail, string reportlink) throws exception { mimemessage message = sender.createmimemessage(); mimemessagehelper helper = new mimemessagehelper(message); string stud1 = userservice.findbyid(userid1).getfname(); string stud2 = userservice.findbyid(userid2).getfname(); helper.setto("[email protected]"); helper.settext("codesniffer found plagiarised submission with similarity score" + score + "click the below link to view the full report+\n" + "https://s3.amazonaws.com/codesniffer-reports/" + reportlink+ "/match0.html"); helper.setsubject("plag detected in " + asgmtname + " between " + stud1 + " and " + stud2); sender.send(message); }
Stephen3333/codesniffer
[ 0, 1, 0, 0 ]
17,081
@Override public void refresh() throws LoginException, GSSException { // TODO: do we need to call logout() on the LoginContext? loginContext = new LoginContext("", null, null, new Configuration() { @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { ImmutableMap.Builder<String, String> options = ImmutableMap.builder(); options.put("refreshKrb5Config", "true"); options.put("doNotPrompt", "true"); options.put("useKeyTab", "true"); if (getBoolean("trino.client.debugKerberos")) { options.put("debug", "true"); } keytab.ifPresent(file -> options.put("keyTab", file.getAbsolutePath())); credentialCache.ifPresent(file -> { options.put("ticketCache", file.getAbsolutePath()); options.put("renewTGT", "true"); }); if (!keytab.isPresent() || credentialCache.isPresent()) { options.put("useTicketCache", "true"); } principal.ifPresent(value -> options.put("principal", value)); return new AppConfigurationEntry[] { new AppConfigurationEntry(Krb5LoginModule.class.getName(), REQUIRED, options.buildOrThrow()) }; } }); loginContext.login(); }
@Override public void refresh() throws LoginException, GSSException { loginContext = new LoginContext("", null, null, new Configuration() { @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { ImmutableMap.Builder<String, String> options = ImmutableMap.builder(); options.put("refreshKrb5Config", "true"); options.put("doNotPrompt", "true"); options.put("useKeyTab", "true"); if (getBoolean("trino.client.debugKerberos")) { options.put("debug", "true"); } keytab.ifPresent(file -> options.put("keyTab", file.getAbsolutePath())); credentialCache.ifPresent(file -> { options.put("ticketCache", file.getAbsolutePath()); options.put("renewTGT", "true"); }); if (!keytab.isPresent() || credentialCache.isPresent()) { options.put("useTicketCache", "true"); } principal.ifPresent(value -> options.put("principal", value)); return new AppConfigurationEntry[] { new AppConfigurationEntry(Krb5LoginModule.class.getName(), REQUIRED, options.buildOrThrow()) }; } }); loginContext.login(); }
@override public void refresh() throws loginexception, gssexception { logincontext = new logincontext("", null, null, new configuration() { @override public appconfigurationentry[] getappconfigurationentry(string name) { immutablemap.builder<string, string> options = immutablemap.builder(); options.put("refreshkrb5config", "true"); options.put("donotprompt", "true"); options.put("usekeytab", "true"); if (getboolean("trino.client.debugkerberos")) { options.put("debug", "true"); } keytab.ifpresent(file -> options.put("keytab", file.getabsolutepath())); credentialcache.ifpresent(file -> { options.put("ticketcache", file.getabsolutepath()); options.put("renewtgt", "true"); }); if (!keytab.ispresent() || credentialcache.ispresent()) { options.put("useticketcache", "true"); } principal.ifpresent(value -> options.put("principal", value)); return new appconfigurationentry[] { new appconfigurationentry(krb5loginmodule.class.getname(), required, options.buildorthrow()) }; } }); logincontext.login(); }
SanjayTechGuru/TRINO
[ 1, 0, 0, 0 ]
17,089
@Override public void reduce(BytesWritable key, Iterable<BytesWritable> values, Context context) throws IOException, InterruptedException { int defCount = 0; refs.clear(); // We only expect two values, a DEF and a reference, but there might be more. for (BytesWritable type : values) { if (type.getLength() == DEF.getLength()) { defCount++; } else { byte[] bytes = new byte[type.getLength()]; System.arraycopy(type.getBytes(), 0, bytes, 0, type.getLength()); refs.add(bytes); } } // TODO check for more than one def, should not happen List<String> refsList = new ArrayList<>(refs.size()); String keyString = null; if (defCount == 0 || refs.size() != 1) { for (byte[] ref : refs) { refsList.add(COMMA_JOINER.join(Bytes.getLong(ref), Bytes.getLong(ref, 8))); } keyString = COMMA_JOINER.join(Bytes.getLong(key.getBytes()), Bytes.getLong(key.getBytes(), 8)); LOG.error("Linked List error: Key = " + keyString + " References = " + refsList); } if (defCount == 0 && refs.size() > 0) { // this is bad, found a node that is referenced but not defined. It must have been // lost, emit some info about this node for debugging purposes. context.write(new Text(keyString), new Text(refsList.toString())); context.getCounter(Counts.UNDEFINED).increment(1); } else if (defCount > 0 && refs.size() == 0) { // node is defined but not referenced context.write(new Text(keyString), new Text("none")); context.getCounter(Counts.UNREFERENCED).increment(1); } else { if (refs.size() > 1) { if (refsList != null) { context.write(new Text(keyString), new Text(refsList.toString())); } context.getCounter(Counts.EXTRAREFERENCES).increment(refs.size() - 1); } // node is defined and referenced context.getCounter(Counts.REFERENCED).increment(1); } }
@Override public void reduce(BytesWritable key, Iterable<BytesWritable> values, Context context) throws IOException, InterruptedException { int defCount = 0; refs.clear(); for (BytesWritable type : values) { if (type.getLength() == DEF.getLength()) { defCount++; } else { byte[] bytes = new byte[type.getLength()]; System.arraycopy(type.getBytes(), 0, bytes, 0, type.getLength()); refs.add(bytes); } } List<String> refsList = new ArrayList<>(refs.size()); String keyString = null; if (defCount == 0 || refs.size() != 1) { for (byte[] ref : refs) { refsList.add(COMMA_JOINER.join(Bytes.getLong(ref), Bytes.getLong(ref, 8))); } keyString = COMMA_JOINER.join(Bytes.getLong(key.getBytes()), Bytes.getLong(key.getBytes(), 8)); LOG.error("Linked List error: Key = " + keyString + " References = " + refsList); } if (defCount == 0 && refs.size() > 0) { context.write(new Text(keyString), new Text(refsList.toString())); context.getCounter(Counts.UNDEFINED).increment(1); } else if (defCount > 0 && refs.size() == 0) { context.write(new Text(keyString), new Text("none")); context.getCounter(Counts.UNREFERENCED).increment(1); } else { if (refs.size() > 1) { if (refsList != null) { context.write(new Text(keyString), new Text(refsList.toString())); } context.getCounter(Counts.EXTRAREFERENCES).increment(refs.size() - 1); } context.getCounter(Counts.REFERENCED).increment(1); } }
@override public void reduce(byteswritable key, iterable<byteswritable> values, context context) throws ioexception, interruptedexception { int defcount = 0; refs.clear(); for (byteswritable type : values) { if (type.getlength() == def.getlength()) { defcount++; } else { byte[] bytes = new byte[type.getlength()]; system.arraycopy(type.getbytes(), 0, bytes, 0, type.getlength()); refs.add(bytes); } } list<string> refslist = new arraylist<>(refs.size()); string keystring = null; if (defcount == 0 || refs.size() != 1) { for (byte[] ref : refs) { refslist.add(comma_joiner.join(bytes.getlong(ref), bytes.getlong(ref, 8))); } keystring = comma_joiner.join(bytes.getlong(key.getbytes()), bytes.getlong(key.getbytes(), 8)); log.error("linked list error: key = " + keystring + " references = " + refslist); } if (defcount == 0 && refs.size() > 0) { context.write(new text(keystring), new text(refslist.tostring())); context.getcounter(counts.undefined).increment(1); } else if (defcount > 0 && refs.size() == 0) { context.write(new text(keystring), new text("none")); context.getcounter(counts.unreferenced).increment(1); } else { if (refs.size() > 1) { if (refslist != null) { context.write(new text(keystring), new text(refslist.tostring())); } context.getcounter(counts.extrareferences).increment(refs.size() - 1); } context.getcounter(counts.referenced).increment(1); } }
YCjia/kudu
[ 1, 1, 0, 0 ]
748
public boolean addNewTodo(Request req, Response res) { res.type("application/json"); Object o = JSON.parse(req.body()); try { if(o.getClass().equals(BasicDBObject.class)) { try { BasicDBObject dbO = (BasicDBObject) o; String owner = dbO.getString("owner"); //For some reason age is a string right now, caused by angular. //This is a problem and should not be this way but here ya go boolean status = dbO.getBoolean("status"); String body = dbO.getString("body"); String category = dbO.getString("category"); System.err.println("Adding new todo [owner=" + owner + ", category=" + category + " body=" + body + " status=" + status + ']'); return todoController.addNewTodo(owner, category, body, status); } catch(NullPointerException e) { System.err.println("A value was malformed or omitted, new todo request failed."); return false; } } else { System.err.println("Expected BasicDBObject, received " + o.getClass()); return false; } } catch(RuntimeException ree) { ree.printStackTrace(); return false; } }
public boolean addNewTodo(Request req, Response res) { res.type("application/json"); Object o = JSON.parse(req.body()); try { if(o.getClass().equals(BasicDBObject.class)) { try { BasicDBObject dbO = (BasicDBObject) o; String owner = dbO.getString("owner"); boolean status = dbO.getBoolean("status"); String body = dbO.getString("body"); String category = dbO.getString("category"); System.err.println("Adding new todo [owner=" + owner + ", category=" + category + " body=" + body + " status=" + status + ']'); return todoController.addNewTodo(owner, category, body, status); } catch(NullPointerException e) { System.err.println("A value was malformed or omitted, new todo request failed."); return false; } } else { System.err.println("Expected BasicDBObject, received " + o.getClass()); return false; } } catch(RuntimeException ree) { ree.printStackTrace(); return false; } }
public boolean addnewtodo(request req, response res) { res.type("application/json"); object o = json.parse(req.body()); try { if(o.getclass().equals(basicdbobject.class)) { try { basicdbobject dbo = (basicdbobject) o; string owner = dbo.getstring("owner"); boolean status = dbo.getboolean("status"); string body = dbo.getstring("body"); string category = dbo.getstring("category"); system.err.println("adding new todo [owner=" + owner + ", category=" + category + " body=" + body + " status=" + status + ']'); return todocontroller.addnewtodo(owner, category, body, status); } catch(nullpointerexception e) { system.err.println("a value was malformed or omitted, new todo request failed."); return false; } } else { system.err.println("expected basicdbobject, received " + o.getclass()); return false; } } catch(runtimeexception ree) { ree.printstacktrace(); return false; } }
UMM-CSci-3601-S18/lab-4-mongo-voyageurs-national-park
[ 0, 0, 1, 0 ]
25,329
public void shutdown() { try { LOGGER.info("Shutting down listener on " + host + ":" + port); running.set(false); // This isn't good, the Jedis object is not thread safe jedis.disconnect(); } catch (Exception e) { LOGGER.error("Caught exception while shutting down: " + e.getMessage()); } }
public void shutdown() { try { LOGGER.info("Shutting down listener on " + host + ":" + port); running.set(false); jedis.disconnect(); } catch (Exception e) { LOGGER.error("Caught exception while shutting down: " + e.getMessage()); } }
public void shutdown() { try { logger.info("shutting down listener on " + host + ":" + port); running.set(false); jedis.disconnect(); } catch (exception e) { logger.error("caught exception while shutting down: " + e.getmessage()); } }
Samsung/Spark-CEP
[ 1, 0, 0, 0 ]
17,260
public int getLineForVertical(int vertical) { int high = getLineCount(), low = -1, guess; while (high - low > 1) { guess = (high + low) / 2; if (getLineTop(guess) > vertical) high = guess; else low = guess; } if (low < 0) return 0; else return low; }
public int getLineForVertical(int vertical) { int high = getLineCount(), low = -1, guess; while (high - low > 1) { guess = (high + low) / 2; if (getLineTop(guess) > vertical) high = guess; else low = guess; } if (low < 0) return 0; else return low; }
public int getlineforvertical(int vertical) { int high = getlinecount(), low = -1, guess; while (high - low > 1) { guess = (high + low) / 2; if (getlinetop(guess) > vertical) high = guess; else low = guess; } if (low < 0) return 0; else return low; }
VPeruS/JotaTextEditor
[ 1, 0, 0, 0 ]
9,218
@Override public void visitElement(PsiElement element) { if (this.context.skip(element)) { return; } // TODO: the refactor this.holder.registerProblem(element, this.context.getMessage()); }
@Override public void visitElement(PsiElement element) { if (this.context.skip(element)) { return; } this.holder.registerProblem(element, this.context.getMessage()); }
@override public void visitelement(psielement element) { if (this.context.skip(element)) { return; } this.holder.registerproblem(element, this.context.getmessage()); }
aarthibl/intellibot
[ 1, 0, 0, 0 ]
9,220
private static ConfigurationOptions defaultOptions() { return ConfigurationOptions.defaults() .serializers(SpongeCommon.game().configManager().serializers()); }
private static ConfigurationOptions defaultOptions() { return ConfigurationOptions.defaults() .serializers(SpongeCommon.game().configManager().serializers()); }
private static configurationoptions defaultoptions() { return configurationoptions.defaults() .serializers(spongecommon.game().configmanager().serializers()); }
SpongePowered/Common
[ 1, 0, 0, 0 ]
25,606
@Test public void testRetrieveUserByName() { em.getTransaction().begin(); em.createNativeQuery("INSERT INTO t_users( user_id, name, date_added, description)" + " VALUES (1, 'BOOM1', '1988-09-15', 'TEST USER1');").executeUpdate(); em.createNativeQuery("INSERT INTO t_users( user_id, name, date_added, description)" + " VALUES (2, 'BOOM2', '1988-09-15', 'TEST USER2');").executeUpdate(); em.createNativeQuery("INSERT INTO t_users( user_id, name, date_added, description)" + " VALUES (3, 'BOOM3', '1988-09-15', 'TEST USER3');").executeUpdate(); em.getTransaction().commit(); List<User> users = null; try { //TODO use .equals() once we ahve overridden appropriate methods users = dao.getUsers(); } catch (Throwable th){ fail(th.getMessage()); } Calendar cal = Calendar.getInstance(); cal.set(1988, Calendar.SEPTEMBER, 15, 0, 0, 0); assertEquals(3, users.size()); for (int i = 0; i < 3; i++) { assertEquals("BOOM" + users.get(i).getId(), users.get(i).getName()); assertEquals("TEST USER" + users.get(i).getId(), users.get(i).getDescription()); assertEquals(cal.getTime().toString(), users.get(i).getDate().toString()); } }
@Test public void testRetrieveUserByName() { em.getTransaction().begin(); em.createNativeQuery("INSERT INTO t_users( user_id, name, date_added, description)" + " VALUES (1, 'BOOM1', '1988-09-15', 'TEST USER1');").executeUpdate(); em.createNativeQuery("INSERT INTO t_users( user_id, name, date_added, description)" + " VALUES (2, 'BOOM2', '1988-09-15', 'TEST USER2');").executeUpdate(); em.createNativeQuery("INSERT INTO t_users( user_id, name, date_added, description)" + " VALUES (3, 'BOOM3', '1988-09-15', 'TEST USER3');").executeUpdate(); em.getTransaction().commit(); List<User> users = null; try { users = dao.getUsers(); } catch (Throwable th){ fail(th.getMessage()); } Calendar cal = Calendar.getInstance(); cal.set(1988, Calendar.SEPTEMBER, 15, 0, 0, 0); assertEquals(3, users.size()); for (int i = 0; i < 3; i++) { assertEquals("BOOM" + users.get(i).getId(), users.get(i).getName()); assertEquals("TEST USER" + users.get(i).getId(), users.get(i).getDescription()); assertEquals(cal.getTime().toString(), users.get(i).getDate().toString()); } }
@test public void testretrieveuserbyname() { em.gettransaction().begin(); em.createnativequery("insert into t_users( user_id, name, date_added, description)" + " values (1, 'boom1', '1988-09-15', 'test user1');").executeupdate(); em.createnativequery("insert into t_users( user_id, name, date_added, description)" + " values (2, 'boom2', '1988-09-15', 'test user2');").executeupdate(); em.createnativequery("insert into t_users( user_id, name, date_added, description)" + " values (3, 'boom3', '1988-09-15', 'test user3');").executeupdate(); em.gettransaction().commit(); list<user> users = null; try { users = dao.getusers(); } catch (throwable th){ fail(th.getmessage()); } calendar cal = calendar.getinstance(); cal.set(1988, calendar.september, 15, 0, 0, 0); assertequals(3, users.size()); for (int i = 0; i < 3; i++) { assertequals("boom" + users.get(i).getid(), users.get(i).getname()); assertequals("test user" + users.get(i).getid(), users.get(i).getdescription()); assertequals(cal.gettime().tostring(), users.get(i).getdate().tostring()); } }
andrewflbarnes/debt-tracker
[ 0, 1, 0, 0 ]
1,134
private void restoreKVStateMetaData() throws IOException, StateMigrationException, RocksDBException { KeyedBackendSerializationProxy<K> serializationProxy = new KeyedBackendSerializationProxy<>(rocksDBKeyedStateBackend.userCodeClassLoader); serializationProxy.read(currentStateHandleInView); // check for key serializer compatibility; this also reconfigures the // key serializer to be compatible, if it is required and is possible if (CompatibilityUtil.resolveCompatibilityResult( serializationProxy.getKeySerializer(), UnloadableDummyTypeSerializer.class, serializationProxy.getKeySerializerConfigSnapshot(), rocksDBKeyedStateBackend.keySerializer) .isRequiresMigration()) { // TODO replace with state migration; note that key hash codes need to remain the same after migration throw new StateMigrationException("The new key serializer is not compatible to read previous keys. " + "Aborting now since state migration is currently not available"); } this.keygroupStreamCompressionDecorator = serializationProxy.isUsingKeyGroupCompression() ? SnappyStreamCompressionDecorator.INSTANCE : UncompressedStreamCompressionDecorator.INSTANCE; List<RegisteredKeyedBackendStateMetaInfo.Snapshot<?, ?>> restoredMetaInfos = serializationProxy.getStateMetaInfoSnapshots(); currentStateHandleKVStateColumnFamilies = new ArrayList<>(restoredMetaInfos.size()); //rocksDBKeyedStateBackend.restoredKvStateMetaInfos = new HashMap<>(restoredMetaInfos.size()); for (RegisteredKeyedBackendStateMetaInfo.Snapshot<?, ?> restoredMetaInfo : restoredMetaInfos) { Tuple2<ColumnFamilyHandle, RegisteredKeyedBackendStateMetaInfo<?, ?>> registeredColumn = rocksDBKeyedStateBackend.kvStateInformation.get(restoredMetaInfo.getName()); if (registeredColumn == null) { ColumnFamilyDescriptor columnFamilyDescriptor = new ColumnFamilyDescriptor( restoredMetaInfo.getName().getBytes(ConfigConstants.DEFAULT_CHARSET), rocksDBKeyedStateBackend.columnOptions); RegisteredKeyedBackendStateMetaInfo<?, ?> stateMetaInfo = new RegisteredKeyedBackendStateMetaInfo<>( restoredMetaInfo.getStateType(), restoredMetaInfo.getName(), restoredMetaInfo.getNamespaceSerializer(), restoredMetaInfo.getStateSerializer()); rocksDBKeyedStateBackend.restoredKvStateMetaInfos.put(restoredMetaInfo.getName(), restoredMetaInfo); ColumnFamilyHandle columnFamily = rocksDBKeyedStateBackend.db.createColumnFamily(columnFamilyDescriptor); registeredColumn = new Tuple2<ColumnFamilyHandle, RegisteredKeyedBackendStateMetaInfo<?, ?>>(columnFamily, stateMetaInfo); rocksDBKeyedStateBackend.kvStateInformation.put(stateMetaInfo.getName(), registeredColumn); } else { // TODO with eager state registration in place, check here for serializer migration strategies } currentStateHandleKVStateColumnFamilies.add(registeredColumn.f0); } }
private void restoreKVStateMetaData() throws IOException, StateMigrationException, RocksDBException { KeyedBackendSerializationProxy<K> serializationProxy = new KeyedBackendSerializationProxy<>(rocksDBKeyedStateBackend.userCodeClassLoader); serializationProxy.read(currentStateHandleInView); if (CompatibilityUtil.resolveCompatibilityResult( serializationProxy.getKeySerializer(), UnloadableDummyTypeSerializer.class, serializationProxy.getKeySerializerConfigSnapshot(), rocksDBKeyedStateBackend.keySerializer) .isRequiresMigration()) { throw new StateMigrationException("The new key serializer is not compatible to read previous keys. " + "Aborting now since state migration is currently not available"); } this.keygroupStreamCompressionDecorator = serializationProxy.isUsingKeyGroupCompression() ? SnappyStreamCompressionDecorator.INSTANCE : UncompressedStreamCompressionDecorator.INSTANCE; List<RegisteredKeyedBackendStateMetaInfo.Snapshot<?, ?>> restoredMetaInfos = serializationProxy.getStateMetaInfoSnapshots(); currentStateHandleKVStateColumnFamilies = new ArrayList<>(restoredMetaInfos.size()); for (RegisteredKeyedBackendStateMetaInfo.Snapshot<?, ?> restoredMetaInfo : restoredMetaInfos) { Tuple2<ColumnFamilyHandle, RegisteredKeyedBackendStateMetaInfo<?, ?>> registeredColumn = rocksDBKeyedStateBackend.kvStateInformation.get(restoredMetaInfo.getName()); if (registeredColumn == null) { ColumnFamilyDescriptor columnFamilyDescriptor = new ColumnFamilyDescriptor( restoredMetaInfo.getName().getBytes(ConfigConstants.DEFAULT_CHARSET), rocksDBKeyedStateBackend.columnOptions); RegisteredKeyedBackendStateMetaInfo<?, ?> stateMetaInfo = new RegisteredKeyedBackendStateMetaInfo<>( restoredMetaInfo.getStateType(), restoredMetaInfo.getName(), restoredMetaInfo.getNamespaceSerializer(), restoredMetaInfo.getStateSerializer()); rocksDBKeyedStateBackend.restoredKvStateMetaInfos.put(restoredMetaInfo.getName(), restoredMetaInfo); ColumnFamilyHandle columnFamily = rocksDBKeyedStateBackend.db.createColumnFamily(columnFamilyDescriptor); registeredColumn = new Tuple2<ColumnFamilyHandle, RegisteredKeyedBackendStateMetaInfo<?, ?>>(columnFamily, stateMetaInfo); rocksDBKeyedStateBackend.kvStateInformation.put(stateMetaInfo.getName(), registeredColumn); } else { } currentStateHandleKVStateColumnFamilies.add(registeredColumn.f0); } }
private void restorekvstatemetadata() throws ioexception, statemigrationexception, rocksdbexception { keyedbackendserializationproxy<k> serializationproxy = new keyedbackendserializationproxy<>(rocksdbkeyedstatebackend.usercodeclassloader); serializationproxy.read(currentstatehandleinview); if (compatibilityutil.resolvecompatibilityresult( serializationproxy.getkeyserializer(), unloadabledummytypeserializer.class, serializationproxy.getkeyserializerconfigsnapshot(), rocksdbkeyedstatebackend.keyserializer) .isrequiresmigration()) { throw new statemigrationexception("the new key serializer is not compatible to read previous keys. " + "aborting now since state migration is currently not available"); } this.keygroupstreamcompressiondecorator = serializationproxy.isusingkeygroupcompression() ? snappystreamcompressiondecorator.instance : uncompressedstreamcompressiondecorator.instance; list<registeredkeyedbackendstatemetainfo.snapshot<?, ?>> restoredmetainfos = serializationproxy.getstatemetainfosnapshots(); currentstatehandlekvstatecolumnfamilies = new arraylist<>(restoredmetainfos.size()); for (registeredkeyedbackendstatemetainfo.snapshot<?, ?> restoredmetainfo : restoredmetainfos) { tuple2<columnfamilyhandle, registeredkeyedbackendstatemetainfo<?, ?>> registeredcolumn = rocksdbkeyedstatebackend.kvstateinformation.get(restoredmetainfo.getname()); if (registeredcolumn == null) { columnfamilydescriptor columnfamilydescriptor = new columnfamilydescriptor( restoredmetainfo.getname().getbytes(configconstants.default_charset), rocksdbkeyedstatebackend.columnoptions); registeredkeyedbackendstatemetainfo<?, ?> statemetainfo = new registeredkeyedbackendstatemetainfo<>( restoredmetainfo.getstatetype(), restoredmetainfo.getname(), restoredmetainfo.getnamespaceserializer(), restoredmetainfo.getstateserializer()); rocksdbkeyedstatebackend.restoredkvstatemetainfos.put(restoredmetainfo.getname(), restoredmetainfo); columnfamilyhandle columnfamily = rocksdbkeyedstatebackend.db.createcolumnfamily(columnfamilydescriptor); registeredcolumn = new tuple2<columnfamilyhandle, registeredkeyedbackendstatemetainfo<?, ?>>(columnfamily, statemetainfo); rocksdbkeyedstatebackend.kvstateinformation.put(statemetainfo.getname(), registeredcolumn); } else { } currentstatehandlekvstatecolumnfamilies.add(registeredcolumn.f0); } }
alpinegizmo/flink
[ 1, 1, 0, 0 ]
1,136
private List<RegisteredKeyedBackendStateMetaInfo.Snapshot<?, ?>> readMetaData( StreamStateHandle metaStateHandle) throws Exception { FSDataInputStream inputStream = null; try { inputStream = metaStateHandle.openInputStream(); stateBackend.cancelStreamRegistry.registerClosable(inputStream); KeyedBackendSerializationProxy<T> serializationProxy = new KeyedBackendSerializationProxy<>(stateBackend.userCodeClassLoader); DataInputView in = new DataInputViewStreamWrapper(inputStream); serializationProxy.read(in); // check for key serializer compatibility; this also reconfigures the // key serializer to be compatible, if it is required and is possible if (CompatibilityUtil.resolveCompatibilityResult( serializationProxy.getKeySerializer(), UnloadableDummyTypeSerializer.class, serializationProxy.getKeySerializerConfigSnapshot(), stateBackend.keySerializer) .isRequiresMigration()) { // TODO replace with state migration; note that key hash codes need to remain the same after migration throw new StateMigrationException("The new key serializer is not compatible to read previous keys. " + "Aborting now since state migration is currently not available"); } return serializationProxy.getStateMetaInfoSnapshots(); } finally { if (inputStream != null) { stateBackend.cancelStreamRegistry.unregisterClosable(inputStream); inputStream.close(); } } }
private List<RegisteredKeyedBackendStateMetaInfo.Snapshot<?, ?>> readMetaData( StreamStateHandle metaStateHandle) throws Exception { FSDataInputStream inputStream = null; try { inputStream = metaStateHandle.openInputStream(); stateBackend.cancelStreamRegistry.registerClosable(inputStream); KeyedBackendSerializationProxy<T> serializationProxy = new KeyedBackendSerializationProxy<>(stateBackend.userCodeClassLoader); DataInputView in = new DataInputViewStreamWrapper(inputStream); serializationProxy.read(in); if (CompatibilityUtil.resolveCompatibilityResult( serializationProxy.getKeySerializer(), UnloadableDummyTypeSerializer.class, serializationProxy.getKeySerializerConfigSnapshot(), stateBackend.keySerializer) .isRequiresMigration()) { throw new StateMigrationException("The new key serializer is not compatible to read previous keys. " + "Aborting now since state migration is currently not available"); } return serializationProxy.getStateMetaInfoSnapshots(); } finally { if (inputStream != null) { stateBackend.cancelStreamRegistry.unregisterClosable(inputStream); inputStream.close(); } } }
private list<registeredkeyedbackendstatemetainfo.snapshot<?, ?>> readmetadata( streamstatehandle metastatehandle) throws exception { fsdatainputstream inputstream = null; try { inputstream = metastatehandle.openinputstream(); statebackend.cancelstreamregistry.registerclosable(inputstream); keyedbackendserializationproxy<t> serializationproxy = new keyedbackendserializationproxy<>(statebackend.usercodeclassloader); datainputview in = new datainputviewstreamwrapper(inputstream); serializationproxy.read(in); if (compatibilityutil.resolvecompatibilityresult( serializationproxy.getkeyserializer(), unloadabledummytypeserializer.class, serializationproxy.getkeyserializerconfigsnapshot(), statebackend.keyserializer) .isrequiresmigration()) { throw new statemigrationexception("the new key serializer is not compatible to read previous keys. " + "aborting now since state migration is currently not available"); } return serializationproxy.getstatemetainfosnapshots(); } finally { if (inputstream != null) { statebackend.cancelstreamregistry.unregisterclosable(inputstream); inputstream.close(); } } }
alpinegizmo/flink
[ 1, 0, 0, 0 ]
25,762
@Test public void testCreateDbAndTable() throws Exception { // 1. create connect context ConnectContext ctx = UtFrameUtils.createDefaultCtx(); // 2. create database db1 String createDbStmtStr = "create database db1;"; CreateDbStmt createDbStmt = (CreateDbStmt) UtFrameUtils.parseAndAnalyzeStmt(createDbStmtStr, ctx); Catalog.getCurrentCatalog().createDb(createDbStmt); System.out.println(Catalog.getCurrentCatalog().getDbNames()); // 3. create table tbl1 String createTblStmtStr = "create table db1.tbl1(k1 int) distributed by hash(k1) buckets 3 properties('replication_num' = '3'," + "'colocate_with' = 'g1');"; CreateTableStmt createTableStmt = (CreateTableStmt) UtFrameUtils.parseAndAnalyzeStmt(createTblStmtStr, ctx); Catalog.getCurrentCatalog().createTable(createTableStmt); // must set replicas' path hash, or the tablet scheduler won't work updateReplicaPathHash(); // 4. get and test the created db and table Database db = Catalog.getCurrentCatalog().getDbNullable("default_cluster:db1"); Assert.assertNotNull(db); OlapTable tbl = (OlapTable) db.getTableNullable("tbl1"); tbl.readLock(); try { Assert.assertNotNull(tbl); System.out.println(tbl.getName()); Assert.assertEquals("Doris", tbl.getEngine()); Assert.assertEquals(1, tbl.getBaseSchema().size()); } finally { tbl.readUnlock(); } // 5. process a schema change job String alterStmtStr = "alter table db1.tbl1 add column k2 int default '1'"; AlterTableStmt alterTableStmt = (AlterTableStmt) UtFrameUtils.parseAndAnalyzeStmt(alterStmtStr, ctx); Catalog.getCurrentCatalog().getAlterInstance().processAlterTable(alterTableStmt); // 6. check alter job Map<Long, AlterJobV2> alterJobs = Catalog.getCurrentCatalog().getSchemaChangeHandler().getAlterJobsV2(); Assert.assertEquals(1, alterJobs.size()); for (AlterJobV2 alterJobV2 : alterJobs.values()) { while (!alterJobV2.getJobState().isFinalState()) { System.out.println("alter job " + alterJobV2.getJobId() + " is running. state: " + alterJobV2.getJobState()); Thread.sleep(1000); } System.out.println("alter job " + alterJobV2.getJobId() + " is done. state: " + alterJobV2.getJobState()); Assert.assertEquals(AlterJobV2.JobState.FINISHED, alterJobV2.getJobState()); } OlapTable tbl1 = (OlapTable) db.getTableNullable("tbl1"); tbl1.readLock(); try { Assert.assertEquals(2, tbl1.getBaseSchema().size()); String baseIndexName = tbl1.getIndexNameById(tbl.getBaseIndexId()); Assert.assertEquals(baseIndexName, tbl1.getName()); MaterializedIndexMeta indexMeta = tbl1.getIndexMetaByIndexId(tbl1.getBaseIndexId()); Assert.assertNotNull(indexMeta); } finally { tbl1.readUnlock(); } // 7. query // TODO: we can not process real query for now. So it has to be a explain query String queryStr = "explain select * from db1.tbl1"; String a = UtFrameUtils.getSQLPlanOrErrorMsg(ctx, queryStr); System.out.println(a); StmtExecutor stmtExecutor = new StmtExecutor(ctx, queryStr); stmtExecutor.execute(); Planner planner = stmtExecutor.planner(); List<PlanFragment> fragments = planner.getFragments(); Assert.assertEquals(2, fragments.size()); PlanFragment fragment = fragments.get(1); Assert.assertTrue(fragment.getPlanRoot() instanceof OlapScanNode); Assert.assertEquals(0, fragment.getChildren().size()); // test show backends; BackendsProcDir dir = new BackendsProcDir(Catalog.getCurrentSystemInfo()); ProcResult result = dir.fetchResult(); Assert.assertEquals(BackendsProcDir.TITLE_NAMES.size(), result.getColumnNames().size()); Assert.assertEquals("{\"location\" : \"default\"}", result.getRows().get(0).get(19)); Assert.assertEquals("{\"lastSuccessReportTabletsTime\":\"N/A\",\"lastStreamLoadTime\":-1}", result.getRows().get(0).get(BackendsProcDir.TITLE_NAMES.size() - 1)); }
@Test public void testCreateDbAndTable() throws Exception { ConnectContext ctx = UtFrameUtils.createDefaultCtx(); String createDbStmtStr = "create database db1;"; CreateDbStmt createDbStmt = (CreateDbStmt) UtFrameUtils.parseAndAnalyzeStmt(createDbStmtStr, ctx); Catalog.getCurrentCatalog().createDb(createDbStmt); System.out.println(Catalog.getCurrentCatalog().getDbNames()); String createTblStmtStr = "create table db1.tbl1(k1 int) distributed by hash(k1) buckets 3 properties('replication_num' = '3'," + "'colocate_with' = 'g1');"; CreateTableStmt createTableStmt = (CreateTableStmt) UtFrameUtils.parseAndAnalyzeStmt(createTblStmtStr, ctx); Catalog.getCurrentCatalog().createTable(createTableStmt); updateReplicaPathHash(); Database db = Catalog.getCurrentCatalog().getDbNullable("default_cluster:db1"); Assert.assertNotNull(db); OlapTable tbl = (OlapTable) db.getTableNullable("tbl1"); tbl.readLock(); try { Assert.assertNotNull(tbl); System.out.println(tbl.getName()); Assert.assertEquals("Doris", tbl.getEngine()); Assert.assertEquals(1, tbl.getBaseSchema().size()); } finally { tbl.readUnlock(); } String alterStmtStr = "alter table db1.tbl1 add column k2 int default '1'"; AlterTableStmt alterTableStmt = (AlterTableStmt) UtFrameUtils.parseAndAnalyzeStmt(alterStmtStr, ctx); Catalog.getCurrentCatalog().getAlterInstance().processAlterTable(alterTableStmt); Map<Long, AlterJobV2> alterJobs = Catalog.getCurrentCatalog().getSchemaChangeHandler().getAlterJobsV2(); Assert.assertEquals(1, alterJobs.size()); for (AlterJobV2 alterJobV2 : alterJobs.values()) { while (!alterJobV2.getJobState().isFinalState()) { System.out.println("alter job " + alterJobV2.getJobId() + " is running. state: " + alterJobV2.getJobState()); Thread.sleep(1000); } System.out.println("alter job " + alterJobV2.getJobId() + " is done. state: " + alterJobV2.getJobState()); Assert.assertEquals(AlterJobV2.JobState.FINISHED, alterJobV2.getJobState()); } OlapTable tbl1 = (OlapTable) db.getTableNullable("tbl1"); tbl1.readLock(); try { Assert.assertEquals(2, tbl1.getBaseSchema().size()); String baseIndexName = tbl1.getIndexNameById(tbl.getBaseIndexId()); Assert.assertEquals(baseIndexName, tbl1.getName()); MaterializedIndexMeta indexMeta = tbl1.getIndexMetaByIndexId(tbl1.getBaseIndexId()); Assert.assertNotNull(indexMeta); } finally { tbl1.readUnlock(); } String queryStr = "explain select * from db1.tbl1"; String a = UtFrameUtils.getSQLPlanOrErrorMsg(ctx, queryStr); System.out.println(a); StmtExecutor stmtExecutor = new StmtExecutor(ctx, queryStr); stmtExecutor.execute(); Planner planner = stmtExecutor.planner(); List<PlanFragment> fragments = planner.getFragments(); Assert.assertEquals(2, fragments.size()); PlanFragment fragment = fragments.get(1); Assert.assertTrue(fragment.getPlanRoot() instanceof OlapScanNode); Assert.assertEquals(0, fragment.getChildren().size()); BackendsProcDir dir = new BackendsProcDir(Catalog.getCurrentSystemInfo()); ProcResult result = dir.fetchResult(); Assert.assertEquals(BackendsProcDir.TITLE_NAMES.size(), result.getColumnNames().size()); Assert.assertEquals("{\"location\" : \"default\"}", result.getRows().get(0).get(19)); Assert.assertEquals("{\"lastSuccessReportTabletsTime\":\"N/A\",\"lastStreamLoadTime\":-1}", result.getRows().get(0).get(BackendsProcDir.TITLE_NAMES.size() - 1)); }
@test public void testcreatedbandtable() throws exception { connectcontext ctx = utframeutils.createdefaultctx(); string createdbstmtstr = "create database db1;"; createdbstmt createdbstmt = (createdbstmt) utframeutils.parseandanalyzestmt(createdbstmtstr, ctx); catalog.getcurrentcatalog().createdb(createdbstmt); system.out.println(catalog.getcurrentcatalog().getdbnames()); string createtblstmtstr = "create table db1.tbl1(k1 int) distributed by hash(k1) buckets 3 properties('replication_num' = '3'," + "'colocate_with' = 'g1');"; createtablestmt createtablestmt = (createtablestmt) utframeutils.parseandanalyzestmt(createtblstmtstr, ctx); catalog.getcurrentcatalog().createtable(createtablestmt); updatereplicapathhash(); database db = catalog.getcurrentcatalog().getdbnullable("default_cluster:db1"); assert.assertnotnull(db); olaptable tbl = (olaptable) db.gettablenullable("tbl1"); tbl.readlock(); try { assert.assertnotnull(tbl); system.out.println(tbl.getname()); assert.assertequals("doris", tbl.getengine()); assert.assertequals(1, tbl.getbaseschema().size()); } finally { tbl.readunlock(); } string alterstmtstr = "alter table db1.tbl1 add column k2 int default '1'"; altertablestmt altertablestmt = (altertablestmt) utframeutils.parseandanalyzestmt(alterstmtstr, ctx); catalog.getcurrentcatalog().getalterinstance().processaltertable(altertablestmt); map<long, alterjobv2> alterjobs = catalog.getcurrentcatalog().getschemachangehandler().getalterjobsv2(); assert.assertequals(1, alterjobs.size()); for (alterjobv2 alterjobv2 : alterjobs.values()) { while (!alterjobv2.getjobstate().isfinalstate()) { system.out.println("alter job " + alterjobv2.getjobid() + " is running. state: " + alterjobv2.getjobstate()); thread.sleep(1000); } system.out.println("alter job " + alterjobv2.getjobid() + " is done. state: " + alterjobv2.getjobstate()); assert.assertequals(alterjobv2.jobstate.finished, alterjobv2.getjobstate()); } olaptable tbl1 = (olaptable) db.gettablenullable("tbl1"); tbl1.readlock(); try { assert.assertequals(2, tbl1.getbaseschema().size()); string baseindexname = tbl1.getindexnamebyid(tbl.getbaseindexid()); assert.assertequals(baseindexname, tbl1.getname()); materializedindexmeta indexmeta = tbl1.getindexmetabyindexid(tbl1.getbaseindexid()); assert.assertnotnull(indexmeta); } finally { tbl1.readunlock(); } string querystr = "explain select * from db1.tbl1"; string a = utframeutils.getsqlplanorerrormsg(ctx, querystr); system.out.println(a); stmtexecutor stmtexecutor = new stmtexecutor(ctx, querystr); stmtexecutor.execute(); planner planner = stmtexecutor.planner(); list<planfragment> fragments = planner.getfragments(); assert.assertequals(2, fragments.size()); planfragment fragment = fragments.get(1); assert.asserttrue(fragment.getplanroot() instanceof olapscannode); assert.assertequals(0, fragment.getchildren().size()); backendsprocdir dir = new backendsprocdir(catalog.getcurrentsysteminfo()); procresult result = dir.fetchresult(); assert.assertequals(backendsprocdir.title_names.size(), result.getcolumnnames().size()); assert.assertequals("{\"location\" : \"default\"}", result.getrows().get(0).get(19)); assert.assertequals("{\"lastsuccessreporttabletstime\":\"n/a\",\"laststreamloadtime\":-1}", result.getrows().get(0).get(backendsprocdir.title_names.size() - 1)); }
WilsonWangCS/incubator-doris
[ 1, 0, 0, 0 ]
17,588
private void registerSnapshot () { try { Statement statement = connection.createStatement(); // TODO copy over feed_id and feed_version from source namespace? // FIXME do the following only on databases that support schemas. // SQLite does not support them. Is there any advantage of schemas over flat tables? statement.execute("create schema " + tablePrefix); // TODO: Record total snapshot processing time? // Simply insert into feeds table (no need for table creation) because making a snapshot presumes that the // feeds table already exists. PreparedStatement insertStatement = connection.prepareStatement( "insert into feeds values (?, null, null, null, null, null, current_timestamp, ?)"); insertStatement.setString(1, tablePrefix); insertStatement.setString(2, feedIdToSnapshot); insertStatement.execute(); connection.commit(); LOG.info("Created new snapshot namespace: {}", insertStatement); } catch (Exception ex) { LOG.error("Exception while registering snapshot namespace in feeds table: {}", ex.getMessage()); DbUtils.closeQuietly(connection); } }
private void registerSnapshot () { try { Statement statement = connection.createStatement(); statement.execute("create schema " + tablePrefix); PreparedStatement insertStatement = connection.prepareStatement( "insert into feeds values (?, null, null, null, null, null, current_timestamp, ?)"); insertStatement.setString(1, tablePrefix); insertStatement.setString(2, feedIdToSnapshot); insertStatement.execute(); connection.commit(); LOG.info("Created new snapshot namespace: {}", insertStatement); } catch (Exception ex) { LOG.error("Exception while registering snapshot namespace in feeds table: {}", ex.getMessage()); DbUtils.closeQuietly(connection); } }
private void registersnapshot () { try { statement statement = connection.createstatement(); statement.execute("create schema " + tableprefix); preparedstatement insertstatement = connection.preparestatement( "insert into feeds values (?, null, null, null, null, null, current_timestamp, ?)"); insertstatement.setstring(1, tableprefix); insertstatement.setstring(2, feedidtosnapshot); insertstatement.execute(); connection.commit(); log.info("created new snapshot namespace: {}", insertstatement); } catch (exception ex) { log.error("exception while registering snapshot namespace in feeds table: {}", ex.getmessage()); dbutils.closequietly(connection); } }
Wilhansen/gtfs-lib
[ 1, 1, 0, 0 ]
9,474
@Override protected void channelRead0(ChannelHandlerContext ctx, CoapMessage msg) { try { // Find proper device and raise event. Device targetDevice = ctx.channel().attr(keyDevice).get(); if (targetDevice == null) { throw new InternalServerErrorException( "Unable to find device"); } if (msg instanceof CoapRequest) { onRequestReceived(targetDevice, (CoapRequest) msg); } else if (msg instanceof CoapResponse) { // TODO: Re-architecturing required IRequestChannel reqChannel = ((CoapDevice) targetDevice) .getRequestChannel(); CoapClient coapClient = (CoapClient) reqChannel; coapClient.onResponseReceived(msg); } } catch (ServerException e) { ctx.writeAndFlush(MessageBuilder.createResponse(msg, e.getErrorResponse())); Log.f(ctx.channel(), e); } catch (ClientException e) { Log.f(ctx.channel(), e); } catch (Throwable t) { Log.f(ctx.channel(), t); if (msg instanceof CoapRequest) { ctx.writeAndFlush(MessageBuilder.createResponse(msg, ResponseStatus.INTERNAL_SERVER_ERROR)); } } }
@Override protected void channelRead0(ChannelHandlerContext ctx, CoapMessage msg) { try { Device targetDevice = ctx.channel().attr(keyDevice).get(); if (targetDevice == null) { throw new InternalServerErrorException( "Unable to find device"); } if (msg instanceof CoapRequest) { onRequestReceived(targetDevice, (CoapRequest) msg); } else if (msg instanceof CoapResponse) { IRequestChannel reqChannel = ((CoapDevice) targetDevice) .getRequestChannel(); CoapClient coapClient = (CoapClient) reqChannel; coapClient.onResponseReceived(msg); } } catch (ServerException e) { ctx.writeAndFlush(MessageBuilder.createResponse(msg, e.getErrorResponse())); Log.f(ctx.channel(), e); } catch (ClientException e) { Log.f(ctx.channel(), e); } catch (Throwable t) { Log.f(ctx.channel(), t); if (msg instanceof CoapRequest) { ctx.writeAndFlush(MessageBuilder.createResponse(msg, ResponseStatus.INTERNAL_SERVER_ERROR)); } } }
@override protected void channelread0(channelhandlercontext ctx, coapmessage msg) { try { device targetdevice = ctx.channel().attr(keydevice).get(); if (targetdevice == null) { throw new internalservererrorexception( "unable to find device"); } if (msg instanceof coaprequest) { onrequestreceived(targetdevice, (coaprequest) msg); } else if (msg instanceof coapresponse) { irequestchannel reqchannel = ((coapdevice) targetdevice) .getrequestchannel(); coapclient coapclient = (coapclient) reqchannel; coapclient.onresponsereceived(msg); } } catch (serverexception e) { ctx.writeandflush(messagebuilder.createresponse(msg, e.geterrorresponse())); log.f(ctx.channel(), e); } catch (clientexception e) { log.f(ctx.channel(), e); } catch (throwable t) { log.f(ctx.channel(), t); if (msg instanceof coaprequest) { ctx.writeandflush(messagebuilder.createresponse(msg, responsestatus.internal_server_error)); } } }
SenthilKumarGS/TizenRT
[ 1, 0, 0, 0 ]
9,490
public LNode reverseListRec(LNode head) { // TODO: implement this method /*This method takes a reference to the head of a linked list and returns the reference to the head of the linked list in the reversed order. */ if(head == null) { return head; } if(head.getLink() == null) { return head; } head.getLink().setLink(head); head.setLink(null); return reverseListRec(head); // replace this statement with your own return }
public LNode reverseListRec(LNode head) { if(head == null) { return head; } if(head.getLink() == null) { return head; } head.getLink().setLink(head); head.setLink(null); return reverseListRec(head); }
public lnode reverselistrec(lnode head) { if(head == null) { return head; } if(head.getlink() == null) { return head; } head.getlink().setlink(head); head.setlink(null); return reverselistrec(head); }
Sailia/data_structures
[ 0, 1, 0, 0 ]
17,706
@SuppressWarnings("ParameterName") public void drive(double xSpeed, double ySpeed, double rot, boolean fieldRelative) { // ask the kinematics to determine our swerve command ChassisSpeeds speeds; if (fieldRelative == true) { speeds = ChassisSpeeds.fromFieldRelativeSpeeds(xSpeed, ySpeed, rot, getHeading()); } else { speeds = new ChassisSpeeds(xSpeed, ySpeed, rot); } SwerveModuleState[] swerveModuleStates = kinematics.toSwerveModuleStates(speeds); // sometime the Kinematics spits out too fast of speeds, so this will fix this SwerveDriveKinematics.desaturateWheelSpeeds(swerveModuleStates, kMaxSpeed); // command each swerve module for (int i = 0; i < modules.length; i++) { modules[i].setDesiredState(swerveModuleStates[i]); } // report our commands to the dashboard SmartDashboard.putNumber("SwerveDrive/xSpeed", xSpeed); SmartDashboard.putNumber("SwerveDrive/ySpeed", ySpeed); SmartDashboard.putNumber("SwerveDrive/rot", rot); SmartDashboard.putBoolean("SwerveDrive/fieldRelative", fieldRelative); }
@SuppressWarnings("ParameterName") public void drive(double xSpeed, double ySpeed, double rot, boolean fieldRelative) { ChassisSpeeds speeds; if (fieldRelative == true) { speeds = ChassisSpeeds.fromFieldRelativeSpeeds(xSpeed, ySpeed, rot, getHeading()); } else { speeds = new ChassisSpeeds(xSpeed, ySpeed, rot); } SwerveModuleState[] swerveModuleStates = kinematics.toSwerveModuleStates(speeds); SwerveDriveKinematics.desaturateWheelSpeeds(swerveModuleStates, kMaxSpeed); for (int i = 0; i < modules.length; i++) { modules[i].setDesiredState(swerveModuleStates[i]); } SmartDashboard.putNumber("SwerveDrive/xSpeed", xSpeed); SmartDashboard.putNumber("SwerveDrive/ySpeed", ySpeed); SmartDashboard.putNumber("SwerveDrive/rot", rot); SmartDashboard.putBoolean("SwerveDrive/fieldRelative", fieldRelative); }
@suppresswarnings("parametername") public void drive(double xspeed, double yspeed, double rot, boolean fieldrelative) { chassisspeeds speeds; if (fieldrelative == true) { speeds = chassisspeeds.fromfieldrelativespeeds(xspeed, yspeed, rot, getheading()); } else { speeds = new chassisspeeds(xspeed, yspeed, rot); } swervemodulestate[] swervemodulestates = kinematics.toswervemodulestates(speeds); swervedrivekinematics.desaturatewheelspeeds(swervemodulestates, kmaxspeed); for (int i = 0; i < modules.length; i++) { modules[i].setdesiredstate(swervemodulestates[i]); } smartdashboard.putnumber("swervedrive/xspeed", xspeed); smartdashboard.putnumber("swervedrive/yspeed", yspeed); smartdashboard.putnumber("swervedrive/rot", rot); smartdashboard.putboolean("swervedrive/fieldrelative", fieldrelative); }
Sammoore15/Robot2022-2832-altencoderforingestor
[ 0, 0, 0, 0 ]
1,344
private int generateNewTicketNumber() { //TODO: this may take foreever. fix int generated = numberGenerator.next(); while(purchased.containsKey(generated)){ generated = numberGenerator.next(); } return generated; }
private int generateNewTicketNumber() { int generated = numberGenerator.next(); while(purchased.containsKey(generated)){ generated = numberGenerator.next(); } return generated; }
private int generatenewticketnumber() { int generated = numbergenerator.next(); while(purchased.containskey(generated)){ generated = numbergenerator.next(); } return generated; }
aha0x0x/LotteryApplication
[ 0, 0, 1, 0 ]
17,729
public void setParentAtRowAndColumn(GridLayout parent, int row, int col) { // prepare the layout parameters for the EditText // TODO: Consider caching the layout params and only changing the spec row and spec column LayoutParams layoutParams = new GridLayout.LayoutParams(); layoutParams.width = LayoutParams.WRAP_CONTENT; layoutParams.height = LayoutParams.WRAP_CONTENT; // set the row and column in the correct location of the Sudoku Board layoutParams.rowSpec = GridLayout.spec(row); layoutParams.columnSpec = GridLayout.spec(col); // set the layout params and add the EditText to the GridLayout parent _text.setLayoutParams(layoutParams); parent.addView(_text); }
public void setParentAtRowAndColumn(GridLayout parent, int row, int col) { LayoutParams layoutParams = new GridLayout.LayoutParams(); layoutParams.width = LayoutParams.WRAP_CONTENT; layoutParams.height = LayoutParams.WRAP_CONTENT; layoutParams.rowSpec = GridLayout.spec(row); layoutParams.columnSpec = GridLayout.spec(col); _text.setLayoutParams(layoutParams); parent.addView(_text); }
public void setparentatrowandcolumn(gridlayout parent, int row, int col) { layoutparams layoutparams = new gridlayout.layoutparams(); layoutparams.width = layoutparams.wrap_content; layoutparams.height = layoutparams.wrap_content; layoutparams.rowspec = gridlayout.spec(row); layoutparams.columnspec = gridlayout.spec(col); _text.setlayoutparams(layoutparams); parent.addview(_text); }
SnoBoarder/Sudoku-Solver
[ 0, 1, 0, 0 ]
34,188
public void testZKSMFalse() throws ZKSetMembershipException, BigIntegerClassNotValid { BigInteger[] theSet = {new BigInteger("0"), new BigInteger("1"), new BigInteger("2"), new BigInteger("3"), new BigInteger("4")}; EncryptedInteger c = new EncryptedInteger(new BigInteger("10"), pub); BigInteger r = c.set(new BigInteger("10")); int msgIndex = 2; for (int i=0; i<10; i++) { ZKSetMembershipProver prover = new ZKSetMembershipProver(pub, theSet, msgIndex, c); BigInteger[] uVals = prover.genCommitments(); ZKSetMembershipVerifier verifier = new ZKSetMembershipVerifier(pub, c, uVals, theSet); BigInteger e = verifier.genChallenge(new BigInteger("128")); prover.computeResponse(e, r); BigInteger[] eVals = prover.getEs(); BigInteger[] vVals = prover.getVs(); assertFalse(verifier.checkResponse(eVals, vVals)); // TODO: This could actually be true with low probability } }
public void testZKSMFalse() throws ZKSetMembershipException, BigIntegerClassNotValid { BigInteger[] theSet = {new BigInteger("0"), new BigInteger("1"), new BigInteger("2"), new BigInteger("3"), new BigInteger("4")}; EncryptedInteger c = new EncryptedInteger(new BigInteger("10"), pub); BigInteger r = c.set(new BigInteger("10")); int msgIndex = 2; for (int i=0; i<10; i++) { ZKSetMembershipProver prover = new ZKSetMembershipProver(pub, theSet, msgIndex, c); BigInteger[] uVals = prover.genCommitments(); ZKSetMembershipVerifier verifier = new ZKSetMembershipVerifier(pub, c, uVals, theSet); BigInteger e = verifier.genChallenge(new BigInteger("128")); prover.computeResponse(e, r); BigInteger[] eVals = prover.getEs(); BigInteger[] vVals = prover.getVs(); assertFalse(verifier.checkResponse(eVals, vVals)); } }
public void testzksmfalse() throws zksetmembershipexception, bigintegerclassnotvalid { biginteger[] theset = {new biginteger("0"), new biginteger("1"), new biginteger("2"), new biginteger("3"), new biginteger("4")}; encryptedinteger c = new encryptedinteger(new biginteger("10"), pub); biginteger r = c.set(new biginteger("10")); int msgindex = 2; for (int i=0; i<10; i++) { zksetmembershipprover prover = new zksetmembershipprover(pub, theset, msgindex, c); biginteger[] uvals = prover.gencommitments(); zksetmembershipverifier verifier = new zksetmembershipverifier(pub, c, uvals, theset); biginteger e = verifier.genchallenge(new biginteger("128")); prover.computeresponse(e, r); biginteger[] evals = prover.getes(); biginteger[] vvals = prover.getvs(); assertfalse(verifier.checkresponse(evals, vvals)); } }
SoftwareEngineeringToolDemos/type-inference
[ 0, 0, 1, 0 ]
34,189
public void testZKSMSingleMemberSetFalse() throws ZKSetMembershipException, BigIntegerClassNotValid { BigInteger[] theSet = {new BigInteger("0")}; EncryptedInteger c = new EncryptedInteger(BigInteger.ONE, pub); BigInteger r = c.set(BigInteger.ONE); int msgIndex = 0; for (int i=0; i<10; i++) { ZKSetMembershipProver prover = new ZKSetMembershipProver(pub, theSet, msgIndex, c); BigInteger[] uVals = prover.genCommitments(); ZKSetMembershipVerifier verifier = new ZKSetMembershipVerifier(pub, c, uVals, theSet); BigInteger e = verifier.genChallenge(new BigInteger("128")); prover.computeResponse(e, r); BigInteger[] eVals = prover.getEs(); BigInteger[] vVals = prover.getVs(); assertFalse(verifier.checkResponse(eVals, vVals)); // TODO: This could actually be true with low probability } }
public void testZKSMSingleMemberSetFalse() throws ZKSetMembershipException, BigIntegerClassNotValid { BigInteger[] theSet = {new BigInteger("0")}; EncryptedInteger c = new EncryptedInteger(BigInteger.ONE, pub); BigInteger r = c.set(BigInteger.ONE); int msgIndex = 0; for (int i=0; i<10; i++) { ZKSetMembershipProver prover = new ZKSetMembershipProver(pub, theSet, msgIndex, c); BigInteger[] uVals = prover.genCommitments(); ZKSetMembershipVerifier verifier = new ZKSetMembershipVerifier(pub, c, uVals, theSet); BigInteger e = verifier.genChallenge(new BigInteger("128")); prover.computeResponse(e, r); BigInteger[] eVals = prover.getEs(); BigInteger[] vVals = prover.getVs(); assertFalse(verifier.checkResponse(eVals, vVals)); } }
public void testzksmsinglemembersetfalse() throws zksetmembershipexception, bigintegerclassnotvalid { biginteger[] theset = {new biginteger("0")}; encryptedinteger c = new encryptedinteger(biginteger.one, pub); biginteger r = c.set(biginteger.one); int msgindex = 0; for (int i=0; i<10; i++) { zksetmembershipprover prover = new zksetmembershipprover(pub, theset, msgindex, c); biginteger[] uvals = prover.gencommitments(); zksetmembershipverifier verifier = new zksetmembershipverifier(pub, c, uvals, theset); biginteger e = verifier.genchallenge(new biginteger("128")); prover.computeresponse(e, r); biginteger[] evals = prover.getes(); biginteger[] vvals = prover.getvs(); assertfalse(verifier.checkresponse(evals, vvals)); } }
SoftwareEngineeringToolDemos/type-inference
[ 0, 0, 1, 0 ]
34,190
public void testZKSMAddTrue() throws ZKSetMembershipException, PublicKeysNotEqualException, BigIntegerClassNotValid { BigInteger[] theSet = {new BigInteger("0"), new BigInteger("1"), new BigInteger("2"), new BigInteger("3"), new BigInteger("4"), new BigInteger("6")}; EncryptedInteger c1 = new EncryptedInteger(new BigInteger("2"), pub); BigInteger r1 = c1.set(new BigInteger("2")); EncryptedInteger c2 = new EncryptedInteger(new BigInteger("3"), pub); BigInteger r2 = c2.set(new BigInteger("3")); EncryptedInteger c = c1.add(c2); BigInteger r = r1.multiply(r2).mod(this.pub.getNSquared()); int msgIndex = 5; for (int i=0; i<10; i++) { ZKSetMembershipProver prover = new ZKSetMembershipProver(pub, theSet, msgIndex, c); BigInteger[] uVals = prover.genCommitments(); ZKSetMembershipVerifier verifier = new ZKSetMembershipVerifier(pub, c, uVals, theSet); BigInteger e = verifier.genChallenge(new BigInteger("128")); prover.computeResponse(e, r); BigInteger[] eVals = prover.getEs(); BigInteger[] vVals = prover.getVs(); assertFalse(verifier.checkResponse(eVals, vVals)); // TODO: This could actually be true with low probability } }
public void testZKSMAddTrue() throws ZKSetMembershipException, PublicKeysNotEqualException, BigIntegerClassNotValid { BigInteger[] theSet = {new BigInteger("0"), new BigInteger("1"), new BigInteger("2"), new BigInteger("3"), new BigInteger("4"), new BigInteger("6")}; EncryptedInteger c1 = new EncryptedInteger(new BigInteger("2"), pub); BigInteger r1 = c1.set(new BigInteger("2")); EncryptedInteger c2 = new EncryptedInteger(new BigInteger("3"), pub); BigInteger r2 = c2.set(new BigInteger("3")); EncryptedInteger c = c1.add(c2); BigInteger r = r1.multiply(r2).mod(this.pub.getNSquared()); int msgIndex = 5; for (int i=0; i<10; i++) { ZKSetMembershipProver prover = new ZKSetMembershipProver(pub, theSet, msgIndex, c); BigInteger[] uVals = prover.genCommitments(); ZKSetMembershipVerifier verifier = new ZKSetMembershipVerifier(pub, c, uVals, theSet); BigInteger e = verifier.genChallenge(new BigInteger("128")); prover.computeResponse(e, r); BigInteger[] eVals = prover.getEs(); BigInteger[] vVals = prover.getVs(); assertFalse(verifier.checkResponse(eVals, vVals)); } }
public void testzksmaddtrue() throws zksetmembershipexception, publickeysnotequalexception, bigintegerclassnotvalid { biginteger[] theset = {new biginteger("0"), new biginteger("1"), new biginteger("2"), new biginteger("3"), new biginteger("4"), new biginteger("6")}; encryptedinteger c1 = new encryptedinteger(new biginteger("2"), pub); biginteger r1 = c1.set(new biginteger("2")); encryptedinteger c2 = new encryptedinteger(new biginteger("3"), pub); biginteger r2 = c2.set(new biginteger("3")); encryptedinteger c = c1.add(c2); biginteger r = r1.multiply(r2).mod(this.pub.getnsquared()); int msgindex = 5; for (int i=0; i<10; i++) { zksetmembershipprover prover = new zksetmembershipprover(pub, theset, msgindex, c); biginteger[] uvals = prover.gencommitments(); zksetmembershipverifier verifier = new zksetmembershipverifier(pub, c, uvals, theset); biginteger e = verifier.genchallenge(new biginteger("128")); prover.computeresponse(e, r); biginteger[] evals = prover.getes(); biginteger[] vvals = prover.getvs(); assertfalse(verifier.checkresponse(evals, vvals)); } }
SoftwareEngineeringToolDemos/type-inference
[ 0, 0, 1, 0 ]
34,191
public void testZKSMManyOperations() throws ZKSetMembershipException, PublicKeysNotEqualException, BigIntegerClassNotValid { BigInteger[] theSet = {new BigInteger("0"), new BigInteger("1"), new BigInteger("2"), new BigInteger("3"), new BigInteger("4"), new BigInteger("6")}; EncryptedInteger c1 = new EncryptedInteger(new BigInteger("2"), pub); BigInteger r1 = c1.set(new BigInteger("2")); EncryptedInteger c2 = new EncryptedInteger(new BigInteger("3"), pub); BigInteger r2 = c2.set(new BigInteger("3")); EncryptedInteger c = c1.add(c2); BigInteger r = r1.multiply(r2).mod(this.pub.getNSquared()); int msgIndex = 5; for (int i=0; i<10; i++) { ZKSetMembershipProver prover = new ZKSetMembershipProver(pub, theSet, msgIndex, c); BigInteger[] uVals = prover.genCommitments(); ZKSetMembershipVerifier verifier = new ZKSetMembershipVerifier(pub, c, uVals, theSet); BigInteger e = verifier.genChallenge(new BigInteger("128")); prover.computeResponse(e, r); BigInteger[] eVals = prover.getEs(); BigInteger[] vVals = prover.getVs(); assertFalse(verifier.checkResponse(eVals, vVals)); // TODO: This could actually be true with low probability } }
public void testZKSMManyOperations() throws ZKSetMembershipException, PublicKeysNotEqualException, BigIntegerClassNotValid { BigInteger[] theSet = {new BigInteger("0"), new BigInteger("1"), new BigInteger("2"), new BigInteger("3"), new BigInteger("4"), new BigInteger("6")}; EncryptedInteger c1 = new EncryptedInteger(new BigInteger("2"), pub); BigInteger r1 = c1.set(new BigInteger("2")); EncryptedInteger c2 = new EncryptedInteger(new BigInteger("3"), pub); BigInteger r2 = c2.set(new BigInteger("3")); EncryptedInteger c = c1.add(c2); BigInteger r = r1.multiply(r2).mod(this.pub.getNSquared()); int msgIndex = 5; for (int i=0; i<10; i++) { ZKSetMembershipProver prover = new ZKSetMembershipProver(pub, theSet, msgIndex, c); BigInteger[] uVals = prover.genCommitments(); ZKSetMembershipVerifier verifier = new ZKSetMembershipVerifier(pub, c, uVals, theSet); BigInteger e = verifier.genChallenge(new BigInteger("128")); prover.computeResponse(e, r); BigInteger[] eVals = prover.getEs(); BigInteger[] vVals = prover.getVs(); assertFalse(verifier.checkResponse(eVals, vVals)); } }
public void testzksmmanyoperations() throws zksetmembershipexception, publickeysnotequalexception, bigintegerclassnotvalid { biginteger[] theset = {new biginteger("0"), new biginteger("1"), new biginteger("2"), new biginteger("3"), new biginteger("4"), new biginteger("6")}; encryptedinteger c1 = new encryptedinteger(new biginteger("2"), pub); biginteger r1 = c1.set(new biginteger("2")); encryptedinteger c2 = new encryptedinteger(new biginteger("3"), pub); biginteger r2 = c2.set(new biginteger("3")); encryptedinteger c = c1.add(c2); biginteger r = r1.multiply(r2).mod(this.pub.getnsquared()); int msgindex = 5; for (int i=0; i<10; i++) { zksetmembershipprover prover = new zksetmembershipprover(pub, theset, msgindex, c); biginteger[] uvals = prover.gencommitments(); zksetmembershipverifier verifier = new zksetmembershipverifier(pub, c, uvals, theset); biginteger e = verifier.genchallenge(new biginteger("128")); prover.computeresponse(e, r); biginteger[] evals = prover.getes(); biginteger[] vvals = prover.getvs(); assertfalse(verifier.checkresponse(evals, vvals)); } }
SoftwareEngineeringToolDemos/type-inference
[ 0, 0, 1, 0 ]
34,311
private void assertTestSummary() { int fails = testResult.fails().size(); int errors = testResult.errors().size(); int succeeds = testResult.succeeds().size(); int testCount = fails + errors + succeeds; if (testMode.isJ2cl()) { // Like Junit4, J2CL always counts errors as failures fails += errors; errors = 0; // TODO(b/32608089): jsunit_test does not report number of tests correctly testCount = 1; // Since total number of tests cannot be asserted; ensure nummber of succeeds is correct. assertThat(consoleLogs.stream().filter(x -> x.contains(": PASSED"))).hasSize(succeeds); } if (fails + errors > 0) { assertTestSummaryForFailure(fails, errors, testCount); } else { assertTestSummaryForSuccess(testCount); } }
private void assertTestSummary() { int fails = testResult.fails().size(); int errors = testResult.errors().size(); int succeeds = testResult.succeeds().size(); int testCount = fails + errors + succeeds; if (testMode.isJ2cl()) { fails += errors; errors = 0; testCount = 1; assertThat(consoleLogs.stream().filter(x -> x.contains(": PASSED"))).hasSize(succeeds); } if (fails + errors > 0) { assertTestSummaryForFailure(fails, errors, testCount); } else { assertTestSummaryForSuccess(testCount); } }
private void asserttestsummary() { int fails = testresult.fails().size(); int errors = testresult.errors().size(); int succeeds = testresult.succeeds().size(); int testcount = fails + errors + succeeds; if (testmode.isj2cl()) { fails += errors; errors = 0; testcount = 1; assertthat(consolelogs.stream().filter(x -> x.contains(": passed"))).hassize(succeeds); } if (fails + errors > 0) { asserttestsummaryforfailure(fails, errors, testcount); } else { asserttestsummaryforsuccess(testcount); } }
VishrutMehta/j2cl
[ 0, 0, 1, 0 ]
18,084
public boolean connect(long timeoutMs) { if (LOG.isDebugEnabled()) LOG.debug("Connecting to JMX URL: {} ({})", url, ((timeoutMs == -1) ? "indefinitely" : timeoutMs+"ms timeout")); long startMs = System.currentTimeMillis(); long endMs = (timeoutMs == -1) ? Long.MAX_VALUE : (startMs + timeoutMs); long currentTime = startMs; Throwable lastError = null; int attempt = 0; while (currentTime <= endMs) { currentTime = System.currentTimeMillis(); if (attempt != 0) sleep(100); //sleep 100 to prevent thrashing and facilitate interruption if (LOG.isTraceEnabled()) LOG.trace("trying connection to {} at time {}", url, currentTime); try { connect(); return true; } catch (Exception e) { Exceptions.propagateIfFatal(e); if (!terminated.get() && shouldRetryOn(e)) { if (LOG.isDebugEnabled()) LOG.debug("Attempt {} failed connecting to {} ({})", new Object[] {attempt + 1, url, e.getMessage()}); lastError = e; } else { throw Exceptions.propagate(e); } } attempt++; } LOG.warn("unable to connect to JMX url: "+url, lastError); return false; }
public boolean connect(long timeoutMs) { if (LOG.isDebugEnabled()) LOG.debug("Connecting to JMX URL: {} ({})", url, ((timeoutMs == -1) ? "indefinitely" : timeoutMs+"ms timeout")); long startMs = System.currentTimeMillis(); long endMs = (timeoutMs == -1) ? Long.MAX_VALUE : (startMs + timeoutMs); long currentTime = startMs; Throwable lastError = null; int attempt = 0; while (currentTime <= endMs) { currentTime = System.currentTimeMillis(); if (attempt != 0) sleep(100); if (LOG.isTraceEnabled()) LOG.trace("trying connection to {} at time {}", url, currentTime); try { connect(); return true; } catch (Exception e) { Exceptions.propagateIfFatal(e); if (!terminated.get() && shouldRetryOn(e)) { if (LOG.isDebugEnabled()) LOG.debug("Attempt {} failed connecting to {} ({})", new Object[] {attempt + 1, url, e.getMessage()}); lastError = e; } else { throw Exceptions.propagate(e); } } attempt++; } LOG.warn("unable to connect to JMX url: "+url, lastError); return false; }
public boolean connect(long timeoutms) { if (log.isdebugenabled()) log.debug("connecting to jmx url: {} ({})", url, ((timeoutms == -1) ? "indefinitely" : timeoutms+"ms timeout")); long startms = system.currenttimemillis(); long endms = (timeoutms == -1) ? long.max_value : (startms + timeoutms); long currenttime = startms; throwable lasterror = null; int attempt = 0; while (currenttime <= endms) { currenttime = system.currenttimemillis(); if (attempt != 0) sleep(100); if (log.istraceenabled()) log.trace("trying connection to {} at time {}", url, currenttime); try { connect(); return true; } catch (exception e) { exceptions.propagateiffatal(e); if (!terminated.get() && shouldretryon(e)) { if (log.isdebugenabled()) log.debug("attempt {} failed connecting to {} ({})", new object[] {attempt + 1, url, e.getmessage()}); lasterror = e; } else { throw exceptions.propagate(e); } } attempt++; } log.warn("unable to connect to jmx url: "+url, lasterror); return false; }
YYTVicky/brooklyn-server
[ 1, 0, 0, 0 ]
34,588
public String toString(int indentFactor) { try { StringWriter w = new StringWriter(); synchronized (w.getBuffer()) { return this.write(w, indentFactor, 0).toString(); } } catch (Exception e) { //there is no conceivable exception that can come out of this, but throw something //just in case. Want the signature to not have exception in it. throw new RuntimeException("Can not serialize JSONObject????", e); } }
public String toString(int indentFactor) { try { StringWriter w = new StringWriter(); synchronized (w.getBuffer()) { return this.write(w, indentFactor, 0).toString(); } } catch (Exception e) { throw new RuntimeException("Can not serialize JSONObject????", e); } }
public string tostring(int indentfactor) { try { stringwriter w = new stringwriter(); synchronized (w.getbuffer()) { return this.write(w, indentfactor, 0).tostring(); } } catch (exception e) { throw new runtimeexception("can not serialize jsonobject????", e); } }
agilepro/purple
[ 0, 0, 0, 0 ]
18,326
private void validate() throws IllegalStateException { Set<DateComponentOrdering> orderings = Sets.newHashSet(); if(preferred != null) { orderings.add(preferred.getOrdering()); } for(DateTimeParser parser : otherParsers) { if(!orderings.add(parser.getOrdering())) { throw new IllegalStateException("DateComponentOrdering can only be used once in a DateTimeMultiParser." + "[" + parser.getOrdering() + "]"); } } }
private void validate() throws IllegalStateException { Set<DateComponentOrdering> orderings = Sets.newHashSet(); if(preferred != null) { orderings.add(preferred.getOrdering()); } for(DateTimeParser parser : otherParsers) { if(!orderings.add(parser.getOrdering())) { throw new IllegalStateException("DateComponentOrdering can only be used once in a DateTimeMultiParser." + "[" + parser.getOrdering() + "]"); } } }
private void validate() throws illegalstateexception { set<datecomponentordering> orderings = sets.newhashset(); if(preferred != null) { orderings.add(preferred.getordering()); } for(datetimeparser parser : otherparsers) { if(!orderings.add(parser.getordering())) { throw new illegalstateexception("datecomponentordering can only be used once in a datetimemultiparser." + "[" + parser.getordering() + "]"); } } }
adam-collins/parsers
[ 1, 0, 0, 0 ]
18,370
public static String getEnumName(String fieldName ) { //Later TODO //return super.getEnumName(fieldName); return null; }
public static String getEnumName(String fieldName ) { return null; }
public static string getenumname(string fieldname ) { return null; }
aloklal99/apache-ranger
[ 0, 1, 0, 0 ]
18,422
public static StatsValues createStatsValues(StatsField statsField) { final SchemaField sf = statsField.getSchemaField(); if (null == sf) { // function stats return new NumericStatsValues(statsField); } final FieldType fieldType = sf.getType(); // TODO: allow FieldType to provide impl. if (TrieDateField.class.isInstance(fieldType) || DatePointField.class.isInstance(fieldType)) { DateStatsValues statsValues = new DateStatsValues(statsField); if (sf.multiValued()) { return new SortedDateStatsValues(statsValues, statsField); } return statsValues; } else if (TrieField.class.isInstance(fieldType) || PointField.class.isInstance(fieldType)) { NumericStatsValues statsValue = new NumericStatsValues(statsField); if (sf.multiValued()) { return new SortedNumericStatsValues(statsValue, statsField); } return statsValue; } else if (StrField.class.isInstance(fieldType)) { return new StringStatsValues(statsField); } else if (AbstractEnumField.class.isInstance(fieldType)) { return new EnumStatsValues(statsField); } else { throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "Field type " + fieldType + " is not currently supported"); } }
public static StatsValues createStatsValues(StatsField statsField) { final SchemaField sf = statsField.getSchemaField(); if (null == sf) { return new NumericStatsValues(statsField); } final FieldType fieldType = sf.getType(); if (TrieDateField.class.isInstance(fieldType) || DatePointField.class.isInstance(fieldType)) { DateStatsValues statsValues = new DateStatsValues(statsField); if (sf.multiValued()) { return new SortedDateStatsValues(statsValues, statsField); } return statsValues; } else if (TrieField.class.isInstance(fieldType) || PointField.class.isInstance(fieldType)) { NumericStatsValues statsValue = new NumericStatsValues(statsField); if (sf.multiValued()) { return new SortedNumericStatsValues(statsValue, statsField); } return statsValue; } else if (StrField.class.isInstance(fieldType)) { return new StringStatsValues(statsField); } else if (AbstractEnumField.class.isInstance(fieldType)) { return new EnumStatsValues(statsField); } else { throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "Field type " + fieldType + " is not currently supported"); } }
public static statsvalues createstatsvalues(statsfield statsfield) { final schemafield sf = statsfield.getschemafield(); if (null == sf) { return new numericstatsvalues(statsfield); } final fieldtype fieldtype = sf.gettype(); if (triedatefield.class.isinstance(fieldtype) || datepointfield.class.isinstance(fieldtype)) { datestatsvalues statsvalues = new datestatsvalues(statsfield); if (sf.multivalued()) { return new sorteddatestatsvalues(statsvalues, statsfield); } return statsvalues; } else if (triefield.class.isinstance(fieldtype) || pointfield.class.isinstance(fieldtype)) { numericstatsvalues statsvalue = new numericstatsvalues(statsfield); if (sf.multivalued()) { return new sortednumericstatsvalues(statsvalue, statsfield); } return statsvalue; } else if (strfield.class.isinstance(fieldtype)) { return new stringstatsvalues(statsfield); } else if (abstractenumfield.class.isinstance(fieldtype)) { return new enumstatsvalues(statsfield); } else { throw new solrexception( solrexception.errorcode.bad_request, "field type " + fieldtype + " is not currently supported"); } }
ackepenek/solr
[ 0, 1, 0, 0 ]
18,424
public void setSelected(@Nullable PackListWidget.PackEntry entry) { this.setSelected(entry, true); }
public void setSelected(@Nullable PackListWidget.PackEntry entry) { this.setSelected(entry, true); }
public void setselected(@nullable packlistwidget.packentry entry) { this.setselected(entry, true); }
VanillaImprovements/VVDownloader
[ 0, 1, 0, 0 ]
2,045
synchronized ImmutableList<JobEvent> getActiveEvents() { ImmutableList.Builder<JobEvent> builder = ImmutableList.builder(); for (String id : activeJobIds) { JobEvent p = eventsByJobId.get(id); assert p != null; builder.add(p); } return builder.build(); }
synchronized ImmutableList<JobEvent> getActiveEvents() { ImmutableList.Builder<JobEvent> builder = ImmutableList.builder(); for (String id : activeJobIds) { JobEvent p = eventsByJobId.get(id); assert p != null; builder.add(p); } return builder.build(); }
synchronized immutablelist<jobevent> getactiveevents() { immutablelist.builder<jobevent> builder = immutablelist.builder(); for (string id : activejobids) { jobevent p = eventsbyjobid.get(id); assert p != null; builder.add(p); } return builder.build(); }
TeamSPoon/CYC_JRTL_with_CommonLisp_OLD
[ 1, 0, 0, 0 ]
18,433
private VdsmVm appendStatistics(VdsmVm vm, V1VirtualMachineInstance vmi) { VmStatistics statistics = new VmStatistics(); statistics.setId(vm.getId()); DateTime creationTimestampDate = vmi.getMetadata().getCreationTimestamp(); if (creationTimestampDate != null) { DateTime now = DateTime.now(); Seconds seconds = Seconds.secondsBetween(creationTimestampDate, now); statistics.setElapsedTime((double) seconds.getSeconds()); } PrometheusClient promClient = getPrometheusClient(); if (promClient != null) { // FIXME: Kubevirt currently have only kubevirt_vmi_vcpu_seconds, which is total CPU time, // so we are setting it here only as system time, which is wrong. statistics.setCpuSys( promClient.getVmiCpuUsage(vmi.getMetadata().getName(), vmi.getMetadata().getNamespace()) ); } return vm.setVmStatistics(statistics) .setDiskStatistics(Collections.emptyList()) .setVmJobs(Collections.emptyList()); }
private VdsmVm appendStatistics(VdsmVm vm, V1VirtualMachineInstance vmi) { VmStatistics statistics = new VmStatistics(); statistics.setId(vm.getId()); DateTime creationTimestampDate = vmi.getMetadata().getCreationTimestamp(); if (creationTimestampDate != null) { DateTime now = DateTime.now(); Seconds seconds = Seconds.secondsBetween(creationTimestampDate, now); statistics.setElapsedTime((double) seconds.getSeconds()); } PrometheusClient promClient = getPrometheusClient(); if (promClient != null) { statistics.setCpuSys( promClient.getVmiCpuUsage(vmi.getMetadata().getName(), vmi.getMetadata().getNamespace()) ); } return vm.setVmStatistics(statistics) .setDiskStatistics(Collections.emptyList()) .setVmJobs(Collections.emptyList()); }
private vdsmvm appendstatistics(vdsmvm vm, v1virtualmachineinstance vmi) { vmstatistics statistics = new vmstatistics(); statistics.setid(vm.getid()); datetime creationtimestampdate = vmi.getmetadata().getcreationtimestamp(); if (creationtimestampdate != null) { datetime now = datetime.now(); seconds seconds = seconds.secondsbetween(creationtimestampdate, now); statistics.setelapsedtime((double) seconds.getseconds()); } prometheusclient promclient = getprometheusclient(); if (promclient != null) { statistics.setcpusys( promclient.getvmicpuusage(vmi.getmetadata().getname(), vmi.getmetadata().getnamespace()) ); } return vm.setvmstatistics(statistics) .setdiskstatistics(collections.emptylist()) .setvmjobs(collections.emptylist()); }
StevenCode/ovirt-engine
[ 0, 0, 1, 0 ]
18,456
@Test @Ignore("dbpedia is not reliable") public void testDBPedia() throws Exception { testResource(DBPEDIA, "dbpedia-berlin.sparql" ); }
@Test @Ignore("dbpedia is not reliable") public void testDBPedia() throws Exception { testResource(DBPEDIA, "dbpedia-berlin.sparql" ); }
@test @ignore("dbpedia is not reliable") public void testdbpedia() throws exception { testresource(dbpedia, "dbpedia-berlin.sparql" ); }
YYTVicky/marmotta
[ 1, 0, 0, 0 ]
34,925
@Test public void canCompleteItself() throws IOException { String jid = queue.put("Foo", null, null); queue.pop().complete(); // TODO: this test passes even when this line is removed Assert.assertEquals("complete", client.getJob(jid).getState()); }
@Test public void canCompleteItself() throws IOException { String jid = queue.put("Foo", null, null); queue.pop().complete(); Assert.assertEquals("complete", client.getJob(jid).getState()); }
@test public void cancompleteitself() throws ioexception { string jid = queue.put("foo", null, null); queue.pop().complete(); assert.assertequals("complete", client.getjob(jid).getstate()); }
Zimbra/qless-java
[ 0, 0, 0, 1 ]
18,643
@Override public boolean applies(UUID objectId, Ability source, UUID affectedControllerId, Game game) { if (affectedControllerId.equals(source.getControllerId())) { Card card = game.getCard(objectId); MageObject sourceObject = source.getSourceObject(game); if (card != null && !card.isLand() && sourceObject != null) { UUID exileId = CardUtil.getExileZoneId(game, source.getSourceId(), source.getSourceObjectZoneChangeCounter()); if (exileId != null) { ExileZone exileZone = game.getState().getExile().getExileZone(exileId); if (exileZone != null && exileZone.contains(objectId)) { if (game.getTurnNum() == turnNumber) { if (!exileZone.contains(cardId)) { // last checked card this turn is no longer exiled, so you can't cast another with this effect // TODO: Handle if card was cast/removed from exile with effect from another card. // If so, this effect could prevent player from casting although they should be able to use it return false; } } this.turnNumber = game.getTurnNum(); this.cardId = objectId; return true; } } } } return false; }
@Override public boolean applies(UUID objectId, Ability source, UUID affectedControllerId, Game game) { if (affectedControllerId.equals(source.getControllerId())) { Card card = game.getCard(objectId); MageObject sourceObject = source.getSourceObject(game); if (card != null && !card.isLand() && sourceObject != null) { UUID exileId = CardUtil.getExileZoneId(game, source.getSourceId(), source.getSourceObjectZoneChangeCounter()); if (exileId != null) { ExileZone exileZone = game.getState().getExile().getExileZone(exileId); if (exileZone != null && exileZone.contains(objectId)) { if (game.getTurnNum() == turnNumber) { if (!exileZone.contains(cardId)) { return false; } } this.turnNumber = game.getTurnNum(); this.cardId = objectId; return true; } } } } return false; }
@override public boolean applies(uuid objectid, ability source, uuid affectedcontrollerid, game game) { if (affectedcontrollerid.equals(source.getcontrollerid())) { card card = game.getcard(objectid); mageobject sourceobject = source.getsourceobject(game); if (card != null && !card.island() && sourceobject != null) { uuid exileid = cardutil.getexilezoneid(game, source.getsourceid(), source.getsourceobjectzonechangecounter()); if (exileid != null) { exilezone exilezone = game.getstate().getexile().getexilezone(exileid); if (exilezone != null && exilezone.contains(objectid)) { if (game.getturnnum() == turnnumber) { if (!exilezone.contains(cardid)) { return false; } } this.turnnumber = game.getturnnum(); this.cardid = objectid; return true; } } } } return false; }
amc8391/mage
[ 0, 0, 1, 0 ]
2,359
public static String getFilePathDiskCache(final String key) { if (sDiskLruCache == null) { return null; } // This violates encapsulation but there is no convenience method to get a filename from // DiskLruCache. Filename was derived from private class method Entry#getCleanFile // in DiskLruCache.java return sDiskLruCache.getDirectory() + File.separator + createValidDiskCacheKey(key) + "." + DISK_CACHE_INDEX; }
public static String getFilePathDiskCache(final String key) { if (sDiskLruCache == null) { return null; } return sDiskLruCache.getDirectory() + File.separator + createValidDiskCacheKey(key) + "." + DISK_CACHE_INDEX; }
public static string getfilepathdiskcache(final string key) { if (sdisklrucache == null) { return null; } return sdisklrucache.getdirectory() + file.separator + createvaliddiskcachekey(key) + "." + disk_cache_index; }
SinnerSchraderMobileMirrors/mopub-android-sdk
[ 1, 0, 0, 0 ]
18,861
private void setUpViews() { glucometerAttribution = findViewById(R.id.glucometerAttribution); glucometerImg = findViewById(R.id.glucometerImg); insertStripText = findViewById(R.id.insertStripText); upArrow = findViewById(R.id.upArrow); droplet = findViewById(R.id.dropletImg); attributionText = findViewById(R.id.attributionText); placeBloodSweatImg = findViewById(R.id.placeBloodSweatImg); placeBloodSweatText = findViewById(R.id.placeBloodSweatText); waitForReadingText = findViewById(R.id.waitForReadingText); progressBar = findViewById(R.id.progressBar); unitsText = findViewById(R.id.unitsText); glucoseLevelText = findViewById(R.id.glucoseLevelText); descriptionTxt = findViewById(R.id.descriptionTxt); detailsBtn = findViewById(R.id.detailsBtn); anotherReadingBtn = findViewById(R.id.anotherReadingBtn); showBtn = findViewById(R.id.button7); dippedBtn = findViewById(R.id.button6); stripBtn = findViewById(R.id.button8); startButton = findViewById(R.id.btnStripInserted); rgMode = findViewById(R.id.rgMode); rbBlood = findViewById(R.id.rbBlood); rbSweat = findViewById(R.id.rbSweat); rb_mg_dL = findViewById(R.id.rb_mg_dL); rb_mmol_L = findViewById(R.id.rb_mmol_L); glucometerSwitch = findViewById(R.id.glucometerSwitch); rgUnits = findViewById(R.id.rgUnits); startButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!rbSweat.isChecked() && !rbBlood.isChecked()) { Toast.makeText(GlucometerActivity.this, "Please select a mode", Toast.LENGTH_SHORT).show(); } else { instance.sendDataToArduino("start"); instance.setReading(true); glucometerSwitch.setEnabled(false); rbBlood.setEnabled(false); rbSweat.setEnabled(false); rb_mg_dL.setEnabled(false); rb_mmol_L.setEnabled(false); startButton.setEnabled(false); glucometerImg.setVisibility(View.VISIBLE); glucometerAttribution.setVisibility(View.VISIBLE); insertStripText.setVisibility(View.VISIBLE); upArrow.setVisibility(View.VISIBLE); } } }); rgMode.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.rbBlood: instance.sendDataToArduino("Blood"); droplet.setColorFilter(Color.parseColor("#F44336")); placeBloodSweatText.setText("Place blood on the test strip"); break; case R.id.rbSweat: instance.sendDataToArduino("Sweat"); droplet.setColorFilter(Color.parseColor("#1b95e0")); placeBloodSweatText.setText("Place sweat on the test strip"); break; } viewDelay(); } }); glucometerSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked){ instance.sendDataToArduino("G_on"); viewDelay(); }else { instance.sendDataToArduino("G_off"); startButton.setEnabled(false); rbBlood.setEnabled(false); rbSweat.setEnabled(false); rb_mg_dL.setEnabled(false); rb_mmol_L.setEnabled(false); glucometerSwitch.setEnabled(false); viewHandler = new Handler(); Runnable delay = new Runnable() { @Override public void run() { glucometerSwitch.setEnabled(true); } }; viewHandler.postDelayed(delay, 1000); } } }); rgUnits.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.rb_mg_dL: //TODO Display readings in mg/dL unitsText.setText("mg/dL"); break; case R.id.rb_mmol_L: //TODO Display readings in mmol/L unitsText.setText("mmol/L"); break; } viewDelay(); } }); detailsBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Move to new activity Intent intent = new Intent(GlucometerActivity.this, GlucoseReadingDetailsActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); startActivity(intent); } }); anotherReadingBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { instance.setReading(false); glucometerSwitch.setEnabled(true); rbBlood.setEnabled(true); rbSweat.setEnabled(true); rb_mg_dL.setEnabled(true); rb_mmol_L.setEnabled(true); startButton.setEnabled(true); instance.setStringData(null); instance.setCommand(null); unitsText.setVisibility(View.INVISIBLE); glucoseLevelText.setVisibility(View.INVISIBLE); descriptionTxt.setVisibility(View.INVISIBLE); detailsBtn.setVisibility(View.INVISIBLE); anotherReadingBtn.setVisibility(View.INVISIBLE); } }); showBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { instance.setCommand("show"); } }); stripBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { instance.setCommand("strip"); } }); dippedBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { instance.setCommand("dipped"); } }); }
private void setUpViews() { glucometerAttribution = findViewById(R.id.glucometerAttribution); glucometerImg = findViewById(R.id.glucometerImg); insertStripText = findViewById(R.id.insertStripText); upArrow = findViewById(R.id.upArrow); droplet = findViewById(R.id.dropletImg); attributionText = findViewById(R.id.attributionText); placeBloodSweatImg = findViewById(R.id.placeBloodSweatImg); placeBloodSweatText = findViewById(R.id.placeBloodSweatText); waitForReadingText = findViewById(R.id.waitForReadingText); progressBar = findViewById(R.id.progressBar); unitsText = findViewById(R.id.unitsText); glucoseLevelText = findViewById(R.id.glucoseLevelText); descriptionTxt = findViewById(R.id.descriptionTxt); detailsBtn = findViewById(R.id.detailsBtn); anotherReadingBtn = findViewById(R.id.anotherReadingBtn); showBtn = findViewById(R.id.button7); dippedBtn = findViewById(R.id.button6); stripBtn = findViewById(R.id.button8); startButton = findViewById(R.id.btnStripInserted); rgMode = findViewById(R.id.rgMode); rbBlood = findViewById(R.id.rbBlood); rbSweat = findViewById(R.id.rbSweat); rb_mg_dL = findViewById(R.id.rb_mg_dL); rb_mmol_L = findViewById(R.id.rb_mmol_L); glucometerSwitch = findViewById(R.id.glucometerSwitch); rgUnits = findViewById(R.id.rgUnits); startButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!rbSweat.isChecked() && !rbBlood.isChecked()) { Toast.makeText(GlucometerActivity.this, "Please select a mode", Toast.LENGTH_SHORT).show(); } else { instance.sendDataToArduino("start"); instance.setReading(true); glucometerSwitch.setEnabled(false); rbBlood.setEnabled(false); rbSweat.setEnabled(false); rb_mg_dL.setEnabled(false); rb_mmol_L.setEnabled(false); startButton.setEnabled(false); glucometerImg.setVisibility(View.VISIBLE); glucometerAttribution.setVisibility(View.VISIBLE); insertStripText.setVisibility(View.VISIBLE); upArrow.setVisibility(View.VISIBLE); } } }); rgMode.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.rbBlood: instance.sendDataToArduino("Blood"); droplet.setColorFilter(Color.parseColor("#F44336")); placeBloodSweatText.setText("Place blood on the test strip"); break; case R.id.rbSweat: instance.sendDataToArduino("Sweat"); droplet.setColorFilter(Color.parseColor("#1b95e0")); placeBloodSweatText.setText("Place sweat on the test strip"); break; } viewDelay(); } }); glucometerSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked){ instance.sendDataToArduino("G_on"); viewDelay(); }else { instance.sendDataToArduino("G_off"); startButton.setEnabled(false); rbBlood.setEnabled(false); rbSweat.setEnabled(false); rb_mg_dL.setEnabled(false); rb_mmol_L.setEnabled(false); glucometerSwitch.setEnabled(false); viewHandler = new Handler(); Runnable delay = new Runnable() { @Override public void run() { glucometerSwitch.setEnabled(true); } }; viewHandler.postDelayed(delay, 1000); } } }); rgUnits.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.rb_mg_dL: unitsText.setText("mg/dL"); break; case R.id.rb_mmol_L: unitsText.setText("mmol/L"); break; } viewDelay(); } }); detailsBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(GlucometerActivity.this, GlucoseReadingDetailsActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); startActivity(intent); } }); anotherReadingBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { instance.setReading(false); glucometerSwitch.setEnabled(true); rbBlood.setEnabled(true); rbSweat.setEnabled(true); rb_mg_dL.setEnabled(true); rb_mmol_L.setEnabled(true); startButton.setEnabled(true); instance.setStringData(null); instance.setCommand(null); unitsText.setVisibility(View.INVISIBLE); glucoseLevelText.setVisibility(View.INVISIBLE); descriptionTxt.setVisibility(View.INVISIBLE); detailsBtn.setVisibility(View.INVISIBLE); anotherReadingBtn.setVisibility(View.INVISIBLE); } }); showBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { instance.setCommand("show"); } }); stripBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { instance.setCommand("strip"); } }); dippedBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { instance.setCommand("dipped"); } }); }
private void setupviews() { glucometerattribution = findviewbyid(r.id.glucometerattribution); glucometerimg = findviewbyid(r.id.glucometerimg); insertstriptext = findviewbyid(r.id.insertstriptext); uparrow = findviewbyid(r.id.uparrow); droplet = findviewbyid(r.id.dropletimg); attributiontext = findviewbyid(r.id.attributiontext); placebloodsweatimg = findviewbyid(r.id.placebloodsweatimg); placebloodsweattext = findviewbyid(r.id.placebloodsweattext); waitforreadingtext = findviewbyid(r.id.waitforreadingtext); progressbar = findviewbyid(r.id.progressbar); unitstext = findviewbyid(r.id.unitstext); glucoseleveltext = findviewbyid(r.id.glucoseleveltext); descriptiontxt = findviewbyid(r.id.descriptiontxt); detailsbtn = findviewbyid(r.id.detailsbtn); anotherreadingbtn = findviewbyid(r.id.anotherreadingbtn); showbtn = findviewbyid(r.id.button7); dippedbtn = findviewbyid(r.id.button6); stripbtn = findviewbyid(r.id.button8); startbutton = findviewbyid(r.id.btnstripinserted); rgmode = findviewbyid(r.id.rgmode); rbblood = findviewbyid(r.id.rbblood); rbsweat = findviewbyid(r.id.rbsweat); rb_mg_dl = findviewbyid(r.id.rb_mg_dl); rb_mmol_l = findviewbyid(r.id.rb_mmol_l); glucometerswitch = findviewbyid(r.id.glucometerswitch); rgunits = findviewbyid(r.id.rgunits); startbutton.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { if (!rbsweat.ischecked() && !rbblood.ischecked()) { toast.maketext(glucometeractivity.this, "please select a mode", toast.length_short).show(); } else { instance.senddatatoarduino("start"); instance.setreading(true); glucometerswitch.setenabled(false); rbblood.setenabled(false); rbsweat.setenabled(false); rb_mg_dl.setenabled(false); rb_mmol_l.setenabled(false); startbutton.setenabled(false); glucometerimg.setvisibility(view.visible); glucometerattribution.setvisibility(view.visible); insertstriptext.setvisibility(view.visible); uparrow.setvisibility(view.visible); } } }); rgmode.setoncheckedchangelistener(new radiogroup.oncheckedchangelistener() { @override public void oncheckedchanged(radiogroup group, int checkedid) { switch (checkedid) { case r.id.rbblood: instance.senddatatoarduino("blood"); droplet.setcolorfilter(color.parsecolor("#f44336")); placebloodsweattext.settext("place blood on the test strip"); break; case r.id.rbsweat: instance.senddatatoarduino("sweat"); droplet.setcolorfilter(color.parsecolor("#1b95e0")); placebloodsweattext.settext("place sweat on the test strip"); break; } viewdelay(); } }); glucometerswitch.setoncheckedchangelistener(new compoundbutton.oncheckedchangelistener() { @override public void oncheckedchanged(compoundbutton buttonview, boolean ischecked) { if (ischecked){ instance.senddatatoarduino("g_on"); viewdelay(); }else { instance.senddatatoarduino("g_off"); startbutton.setenabled(false); rbblood.setenabled(false); rbsweat.setenabled(false); rb_mg_dl.setenabled(false); rb_mmol_l.setenabled(false); glucometerswitch.setenabled(false); viewhandler = new handler(); runnable delay = new runnable() { @override public void run() { glucometerswitch.setenabled(true); } }; viewhandler.postdelayed(delay, 1000); } } }); rgunits.setoncheckedchangelistener(new radiogroup.oncheckedchangelistener() { @override public void oncheckedchanged(radiogroup group, int checkedid) { switch (checkedid) { case r.id.rb_mg_dl: unitstext.settext("mg/dl"); break; case r.id.rb_mmol_l: unitstext.settext("mmol/l"); break; } viewdelay(); } }); detailsbtn.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { intent intent = new intent(glucometeractivity.this, glucosereadingdetailsactivity.class); intent.addflags(intent.flag_activity_no_animation); startactivity(intent); } }); anotherreadingbtn.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { instance.setreading(false); glucometerswitch.setenabled(true); rbblood.setenabled(true); rbsweat.setenabled(true); rb_mg_dl.setenabled(true); rb_mmol_l.setenabled(true); startbutton.setenabled(true); instance.setstringdata(null); instance.setcommand(null); unitstext.setvisibility(view.invisible); glucoseleveltext.setvisibility(view.invisible); descriptiontxt.setvisibility(view.invisible); detailsbtn.setvisibility(view.invisible); anotherreadingbtn.setvisibility(view.invisible); } }); showbtn.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { instance.setcommand("show"); } }); stripbtn.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { instance.setcommand("strip"); } }); dippedbtn.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { instance.setcommand("dipped"); } }); }
W6WM9M/VitalityMeter
[ 0, 1, 0, 0 ]
10,671
public void render(SpriteBatch batch) { viewport.apply(); batch.setProjectionMatrix(viewport.getCamera().combined); batch.begin(); // TODO: Draw a game over message // Feel free to get more creative with this screen. Perhaps you could cover the screen in enemy robots? float timeElapsed = Utils.secondsSince(startTime); int enemiesToShow = (int) (Constants.ENEMY_COUNT * (timeElapsed / Constants.LEVEL_END_DURATION)); for (int i = 0; i < enemiesToShow; i++){ Enemy enemy = enemies.get(i); enemy.update(0); enemy.render(batch); } font.draw(batch, Constants.GAME_OVER_MESSAGE, viewport.getWorldWidth() / 2, viewport.getWorldHeight() / 2.5f, 0, Align.center, false); batch.end(); }
public void render(SpriteBatch batch) { viewport.apply(); batch.setProjectionMatrix(viewport.getCamera().combined); batch.begin(); float timeElapsed = Utils.secondsSince(startTime); int enemiesToShow = (int) (Constants.ENEMY_COUNT * (timeElapsed / Constants.LEVEL_END_DURATION)); for (int i = 0; i < enemiesToShow; i++){ Enemy enemy = enemies.get(i); enemy.update(0); enemy.render(batch); } font.draw(batch, Constants.GAME_OVER_MESSAGE, viewport.getWorldWidth() / 2, viewport.getWorldHeight() / 2.5f, 0, Align.center, false); batch.end(); }
public void render(spritebatch batch) { viewport.apply(); batch.setprojectionmatrix(viewport.getcamera().combined); batch.begin(); float timeelapsed = utils.secondssince(starttime); int enemiestoshow = (int) (constants.enemy_count * (timeelapsed / constants.level_end_duration)); for (int i = 0; i < enemiestoshow; i++){ enemy enemy = enemies.get(i); enemy.update(0); enemy.render(batch); } font.draw(batch, constants.game_over_message, viewport.getworldwidth() / 2, viewport.getworldheight() / 2.5f, 0, align.center, false); batch.end(); }
Sceptres/ud406
[ 0, 1, 0, 0 ]
2,527
public static <T extends Enum> String getEnumI18n(Locale locale, String base, T enumToGet) { return Language.i18n(locale, base + "." + enumToGet.name().toLowerCase()); }
public static <T extends Enum> String getEnumI18n(Locale locale, String base, T enumToGet) { return Language.i18n(locale, base + "." + enumToGet.name().toLowerCase()); }
public static <t extends enum> string getenumi18n(locale locale, string base, t enumtoget) { return language.i18n(locale, base + "." + enumtoget.name().tolowercase()); }
TortleWortle/CascadeBot
[ 0, 0, 0, 0 ]
10,747
public JsonObject setMaxComments(int comments){ JsonObject result = new JsonObject(); if( dbServices.setMaxCommentsPerVideo(comments)) { result.addProperty("msg", "Max comments to collect for each video is now: " + comments); } else result.addProperty("error","Failed to set max comments per video"); return result; }
public JsonObject setMaxComments(int comments){ JsonObject result = new JsonObject(); if( dbServices.setMaxCommentsPerVideo(comments)) { result.addProperty("msg", "Max comments to collect for each video is now: " + comments); } else result.addProperty("error","Failed to set max comments per video"); return result; }
public jsonobject setmaxcomments(int comments){ jsonobject result = new jsonobject(); if( dbservices.setmaxcommentspervideo(comments)) { result.addproperty("msg", "max comments to collect for each video is now: " + comments); } else result.addproperty("error","failed to set max comments per video"); return result; }
UCY-LINC-LAB/YouTube-Twitter-Analysis
[ 0, 1, 0, 0 ]
2,557
static OzoneClient getOzoneClient(boolean secure) throws IOException { OzoneConfiguration conf = new OzoneConfiguration(); // TODO: If you don't have OM HA configured, change the following as appropriate. conf.set("ozone.om.address", "9.29.173.57:9862"); if (disableChecksum) conf.set("ozone.client.checksum.type", "NONE"); return OzoneClientFactory.getRpcClient(conf); }
static OzoneClient getOzoneClient(boolean secure) throws IOException { OzoneConfiguration conf = new OzoneConfiguration(); conf.set("ozone.om.address", "9.29.173.57:9862"); if (disableChecksum) conf.set("ozone.client.checksum.type", "NONE"); return OzoneClientFactory.getRpcClient(conf); }
static ozoneclient getozoneclient(boolean secure) throws ioexception { ozoneconfiguration conf = new ozoneconfiguration(); conf.set("ozone.om.address", "9.29.173.57:9862"); if (disablechecksum) conf.set("ozone.client.checksum.type", "none"); return ozoneclientfactory.getrpcclient(conf); }
SincereXIA/ozonerpc2
[ 1, 0, 0, 0 ]
10,797
@Unused @Doc("Init 'record' node") @Reviewed(when = "02/12/2020") @Original(version="2.38.0", path="lib/common/shapes.c", name="record_init", key="h2lcuthzwljbcjwdeidw1jiv", definition="static void record_init(node_t * n)") public static void record_init(ST_Agnode_s n) { ENTERING("h2lcuthzwljbcjwdeidw1jiv","record_init"); try { ST_field_t info; final ST_pointf ul = new ST_pointf(), sz = new ST_pointf(); boolean flip; int len; CString textbuf; /* temp buffer for storing labels */ int sides = BOTTOM | RIGHT | TOP | LEFT; /* Always use rankdir to determine how records are laid out */ flip = NOT(GD_realflip(agraphof(n))); Z.z().reclblp = ND_label(n).text; len = strlen(Z.z().reclblp); /* For some forgotten reason, an empty label is parsed into a space, so * we need at least two bytes in textbuf. */ len = MAX(len, 1); textbuf = CString.gmalloc(len + 1); if (N(info = parse_reclbl(n, flip, NOT(0), textbuf))) { UNSUPPORTED("7iezaksu9hyxhmv3r4cp4o529"); // agerr(AGERR, "bad label format %s\n", ND_label(n)->text); UNSUPPORTED("8f1id7rqm71svssnxbjo0uwcu"); // reclblp = "\\N"; UNSUPPORTED("2wv3zfqhq53941rwk4vu9p9th"); // info = parse_reclbl(n, flip, NOT(0), textbuf); } Memory.free(textbuf); size_reclbl(n, info); sz.x = POINTS(ND_width(n));; sz.y = POINTS(ND_height(n)); if (mapbool(late_string(n, Z.z().N_fixed, new CString("false")))) { UNSUPPORTED("8iu51xbtntpdf5sc00g91djym"); // if ((sz.x < info->size.x) || (sz.y < info->size.y)) { UNSUPPORTED("4vs5u30jzsrn6fpjd327xjf7r"); // /* should check that the record really won't fit, e.g., there may be no text. UNSUPPORTED("7k6yytek9nu1ihxix2880667g"); // agerr(AGWARN, "node '%s' size may be too small\n", agnameof(n)); UNSUPPORTED("bnetqzovnscxile7ao44kc0qd"); // */ UNSUPPORTED("flupwh3kosf3fkhkxllllt1"); // } } else { sz.x = MAX(info.size.x, sz.x); sz.y = MAX(info.size.y, sz.y); } resize_reclbl(info, sz, mapbool(late_string(n, Z.z().N_nojustify, new CString("false")))); ul.___(pointfof(-sz.x / 2., sz.y / 2.)); /* FIXME - is this still true: suspected to introduce ronding error - see Kluge below */ pos_reclbl(info, ul, sides); ND_width(n, PS2INCH(info.size.x)); ND_height(n, PS2INCH(info.size.y + 1)); /* Kluge!! +1 to fix rounding diff between layout and rendering otherwise we can get -1 coords in output */ ND_shape_info(n, info); } finally { LEAVING("h2lcuthzwljbcjwdeidw1jiv","poly_init"); } }
@Unused @Doc("Init 'record' node") @Reviewed(when = "02/12/2020") @Original(version="2.38.0", path="lib/common/shapes.c", name="record_init", key="h2lcuthzwljbcjwdeidw1jiv", definition="static void record_init(node_t * n)") public static void record_init(ST_Agnode_s n) { ENTERING("h2lcuthzwljbcjwdeidw1jiv","record_init"); try { ST_field_t info; final ST_pointf ul = new ST_pointf(), sz = new ST_pointf(); boolean flip; int len; CString textbuf; int sides = BOTTOM | RIGHT | TOP | LEFT; flip = NOT(GD_realflip(agraphof(n))); Z.z().reclblp = ND_label(n).text; len = strlen(Z.z().reclblp); len = MAX(len, 1); textbuf = CString.gmalloc(len + 1); if (N(info = parse_reclbl(n, flip, NOT(0), textbuf))) { UNSUPPORTED("7iezaksu9hyxhmv3r4cp4o529"); UNSUPPORTED("8f1id7rqm71svssnxbjo0uwcu"); UNSUPPORTED("2wv3zfqhq53941rwk4vu9p9th"); } Memory.free(textbuf); size_reclbl(n, info); sz.x = POINTS(ND_width(n));; sz.y = POINTS(ND_height(n)); if (mapbool(late_string(n, Z.z().N_fixed, new CString("false")))) { UNSUPPORTED("8iu51xbtntpdf5sc00g91djym"); UNSUPPORTED("4vs5u30jzsrn6fpjd327xjf7r"); UNSUPPORTED("7k6yytek9nu1ihxix2880667g"); UNSUPPORTED("bnetqzovnscxile7ao44kc0qd"); UNSUPPORTED("flupwh3kosf3fkhkxllllt1"); } else { sz.x = MAX(info.size.x, sz.x); sz.y = MAX(info.size.y, sz.y); } resize_reclbl(info, sz, mapbool(late_string(n, Z.z().N_nojustify, new CString("false")))); ul.___(pointfof(-sz.x / 2., sz.y / 2.)); pos_reclbl(info, ul, sides); ND_width(n, PS2INCH(info.size.x)); ND_height(n, PS2INCH(info.size.y + 1)); ND_shape_info(n, info); } finally { LEAVING("h2lcuthzwljbcjwdeidw1jiv","poly_init"); } }
@unused @doc("init 'record' node") @reviewed(when = "02/12/2020") @original(version="2.38.0", path="lib/common/shapes.c", name="record_init", key="h2lcuthzwljbcjwdeidw1jiv", definition="static void record_init(node_t * n)") public static void record_init(st_agnode_s n) { entering("h2lcuthzwljbcjwdeidw1jiv","record_init"); try { st_field_t info; final st_pointf ul = new st_pointf(), sz = new st_pointf(); boolean flip; int len; cstring textbuf; int sides = bottom | right | top | left; flip = not(gd_realflip(agraphof(n))); z.z().reclblp = nd_label(n).text; len = strlen(z.z().reclblp); len = max(len, 1); textbuf = cstring.gmalloc(len + 1); if (n(info = parse_reclbl(n, flip, not(0), textbuf))) { unsupported("7iezaksu9hyxhmv3r4cp4o529"); unsupported("8f1id7rqm71svssnxbjo0uwcu"); unsupported("2wv3zfqhq53941rwk4vu9p9th"); } memory.free(textbuf); size_reclbl(n, info); sz.x = points(nd_width(n));; sz.y = points(nd_height(n)); if (mapbool(late_string(n, z.z().n_fixed, new cstring("false")))) { unsupported("8iu51xbtntpdf5sc00g91djym"); unsupported("4vs5u30jzsrn6fpjd327xjf7r"); unsupported("7k6yytek9nu1ihxix2880667g"); unsupported("bnetqzovnscxile7ao44kc0qd"); unsupported("flupwh3kosf3fkhkxllllt1"); } else { sz.x = max(info.size.x, sz.x); sz.y = max(info.size.y, sz.y); } resize_reclbl(info, sz, mapbool(late_string(n, z.z().n_nojustify, new cstring("false")))); ul.___(pointfof(-sz.x / 2., sz.y / 2.)); pos_reclbl(info, ul, sides); nd_width(n, ps2inch(info.size.x)); nd_height(n, ps2inch(info.size.y + 1)); nd_shape_info(n, info); } finally { leaving("h2lcuthzwljbcjwdeidw1jiv","poly_init"); } }
SandraBSofiaH/Final-UMldoclet
[ 1, 1, 1, 0 ]
19,017
private Table buildHeader() { Skin skin = getSkin(); SquareButton ffBack = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-ff")); ffBack.flipHorizontal(); playBack = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-play"), true); playBack.flipHorizontal(); play = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-play"), true); SquareButton ffForward = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-ff")); repeatBtn = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-repeat"), true); newBtn = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-new")); newBtn.getIconCell().padTop(2).padLeft(1); SquareButton deleteBtn = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-delete")); upBtn = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-play")); upBtn.flipVertical(); downBtn = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-play")); downBtn.flipVertical(); downBtn.flipHorizontal(); Table header = new Table(); header.setBackground(skin.getDrawable("timeline-top-bar-bg")); Table topPart = new Table(); Table bottomPart = new Table(); topPart.add(ffBack).padLeft(6).left(); //topPart.add(playBack).padLeft(6).left(); // TODO: add this back when we can support topPart.add(play).padLeft(6).left(); topPart.add(ffForward).padLeft(6).left(); topPart.add(repeatBtn).padLeft(6).left(); topPart.add().growX().minWidth(20); topPart.add(upBtn).padRight(6).right(); topPart.add(downBtn).padRight(10).right(); topPart.add(newBtn).right().padRight(6); topPart.add(deleteBtn).right().padRight(6); topActionCell = topPart.add().right(); typeLabel = new Label("Items", skin); typeLabel.setColor(ColorLibrary.FONT_GRAY); bottomPart.add(typeLabel).padBottom(2).padLeft(5).left().expandX(); header.add(topPart).height(33).padBottom(1).growX().row(); header.add(bottomPart).height(16).growX().row(); /** * Build header actions */ ffBack.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.skipToStart); } }); ffForward.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.skipToEnd); } }); playBack.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.rewind); } }); play.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.play); } }); repeatBtn.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.toggleLoop); } }); deleteBtn.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.deleteSelection); } }); newBtn.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.newItem); } }); upBtn.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.up); } }); downBtn.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.down); } }); return header; }
private Table buildHeader() { Skin skin = getSkin(); SquareButton ffBack = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-ff")); ffBack.flipHorizontal(); playBack = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-play"), true); playBack.flipHorizontal(); play = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-play"), true); SquareButton ffForward = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-ff")); repeatBtn = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-repeat"), true); newBtn = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-new")); newBtn.getIconCell().padTop(2).padLeft(1); SquareButton deleteBtn = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-delete")); upBtn = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-play")); upBtn.flipVertical(); downBtn = new SquareButton(skin, skin.getDrawable("timeline-btn-icon-play")); downBtn.flipVertical(); downBtn.flipHorizontal(); Table header = new Table(); header.setBackground(skin.getDrawable("timeline-top-bar-bg")); Table topPart = new Table(); Table bottomPart = new Table(); topPart.add(ffBack).padLeft(6).left(); topPart.add(play).padLeft(6).left(); topPart.add(ffForward).padLeft(6).left(); topPart.add(repeatBtn).padLeft(6).left(); topPart.add().growX().minWidth(20); topPart.add(upBtn).padRight(6).right(); topPart.add(downBtn).padRight(10).right(); topPart.add(newBtn).right().padRight(6); topPart.add(deleteBtn).right().padRight(6); topActionCell = topPart.add().right(); typeLabel = new Label("Items", skin); typeLabel.setColor(ColorLibrary.FONT_GRAY); bottomPart.add(typeLabel).padBottom(2).padLeft(5).left().expandX(); header.add(topPart).height(33).padBottom(1).growX().row(); header.add(bottomPart).height(16).growX().row(); ffBack.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.skipToStart); } }); ffForward.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.skipToEnd); } }); playBack.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.rewind); } }); play.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.play); } }); repeatBtn.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.toggleLoop); } }); deleteBtn.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.deleteSelection); } }); newBtn.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.newItem); } }); upBtn.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.up); } }); downBtn.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { timeline.onActionButtonClicked(TimelineListener.Type.down); } }); return header; }
private table buildheader() { skin skin = getskin(); squarebutton ffback = new squarebutton(skin, skin.getdrawable("timeline-btn-icon-ff")); ffback.fliphorizontal(); playback = new squarebutton(skin, skin.getdrawable("timeline-btn-icon-play"), true); playback.fliphorizontal(); play = new squarebutton(skin, skin.getdrawable("timeline-btn-icon-play"), true); squarebutton ffforward = new squarebutton(skin, skin.getdrawable("timeline-btn-icon-ff")); repeatbtn = new squarebutton(skin, skin.getdrawable("timeline-btn-icon-repeat"), true); newbtn = new squarebutton(skin, skin.getdrawable("timeline-btn-icon-new")); newbtn.geticoncell().padtop(2).padleft(1); squarebutton deletebtn = new squarebutton(skin, skin.getdrawable("timeline-btn-icon-delete")); upbtn = new squarebutton(skin, skin.getdrawable("timeline-btn-icon-play")); upbtn.flipvertical(); downbtn = new squarebutton(skin, skin.getdrawable("timeline-btn-icon-play")); downbtn.flipvertical(); downbtn.fliphorizontal(); table header = new table(); header.setbackground(skin.getdrawable("timeline-top-bar-bg")); table toppart = new table(); table bottompart = new table(); toppart.add(ffback).padleft(6).left(); toppart.add(play).padleft(6).left(); toppart.add(ffforward).padleft(6).left(); toppart.add(repeatbtn).padleft(6).left(); toppart.add().growx().minwidth(20); toppart.add(upbtn).padright(6).right(); toppart.add(downbtn).padright(10).right(); toppart.add(newbtn).right().padright(6); toppart.add(deletebtn).right().padright(6); topactioncell = toppart.add().right(); typelabel = new label("items", skin); typelabel.setcolor(colorlibrary.font_gray); bottompart.add(typelabel).padbottom(2).padleft(5).left().expandx(); header.add(toppart).height(33).padbottom(1).growx().row(); header.add(bottompart).height(16).growx().row(); ffback.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.skiptostart); } }); ffforward.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.skiptoend); } }); playback.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.rewind); } }); play.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.play); } }); repeatbtn.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.toggleloop); } }); deletebtn.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.deleteselection); } }); newbtn.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.newitem); } }); upbtn.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.up); } }); downbtn.addlistener(new clicklistener() { @override public void clicked(inputevent event, float x, float y) { timeline.onactionbuttonclicked(timelinelistener.type.down); } }); return header; }
TheSenPie/talos
[ 0, 1, 0, 0 ]
10,974
public Map<String, Double> classifyImageVGG16(IplImage iplImage) throws IOException { NativeImageLoader loader = new NativeImageLoader(224, 224, 3); BufferedImage buffImg = OpenCV.toBufferedImage(iplImage); INDArray image = loader.asMatrix(buffImg); // TODO: we should consider the model as not only the model, but also the // input transforms // for that model. DataNormalization scaler = new VGG16ImagePreProcessor(); scaler.transform(image); INDArray[] output = vgg16.output(false, image); log.info("Complete with output from vgg16.."); // TODO: return a more native datastructure! // String predictions = TrainedModels.VGG16.decodePredictions(output[0]); // log.info("Image Predictions: {}", predictions); return decodeVGG16Predictions(output[0]); }
public Map<String, Double> classifyImageVGG16(IplImage iplImage) throws IOException { NativeImageLoader loader = new NativeImageLoader(224, 224, 3); BufferedImage buffImg = OpenCV.toBufferedImage(iplImage); INDArray image = loader.asMatrix(buffImg); DataNormalization scaler = new VGG16ImagePreProcessor(); scaler.transform(image); INDArray[] output = vgg16.output(false, image); log.info("Complete with output from vgg16.."); return decodeVGG16Predictions(output[0]); }
public map<string, double> classifyimagevgg16(iplimage iplimage) throws ioexception { nativeimageloader loader = new nativeimageloader(224, 224, 3); bufferedimage buffimg = opencv.tobufferedimage(iplimage); indarray image = loader.asmatrix(buffimg); datanormalization scaler = new vgg16imagepreprocessor(); scaler.transform(image); indarray[] output = vgg16.output(false, image); log.info("complete with output from vgg16.."); return decodevgg16predictions(output[0]); }
ShaunHolt/myrobotlab
[ 1, 0, 0, 0 ]
10,975
public Map<String, Double> classifyImageFileVGG16(String filename) throws IOException { File file = new File(filename); NativeImageLoader loader = new NativeImageLoader(224, 224, 3); INDArray image = loader.asMatrix(file); // TODO: we should consider the model as not only the model, but also the // input transforms // for that model. DataNormalization scaler = new VGG16ImagePreProcessor(); scaler.transform(image); INDArray[] output = vgg16.output(false, image); // TODO: return a more native datastructure! // String predictions = TrainedModels.VGG16.decodePredictions(output[0]); // log.info("Image Predictions: {}", predictions); return decodeVGG16Predictions(output[0]); }
public Map<String, Double> classifyImageFileVGG16(String filename) throws IOException { File file = new File(filename); NativeImageLoader loader = new NativeImageLoader(224, 224, 3); INDArray image = loader.asMatrix(file); DataNormalization scaler = new VGG16ImagePreProcessor(); scaler.transform(image); INDArray[] output = vgg16.output(false, image); return decodeVGG16Predictions(output[0]); }
public map<string, double> classifyimagefilevgg16(string filename) throws ioexception { file file = new file(filename); nativeimageloader loader = new nativeimageloader(224, 224, 3); indarray image = loader.asmatrix(file); datanormalization scaler = new vgg16imagepreprocessor(); scaler.transform(image); indarray[] output = vgg16.output(false, image); return decodevgg16predictions(output[0]); }
ShaunHolt/myrobotlab
[ 1, 0, 0, 0 ]
10,994
private long getReservedCacheSize(String uuid) { // TODO: Revisit the cache size after running more storage tests. // TODO: Figure out how to ensure ExtServices has the permissions to call // StorageStatsManager, because this is ignoring the cache... StorageManager storageManager = getSystemService(StorageManager.class); long freeBytes = 0; if (uuid == StorageManager.UUID_PRIVATE_INTERNAL) { // regular equals because of null freeBytes = Environment.getDataDirectory().getUsableSpace(); } else { final VolumeInfo vol = storageManager.findVolumeByUuid(uuid); freeBytes = vol.getPath().getUsableSpace(); } return Math.round(freeBytes * CACHE_RESERVE_RATIO); }
private long getReservedCacheSize(String uuid) { StorageManager storageManager = getSystemService(StorageManager.class); long freeBytes = 0; if (uuid == StorageManager.UUID_PRIVATE_INTERNAL) { freeBytes = Environment.getDataDirectory().getUsableSpace(); } else { final VolumeInfo vol = storageManager.findVolumeByUuid(uuid); freeBytes = vol.getPath().getUsableSpace(); } return Math.round(freeBytes * CACHE_RESERVE_RATIO); }
private long getreservedcachesize(string uuid) { storagemanager storagemanager = getsystemservice(storagemanager.class); long freebytes = 0; if (uuid == storagemanager.uuid_private_internal) { freebytes = environment.getdatadirectory().getusablespace(); } else { final volumeinfo vol = storagemanager.findvolumebyuuid(uuid); freebytes = vol.getpath().getusablespace(); } return math.round(freebytes * cache_reserve_ratio); }
Y-D-Lu/rr_frameworks_base
[ 1, 0, 0, 0 ]
11,115
public static Intent createEmailAttendeesIntent(Resources resources, String eventTitle, String body, List<String> toEmails, List<String> ccEmails, String ownerAccount) { List<String> toList = toEmails; List<String> ccList = ccEmails; if (toEmails.size() <= 0) { if (ccEmails.size() <= 0) { // TODO: Return a SEND intent if no one to email to, to at least populate // a draft email with the subject (and no recipients). throw new IllegalArgumentException("Both toEmails and ccEmails are empty."); } // Email app does not work with no "to" recipient. Move all 'cc' to 'to' // in this case. toList = ccEmails; ccList = null; } // Use the event title as the email subject (prepended with 'Re: '). String subject = null; if (eventTitle != null) { subject = resources.getString(R.string.email_subject_prefix) + eventTitle; } // Use the SENDTO intent with a 'mailto' URI, because using SEND will cause // the picker to show apps like text messaging, which does not make sense // for email addresses. We put all data in the URI instead of using the extra // Intent fields (ie. EXTRA_CC, etc) because some email apps might not handle // those (though gmail does). Uri.Builder uriBuilder = new Uri.Builder(); uriBuilder.scheme("mailto"); // We will append the first email to the 'mailto' field later (because the // current state of the Email app requires it). Add the remaining 'to' values // here. When the email codebase is updated, we can simplify this. if (toList.size() > 1) { for (int i = 1; i < toList.size(); i++) { // The Email app requires repeated parameter settings instead of // a single comma-separated list. uriBuilder.appendQueryParameter("to", toList.get(i)); } } // Add the subject parameter. if (subject != null) { uriBuilder.appendQueryParameter("subject", subject); } // Add the subject parameter. if (body != null) { uriBuilder.appendQueryParameter("body", body); } // Add the cc parameters. if (ccList != null && ccList.size() > 0) { for (String email : ccList) { uriBuilder.appendQueryParameter("cc", email); } } // Insert the first email after 'mailto:' in the URI manually since Uri.Builder // doesn't seem to have a way to do this. String uri = uriBuilder.toString(); if (uri.startsWith("mailto:")) { StringBuilder builder = new StringBuilder(uri); builder.insert(7, Uri.encode(toList.get(0))); uri = builder.toString(); } // Start the email intent. Email from the account of the calendar owner in case there // are multiple email accounts. Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse(uri)); emailIntent.putExtra("fromAccountString", ownerAccount); // Workaround a Email bug that overwrites the body with this intent extra. If not // set, it clears the body. if (body != null) { emailIntent.putExtra(Intent.EXTRA_TEXT, body); } return Intent.createChooser(emailIntent, resources.getString(R.string.email_picker_label)); }
public static Intent createEmailAttendeesIntent(Resources resources, String eventTitle, String body, List<String> toEmails, List<String> ccEmails, String ownerAccount) { List<String> toList = toEmails; List<String> ccList = ccEmails; if (toEmails.size() <= 0) { if (ccEmails.size() <= 0) { throw new IllegalArgumentException("Both toEmails and ccEmails are empty."); } toList = ccEmails; ccList = null; } String subject = null; if (eventTitle != null) { subject = resources.getString(R.string.email_subject_prefix) + eventTitle; } Uri.Builder uriBuilder = new Uri.Builder(); uriBuilder.scheme("mailto"); if (toList.size() > 1) { for (int i = 1; i < toList.size(); i++) { uriBuilder.appendQueryParameter("to", toList.get(i)); } } if (subject != null) { uriBuilder.appendQueryParameter("subject", subject); } if (body != null) { uriBuilder.appendQueryParameter("body", body); } if (ccList != null && ccList.size() > 0) { for (String email : ccList) { uriBuilder.appendQueryParameter("cc", email); } } String uri = uriBuilder.toString(); if (uri.startsWith("mailto:")) { StringBuilder builder = new StringBuilder(uri); builder.insert(7, Uri.encode(toList.get(0))); uri = builder.toString(); } Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse(uri)); emailIntent.putExtra("fromAccountString", ownerAccount); if (body != null) { emailIntent.putExtra(Intent.EXTRA_TEXT, body); } return Intent.createChooser(emailIntent, resources.getString(R.string.email_picker_label)); }
public static intent createemailattendeesintent(resources resources, string eventtitle, string body, list<string> toemails, list<string> ccemails, string owneraccount) { list<string> tolist = toemails; list<string> cclist = ccemails; if (toemails.size() <= 0) { if (ccemails.size() <= 0) { throw new illegalargumentexception("both toemails and ccemails are empty."); } tolist = ccemails; cclist = null; } string subject = null; if (eventtitle != null) { subject = resources.getstring(r.string.email_subject_prefix) + eventtitle; } uri.builder uribuilder = new uri.builder(); uribuilder.scheme("mailto"); if (tolist.size() > 1) { for (int i = 1; i < tolist.size(); i++) { uribuilder.appendqueryparameter("to", tolist.get(i)); } } if (subject != null) { uribuilder.appendqueryparameter("subject", subject); } if (body != null) { uribuilder.appendqueryparameter("body", body); } if (cclist != null && cclist.size() > 0) { for (string email : cclist) { uribuilder.appendqueryparameter("cc", email); } } string uri = uribuilder.tostring(); if (uri.startswith("mailto:")) { stringbuilder builder = new stringbuilder(uri); builder.insert(7, uri.encode(tolist.get(0))); uri = builder.tostring(); } intent emailintent = new intent(intent.action_sendto, uri.parse(uri)); emailintent.putextra("fromaccountstring", owneraccount); if (body != null) { emailintent.putextra(intent.extra_text, body); } return intent.createchooser(emailintent, resources.getstring(r.string.email_picker_label)); }
Shusshu/Android-RecurrencePicker
[ 0, 1, 1, 0 ]
11,181
@NotNull public abstract Biome getBiome(@NotNull WorldInfo worldInfo, int x, int y, int z);
@NotNull public abstract Biome getBiome(@NotNull WorldInfo worldInfo, int x, int y, int z);
@notnull public abstract biome getbiome(@notnull worldinfo worldinfo, int x, int y, int z);
abcd1234-byte/spigot2
[ 0, 1, 0, 0 ]
3,159
private static void addField(SolrInputDocument doc, String fieldName, Object value, Class type, String dynamicFieldSuffix) { if (type.isArray()) return; // TODO: Array types not supported yet ... if (dynamicFieldSuffix == null) { dynamicFieldSuffix = getDefaultDynamicFieldMapping(type); // treat strings with multiple terms as text only if using the default! if ("_s".equals(dynamicFieldSuffix)) { String str = (String)value; if (str.indexOf(" ") != -1) dynamicFieldSuffix = "_t"; } } if (dynamicFieldSuffix != null) // don't auto-map if we don't have a type doc.addField(fieldName + dynamicFieldSuffix, value); }
private static void addField(SolrInputDocument doc, String fieldName, Object value, Class type, String dynamicFieldSuffix) { if (type.isArray()) return; if (dynamicFieldSuffix == null) { dynamicFieldSuffix = getDefaultDynamicFieldMapping(type); if ("_s".equals(dynamicFieldSuffix)) { String str = (String)value; if (str.indexOf(" ") != -1) dynamicFieldSuffix = "_t"; } } if (dynamicFieldSuffix != null) doc.addField(fieldName + dynamicFieldSuffix, value); }
private static void addfield(solrinputdocument doc, string fieldname, object value, class type, string dynamicfieldsuffix) { if (type.isarray()) return; if (dynamicfieldsuffix == null) { dynamicfieldsuffix = getdefaultdynamicfieldmapping(type); if ("_s".equals(dynamicfieldsuffix)) { string str = (string)value; if (str.indexof(" ") != -1) dynamicfieldsuffix = "_t"; } } if (dynamicfieldsuffix != null) doc.addfield(fieldname + dynamicfieldsuffix, value); }
Stratio/spark-solr
[ 1, 0, 0, 0 ]
11,407
protected Path getRealPath2(TVFSAbstractPath path) { List<String> list = new ArrayList<>(); for (String s : path.path) { list.add(s); } Path p; if (list.isEmpty()) { //p = virtualFS.getTvFileSystem().getPath(virtualFS.getName().getName()); p = fileSystem.getRootPath(); } else { String first = ""; String others[] = null; // if (list.size() >= 1) { // first = list.get(0); // } // if (list.size() > 1) { // others = new String[list.size() - 1]; // // for (int i = 1; i < list.size(); i++) { // others[i - 1] = list.get(i); // } // } //if (others == null) { p = fileSystem.getRootPath().resolve(list.stream().collect(Collectors.joining(fileSystem.getSeparator()))); //p = virtualFS.getTvFileSystem().getPath(virtualFS.getName().getName(),first); // } else { // p = virtualFS.getTvFileSystem().getPath(first, others); // } } return p; }
protected Path getRealPath2(TVFSAbstractPath path) { List<String> list = new ArrayList<>(); for (String s : path.path) { list.add(s); } Path p; if (list.isEmpty()) { p = fileSystem.getRootPath(); } else { String first = ""; String others[] = null; p = fileSystem.getRootPath().resolve(list.stream().collect(Collectors.joining(fileSystem.getSeparator()))); } return p; }
protected path getrealpath2(tvfsabstractpath path) { list<string> list = new arraylist<>(); for (string s : path.path) { list.add(s); } path p; if (list.isempty()) { p = filesystem.getrootpath(); } else { string first = ""; string others[] = null; p = filesystem.getrootpath().resolve(list.stream().collect(collectors.joining(filesystem.getseparator()))); } return p; }
abarhub/tinyvfs
[ 1, 0, 0, 0 ]
11,482
@Override public void populateGui() { // Filler this.getFiller(); // Items for (Map.Entry<Material, Integer> entry : collector.getContents().entrySet()) { // Args Material material = entry.getKey(); int startAmount = entry.getValue(); double startValue = plugin.getCollectorManager().value(collector, material); List<String> lore = Color.color(plugin.getConfig().getStringList("guis.contents.item.lore").stream().map(text -> text.replace("%amount%", String.format("%,d", startAmount)).replace("%value%", String.format("%,.1f", startValue))).collect(Collectors.toList())); List<Component> components = lore.stream().map(Component::text).collect(Collectors.toList()); // Add this.addItem(ItemBuilder.from(material).name(Component.text(this.getNicedEnumString(material.name()))).lore(components).asGuiItem(event -> { // Cancel event.setCancelled(true); // Args Player player = (Player) event.getWhoClicked(); int amount = collector.getMaterialAmount(material); double total = plugin.getCollectorManager().sell(collector, material); // Check if (total == 0.0d) { // TODO: Make it so collectors don't pick up items which can't be sold return; } // Deposit & Inform plugin.getMoneyManager().pay(player.getUniqueId(), total); String message = plugin.getConfig().getString("messages.material-sold"); if (message != null && !message.isEmpty()) player.sendMessage(Color.color(message.replace("%amount%", String.format("%,d", amount)).replace("%material%", this.getNicedEnumString(material.name())).replace("%total%", String.format("%.1f", total)))); // Update this.update(); })); } // Navigation this.setItem(3, 3, ItemBuilder.from(Material.ARROW).name(Component.text(Color.color("Previous"))).asGuiItem(event -> this.previous())); this.setItem(3, 7, ItemBuilder.from(Material.ARROW).name(Component.text(Color.color("Next"))).asGuiItem(event -> this.next())); }
@Override public void populateGui() { this.getFiller(); for (Map.Entry<Material, Integer> entry : collector.getContents().entrySet()) { Material material = entry.getKey(); int startAmount = entry.getValue(); double startValue = plugin.getCollectorManager().value(collector, material); List<String> lore = Color.color(plugin.getConfig().getStringList("guis.contents.item.lore").stream().map(text -> text.replace("%amount%", String.format("%,d", startAmount)).replace("%value%", String.format("%,.1f", startValue))).collect(Collectors.toList())); List<Component> components = lore.stream().map(Component::text).collect(Collectors.toList()); this.addItem(ItemBuilder.from(material).name(Component.text(this.getNicedEnumString(material.name()))).lore(components).asGuiItem(event -> { event.setCancelled(true); Player player = (Player) event.getWhoClicked(); int amount = collector.getMaterialAmount(material); double total = plugin.getCollectorManager().sell(collector, material); if (total == 0.0d) { return; } plugin.getMoneyManager().pay(player.getUniqueId(), total); String message = plugin.getConfig().getString("messages.material-sold"); if (message != null && !message.isEmpty()) player.sendMessage(Color.color(message.replace("%amount%", String.format("%,d", amount)).replace("%material%", this.getNicedEnumString(material.name())).replace("%total%", String.format("%.1f", total)))); this.update(); })); } this.setItem(3, 3, ItemBuilder.from(Material.ARROW).name(Component.text(Color.color("Previous"))).asGuiItem(event -> this.previous())); this.setItem(3, 7, ItemBuilder.from(Material.ARROW).name(Component.text(Color.color("Next"))).asGuiItem(event -> this.next())); }
@override public void populategui() { this.getfiller(); for (map.entry<material, integer> entry : collector.getcontents().entryset()) { material material = entry.getkey(); int startamount = entry.getvalue(); double startvalue = plugin.getcollectormanager().value(collector, material); list<string> lore = color.color(plugin.getconfig().getstringlist("guis.contents.item.lore").stream().map(text -> text.replace("%amount%", string.format("%,d", startamount)).replace("%value%", string.format("%,.1f", startvalue))).collect(collectors.tolist())); list<component> components = lore.stream().map(component::text).collect(collectors.tolist()); this.additem(itembuilder.from(material).name(component.text(this.getnicedenumstring(material.name()))).lore(components).asguiitem(event -> { event.setcancelled(true); player player = (player) event.getwhoclicked(); int amount = collector.getmaterialamount(material); double total = plugin.getcollectormanager().sell(collector, material); if (total == 0.0d) { return; } plugin.getmoneymanager().pay(player.getuniqueid(), total); string message = plugin.getconfig().getstring("messages.material-sold"); if (message != null && !message.isempty()) player.sendmessage(color.color(message.replace("%amount%", string.format("%,d", amount)).replace("%material%", this.getnicedenumstring(material.name())).replace("%total%", string.format("%.1f", total)))); this.update(); })); } this.setitem(3, 3, itembuilder.from(material.arrow).name(component.text(color.color("previous"))).asguiitem(event -> this.previous())); this.setitem(3, 7, itembuilder.from(material.arrow).name(component.text(color.color("next"))).asguiitem(event -> this.next())); }
Workinq/AsyncCollectors
[ 0, 1, 0, 0 ]
3,400
protected List<String> updateProvisioning(Map<String, File> artifacts, Provisioner provisionService) throws Exception { ResourceInstaller resourceInstaller = provisionService.getResourceInstaller(); Map<ResourceIdentity, Resource> installedResources = getInstalledResources(provisionService); Map<Requirement, Resource> requirements = new HashMap<Requirement, Resource>(); Set<Map.Entry<String, File>> entries = artifacts.entrySet(); List<Resource> resourcesToInstall = new ArrayList<Resource>(); List<String> resourceUrisInstalled = new ArrayList<String>(); updateStatus("installing", null, null); for (Map.Entry<String, File> entry : entries) { String name = entry.getKey(); File file = entry.getValue(); String coords = name; int idx = coords.lastIndexOf(':'); if (idx > 0) { coords = name.substring(idx + 1); } // lets switch to gravia's mvn coordinates coords = coords.replace('/', ':'); MavenCoordinates mvnCoords = parse(coords); URL url = file.toURI().toURL(); if (url == null) { LOGGER.warn("Could not find URL for file " + file); continue; } // TODO lets just detect wars for now for servlet engines - how do we decide on WildFly? boolean isShared = !isWar(name, file); Resource resource = findMavenResource(mvnCoords, url, isShared); if (resource == null) { LOGGER.warn("Could not find resource for " + mvnCoords + " and " + url); } else { ResourceIdentity identity = resource.getIdentity(); Resource oldResource = installedResources.remove(identity); if (oldResource == null && !resourcehandleMap.containsKey(identity)) { if (isShared) { // TODO lest not deploy shared stuff for now since bundles throw an exception when trying to stop them // which breaks the tests ;) LOGGER.debug("TODO not installing " + (isShared ? "shared" : "non-shared") + " resource: " + identity); } else { LOGGER.info("Installing " + (isShared ? "shared" : "non-shared") + " resource: " + identity); resourcesToInstall.add(resource); resourceUrisInstalled.add(name); } } } } for (Resource installedResource : installedResources.values()) { ResourceIdentity identity = installedResource.getIdentity(); ResourceHandle resourceHandle = resourcehandleMap.get(identity); if (resourceHandle == null) { // TODO should not really happen when we can ask about the installed Resources LOGGER.warn("TODO: Cannot uninstall " + installedResource + " as we have no handle!"); } else { LOGGER.info("Uninstalling " + installedResource); resourceHandle.uninstall(); resourcehandleMap.remove(identity); LOGGER.info("Uninstalled " + installedResource); } } if (resourcesToInstall.size() > 0) { LOGGER.info("Installing " + resourcesToInstall.size() + " resource(s)"); Set<ResourceHandle> resourceHandles = new LinkedHashSet<>(); ResourceInstaller.Context context = new DefaultInstallerContext(resourcesToInstall, requirements); for (Resource resource : resourcesToInstall) { resourceHandles.add(resourceInstaller.installResource(context, resource)); } LOGGER.info("Got " + resourceHandles.size() + " resource handle(s)"); for (ResourceHandle resourceHandle : resourceHandles) { resourcehandleMap.put(resourceHandle.getResource().getIdentity(), resourceHandle); } } return resourceUrisInstalled; }
protected List<String> updateProvisioning(Map<String, File> artifacts, Provisioner provisionService) throws Exception { ResourceInstaller resourceInstaller = provisionService.getResourceInstaller(); Map<ResourceIdentity, Resource> installedResources = getInstalledResources(provisionService); Map<Requirement, Resource> requirements = new HashMap<Requirement, Resource>(); Set<Map.Entry<String, File>> entries = artifacts.entrySet(); List<Resource> resourcesToInstall = new ArrayList<Resource>(); List<String> resourceUrisInstalled = new ArrayList<String>(); updateStatus("installing", null, null); for (Map.Entry<String, File> entry : entries) { String name = entry.getKey(); File file = entry.getValue(); String coords = name; int idx = coords.lastIndexOf(':'); if (idx > 0) { coords = name.substring(idx + 1); } coords = coords.replace('/', ':'); MavenCoordinates mvnCoords = parse(coords); URL url = file.toURI().toURL(); if (url == null) { LOGGER.warn("Could not find URL for file " + file); continue; } boolean isShared = !isWar(name, file); Resource resource = findMavenResource(mvnCoords, url, isShared); if (resource == null) { LOGGER.warn("Could not find resource for " + mvnCoords + " and " + url); } else { ResourceIdentity identity = resource.getIdentity(); Resource oldResource = installedResources.remove(identity); if (oldResource == null && !resourcehandleMap.containsKey(identity)) { if (isShared) { LOGGER.debug("TODO not installing " + (isShared ? "shared" : "non-shared") + " resource: " + identity); } else { LOGGER.info("Installing " + (isShared ? "shared" : "non-shared") + " resource: " + identity); resourcesToInstall.add(resource); resourceUrisInstalled.add(name); } } } } for (Resource installedResource : installedResources.values()) { ResourceIdentity identity = installedResource.getIdentity(); ResourceHandle resourceHandle = resourcehandleMap.get(identity); if (resourceHandle == null) { LOGGER.warn("TODO: Cannot uninstall " + installedResource + " as we have no handle!"); } else { LOGGER.info("Uninstalling " + installedResource); resourceHandle.uninstall(); resourcehandleMap.remove(identity); LOGGER.info("Uninstalled " + installedResource); } } if (resourcesToInstall.size() > 0) { LOGGER.info("Installing " + resourcesToInstall.size() + " resource(s)"); Set<ResourceHandle> resourceHandles = new LinkedHashSet<>(); ResourceInstaller.Context context = new DefaultInstallerContext(resourcesToInstall, requirements); for (Resource resource : resourcesToInstall) { resourceHandles.add(resourceInstaller.installResource(context, resource)); } LOGGER.info("Got " + resourceHandles.size() + " resource handle(s)"); for (ResourceHandle resourceHandle : resourceHandles) { resourcehandleMap.put(resourceHandle.getResource().getIdentity(), resourceHandle); } } return resourceUrisInstalled; }
protected list<string> updateprovisioning(map<string, file> artifacts, provisioner provisionservice) throws exception { resourceinstaller resourceinstaller = provisionservice.getresourceinstaller(); map<resourceidentity, resource> installedresources = getinstalledresources(provisionservice); map<requirement, resource> requirements = new hashmap<requirement, resource>(); set<map.entry<string, file>> entries = artifacts.entryset(); list<resource> resourcestoinstall = new arraylist<resource>(); list<string> resourceurisinstalled = new arraylist<string>(); updatestatus("installing", null, null); for (map.entry<string, file> entry : entries) { string name = entry.getkey(); file file = entry.getvalue(); string coords = name; int idx = coords.lastindexof(':'); if (idx > 0) { coords = name.substring(idx + 1); } coords = coords.replace('/', ':'); mavencoordinates mvncoords = parse(coords); url url = file.touri().tourl(); if (url == null) { logger.warn("could not find url for file " + file); continue; } boolean isshared = !iswar(name, file); resource resource = findmavenresource(mvncoords, url, isshared); if (resource == null) { logger.warn("could not find resource for " + mvncoords + " and " + url); } else { resourceidentity identity = resource.getidentity(); resource oldresource = installedresources.remove(identity); if (oldresource == null && !resourcehandlemap.containskey(identity)) { if (isshared) { logger.debug("todo not installing " + (isshared ? "shared" : "non-shared") + " resource: " + identity); } else { logger.info("installing " + (isshared ? "shared" : "non-shared") + " resource: " + identity); resourcestoinstall.add(resource); resourceurisinstalled.add(name); } } } } for (resource installedresource : installedresources.values()) { resourceidentity identity = installedresource.getidentity(); resourcehandle resourcehandle = resourcehandlemap.get(identity); if (resourcehandle == null) { logger.warn("todo: cannot uninstall " + installedresource + " as we have no handle!"); } else { logger.info("uninstalling " + installedresource); resourcehandle.uninstall(); resourcehandlemap.remove(identity); logger.info("uninstalled " + installedresource); } } if (resourcestoinstall.size() > 0) { logger.info("installing " + resourcestoinstall.size() + " resource(s)"); set<resourcehandle> resourcehandles = new linkedhashset<>(); resourceinstaller.context context = new defaultinstallercontext(resourcestoinstall, requirements); for (resource resource : resourcestoinstall) { resourcehandles.add(resourceinstaller.installresource(context, resource)); } logger.info("got " + resourcehandles.size() + " resource handle(s)"); for (resourcehandle resourcehandle : resourcehandles) { resourcehandlemap.put(resourcehandle.getresource().getidentity(), resourcehandle); } } return resourceurisinstalled; }
WillemJiang/fabric8
[ 1, 0, 0, 0 ]
3,401
private static MavenCoordinates parse(String coordinates) { MavenCoordinates result; String[] parts = coordinates.split(":"); if (parts.length == 3) { result = MavenCoordinates.create(parts[0], parts[1], parts[2], null, null); } else if (parts.length == 4) { result = MavenCoordinates.create(parts[0], parts[1], parts[2], parts[3], null); } else if (parts.length == 5) { result = MavenCoordinates.create(parts[0], parts[1], parts[2], parts[3], parts[4]); } else { throw new IllegalArgumentException("Invalid coordinates: " + coordinates); } return result; }
private static MavenCoordinates parse(String coordinates) { MavenCoordinates result; String[] parts = coordinates.split(":"); if (parts.length == 3) { result = MavenCoordinates.create(parts[0], parts[1], parts[2], null, null); } else if (parts.length == 4) { result = MavenCoordinates.create(parts[0], parts[1], parts[2], parts[3], null); } else if (parts.length == 5) { result = MavenCoordinates.create(parts[0], parts[1], parts[2], parts[3], parts[4]); } else { throw new IllegalArgumentException("Invalid coordinates: " + coordinates); } return result; }
private static mavencoordinates parse(string coordinates) { mavencoordinates result; string[] parts = coordinates.split(":"); if (parts.length == 3) { result = mavencoordinates.create(parts[0], parts[1], parts[2], null, null); } else if (parts.length == 4) { result = mavencoordinates.create(parts[0], parts[1], parts[2], parts[3], null); } else if (parts.length == 5) { result = mavencoordinates.create(parts[0], parts[1], parts[2], parts[3], parts[4]); } else { throw new illegalargumentexception("invalid coordinates: " + coordinates); } return result; }
WillemJiang/fabric8
[ 0, 0, 1, 0 ]
19,814
@Override public void validateDataOnEntry() throws DataModelException { // TODO auto-generated method stub, to be implemented by parser }
@Override public void validateDataOnEntry() throws DataModelException { }
@override public void validatedataonentry() throws datamodelexception { }
airlenet/yang-maven-plugin
[ 0, 1, 0, 0 ]
19,815
@Override public void validateDataOnExit() throws DataModelException { // TODO auto-generated method stub, to be implemented by parser }
@Override public void validateDataOnExit() throws DataModelException { }
@override public void validatedataonexit() throws datamodelexception { }
airlenet/yang-maven-plugin
[ 0, 1, 0, 0 ]
19,923
@OnClick(R.id.btn_meter_set_minus) void decreaseLevel() { if (mLevelToSet == Channels.CHN_MIN_VALUE_OF_EVERYTHING) { return; } mLevelToSet--; mTextViewLevel.setText(String.format(Locale.US, "%1$d", mLevelToSet)); //TODO send setting level frame and change shared prefs and display updateLevelForPrefsAndViewAndSendFrame(mLevelToSet); isLevelZero(); }
@OnClick(R.id.btn_meter_set_minus) void decreaseLevel() { if (mLevelToSet == Channels.CHN_MIN_VALUE_OF_EVERYTHING) { return; } mLevelToSet--; mTextViewLevel.setText(String.format(Locale.US, "%1$d", mLevelToSet)); updateLevelForPrefsAndViewAndSendFrame(mLevelToSet); isLevelZero(); }
@onclick(r.id.btn_meter_set_minus) void decreaselevel() { if (mleveltoset == channels.chn_min_value_of_everything) { return; } mleveltoset--; mtextviewlevel.settext(string.format(locale.us, "%1$d", mleveltoset)); updatelevelforprefsandviewandsendframe(mleveltoset); islevelzero(); }
SirdarYangK/SirdarYKCode
[ 0, 1, 0, 0 ]
19,924
@OnClick(R.id.btn_meter_set_plus) void increaseLevel() { if (mLevelToSet == Channels.CHN_MAX_LEVEL) { return; } mLevelToSet++; mTextViewLevel.setText(String.format(Locale.US, "%1$d", mLevelToSet)); //TODO send setting level frame and change shared prefs and display updateLevelForPrefsAndViewAndSendFrame(mLevelToSet); isLevelZero(); }
@OnClick(R.id.btn_meter_set_plus) void increaseLevel() { if (mLevelToSet == Channels.CHN_MAX_LEVEL) { return; } mLevelToSet++; mTextViewLevel.setText(String.format(Locale.US, "%1$d", mLevelToSet)); updateLevelForPrefsAndViewAndSendFrame(mLevelToSet); isLevelZero(); }
@onclick(r.id.btn_meter_set_plus) void increaselevel() { if (mleveltoset == channels.chn_max_level) { return; } mleveltoset++; mtextviewlevel.settext(string.format(locale.us, "%1$d", mleveltoset)); updatelevelforprefsandviewandsendframe(mleveltoset); islevelzero(); }
SirdarYangK/SirdarYKCode
[ 0, 1, 0, 0 ]