When I Ctrl C my program on linux I often get output that looks similar to a stack-dump (a crash).
Can I catch the Ctrl-C signal and exit gracefully?
Thanks!
I am trying to get the html for this link http://slashdot.org/firehose.pl?op=rss&content_type=rss&orderby=createtime&fhfilter="home:vamsivanka"
Dim myRequest As WebRequest
Dim myResponse As WebResponse
Try
myRequest = System.Net.WebRequest.Create(url)
myRequest.Timeout = 10000
myResponse = myRequest.GetResponse()
Dim rssStream As Stream = myResponse.GetResponseStream()
Dim rssDoc As New XmlDocument()
rssDoc.Load(rssStream)
Catch ex As Exception
End Try
But the rssDoc.Load is giving me an error '--' is an unexpected token. The expected token is ''. Line 81, position 5.
Please Let me know your suggestions.
Hi All,
I am writing an application that can record a 3GP video.
I have tried both MMAPI and Invoke API. But have following issues.
Using MMAPI:
1. When I record to stream, It records video in RIMM streaming format. when I try to play this video player gives error "Unsupported media format.".
2. When I record to a file. It will create a file of size 0.
Using Invoke API:
1. In MMS mode it does not allow to record a video more than 30 seconds.
2. In Normal mode size of the file is very large.
3. Once I invoke camera application I do not have any control on application.
Here is my source code:
_player = javax.microedition.media.Manager
.createPlayer("capture://video?encoding=video/3gpp&mode=mms");
// I have tried every encoding returns from System.getProperty("video.encodings") method
_player.realize();
_videoControl = (VideoControl) _player.getControl("VideoControl");
_recordControl = (RecordControl) _player.getControl("RecordControl");
_volumeControl = (VolumeControl) _player.getControl("VolumeControl");
String videoPath = System.getProperty("fileconn.dir.videos");
if (videoPath == null) {
videoPath = "file:///store/home/user/videos/";
}
_recordControl.setRecordLocation(videoPath + "RecordedVideo.3gp");
_player.addPlayerListener(this);
Field videoField = (Field) _videoControl.initDisplayMode(
VideoControl.USE_GUI_PRIMITIVE,
"net.rim.device.api.ui.Field");
_videoControl.setVisible(true);
add(videoField);
_player.start();
ON start menu item Selection:
try {
_recordControl.startRecord();
} catch (Exception e) {
_player.close();
showAlert(e.getClass() + " " + e.getMessage());
}
On stop menuItem selection:
try {
_recordControl.commit();
} catch (Exception e) {
_player.close();
showAlert(e.getClass() + " " + e.getMessage());
}
Please let me if I am doing something wrong.
Thanks,
Pankaj
Hi, I have this script which loads external content:
<script type="text/javascript">
var http_request = false;
function makePOSTRequest(url, parameters) {
http_request = false;
if (window.XMLHttpRequest) {
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) {
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
result = http_request.responseText;
document.getElementById('opciones').innerHTML = result;
} else {
alert('Hubo un problema con la operación.');
}
}
}
function get(obj) {
var poststr = "port_post=" + encodeURI( document.getElementById("port-post").value );
makePOSTRequest('http://www.site.com/inc/metaform.php?opcion='+ encodeURI( document.getElementById("port-post").value ), poststr);
}
</script>
This is the select that retrieves the content:
<select name="port_post" id="port-post" onchange="get(this.parentNode);">
<option value="1">Select one...</option>
<option value="2">Pear</option>
<option value="3">Pineapple</option>
</select>
And this is the container div:
<div id="opciones">Default content</div>
All I whish to know is how I can unset the ajax loading when I change the selection to "Select one...". I wish to say, how restoring the Default content once the "Select one..." option is selected.
Hello!
I cannot find a simple example about my question above: how can i detect the end of a method chain?
I'm just looked Zend_Db_Select for example but this one is too complex for this simple question i think.
Is it possible to catch the 'end' of a method chain in PHP?
thanks,
fabrik
Does anybody know if you can access the SaevFileDialog control that's used by the WebBrowser control? Once somebody saves the webpage being displayed I need to catch where the files have been created; however I can't seem to find any events/members that allow me access to that information.
Regarding the terminate handler,
As i understand it, when something bad happens in code, for example when we dont catch an exception,
terminate() is called, which in turn calls abort()
set_terminate(my_function) allows us to get terminate() to call a user specified function my_terminate.
my question is: where do these functions "live" they don't seem to be a part of the language, but work as if they are present in every single cpp file, without having to include any header file.
hi guys,
if i put a thread to sleep in a loop, netbeans gives me a caution saying Invoking Thread.sleep in loop can cause performance problems. However, if i were to replace the sleep with join, no such caution is given. Both versions compile and work fine tho. My code is below (check the last few lines for "Thread.sleep() vs t.join()").
public class Test{
//Display a message, preceded by the name of the current thread
static void threadMessage(String message) {
String threadName = Thread.currentThread().getName();
System.out.format("%s: %s%n", threadName, message);
}
private static class MessageLoop implements Runnable {
public void run() {
String importantInfo[] = {
"Mares eat oats",
"Does eat oats",
"Little lambs eat ivy",
"A kid will eat ivy too"
};
try {
for (int i = 0; i < importantInfo.length; i++) {
//Pause for 4 seconds
Thread.sleep(4000);
//Print a message
threadMessage(importantInfo[i]);
}
} catch (InterruptedException e) {
threadMessage("I wasn't done!");
}
}
}
public static void main(String args[]) throws InterruptedException {
//Delay, in milliseconds before we interrupt MessageLoop
//thread (default one hour).
long patience = 1000 * 60 * 60;
//If command line argument present, gives patience in seconds.
if (args.length > 0) {
try {
patience = Long.parseLong(args[0]) * 1000;
} catch (NumberFormatException e) {
System.err.println("Argument must be an integer.");
System.exit(1);
}
}
threadMessage("Starting MessageLoop thread");
long startTime = System.currentTimeMillis();
Thread t = new Thread(new MessageLoop());
t.start();
threadMessage("Waiting for MessageLoop thread to finish");
//loop until MessageLoop thread exits
while (t.isAlive()) {
threadMessage("Still waiting...");
//Wait maximum of 1 second for MessageLoop thread to
//finish.
/*******LOOK HERE**********************/
Thread.sleep(1000);//issues caution unlike t.join(1000)
/**************************************/
if (((System.currentTimeMillis() - startTime) > patience) &&
t.isAlive()) {
threadMessage("Tired of waiting!");
t.interrupt();
//Shouldn't be long now -- wait indefinitely
t.join();
}
}
threadMessage("Finally!");
}
}
As i understand it, join waits for the other thread to complete, but in this case, arent both sleep and join doing the same thing? Then why does netbeans throw the caution?
I have a scale that connect to PC through RS232, I send "W" to receive the weight. The scale sends the weight all the time as it's read. How do I catch the weight that is being read?
Can i get any C# sample code?
hi ,
i am making a app which takes photo on button click
i have camera.java which operates camera and takes photo
how to i call it on the below event?
public void onClick(DialogInterface arg0, int arg1) {
setContentView(R.layout.startcamera);
}
Camera .java
package neuro.com;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
public class CameraDemo extends Activity {
private static final String TAG = "CameraDemo";
Camera camera;
Preview preview;
Button buttonClick;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.startcamera);
preview = new Preview(this);
((FrameLayout) findViewById(R.id.preview)).addView(preview);
buttonClick = (Button) findViewById(R.id.buttonClick);
buttonClick.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
preview.camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
});
Log.d(TAG, "onCreate'd");
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
Log.d(TAG, "onShutter'd");
}
};
/** Handles data for raw picture */
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Log.d(TAG, "onPictureTaken - raw");
}
};
/** Handles data for jpeg picture */
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
try {
// write to local sandbox file system
// outStream = CameraDemo.this.openFileOutput(String.format("%d.jpg", System.currentTimeMillis()), 0);
// Or write to sdcard
outStream = new FileOutputStream(String.format("/sdcard/%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Log.d(TAG, "onPictureTaken - jpeg");
}
};
}
Hi all,
Currently we are using method_missing to catch for calls to SEO friendly actions in our controllers rather than creating actions for every conceivable value for a variable. What we want are URLS like this:
/students/BobSmith
and NOT /students/show/342
IS there a cleaner solution than method_missing?
Thank you!
Hi,
How to properly construct regular expression for "grep" linux program, to find all email in, say /etc directory ?
Currently, my script is following:
grep -srhw "[[:alnum:]]*@[[:alnum:]]*" /etc
It working OK - a see some of the emails, but when i modify it, to catch the one-or-more charactes before- and after the "@" sign ...
grep -srhw "[[:alnum:]]+@[[:alnum:]]+" /etc
.. it stops working at all
Also, it does't catches emails of form "[email protected]"
Help !
Hi,
I have an UITextField object in my view and want to launch a method when user press backspace button and textField is empty.
First I have to do is to create a cursor storing text length, so when cursor changes from 1 to 0 there is nothing to do.
The only way to launch the method is when text length is 0 - press backspace - remain to 0.
How to catch the event of pressing the backspace key in my UITextField ?
Thanks in advance !
I have a system with a few different databases, and I would like to check if a certain database is down, and if so display a message to the user.
Is it possible in NHibernate to check if there is an active connection to the database, without having to request data and then catch the exception?
I am trying to use exceptions for the first time
but even though it is quite a simple example I
just cannot get it to compile, I have looked
at several examples and tried coding it in
many, many different ways
but I am still not even sure exactly where
the problem is because I get namemangling
when I introduce the catch/try/throw anyway
here is my code hopefully it is something
really stupid :)
#include "Surface.h"
#include "SDL_Image.h"
using namespace std;
SDL_Surface* surface::Load(string fileName){
SDL_Surface* loadedSurface = IMG_Load(fileName.c_str());
if(loadedSurface == 0) throw 0;
//Convert surface to same format as display
loadedSurface = SDL_DisplayFormatAlpha(loadedSurface);
return loadedSurface;
}
#include "GameState.h"
#include "Surface.h"
#include<iostream>
using namespace std;
GameState::GameState(string fileName){
try{
stateWallpaper_ = surface::Load(fileName);
}
catch(int& e){
cerr << "Could not load " << fileName << endl;
}
}
Thanks in advance for any help!
EDIT: Sorry I forgot to post the error message: It is
In function `ZN14GameStateIntroC1Ev':|
-undefined reference to `__gxx_personality_sj0'|
-undefined reference to `_Unwind_SjLj_Register'|
-undefined reference to `_Unwind_SjLj_Unregister'|
In function `ZN14GameStateIntroC1Ev':|
undefined reference to `_Unwind_SjLj_Resume'|
In function `ZN14GameStateIntroC2Ev':|
-undefined reference to `__gxx_personality_sj0'|
-undefined reference to `_Unwind_SjLj_Register'|
-undefined reference to `_Unwind_SjLj_Unregister'|
obj\Release\GameStateIntro.o||In function `ZN14GameStateIntroC2Ev':|
C:\Program Files (x86)\CodeBlocks\MinGW\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\include\c++\3.4.5\ext\new_allocator.h|69|undefined reference to `_Unwind_SjLj_Resume'|
C:\MinGW\lib\libSDLmain.a(SDL_win32_main.o)||In function `redirect_output':|
\Users\slouken\release\SDL\SDL-1.2.15\.\src\main\win32\SDL_win32_main.c|219|undefined reference to `SDL_strlcpy'|
\Users\slouken\release\SDL\SDL-1.2.15\.\src\main\win32\SDL_win32_main.c|220|undefined reference to `SDL_strlcat'|
\Users\slouken\release\SDL\SDL-1.2.15\.\src\main\win32\SDL_win32_main.c|243|undefined reference to `SDL_strlcpy'|
\Users\slouken\release\SDL\SDL-1.2.15\.\src\main\win32\SDL_win32_main.c|244|undefined reference to `SDL_strlcat'|
C:\MinGW\lib\libSDLmain.a(SDL_win32_main.o)||In function `console_main':|
\Users\slouken\release\SDL\SDL-1.2.15\.\src\main\win32\SDL_win32_main.c|296|undefined reference to `SDL_strlcpy'|
\Users\slouken\release\SDL\SDL-1.2.15\.\src\main\win32\SDL_win32_main.c|301|undefined reference to `SDL_GetError'|
\Users\slouken\release\SDL\SDL-1.2.15\.\src\main\win32\SDL_win32_main.c|312|undefined reference to `SDL_SetModuleHandle'|
C:\MinGW\lib\libSDLmain.a(SDL_win32_main.o)||In function `WinMain@16':|
\Users\slouken\release\SDL\SDL-1.2.15\.\src\main\win32\SDL_win32_main.c|354|undefined reference to `SDL_getenv'|
\Users\slouken\release\SDL\SDL-1.2.15\.\src\main\win32\SDL_win32_main.c|386|undefined reference to `SDL_strlcpy'|
C:\MinGW\lib\libSDLmain.a(SDL_win32_main.o)||In function `cleanup':|
\Users\slouken\release\SDL\SDL-1.2.15\.\src\main\win32\SDL_win32_main.c|158|undefined reference to `SDL_Quit'|
**
try
{
$con->beginTransaction();
$this->doSave($con);
$con->commit();
}
catch (Exception $e)
{
$con->rollBack();
throw $e;
}
The code above is quite standard an approach to deal with transactions,
but my question is:what if $con->rollBack() also fails?
It may cause db lock,right?If so,what's the perfect way to go?
I'm working on a Serpinski triangle program that asks the user for the levels of triangles to draw. In the interests of idiot-proofing my program, I put this in:
Scanner input= new Scanner(System.in);
System.out.println(msg);
try {
level= input.nextInt();
} catch (Exception e) {
System.out.print(warning);
//restart main method
}
Is it possible, if the user punches in a letter or symbol, to restart the main method after the exception has been caught?
I have a SurfaceView and I want the Bitmap Logo inside it in the canvas to be movable
What I'm doing wrong ?
static float x, y;
Bitmap logo;
SurfaceView ss = (SurfaceView) findViewById(R.id.svSS);
logo = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
x = 40;
y = 415;
ss.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent me) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
switch(me.getAction()) {
case MotionEvent.ACTION_DOWN:
x = me.getX();
y = me.getY();
break;
case MotionEvent.ACTION_UP:
x = me.getX();
y = me.getY();
break;
case MotionEvent.ACTION_MOVE:
x = me.getX();
y = me.getY();
break;
}
return true;
}
});
public class OurView extends SurfaceView implements Runnable{
Thread t = null;
SurfaceHolder holder;
boolean isItOK = false;
public OurView(Context context) {
super(context);
holder = getHolder();
}
public void run (){
while (isItOK == true){
//canvas DRAWING
if (!holder.getSurface().isValid()){
continue;
}
Canvas c = holder.lockCanvas();
c.drawARGB(255, 200, 100, 100);
c.drawBitmap(logo, x,y,null);
holder.unlockCanvasAndPost(c);
}
}
public void pause(){
isItOK = false;
while(true){
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
}
t = null;
}
public void resume(){
isItOK = true;
t = new Thread(this);
t.start();
}
}
Now the surface view is just black .. nothing happens also its not colored 200, 100, 100
In my project I can successfully test database code. I'm using Spring, Hibernate, HSQL, junit and Maven.
The catch is that currently I have to launch HSQL manually prior to running the tests. What is the best way to automate the launching of HSQL with the technologies being used?
I'm using the following code to check the access on selected folder. but it's not working.
private boolean writeAccess(String path){
try {
AccessController.checkPermission(new FilePermission(path, "read,write"));/*,*/
// Has permission
return true;
}
catch (SecurityException e) {
// Does not have permission
return false;
}
}
wt is prblm in it. and is there any other options to check the existance and access on the folders/directories?
I have written the code it works on Android 2.2 API but it does not work on Android 4.0
String url = textUrl.getText().toString();
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try
{
HttpResponse response = client.execute(request);
textResult.setText(HttpHelper.request(response));
}
catch (Exception e) {
// TODO: handle exception
textResult.setText("Failed");
}
Hi,
I created one blackberry application which will play a video on a button click.This is my code,
invocation=new Invocation("file:///SDCard/Blackberry/videos/PlayingVideo/funny.mp4");
registry=Registry.getRegistry("net.rim.device.api.content.BlackBerryContentHandler");
try
{
registry.invoke(invocation);
}
catch(Exception e)
{
}
Now i can play the Video file.After clicking the Back button the native player is going to the background.It always running in the background.But i want to close that player.I have no idea about how to do it.Anybody knows please help me.
Apologies if my terminology is off, I'm new to C#. I'm trying to use an ApplicationContext file to store mysql conn values, like dbname, username, password. The class with mysql conn string is "using" the namespace for the ApplicationContext, but when I print out the connection string, the values are making it.
A friend said, "I'm not initializing it" but couldn't stay to expand on what "it" was.
and the "Console.WriteLine("1");" in ApplicationContext.cs never shows up. Do I need to create an ApplicationContext object and the call Initialize() on that object?
Thanks for any help.
ApplicationContext.cs:
namespace NewApplication.Context
{
class ApplicationContext
{
public static string serverName;
public static string username;
public static string password;
public static void Initialize()
{
//need to read through config here
try
{
Console.WriteLine("1");
XmlDocument xDoc = new XmlDocument();
xDoc.Load(".\\Settings.xml");
XmlNodeList serverNodeList = xDoc.GetElementsByTagName("DatabaseServer");
XmlNodeList usernameNodeList = xDoc.GetElementsByTagName("UserName");
XmlNodeList passwordNodeList = xDoc.GetElementsByTagName("Password");
}
catch (Exception ex)
{
// MessageBox.Show(ex.ToString());
//TODO: Future write to log file
username = "user";
password = "password";
serverName = "localhost";
}
}
}
}
MySQLManager.cs:
note: dbname is the same as the username as you'll see in the code, I copied this from a friend who does that.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data;
using MySql.Data.MySqlClient;
using NewApplication.Context;
namespace NewApplication.DAO
{
class MySQLManager
{
private static MySqlConnection conn;
public static MySqlConnection getConnection()
{
if (conn == null || conn.State == System.Data.ConnectionState.Closed)
{
string connStr = "server=" + ApplicationContext.serverName +
";user=" + ApplicationContext.username + ";database=" + ApplicationContext.username + ";port=3306;password=" +
ApplicationContext.password + ";";
conn = new MySqlConnection(connStr);
try
{
Console.WriteLine("Connecting to MySQL... ");
Console.WriteLine("Connection string: " + connStr + "\n");
conn.Open();
// Perform databse operations
// conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
return conn;
}
}
}
and, thanks for still reading, this is the code that uses the two previous files:
class LogDAO
{
MySqlConnection conn;
public LogDAO()
{
conn = MySQLManager.getConnection();
}
Thank you,
rd42
can I do something like this:
using (var scope = new TransactionScope())
{
using (var conn = new SqlConnection(Cs))
{
using (var cmd = conn.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
...
scope.complete();
}
}
}
is going to be the same thing as using the SqlTransaction with catch(){rollback;}