iam a beginner in Programming and trying to make a Cleaning Robot NXT
i attached ( Ultrasonic Sensor) ,and ( Sound Sensor )
the job of the Robot is that when i Clap it have to start moving Forward and when the UltraSonic Sensor sees Something on the way it must turns around and keep going Forward .
The Problem is that when it turns it doesn't keep moving Forward till i clap again !!!!!
and this is the code that i wrote :
public static void main(String[] args) {
// TODO Auto-generated method stub
TouchSensor touch = new TouchSensor(SensorPort.S2);
SoundSensor sound = new SoundSensor( SensorPort.S4 );
UltrasonicSensor sonic = new UltrasonicSensor( SensorPort.S3);
Motor.A.setSpeed( 400 );
Motor.C.setSpeed( 400 );
Button.waitForAnyPress();
int SoundValue;
SoundValue = sound.readValue();
System.out.print(SoundValue);
do {
if ( sound.readValue() > 50 ) {
// PROBLEM:
while ( sonic.getDistance() > 30 ){
Motor.B.backward();
Motor.A.backward();
Motor.C.backward();
}
{
Motor.A.rotate( -185, true );
Motor.C.rotate( 185, true );
}
};
}
while( Button.readButtons() != Button.ID_ESCAPE );
}
Can any one help solving this Problem please?????
thnx Any way .
The think the loop is slightly wrong...
Basically, I think you need a flag to indicate that the bot should be moving, so that when you clap, it flips the flag...
boolean move = false;
do {
if ( sound.readValue() > 50 ) {
move = !move;
}
while ( sonic.getDistance() > 30 ){
Motor.B.backward();
Motor.A.backward();
Motor.C.backward();
}
if (move) {
Motor.A.rotate( -185, true );
Motor.C.rotate( 185, true );
}
} while( Button.readButtons() != Button.ID_ESCAPE );
Or something similar. Otherwise, it will only move when there is another sound
I'd also just like to say, I'm very jealous ;)
Related
I have a table whose rows are filtered based on a text input.
I recently put the predicate in a delayed system (full code below) to avoid freezing the UI while the large dataset is filtered.
I can generate the following exception by spamming the filter input text box right as the program launches. As you will see, the entire exception takes place within Oracle's code base. I don't see any of my project's classes on the stacktrace.
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at javafx.collections.transformation.SortedList$Element.access$200(SortedList.java:272)
at javafx.collections.transformation.SortedList.get(SortedList.java:170)
at javafx.scene.control.TableColumn.getCellObservableValue(TableColumn.java:562)
at javafx.scene.control.TableCell.updateItem(TableCell.java:644)
at javafx.scene.control.TableCell.indexChanged(TableCell.java:468)
at javafx.scene.control.IndexedCell.updateIndex(IndexedCell.java:116)
at com.sun.javafx.scene.control.skin.TableRowSkinBase.requestCellUpdate(TableRowSkinBase.java:659)
at com.sun.javafx.scene.control.skin.TableRowSkinBase.lambda$init$0(TableRowSkinBase.java:159)
at com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(ExpressionHelper.java:137)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
at javafx.beans.property.ObjectPropertyBase.fireValueChangedEvent(ObjectPropertyBase.java:105)
at javafx.beans.property.ObjectPropertyBase.markInvalid(ObjectPropertyBase.java:112)
at javafx.beans.property.ObjectPropertyBase.set(ObjectPropertyBase.java:146)
at javafx.scene.control.Cell.setItem(Cell.java:403)
at javafx.scene.control.Cell.updateItem(Cell.java:670)
at javafx.scene.control.TableRow.updateItem(TableRow.java:259)
at javafx.scene.control.TableRow.indexChanged(TableRow.java:225)
at javafx.scene.control.IndexedCell.updateIndex(IndexedCell.java:116)
at com.sun.javafx.scene.control.skin.VirtualFlow.setCellIndex(VirtualFlow.java:1957)
at com.sun.javafx.scene.control.skin.VirtualFlow.addTrailingCells(VirtualFlow.java:1344)
at com.sun.javafx.scene.control.skin.VirtualFlow.layoutChildren(VirtualFlow.java:1197)
at com.sun.javafx.scene.control.skin.VirtualFlow.setCellCount(VirtualFlow.java:231)
at com.sun.javafx.scene.control.skin.TableViewSkinBase.updateRowCount(TableViewSkinBase.java:567)
at com.sun.javafx.scene.control.skin.VirtualContainerBase.checkState(VirtualContainerBase.java:113)
at com.sun.javafx.scene.control.skin.VirtualContainerBase.layoutChildren(VirtualContainerBase.java:108)
at com.sun.javafx.scene.control.skin.TableViewSkinBase.layoutChildren(TableViewSkinBase.java:696)
at javafx.scene.control.Control.layoutChildren(Control.java:578)
at javafx.scene.Parent.layout(Parent.java:1087)
at javafx.scene.Parent.layout(Parent.java:1093)
at javafx.scene.Parent.layout(Parent.java:1093)
at javafx.scene.Parent.layout(Parent.java:1093)
at javafx.scene.Parent.layout(Parent.java:1093)
at javafx.scene.Parent.layout(Parent.java:1093)
at javafx.scene.Parent.layout(Parent.java:1093)
at javafx.scene.Parent.layout(Parent.java:1093)
at javafx.scene.Scene.doLayoutPass(Scene.java:552)
at javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2397)
at com.sun.javafx.tk.Toolkit.lambda$runPulse$3(Toolkit.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.Toolkit.runPulse(Toolkit.java:354)
at com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:381)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:510)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:490)
at com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$11(QuantumToolkit.java:319)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
at com.sun.glass.ui.gtk.GtkApplication.lambda$null$5(GtkApplication.java:139)
at java.lang.Thread.run(Thread.java:748)
The code I recently added is this, replacing the normal way of doing filtering of a table. The basic idea is to avoid applying predicates that aren't necessary.
import java.text.Normalizer;
import java.util.ArrayList;
import javafx.collections.transformation.FilteredList;
import net.joshuad.hypnos.Album;
public class ThrottledAlbumFilter {
private String requestedFilter = "";
private long timeRequestMadeMS = 0;
private Thread filterThread;
private boolean interruptFiltering = false;
private String currentAppliedFilter = "";
private FilteredList <Album> filteredList;
public ThrottledAlbumFilter ( FilteredList <Album> filteredList ) {
this.filteredList = filteredList;
filterThread = new Thread ( () -> {
while ( true ) {
String filter = requestedFilter;
if ( !filter.equals( currentAppliedFilter ) ) {
if ( System.currentTimeMillis() >= timeRequestMadeMS + 100 ) {
interruptFiltering = false;
setPredicate( filter );
currentAppliedFilter = filter;
}
}
try { Thread.sleep( 25 ); } catch ( InterruptedException e ) {}
}
});
filterThread.setDaemon( true );
filterThread.start();
}
public void setFilter ( String filter ) {
if ( filter == null ) filter = "";
timeRequestMadeMS = System.currentTimeMillis();
this.requestedFilter = filter;
interruptFiltering = true;
}
private void setPredicate ( String filterText ) {
filteredList.setPredicate( album -> {
if ( interruptFiltering ) return true;
if ( filterText.isEmpty() ) return true;
ArrayList <String> matchableText = new ArrayList <String>();
matchableText.add( album.getAlbumArtist().toLowerCase() );
matchableText.add( album.getYear().toLowerCase() );
matchableText.add( album.getFullAlbumTitle().toLowerCase() );
matchableText.add( Normalizer.normalize( album.getFullAlbumTitle(), Normalizer.Form.NFD )
.replaceAll( "[^\\p{ASCII}]", "" ).toLowerCase()
);
matchableText.add( Normalizer.normalize( album.getYear(), Normalizer.Form.NFD )
.replaceAll( "[^\\p{ASCII}]", "" ).toLowerCase()
);
matchableText.add( Normalizer.normalize( album.getAlbumArtist(), Normalizer.Form.NFD )
.replaceAll( "[^\\p{ASCII}]", "" ).toLowerCase()
);
String[] lowerCaseFilterTokens = filterText.toLowerCase().split( "\\s+" );
for ( String token : lowerCaseFilterTokens ) {
boolean tokenMatches = false;
for ( String test : matchableText ) {
if ( test.contains( token ) ) {
tokenMatches = true;
}
}
if ( !tokenMatches ) {
return false;
}
}
return true;
});
}
}
The previous version was heavily tested and had no problems. Now, I can generate it pretty dependably by quickly changing the filter text a lot right as the program is starting. I have to assume the crash is arising as a result of this changed code, but since my stack trace doesn't reference my codebase at all, I'm not really sure where to start.
edit: Interestingly, changing that sleep to 50ms from 25ms seems to squash the bug on my computer. That makes me very nervous, because I have to imagine the "right" value is different for different speed systems.
This is definitely concurrency issue.
The TableView is trying to render during a render pulse, and the backing list is changing when this is happening. NullPointerException is being thrown because the Element object holding the actual element has "mysteriously" disappeared.
Relying on sleep time is a very bad idea - I'm sure you have realized that as well. There are two main methods to solve this:
Modifying UI on the UI thread (i.e. JavaFX Application thread)
You can do the same, except that you would wrap the filteredList.setPredicate() call in Platform.runLater().
In other words, it should look like this:
final Predicate<Album> predicate = album -> {
// Whatever you have
};
Platform.runLater(() -> filteredList.setPredicate(predicate));
Doing this will off-load the generation of Predicate in the background thread, while the actual updating is done on the UI thread. I would say that this will cause a good chunk of processing to be shifted back to UI thread as well, but it is probably unavoidable.
However, you can still skip some predicate changes, because of the codes you have written in the Runnable object in the thread. I assume this fulfills your requirement of "avoiding applying predicates that aren't necessary."
Use TimeLine
JavaFX has this very handy class called TimeLine that works like a timer, and it runs on the UI thread.
Instead of using another thread, create a single TimeLine object in your class.
private String filter;
private final Timeline timeline = new Timeline(
new KeyFrame(Duration.millis(100),
ae -> setPredicate()
));
public void setFilter ( String filter ) {
if ( filter == null ) filter = "";
if ( !this.filter.equals( filter ) ) {
this.filter = filter;
this.timeline.playFromStart();
}
}
private void setPredicate() {
final String filterText = this.filter;
// The rest remains pretty much the same.
}
Using this approach causes all codes to run on UI thread, so you will not have those weird exceptions.
Another good thing is, you will not have to manage the thread. Although you have set the thread to daemon, the thread will still run the Runnable every 25ms until your program totally terminates.
Lastly, this provides a uniform delay that starts from the last change in the filter string. This will provide a slightly better user experience.
I'm having a project where I have a client which makes calls to the webserver. The webserver continuously opens one connection to another server which serves a XML file. This XML file gets converted into Java objects. To perform these actions, I use a thread pool.
First there is this worker thread with a while loop. In the loop I call another method to retrieve the XML data.
public static void startXmlRetrieval( String sbeSystem, String params ) throws Exception {
Processable xmlEventTask = sTaskWorkQueue.poll();
if ( xmlEventTask == null )
xmlEventTask = new EventXMLTask( sInstance );
else if ( !(xmlEventTask instanceof EventXMLTask) )
xmlEventTask = new EventXMLTask( sInstance );
((EventXMLTask) xmlEventTask).setXmlRetrievalParams( params );
((EventXMLTask) xmlEventTask).setXmlRetrievalAddr( sbeSystem );
sTaskWorkQueue.add( xmlEventTask );
synchronized ( sLockObject ) {
System.out.println( "Initiating thread to retrieve XML feed" );
sThreadPool.execute( ((EventXMLTask) xmlEventTask).getTaskRunnable());
// send the continuous thread from the ServerSessionHandler class to wait for this execution to finish
sLockObject.wait();
}
}
The above method executes and comes back to the object where the method is declared.
#Override
public void handleState( Processable task, int state ) throws Exception {
switch ( state ) {
case XML_RETRIEVAL_FAILED:
recycleXMLTask( (EventXMLTask) task );
//throw new Exception( "XML retrieval failed" );
case XML_RETRIEVAL_COMPLETED:
synchronized ( sLockObject ) {
ConvertManager.startXMLConversion( sInstance, sXmlData );
}
break;
case DATABASE_RETRIEVAL_FAILED:
case DATABASE_RETRIEVAL_COMPLETED:
recycleDatabaseTask( (DatabaseTask) task );
break;
case UNX_COMMAND_EXEC_FAILED:
case UNX_COMMAND_EXEC_COMPLETED:
recycleUnxCommandExecTask( (CommandOutputRetrievalTask) task );
break;
case ConvertManager.XML_CONVERSION_COMPLETED:
synchronized ( sLockObject ) {
removeXMLEventRetrieval( (TaskBase) task );
sLockObject.notifyAll();
}
break;
}
}
In the cas section "XML_RETRIEVAL_COMPLETED" i want to pass another thread to the same threadpool to execute the conversion of the XML data.
The problem is that the method ConvertManager.startXMLConversion is executed, but when it comes to a submit on the threadpool for submittng a callable (FutureTask), this call method is not executed anymore.
For the Thread group in the debugger, it says "WAIT" and it's currently stuck in the Unsafe.park method which is called from the FutureTask.awaitDone method.
Please help me with what the thread is waiting for as I used the synchronized statement for the one thread wait for the other one, but the other one is only executed to a certain point and the stops. I also tried playing around with notify and notifyAll on the sLockObject without any success.
The ConvertManager.startXmlConversion method looks as follows:
public static List<XMLEventData> startXMLConversion( AbstractManager mng, Document xmlDocument ) throws Exception {
sInstance.mCallingManager = mng;
List<XMLEventData> retVal;
Processable converterTask = sInstance.sTaskWorkQueue.poll();
try {
if ( converterTask == null )
converterTask = new XMLToXMLEventConverterTask( sInstance );
else if ( !(converterTask instanceof XMLToXMLEventConverterTask) )
converterTask = new XMLToXMLEventConverterTask( sInstance );
else if ( ((XMLToXMLEventConverterTask) converterTask).getTaskCallable() == null ) {
converterTask = new XMLToXMLEventConverterTask( sInstance );
}
sTaskWorkQueue.add( converterTask );
((XMLToXMLEventConverterTask) converterTask).setXmlDocument( xmlDocument );
System.out.println( "Starting new thread to convert XML data" );
retVal = (List<XMLEventData>) sThreadPool.submit( ((XMLToXMLEventConverterTask) converterTask).getTaskRunnable() ).get();
} catch ( Exception e ) {
e.printStackTrace();
throw new Exception( e );
}
return retVal;
}
Thank you in advance!
I have a Java application, developed in eclipse and with an exe wrapper. It runs full screen on a win 7 desktop, but not on a Win 8 surface (original) with Intel HD Graphics 4000. When run on the surface it has black space all around it. I found multiple references to updating the graphics driver to get extra options about how the screen scales. The latest drivers from Intel are rejected when I try to install them. If I try to do an update via device manager it says I am current. Looking for any suggestions/info. Thank you.
--- add ons ---
Surface has Java 8 update 65
public class Fullscreen
{
private static GraphicsDevice _device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
private static DisplayMode _oldMode = null;
public static Drawable _drawable;
public static BufferStrategy _bufStrat;
public static int _frameCount;
public static long _secondTrack;
//==========================================================================
/**
* Set some video related stuff
* #param frame - The App's JFrame
* #return - true if sucessful
*/
public static boolean set( JFrame frame )
{
frame.setResizable ( false );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
if (MainBase._fullScreen) // Is true for this version
{
frame.setUndecorated ( true );
frame.setIgnoreRepaint ( true );
if (MainBase._fullScreen && !_device.isFullScreenSupported())
{
System.err.println( "Full screen not supported" );
return false;
}
try
{
_device.setFullScreenWindow( frame );
}
catch ( Exception e )
{
_device.setFullScreenWindow( null );
System.err.println( "Failed setting full screen" );
return false;
}
_oldMode = _device.getDisplayMode();
//TODO: what to do about display refresh vs frame rate
DisplayMode displayMode = new DisplayMode( MainBase._screenW, MainBase._screenH, 32, 60); //MainBase._fps );
if (displayMode != null && _device.isDisplayChangeSupported())
{
try
{
_device.setDisplayMode( displayMode );
}
catch (Exception e)
{
_device.setDisplayMode( _oldMode );
_device.setFullScreenWindow( null );
System.err.println( "Failed setting full screen mode" );
return false;
}
}
}
//System.out.println( "Display Mode W " + MainBase._screenW + " H " + MainBase._screenH + " BitDepth " + 32 );
return true;
}
----- Important info although not solved -----
I tried to update the surface to Win 10. The update failed. I then rolled back to Win 8. After I reinstalled my extra stuff the application ran at full screen. Until it crashed and I had to kill it in Task Manager. After that it was back to not full screen. Something obviously got tweaked or carried of from that run. Not a solution but an important lead to follow.
within a web page is a script that allows you to see a video and other.
using python and selenium can not be run the script after the mouse clicks. Of the currently am using this code:
videoGemPath = ".//*[#id='brandconnect']/a/img"
scriptPath = ".//*[#id='content']/script"
elementScript = "/html/body/div[2]/div[1]"
location = driver.find_element_by_xpath(scriptPath)
ActionChains(driver).move_to_element(location).click().perform()
but it returns this error
=========================================================================
Traceback (most recent call last):
File "C:\Users\xxxxxx\Desktop\Proggetti VB\Per Web\PythonApplication4\PythonApplication4\PythonApplication4.py", line 66, in test_Login
ActionChains(driver).move_to_element(location).click().perform()
File "C:\Python27\lib\site-packages\selenium-2.48.0-py2.7.egg\selenium\webdriver\common\action_chains.py", line 72, in perform
action()
File "C:\Python27\lib\site-packages\selenium-2.48.0-py2.7.egg\selenium\webdriver\common\action_chains.py", line 217, in
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
File "C:\Python27\lib\site-packages\selenium-2.48.0-py2.7.egg\selenium\webdriver\remote\webdriver.py", line 201, in execute
self.error_handler.check_response(response)
File "C:\Python27\lib\site-packages\selenium-2.48.0-py2.7.egg\selenium\webdriver\remote\errorhandler.py", line 181, in check_response
raise exception_class(message, screen, stacktrace)
MoveTargetOutOfBoundsException: Message: Offset within element cannot be scrolled into view: (352.5, 241.5): [object HTMLScriptElement]
Stacktrace:
at FirefoxDriver.prototype.mouseMoveTo (file:///c:/users/xxxxxx/appdata/local/temp/tmpgnvb0k/extensions/fxdriver#googlecode.com/components/driver-component.js:10961)
at DelayedCommand.prototype.executeInternal_/h (file:///c:/users/xxxxxx/appdata/local/temp/tmpgnvb0k/extensions/fxdriver#googlecode.com/components/command-processor.js:12534)
at DelayedCommand.prototype.executeInternal_ (file:///c:/users/xxxxxx/appdata/local/temp/tmpgnvb0k/extensions/fxdriver#googlecode.com/components/command-processor.js:12539)
at DelayedCommand.prototype.execute/< (file:///c:/users/xxxxxxx/appdata/local/temp/tmpgnvb0k/extensions/fxdriver#googlecode.com/components/command-processor.js:12481)
=========================================================================
the script code is this:
// create button
document.write('<div id="brandconnect"><img src="img/bconnect_area.png" class="tooltip" rel="Guarda video e ricevi Gemme gratis!" alt="" /></div>');
// ini local storage to save last button state if this html5 feature is available
var storage = false;
try {
if( window && window.localStorage ) {
storage = window.localStorage;
if( typeof(storage.bcVisible) === 'string' ) {
if( storage.bcVisible == 'true' ) {
showBC();
}
else {
hideBC();
}
}
}
}
catch( ignore ) {
// local storage might require user approval. in this case we don't use it
}
// handle button visibility
function handleBC(obj) {
if( typeof(obj) != 'object' || obj.length < 1 ) {
// no videos available
hideBC();
}
else {
// videos are available
showBC();
}
}
// show brandconnect button
function showBC() {
clink = document.getElementById('brandconnect');
if( clink ) {
clink.style.display = 'block';
}
if( storage ) {
storage.bcVisible = 'true';
}
}
// hide brandconnect button
function hideBC() {
document.getElementById('brandconnect').style.display = 'none';
if( storage ) {
storage.bcVisible = 'false';
}
}
function hoverBC() {
document.getElementById('brandconnect').style.backgroundPosition = '-89px 0';
}
function unhoverBC() {
document.getElementById('brandconnect').style.backgroundPosition = '0 0';
}
// definitions by JSON
var ssa_json = {
'applicationUserId': '512000516',
'applicationKey': '2ae25b1d',
'currencyName': 'Gemme',
'onCampaignsReady': handleBC,
'onCampaignsDone': hideBC,
'onCampaignCompleted': handleBC,
'onCampaignClose': handleBC
};
// embed supersonic script
(function(d,t){
var g = d.createElement(t), s = d.getElementsByTagName(t)[0]; g.async = true;
g.src = ('https:' != location.protocol ? 'http://jsd.supersonicads.com' :
'https://supersonicads.cotssl.net') + '/inlineDelivery/delivery.min.gz.js';
s.parentNode.insertBefore(g,s);
}(document,'script'));
//]]>
How can I fix it?
I have an aplication where is picture with SIN, COS..
TextArea1 will tell somebody: "Click in picture where SIN"
if user do this, textArea2 tell him: "It is corect"
After that, textArea1.append "Click in picture where COS"
-but program is still waiting for clicking to SIN :(
Can you help me and give a little advice to me please?
There is some code:
private class KlikaniMysi implements MouseListener {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(e.getX() + " " + e.getY());
//for finding coordinates (by console)
//textArea2 = "try" at start !!
//textArea1 = "Find SIN" at start !!!!!!!!
if(textArea2.equals("try")){
if( (((e.getX()) > 420)&&((e.getX()) < 580)) && ( ((e.getY()) > 164)&&((e.getY()) < 178) )){
textArea2.setText("");
textArea2.append("RIGHT1");
textArea1.append("Find COS"); //!!!! work!!
//How to stop the IF cycle here and run class KlikaniMysi (mouselistener) again ?
}
else{
textArea1.setText("");
textArea1.append("try again");
}
}else{
if( (((e.getX()) > 586)&&((e.getX()) < 594)) && ( ((e.getY()) > 174)&&((e.getY()) < 282) )){
//This isnt nice, but I dont know how to expres range better.
textArea1.setText("");
textArea2.append("Right2");
textArea1.append("Find TAN");
}
else{
vystup.setText("");
textArea1.append("Try again");
}
}
}
There are many more aspects about this code that are 'suboptimal' but I think your problem is here:
if(textArea2.equals("try"))
You want to test the content of that area, not the area itself, hence change it to
if(textArea2.getText().equals("try"))