id
int64 22
34.9k
| comment_id
int64 0
328
| comment
stringlengths 2
2.55k
| code
stringlengths 31
107k
| classification
stringclasses 6
values | isFinished
bool 1
class | code_context_2
stringlengths 21
27.3k
| code_context_10
stringlengths 29
27.3k
| code_context_20
stringlengths 29
27.3k
|
---|---|---|---|---|---|---|---|---|
14,380 | 1 | // FIXME these tests are not correct | public void testEmit() throws Exception {
eh.on("ok", new EventEmitter.Listener() {
@Override
public void onEvent(Object data) {
String ss = (String) data;
if (ss == "ok")
Log.d(TAG, "pass@" + ss);
else
Log.d(TAG, "fail@" + ss);
}
});
eh.on("no", new EventEmitter.Listener() {
@Override
public void onEvent(Object data) {
String ss = (String) data;
if (ss == "no")
Log.d(TAG, "pass@" + ss);
else
Log.d(TAG, "fail@" + ss);
}
});
eh.emit("ok");
eh.emit("ok", "ok");
eh.emit("ok", "no");
eh.emit("no");
eh.emit("no", "no");
eh.emit("no", "ok");
eh.emit("unknown");
eh.emit("unknown", "ok");
eh.emit("unknown", "no");
fail(); // FIXME these tests are not correct
} | TEST | true | eh.emit("unknown", "ok");
eh.emit("unknown", "no");
fail(); // FIXME these tests are not correct
} | });
eh.emit("ok");
eh.emit("ok", "ok");
eh.emit("ok", "no");
eh.emit("no");
eh.emit("no", "no");
eh.emit("no", "ok");
eh.emit("unknown");
eh.emit("unknown", "ok");
eh.emit("unknown", "no");
fail(); // FIXME these tests are not correct
} | });
eh.on("no", new EventEmitter.Listener() {
@Override
public void onEvent(Object data) {
String ss = (String) data;
if (ss == "no")
Log.d(TAG, "pass@" + ss);
else
Log.d(TAG, "fail@" + ss);
}
});
eh.emit("ok");
eh.emit("ok", "ok");
eh.emit("ok", "no");
eh.emit("no");
eh.emit("no", "no");
eh.emit("no", "ok");
eh.emit("unknown");
eh.emit("unknown", "ok");
eh.emit("unknown", "no");
fail(); // FIXME these tests are not correct
} |
22,578 | 0 | /** Sends the level finish packet. */ | public void sendLevelFinish() {
TaskQueue.getTaskQueue()
.push(
new Task() {
public void execute() {
try {
// for thread safety
final Level level = World.getWorld().getLevel();
PacketBuilder bldr =
new PacketBuilder(
PersistingPacketManager.getPacketManager().getOutgoingPacket(4));
bldr.putShort("width", level.getWidth());
bldr.putShort("height", level.getHeight());
bldr.putShort("depth", level.getDepth());
session.send(bldr.toPacket());
Position spawn = level.getSpawnPosition();
Rotation r = level.getSpawnRotation();
sendSpawn(
(byte) -1,
session.getPlayer().nameId,
session.getPlayer().getColoredName(),
session.getPlayer().getTeamName(),
session.getPlayer().getName(),
session.getPlayer().getListName(),
session.getPlayer().getSkinUrl(),
spawn.getX(),
spawn.getY(),
spawn.getZ(),
(byte) r.getRotation(),
(byte) r.getLook(),
false,
true);
// now load the player's game (TODO in the future do this in parallel with loading
// the
// level)
SavedGameManager.getSavedGameManager()
.queuePersistenceRequest(new LoadPersistenceRequest(session.getPlayer()));
session.setReady();
World.getWorld().completeRegistration(session);
} catch (Exception ex) {
Server.log(ex);
}
}
});
} | NONSATD | true | public void sendLevelFinish() {
TaskQueue.getTaskQueue()
.push(
new Task() {
public void execute() {
try {
// for thread safety
final Level level = World.getWorld().getLevel();
PacketBuilder bldr =
new PacketBuilder(
PersistingPacketManager.getPacketManager().getOutgoingPacket(4));
bldr.putShort("width", level.getWidth());
bldr.putShort("height", level.getHeight());
bldr.putShort("depth", level.getDepth());
session.send(bldr.toPacket());
Position spawn = level.getSpawnPosition();
Rotation r = level.getSpawnRotation();
sendSpawn(
(byte) -1,
session.getPlayer().nameId,
session.getPlayer().getColoredName(),
session.getPlayer().getTeamName(),
session.getPlayer().getName(),
session.getPlayer().getListName(),
session.getPlayer().getSkinUrl(),
spawn.getX(),
spawn.getY(),
spawn.getZ(),
(byte) r.getRotation(),
(byte) r.getLook(),
false,
true);
// now load the player's game (TODO in the future do this in parallel with loading
// the
// level)
SavedGameManager.getSavedGameManager()
.queuePersistenceRequest(new LoadPersistenceRequest(session.getPlayer()));
session.setReady();
World.getWorld().completeRegistration(session);
} catch (Exception ex) {
Server.log(ex);
}
}
});
} | public void sendLevelFinish() {
TaskQueue.getTaskQueue()
.push(
new Task() {
public void execute() {
try {
// for thread safety
final Level level = World.getWorld().getLevel();
PacketBuilder bldr =
new PacketBuilder(
PersistingPacketManager.getPacketManager().getOutgoingPacket(4));
bldr.putShort("width", level.getWidth());
bldr.putShort("height", level.getHeight());
bldr.putShort("depth", level.getDepth());
session.send(bldr.toPacket());
Position spawn = level.getSpawnPosition();
Rotation r = level.getSpawnRotation();
sendSpawn(
(byte) -1,
session.getPlayer().nameId,
session.getPlayer().getColoredName(),
session.getPlayer().getTeamName(),
session.getPlayer().getName(),
session.getPlayer().getListName(),
session.getPlayer().getSkinUrl(),
spawn.getX(),
spawn.getY(),
spawn.getZ(),
(byte) r.getRotation(),
(byte) r.getLook(),
false,
true);
// now load the player's game (TODO in the future do this in parallel with loading
// the
// level)
SavedGameManager.getSavedGameManager()
.queuePersistenceRequest(new LoadPersistenceRequest(session.getPlayer()));
session.setReady();
World.getWorld().completeRegistration(session);
} catch (Exception ex) {
Server.log(ex);
}
}
});
} | public void sendLevelFinish() {
TaskQueue.getTaskQueue()
.push(
new Task() {
public void execute() {
try {
// for thread safety
final Level level = World.getWorld().getLevel();
PacketBuilder bldr =
new PacketBuilder(
PersistingPacketManager.getPacketManager().getOutgoingPacket(4));
bldr.putShort("width", level.getWidth());
bldr.putShort("height", level.getHeight());
bldr.putShort("depth", level.getDepth());
session.send(bldr.toPacket());
Position spawn = level.getSpawnPosition();
Rotation r = level.getSpawnRotation();
sendSpawn(
(byte) -1,
session.getPlayer().nameId,
session.getPlayer().getColoredName(),
session.getPlayer().getTeamName(),
session.getPlayer().getName(),
session.getPlayer().getListName(),
session.getPlayer().getSkinUrl(),
spawn.getX(),
spawn.getY(),
spawn.getZ(),
(byte) r.getRotation(),
(byte) r.getLook(),
false,
true);
// now load the player's game (TODO in the future do this in parallel with loading
// the
// level)
SavedGameManager.getSavedGameManager()
.queuePersistenceRequest(new LoadPersistenceRequest(session.getPlayer()));
session.setReady();
World.getWorld().completeRegistration(session);
} catch (Exception ex) {
Server.log(ex);
}
}
});
} |
22,578 | 1 | // for thread safety | public void sendLevelFinish() {
TaskQueue.getTaskQueue()
.push(
new Task() {
public void execute() {
try {
// for thread safety
final Level level = World.getWorld().getLevel();
PacketBuilder bldr =
new PacketBuilder(
PersistingPacketManager.getPacketManager().getOutgoingPacket(4));
bldr.putShort("width", level.getWidth());
bldr.putShort("height", level.getHeight());
bldr.putShort("depth", level.getDepth());
session.send(bldr.toPacket());
Position spawn = level.getSpawnPosition();
Rotation r = level.getSpawnRotation();
sendSpawn(
(byte) -1,
session.getPlayer().nameId,
session.getPlayer().getColoredName(),
session.getPlayer().getTeamName(),
session.getPlayer().getName(),
session.getPlayer().getListName(),
session.getPlayer().getSkinUrl(),
spawn.getX(),
spawn.getY(),
spawn.getZ(),
(byte) r.getRotation(),
(byte) r.getLook(),
false,
true);
// now load the player's game (TODO in the future do this in parallel with loading
// the
// level)
SavedGameManager.getSavedGameManager()
.queuePersistenceRequest(new LoadPersistenceRequest(session.getPlayer()));
session.setReady();
World.getWorld().completeRegistration(session);
} catch (Exception ex) {
Server.log(ex);
}
}
});
} | NONSATD | true | public void execute() {
try {
// for thread safety
final Level level = World.getWorld().getLevel();
PacketBuilder bldr = | public void sendLevelFinish() {
TaskQueue.getTaskQueue()
.push(
new Task() {
public void execute() {
try {
// for thread safety
final Level level = World.getWorld().getLevel();
PacketBuilder bldr =
new PacketBuilder(
PersistingPacketManager.getPacketManager().getOutgoingPacket(4));
bldr.putShort("width", level.getWidth());
bldr.putShort("height", level.getHeight());
bldr.putShort("depth", level.getDepth());
session.send(bldr.toPacket());
Position spawn = level.getSpawnPosition();
Rotation r = level.getSpawnRotation(); | public void sendLevelFinish() {
TaskQueue.getTaskQueue()
.push(
new Task() {
public void execute() {
try {
// for thread safety
final Level level = World.getWorld().getLevel();
PacketBuilder bldr =
new PacketBuilder(
PersistingPacketManager.getPacketManager().getOutgoingPacket(4));
bldr.putShort("width", level.getWidth());
bldr.putShort("height", level.getHeight());
bldr.putShort("depth", level.getDepth());
session.send(bldr.toPacket());
Position spawn = level.getSpawnPosition();
Rotation r = level.getSpawnRotation();
sendSpawn(
(byte) -1,
session.getPlayer().nameId,
session.getPlayer().getColoredName(),
session.getPlayer().getTeamName(),
session.getPlayer().getName(),
session.getPlayer().getListName(),
session.getPlayer().getSkinUrl(),
spawn.getX(),
spawn.getY(), |
22,578 | 2 | // now load the player's game (TODO in the future do this in parallel with loading
// the
// level) | public void sendLevelFinish() {
TaskQueue.getTaskQueue()
.push(
new Task() {
public void execute() {
try {
// for thread safety
final Level level = World.getWorld().getLevel();
PacketBuilder bldr =
new PacketBuilder(
PersistingPacketManager.getPacketManager().getOutgoingPacket(4));
bldr.putShort("width", level.getWidth());
bldr.putShort("height", level.getHeight());
bldr.putShort("depth", level.getDepth());
session.send(bldr.toPacket());
Position spawn = level.getSpawnPosition();
Rotation r = level.getSpawnRotation();
sendSpawn(
(byte) -1,
session.getPlayer().nameId,
session.getPlayer().getColoredName(),
session.getPlayer().getTeamName(),
session.getPlayer().getName(),
session.getPlayer().getListName(),
session.getPlayer().getSkinUrl(),
spawn.getX(),
spawn.getY(),
spawn.getZ(),
(byte) r.getRotation(),
(byte) r.getLook(),
false,
true);
// now load the player's game (TODO in the future do this in parallel with loading
// the
// level)
SavedGameManager.getSavedGameManager()
.queuePersistenceRequest(new LoadPersistenceRequest(session.getPlayer()));
session.setReady();
World.getWorld().completeRegistration(session);
} catch (Exception ex) {
Server.log(ex);
}
}
});
} | IMPLEMENTATION | true | false,
true);
// now load the player's game (TODO in the future do this in parallel with loading
// the
// level)
SavedGameManager.getSavedGameManager()
.queuePersistenceRequest(new LoadPersistenceRequest(session.getPlayer())); | session.getPlayer().getName(),
session.getPlayer().getListName(),
session.getPlayer().getSkinUrl(),
spawn.getX(),
spawn.getY(),
spawn.getZ(),
(byte) r.getRotation(),
(byte) r.getLook(),
false,
true);
// now load the player's game (TODO in the future do this in parallel with loading
// the
// level)
SavedGameManager.getSavedGameManager()
.queuePersistenceRequest(new LoadPersistenceRequest(session.getPlayer()));
session.setReady();
World.getWorld().completeRegistration(session);
} catch (Exception ex) {
Server.log(ex);
}
}
});
} | bldr.putShort("height", level.getHeight());
bldr.putShort("depth", level.getDepth());
session.send(bldr.toPacket());
Position spawn = level.getSpawnPosition();
Rotation r = level.getSpawnRotation();
sendSpawn(
(byte) -1,
session.getPlayer().nameId,
session.getPlayer().getColoredName(),
session.getPlayer().getTeamName(),
session.getPlayer().getName(),
session.getPlayer().getListName(),
session.getPlayer().getSkinUrl(),
spawn.getX(),
spawn.getY(),
spawn.getZ(),
(byte) r.getRotation(),
(byte) r.getLook(),
false,
true);
// now load the player's game (TODO in the future do this in parallel with loading
// the
// level)
SavedGameManager.getSavedGameManager()
.queuePersistenceRequest(new LoadPersistenceRequest(session.getPlayer()));
session.setReady();
World.getWorld().completeRegistration(session);
} catch (Exception ex) {
Server.log(ex);
}
}
});
} |
30,787 | 0 | //--- DRK > NOTE: Assuming here that caja.load creates frames in order of calls...if not, this method could be trouble. | private void onFrameLoad(JavaScriptObject cajaFrameObject)
{
//--- This is to catch the theoretical case where we call start and stop then start really fast,
//--- but the load call from the first start didn't finish before the first stop, and comes in between
//--- the first stop and the second start...NOTE this is just done based on my thoughts on possible fringe
//--- cases, not because I actually noticed this behavior.
//this.stop();
//m_cajaFrameObjects.push(cajaFrameObject);
} | DEFECT | true | private void onFrameLoad(JavaScriptObject cajaFrameObject)
{
//--- This is to catch the theoretical case where we call start and stop then start really fast,
//--- but the load call from the first start didn't finish before the first stop, and comes in between
//--- the first stop and the second start...NOTE this is just done based on my thoughts on possible fringe
//--- cases, not because I actually noticed this behavior.
//this.stop();
//m_cajaFrameObjects.push(cajaFrameObject);
} | private void onFrameLoad(JavaScriptObject cajaFrameObject)
{
//--- This is to catch the theoretical case where we call start and stop then start really fast,
//--- but the load call from the first start didn't finish before the first stop, and comes in between
//--- the first stop and the second start...NOTE this is just done based on my thoughts on possible fringe
//--- cases, not because I actually noticed this behavior.
//this.stop();
//m_cajaFrameObjects.push(cajaFrameObject);
} | private void onFrameLoad(JavaScriptObject cajaFrameObject)
{
//--- This is to catch the theoretical case where we call start and stop then start really fast,
//--- but the load call from the first start didn't finish before the first stop, and comes in between
//--- the first stop and the second start...NOTE this is just done based on my thoughts on possible fringe
//--- cases, not because I actually noticed this behavior.
//this.stop();
//m_cajaFrameObjects.push(cajaFrameObject);
} |
30,787 | 1 | //--- This is to catch the theoretical case where we call start and stop then start really fast,
//--- but the load call from the first start didn't finish before the first stop, and comes in between
//--- the first stop and the second start...NOTE this is just done based on my thoughts on possible fringe
//--- cases, not because I actually noticed this behavior.
//this.stop();
//m_cajaFrameObjects.push(cajaFrameObject); | private void onFrameLoad(JavaScriptObject cajaFrameObject)
{
//--- This is to catch the theoretical case where we call start and stop then start really fast,
//--- but the load call from the first start didn't finish before the first stop, and comes in between
//--- the first stop and the second start...NOTE this is just done based on my thoughts on possible fringe
//--- cases, not because I actually noticed this behavior.
//this.stop();
//m_cajaFrameObjects.push(cajaFrameObject);
} | DESIGN | true | private void onFrameLoad(JavaScriptObject cajaFrameObject)
{
//--- This is to catch the theoretical case where we call start and stop then start really fast,
//--- but the load call from the first start didn't finish before the first stop, and comes in between
//--- the first stop and the second start...NOTE this is just done based on my thoughts on possible fringe
//--- cases, not because I actually noticed this behavior.
//this.stop();
//m_cajaFrameObjects.push(cajaFrameObject);
} | private void onFrameLoad(JavaScriptObject cajaFrameObject)
{
//--- This is to catch the theoretical case where we call start and stop then start really fast,
//--- but the load call from the first start didn't finish before the first stop, and comes in between
//--- the first stop and the second start...NOTE this is just done based on my thoughts on possible fringe
//--- cases, not because I actually noticed this behavior.
//this.stop();
//m_cajaFrameObjects.push(cajaFrameObject);
} | private void onFrameLoad(JavaScriptObject cajaFrameObject)
{
//--- This is to catch the theoretical case where we call start and stop then start really fast,
//--- but the load call from the first start didn't finish before the first stop, and comes in between
//--- the first stop and the second start...NOTE this is just done based on my thoughts on possible fringe
//--- cases, not because I actually noticed this behavior.
//this.stop();
//m_cajaFrameObjects.push(cajaFrameObject);
} |
30,799 | 0 | // probably a memory leak | public final Node createView(OpenedFile file, String path) {
Node node = createView0(file, path);
node.getProperties().put("editor", this);
node.getProperties().put("file", file); // probably a memory leak
node.getProperties().put("path", path);
return node;
} | DEFECT | true | Node node = createView0(file, path);
node.getProperties().put("editor", this);
node.getProperties().put("file", file); // probably a memory leak
node.getProperties().put("path", path);
return node; | public final Node createView(OpenedFile file, String path) {
Node node = createView0(file, path);
node.getProperties().put("editor", this);
node.getProperties().put("file", file); // probably a memory leak
node.getProperties().put("path", path);
return node;
} | public final Node createView(OpenedFile file, String path) {
Node node = createView0(file, path);
node.getProperties().put("editor", this);
node.getProperties().put("file", file); // probably a memory leak
node.getProperties().put("path", path);
return node;
} |
22,629 | 0 | /**
* Stop the thread if the thread can bring back to runnable state , and the
* program will go to next loop. Note: this may not work, in some case. For
* example, the thread is block in some reason (Locking, blocking queue...),
* the thread is waked up , but it sleep or blocked again, and never reach
* the next loop in the while loop.
*/ | public synchronized void stop() {
task = null; // set the flag and while loop in the run() will exit
i = 0;
notify(); // try to wake up the thread which associate this object
} | DESIGN | true | public synchronized void stop() {
task = null; // set the flag and while loop in the run() will exit
i = 0;
notify(); // try to wake up the thread which associate this object
} | public synchronized void stop() {
task = null; // set the flag and while loop in the run() will exit
i = 0;
notify(); // try to wake up the thread which associate this object
} | public synchronized void stop() {
task = null; // set the flag and while loop in the run() will exit
i = 0;
notify(); // try to wake up the thread which associate this object
} |
22,629 | 1 | // set the flag and while loop in the run() will exit | public synchronized void stop() {
task = null; // set the flag and while loop in the run() will exit
i = 0;
notify(); // try to wake up the thread which associate this object
} | NONSATD | true | public synchronized void stop() {
task = null; // set the flag and while loop in the run() will exit
i = 0;
notify(); // try to wake up the thread which associate this object | public synchronized void stop() {
task = null; // set the flag and while loop in the run() will exit
i = 0;
notify(); // try to wake up the thread which associate this object
} | public synchronized void stop() {
task = null; // set the flag and while loop in the run() will exit
i = 0;
notify(); // try to wake up the thread which associate this object
} |
22,629 | 2 | // try to wake up the thread which associate this object | public synchronized void stop() {
task = null; // set the flag and while loop in the run() will exit
i = 0;
notify(); // try to wake up the thread which associate this object
} | NONSATD | true | task = null; // set the flag and while loop in the run() will exit
i = 0;
notify(); // try to wake up the thread which associate this object
} | public synchronized void stop() {
task = null; // set the flag and while loop in the run() will exit
i = 0;
notify(); // try to wake up the thread which associate this object
} | public synchronized void stop() {
task = null; // set the flag and while loop in the run() will exit
i = 0;
notify(); // try to wake up the thread which associate this object
} |
30,822 | 0 | //TODO refresh current bookmark if not SAME | 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();
}
} | IMPLEMENTATION | true | 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);
//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);
//TODO refresh current bookmark if not SAME
if (currentBookmark != null/* && JavaFxUtils.currentBookmark.getStatus() == BookmarkStatus.CHANGED*/) {
JavaFxUtils.getController(BookmarksController.class).refresh();
}
} |
30,822 | 1 | /* && JavaFxUtils.currentBookmark.getStatus() == BookmarkStatus.CHANGED*/ | 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();
}
} | NONSATD | true | 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);
//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);
//TODO refresh current bookmark if not SAME
if (currentBookmark != null/* && JavaFxUtils.currentBookmark.getStatus() == BookmarkStatus.CHANGED*/) {
JavaFxUtils.getController(BookmarksController.class).refresh();
}
} |
22,631 | 0 | // TODO(ross): this should take in a list of who we are comparing againt, not just use the current pool... | public static ExchangeUnitAuxiliaryInputStatistics getAuxiliaryStatisticsWithVPra(KepProblemData<ExchangeUnit,DonorEdge> kepProblemData){
AuxiliaryInputStatistics<ExchangeUnit,DonorEdge> regular = getAuxiliaryStatistics(kepProblemData);
List<Donor> donors = new ArrayList<Donor>();
List<Receiver> receivers = new ArrayList<Receiver>();
for(ExchangeUnit unit: kepProblemData.getGraph().getVertices()){
for(Donor donor: unit.getDonor()){
donors.add(donor);
}
if(!kepProblemData.getRootNodes().contains(unit)){
receivers.add(unit.getReceiver());
}
}
ImmutableMap.Builder<Receiver,Double> builder = ImmutableMap.<Receiver,Double>builder();
for(Receiver receiver: receivers){
int count = 0;
for(Donor donor: donors){
if(!receiver.getTissueTypeSensitivity().isCompatible(donor.getTissueType())){
count++;
}
}
builder.put(receiver, 100*count/(double)donors.size());
}
return new ExchangeUnitAuxiliaryInputStatistics(
regular.getDonorPowerPostPreference(),
regular.getReceiverPowerPostPreference(),
builder.build()) ;
} | DESIGN | true | public static ExchangeUnitAuxiliaryInputStatistics getAuxiliaryStatisticsWithVPra(KepProblemData<ExchangeUnit,DonorEdge> kepProblemData){
AuxiliaryInputStatistics<ExchangeUnit,DonorEdge> regular = getAuxiliaryStatistics(kepProblemData);
List<Donor> donors = new ArrayList<Donor>();
List<Receiver> receivers = new ArrayList<Receiver>();
for(ExchangeUnit unit: kepProblemData.getGraph().getVertices()){
for(Donor donor: unit.getDonor()){
donors.add(donor);
}
if(!kepProblemData.getRootNodes().contains(unit)){
receivers.add(unit.getReceiver());
}
}
ImmutableMap.Builder<Receiver,Double> builder = ImmutableMap.<Receiver,Double>builder();
for(Receiver receiver: receivers){
int count = 0;
for(Donor donor: donors){
if(!receiver.getTissueTypeSensitivity().isCompatible(donor.getTissueType())){
count++;
}
}
builder.put(receiver, 100*count/(double)donors.size());
}
return new ExchangeUnitAuxiliaryInputStatistics(
regular.getDonorPowerPostPreference(),
regular.getReceiverPowerPostPreference(),
builder.build()) ;
} | public static ExchangeUnitAuxiliaryInputStatistics getAuxiliaryStatisticsWithVPra(KepProblemData<ExchangeUnit,DonorEdge> kepProblemData){
AuxiliaryInputStatistics<ExchangeUnit,DonorEdge> regular = getAuxiliaryStatistics(kepProblemData);
List<Donor> donors = new ArrayList<Donor>();
List<Receiver> receivers = new ArrayList<Receiver>();
for(ExchangeUnit unit: kepProblemData.getGraph().getVertices()){
for(Donor donor: unit.getDonor()){
donors.add(donor);
}
if(!kepProblemData.getRootNodes().contains(unit)){
receivers.add(unit.getReceiver());
}
}
ImmutableMap.Builder<Receiver,Double> builder = ImmutableMap.<Receiver,Double>builder();
for(Receiver receiver: receivers){
int count = 0;
for(Donor donor: donors){
if(!receiver.getTissueTypeSensitivity().isCompatible(donor.getTissueType())){
count++;
}
}
builder.put(receiver, 100*count/(double)donors.size());
}
return new ExchangeUnitAuxiliaryInputStatistics(
regular.getDonorPowerPostPreference(),
regular.getReceiverPowerPostPreference(),
builder.build()) ;
} | public static ExchangeUnitAuxiliaryInputStatistics getAuxiliaryStatisticsWithVPra(KepProblemData<ExchangeUnit,DonorEdge> kepProblemData){
AuxiliaryInputStatistics<ExchangeUnit,DonorEdge> regular = getAuxiliaryStatistics(kepProblemData);
List<Donor> donors = new ArrayList<Donor>();
List<Receiver> receivers = new ArrayList<Receiver>();
for(ExchangeUnit unit: kepProblemData.getGraph().getVertices()){
for(Donor donor: unit.getDonor()){
donors.add(donor);
}
if(!kepProblemData.getRootNodes().contains(unit)){
receivers.add(unit.getReceiver());
}
}
ImmutableMap.Builder<Receiver,Double> builder = ImmutableMap.<Receiver,Double>builder();
for(Receiver receiver: receivers){
int count = 0;
for(Donor donor: donors){
if(!receiver.getTissueTypeSensitivity().isCompatible(donor.getTissueType())){
count++;
}
}
builder.put(receiver, 100*count/(double)donors.size());
}
return new ExchangeUnitAuxiliaryInputStatistics(
regular.getDonorPowerPostPreference(),
regular.getReceiverPowerPostPreference(),
builder.build()) ;
} |
22,632 | 0 | // if(new File(item.second).isAbsolute()){ | public void copyResourcesToCacheIfRequired1(Activity activity){
if( ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED )
return;
String sigFilePath = resFolderPath + "/sarvamoola/aitareya.txt";
File sigFile = new File(sigFilePath);
if(!sigFile.exists())
{
for (Pair<String, String> item : mFilesToCopy) {
String fileName ;
if(item.first.indexOf('/')!= -1)
fileName = item.first.substring(item.first.lastIndexOf("/")+1);
else
fileName = item.first;
String destUrl = resFolderPath;
if(!item.second.isEmpty()) {
// if(new File(item.second).isAbsolute()){
if(File.separator.equals(item.second.substring(0,1))){ // Shortcut to check isAbsolute()
// Its an absolute url. set the destUrl to empty so that item.second is taken as is
destUrl = "";
}
destUrl = destUrl + item.second + '/';
}
destUrl = destUrl + fileName;
copyFile(item.first, destUrl);
}
}
} | NONSATD | true | String destUrl = resFolderPath;
if(!item.second.isEmpty()) {
// if(new File(item.second).isAbsolute()){
if(File.separator.equals(item.second.substring(0,1))){ // Shortcut to check isAbsolute()
// Its an absolute url. set the destUrl to empty so that item.second is taken as is | if(!sigFile.exists())
{
for (Pair<String, String> item : mFilesToCopy) {
String fileName ;
if(item.first.indexOf('/')!= -1)
fileName = item.first.substring(item.first.lastIndexOf("/")+1);
else
fileName = item.first;
String destUrl = resFolderPath;
if(!item.second.isEmpty()) {
// if(new File(item.second).isAbsolute()){
if(File.separator.equals(item.second.substring(0,1))){ // Shortcut to check isAbsolute()
// Its an absolute url. set the destUrl to empty so that item.second is taken as is
destUrl = "";
}
destUrl = destUrl + item.second + '/';
}
destUrl = destUrl + fileName;
copyFile(item.first, destUrl);
}
} | public void copyResourcesToCacheIfRequired1(Activity activity){
if( ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED )
return;
String sigFilePath = resFolderPath + "/sarvamoola/aitareya.txt";
File sigFile = new File(sigFilePath);
if(!sigFile.exists())
{
for (Pair<String, String> item : mFilesToCopy) {
String fileName ;
if(item.first.indexOf('/')!= -1)
fileName = item.first.substring(item.first.lastIndexOf("/")+1);
else
fileName = item.first;
String destUrl = resFolderPath;
if(!item.second.isEmpty()) {
// if(new File(item.second).isAbsolute()){
if(File.separator.equals(item.second.substring(0,1))){ // Shortcut to check isAbsolute()
// Its an absolute url. set the destUrl to empty so that item.second is taken as is
destUrl = "";
}
destUrl = destUrl + item.second + '/';
}
destUrl = destUrl + fileName;
copyFile(item.first, destUrl);
}
}
} |
22,632 | 1 | // Shortcut to check isAbsolute() | public void copyResourcesToCacheIfRequired1(Activity activity){
if( ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED )
return;
String sigFilePath = resFolderPath + "/sarvamoola/aitareya.txt";
File sigFile = new File(sigFilePath);
if(!sigFile.exists())
{
for (Pair<String, String> item : mFilesToCopy) {
String fileName ;
if(item.first.indexOf('/')!= -1)
fileName = item.first.substring(item.first.lastIndexOf("/")+1);
else
fileName = item.first;
String destUrl = resFolderPath;
if(!item.second.isEmpty()) {
// if(new File(item.second).isAbsolute()){
if(File.separator.equals(item.second.substring(0,1))){ // Shortcut to check isAbsolute()
// Its an absolute url. set the destUrl to empty so that item.second is taken as is
destUrl = "";
}
destUrl = destUrl + item.second + '/';
}
destUrl = destUrl + fileName;
copyFile(item.first, destUrl);
}
}
} | IMPLEMENTATION | true | if(!item.second.isEmpty()) {
// if(new File(item.second).isAbsolute()){
if(File.separator.equals(item.second.substring(0,1))){ // Shortcut to check isAbsolute()
// Its an absolute url. set the destUrl to empty so that item.second is taken as is
destUrl = ""; | {
for (Pair<String, String> item : mFilesToCopy) {
String fileName ;
if(item.first.indexOf('/')!= -1)
fileName = item.first.substring(item.first.lastIndexOf("/")+1);
else
fileName = item.first;
String destUrl = resFolderPath;
if(!item.second.isEmpty()) {
// if(new File(item.second).isAbsolute()){
if(File.separator.equals(item.second.substring(0,1))){ // Shortcut to check isAbsolute()
// Its an absolute url. set the destUrl to empty so that item.second is taken as is
destUrl = "";
}
destUrl = destUrl + item.second + '/';
}
destUrl = destUrl + fileName;
copyFile(item.first, destUrl);
}
}
} | public void copyResourcesToCacheIfRequired1(Activity activity){
if( ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED )
return;
String sigFilePath = resFolderPath + "/sarvamoola/aitareya.txt";
File sigFile = new File(sigFilePath);
if(!sigFile.exists())
{
for (Pair<String, String> item : mFilesToCopy) {
String fileName ;
if(item.first.indexOf('/')!= -1)
fileName = item.first.substring(item.first.lastIndexOf("/")+1);
else
fileName = item.first;
String destUrl = resFolderPath;
if(!item.second.isEmpty()) {
// if(new File(item.second).isAbsolute()){
if(File.separator.equals(item.second.substring(0,1))){ // Shortcut to check isAbsolute()
// Its an absolute url. set the destUrl to empty so that item.second is taken as is
destUrl = "";
}
destUrl = destUrl + item.second + '/';
}
destUrl = destUrl + fileName;
copyFile(item.first, destUrl);
}
}
} |
22,632 | 2 | // Its an absolute url. set the destUrl to empty so that item.second is taken as is | public void copyResourcesToCacheIfRequired1(Activity activity){
if( ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED )
return;
String sigFilePath = resFolderPath + "/sarvamoola/aitareya.txt";
File sigFile = new File(sigFilePath);
if(!sigFile.exists())
{
for (Pair<String, String> item : mFilesToCopy) {
String fileName ;
if(item.first.indexOf('/')!= -1)
fileName = item.first.substring(item.first.lastIndexOf("/")+1);
else
fileName = item.first;
String destUrl = resFolderPath;
if(!item.second.isEmpty()) {
// if(new File(item.second).isAbsolute()){
if(File.separator.equals(item.second.substring(0,1))){ // Shortcut to check isAbsolute()
// Its an absolute url. set the destUrl to empty so that item.second is taken as is
destUrl = "";
}
destUrl = destUrl + item.second + '/';
}
destUrl = destUrl + fileName;
copyFile(item.first, destUrl);
}
}
} | NONSATD | true | // if(new File(item.second).isAbsolute()){
if(File.separator.equals(item.second.substring(0,1))){ // Shortcut to check isAbsolute()
// Its an absolute url. set the destUrl to empty so that item.second is taken as is
destUrl = "";
} | for (Pair<String, String> item : mFilesToCopy) {
String fileName ;
if(item.first.indexOf('/')!= -1)
fileName = item.first.substring(item.first.lastIndexOf("/")+1);
else
fileName = item.first;
String destUrl = resFolderPath;
if(!item.second.isEmpty()) {
// if(new File(item.second).isAbsolute()){
if(File.separator.equals(item.second.substring(0,1))){ // Shortcut to check isAbsolute()
// Its an absolute url. set the destUrl to empty so that item.second is taken as is
destUrl = "";
}
destUrl = destUrl + item.second + '/';
}
destUrl = destUrl + fileName;
copyFile(item.first, destUrl);
}
}
} | public void copyResourcesToCacheIfRequired1(Activity activity){
if( ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED )
return;
String sigFilePath = resFolderPath + "/sarvamoola/aitareya.txt";
File sigFile = new File(sigFilePath);
if(!sigFile.exists())
{
for (Pair<String, String> item : mFilesToCopy) {
String fileName ;
if(item.first.indexOf('/')!= -1)
fileName = item.first.substring(item.first.lastIndexOf("/")+1);
else
fileName = item.first;
String destUrl = resFolderPath;
if(!item.second.isEmpty()) {
// if(new File(item.second).isAbsolute()){
if(File.separator.equals(item.second.substring(0,1))){ // Shortcut to check isAbsolute()
// Its an absolute url. set the destUrl to empty so that item.second is taken as is
destUrl = "";
}
destUrl = destUrl + item.second + '/';
}
destUrl = destUrl + fileName;
copyFile(item.first, destUrl);
}
}
} |
14,444 | 0 | /**
* Set a new strategies how to load options.
*
* @param filterablePagingProvider the paging provider that gives the actual
* options in pages
* @param filterableCountProvider the count provider to give the total about
* of options with current filter
* @param pageLength the length of the pages that component should use to
* access providers
*/ | public void loadFrom(FilterablePagingProvider<T> filterablePagingProvider, FilterableCountProvider filterableCountProvider, int pageLength) {
this.fpp = filterablePagingProvider;
this.fcp = filterableCountProvider;
// Need to re-create the piggybackList & set container, some refactoring should be done here
piggybackLazyList = new LazyList<>(new LazyList.PagingProvider<T>() {
private static final long serialVersionUID = 1027614132444478021L;
@Override
public List<T> findEntities(int firstRow) {
return fpp.findEntities(firstRow,
getCurrentFilter());
}
},
new LazyList.CountProvider() {
private static final long serialVersionUID = -7339189124024626177L;
@Override
public int size() {
return fcp.size(getCurrentFilter());
}
}, pageLength);
setBic(new DummyFilterableListContainer<T>(getType(),
piggybackLazyList));
getSelect().setContainerDataSource(getBic());
} | NONSATD | true | public void loadFrom(FilterablePagingProvider<T> filterablePagingProvider, FilterableCountProvider filterableCountProvider, int pageLength) {
this.fpp = filterablePagingProvider;
this.fcp = filterableCountProvider;
// Need to re-create the piggybackList & set container, some refactoring should be done here
piggybackLazyList = new LazyList<>(new LazyList.PagingProvider<T>() {
private static final long serialVersionUID = 1027614132444478021L;
@Override
public List<T> findEntities(int firstRow) {
return fpp.findEntities(firstRow,
getCurrentFilter());
}
},
new LazyList.CountProvider() {
private static final long serialVersionUID = -7339189124024626177L;
@Override
public int size() {
return fcp.size(getCurrentFilter());
}
}, pageLength);
setBic(new DummyFilterableListContainer<T>(getType(),
piggybackLazyList));
getSelect().setContainerDataSource(getBic());
} | public void loadFrom(FilterablePagingProvider<T> filterablePagingProvider, FilterableCountProvider filterableCountProvider, int pageLength) {
this.fpp = filterablePagingProvider;
this.fcp = filterableCountProvider;
// Need to re-create the piggybackList & set container, some refactoring should be done here
piggybackLazyList = new LazyList<>(new LazyList.PagingProvider<T>() {
private static final long serialVersionUID = 1027614132444478021L;
@Override
public List<T> findEntities(int firstRow) {
return fpp.findEntities(firstRow,
getCurrentFilter());
}
},
new LazyList.CountProvider() {
private static final long serialVersionUID = -7339189124024626177L;
@Override
public int size() {
return fcp.size(getCurrentFilter());
}
}, pageLength);
setBic(new DummyFilterableListContainer<T>(getType(),
piggybackLazyList));
getSelect().setContainerDataSource(getBic());
} | public void loadFrom(FilterablePagingProvider<T> filterablePagingProvider, FilterableCountProvider filterableCountProvider, int pageLength) {
this.fpp = filterablePagingProvider;
this.fcp = filterableCountProvider;
// Need to re-create the piggybackList & set container, some refactoring should be done here
piggybackLazyList = new LazyList<>(new LazyList.PagingProvider<T>() {
private static final long serialVersionUID = 1027614132444478021L;
@Override
public List<T> findEntities(int firstRow) {
return fpp.findEntities(firstRow,
getCurrentFilter());
}
},
new LazyList.CountProvider() {
private static final long serialVersionUID = -7339189124024626177L;
@Override
public int size() {
return fcp.size(getCurrentFilter());
}
}, pageLength);
setBic(new DummyFilterableListContainer<T>(getType(),
piggybackLazyList));
getSelect().setContainerDataSource(getBic());
} |
14,444 | 1 | // Need to re-create the piggybackList & set container, some refactoring should be done here | public void loadFrom(FilterablePagingProvider<T> filterablePagingProvider, FilterableCountProvider filterableCountProvider, int pageLength) {
this.fpp = filterablePagingProvider;
this.fcp = filterableCountProvider;
// Need to re-create the piggybackList & set container, some refactoring should be done here
piggybackLazyList = new LazyList<>(new LazyList.PagingProvider<T>() {
private static final long serialVersionUID = 1027614132444478021L;
@Override
public List<T> findEntities(int firstRow) {
return fpp.findEntities(firstRow,
getCurrentFilter());
}
},
new LazyList.CountProvider() {
private static final long serialVersionUID = -7339189124024626177L;
@Override
public int size() {
return fcp.size(getCurrentFilter());
}
}, pageLength);
setBic(new DummyFilterableListContainer<T>(getType(),
piggybackLazyList));
getSelect().setContainerDataSource(getBic());
} | DESIGN | true | this.fpp = filterablePagingProvider;
this.fcp = filterableCountProvider;
// Need to re-create the piggybackList & set container, some refactoring should be done here
piggybackLazyList = new LazyList<>(new LazyList.PagingProvider<T>() {
private static final long serialVersionUID = 1027614132444478021L; | public void loadFrom(FilterablePagingProvider<T> filterablePagingProvider, FilterableCountProvider filterableCountProvider, int pageLength) {
this.fpp = filterablePagingProvider;
this.fcp = filterableCountProvider;
// Need to re-create the piggybackList & set container, some refactoring should be done here
piggybackLazyList = new LazyList<>(new LazyList.PagingProvider<T>() {
private static final long serialVersionUID = 1027614132444478021L;
@Override
public List<T> findEntities(int firstRow) {
return fpp.findEntities(firstRow,
getCurrentFilter());
}
},
new LazyList.CountProvider() {
private static final long serialVersionUID = -7339189124024626177L; | public void loadFrom(FilterablePagingProvider<T> filterablePagingProvider, FilterableCountProvider filterableCountProvider, int pageLength) {
this.fpp = filterablePagingProvider;
this.fcp = filterableCountProvider;
// Need to re-create the piggybackList & set container, some refactoring should be done here
piggybackLazyList = new LazyList<>(new LazyList.PagingProvider<T>() {
private static final long serialVersionUID = 1027614132444478021L;
@Override
public List<T> findEntities(int firstRow) {
return fpp.findEntities(firstRow,
getCurrentFilter());
}
},
new LazyList.CountProvider() {
private static final long serialVersionUID = -7339189124024626177L;
@Override
public int size() {
return fcp.size(getCurrentFilter());
}
}, pageLength);
setBic(new DummyFilterableListContainer<T>(getType(),
piggybackLazyList));
getSelect().setContainerDataSource(getBic());
} |
30,838 | 0 | // Look up the beginning and the end of the line (outside of the extracted string)
// such that we can show a preview of the diff, e.g. if you have
// foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello);
// so we need to extract "foo.setTitle(" and ");".
// Look backwards to the beginning of the line (and strip whitespace) | @Override
public String getAdditionalProposalInfo() {
try {
ASTNode coveringNode = mContext.getCoveringNode();
int start = coveringNode.getStartPosition();
int length = coveringNode.getLength();
IBuffer buffer = mContext.getCompilationUnit().getBuffer();
StringBuilder sb = new StringBuilder();
String string = buffer.getText(start, length);
string = ExtractStringRefactoring.unquoteAttrValue(string);
String token = ExtractStringInputPage.guessId(string);
// Look up the beginning and the end of the line (outside of the extracted string)
// such that we can show a preview of the diff, e.g. if you have
// foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello);
// so we need to extract "foo.setTitle(" and ");".
// Look backwards to the beginning of the line (and strip whitespace)
int i = start - 1;
while (i > 0) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i--;
}
String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim();
// Look forwards to the end of the line (and strip whitespace)
i = start + length;
while (i < buffer.getLength()) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string);
sb.append("</string></b><br>"); //$NON-NLS-1$
sb.append("</resources>"); //$NON-NLS-1$
return sb.toString();
} catch (JavaModelException e) {
AdtPlugin.log(e, null);
}
return "Initiates the Extract String refactoring operation";
} | NONSATD | true | string = ExtractStringRefactoring.unquoteAttrValue(string);
String token = ExtractStringInputPage.guessId(string);
// Look up the beginning and the end of the line (outside of the extracted string)
// such that we can show a preview of the diff, e.g. if you have
// foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello);
// so we need to extract "foo.setTitle(" and ");".
// Look backwards to the beginning of the line (and strip whitespace)
int i = start - 1;
while (i > 0) { | public String getAdditionalProposalInfo() {
try {
ASTNode coveringNode = mContext.getCoveringNode();
int start = coveringNode.getStartPosition();
int length = coveringNode.getLength();
IBuffer buffer = mContext.getCompilationUnit().getBuffer();
StringBuilder sb = new StringBuilder();
String string = buffer.getText(start, length);
string = ExtractStringRefactoring.unquoteAttrValue(string);
String token = ExtractStringInputPage.guessId(string);
// Look up the beginning and the end of the line (outside of the extracted string)
// such that we can show a preview of the diff, e.g. if you have
// foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello);
// so we need to extract "foo.setTitle(" and ");".
// Look backwards to the beginning of the line (and strip whitespace)
int i = start - 1;
while (i > 0) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i--;
}
String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim();
// Look forwards to the end of the line (and strip whitespace) | @Override
public String getAdditionalProposalInfo() {
try {
ASTNode coveringNode = mContext.getCoveringNode();
int start = coveringNode.getStartPosition();
int length = coveringNode.getLength();
IBuffer buffer = mContext.getCompilationUnit().getBuffer();
StringBuilder sb = new StringBuilder();
String string = buffer.getText(start, length);
string = ExtractStringRefactoring.unquoteAttrValue(string);
String token = ExtractStringInputPage.guessId(string);
// Look up the beginning and the end of the line (outside of the extracted string)
// such that we can show a preview of the diff, e.g. if you have
// foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello);
// so we need to extract "foo.setTitle(" and ");".
// Look backwards to the beginning of the line (and strip whitespace)
int i = start - 1;
while (i > 0) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i--;
}
String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim();
// Look forwards to the end of the line (and strip whitespace)
i = start + length;
while (i < buffer.getLength()) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or |
30,838 | 1 | // Look forwards to the end of the line (and strip whitespace) | @Override
public String getAdditionalProposalInfo() {
try {
ASTNode coveringNode = mContext.getCoveringNode();
int start = coveringNode.getStartPosition();
int length = coveringNode.getLength();
IBuffer buffer = mContext.getCompilationUnit().getBuffer();
StringBuilder sb = new StringBuilder();
String string = buffer.getText(start, length);
string = ExtractStringRefactoring.unquoteAttrValue(string);
String token = ExtractStringInputPage.guessId(string);
// Look up the beginning and the end of the line (outside of the extracted string)
// such that we can show a preview of the diff, e.g. if you have
// foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello);
// so we need to extract "foo.setTitle(" and ");".
// Look backwards to the beginning of the line (and strip whitespace)
int i = start - 1;
while (i > 0) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i--;
}
String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim();
// Look forwards to the end of the line (and strip whitespace)
i = start + length;
while (i < buffer.getLength()) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string);
sb.append("</string></b><br>"); //$NON-NLS-1$
sb.append("</resources>"); //$NON-NLS-1$
return sb.toString();
} catch (JavaModelException e) {
AdtPlugin.log(e, null);
}
return "Initiates the Extract String refactoring operation";
} | NONSATD | true | }
String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim();
// Look forwards to the end of the line (and strip whitespace)
i = start + length;
while (i < buffer.getLength()) { | // Look backwards to the beginning of the line (and strip whitespace)
int i = start - 1;
while (i > 0) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i--;
}
String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim();
// Look forwards to the end of the line (and strip whitespace)
i = start + length;
while (i < buffer.getLength()) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or | int length = coveringNode.getLength();
IBuffer buffer = mContext.getCompilationUnit().getBuffer();
StringBuilder sb = new StringBuilder();
String string = buffer.getText(start, length);
string = ExtractStringRefactoring.unquoteAttrValue(string);
String token = ExtractStringInputPage.guessId(string);
// Look up the beginning and the end of the line (outside of the extracted string)
// such that we can show a preview of the diff, e.g. if you have
// foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello);
// so we need to extract "foo.setTitle(" and ");".
// Look backwards to the beginning of the line (and strip whitespace)
int i = start - 1;
while (i > 0) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i--;
}
String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim();
// Look forwards to the end of the line (and strip whitespace)
i = start + length;
while (i < buffer.getLength()) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true; |
30,838 | 2 | // Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ? | @Override
public String getAdditionalProposalInfo() {
try {
ASTNode coveringNode = mContext.getCoveringNode();
int start = coveringNode.getStartPosition();
int length = coveringNode.getLength();
IBuffer buffer = mContext.getCompilationUnit().getBuffer();
StringBuilder sb = new StringBuilder();
String string = buffer.getText(start, length);
string = ExtractStringRefactoring.unquoteAttrValue(string);
String token = ExtractStringInputPage.guessId(string);
// Look up the beginning and the end of the line (outside of the extracted string)
// such that we can show a preview of the diff, e.g. if you have
// foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello);
// so we need to extract "foo.setTitle(" and ");".
// Look backwards to the beginning of the line (and strip whitespace)
int i = start - 1;
while (i > 0) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i--;
}
String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim();
// Look forwards to the end of the line (and strip whitespace)
i = start + length;
while (i < buffer.getLength()) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string);
sb.append("</string></b><br>"); //$NON-NLS-1$
sb.append("</resources>"); //$NON-NLS-1$
return sb.toString();
} catch (JavaModelException e) {
AdtPlugin.log(e, null);
}
return "Initiates the Extract String refactoring operation";
} | DESIGN | true | }
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent(); | // Look forwards to the end of the line (and strip whitespace)
i = start + length;
while (i < buffer.getLength()) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
} | // Look backwards to the beginning of the line (and strip whitespace)
int i = start - 1;
while (i > 0) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i--;
}
String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim();
// Look forwards to the end of the line (and strip whitespace)
i = start + length;
while (i < buffer.getLength()) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token); |
30,838 | 3 | // Display .java change: | @Override
public String getAdditionalProposalInfo() {
try {
ASTNode coveringNode = mContext.getCoveringNode();
int start = coveringNode.getStartPosition();
int length = coveringNode.getLength();
IBuffer buffer = mContext.getCompilationUnit().getBuffer();
StringBuilder sb = new StringBuilder();
String string = buffer.getText(start, length);
string = ExtractStringRefactoring.unquoteAttrValue(string);
String token = ExtractStringInputPage.guessId(string);
// Look up the beginning and the end of the line (outside of the extracted string)
// such that we can show a preview of the diff, e.g. if you have
// foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello);
// so we need to extract "foo.setTitle(" and ");".
// Look backwards to the beginning of the line (and strip whitespace)
int i = start - 1;
while (i > 0) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i--;
}
String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim();
// Look forwards to the end of the line (and strip whitespace)
i = start + length;
while (i < buffer.getLength()) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string);
sb.append("</string></b><br>"); //$NON-NLS-1$
sb.append("</resources>"); //$NON-NLS-1$
return sb.toString();
} catch (JavaModelException e) {
AdtPlugin.log(e, null);
}
return "Initiates the Extract String refactoring operation";
} | NONSATD | true | }
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix); | ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$ | char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$ |
30,838 | 4 | //$NON-NLS-1$ | @Override
public String getAdditionalProposalInfo() {
try {
ASTNode coveringNode = mContext.getCoveringNode();
int start = coveringNode.getStartPosition();
int length = coveringNode.getLength();
IBuffer buffer = mContext.getCompilationUnit().getBuffer();
StringBuilder sb = new StringBuilder();
String string = buffer.getText(start, length);
string = ExtractStringRefactoring.unquoteAttrValue(string);
String token = ExtractStringInputPage.guessId(string);
// Look up the beginning and the end of the line (outside of the extracted string)
// such that we can show a preview of the diff, e.g. if you have
// foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello);
// so we need to extract "foo.setTitle(" and ");".
// Look backwards to the beginning of the line (and strip whitespace)
int i = start - 1;
while (i > 0) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i--;
}
String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim();
// Look forwards to the end of the line (and strip whitespace)
i = start + length;
while (i < buffer.getLength()) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string);
sb.append("</string></b><br>"); //$NON-NLS-1$
sb.append("</resources>"); //$NON-NLS-1$
return sb.toString();
} catch (JavaModelException e) {
AdtPlugin.log(e, null);
}
return "Initiates the Extract String refactoring operation";
} | NONSATD | true | }
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$ | if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
} | if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string); |
30,838 | 5 | //$NON-NLS-1$ | @Override
public String getAdditionalProposalInfo() {
try {
ASTNode coveringNode = mContext.getCoveringNode();
int start = coveringNode.getStartPosition();
int length = coveringNode.getLength();
IBuffer buffer = mContext.getCompilationUnit().getBuffer();
StringBuilder sb = new StringBuilder();
String string = buffer.getText(start, length);
string = ExtractStringRefactoring.unquoteAttrValue(string);
String token = ExtractStringInputPage.guessId(string);
// Look up the beginning and the end of the line (outside of the extracted string)
// such that we can show a preview of the diff, e.g. if you have
// foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello);
// so we need to extract "foo.setTitle(" and ");".
// Look backwards to the beginning of the line (and strip whitespace)
int i = start - 1;
while (i > 0) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i--;
}
String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim();
// Look forwards to the end of the line (and strip whitespace)
i = start + length;
while (i < buffer.getLength()) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string);
sb.append("</string></b><br>"); //$NON-NLS-1$
sb.append("</resources>"); //$NON-NLS-1$
return sb.toString();
} catch (JavaModelException e) {
AdtPlugin.log(e, null);
}
return "Initiates the Extract String refactoring operation";
} | NONSATD | true | }
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$ | if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
} | if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string); |
30,838 | 6 | //$NON-NLS-1$ | @Override
public String getAdditionalProposalInfo() {
try {
ASTNode coveringNode = mContext.getCoveringNode();
int start = coveringNode.getStartPosition();
int length = coveringNode.getLength();
IBuffer buffer = mContext.getCompilationUnit().getBuffer();
StringBuilder sb = new StringBuilder();
String string = buffer.getText(start, length);
string = ExtractStringRefactoring.unquoteAttrValue(string);
String token = ExtractStringInputPage.guessId(string);
// Look up the beginning and the end of the line (outside of the extracted string)
// such that we can show a preview of the diff, e.g. if you have
// foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello);
// so we need to extract "foo.setTitle(" and ");".
// Look backwards to the beginning of the line (and strip whitespace)
int i = start - 1;
while (i > 0) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i--;
}
String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim();
// Look forwards to the end of the line (and strip whitespace)
i = start + length;
while (i < buffer.getLength()) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string);
sb.append("</string></b><br>"); //$NON-NLS-1$
sb.append("</resources>"); //$NON-NLS-1$
return sb.toString();
} catch (JavaModelException e) {
AdtPlugin.log(e, null);
}
return "Initiates the Extract String refactoring operation";
} | NONSATD | true | }
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$ | if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
} | if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string); |
30,838 | 7 | //$NON-NLS-1$ | @Override
public String getAdditionalProposalInfo() {
try {
ASTNode coveringNode = mContext.getCoveringNode();
int start = coveringNode.getStartPosition();
int length = coveringNode.getLength();
IBuffer buffer = mContext.getCompilationUnit().getBuffer();
StringBuilder sb = new StringBuilder();
String string = buffer.getText(start, length);
string = ExtractStringRefactoring.unquoteAttrValue(string);
String token = ExtractStringInputPage.guessId(string);
// Look up the beginning and the end of the line (outside of the extracted string)
// such that we can show a preview of the diff, e.g. if you have
// foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello);
// so we need to extract "foo.setTitle(" and ");".
// Look backwards to the beginning of the line (and strip whitespace)
int i = start - 1;
while (i > 0) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i--;
}
String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim();
// Look forwards to the end of the line (and strip whitespace)
i = start + length;
while (i < buffer.getLength()) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string);
sb.append("</string></b><br>"); //$NON-NLS-1$
sb.append("</resources>"); //$NON-NLS-1$
return sb.toString();
} catch (JavaModelException e) {
AdtPlugin.log(e, null);
}
return "Initiates the Extract String refactoring operation";
} | NONSATD | true | }
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$ | if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
} | if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string); |
30,838 | 8 | //$NON-NLS-1$ | @Override
public String getAdditionalProposalInfo() {
try {
ASTNode coveringNode = mContext.getCoveringNode();
int start = coveringNode.getStartPosition();
int length = coveringNode.getLength();
IBuffer buffer = mContext.getCompilationUnit().getBuffer();
StringBuilder sb = new StringBuilder();
String string = buffer.getText(start, length);
string = ExtractStringRefactoring.unquoteAttrValue(string);
String token = ExtractStringInputPage.guessId(string);
// Look up the beginning and the end of the line (outside of the extracted string)
// such that we can show a preview of the diff, e.g. if you have
// foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello);
// so we need to extract "foo.setTitle(" and ");".
// Look backwards to the beginning of the line (and strip whitespace)
int i = start - 1;
while (i > 0) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i--;
}
String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim();
// Look forwards to the end of the line (and strip whitespace)
i = start + length;
while (i < buffer.getLength()) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string);
sb.append("</string></b><br>"); //$NON-NLS-1$
sb.append("</resources>"); //$NON-NLS-1$
return sb.toString();
} catch (JavaModelException e) {
AdtPlugin.log(e, null);
}
return "Initiates the Extract String refactoring operation";
} | NONSATD | true | }
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$ | if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
} | if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string); |
30,838 | 9 | //$NON-NLS-1$ | @Override
public String getAdditionalProposalInfo() {
try {
ASTNode coveringNode = mContext.getCoveringNode();
int start = coveringNode.getStartPosition();
int length = coveringNode.getLength();
IBuffer buffer = mContext.getCompilationUnit().getBuffer();
StringBuilder sb = new StringBuilder();
String string = buffer.getText(start, length);
string = ExtractStringRefactoring.unquoteAttrValue(string);
String token = ExtractStringInputPage.guessId(string);
// Look up the beginning and the end of the line (outside of the extracted string)
// such that we can show a preview of the diff, e.g. if you have
// foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello);
// so we need to extract "foo.setTitle(" and ");".
// Look backwards to the beginning of the line (and strip whitespace)
int i = start - 1;
while (i > 0) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i--;
}
String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim();
// Look forwards to the end of the line (and strip whitespace)
i = start + length;
while (i < buffer.getLength()) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string);
sb.append("</string></b><br>"); //$NON-NLS-1$
sb.append("</resources>"); //$NON-NLS-1$
return sb.toString();
} catch (JavaModelException e) {
AdtPlugin.log(e, null);
}
return "Initiates the Extract String refactoring operation";
} | NONSATD | true | }
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$ | if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
} | if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string); |
30,838 | 10 | //$NON-NLS-1$ | @Override
public String getAdditionalProposalInfo() {
try {
ASTNode coveringNode = mContext.getCoveringNode();
int start = coveringNode.getStartPosition();
int length = coveringNode.getLength();
IBuffer buffer = mContext.getCompilationUnit().getBuffer();
StringBuilder sb = new StringBuilder();
String string = buffer.getText(start, length);
string = ExtractStringRefactoring.unquoteAttrValue(string);
String token = ExtractStringInputPage.guessId(string);
// Look up the beginning and the end of the line (outside of the extracted string)
// such that we can show a preview of the diff, e.g. if you have
// foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello);
// so we need to extract "foo.setTitle(" and ");".
// Look backwards to the beginning of the line (and strip whitespace)
int i = start - 1;
while (i > 0) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i--;
}
String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim();
// Look forwards to the end of the line (and strip whitespace)
i = start + length;
while (i < buffer.getLength()) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string);
sb.append("</string></b><br>"); //$NON-NLS-1$
sb.append("</resources>"); //$NON-NLS-1$
return sb.toString();
} catch (JavaModelException e) {
AdtPlugin.log(e, null);
}
return "Initiates the Extract String refactoring operation";
} | NONSATD | true | }
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$ | if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
} | if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string); |
30,838 | 11 | // Display strings.xml change: | @Override
public String getAdditionalProposalInfo() {
try {
ASTNode coveringNode = mContext.getCoveringNode();
int start = coveringNode.getStartPosition();
int length = coveringNode.getLength();
IBuffer buffer = mContext.getCompilationUnit().getBuffer();
StringBuilder sb = new StringBuilder();
String string = buffer.getText(start, length);
string = ExtractStringRefactoring.unquoteAttrValue(string);
String token = ExtractStringInputPage.guessId(string);
// Look up the beginning and the end of the line (outside of the extracted string)
// such that we can show a preview of the diff, e.g. if you have
// foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello);
// so we need to extract "foo.setTitle(" and ");".
// Look backwards to the beginning of the line (and strip whitespace)
int i = start - 1;
while (i > 0) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i--;
}
String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim();
// Look forwards to the end of the line (and strip whitespace)
i = start + length;
while (i < buffer.getLength()) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string);
sb.append("</string></b><br>"); //$NON-NLS-1$
sb.append("</resources>"); //$NON-NLS-1$
return sb.toString();
} catch (JavaModelException e) {
AdtPlugin.log(e, null);
}
return "Initiates the Extract String refactoring operation";
} | NONSATD | true | sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$ | sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string);
sb.append("</string></b><br>"); //$NON-NLS-1$
sb.append("</resources>"); //$NON-NLS-1$
return sb.toString();
} catch (JavaModelException e) { | || type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string);
sb.append("</string></b><br>"); //$NON-NLS-1$
sb.append("</resources>"); //$NON-NLS-1$
return sb.toString();
} catch (JavaModelException e) {
AdtPlugin.log(e, null);
}
return "Initiates the Extract String refactoring operation";
} |
30,838 | 12 | //$NON-NLS-1$ | @Override
public String getAdditionalProposalInfo() {
try {
ASTNode coveringNode = mContext.getCoveringNode();
int start = coveringNode.getStartPosition();
int length = coveringNode.getLength();
IBuffer buffer = mContext.getCompilationUnit().getBuffer();
StringBuilder sb = new StringBuilder();
String string = buffer.getText(start, length);
string = ExtractStringRefactoring.unquoteAttrValue(string);
String token = ExtractStringInputPage.guessId(string);
// Look up the beginning and the end of the line (outside of the extracted string)
// such that we can show a preview of the diff, e.g. if you have
// foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello);
// so we need to extract "foo.setTitle(" and ");".
// Look backwards to the beginning of the line (and strip whitespace)
int i = start - 1;
while (i > 0) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i--;
}
String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim();
// Look forwards to the end of the line (and strip whitespace)
i = start + length;
while (i < buffer.getLength()) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string);
sb.append("</string></b><br>"); //$NON-NLS-1$
sb.append("</resources>"); //$NON-NLS-1$
return sb.toString();
} catch (JavaModelException e) {
AdtPlugin.log(e, null);
}
return "Initiates the Extract String refactoring operation";
} | NONSATD | true | }
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$ | if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
} | if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string); |
30,838 | 13 | //$NON-NLS-1$ | @Override
public String getAdditionalProposalInfo() {
try {
ASTNode coveringNode = mContext.getCoveringNode();
int start = coveringNode.getStartPosition();
int length = coveringNode.getLength();
IBuffer buffer = mContext.getCompilationUnit().getBuffer();
StringBuilder sb = new StringBuilder();
String string = buffer.getText(start, length);
string = ExtractStringRefactoring.unquoteAttrValue(string);
String token = ExtractStringInputPage.guessId(string);
// Look up the beginning and the end of the line (outside of the extracted string)
// such that we can show a preview of the diff, e.g. if you have
// foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello);
// so we need to extract "foo.setTitle(" and ");".
// Look backwards to the beginning of the line (and strip whitespace)
int i = start - 1;
while (i > 0) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i--;
}
String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim();
// Look forwards to the end of the line (and strip whitespace)
i = start + length;
while (i < buffer.getLength()) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string);
sb.append("</string></b><br>"); //$NON-NLS-1$
sb.append("</resources>"); //$NON-NLS-1$
return sb.toString();
} catch (JavaModelException e) {
AdtPlugin.log(e, null);
}
return "Initiates the Extract String refactoring operation";
} | NONSATD | true | }
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$ | if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
} | if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string); |
30,838 | 14 | //$NON-NLS-1$ | @Override
public String getAdditionalProposalInfo() {
try {
ASTNode coveringNode = mContext.getCoveringNode();
int start = coveringNode.getStartPosition();
int length = coveringNode.getLength();
IBuffer buffer = mContext.getCompilationUnit().getBuffer();
StringBuilder sb = new StringBuilder();
String string = buffer.getText(start, length);
string = ExtractStringRefactoring.unquoteAttrValue(string);
String token = ExtractStringInputPage.guessId(string);
// Look up the beginning and the end of the line (outside of the extracted string)
// such that we can show a preview of the diff, e.g. if you have
// foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello);
// so we need to extract "foo.setTitle(" and ");".
// Look backwards to the beginning of the line (and strip whitespace)
int i = start - 1;
while (i > 0) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i--;
}
String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim();
// Look forwards to the end of the line (and strip whitespace)
i = start + length;
while (i < buffer.getLength()) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string);
sb.append("</string></b><br>"); //$NON-NLS-1$
sb.append("</resources>"); //$NON-NLS-1$
return sb.toString();
} catch (JavaModelException e) {
AdtPlugin.log(e, null);
}
return "Initiates the Extract String refactoring operation";
} | NONSATD | true | }
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$ | if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
} | if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string); |
30,838 | 15 | //$NON-NLS-1$ | @Override
public String getAdditionalProposalInfo() {
try {
ASTNode coveringNode = mContext.getCoveringNode();
int start = coveringNode.getStartPosition();
int length = coveringNode.getLength();
IBuffer buffer = mContext.getCompilationUnit().getBuffer();
StringBuilder sb = new StringBuilder();
String string = buffer.getText(start, length);
string = ExtractStringRefactoring.unquoteAttrValue(string);
String token = ExtractStringInputPage.guessId(string);
// Look up the beginning and the end of the line (outside of the extracted string)
// such that we can show a preview of the diff, e.g. if you have
// foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello);
// so we need to extract "foo.setTitle(" and ");".
// Look backwards to the beginning of the line (and strip whitespace)
int i = start - 1;
while (i > 0) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i--;
}
String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim();
// Look forwards to the end of the line (and strip whitespace)
i = start + length;
while (i < buffer.getLength()) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string);
sb.append("</string></b><br>"); //$NON-NLS-1$
sb.append("</resources>"); //$NON-NLS-1$
return sb.toString();
} catch (JavaModelException e) {
AdtPlugin.log(e, null);
}
return "Initiates the Extract String refactoring operation";
} | NONSATD | true | }
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$ | if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
} | if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string); |
30,838 | 16 | //$NON-NLS-1$ | @Override
public String getAdditionalProposalInfo() {
try {
ASTNode coveringNode = mContext.getCoveringNode();
int start = coveringNode.getStartPosition();
int length = coveringNode.getLength();
IBuffer buffer = mContext.getCompilationUnit().getBuffer();
StringBuilder sb = new StringBuilder();
String string = buffer.getText(start, length);
string = ExtractStringRefactoring.unquoteAttrValue(string);
String token = ExtractStringInputPage.guessId(string);
// Look up the beginning and the end of the line (outside of the extracted string)
// such that we can show a preview of the diff, e.g. if you have
// foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello);
// so we need to extract "foo.setTitle(" and ");".
// Look backwards to the beginning of the line (and strip whitespace)
int i = start - 1;
while (i > 0) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i--;
}
String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim();
// Look forwards to the end of the line (and strip whitespace)
i = start + length;
while (i < buffer.getLength()) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string);
sb.append("</string></b><br>"); //$NON-NLS-1$
sb.append("</resources>"); //$NON-NLS-1$
return sb.toString();
} catch (JavaModelException e) {
AdtPlugin.log(e, null);
}
return "Initiates the Extract String refactoring operation";
} | NONSATD | true | }
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$ | if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
} | if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string); |
30,838 | 17 | //$NON-NLS-1$ | @Override
public String getAdditionalProposalInfo() {
try {
ASTNode coveringNode = mContext.getCoveringNode();
int start = coveringNode.getStartPosition();
int length = coveringNode.getLength();
IBuffer buffer = mContext.getCompilationUnit().getBuffer();
StringBuilder sb = new StringBuilder();
String string = buffer.getText(start, length);
string = ExtractStringRefactoring.unquoteAttrValue(string);
String token = ExtractStringInputPage.guessId(string);
// Look up the beginning and the end of the line (outside of the extracted string)
// such that we can show a preview of the diff, e.g. if you have
// foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello);
// so we need to extract "foo.setTitle(" and ");".
// Look backwards to the beginning of the line (and strip whitespace)
int i = start - 1;
while (i > 0) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i--;
}
String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim();
// Look forwards to the end of the line (and strip whitespace)
i = start + length;
while (i < buffer.getLength()) {
char c = buffer.getChar(i);
if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string);
sb.append("</string></b><br>"); //$NON-NLS-1$
sb.append("</resources>"); //$NON-NLS-1$
return sb.toString();
} catch (JavaModelException e) {
AdtPlugin.log(e, null);
}
return "Initiates the Extract String refactoring operation";
} | NONSATD | true | }
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$ | if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
} | if (c == '\r' || (c == '\n')) {
break;
}
i++;
}
String lineSuffix = buffer.getText(start + length, i - (start + length));
// Should we show the replacement as just R.string.foo or
// context.getString(R.string.foo) ?
boolean useContext = false;
ASTNode parent = coveringNode.getParent();
if (parent != null) {
int type = parent.getNodeType();
if (type == ASTNode.ASSIGNMENT
|| type == ASTNode.VARIABLE_DECLARATION_STATEMENT
|| type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
|| type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
useContext = true;
}
}
// Display .java change:
sb.append("...<br>"); //$NON-NLS-1$
sb.append(linePrefix);
sb.append("<b>"); //$NON-NLS-1$
if (useContext) {
sb.append("context.getString("); //$NON-NLS-1$
}
sb.append("R.string."); //$NON-NLS-1$
sb.append(token);
if (useContext) {
sb.append(")"); //$NON-NLS-1$
}
sb.append("</b>"); //$NON-NLS-1$
sb.append(lineSuffix);
sb.append("<br>...<br>"); //$NON-NLS-1$
// Display strings.xml change:
sb.append("<br>"); //$NON-NLS-1$
sb.append("<resources><br>"); //$NON-NLS-1$
sb.append(" <b><string name=\""); //$NON-NLS-1$
sb.append(token);
sb.append("\">"); //$NON-NLS-1$
sb.append(string); |
14,459 | 0 | /**
* Metodo encargado de asignar un/a enfermero/a a un registro de vacunacion
*
* Este metodo hace uso del metodo searchForVaccinationRegister() para buscar el registro
* y a continuacion asignar el/la enfermero/a
*
* @param patient El paciente al cual se le quiere asignar el/la enfermero/a
* @param nurse El/la enfermero/a a asignar
*/ | public void assignNurseToRegister(Patient patient, Nurse nurse)
{
VaccinationRegister registerToAssingNurse = searchForVaccinationRegister(patient);
registerToAssingNurse.assignNurse(nurse);
} | NONSATD | true | public void assignNurseToRegister(Patient patient, Nurse nurse)
{
VaccinationRegister registerToAssingNurse = searchForVaccinationRegister(patient);
registerToAssingNurse.assignNurse(nurse);
} | public void assignNurseToRegister(Patient patient, Nurse nurse)
{
VaccinationRegister registerToAssingNurse = searchForVaccinationRegister(patient);
registerToAssingNurse.assignNurse(nurse);
} | public void assignNurseToRegister(Patient patient, Nurse nurse)
{
VaccinationRegister registerToAssingNurse = searchForVaccinationRegister(patient);
registerToAssingNurse.assignNurse(nurse);
} |
22,702 | 0 | /**
* Metodo para buscar una compra (READ)
* @param compraId, id de la compra a buscar
* @return la compra con el id ingresado por parametro
*/ | public CompraEntity find(Long compraId) {
LOGGER.log(Level.INFO, "Buscando compra con el id={0}", compraId);
return em.find(CompraEntity.class, compraId);
} | IMPLEMENTATION | true | public CompraEntity find(Long compraId) {
LOGGER.log(Level.INFO, "Buscando compra con el id={0}", compraId);
return em.find(CompraEntity.class, compraId);
} | public CompraEntity find(Long compraId) {
LOGGER.log(Level.INFO, "Buscando compra con el id={0}", compraId);
return em.find(CompraEntity.class, compraId);
} | public CompraEntity find(Long compraId) {
LOGGER.log(Level.INFO, "Buscando compra con el id={0}", compraId);
return em.find(CompraEntity.class, compraId);
} |
22,714 | 0 | // TODO: !! Delete key should also delete this attachment. | public Dialog onCreateDialog(int dialogId){
Dialog dialog = null;
try{
//Log.v(TAG, "onCreateDialog() called");
if (mManagedDialogs == null) {
mManagedDialogs = new SparseArray<Dialog>();
}
switch(dialogId){
case DIALOG_DELETE_ATTACHMENT_ID:
dialog = new AlertDialog.Builder(mActivity)
.setTitle(R.string.dialog_confirmDelete)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.dialog_areYouSure)
.setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener.
public void onClick(DialogInterface dialog, int whichButton){
try{
if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){
if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){
ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user.
}
// Notify the ListAdapter that it's cursor needs refreshing
notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FD", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FD", exp, mActivity);
}
}
})
.setNegativeButton(R.string.button_no, null)
.create();
mManagedDialogs.put(dialogId, dialog);
break;
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FC", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FC", exp, mActivity);
}
return dialog;
} | DESIGN | true | public Dialog onCreateDialog(int dialogId){
Dialog dialog = null;
try{
//Log.v(TAG, "onCreateDialog() called");
if (mManagedDialogs == null) {
mManagedDialogs = new SparseArray<Dialog>();
}
switch(dialogId){
case DIALOG_DELETE_ATTACHMENT_ID:
dialog = new AlertDialog.Builder(mActivity)
.setTitle(R.string.dialog_confirmDelete)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.dialog_areYouSure)
.setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener.
public void onClick(DialogInterface dialog, int whichButton){
try{
if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){
if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){
ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user.
}
// Notify the ListAdapter that it's cursor needs refreshing
notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FD", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FD", exp, mActivity);
}
}
})
.setNegativeButton(R.string.button_no, null)
.create();
mManagedDialogs.put(dialogId, dialog);
break;
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FC", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FC", exp, mActivity);
}
return dialog;
} | public Dialog onCreateDialog(int dialogId){
Dialog dialog = null;
try{
//Log.v(TAG, "onCreateDialog() called");
if (mManagedDialogs == null) {
mManagedDialogs = new SparseArray<Dialog>();
}
switch(dialogId){
case DIALOG_DELETE_ATTACHMENT_ID:
dialog = new AlertDialog.Builder(mActivity)
.setTitle(R.string.dialog_confirmDelete)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.dialog_areYouSure)
.setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener.
public void onClick(DialogInterface dialog, int whichButton){
try{
if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){
if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){
ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user.
}
// Notify the ListAdapter that it's cursor needs refreshing
notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FD", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FD", exp, mActivity);
}
}
})
.setNegativeButton(R.string.button_no, null)
.create();
mManagedDialogs.put(dialogId, dialog);
break;
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FC", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FC", exp, mActivity);
}
return dialog;
} | public Dialog onCreateDialog(int dialogId){
Dialog dialog = null;
try{
//Log.v(TAG, "onCreateDialog() called");
if (mManagedDialogs == null) {
mManagedDialogs = new SparseArray<Dialog>();
}
switch(dialogId){
case DIALOG_DELETE_ATTACHMENT_ID:
dialog = new AlertDialog.Builder(mActivity)
.setTitle(R.string.dialog_confirmDelete)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.dialog_areYouSure)
.setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener.
public void onClick(DialogInterface dialog, int whichButton){
try{
if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){
if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){
ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user.
}
// Notify the ListAdapter that it's cursor needs refreshing
notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FD", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FD", exp, mActivity);
}
}
})
.setNegativeButton(R.string.button_no, null)
.create();
mManagedDialogs.put(dialogId, dialog);
break;
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FC", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FC", exp, mActivity);
}
return dialog;
} |
22,714 | 1 | //Log.v(TAG, "onCreateDialog() called"); | public Dialog onCreateDialog(int dialogId){
Dialog dialog = null;
try{
//Log.v(TAG, "onCreateDialog() called");
if (mManagedDialogs == null) {
mManagedDialogs = new SparseArray<Dialog>();
}
switch(dialogId){
case DIALOG_DELETE_ATTACHMENT_ID:
dialog = new AlertDialog.Builder(mActivity)
.setTitle(R.string.dialog_confirmDelete)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.dialog_areYouSure)
.setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener.
public void onClick(DialogInterface dialog, int whichButton){
try{
if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){
if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){
ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user.
}
// Notify the ListAdapter that it's cursor needs refreshing
notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FD", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FD", exp, mActivity);
}
}
})
.setNegativeButton(R.string.button_no, null)
.create();
mManagedDialogs.put(dialogId, dialog);
break;
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FC", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FC", exp, mActivity);
}
return dialog;
} | NONSATD | true | Dialog dialog = null;
try{
//Log.v(TAG, "onCreateDialog() called");
if (mManagedDialogs == null) {
mManagedDialogs = new SparseArray<Dialog>(); | public Dialog onCreateDialog(int dialogId){
Dialog dialog = null;
try{
//Log.v(TAG, "onCreateDialog() called");
if (mManagedDialogs == null) {
mManagedDialogs = new SparseArray<Dialog>();
}
switch(dialogId){
case DIALOG_DELETE_ATTACHMENT_ID:
dialog = new AlertDialog.Builder(mActivity)
.setTitle(R.string.dialog_confirmDelete)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.dialog_areYouSure)
.setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener. | public Dialog onCreateDialog(int dialogId){
Dialog dialog = null;
try{
//Log.v(TAG, "onCreateDialog() called");
if (mManagedDialogs == null) {
mManagedDialogs = new SparseArray<Dialog>();
}
switch(dialogId){
case DIALOG_DELETE_ATTACHMENT_ID:
dialog = new AlertDialog.Builder(mActivity)
.setTitle(R.string.dialog_confirmDelete)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.dialog_areYouSure)
.setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener.
public void onClick(DialogInterface dialog, int whichButton){
try{
if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){
if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){
ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user.
}
// Notify the ListAdapter that it's cursor needs refreshing
notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore. |
22,714 | 2 | // TODO: !!! Make handler implement the DialogInterface.OnClickListener. | public Dialog onCreateDialog(int dialogId){
Dialog dialog = null;
try{
//Log.v(TAG, "onCreateDialog() called");
if (mManagedDialogs == null) {
mManagedDialogs = new SparseArray<Dialog>();
}
switch(dialogId){
case DIALOG_DELETE_ATTACHMENT_ID:
dialog = new AlertDialog.Builder(mActivity)
.setTitle(R.string.dialog_confirmDelete)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.dialog_areYouSure)
.setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener.
public void onClick(DialogInterface dialog, int whichButton){
try{
if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){
if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){
ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user.
}
// Notify the ListAdapter that it's cursor needs refreshing
notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FD", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FD", exp, mActivity);
}
}
})
.setNegativeButton(R.string.button_no, null)
.create();
mManagedDialogs.put(dialogId, dialog);
break;
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FC", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FC", exp, mActivity);
}
return dialog;
} | IMPLEMENTATION | true | .setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.dialog_areYouSure)
.setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener.
public void onClick(DialogInterface dialog, int whichButton){
try{ | //Log.v(TAG, "onCreateDialog() called");
if (mManagedDialogs == null) {
mManagedDialogs = new SparseArray<Dialog>();
}
switch(dialogId){
case DIALOG_DELETE_ATTACHMENT_ID:
dialog = new AlertDialog.Builder(mActivity)
.setTitle(R.string.dialog_confirmDelete)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.dialog_areYouSure)
.setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener.
public void onClick(DialogInterface dialog, int whichButton){
try{
if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){
if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){
ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user.
}
// Notify the ListAdapter that it's cursor needs refreshing
notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore. | public Dialog onCreateDialog(int dialogId){
Dialog dialog = null;
try{
//Log.v(TAG, "onCreateDialog() called");
if (mManagedDialogs == null) {
mManagedDialogs = new SparseArray<Dialog>();
}
switch(dialogId){
case DIALOG_DELETE_ATTACHMENT_ID:
dialog = new AlertDialog.Builder(mActivity)
.setTitle(R.string.dialog_confirmDelete)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.dialog_areYouSure)
.setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener.
public void onClick(DialogInterface dialog, int whichButton){
try{
if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){
if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){
ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user.
}
// Notify the ListAdapter that it's cursor needs refreshing
notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FD", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FD", exp, mActivity);
}
}
})
.setNegativeButton(R.string.button_no, null)
.create();
mManagedDialogs.put(dialogId, dialog);
break; |
22,714 | 3 | // Error already handled, so just notify user. | public Dialog onCreateDialog(int dialogId){
Dialog dialog = null;
try{
//Log.v(TAG, "onCreateDialog() called");
if (mManagedDialogs == null) {
mManagedDialogs = new SparseArray<Dialog>();
}
switch(dialogId){
case DIALOG_DELETE_ATTACHMENT_ID:
dialog = new AlertDialog.Builder(mActivity)
.setTitle(R.string.dialog_confirmDelete)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.dialog_areYouSure)
.setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener.
public void onClick(DialogInterface dialog, int whichButton){
try{
if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){
if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){
ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user.
}
// Notify the ListAdapter that it's cursor needs refreshing
notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FD", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FD", exp, mActivity);
}
}
})
.setNegativeButton(R.string.button_no, null)
.create();
mManagedDialogs.put(dialogId, dialog);
break;
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FC", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FC", exp, mActivity);
}
return dialog;
} | NONSATD | true | if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){
if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){
ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user.
}
// Notify the ListAdapter that it's cursor needs refreshing | case DIALOG_DELETE_ATTACHMENT_ID:
dialog = new AlertDialog.Builder(mActivity)
.setTitle(R.string.dialog_confirmDelete)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.dialog_areYouSure)
.setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener.
public void onClick(DialogInterface dialog, int whichButton){
try{
if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){
if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){
ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user.
}
// Notify the ListAdapter that it's cursor needs refreshing
notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FD", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FD", exp, mActivity);
}
} | public Dialog onCreateDialog(int dialogId){
Dialog dialog = null;
try{
//Log.v(TAG, "onCreateDialog() called");
if (mManagedDialogs == null) {
mManagedDialogs = new SparseArray<Dialog>();
}
switch(dialogId){
case DIALOG_DELETE_ATTACHMENT_ID:
dialog = new AlertDialog.Builder(mActivity)
.setTitle(R.string.dialog_confirmDelete)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.dialog_areYouSure)
.setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener.
public void onClick(DialogInterface dialog, int whichButton){
try{
if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){
if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){
ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user.
}
// Notify the ListAdapter that it's cursor needs refreshing
notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FD", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FD", exp, mActivity);
}
}
})
.setNegativeButton(R.string.button_no, null)
.create();
mManagedDialogs.put(dialogId, dialog);
break;
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FC", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FC", exp, mActivity); |
22,714 | 4 | // Notify the ListAdapter that it's cursor needs refreshing | public Dialog onCreateDialog(int dialogId){
Dialog dialog = null;
try{
//Log.v(TAG, "onCreateDialog() called");
if (mManagedDialogs == null) {
mManagedDialogs = new SparseArray<Dialog>();
}
switch(dialogId){
case DIALOG_DELETE_ATTACHMENT_ID:
dialog = new AlertDialog.Builder(mActivity)
.setTitle(R.string.dialog_confirmDelete)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.dialog_areYouSure)
.setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener.
public void onClick(DialogInterface dialog, int whichButton){
try{
if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){
if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){
ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user.
}
// Notify the ListAdapter that it's cursor needs refreshing
notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FD", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FD", exp, mActivity);
}
}
})
.setNegativeButton(R.string.button_no, null)
.create();
mManagedDialogs.put(dialogId, dialog);
break;
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FC", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FC", exp, mActivity);
}
return dialog;
} | NONSATD | true | ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user.
}
// Notify the ListAdapter that it's cursor needs refreshing
notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
} | .setTitle(R.string.dialog_confirmDelete)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.dialog_areYouSure)
.setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener.
public void onClick(DialogInterface dialog, int whichButton){
try{
if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){
if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){
ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user.
}
// Notify the ListAdapter that it's cursor needs refreshing
notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FD", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FD", exp, mActivity);
}
}
})
.setNegativeButton(R.string.button_no, null) | public Dialog onCreateDialog(int dialogId){
Dialog dialog = null;
try{
//Log.v(TAG, "onCreateDialog() called");
if (mManagedDialogs == null) {
mManagedDialogs = new SparseArray<Dialog>();
}
switch(dialogId){
case DIALOG_DELETE_ATTACHMENT_ID:
dialog = new AlertDialog.Builder(mActivity)
.setTitle(R.string.dialog_confirmDelete)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.dialog_areYouSure)
.setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener.
public void onClick(DialogInterface dialog, int whichButton){
try{
if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){
if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){
ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user.
}
// Notify the ListAdapter that it's cursor needs refreshing
notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FD", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FD", exp, mActivity);
}
}
})
.setNegativeButton(R.string.button_no, null)
.create();
mManagedDialogs.put(dialogId, dialog);
break;
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FC", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FC", exp, mActivity);
}
return dialog; |
22,714 | 5 | // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record. | public Dialog onCreateDialog(int dialogId){
Dialog dialog = null;
try{
//Log.v(TAG, "onCreateDialog() called");
if (mManagedDialogs == null) {
mManagedDialogs = new SparseArray<Dialog>();
}
switch(dialogId){
case DIALOG_DELETE_ATTACHMENT_ID:
dialog = new AlertDialog.Builder(mActivity)
.setTitle(R.string.dialog_confirmDelete)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.dialog_areYouSure)
.setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener.
public void onClick(DialogInterface dialog, int whichButton){
try{
if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){
if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){
ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user.
}
// Notify the ListAdapter that it's cursor needs refreshing
notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FD", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FD", exp, mActivity);
}
}
})
.setNegativeButton(R.string.button_no, null)
.create();
mManagedDialogs.put(dialogId, dialog);
break;
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FC", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FC", exp, mActivity);
}
return dialog;
} | DESIGN | true | }
// Notify the ListAdapter that it's cursor needs refreshing
notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore. | .setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.dialog_areYouSure)
.setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener.
public void onClick(DialogInterface dialog, int whichButton){
try{
if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){
if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){
ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user.
}
// Notify the ListAdapter that it's cursor needs refreshing
notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FD", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FD", exp, mActivity);
}
}
})
.setNegativeButton(R.string.button_no, null)
.create(); | Dialog dialog = null;
try{
//Log.v(TAG, "onCreateDialog() called");
if (mManagedDialogs == null) {
mManagedDialogs = new SparseArray<Dialog>();
}
switch(dialogId){
case DIALOG_DELETE_ATTACHMENT_ID:
dialog = new AlertDialog.Builder(mActivity)
.setTitle(R.string.dialog_confirmDelete)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.dialog_areYouSure)
.setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener.
public void onClick(DialogInterface dialog, int whichButton){
try{
if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){
if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){
ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user.
}
// Notify the ListAdapter that it's cursor needs refreshing
notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FD", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FD", exp, mActivity);
}
}
})
.setNegativeButton(R.string.button_no, null)
.create();
mManagedDialogs.put(dialogId, dialog);
break;
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FC", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FC", exp, mActivity);
}
return dialog;
} |
22,714 | 6 | // Ignore. | public Dialog onCreateDialog(int dialogId){
Dialog dialog = null;
try{
//Log.v(TAG, "onCreateDialog() called");
if (mManagedDialogs == null) {
mManagedDialogs = new SparseArray<Dialog>();
}
switch(dialogId){
case DIALOG_DELETE_ATTACHMENT_ID:
dialog = new AlertDialog.Builder(mActivity)
.setTitle(R.string.dialog_confirmDelete)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.dialog_areYouSure)
.setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener.
public void onClick(DialogInterface dialog, int whichButton){
try{
if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){
if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){
ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user.
}
// Notify the ListAdapter that it's cursor needs refreshing
notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FD", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FD", exp, mActivity);
}
}
})
.setNegativeButton(R.string.button_no, null)
.create();
mManagedDialogs.put(dialogId, dialog);
break;
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FC", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FC", exp, mActivity);
}
return dialog;
} | NONSATD | true | notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FD", exp); | .setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener.
public void onClick(DialogInterface dialog, int whichButton){
try{
if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){
if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){
ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user.
}
// Notify the ListAdapter that it's cursor needs refreshing
notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FD", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FD", exp, mActivity);
}
}
})
.setNegativeButton(R.string.button_no, null)
.create();
mManagedDialogs.put(dialogId, dialog);
break; | //Log.v(TAG, "onCreateDialog() called");
if (mManagedDialogs == null) {
mManagedDialogs = new SparseArray<Dialog>();
}
switch(dialogId){
case DIALOG_DELETE_ATTACHMENT_ID:
dialog = new AlertDialog.Builder(mActivity)
.setTitle(R.string.dialog_confirmDelete)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.dialog_areYouSure)
.setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener.
public void onClick(DialogInterface dialog, int whichButton){
try{
if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){
if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){
ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user.
}
// Notify the ListAdapter that it's cursor needs refreshing
notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FD", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FD", exp, mActivity);
}
}
})
.setNegativeButton(R.string.button_no, null)
.create();
mManagedDialogs.put(dialogId, dialog);
break;
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FC", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FC", exp, mActivity);
}
return dialog;
} |
22,714 | 7 | // Ignore. | public Dialog onCreateDialog(int dialogId){
Dialog dialog = null;
try{
//Log.v(TAG, "onCreateDialog() called");
if (mManagedDialogs == null) {
mManagedDialogs = new SparseArray<Dialog>();
}
switch(dialogId){
case DIALOG_DELETE_ATTACHMENT_ID:
dialog = new AlertDialog.Builder(mActivity)
.setTitle(R.string.dialog_confirmDelete)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.dialog_areYouSure)
.setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener.
public void onClick(DialogInterface dialog, int whichButton){
try{
if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){
if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){
ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user.
}
// Notify the ListAdapter that it's cursor needs refreshing
notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FD", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FD", exp, mActivity);
}
}
})
.setNegativeButton(R.string.button_no, null)
.create();
mManagedDialogs.put(dialogId, dialog);
break;
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FC", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FC", exp, mActivity);
}
return dialog;
} | NONSATD | true | notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FD", exp); | .setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener.
public void onClick(DialogInterface dialog, int whichButton){
try{
if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){
if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){
ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user.
}
// Notify the ListAdapter that it's cursor needs refreshing
notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FD", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FD", exp, mActivity);
}
}
})
.setNegativeButton(R.string.button_no, null)
.create();
mManagedDialogs.put(dialogId, dialog);
break; | //Log.v(TAG, "onCreateDialog() called");
if (mManagedDialogs == null) {
mManagedDialogs = new SparseArray<Dialog>();
}
switch(dialogId){
case DIALOG_DELETE_ATTACHMENT_ID:
dialog = new AlertDialog.Builder(mActivity)
.setTitle(R.string.dialog_confirmDelete)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.dialog_areYouSure)
.setPositiveButton(R.string.button_yes, new android.content.DialogInterface.OnClickListener(){ // TODO: !!! Make handler implement the DialogInterface.OnClickListener.
public void onClick(DialogInterface dialog, int whichButton){
try{
if( whichButton == android.content.DialogInterface.BUTTON_POSITIVE){
if( !CompletableUtil.delete(mActivity, mAttachmentUri) ){
ErrorUtil.notifyUser(mActivity); // Error already handled, so just notify user.
}
// Notify the ListAdapter that it's cursor needs refreshing
notifyDataSetChanged(); // TODO: !! Isn't this a hack to get around the normal observer thing? NO, not always. Sometimes data changes in the db record that the URI refers to and it isn't really a change to the attachment record.
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FD", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FD", exp, mActivity);
}
}
})
.setNegativeButton(R.string.button_no, null)
.create();
mManagedDialogs.put(dialogId, dialog);
break;
}
}catch(HandledException h){ // Ignore.
}catch(Exception exp){
Log.e(TAG, "ERR000FC", exp);
ErrorUtil.handleExceptionNotifyUser("ERR000FC", exp, mActivity);
}
return dialog;
} |
30,915 | 0 | /**
* Overrides setup() in ApplicationTest and does not call super.setup().
*/ | @BeforeEach
protected void setup() throws Exception {
// Remove the existing program data folder
String suffix = "-" + Profile.TEST;
ProductCard metadata = ProductCard.info( Program.class );
Path programDataFolder = OperatingSystem.getUserProgramDataFolder( metadata.getArtifact() + suffix, metadata.getName() + suffix );
assertThat( aggressiveDelete( programDataFolder ) ).withFailMessage( "Failed to delete program data folder" ).isTrue();
// For the parameters to be available using Java 9, the following needs to be added
// to the test JVM command line parameters because com.sun.javafx.application.ParametersImpl
// is not exposed, nor is there a "proper" way to access it:
//
// --add-opens=javafx.graphics/com.sun.javafx.application=ALL-UNNAMED
program = (Program)FxToolkit.setupApplication( Program.class, ProgramTestConfig.getParameterValues() );
program.register( ProgramEvent.ANY, programWatcher = new EventWatcher( TIMEOUT ) );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
programWatcher.waitForEvent( ProgramEvent.STARTED, TIMEOUT );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
// Wait for the active workarea
// FIXME This should use an event listener to wait for the workarea
long limit = System.currentTimeMillis() + TIMEOUT;
while( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() == null && System.currentTimeMillis() < limit ) {
ThreadUtil.pause( 100 );
}
assertThat( program ).withFailMessage( "Program is null" ).isNotNull();
assertThat( program.getWorkspaceManager() ).withFailMessage( "Workspace manager is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace() ).withFailMessage( "Active workspace is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() ).withFailMessage( "Active workarea is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane() ).withFailMessage( "Active workpane is null" ).isNotNull();
Workpane workpane = program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane();
workpane.addEventHandler( WorkpaneEvent.ANY, workpaneWatcher = new FxEventWatcher() );
initialMemoryUse = getMemoryUse();
} | NONSATD | true | @BeforeEach
protected void setup() throws Exception {
// Remove the existing program data folder
String suffix = "-" + Profile.TEST;
ProductCard metadata = ProductCard.info( Program.class );
Path programDataFolder = OperatingSystem.getUserProgramDataFolder( metadata.getArtifact() + suffix, metadata.getName() + suffix );
assertThat( aggressiveDelete( programDataFolder ) ).withFailMessage( "Failed to delete program data folder" ).isTrue();
// For the parameters to be available using Java 9, the following needs to be added
// to the test JVM command line parameters because com.sun.javafx.application.ParametersImpl
// is not exposed, nor is there a "proper" way to access it:
//
// --add-opens=javafx.graphics/com.sun.javafx.application=ALL-UNNAMED
program = (Program)FxToolkit.setupApplication( Program.class, ProgramTestConfig.getParameterValues() );
program.register( ProgramEvent.ANY, programWatcher = new EventWatcher( TIMEOUT ) );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
programWatcher.waitForEvent( ProgramEvent.STARTED, TIMEOUT );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
// Wait for the active workarea
// FIXME This should use an event listener to wait for the workarea
long limit = System.currentTimeMillis() + TIMEOUT;
while( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() == null && System.currentTimeMillis() < limit ) {
ThreadUtil.pause( 100 );
}
assertThat( program ).withFailMessage( "Program is null" ).isNotNull();
assertThat( program.getWorkspaceManager() ).withFailMessage( "Workspace manager is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace() ).withFailMessage( "Active workspace is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() ).withFailMessage( "Active workarea is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane() ).withFailMessage( "Active workpane is null" ).isNotNull();
Workpane workpane = program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane();
workpane.addEventHandler( WorkpaneEvent.ANY, workpaneWatcher = new FxEventWatcher() );
initialMemoryUse = getMemoryUse();
} | @BeforeEach
protected void setup() throws Exception {
// Remove the existing program data folder
String suffix = "-" + Profile.TEST;
ProductCard metadata = ProductCard.info( Program.class );
Path programDataFolder = OperatingSystem.getUserProgramDataFolder( metadata.getArtifact() + suffix, metadata.getName() + suffix );
assertThat( aggressiveDelete( programDataFolder ) ).withFailMessage( "Failed to delete program data folder" ).isTrue();
// For the parameters to be available using Java 9, the following needs to be added
// to the test JVM command line parameters because com.sun.javafx.application.ParametersImpl
// is not exposed, nor is there a "proper" way to access it:
//
// --add-opens=javafx.graphics/com.sun.javafx.application=ALL-UNNAMED
program = (Program)FxToolkit.setupApplication( Program.class, ProgramTestConfig.getParameterValues() );
program.register( ProgramEvent.ANY, programWatcher = new EventWatcher( TIMEOUT ) );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
programWatcher.waitForEvent( ProgramEvent.STARTED, TIMEOUT );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
// Wait for the active workarea
// FIXME This should use an event listener to wait for the workarea
long limit = System.currentTimeMillis() + TIMEOUT;
while( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() == null && System.currentTimeMillis() < limit ) {
ThreadUtil.pause( 100 );
}
assertThat( program ).withFailMessage( "Program is null" ).isNotNull();
assertThat( program.getWorkspaceManager() ).withFailMessage( "Workspace manager is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace() ).withFailMessage( "Active workspace is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() ).withFailMessage( "Active workarea is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane() ).withFailMessage( "Active workpane is null" ).isNotNull();
Workpane workpane = program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane();
workpane.addEventHandler( WorkpaneEvent.ANY, workpaneWatcher = new FxEventWatcher() );
initialMemoryUse = getMemoryUse();
} | @BeforeEach
protected void setup() throws Exception {
// Remove the existing program data folder
String suffix = "-" + Profile.TEST;
ProductCard metadata = ProductCard.info( Program.class );
Path programDataFolder = OperatingSystem.getUserProgramDataFolder( metadata.getArtifact() + suffix, metadata.getName() + suffix );
assertThat( aggressiveDelete( programDataFolder ) ).withFailMessage( "Failed to delete program data folder" ).isTrue();
// For the parameters to be available using Java 9, the following needs to be added
// to the test JVM command line parameters because com.sun.javafx.application.ParametersImpl
// is not exposed, nor is there a "proper" way to access it:
//
// --add-opens=javafx.graphics/com.sun.javafx.application=ALL-UNNAMED
program = (Program)FxToolkit.setupApplication( Program.class, ProgramTestConfig.getParameterValues() );
program.register( ProgramEvent.ANY, programWatcher = new EventWatcher( TIMEOUT ) );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
programWatcher.waitForEvent( ProgramEvent.STARTED, TIMEOUT );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
// Wait for the active workarea
// FIXME This should use an event listener to wait for the workarea
long limit = System.currentTimeMillis() + TIMEOUT;
while( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() == null && System.currentTimeMillis() < limit ) {
ThreadUtil.pause( 100 );
}
assertThat( program ).withFailMessage( "Program is null" ).isNotNull();
assertThat( program.getWorkspaceManager() ).withFailMessage( "Workspace manager is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace() ).withFailMessage( "Active workspace is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() ).withFailMessage( "Active workarea is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane() ).withFailMessage( "Active workpane is null" ).isNotNull();
Workpane workpane = program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane();
workpane.addEventHandler( WorkpaneEvent.ANY, workpaneWatcher = new FxEventWatcher() );
initialMemoryUse = getMemoryUse();
} |
30,915 | 1 | // Remove the existing program data folder | @BeforeEach
protected void setup() throws Exception {
// Remove the existing program data folder
String suffix = "-" + Profile.TEST;
ProductCard metadata = ProductCard.info( Program.class );
Path programDataFolder = OperatingSystem.getUserProgramDataFolder( metadata.getArtifact() + suffix, metadata.getName() + suffix );
assertThat( aggressiveDelete( programDataFolder ) ).withFailMessage( "Failed to delete program data folder" ).isTrue();
// For the parameters to be available using Java 9, the following needs to be added
// to the test JVM command line parameters because com.sun.javafx.application.ParametersImpl
// is not exposed, nor is there a "proper" way to access it:
//
// --add-opens=javafx.graphics/com.sun.javafx.application=ALL-UNNAMED
program = (Program)FxToolkit.setupApplication( Program.class, ProgramTestConfig.getParameterValues() );
program.register( ProgramEvent.ANY, programWatcher = new EventWatcher( TIMEOUT ) );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
programWatcher.waitForEvent( ProgramEvent.STARTED, TIMEOUT );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
// Wait for the active workarea
// FIXME This should use an event listener to wait for the workarea
long limit = System.currentTimeMillis() + TIMEOUT;
while( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() == null && System.currentTimeMillis() < limit ) {
ThreadUtil.pause( 100 );
}
assertThat( program ).withFailMessage( "Program is null" ).isNotNull();
assertThat( program.getWorkspaceManager() ).withFailMessage( "Workspace manager is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace() ).withFailMessage( "Active workspace is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() ).withFailMessage( "Active workarea is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane() ).withFailMessage( "Active workpane is null" ).isNotNull();
Workpane workpane = program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane();
workpane.addEventHandler( WorkpaneEvent.ANY, workpaneWatcher = new FxEventWatcher() );
initialMemoryUse = getMemoryUse();
} | NONSATD | true | @BeforeEach
protected void setup() throws Exception {
// Remove the existing program data folder
String suffix = "-" + Profile.TEST;
ProductCard metadata = ProductCard.info( Program.class ); | @BeforeEach
protected void setup() throws Exception {
// Remove the existing program data folder
String suffix = "-" + Profile.TEST;
ProductCard metadata = ProductCard.info( Program.class );
Path programDataFolder = OperatingSystem.getUserProgramDataFolder( metadata.getArtifact() + suffix, metadata.getName() + suffix );
assertThat( aggressiveDelete( programDataFolder ) ).withFailMessage( "Failed to delete program data folder" ).isTrue();
// For the parameters to be available using Java 9, the following needs to be added
// to the test JVM command line parameters because com.sun.javafx.application.ParametersImpl
// is not exposed, nor is there a "proper" way to access it:
//
// --add-opens=javafx.graphics/com.sun.javafx.application=ALL-UNNAMED
program = (Program)FxToolkit.setupApplication( Program.class, ProgramTestConfig.getParameterValues() ); | @BeforeEach
protected void setup() throws Exception {
// Remove the existing program data folder
String suffix = "-" + Profile.TEST;
ProductCard metadata = ProductCard.info( Program.class );
Path programDataFolder = OperatingSystem.getUserProgramDataFolder( metadata.getArtifact() + suffix, metadata.getName() + suffix );
assertThat( aggressiveDelete( programDataFolder ) ).withFailMessage( "Failed to delete program data folder" ).isTrue();
// For the parameters to be available using Java 9, the following needs to be added
// to the test JVM command line parameters because com.sun.javafx.application.ParametersImpl
// is not exposed, nor is there a "proper" way to access it:
//
// --add-opens=javafx.graphics/com.sun.javafx.application=ALL-UNNAMED
program = (Program)FxToolkit.setupApplication( Program.class, ProgramTestConfig.getParameterValues() );
program.register( ProgramEvent.ANY, programWatcher = new EventWatcher( TIMEOUT ) );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
programWatcher.waitForEvent( ProgramEvent.STARTED, TIMEOUT );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
// Wait for the active workarea
// FIXME This should use an event listener to wait for the workarea |
30,915 | 2 | // For the parameters to be available using Java 9, the following needs to be added
// to the test JVM command line parameters because com.sun.javafx.application.ParametersImpl
// is not exposed, nor is there a "proper" way to access it:
//
// --add-opens=javafx.graphics/com.sun.javafx.application=ALL-UNNAMED | @BeforeEach
protected void setup() throws Exception {
// Remove the existing program data folder
String suffix = "-" + Profile.TEST;
ProductCard metadata = ProductCard.info( Program.class );
Path programDataFolder = OperatingSystem.getUserProgramDataFolder( metadata.getArtifact() + suffix, metadata.getName() + suffix );
assertThat( aggressiveDelete( programDataFolder ) ).withFailMessage( "Failed to delete program data folder" ).isTrue();
// For the parameters to be available using Java 9, the following needs to be added
// to the test JVM command line parameters because com.sun.javafx.application.ParametersImpl
// is not exposed, nor is there a "proper" way to access it:
//
// --add-opens=javafx.graphics/com.sun.javafx.application=ALL-UNNAMED
program = (Program)FxToolkit.setupApplication( Program.class, ProgramTestConfig.getParameterValues() );
program.register( ProgramEvent.ANY, programWatcher = new EventWatcher( TIMEOUT ) );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
programWatcher.waitForEvent( ProgramEvent.STARTED, TIMEOUT );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
// Wait for the active workarea
// FIXME This should use an event listener to wait for the workarea
long limit = System.currentTimeMillis() + TIMEOUT;
while( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() == null && System.currentTimeMillis() < limit ) {
ThreadUtil.pause( 100 );
}
assertThat( program ).withFailMessage( "Program is null" ).isNotNull();
assertThat( program.getWorkspaceManager() ).withFailMessage( "Workspace manager is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace() ).withFailMessage( "Active workspace is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() ).withFailMessage( "Active workarea is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane() ).withFailMessage( "Active workpane is null" ).isNotNull();
Workpane workpane = program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane();
workpane.addEventHandler( WorkpaneEvent.ANY, workpaneWatcher = new FxEventWatcher() );
initialMemoryUse = getMemoryUse();
} | NONSATD | true | Path programDataFolder = OperatingSystem.getUserProgramDataFolder( metadata.getArtifact() + suffix, metadata.getName() + suffix );
assertThat( aggressiveDelete( programDataFolder ) ).withFailMessage( "Failed to delete program data folder" ).isTrue();
// For the parameters to be available using Java 9, the following needs to be added
// to the test JVM command line parameters because com.sun.javafx.application.ParametersImpl
// is not exposed, nor is there a "proper" way to access it:
//
// --add-opens=javafx.graphics/com.sun.javafx.application=ALL-UNNAMED
program = (Program)FxToolkit.setupApplication( Program.class, ProgramTestConfig.getParameterValues() );
program.register( ProgramEvent.ANY, programWatcher = new EventWatcher( TIMEOUT ) ); | @BeforeEach
protected void setup() throws Exception {
// Remove the existing program data folder
String suffix = "-" + Profile.TEST;
ProductCard metadata = ProductCard.info( Program.class );
Path programDataFolder = OperatingSystem.getUserProgramDataFolder( metadata.getArtifact() + suffix, metadata.getName() + suffix );
assertThat( aggressiveDelete( programDataFolder ) ).withFailMessage( "Failed to delete program data folder" ).isTrue();
// For the parameters to be available using Java 9, the following needs to be added
// to the test JVM command line parameters because com.sun.javafx.application.ParametersImpl
// is not exposed, nor is there a "proper" way to access it:
//
// --add-opens=javafx.graphics/com.sun.javafx.application=ALL-UNNAMED
program = (Program)FxToolkit.setupApplication( Program.class, ProgramTestConfig.getParameterValues() );
program.register( ProgramEvent.ANY, programWatcher = new EventWatcher( TIMEOUT ) );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
programWatcher.waitForEvent( ProgramEvent.STARTED, TIMEOUT );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
// Wait for the active workarea | @BeforeEach
protected void setup() throws Exception {
// Remove the existing program data folder
String suffix = "-" + Profile.TEST;
ProductCard metadata = ProductCard.info( Program.class );
Path programDataFolder = OperatingSystem.getUserProgramDataFolder( metadata.getArtifact() + suffix, metadata.getName() + suffix );
assertThat( aggressiveDelete( programDataFolder ) ).withFailMessage( "Failed to delete program data folder" ).isTrue();
// For the parameters to be available using Java 9, the following needs to be added
// to the test JVM command line parameters because com.sun.javafx.application.ParametersImpl
// is not exposed, nor is there a "proper" way to access it:
//
// --add-opens=javafx.graphics/com.sun.javafx.application=ALL-UNNAMED
program = (Program)FxToolkit.setupApplication( Program.class, ProgramTestConfig.getParameterValues() );
program.register( ProgramEvent.ANY, programWatcher = new EventWatcher( TIMEOUT ) );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
programWatcher.waitForEvent( ProgramEvent.STARTED, TIMEOUT );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
// Wait for the active workarea
// FIXME This should use an event listener to wait for the workarea
long limit = System.currentTimeMillis() + TIMEOUT;
while( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() == null && System.currentTimeMillis() < limit ) {
ThreadUtil.pause( 100 );
}
assertThat( program ).withFailMessage( "Program is null" ).isNotNull();
assertThat( program.getWorkspaceManager() ).withFailMessage( "Workspace manager is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace() ).withFailMessage( "Active workspace is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() ).withFailMessage( "Active workarea is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane() ).withFailMessage( "Active workpane is null" ).isNotNull(); |
30,915 | 3 | // NOTE Thread.yield() is helpful but not consistent | @BeforeEach
protected void setup() throws Exception {
// Remove the existing program data folder
String suffix = "-" + Profile.TEST;
ProductCard metadata = ProductCard.info( Program.class );
Path programDataFolder = OperatingSystem.getUserProgramDataFolder( metadata.getArtifact() + suffix, metadata.getName() + suffix );
assertThat( aggressiveDelete( programDataFolder ) ).withFailMessage( "Failed to delete program data folder" ).isTrue();
// For the parameters to be available using Java 9, the following needs to be added
// to the test JVM command line parameters because com.sun.javafx.application.ParametersImpl
// is not exposed, nor is there a "proper" way to access it:
//
// --add-opens=javafx.graphics/com.sun.javafx.application=ALL-UNNAMED
program = (Program)FxToolkit.setupApplication( Program.class, ProgramTestConfig.getParameterValues() );
program.register( ProgramEvent.ANY, programWatcher = new EventWatcher( TIMEOUT ) );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
programWatcher.waitForEvent( ProgramEvent.STARTED, TIMEOUT );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
// Wait for the active workarea
// FIXME This should use an event listener to wait for the workarea
long limit = System.currentTimeMillis() + TIMEOUT;
while( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() == null && System.currentTimeMillis() < limit ) {
ThreadUtil.pause( 100 );
}
assertThat( program ).withFailMessage( "Program is null" ).isNotNull();
assertThat( program.getWorkspaceManager() ).withFailMessage( "Workspace manager is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace() ).withFailMessage( "Active workspace is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() ).withFailMessage( "Active workarea is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane() ).withFailMessage( "Active workpane is null" ).isNotNull();
Workpane workpane = program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane();
workpane.addEventHandler( WorkpaneEvent.ANY, workpaneWatcher = new FxEventWatcher() );
initialMemoryUse = getMemoryUse();
} | DESIGN | true | program.register( ProgramEvent.ANY, programWatcher = new EventWatcher( TIMEOUT ) );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
programWatcher.waitForEvent( ProgramEvent.STARTED, TIMEOUT ); | Path programDataFolder = OperatingSystem.getUserProgramDataFolder( metadata.getArtifact() + suffix, metadata.getName() + suffix );
assertThat( aggressiveDelete( programDataFolder ) ).withFailMessage( "Failed to delete program data folder" ).isTrue();
// For the parameters to be available using Java 9, the following needs to be added
// to the test JVM command line parameters because com.sun.javafx.application.ParametersImpl
// is not exposed, nor is there a "proper" way to access it:
//
// --add-opens=javafx.graphics/com.sun.javafx.application=ALL-UNNAMED
program = (Program)FxToolkit.setupApplication( Program.class, ProgramTestConfig.getParameterValues() );
program.register( ProgramEvent.ANY, programWatcher = new EventWatcher( TIMEOUT ) );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
programWatcher.waitForEvent( ProgramEvent.STARTED, TIMEOUT );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
// Wait for the active workarea
// FIXME This should use an event listener to wait for the workarea
long limit = System.currentTimeMillis() + TIMEOUT;
while( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() == null && System.currentTimeMillis() < limit ) {
ThreadUtil.pause( 100 ); | @BeforeEach
protected void setup() throws Exception {
// Remove the existing program data folder
String suffix = "-" + Profile.TEST;
ProductCard metadata = ProductCard.info( Program.class );
Path programDataFolder = OperatingSystem.getUserProgramDataFolder( metadata.getArtifact() + suffix, metadata.getName() + suffix );
assertThat( aggressiveDelete( programDataFolder ) ).withFailMessage( "Failed to delete program data folder" ).isTrue();
// For the parameters to be available using Java 9, the following needs to be added
// to the test JVM command line parameters because com.sun.javafx.application.ParametersImpl
// is not exposed, nor is there a "proper" way to access it:
//
// --add-opens=javafx.graphics/com.sun.javafx.application=ALL-UNNAMED
program = (Program)FxToolkit.setupApplication( Program.class, ProgramTestConfig.getParameterValues() );
program.register( ProgramEvent.ANY, programWatcher = new EventWatcher( TIMEOUT ) );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
programWatcher.waitForEvent( ProgramEvent.STARTED, TIMEOUT );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
// Wait for the active workarea
// FIXME This should use an event listener to wait for the workarea
long limit = System.currentTimeMillis() + TIMEOUT;
while( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() == null && System.currentTimeMillis() < limit ) {
ThreadUtil.pause( 100 );
}
assertThat( program ).withFailMessage( "Program is null" ).isNotNull();
assertThat( program.getWorkspaceManager() ).withFailMessage( "Workspace manager is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace() ).withFailMessage( "Active workspace is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() ).withFailMessage( "Active workarea is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane() ).withFailMessage( "Active workpane is null" ).isNotNull();
Workpane workpane = program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane();
workpane.addEventHandler( WorkpaneEvent.ANY, workpaneWatcher = new FxEventWatcher() );
initialMemoryUse = getMemoryUse();
} |
30,915 | 4 | // NOTE Thread.yield() is helpful but not consistent | @BeforeEach
protected void setup() throws Exception {
// Remove the existing program data folder
String suffix = "-" + Profile.TEST;
ProductCard metadata = ProductCard.info( Program.class );
Path programDataFolder = OperatingSystem.getUserProgramDataFolder( metadata.getArtifact() + suffix, metadata.getName() + suffix );
assertThat( aggressiveDelete( programDataFolder ) ).withFailMessage( "Failed to delete program data folder" ).isTrue();
// For the parameters to be available using Java 9, the following needs to be added
// to the test JVM command line parameters because com.sun.javafx.application.ParametersImpl
// is not exposed, nor is there a "proper" way to access it:
//
// --add-opens=javafx.graphics/com.sun.javafx.application=ALL-UNNAMED
program = (Program)FxToolkit.setupApplication( Program.class, ProgramTestConfig.getParameterValues() );
program.register( ProgramEvent.ANY, programWatcher = new EventWatcher( TIMEOUT ) );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
programWatcher.waitForEvent( ProgramEvent.STARTED, TIMEOUT );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
// Wait for the active workarea
// FIXME This should use an event listener to wait for the workarea
long limit = System.currentTimeMillis() + TIMEOUT;
while( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() == null && System.currentTimeMillis() < limit ) {
ThreadUtil.pause( 100 );
}
assertThat( program ).withFailMessage( "Program is null" ).isNotNull();
assertThat( program.getWorkspaceManager() ).withFailMessage( "Workspace manager is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace() ).withFailMessage( "Active workspace is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() ).withFailMessage( "Active workarea is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane() ).withFailMessage( "Active workpane is null" ).isNotNull();
Workpane workpane = program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane();
workpane.addEventHandler( WorkpaneEvent.ANY, workpaneWatcher = new FxEventWatcher() );
initialMemoryUse = getMemoryUse();
} | DESIGN | true | program.register( ProgramEvent.ANY, programWatcher = new EventWatcher( TIMEOUT ) );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
programWatcher.waitForEvent( ProgramEvent.STARTED, TIMEOUT ); | Path programDataFolder = OperatingSystem.getUserProgramDataFolder( metadata.getArtifact() + suffix, metadata.getName() + suffix );
assertThat( aggressiveDelete( programDataFolder ) ).withFailMessage( "Failed to delete program data folder" ).isTrue();
// For the parameters to be available using Java 9, the following needs to be added
// to the test JVM command line parameters because com.sun.javafx.application.ParametersImpl
// is not exposed, nor is there a "proper" way to access it:
//
// --add-opens=javafx.graphics/com.sun.javafx.application=ALL-UNNAMED
program = (Program)FxToolkit.setupApplication( Program.class, ProgramTestConfig.getParameterValues() );
program.register( ProgramEvent.ANY, programWatcher = new EventWatcher( TIMEOUT ) );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
programWatcher.waitForEvent( ProgramEvent.STARTED, TIMEOUT );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
// Wait for the active workarea
// FIXME This should use an event listener to wait for the workarea
long limit = System.currentTimeMillis() + TIMEOUT;
while( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() == null && System.currentTimeMillis() < limit ) {
ThreadUtil.pause( 100 ); | @BeforeEach
protected void setup() throws Exception {
// Remove the existing program data folder
String suffix = "-" + Profile.TEST;
ProductCard metadata = ProductCard.info( Program.class );
Path programDataFolder = OperatingSystem.getUserProgramDataFolder( metadata.getArtifact() + suffix, metadata.getName() + suffix );
assertThat( aggressiveDelete( programDataFolder ) ).withFailMessage( "Failed to delete program data folder" ).isTrue();
// For the parameters to be available using Java 9, the following needs to be added
// to the test JVM command line parameters because com.sun.javafx.application.ParametersImpl
// is not exposed, nor is there a "proper" way to access it:
//
// --add-opens=javafx.graphics/com.sun.javafx.application=ALL-UNNAMED
program = (Program)FxToolkit.setupApplication( Program.class, ProgramTestConfig.getParameterValues() );
program.register( ProgramEvent.ANY, programWatcher = new EventWatcher( TIMEOUT ) );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
programWatcher.waitForEvent( ProgramEvent.STARTED, TIMEOUT );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
// Wait for the active workarea
// FIXME This should use an event listener to wait for the workarea
long limit = System.currentTimeMillis() + TIMEOUT;
while( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() == null && System.currentTimeMillis() < limit ) {
ThreadUtil.pause( 100 );
}
assertThat( program ).withFailMessage( "Program is null" ).isNotNull();
assertThat( program.getWorkspaceManager() ).withFailMessage( "Workspace manager is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace() ).withFailMessage( "Active workspace is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() ).withFailMessage( "Active workarea is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane() ).withFailMessage( "Active workpane is null" ).isNotNull();
Workpane workpane = program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane();
workpane.addEventHandler( WorkpaneEvent.ANY, workpaneWatcher = new FxEventWatcher() );
initialMemoryUse = getMemoryUse();
} |
30,915 | 5 | // Wait for the active workarea
// FIXME This should use an event listener to wait for the workarea | @BeforeEach
protected void setup() throws Exception {
// Remove the existing program data folder
String suffix = "-" + Profile.TEST;
ProductCard metadata = ProductCard.info( Program.class );
Path programDataFolder = OperatingSystem.getUserProgramDataFolder( metadata.getArtifact() + suffix, metadata.getName() + suffix );
assertThat( aggressiveDelete( programDataFolder ) ).withFailMessage( "Failed to delete program data folder" ).isTrue();
// For the parameters to be available using Java 9, the following needs to be added
// to the test JVM command line parameters because com.sun.javafx.application.ParametersImpl
// is not exposed, nor is there a "proper" way to access it:
//
// --add-opens=javafx.graphics/com.sun.javafx.application=ALL-UNNAMED
program = (Program)FxToolkit.setupApplication( Program.class, ProgramTestConfig.getParameterValues() );
program.register( ProgramEvent.ANY, programWatcher = new EventWatcher( TIMEOUT ) );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
programWatcher.waitForEvent( ProgramEvent.STARTED, TIMEOUT );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
// Wait for the active workarea
// FIXME This should use an event listener to wait for the workarea
long limit = System.currentTimeMillis() + TIMEOUT;
while( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() == null && System.currentTimeMillis() < limit ) {
ThreadUtil.pause( 100 );
}
assertThat( program ).withFailMessage( "Program is null" ).isNotNull();
assertThat( program.getWorkspaceManager() ).withFailMessage( "Workspace manager is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace() ).withFailMessage( "Active workspace is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() ).withFailMessage( "Active workarea is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane() ).withFailMessage( "Active workpane is null" ).isNotNull();
Workpane workpane = program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane();
workpane.addEventHandler( WorkpaneEvent.ANY, workpaneWatcher = new FxEventWatcher() );
initialMemoryUse = getMemoryUse();
} | DESIGN | true | // NOTE Thread.yield() is helpful but not consistent
Thread.yield();
// Wait for the active workarea
// FIXME This should use an event listener to wait for the workarea
long limit = System.currentTimeMillis() + TIMEOUT;
while( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() == null && System.currentTimeMillis() < limit ) { | // --add-opens=javafx.graphics/com.sun.javafx.application=ALL-UNNAMED
program = (Program)FxToolkit.setupApplication( Program.class, ProgramTestConfig.getParameterValues() );
program.register( ProgramEvent.ANY, programWatcher = new EventWatcher( TIMEOUT ) );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
programWatcher.waitForEvent( ProgramEvent.STARTED, TIMEOUT );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
// Wait for the active workarea
// FIXME This should use an event listener to wait for the workarea
long limit = System.currentTimeMillis() + TIMEOUT;
while( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() == null && System.currentTimeMillis() < limit ) {
ThreadUtil.pause( 100 );
}
assertThat( program ).withFailMessage( "Program is null" ).isNotNull();
assertThat( program.getWorkspaceManager() ).withFailMessage( "Workspace manager is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace() ).withFailMessage( "Active workspace is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() ).withFailMessage( "Active workarea is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane() ).withFailMessage( "Active workpane is null" ).isNotNull();
Workpane workpane = program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane(); | protected void setup() throws Exception {
// Remove the existing program data folder
String suffix = "-" + Profile.TEST;
ProductCard metadata = ProductCard.info( Program.class );
Path programDataFolder = OperatingSystem.getUserProgramDataFolder( metadata.getArtifact() + suffix, metadata.getName() + suffix );
assertThat( aggressiveDelete( programDataFolder ) ).withFailMessage( "Failed to delete program data folder" ).isTrue();
// For the parameters to be available using Java 9, the following needs to be added
// to the test JVM command line parameters because com.sun.javafx.application.ParametersImpl
// is not exposed, nor is there a "proper" way to access it:
//
// --add-opens=javafx.graphics/com.sun.javafx.application=ALL-UNNAMED
program = (Program)FxToolkit.setupApplication( Program.class, ProgramTestConfig.getParameterValues() );
program.register( ProgramEvent.ANY, programWatcher = new EventWatcher( TIMEOUT ) );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
programWatcher.waitForEvent( ProgramEvent.STARTED, TIMEOUT );
Fx.waitForWithExceptions( TIMEOUT );
// NOTE Thread.yield() is helpful but not consistent
Thread.yield();
// Wait for the active workarea
// FIXME This should use an event listener to wait for the workarea
long limit = System.currentTimeMillis() + TIMEOUT;
while( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() == null && System.currentTimeMillis() < limit ) {
ThreadUtil.pause( 100 );
}
assertThat( program ).withFailMessage( "Program is null" ).isNotNull();
assertThat( program.getWorkspaceManager() ).withFailMessage( "Workspace manager is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace() ).withFailMessage( "Active workspace is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea() ).withFailMessage( "Active workarea is null" ).isNotNull();
assertThat( program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane() ).withFailMessage( "Active workpane is null" ).isNotNull();
Workpane workpane = program.getWorkspaceManager().getActiveWorkspace().getActiveWorkarea().getWorkpane();
workpane.addEventHandler( WorkpaneEvent.ANY, workpaneWatcher = new FxEventWatcher() );
initialMemoryUse = getMemoryUse();
} |
14,534 | 0 | // TODO: handle pinProtocol != 1 somehow | public RawMessage handleCborRequest(ChannelId channelId, byte[] payload) {
if (payload.length == 0) {
return RawMessage.error(channelId, HidError.INVALID_LEN);
}
Ctap2Method method = Ctap2Method.from(payload[0]);
byte[] params = new byte[payload.length - 1];
System.arraycopy(payload, 1, params, 0, payload.length - 1);
try {
log.debug("Received CBOR request with method {} and body {}", method, CborDecoder.decode(params));
} catch (CborException e) {
log.error("Unable to deserialize CBOR parameters", e);
return failure(channelId, Ctap2ResponseCode.INVALID_CBOR);
}
try {
switch (method) {
case GET_ASSERTION:
GetAssertionRequest gar = GetAssertionRequest.fromBytes(params);
byte[] assertion = authenticator.getAssertion(gar)
.handleError(err -> asPayload(err, Collections.emptyList()))
.elseGet(value -> asPayload(Ctap2ResponseCode.OK, value.asCborMap()));
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(assertion)
.build();
case GET_INFO:
GetInfoResponse response = authenticator.getInfo();
log.trace("Authenticator supports options {}", response);
byte[] info = asPayload(Ctap2ResponseCode.OK, response.asCborMap());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(info)
.build();
case MAKE_CREDENTIAL:
MakeCredentialRequest request = MakeCredentialRequest.fromBytes(params);
Result<MakeCredentialResponse, Ctap2ResponseCode> result = authenticator.makeCredential(request.clientDataHash(),
request.relayingPartyId(), request.userId(), request.supportedAlgorithmIds(), request.pinAuth());
byte[] credential = result
.handleError(err -> asPayload(err, Collections.emptyList()))
.elseGet(value -> asPayload(Ctap2ResponseCode.OK, value.asCborMap()));
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(credential)
.build();
case CLIENT_PIN:
Map pinParams = (Map) CborDecoder.decode(params).get(0);
UnsignedInteger pinProtocol = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x01));
// TODO: handle pinProtocol != 1 somehow
UnsignedInteger subCommand = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x02));
switch(subCommand.getValue().intValue()) {
case 0x01: // get retries
List<DataItem> retries = pinRequestHandler.getRetries();
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, retries))
.build();
case 0x02: // get key
List<DataItem> key = pinRequestHandler.getKeyAgreementKey();
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, key))
.build();
case 0x03: // set pin
Map hostCoseKey = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc = (ByteString) pinParams.get(new UnsignedInteger(0x05));
Ctap2ResponseCode code = pinRequestHandler.setPin(hostCoseKey, newPinEnc.getBytes(), pinAuth.getBytes());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(code, Collections.emptyList()))
.build();
case 0x04: // change pin
Map hostCoseKey2 = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth2 = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc2 = (ByteString) pinParams.get(new UnsignedInteger(0x05));
ByteString PinHashEnc = (ByteString) pinParams.get(new UnsignedInteger(0x06));
Ctap2ResponseCode code2 = pinRequestHandler.changePin(hostCoseKey2, PinHashEnc.getBytes(), newPinEnc2.getBytes(), pinAuth2.getBytes());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(code2, Collections.emptyList()))
.build();
case 0x05: // get pin token
Map hostCoseKey3 = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinHashEnc2 = (ByteString) pinParams.get(new UnsignedInteger(0x06));
Result<List<DataItem>, Ctap2ResponseCode> pinToken = pinRequestHandler.getPinToken(hostCoseKey3, pinHashEnc2.getBytes());
byte[] pinTokenPayload = pinToken.handleError(err -> asPayload(err, Collections.emptyList()))
.elseGet(val -> asPayload(Ctap2ResponseCode.OK, val));
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(pinTokenPayload)
.build();
}
break;
case RESET:
case GET_NEXT_ASSERTION:
default:
return RawMessage.error(channelId, HidError.INVALID_CMD);
}
} catch (CborException e) {
log.error("Unable to deserialize CBOR", e);
}
return failure(channelId, Ctap2ResponseCode.INVALID_CBOR);
} | DESIGN | true | Map pinParams = (Map) CborDecoder.decode(params).get(0);
UnsignedInteger pinProtocol = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x01));
// TODO: handle pinProtocol != 1 somehow
UnsignedInteger subCommand = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x02));
switch(subCommand.getValue().intValue()) { | .handleError(err -> asPayload(err, Collections.emptyList()))
.elseGet(value -> asPayload(Ctap2ResponseCode.OK, value.asCborMap()));
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(credential)
.build();
case CLIENT_PIN:
Map pinParams = (Map) CborDecoder.decode(params).get(0);
UnsignedInteger pinProtocol = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x01));
// TODO: handle pinProtocol != 1 somehow
UnsignedInteger subCommand = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x02));
switch(subCommand.getValue().intValue()) {
case 0x01: // get retries
List<DataItem> retries = pinRequestHandler.getRetries();
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, retries))
.build();
case 0x02: // get key | return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(info)
.build();
case MAKE_CREDENTIAL:
MakeCredentialRequest request = MakeCredentialRequest.fromBytes(params);
Result<MakeCredentialResponse, Ctap2ResponseCode> result = authenticator.makeCredential(request.clientDataHash(),
request.relayingPartyId(), request.userId(), request.supportedAlgorithmIds(), request.pinAuth());
byte[] credential = result
.handleError(err -> asPayload(err, Collections.emptyList()))
.elseGet(value -> asPayload(Ctap2ResponseCode.OK, value.asCborMap()));
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(credential)
.build();
case CLIENT_PIN:
Map pinParams = (Map) CborDecoder.decode(params).get(0);
UnsignedInteger pinProtocol = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x01));
// TODO: handle pinProtocol != 1 somehow
UnsignedInteger subCommand = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x02));
switch(subCommand.getValue().intValue()) {
case 0x01: // get retries
List<DataItem> retries = pinRequestHandler.getRetries();
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, retries))
.build();
case 0x02: // get key
List<DataItem> key = pinRequestHandler.getKeyAgreementKey();
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, key))
.build();
case 0x03: // set pin
Map hostCoseKey = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc = (ByteString) pinParams.get(new UnsignedInteger(0x05)); |
14,534 | 1 | // get retries | public RawMessage handleCborRequest(ChannelId channelId, byte[] payload) {
if (payload.length == 0) {
return RawMessage.error(channelId, HidError.INVALID_LEN);
}
Ctap2Method method = Ctap2Method.from(payload[0]);
byte[] params = new byte[payload.length - 1];
System.arraycopy(payload, 1, params, 0, payload.length - 1);
try {
log.debug("Received CBOR request with method {} and body {}", method, CborDecoder.decode(params));
} catch (CborException e) {
log.error("Unable to deserialize CBOR parameters", e);
return failure(channelId, Ctap2ResponseCode.INVALID_CBOR);
}
try {
switch (method) {
case GET_ASSERTION:
GetAssertionRequest gar = GetAssertionRequest.fromBytes(params);
byte[] assertion = authenticator.getAssertion(gar)
.handleError(err -> asPayload(err, Collections.emptyList()))
.elseGet(value -> asPayload(Ctap2ResponseCode.OK, value.asCborMap()));
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(assertion)
.build();
case GET_INFO:
GetInfoResponse response = authenticator.getInfo();
log.trace("Authenticator supports options {}", response);
byte[] info = asPayload(Ctap2ResponseCode.OK, response.asCborMap());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(info)
.build();
case MAKE_CREDENTIAL:
MakeCredentialRequest request = MakeCredentialRequest.fromBytes(params);
Result<MakeCredentialResponse, Ctap2ResponseCode> result = authenticator.makeCredential(request.clientDataHash(),
request.relayingPartyId(), request.userId(), request.supportedAlgorithmIds(), request.pinAuth());
byte[] credential = result
.handleError(err -> asPayload(err, Collections.emptyList()))
.elseGet(value -> asPayload(Ctap2ResponseCode.OK, value.asCborMap()));
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(credential)
.build();
case CLIENT_PIN:
Map pinParams = (Map) CborDecoder.decode(params).get(0);
UnsignedInteger pinProtocol = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x01));
// TODO: handle pinProtocol != 1 somehow
UnsignedInteger subCommand = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x02));
switch(subCommand.getValue().intValue()) {
case 0x01: // get retries
List<DataItem> retries = pinRequestHandler.getRetries();
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, retries))
.build();
case 0x02: // get key
List<DataItem> key = pinRequestHandler.getKeyAgreementKey();
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, key))
.build();
case 0x03: // set pin
Map hostCoseKey = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc = (ByteString) pinParams.get(new UnsignedInteger(0x05));
Ctap2ResponseCode code = pinRequestHandler.setPin(hostCoseKey, newPinEnc.getBytes(), pinAuth.getBytes());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(code, Collections.emptyList()))
.build();
case 0x04: // change pin
Map hostCoseKey2 = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth2 = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc2 = (ByteString) pinParams.get(new UnsignedInteger(0x05));
ByteString PinHashEnc = (ByteString) pinParams.get(new UnsignedInteger(0x06));
Ctap2ResponseCode code2 = pinRequestHandler.changePin(hostCoseKey2, PinHashEnc.getBytes(), newPinEnc2.getBytes(), pinAuth2.getBytes());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(code2, Collections.emptyList()))
.build();
case 0x05: // get pin token
Map hostCoseKey3 = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinHashEnc2 = (ByteString) pinParams.get(new UnsignedInteger(0x06));
Result<List<DataItem>, Ctap2ResponseCode> pinToken = pinRequestHandler.getPinToken(hostCoseKey3, pinHashEnc2.getBytes());
byte[] pinTokenPayload = pinToken.handleError(err -> asPayload(err, Collections.emptyList()))
.elseGet(val -> asPayload(Ctap2ResponseCode.OK, val));
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(pinTokenPayload)
.build();
}
break;
case RESET:
case GET_NEXT_ASSERTION:
default:
return RawMessage.error(channelId, HidError.INVALID_CMD);
}
} catch (CborException e) {
log.error("Unable to deserialize CBOR", e);
}
return failure(channelId, Ctap2ResponseCode.INVALID_CBOR);
} | NONSATD | true | UnsignedInteger subCommand = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x02));
switch(subCommand.getValue().intValue()) {
case 0x01: // get retries
List<DataItem> retries = pinRequestHandler.getRetries();
return ImmutableRawMessage.builder() | .channelId(channelId)
.command(HidCommand.CBOR)
.payload(credential)
.build();
case CLIENT_PIN:
Map pinParams = (Map) CborDecoder.decode(params).get(0);
UnsignedInteger pinProtocol = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x01));
// TODO: handle pinProtocol != 1 somehow
UnsignedInteger subCommand = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x02));
switch(subCommand.getValue().intValue()) {
case 0x01: // get retries
List<DataItem> retries = pinRequestHandler.getRetries();
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, retries))
.build();
case 0x02: // get key
List<DataItem> key = pinRequestHandler.getKeyAgreementKey();
return ImmutableRawMessage.builder()
.channelId(channelId) | .payload(info)
.build();
case MAKE_CREDENTIAL:
MakeCredentialRequest request = MakeCredentialRequest.fromBytes(params);
Result<MakeCredentialResponse, Ctap2ResponseCode> result = authenticator.makeCredential(request.clientDataHash(),
request.relayingPartyId(), request.userId(), request.supportedAlgorithmIds(), request.pinAuth());
byte[] credential = result
.handleError(err -> asPayload(err, Collections.emptyList()))
.elseGet(value -> asPayload(Ctap2ResponseCode.OK, value.asCborMap()));
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(credential)
.build();
case CLIENT_PIN:
Map pinParams = (Map) CborDecoder.decode(params).get(0);
UnsignedInteger pinProtocol = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x01));
// TODO: handle pinProtocol != 1 somehow
UnsignedInteger subCommand = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x02));
switch(subCommand.getValue().intValue()) {
case 0x01: // get retries
List<DataItem> retries = pinRequestHandler.getRetries();
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, retries))
.build();
case 0x02: // get key
List<DataItem> key = pinRequestHandler.getKeyAgreementKey();
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, key))
.build();
case 0x03: // set pin
Map hostCoseKey = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc = (ByteString) pinParams.get(new UnsignedInteger(0x05));
Ctap2ResponseCode code = pinRequestHandler.setPin(hostCoseKey, newPinEnc.getBytes(), pinAuth.getBytes());
return ImmutableRawMessage.builder()
.channelId(channelId) |
14,534 | 2 | // get key | public RawMessage handleCborRequest(ChannelId channelId, byte[] payload) {
if (payload.length == 0) {
return RawMessage.error(channelId, HidError.INVALID_LEN);
}
Ctap2Method method = Ctap2Method.from(payload[0]);
byte[] params = new byte[payload.length - 1];
System.arraycopy(payload, 1, params, 0, payload.length - 1);
try {
log.debug("Received CBOR request with method {} and body {}", method, CborDecoder.decode(params));
} catch (CborException e) {
log.error("Unable to deserialize CBOR parameters", e);
return failure(channelId, Ctap2ResponseCode.INVALID_CBOR);
}
try {
switch (method) {
case GET_ASSERTION:
GetAssertionRequest gar = GetAssertionRequest.fromBytes(params);
byte[] assertion = authenticator.getAssertion(gar)
.handleError(err -> asPayload(err, Collections.emptyList()))
.elseGet(value -> asPayload(Ctap2ResponseCode.OK, value.asCborMap()));
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(assertion)
.build();
case GET_INFO:
GetInfoResponse response = authenticator.getInfo();
log.trace("Authenticator supports options {}", response);
byte[] info = asPayload(Ctap2ResponseCode.OK, response.asCborMap());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(info)
.build();
case MAKE_CREDENTIAL:
MakeCredentialRequest request = MakeCredentialRequest.fromBytes(params);
Result<MakeCredentialResponse, Ctap2ResponseCode> result = authenticator.makeCredential(request.clientDataHash(),
request.relayingPartyId(), request.userId(), request.supportedAlgorithmIds(), request.pinAuth());
byte[] credential = result
.handleError(err -> asPayload(err, Collections.emptyList()))
.elseGet(value -> asPayload(Ctap2ResponseCode.OK, value.asCborMap()));
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(credential)
.build();
case CLIENT_PIN:
Map pinParams = (Map) CborDecoder.decode(params).get(0);
UnsignedInteger pinProtocol = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x01));
// TODO: handle pinProtocol != 1 somehow
UnsignedInteger subCommand = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x02));
switch(subCommand.getValue().intValue()) {
case 0x01: // get retries
List<DataItem> retries = pinRequestHandler.getRetries();
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, retries))
.build();
case 0x02: // get key
List<DataItem> key = pinRequestHandler.getKeyAgreementKey();
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, key))
.build();
case 0x03: // set pin
Map hostCoseKey = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc = (ByteString) pinParams.get(new UnsignedInteger(0x05));
Ctap2ResponseCode code = pinRequestHandler.setPin(hostCoseKey, newPinEnc.getBytes(), pinAuth.getBytes());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(code, Collections.emptyList()))
.build();
case 0x04: // change pin
Map hostCoseKey2 = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth2 = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc2 = (ByteString) pinParams.get(new UnsignedInteger(0x05));
ByteString PinHashEnc = (ByteString) pinParams.get(new UnsignedInteger(0x06));
Ctap2ResponseCode code2 = pinRequestHandler.changePin(hostCoseKey2, PinHashEnc.getBytes(), newPinEnc2.getBytes(), pinAuth2.getBytes());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(code2, Collections.emptyList()))
.build();
case 0x05: // get pin token
Map hostCoseKey3 = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinHashEnc2 = (ByteString) pinParams.get(new UnsignedInteger(0x06));
Result<List<DataItem>, Ctap2ResponseCode> pinToken = pinRequestHandler.getPinToken(hostCoseKey3, pinHashEnc2.getBytes());
byte[] pinTokenPayload = pinToken.handleError(err -> asPayload(err, Collections.emptyList()))
.elseGet(val -> asPayload(Ctap2ResponseCode.OK, val));
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(pinTokenPayload)
.build();
}
break;
case RESET:
case GET_NEXT_ASSERTION:
default:
return RawMessage.error(channelId, HidError.INVALID_CMD);
}
} catch (CborException e) {
log.error("Unable to deserialize CBOR", e);
}
return failure(channelId, Ctap2ResponseCode.INVALID_CBOR);
} | NONSATD | true | .payload(asPayload(Ctap2ResponseCode.OK, retries))
.build();
case 0x02: // get key
List<DataItem> key = pinRequestHandler.getKeyAgreementKey();
return ImmutableRawMessage.builder() | // TODO: handle pinProtocol != 1 somehow
UnsignedInteger subCommand = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x02));
switch(subCommand.getValue().intValue()) {
case 0x01: // get retries
List<DataItem> retries = pinRequestHandler.getRetries();
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, retries))
.build();
case 0x02: // get key
List<DataItem> key = pinRequestHandler.getKeyAgreementKey();
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, key))
.build();
case 0x03: // set pin
Map hostCoseKey = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc = (ByteString) pinParams.get(new UnsignedInteger(0x05)); | .handleError(err -> asPayload(err, Collections.emptyList()))
.elseGet(value -> asPayload(Ctap2ResponseCode.OK, value.asCborMap()));
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(credential)
.build();
case CLIENT_PIN:
Map pinParams = (Map) CborDecoder.decode(params).get(0);
UnsignedInteger pinProtocol = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x01));
// TODO: handle pinProtocol != 1 somehow
UnsignedInteger subCommand = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x02));
switch(subCommand.getValue().intValue()) {
case 0x01: // get retries
List<DataItem> retries = pinRequestHandler.getRetries();
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, retries))
.build();
case 0x02: // get key
List<DataItem> key = pinRequestHandler.getKeyAgreementKey();
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, key))
.build();
case 0x03: // set pin
Map hostCoseKey = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc = (ByteString) pinParams.get(new UnsignedInteger(0x05));
Ctap2ResponseCode code = pinRequestHandler.setPin(hostCoseKey, newPinEnc.getBytes(), pinAuth.getBytes());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(code, Collections.emptyList()))
.build();
case 0x04: // change pin
Map hostCoseKey2 = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth2 = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc2 = (ByteString) pinParams.get(new UnsignedInteger(0x05)); |
14,534 | 3 | // set pin | public RawMessage handleCborRequest(ChannelId channelId, byte[] payload) {
if (payload.length == 0) {
return RawMessage.error(channelId, HidError.INVALID_LEN);
}
Ctap2Method method = Ctap2Method.from(payload[0]);
byte[] params = new byte[payload.length - 1];
System.arraycopy(payload, 1, params, 0, payload.length - 1);
try {
log.debug("Received CBOR request with method {} and body {}", method, CborDecoder.decode(params));
} catch (CborException e) {
log.error("Unable to deserialize CBOR parameters", e);
return failure(channelId, Ctap2ResponseCode.INVALID_CBOR);
}
try {
switch (method) {
case GET_ASSERTION:
GetAssertionRequest gar = GetAssertionRequest.fromBytes(params);
byte[] assertion = authenticator.getAssertion(gar)
.handleError(err -> asPayload(err, Collections.emptyList()))
.elseGet(value -> asPayload(Ctap2ResponseCode.OK, value.asCborMap()));
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(assertion)
.build();
case GET_INFO:
GetInfoResponse response = authenticator.getInfo();
log.trace("Authenticator supports options {}", response);
byte[] info = asPayload(Ctap2ResponseCode.OK, response.asCborMap());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(info)
.build();
case MAKE_CREDENTIAL:
MakeCredentialRequest request = MakeCredentialRequest.fromBytes(params);
Result<MakeCredentialResponse, Ctap2ResponseCode> result = authenticator.makeCredential(request.clientDataHash(),
request.relayingPartyId(), request.userId(), request.supportedAlgorithmIds(), request.pinAuth());
byte[] credential = result
.handleError(err -> asPayload(err, Collections.emptyList()))
.elseGet(value -> asPayload(Ctap2ResponseCode.OK, value.asCborMap()));
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(credential)
.build();
case CLIENT_PIN:
Map pinParams = (Map) CborDecoder.decode(params).get(0);
UnsignedInteger pinProtocol = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x01));
// TODO: handle pinProtocol != 1 somehow
UnsignedInteger subCommand = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x02));
switch(subCommand.getValue().intValue()) {
case 0x01: // get retries
List<DataItem> retries = pinRequestHandler.getRetries();
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, retries))
.build();
case 0x02: // get key
List<DataItem> key = pinRequestHandler.getKeyAgreementKey();
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, key))
.build();
case 0x03: // set pin
Map hostCoseKey = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc = (ByteString) pinParams.get(new UnsignedInteger(0x05));
Ctap2ResponseCode code = pinRequestHandler.setPin(hostCoseKey, newPinEnc.getBytes(), pinAuth.getBytes());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(code, Collections.emptyList()))
.build();
case 0x04: // change pin
Map hostCoseKey2 = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth2 = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc2 = (ByteString) pinParams.get(new UnsignedInteger(0x05));
ByteString PinHashEnc = (ByteString) pinParams.get(new UnsignedInteger(0x06));
Ctap2ResponseCode code2 = pinRequestHandler.changePin(hostCoseKey2, PinHashEnc.getBytes(), newPinEnc2.getBytes(), pinAuth2.getBytes());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(code2, Collections.emptyList()))
.build();
case 0x05: // get pin token
Map hostCoseKey3 = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinHashEnc2 = (ByteString) pinParams.get(new UnsignedInteger(0x06));
Result<List<DataItem>, Ctap2ResponseCode> pinToken = pinRequestHandler.getPinToken(hostCoseKey3, pinHashEnc2.getBytes());
byte[] pinTokenPayload = pinToken.handleError(err -> asPayload(err, Collections.emptyList()))
.elseGet(val -> asPayload(Ctap2ResponseCode.OK, val));
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(pinTokenPayload)
.build();
}
break;
case RESET:
case GET_NEXT_ASSERTION:
default:
return RawMessage.error(channelId, HidError.INVALID_CMD);
}
} catch (CborException e) {
log.error("Unable to deserialize CBOR", e);
}
return failure(channelId, Ctap2ResponseCode.INVALID_CBOR);
} | NONSATD | true | .payload(asPayload(Ctap2ResponseCode.OK, key))
.build();
case 0x03: // set pin
Map hostCoseKey = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth = (ByteString) pinParams.get(new UnsignedInteger(0x04)); | .command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, retries))
.build();
case 0x02: // get key
List<DataItem> key = pinRequestHandler.getKeyAgreementKey();
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, key))
.build();
case 0x03: // set pin
Map hostCoseKey = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc = (ByteString) pinParams.get(new UnsignedInteger(0x05));
Ctap2ResponseCode code = pinRequestHandler.setPin(hostCoseKey, newPinEnc.getBytes(), pinAuth.getBytes());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(code, Collections.emptyList()))
.build();
case 0x04: // change pin | case CLIENT_PIN:
Map pinParams = (Map) CborDecoder.decode(params).get(0);
UnsignedInteger pinProtocol = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x01));
// TODO: handle pinProtocol != 1 somehow
UnsignedInteger subCommand = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x02));
switch(subCommand.getValue().intValue()) {
case 0x01: // get retries
List<DataItem> retries = pinRequestHandler.getRetries();
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, retries))
.build();
case 0x02: // get key
List<DataItem> key = pinRequestHandler.getKeyAgreementKey();
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, key))
.build();
case 0x03: // set pin
Map hostCoseKey = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc = (ByteString) pinParams.get(new UnsignedInteger(0x05));
Ctap2ResponseCode code = pinRequestHandler.setPin(hostCoseKey, newPinEnc.getBytes(), pinAuth.getBytes());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(code, Collections.emptyList()))
.build();
case 0x04: // change pin
Map hostCoseKey2 = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth2 = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc2 = (ByteString) pinParams.get(new UnsignedInteger(0x05));
ByteString PinHashEnc = (ByteString) pinParams.get(new UnsignedInteger(0x06));
Ctap2ResponseCode code2 = pinRequestHandler.changePin(hostCoseKey2, PinHashEnc.getBytes(), newPinEnc2.getBytes(), pinAuth2.getBytes());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(code2, Collections.emptyList()))
.build(); |
14,534 | 4 | // change pin | public RawMessage handleCborRequest(ChannelId channelId, byte[] payload) {
if (payload.length == 0) {
return RawMessage.error(channelId, HidError.INVALID_LEN);
}
Ctap2Method method = Ctap2Method.from(payload[0]);
byte[] params = new byte[payload.length - 1];
System.arraycopy(payload, 1, params, 0, payload.length - 1);
try {
log.debug("Received CBOR request with method {} and body {}", method, CborDecoder.decode(params));
} catch (CborException e) {
log.error("Unable to deserialize CBOR parameters", e);
return failure(channelId, Ctap2ResponseCode.INVALID_CBOR);
}
try {
switch (method) {
case GET_ASSERTION:
GetAssertionRequest gar = GetAssertionRequest.fromBytes(params);
byte[] assertion = authenticator.getAssertion(gar)
.handleError(err -> asPayload(err, Collections.emptyList()))
.elseGet(value -> asPayload(Ctap2ResponseCode.OK, value.asCborMap()));
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(assertion)
.build();
case GET_INFO:
GetInfoResponse response = authenticator.getInfo();
log.trace("Authenticator supports options {}", response);
byte[] info = asPayload(Ctap2ResponseCode.OK, response.asCborMap());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(info)
.build();
case MAKE_CREDENTIAL:
MakeCredentialRequest request = MakeCredentialRequest.fromBytes(params);
Result<MakeCredentialResponse, Ctap2ResponseCode> result = authenticator.makeCredential(request.clientDataHash(),
request.relayingPartyId(), request.userId(), request.supportedAlgorithmIds(), request.pinAuth());
byte[] credential = result
.handleError(err -> asPayload(err, Collections.emptyList()))
.elseGet(value -> asPayload(Ctap2ResponseCode.OK, value.asCborMap()));
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(credential)
.build();
case CLIENT_PIN:
Map pinParams = (Map) CborDecoder.decode(params).get(0);
UnsignedInteger pinProtocol = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x01));
// TODO: handle pinProtocol != 1 somehow
UnsignedInteger subCommand = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x02));
switch(subCommand.getValue().intValue()) {
case 0x01: // get retries
List<DataItem> retries = pinRequestHandler.getRetries();
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, retries))
.build();
case 0x02: // get key
List<DataItem> key = pinRequestHandler.getKeyAgreementKey();
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, key))
.build();
case 0x03: // set pin
Map hostCoseKey = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc = (ByteString) pinParams.get(new UnsignedInteger(0x05));
Ctap2ResponseCode code = pinRequestHandler.setPin(hostCoseKey, newPinEnc.getBytes(), pinAuth.getBytes());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(code, Collections.emptyList()))
.build();
case 0x04: // change pin
Map hostCoseKey2 = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth2 = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc2 = (ByteString) pinParams.get(new UnsignedInteger(0x05));
ByteString PinHashEnc = (ByteString) pinParams.get(new UnsignedInteger(0x06));
Ctap2ResponseCode code2 = pinRequestHandler.changePin(hostCoseKey2, PinHashEnc.getBytes(), newPinEnc2.getBytes(), pinAuth2.getBytes());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(code2, Collections.emptyList()))
.build();
case 0x05: // get pin token
Map hostCoseKey3 = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinHashEnc2 = (ByteString) pinParams.get(new UnsignedInteger(0x06));
Result<List<DataItem>, Ctap2ResponseCode> pinToken = pinRequestHandler.getPinToken(hostCoseKey3, pinHashEnc2.getBytes());
byte[] pinTokenPayload = pinToken.handleError(err -> asPayload(err, Collections.emptyList()))
.elseGet(val -> asPayload(Ctap2ResponseCode.OK, val));
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(pinTokenPayload)
.build();
}
break;
case RESET:
case GET_NEXT_ASSERTION:
default:
return RawMessage.error(channelId, HidError.INVALID_CMD);
}
} catch (CborException e) {
log.error("Unable to deserialize CBOR", e);
}
return failure(channelId, Ctap2ResponseCode.INVALID_CBOR);
} | NONSATD | true | .payload(asPayload(code, Collections.emptyList()))
.build();
case 0x04: // change pin
Map hostCoseKey2 = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth2 = (ByteString) pinParams.get(new UnsignedInteger(0x04)); | case 0x03: // set pin
Map hostCoseKey = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc = (ByteString) pinParams.get(new UnsignedInteger(0x05));
Ctap2ResponseCode code = pinRequestHandler.setPin(hostCoseKey, newPinEnc.getBytes(), pinAuth.getBytes());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(code, Collections.emptyList()))
.build();
case 0x04: // change pin
Map hostCoseKey2 = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth2 = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc2 = (ByteString) pinParams.get(new UnsignedInteger(0x05));
ByteString PinHashEnc = (ByteString) pinParams.get(new UnsignedInteger(0x06));
Ctap2ResponseCode code2 = pinRequestHandler.changePin(hostCoseKey2, PinHashEnc.getBytes(), newPinEnc2.getBytes(), pinAuth2.getBytes());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(code2, Collections.emptyList()))
.build(); | .command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, retries))
.build();
case 0x02: // get key
List<DataItem> key = pinRequestHandler.getKeyAgreementKey();
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, key))
.build();
case 0x03: // set pin
Map hostCoseKey = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc = (ByteString) pinParams.get(new UnsignedInteger(0x05));
Ctap2ResponseCode code = pinRequestHandler.setPin(hostCoseKey, newPinEnc.getBytes(), pinAuth.getBytes());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(code, Collections.emptyList()))
.build();
case 0x04: // change pin
Map hostCoseKey2 = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth2 = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc2 = (ByteString) pinParams.get(new UnsignedInteger(0x05));
ByteString PinHashEnc = (ByteString) pinParams.get(new UnsignedInteger(0x06));
Ctap2ResponseCode code2 = pinRequestHandler.changePin(hostCoseKey2, PinHashEnc.getBytes(), newPinEnc2.getBytes(), pinAuth2.getBytes());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(code2, Collections.emptyList()))
.build();
case 0x05: // get pin token
Map hostCoseKey3 = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinHashEnc2 = (ByteString) pinParams.get(new UnsignedInteger(0x06));
Result<List<DataItem>, Ctap2ResponseCode> pinToken = pinRequestHandler.getPinToken(hostCoseKey3, pinHashEnc2.getBytes());
byte[] pinTokenPayload = pinToken.handleError(err -> asPayload(err, Collections.emptyList()))
.elseGet(val -> asPayload(Ctap2ResponseCode.OK, val));
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(pinTokenPayload) |
14,534 | 5 | // get pin token | public RawMessage handleCborRequest(ChannelId channelId, byte[] payload) {
if (payload.length == 0) {
return RawMessage.error(channelId, HidError.INVALID_LEN);
}
Ctap2Method method = Ctap2Method.from(payload[0]);
byte[] params = new byte[payload.length - 1];
System.arraycopy(payload, 1, params, 0, payload.length - 1);
try {
log.debug("Received CBOR request with method {} and body {}", method, CborDecoder.decode(params));
} catch (CborException e) {
log.error("Unable to deserialize CBOR parameters", e);
return failure(channelId, Ctap2ResponseCode.INVALID_CBOR);
}
try {
switch (method) {
case GET_ASSERTION:
GetAssertionRequest gar = GetAssertionRequest.fromBytes(params);
byte[] assertion = authenticator.getAssertion(gar)
.handleError(err -> asPayload(err, Collections.emptyList()))
.elseGet(value -> asPayload(Ctap2ResponseCode.OK, value.asCborMap()));
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(assertion)
.build();
case GET_INFO:
GetInfoResponse response = authenticator.getInfo();
log.trace("Authenticator supports options {}", response);
byte[] info = asPayload(Ctap2ResponseCode.OK, response.asCborMap());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(info)
.build();
case MAKE_CREDENTIAL:
MakeCredentialRequest request = MakeCredentialRequest.fromBytes(params);
Result<MakeCredentialResponse, Ctap2ResponseCode> result = authenticator.makeCredential(request.clientDataHash(),
request.relayingPartyId(), request.userId(), request.supportedAlgorithmIds(), request.pinAuth());
byte[] credential = result
.handleError(err -> asPayload(err, Collections.emptyList()))
.elseGet(value -> asPayload(Ctap2ResponseCode.OK, value.asCborMap()));
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(credential)
.build();
case CLIENT_PIN:
Map pinParams = (Map) CborDecoder.decode(params).get(0);
UnsignedInteger pinProtocol = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x01));
// TODO: handle pinProtocol != 1 somehow
UnsignedInteger subCommand = (UnsignedInteger) pinParams.get(new UnsignedInteger(0x02));
switch(subCommand.getValue().intValue()) {
case 0x01: // get retries
List<DataItem> retries = pinRequestHandler.getRetries();
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, retries))
.build();
case 0x02: // get key
List<DataItem> key = pinRequestHandler.getKeyAgreementKey();
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(Ctap2ResponseCode.OK, key))
.build();
case 0x03: // set pin
Map hostCoseKey = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc = (ByteString) pinParams.get(new UnsignedInteger(0x05));
Ctap2ResponseCode code = pinRequestHandler.setPin(hostCoseKey, newPinEnc.getBytes(), pinAuth.getBytes());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(code, Collections.emptyList()))
.build();
case 0x04: // change pin
Map hostCoseKey2 = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth2 = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc2 = (ByteString) pinParams.get(new UnsignedInteger(0x05));
ByteString PinHashEnc = (ByteString) pinParams.get(new UnsignedInteger(0x06));
Ctap2ResponseCode code2 = pinRequestHandler.changePin(hostCoseKey2, PinHashEnc.getBytes(), newPinEnc2.getBytes(), pinAuth2.getBytes());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(code2, Collections.emptyList()))
.build();
case 0x05: // get pin token
Map hostCoseKey3 = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinHashEnc2 = (ByteString) pinParams.get(new UnsignedInteger(0x06));
Result<List<DataItem>, Ctap2ResponseCode> pinToken = pinRequestHandler.getPinToken(hostCoseKey3, pinHashEnc2.getBytes());
byte[] pinTokenPayload = pinToken.handleError(err -> asPayload(err, Collections.emptyList()))
.elseGet(val -> asPayload(Ctap2ResponseCode.OK, val));
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(pinTokenPayload)
.build();
}
break;
case RESET:
case GET_NEXT_ASSERTION:
default:
return RawMessage.error(channelId, HidError.INVALID_CMD);
}
} catch (CborException e) {
log.error("Unable to deserialize CBOR", e);
}
return failure(channelId, Ctap2ResponseCode.INVALID_CBOR);
} | NONSATD | true | .payload(asPayload(code2, Collections.emptyList()))
.build();
case 0x05: // get pin token
Map hostCoseKey3 = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinHashEnc2 = (ByteString) pinParams.get(new UnsignedInteger(0x06)); | Map hostCoseKey2 = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth2 = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc2 = (ByteString) pinParams.get(new UnsignedInteger(0x05));
ByteString PinHashEnc = (ByteString) pinParams.get(new UnsignedInteger(0x06));
Ctap2ResponseCode code2 = pinRequestHandler.changePin(hostCoseKey2, PinHashEnc.getBytes(), newPinEnc2.getBytes(), pinAuth2.getBytes());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(code2, Collections.emptyList()))
.build();
case 0x05: // get pin token
Map hostCoseKey3 = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinHashEnc2 = (ByteString) pinParams.get(new UnsignedInteger(0x06));
Result<List<DataItem>, Ctap2ResponseCode> pinToken = pinRequestHandler.getPinToken(hostCoseKey3, pinHashEnc2.getBytes());
byte[] pinTokenPayload = pinToken.handleError(err -> asPayload(err, Collections.emptyList()))
.elseGet(val -> asPayload(Ctap2ResponseCode.OK, val));
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(pinTokenPayload)
.build(); | Map hostCoseKey = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc = (ByteString) pinParams.get(new UnsignedInteger(0x05));
Ctap2ResponseCode code = pinRequestHandler.setPin(hostCoseKey, newPinEnc.getBytes(), pinAuth.getBytes());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(code, Collections.emptyList()))
.build();
case 0x04: // change pin
Map hostCoseKey2 = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinAuth2 = (ByteString) pinParams.get(new UnsignedInteger(0x04));
ByteString newPinEnc2 = (ByteString) pinParams.get(new UnsignedInteger(0x05));
ByteString PinHashEnc = (ByteString) pinParams.get(new UnsignedInteger(0x06));
Ctap2ResponseCode code2 = pinRequestHandler.changePin(hostCoseKey2, PinHashEnc.getBytes(), newPinEnc2.getBytes(), pinAuth2.getBytes());
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(asPayload(code2, Collections.emptyList()))
.build();
case 0x05: // get pin token
Map hostCoseKey3 = (Map) pinParams.get(new UnsignedInteger(0x03));
ByteString pinHashEnc2 = (ByteString) pinParams.get(new UnsignedInteger(0x06));
Result<List<DataItem>, Ctap2ResponseCode> pinToken = pinRequestHandler.getPinToken(hostCoseKey3, pinHashEnc2.getBytes());
byte[] pinTokenPayload = pinToken.handleError(err -> asPayload(err, Collections.emptyList()))
.elseGet(val -> asPayload(Ctap2ResponseCode.OK, val));
return ImmutableRawMessage.builder()
.channelId(channelId)
.command(HidCommand.CBOR)
.payload(pinTokenPayload)
.build();
}
break;
case RESET:
case GET_NEXT_ASSERTION:
default:
return RawMessage.error(channelId, HidError.INVALID_CMD);
}
} catch (CborException e) {
log.error("Unable to deserialize CBOR", e);
} |
22,747 | 0 | //TODO use scheduled task to implement timeout | public void waitFor(String name,Cmd command,Context context,String input, long timeout, TimeUnit unit){
//TODO use scheduled task to implement timeout
Waiter waiter = new Waiter(command,context,input);
waitFor(name,waiter);
} | IMPLEMENTATION | true | public void waitFor(String name,Cmd command,Context context,String input, long timeout, TimeUnit unit){
//TODO use scheduled task to implement timeout
Waiter waiter = new Waiter(command,context,input);
waitFor(name,waiter); | public void waitFor(String name,Cmd command,Context context,String input, long timeout, TimeUnit unit){
//TODO use scheduled task to implement timeout
Waiter waiter = new Waiter(command,context,input);
waitFor(name,waiter);
} | public void waitFor(String name,Cmd command,Context context,String input, long timeout, TimeUnit unit){
//TODO use scheduled task to implement timeout
Waiter waiter = new Waiter(command,context,input);
waitFor(name,waiter);
} |
22,750 | 0 | //FIXME - this is likely wrong | @Test
public void acceptedRequestIsFullyApplied() throws EngineException
{
RegistrationContext defContext = new RegistrationContext(false, TriggeringMode.manualAtLogin);
initAndCreateForm(false, null);
RegistrationRequest request = getRequest();
String id3 = registrationsMan.submitRegistrationRequest(request, defContext);
registrationsMan.processRegistrationRequest(id3, null,
RegistrationRequestAction.accept, "a2", "p2");
RegistrationRequestState fromDb = registrationsMan.getRegistrationRequests().get(0);
assertEquals(request, fromDb.getRequest());
assertEquals(2, fromDb.getAdminComments().size());
assertEquals("p2", fromDb.getAdminComments().get(1).getContents());
assertEquals("a2", fromDb.getAdminComments().get(0).getContents());
assertEquals(RegistrationRequestStatus.accepted, fromDb.getStatus());
assertEquals(id3, fromDb.getRequestId());
assertNotNull(fromDb.getTimestamp());
Entity added = idsMan.getEntity(new EntityParam(new IdentityTaV(X500Identity.ID, "CN=registration test")));
assertEquals(EntityState.valid, added.getState());
assertEquals(EngineInitialization.DEFAULT_CREDENTIAL_REQUIREMENT,
added.getCredentialInfo().getCredentialRequirementId());
assertThat(fromDb.getCreatedEntityId(), is(added.getId()));
CredentialPublicInformation cpi = added.getCredentialInfo().getCredentialsState().get(
EngineInitialization.DEFAULT_CREDENTIAL);
assertEquals(LocalCredentialState.correct, cpi.getState());
EntityParam addedP = new EntityParam(added.getId());
Collection<String> groups = idsMan.getGroups(addedP).keySet();
assertTrue(groups.contains("/"));
assertTrue(groups.contains("/A"));
assertTrue(groups.contains("/B"));
Collection<AttributesClass> acs = acMan.getEntityAttributeClasses(addedP, "/");
assertEquals(1, acs.size());
assertEquals(InitializerCommon.NAMING_AC, acs.iterator().next().getName());
Collection<AttributeExt> attrs = attrsMan.getAttributes(addedP, "/", "cn");
assertEquals(1, attrs.size());
assertEquals("val", attrs.iterator().next().getValues().get(0));
attrs = attrsMan.getAttributes(addedP, "/", "email");
assertEquals(1, attrs.size());
String value = attrs.iterator().next().getValues().get(0);
VerifiableEmail ve = new VerifiableEmail(JsonUtil.parse(value)); //FIXME - this is likely wrong
assertEquals("[email protected]", ve.getValue());
assertEquals(false, ve.getConfirmationInfo().isConfirmed());
} | DEFECT | true | assertEquals(1, attrs.size());
String value = attrs.iterator().next().getValues().get(0);
VerifiableEmail ve = new VerifiableEmail(JsonUtil.parse(value)); //FIXME - this is likely wrong
assertEquals("[email protected]", ve.getValue());
assertEquals(false, ve.getConfirmationInfo().isConfirmed()); | assertTrue(groups.contains("/B"));
Collection<AttributesClass> acs = acMan.getEntityAttributeClasses(addedP, "/");
assertEquals(1, acs.size());
assertEquals(InitializerCommon.NAMING_AC, acs.iterator().next().getName());
Collection<AttributeExt> attrs = attrsMan.getAttributes(addedP, "/", "cn");
assertEquals(1, attrs.size());
assertEquals("val", attrs.iterator().next().getValues().get(0));
attrs = attrsMan.getAttributes(addedP, "/", "email");
assertEquals(1, attrs.size());
String value = attrs.iterator().next().getValues().get(0);
VerifiableEmail ve = new VerifiableEmail(JsonUtil.parse(value)); //FIXME - this is likely wrong
assertEquals("[email protected]", ve.getValue());
assertEquals(false, ve.getConfirmationInfo().isConfirmed());
} | assertEquals(EngineInitialization.DEFAULT_CREDENTIAL_REQUIREMENT,
added.getCredentialInfo().getCredentialRequirementId());
assertThat(fromDb.getCreatedEntityId(), is(added.getId()));
CredentialPublicInformation cpi = added.getCredentialInfo().getCredentialsState().get(
EngineInitialization.DEFAULT_CREDENTIAL);
assertEquals(LocalCredentialState.correct, cpi.getState());
EntityParam addedP = new EntityParam(added.getId());
Collection<String> groups = idsMan.getGroups(addedP).keySet();
assertTrue(groups.contains("/"));
assertTrue(groups.contains("/A"));
assertTrue(groups.contains("/B"));
Collection<AttributesClass> acs = acMan.getEntityAttributeClasses(addedP, "/");
assertEquals(1, acs.size());
assertEquals(InitializerCommon.NAMING_AC, acs.iterator().next().getName());
Collection<AttributeExt> attrs = attrsMan.getAttributes(addedP, "/", "cn");
assertEquals(1, attrs.size());
assertEquals("val", attrs.iterator().next().getValues().get(0));
attrs = attrsMan.getAttributes(addedP, "/", "email");
assertEquals(1, attrs.size());
String value = attrs.iterator().next().getValues().get(0);
VerifiableEmail ve = new VerifiableEmail(JsonUtil.parse(value)); //FIXME - this is likely wrong
assertEquals("[email protected]", ve.getValue());
assertEquals(false, ve.getConfirmationInfo().isConfirmed());
} |
22,752 | 0 | /*
* (non-Javadoc)
*
* @see java.util.Iterator#remove()
*/ | public void remove( )
{
// TODO Add remove operation support.
} | NONSATD | true | public void remove( )
{
// TODO Add remove operation support.
} | public void remove( )
{
// TODO Add remove operation support.
} | public void remove( )
{
// TODO Add remove operation support.
} |
22,752 | 1 | // TODO Add remove operation support. | public void remove( )
{
// TODO Add remove operation support.
} | IMPLEMENTATION | true | public void remove( )
{
// TODO Add remove operation support.
} | public void remove( )
{
// TODO Add remove operation support.
} | public void remove( )
{
// TODO Add remove operation support.
} |
30,944 | 0 | //----------- search = false, filter = false ---------------- | @Override
protected FilterResults performFiltering(CharSequence constraint) {
List<DailyExpenseTagsWithPicsPojo> filteredListHelper = new ArrayList<>();
List<DailyExpenseTagsWithPicsPojo> filteredList = new ArrayList<>();
//----------- search = false, filter = false ----------------
if ((constraint == null || constraint.length() == 0) && (categoriesForFilter == null || categoriesForFilter.size() == 0) && (tagsForFilter == null || tagsForFilter.size() == 0)) {
filteredList.addAll(searchAllCosts);
//----------- search = false, filter = true ----------------
} else if ((constraint == null || constraint.length() == 0) && (categoriesForFilter != null || tagsForFilter != null)) {
if (categoriesForFilter != null && tagsForFilter == null) {
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String category : categoriesForFilter) {
if (category.equals(item.getCostEntry().getCategory())) {
filteredList.add(item);
}
}
}
} else if (categoriesForFilter == null && tagsForFilter != null) { //todo bug
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String tag : tagsForFilter) {
if (item.getTagNames().contains(tag)) {
if (!filteredList.contains(item)) {
filteredList.add(item);
}
}
}
}
} else if (categoriesForFilter != null && tagsForFilter != null) {
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String category : categoriesForFilter) {
if (category.equals(item.getCostEntry().getCategory())) {
filteredListHelper.add(item);
}
}
}
for (DailyExpenseTagsWithPicsPojo item : filteredListHelper) {
for (String tag : tagsForFilter) {
if (item.getTagNames().contains(tag)) {
if (!filteredList.contains(item)) {
filteredList.add(item);
}
}
}
}
}
//----------- search = true, filter = false ----------------
} else if (constraint.length() != 0) {
String filterPattern = constraint.toString().toLowerCase().trim();
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
if (item.getCostEntry().getName().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
// TODO: simultaneously search what is filtered and filter what is searched
FilterResults results = new FilterResults();
results.values = filteredList;
Log.d("kraj metode", "testt");
return results;
} | NONSATD | true | List<DailyExpenseTagsWithPicsPojo> filteredListHelper = new ArrayList<>();
List<DailyExpenseTagsWithPicsPojo> filteredList = new ArrayList<>();
//----------- search = false, filter = false ----------------
if ((constraint == null || constraint.length() == 0) && (categoriesForFilter == null || categoriesForFilter.size() == 0) && (tagsForFilter == null || tagsForFilter.size() == 0)) {
filteredList.addAll(searchAllCosts); | @Override
protected FilterResults performFiltering(CharSequence constraint) {
List<DailyExpenseTagsWithPicsPojo> filteredListHelper = new ArrayList<>();
List<DailyExpenseTagsWithPicsPojo> filteredList = new ArrayList<>();
//----------- search = false, filter = false ----------------
if ((constraint == null || constraint.length() == 0) && (categoriesForFilter == null || categoriesForFilter.size() == 0) && (tagsForFilter == null || tagsForFilter.size() == 0)) {
filteredList.addAll(searchAllCosts);
//----------- search = false, filter = true ----------------
} else if ((constraint == null || constraint.length() == 0) && (categoriesForFilter != null || tagsForFilter != null)) {
if (categoriesForFilter != null && tagsForFilter == null) {
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String category : categoriesForFilter) {
if (category.equals(item.getCostEntry().getCategory())) {
filteredList.add(item);
} | @Override
protected FilterResults performFiltering(CharSequence constraint) {
List<DailyExpenseTagsWithPicsPojo> filteredListHelper = new ArrayList<>();
List<DailyExpenseTagsWithPicsPojo> filteredList = new ArrayList<>();
//----------- search = false, filter = false ----------------
if ((constraint == null || constraint.length() == 0) && (categoriesForFilter == null || categoriesForFilter.size() == 0) && (tagsForFilter == null || tagsForFilter.size() == 0)) {
filteredList.addAll(searchAllCosts);
//----------- search = false, filter = true ----------------
} else if ((constraint == null || constraint.length() == 0) && (categoriesForFilter != null || tagsForFilter != null)) {
if (categoriesForFilter != null && tagsForFilter == null) {
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String category : categoriesForFilter) {
if (category.equals(item.getCostEntry().getCategory())) {
filteredList.add(item);
}
}
}
} else if (categoriesForFilter == null && tagsForFilter != null) { //todo bug
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String tag : tagsForFilter) {
if (item.getTagNames().contains(tag)) {
if (!filteredList.contains(item)) {
filteredList.add(item);
}
} |
30,944 | 1 | //----------- search = false, filter = true ---------------- | @Override
protected FilterResults performFiltering(CharSequence constraint) {
List<DailyExpenseTagsWithPicsPojo> filteredListHelper = new ArrayList<>();
List<DailyExpenseTagsWithPicsPojo> filteredList = new ArrayList<>();
//----------- search = false, filter = false ----------------
if ((constraint == null || constraint.length() == 0) && (categoriesForFilter == null || categoriesForFilter.size() == 0) && (tagsForFilter == null || tagsForFilter.size() == 0)) {
filteredList.addAll(searchAllCosts);
//----------- search = false, filter = true ----------------
} else if ((constraint == null || constraint.length() == 0) && (categoriesForFilter != null || tagsForFilter != null)) {
if (categoriesForFilter != null && tagsForFilter == null) {
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String category : categoriesForFilter) {
if (category.equals(item.getCostEntry().getCategory())) {
filteredList.add(item);
}
}
}
} else if (categoriesForFilter == null && tagsForFilter != null) { //todo bug
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String tag : tagsForFilter) {
if (item.getTagNames().contains(tag)) {
if (!filteredList.contains(item)) {
filteredList.add(item);
}
}
}
}
} else if (categoriesForFilter != null && tagsForFilter != null) {
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String category : categoriesForFilter) {
if (category.equals(item.getCostEntry().getCategory())) {
filteredListHelper.add(item);
}
}
}
for (DailyExpenseTagsWithPicsPojo item : filteredListHelper) {
for (String tag : tagsForFilter) {
if (item.getTagNames().contains(tag)) {
if (!filteredList.contains(item)) {
filteredList.add(item);
}
}
}
}
}
//----------- search = true, filter = false ----------------
} else if (constraint.length() != 0) {
String filterPattern = constraint.toString().toLowerCase().trim();
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
if (item.getCostEntry().getName().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
// TODO: simultaneously search what is filtered and filter what is searched
FilterResults results = new FilterResults();
results.values = filteredList;
Log.d("kraj metode", "testt");
return results;
} | NONSATD | true | if ((constraint == null || constraint.length() == 0) && (categoriesForFilter == null || categoriesForFilter.size() == 0) && (tagsForFilter == null || tagsForFilter.size() == 0)) {
filteredList.addAll(searchAllCosts);
//----------- search = false, filter = true ----------------
} else if ((constraint == null || constraint.length() == 0) && (categoriesForFilter != null || tagsForFilter != null)) {
if (categoriesForFilter != null && tagsForFilter == null) { | @Override
protected FilterResults performFiltering(CharSequence constraint) {
List<DailyExpenseTagsWithPicsPojo> filteredListHelper = new ArrayList<>();
List<DailyExpenseTagsWithPicsPojo> filteredList = new ArrayList<>();
//----------- search = false, filter = false ----------------
if ((constraint == null || constraint.length() == 0) && (categoriesForFilter == null || categoriesForFilter.size() == 0) && (tagsForFilter == null || tagsForFilter.size() == 0)) {
filteredList.addAll(searchAllCosts);
//----------- search = false, filter = true ----------------
} else if ((constraint == null || constraint.length() == 0) && (categoriesForFilter != null || tagsForFilter != null)) {
if (categoriesForFilter != null && tagsForFilter == null) {
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String category : categoriesForFilter) {
if (category.equals(item.getCostEntry().getCategory())) {
filteredList.add(item);
}
}
}
} else if (categoriesForFilter == null && tagsForFilter != null) { //todo bug | @Override
protected FilterResults performFiltering(CharSequence constraint) {
List<DailyExpenseTagsWithPicsPojo> filteredListHelper = new ArrayList<>();
List<DailyExpenseTagsWithPicsPojo> filteredList = new ArrayList<>();
//----------- search = false, filter = false ----------------
if ((constraint == null || constraint.length() == 0) && (categoriesForFilter == null || categoriesForFilter.size() == 0) && (tagsForFilter == null || tagsForFilter.size() == 0)) {
filteredList.addAll(searchAllCosts);
//----------- search = false, filter = true ----------------
} else if ((constraint == null || constraint.length() == 0) && (categoriesForFilter != null || tagsForFilter != null)) {
if (categoriesForFilter != null && tagsForFilter == null) {
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String category : categoriesForFilter) {
if (category.equals(item.getCostEntry().getCategory())) {
filteredList.add(item);
}
}
}
} else if (categoriesForFilter == null && tagsForFilter != null) { //todo bug
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String tag : tagsForFilter) {
if (item.getTagNames().contains(tag)) {
if (!filteredList.contains(item)) {
filteredList.add(item);
}
}
}
}
} else if (categoriesForFilter != null && tagsForFilter != null) { |
30,944 | 2 | //todo bug | @Override
protected FilterResults performFiltering(CharSequence constraint) {
List<DailyExpenseTagsWithPicsPojo> filteredListHelper = new ArrayList<>();
List<DailyExpenseTagsWithPicsPojo> filteredList = new ArrayList<>();
//----------- search = false, filter = false ----------------
if ((constraint == null || constraint.length() == 0) && (categoriesForFilter == null || categoriesForFilter.size() == 0) && (tagsForFilter == null || tagsForFilter.size() == 0)) {
filteredList.addAll(searchAllCosts);
//----------- search = false, filter = true ----------------
} else if ((constraint == null || constraint.length() == 0) && (categoriesForFilter != null || tagsForFilter != null)) {
if (categoriesForFilter != null && tagsForFilter == null) {
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String category : categoriesForFilter) {
if (category.equals(item.getCostEntry().getCategory())) {
filteredList.add(item);
}
}
}
} else if (categoriesForFilter == null && tagsForFilter != null) { //todo bug
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String tag : tagsForFilter) {
if (item.getTagNames().contains(tag)) {
if (!filteredList.contains(item)) {
filteredList.add(item);
}
}
}
}
} else if (categoriesForFilter != null && tagsForFilter != null) {
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String category : categoriesForFilter) {
if (category.equals(item.getCostEntry().getCategory())) {
filteredListHelper.add(item);
}
}
}
for (DailyExpenseTagsWithPicsPojo item : filteredListHelper) {
for (String tag : tagsForFilter) {
if (item.getTagNames().contains(tag)) {
if (!filteredList.contains(item)) {
filteredList.add(item);
}
}
}
}
}
//----------- search = true, filter = false ----------------
} else if (constraint.length() != 0) {
String filterPattern = constraint.toString().toLowerCase().trim();
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
if (item.getCostEntry().getName().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
// TODO: simultaneously search what is filtered and filter what is searched
FilterResults results = new FilterResults();
results.values = filteredList;
Log.d("kraj metode", "testt");
return results;
} | DEFECT | true | }
}
} else if (categoriesForFilter == null && tagsForFilter != null) { //todo bug
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String tag : tagsForFilter) { | //----------- search = false, filter = true ----------------
} else if ((constraint == null || constraint.length() == 0) && (categoriesForFilter != null || tagsForFilter != null)) {
if (categoriesForFilter != null && tagsForFilter == null) {
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String category : categoriesForFilter) {
if (category.equals(item.getCostEntry().getCategory())) {
filteredList.add(item);
}
}
}
} else if (categoriesForFilter == null && tagsForFilter != null) { //todo bug
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String tag : tagsForFilter) {
if (item.getTagNames().contains(tag)) {
if (!filteredList.contains(item)) {
filteredList.add(item);
}
}
}
}
} else if (categoriesForFilter != null && tagsForFilter != null) { | @Override
protected FilterResults performFiltering(CharSequence constraint) {
List<DailyExpenseTagsWithPicsPojo> filteredListHelper = new ArrayList<>();
List<DailyExpenseTagsWithPicsPojo> filteredList = new ArrayList<>();
//----------- search = false, filter = false ----------------
if ((constraint == null || constraint.length() == 0) && (categoriesForFilter == null || categoriesForFilter.size() == 0) && (tagsForFilter == null || tagsForFilter.size() == 0)) {
filteredList.addAll(searchAllCosts);
//----------- search = false, filter = true ----------------
} else if ((constraint == null || constraint.length() == 0) && (categoriesForFilter != null || tagsForFilter != null)) {
if (categoriesForFilter != null && tagsForFilter == null) {
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String category : categoriesForFilter) {
if (category.equals(item.getCostEntry().getCategory())) {
filteredList.add(item);
}
}
}
} else if (categoriesForFilter == null && tagsForFilter != null) { //todo bug
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String tag : tagsForFilter) {
if (item.getTagNames().contains(tag)) {
if (!filteredList.contains(item)) {
filteredList.add(item);
}
}
}
}
} else if (categoriesForFilter != null && tagsForFilter != null) {
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String category : categoriesForFilter) {
if (category.equals(item.getCostEntry().getCategory())) {
filteredListHelper.add(item);
}
}
}
for (DailyExpenseTagsWithPicsPojo item : filteredListHelper) {
for (String tag : tagsForFilter) {
if (item.getTagNames().contains(tag)) { |
30,944 | 3 | //----------- search = true, filter = false ---------------- | @Override
protected FilterResults performFiltering(CharSequence constraint) {
List<DailyExpenseTagsWithPicsPojo> filteredListHelper = new ArrayList<>();
List<DailyExpenseTagsWithPicsPojo> filteredList = new ArrayList<>();
//----------- search = false, filter = false ----------------
if ((constraint == null || constraint.length() == 0) && (categoriesForFilter == null || categoriesForFilter.size() == 0) && (tagsForFilter == null || tagsForFilter.size() == 0)) {
filteredList.addAll(searchAllCosts);
//----------- search = false, filter = true ----------------
} else if ((constraint == null || constraint.length() == 0) && (categoriesForFilter != null || tagsForFilter != null)) {
if (categoriesForFilter != null && tagsForFilter == null) {
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String category : categoriesForFilter) {
if (category.equals(item.getCostEntry().getCategory())) {
filteredList.add(item);
}
}
}
} else if (categoriesForFilter == null && tagsForFilter != null) { //todo bug
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String tag : tagsForFilter) {
if (item.getTagNames().contains(tag)) {
if (!filteredList.contains(item)) {
filteredList.add(item);
}
}
}
}
} else if (categoriesForFilter != null && tagsForFilter != null) {
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String category : categoriesForFilter) {
if (category.equals(item.getCostEntry().getCategory())) {
filteredListHelper.add(item);
}
}
}
for (DailyExpenseTagsWithPicsPojo item : filteredListHelper) {
for (String tag : tagsForFilter) {
if (item.getTagNames().contains(tag)) {
if (!filteredList.contains(item)) {
filteredList.add(item);
}
}
}
}
}
//----------- search = true, filter = false ----------------
} else if (constraint.length() != 0) {
String filterPattern = constraint.toString().toLowerCase().trim();
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
if (item.getCostEntry().getName().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
// TODO: simultaneously search what is filtered and filter what is searched
FilterResults results = new FilterResults();
results.values = filteredList;
Log.d("kraj metode", "testt");
return results;
} | NONSATD | true | }
}
//----------- search = true, filter = false ----------------
} else if (constraint.length() != 0) {
String filterPattern = constraint.toString().toLowerCase().trim(); | for (DailyExpenseTagsWithPicsPojo item : filteredListHelper) {
for (String tag : tagsForFilter) {
if (item.getTagNames().contains(tag)) {
if (!filteredList.contains(item)) {
filteredList.add(item);
}
}
}
}
}
//----------- search = true, filter = false ----------------
} else if (constraint.length() != 0) {
String filterPattern = constraint.toString().toLowerCase().trim();
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
if (item.getCostEntry().getName().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
// TODO: simultaneously search what is filtered and filter what is searched
FilterResults results = new FilterResults(); | }
}
} else if (categoriesForFilter != null && tagsForFilter != null) {
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String category : categoriesForFilter) {
if (category.equals(item.getCostEntry().getCategory())) {
filteredListHelper.add(item);
}
}
}
for (DailyExpenseTagsWithPicsPojo item : filteredListHelper) {
for (String tag : tagsForFilter) {
if (item.getTagNames().contains(tag)) {
if (!filteredList.contains(item)) {
filteredList.add(item);
}
}
}
}
}
//----------- search = true, filter = false ----------------
} else if (constraint.length() != 0) {
String filterPattern = constraint.toString().toLowerCase().trim();
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
if (item.getCostEntry().getName().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
// TODO: simultaneously search what is filtered and filter what is searched
FilterResults results = new FilterResults();
results.values = filteredList;
Log.d("kraj metode", "testt");
return results;
} |
30,944 | 4 | // TODO: simultaneously search what is filtered and filter what is searched | @Override
protected FilterResults performFiltering(CharSequence constraint) {
List<DailyExpenseTagsWithPicsPojo> filteredListHelper = new ArrayList<>();
List<DailyExpenseTagsWithPicsPojo> filteredList = new ArrayList<>();
//----------- search = false, filter = false ----------------
if ((constraint == null || constraint.length() == 0) && (categoriesForFilter == null || categoriesForFilter.size() == 0) && (tagsForFilter == null || tagsForFilter.size() == 0)) {
filteredList.addAll(searchAllCosts);
//----------- search = false, filter = true ----------------
} else if ((constraint == null || constraint.length() == 0) && (categoriesForFilter != null || tagsForFilter != null)) {
if (categoriesForFilter != null && tagsForFilter == null) {
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String category : categoriesForFilter) {
if (category.equals(item.getCostEntry().getCategory())) {
filteredList.add(item);
}
}
}
} else if (categoriesForFilter == null && tagsForFilter != null) { //todo bug
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String tag : tagsForFilter) {
if (item.getTagNames().contains(tag)) {
if (!filteredList.contains(item)) {
filteredList.add(item);
}
}
}
}
} else if (categoriesForFilter != null && tagsForFilter != null) {
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
for (String category : categoriesForFilter) {
if (category.equals(item.getCostEntry().getCategory())) {
filteredListHelper.add(item);
}
}
}
for (DailyExpenseTagsWithPicsPojo item : filteredListHelper) {
for (String tag : tagsForFilter) {
if (item.getTagNames().contains(tag)) {
if (!filteredList.contains(item)) {
filteredList.add(item);
}
}
}
}
}
//----------- search = true, filter = false ----------------
} else if (constraint.length() != 0) {
String filterPattern = constraint.toString().toLowerCase().trim();
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
if (item.getCostEntry().getName().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
// TODO: simultaneously search what is filtered and filter what is searched
FilterResults results = new FilterResults();
results.values = filteredList;
Log.d("kraj metode", "testt");
return results;
} | IMPLEMENTATION | true | }
}
// TODO: simultaneously search what is filtered and filter what is searched
FilterResults results = new FilterResults();
results.values = filteredList; | }
//----------- search = true, filter = false ----------------
} else if (constraint.length() != 0) {
String filterPattern = constraint.toString().toLowerCase().trim();
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
if (item.getCostEntry().getName().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
// TODO: simultaneously search what is filtered and filter what is searched
FilterResults results = new FilterResults();
results.values = filteredList;
Log.d("kraj metode", "testt");
return results;
} | }
for (DailyExpenseTagsWithPicsPojo item : filteredListHelper) {
for (String tag : tagsForFilter) {
if (item.getTagNames().contains(tag)) {
if (!filteredList.contains(item)) {
filteredList.add(item);
}
}
}
}
}
//----------- search = true, filter = false ----------------
} else if (constraint.length() != 0) {
String filterPattern = constraint.toString().toLowerCase().trim();
for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) {
if (item.getCostEntry().getName().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
// TODO: simultaneously search what is filtered and filter what is searched
FilterResults results = new FilterResults();
results.values = filteredList;
Log.d("kraj metode", "testt");
return results;
} |
14,566 | 0 | // TODO consider showing actual source code instead of just types and names | private void resolveDetail(CompletionItem item, CompletionData data, Tree tree) {
if (tree instanceof MethodTree) {
var method = (MethodTree) tree;
var parameters = new StringJoiner(", ");
for (var p : method.getParameters()) {
parameters.add(p.getType() + " " + p.getName());
}
item.detail = method.getReturnType() + " " + method.getName() + "(" + parameters + ")";
if (!method.getThrows().isEmpty()) {
var exceptions = new StringJoiner(", ");
for (var e : method.getThrows()) {
exceptions.add(e.toString());
}
item.detail += " throws " + exceptions;
}
if (data.plusOverloads != 0) {
item.detail += " (+" + data.plusOverloads + " overloads)";
}
}
} | DESIGN | true | private void resolveDetail(CompletionItem item, CompletionData data, Tree tree) {
if (tree instanceof MethodTree) {
var method = (MethodTree) tree;
var parameters = new StringJoiner(", ");
for (var p : method.getParameters()) {
parameters.add(p.getType() + " " + p.getName());
}
item.detail = method.getReturnType() + " " + method.getName() + "(" + parameters + ")";
if (!method.getThrows().isEmpty()) {
var exceptions = new StringJoiner(", ");
for (var e : method.getThrows()) {
exceptions.add(e.toString());
}
item.detail += " throws " + exceptions;
}
if (data.plusOverloads != 0) {
item.detail += " (+" + data.plusOverloads + " overloads)";
}
}
} | private void resolveDetail(CompletionItem item, CompletionData data, Tree tree) {
if (tree instanceof MethodTree) {
var method = (MethodTree) tree;
var parameters = new StringJoiner(", ");
for (var p : method.getParameters()) {
parameters.add(p.getType() + " " + p.getName());
}
item.detail = method.getReturnType() + " " + method.getName() + "(" + parameters + ")";
if (!method.getThrows().isEmpty()) {
var exceptions = new StringJoiner(", ");
for (var e : method.getThrows()) {
exceptions.add(e.toString());
}
item.detail += " throws " + exceptions;
}
if (data.plusOverloads != 0) {
item.detail += " (+" + data.plusOverloads + " overloads)";
}
}
} | private void resolveDetail(CompletionItem item, CompletionData data, Tree tree) {
if (tree instanceof MethodTree) {
var method = (MethodTree) tree;
var parameters = new StringJoiner(", ");
for (var p : method.getParameters()) {
parameters.add(p.getType() + " " + p.getName());
}
item.detail = method.getReturnType() + " " + method.getName() + "(" + parameters + ")";
if (!method.getThrows().isEmpty()) {
var exceptions = new StringJoiner(", ");
for (var e : method.getThrows()) {
exceptions.add(e.toString());
}
item.detail += " throws " + exceptions;
}
if (data.plusOverloads != 0) {
item.detail += " (+" + data.plusOverloads + " overloads)";
}
}
} |
30,955 | 0 | /**
* Metodo para compartir el anuncio a traves del email
*
* @param email
* @param model
* @param authentication
* @param req
* @param flash
* @return
*/ | @RequestMapping(value = "/shareAnuncio", method = RequestMethod.POST)
public String shareAnuncio(@RequestParam("email") String email, Model model, Authentication authentication,
HttpServletRequest req, RedirectAttributes flash) {
logger.info("contactar-anunciante");
Integer id = Integer.parseInt(req.getParameter("id"));
try {
Vehiculo veh = vehiculoService.findById(id);
String appUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort();
// Email message
SimpleMailMessage shareEmail = new SimpleMailMessage();
shareEmail.setTo(email);
shareEmail.setSubject("Coches: Un amigo te recomienda este anuncio");
shareEmail.setText("¡Hola!\n" + "Un amigo se ha acordado de ti al ver este anuncio " + veh.getMarca()
+ " y cree que te puede interesar." + "\n¿Tienes curiosidad?\n" + appUrl + "/anuncio/detalle/"
+ id);
emailService.sendEmail(shareEmail);
model.addAttribute("emailSend", "El correo se envio correctamente");
logger.info("Email enviado correctamente");
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/anuncio/detalle/" + id;
} | NONSATD | true | @RequestMapping(value = "/shareAnuncio", method = RequestMethod.POST)
public String shareAnuncio(@RequestParam("email") String email, Model model, Authentication authentication,
HttpServletRequest req, RedirectAttributes flash) {
logger.info("contactar-anunciante");
Integer id = Integer.parseInt(req.getParameter("id"));
try {
Vehiculo veh = vehiculoService.findById(id);
String appUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort();
// Email message
SimpleMailMessage shareEmail = new SimpleMailMessage();
shareEmail.setTo(email);
shareEmail.setSubject("Coches: Un amigo te recomienda este anuncio");
shareEmail.setText("¡Hola!\n" + "Un amigo se ha acordado de ti al ver este anuncio " + veh.getMarca()
+ " y cree que te puede interesar." + "\n¿Tienes curiosidad?\n" + appUrl + "/anuncio/detalle/"
+ id);
emailService.sendEmail(shareEmail);
model.addAttribute("emailSend", "El correo se envio correctamente");
logger.info("Email enviado correctamente");
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/anuncio/detalle/" + id;
} | @RequestMapping(value = "/shareAnuncio", method = RequestMethod.POST)
public String shareAnuncio(@RequestParam("email") String email, Model model, Authentication authentication,
HttpServletRequest req, RedirectAttributes flash) {
logger.info("contactar-anunciante");
Integer id = Integer.parseInt(req.getParameter("id"));
try {
Vehiculo veh = vehiculoService.findById(id);
String appUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort();
// Email message
SimpleMailMessage shareEmail = new SimpleMailMessage();
shareEmail.setTo(email);
shareEmail.setSubject("Coches: Un amigo te recomienda este anuncio");
shareEmail.setText("¡Hola!\n" + "Un amigo se ha acordado de ti al ver este anuncio " + veh.getMarca()
+ " y cree que te puede interesar." + "\n¿Tienes curiosidad?\n" + appUrl + "/anuncio/detalle/"
+ id);
emailService.sendEmail(shareEmail);
model.addAttribute("emailSend", "El correo se envio correctamente");
logger.info("Email enviado correctamente");
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/anuncio/detalle/" + id;
} | @RequestMapping(value = "/shareAnuncio", method = RequestMethod.POST)
public String shareAnuncio(@RequestParam("email") String email, Model model, Authentication authentication,
HttpServletRequest req, RedirectAttributes flash) {
logger.info("contactar-anunciante");
Integer id = Integer.parseInt(req.getParameter("id"));
try {
Vehiculo veh = vehiculoService.findById(id);
String appUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort();
// Email message
SimpleMailMessage shareEmail = new SimpleMailMessage();
shareEmail.setTo(email);
shareEmail.setSubject("Coches: Un amigo te recomienda este anuncio");
shareEmail.setText("¡Hola!\n" + "Un amigo se ha acordado de ti al ver este anuncio " + veh.getMarca()
+ " y cree que te puede interesar." + "\n¿Tienes curiosidad?\n" + appUrl + "/anuncio/detalle/"
+ id);
emailService.sendEmail(shareEmail);
model.addAttribute("emailSend", "El correo se envio correctamente");
logger.info("Email enviado correctamente");
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/anuncio/detalle/" + id;
} |
30,955 | 1 | // Email message | @RequestMapping(value = "/shareAnuncio", method = RequestMethod.POST)
public String shareAnuncio(@RequestParam("email") String email, Model model, Authentication authentication,
HttpServletRequest req, RedirectAttributes flash) {
logger.info("contactar-anunciante");
Integer id = Integer.parseInt(req.getParameter("id"));
try {
Vehiculo veh = vehiculoService.findById(id);
String appUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort();
// Email message
SimpleMailMessage shareEmail = new SimpleMailMessage();
shareEmail.setTo(email);
shareEmail.setSubject("Coches: Un amigo te recomienda este anuncio");
shareEmail.setText("¡Hola!\n" + "Un amigo se ha acordado de ti al ver este anuncio " + veh.getMarca()
+ " y cree que te puede interesar." + "\n¿Tienes curiosidad?\n" + appUrl + "/anuncio/detalle/"
+ id);
emailService.sendEmail(shareEmail);
model.addAttribute("emailSend", "El correo se envio correctamente");
logger.info("Email enviado correctamente");
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/anuncio/detalle/" + id;
} | NONSATD | true | Vehiculo veh = vehiculoService.findById(id);
String appUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort();
// Email message
SimpleMailMessage shareEmail = new SimpleMailMessage();
shareEmail.setTo(email); | @RequestMapping(value = "/shareAnuncio", method = RequestMethod.POST)
public String shareAnuncio(@RequestParam("email") String email, Model model, Authentication authentication,
HttpServletRequest req, RedirectAttributes flash) {
logger.info("contactar-anunciante");
Integer id = Integer.parseInt(req.getParameter("id"));
try {
Vehiculo veh = vehiculoService.findById(id);
String appUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort();
// Email message
SimpleMailMessage shareEmail = new SimpleMailMessage();
shareEmail.setTo(email);
shareEmail.setSubject("Coches: Un amigo te recomienda este anuncio");
shareEmail.setText("¡Hola!\n" + "Un amigo se ha acordado de ti al ver este anuncio " + veh.getMarca()
+ " y cree que te puede interesar." + "\n¿Tienes curiosidad?\n" + appUrl + "/anuncio/detalle/"
+ id);
emailService.sendEmail(shareEmail);
model.addAttribute("emailSend", "El correo se envio correctamente");
logger.info("Email enviado correctamente");
} catch (Exception e) { | @RequestMapping(value = "/shareAnuncio", method = RequestMethod.POST)
public String shareAnuncio(@RequestParam("email") String email, Model model, Authentication authentication,
HttpServletRequest req, RedirectAttributes flash) {
logger.info("contactar-anunciante");
Integer id = Integer.parseInt(req.getParameter("id"));
try {
Vehiculo veh = vehiculoService.findById(id);
String appUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort();
// Email message
SimpleMailMessage shareEmail = new SimpleMailMessage();
shareEmail.setTo(email);
shareEmail.setSubject("Coches: Un amigo te recomienda este anuncio");
shareEmail.setText("¡Hola!\n" + "Un amigo se ha acordado de ti al ver este anuncio " + veh.getMarca()
+ " y cree que te puede interesar." + "\n¿Tienes curiosidad?\n" + appUrl + "/anuncio/detalle/"
+ id);
emailService.sendEmail(shareEmail);
model.addAttribute("emailSend", "El correo se envio correctamente");
logger.info("Email enviado correctamente");
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/anuncio/detalle/" + id;
} |
22,765 | 0 | // TODO : Replace this with conversion at the item level. | private Object convert(final Field field, final Val val) {
if (field != null && field.getFormat() != null && field.getFormat().getType() != null) {
final Type type = field.getFormat().getType();
if (Type.NUMBER.equals(type) || Type.DATE_TIME.equals(type)) {
return val.toDouble();
}
}
return val.toString();
} | DESIGN | true | private Object convert(final Field field, final Val val) {
if (field != null && field.getFormat() != null && field.getFormat().getType() != null) {
final Type type = field.getFormat().getType();
if (Type.NUMBER.equals(type) || Type.DATE_TIME.equals(type)) {
return val.toDouble();
}
}
return val.toString();
} | private Object convert(final Field field, final Val val) {
if (field != null && field.getFormat() != null && field.getFormat().getType() != null) {
final Type type = field.getFormat().getType();
if (Type.NUMBER.equals(type) || Type.DATE_TIME.equals(type)) {
return val.toDouble();
}
}
return val.toString();
} | private Object convert(final Field field, final Val val) {
if (field != null && field.getFormat() != null && field.getFormat().getType() != null) {
final Type type = field.getFormat().getType();
if (Type.NUMBER.equals(type) || Type.DATE_TIME.equals(type)) {
return val.toDouble();
}
}
return val.toString();
} |
30,960 | 0 | // TODO: fix to compare provided eventDate and reproductiveState with data from FNA | public void validateFloweringTime(String scientificName, String eventDate, String reproductiveState, String country, String kingdom, String latitude, String longitude) {
HashMap<String, String> initialValues = new HashMap<String, String>();
initialValues.put("eventDate", eventDate);
initialValues.put("scientificName", scientificName);
initialValues.put("reproductive", reproductiveState);
initialValues.put("country", country);
initialValues.put("kingdom", kingdom);
initialValues.put("latitude", latitude);
initialValues.put("longitude", longitude);
initDate(new CurationStep("Validate Collecting Event Date: check dwc:eventDate against reproductive state. ", initialValues));
// TODO: fix to compare provided eventDate and reproductiveState with data from FNA
Vector<String> months = new Vector<String>();
Vector<String> foundFloweringTime = null;
if(authoritativeFloweringTimeMap != null && authoritativeFloweringTimeMap.containsKey(scientificName.toLowerCase())){
foundFloweringTime = authoritativeFloweringTimeMap.get(scientificName.toLowerCase());
}
if(foundFloweringTime == null){
setCurationStatus(CurationComment.UNABLE_DETERMINE_VALIDITY);
addToComment("Can't find the flowering time of the "+scientificName+" in the current available phenology data from FNA.");
correctedFloweringTime = null;
}else{
if(months==null || !months.containsAll(foundFloweringTime) || !foundFloweringTime.containsAll(months) ){
setCurationStatus(CurationComment.UNABLE_CURATED);
addToComment("Provided event date and flowering state is inconsistent with known flowering times for species according to FNA.");
}else{
setCurationStatus(CurationComment.CORRECT);
addToComment("The event date and flowering state is consistent with authoritative data from FNA");
correctedFloweringTime = months;
}
}
} | DESIGN | true | initialValues.put("longitude", longitude);
initDate(new CurationStep("Validate Collecting Event Date: check dwc:eventDate against reproductive state. ", initialValues));
// TODO: fix to compare provided eventDate and reproductiveState with data from FNA
Vector<String> months = new Vector<String>();
Vector<String> foundFloweringTime = null; | public void validateFloweringTime(String scientificName, String eventDate, String reproductiveState, String country, String kingdom, String latitude, String longitude) {
HashMap<String, String> initialValues = new HashMap<String, String>();
initialValues.put("eventDate", eventDate);
initialValues.put("scientificName", scientificName);
initialValues.put("reproductive", reproductiveState);
initialValues.put("country", country);
initialValues.put("kingdom", kingdom);
initialValues.put("latitude", latitude);
initialValues.put("longitude", longitude);
initDate(new CurationStep("Validate Collecting Event Date: check dwc:eventDate against reproductive state. ", initialValues));
// TODO: fix to compare provided eventDate and reproductiveState with data from FNA
Vector<String> months = new Vector<String>();
Vector<String> foundFloweringTime = null;
if(authoritativeFloweringTimeMap != null && authoritativeFloweringTimeMap.containsKey(scientificName.toLowerCase())){
foundFloweringTime = authoritativeFloweringTimeMap.get(scientificName.toLowerCase());
}
if(foundFloweringTime == null){
setCurationStatus(CurationComment.UNABLE_DETERMINE_VALIDITY);
addToComment("Can't find the flowering time of the "+scientificName+" in the current available phenology data from FNA.");
correctedFloweringTime = null;
}else{ | public void validateFloweringTime(String scientificName, String eventDate, String reproductiveState, String country, String kingdom, String latitude, String longitude) {
HashMap<String, String> initialValues = new HashMap<String, String>();
initialValues.put("eventDate", eventDate);
initialValues.put("scientificName", scientificName);
initialValues.put("reproductive", reproductiveState);
initialValues.put("country", country);
initialValues.put("kingdom", kingdom);
initialValues.put("latitude", latitude);
initialValues.put("longitude", longitude);
initDate(new CurationStep("Validate Collecting Event Date: check dwc:eventDate against reproductive state. ", initialValues));
// TODO: fix to compare provided eventDate and reproductiveState with data from FNA
Vector<String> months = new Vector<String>();
Vector<String> foundFloweringTime = null;
if(authoritativeFloweringTimeMap != null && authoritativeFloweringTimeMap.containsKey(scientificName.toLowerCase())){
foundFloweringTime = authoritativeFloweringTimeMap.get(scientificName.toLowerCase());
}
if(foundFloweringTime == null){
setCurationStatus(CurationComment.UNABLE_DETERMINE_VALIDITY);
addToComment("Can't find the flowering time of the "+scientificName+" in the current available phenology data from FNA.");
correctedFloweringTime = null;
}else{
if(months==null || !months.containsAll(foundFloweringTime) || !foundFloweringTime.containsAll(months) ){
setCurationStatus(CurationComment.UNABLE_CURATED);
addToComment("Provided event date and flowering state is inconsistent with known flowering times for species according to FNA.");
}else{
setCurationStatus(CurationComment.CORRECT);
addToComment("The event date and flowering state is consistent with authoritative data from FNA");
correctedFloweringTime = months;
}
}
} |
22,775 | 0 | /**
* find the edges and return as a list of points. The method uses a
* DFS search through all points in the image with values > 0 to link
* adjacent sequential points into edges.
* The method then uses method mergeAdjacentEndPoints.
* Note that the later 2 methods are not needed if the edges will be used
* in a corner detector only, but if the edges are to be used to
* find inflection points in scale space maps, those methods help to
* provide more complete shapes and better matches between the same object
* in another scale space map.
*
* @return
*/ | public List<PairIntArray> findEdges() {
// DFS search for sequential neighbors.
Stack<PairInt> stack = new Stack<PairInt>();
int thresh0 = 1;
for (int i = 0; i < img.getWidth(); i++) {
for (int j = 0; j < img.getHeight(); j++) {
//for now, choosing to look only at the blue
int bPix = img.getValue(i, j);
if (bPix >= thresh0) {
stack.add(new PairInt(i, j));
}
}
}
numberOfPixelsAboveThreshold = stack.size();
log.log(Level.FINE, "Number of pixels that exceed threshhold={0}",
Long.toString(numberOfPixelsAboveThreshold));
List<PairIntArray> output = new ArrayList<PairIntArray>();
int[] uNodeEdgeIdx = new int[img.getWidth() * img.getHeight()];
Arrays.fill(uNodeEdgeIdx, -1);
while (!stack.isEmpty()) {
PairInt uNode = stack.pop();
int uX = uNode.getX();
int uY = uNode.getY();
int uIdx = (uY * img.getWidth()) + uX;
boolean foundNeighbor = false;
// for each neighbor v of u
for (int vX = (uX - 1); vX < (uX + 2); vX++) {
if (foundNeighbor) {
break;
}
if (vX < 0 || vX > (img.getWidth() - 1)) {
continue;
}
for (int vY = (uY - 1); vY < (uY + 2); vY++) {
if (vY < 0 || vY > (img.getHeight() - 1)) {
continue;
}
int vIdx = (vY * img.getWidth()) + vX;
if (uNodeEdgeIdx[vIdx] != -1 || (uIdx == vIdx)) {
continue;
}
if (img.getValue(vX, vY) < thresh0) {
continue;
}
// if u is not in an edge already, create a new one
if (uNodeEdgeIdx[uIdx] == -1) {
PairIntArray edge = new PairIntArray();
edge.add(uX, uY);
uNodeEdgeIdx[uIdx] = output.size();
output.add(edge);
}
// keep the curve points ordered
// add v to the edge u if u is the last node in it's edge
PairIntArray appendToNode = output.get(uNodeEdgeIdx[uIdx]);
int aIdx = appendToNode.getN() - 1;
if ((appendToNode.getX(aIdx) != uX) ||
(appendToNode.getY(aIdx) != uY)) {
continue;
}
appendToNode.add(vX, vY);
uNodeEdgeIdx[vIdx] = uNodeEdgeIdx[uIdx];
//TODO: do we only want 1 neighbor from the 9 as a continuation?
// yes for now, but this requires edges be only 1 pixel wide
// inserting back at the top of the stack assures that the
// search continues next from an associated point
stack.add(new PairInt(vX, vY));
foundNeighbor = true;
break;
}
}
}
log.fine(output.size() + " edges after DFS");
int nIterMax = 100;
int n, sz, lastSize;
// count the number of points in edges
long sum = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0} pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum),
Long.toString(numberOfPixelsAboveThreshold)});
log.log(Level.FINE, "there are {0} edges",
Integer.toString(output.size()));
output = mergeAdjacentEndPoints(output);
log.log(Level.FINE, "{0} edges after merge adjacent",
Integer.toString(output.size()));
/*
//not necessary now that lines from CannyEdgeFilter are 1 pix width.
MiscellaneousCurveHelper ch = new MiscellaneousCurveHelper();
n = 0;
sz = output.size();
lastSize = Integer.MAX_VALUE;
while ((sz < lastSize) && (n < nIterMax)) {
lastSize = sz;
output = ch.pruneAndIncludeAdjacentCurves(output, img.getWidth());
sz = output.size();
log.log(Level.FINE, "{0}) {1} edges after prune overlapping",
new Object[]{Integer.toString(n), Integer.toString(sz)});
n++;
}
*/
// This helps to merge edges (that is extracted curves) at adjacent
// points that resemble an intersection of the lines, but it's not
// necessarily useful if only interested in corners and not inflection
// points because the curvature is determined correctly
// whether the curves are merged or not.
output = connectClosestPointsIfCanTrim(output);
log.fine(output.size() + " edges after connect closest");
output = fillInGaps(output);
log.log(Level.FINE, "{0} edges after fill in gaps",
new Object[]{Integer.toString(output.size())});
//TODO: this may need to change
removeEdgesShorterThan(output, edgeSizeLowerLimit);
sz = output.size();
log.log(Level.FINE, "{0} edges after removing those shorter",
new Object[]{Integer.toString(sz)});
long sum2 = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0}) pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum2),
Long.toString(numberOfPixelsAboveThreshold)});
//pruneSpurs(output);
adjustEdgesTowardsBrightPixels(output);
return output;
} | NONSATD | true | public List<PairIntArray> findEdges() {
// DFS search for sequential neighbors.
Stack<PairInt> stack = new Stack<PairInt>();
int thresh0 = 1;
for (int i = 0; i < img.getWidth(); i++) {
for (int j = 0; j < img.getHeight(); j++) {
//for now, choosing to look only at the blue
int bPix = img.getValue(i, j);
if (bPix >= thresh0) {
stack.add(new PairInt(i, j));
}
}
}
numberOfPixelsAboveThreshold = stack.size();
log.log(Level.FINE, "Number of pixels that exceed threshhold={0}",
Long.toString(numberOfPixelsAboveThreshold));
List<PairIntArray> output = new ArrayList<PairIntArray>();
int[] uNodeEdgeIdx = new int[img.getWidth() * img.getHeight()];
Arrays.fill(uNodeEdgeIdx, -1);
while (!stack.isEmpty()) {
PairInt uNode = stack.pop();
int uX = uNode.getX();
int uY = uNode.getY();
int uIdx = (uY * img.getWidth()) + uX;
boolean foundNeighbor = false;
// for each neighbor v of u
for (int vX = (uX - 1); vX < (uX + 2); vX++) {
if (foundNeighbor) {
break;
}
if (vX < 0 || vX > (img.getWidth() - 1)) {
continue;
}
for (int vY = (uY - 1); vY < (uY + 2); vY++) {
if (vY < 0 || vY > (img.getHeight() - 1)) {
continue;
}
int vIdx = (vY * img.getWidth()) + vX;
if (uNodeEdgeIdx[vIdx] != -1 || (uIdx == vIdx)) {
continue;
}
if (img.getValue(vX, vY) < thresh0) {
continue;
}
// if u is not in an edge already, create a new one
if (uNodeEdgeIdx[uIdx] == -1) {
PairIntArray edge = new PairIntArray();
edge.add(uX, uY);
uNodeEdgeIdx[uIdx] = output.size();
output.add(edge);
}
// keep the curve points ordered
// add v to the edge u if u is the last node in it's edge
PairIntArray appendToNode = output.get(uNodeEdgeIdx[uIdx]);
int aIdx = appendToNode.getN() - 1;
if ((appendToNode.getX(aIdx) != uX) ||
(appendToNode.getY(aIdx) != uY)) {
continue;
}
appendToNode.add(vX, vY);
uNodeEdgeIdx[vIdx] = uNodeEdgeIdx[uIdx];
//TODO: do we only want 1 neighbor from the 9 as a continuation?
// yes for now, but this requires edges be only 1 pixel wide
// inserting back at the top of the stack assures that the
// search continues next from an associated point
stack.add(new PairInt(vX, vY));
foundNeighbor = true;
break;
}
}
}
log.fine(output.size() + " edges after DFS");
int nIterMax = 100;
int n, sz, lastSize;
// count the number of points in edges
long sum = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0} pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum),
Long.toString(numberOfPixelsAboveThreshold)});
log.log(Level.FINE, "there are {0} edges",
Integer.toString(output.size()));
output = mergeAdjacentEndPoints(output);
log.log(Level.FINE, "{0} edges after merge adjacent",
Integer.toString(output.size()));
/*
//not necessary now that lines from CannyEdgeFilter are 1 pix width.
MiscellaneousCurveHelper ch = new MiscellaneousCurveHelper();
n = 0;
sz = output.size();
lastSize = Integer.MAX_VALUE;
while ((sz < lastSize) && (n < nIterMax)) {
lastSize = sz;
output = ch.pruneAndIncludeAdjacentCurves(output, img.getWidth());
sz = output.size();
log.log(Level.FINE, "{0}) {1} edges after prune overlapping",
new Object[]{Integer.toString(n), Integer.toString(sz)});
n++;
}
*/
// This helps to merge edges (that is extracted curves) at adjacent
// points that resemble an intersection of the lines, but it's not
// necessarily useful if only interested in corners and not inflection
// points because the curvature is determined correctly
// whether the curves are merged or not.
output = connectClosestPointsIfCanTrim(output);
log.fine(output.size() + " edges after connect closest");
output = fillInGaps(output);
log.log(Level.FINE, "{0} edges after fill in gaps",
new Object[]{Integer.toString(output.size())});
//TODO: this may need to change
removeEdgesShorterThan(output, edgeSizeLowerLimit);
sz = output.size();
log.log(Level.FINE, "{0} edges after removing those shorter",
new Object[]{Integer.toString(sz)});
long sum2 = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0}) pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum2),
Long.toString(numberOfPixelsAboveThreshold)});
//pruneSpurs(output);
adjustEdgesTowardsBrightPixels(output);
return output;
} | public List<PairIntArray> findEdges() {
// DFS search for sequential neighbors.
Stack<PairInt> stack = new Stack<PairInt>();
int thresh0 = 1;
for (int i = 0; i < img.getWidth(); i++) {
for (int j = 0; j < img.getHeight(); j++) {
//for now, choosing to look only at the blue
int bPix = img.getValue(i, j);
if (bPix >= thresh0) {
stack.add(new PairInt(i, j));
}
}
}
numberOfPixelsAboveThreshold = stack.size();
log.log(Level.FINE, "Number of pixels that exceed threshhold={0}",
Long.toString(numberOfPixelsAboveThreshold));
List<PairIntArray> output = new ArrayList<PairIntArray>();
int[] uNodeEdgeIdx = new int[img.getWidth() * img.getHeight()];
Arrays.fill(uNodeEdgeIdx, -1);
while (!stack.isEmpty()) {
PairInt uNode = stack.pop();
int uX = uNode.getX();
int uY = uNode.getY();
int uIdx = (uY * img.getWidth()) + uX;
boolean foundNeighbor = false;
// for each neighbor v of u
for (int vX = (uX - 1); vX < (uX + 2); vX++) {
if (foundNeighbor) {
break;
}
if (vX < 0 || vX > (img.getWidth() - 1)) {
continue;
}
for (int vY = (uY - 1); vY < (uY + 2); vY++) {
if (vY < 0 || vY > (img.getHeight() - 1)) {
continue;
}
int vIdx = (vY * img.getWidth()) + vX;
if (uNodeEdgeIdx[vIdx] != -1 || (uIdx == vIdx)) {
continue;
}
if (img.getValue(vX, vY) < thresh0) {
continue;
}
// if u is not in an edge already, create a new one
if (uNodeEdgeIdx[uIdx] == -1) {
PairIntArray edge = new PairIntArray();
edge.add(uX, uY);
uNodeEdgeIdx[uIdx] = output.size();
output.add(edge);
}
// keep the curve points ordered
// add v to the edge u if u is the last node in it's edge
PairIntArray appendToNode = output.get(uNodeEdgeIdx[uIdx]);
int aIdx = appendToNode.getN() - 1;
if ((appendToNode.getX(aIdx) != uX) ||
(appendToNode.getY(aIdx) != uY)) {
continue;
}
appendToNode.add(vX, vY);
uNodeEdgeIdx[vIdx] = uNodeEdgeIdx[uIdx];
//TODO: do we only want 1 neighbor from the 9 as a continuation?
// yes for now, but this requires edges be only 1 pixel wide
// inserting back at the top of the stack assures that the
// search continues next from an associated point
stack.add(new PairInt(vX, vY));
foundNeighbor = true;
break;
}
}
}
log.fine(output.size() + " edges after DFS");
int nIterMax = 100;
int n, sz, lastSize;
// count the number of points in edges
long sum = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0} pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum),
Long.toString(numberOfPixelsAboveThreshold)});
log.log(Level.FINE, "there are {0} edges",
Integer.toString(output.size()));
output = mergeAdjacentEndPoints(output);
log.log(Level.FINE, "{0} edges after merge adjacent",
Integer.toString(output.size()));
/*
//not necessary now that lines from CannyEdgeFilter are 1 pix width.
MiscellaneousCurveHelper ch = new MiscellaneousCurveHelper();
n = 0;
sz = output.size();
lastSize = Integer.MAX_VALUE;
while ((sz < lastSize) && (n < nIterMax)) {
lastSize = sz;
output = ch.pruneAndIncludeAdjacentCurves(output, img.getWidth());
sz = output.size();
log.log(Level.FINE, "{0}) {1} edges after prune overlapping",
new Object[]{Integer.toString(n), Integer.toString(sz)});
n++;
}
*/
// This helps to merge edges (that is extracted curves) at adjacent
// points that resemble an intersection of the lines, but it's not
// necessarily useful if only interested in corners and not inflection
// points because the curvature is determined correctly
// whether the curves are merged or not.
output = connectClosestPointsIfCanTrim(output);
log.fine(output.size() + " edges after connect closest");
output = fillInGaps(output);
log.log(Level.FINE, "{0} edges after fill in gaps",
new Object[]{Integer.toString(output.size())});
//TODO: this may need to change
removeEdgesShorterThan(output, edgeSizeLowerLimit);
sz = output.size();
log.log(Level.FINE, "{0} edges after removing those shorter",
new Object[]{Integer.toString(sz)});
long sum2 = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0}) pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum2),
Long.toString(numberOfPixelsAboveThreshold)});
//pruneSpurs(output);
adjustEdgesTowardsBrightPixels(output);
return output;
} | public List<PairIntArray> findEdges() {
// DFS search for sequential neighbors.
Stack<PairInt> stack = new Stack<PairInt>();
int thresh0 = 1;
for (int i = 0; i < img.getWidth(); i++) {
for (int j = 0; j < img.getHeight(); j++) {
//for now, choosing to look only at the blue
int bPix = img.getValue(i, j);
if (bPix >= thresh0) {
stack.add(new PairInt(i, j));
}
}
}
numberOfPixelsAboveThreshold = stack.size();
log.log(Level.FINE, "Number of pixels that exceed threshhold={0}",
Long.toString(numberOfPixelsAboveThreshold));
List<PairIntArray> output = new ArrayList<PairIntArray>();
int[] uNodeEdgeIdx = new int[img.getWidth() * img.getHeight()];
Arrays.fill(uNodeEdgeIdx, -1);
while (!stack.isEmpty()) {
PairInt uNode = stack.pop();
int uX = uNode.getX();
int uY = uNode.getY();
int uIdx = (uY * img.getWidth()) + uX;
boolean foundNeighbor = false;
// for each neighbor v of u
for (int vX = (uX - 1); vX < (uX + 2); vX++) {
if (foundNeighbor) {
break;
}
if (vX < 0 || vX > (img.getWidth() - 1)) {
continue;
}
for (int vY = (uY - 1); vY < (uY + 2); vY++) {
if (vY < 0 || vY > (img.getHeight() - 1)) {
continue;
}
int vIdx = (vY * img.getWidth()) + vX;
if (uNodeEdgeIdx[vIdx] != -1 || (uIdx == vIdx)) {
continue;
}
if (img.getValue(vX, vY) < thresh0) {
continue;
}
// if u is not in an edge already, create a new one
if (uNodeEdgeIdx[uIdx] == -1) {
PairIntArray edge = new PairIntArray();
edge.add(uX, uY);
uNodeEdgeIdx[uIdx] = output.size();
output.add(edge);
}
// keep the curve points ordered
// add v to the edge u if u is the last node in it's edge
PairIntArray appendToNode = output.get(uNodeEdgeIdx[uIdx]);
int aIdx = appendToNode.getN() - 1;
if ((appendToNode.getX(aIdx) != uX) ||
(appendToNode.getY(aIdx) != uY)) {
continue;
}
appendToNode.add(vX, vY);
uNodeEdgeIdx[vIdx] = uNodeEdgeIdx[uIdx];
//TODO: do we only want 1 neighbor from the 9 as a continuation?
// yes for now, but this requires edges be only 1 pixel wide
// inserting back at the top of the stack assures that the
// search continues next from an associated point
stack.add(new PairInt(vX, vY));
foundNeighbor = true;
break;
}
}
}
log.fine(output.size() + " edges after DFS");
int nIterMax = 100;
int n, sz, lastSize;
// count the number of points in edges
long sum = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0} pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum),
Long.toString(numberOfPixelsAboveThreshold)});
log.log(Level.FINE, "there are {0} edges",
Integer.toString(output.size()));
output = mergeAdjacentEndPoints(output);
log.log(Level.FINE, "{0} edges after merge adjacent",
Integer.toString(output.size()));
/*
//not necessary now that lines from CannyEdgeFilter are 1 pix width.
MiscellaneousCurveHelper ch = new MiscellaneousCurveHelper();
n = 0;
sz = output.size();
lastSize = Integer.MAX_VALUE;
while ((sz < lastSize) && (n < nIterMax)) {
lastSize = sz;
output = ch.pruneAndIncludeAdjacentCurves(output, img.getWidth());
sz = output.size();
log.log(Level.FINE, "{0}) {1} edges after prune overlapping",
new Object[]{Integer.toString(n), Integer.toString(sz)});
n++;
}
*/
// This helps to merge edges (that is extracted curves) at adjacent
// points that resemble an intersection of the lines, but it's not
// necessarily useful if only interested in corners and not inflection
// points because the curvature is determined correctly
// whether the curves are merged or not.
output = connectClosestPointsIfCanTrim(output);
log.fine(output.size() + " edges after connect closest");
output = fillInGaps(output);
log.log(Level.FINE, "{0} edges after fill in gaps",
new Object[]{Integer.toString(output.size())});
//TODO: this may need to change
removeEdgesShorterThan(output, edgeSizeLowerLimit);
sz = output.size();
log.log(Level.FINE, "{0} edges after removing those shorter",
new Object[]{Integer.toString(sz)});
long sum2 = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0}) pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum2),
Long.toString(numberOfPixelsAboveThreshold)});
//pruneSpurs(output);
adjustEdgesTowardsBrightPixels(output);
return output;
} |
22,775 | 1 | // DFS search for sequential neighbors. | public List<PairIntArray> findEdges() {
// DFS search for sequential neighbors.
Stack<PairInt> stack = new Stack<PairInt>();
int thresh0 = 1;
for (int i = 0; i < img.getWidth(); i++) {
for (int j = 0; j < img.getHeight(); j++) {
//for now, choosing to look only at the blue
int bPix = img.getValue(i, j);
if (bPix >= thresh0) {
stack.add(new PairInt(i, j));
}
}
}
numberOfPixelsAboveThreshold = stack.size();
log.log(Level.FINE, "Number of pixels that exceed threshhold={0}",
Long.toString(numberOfPixelsAboveThreshold));
List<PairIntArray> output = new ArrayList<PairIntArray>();
int[] uNodeEdgeIdx = new int[img.getWidth() * img.getHeight()];
Arrays.fill(uNodeEdgeIdx, -1);
while (!stack.isEmpty()) {
PairInt uNode = stack.pop();
int uX = uNode.getX();
int uY = uNode.getY();
int uIdx = (uY * img.getWidth()) + uX;
boolean foundNeighbor = false;
// for each neighbor v of u
for (int vX = (uX - 1); vX < (uX + 2); vX++) {
if (foundNeighbor) {
break;
}
if (vX < 0 || vX > (img.getWidth() - 1)) {
continue;
}
for (int vY = (uY - 1); vY < (uY + 2); vY++) {
if (vY < 0 || vY > (img.getHeight() - 1)) {
continue;
}
int vIdx = (vY * img.getWidth()) + vX;
if (uNodeEdgeIdx[vIdx] != -1 || (uIdx == vIdx)) {
continue;
}
if (img.getValue(vX, vY) < thresh0) {
continue;
}
// if u is not in an edge already, create a new one
if (uNodeEdgeIdx[uIdx] == -1) {
PairIntArray edge = new PairIntArray();
edge.add(uX, uY);
uNodeEdgeIdx[uIdx] = output.size();
output.add(edge);
}
// keep the curve points ordered
// add v to the edge u if u is the last node in it's edge
PairIntArray appendToNode = output.get(uNodeEdgeIdx[uIdx]);
int aIdx = appendToNode.getN() - 1;
if ((appendToNode.getX(aIdx) != uX) ||
(appendToNode.getY(aIdx) != uY)) {
continue;
}
appendToNode.add(vX, vY);
uNodeEdgeIdx[vIdx] = uNodeEdgeIdx[uIdx];
//TODO: do we only want 1 neighbor from the 9 as a continuation?
// yes for now, but this requires edges be only 1 pixel wide
// inserting back at the top of the stack assures that the
// search continues next from an associated point
stack.add(new PairInt(vX, vY));
foundNeighbor = true;
break;
}
}
}
log.fine(output.size() + " edges after DFS");
int nIterMax = 100;
int n, sz, lastSize;
// count the number of points in edges
long sum = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0} pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum),
Long.toString(numberOfPixelsAboveThreshold)});
log.log(Level.FINE, "there are {0} edges",
Integer.toString(output.size()));
output = mergeAdjacentEndPoints(output);
log.log(Level.FINE, "{0} edges after merge adjacent",
Integer.toString(output.size()));
/*
//not necessary now that lines from CannyEdgeFilter are 1 pix width.
MiscellaneousCurveHelper ch = new MiscellaneousCurveHelper();
n = 0;
sz = output.size();
lastSize = Integer.MAX_VALUE;
while ((sz < lastSize) && (n < nIterMax)) {
lastSize = sz;
output = ch.pruneAndIncludeAdjacentCurves(output, img.getWidth());
sz = output.size();
log.log(Level.FINE, "{0}) {1} edges after prune overlapping",
new Object[]{Integer.toString(n), Integer.toString(sz)});
n++;
}
*/
// This helps to merge edges (that is extracted curves) at adjacent
// points that resemble an intersection of the lines, but it's not
// necessarily useful if only interested in corners and not inflection
// points because the curvature is determined correctly
// whether the curves are merged or not.
output = connectClosestPointsIfCanTrim(output);
log.fine(output.size() + " edges after connect closest");
output = fillInGaps(output);
log.log(Level.FINE, "{0} edges after fill in gaps",
new Object[]{Integer.toString(output.size())});
//TODO: this may need to change
removeEdgesShorterThan(output, edgeSizeLowerLimit);
sz = output.size();
log.log(Level.FINE, "{0} edges after removing those shorter",
new Object[]{Integer.toString(sz)});
long sum2 = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0}) pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum2),
Long.toString(numberOfPixelsAboveThreshold)});
//pruneSpurs(output);
adjustEdgesTowardsBrightPixels(output);
return output;
} | NONSATD | true | public List<PairIntArray> findEdges() {
// DFS search for sequential neighbors.
Stack<PairInt> stack = new Stack<PairInt>();
int thresh0 = 1; | public List<PairIntArray> findEdges() {
// DFS search for sequential neighbors.
Stack<PairInt> stack = new Stack<PairInt>();
int thresh0 = 1;
for (int i = 0; i < img.getWidth(); i++) {
for (int j = 0; j < img.getHeight(); j++) {
//for now, choosing to look only at the blue
int bPix = img.getValue(i, j);
if (bPix >= thresh0) {
stack.add(new PairInt(i, j));
}
} | public List<PairIntArray> findEdges() {
// DFS search for sequential neighbors.
Stack<PairInt> stack = new Stack<PairInt>();
int thresh0 = 1;
for (int i = 0; i < img.getWidth(); i++) {
for (int j = 0; j < img.getHeight(); j++) {
//for now, choosing to look only at the blue
int bPix = img.getValue(i, j);
if (bPix >= thresh0) {
stack.add(new PairInt(i, j));
}
}
}
numberOfPixelsAboveThreshold = stack.size();
log.log(Level.FINE, "Number of pixels that exceed threshhold={0}",
Long.toString(numberOfPixelsAboveThreshold));
List<PairIntArray> output = new ArrayList<PairIntArray>();
int[] uNodeEdgeIdx = new int[img.getWidth() * img.getHeight()];
Arrays.fill(uNodeEdgeIdx, -1);
while (!stack.isEmpty()) {
PairInt uNode = stack.pop();
int uX = uNode.getX(); |
22,775 | 2 | //for now, choosing to look only at the blue | public List<PairIntArray> findEdges() {
// DFS search for sequential neighbors.
Stack<PairInt> stack = new Stack<PairInt>();
int thresh0 = 1;
for (int i = 0; i < img.getWidth(); i++) {
for (int j = 0; j < img.getHeight(); j++) {
//for now, choosing to look only at the blue
int bPix = img.getValue(i, j);
if (bPix >= thresh0) {
stack.add(new PairInt(i, j));
}
}
}
numberOfPixelsAboveThreshold = stack.size();
log.log(Level.FINE, "Number of pixels that exceed threshhold={0}",
Long.toString(numberOfPixelsAboveThreshold));
List<PairIntArray> output = new ArrayList<PairIntArray>();
int[] uNodeEdgeIdx = new int[img.getWidth() * img.getHeight()];
Arrays.fill(uNodeEdgeIdx, -1);
while (!stack.isEmpty()) {
PairInt uNode = stack.pop();
int uX = uNode.getX();
int uY = uNode.getY();
int uIdx = (uY * img.getWidth()) + uX;
boolean foundNeighbor = false;
// for each neighbor v of u
for (int vX = (uX - 1); vX < (uX + 2); vX++) {
if (foundNeighbor) {
break;
}
if (vX < 0 || vX > (img.getWidth() - 1)) {
continue;
}
for (int vY = (uY - 1); vY < (uY + 2); vY++) {
if (vY < 0 || vY > (img.getHeight() - 1)) {
continue;
}
int vIdx = (vY * img.getWidth()) + vX;
if (uNodeEdgeIdx[vIdx] != -1 || (uIdx == vIdx)) {
continue;
}
if (img.getValue(vX, vY) < thresh0) {
continue;
}
// if u is not in an edge already, create a new one
if (uNodeEdgeIdx[uIdx] == -1) {
PairIntArray edge = new PairIntArray();
edge.add(uX, uY);
uNodeEdgeIdx[uIdx] = output.size();
output.add(edge);
}
// keep the curve points ordered
// add v to the edge u if u is the last node in it's edge
PairIntArray appendToNode = output.get(uNodeEdgeIdx[uIdx]);
int aIdx = appendToNode.getN() - 1;
if ((appendToNode.getX(aIdx) != uX) ||
(appendToNode.getY(aIdx) != uY)) {
continue;
}
appendToNode.add(vX, vY);
uNodeEdgeIdx[vIdx] = uNodeEdgeIdx[uIdx];
//TODO: do we only want 1 neighbor from the 9 as a continuation?
// yes for now, but this requires edges be only 1 pixel wide
// inserting back at the top of the stack assures that the
// search continues next from an associated point
stack.add(new PairInt(vX, vY));
foundNeighbor = true;
break;
}
}
}
log.fine(output.size() + " edges after DFS");
int nIterMax = 100;
int n, sz, lastSize;
// count the number of points in edges
long sum = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0} pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum),
Long.toString(numberOfPixelsAboveThreshold)});
log.log(Level.FINE, "there are {0} edges",
Integer.toString(output.size()));
output = mergeAdjacentEndPoints(output);
log.log(Level.FINE, "{0} edges after merge adjacent",
Integer.toString(output.size()));
/*
//not necessary now that lines from CannyEdgeFilter are 1 pix width.
MiscellaneousCurveHelper ch = new MiscellaneousCurveHelper();
n = 0;
sz = output.size();
lastSize = Integer.MAX_VALUE;
while ((sz < lastSize) && (n < nIterMax)) {
lastSize = sz;
output = ch.pruneAndIncludeAdjacentCurves(output, img.getWidth());
sz = output.size();
log.log(Level.FINE, "{0}) {1} edges after prune overlapping",
new Object[]{Integer.toString(n), Integer.toString(sz)});
n++;
}
*/
// This helps to merge edges (that is extracted curves) at adjacent
// points that resemble an intersection of the lines, but it's not
// necessarily useful if only interested in corners and not inflection
// points because the curvature is determined correctly
// whether the curves are merged or not.
output = connectClosestPointsIfCanTrim(output);
log.fine(output.size() + " edges after connect closest");
output = fillInGaps(output);
log.log(Level.FINE, "{0} edges after fill in gaps",
new Object[]{Integer.toString(output.size())});
//TODO: this may need to change
removeEdgesShorterThan(output, edgeSizeLowerLimit);
sz = output.size();
log.log(Level.FINE, "{0} edges after removing those shorter",
new Object[]{Integer.toString(sz)});
long sum2 = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0}) pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum2),
Long.toString(numberOfPixelsAboveThreshold)});
//pruneSpurs(output);
adjustEdgesTowardsBrightPixels(output);
return output;
} | NONSATD | true | for (int i = 0; i < img.getWidth(); i++) {
for (int j = 0; j < img.getHeight(); j++) {
//for now, choosing to look only at the blue
int bPix = img.getValue(i, j);
if (bPix >= thresh0) { | public List<PairIntArray> findEdges() {
// DFS search for sequential neighbors.
Stack<PairInt> stack = new Stack<PairInt>();
int thresh0 = 1;
for (int i = 0; i < img.getWidth(); i++) {
for (int j = 0; j < img.getHeight(); j++) {
//for now, choosing to look only at the blue
int bPix = img.getValue(i, j);
if (bPix >= thresh0) {
stack.add(new PairInt(i, j));
}
}
}
numberOfPixelsAboveThreshold = stack.size();
log.log(Level.FINE, "Number of pixels that exceed threshhold={0}",
Long.toString(numberOfPixelsAboveThreshold));
List<PairIntArray> output = new ArrayList<PairIntArray>(); | public List<PairIntArray> findEdges() {
// DFS search for sequential neighbors.
Stack<PairInt> stack = new Stack<PairInt>();
int thresh0 = 1;
for (int i = 0; i < img.getWidth(); i++) {
for (int j = 0; j < img.getHeight(); j++) {
//for now, choosing to look only at the blue
int bPix = img.getValue(i, j);
if (bPix >= thresh0) {
stack.add(new PairInt(i, j));
}
}
}
numberOfPixelsAboveThreshold = stack.size();
log.log(Level.FINE, "Number of pixels that exceed threshhold={0}",
Long.toString(numberOfPixelsAboveThreshold));
List<PairIntArray> output = new ArrayList<PairIntArray>();
int[] uNodeEdgeIdx = new int[img.getWidth() * img.getHeight()];
Arrays.fill(uNodeEdgeIdx, -1);
while (!stack.isEmpty()) {
PairInt uNode = stack.pop();
int uX = uNode.getX();
int uY = uNode.getY();
int uIdx = (uY * img.getWidth()) + uX;
boolean foundNeighbor = false;
// for each neighbor v of u
for (int vX = (uX - 1); vX < (uX + 2); vX++) { |
22,775 | 3 | // for each neighbor v of u | public List<PairIntArray> findEdges() {
// DFS search for sequential neighbors.
Stack<PairInt> stack = new Stack<PairInt>();
int thresh0 = 1;
for (int i = 0; i < img.getWidth(); i++) {
for (int j = 0; j < img.getHeight(); j++) {
//for now, choosing to look only at the blue
int bPix = img.getValue(i, j);
if (bPix >= thresh0) {
stack.add(new PairInt(i, j));
}
}
}
numberOfPixelsAboveThreshold = stack.size();
log.log(Level.FINE, "Number of pixels that exceed threshhold={0}",
Long.toString(numberOfPixelsAboveThreshold));
List<PairIntArray> output = new ArrayList<PairIntArray>();
int[] uNodeEdgeIdx = new int[img.getWidth() * img.getHeight()];
Arrays.fill(uNodeEdgeIdx, -1);
while (!stack.isEmpty()) {
PairInt uNode = stack.pop();
int uX = uNode.getX();
int uY = uNode.getY();
int uIdx = (uY * img.getWidth()) + uX;
boolean foundNeighbor = false;
// for each neighbor v of u
for (int vX = (uX - 1); vX < (uX + 2); vX++) {
if (foundNeighbor) {
break;
}
if (vX < 0 || vX > (img.getWidth() - 1)) {
continue;
}
for (int vY = (uY - 1); vY < (uY + 2); vY++) {
if (vY < 0 || vY > (img.getHeight() - 1)) {
continue;
}
int vIdx = (vY * img.getWidth()) + vX;
if (uNodeEdgeIdx[vIdx] != -1 || (uIdx == vIdx)) {
continue;
}
if (img.getValue(vX, vY) < thresh0) {
continue;
}
// if u is not in an edge already, create a new one
if (uNodeEdgeIdx[uIdx] == -1) {
PairIntArray edge = new PairIntArray();
edge.add(uX, uY);
uNodeEdgeIdx[uIdx] = output.size();
output.add(edge);
}
// keep the curve points ordered
// add v to the edge u if u is the last node in it's edge
PairIntArray appendToNode = output.get(uNodeEdgeIdx[uIdx]);
int aIdx = appendToNode.getN() - 1;
if ((appendToNode.getX(aIdx) != uX) ||
(appendToNode.getY(aIdx) != uY)) {
continue;
}
appendToNode.add(vX, vY);
uNodeEdgeIdx[vIdx] = uNodeEdgeIdx[uIdx];
//TODO: do we only want 1 neighbor from the 9 as a continuation?
// yes for now, but this requires edges be only 1 pixel wide
// inserting back at the top of the stack assures that the
// search continues next from an associated point
stack.add(new PairInt(vX, vY));
foundNeighbor = true;
break;
}
}
}
log.fine(output.size() + " edges after DFS");
int nIterMax = 100;
int n, sz, lastSize;
// count the number of points in edges
long sum = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0} pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum),
Long.toString(numberOfPixelsAboveThreshold)});
log.log(Level.FINE, "there are {0} edges",
Integer.toString(output.size()));
output = mergeAdjacentEndPoints(output);
log.log(Level.FINE, "{0} edges after merge adjacent",
Integer.toString(output.size()));
/*
//not necessary now that lines from CannyEdgeFilter are 1 pix width.
MiscellaneousCurveHelper ch = new MiscellaneousCurveHelper();
n = 0;
sz = output.size();
lastSize = Integer.MAX_VALUE;
while ((sz < lastSize) && (n < nIterMax)) {
lastSize = sz;
output = ch.pruneAndIncludeAdjacentCurves(output, img.getWidth());
sz = output.size();
log.log(Level.FINE, "{0}) {1} edges after prune overlapping",
new Object[]{Integer.toString(n), Integer.toString(sz)});
n++;
}
*/
// This helps to merge edges (that is extracted curves) at adjacent
// points that resemble an intersection of the lines, but it's not
// necessarily useful if only interested in corners and not inflection
// points because the curvature is determined correctly
// whether the curves are merged or not.
output = connectClosestPointsIfCanTrim(output);
log.fine(output.size() + " edges after connect closest");
output = fillInGaps(output);
log.log(Level.FINE, "{0} edges after fill in gaps",
new Object[]{Integer.toString(output.size())});
//TODO: this may need to change
removeEdgesShorterThan(output, edgeSizeLowerLimit);
sz = output.size();
log.log(Level.FINE, "{0} edges after removing those shorter",
new Object[]{Integer.toString(sz)});
long sum2 = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0}) pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum2),
Long.toString(numberOfPixelsAboveThreshold)});
//pruneSpurs(output);
adjustEdgesTowardsBrightPixels(output);
return output;
} | NONSATD | true | int uIdx = (uY * img.getWidth()) + uX;
boolean foundNeighbor = false;
// for each neighbor v of u
for (int vX = (uX - 1); vX < (uX + 2); vX++) {
if (foundNeighbor) { | Long.toString(numberOfPixelsAboveThreshold));
List<PairIntArray> output = new ArrayList<PairIntArray>();
int[] uNodeEdgeIdx = new int[img.getWidth() * img.getHeight()];
Arrays.fill(uNodeEdgeIdx, -1);
while (!stack.isEmpty()) {
PairInt uNode = stack.pop();
int uX = uNode.getX();
int uY = uNode.getY();
int uIdx = (uY * img.getWidth()) + uX;
boolean foundNeighbor = false;
// for each neighbor v of u
for (int vX = (uX - 1); vX < (uX + 2); vX++) {
if (foundNeighbor) {
break;
}
if (vX < 0 || vX > (img.getWidth() - 1)) {
continue;
}
for (int vY = (uY - 1); vY < (uY + 2); vY++) {
if (vY < 0 || vY > (img.getHeight() - 1)) {
continue; | for (int j = 0; j < img.getHeight(); j++) {
//for now, choosing to look only at the blue
int bPix = img.getValue(i, j);
if (bPix >= thresh0) {
stack.add(new PairInt(i, j));
}
}
}
numberOfPixelsAboveThreshold = stack.size();
log.log(Level.FINE, "Number of pixels that exceed threshhold={0}",
Long.toString(numberOfPixelsAboveThreshold));
List<PairIntArray> output = new ArrayList<PairIntArray>();
int[] uNodeEdgeIdx = new int[img.getWidth() * img.getHeight()];
Arrays.fill(uNodeEdgeIdx, -1);
while (!stack.isEmpty()) {
PairInt uNode = stack.pop();
int uX = uNode.getX();
int uY = uNode.getY();
int uIdx = (uY * img.getWidth()) + uX;
boolean foundNeighbor = false;
// for each neighbor v of u
for (int vX = (uX - 1); vX < (uX + 2); vX++) {
if (foundNeighbor) {
break;
}
if (vX < 0 || vX > (img.getWidth() - 1)) {
continue;
}
for (int vY = (uY - 1); vY < (uY + 2); vY++) {
if (vY < 0 || vY > (img.getHeight() - 1)) {
continue;
}
int vIdx = (vY * img.getWidth()) + vX;
if (uNodeEdgeIdx[vIdx] != -1 || (uIdx == vIdx)) {
continue;
}
if (img.getValue(vX, vY) < thresh0) {
continue;
}
// if u is not in an edge already, create a new one
if (uNodeEdgeIdx[uIdx] == -1) { |
22,775 | 4 | // if u is not in an edge already, create a new one | public List<PairIntArray> findEdges() {
// DFS search for sequential neighbors.
Stack<PairInt> stack = new Stack<PairInt>();
int thresh0 = 1;
for (int i = 0; i < img.getWidth(); i++) {
for (int j = 0; j < img.getHeight(); j++) {
//for now, choosing to look only at the blue
int bPix = img.getValue(i, j);
if (bPix >= thresh0) {
stack.add(new PairInt(i, j));
}
}
}
numberOfPixelsAboveThreshold = stack.size();
log.log(Level.FINE, "Number of pixels that exceed threshhold={0}",
Long.toString(numberOfPixelsAboveThreshold));
List<PairIntArray> output = new ArrayList<PairIntArray>();
int[] uNodeEdgeIdx = new int[img.getWidth() * img.getHeight()];
Arrays.fill(uNodeEdgeIdx, -1);
while (!stack.isEmpty()) {
PairInt uNode = stack.pop();
int uX = uNode.getX();
int uY = uNode.getY();
int uIdx = (uY * img.getWidth()) + uX;
boolean foundNeighbor = false;
// for each neighbor v of u
for (int vX = (uX - 1); vX < (uX + 2); vX++) {
if (foundNeighbor) {
break;
}
if (vX < 0 || vX > (img.getWidth() - 1)) {
continue;
}
for (int vY = (uY - 1); vY < (uY + 2); vY++) {
if (vY < 0 || vY > (img.getHeight() - 1)) {
continue;
}
int vIdx = (vY * img.getWidth()) + vX;
if (uNodeEdgeIdx[vIdx] != -1 || (uIdx == vIdx)) {
continue;
}
if (img.getValue(vX, vY) < thresh0) {
continue;
}
// if u is not in an edge already, create a new one
if (uNodeEdgeIdx[uIdx] == -1) {
PairIntArray edge = new PairIntArray();
edge.add(uX, uY);
uNodeEdgeIdx[uIdx] = output.size();
output.add(edge);
}
// keep the curve points ordered
// add v to the edge u if u is the last node in it's edge
PairIntArray appendToNode = output.get(uNodeEdgeIdx[uIdx]);
int aIdx = appendToNode.getN() - 1;
if ((appendToNode.getX(aIdx) != uX) ||
(appendToNode.getY(aIdx) != uY)) {
continue;
}
appendToNode.add(vX, vY);
uNodeEdgeIdx[vIdx] = uNodeEdgeIdx[uIdx];
//TODO: do we only want 1 neighbor from the 9 as a continuation?
// yes for now, but this requires edges be only 1 pixel wide
// inserting back at the top of the stack assures that the
// search continues next from an associated point
stack.add(new PairInt(vX, vY));
foundNeighbor = true;
break;
}
}
}
log.fine(output.size() + " edges after DFS");
int nIterMax = 100;
int n, sz, lastSize;
// count the number of points in edges
long sum = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0} pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum),
Long.toString(numberOfPixelsAboveThreshold)});
log.log(Level.FINE, "there are {0} edges",
Integer.toString(output.size()));
output = mergeAdjacentEndPoints(output);
log.log(Level.FINE, "{0} edges after merge adjacent",
Integer.toString(output.size()));
/*
//not necessary now that lines from CannyEdgeFilter are 1 pix width.
MiscellaneousCurveHelper ch = new MiscellaneousCurveHelper();
n = 0;
sz = output.size();
lastSize = Integer.MAX_VALUE;
while ((sz < lastSize) && (n < nIterMax)) {
lastSize = sz;
output = ch.pruneAndIncludeAdjacentCurves(output, img.getWidth());
sz = output.size();
log.log(Level.FINE, "{0}) {1} edges after prune overlapping",
new Object[]{Integer.toString(n), Integer.toString(sz)});
n++;
}
*/
// This helps to merge edges (that is extracted curves) at adjacent
// points that resemble an intersection of the lines, but it's not
// necessarily useful if only interested in corners and not inflection
// points because the curvature is determined correctly
// whether the curves are merged or not.
output = connectClosestPointsIfCanTrim(output);
log.fine(output.size() + " edges after connect closest");
output = fillInGaps(output);
log.log(Level.FINE, "{0} edges after fill in gaps",
new Object[]{Integer.toString(output.size())});
//TODO: this may need to change
removeEdgesShorterThan(output, edgeSizeLowerLimit);
sz = output.size();
log.log(Level.FINE, "{0} edges after removing those shorter",
new Object[]{Integer.toString(sz)});
long sum2 = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0}) pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum2),
Long.toString(numberOfPixelsAboveThreshold)});
//pruneSpurs(output);
adjustEdgesTowardsBrightPixels(output);
return output;
} | NONSATD | true | continue;
}
// if u is not in an edge already, create a new one
if (uNodeEdgeIdx[uIdx] == -1) {
PairIntArray edge = new PairIntArray(); | if (vY < 0 || vY > (img.getHeight() - 1)) {
continue;
}
int vIdx = (vY * img.getWidth()) + vX;
if (uNodeEdgeIdx[vIdx] != -1 || (uIdx == vIdx)) {
continue;
}
if (img.getValue(vX, vY) < thresh0) {
continue;
}
// if u is not in an edge already, create a new one
if (uNodeEdgeIdx[uIdx] == -1) {
PairIntArray edge = new PairIntArray();
edge.add(uX, uY);
uNodeEdgeIdx[uIdx] = output.size();
output.add(edge);
}
// keep the curve points ordered
// add v to the edge u if u is the last node in it's edge
PairIntArray appendToNode = output.get(uNodeEdgeIdx[uIdx]);
int aIdx = appendToNode.getN() - 1; | boolean foundNeighbor = false;
// for each neighbor v of u
for (int vX = (uX - 1); vX < (uX + 2); vX++) {
if (foundNeighbor) {
break;
}
if (vX < 0 || vX > (img.getWidth() - 1)) {
continue;
}
for (int vY = (uY - 1); vY < (uY + 2); vY++) {
if (vY < 0 || vY > (img.getHeight() - 1)) {
continue;
}
int vIdx = (vY * img.getWidth()) + vX;
if (uNodeEdgeIdx[vIdx] != -1 || (uIdx == vIdx)) {
continue;
}
if (img.getValue(vX, vY) < thresh0) {
continue;
}
// if u is not in an edge already, create a new one
if (uNodeEdgeIdx[uIdx] == -1) {
PairIntArray edge = new PairIntArray();
edge.add(uX, uY);
uNodeEdgeIdx[uIdx] = output.size();
output.add(edge);
}
// keep the curve points ordered
// add v to the edge u if u is the last node in it's edge
PairIntArray appendToNode = output.get(uNodeEdgeIdx[uIdx]);
int aIdx = appendToNode.getN() - 1;
if ((appendToNode.getX(aIdx) != uX) ||
(appendToNode.getY(aIdx) != uY)) {
continue;
}
appendToNode.add(vX, vY);
uNodeEdgeIdx[vIdx] = uNodeEdgeIdx[uIdx];
//TODO: do we only want 1 neighbor from the 9 as a continuation?
// yes for now, but this requires edges be only 1 pixel wide
// inserting back at the top of the stack assures that the
// search continues next from an associated point |
22,775 | 5 | // keep the curve points ordered
// add v to the edge u if u is the last node in it's edge | public List<PairIntArray> findEdges() {
// DFS search for sequential neighbors.
Stack<PairInt> stack = new Stack<PairInt>();
int thresh0 = 1;
for (int i = 0; i < img.getWidth(); i++) {
for (int j = 0; j < img.getHeight(); j++) {
//for now, choosing to look only at the blue
int bPix = img.getValue(i, j);
if (bPix >= thresh0) {
stack.add(new PairInt(i, j));
}
}
}
numberOfPixelsAboveThreshold = stack.size();
log.log(Level.FINE, "Number of pixels that exceed threshhold={0}",
Long.toString(numberOfPixelsAboveThreshold));
List<PairIntArray> output = new ArrayList<PairIntArray>();
int[] uNodeEdgeIdx = new int[img.getWidth() * img.getHeight()];
Arrays.fill(uNodeEdgeIdx, -1);
while (!stack.isEmpty()) {
PairInt uNode = stack.pop();
int uX = uNode.getX();
int uY = uNode.getY();
int uIdx = (uY * img.getWidth()) + uX;
boolean foundNeighbor = false;
// for each neighbor v of u
for (int vX = (uX - 1); vX < (uX + 2); vX++) {
if (foundNeighbor) {
break;
}
if (vX < 0 || vX > (img.getWidth() - 1)) {
continue;
}
for (int vY = (uY - 1); vY < (uY + 2); vY++) {
if (vY < 0 || vY > (img.getHeight() - 1)) {
continue;
}
int vIdx = (vY * img.getWidth()) + vX;
if (uNodeEdgeIdx[vIdx] != -1 || (uIdx == vIdx)) {
continue;
}
if (img.getValue(vX, vY) < thresh0) {
continue;
}
// if u is not in an edge already, create a new one
if (uNodeEdgeIdx[uIdx] == -1) {
PairIntArray edge = new PairIntArray();
edge.add(uX, uY);
uNodeEdgeIdx[uIdx] = output.size();
output.add(edge);
}
// keep the curve points ordered
// add v to the edge u if u is the last node in it's edge
PairIntArray appendToNode = output.get(uNodeEdgeIdx[uIdx]);
int aIdx = appendToNode.getN() - 1;
if ((appendToNode.getX(aIdx) != uX) ||
(appendToNode.getY(aIdx) != uY)) {
continue;
}
appendToNode.add(vX, vY);
uNodeEdgeIdx[vIdx] = uNodeEdgeIdx[uIdx];
//TODO: do we only want 1 neighbor from the 9 as a continuation?
// yes for now, but this requires edges be only 1 pixel wide
// inserting back at the top of the stack assures that the
// search continues next from an associated point
stack.add(new PairInt(vX, vY));
foundNeighbor = true;
break;
}
}
}
log.fine(output.size() + " edges after DFS");
int nIterMax = 100;
int n, sz, lastSize;
// count the number of points in edges
long sum = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0} pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum),
Long.toString(numberOfPixelsAboveThreshold)});
log.log(Level.FINE, "there are {0} edges",
Integer.toString(output.size()));
output = mergeAdjacentEndPoints(output);
log.log(Level.FINE, "{0} edges after merge adjacent",
Integer.toString(output.size()));
/*
//not necessary now that lines from CannyEdgeFilter are 1 pix width.
MiscellaneousCurveHelper ch = new MiscellaneousCurveHelper();
n = 0;
sz = output.size();
lastSize = Integer.MAX_VALUE;
while ((sz < lastSize) && (n < nIterMax)) {
lastSize = sz;
output = ch.pruneAndIncludeAdjacentCurves(output, img.getWidth());
sz = output.size();
log.log(Level.FINE, "{0}) {1} edges after prune overlapping",
new Object[]{Integer.toString(n), Integer.toString(sz)});
n++;
}
*/
// This helps to merge edges (that is extracted curves) at adjacent
// points that resemble an intersection of the lines, but it's not
// necessarily useful if only interested in corners and not inflection
// points because the curvature is determined correctly
// whether the curves are merged or not.
output = connectClosestPointsIfCanTrim(output);
log.fine(output.size() + " edges after connect closest");
output = fillInGaps(output);
log.log(Level.FINE, "{0} edges after fill in gaps",
new Object[]{Integer.toString(output.size())});
//TODO: this may need to change
removeEdgesShorterThan(output, edgeSizeLowerLimit);
sz = output.size();
log.log(Level.FINE, "{0} edges after removing those shorter",
new Object[]{Integer.toString(sz)});
long sum2 = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0}) pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum2),
Long.toString(numberOfPixelsAboveThreshold)});
//pruneSpurs(output);
adjustEdgesTowardsBrightPixels(output);
return output;
} | NONSATD | true | output.add(edge);
}
// keep the curve points ordered
// add v to the edge u if u is the last node in it's edge
PairIntArray appendToNode = output.get(uNodeEdgeIdx[uIdx]);
int aIdx = appendToNode.getN() - 1; | if (img.getValue(vX, vY) < thresh0) {
continue;
}
// if u is not in an edge already, create a new one
if (uNodeEdgeIdx[uIdx] == -1) {
PairIntArray edge = new PairIntArray();
edge.add(uX, uY);
uNodeEdgeIdx[uIdx] = output.size();
output.add(edge);
}
// keep the curve points ordered
// add v to the edge u if u is the last node in it's edge
PairIntArray appendToNode = output.get(uNodeEdgeIdx[uIdx]);
int aIdx = appendToNode.getN() - 1;
if ((appendToNode.getX(aIdx) != uX) ||
(appendToNode.getY(aIdx) != uY)) {
continue;
}
appendToNode.add(vX, vY);
uNodeEdgeIdx[vIdx] = uNodeEdgeIdx[uIdx];
//TODO: do we only want 1 neighbor from the 9 as a continuation?
// yes for now, but this requires edges be only 1 pixel wide | continue;
}
for (int vY = (uY - 1); vY < (uY + 2); vY++) {
if (vY < 0 || vY > (img.getHeight() - 1)) {
continue;
}
int vIdx = (vY * img.getWidth()) + vX;
if (uNodeEdgeIdx[vIdx] != -1 || (uIdx == vIdx)) {
continue;
}
if (img.getValue(vX, vY) < thresh0) {
continue;
}
// if u is not in an edge already, create a new one
if (uNodeEdgeIdx[uIdx] == -1) {
PairIntArray edge = new PairIntArray();
edge.add(uX, uY);
uNodeEdgeIdx[uIdx] = output.size();
output.add(edge);
}
// keep the curve points ordered
// add v to the edge u if u is the last node in it's edge
PairIntArray appendToNode = output.get(uNodeEdgeIdx[uIdx]);
int aIdx = appendToNode.getN() - 1;
if ((appendToNode.getX(aIdx) != uX) ||
(appendToNode.getY(aIdx) != uY)) {
continue;
}
appendToNode.add(vX, vY);
uNodeEdgeIdx[vIdx] = uNodeEdgeIdx[uIdx];
//TODO: do we only want 1 neighbor from the 9 as a continuation?
// yes for now, but this requires edges be only 1 pixel wide
// inserting back at the top of the stack assures that the
// search continues next from an associated point
stack.add(new PairInt(vX, vY));
foundNeighbor = true;
break;
}
}
}
log.fine(output.size() + " edges after DFS");
int nIterMax = 100; |
22,775 | 6 | //TODO: do we only want 1 neighbor from the 9 as a continuation?
// yes for now, but this requires edges be only 1 pixel wide
// inserting back at the top of the stack assures that the
// search continues next from an associated point | public List<PairIntArray> findEdges() {
// DFS search for sequential neighbors.
Stack<PairInt> stack = new Stack<PairInt>();
int thresh0 = 1;
for (int i = 0; i < img.getWidth(); i++) {
for (int j = 0; j < img.getHeight(); j++) {
//for now, choosing to look only at the blue
int bPix = img.getValue(i, j);
if (bPix >= thresh0) {
stack.add(new PairInt(i, j));
}
}
}
numberOfPixelsAboveThreshold = stack.size();
log.log(Level.FINE, "Number of pixels that exceed threshhold={0}",
Long.toString(numberOfPixelsAboveThreshold));
List<PairIntArray> output = new ArrayList<PairIntArray>();
int[] uNodeEdgeIdx = new int[img.getWidth() * img.getHeight()];
Arrays.fill(uNodeEdgeIdx, -1);
while (!stack.isEmpty()) {
PairInt uNode = stack.pop();
int uX = uNode.getX();
int uY = uNode.getY();
int uIdx = (uY * img.getWidth()) + uX;
boolean foundNeighbor = false;
// for each neighbor v of u
for (int vX = (uX - 1); vX < (uX + 2); vX++) {
if (foundNeighbor) {
break;
}
if (vX < 0 || vX > (img.getWidth() - 1)) {
continue;
}
for (int vY = (uY - 1); vY < (uY + 2); vY++) {
if (vY < 0 || vY > (img.getHeight() - 1)) {
continue;
}
int vIdx = (vY * img.getWidth()) + vX;
if (uNodeEdgeIdx[vIdx] != -1 || (uIdx == vIdx)) {
continue;
}
if (img.getValue(vX, vY) < thresh0) {
continue;
}
// if u is not in an edge already, create a new one
if (uNodeEdgeIdx[uIdx] == -1) {
PairIntArray edge = new PairIntArray();
edge.add(uX, uY);
uNodeEdgeIdx[uIdx] = output.size();
output.add(edge);
}
// keep the curve points ordered
// add v to the edge u if u is the last node in it's edge
PairIntArray appendToNode = output.get(uNodeEdgeIdx[uIdx]);
int aIdx = appendToNode.getN() - 1;
if ((appendToNode.getX(aIdx) != uX) ||
(appendToNode.getY(aIdx) != uY)) {
continue;
}
appendToNode.add(vX, vY);
uNodeEdgeIdx[vIdx] = uNodeEdgeIdx[uIdx];
//TODO: do we only want 1 neighbor from the 9 as a continuation?
// yes for now, but this requires edges be only 1 pixel wide
// inserting back at the top of the stack assures that the
// search continues next from an associated point
stack.add(new PairInt(vX, vY));
foundNeighbor = true;
break;
}
}
}
log.fine(output.size() + " edges after DFS");
int nIterMax = 100;
int n, sz, lastSize;
// count the number of points in edges
long sum = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0} pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum),
Long.toString(numberOfPixelsAboveThreshold)});
log.log(Level.FINE, "there are {0} edges",
Integer.toString(output.size()));
output = mergeAdjacentEndPoints(output);
log.log(Level.FINE, "{0} edges after merge adjacent",
Integer.toString(output.size()));
/*
//not necessary now that lines from CannyEdgeFilter are 1 pix width.
MiscellaneousCurveHelper ch = new MiscellaneousCurveHelper();
n = 0;
sz = output.size();
lastSize = Integer.MAX_VALUE;
while ((sz < lastSize) && (n < nIterMax)) {
lastSize = sz;
output = ch.pruneAndIncludeAdjacentCurves(output, img.getWidth());
sz = output.size();
log.log(Level.FINE, "{0}) {1} edges after prune overlapping",
new Object[]{Integer.toString(n), Integer.toString(sz)});
n++;
}
*/
// This helps to merge edges (that is extracted curves) at adjacent
// points that resemble an intersection of the lines, but it's not
// necessarily useful if only interested in corners and not inflection
// points because the curvature is determined correctly
// whether the curves are merged or not.
output = connectClosestPointsIfCanTrim(output);
log.fine(output.size() + " edges after connect closest");
output = fillInGaps(output);
log.log(Level.FINE, "{0} edges after fill in gaps",
new Object[]{Integer.toString(output.size())});
//TODO: this may need to change
removeEdgesShorterThan(output, edgeSizeLowerLimit);
sz = output.size();
log.log(Level.FINE, "{0} edges after removing those shorter",
new Object[]{Integer.toString(sz)});
long sum2 = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0}) pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum2),
Long.toString(numberOfPixelsAboveThreshold)});
//pruneSpurs(output);
adjustEdgesTowardsBrightPixels(output);
return output;
} | DESIGN | true | appendToNode.add(vX, vY);
uNodeEdgeIdx[vIdx] = uNodeEdgeIdx[uIdx];
//TODO: do we only want 1 neighbor from the 9 as a continuation?
// yes for now, but this requires edges be only 1 pixel wide
// inserting back at the top of the stack assures that the
// search continues next from an associated point
stack.add(new PairInt(vX, vY));
foundNeighbor = true; | // keep the curve points ordered
// add v to the edge u if u is the last node in it's edge
PairIntArray appendToNode = output.get(uNodeEdgeIdx[uIdx]);
int aIdx = appendToNode.getN() - 1;
if ((appendToNode.getX(aIdx) != uX) ||
(appendToNode.getY(aIdx) != uY)) {
continue;
}
appendToNode.add(vX, vY);
uNodeEdgeIdx[vIdx] = uNodeEdgeIdx[uIdx];
//TODO: do we only want 1 neighbor from the 9 as a continuation?
// yes for now, but this requires edges be only 1 pixel wide
// inserting back at the top of the stack assures that the
// search continues next from an associated point
stack.add(new PairInt(vX, vY));
foundNeighbor = true;
break;
}
}
}
log.fine(output.size() + " edges after DFS");
int nIterMax = 100;
int n, sz, lastSize;
// count the number of points in edges | if (img.getValue(vX, vY) < thresh0) {
continue;
}
// if u is not in an edge already, create a new one
if (uNodeEdgeIdx[uIdx] == -1) {
PairIntArray edge = new PairIntArray();
edge.add(uX, uY);
uNodeEdgeIdx[uIdx] = output.size();
output.add(edge);
}
// keep the curve points ordered
// add v to the edge u if u is the last node in it's edge
PairIntArray appendToNode = output.get(uNodeEdgeIdx[uIdx]);
int aIdx = appendToNode.getN() - 1;
if ((appendToNode.getX(aIdx) != uX) ||
(appendToNode.getY(aIdx) != uY)) {
continue;
}
appendToNode.add(vX, vY);
uNodeEdgeIdx[vIdx] = uNodeEdgeIdx[uIdx];
//TODO: do we only want 1 neighbor from the 9 as a continuation?
// yes for now, but this requires edges be only 1 pixel wide
// inserting back at the top of the stack assures that the
// search continues next from an associated point
stack.add(new PairInt(vX, vY));
foundNeighbor = true;
break;
}
}
}
log.fine(output.size() + " edges after DFS");
int nIterMax = 100;
int n, sz, lastSize;
// count the number of points in edges
long sum = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0} pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum),
Long.toString(numberOfPixelsAboveThreshold)});
log.log(Level.FINE, "there are {0} edges",
Integer.toString(output.size()));
output = mergeAdjacentEndPoints(output);
log.log(Level.FINE, "{0} edges after merge adjacent",
Integer.toString(output.size())); |
22,775 | 7 | // count the number of points in edges | public List<PairIntArray> findEdges() {
// DFS search for sequential neighbors.
Stack<PairInt> stack = new Stack<PairInt>();
int thresh0 = 1;
for (int i = 0; i < img.getWidth(); i++) {
for (int j = 0; j < img.getHeight(); j++) {
//for now, choosing to look only at the blue
int bPix = img.getValue(i, j);
if (bPix >= thresh0) {
stack.add(new PairInt(i, j));
}
}
}
numberOfPixelsAboveThreshold = stack.size();
log.log(Level.FINE, "Number of pixels that exceed threshhold={0}",
Long.toString(numberOfPixelsAboveThreshold));
List<PairIntArray> output = new ArrayList<PairIntArray>();
int[] uNodeEdgeIdx = new int[img.getWidth() * img.getHeight()];
Arrays.fill(uNodeEdgeIdx, -1);
while (!stack.isEmpty()) {
PairInt uNode = stack.pop();
int uX = uNode.getX();
int uY = uNode.getY();
int uIdx = (uY * img.getWidth()) + uX;
boolean foundNeighbor = false;
// for each neighbor v of u
for (int vX = (uX - 1); vX < (uX + 2); vX++) {
if (foundNeighbor) {
break;
}
if (vX < 0 || vX > (img.getWidth() - 1)) {
continue;
}
for (int vY = (uY - 1); vY < (uY + 2); vY++) {
if (vY < 0 || vY > (img.getHeight() - 1)) {
continue;
}
int vIdx = (vY * img.getWidth()) + vX;
if (uNodeEdgeIdx[vIdx] != -1 || (uIdx == vIdx)) {
continue;
}
if (img.getValue(vX, vY) < thresh0) {
continue;
}
// if u is not in an edge already, create a new one
if (uNodeEdgeIdx[uIdx] == -1) {
PairIntArray edge = new PairIntArray();
edge.add(uX, uY);
uNodeEdgeIdx[uIdx] = output.size();
output.add(edge);
}
// keep the curve points ordered
// add v to the edge u if u is the last node in it's edge
PairIntArray appendToNode = output.get(uNodeEdgeIdx[uIdx]);
int aIdx = appendToNode.getN() - 1;
if ((appendToNode.getX(aIdx) != uX) ||
(appendToNode.getY(aIdx) != uY)) {
continue;
}
appendToNode.add(vX, vY);
uNodeEdgeIdx[vIdx] = uNodeEdgeIdx[uIdx];
//TODO: do we only want 1 neighbor from the 9 as a continuation?
// yes for now, but this requires edges be only 1 pixel wide
// inserting back at the top of the stack assures that the
// search continues next from an associated point
stack.add(new PairInt(vX, vY));
foundNeighbor = true;
break;
}
}
}
log.fine(output.size() + " edges after DFS");
int nIterMax = 100;
int n, sz, lastSize;
// count the number of points in edges
long sum = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0} pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum),
Long.toString(numberOfPixelsAboveThreshold)});
log.log(Level.FINE, "there are {0} edges",
Integer.toString(output.size()));
output = mergeAdjacentEndPoints(output);
log.log(Level.FINE, "{0} edges after merge adjacent",
Integer.toString(output.size()));
/*
//not necessary now that lines from CannyEdgeFilter are 1 pix width.
MiscellaneousCurveHelper ch = new MiscellaneousCurveHelper();
n = 0;
sz = output.size();
lastSize = Integer.MAX_VALUE;
while ((sz < lastSize) && (n < nIterMax)) {
lastSize = sz;
output = ch.pruneAndIncludeAdjacentCurves(output, img.getWidth());
sz = output.size();
log.log(Level.FINE, "{0}) {1} edges after prune overlapping",
new Object[]{Integer.toString(n), Integer.toString(sz)});
n++;
}
*/
// This helps to merge edges (that is extracted curves) at adjacent
// points that resemble an intersection of the lines, but it's not
// necessarily useful if only interested in corners and not inflection
// points because the curvature is determined correctly
// whether the curves are merged or not.
output = connectClosestPointsIfCanTrim(output);
log.fine(output.size() + " edges after connect closest");
output = fillInGaps(output);
log.log(Level.FINE, "{0} edges after fill in gaps",
new Object[]{Integer.toString(output.size())});
//TODO: this may need to change
removeEdgesShorterThan(output, edgeSizeLowerLimit);
sz = output.size();
log.log(Level.FINE, "{0} edges after removing those shorter",
new Object[]{Integer.toString(sz)});
long sum2 = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0}) pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum2),
Long.toString(numberOfPixelsAboveThreshold)});
//pruneSpurs(output);
adjustEdgesTowardsBrightPixels(output);
return output;
} | NONSATD | true | int nIterMax = 100;
int n, sz, lastSize;
// count the number of points in edges
long sum = countPixelsInEdges(output);
log.log(Level.FINE, | // search continues next from an associated point
stack.add(new PairInt(vX, vY));
foundNeighbor = true;
break;
}
}
}
log.fine(output.size() + " edges after DFS");
int nIterMax = 100;
int n, sz, lastSize;
// count the number of points in edges
long sum = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0} pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum),
Long.toString(numberOfPixelsAboveThreshold)});
log.log(Level.FINE, "there are {0} edges",
Integer.toString(output.size()));
output = mergeAdjacentEndPoints(output);
log.log(Level.FINE, "{0} edges after merge adjacent",
Integer.toString(output.size())); | int aIdx = appendToNode.getN() - 1;
if ((appendToNode.getX(aIdx) != uX) ||
(appendToNode.getY(aIdx) != uY)) {
continue;
}
appendToNode.add(vX, vY);
uNodeEdgeIdx[vIdx] = uNodeEdgeIdx[uIdx];
//TODO: do we only want 1 neighbor from the 9 as a continuation?
// yes for now, but this requires edges be only 1 pixel wide
// inserting back at the top of the stack assures that the
// search continues next from an associated point
stack.add(new PairInt(vX, vY));
foundNeighbor = true;
break;
}
}
}
log.fine(output.size() + " edges after DFS");
int nIterMax = 100;
int n, sz, lastSize;
// count the number of points in edges
long sum = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0} pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum),
Long.toString(numberOfPixelsAboveThreshold)});
log.log(Level.FINE, "there are {0} edges",
Integer.toString(output.size()));
output = mergeAdjacentEndPoints(output);
log.log(Level.FINE, "{0} edges after merge adjacent",
Integer.toString(output.size()));
/*
//not necessary now that lines from CannyEdgeFilter are 1 pix width.
MiscellaneousCurveHelper ch = new MiscellaneousCurveHelper();
n = 0;
sz = output.size();
lastSize = Integer.MAX_VALUE;
while ((sz < lastSize) && (n < nIterMax)) {
lastSize = sz;
output = ch.pruneAndIncludeAdjacentCurves(output, img.getWidth());
sz = output.size(); |
22,775 | 8 | /*
//not necessary now that lines from CannyEdgeFilter are 1 pix width.
MiscellaneousCurveHelper ch = new MiscellaneousCurveHelper();
n = 0;
sz = output.size();
lastSize = Integer.MAX_VALUE;
while ((sz < lastSize) && (n < nIterMax)) {
lastSize = sz;
output = ch.pruneAndIncludeAdjacentCurves(output, img.getWidth());
sz = output.size();
log.log(Level.FINE, "{0}) {1} edges after prune overlapping",
new Object[]{Integer.toString(n), Integer.toString(sz)});
n++;
}
*/ | public List<PairIntArray> findEdges() {
// DFS search for sequential neighbors.
Stack<PairInt> stack = new Stack<PairInt>();
int thresh0 = 1;
for (int i = 0; i < img.getWidth(); i++) {
for (int j = 0; j < img.getHeight(); j++) {
//for now, choosing to look only at the blue
int bPix = img.getValue(i, j);
if (bPix >= thresh0) {
stack.add(new PairInt(i, j));
}
}
}
numberOfPixelsAboveThreshold = stack.size();
log.log(Level.FINE, "Number of pixels that exceed threshhold={0}",
Long.toString(numberOfPixelsAboveThreshold));
List<PairIntArray> output = new ArrayList<PairIntArray>();
int[] uNodeEdgeIdx = new int[img.getWidth() * img.getHeight()];
Arrays.fill(uNodeEdgeIdx, -1);
while (!stack.isEmpty()) {
PairInt uNode = stack.pop();
int uX = uNode.getX();
int uY = uNode.getY();
int uIdx = (uY * img.getWidth()) + uX;
boolean foundNeighbor = false;
// for each neighbor v of u
for (int vX = (uX - 1); vX < (uX + 2); vX++) {
if (foundNeighbor) {
break;
}
if (vX < 0 || vX > (img.getWidth() - 1)) {
continue;
}
for (int vY = (uY - 1); vY < (uY + 2); vY++) {
if (vY < 0 || vY > (img.getHeight() - 1)) {
continue;
}
int vIdx = (vY * img.getWidth()) + vX;
if (uNodeEdgeIdx[vIdx] != -1 || (uIdx == vIdx)) {
continue;
}
if (img.getValue(vX, vY) < thresh0) {
continue;
}
// if u is not in an edge already, create a new one
if (uNodeEdgeIdx[uIdx] == -1) {
PairIntArray edge = new PairIntArray();
edge.add(uX, uY);
uNodeEdgeIdx[uIdx] = output.size();
output.add(edge);
}
// keep the curve points ordered
// add v to the edge u if u is the last node in it's edge
PairIntArray appendToNode = output.get(uNodeEdgeIdx[uIdx]);
int aIdx = appendToNode.getN() - 1;
if ((appendToNode.getX(aIdx) != uX) ||
(appendToNode.getY(aIdx) != uY)) {
continue;
}
appendToNode.add(vX, vY);
uNodeEdgeIdx[vIdx] = uNodeEdgeIdx[uIdx];
//TODO: do we only want 1 neighbor from the 9 as a continuation?
// yes for now, but this requires edges be only 1 pixel wide
// inserting back at the top of the stack assures that the
// search continues next from an associated point
stack.add(new PairInt(vX, vY));
foundNeighbor = true;
break;
}
}
}
log.fine(output.size() + " edges after DFS");
int nIterMax = 100;
int n, sz, lastSize;
// count the number of points in edges
long sum = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0} pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum),
Long.toString(numberOfPixelsAboveThreshold)});
log.log(Level.FINE, "there are {0} edges",
Integer.toString(output.size()));
output = mergeAdjacentEndPoints(output);
log.log(Level.FINE, "{0} edges after merge adjacent",
Integer.toString(output.size()));
/*
//not necessary now that lines from CannyEdgeFilter are 1 pix width.
MiscellaneousCurveHelper ch = new MiscellaneousCurveHelper();
n = 0;
sz = output.size();
lastSize = Integer.MAX_VALUE;
while ((sz < lastSize) && (n < nIterMax)) {
lastSize = sz;
output = ch.pruneAndIncludeAdjacentCurves(output, img.getWidth());
sz = output.size();
log.log(Level.FINE, "{0}) {1} edges after prune overlapping",
new Object[]{Integer.toString(n), Integer.toString(sz)});
n++;
}
*/
// This helps to merge edges (that is extracted curves) at adjacent
// points that resemble an intersection of the lines, but it's not
// necessarily useful if only interested in corners and not inflection
// points because the curvature is determined correctly
// whether the curves are merged or not.
output = connectClosestPointsIfCanTrim(output);
log.fine(output.size() + " edges after connect closest");
output = fillInGaps(output);
log.log(Level.FINE, "{0} edges after fill in gaps",
new Object[]{Integer.toString(output.size())});
//TODO: this may need to change
removeEdgesShorterThan(output, edgeSizeLowerLimit);
sz = output.size();
log.log(Level.FINE, "{0} edges after removing those shorter",
new Object[]{Integer.toString(sz)});
long sum2 = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0}) pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum2),
Long.toString(numberOfPixelsAboveThreshold)});
//pruneSpurs(output);
adjustEdgesTowardsBrightPixels(output);
return output;
} | NONSATD | true | log.log(Level.FINE, "{0} edges after merge adjacent",
Integer.toString(output.size()));
/*
//not necessary now that lines from CannyEdgeFilter are 1 pix width.
MiscellaneousCurveHelper ch = new MiscellaneousCurveHelper();
n = 0;
sz = output.size();
lastSize = Integer.MAX_VALUE;
while ((sz < lastSize) && (n < nIterMax)) {
lastSize = sz;
output = ch.pruneAndIncludeAdjacentCurves(output, img.getWidth());
sz = output.size();
log.log(Level.FINE, "{0}) {1} edges after prune overlapping",
new Object[]{Integer.toString(n), Integer.toString(sz)});
n++;
}
*/
// This helps to merge edges (that is extracted curves) at adjacent
// points that resemble an intersection of the lines, but it's not | long sum = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0} pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum),
Long.toString(numberOfPixelsAboveThreshold)});
log.log(Level.FINE, "there are {0} edges",
Integer.toString(output.size()));
output = mergeAdjacentEndPoints(output);
log.log(Level.FINE, "{0} edges after merge adjacent",
Integer.toString(output.size()));
/*
//not necessary now that lines from CannyEdgeFilter are 1 pix width.
MiscellaneousCurveHelper ch = new MiscellaneousCurveHelper();
n = 0;
sz = output.size();
lastSize = Integer.MAX_VALUE;
while ((sz < lastSize) && (n < nIterMax)) {
lastSize = sz;
output = ch.pruneAndIncludeAdjacentCurves(output, img.getWidth());
sz = output.size();
log.log(Level.FINE, "{0}) {1} edges after prune overlapping",
new Object[]{Integer.toString(n), Integer.toString(sz)});
n++;
}
*/
// This helps to merge edges (that is extracted curves) at adjacent
// points that resemble an intersection of the lines, but it's not
// necessarily useful if only interested in corners and not inflection
// points because the curvature is determined correctly
// whether the curves are merged or not.
output = connectClosestPointsIfCanTrim(output);
log.fine(output.size() + " edges after connect closest");
output = fillInGaps(output);
log.log(Level.FINE, "{0} edges after fill in gaps",
new Object[]{Integer.toString(output.size())}); | stack.add(new PairInt(vX, vY));
foundNeighbor = true;
break;
}
}
}
log.fine(output.size() + " edges after DFS");
int nIterMax = 100;
int n, sz, lastSize;
// count the number of points in edges
long sum = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0} pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum),
Long.toString(numberOfPixelsAboveThreshold)});
log.log(Level.FINE, "there are {0} edges",
Integer.toString(output.size()));
output = mergeAdjacentEndPoints(output);
log.log(Level.FINE, "{0} edges after merge adjacent",
Integer.toString(output.size()));
/*
//not necessary now that lines from CannyEdgeFilter are 1 pix width.
MiscellaneousCurveHelper ch = new MiscellaneousCurveHelper();
n = 0;
sz = output.size();
lastSize = Integer.MAX_VALUE;
while ((sz < lastSize) && (n < nIterMax)) {
lastSize = sz;
output = ch.pruneAndIncludeAdjacentCurves(output, img.getWidth());
sz = output.size();
log.log(Level.FINE, "{0}) {1} edges after prune overlapping",
new Object[]{Integer.toString(n), Integer.toString(sz)});
n++;
}
*/
// This helps to merge edges (that is extracted curves) at adjacent
// points that resemble an intersection of the lines, but it's not
// necessarily useful if only interested in corners and not inflection
// points because the curvature is determined correctly
// whether the curves are merged or not.
output = connectClosestPointsIfCanTrim(output);
log.fine(output.size() + " edges after connect closest");
output = fillInGaps(output);
log.log(Level.FINE, "{0} edges after fill in gaps",
new Object[]{Integer.toString(output.size())});
//TODO: this may need to change
removeEdgesShorterThan(output, edgeSizeLowerLimit);
sz = output.size();
log.log(Level.FINE, "{0} edges after removing those shorter",
new Object[]{Integer.toString(sz)});
long sum2 = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0}) pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum2),
Long.toString(numberOfPixelsAboveThreshold)}); |
22,775 | 9 | // This helps to merge edges (that is extracted curves) at adjacent
// points that resemble an intersection of the lines, but it's not
// necessarily useful if only interested in corners and not inflection
// points because the curvature is determined correctly
// whether the curves are merged or not. | public List<PairIntArray> findEdges() {
// DFS search for sequential neighbors.
Stack<PairInt> stack = new Stack<PairInt>();
int thresh0 = 1;
for (int i = 0; i < img.getWidth(); i++) {
for (int j = 0; j < img.getHeight(); j++) {
//for now, choosing to look only at the blue
int bPix = img.getValue(i, j);
if (bPix >= thresh0) {
stack.add(new PairInt(i, j));
}
}
}
numberOfPixelsAboveThreshold = stack.size();
log.log(Level.FINE, "Number of pixels that exceed threshhold={0}",
Long.toString(numberOfPixelsAboveThreshold));
List<PairIntArray> output = new ArrayList<PairIntArray>();
int[] uNodeEdgeIdx = new int[img.getWidth() * img.getHeight()];
Arrays.fill(uNodeEdgeIdx, -1);
while (!stack.isEmpty()) {
PairInt uNode = stack.pop();
int uX = uNode.getX();
int uY = uNode.getY();
int uIdx = (uY * img.getWidth()) + uX;
boolean foundNeighbor = false;
// for each neighbor v of u
for (int vX = (uX - 1); vX < (uX + 2); vX++) {
if (foundNeighbor) {
break;
}
if (vX < 0 || vX > (img.getWidth() - 1)) {
continue;
}
for (int vY = (uY - 1); vY < (uY + 2); vY++) {
if (vY < 0 || vY > (img.getHeight() - 1)) {
continue;
}
int vIdx = (vY * img.getWidth()) + vX;
if (uNodeEdgeIdx[vIdx] != -1 || (uIdx == vIdx)) {
continue;
}
if (img.getValue(vX, vY) < thresh0) {
continue;
}
// if u is not in an edge already, create a new one
if (uNodeEdgeIdx[uIdx] == -1) {
PairIntArray edge = new PairIntArray();
edge.add(uX, uY);
uNodeEdgeIdx[uIdx] = output.size();
output.add(edge);
}
// keep the curve points ordered
// add v to the edge u if u is the last node in it's edge
PairIntArray appendToNode = output.get(uNodeEdgeIdx[uIdx]);
int aIdx = appendToNode.getN() - 1;
if ((appendToNode.getX(aIdx) != uX) ||
(appendToNode.getY(aIdx) != uY)) {
continue;
}
appendToNode.add(vX, vY);
uNodeEdgeIdx[vIdx] = uNodeEdgeIdx[uIdx];
//TODO: do we only want 1 neighbor from the 9 as a continuation?
// yes for now, but this requires edges be only 1 pixel wide
// inserting back at the top of the stack assures that the
// search continues next from an associated point
stack.add(new PairInt(vX, vY));
foundNeighbor = true;
break;
}
}
}
log.fine(output.size() + " edges after DFS");
int nIterMax = 100;
int n, sz, lastSize;
// count the number of points in edges
long sum = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0} pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum),
Long.toString(numberOfPixelsAboveThreshold)});
log.log(Level.FINE, "there are {0} edges",
Integer.toString(output.size()));
output = mergeAdjacentEndPoints(output);
log.log(Level.FINE, "{0} edges after merge adjacent",
Integer.toString(output.size()));
/*
//not necessary now that lines from CannyEdgeFilter are 1 pix width.
MiscellaneousCurveHelper ch = new MiscellaneousCurveHelper();
n = 0;
sz = output.size();
lastSize = Integer.MAX_VALUE;
while ((sz < lastSize) && (n < nIterMax)) {
lastSize = sz;
output = ch.pruneAndIncludeAdjacentCurves(output, img.getWidth());
sz = output.size();
log.log(Level.FINE, "{0}) {1} edges after prune overlapping",
new Object[]{Integer.toString(n), Integer.toString(sz)});
n++;
}
*/
// This helps to merge edges (that is extracted curves) at adjacent
// points that resemble an intersection of the lines, but it's not
// necessarily useful if only interested in corners and not inflection
// points because the curvature is determined correctly
// whether the curves are merged or not.
output = connectClosestPointsIfCanTrim(output);
log.fine(output.size() + " edges after connect closest");
output = fillInGaps(output);
log.log(Level.FINE, "{0} edges after fill in gaps",
new Object[]{Integer.toString(output.size())});
//TODO: this may need to change
removeEdgesShorterThan(output, edgeSizeLowerLimit);
sz = output.size();
log.log(Level.FINE, "{0} edges after removing those shorter",
new Object[]{Integer.toString(sz)});
long sum2 = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0}) pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum2),
Long.toString(numberOfPixelsAboveThreshold)});
//pruneSpurs(output);
adjustEdgesTowardsBrightPixels(output);
return output;
} | NONSATD | true | }
*/
// This helps to merge edges (that is extracted curves) at adjacent
// points that resemble an intersection of the lines, but it's not
// necessarily useful if only interested in corners and not inflection
// points because the curvature is determined correctly
// whether the curves are merged or not.
output = connectClosestPointsIfCanTrim(output);
log.fine(output.size() + " edges after connect closest"); | lastSize = Integer.MAX_VALUE;
while ((sz < lastSize) && (n < nIterMax)) {
lastSize = sz;
output = ch.pruneAndIncludeAdjacentCurves(output, img.getWidth());
sz = output.size();
log.log(Level.FINE, "{0}) {1} edges after prune overlapping",
new Object[]{Integer.toString(n), Integer.toString(sz)});
n++;
}
*/
// This helps to merge edges (that is extracted curves) at adjacent
// points that resemble an intersection of the lines, but it's not
// necessarily useful if only interested in corners and not inflection
// points because the curvature is determined correctly
// whether the curves are merged or not.
output = connectClosestPointsIfCanTrim(output);
log.fine(output.size() + " edges after connect closest");
output = fillInGaps(output);
log.log(Level.FINE, "{0} edges after fill in gaps",
new Object[]{Integer.toString(output.size())});
//TODO: this may need to change
removeEdgesShorterThan(output, edgeSizeLowerLimit);
sz = output.size();
log.log(Level.FINE, "{0} edges after removing those shorter",
new Object[]{Integer.toString(sz)}); | log.log(Level.FINE, "there are {0} edges",
Integer.toString(output.size()));
output = mergeAdjacentEndPoints(output);
log.log(Level.FINE, "{0} edges after merge adjacent",
Integer.toString(output.size()));
/*
//not necessary now that lines from CannyEdgeFilter are 1 pix width.
MiscellaneousCurveHelper ch = new MiscellaneousCurveHelper();
n = 0;
sz = output.size();
lastSize = Integer.MAX_VALUE;
while ((sz < lastSize) && (n < nIterMax)) {
lastSize = sz;
output = ch.pruneAndIncludeAdjacentCurves(output, img.getWidth());
sz = output.size();
log.log(Level.FINE, "{0}) {1} edges after prune overlapping",
new Object[]{Integer.toString(n), Integer.toString(sz)});
n++;
}
*/
// This helps to merge edges (that is extracted curves) at adjacent
// points that resemble an intersection of the lines, but it's not
// necessarily useful if only interested in corners and not inflection
// points because the curvature is determined correctly
// whether the curves are merged or not.
output = connectClosestPointsIfCanTrim(output);
log.fine(output.size() + " edges after connect closest");
output = fillInGaps(output);
log.log(Level.FINE, "{0} edges after fill in gaps",
new Object[]{Integer.toString(output.size())});
//TODO: this may need to change
removeEdgesShorterThan(output, edgeSizeLowerLimit);
sz = output.size();
log.log(Level.FINE, "{0} edges after removing those shorter",
new Object[]{Integer.toString(sz)});
long sum2 = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0}) pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum2),
Long.toString(numberOfPixelsAboveThreshold)});
//pruneSpurs(output);
adjustEdgesTowardsBrightPixels(output);
return output;
} |
22,775 | 10 | //TODO: this may need to change | public List<PairIntArray> findEdges() {
// DFS search for sequential neighbors.
Stack<PairInt> stack = new Stack<PairInt>();
int thresh0 = 1;
for (int i = 0; i < img.getWidth(); i++) {
for (int j = 0; j < img.getHeight(); j++) {
//for now, choosing to look only at the blue
int bPix = img.getValue(i, j);
if (bPix >= thresh0) {
stack.add(new PairInt(i, j));
}
}
}
numberOfPixelsAboveThreshold = stack.size();
log.log(Level.FINE, "Number of pixels that exceed threshhold={0}",
Long.toString(numberOfPixelsAboveThreshold));
List<PairIntArray> output = new ArrayList<PairIntArray>();
int[] uNodeEdgeIdx = new int[img.getWidth() * img.getHeight()];
Arrays.fill(uNodeEdgeIdx, -1);
while (!stack.isEmpty()) {
PairInt uNode = stack.pop();
int uX = uNode.getX();
int uY = uNode.getY();
int uIdx = (uY * img.getWidth()) + uX;
boolean foundNeighbor = false;
// for each neighbor v of u
for (int vX = (uX - 1); vX < (uX + 2); vX++) {
if (foundNeighbor) {
break;
}
if (vX < 0 || vX > (img.getWidth() - 1)) {
continue;
}
for (int vY = (uY - 1); vY < (uY + 2); vY++) {
if (vY < 0 || vY > (img.getHeight() - 1)) {
continue;
}
int vIdx = (vY * img.getWidth()) + vX;
if (uNodeEdgeIdx[vIdx] != -1 || (uIdx == vIdx)) {
continue;
}
if (img.getValue(vX, vY) < thresh0) {
continue;
}
// if u is not in an edge already, create a new one
if (uNodeEdgeIdx[uIdx] == -1) {
PairIntArray edge = new PairIntArray();
edge.add(uX, uY);
uNodeEdgeIdx[uIdx] = output.size();
output.add(edge);
}
// keep the curve points ordered
// add v to the edge u if u is the last node in it's edge
PairIntArray appendToNode = output.get(uNodeEdgeIdx[uIdx]);
int aIdx = appendToNode.getN() - 1;
if ((appendToNode.getX(aIdx) != uX) ||
(appendToNode.getY(aIdx) != uY)) {
continue;
}
appendToNode.add(vX, vY);
uNodeEdgeIdx[vIdx] = uNodeEdgeIdx[uIdx];
//TODO: do we only want 1 neighbor from the 9 as a continuation?
// yes for now, but this requires edges be only 1 pixel wide
// inserting back at the top of the stack assures that the
// search continues next from an associated point
stack.add(new PairInt(vX, vY));
foundNeighbor = true;
break;
}
}
}
log.fine(output.size() + " edges after DFS");
int nIterMax = 100;
int n, sz, lastSize;
// count the number of points in edges
long sum = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0} pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum),
Long.toString(numberOfPixelsAboveThreshold)});
log.log(Level.FINE, "there are {0} edges",
Integer.toString(output.size()));
output = mergeAdjacentEndPoints(output);
log.log(Level.FINE, "{0} edges after merge adjacent",
Integer.toString(output.size()));
/*
//not necessary now that lines from CannyEdgeFilter are 1 pix width.
MiscellaneousCurveHelper ch = new MiscellaneousCurveHelper();
n = 0;
sz = output.size();
lastSize = Integer.MAX_VALUE;
while ((sz < lastSize) && (n < nIterMax)) {
lastSize = sz;
output = ch.pruneAndIncludeAdjacentCurves(output, img.getWidth());
sz = output.size();
log.log(Level.FINE, "{0}) {1} edges after prune overlapping",
new Object[]{Integer.toString(n), Integer.toString(sz)});
n++;
}
*/
// This helps to merge edges (that is extracted curves) at adjacent
// points that resemble an intersection of the lines, but it's not
// necessarily useful if only interested in corners and not inflection
// points because the curvature is determined correctly
// whether the curves are merged or not.
output = connectClosestPointsIfCanTrim(output);
log.fine(output.size() + " edges after connect closest");
output = fillInGaps(output);
log.log(Level.FINE, "{0} edges after fill in gaps",
new Object[]{Integer.toString(output.size())});
//TODO: this may need to change
removeEdgesShorterThan(output, edgeSizeLowerLimit);
sz = output.size();
log.log(Level.FINE, "{0} edges after removing those shorter",
new Object[]{Integer.toString(sz)});
long sum2 = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0}) pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum2),
Long.toString(numberOfPixelsAboveThreshold)});
//pruneSpurs(output);
adjustEdgesTowardsBrightPixels(output);
return output;
} | DESIGN | true | log.log(Level.FINE, "{0} edges after fill in gaps",
new Object[]{Integer.toString(output.size())});
//TODO: this may need to change
removeEdgesShorterThan(output, edgeSizeLowerLimit);
sz = output.size(); | // This helps to merge edges (that is extracted curves) at adjacent
// points that resemble an intersection of the lines, but it's not
// necessarily useful if only interested in corners and not inflection
// points because the curvature is determined correctly
// whether the curves are merged or not.
output = connectClosestPointsIfCanTrim(output);
log.fine(output.size() + " edges after connect closest");
output = fillInGaps(output);
log.log(Level.FINE, "{0} edges after fill in gaps",
new Object[]{Integer.toString(output.size())});
//TODO: this may need to change
removeEdgesShorterThan(output, edgeSizeLowerLimit);
sz = output.size();
log.log(Level.FINE, "{0} edges after removing those shorter",
new Object[]{Integer.toString(sz)});
long sum2 = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0}) pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum2),
Long.toString(numberOfPixelsAboveThreshold)});
//pruneSpurs(output); | lastSize = Integer.MAX_VALUE;
while ((sz < lastSize) && (n < nIterMax)) {
lastSize = sz;
output = ch.pruneAndIncludeAdjacentCurves(output, img.getWidth());
sz = output.size();
log.log(Level.FINE, "{0}) {1} edges after prune overlapping",
new Object[]{Integer.toString(n), Integer.toString(sz)});
n++;
}
*/
// This helps to merge edges (that is extracted curves) at adjacent
// points that resemble an intersection of the lines, but it's not
// necessarily useful if only interested in corners and not inflection
// points because the curvature is determined correctly
// whether the curves are merged or not.
output = connectClosestPointsIfCanTrim(output);
log.fine(output.size() + " edges after connect closest");
output = fillInGaps(output);
log.log(Level.FINE, "{0} edges after fill in gaps",
new Object[]{Integer.toString(output.size())});
//TODO: this may need to change
removeEdgesShorterThan(output, edgeSizeLowerLimit);
sz = output.size();
log.log(Level.FINE, "{0} edges after removing those shorter",
new Object[]{Integer.toString(sz)});
long sum2 = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0}) pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum2),
Long.toString(numberOfPixelsAboveThreshold)});
//pruneSpurs(output);
adjustEdgesTowardsBrightPixels(output);
return output;
} |
22,775 | 11 | //pruneSpurs(output); | public List<PairIntArray> findEdges() {
// DFS search for sequential neighbors.
Stack<PairInt> stack = new Stack<PairInt>();
int thresh0 = 1;
for (int i = 0; i < img.getWidth(); i++) {
for (int j = 0; j < img.getHeight(); j++) {
//for now, choosing to look only at the blue
int bPix = img.getValue(i, j);
if (bPix >= thresh0) {
stack.add(new PairInt(i, j));
}
}
}
numberOfPixelsAboveThreshold = stack.size();
log.log(Level.FINE, "Number of pixels that exceed threshhold={0}",
Long.toString(numberOfPixelsAboveThreshold));
List<PairIntArray> output = new ArrayList<PairIntArray>();
int[] uNodeEdgeIdx = new int[img.getWidth() * img.getHeight()];
Arrays.fill(uNodeEdgeIdx, -1);
while (!stack.isEmpty()) {
PairInt uNode = stack.pop();
int uX = uNode.getX();
int uY = uNode.getY();
int uIdx = (uY * img.getWidth()) + uX;
boolean foundNeighbor = false;
// for each neighbor v of u
for (int vX = (uX - 1); vX < (uX + 2); vX++) {
if (foundNeighbor) {
break;
}
if (vX < 0 || vX > (img.getWidth() - 1)) {
continue;
}
for (int vY = (uY - 1); vY < (uY + 2); vY++) {
if (vY < 0 || vY > (img.getHeight() - 1)) {
continue;
}
int vIdx = (vY * img.getWidth()) + vX;
if (uNodeEdgeIdx[vIdx] != -1 || (uIdx == vIdx)) {
continue;
}
if (img.getValue(vX, vY) < thresh0) {
continue;
}
// if u is not in an edge already, create a new one
if (uNodeEdgeIdx[uIdx] == -1) {
PairIntArray edge = new PairIntArray();
edge.add(uX, uY);
uNodeEdgeIdx[uIdx] = output.size();
output.add(edge);
}
// keep the curve points ordered
// add v to the edge u if u is the last node in it's edge
PairIntArray appendToNode = output.get(uNodeEdgeIdx[uIdx]);
int aIdx = appendToNode.getN() - 1;
if ((appendToNode.getX(aIdx) != uX) ||
(appendToNode.getY(aIdx) != uY)) {
continue;
}
appendToNode.add(vX, vY);
uNodeEdgeIdx[vIdx] = uNodeEdgeIdx[uIdx];
//TODO: do we only want 1 neighbor from the 9 as a continuation?
// yes for now, but this requires edges be only 1 pixel wide
// inserting back at the top of the stack assures that the
// search continues next from an associated point
stack.add(new PairInt(vX, vY));
foundNeighbor = true;
break;
}
}
}
log.fine(output.size() + " edges after DFS");
int nIterMax = 100;
int n, sz, lastSize;
// count the number of points in edges
long sum = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0} pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum),
Long.toString(numberOfPixelsAboveThreshold)});
log.log(Level.FINE, "there are {0} edges",
Integer.toString(output.size()));
output = mergeAdjacentEndPoints(output);
log.log(Level.FINE, "{0} edges after merge adjacent",
Integer.toString(output.size()));
/*
//not necessary now that lines from CannyEdgeFilter are 1 pix width.
MiscellaneousCurveHelper ch = new MiscellaneousCurveHelper();
n = 0;
sz = output.size();
lastSize = Integer.MAX_VALUE;
while ((sz < lastSize) && (n < nIterMax)) {
lastSize = sz;
output = ch.pruneAndIncludeAdjacentCurves(output, img.getWidth());
sz = output.size();
log.log(Level.FINE, "{0}) {1} edges after prune overlapping",
new Object[]{Integer.toString(n), Integer.toString(sz)});
n++;
}
*/
// This helps to merge edges (that is extracted curves) at adjacent
// points that resemble an intersection of the lines, but it's not
// necessarily useful if only interested in corners and not inflection
// points because the curvature is determined correctly
// whether the curves are merged or not.
output = connectClosestPointsIfCanTrim(output);
log.fine(output.size() + " edges after connect closest");
output = fillInGaps(output);
log.log(Level.FINE, "{0} edges after fill in gaps",
new Object[]{Integer.toString(output.size())});
//TODO: this may need to change
removeEdgesShorterThan(output, edgeSizeLowerLimit);
sz = output.size();
log.log(Level.FINE, "{0} edges after removing those shorter",
new Object[]{Integer.toString(sz)});
long sum2 = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0}) pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum2),
Long.toString(numberOfPixelsAboveThreshold)});
//pruneSpurs(output);
adjustEdgesTowardsBrightPixels(output);
return output;
} | NONSATD | true | new Object[]{Long.toString(sum2),
Long.toString(numberOfPixelsAboveThreshold)});
//pruneSpurs(output);
adjustEdgesTowardsBrightPixels(output);
return output; | //TODO: this may need to change
removeEdgesShorterThan(output, edgeSizeLowerLimit);
sz = output.size();
log.log(Level.FINE, "{0} edges after removing those shorter",
new Object[]{Integer.toString(sz)});
long sum2 = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0}) pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum2),
Long.toString(numberOfPixelsAboveThreshold)});
//pruneSpurs(output);
adjustEdgesTowardsBrightPixels(output);
return output;
} | // This helps to merge edges (that is extracted curves) at adjacent
// points that resemble an intersection of the lines, but it's not
// necessarily useful if only interested in corners and not inflection
// points because the curvature is determined correctly
// whether the curves are merged or not.
output = connectClosestPointsIfCanTrim(output);
log.fine(output.size() + " edges after connect closest");
output = fillInGaps(output);
log.log(Level.FINE, "{0} edges after fill in gaps",
new Object[]{Integer.toString(output.size())});
//TODO: this may need to change
removeEdgesShorterThan(output, edgeSizeLowerLimit);
sz = output.size();
log.log(Level.FINE, "{0} edges after removing those shorter",
new Object[]{Integer.toString(sz)});
long sum2 = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0}) pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum2),
Long.toString(numberOfPixelsAboveThreshold)});
//pruneSpurs(output);
adjustEdgesTowardsBrightPixels(output);
return output;
} |
22,779 | 0 | //todo refactor logic
//select direction | public void fillPath(DirectionRobot robot, int endX, int endY) {
int width = robot.getX() - endX;
int height = robot.getY() - endY;
//todo refactor logic
//select direction
AbstractRobot.Direction abstractDirection = robot.getDirection();
System.out.println("first!");
if (width < 0) {
//start on the left side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateRightComand(robot));
}
break;
case LEFT: {
this.addComand(new RotateRightComand(robot));
this.addComand(new RotateRightComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.RIGHT;
}
if (width > 0) {
//start on the right side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateLeftComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot));
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.LEFT;
}
//move X
System.out.println(width);
for (int i = 0; i < abs(width); i++) {
this.addComand(new MoveForwardComand(robot));
}
//select direction again
if (height < 0) {
//if start above end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateLeftComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateRightComand(robot));
}
break;
}
// abstractDirection = AbstractRobot.Direction.DOWN;
}
if (height > 0) {
//if start below end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot)); //done
}
break;
}
// abstractDirection = AbstractRobot.Direction.UP;
}
//move Y
System.out.println(height);
for (int i = 0; i < abs(height); i++) {
this.addComand(new MoveForwardComand(robot));
}
} | DESIGN | true | int width = robot.getX() - endX;
int height = robot.getY() - endY;
//todo refactor logic
//select direction
AbstractRobot.Direction abstractDirection = robot.getDirection();
System.out.println("first!"); | public void fillPath(DirectionRobot robot, int endX, int endY) {
int width = robot.getX() - endX;
int height = robot.getY() - endY;
//todo refactor logic
//select direction
AbstractRobot.Direction abstractDirection = robot.getDirection();
System.out.println("first!");
if (width < 0) {
//start on the left side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateRightComand(robot));
}
break;
case LEFT: { | public void fillPath(DirectionRobot robot, int endX, int endY) {
int width = robot.getX() - endX;
int height = robot.getY() - endY;
//todo refactor logic
//select direction
AbstractRobot.Direction abstractDirection = robot.getDirection();
System.out.println("first!");
if (width < 0) {
//start on the left side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateRightComand(robot));
}
break;
case LEFT: {
this.addComand(new RotateRightComand(robot));
this.addComand(new RotateRightComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.RIGHT; |
22,779 | 1 | //start on the left side | public void fillPath(DirectionRobot robot, int endX, int endY) {
int width = robot.getX() - endX;
int height = robot.getY() - endY;
//todo refactor logic
//select direction
AbstractRobot.Direction abstractDirection = robot.getDirection();
System.out.println("first!");
if (width < 0) {
//start on the left side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateRightComand(robot));
}
break;
case LEFT: {
this.addComand(new RotateRightComand(robot));
this.addComand(new RotateRightComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.RIGHT;
}
if (width > 0) {
//start on the right side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateLeftComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot));
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.LEFT;
}
//move X
System.out.println(width);
for (int i = 0; i < abs(width); i++) {
this.addComand(new MoveForwardComand(robot));
}
//select direction again
if (height < 0) {
//if start above end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateLeftComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateRightComand(robot));
}
break;
}
// abstractDirection = AbstractRobot.Direction.DOWN;
}
if (height > 0) {
//if start below end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot)); //done
}
break;
}
// abstractDirection = AbstractRobot.Direction.UP;
}
//move Y
System.out.println(height);
for (int i = 0; i < abs(height); i++) {
this.addComand(new MoveForwardComand(robot));
}
} | NONSATD | true | System.out.println("first!");
if (width < 0) {
//start on the left side
switch (abstractDirection) {
case UP: { | public void fillPath(DirectionRobot robot, int endX, int endY) {
int width = robot.getX() - endX;
int height = robot.getY() - endY;
//todo refactor logic
//select direction
AbstractRobot.Direction abstractDirection = robot.getDirection();
System.out.println("first!");
if (width < 0) {
//start on the left side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateRightComand(robot));
}
break;
case LEFT: {
this.addComand(new RotateRightComand(robot));
this.addComand(new RotateRightComand(robot));
}
break; | public void fillPath(DirectionRobot robot, int endX, int endY) {
int width = robot.getX() - endX;
int height = robot.getY() - endY;
//todo refactor logic
//select direction
AbstractRobot.Direction abstractDirection = robot.getDirection();
System.out.println("first!");
if (width < 0) {
//start on the left side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateRightComand(robot));
}
break;
case LEFT: {
this.addComand(new RotateRightComand(robot));
this.addComand(new RotateRightComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.RIGHT;
}
if (width > 0) {
//start on the right side
switch (abstractDirection) { |
22,779 | 2 | //start on the right side | public void fillPath(DirectionRobot robot, int endX, int endY) {
int width = robot.getX() - endX;
int height = robot.getY() - endY;
//todo refactor logic
//select direction
AbstractRobot.Direction abstractDirection = robot.getDirection();
System.out.println("first!");
if (width < 0) {
//start on the left side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateRightComand(robot));
}
break;
case LEFT: {
this.addComand(new RotateRightComand(robot));
this.addComand(new RotateRightComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.RIGHT;
}
if (width > 0) {
//start on the right side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateLeftComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot));
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.LEFT;
}
//move X
System.out.println(width);
for (int i = 0; i < abs(width); i++) {
this.addComand(new MoveForwardComand(robot));
}
//select direction again
if (height < 0) {
//if start above end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateLeftComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateRightComand(robot));
}
break;
}
// abstractDirection = AbstractRobot.Direction.DOWN;
}
if (height > 0) {
//if start below end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot)); //done
}
break;
}
// abstractDirection = AbstractRobot.Direction.UP;
}
//move Y
System.out.println(height);
for (int i = 0; i < abs(height); i++) {
this.addComand(new MoveForwardComand(robot));
}
} | NONSATD | true | }
if (width > 0) {
//start on the right side
switch (abstractDirection) {
case UP: { | }
break;
case DOWN: {
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.RIGHT;
}
if (width > 0) {
//start on the right side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateLeftComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: { | if (width < 0) {
//start on the left side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateRightComand(robot));
}
break;
case LEFT: {
this.addComand(new RotateRightComand(robot));
this.addComand(new RotateRightComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.RIGHT;
}
if (width > 0) {
//start on the right side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateLeftComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot));
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.LEFT;
}
//move X
System.out.println(width);
for (int i = 0; i < abs(width); i++) { |
22,779 | 3 | //move X | public void fillPath(DirectionRobot robot, int endX, int endY) {
int width = robot.getX() - endX;
int height = robot.getY() - endY;
//todo refactor logic
//select direction
AbstractRobot.Direction abstractDirection = robot.getDirection();
System.out.println("first!");
if (width < 0) {
//start on the left side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateRightComand(robot));
}
break;
case LEFT: {
this.addComand(new RotateRightComand(robot));
this.addComand(new RotateRightComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.RIGHT;
}
if (width > 0) {
//start on the right side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateLeftComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot));
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.LEFT;
}
//move X
System.out.println(width);
for (int i = 0; i < abs(width); i++) {
this.addComand(new MoveForwardComand(robot));
}
//select direction again
if (height < 0) {
//if start above end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateLeftComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateRightComand(robot));
}
break;
}
// abstractDirection = AbstractRobot.Direction.DOWN;
}
if (height > 0) {
//if start below end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot)); //done
}
break;
}
// abstractDirection = AbstractRobot.Direction.UP;
}
//move Y
System.out.println(height);
for (int i = 0; i < abs(height); i++) {
this.addComand(new MoveForwardComand(robot));
}
} | NONSATD | true | abstractDirection = AbstractRobot.Direction.LEFT;
}
//move X
System.out.println(width);
for (int i = 0; i < abs(width); i++) { | }
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot));
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.LEFT;
}
//move X
System.out.println(width);
for (int i = 0; i < abs(width); i++) {
this.addComand(new MoveForwardComand(robot));
}
//select direction again
if (height < 0) {
//if start above end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateLeftComand(robot)); | }
if (width > 0) {
//start on the right side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateLeftComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot));
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.LEFT;
}
//move X
System.out.println(width);
for (int i = 0; i < abs(width); i++) {
this.addComand(new MoveForwardComand(robot));
}
//select direction again
if (height < 0) {
//if start above end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateLeftComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateRightComand(robot));
}
break;
}
// abstractDirection = AbstractRobot.Direction.DOWN;
}
if (height > 0) { |
22,779 | 4 | //select direction again | public void fillPath(DirectionRobot robot, int endX, int endY) {
int width = robot.getX() - endX;
int height = robot.getY() - endY;
//todo refactor logic
//select direction
AbstractRobot.Direction abstractDirection = robot.getDirection();
System.out.println("first!");
if (width < 0) {
//start on the left side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateRightComand(robot));
}
break;
case LEFT: {
this.addComand(new RotateRightComand(robot));
this.addComand(new RotateRightComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.RIGHT;
}
if (width > 0) {
//start on the right side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateLeftComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot));
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.LEFT;
}
//move X
System.out.println(width);
for (int i = 0; i < abs(width); i++) {
this.addComand(new MoveForwardComand(robot));
}
//select direction again
if (height < 0) {
//if start above end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateLeftComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateRightComand(robot));
}
break;
}
// abstractDirection = AbstractRobot.Direction.DOWN;
}
if (height > 0) {
//if start below end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot)); //done
}
break;
}
// abstractDirection = AbstractRobot.Direction.UP;
}
//move Y
System.out.println(height);
for (int i = 0; i < abs(height); i++) {
this.addComand(new MoveForwardComand(robot));
}
} | NONSATD | true | this.addComand(new MoveForwardComand(robot));
}
//select direction again
if (height < 0) {
//if start above end | }
break;
}
abstractDirection = AbstractRobot.Direction.LEFT;
}
//move X
System.out.println(width);
for (int i = 0; i < abs(width); i++) {
this.addComand(new MoveForwardComand(robot));
}
//select direction again
if (height < 0) {
//if start above end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateLeftComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateRightComand(robot));
} | this.addComand(new RotateLeftComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot));
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.LEFT;
}
//move X
System.out.println(width);
for (int i = 0; i < abs(width); i++) {
this.addComand(new MoveForwardComand(robot));
}
//select direction again
if (height < 0) {
//if start above end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateLeftComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateRightComand(robot));
}
break;
}
// abstractDirection = AbstractRobot.Direction.DOWN;
}
if (height > 0) {
//if start below end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateRightComand(robot));
} |
22,779 | 5 | //if start above end | public void fillPath(DirectionRobot robot, int endX, int endY) {
int width = robot.getX() - endX;
int height = robot.getY() - endY;
//todo refactor logic
//select direction
AbstractRobot.Direction abstractDirection = robot.getDirection();
System.out.println("first!");
if (width < 0) {
//start on the left side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateRightComand(robot));
}
break;
case LEFT: {
this.addComand(new RotateRightComand(robot));
this.addComand(new RotateRightComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.RIGHT;
}
if (width > 0) {
//start on the right side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateLeftComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot));
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.LEFT;
}
//move X
System.out.println(width);
for (int i = 0; i < abs(width); i++) {
this.addComand(new MoveForwardComand(robot));
}
//select direction again
if (height < 0) {
//if start above end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateLeftComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateRightComand(robot));
}
break;
}
// abstractDirection = AbstractRobot.Direction.DOWN;
}
if (height > 0) {
//if start below end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot)); //done
}
break;
}
// abstractDirection = AbstractRobot.Direction.UP;
}
//move Y
System.out.println(height);
for (int i = 0; i < abs(height); i++) {
this.addComand(new MoveForwardComand(robot));
}
} | NONSATD | true | //select direction again
if (height < 0) {
//if start above end
switch (abstractDirection) {
case LEFT: { | }
abstractDirection = AbstractRobot.Direction.LEFT;
}
//move X
System.out.println(width);
for (int i = 0; i < abs(width); i++) {
this.addComand(new MoveForwardComand(robot));
}
//select direction again
if (height < 0) {
//if start above end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateLeftComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateRightComand(robot));
}
break;
} | break;
case DOWN: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot));
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.LEFT;
}
//move X
System.out.println(width);
for (int i = 0; i < abs(width); i++) {
this.addComand(new MoveForwardComand(robot));
}
//select direction again
if (height < 0) {
//if start above end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateLeftComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateRightComand(robot));
}
break;
}
// abstractDirection = AbstractRobot.Direction.DOWN;
}
if (height > 0) {
//if start below end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: { |
22,779 | 6 | // abstractDirection = AbstractRobot.Direction.DOWN; | public void fillPath(DirectionRobot robot, int endX, int endY) {
int width = robot.getX() - endX;
int height = robot.getY() - endY;
//todo refactor logic
//select direction
AbstractRobot.Direction abstractDirection = robot.getDirection();
System.out.println("first!");
if (width < 0) {
//start on the left side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateRightComand(robot));
}
break;
case LEFT: {
this.addComand(new RotateRightComand(robot));
this.addComand(new RotateRightComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.RIGHT;
}
if (width > 0) {
//start on the right side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateLeftComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot));
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.LEFT;
}
//move X
System.out.println(width);
for (int i = 0; i < abs(width); i++) {
this.addComand(new MoveForwardComand(robot));
}
//select direction again
if (height < 0) {
//if start above end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateLeftComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateRightComand(robot));
}
break;
}
// abstractDirection = AbstractRobot.Direction.DOWN;
}
if (height > 0) {
//if start below end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot)); //done
}
break;
}
// abstractDirection = AbstractRobot.Direction.UP;
}
//move Y
System.out.println(height);
for (int i = 0; i < abs(height); i++) {
this.addComand(new MoveForwardComand(robot));
}
} | NONSATD | true | break;
}
// abstractDirection = AbstractRobot.Direction.DOWN;
}
if (height > 0) { | switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateLeftComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateRightComand(robot));
}
break;
}
// abstractDirection = AbstractRobot.Direction.DOWN;
}
if (height > 0) {
//if start below end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot)); //done | abstractDirection = AbstractRobot.Direction.LEFT;
}
//move X
System.out.println(width);
for (int i = 0; i < abs(width); i++) {
this.addComand(new MoveForwardComand(robot));
}
//select direction again
if (height < 0) {
//if start above end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateLeftComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateRightComand(robot));
}
break;
}
// abstractDirection = AbstractRobot.Direction.DOWN;
}
if (height > 0) {
//if start below end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot)); //done
}
break;
}
// abstractDirection = AbstractRobot.Direction.UP;
}
//move Y
System.out.println(height);
for (int i = 0; i < abs(height); i++) {
this.addComand(new MoveForwardComand(robot));
} |
22,779 | 7 | //if start below end | public void fillPath(DirectionRobot robot, int endX, int endY) {
int width = robot.getX() - endX;
int height = robot.getY() - endY;
//todo refactor logic
//select direction
AbstractRobot.Direction abstractDirection = robot.getDirection();
System.out.println("first!");
if (width < 0) {
//start on the left side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateRightComand(robot));
}
break;
case LEFT: {
this.addComand(new RotateRightComand(robot));
this.addComand(new RotateRightComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.RIGHT;
}
if (width > 0) {
//start on the right side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateLeftComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot));
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.LEFT;
}
//move X
System.out.println(width);
for (int i = 0; i < abs(width); i++) {
this.addComand(new MoveForwardComand(robot));
}
//select direction again
if (height < 0) {
//if start above end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateLeftComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateRightComand(robot));
}
break;
}
// abstractDirection = AbstractRobot.Direction.DOWN;
}
if (height > 0) {
//if start below end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot)); //done
}
break;
}
// abstractDirection = AbstractRobot.Direction.UP;
}
//move Y
System.out.println(height);
for (int i = 0; i < abs(height); i++) {
this.addComand(new MoveForwardComand(robot));
}
} | NONSATD | true | }
if (height > 0) {
//if start below end
switch (abstractDirection) {
case LEFT: { | }
break;
case RIGHT: {
this.addComand(new RotateRightComand(robot));
}
break;
}
// abstractDirection = AbstractRobot.Direction.DOWN;
}
if (height > 0) {
//if start below end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot)); //done
}
break;
} | System.out.println(width);
for (int i = 0; i < abs(width); i++) {
this.addComand(new MoveForwardComand(robot));
}
//select direction again
if (height < 0) {
//if start above end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateLeftComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateRightComand(robot));
}
break;
}
// abstractDirection = AbstractRobot.Direction.DOWN;
}
if (height > 0) {
//if start below end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot)); //done
}
break;
}
// abstractDirection = AbstractRobot.Direction.UP;
}
//move Y
System.out.println(height);
for (int i = 0; i < abs(height); i++) {
this.addComand(new MoveForwardComand(robot));
}
} |
22,779 | 8 | //done | public void fillPath(DirectionRobot robot, int endX, int endY) {
int width = robot.getX() - endX;
int height = robot.getY() - endY;
//todo refactor logic
//select direction
AbstractRobot.Direction abstractDirection = robot.getDirection();
System.out.println("first!");
if (width < 0) {
//start on the left side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateRightComand(robot));
}
break;
case LEFT: {
this.addComand(new RotateRightComand(robot));
this.addComand(new RotateRightComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.RIGHT;
}
if (width > 0) {
//start on the right side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateLeftComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot));
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.LEFT;
}
//move X
System.out.println(width);
for (int i = 0; i < abs(width); i++) {
this.addComand(new MoveForwardComand(robot));
}
//select direction again
if (height < 0) {
//if start above end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateLeftComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateRightComand(robot));
}
break;
}
// abstractDirection = AbstractRobot.Direction.DOWN;
}
if (height > 0) {
//if start below end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot)); //done
}
break;
}
// abstractDirection = AbstractRobot.Direction.UP;
}
//move Y
System.out.println(height);
for (int i = 0; i < abs(height); i++) {
this.addComand(new MoveForwardComand(robot));
}
} | NONSATD | true | break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot)); //done
}
break; | // abstractDirection = AbstractRobot.Direction.DOWN;
}
if (height > 0) {
//if start below end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot)); //done
}
break;
}
// abstractDirection = AbstractRobot.Direction.UP;
}
//move Y
System.out.println(height);
for (int i = 0; i < abs(height); i++) {
this.addComand(new MoveForwardComand(robot));
} | switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateLeftComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateRightComand(robot));
}
break;
}
// abstractDirection = AbstractRobot.Direction.DOWN;
}
if (height > 0) {
//if start below end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot)); //done
}
break;
}
// abstractDirection = AbstractRobot.Direction.UP;
}
//move Y
System.out.println(height);
for (int i = 0; i < abs(height); i++) {
this.addComand(new MoveForwardComand(robot));
}
} |
22,779 | 9 | // abstractDirection = AbstractRobot.Direction.UP; | public void fillPath(DirectionRobot robot, int endX, int endY) {
int width = robot.getX() - endX;
int height = robot.getY() - endY;
//todo refactor logic
//select direction
AbstractRobot.Direction abstractDirection = robot.getDirection();
System.out.println("first!");
if (width < 0) {
//start on the left side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateRightComand(robot));
}
break;
case LEFT: {
this.addComand(new RotateRightComand(robot));
this.addComand(new RotateRightComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.RIGHT;
}
if (width > 0) {
//start on the right side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateLeftComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot));
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.LEFT;
}
//move X
System.out.println(width);
for (int i = 0; i < abs(width); i++) {
this.addComand(new MoveForwardComand(robot));
}
//select direction again
if (height < 0) {
//if start above end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateLeftComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateRightComand(robot));
}
break;
}
// abstractDirection = AbstractRobot.Direction.DOWN;
}
if (height > 0) {
//if start below end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot)); //done
}
break;
}
// abstractDirection = AbstractRobot.Direction.UP;
}
//move Y
System.out.println(height);
for (int i = 0; i < abs(height); i++) {
this.addComand(new MoveForwardComand(robot));
}
} | NONSATD | true | break;
}
// abstractDirection = AbstractRobot.Direction.UP;
}
//move Y | switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot)); //done
}
break;
}
// abstractDirection = AbstractRobot.Direction.UP;
}
//move Y
System.out.println(height);
for (int i = 0; i < abs(height); i++) {
this.addComand(new MoveForwardComand(robot));
}
} | break;
case RIGHT: {
this.addComand(new RotateRightComand(robot));
}
break;
}
// abstractDirection = AbstractRobot.Direction.DOWN;
}
if (height > 0) {
//if start below end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot)); //done
}
break;
}
// abstractDirection = AbstractRobot.Direction.UP;
}
//move Y
System.out.println(height);
for (int i = 0; i < abs(height); i++) {
this.addComand(new MoveForwardComand(robot));
}
} |
22,779 | 10 | //move Y | public void fillPath(DirectionRobot robot, int endX, int endY) {
int width = robot.getX() - endX;
int height = robot.getY() - endY;
//todo refactor logic
//select direction
AbstractRobot.Direction abstractDirection = robot.getDirection();
System.out.println("first!");
if (width < 0) {
//start on the left side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateRightComand(robot));
}
break;
case LEFT: {
this.addComand(new RotateRightComand(robot));
this.addComand(new RotateRightComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.RIGHT;
}
if (width > 0) {
//start on the right side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateLeftComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot));
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.LEFT;
}
//move X
System.out.println(width);
for (int i = 0; i < abs(width); i++) {
this.addComand(new MoveForwardComand(robot));
}
//select direction again
if (height < 0) {
//if start above end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateLeftComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateRightComand(robot));
}
break;
}
// abstractDirection = AbstractRobot.Direction.DOWN;
}
if (height > 0) {
//if start below end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot)); //done
}
break;
}
// abstractDirection = AbstractRobot.Direction.UP;
}
//move Y
System.out.println(height);
for (int i = 0; i < abs(height); i++) {
this.addComand(new MoveForwardComand(robot));
}
} | NONSATD | true | // abstractDirection = AbstractRobot.Direction.UP;
}
//move Y
System.out.println(height);
for (int i = 0; i < abs(height); i++) { | this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot)); //done
}
break;
}
// abstractDirection = AbstractRobot.Direction.UP;
}
//move Y
System.out.println(height);
for (int i = 0; i < abs(height); i++) {
this.addComand(new MoveForwardComand(robot));
}
} | this.addComand(new RotateRightComand(robot));
}
break;
}
// abstractDirection = AbstractRobot.Direction.DOWN;
}
if (height > 0) {
//if start below end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot)); //done
}
break;
}
// abstractDirection = AbstractRobot.Direction.UP;
}
//move Y
System.out.println(height);
for (int i = 0; i < abs(height); i++) {
this.addComand(new MoveForwardComand(robot));
}
} |
14,588 | 0 | /** test solve */ | public void testSolve() {
RealMatrixImpl m = new RealMatrixImpl(testData);
RealMatrix mInv = new RealMatrixImpl(testDataInv);
// being a bit slothful here -- actually testing that X = A^-1 * B
assertClose("inverse-operate",mInv.operate(testVector),
m.solve(testVector),normTolerance);
try {
m.solve(testVector2);
fail("expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
;
}
RealMatrix bs = new RealMatrixImpl(bigSingular);
try {
bs.solve(bs);
fail("Expecting InvalidMatrixException");
} catch (InvalidMatrixException ex) {
;
}
try {
m.solve(bs);
fail("Expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
;
}
try {
new RealMatrixImpl(testData2).solve(bs);
fail("Expecting illegalArgumentException");
} catch (IllegalArgumentException ex) {
;
}
try {
(new RealMatrixImpl(testData2)).luDecompose();
fail("Expecting InvalidMatrixException");
} catch (InvalidMatrixException ex) {
;
}
} | NONSATD | true | public void testSolve() {
RealMatrixImpl m = new RealMatrixImpl(testData);
RealMatrix mInv = new RealMatrixImpl(testDataInv);
// being a bit slothful here -- actually testing that X = A^-1 * B
assertClose("inverse-operate",mInv.operate(testVector),
m.solve(testVector),normTolerance);
try {
m.solve(testVector2);
fail("expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
;
}
RealMatrix bs = new RealMatrixImpl(bigSingular);
try {
bs.solve(bs);
fail("Expecting InvalidMatrixException");
} catch (InvalidMatrixException ex) {
;
}
try {
m.solve(bs);
fail("Expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
;
}
try {
new RealMatrixImpl(testData2).solve(bs);
fail("Expecting illegalArgumentException");
} catch (IllegalArgumentException ex) {
;
}
try {
(new RealMatrixImpl(testData2)).luDecompose();
fail("Expecting InvalidMatrixException");
} catch (InvalidMatrixException ex) {
;
}
} | public void testSolve() {
RealMatrixImpl m = new RealMatrixImpl(testData);
RealMatrix mInv = new RealMatrixImpl(testDataInv);
// being a bit slothful here -- actually testing that X = A^-1 * B
assertClose("inverse-operate",mInv.operate(testVector),
m.solve(testVector),normTolerance);
try {
m.solve(testVector2);
fail("expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
;
}
RealMatrix bs = new RealMatrixImpl(bigSingular);
try {
bs.solve(bs);
fail("Expecting InvalidMatrixException");
} catch (InvalidMatrixException ex) {
;
}
try {
m.solve(bs);
fail("Expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
;
}
try {
new RealMatrixImpl(testData2).solve(bs);
fail("Expecting illegalArgumentException");
} catch (IllegalArgumentException ex) {
;
}
try {
(new RealMatrixImpl(testData2)).luDecompose();
fail("Expecting InvalidMatrixException");
} catch (InvalidMatrixException ex) {
;
}
} | public void testSolve() {
RealMatrixImpl m = new RealMatrixImpl(testData);
RealMatrix mInv = new RealMatrixImpl(testDataInv);
// being a bit slothful here -- actually testing that X = A^-1 * B
assertClose("inverse-operate",mInv.operate(testVector),
m.solve(testVector),normTolerance);
try {
m.solve(testVector2);
fail("expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
;
}
RealMatrix bs = new RealMatrixImpl(bigSingular);
try {
bs.solve(bs);
fail("Expecting InvalidMatrixException");
} catch (InvalidMatrixException ex) {
;
}
try {
m.solve(bs);
fail("Expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
;
}
try {
new RealMatrixImpl(testData2).solve(bs);
fail("Expecting illegalArgumentException");
} catch (IllegalArgumentException ex) {
;
}
try {
(new RealMatrixImpl(testData2)).luDecompose();
fail("Expecting InvalidMatrixException");
} catch (InvalidMatrixException ex) {
;
}
} |
14,588 | 1 | // being a bit slothful here -- actually testing that X = A^-1 * B | public void testSolve() {
RealMatrixImpl m = new RealMatrixImpl(testData);
RealMatrix mInv = new RealMatrixImpl(testDataInv);
// being a bit slothful here -- actually testing that X = A^-1 * B
assertClose("inverse-operate",mInv.operate(testVector),
m.solve(testVector),normTolerance);
try {
m.solve(testVector2);
fail("expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
;
}
RealMatrix bs = new RealMatrixImpl(bigSingular);
try {
bs.solve(bs);
fail("Expecting InvalidMatrixException");
} catch (InvalidMatrixException ex) {
;
}
try {
m.solve(bs);
fail("Expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
;
}
try {
new RealMatrixImpl(testData2).solve(bs);
fail("Expecting illegalArgumentException");
} catch (IllegalArgumentException ex) {
;
}
try {
(new RealMatrixImpl(testData2)).luDecompose();
fail("Expecting InvalidMatrixException");
} catch (InvalidMatrixException ex) {
;
}
} | DESIGN | true | RealMatrixImpl m = new RealMatrixImpl(testData);
RealMatrix mInv = new RealMatrixImpl(testDataInv);
// being a bit slothful here -- actually testing that X = A^-1 * B
assertClose("inverse-operate",mInv.operate(testVector),
m.solve(testVector),normTolerance); | public void testSolve() {
RealMatrixImpl m = new RealMatrixImpl(testData);
RealMatrix mInv = new RealMatrixImpl(testDataInv);
// being a bit slothful here -- actually testing that X = A^-1 * B
assertClose("inverse-operate",mInv.operate(testVector),
m.solve(testVector),normTolerance);
try {
m.solve(testVector2);
fail("expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
;
}
RealMatrix bs = new RealMatrixImpl(bigSingular);
try { | public void testSolve() {
RealMatrixImpl m = new RealMatrixImpl(testData);
RealMatrix mInv = new RealMatrixImpl(testDataInv);
// being a bit slothful here -- actually testing that X = A^-1 * B
assertClose("inverse-operate",mInv.operate(testVector),
m.solve(testVector),normTolerance);
try {
m.solve(testVector2);
fail("expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
;
}
RealMatrix bs = new RealMatrixImpl(bigSingular);
try {
bs.solve(bs);
fail("Expecting InvalidMatrixException");
} catch (InvalidMatrixException ex) {
;
}
try {
m.solve(bs);
fail("Expecting IllegalArgumentException");
} catch (IllegalArgumentException ex) {
; |
30,989 | 0 | /**
* @param s: input string
* @return: the longest palindromic substring
*/ | public String longestPalindrome(String s) {
// TODO:write your code here
return "";
} | NONSATD | true | public String longestPalindrome(String s) {
// TODO:write your code here
return "";
} | public String longestPalindrome(String s) {
// TODO:write your code here
return "";
} | public String longestPalindrome(String s) {
// TODO:write your code here
return "";
} |
30,989 | 1 | // TODO:write your code here | public String longestPalindrome(String s) {
// TODO:write your code here
return "";
} | IMPLEMENTATION | true | public String longestPalindrome(String s) {
// TODO:write your code here
return "";
} | public String longestPalindrome(String s) {
// TODO:write your code here
return "";
} | public String longestPalindrome(String s) {
// TODO:write your code here
return "";
} |
30,992 | 0 | /**
* Executes the PNGOut, OptiPNG, and AdvPNG optimization programs on the
* working file passed into the constructor.
*
* @return The optimized file.
* @throws IOException If there was an issue reading / writing to the
* file system
* @throws InterruptedException If the optimization was interrupted.
*/ | 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);
} | NONSATD | true | 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();
// 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();
// 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);
} |