Search Results

Search found 8588 results on 344 pages for 'thread abort'.

Page 160/344 | < Previous Page | 156 157 158 159 160 161 162 163 164 165 166 167  | Next Page >

  • Java CountDownLatch used to wait for JFrame to dispose

    - by Brian
    I have referenced this previous question as well as other sources, but cannot get CountDownLatch to work correctly. Background: mainFrame creates new Frame called dataEntryFrame. When dataEntryFrame "Submit" button is clicked, record added to database and dataEntryFrame disposed. At this point, mainFrame should clear and reload a jList that shows all records. Issue: When dataEntryFrame loads, java freezes, dataEntryFrame components never load. I cannot get past this part... then, in the DataEntryFrame, CountDownLatch should only decrements after the submit button is clicked, successfully adds a record to a database table, and disposes itself. Or when the user clicks cancel... Code: From MainFrame CountDownLatch dataEntryDone = new CountDownLatch(1); DataEntryFrame f = new DataEntryFrame(dataEntryDone); Thread newThread = new Thread(f); newThread.start(); dataEntryDone.await(); Code: From DataEntryFrame public void run(){ initComponents(); loadOtherData(); this.setVisible(true); } void submit(){ addRecord(); this.dispose() dataEntryDone.countDown(); }

    Read the article

  • BeginInvoke on ObservableCollection not immediate.

    - by Padu Merloti
    In my code I subscribe to an event that happens on a different thread. Every time this event happens, I receive an string that is posted to the observable collection: Dispatcher currentDispatcher = Dispatcher.CurrentDispatcher; var SerialLog = new ObservableCollection<string>(); private void hitStation_RawCommandSent(object sender, StringEventArgs e) { string command = e.Value.Replace("\r\n", ""); Action dispatchAction = () => SerialLog.Add(command); currentDispatcher.BeginInvoke(dispatchAction, DispatcherPriority.Render); } The code below is in my view model (could be in the code behind, it doesn't matter in this case). When I call "hitstation.PrepareHit", the event above gets called a couple times, then I wait and call "hitStation.HitBall", and the event above gets called a couple more times. private void HitBall() { try { try { Mouse.OverrideCursor = Cursors.Wait; //prepare hit hitStation.PrepareHit(hitSpeed); Thread.Wait(1000); PlayWarning(); //hit hitStation.HitBall(hitSpeed); } catch (TimeoutException ex) { MessageBox.Show("Timeout hitting ball: " + ex.Message); } } finally { Mouse.OverrideCursor = null; } } The problem I'm having is that the ListBox that is bound to my SerialLog gets updated only when the HitBall method finishes. I was expecting seeing a bunch of updates from the PrepareHit, a pause and then a bunch more updates from the HitBall. I've tried a couple of DispatcherPriority arguments, but they don't seem to have any effect.

    Read the article

  • Java: Efficiency of the readLine method of the BufferedReader and possible alternatives

    - by Luhar
    We are working to reduce the latency and increase the performance of a process written in Java that consumes data (xml strings) from a socket via the readLine() method of the BufferedReader class. The data is delimited by the end of line separater (\n), and each line can be of a variable length (6KBits - 32KBits). Our code looks like: Socket sock = connection; InputStream in = sock.getInputStream(); BufferedReader inputReader = new BufferedReader(new InputStreamReader(in)); ... do { String input = inputReader.readLine(); // Executor call to parse the input thread in a seperate thread }while(true) So I have a couple of questions: Will the inputReader.readLine() method return as soon as it hits the \n character or will it wait till the buffer is full? Is there a faster of picking up data from the socket than using a BufferedReader? What happens when the size of the input string is smaller than the size of the Socket's receive buffer? What happens when the size of the input string is bigger than the size of the Socket's receive buffer? I am getting to grips (slowly) with Java's IO libraries, so any pointers are much appreciated. Thank you!

    Read the article

  • Shutting down a windows service that has threads

    - by Dave
    I have a windows service written in .NET 3.5 (c#) with a System.Threading.Timer that spawns several Threads in each callback. These are just normal threads (no Thread Pool) and I've set the IsBackground = true on each thread since I'm only going to be running managed code. When a user stops the service, what happens to all the threads? Do they die gracefully? I don't have any code that manages the threads via calling join or abort. Is it correct to assume the IsBackground = true is enough to assume the threads will be disposed and stopped when a user stops the service? What exactly happens when someone stops a windows service via the Service Manager GUI? Does it kill the process after it fires the OnStop event? This would actually be acceptable for me because I've built a separate mechanism that allows a user know for sure there are no threads before they stop the service. This is done via 2 WCF methods exposed from a ServiceHost that runs inside the Windows Service. There's one method to stop spawning new threads and another method to query how many running threads there are left. I'm just curious what happens if they skip those steps and just stop the service... It seems the IsBackground helps achieve this:

    Read the article

  • Special technology needed for browser based chat?

    - by orokusaki
    On this post, I read about the usage of XMPP. Is this sort of thing necessary, and more importantly, my main question expanded: Can a chat server and client be built efficiently using only standard HTTP and browser technologies (such as PHP and JS, or RoR and JS, etc)? Or, is it best to stick with old protocols like XMPP find a way to integrate them with my application? I looked into CampFire via LiveHTTPHeaders and Firebug for about 5 minutes, and it appears to use Ajax to send a request which is never answered until another chat happens. Is this just CampFire opening a new thread on the server to listen for an update and then returning a response to the request when the thread hears an update? I noticed that they're requesting on a specific port (8043 if memory serves me) which makes me think that they're doing something more complex than just what I mentioned. Also, the URL requested started with /tcp/ which I found interesting. Note: I don't expect to ever have more than 150 users live-chatting in all the rooms combined at the same time. I understand that if I was building a hosted pay for chat service like CampFire with thousands of concurrent users, it would behoove me to invest time in researching special technologies vs trying to reinvent the wheel in a simple way in my app. Also, if you're going to do it with server polling, how often would you personally poll to maximize response without slamming the server?

    Read the article

  • Does Android AsyncTaskQueue or similar exist?

    - by Ben L.
    I read somewhere (and have observed) that starting threads is slow. I always assumed that AsyncTask created and reused a single thread because it required being started inside the UI thread. The following (anonymized) code is called from a ListAdapter's getView method to load images asynchronously. It works well until the user moves the list quickly, and then it becomes "janky". final File imageFile = new File(getCacheDir().getPath() + "/img/" + p.image); image.setVisibility(View.GONE); view.findViewById(R.id.imageLoading).setVisibility(View.VISIBLE); (new AsyncTask<Void, Void, Bitmap>() { @Override protected Bitmap doInBackground(Void... params) { try { Bitmap image; if (!imageFile.exists() || imageFile.length() == 0) { image = BitmapFactory.decodeStream(new URL( "http://example.com/images/" + p.image).openStream()); image.compress(Bitmap.CompressFormat.JPEG, 85, new FileOutputStream(imageFile)); image.recycle(); } image = BitmapFactory.decodeFile(imageFile.getPath(), bitmapOptions); return image; } catch (MalformedURLException ex) { // TODO Auto-generated catch block ex.printStackTrace(); return null; } catch (IOException ex) { // TODO Auto-generated catch block ex.printStackTrace(); return null; } } @Override protected void onPostExecute(Bitmap image) { if (view.getTag() != p) // The view was recycled. return; view.findViewById(R.id.imageLoading).setVisibility( View.GONE); view.findViewById(R.id.image) .setVisibility(View.VISIBLE); ((ImageView) view.findViewById(R.id.image)) .setImageBitmap(image); } }).execute(); I'm thinking that a queue-based method would work better, but I'm wondering if there is one or if I should attempt to create my own implementation.

    Read the article

  • Trying to use a grails domain class from the shell

    - by ?????
    I'm new to Grails. I'm trying to experiement with my grails domains from the shell, and I can't get it to work. These domains work fine from the scaffold code when I run the app. Given this domain class class IncomingCall { String caller_id Date call_time int call_length static constraints = { } } I try to create an "IncomingCall" and save it from the shell. No matter what I do, I always get "Null"; the object isn't created. And if I try to create the object and then do a save, I get the "No hibernate session bound to thread" error (see below). groovy:000> new IncomingCall(caller_id:'555-1212', call_time: new Date(), call_length:10).save() ERROR org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here at org.springframework.orm.hibernate3.SpringSessionContext.currentSession (SpringSessionContext.java:63) at org.hibernate.impl.SessionFactoryImpl.getCurrentSession (SessionFactoryImpl.java:574) at groovysh_evaluate.run (groovysh_evaluate:3) ... groovy:000> How can I make this work from the shell?

    Read the article

  • NetBeans parameter fill after code completion

    - by byte
    This is a particularly annoying problem I'm having, and I can't be the only one to have issue with it. In NetBeans, when you type part of a method, then hit CTRL-SPACE, it displays the code-completion popup, whereupon you can hit tab to finish out the word. This is great, and pretty much how all IDE's operate. Example: Thread.sl < CTRL-SPACE Thread.sleep Yay! Problem is that in this context, once you type in a paren, it auto-fills the parameters for the method with their default names, and inserts a closing paren (regardless of whether you have disabled the option to automatically close them on the preferences page for code completion). This behavior is NOT present if you had manually typed out the full name. How is this helpful to anyone? You've got to type over it your actual variable that you will be passing, and NetBeans gives you no option to prevent the closing paren on code-completion. Does anyone have a way to solve this issue, without having to dive into the netbeans source and build it just for this minor of an issue?

    Read the article

  • Threads in Java

    - by owca
    I've created simple program to test Threads in Java. I'd like it to print me numbers infinitely, like 123123123123123. Dunno why, but currently it stops after one cycle finishing 213 only. Anyone knows why ? public class Main { int number; public Main(int number){ } public static void main(String[] args) { new Infinite(2).start(); new Infinite(1).start(); new Infinite(3).start(); } } class Infinite extends Thread { static int which=1; static int order=1; int id; int number; Object console = new Object(); public Infinite(int number){ id = which; which++; this.number = number; } @Override public void run(){ while(1==1){ synchronized(console){ if(order == id){ System.out.print(number); order++; if(order >= which){ order = 1; } try{ console.notifyAll(); console.wait(); } catch(Exception e) {} } else { try{ console.notifyAll(); console.wait(); } catch(Exception e) {} } } try{Thread.sleep(0);} catch(Exception e) {} } } }

    Read the article

  • Access denied for pdf to read using itextsharp at server level..

    - by apekshabs
    Am facing error after uploadind to server... as access denied .... can anyone help me.... Document myDocument = new Document(PageSize.A5, 26, 72, 180, 180); string strUniqueFn = "onlineinvoice.pdf"; string imgpath = "logo.gif"; string strUser = Thread.CurrentPrincipal.Identity.Name.Substring(Thread.CurrentPrincipal.Identity.Name.IndexOf("\\") + 1).ToUpper(); string strFolder = Server.MapPath("."); System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(strFolder); System.IO.FileInfo[] fi = di.GetFiles(strUser + "*.*"); for (i = 0; i <= fi.Length - 1; i++) { System.IO.File.Delete(strFolder + "\\" + strUniqueFn); } string strPath = strFolder + "\\" + strUniqueFn; PdfWriter pdfw = PdfWriter.GetInstance(myDocument, new FileStream(strPath, FileMode.Create)); string iPath = strFolder + "\\" + imgpath; pdfw.CloseStream = false; myDocument.Open(); ...................... myDocument.Close(); Am facing error at PdfWriter pdfw = PdfWriter.GetInstance(myDocument, new FileStream(strPath, FileMode.Create)); can anyone help me... Thank you

    Read the article

  • Problem when trying to connect to a desktop server from android on wifi

    - by thiagolee
    Hello, I am trying to send a file from the phone running Android 1.5 to a server on a desktop. I wrote some code, which works on emulator, but on the phone it doesn't. I'm connecting to the network through WiFi. It works, I can access the internet through my phone and I've configured my router. The application stops when I'm trying to connect. I have the permissions. Someone have any ideas, below is my code. Running on Android package br.ufs.reconhecimento; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.Socket; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.ImageButton; /** * Sample code that invokes the speech recognition intent API. */ public class Reconhecimento extends Activity implements OnClickListener { static final int VOICE_RECOGNITION_REQUEST_CODE = 1234; static final String LOG_VOZ = "UFS-Reconhecimento"; final int INICIAR_GRAVACAO = 01; int porta = 5158; // Porta definida no servidor int tempoEspera = 1000; String ipConexao = "172.20.0.189"; EditText ipEdit; /** * Called with the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Inflate our UI from its XML layout description. setContentView(R.layout.main); // Get display items for later interaction ImageButton speakButton = (ImageButton) findViewById(R.id.btn_speak); speakButton.setPadding(10, 10, 10, 10); speakButton.setOnClickListener(this); //Alerta para o endereço IP AlertDialog.Builder alerta = new AlertDialog.Builder(this); alerta.setTitle("IP");//+mainWifi.getWifiState()); ipEdit = new EditText(this); ipEdit.setText(ipConexao); alerta.setView(ipEdit); alerta.setMessage("Por favor, Confirme o endereço IP."); alerta.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { ipConexao = ipEdit.getText().toString(); Log.d(LOG_VOZ, "Nova Atribuição do Endreço IP: " + ipConexao); } }); alerta.create(); alerta.show(); } /** * Handle the click on the start recognition button. */ public void onClick(View v) { if (v.getId() == R.id.btn_speak) { //startVoiceRecognitionActivity(); Log.d(LOG_VOZ, "Iniciando a próxima tela"); Intent recordIntent = new Intent(this, GravacaoAtivity.class); Log.d(LOG_VOZ, "Iniciando a tela (instancia criada)"); startActivityForResult(recordIntent, INICIAR_GRAVACAO); Log.d(LOG_VOZ, "Gravação iniciada ..."); } } /** * Handle the results from the recognition activity. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(LOG_VOZ, "Iniciando onActivityResult()"); if (requestCode == INICIAR_GRAVACAO && resultCode == RESULT_OK) { String path = data.getStringExtra(GravacaoAtivity.RETORNO); conexaoSocket(path); } else Log.e(LOG_VOZ, "Resultado Inexperado ..."); } private void conexaoSocket(String path) { Socket socket = SocketOpener.openSocket(ipConexao, porta, tempoEspera); if(socket == null) return; try { DataOutputStream conexao = new DataOutputStream(socket.getOutputStream()); Log.d(LOG_VOZ, "Acessando arquivo ..."); File file = new File(path); DataInputStream arquivo = new DataInputStream(new FileInputStream(file)); Log.d(LOG_VOZ, "Iniciando Transmissão ..."); conexao.writeLong(file.length()); for(int i = 0; i < file.length(); i++) conexao.writeByte(arquivo.readByte()); Log.d(LOG_VOZ, "Transmissão realizada com sucesso..."); Log.d(LOG_VOZ, "Fechando a conexão..."); conexao.close(); socket.close(); Log.d(LOG_VOZ, "============ Processo finalizado com Sucesso =============="); } catch (IOException e) { Log.e(LOG_VOZ, "Erro ao fazer a conexão via Socket. " + e.getMessage()); // TODO Auto-generated catch block } } } class SocketOpener implements Runnable { private String host; private int porta; private Socket socket; public SocketOpener(String host, int porta) { this.host = host; this.porta = porta; socket = null; } public static Socket openSocket(String host, int porta, int timeOut) { SocketOpener opener = new SocketOpener(host, porta); Thread t = new Thread(opener); t.start(); try { t.join(timeOut); } catch(InterruptedException e) { Log.e(Reconhecimento.LOG_VOZ, "Erro ao fazer o join da thread do socket. " + e.getMessage()); //TODO: Mensagem informativa return null; } return opener.getSocket(); } public void run() { try { socket = new Socket(host, porta); }catch(IOException e) { Log.e(Reconhecimento.LOG_VOZ, "Erro na criação do socket. " + e.getMessage()); //TODO: Mensagem informativa } } public Socket getSocket() { return socket; } } Running on the desktop Java: import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class ServidorArquivo { private static int porta = 5158; static String ARQUIVO = "voz.amr"; /** * Caminho que será gravado o arquivo de audio */ static String PATH = "/home/iade/Trabalho/lib/"; public static void main(String[] args) { int i = 1; try { System.out.println("Iniciando o Servidor Socket - Android."); ServerSocket s = new ServerSocket(porta); System.out.println("Servidor Iniciado com Sucesso..."); System.out.println("Aguardando conexões na porta: " + porta); while(true) { Socket recebendo = s.accept(); System.out.println("Aceitando conexão de nº " + i); new ThreadedHandler(recebendo).start(); i++; } } catch (Exception e) { System.out.println("Erro: " + e.getMessage()); e.printStackTrace(); } } } class ThreadedHandler extends Thread { private Socket socket; public ThreadedHandler(Socket so) { socket = so; } public void run() { DataInputStream entrada = null; DataOutputStream arquivo = null; try { entrada = new DataInputStream(socket.getInputStream()); System.out.println("========== Iniciando a leitura dos dados via Sockets =========="); long tamanho = entrada.readLong(); System.out.println("Tamanho do vetor " + tamanho); File file = new File(ServidorArquivo.PATH + ServidorArquivo.ARQUIVO); if(!file.exists()) file.createNewFile(); arquivo = new DataOutputStream(new FileOutputStream(file)); for(int j = 0; j < tamanho; j++) { arquivo.write(entrada.readByte()); } System.out.println("========== Dados recebidos com sucesso =========="); } catch (Exception e) { System.out.println("Erro ao tratar do socket: " + e.getMessage()); e.printStackTrace(); } finally { System.out.println("**** Fechando as conexões ****"); try { entrada.close(); socket.close(); arquivo.close(); } catch (IOException e) { System.out.println("Erro ao fechar conex&#65533;es " + e.getMessage()); e.printStackTrace(); } } System.out.println("============= Fim da Gravação ==========="); // tratar o arquivo String cmd1 = "ffmpeg -i voz.amr -ab 12288 -ar 16000 voz.wav"; String cmd2 = "soundstretch voz.wav voz2.wav -tempo=100"; String dir = "/home/iade/Trabalho/lib"; File workDir = new File(dir); File f1 = new File(dir+"/voz.wav"); File f2 = new File(dir+"/voz2.wav"); f1.delete(); f2.delete(); try { executeCommand(cmd1, workDir); System.out.println("realizou cmd1"); executeCommand(cmd2, workDir); System.out.println("realizou cmd2"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void executeCommand(String cmd1, File workDir) throws IOException, InterruptedException { String s; Process p = Runtime.getRuntime().exec(cmd1,null,workDir); int i = p.waitFor(); if (i == 0) { BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); // read the output from the command while ((s = stdInput.readLine()) != null) { System.out.println(s); } } else { BufferedReader stdErr = new BufferedReader(new InputStreamReader(p.getErrorStream())); // read the output from the command while ((s = stdErr.readLine()) != null) { System.out.println(s); } } } } Thanks in advance.

    Read the article

  • ObjectDisposedException when .Show()'ing a form that shouldn't be disposed.

    - by user320781
    ive checked out some of the other questions and obviously the best solution is to prevent the behavior that causes this issue in the first place, but the problem is very intermittent, and very un-reproduceable. I basically have a main form, with sub forms. The sub forms are shown from menus and/or buttons from the main form like so: private void myToolStripMenuItem_Click(object sender, EventArgs e) { try { xDataForm.Show(); xDataForm.Activate(); } catch (ObjectDisposedException) { MessageBox.Show("ERROR 10103"); ErrorLogging newLogger = new ErrorLogging("10103"); Thread errorThread = new Thread(ErrorLogging.writeErrorToLog); errorThread.Start(); } } and the sub forms are actually in the main form(for better or worse. i would actually like to change this but would be a considerable amount of time to do so): public partial class FormMainScreen : Form { Form xDataForm = new xData(); ...(lots more here) public FormMainScreen(int pCount, string pName) { InitializeComponent(); ... } ... } The Dispose function for the sub form is modified so that, the 'close' and 'X' buttons actually hide the form so we dont have to re-create it every time. When the main screen closes, it sets a "flag" to 2, so the other forms know that it is actually ok to close; protected override void Dispose(bool disposing) { if (FormMainScreen.isExiting == 2) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } else { if (xData.ActiveForm != null) { xData.ActiveForm.Hide(); } } } So, the question is, why would this work over and over and over again flawlessly, but, literally, about every 1/1000 of the time, cause an exception, or rather, why is my form being disposed? I had a suspicion that the garbage collector was getting confused, because it occurs slightly more frequently after it has been running for many hours.

    Read the article

  • Long running operations (threads) in a web (asp.net) environment

    - by rrejc
    I have an asp.net (mvc) web site. As the part of the functions I will have to support some long running operations, for example: Initiated from user: User can upload (xml) file to the server. On the server I need to extract file, do some manipulation (insert into the db) etc... This can take from one minute to ten minutes (or even more - depends on file size). Of course I don't want to block the request when the import is running , but I want to redirect user to some progress page where he will have a chance to watch the status, errors or even cancel the import. This operation will not be frequently used, but it may happen that two users at the same time will try to import the data. It would be nice to run the imports in parallel. At the beginning I was thinking to create a new thread in the iis (controller action) and run the import in a new thread. But I am not sure if this is a good idea (to create working threads on a web server). Should I use windows services or any other approach? Initiated from system: - I will have to periodically update lucene index with the new data. - I will have to send mass emails (in the future). Should I implement this as a job in the site and run the job via Quartz.net or should I also create a windows service or something? What are the best practices when it comes to running site "jobs"? Thanks!

    Read the article

  • C# DynamicMethod prelink

    - by soywiz
    I'm the author of a psp emulator made in C#. I'm generating lots of "DynamicMethod" using ILGenerator. I'm converting assembly code into an AST, and then generating IL code and building that DynamicMethod. I'm doing this in another thread, so I can generate new methods while the program is executing others so it can run smoothly. My problem is that the native code generation is lazy, so the machine code is generated when the function is called, not when the IL is generated. So it generates in the program executing thread, native code generation is prettly slow as it is the asm-ast-il step. I have tried the Marshal.Prelink method that it is suposed to generate the machine code before executing the function. It does work on Mono, but it doesn't work on MS .NET. Marshal.Prelink(MethodInfo); Is there a way of prelinking a DynamicMethod on MS .NET? I thought adding a boolean parameter to the function that if set, exits the function immediately so no code is actually executed. I could "prelink" that way, but I think that's a nasty solution I want to avoid. Any idea?

    Read the article

  • C# - Take Screenshot based on a Timer

    - by APShredder
    Hello everybody. I'm trying to create a WinForms app that takes a screenshot on a set interval. I think my code is correct, but when I try to run it, I get the error message "System.Runtime.InteropServices.ExternalException was unhandled, A generic error occurred in GDI+." System.Windows.Forms.Timer t = new System.Windows.Forms.Timer(); Thread th; private static Bitmap bmpScreenshot; private static Graphics gfxScreenshot; void TakeScreenShot() { bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb); gfxScreenshot = Graphics.FromImage(bmpScreenshot); gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy); bmpScreenshot.Save(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\ScreenCaptures", ImageFormat.Png); th.Abort(); } void StartThread(object sender, EventArgs e) { th = new Thread(new ThreadStart(TakeScreenShot)); th.Start(); } private void Form1_Load(object sender, EventArgs e) { Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\ScreenCaptures"); t.Interval = 500; t.Tick += new EventHandler(StartThread); t.Start(); } The line that's giving my trouble is: bmpScreenshot.Save(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\ScreenCaptures", ImageFormat.Png); Any ideas about what is going wrong? Thanks in advance.

    Read the article

  • Java - If statement with String comparison fails

    - by Andrea
    I really don't know why the if statement below is not executing: if (s == "/quit") { System.out.println("quitted"); } Below is the whole class. It is probably a really stupid logic problem but I have been pulling my hair out over here not being able to figure this out. Thanks for looking :) class TextParser extends Thread { public void run() { while (true) { for(int i = 0; i < connectionList.size(); i++) { try { System.out.println("reading " + i); Connection c = connectionList.elementAt(i); Thread.sleep(200); System.out.println("reading " + i); String s = ""; if (c.in.ready() == true) { s = c.in.readLine(); //System.out.println(i + "> "+ s); if (s == "/quit") { System.out.println("quitted"); } if(! s.equals("")) { for(int j = 0; j < connectionList.size(); j++) { Connection c2 = connectionList.elementAt(j); c2.out.println(s); } } } } catch(Exception e){ System.out.println("reading error"); } } } } }

    Read the article

  • Deep Zoom in Ajax - Possible? Any examples out there?

    - by Phil
    I have an idea to implement a deep zoom type interface hosted in a browser for sports training data (speed, distance, heart rate etc.) However, rather than images I actually want to zoom into a hierarchy of information. For example, the initial display would contain a grid of years - hover over 2008, for example, and spin the mouse wheel (or click) will zoom into that year but during the zoom I want 2008 to fade out and be replaced with a calendar of months. Again zoom into a month and the months are replaced with the months calendar, zoom into a day and you finally see a chart with the training data plotted on it. All the time only dates with actual data would be highlighted in some fashion. My question is whether this would even be possible and whether anyone has seen examples of this already. I'm imagining that most of the time the next level of information could be cached in the browser (in fact, because this is calendar-based, I can calculate most of that and cache the dates to be highlighted.) I could also zoom into an empty chart whilst an Ajax thread is fetching the data to display. I've never tried anything like this before and I'm especially interested in whether DHTML would be capable of this sort of zoom (I suspect not and I would have to resort to Silverlight) and whether the Ajax execution would be uninterrupted whilst the browser rendering thread is kept busy zooming.

    Read the article

  • why the main method are not covered? urgent, please help me

    - by Mike.Huang
    main method: public static void main(String[] args) throws Exception { if (args.length != EXPECTED_NUMBER_OF_ARGUMENTS) { System.err.println("Usage - java XFRCompiler ConfigXML PackageXML XFR"); } String configXML = args[0]; String packageXML = args[1]; String xfr = args[2]; AutoConfigCompiler compiler = new AutoConfigCompiler(); compiler.setConfigDocument(loadDocument(configXML)); compiler.setPackageInfoDoc(loadDocument(packageXML)); // compiler.setVisiblityDoc(loadDocument("VisibilityFilter.xml")); compiler.compileModel(xfr); } private static Document loadDocument(String fileName) throws Exception { TXDOMParser parser = (TXDOMParser) ParserFactory.makeParser(TXDOMParser.class.getName()); InputSource source = new InputSource(new FileInputStream(fileName)); parser.parse(source); return parser.getDocument(); } testcase: @Test public void testCompileModel() throws Exception { // construct parameters URL configFile = Thread.currentThread().getContextClassLoader().getResource("Ford_2008_Mustang_Config.xml"); URL packageFile = Thread.currentThread().getContextClassLoader().getResource("Ford_2008_Mustang_Package.xml"); File tmpFile = new File("Ford_2008_Mustang_tmp.xfr"); if(!tmpFile.exists()) { tmpFile.createNewFile(); } String[] args = new String[]{configFile.getPath(),packageFile.getPath(),tmpFile.getPath()}; try { // test main method XFRCompiler.main(args); } catch (Exception e) { assertTrue(true); } try { // test args length is less than 3 XFRCompiler.main(new String[]{"",""}); } catch (Exception e) { assertTrue(true); } tmpFile.delete(); } coverage outputs displayed as the lines from “String configXML = args[0];" in main method are not covered

    Read the article

  • How to tell when a Socket has been disconnected

    - by BowserKingKoopa
    On the client side I need to know when/if my socket connection has been broken. However the Socket.Connected property always returns true, even after the server side has been disconnected and I've tried sending data through it. Can anyone help me figure out what's going on here. I need to know when a socket has been disconnected. Socket serverSocket = null; TcpListener listener = new TcpListener(1530); listener.Start(); listener.BeginAcceptSocket(new AsyncCallback(delegate(IAsyncResult result) { Debug.WriteLine("ACCEPTING SOCKET CONNECTION"); TcpListener currentListener = (TcpListener)result.AsyncState; serverSocket = currentListener.EndAcceptSocket(result); }), listener); Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Debug.WriteLine("client socket connected: " + clientSocket.Connected);//should be FALSE, and it is clientSocket.Connect("localhost", 1530); Debug.WriteLine("client socket connected: " + clientSocket.Connected);//should be TRUE, and it is Thread.Sleep(1000); serverSocket.Close();//closing the server socket here Thread.Sleep(1000); clientSocket.Send(new byte[0]);//sending data should cause the socket to update its Connected property. Debug.WriteLine("client socket connected: " + clientSocket.Connected);//should be FALSE, but its always TRUE

    Read the article

  • How to play mpg/3gp 5 sec video at start of application?

    - by Asad Ahmed
    I am developing an application in which i want to play a short 5 seconds video at the startup. which is the best format 3gp, mpg or something else? i have generated a title activity. I wanted to play the video before title. Help please!!! Below is the code of my title activity. public class Title extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.title); setTitle("M.I.S.T"); this.setTitleColor(Color.BLUE); View title = getWindow().findViewById(android.R.id.title); View titleBar = (View) title.getParent(); titleBar.setBackgroundColor(Color.YELLOW); Thread timer = new Thread(){ public void run(){ try{ sleep(3000); }catch (InterruptedException e){ e.printStackTrace(); }finally{ Intent open= new Intent("com.congestion6.asad.MENU"); startActivity(open); } } }; timer.start(); } protected void onPause() { // TODO Auto-generated method stub super.onPause(); finish(); } }

    Read the article

  • How to: generate UnhandledException?

    - by serhio
    I use this code to catch the WinForm application UnhandledException. [STAThread] static void Main(string[] args) { // Add the event handler for handling UI thread exceptions to the event. Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); // Set the unhandled exception mode to force all Windows Forms errors // to go through our handler. Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); // Add the event handler for handling non-UI thread exceptions to the event. AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); try { Application.Run(new MainForm()); } catch.... There I will try to restart the application. Now my problem is to simulate a exception like this. I tried before try (in main): throw new NullReferenceException("test"); VS caught it. Tried also in MainForm code with button : private void button1_Click(object sender, EventArgs ev) { ThreadPool.QueueUserWorkItem(new WaitCallback(TestMe), null); } protected void TestMe(object state) { string s = state.ToString(); } did not help, VS caught it, even in Release mode. How should I, finally, force the application generate UnhandleldException? Will I be able to restart the application in CurrentDomain_UnhandledException?

    Read the article

  • Java UnknownHostException When and Why?

    - by interstar
    I'm trying to post to a website from a Processing Sketch. (Processing is basically Java running in a fancy environment). I'm using this library : http://libraries.seltar.org/postToWeb/ but I don't know if that makes a difference. You can see from the stack trace below that this is just a wrapper for the Java standard library. Anyway, the important point is that the host "mysite.com" is up and running. I am seeing it from the browser. But when I try to post to it from Java I just get the UnknownHostException appearing. Given that the site is up. What else might this mean? The program is currently running inside the Processing environment. Presumably as an Applet. java.net.UnknownHostException: mysite.com at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:195) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366) at java.net.Socket.connect(Socket.java:529) at java.net.Socket.connect(Socket.java:478) at sun.net.NetworkClient.doConnect(NetworkClient.java:163) at sun.net.www.http.HttpClient.openServer(HttpClient.java:394) at sun.net.www.http.HttpClient.openServer(HttpClient.java:529) at sun.net.www.http.HttpClient.<init>(HttpClient.java:233) at sun.net.www.http.HttpClient.New(HttpClient.java:306) at sun.net.www.http.HttpClient.New(HttpClient.java:323) at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:970) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:911) at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:836) at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1014) at org.seltar.Bytes2Web.PostToWeb._post(PostToWeb.java:90) at org.seltar.Bytes2Web.ByteToWeb.post(ByteToWeb.java:66) at experimentPostToWeb.keyPressed(experimentPostToWeb.java:35) at processing.core.PApplet.handleKeyEvent(Unknown Source) at processing.core.PApplet.dequeueKeyEvents(Unknown Source) at processing.core.PApplet.handleDraw(Unknown Source) at processing.core.PApplet.run(Unknown Source) at java.lang.Thread.run(Thread.java:662)

    Read the article

  • NSOperations or NSThread for bursts of smaller tasks that continuously cancel each other?

    - by RickiG
    Hi I would like to see if I can make a "search as you type" implementation, against a web service, that is optimized enough for it to run on an iPhone. The idea is that the user starts typing a word; "Foo", after each new letter I wait XXX ms. to see if they type another letter, if they don't, I call the web service using the word as a parameter. The web service call and the subsequent parsing of the result I would like to move to a different thread. I have written a simple SearchWebService class, it has only one public method: - (void) searchFor:(NSString*) str; This method tests if a search is already in progress (the user has had a XXX ms. delay in their typing) and subsequently stops that search and starts a new one. When a result is ready a delegate method is called: - (NSArray*) resultsReady; I can't figure out how to get this functionality 'threaded'. If I keep spawning new threads each time a user has a XXX ms. delay in the typing I end up in a bad spot with many threads, especially because I don't need any other search, but the last one. Instead of spawning threads continuously, I have tried keeping one thread running in the background all the time by: - (void) keepRunning { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; SearchWebService *searchObj = [[SearchWebService alloc] init]; [[NSRunLoop currentRunLoop] run]; //keeps it alive [searchObj release]; [pool release]; } But I can't figure out how to access the "searchFor" method in the "searchObj" object, so the above code works and keeps running. I just can't message the searchObj or retrieve the resultReady objects? Hope someone could point me in the right direction, threading is giving me grief:) Thank you.

    Read the article

  • How to use Hibernate SchemaUpdate class with a JPA persistence.xml?

    - by John Rizzo
    I've a main method using SchemaUpdate to display at the console what tables to alter/create and it works fine in my Hibernate project: public static void main(String[] args) throws IOException { //first we prepare the configuration Properties hibProps = new Properties(); hibProps.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("jbbconfigs.properties")); Configuration cfg = new AnnotationConfiguration(); cfg.configure("/hibernate.cfg.xml").addProperties(hibProps); //We create the SchemaUpdate thanks to the configs SchemaUpdate schemaUpdate = new SchemaUpdate(cfg); //The update is executed in script mode only schemaUpdate.execute(true, false); ... I'd like to reuse this code in a JPA project, having no hibernate.cfg.xml file (and no .properties file), but a persistence.xml file (autodetected in the META-INF directory as specified by the JPA spec). I tried this too simple adaptation, Configuration cfg = new AnnotationConfiguration(); cfg.configure(); but it failed with that exception. Exception in thread "main" org.hibernate.HibernateException: /hibernate.cfg.xml not found Has anybody done that? Thanks.

    Read the article

  • Facing error in apple multitasking code

    - by user366584
    Actually I am working for multitasking and facing error please assist me, as I need to work on background application and also in foreground application - (void)applicationDidEnterBackground:(UIApplication *)application { UIApplication* app = [UIApplication sharedApplication]; // Request permission to run in the background. Provide an // expiration handler in case the task runs long. NSAssert(bgTask == UIBackgroundTaskInvalid, nil); bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ // Synchronize the cleanup call on the main thread in case // the task actually finishes at around the same time. dispatch_async(dispatch_get_main_queue(), ^{ if (bgTask != UIBackgroundTaskInvalid) { [app endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; } }); }]; // Start the long-running task and return immediately. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // Do the work associated with the task. // Synchronize the cleanup call on the main thread in case // the expiration handler is fired at the same time. dispatch_async(dispatch_get_main_queue(), ^{ if (bgTask != UIBackgroundTaskInvalid) { [app endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; } }); }); }

    Read the article

< Previous Page | 156 157 158 159 160 161 162 163 164 165 166 167  | Next Page >