text
stringlengths
8
267k
meta
dict
Q: calling a web service from an android application I am using the following code which i found on internet to call a web service from my android app: public class WebServiceActivity extends Activity { private static final String SOAP_ACTION = "http://tempuri.org/HelloWorld"; private static final String METHOD_NAME = "HelloWorld"; private static final String NAMESPACE = "http://tempuri.org/"; private static final String URL = "http://192.168.1.19/TestWeb/WebService.asmx"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button getquote = (Button) findViewById(R.id.getquote); getquote.setOnClickListener(new OnClickListener() { public void onClick(View v) { TextView result1; result1=(TextView)findViewById(R.id.result1); try { SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); EditText CompanyName = (EditText) findViewById(R.id.CompanyName); String val1 = (CompanyName.getText().toString()); request.addProperty("passonString", val1); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet=true; envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); androidHttpTransport.call(SOAP_ACTION, envelope); Object result = (Object)envelope.getResponse(); result1.setText(result.toString()); } catch (Exception e) { result1.setText(e.getMessage()); } } }); } } I am getting error that application is not responding.I am new in the field , please help. Thanks in advance A: Put your web service request as a background task. Usually time taken by a network activity is unpredictable. If you use above, the UI Thread will block. That is why it says "Application not responding". I found this great article. http://www.vogella.de/articles/AndroidPerformance/article.html#concurrency Have a look at 2. Background Processing Your example can be modified as following. public class WebServiceActivity extends Activity { private static final String SOAP_ACTION = "http://tempuri.org/HelloWorld"; private static final String METHOD_NAME = "HelloWorld"; private static final String NAMESPACE = "http://tempuri.org/"; private static final String URL = "http://192.168.1.19/TestWeb/WebService.asmx"; TextView result1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); result1 = (TextView) findViewById(R.id.result1); Button getquote = (Button) findViewById(R.id.getquote); getquote.setOnClickListener(new OnClickListener() { public void onClick(View v) { // push soap request into background. new Thread(new Runnable(){ @Override public void run() { doSoapRequest(); } },"DOINBACKGROUND"); } }); } private void doSoapRequest(){ try { SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); EditText CompanyName = (EditText) findViewById(R.id.CompanyName); String val1 = (CompanyName.getText().toString()); request.addProperty("passonString", val1); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE( URL); androidHttpTransport.call(SOAP_ACTION, envelope); Object result = (Object) envelope.getResponse(); // result1.setText(result.toString()); // update UI data in a Handler Message msg = new Message(); msg.obj = result.toString(); result1Handler.sendMessage(msg); } catch (Exception e) { // result1.setText(e.getMessage()); // update UI data in a Handler Message msg = new Message(); msg.obj = e.getMessage(); result1Handler.sendMessage(msg); } } private Handler result1Handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); result1.setText(msg.obj.toString()); } }; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7605866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I run a set of junit tests in multiple test classes? In my webapp, there are multiple screens that have common webElements. I want to assert that all these common elements exist on each page. But I don't want to put all my asserts into a single utility function that will abort halfway through if one assert fails. I want to have individual test cases for each assert and run that set of tests in multiple test classes (one for each page). I read that inheritance is a bad idea because then you have to dig deeper than the immediate test class to see all the tests that are being run. But at the same time, I don't want to maintain multiple copies of tests that are common across pages. A: The same rules apply to test development that apply to the rest of your development, you do what you and your team find the easiest to understand. You have the following options: * *Inheritance: defining tests in a parent class. I have used inheritance with JUnit tests, including tests in the parent class. This worked and worked well, and the main advantage was that it saved duplicating code. Disadvantages: you have to look in multiple places for your tests. When you double click on the test name in the Junit view in Eclipse, it takes you to the parent class, which is sometimes confusing. *Have a class specifically for testing the common features of your pages, lets call it PageTest. PageTest would use @Parameterized to test all of the pages. Advantages: All of your tests for common stuff is centralized. Disadvantages, if you add a page, you need to add the page to the list. You can avoid having to add stuff to the list by using reflection, if that's possible. We had one set of tests which searched the classpath for any class which inherited from a certain class (struts Action in this case) and ran some tests on that class. Of the two options, I would choose the former because it's less work; everything for a single page is on one place, and you never 'forget' to test the common elements. But it's your project, do what works for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7605875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iPhone App :show direction using Map in My iPhone App How Can I show directions from current location to End Point? is there any built in component or facility available on iphone which can show maps and direction using GPS and built in compass? A: If you mean taking the user to the maps application based on two points, then you can do it like this: * *Create an NSURL that looks like this: NSURL *URL = [NSURL URLWithString:@"http://maps.google.com/maps?saddr=%f,%f&daddr=%f,%f"]; You plug in your starting address and destination (in lat. and long.) appropriately. *Tell your application to open the URL [[UIApplication sharedApplication] openURL:URL]; It should take you to the maps application automatically! A: try this:- NSString *urlstring=[NSString stringWithFormat:@"http://maps.google.com/?saddr=%f,%f&daddr=%f,%f",sourcelocation.latitude,sourcelocation.longitude,destinationlocation.latitude,destinationlocation.longitude]; [[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlstring]]; A: NSString *Urlstring=[NSString stringWithFormat:@"http://maps.google.com/?saddr=%@&daddr=%@",from_address,to_address]; [[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlstring]]; This will give clear direction mentioning the source address and destination address.
{ "language": "en", "url": "https://stackoverflow.com/questions/7605879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Spring Web Flow - Issue of Reusing Subflow This is probably a design issue then coding issue. We have an existing ordering interface which we are trying to convert into Spring Web Flow. For each product we have a few reusable components such as contact details, contract details, order details, pricing ... Now we want to put them on a single page but still keep it reusable such that it can be used for different product. eg - I have a Service Details page on which I have three different components called: Host Details IP Details Backup Details Each of these components needs to be reused in other products, so the question is how to achieve this? Problem: If i create a subflow called "Service Details" then the view associated will have to have all three jsps included and the subflow's model attribute will be a composite attribute which will have to bind all above values such as Host Details, IP Details, Backup Details .... I am never going to reuse entire page, only the components are needed to be reused across different pages. A: This isn't really specific to webflow - you want to create re-usable view components which are related to components in your model? Its true that in webflow you can only do automatic binding & validation against a single object in one of the variable scopes, so I suggest that you create a bean to hold these three components, e.g. public class Holder implements Serializable { private HostDetails; private IpDetails; private BackupDetails; //getters & setters } Then the 'model' attribute in your flow would refer to an instance of this Holder class. You just need to remember that if you want to bind a submitted field to e.g. HostDetails, your input should use dot notation to reference the field (including 'holder'): <input type="text" name="holder.hostDetails.hostName"/> Then, in order to re-use components in your view layer, create one JSP which includes the other components. I like to create .tag files for this purpose, one tag file responsible for rendering each component. <%!-- This is the main JSP --%> <%!-- Include modules using tag files --%> <content:hostDetails details="${holder.hostDetails}" nestedPath="holder.hostDetails"/> <content:ipDetails details="${holder.ipDetails}" nestedPath="holder.ipDetails"/> <content:backupDetails details="${holder.backupDetails}" nestedPath="holder.backupDetails "/> I put the 'nestedPath' attribute there so that the tag file is modular and re-usable even when included in different pages (even without the Holder.class). There might be a more elegant way of doing that bit... I haven't shown the tag file implementation here, but look here: http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPTags5.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7605883", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Codeigniter selecting data with multiple id's Here is an example of my code and an explanation what I am trying to do. At the beginning of the code I am selecting three variables in my database. I then compare them to a function that determines the distance, if the distance is within the given distance then I have the id of that record. This will result in multiple id's. Could be five or none, depends on the variables given. What I need to know is once I have determined that id I need to use I need to put into either a variable or something else that is manageable. Basically I need to take the list and query the database again to get the list of details from the database. The list will return objects that will later be past to json_encode for processing. What I need to know is what is the best way to put each id into a variable and pass it to a database query and get the results I need. I've tried using $dbStations->where('_id', '34,33,45') but it only returns the first value. I need something like WHERE _id = 34 AND 33 AND 45 if possible. I am using Codeigniter for my framework and I have went over the documentation and I have not found a solution. EDIT: Now that I have the the data selected from the database I need to get the distance to be displayed at the end of each record retrieved. Example of json: {"details":[{"country":"United States","_id":"3892","lat":"39.954559","lng":"-82.837608","admin_level_1":"Ohio","locale":"Columbus"}]} This is what it needs to be, keep in mind that distance is not in the database, it is calculated on the fly. Example of json: {"details":[{"country":"United States","_id":"3892","lat":"39.954559","lng":"-82.837608","admin_level_1":"Ohio","locale":"Columbus", "distance": "1.2 Mi"}]} Any ideas on how to get ths distance that is caculcated to be appended to the end of each result? $dbStations->select('lat'); $dbStations->select('lng'); $dbStations->select('_id'); $stations = $dbStations->get('stDetails'); foreach ($stations->result() as $station) { $lat2 = $station->lat; $lng2 = $station->lng; $stId = $station->_id; $distance = $this->distance->gpsdistance($lat1, $lng1, $lat2, $lng2, "M"); if ($distance <= $rad) { //at this point the code has determined that this id is within //the preferred distance. $stationArr[] = $stId; } } $dbStations->select('country, _id, lat, lng, admin_level_1, locale'); $dbStations->where_in('_id', $stationArr); $stations = $dbStations->get('stationDetails'); echo json_encode(array('stations' => $stations->result())); } A: Try using where_in() $ids = array(33, 34, 45); $dbStations->where_in('id', $ids); // Produces: WHERE id IN (33, 34, 45) This will return records that have the ID of 33, 34, 45
{ "language": "en", "url": "https://stackoverflow.com/questions/7605884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is more efficient to join T2 to T1 rather than T1 to T2 when T1 has many T2 with a condition held in T2? Or it's the same? I know the followings queries return the same: SELECT `cimgs`.* FROM `cimgs` INNER JOIN `cimgs_tags` ON `cimgs_tags`.`cimg_id` = `cimgs`.`id` WHERE `cimgs_tags`.`tag_id` IN (1, 2, 3, 4, 5) AND (cimgs.id != 1) SELECT `cimgs`.* FROM `cimgs_tags` INNER JOIN `cimgs` ON `cimgs`.`id` = `cimgs_tags`.`cimg_id` WHERE `cimgs_tags`.`tag_id` IN (1, 2, 3, 4, 5) AND (cimgs.id != 1) But, at a first glance I would say that the first one duplicates the cimgs table for each tag before checking the conditions, when the second one check the conditions and then it joins the corresponding tables... Though I don't know if MySQL detects and optimize this automatically and these two queries have a similar performance? A: The query optimizer will do this for you. It will use the index statistics, which you should keep up to date with ANALYSE TABLE. You can force te join order using STRAIGHT_JOIN though, and you can force to use certain indexes, too. You can do an explain: EXPLAIN SELECT `cimgs`.* FROM `cimgs` INNER JOIN `cimgs_tags` ON `cimgs_tags`.`cimg_id` = `cimgs`.`id` WHERE `cimgs_tags`.`tag_id` IN (1, 2, 3, 4, 5) AND (cimgs.id != 1) EXPLAIN SELECT `cimgs`.* FROM `cimgs_tags` INNER JOIN `cimgs` ON `cimgs`.`id` = `cimgs_tags`.`cimg_id` WHERE `cimgs_tags`.`tag_id` IN (1, 2, 3, 4, 5) AND (cimgs.id != 1) to see the differences. Offcourse, for a LEFT JOIN or RIGHT JOIN, there is a semantic difference. A: It doesn't matter from INNER JOINS. In the same fashion neither does WHERE clause order WHERE `cimgs_tags`.`tag_id` IN (1, 2, 3, 4, 5) AND (cimgs.id != 1) WHERE (cimgs.id != 1) AND `cimgs_tags`.`tag_id` IN (1, 2, 3, 4, 5) * *The optimiser knows this *SQL is declarative not procedural. That is, you say "what" and the optimiser decides "how" A: I believe this question answers your question. "For inner joins, the order does not matter. For outer joins the order does matter. If you want to force a certain order, you can use a STRAIGHT_JOIN."
{ "language": "en", "url": "https://stackoverflow.com/questions/7605891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UIScrollview in a UIModalPresentationFormSheet I'm having some issues with a UIScrollView inside of a modal view, specifically when I use setModalPresentationStyle:UIModalPresentationFormSheet. Whenever I use the UIModalPresentationFormSheet, it resizes the UIScrollView in the modal view to a small square that can't show all the information needed, regardless if I set the XIB file or in code, it always ends up small. If I change the modal view type to UIModalPresentationPageSheet, it works perfectly. What can I do to fix this? Or am I doing anything wrong by doing this? Thanks in advance! A: Fixed it, ended up having to cheat my way into it. I think it may be a bug in Xcode. I made the UIScrollView large (as if it was to be shown on the full screen) in the XIB file, and for whatever reason it scaled down to the UIModalPresentationFormSheet size. All of my other UI elements were the same size, only the UIScrollView scaled down. Leaving this for anyone that runs in to the same thing!
{ "language": "en", "url": "https://stackoverflow.com/questions/7605893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to change the output volume of any sound that comes from your site? This may sound weird even to me but whatever, I'll ask it and get it done with. I was wondering if there is any way to alter the output volume of all noisy stuff of your site or of a particular element. I'll appreciate any info about it, like for example a third party plugin, whether is technically impossible or whatever. I tagged it as javascript because I have no idea what to tag it with. Thanks A: I cannot provide an easy solution, but I can provide some info. Check out https://github.com/jussi-kalliokoski/audiolib.js for a HTML5/javascript audio library. The guys at ofmlabs.org live and breathe this stuff.
{ "language": "en", "url": "https://stackoverflow.com/questions/7605896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: OCaml: Iterating through a list and skipping elements if of the wrong constructor This may seem like an odd thing to do, and you're certainly welcome to suggest a better way to do it. Here's my goal: I want to scroll through each element of a list passed into a function. If it's of constructor Y, then I want to call some function on it. If it's of constructor Z, I want to skip it. If there's a way to check this in an if statement, then that seems like the way to go since I don't need to write an else. However, I only know how to check this in a match. For example: let myFunct list = List.iter (fun x -> match x with | Y y -> otherFunction y ) list;; Now, this gives me a warning about not being able to handle Z. So I could throw something in there like... let myFunct list = List.iter (fun x -> match x with | Y y -> otherFunction y | Z z -> (*skip*) ) list;; Of course, I can't just leave Z's match blank.... How can I accomplish what I'm trying to do? A: Just return unit (ie, ()) the Z case. Are you sure you want List.iter. It is primarily used to apply a function for its side effect. A more idiomatic approach in functional programs is to filter the list using List.filter and then apply a transformation to all the remaining elements using List.map. A: You could use List.filter to filter the list based on the condition, then use List.iter on the filtered list. See the docs here for more info about the methods in the list module. http://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html I don't have access to the OCaml compiler at the moment but the code would look something like this: List.iter (fun x -> ....) (List.filter (fun x -> ...) mylist) A: Lambdageek's answer for List.iter is right. You just need to use () as your result in any case where you don't have anything to do. All the different cases of your match expression should return () when you're doing an iteration. That's what List.iter is all about. Everyone else is (rightly, in my opinion) worried that you might not really want to use List.iter. It might be the first thing you think of when coming from other (imperative) languages, but iteration per se isn't at all as commonly used when doing functional programming. If you're learning OCaml in a course of some kind, it's even less likely that you want to use List.iter. A course on OCaml would definitely begin by covering the functional parts. To think functionally you want to think about transforming values from one form to another (i.e., applying functions to them). Let's say you did want to use List.filter. Then, as you say, you'll end up doing a match expression, but instead of returning () in all the different cases, you'd want to return a Boolean (true or false) in each case. If you return true, the value will be included in the resulting list. If you return false, the value won't be included in the resulting list. Once again, that's what List.filter is all about. Here's some code that returns a new list containing just the elements of a given list that have a Z constructor. let myFunc list = List.filter (fun x -> match x with Z _ -> true | _ -> false) list I'm not sure this helps, but I think what I'm trying to say is that using match isn't difficult. You just need to cover every case. This is good, you want your code to work in every case!
{ "language": "en", "url": "https://stackoverflow.com/questions/7605900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to support includelevel in Visual Studio 2010 At school we use c++/g++ compilers on Linux to support includelevel. This allow us to write an app, include a main that proves the functions work, and then to include that file in another program to use it's functions. The theory is that includelevel will block out code when you include so that you don't duplicate things (like having two mains). Is there a way to get Visual Studio 2010 to recognize includelevel? When compiling, it simply says there are two mains (which there are, but one is blocked off with include level) and fails to compile. I have been just commenting out code in the included, so that it compiles in VS2010, then uncommenting when pushing to the school server (Linux) to compile for submission. Ex: // file: sort.cpp #include <iostream> using namespace std; void BubbleSort(int arr[], int numitems, int &bcost); // Fancy sorting function description #if __INCLUDE_LEVEL__ < 1 int main() { //fancy program that proves the sorting function works return 0; } #endif void BubbleSort(int arr[], int numitems, int &bcost) { // Fancy sorting function code } ---------------------------------------------------------- // file: myapp.cpp #include <iostream> #include "sort.cpp" using namespace std; int main() { //fancy application code that uses functions from the sort program return 0; } A: What I believe you are doing is writing a test(s) in the same source file as the functions they test. While this may be handy for a simple program, once it becomes more complicated the standard practice is to extract out the test functions into a seperate source file, and compile it into a seperate test executable (or DLL in some cases). A simple structure that I've used before is to have a library project that implements the core functionality, have another project that contains the main function and compiles to the 'real' program, and have a third project that contains the tests and its own main function that runs them. It's also non-standard to include a source/implementation (.cpp) file from another.
{ "language": "en", "url": "https://stackoverflow.com/questions/7605902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you get a simple camera program working for Android? I just started programming in Java, and I need to get a simple application up that shows the camera, takes a picture, and sends that picture data somewhere. I have been searching all over the web trying to find a good camera tutorial that worked as expected, but apparently they all require some inner knowledge that I do not have yet. On this page, commonsWare pointed to code that had some sample code in it for using the camera. I have taken the PictureDemo code and got it running with no errors. However, it only brings up a black screen. I assume this is because the program is not actually activating the preview, or camera in the main function, but every time I try adding the code I think I need, I am getting exceptions. So my question is, what do I need to add in the main function to get the camera going? Or is there a better tutorial somewhere that I can see simple basic code for getting the camera up? package assist.core; import android.app.Activity; import android.graphics.PixelFormat; import android.hardware.Camera; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.KeyEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.widget.Toast; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; public class MainActivity extends Activity { private SurfaceView preview = null; private SurfaceHolder previewHolder = null; private Camera camera = null; private boolean inPreview = false; /** * */ @Override public void onCreate(Bundle savedInstanceState) { //Call the parent class super.onCreate(savedInstanceState); setContentView(R.layout.main); preview = (SurfaceView) findViewById(R.id.preview); previewHolder = preview.getHolder(); previewHolder.addCallback(surfaceCallback); previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } @Override public void onResume() { super.onResume(); //Get the camera instance camera = CameraFinder.INSTANCE.open(); } @Override public void onPause() { if (inPreview) { camera.stopPreview(); } camera.release(); camera = null; inPreview = false; super.onPause(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_CAMERA || keyCode == KeyEvent.KEYCODE_SEARCH) { if (inPreview) { camera.takePicture(null, null, photoCallback); inPreview = false; } return(true); } return(super.onKeyDown(keyCode, event)); } private Camera.Size getBestPreviewSize(int width, int height, Camera.Parameters parameters) { Camera.Size result = null; for (Camera.Size size : parameters.getSupportedPreviewSizes()) { if (size.width <= width && size.height <= height) { if (result == null) { result=size; } else { int resultArea = result.width * result.height; int newArea = size.width * size.height; if (newArea > resultArea) { result = size; } } } } return(result); } SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() { public void surfaceCreated(SurfaceHolder holder) { try { camera.setPreviewDisplay(previewHolder); } catch (Throwable t) { Log.e("MainActivity-surfaceCallback", "Exception in setPreviewDisplay()", t); Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_LONG).show(); } } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Camera.Parameters parameters = camera.getParameters(); Camera.Size size = getBestPreviewSize(width, height, parameters); if (size != null) { parameters.setPreviewSize(size.width, size.height); parameters.setPictureFormat(PixelFormat.JPEG); camera.setParameters(parameters); camera.startPreview(); inPreview = true; } } public void surfaceDestroyed(SurfaceHolder holder) { // no-op } }; Camera.PictureCallback photoCallback = new Camera.PictureCallback() { public void onPictureTaken(byte[] data, Camera camera) { new SavePhotoTask().execute(data); camera.startPreview(); inPreview = true; } }; class SavePhotoTask extends AsyncTask<byte[], String, String> { @Override protected String doInBackground(byte[]... jpeg) { File photo = new File(Environment.getExternalStorageDirectory(), "photo.jpg"); if(photo.exists()) { photo.delete(); } try { FileOutputStream fos = new FileOutputStream(photo.getPath()); fos.write(jpeg[0]); fos.close(); } catch (java.io.IOException e) { Log.e("MainActivity", "Exception in photoCallback", e); } return(null); } } } Update As for the exceptions I was getting, if I tried making the main function like the code below, public void onCreate(Bundle savedInstanceState) { //Call the parent class super.onCreate(savedInstanceState); setContentView(R.layout.main); preview = (SurfaceView) findViewById(R.id.preview); previewHolder = preview.getHolder(); previewHolder.addCallback(surfaceCallback); previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); Camera.Parameters parameters = camera.getParameters(); parameters.setPictureFormat(PixelFormat.JPEG); camera.setParameters(parameters); try { //Start the camera preview display camera.setPreviewDisplay(previewHolder); camera.startPreview(); } catch (IOException ex) { Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex); } } I get "The application has stopped unexpectedly. Please Try again." I was basically trying to follow the steps that the android documention specifies. I also tried putting this code into the onResume function after the camera object is retrieved, and then calling this.onResume. A: this is a fully functional camera working with Intents (I am calling the camera immediately, you would obviously include a button or menu item). It saves the image to the gallery and to root as Pic.jpg and then displays the captured image. this answer is an expanded and complete version of this EXCELLENT snippet by Aleksander O. import java.io.File; import android.app.Activity; import android.content.ContentResolver; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.Toast; public class CallCameraActivity extends Activity { final int TAKE_PICTURE = 1; private Uri imageUri; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); takePhoto(); } public void takePhoto() { Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); File photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg"); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo)); imageUri = Uri.fromFile(photo); startActivityForResult(intent, TAKE_PICTURE); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case TAKE_PICTURE: if (resultCode == Activity.RESULT_OK) { //Uri imageUri; Uri selectedImage = imageUri; getContentResolver().notifyChange(selectedImage, null); ImageView imageView = (ImageView) findViewById(R.id.IMAGE); ContentResolver cr = getContentResolver(); Bitmap bitmap; try { bitmap = android.provider.MediaStore.Images.Media .getBitmap(cr, selectedImage); imageView.setImageBitmap(bitmap); Toast.makeText(this, "This file: "+selectedImage.toString(), Toast.LENGTH_LONG).show(); } catch (Exception e) { Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT) .show(); Log.e("Camera", e.toString()); } } } } } use this as your main.xml layout <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <ImageView android:id="@+id/IMAGE" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" /> </LinearLayout> strings.xml <?xml version="1.0" encoding="utf-8" standalone="no"?> <resources> <string name="hello">Hello World, TonyPicturesInc!</string> <string name="app_name">TGCam</string> </resources> A: If what you need is just open up a camera, take a picture, and get the image. then you can do: launch Camera using Intents Your above code is the integrated version. That integrates the camera into your app. I am not sure if you have the real android device to test. The simulator will show either black or "android icon" screen in replacing the real camera. so test it on real device if you weren't. And could you be more specified on the exceptions you got? A: Hey you have to look in this answer it may help you. Click here or also you can use Intent to start inbuilt camera like below Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(i, CAMERA_RESULT); And you have to get result from camera activity like below code @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK && requestCode == CAMERA_RESULT) { Bundle extras = data.getExtras(); if(extras.containsKey("data")) { Bitmap bmp = (Bitmap) extras.get("data"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 100, baos); byte[] image = baos.toByteArray(); if(image != null) { BitmapFactory.Options options=new BitmapFactory.Options(); options.inSampleSize = 5; Bitmap myImage = BitmapFactory.decodeByteArray(image , 0, image.length, options); imageView.setImageBitmap(myImage); } }else { Toast.makeText(getBaseContext(), "Please capture again", Toast.LENGTH_LONG).show(); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7605904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Must I use Fragments to get a LoaderManager? According to some of the documentation I can use a Loader in either an Activity or a Fragment but the Compatibility Package is showing that only a FragmentActivity has the getLoaderManager() method. Since the old managed cursor has been deprecated we have to use the Cursor Loader. So why should this data management function be tied to a choice of UI widgets ? It makes no sense to me. thanks P. A: Since the old managed cursor has been deprecated we have to use the Cursor Loader. No, managed cursors still work. Usually, "deprecated" in Android means "we will support this mechanism as long as we can, but we think there are better options". So why should this data management function be tied to a choice of UI widgets ? It's not. You do not have to use fragments to inherit from FragmentActivity. You are also welcome to create your own LoaderManagerCapableActivity, where you clone the relevant data members and methods from FragmentActivity (the source code is on your hard drive). However, LoaderManager has to be associated with an activity, because it is tied into the activity lifecycle, as are the managed cursors. For example, the LoaderManager instances are passed between activities via onRetainNonConfigurationInstance(). A: Yes, inorder to get loaderManager it must be associated with an a activity however it is possible to use loaders without the need of loaderManger. 1) Implement the AsynTaskLoader. 2) Instantiate the Loader you implemented in your class. 3) Register a listener for your loader so that you will get the callback once the load is complete. 4) Call the startLoading method of the loader. 5) After the load is complete the callback method will be called where you can use the loaded data for any purpose.
{ "language": "en", "url": "https://stackoverflow.com/questions/7605912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Dynamic PHP image with a PNG extension I'm trying to make an image similar to one of these: http://www.danasoft.com/vipersig.jpg Not really content wise (displaying IP addresses and headers), but more so a PHP image displayed in a PNG format (so I can use it on websites, within BB image tags). I know how to create a dynamic image, but that's only when you visit the PHP pages. Currently using this if it's matters: $image = imagecreate(200, 60); $text_color = imagecolorallocate($image, 255, 255, 0); header("Content-type: image/png"); imagestring($image, 4, 40, 30, "hello", $text_color); imagepng($image); imagecolordeallocate($text_color); imagedestroy($image); Any thoughts on how this could be achieved? A few more examples of what I'm looking for are: http://draynor.net/signatures Edit: most comments are about converting from PNG to PHP, I want to convert from PHP to PNG, just to clear it up. A: You are close, create your image like you have done above, helpful variables would be $_SERVER['REMOTE_ADDR'] (ip address), $_SERVER['HTTP_USER_AGENT'] (browser). See the reserved server variables. Format them on your image and get it looking how you want by viewing the PHP script in your browser. Then if you are using Apache, set up a rewrite rule to rewrite a URL to point to your PHP script. Here is an example: RewriteEngine On RewriteRule ^/signatures/sig.png$ /signature.php [L] This will rewrite http://yoursite.com/signatures/sig.png to http://yoursite.com/signature.php That way users can embed that png URL in their signatures or webpages to display your image. Eventually you can have multiple signatures and rewrite your URLs by rewriting special parameters (i.e. /signature/1234.png to signature.php?id=1234 or /signature/style1/1234.png to signature.php?id=1234&style=style1). A: If you're hosting on apache, you can use mod_rewrite. Here's a sample (not tested): RewriteEngine On RewriteRule /signatures/([A-Za-z0-9])+\.png$ /signature.php?name=$1 Here's a tutorial: http://www.easymodrewrite.com/ More info: http://httpd.apache.org/docs/current/mod/mod_rewrite.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7605913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: system() with powershell in vim I'm trying to write a simple function in Vim to return the results of a powershell command. I keep getting gibberish in the results though. I think this may be an encoding problem, but as you'll see the problem is strange since it "sort of works". I don't have any solution to the problem though. With the following non-default shell options set in vim: set shell=powershell set shellcmdflag=-c Given the following function: function! Test() let result = system("ls") call setline(1, result) endfunction When I run (from C:\Windows): :call Test() The following is written to my buffer: ^@^@ Directory: C:\Windows^@^@^@ Mode LastWriteTime Length Name ^@------- ....continues However when I run the following command: :r!ls I get back exactly what I would expect (i.e. the powershell results of ls) Even more interesting is when I run the command: :echo system("ls") The results look correct I've tried modifying my original function as follows: function! Test() let result = system("ls") echo result call setline(1, result) endfunction and the value echo'ed out is exactly what I would expect - yet I still see gibberish I've also tried the following modification to my function: function! Test() let result = system("ls") let conv = iconv(result, "utf-8", &enc) call setline(1, conv) endfunction But the results are exactly the same (i.e. they include the ^@^@ symbols and other gibberish) My guess as to what's happening is that powershell cmds which are redirected using > produce utf-16 output, and vim is unable to deal with this. I get the following from powershell (file in this case is the gnu32 program): PS> ls > test PS> file test test; Little-endian UTF-16 Unicode text, with CRLF, CR line terminator I've also tried playing around with $OutputEncoding, without any success, as described here: http://blogs.msdn.com/b/powershell/archive/2006/12/11/outputencoding-to-the-rescue.aspx Anyone have any ideas what I'm doing wrong here? A: I've finally figured this out. The following modification to my function does pretty much exactly what I want: function! Test() let @r = system("ls") put! r endfunction I think Artomegus is correct, the problem is really the carriage return, and not an encoding problem. As a side note, I ran into problems when I had only the following in my .vimrc file: set shell=powershell set shellcmdflag=-c With just these settings when I ran :call Test() I would get an error about Vim being unable to read the temp file. The fix for this problem is to add the following to your .vimrc file: set shell=powershell set shellcmdflag=-c set shellquote=\" set shellxquote= You must set the shellquote to be \" and shellxquote to be a blank space (i.e. empty) because by default on windows, shellxquote is set to \" which overrides the value of shellquote. This is problematic when using the system function, which runs the vimrun.exe program behind the scenes. Hopefully this helps someone else. I've been stuck on this for a long time, but now powershell works perfectly for me with Vim. A: Try instead set shellcmdflag=\ -c Explanation: Vim uses tempname() to generate a temp file path that system() reads. If &shell contains 'sh' and &shellcmdflag starts with '-' then tempname() generates a temp file path with forward slashes. Thus, if set shell=powershell set shellcmdflag=-c then Vim will try to read a temp file with forward slashes that cannot be found. A remedy is to set instead set shellcmdflag=\ -c that is, add a whitespace to &shellcmdflag so that the first character is no longer '-' and tempname() produces a temp file path with backward slashes that can be found by system().
{ "language": "en", "url": "https://stackoverflow.com/questions/7605917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: SQL Server - DATEDIFF rounding error In my sql statement, I need to retrieve rows which datediff more than 3 months. But I found that it seems have rounding problem such as From Date: 2010-09-09 To Date: 2010-12-01 select datediff(month,' 2010-09-09', '2010-12-01') It returns 3 for result. How to fix it ? thanks. regards, Joe A: You could use datediff(day,@d1,@d2) >= 90 A: Datediff(month, date1, date2) will only compare the difference between the month parts and does not take days into account. In order to calculate the real number of months between the dates, you will have to do some manual work. This answer looks to be a match to what you are asking but you may have to modify depending on your specific definition of what constitutes a 'month' difference (partial months included?).
{ "language": "en", "url": "https://stackoverflow.com/questions/7605918", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: loading gif image on above bitmap field in blackberry I've add splash screen image on bitmapfield when open my app. in thread method i get logo from httpconnection. After complete the thread execution , i delete the bitmapfield. and load the logos on that screen. I want show loading gif images on above the bitmapfield when executing the thread. Pls help. Hi, already i display image on fullscreen using bitmap field. in above bitmap field how to show loading gif image. thats my question. A: Go to this link: http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/800332/800505/800345/How_To_-_Display_an_animated_GIF.html?nodeid=1405903&vernum=0 You will get the AnimatedGIFField.java file. Save it with proper name. and write like this.... GIFEncodedImage bitmapImage=(GIFEncodedImage)GIFEncodedImage.getEncodedImageResource("loading.gif"); AnimatedGIFField image_field=new AnimatedGIFField(bitmapImage); add(image_field); NOTE: If you are Using this "loading.gif" in >6.0 versions it gives exceptoin. For this you have to rename the file as "loading.agif". Means for 7.0 version you have to use "loading.agif" not "loading.gif". Rename that file and put in the res folder and change the file name as: GIFEncodedImage.getEncodedImageResource("loading.agif") If you have any doubts come on stackOverFlow chat room name "Life for Blackberry" to clarify your and our doubts. A: Use the following class to load a GIF file into a BitmapField, To call it and display it use the code below: GIFEncodedImage yourImage =(GIFEncodedImage)GIFEncodedImage.getEncodedImageResource("picture.gif"); AnimatedGIFField yourImageField =new AnimatedGIFField(yourImage); add(yourImageField); ** * *Class: ** import net.rim.device.api.ui.UiApplication; import net.rim.device.api.system.GIFEncodedImage; import net.rim.device.api.ui.Graphics; import net.rim.device.api.ui.component.BitmapField; import net.rim.device.api.ui.Color; //A field that displays an animated GIF. public class AnimatedGIFField extends BitmapField { private GIFEncodedImage _image; //The image to draw. private int _currentFrame; //The current frame in the animation sequence. private int _width; //The width of the image (background frame). private int _height; //The height of the image (background frame). private AnimatorThread _animatorThread; public AnimatedGIFField(GIFEncodedImage image) { this(image, 0); } public AnimatedGIFField(GIFEncodedImage image, long style) { //Call super to setup the field with the specified style. //The image is passed in as well for the field to configure its required size. super(image.getBitmap(), style); //Store the image and it's dimensions. _image = image; _width = image.getWidth(); _height = image.getHeight(); //Start the animation thread. _animatorThread = new AnimatorThread(this); _animatorThread.start(); } protected void paint(Graphics graphics) { //Call super.paint. This will draw the first background frame and handle any required focus drawing. super.paint(graphics); //Don't redraw the background if this is the first frame. if (_currentFrame != 0) { //Draw the animation frame. graphics.drawImage(_image.getFrameLeft(_currentFrame), _image.getFrameTop(_currentFrame), _image.getFrameWidth(_currentFrame), _image.getFrameHeight(_currentFrame), _image, _currentFrame, 0, 0); } } //Stop the animation thread when the screen the field is on is //popped off of the display stack. protected void onUndisplay() { _animatorThread.stop(); super.onUndisplay(); } //A thread to handle the animation. private class AnimatorThread extends Thread { private AnimatedGIFField _theField; private boolean _keepGoing = true; private int _totalFrames; //The total number of frames in the image. private int _loopCount; //The number of times the animation has looped (completed). private int _totalLoops; //The number of times the animation should loop (set in the image). public AnimatorThread(AnimatedGIFField theField) { _theField = theField; _totalFrames = _image.getFrameCount(); _totalLoops = _image.getIterations(); } public synchronized void stop() { _keepGoing = false; } public void run() { while(_keepGoing) { //Invalidate the field so that it is redrawn. UiApplication.getUiApplication().invokeAndWait(new Runnable() { public void run() { _theField.invalidate(); } }); try { //Sleep for the current frame delay before the next frame is drawn. sleep(_image.getFrameDelay(_currentFrame) * 10); } catch (InterruptedException iex) {} //Couldn't sleep. //Increment the frame. ++_currentFrame; if (_currentFrame == _totalFrames) { //Reset back to frame 0 if we have reached the end. _currentFrame = 0; ++_loopCount; //Check if the animation should continue. if (_loopCount == _totalLoops) { _keepGoing = false; } } } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7605919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Function to calculate smallest set of zip codes in which all zip codes are within x miles I need a function (in any language but preferably a script) that can take an array of objects (lets say zipcodes) with latitude/longitude coordinates and return the smallest subset in which all the elements of the original array are within x (lets say 20) miles of at least 1 member of the subset. A: Here is a greedy algorithm to get you started. * *Start with an empty result set R and let S be the set of all zipcodes. *For each zipcode Zn in S, calculate the set Vn of zipcodes which are within 20 miles of Zn. *Find the set Vmax with the most elements - Add the corresponding zipcode Zmax into the result set R, and remove all the elements of Vmax from S. *With the remaining elements in S, repeat from step 2 until S is empty. Then the final set is R.
{ "language": "en", "url": "https://stackoverflow.com/questions/7605922", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: About callgrind output I am using http://valgrind.org/docs/manual/cl-manual.html to profile my application. But I have a question about it's o/p does it shows * *time consumed inside that function OR * *cpU consumed inside that function call What I guess is Currently it is showing 90% usage in curl connect. I think which is i/o bound process. So I think it is showing time consumed inside that function call. A: The callgrind tool of valgrind as stated in the document has only Instructions read (Ir) enabled by default. The tool itself is not suitable for calculating the time consumed by the function, refer here. For getting time and CPU usage I prefer running "time" command in Unix in verbose mode /usr/bin/time -v However, we can get other utilities such as ==snippet from the doc=== Cache misses on instruction reads ("I1mr"/"ILmr"), data read accesses ("Dr") and related cache misses ("D1mr"/"DLmr"), data write accesses ("Dw") and related cache misses ("D1mw"/"DLmw") by enabling the option of --cache-sim=yes Also its possible to get other utilities such as Number of executed conditional branches and related predictor misses ("Bc"/"Bcm"), executed indirect jumps and related misses of the jump address predictor ("Bi"/"Bim") by enabling option of --branch-sim=yes Finally with the help of callgrind_annotate utility we get the desired output file. ========== A: It can show various things, either instruction count (a rough proxy for CPU time), an estimated cycle count (also a rough proxy for CPU time), or various sorts of estimated cache hit/miss counts.
{ "language": "en", "url": "https://stackoverflow.com/questions/7605926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to set start time offset using setCurrentTime() I have recordings of spoken text where I would like to allow users to start an audio recording at a specific point within the recording, for example, 12.5 seconds after the start time. Using the sample code below, how can I make this happen? <audio id="player2" src="/player/media/AirReview-Landmarks-02-ChasingCorporate.mp3" type="audio/mp3" controls="controls" preload="preload"> </audio> <script> var player = $('audio,video').mediaelementplayer( { // the order of controls you want on the control bar (and other plugins below) features: ['playpause','progress','current','duration','tracks','volume','fullscreen'], audioWidth: 300, // enables Flash and Silverlight to resize to content size enableAutosize: true, startVolume: 0.7, success: function(player, node) { $('#' + node.id + '-mode').html('mode: ' + player.pluginType); } } ); </script> A: Find mediaelementplayer object: var myplayer = jQuery('#your_player')["0"]; Set time in seconds (12.5 for example): myplayer.player.setCurrentTime(12.5); myplayer.player.setCurrentRail(); :) A: I was able to figure out how to control the mediaelement.js player with external links. The player has to be initialized using a variable. <video id="player1" width="720" height="406" controls="controls" preload="none"> <source src="myvid.mp4" type="video/mp4" /> </video> <a href="#" class="mpplay">play</a> <a href="#" class="mppause">pause</a> <a href="#" class="mptime">1:00</a> <a href="#" class="mptime">0:30</a> <script> function convert(input) { var parts = input.split(':'), minutes = +parts[0], seconds = +parts[1]; return (minutes * 60 + seconds).toFixed(2); } jQuery(document).ready(function($) { // declare object for video var player = new MediaElementPlayer('#player1'); jQuery('.mpplay').click(function() { player.play(); }); jQuery('.mppause').click(function() { player.pause(); }); jQuery('.mptime').click(function() { var timeToGoVideo = ""; timeToGoVideo = (this).text; timeToGoVideo = convert(timeToGoVideo); player.setCurrentTime(timeToGoVideo); player.setCurrentRail(); player.play(); }); }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7605930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: an issue about Admob I just want to ask that is setGoneWithoutAd() function available in Android. I tried to use it but it showed: The method setGoneWithoutAd(Boolean) is undefined for the Type AdView Please help if you had experienced it before.
{ "language": "en", "url": "https://stackoverflow.com/questions/7605931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using static const char* const instead of #define I get the error error: ‘Name’ was not declared in this scope What am I missing here. Source File: #include<iostream> #include "scr.h" using namespace std; const char* const Test::Name; void Test::Print() { cout<<Name; } int main() { Test *t = new Test(); t->Print(); delete t; } Header File: class Test { static const char* const Name = "Product Name"; public: void Print(); }; EDIT: If I replace char* const with int, it works. Why? static const int Name = 4; //in header const int Test::Name; //In source The purpose of the code is to have an alternate for #define as mentioned in Effective C++. In the example there, static const int is used. A: You cannot initialize a static member variable within a class. Not even in the header file. Header File: class Test { static const char* const Name; public: void Print(); }; In your cpp file: const char* const Test::Name = "Product Name"; Edit: I must have added that the initialization is allowed only for int and enumerations and that too with constants that can be evaluated at compile time. A: You can't initialize members in class definition. Take a look at Parashift post - Can I add = initializer; to the declaration of a class-scope static const data member? SUMMARY: The caveats are that you may do this only with integral or enumeration types, and that the initializer expression must be an expression that can be evaluated at compile-time: it must only contain other constants, possibly combined with built-in operators. A: In general, you can't initialize static variables directly in the class definition, you have to do it in a separate source file, like this: const char* const Test::Name = "Product Name"; An exception is integral constants, which are allowed to be in the class definition. An easy workaround is to use a static member function instead: struct Test { static const char *Name() { return "Product Name"; } }; A: Move the assignment of the string to the source/implementation file (.cpp).
{ "language": "en", "url": "https://stackoverflow.com/questions/7605934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Flash Socket HTTP-POST Example This article provides an example of using the flash.net.Socket class to connect to a socket: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/Socket.html The example at the bottom shows how to use an HTTP-GET request. I need to use an HTTP-POST request. Bonus: Does this work with HTTPS port 443? A: The Socket is not the correct class for this job. Sockets are used for working with raw TCP data connections. For example, you would use Socket to integrate with custom server component that uses a proprietary communications protocol. Instead, use the URLRequest class to perform HTTP requests from flash/actionscript. This class supports POST as well as GET. It also supports HTTPS. Here is an example of doing a POST request. (incidentally, that is the first result google gives when you search for "as3 post request") There are also examples available in the documentation (linked above), and other places around the net. Edit: To retrieve binary streaming data from an HTTP server, you should use URLStream. Something like the following will accomplish this via a POST request: private var stream:URLStream; private var uploadData:ByteArray; public function URLStreamExample() { stream = new URLStream(); stream.addEventListener(ProgressEvent.PROGRESS, progressHandler); var request:URLRequest = new URLRequest("URLStreamExample.swf"); request.method = URLRequestMethod.POST; // uploadData contains the data to send with the post request // set the proper content type for the data you're sending request.contentType = "application/octet-stream"; request.data = uploadData; // initiate the request stream.load(request); } private function progressHandler(event:Event):void { // called repeatedly as data arrives (just like Socket's progress event) // URLStream is an IDataInput (just like Socket) while( stream.bytesAvailable ) { var b:int = stream.readByte(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7605935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why am I getting this error when trying to connect to my WCF service The caller was not authenticated by the service. I have a WCF service hosted in a windows service on one machine and I have another windows service on a different machine as a client connecting to the WCF service on the first machine. I'm guessing it has something to do with security, but I'm not sure what to do. Here is the app.config of the client: <system.serviceModel> <bindings> <wsDualHttpBinding> <binding name="WSDualHttpBinding_IWCFService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/> <reliableSession ordered="true" inactivityTimeout="00:10:00"/> <security mode="Message"> <message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default"/> </security> </binding> </wsDualHttpBinding> </bindings> <client> <endpoint address="http://localhost:8731/Design_Time_Addresses/WCF/WCFService/" binding="wsDualHttpBinding" bindingConfiguration="WSDualHttpBinding_IWCFService" contract="WCFService.IWCFService" name="WSDualHttpBinding_IWCFService"> <identity> <dns value="localhost"/> </identity> </endpoint> </client> </system.serviceModel> And the app.config of the service: <system.serviceModel> <services> <service name="WCF.WCFService" behaviorConfiguration="WCFBehavior"> <endpoint address="" binding="wsDualHttpBinding" contract="WCF.IWCFService"> <identity> <dns value="localhost" /> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" bindingConfiguration="" contract="IMetadataExchange"/> <host> <baseAddresses> <add baseAddress="http://localhost:8731/Design_Time_Addresses/WCF/WCFService/" /> </baseAddresses> </host> </service> </services> <behaviors> <serviceBehaviors> <behavior name="WCFBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> What do I need to do to be able to connect to my WCF service. One other thing to note is I created a simple console app as a client to the wcf service and it is able to connect to the service without a problem and the app.config file looks identical. Maybe is has something to do with the client service running as a different user? I am ok with removing any and all security, but don't know how. A: The Console application is probably running with your credentials, the Windows Service that cannot connect with the wcf service is probably running with the local system account. Try installing the service with authentication mode "user" and your credentials A: two things: check the identity above and make sure that your other service is running not as a local-user (default! for example NetworkService) but as a domain user or rethink your settings (you can TEST this by running the service under your account if you got the needed rights in your domain)
{ "language": "en", "url": "https://stackoverflow.com/questions/7605938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: BGI error, How to Resolve it? I want to run a C program that draws a circle. The program is compiling with no error and it is running. After getting the values like radius from the user, I get the error like this : BGI error: Graphics not initialized ( use "initgraph") Even though in my source code I have added this line : int gmode,gdrive=DETECT; initgraph(&gdrive,&gmode,"c\\tc\\bgi"); Still I'm getting error. I'm using Windows and I couldn't figure out where I went wrong. Can anyone help me in this regard? Thanks in advance. A: Your path in initgraph is wrong. Use "c:\\tc\bgi" instead. A: If you get this error message when you run your graphics program: BGI Error: Graphics not initialized (use 'initgraph') Just you need to copy the \tc\bgi\EGAVGA.BGI file to your local folder where you are running the application. A: Try this (it worked for me) : The BGI folder is usually in the following path, C:\TurboC++\disk\TurboC3\BGI So the code you need to put in your program is as follows, initgraph(&gd, &gm, "C:\\TurboC3\\BGI"); A: I also suffered from that problem. Simply put this line: initgraph(&gdrive,&gmode, "c:\tc\bgi"); here c:\tc\bgi is important. MOST IMPORTANT: In tc.exe (which you are using) at top are some menus like file, edit, options: * *Go options>application *select overlay (By Default it is "standard" but you must select "overlay" option), then click on ok. *now you run your graphics progaram. NOTE: in the output, if it gives an error about bgi, ignore it, just give the input for the program if it is required and it will give you the graphics output. Enjoy. A: Could be multiple reasons: * *wrong path to the bgi file (I see the colon is missing) *unsupported graphics mode (don't expect DOS graphics apps to work under Vista and up) A: if by including "C:\tc\bgi" still the error persists , try this: goto file-> change directory.. change it to bgi.. but this has to be done every time u open the turboc
{ "language": "en", "url": "https://stackoverflow.com/questions/7605942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to serve a JS file to every browser but IE I dont know why this isn't working. I'm trying to serve a file to good browsers, namely everyone but IE. <!--[if !IE]> <script type="text/javascript" src="JS/script.js"></script> <![endif]--> but it doesn't get served to any...any idea? A: <!--[if !IE]> --> <!-- <![endif]--> Missing trailing -->
{ "language": "en", "url": "https://stackoverflow.com/questions/7605943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android Date incorrect results I am getting the dates from twitter status feed. I am trying to find out all the latest updates (past 24 hours) long referenceTime =System.currentTimeMillis()-(24*60*60*1000); //ti.getDateTime() returns the string time returned from twitter.. long statusTime =DateUtil.convertStringToDate(ti.getDateTime(), "EEE MMM dd HH:mm:ss ZZZZZ yyyy").getTime(); if(statusTime>referenceTime ) { Log.d(TAG,"Recent update"); } Now for the following dates it returns as "Recent update" //Current system time 9:52 am sep 30 2011 Thu Sep 29 11:28:16 +0000 2011 // Correct Thu Sep 29 11:33:07 +0000 2011 // Correct Fri Mar 25 16:15:05 +0000 2011 // Incorrect Tue Mar 22 19:32:38 +0000 2011 // Incorrect Sat Jul 24 12:05:49 +0000 2010 // Incorrect Wed Jul 14 23:56:27 +0000 2010 // Incorrect [These are the strings that ti.getDateTime() returns.] Why is it happening so ? and its pretty much random since the following dates the log is not printed. Fri Jul 09 22:07:53 +0000 2010 Fri Jul 09 21:17:23 +0000 2010 Tue Apr 26 22:33:59 +0000 2011 DateUtil : public static final Date convertStringToDate(String date, String entryFormat) { Date theDate = null; try { //SimpleDateFormat formatter = new SimpleDateFormat( "MMMM d, yyyy");"yyyy-mm-dd" SimpleDateFormat formatter = new SimpleDateFormat( entryFormat); theDate = formatter.parse(date); } catch (Exception e){ } return theDate; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7605949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Variable setting not going through to form element I have a global variable called 'name', when a user clicks on a button a text boxes content is queried and 'name' is set to the contents then the name gets printed in a different jquery page. My problem is name is never printed as the name it was set to, it's always printed as what it was initially set to instead. Here's my callback function: <script type="text/javascript"> $("#finalize").click(function(e) { g_name = "BLAH"; return true; }); </script> For simplicity I've set the name to just be 'BLAH' on the click. g_name is declared globally (i.e. outside the function scope). In the other jquery page I have: document.write('<label for="testname">Name:</label>'); document.write('<input type="text" name="testname" id="testname" value="'); document.write(g_name) document.write('"/>'); And g_name is always shown as something else, whatever g_name was initially initilized to. The button whose click callback sets the global variable also transitions the pages if that makes a difference... edit: Ok I've figured out what was wrong, the global variable was being written down before it was set. Now I'm trying to do this: <script type="text/javascript"> $('#confirmscreen').bind('pageshow',function() { document.write('<label for="testname">Name:</label>'); document.write('<input type="text" name="testname" id="testname" value="'); document.write(g_name); document.write('"/>'); document.write(g_phonenumber); }); </script> However jquery doesn't seem to like using document.write on the 'pageshow' event, is there a way I can make this work, that is to say, write out g_name WHEN the page shows and not when the website is loaded up? A: Instead of using document.write use the javascript method document.createElement() and use the setAttribute() method to assign the values and attributes to the created element. Hope this helps you. A: If that button is causing the page location to change then your global variable will be reset and not available on the second page if that makes sense. In javascript global variables are per window, if window location changes, new set of global variables.
{ "language": "en", "url": "https://stackoverflow.com/questions/7605952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change MySQL timezone in a database connection using Java? MySQL runs with timezone "GMT+8", but Tomcat with "GMT". When I save datetime to my database, everything seems to be OK, but when I check the datetime value in the database, I see the "GMT" value. Also when I try get the value from the database the value is changed, seems like the value in the database is taken as "GMT+8", so Java changes the value to "GMT". I have set the connection URL like this: useTimezone=true&serverTimezone=GMT but it does not work. A: useTimezone is an older workaround. MySQL team rewrote the setTimestamp/getTimestamp code fairly recently, but it will only be enabled if you set the connection parameter useLegacyDatetimeCode=false and you're using the latest version of mysql JDBC connector. So for example: String url = "jdbc:mysql://localhost/mydb?useLegacyDatetimeCode=false If you download the mysql-connector source code and look at setTimestamp, it's very easy to see what's happening: If use legacy date time code = false, newSetTimestampInternal(...) is called. Then, if the Calendar passed to newSetTimestampInternal is NULL, your date object is formatted in the database's time zone: this.tsdf = new SimpleDateFormat("''yyyy-MM-dd HH:mm:ss", Locale.US); this.tsdf.setTimeZone(this.connection.getServerTimezoneTZ()); timestampString = this.tsdf.format(x); It's very important that Calendar is null - so make sure you're using: setTimestamp(int,Timestamp). ... NOT setTimestamp(int,Timestamp,Calendar). It should be obvious now how this works. If you construct a date: January 5, 2011 3:00 AM in America/Los_Angeles (or whatever time zone you want) using java.util.Calendar and call setTimestamp(1, myDate), then it will take your date, use SimpleDateFormat to format it in the database time zone. So if your DB is in America/New_York, it will construct the String '2011-01-05 6:00:00' to be inserted (since NY is ahead of LA by 3 hours). To retrieve the date, use getTimestamp(int) (without the Calendar). Once again it will use the database time zone to build a date. Note: The webserver time zone is completely irrelevant now! If you don't set useLegacyDatetimecode to false, the webserver time zone is used for formatting - adding lots of confusion. Note: It's possible MySQL my complain that the server time zone is ambiguous. For example, if your database is set to use EST, there might be several possible EST time zones in Java, so you can clarify this for mysql-connector by telling it exactly what the database time zone is: String url = "jdbc:mysql://localhost/mydb?useLegacyDatetimeCode=false&serverTimezone=America/New_York"; You only need to do this if it complains. A: JDBC uses a so-called "connection URL", so you can escape "+" by "%2B", that is useTimezone=true&serverTimezone=GMT%2B8 A: For applications such as Squirrel SQL Client (http://squirrel-sql.sourceforge.net/) version 4 you can set "serverTimezone" under "driver properties" to GMT+1 (example of timezone "Europe/Vienna). A: Is there a way we can get the list of supported timeZone from MySQL ? ex - serverTimezone=America/New_York. That can solve many such issue. I believe every time you need to specify the correct time zone from the Application irrespective of the DB TimeZone. A: Works for me spring.datasource.url= jdbc:mysql://localhost:3306/catalog?serverTimezone=UTC A: Change databasename, username and userpassword connection = DriverManager.getConnection("jdbc:mysql://localhost/databasename?user=username&password=userpassword" + "&userUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetime=false&serverTimezone=UTC");
{ "language": "en", "url": "https://stackoverflow.com/questions/7605953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "54" }
Q: Trouble with ArrayCollection in flex I have trouble with ArrayCollection in Flex. Here is my code: private var productPageArr:ArrayCollection; private var productCount:Number = 10; private function dviceProductPage(arr1:ArrayCollection,arr2:ArrayCollection):ArrayCollection { var page:Number = arr1.length //productCount; var i:int; arr2 = new ArrayCollection(); //productPageArr = new ArrayCollection(); for(i = 0; i<page; i++) { var o:Object = new Object(); o.label = String(i+1); arr2.addItem(o); } //arr2.refresh(); return arr2; } When I run this block of code, my application is terminated. But when productPageArr is replaced with arr2 then my application runs smoothly. A: The problem is around the use of "arr2". "arr2" is an argument to your function, which may not be accessible from here. I can't really tell what you are trying to achieve but my suggestion is to create a new variable within your function which you can safely return as the result of your function (which leaves the question as to why you are accepting "arr2" as an argument at all). I hope this helps. private var productPageArr:ArrayCollection; private var productCount:Number = 10; private function dviceProductPage(arr1:ArrayCollection,arr2:ArrayCollection):ArrayCollection { var page:Number = arr1.length //productCount; var i:int; var arr3 = new ArrayCollection(); for(i = 0; i<page; i++) { var o:Object = new Object(); o.label = String(i+1); arr3.addItem(o); } return arr3; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7605954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating an JSON Date a la ASP.NET Format There's a great thread here: How do I format a Microsoft JSON date? that shows how to parse an ASP.NET formatted JSON date: /Date(1224043200000)/ ... back into an actual JavaScript Date object. However, it doesn't show how to go the other way. So, given a date - how do I go from: new Date() // to /Date(1224043200000)/ ??? A: var d = ['/Date(', new Date().getTime(), ')/'].join(''); A: var t = new Date(); t.getTime();
{ "language": "en", "url": "https://stackoverflow.com/questions/7605958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how do I use variables when binding backbone view events? I want to bind an event to a view using a selector I define in the view's options. Something like (in coffescript): events: ()-> "change" : "setNewCheckedStateWithCheckbox" '"click'+ @.options.choices_button_selector +'"' : "test" Can't for the life of me figure it out. A: The problem here is that you can't do expressions in the keys of JavaScript object literals. The only way to set arbitrary keys on objects it to use the obj[expression] syntax. Here's one way to rewrite your code to do what you want: class MyView extends Backbone.View _events = change: "setNewCheckedStateWithCheckbox" events: -> eventsHash = _.extend {}, _events eventsHash["click #{@.options.choices_button_selector}"] = "test" eventsHash A: try this events: ()-> "change" : "setNewCheckedStateWithCheckbox" "click#{@options.choices_button_selector}" : "test" next time just stick in a console.log to display values you're not sure about. console.log '"click'+ @.options.choices_button_selector +'"' that would output "click#selector" with the quotes (that shouldn't be there).
{ "language": "en", "url": "https://stackoverflow.com/questions/7605967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Translate one line please from python to ruby Need to calculate IP => int just like in here: https://bitbucket.org/lorien/django-ipgeo/src/d19648c9b14f/ipgeo/models.py but in ruby. I'm pretty new in ruby, so cannot translate this into ruby: number = struct.unpack('!L', socket.inet_aton(ip))[0] struct, socket are python std, ip is a string like '127.0.0.1' A: Ruby comes with an ipaddr module that specifies an IPAddr class that can return a representation as an integer. require 'ipaddr' addr = IPAddr.new '127.0.0.1' print addr.to_i Here it is in irb: ruby-1.9.2-p290 :002 > require 'ipaddr' => true ruby-1.9.2-p290 :003 > addr = IPAddr.new '127.0.0.1' => #<IPAddr: IPv4:127.0.0.1/255.255.255.255> ruby-1.9.2-p290 :004 > addr.to_i => 2130706433
{ "language": "en", "url": "https://stackoverflow.com/questions/7605968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I want to catch only update,insert and delete operation of Contacts when onChange is called. How can i do it ...? I have following code. public class TestContentObserver extends Activity { int contactCount = 0; final String[] projection = new String[] { RawContacts.CONTACT_ID, RawContacts.DELETED }; Cursor curval; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); curval = getContentResolver().query(RawContacts.CONTENT_URI, projection, null, null, null); contactCount = curval.getCount(); curval.registerContentObserver(new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { getChangedContactDetails(); } @Override public boolean deliverSelfNotifications() { return true; } }); } public void getChangedContactDetails(){ // how can I catch the affected contact details } } when i make a call from contacts it also goes to onChange function. But i want to take only insert,update and delete of contacts. Please can you help me. Thank you A: This is a trick question, you need to understand how contacts actually work before you do this. Each contact is associated with an Account and hence whenever there is a change in contact (outside that Account), it is marked dirty. You can fetch all these contacts using this dirty flag. But if the contacts are actually changed by the Account itself, then this flag will not be set. If you are not sure what I am talking about and you don't care which account the contacts belongs too then the ideal way would be to keep a contact id and version reference in your app somewhere. In this function of yours query all the contacts and iterate through the list * *Check if there is a new contact which you can't find in your reference table. It is an newly added contact. *Check if the version is higher now, it is an updated contact *Check if the contact is missing (which you had in your table previously) it has been deleted. If you don't use Account Manager, you have no option but to go through this cycle.
{ "language": "en", "url": "https://stackoverflow.com/questions/7605970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to break this string correctly I have strings that have the following pattern. Some text on some more text before some text. How do I find * *the position of the word "before" and remove it with anything after it, *and the position of the word " on " and remove it with anything before it? A: Regular expressions are overkill for this. Just do a substring from where you find "on" to where you find "before": $str = 'Some text on some more text before some text'; // Find " on " $start = strpos($str, " on "); // Check for errors // Note the 3 ='s if($start === FALSE) { // Error occurred, do something } $start += 4; // Go after "on" // Find " before " $end = strpos($str, " before ", $start); // Check for errors // Note the 3 ='s if($end === FALSE) { // Error occurred, do something } // Get just the part we want $length = $end - $start; $result = substr($str, $start, $end - $start); A: preg_match('~\bon\b(.+)\bbefore\b~',$text,$match); //use $match[1]; e.g $text=$match[1]; A: consider using regular expressions: $text= "Some text on some more text before some text"; $pattern = '/^.* on(.*)before.*$/'; preg_match($pattern, $text, $matches); if($matches) { print $matches[1]; } A: Try this: <?php $string = 'Some text on some more text before some text'; $newString = preg_replace('/(.*)on(.*)before(.*)/', '$2', $string); echo $newString; Regex: http://regexr.com?2uqq7 PHP demo: http://codepad.org/uXBL8IaA A: $var="Some text on some more text before some text"; preg_match('/\bon\b(.*)\bbefore\b/',$var,$match); //Edit: You can use `(.+)` too if, by any chance, there is no text between 'on' and 'before'. print_r ($match); //$match[1] has "some more text" Is this what you want? and as for the position thing, you can echo strrpos($var, " on "); if I'm getting this correctly (as you said in the comment that "on" has spaces around it. echo strrpos($var, "before"); too, this will return the position of the first character. A: $str = 'Some text on some more text before some text'; $str = str_replace(array('on','before'), '', $str);
{ "language": "en", "url": "https://stackoverflow.com/questions/7605977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Single DoubleTapDetector for a few UI controls I am trying to identify UI-control that fired MotionEvent in Android. I have one doubleTapDetector public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); doubleTapDetector = new GestureDetector(this, new DoubleTapDetector()); } declared as private class DoubleTapDetector extends GestureDetector.SimpleOnGestureListener { @Override public boolean onDoubleTap(MotionEvent e) { String uiControlName = obtainUiControlName(e); // Do something depends on uiControlName return true; } private String obtainUiControlName(MotionEvent e) { int deviceId = e.getDeviceId(); switch (deviceId) { case R.id.button1: return "Button1"; case R.id.button2: return "Button2"; } return null; } } placed on both buttons Button button1 = (Button) findViewById(R.id.button1); outcomeButton.setOnTouchListener(new OnTouchListener(){ @Override public boolean onTouch(View v, MotionEvent event) { doubleTapDetector.onTouchEvent(event); return true; } }); Button button2 = (Button) findViewById(R.id.button2); outcomeButton.setOnTouchListener(new OnTouchListener(){ @Override public boolean onTouch(View v, MotionEvent event) { doubleTapDetector.onTouchEvent(event); return true; } }); The problem is that deviceId always equals 0 and I can't identify which button fires double click event. Is there a way to do that without implementing of two different doubleTapDetector's for each button? A: Mistake. getDeviceId returns physical pointer device id from where touch was received. Not Widget ID. I feel that only way to do it is to create unique DoubleTapDetector for each your button, and also store some kind of button's ID in your DoubleTapDetector class. Because onDoubleTap method doesn't give enough info about Widget on which tap happened. Like this: private class DoubleTapDetector extends GestureDetector.SimpleOnGestureListener { int id; DoubleTapDetector(int id){ this.id = id; } ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7605980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Maven project builds successfully in Eclipse, but shows compile errors in cmd prompt I have imported an existing Maven project into Eclipse IDE. I modified some of the code and built the project in Eclipse. There are no build errors. However, when I ran mvn clean install from the command prompt, it is showing a lot of compilation errors. Why is Eclipse not showing errors and whereas Maven shows compilation errors? A: Eclipse doesn't have the concept of the maven scopes. Whereas maven will have different classpaths depending on the scope--eclipse will only have a single classpath set. IMHO, I don't trust m2eclipse for builds--just let it assist with development. A: Building on TJR's answer, I want to give a concrete example that just happened to me. I also had a build that "works" in Eclipse, but failed with many Java compiler errors on the command line. (Thankfully, I always test with 'mvn clean install' before doing a release.) In my case, I had build some custom hamcrest matchers, but the hamcrest dependencies in my POM were set as: <scope>test</scope> Removing this scope restriction fixed my bug. Seems like m2e still needs more work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7605983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Rails to_xls in rake task I am trying to use the rails to_xls gem in my rake task. My code is: tmp_file = Tempfile.new(['export_test', '.xls']) ToXls::ArrayWriter.new(@logins_report, :name => 'export_test').write_io(tmp_file) I receive an error that says "rake aborted! uninitialized constant ToXls" Any suggestions? A: Did you require 'to_xls' in your Rake task? A: Turns out my gem file would not update to the new version. I had to add the "~> 1.0.0" after it and run bundle install.
{ "language": "en", "url": "https://stackoverflow.com/questions/7605991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How should I cleanly break out of a recv loop? I'm using the recv function in a loop to receive network data, but let's say I want to stop receiving data mid-loop. I could just break the loop, but this doesn't seem like a very clean way to stop receiving data. So is there any way to cleanly stop receiving data, or is just breaking the loop ok? It's HTTP GET/POST requests. Here's simplifed I'm using: do { nDataLen = recv(mySocket, data, BUFFSIZE, 0); if (nDataLen > 0) { /* Process Data */ // I'd like to break out of the loop // if something is found when processing the data // But, I want to do this cleanly. } } while (nDataLen != 0); A: Breaking out of the recv loop won't close the connection. All that happens is that you stop calling recv and therefore stop reading data from the socket. Data from the peer will still be arriving on your socket. If you want to cleanly shutdown then call close on the socket file descriptor. A: Breaking out of the loop is a way of stop calling recv. Another is to include a boolean should_stop and check for it in the loop condition. You should however receive whatever is left in the socket and properly close it. A: If you don't need the socket close the socket and break out of loop.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Can't use glLoadIdentity as expected after a translation in JOGL I'm just starting with JOGL, and there's something I haven't been able to do: There's an example of basic drawing and rotation in NeHe tutorials, and everything works just fine, except the glLoadIdentity(); used after the first triangle and before the next quad. The JOGL code is the next: float rtri = 0.0f; float rquad = 0.0f; @Override public void display(GLAutoDrawable drawable) { final GL2 gl = drawable.getGL().getGL2(); gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT); gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glLoadIdentity(); gl.glTranslatef(-1.5f,0.0f,-6.0f); gl.glRotatef(rtri, 0.0f, 1.0f, 0.0f); gl.glBegin(GL2.GL_TRIANGLES); { gl.glColor3f(1.0f,0.0f,0.0f); gl.glVertex3f( 0.0f, 1.0f, 0.0f); gl.glColor3f(0.0f,1.0f,0.0f); gl.glVertex3f(-1.0f,-1.0f, 0.0f); gl.glColor3f(0.0f,0.0f,1.0f); gl.glVertex3f( 1.0f,-1.0f, 0.0f); } gl.glEnd(); // Here seems to be the problem gl.glLoadIdentity(); gl.glTranslatef(3.0f, 0.0f, 0.0f); gl.glRotatef(rquad, 1.0f, 0.0f, 0.0f); gl.glBegin(GL2.GL_QUADS); { gl.glColor3f(0.5f, 0.5f, 1.0f); gl.glVertex3f(-1.0f, 1.0f, 0.0f); gl.glVertex3f( 1.0f, 1.0f, 0.0f); gl.glVertex3f( 1.0f,-1.0f, 0.0f); gl.glVertex3f(-1.0f,-1.0f, 0.0f); } gl.glEnd(); gl.glFlush(); rtri += 0.15f; rquad -= 0.5f; } As you can see, there is a gl.glLoadIdentity(); before the Quad is defined. If this line is commented, the final program renders the first triangle rotating, and the quad translating around the triangle, but the quad has it's own rotation too. If that line is NOT commented, the quad is not rendered at all, and only the triangle is rendered, with it's defined colors and rotation. All examples I've seen so far seem to use the gl.glLoadIdentity(); to restore the default state for current matrix mode (GL_MODELVIEW), but in this case, something else seems to be happening. I've tested with gl.glPushMatrix(); and gl.glPopMatrix(); before each drawing operation, surrounding all the drawing code, with and without the gl.glLoadIdentity(); in the middle, but nothing seems to help. I've checked other examples' init and reshape method, but everything seems just fine: @Override public void init(GLAutoDrawable drawable) { final GL2 gl = drawable.getGL().getGL2(); gl.glShadeModel(GL2.GL_SMOOTH); gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); gl.glClearDepth(1.0f); gl.glEnable(GL2.GL_DEPTH_TEST); gl.glDepthFunc(GL2.GL_LEQUAL); gl.glHint(GL2ES1.GL_PERSPECTIVE_CORRECTION_HINT, GL2.GL_NICEST); } @Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { final GL2 gl = drawable.getGL().getGL2(); if (height <= 0) { height = 1; } float h = (float) width / (float) height; gl.glMatrixMode(GL2.GL_PROJECTION); gl.glLoadIdentity(); glu.gluPerspective(50.0f, h, 1.0, 1000.0); gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glLoadIdentity(); } I'd like to keep learning OpenGL, while using Java (I'd love Java, and a long time ago I don't use C++), but I'm supposed to be in the very basics of OpenGL, and I wouldn't like to go on missing such a "basic" thing. Thank you all for your help, and sorry if my english has errors. A: Your problem isn't glLoadIdentity. Your problem is this: gl.glTranslatef(3.0f, 0.0f, 0.0f); gl.glRotatef(rquad, 1.0f, 0.0f, 0.0f); You translate the quad 3 units in the X direction. OK, but it still has a Z of zero. Your camera also has a Z of zero, since you're operating in camera space. And since your near-Z is 1, you're going to clip out a lot of the camera. Plus, there's the fact that, given your FOV of 50 degrees, and the fact that you put the quad 3 units in the X direction, it is probably off to the right of the camera. So it's simply out of view. You need to move your object away from the camera if you want to see it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use unicode in GNAT Programming Studio? I am using the GPS to programming. But I can't use unicode characters in code. I set the Character Set as UTF-8 in preferences. But I still could not type the unicode characters as comment in the code. Can anyone tell me how to use unicode characters in source code? I will very appreciate for your assistance. Thanks! Sun A: How ["03C0"] match <Ada Reference Manual>'s grammar in Annex P? Maybe this question&answer can answer your question. Which is your problem? 1. Can not type in the unicode character. 2. Can copy an unicode character but can not paste in GPS. 3. Can type or paste in GPS, but can not save. 4. Can type or paste in GPS and can save, but can not compile. I guess your problem is the No. 4, then refer to my previous post as above link. You need to use "gnatmake -gnatW8 Hello.adb" to compile. Goto Build | Settings | Targets | Check Syntax At the bottom insert -gnatW8 in the command field like: %gnatmake -q -gnatW8 -c -gnats -u %eL -P%PP %X %fp So does to Check Semantic if needed. A: If you just get a box in the edit fields you need to use a different font for GUI and editing. DejaVu is a good one as it contains almost all unicode characters. Setting them up depends a bit on your OS.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there any utility that will remove console calls in Javascript files? This is primarily for the purpose of deploying to a production environment. A solution that parses the JS file into an AST and then removes the console calls is preferable, but I'm willing to look at altneratives. I'm especially interested in ones that can remove console.assert calls. A: I handle this two ways: 1) I never use console.log() or any console calls in my code. For debugging purposes, I have my own debugging object with it's own methods. I can then control with a single setting whether console messages go to the actual debug console, go to my own textarea object or do nothing. Thus I can turn them on or off or redirect them with one line of code. 2) I wrote my own python script that search my JS files for my own debugging calls and removes them. It also removes all comments, but does not minimize the file so it's still fully debuggable. This is my "pre-production" or "beta" version of the code that I can freely let out in the world and it's easy to track down problems in, but it doesn't have all my comments and notes in the code. This particular python script isn't super general purpose so I haven't made it publicly available, but it wasn't hard to write. A: debug = 0; if (debug) console.log(); also many text editors have an arcane feature called "find and replace"
{ "language": "en", "url": "https://stackoverflow.com/questions/7606015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL Server - using CASE in WHERE clause I want to use CASE in WHERE clause, but it returns error. Can I use CASE in where clause? or how to fix it ? Thanks SELECT * FROM hris_leave.dbo.tbl_act inner join hris_leave.dbo.tstaff on hris_leave.dbo.tstaff.s_id = hris_leave.dbo.tbl_act.s_id where case when acting_to is not null then datediff(day, acting_from, acting_to) >= 90 and acting_to >= '2010-10-01' else acting_to is null order by hris_leave.dbo.tbl_act.s_id A: In your case, you only need OR WHERE ( acting_to is null OR ( datediff(day, acting_from, acting_to) >= 90 AND acting_to >= '2010-10-01' ) ) A case is for values, not conditions. The condition is outside the CASE expression eg CASE WHEN SomeCol = 'a' THEN ColA WHEN SomeCol = 'c' THEN ColC ELSE ColB END > 42
{ "language": "en", "url": "https://stackoverflow.com/questions/7606019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Use StringBuilder or String in the following case? String address=null; String body = ""; String date = ""; for(int i = 0; somecondition; i++) { body = cursor.getBody(i); //and so on all strings get changed //REST OF THE CODE } This loops for arround 500 times so what should I use? A: Given that nothing changes in the String you are just reassigning it, use a String. StringBuilder is used when you want to build up a String in pieces. A: Since you're just assigning some string to the variable, just use String instead of StringBuilder. StringBuilder as its name suggest, is used for building a new string where concatenation or manipulation is desired. A: Your example doesn't build any String, just going assign values. In that case you can use String
{ "language": "en", "url": "https://stackoverflow.com/questions/7606020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: are lib files handled differently in Rails 3 versus Rails 2.3.8? I have the following which worked in Rails 2.3.8: /lib/trimmer.rb I use it in my Contact model as follows: include Trimmer #lib module to trim blank spaces in input But I get this error: uninitialized constant Contact::Trimmer I'm guessing lib files are handled differently, but not sure what to change? 1 module Trimmer 2 # Make a class method available to define space-trimming behavior. 3 def self.included base 4 base.extend(ClassMethods) 5 end 6 7 module ClassMethods 8 # Register a before-validation handler for the given fields to 9 # trim leading and trailing spaces. 10 def trimmed_fields *field_list 11 before_validation do |model| 12 field_list.each do |n| 13 model[n] = model[n].strip if model[n].respond_to?('strip') 14 end 15 end 16 end 17 end 18 end I think I figured it out...validate? I have to use require 'trimmer.rb' because in Rails 3, the lib files have to be explicitly required..... A: The lib directory isn't loaded by default in rails 3. You need to add this: config.autoload_paths += Dir["#{config.root}/lib/**/"] To your application.rb file. Then it should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JRPdfExporter is not working I have createad a report in jasper report, when i have wrote the code in servlet to export the report in pdf it is not displaying the report. JRPdfExporter pdfExporter = new JRPdfExporter(); pdfExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); //OutputStream ouputStream = response.getOutputStream(); //pdfExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream); pdfExporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, "C:/reports/payment.pdf"); pdfExporter.exportReport(); Now during debugging when debugger came to at this line JRPdfExporter pdfExporter = new JRPdfExporter(); it simply goes in finally block rather in next line. I am stuck into this any solutions. and the Exception is: java.lang.NoClassDefFoundError: com/lowagie/text/DocumentException java.lang.ClassNotFoundException: com.lowagie.text.DocumentException A: Your code looks fine, and It compiles and runs correctly. I suspect that problem is inside JasperPrint. Make sure you actually complie a JasperPrint from your JRXML file. If you set an empty JasperPrint into the JRPdfExporter, it will still runs correctly, but will result an empty PDF file. Hope this help you locate the error. EDIT : these Exception messages you provided are indicated that JVM can not locate DocumentException, according to package name, that's a class from iText library, if you have used iText, make sure you have included iText in your classpath. A: I think you are not included "iText-2.1.7.js2.jar" file to your classpath. First include mentioned file then it will work fine. Hope it will help to you. A: Using maven just put your jasper dependency: <dependency> <groupId>net.sf.jasperreports</groupId> <artifactId>jasperreports</artifactId> <version>3.7.6</version> </dependency> and he put the dependency A: Just include itext-1.2.jar inside your class path. A: You have to add http://itextpdf.com/ jar file
{ "language": "en", "url": "https://stackoverflow.com/questions/7606023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to instantiate a generic type object in C#? I have class like this: public ClassA<T> where T : class{ ... } Now I need to to create an object of ClassA in the constructor of ClassB: public ClassB{ public ClassA<?> objA; public ClassB(string TypeInfo){ objA = new ClassA<?>(); // Suppose TypeInfo = 'ClassC', and the '?' // Should be derived from TypeInfo } ... } I don't know what to replace '?' for, since the type can only be known at runtime... any ideas? A: The closest to determining and creating the generic type at runtime that you'll probably get (using a string that represents the type name) is instantiating it like this. public class ClassB { public ClassB(string typeInfo) { var typeOfT = Type.GetType(typeInfo); var type = typeof(ClassA<>).MakeGenericType(typeOfT); var instance = Activator.CreateInstance(type); } } Exposing that directly through a public field will not be doable unless you mark your field as dynamic, because otherwise it will need that generic type information up front. public dynamic objA; Also, the string that represents the type must be qualified enough so that it can be located without ambiguity by Type.GetType(). For example, SomeNamespace.ClassC instead of ClassC. A: use object o = Activator.CreateInstance(constructed); this came from MSDN http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx edit we use it in extension methods like; public static object DefaultValue(this Type targetType) { return targetType.IsValueType ? Activator.CreateInstance(targetType) : null; } It's not a huge stretch to make it work with generics A: Since objA is part of the definition of ClassB, ClassB will have to have to have a type parameter if ClassA has a type parameter, i.e. public ClassB<T> { public ClassA<T> objA ... } If the type of objA is not known at compile time it will have to be of type Object or a non-generic base or interface. There's no middle ground. A: There is no reason to use generics for the types not known at compile time, because generics is used only for the KNOWN types, which means you can always make a substitution of a generic parameter with a type. The only matching type in the questioned situation is object type which is a base class for the all object types, and is always known to the compiler. public ClassB{ public ClassA<object> objA; public ClassB(string TypeInfo){ objA = new ClassA<object>(); } ... } About your question... The only way to use a type not known at compile time is resolve the type at run time, make the ClassB generic, and use ILGenerator() for the generic class A to instantiate of construction of that class at the run-time. public ClassB<T>{ public ClassA<T> objA; public ClassB(){ objA = new ClassA<T>(); } ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7606025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Need to show image when validation summary control triggered I have a Warning Image(gif). I want to show this image only when Validation Summary control triggered. Any way to display this Image. Thanks A: Above example from.. below reference link http://weblogs.asp.net/alnurismail/archive/2008/10/16/asp-net-a-validationsummary-with-some-style.aspx Please, take a look to below articles.. for more information and examples... http://sandblogaspnet.blogspot.com/2009/12/showing-image-when-validation-fails.html http://aspnetresources.com/blog/pimpin_validation_summary_with_css A: You can show an image through CssClass attribute but I'd suggest the jQuery plugin. .TestClass { background:url(warning.png) no-repeat ; padding:3px 10px 3px 10px; } Markup <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" CssClass="TestClass" ..... />
{ "language": "en", "url": "https://stackoverflow.com/questions/7606033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android Java countdown and then do somethign How can i countdown to like 5 then something will happen? Ex: Activity Starts it counts down to 5 then a toast comes up A: This you can perform by using CountdownTimer in-build abstract class new CountdownTimer(5000, 1000) { public void onTick(long millisUntilFinished) { mTextField.setText("seconds remaining: " + millisUntilFinished / 1000); } public void onFinish() { // Now countdown is finished, perform whatever you want mTextField.setText("done!"); } }.start(); A: Please use Timer class See this link for reference http://developer.android.com/resources/articles/timed-ui-updates.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7606036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use multiple svn repositories in a project Is it possible to use multiple svn repositories in one project. Lets say I have a framework repository and multiple modules repositories. In my project I will be using the framework and those modules and when that framework repo is updated I need to be able to sync it with that in my project. Same with the modules. A: I'm not 100% clear on what you are trying to do, but you may want to look up the svn:externals property. If another folder in the repository is specified as an external of the folder you are checking out, it will be be included in the working directory after an svn update, and can be committed along with the remainder of the contents of the working directory. I have done this regularly with seperate folders in a single svn repository tree. If that is what you mean, using svn:externals could be helpful for you. I have never tried to specify a folder from a totally different svn repository or server, so if that is what you want to do, I am not sure if svn:externals will work for you. You could always try.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: report module for sugarcrm 6.2 Which Report module is suitable for making reports in sugarcrm 6.2 . I had installed the zucker Report Module on the local site it works properly but when i used to install them on my server it does not installed Anyone please help Thanks A: KReporter certainly the best Reporting tool in the Marketing for SugarCRM, regardless of edition - be it PRO, ENT, CORP or CE. The new free Google Charts are really cool A: I suggest KINAMU Reporter, http://www.sugarforge.org/projects/kinamureporter
{ "language": "en", "url": "https://stackoverflow.com/questions/7606044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Google Protocol buffers in client/server when have different packet type I want to use protocol buffers in tcp/ip communication, but i may have different packets to send/receive, how can i differentiate the package types over protocol buffers, it seems I have to know the next packet type to use protocol buffer, but in my case, i may don't know the type in advance. any idea? is protocol buffers not good for this kind of communication? A: Look at Self-describing Messages section of the documentation. NOTE: Jon Skeet's answer is a complete one as always. A: Pangea noted self-describing messages, but actually I'd suggest union messages, if you don't know which type may be involved, but you know the complete spectrum of types available. (It depends on what exactly you mean by "I may not know the type in advance.") Basically both techniques are "metadata, data" approaches - it just depends on whether the metadata needs to include the message descriptor, or just a discriminator to say which message type comes next. You can combine the two techniques, of course - create a union type where one of the type involved is a self-describing type. This would be useful if you knew what you'd normally expect, but you'd occasionally get something "different" without knowing about the message type in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606051", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: AS3 gotoAndStop() on the timeline of a loaded SWF I'm working on a new ad unit called a Filmstrip for NineMSN (demo here) which basically loads in 5 SWFs vertically. Only one of these 5 is visible at a time (with the exception of a a portion of two SWFs between UP and DOWN transitions. What I'm trying to achieve is ensure that when the user clicks on UP or DOWN, the SWF you scroll to will be playing from the beginning. How can I target the main timeline of an SWF loaded as per below and call gotoAndStop() on this? var loader:Loader = new Loader(); loader.y = index * 600; loader.load( new URLRequest(_assets["ebMovie" + (index+1)]) ); addChild(loader); If the above is not possible, what's the most viable solution to achieve similar? Maybe like quickly unloading/reloading the SWF (I'm just concerned about the issues this could potentially open me up to such as the connection dropping out between clicking UP or DOWN and the ad breaking). A: One of the major curveballs I had here was that content is inaccessible until it's actually been loaded (duh), so firstly we need to attach an event listener to loader.contentLoaderInfo before we can do anything: loader.contentLoaderInfo.addEventListener(Event.COMPLETE, _loaderComplete); Now we can work with content in the triggered function: private function _loaderComplete(e:Event):void { // Capture instance of LoaderInfo var info:LoaderInfo = e.target as LoaderInfo; // Remove triggering listener info.removeEventListener(Event.COMPLETE, _loaderComplete); // Typecast content to MovieClip var timeline:MovieClip = MovieClip(info.loader.content); _timelines.push(timeline); } The above will typecast the content property to a MovieClip representing the Main Timeline of the loaded SWF, allowing full control over it. A: I would use a manager class to keep track of the swfs and the selected index. Then you need to reference the loader content to access the timeline. var swfTimeline:MovieClip = loader.content as MovieClip; swfTimeline.gotoAndPlay(2);
{ "language": "en", "url": "https://stackoverflow.com/questions/7606060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to directly send a python output to clipboard? For example, if a python script will spit out a string giving the path of a newly written file that I'm going to edit immediately after running the script, it would be very nice to have it directly sent to the system clipboard rather than STDOUT. A: This is not really a Python question but a shell question. You already can send the output of a Python script (or any command) to the clipboard instead of standard out, by piping the output of the Python script into the xclip command. myscript.py | xclip If xclip is not already installed on your system (it isn't by default), this is how you get it: sudo apt-get install xclip If you wanted to do it directly from your Python script I guess you could shell out and run the xclip command using os.system() which is simple but deprecated. There are a number of ways to do this (see the subprocess module for the current official way). The command you'd want to execute is something like: echo -n /path/goes/here | xclip Bonus: Under Mac OS X, you can do the same thing by piping into pbcopy. A: You can use an external program, xsel: from subprocess import Popen, PIPE p = Popen(['xsel','-pi'], stdin=PIPE) p.communicate(input='Hello, World') With xsel, you can set the clipboard you want to work on. * *-p works with the PRIMARY selection. That's the middle click one. *-s works with the SECONDARY selection. I don't know if this is used anymore. *-b works with the CLIPBOARD selection. That's your Ctrl + V one. Read more about X's clipboards here and here. A quick and dirty function I created to handle this: def paste(str, p=True, c=True): from subprocess import Popen, PIPE if p: p = Popen(['xsel', '-pi'], stdin=PIPE) p.communicate(input=str) if c: p = Popen(['xsel', '-bi'], stdin=PIPE) p.communicate(input=str) paste('Hello', False) # pastes to CLIPBOARD only paste('Hello', c=False) # pastes to PRIMARY only paste('Hello') # pastes to both You can also try pyGTK's clipboard : import pygtk pygtk.require('2.0') import gtk clipboard = gtk.clipboard_get() clipboard.set_text('Hello, World') clipboard.store() This works with the Ctrl + V selection for me. A: As others have pointed out this is not "Python and batteries" as it involves GUI operations. So It is platform dependent. If you are on windows you can use win32 Python Module and Access win32 clipboard operations. My suggestion though would be picking up one GUI toolkit (PyQT/PySide for QT, PyGTK for GTK+ or wxPython for wxWidgets). Then use the clipboard operations. If you don’t need the heavy weight things of toolkits then make your wrapper which will use win32 package on windows and whatever is available on other platform and switch accordingly! For wxPython here are some helpful links: http://www.wxpython.org/docs/api/wx.Clipboard-class.html http://wiki.wxpython.org/ClipBoard http://www.python-forum.org/pythonforum/viewtopic.php?f=1&t=25549 A: As it was posted in another answer, if you want to solve that within python, you can use Pyperclip which has the added benefit of being cross-platform. >>> import pyperclip >>> pyperclip.copy('The text to be copied to the clipboard.') >>> pyperclip.paste() 'The text to be copied to the clipboard.'
{ "language": "en", "url": "https://stackoverflow.com/questions/7606062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: Python: wait for a key press or until timeout I have a long-running Python script inside a terminal session (the host machine is a FreeBSD box) that performs a task every 9 minutes. Now, I'd like to be able to interrupt that sleep call at any moment so that it performs the task right away. How can I do that? Catching Ctrl+C is not an option as I need it to stop the program (rather than merely interrupting the sleep). Anything else that I can do with a terminal window and a keyboard is fine. A: With Thomas's suggestion, I came up with this function: import signal def input_or_timeout(timeout): def nothing(sig, frame): pass signal.signal(signal.SIGALRM, nothing) signal.alarm(timeout) try: raw_input() signal.alarm(0) except (IOError, EOFError): pass It waits for input for at most timeout seconds. Under Windows, I suppose you could replace raw_input() with getch() from msvcrt.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Is boost.log officially part of Boost? I'm a bit confused as to the status of Boost.Log. Is this an official part of Boost, or has it not been accepted yet? When I google it, I see some posts talking about how it was accepted in 2010, etc, but when I look at the documentation for the last Boost libraries, I see no mention of it. From what I can gather, there is a boost.log library available on sourceforge, however it needs to be extracted on top of an existing boost installation and compiled differently, so I'm basically confused as to whether or not it's official, or if it will ever be official. A: Boost.Log was accepted provisionally but is not yet an official part of Boost, it will be eventually. Here is the review result: http://lists.boost.org/boost-announce/2010/03/0256.php Update: The release of Boost 1.54.0 is the first one to include Boost.Log.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to strip html tags in string then escape the plain string and put the escaped string into html tags back I wanted to strip html tags then escape plain string and put back the escaped string back into html tags , for that i have tried : var aa = "<p>hi testing & </p>"; var bb = $(aa).text(); var cc = escape(bb); var dd = aa.replace(bb, cc); dd gives me the output "<p>hi%20testing%20%26</p>" , but the problem is when i have multiple html tags in string for eg: aa ="<p>hi testing & </p><p> failed & </p>" its not working. Please help. Thanks in advance. A: You were close! jQuery.text() is quite handy for this. When you pass it a function it'll replace the text content of selected elements with the result of the function: var aa = "<p>hi testing & </p><p> failed & </p>" , $aa = $(aa).text(function(_, content) { return escape(content); }) ; console.log($aa); // => [<p>​hi%20testing%20%26%20​</p>​, <p>​%20failed%20%26%20​</p>​]
{ "language": "en", "url": "https://stackoverflow.com/questions/7606068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Incompatible enum types in C I have a question about enums and arrays. Essentially I have an array of enum "BIT"s declared as an enum type "word". typedef enum { ZERO = (uint8_t) 0, ONE = (uint8_t) 1 } BIT; typedef BIT word[16]; As it was explained to me, "word" is simply a predefined array of 16 BITs. However, when I try to assign to a declared word, I simply get an error saying incompatible type word and BIT. BIT ten = ZERO; word Bob; Bob[10] = ten; Can I only write to the word Bob with another word, I would have thought since "word" is an array of "BIT"s that I could simply assign a bit to a position in the "word" array. A: I think the problem is that you're trying to do the Bob[10] = ten; assignment outside of function scope, at the file scope. You can't do that. At the file scope you can't index things freely and you can't initialize variables with anything other than constant values, ten isn't one of them. Now, I'm a little fuzzy as to why the below doesn't want to compile (using gcc 3.4.4 and Open Watcom 1.9): typedef enum { ZERO = 0, ONE = 1 } BIT; typedef BIT word[16]; const BIT ten = ZERO; word Bob = { ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ten, ZERO, ZERO, ZERO, ZERO, ZERO }; int Bob2[] = { ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ten, ZERO, ZERO, ZERO, ZERO, ZERO }; int main(int argc, char** argv) { return 0; } Both compilers say Bob[10] and Bob2[10] aren't being initialized with constants. A: Context One version of the question included the code: Source file logic.c #include "logic.h" void word_not(word *R, word *A) { for (int i = 0; i<16; i++) { if ((A+i)) {*(R+i) = ZERO;} else {*(R+i) = ONE; } } } header file logic.h #ifndef LOGIC_H_ #define LOGIC_H_ #include <stdint.h> /** * Basic element of the LC-3 machine. * * BIT takes on values ZER0 (0) or ONE (1) */ typedef enum { ZERO = (uint8_t) 0, ONE = (uint8_t) 1 } BIT; /** * A 16-"BIT" LC-3 word in big-endian format */ typedef BIT word[16]; void word_not(word *R, word *A); #endif Explanation of the problem The problem is that arguments to word_not() are pointers to arrays. The notation inside has to be adjusted accordingly: void word_not(word *R, word *A) { for (int i = 0; i < 16; i++) { if ((*A)[i]) (*R)[i] = ZERO; else (*R)[i] = ONE; } } Though you could write that more succinctly as: void word_not(word *R, word *A) { for (int i = 0; i < 16; i++) (*R)[i] = !(*A)[i]; } Alternatively, you can simply redefine the function as: void word_not(word R, word A) { for (int i = 0; i < 16; i++) { if (A[i]) R[i] = ZERO; else R[i] = ONE; } } Or, again, more succinctly, as: void word_not(word R, word A) { for (int i = 0; i < 16; i++) R[i] = !A[i]; } Compilable test case - output 0: 1 1 1 1 1: 0 0 0 0 0: 1 1 1 1 1: 0 0 0 0 1: 0 0 0 0 0: 1 1 1 1 1: 0 0 0 0 0: 1 1 1 1 0: 1 1 1 1 0: 1 1 1 1 1: 0 0 0 0 1: 0 0 0 0 1: 0 0 0 0 1: 0 0 0 0 0: 1 1 1 1 0: 1 1 1 1 sizeof(BIT) = 4; sizeof(word) = 64 Compilable test case - source #include "logic.h" void word_not_1(word *R, word *A) { for (int i = 0; i < 16; i++) { if ((*A)[i]) (*R)[i] = ZERO; else (*R)[i] = ONE; } } void word_not_2(word *R, word *A) { for (int i = 0; i < 16; i++) (*R)[i] = !(*A)[i]; } void word_not_3(word R, word A) { for (int i = 0; i < 16; i++) { if (A[i]) R[i] = ZERO; else R[i] = ONE; } } void word_not_4(word R, word A) { for (int i = 0; i < 16; i++) R[i] = !A[i]; } #include <stdio.h> int main(void) { word in = { ZERO, ONE, ZERO, ONE, ONE, ZERO, ONE, ZERO, ZERO, ZERO, ONE, ONE, ONE, ONE, ZERO, ZERO, }; word out1; word out2; word out3; word out4; word_not_1(&out1, &in); word_not_2(&out2, &in); word_not_3(out3, in); word_not_4(out4, in); for (int i = 0; i < 16; i++) printf("%d: %d %d %d %d\n", in[i], out1[i], out2[i], out3[i], out3[i]); printf("sizeof(BIT) = %zu; sizeof(word) = %zu\n", sizeof(BIT), sizeof(word)); return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7606070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I do OAuth request by open new window, instead of redirect user from current page? I have done OAuth authentication with Twitter and Facebook. Currently, with each of these site, my server redirect user to a specified URL (for example, http://api.twitter.com/oauth/authorize with Twitter), then receive authentication parameters by callback url. But by that way, the users get redirected out of my page (to Facebook or Twitter), and only returns after input correct username & password. It's like the way http://techcrunch.com do it when a user try to tweet a post. I remember that in some site, I have seen that we can connect not by redirect user out, but open a popup window for user to input credentials instead. After authentication is completde, the pop-up closed, the main page refresh with new content. This could be a very simple task with javascript, but I still can't figure it out. I can open authentication URL in a pop-up window, but how to get the result & update the main page? A: Assuming you're opening authentication url in a pop-up using window.open(), you can access parent window by using: window.opener and to reload parent window (from a pop-up) use: window.opener.location.reload(); This code should be served on url that you've set up as success callback url of oauth authorization. In general, the flow should be: * *open a pop-up with an authorization page (on twitter.com for example) *after successfull authorization twitter redirects user to url given by you (it gets opened in the very same pop-up) *the opener window gets reloaded (via window.opener.location.reload()) *close the pop-up itself (using javascript is you want) A: I have a follow up ques: Does it matter from the Twitter implementation point of view whether we have opened the authorization page in the the new window or in the same window. What I mean is, does twitter implementation will change if they have to redirect me to the new window (that I have opened for authorization page) vs they have to redirect me to the same window (in case i have not opened the new window for authorization page)
{ "language": "en", "url": "https://stackoverflow.com/questions/7606071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "45" }
Q: Can I use Facebook auth server side flow on an iPhone app and still have client side interactions? I have a website that uses Facebook authentication for logging in users. It uses the oAuth 2.0 server side flow for authentication and it all works fine. I am now developing an iPhone application for the same website and want to allow users to sign in to the website via the iPhone application using FB authentication.The Facebook iOS SDK provides mechanisms to do the authentication using the client side flow, where in my iPhone app gets the access token. Now to authenticate the user with my server, and also make the access token available to my server, I thought of sending this access token to my server (over https) and authenticate the user against my DB and set my own session related cookie. Is this the preferred or advised method? I need the access token on my server as I ask for offline access permission and have my webapp interact with FB user account from my server directly. An easier option for me would be to just use the server side flow for authentication on my iPhone app too, as nothing new needs to be done and the server side code is the same for website or iPhone app. Is that possible? I cannot use client side authentication and pass the access token to my server for authentication against my system and also to be stored for further use. The access token received for client side authentication is totally different from the server side authentication token and the two cannot be used interchangeably. I will have to use server side authentication. One solution ( provided here - in the first comment to the question) is to use an UIWebView and simulate the server side flow. The following comment mentions the problems with this approach, that I have not been able to solve. This has been solved by examining the URL to which the webview is redirected to after the login. Another problem is that, my iPhone app does some client side interactions too (like FBShare, writing to a friend's wall, etc). If I use the simulated server side authentication, I will have to do another client side authentication for these interactions or take the painful approach and route even these actions through my server. The latter is definitely not preferable. How do I go about this? Can I avoid this double login as it will be very bad user experience? A: I am in a similar situation. I've got an iOS native app that needs to know who the user is. I've got a website (RoR), using Devise, that I can login to/create an account with Facebook/Twitter via it's OmniAuth gem. However, with both Facebook and Twitter, it seems that I have to create two entries in each, one for the website, one for the app. Those are separate API keys for each. For the iOS app, the only way I've come up with to make this work is: * If the user wants to auth/create account via Twitter of Facebook, then send them via a UIWebView to the website to login. Any tweets/FB posts from the iOS would actually be posted to each via an API on the website that would use the user's access token to post the tweet on their behalf. The thing is, I rather dislike Webviews for logins. If anyone has any suggestions I'm all ears. A: "I cannot use client side authentication and pass the access token to my server for authentication against my system and also to be stored for further use. The access token received for client side authentication is totally different from the server side authentication token and the two cannot be used interchangeably. I will have to use server side authentication." I just found it opposite. The access tokens generated by the client-side flow and server-side flow authentication are exactly same. They are "interchangeable", in fact once you get the token, it can be used anywhere as long as the user is still logged in and the token is not expired yet. This works. curl "https://graph.facebook.com/{the user id}/friends?access_token={the token} A: I cannot use client side authentication and pass the access token to my server for authentication against my system and also to be stored for further use. Per Facebook's Securing Requests - Verifying Graph API Calls with appsecret_proof page: Access tokens are portable. It's possible to take an access token generated on a client by Facebook's SDK, send it to a server and then make calls from that server on behalf of the person. All this being said, I am perplexed that the SDK does not allow usage of a 3-legged OAuth flow, returning an access code instead of a token, despite their recommendation to do so for security reasons.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606073", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Extract Model from a BackboneJS Collection/UnderscoreJS array I've been checking the docs of Backbone and Underscore for a "proper" way to extract a model (remove the value and have it returned) from a collection. I know I can do this through direct access via the "models" array attribute and the splice method, but is that stepping around some built-in way I'm overlooking? A: It is critical that you use the built-in "remove" method on the collection. Remove does the following: * *updates the built-in index that's used for collection.getByCid() *updates the built-in index that's used for collection.get() *decrements collection.length *removes the model (or models if you pass in an array of models, ids, or cids) *triggers the remove event on the collection If you manipulate the models inside the collection directly, none of the things above will happen. More info on remove: http://documentcloud.github.com/backbone/#Collection-remove A: From your comment: I'm looking to actually remove the model at say index 5 and have that value returned. Try this: // given: myCollection is a Backbone collection var item = myCollection.at(5); myCollection.remove(item); // ... now, do whatever else with `item`...
{ "language": "en", "url": "https://stackoverflow.com/questions/7606076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to display long messages in logcat I am trying to display long message on logcat. If the length of message is more than 1000 characters, it gets broken. What is the mechanism to show all characters of long message in logcat? A: With Kotlin we can make use of the stdlib chunked function: fun logUnlimited(tag: String, string: String) { val maxLogSize = 1000 string.chunked(maxLogSize).forEach { Log.v(tag, it) } } A: As a follow on to spatulamania answer I wrote a wrapper class which handles this for you. You just need to change the import and it will log everything public class Log { public static void d(String TAG, String message) { int maxLogSize = 2000; for(int i = 0; i <= message.length() / maxLogSize; i++) { int start = i * maxLogSize; int end = (i+1) * maxLogSize; end = end > message.length() ? message.length() : end; android.util.Log.d(TAG, message.substring(start, end)); } } } A: In order not to minimize splitting lines across log messages, I take the large string and log each line separately. void logMultilineString(String data) { for (String line : data.split("\n")) { logLargeString(line); } } void logLargeString(String data) { final int CHUNK_SIZE = 4076; // Typical max logcat payload. int offset = 0; while (offset + CHUNK_SIZE <= data.length()) { Log.d(TAG, data.substring(offset, offset += CHUNK_SIZE)); } if (offset < data.length()) { Log.d(TAG, data.substring(offset)); } } A: This builds on spatulamania's answer, is a little more succinct, and won't add an empty log message at the end: final int chunkSize = 2048; for (int i = 0; i < s.length(); i += chunkSize) { Log.d(TAG, s.substring(i, Math.min(s.length(), i + chunkSize))); } A: I consider Timber a good option for this issue. Timber automatically split and print chunks of message in logcat. https://github.com/JakeWharton/timber You can see log method implementation in timber.log.Timber.DebugTree static class. A: If logcat is capping the length at 1000 then you can split the string you want to log with String.subString() and log it in pieces. For example: int maxLogSize = 1000; for(int i = 0; i <= veryLongString.length() / maxLogSize; i++) { int start = i * maxLogSize; int end = (i+1) * maxLogSize; end = end > veryLongString.length() ? veryLongString.length() : end; Log.v(TAG, veryLongString.substring(start, end)); } A: Try this piece of code to show long message in logcat. public void logLargeString(String str) { if(str.length() > 3000) { Log.i(TAG, str.substring(0, 3000)); logLargeString(str.substring(3000)); } else { Log.i(TAG, str); // continuation } } A: This is how OkHttp with HttpLoggingInterceptor does it: public void log(String message) { // Split by line, then ensure each line can fit into Log's maximum length. for (int i = 0, length = message.length(); i < length; i++) { int newline = message.indexOf('\n', i); newline = newline != -1 ? newline : length; do { int end = Math.min(newline, i + MAX_LOG_LENGTH); Log.d("OkHttp", message.substring(i, end)); i = end; } while (i < newline); } } MAX_LOG_LENGTH is 4000. Here it use Log.d (debug) and hardcoded "OkHttp" tag. It split the log at newlines or when it reach the max length. This class below is an helper class you can use (if you have lambda support throw Jack & Jill or retrolambda) to do the same thing OkHttp does on any log: /** * Help printing logs splitting text on new line and creating multiple logs for too long texts */ public class LogHelper { private static final int MAX_LOG_LENGTH = 4000; public static void v(@NonNull String tag, @Nullable String message) { log(message, line -> Log.v(tag, line)); } public static void d(@NonNull String tag, @Nullable String message) { log(message, line -> Log.d(tag, line)); } public static void i(@NonNull String tag, @Nullable String message) { log(message, line -> Log.i(tag, line)); } public static void w(@NonNull String tag, @Nullable String message) { log(message, line -> Log.w(tag, line)); } public static void e(@NonNull String tag, @Nullable String message) { log(message, line -> Log.e(tag, line)); } public static void v(@NonNull String tag, @Nullable String message, @Nullable Throwable throwable) { log(message, throwable, line -> Log.v(tag, line)); } public static void d(@NonNull String tag, @Nullable String message, @Nullable Throwable throwable) { log(message, throwable, line -> Log.d(tag, line)); } public static void i(@NonNull String tag, @Nullable String message, @Nullable Throwable throwable) { log(message, throwable, line -> Log.i(tag, line)); } public static void w(@NonNull String tag, @Nullable String message, @Nullable Throwable throwable) { log(message, throwable, line -> Log.w(tag, line)); } public static void e(@NonNull String tag, @Nullable String message, @Nullable Throwable throwable) { log(message, throwable, line -> Log.e(tag, line)); } private static void log(@Nullable String message, @NonNull LogCB callback) { if (message == null) { callback.log("null"); return; } // Split by line, then ensure each line can fit into Log's maximum length. for (int i = 0, length = message.length(); i < length; i++) { int newline = message.indexOf('\n', i); newline = newline != -1 ? newline : length; do { int end = Math.min(newline, i + MAX_LOG_LENGTH); callback.log(message.substring(i, end)); i = end; } while (i < newline); } } private static void log(@Nullable String message, @Nullable Throwable throwable, @NonNull LogCB callback) { if (throwable == null) { log(message, callback); return; } if (message != null) { log(message + "\n" + Log.getStackTraceString(throwable), callback); } else { log(Log.getStackTraceString(throwable), callback); } } private interface LogCB { void log(@NonNull String message); } } A: Here is a Kotlin version for the @spatulamania answer (especially for lazy/smart peooples): val maxLogSize = 1000 val stringLength = yourString.length for (i in 0..stringLength / maxLogSize) { val start = i * maxLogSize var end = (i + 1) * maxLogSize end = if (end > yourString.length) yourString.length else end Log.v("YOURTAG", yourString.substring(start, end)) } A: if print json string, can use code below @JvmStatic fun j(level: Int, tag: String? = null, msg: String) { if (debug) { if (TextUtils.isEmpty(msg)) { p(level, tag, msg) } else { val message: String message = try { when { msg.startsWith("{") -> { val jsonObject = JSONObject(msg) jsonObject.toString(4) } msg.startsWith("[") -> { val jsonArray = JSONArray(msg) jsonArray.toString(4) } else -> msg } } catch (e: JSONException) { e.printStackTrace() msg } p(level, tag, "╔═══════════════════════════════════════════════════════════════════════════════════════", false) val lines = message.split(LINE_SEPARATOR.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() for (line in lines) { p(level, tag, "║ $line", false) } p(level, tag, "╚═══════════════════════════════════════════════════════════════════════════════════════", false) } } } full code CXLogUtil.j("json-tag","{}") A: public static void largeLog(String tag, String content) { final int SEG_LENGTH = 4000; do { if (content.length() <= SEG_LENGTH) { Log.d(tag, content); break; } Log.d(tag, content.substring(0, SEG_LENGTH)); content = content.substring(SEG_LENGTH); } while (!content.isEmpty()); } A: For an easy solution, use Use soft wrap option in below attach point no 4 options might help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606077", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "109" }
Q: Screen orientation For tablets And devices I am using the same code for both tablets as well as device,Here is my problem while coming to mobile in both orientation it should load list view, coming to tablet in portrait it need to load listview and then coming to landscape it should load gridview? Thanks I have used this code any one can help me plz.. Configuration config = getResources().getConfiguration(); if((config.screenLayout & Configuration.ORIENTATION_LANDSCAPE) == Configuration.SCREENLAYOUT_SIZE_XLARGE)); { this.gridView(); }else{ this.listview(); } A: If you're using xml for your layouts, all you need to do is create different xml files and place them in the layout folder with appropriate configuration qualifier. See this article for details. For you, you would use the following folders: res/layout/my_layout.xml // layout for normal screen size ("default"). Listview here res/layout-xlarge-land/my_layout.xml // layout for extra large in landscape orientation. Gallery here Remember, you need to create these folders if they don't exist. In your code, if you call setContentView(R.id.my_layout), android will use the appropriate layout. Then, you can do a findViewById() call where it should return null for the view of the layout not being used. You can do a findViewById() on both the ListView and GridView. Based on which view returns null, you can set the member (this.gridView or this.listView) appropriately.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to attach .NET Framework 4.0 Client Profile to my setup project? By default, the install location for prerequisites of .NET Framework 4 Client Profile (x86 and x64) is from the Microsoft web site, which requires the client network to be available during installation. I am just wondering, is there a way that we can install .NET Framework 4 Client Profile (x86 and x64) without downloading from the vendor's web site? I assume the second option, "Download prerequisites from the same location as my application", is something I should be looking at here. But I am not 100% sure. Also, in which folder should I place the redistributable file, dotNetFx40_Client_x86_x64.exe? A: Yes, you can select second option "Download prerequisites from the same location as my application" to install .NET Framework 4 Client Profile without downloading it from website. But you need to set path for that prerequisites as it done in below link. Ref: Error_7_The install location for prerequisites has not been set to 'component vendor's web site' and the file 'DotNetFX40\dotNetFx40LP_Full_x86_x64fr.exe' in item 'Microsoft .NET Framework 4 (x86 and x64)' can not be located on disk. UPDATE: You need to set below path for .NET Framework 4.0 Client Profile: C:\Program Files\Microsoft SDKs\Windows\v7.0A\Bootstrapper\Packages\DotNetFX40Client\dotNetFx40_Client_x86_x64.exe A: The common setup project and ClickOnce support .NetFX deployment. Have a look at MSDN page .NET Framework Deployment Guide for Developers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: how would I translate this from searchlogic to metwhere in Rails 3? I had the following in searchlogic: Todo.contact_id_is(self.id).ascend_by_original_date.done_date_not_null.first How would I do this in metawhere now that I am in Rails 3? In particular the not_null and the sorting? Hello, I'm a little confused. When I look at the named scopes found in meta_search (instead of metawhere)...that's more of what I'm looking for...and now metasearch is being replaced with ransack.... What is the way to do chained searches with sql on my models in the way searchlogic made it so drop-dead easy? ...okay...now it looks like ransack is for forms, but queries on models is squeel? Checking that out.... A: It seems that metawhere doesn't have != operator it was added in sqeel so here is a possible workaround Todo.where( { :contact_id => self.id} ).order( :original_date.asc ).where( '"todos"."done_date" NOT NULL' ).first
{ "language": "en", "url": "https://stackoverflow.com/questions/7606091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Adobe LiveCyle - when to use connection properties for ServiceClientFactory in WebLogic? When making a connection from Java to Adobe LiveCycle ES 2.5, the Setting connection properties page lists the default connection properties you should use depending on your server type. For WebLogic, it is this: Properties ConnectionProps = new Properties(); connectionProps.setProperty(ServiceClientFactoryProperties.DSC_DEFAULT_EJB_ENDPOINT, "t3://localhost:7001"); connectionProps.setProperty(ServiceClientFactoryProperties.DSC_TRANSPORT_PROTOCOL,ServiceClientFactoryProperties.DSC_EJB_PROTOCOL); connectionProps.setProperty(ServiceClientFactoryProperties.DSC_SERVER_TYPE, "WebLogic"); connectionProps.setProperty(ServiceClientFactoryProperties.DSC_CREDENTIAL_USERNAME, "administrator"); connectionProps.setProperty(ServiceClientFactoryProperties.DSC_CREDENTIAL_PASSWORD, "password") ... ServiceClientFactory myFactory = ServiceClientFactory.createInstance(connectionProps); My problem is this: on our WebLogic server, the above fails with the following exception: Caused by: java.net.ConnectException: t3://localhost:7001: Destination unreachable; nested exception is: However, if I simply ignore connectionProps, it works: ServiceClientFactory myFactory = ServiceClientFactory.createInstance(); SO, what is going on here? Is Adobe wrong, and you don't use connectionProps for WebLogic, or is there some WebLogic configuration that we are missing? What does it mean when I use ServiceClientFactory.createInstance() - without connectionProps? Thanks for any advice! Rob :) A: Answer given on the this Google Group Post: only need the configuration values if you are connecting to a LiveCycle running in a different JVM. Rob :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7606092", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Colours For The Checked List Box I Am Working On A windows c# form. I have Checked List Boxes in my form. And for those checked List Boxes I want To set Predefined Colors. How can I do It..Is There Any inbuild classes or something to get these predefined colors...please Help A: Rather than repeat the answer, see if How change the color of SelectedItem in CheckedListBox in WindowsForms? helps you solve your problem. There is code there that may get you where you need to go although that refers to forecolor and you may need to change the backcolor in your case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606094", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can i find all the images are loaded in ajax using jquery Is it possible to find whether all the images are loaded in ajax content? I have used var img = $('#slider img'); var length = img.length; img.load(function(){ length--; if(length === 0){ alert("All images loaded"); }; }); but the load is not working, it is not goning in to the loop... A: Try something like this. $('#slider img').each(function() { //Write pre loading script }); A: You need add event listener load before set up src attribute. Or you can scan images and check if every is loaded (by image size): var img = $('#slider img'); var length = img.length; img.each(function(){ if ($(this).width() > 0 && $(this).height() > 0) length--; if(length === 0){ alert("All images loaded"); }; }); I not checked code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: when i click an item than item image alone should appear and unselected listitem's image should disappear In my activity intially Position 0 item alone get checkmarked ,when i click it disappears.same way all items.but what i want is.only one item image should appaer if i click other item previous item image should disappear. In getview() intially i took position 0 item as checkmarked. listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> listView, View itemView, int position, long id) { ImageView imageView = (ImageView) itemView.findViewById(R.id.img); if (position ==0) { itemToggled[position] = ! itemToggled[position]; imageView.setImageResource(itemToggled[position] ? R.drawable.empty :R.drawable.checked); }else{ itemToggled[position] = ! itemToggled[position]; imageView.setImageResource(itemToggled[position] ? R.drawable.checked : R.drawable.empty); } } }); A: You basically need some data structure to keep track of checked items. you can use boolean array in your custom adapter. the same question here Problem with checkbox and also you can find some usefull links in the answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adjusting a Search Time I'm doing a search on files. I need to adjust the search time from the current time (filetime) to current time(file time) less one minute. How would I do this. Thisis what I have so far. Thank you. struct file_data { std::wstring sLastAccessTime; __int64 nFileSize; }; int GetFileList(const wchar_t *searchkey, std::map<std::wstring, file_data> &map) { WIN32_FIND_DATA fd; HANDLE h = FindFirstFile(searchkey,&fd); if(h == INVALID_HANDLE_VALUE) { return 0; // no files found } while(1) { wchar_t buf[128]; FILETIME ft = fd.ftLastWriteTime; SYSTEMTIME sysTime; FileTimeToSystemTime(&ft, &sysTime); wsprintf(buf, L"%d-%02d-%02d",sysTime.wYear, sysTime.wMonth, sysTime.wDay); file_data filedata; filedata.sLastAccessTime= buf; filedata.nFileSize = (((__int64)fd.nFileSizeHigh) << 32) + fd.nFileSizeLow; map[fd.cFileName]= filedata; if (FindNextFile(h, &fd) == FALSE) break; } return map.size(); } int main() { std::map<std::wstring, file_data> map; GetFileList(L"C:\\Users\\DS\\Downloads\\*.jpg", map); GetFileList(L"C:\\Users\\DS\\Downloads\\*.txt", map); int count = GetFileList(L"C:\\Users\\DS\\Downloads\\*.pdf", map); for(std::map<std::wstring, file_data>::const_iterator it = map.begin(); it != map.end(); ++it) { A: Use GetSystemTimeAsFileTime to get the current time in FILETIME format. Subtract 6000000000 to go back in time one minute. Use CompareFileTime to compare each file's time against that value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: stretch, scale, or double up an array with numpy? I was wondering if there is a numpy function to "stretch" an array along a specific axis like the following: a =[[1,2,3,4],[1,2,3,4]] to a = [[1,1,2,2,3,3,4,4],[1,1,2,2,3,3,4,4]] Thanks in advance! A: import numpy as np a = np.array([[1,2,3,4],[1,2,3,4]]) First possibility: a.repeat(2, axis=1) or the second: np.kron(a, [1,1]) Both returning: array([[1, 1, 2, 2, 3, 3, 4, 4], [1, 1, 2, 2, 3, 3, 4, 4]])
{ "language": "en", "url": "https://stackoverflow.com/questions/7606102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Python Audio Transfer Through Lasers I'm currently working on a project that has been relatively easy, up until now. The underlying project is to transmit data/messages over lasers using audio transformation. In a nutshell the process is currently like this * *The user enters a message *Message is turned into binary *For each 1 and 0 in the binary message, it plays a corresponding tone to signal which is which, in my case 250hz for a 1 and 450 hz for a 0. *The outgoing tone is sent over a stereo cable to an audio transformer rigged to a laser *A solar panel acts as a microphone and records the incoming "sound" as a file *It them plays the file back and reads off the tones and tries to match each 250 and 450 hz to a 1 or 0 (which is where my issue lies). Up until the actual processing of the sound is fine, my current issue is the following. I play the tones each for x time, on the receiving end it is recorded for y time, y time is cut sampled many times and then analyzed sample by sample which then logs each frequency. This is inefficient and inaccurate. I have had many issues regardless of the time I play the tones for it often hears a tone twice or doesn't hear it at all, which completely throws off whole messages. I have tried to match the rate at which it samples with the time each tone plays, but unless aligned accordingly it does not work. I've only had a few successful tests for messages like 'test' and 'hi'. I have already looked into bpsk and fsk, but I feel as if I'm already doing something like it but that I have a bad receiving end to decipher it all. This is all written in Python and I'd be very grateful for any tips, suggestions, or possible implementations that you can provide. Also for tone emission I'm using pyaudiere and for recording I'm using pyaudio. Thanks! -Steve A: This sounds like a hardware problem. I'm pretty sure it is a job for FSK. Most modern FSK-type systems use PLLs (Phase-Locking Loop chips) for the actual detection. Frequency-to-Voltage or Frequency-to-current circuits are also usable. I've seen practical circuits in dozens of hobbyist books and in data sheets and on websites. Here are a few: Circuit for demodulating an FSK signal PLL Tutorial I hope this isn't just another trip down the rabbit hole for you -- good luck! A: Did you do a sanity check by listening to the sound files (both transmit and receive), or viewing the waveforms with an audio editor, to see if they roughly sound or look the same? That way you can narrow down the problem to channel induced errors versus your software analysis. Your decoding/demodulation software will need a synchronization method that can determine and track the times that the audio signal changes from one frequency of modulation to another, then you will need to separately test this synchronization method for offset errors. A: I would tackle the receiving end using two FIR filters, one for each frequency that you are trying to detect. The coefficients of the filters are just a copy of the signal you are looking for (i.e. 250Hz in one case and 450Hz in the other). You would have to look at the output of your solar panel to decide whether that is a square wave, sine wave, or something in between. The length of the filter corresponds to the duration of the tone (i.e. 'x' in your question). The samples are fed into both filters in parallel. The output of each filter needs to be rectified (i.e. take the absolute value) and smoothed. The smoothing can be done using a simple moving average over a period of about half x (you can experiment to find the best value). Then if you compare the smoothed values (i.e. is a>b, or b>a) you should get a stream of 0's and 1's. Things to be aware of: This assumes the channel behaves the same for both frequencies (i.e. you get similar snr and attenuation). You might need to tweak your frequencies a bit because 450Hz is quite close to 500Hz which is a harmonic of 250Hz. A: Use a self-clocking signal representation such as Manchester code. That way your timing only has to be "good enough", and you primarily worry about detecting the change, in this case, of frequency. In the linked article the high and low levels refer to voltage, but there is no reason they have to. You can just as easily use a high and low frequency, or turning a single laser on/off.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Javascript Image manipulation Invert color I am trying to play with an image inside a webpage using javascript and it is being a pain. I have no coding platform atm except my browser. It should invert the color I think but i'm not sure what is screwing up. What is wrong with my script? <img src="C:\Documents and Settings\_username_\Desktop\rabbit.jpg" name="myimage" id="myimage"> <input type="button" value="Click Here" onClick="doSomething();"> <SCRIPT language=JavaScript> function doSomething(){ var imgd = myimage.getImageData(x, y, width, height); var pix = imgd.data; for (var i = 0, n = pix.length; i < n; i += 4) { pix[i ] = 255 - pix[i ]; // red pix[i+1] = 255 - pix[i+1]; // green pix[i+2] = 255 - pix[i+2]; // blue // i+3 is alpha (the fourth element) } myimage.putImageData(imgd, x, y); } </SCRIPT> A: If you are using MS Internet Explorer, the following code should work for you <img src="xyz.jpg" onMouseover="this.style.filter='progid:DXImageTransform.Microsoft.BasicImage(invert=1)'" onMouseout="this.style.filter=''" /> Post IE 8 it the "filter" should be replaced by "-ms-filter" Also a smarter way is mentioned at the sohtanaka site, which uses jquery and css to accomplish the required effect http://www.sohtanaka.com/web-design/greyscale-hover-effect-w-css-jquery/ Hope this helps you :-) A: The xolor library has an inverse function: xolor("rgb(100,200,50").inverse().rgb // returns the inverse in rgb format Its implemented like this, where it already parsed the red, green, and blue values which exist as properties on the xolor object: this.inverse = function() { return xolor({ r: this.r ^= 0xff, g: this.g ^= 0xff, b: this.b ^= 0xff }) } A: That would work on a canvas context, but you're working with an image. Create a canvas and copy the image's data into it and then invert the colors.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using join tables in ruby on rails Lets say I have two databases: one for students and one for classes. I would like to be able to 'add' classes to a specific student and also be able to add students to a specific class. I assume I need to use a join table here but I am a little lost on how to use them. I would ultimately like to be able to do something like: @class.students.find(@student_id) and this would tell me if the student is in the class or not. I know the relationship between classes and students is 'has_many' and vice versa. Does doing 't.references :students' in the migrate files accomplish that? I tried adding that line to my migrate file and then tried finding something using the statement above and it gave me an error. I am new to RoR so I am not even sure what the best way to go about achieving this is. Any help is appreciated! A: Everything true what @Jordan said, here the concrete steps to take: * *Create a migration: rails g model CourseStudent creates a join model for the n:m relation, and the migration to the corresponding table. *Edit the migration file CreateCourseStudent so it contains the following: class CreateCourseStudent < ActiveRecord::Migration def change create_table :course_students do |t| # Your code comes here t.integer :student_id t.integer :course_id # Here comes the generated code t.timestamps end end end *Run the migration: rake db:migrate. As a result, the join table should now exist in your database. *Add to the models the following code class Course < ActiveRecord::Base has_many :course_students has_many :students, :through => :course_students end class Student < ActiveRecord::Base has_many :course_students has_many :courses, :through => :course_students end class CourseStudent < ActiveRecord::Base belongs_to :student belongs_to :course end You are now able to use the methods generated by the methods belongs_to and has_many: * *@course.students *@student.courses Try to find all the relevant facts and snippets in the Rails Guides, there you should find all information you need to get on track. Good luck! A: This is an old question, but just in case anyone stumbles upon this like I did, you can now have the relationships has_and_belongs_to_many. So yes, you would create a join table: create_join_table :students, :courses do |t| t.integer :student_id t.integer :course_id end And then in the models, you would say that a student has_and_belongs_to_many :courses And a course has_and_belongs_to_many :students. There is no need to make a third class called CourseStudent. This link has all this information A: Yes, this is a many-to-many relationship (class has many students, student has many classes). For this you'll use a has_many :through relation. Take a look at the docs for ActiveRecord::Associations (Ctrl-F for "Association Join Models"). In a migration, t.references :students is how you would specify a belongs_to relation, as it just adds a student_id column (which can only accommodate one id, i.e. one student). A join model, however, will have two columns: student_id and class_id. (Incidentally, calling a model 'Class' in Ruby is asking for trouble. Might I suggest 'Course'?)
{ "language": "en", "url": "https://stackoverflow.com/questions/7606124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: Rails session doesn't persist I can't get Rails sessions to persist, both on a local environment and an external staging environment. Right now I'm just doing something basic, like session[:cart_id]=1 in one of my controllers. If I reload the page the session comes up empty {}. I must be missing something basic because I can't find anything online about this being common. UPDATE 1 Even the simplest code shows sessions not persisting, for example I can do something as simple as session[:counter] = session[:counter].to_i + 1 in my action, and then = debug session in my view, and every time I refresh the browser I get: {} {"session_id"=>"280031b7eb3b4bf612da85acc8815b3b", "counter"=>1} and a new session_id is generated each time. UPDATE 2 I removed the :domain => :all option from my session store and things look better, but still not persisting. Now the session_id is generating only once, so that is persisting. But if I store an integer inside the session it still isn't persisting to the next request. A: I had the same issue and it was driving me nuts. It turned out that I had a protect_from_forgery in my ApplicationController which silently replaced the session with a NullSession. I noticed this when I ran raise session.class.inspect. Using protect_from_forgery with: :exception instead reveals the underlying problem properly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Xcode 4 fullscreen mode not available Ok. Using XCode 4 for a few weeks now. By and large a great improvement. According to users who answered this question, Xcode 4 has a full screen mode. On my system however, here is what I see when I attempt to turn on full screen. I am using one monitor, and it's an Apple LED Cinema Display: Is there something I am missing? XCode version : A: Are you running Snow Leopard or Lion? I don't think XCode 4.1 supports fullscreen on Snow Leopard because fullscreen apps are a Lion feature. EDIT: In fact yes, your Xcode build number indicates Snow Leopard. Unfortunately, fullscreen mode is not supported. Which makes me wonder why they even bother putting the menu item in there if it's never going to work.. A: Based on the shape of your UI buttons, it looks like you're on Snow Leopard 10.6 or earlier. Lion 10.7 provides a whole new system/API for full-screen, and it's possible that Xcode only supports full-screen on Lion. Upgrade to Lion :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7606128", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: #arraymap not include delimiter in output Many, many times, I have wanted to create a template that takes a list of values, and displays them in a table, each on their own line. I've tried hiding the comma in a span, but that breaks the table. <span style="display:none;">{{#arraymap: {{{programmers|}}}|,|x|</span><!-- -->{{!}} Programmer: {{!!}} x {{!-}}<span style="display:none;">}}</span> Is there a method of hiding the delimiter and still getting a table, or perhaps, is there a separate way to do this altogether? If you want a full simplified testcase, I have the following input: {{authors|programmers=Ryan Scheel, Ryan Dean}} and I want the following output: {| class="wikitable" |- ! colspan="2" style="text-align:center;" ! Authors |- | Programmer: || Ryan Scheel |- | Programmer: || Ryan Dean |} or in template form: {{{!}} class="wikitable" {{!-}} ! colspan="2" style="text-align:center;" ! Authors {{!-}} {{!}} Programmer: {{!!}} Ryan Scheel {{!-}} {{!}} Programmer: {{!!}} Ryan Dean {{!}}} A: I solved your problem by passing an empty 5th argument to the function[1]. This argument defines what to replace the delimiter with. {{#arraymap: Ryan Scheel, Ryan Dean|,|x|<nowiki /> {{!-}} {{!}} Programmer: {{!!}} x |<!-- empty 5th parameter -->}} expanded result will be as following: {| <nowiki /> |- | Programmer: || Ryan Scheel<nowiki /> |- | Programmer: || Ryan Dean |} I slightly modified your example for my own convenience during my tests, feel free to adjust it to your taste. I put the |- (HTML <tr>) before the | (HTML <td>) because it is more logical. More important, as you may already know, arguments of parser functions are trimed[2]. The problem is that wiki tables markup ({|, |-, etc.) should be at the beginning of the lines of the source, otherwise it is not interpreted[3]. So, in order to insert a linebreak, in this example before the |-'s, I used the pretty <nowiki /> trick ;-) As a side note, your line ! colspan="2" (...) ! Authors has a mistake, the ! before "Authors" has to be a | instead. [1] documentation at http://www.mediawiki.org/wiki/Extension:Semantic_Forms/Semantic_Forms_and_templates [2] contrary to unnamed parameters of templates! [3] The only exception, as far as I know, is that you can put spaces and HTML comments before.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Qt-OpenCV:How to display grayscale images(opencv) in Qt I have a piece of code here. This is a camera capture application using OpenCV and Qt(for GUI). void MainWindow::on_pushButton_clicked() { cv::VideoCapture cap(0); if(!cap.isOpened()) return; //namedWindow("edges",1); QVector<QRgb> colorTable; for (int i = 0; i < 256; i++) colorTable.push_back(qRgb(i, i, i)); QImage img; img.setColorTable(colorTable); for(;;) { cap >> image; cvtColor(image, edges, CV_BGR2GRAY); GaussianBlur(edges, edges, cv::Size(7,7), 1.5, 1.5); Canny(edges, edges, 0, 30, 3); //imshow("edges", edges); if(cv::waitKey(30) >= 0) break; // change color channel ordering //cv::cvtColor(image,image,CV_BGR2RGB); img = QImage((const unsigned char*)(edges.data), image.cols,image.rows,QImage::Format_Indexed8); // display on label ui->label->setPixmap(QPixmap::fromImage(img,Qt::AutoColor)); // resize the label to fit the image ui->label->resize(ui->label->pixmap()->size()); } } Initially "edges" is displayed in red with green background.Then it switches to blue background. This switching is happening randomly. How can I display white edges in a black background in a stable manner. A: In short, add the img.setColorTable(colorTable); just before the // display on labelcomment. For more details, you create your image and affect the color table at the begining of your code: QImage img; img.setColorTable(colorTable); Then in the infinite loop, you are doing the following: img = QImage((const unsigned char*)(edges.data), image.cols, image.rows, QImage::Format_Indexed8); What happens is that you destroy the image created at the begining of your code, the color map for this new image is not set and thus uses the default resulting in a colored output.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Making tomcat multi-tenant for SaaS Our tomcat server serves a single war file that is serviced by 3 different identical databases for 3 tenants. Plan is to use a JNDI datasource (3 datasources) and use an Abstract Factory to instantiate the necessary subclasses for that tenant. Want to use container managed authentication. We want to use the builtin Java security annotations like @RolesAllowed etc. Auth is via HTTP Basic Auth. This works great for one tenant (default config). However I cant think of a good solution where tomcat can identify the tenant based on the context (https://server/resources/CLIENT1/Blah) and then lookup the appropriate JNDI for CLIENT1/2/3 etc.. Thoughts or suggestions ? A: Solved by creating Virtual Hosts Created two virtual hosts localhost localhost2 Created two Realms (UserDatabase realm for testing) UserDatabase UserDatabase2 Both hosts point to the same document root By calling http://localhost/service, realm UserDatabase is used and calling http://localhost2/service, realm UserDatabase2 is used Thanks to Tomcat docs.. <Service name="Catalina"> <Host appBase="webapps" autoDeploy="false" name="localhost" unpackWARs="true"> <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t &quot;%r&quot; %s %b" prefix="localhost_access_log." resolveHosts="false" suffix=".txt"/> </Host> <Host appBase="webapps" autoDeploy="false" name="localhost2" unpackWARs="true"> <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase2"/> </Host> </Engine>
{ "language": "en", "url": "https://stackoverflow.com/questions/7606137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Interactive 2D plotting in python I'm trying to write a program that creates a 2D grid in which the user chooses some edges between the points in the grid. Then the program dynamically manipulate those edges(eg. flip them, connect them, ...) till it converges to a particular shape. * *Now my question is there any particular module that suits this kind of interactive plotting. So far I've looked into PyQwt, GuiQwt, and Chaco but cannot figure out which one is more applicable for my program. It be great if someone could compare and contrast them, or suggest new modules. Thanks A: Have you tried PyGame or SFML? Both support 'setting pixels' on a canvas.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: LDAP protocol vs other Directory Service Protocol What are the reason one would use any other protocol for Naming/Directory Services other than LDAP when LDAP is being a common standard? A: There is only 1 alternative to LDAP as far as I learnt (after searching and reading few articles) and that is X.500. Below is the conclusion from one of the comparisions A popular implementation is to use X.500 as the backbone for the directory and use LDAP as the front-end interface. This allows a better performing Client with a more integrated Server network Disclaimer: This is based on just 20 mins of research. Resources (http://nlc-bnc.ca/iso/ill/document/ill_directory/X_500andLDAP.pdf and http://www.isode.com/whitepapers/ic-6033.html)
{ "language": "en", "url": "https://stackoverflow.com/questions/7606140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the cause of a timeout error using input type="file" in classic asp site? We have recently started experiencing timeout errors on an old (very old - 11 years!) portion of our website that we use internally, to maintain some content on another part of our site. Basically the page involves browsing for a file and uploading it, with a link for users to view that file. Whenever the file we select (using the input field) is large (say 10mg) and we submit the form, IE (or Chrome) times out. If we choose a small file (a few 100 kb) it works correctly. I have narrowed the issue down to the use of the input type="file" element in this classic asp page. I can reproduce the scenario with the most basic of HTML as follows; <html> <body> <form id="myForm" name="myForm" method="post" enctype="multipart/form-data"> <input type="file" size="50" id="Test" name="Test" value="Test"> <input type="submit" value="Test"> </form> </body> </html> Selecting a small file here simply posts back and clears the form, while a large file appears to hang before reporting a timeout error. I've tested this on IE9 and Chrome. We have only just started experiencing this error - we don't even use the feature all that much but I would hazard a guess and say the last time anyone used it correctly was probably using IE8. I am now going to attempt to test using older browsers. Does anyone know what could be causing this behaviour? So far I've searched IE 9 options for settings that may be affecting the timeout but none have jumped out at me. I've looked quickly at IIS settings too but nothing seemed obvious however I am far from an expert in this area (the server runs IIS 6 but we've reproduced this in a test environment running IIS 7 as well). [Update] Thanks to the suggestions so far, I have now tried; * *Resetting the file upload limit in the ASP config settings on IIS *Adjusting the ASP timeout value on IIS Temporarily disabling *Anti-Virus on the server and client. (None of these have resolved the problem.) A: Try adjusting the ASP time-out... IIS 6 ASP Default Timeout I've had similar issues with large files in the past, many years ago with classic ASP, I've also seen this issue when a file is larger than the IIS upload file size. Hopefully, one of these two settings should let it work for you... File Upload Size Limit
{ "language": "en", "url": "https://stackoverflow.com/questions/7606141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Separate application log data from server log data using log4j I am creating a java application which starts a server (Selenium server), performs some actions (run automation tests) and shuts down the server in the end. I am using log4j as the logging framework. The log that is generated contains log data which is sent by my application as well as that which is generated by the server. My log4j.properties is as shown - log4j.rootCategory=info,R1,R2 log4j.appender.R2=org.apache.log4j.ConsoleAppender log4j.appender.R2.layout=org.apache.log4j.PatternLayout log4j.appender.R2.layout.ConversionPattern=[%d{MMM dd HH:mm:ss}] %-5p (%F:%L) - %m%n log4j.category.com.xyz.abc.tests=info, R1 log4j.appender.R1.File=C:/my_log.log log4j.appender.R1=org.apache.log4j.RollingFileAppender log4j.appender.R1.layout=org.apache.log4j.PatternLayout log4j.appender.R1.layout.ConversionPattern=[%d{MMM dd HH:mm:ss}] %-5p (%F:%L) - %m%n My question is how do I separate the log data that is sent by my application from that which is generated by the server? A: you should provide appender for that package/category : log4j.category.<selenium-pkg>=<level>, <appender> for example: log4j.category.org.openqa.selenium=INFO, R2
{ "language": "en", "url": "https://stackoverflow.com/questions/7606143", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: flex mobile project : using Blazeds to access data from java class I know how to create a flex web application that uses blazeds for back end data connectivity. Now I need to use blazeds in flex mobile application for accessing data from java classes. I am searching it in internet for two days but I didnt find any solutions. Please help me to use blazeds in flex mobile app A: On Coenraets blog you have a couple of examples relates to connection mobile flex applications to a java backend (both remoting and messaging). In order to detect if the file was modified you can have a timer in java checking for that at a specified interval. When detecting any changes you can send a message to your Flex application using the messaging services from BlazeDS.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make my SSAS cube production ready I am developing a data warehouse + a data cube for a certain client using Microsoft technologies (SSIS, SSAS and SSRS). I have almost finished doing the data warehouse. I have created a data cube in SSAS and already did the initial setting up of the cube dimensions and facts. So far it was in a development environment. We are expecting to deploy the solution at a production server in about two weeks from now. My question is (as this is my first enterprise level cube creation), I do not know whether the cube is production ready yet. Can anyone let me know whether there are anything in specific I should do to the cube before deploying it? Also I have kept the system suggested names for the cube dimensions and measures; do I need to change them before it goes to the users? Any help is deeply appreciated. A: I'm not sure what you mean by "enterprise level": are there specific security/audit requirements, availability levels, backup schedules or support procedures that you need to comply with? And if your users have accepted the dimension names in the test environment and you have developed reports and even code using them, then why would you want to change them in production? Assuming that you've already deployed cubes and packages successfully to different environments, then the things to check should be exactly the same every time: accounts and permissions, package configurations, scheduled jobs for batch processing etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to compare data between two table in different databases using Sql Server 2008? I have two database's, named DB1 and DB2 in Sql server 2008. These two database's have the same tables and same table data also. However, I want to check if there are any differences between the data in these tables. Could anyone help me with a script for this? A: I'v done things like this using the Checksum(*) function In essance it creates a row level checksum on all the columns data, you could then compare the checksum of each row for each table to each other, use a left join, to find rows that are different. Hope that made sense... Better with an example.... select * from ( select checksum(*) as chk, userid as k from UserAccounts) as t1 left join ( select checksum(*) as chk, userid as k from UserAccounts) as t2 on t1.k = t2.k where t1.chk <> t2.chk A: select * from ( select 'T1' T, * from DB1.dbo.Table except select 'T2' T, * from DB2.dbo.Table ) as T union all select * from ( select 'T2' T, * from DB2.dbo.Table except select 'T1' T, * from DB1.dbo.Table ) as T ORDER BY 2,3,4, ..., 1 -- make T1 and T2 to be close in output 2,3,4 are UNIQUE KEY SEGMENTS Test code: declare @T1 table (ID int) declare @T2 table (ID int) insert into @T1 values(1),(2) insert into @T2 values(2),(3) select * from ( select * from @T1 except select * from @T2 ) as T union all select * from ( select * from @T2 except select * from @T1 ) as T Result: ID ----------- 1 3 Note: It can take long time to compare big table, when developing "tuned" solution or refactorig, which will give same result as REFERERCE - it may be wise to chekc simple parameters first: like select count(t.*) from ( select count(*) c0, SUM(BINARY_CHECKSUM(*)%1000000) c1 FROM T_REF_TABLE -- select 12345 c0, -214365454 c1 -- constant values FROM T_REF_TABLE except select count(*) , SUM(BINARY_CHECKSUM(*)%1000000) FROM T_WORK_COPY ) t When this is empty, you have probably things under controll, and may be you can modify when you fail you will see "constant values FROM T_REF" to isert to save even more time for next check!!! A: select * from DB1.dbo.Table a inner join DB2.dbo.Table b on b.PrimKey = a.PrimKey where a.FirstColumn <> b.FirstColumn ... Checksum that Matt recommended is probably a better approach to compare columns rather than comparing each column A: Comparing the two Databases in SQL Database. Try this Query it may help. SELECT T.[name] AS [table_name], AC.[name] AS [column_name], TY.[name] AS system_data_type FROM [***Database Name 1***].sys.[tables] AS T INNER JOIN [***Database Name 1***].sys.[all_columns] AC ON T.[object_id] = AC.[object_id] INNER JOIN [***Database Name 1***].sys.[types] TY ON AC.[system_type_id] = TY.[system_type_id] EXCEPT SELECT T.[name] AS [table_name], AC.[name] AS [column_name], TY.[name] AS system_data_type FROM ***Database Name 2***.sys.[tables] AS T INNER JOIN ***Database Name 2***.sys.[all_columns] AC ON T.[object_id] = AC.[object_id] INNER JOIN ***Database Name 2***.sys.[types] TY ON AC.[system_type_id] = TY.[system_type_id] A: I’d really suggest that people who encounter this problem go and find a third party database comparison tool. Reason – these tools save a lot of time and make the process less error prone. I’ve used comparison tools from ApexSQL (Diff and Data Diff) but you can’t go wrong with other tools marc_s and Marina Nastenko already pointed out. If you’re absolutely sure that you are only going to compare tables once then SQL is fine but if you’re going to need this from time to time you’ll be better off with some 3rd party tool. If you don’t have budget to buy it then just use it in trial mode to get the job done. I hope new readers will find this useful even though it’s a late answer… A: If the database are in the same server use [DatabaseName].[Owner].[TableName] format when accessing a table that resides in a different database. Eg: [DB1].[dbo].[TableName] If databases in different server look at on Creating Linked Servers (SQL Server Database Engine) A: Another solution (non T-SQL): you can use tablediff utility. For example if you want to compare two tables (Localitate) from two different servers (ROBUH01 & ROBUH02) you can use this shell command: C:\Program Files\Microsoft SQL Server\100\COM>tablediff -sourceserver ROBUH01 -s ourcedatabase SIM01 -sourceschema dbo -sourcetable Localitate -destinationserver ROBUH02 -destinationschema dbo -destinationdatabase SIM02 -destinationtable Lo calitate Results: Microsoft (R) SQL Server Replication Diff Tool Copyright (c) 2008 Microsoft Corporation User-specified agent parameter values: -sourceserver ROBUH01 -sourcedatabase SIM01 -sourceschema dbo -sourcetable Localitate -destinationserver ROBUH02 -destinationschema dbo -destinationdatabase SIM02 -destinationtable Localitate Table [SIM01].[dbo].[Localitate] on ROBUH01 and Table [SIM02].[dbo].[Localitate ] on ROBUH02 have 10 differences. Err Id Dest. Only 21433 Dest. Only 21434 Dest. Only 21435 Dest. Only 21436 Dest. Only 21437 Dest. Only 21438 Dest. Only 21439 Dest. Only 21441 Dest. Only 21442 Dest. Only 21443 The requested operation took 9,9472657 seconds. ------------------------------------------------------------------------ A: If both database on same server. You can check similar tables by using following query : select fdb.name, sdb.name from FIRSTDBNAME.sys.tables fdb join SECONDDBNAME.sys.tables sdb on fdb.name = sdb.name -- compare same name tables order by 1 By listing out similar table you can compare columns schema using sys.columns view. Hope this helps you. A: In order to compare two databases, I've written the procedures bellow. If you want to compare two tables you can use procedure 'CompareTables'. Example : EXEC master.dbo.CompareTables 'DB1', 'dbo', 'table1', 'DB2', 'dbo', 'table2' If you want to compare two databases, use the procedure 'CompareDatabases'. Example : EXEC master.dbo.CompareDatabases 'DB1', 'DB2' Note : - I tried to make the procedures secure, but anyway, those procedures are only for testing and debugging. - If you want a complete solution for comparison use third party like (Visual Studio, ...) USE [master] GO create proc [dbo].[CompareDatabases] @FirstDatabaseName nvarchar(50), @SecondDatabaseName nvarchar(50) as begin -- Check that databases exist if not exists(SELECT name FROM sys.databases WHERE name=@FirstDatabaseName) return 0 if not exists(SELECT name FROM sys.databases WHERE name=@SecondDatabaseName) return 0 declare @result table (TABLE_NAME nvarchar(256)) SET NOCOUNT ON insert into @result EXEC('(Select distinct TABLE_NAME from ' + @FirstDatabaseName + '.INFORMATION_SCHEMA.COLUMNS ' +'Where TABLE_SCHEMA=''dbo'')' + 'intersect' + '(Select distinct TABLE_NAME from ' + @SecondDatabaseName + '.INFORMATION_SCHEMA.COLUMNS ' +'Where TABLE_SCHEMA=''dbo'')') DECLARE @TABLE_NAME nvarchar(256) DECLARE curseur CURSOR FOR SELECT TABLE_NAME FROM @result OPEN curseur FETCH curseur INTO @TABLE_NAME WHILE @@FETCH_STATUS = 0 BEGIN print 'TABLE : ' + @TABLE_NAME EXEC master.dbo.CompareTables @FirstDatabaseName, 'dbo', @TABLE_NAME, @SecondDatabaseName, 'dbo', @TABLE_NAME FETCH curseur INTO @TABLE_NAME END CLOSE curseur DEALLOCATE curseur SET NOCOUNT OFF end GO . USE [master] GO CREATE PROC [dbo].[CompareTables] @FirstTABLE_CATALOG nvarchar(256), @FirstTABLE_SCHEMA nvarchar(256), @FirstTABLE_NAME nvarchar(256), @SecondTABLE_CATALOG nvarchar(256), @SecondTABLE_SCHEMA nvarchar(256), @SecondTABLE_NAME nvarchar(256) AS BEGIN -- Verify if first table exist DECLARE @table1 nvarchar(256) = @FirstTABLE_CATALOG + '.' + @FirstTABLE_SCHEMA + '.' + @FirstTABLE_NAME DECLARE @return_status int EXEC @return_status = master.dbo.TableExist @FirstTABLE_CATALOG, @FirstTABLE_SCHEMA, @FirstTABLE_NAME IF @return_status = 0 BEGIN PRINT @table1 + ' : Table Not FOUND' RETURN 0 END -- Verify if second table exist DECLARE @table2 nvarchar(256) = @SecondTABLE_CATALOG + '.' + @SecondTABLE_SCHEMA + '.' + @SecondTABLE_NAME EXEC @return_status = master.dbo.TableExist @SecondTABLE_CATALOG, @SecondTABLE_SCHEMA, @SecondTABLE_NAME IF @return_status = 0 BEGIN PRINT @table2 + ' : Table Not FOUND' RETURN 0 END -- Compare the two tables DECLARE @sql AS NVARCHAR(MAX) SELECT @sql = '(' + '(SELECT ''' + @table1 + ''' as _Table, * FROM ' + @FirstTABLE_CATALOG + '.' + @FirstTABLE_SCHEMA + '.' + @FirstTABLE_NAME + ')' + 'EXCEPT' + '(SELECT ''' + @table1 + ''' as _Table, * FROM ' + @SecondTABLE_CATALOG + '.' + @SecondTABLE_SCHEMA + '.' + @SecondTABLE_NAME + ')' + ')' + 'UNION' + '(' + '(SELECT ''' + @table2 + ''' as _Table, * FROM ' + @SecondTABLE_CATALOG + '.' + @SecondTABLE_SCHEMA + '.' + @SecondTABLE_NAME + ')' + 'EXCEPT' + '(SELECT ''' + @table2 + ''' as _Table, * FROM ' + @FirstTABLE_CATALOG + '.' + @FirstTABLE_SCHEMA + '.' + @FirstTABLE_NAME + ')' + ')' DECLARE @wrapper AS NVARCHAR(MAX) = 'if exists (' + @sql + ')' + char(10) + ' (' + @sql + ')ORDER BY 2' Exec(@wrapper) END GO . USE [master] GO CREATE PROC [dbo].[TableExist] @TABLE_CATALOG nvarchar(256), @TABLE_SCHEMA nvarchar(256), @TABLE_NAME nvarchar(256) AS BEGIN IF NOT EXISTS(SELECT name FROM sys.databases WHERE name=@TABLE_CATALOG) RETURN 0 declare @result table (TABLE_SCHEMA nvarchar(256), TABLE_NAME nvarchar(256)) SET NOCOUNT ON insert into @result EXEC('Select TABLE_SCHEMA, TABLE_NAME from ' + @TABLE_CATALOG + '.INFORMATION_SCHEMA.COLUMNS') SET NOCOUNT OFF IF EXISTS(SELECT TABLE_SCHEMA, TABLE_NAME FROM @result WHERE TABLE_SCHEMA=@TABLE_SCHEMA AND TABLE_NAME=@TABLE_NAME) RETURN 1 RETURN 0 END GO A: Although this question is for SQL 2018, which in the year 2021 might not be that old, when you use Azure Data Studio, there is an extension that can be installed called SQL Server Schema Compare that does this for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "48" }
Q: How to include JavaScript file in Liferay Portlet? I am not able to include http://maps.googleapis.com/maps/api/js?sensor=false. Whenever I load my portlet for the first time it doesn't work but if I refresh the same page then it starts working fine. I don't know what the issue is. Please Help. A: One of the clean ways to include js file in a portlet, independent of the portal server is to configure in portlet deployment descriptor file as below. For liferay, it would be liferay-portlet.xml. <portlet> <portlet-name>MySamplePortlet</portlet-name> <header-portlet-javascript>http://maps.googleapis.com/maps/api/js?sensor=false</header-portlet-javascript> </portlet>
{ "language": "en", "url": "https://stackoverflow.com/questions/7606178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Upload a photo with some parameters to a Ruby-on-rails web app using Objective-C and an ASIFormDataRequest for iOS I need to upload a list of photos (can be one at a time) to my client's server from an iOS app (iOS 4). His server is using the Phusion Passenger 2.2.14 module on Apache Server (Ubuntu) to deploy his Ruby app. Here is the Ruby code my client used to upload a photo using a Ruby rest client and it worked for one image. He mentonned that the image should be in an array but since here we are only sending one image, it worked. resource = RestClient::Resource.new 'http://serveraddress.com/id.json', :user => '********', :password => '*****' resource.put :property => {:new_images => {:public => '0',:t_viewable => '0', :l_viewable => '0', :name => 'name3', :room => 'Bathroom', :attachment_type => 'periodic', :attached_file => File.new('/Users/me/Pictures/12618298.jpg','rb')} } My question is, how should I encode this data using Objective-C collections? Authentication works fine. Here is the code I am using, but it gets a 500 Internal Server Error: [request setPostValue:photoName forKey:@"property[new_images][0][name]"]; [request setPostValue:[NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]] forKey:@"property[new_images][0][created_at]"]; [request setFile:photoPathFull withFileName:[self.localCaptions objectAtIndex:index] andContentType:@"image/jpeg" forKey:@"property[new_images][0][attached_file]"]; [request setPostValue:self.room forKey:@"property[new_images][0][room]"]; [request setPostValue:imageCategory forKey:@"property[new_images][0][attachment_type]"]; [request setPostValue:public forKey:@"property[new_images][0][public]"]; [request setPostValue:tViewable forKey:@"property[new_images][0][t_viewable]"]; [request setPostValue:lViewable forKey:@"property[new_images][0][l_viewable]"]; *Note that the request variable is an ASIFormDataRequest object. He also specified the server expects the following parameters: property[new_images][1][name]=Sink property[new_images][1][created_at]=<timestamp> property[new_images][1][attached_file]=<filedata> property[new_images][1][room]=Kitchen property[new_images][1][attachment_type]=periodic property[new_images][1][public]=0 property[new_images][1][t_viewable]=0 property[new_images][1][l_viewable]=0 Thanks, I finally got access to the errors log on the server side, so here is what it looks like: ActiveRecord::UnknownAttributeError: unknown attribute: 0 {"format"=>"json", "property"=> {"new_images"=> {"0"=> {"tenant_viewable"=>"0", "name"=>"photo2011-10-01 08:43:07 +0000.jpg", "landlord_viewable"=>"0", "attached_file"=>"#<File:0xda0361c>", "created_at"=>"1317459424.523741", "attachment_type"=>"periodic_check", "public"=>"0", "room"=>"Kitchen"}}}, "action"=>"update", "id"=>"866", "controller"=>"properties"} Action properties#update URL http://server.com/000.json File [GEM_ROOT]/gems/activerecord-2.2.2/lib/active_record/base.rb:2587 It seems clear now that the attribute 0 (after attribute "new_images") is not expected from the server. Seems like it's more of an array position than an attribute. A: ASIHTTPRequest can't automatically do a conversion of an array to a HTTP POST like that. Try using ASIFormDataRequest instead: ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; // Upload a file on disk [request setFile:@"/Users/ben/Desktop/ben.jpg" withFileName:@"myphoto.jpg" andContentType:@"image/jpeg" forKey:@"photo"]; You'll probably have to experiment to some extent to figure out exactly the right format. I've advise using charlesproxy to compare the requests send by your working ruby code and the non-working iOS code on the emulator. A: to do it for one image at a time you need to set the full property key value [request setPostValue:@"Sink" forKey:@"property[new_images][1][name]"]; [request setPostValue:<timestamp> forKey:@"property[new_images][1][created_at]"]; .... Tedious, but I'm not sure you can set the single key property using an NSDictionary directly. Dont think ASI is that smart. To do it for an array, just enumerate through your array of images and set the [1] portion of the request key name to the actual index (e.g. [1], [2], [3], etc...) I think that should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Apache poi slide show to pdf conversion Is there any way to convert generated .ppt file using apache poi to .pdf file? OR Any way to convert PPT file to PDF file using JAVA? A: Gagravarr, thanks you for your comment with following approach: PPT -> images -> PDF. It gave me clues for further solutions. Recently, I've faced the same task: convert PPT reports into PDF reports using Java facilities. PPT reports are generated via Apache POI lib, and I intended to reuse ready created PPT structure. I developed two solutions, each has its own advantages/disadvantages. And both of them using iText library with version 2.1.7.(which is free to use, and which is great)). Both of them do support Japanese symbols after additional enhancement. 1. Apache POI Slide -> image -> PDF Demonstration code example: package com.test.pdf; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.hslf.model.Slide; import org.apache.poi.hslf.usermodel.SlideShow; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Image; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.PdfWriter; public class PPTtoImageToPDFexample { public static void main(String[] args) throws IOException, DocumentException { //load any ppt file FileInputStream inputStream = new FileInputStream("d:/temp/initialPPT.ppt"); SlideShow ppt = new SlideShow(inputStream); inputStream.close(); Dimension pgsize = ppt.getPageSize(); //take first slide and save it as an image Slide slide = ppt.getSlides()[0]; BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = img.createGraphics(); graphics.setPaint(Color.white); graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height)); slide.draw(graphics); FileOutputStream out = new FileOutputStream("d:/temp/slideImage.png"); javax.imageio.ImageIO.write(img, "png", out); out.close(); //get saved slide-image and save it into pdf Image slideImage = Image.getInstance("d:/temp/slideImage.png"); Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream("d:/temp/PPTtoImageTest.pdf")); document.setPageSize(new Rectangle(slideImage.getWidth(), slideImage.getHeight())); document.open(); slideImage.setAbsolutePosition(0, 0); document.add(slideImage); document.close(); } } 2. This approach works on-fly: take Apache POI Slide -> get awt.Graphics2 instance from it -> pass this interface to the iText draw engine. Demonstration code example: package com.test.pdf; import java.awt.Dimension; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.hslf.model.Slide; import org.apache.poi.hslf.usermodel.SlideShow; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.PdfGraphics2D; import com.lowagie.text.pdf.PdfWriter; public class PPTtoPDFdirectly { public static void main(String[] args) throws IOException, DocumentException { //load any ppt file FileInputStream inputStream = new FileInputStream("d:/temp/initialPPT.ppt"); SlideShow ppt = new SlideShow(inputStream); inputStream.close(); Dimension pgsize = ppt.getPageSize(); //take first slide and draw it directly into PDF via awt.Graphics2D interface. Slide slide = ppt.getSlides()[0]; Document document = new Document(); PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream("d:/temp/PPTtoPDF.pdf")); document.setPageSize(new Rectangle((float)pgsize.getWidth(), (float) pgsize.getHeight())); document.open(); PdfGraphics2D graphics = (PdfGraphics2D) pdfWriter.getDirectContent().createGraphics((float)pgsize.getWidth(), (float)pgsize.getHeight()); slide.draw(graphics); graphics.dispose(); document.close(); } } A: One option is to use POI to convert each slide into an image, then use something like Apache PDFBox to place each image onto it's own PDF page. This should work well for simpler PPT files, but the code to render slides is still a WIP. So, if you have a very complex slide, you may find some bits missing/incorrect, do send in patches if you fix any of these gaps! Otherwise, your other option is to use the Java bindings for OpenOffice, and have that do the conversion for you
{ "language": "en", "url": "https://stackoverflow.com/questions/7606182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: PInvoke when you don't know the DLL at compile time? In C#, I'm trying to PInvoke a "simple" function I have in C++. The issue is that I don't know the name or location of the library at compile time. In C++, this is easy: typedef HRESULT (*SomeFuncSig)(int, IUnknown *, IUnknown **); const char *lib = "someLib.dll"; // Calculated at runtime HMODULE mod = LoadLibrary(lib); SomeFuncSig func = (SomeFuncSig)GetProcAddress("MyMethod"); IUnknown *in = GetSomeParam(); IUnknown *out = NULL; HRESULT hr = func(12345, in, &out); // Leave module loaded to continue using foo. For the life of me I can't figure out how to do this in C#. I wouldn't have any trouble if I knew the dll name, it would look something like this: [DllImport("someLib.dll")] uint MyMethod(int i, [In, MarshalAs(UnmanagedType.Interface)] IUnknown input, [Out, MarshalAs(UnmanagedType.Interface)] out IUnknown output); How do I do this without knowing the dll I'm loading from at compile time? A: You do it the same way. Declare a delegate type whose signature matches the exported function, just like SomeFuncSig. Pinvoke LoadLibrary and GetProcAddress to get the IntPtr for the exported function, just like you did in C++. Then create the delegate object with Marshal.GetDelegateForFunctionPointer(). A: Thee is a solution here: Dynamically calling an unmanaged dll from .NET (C#) (based on LoadLibrary/GetProcAddress) A: If you know the DLL name in advance, and you know the function names in advance, there is a simpler way. You can simply declare the P/Invoke signatures, then use LoadLibrary to load the DLL based on for example a configuration file entry. As long as you successfully call LoadLibrary before any of the P/Invoke functions are used, they will succeed as the DLL is already loaded.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Deletion in binary search tree So when I delete in binary search tree, do I need to have like 7 different cases i.e. * *Left Leaf; *Right Leaf; *Left child with only left child. //i.e the node to be deleted is the left child of it's parent and it has only left child. *Left Child with only right child. *Right child with only left child. *Right child with only right child. *Node to be deleted has both the children i.e. right and left. Now when this code is using if-else it gets pretty nasty.. is there any other way of doing this. Here is my code snippet if(current->left==NULL && current->right==NULL && current->key<prev->key) //left leaf prev->left=NULL; else if(current->left==NULL && current->right==NULL && current->key>prev->key) // right leaf prev->right=NULL; else if(current->left!=NULL && current->right==NULL && current->key<prev->key) // left child with one child prev->left=current->left; else if(current->left==NULL && current->right!=NULL && current->key<prev->key) prev->left=current->right; else if(current->left!=NULL && current->right==NULL && current->key>prev->key) prev->right=current->left; else if(current->left==NULL && current->right!=NULL && current->key>prev->key) prev->right=current->left; else if(current->left!=NULL && current->right!=NULL) { check=current->right; check1=check; while(check->left!=NULL) { check1=check; check=check->left; } *current=*check; check1->left=NULL; } A: You can keep it a lot simpler than that, and simply restrict yourself to three cases when deleting a node from a BST (binary search tree) : * *a node without children (a leaf) : just remove it - nothing special needs to be done *a node with one child : remove it, and move the child in its place *a node with two children : swap it with either its in-order predecessor or successor, and then remove it The wiki page contains an example of how this could look in code. Or as a very basic example in C : if (current->left==NULL && current->right==NULL) { /* leaf node */ bst_replace(current, NULL); } else if (current->left==NULL || current->right==NULL) { /* node with one child */ bst_replace(current, ((current->left) ? current->left : current->right)); } else { /* node with two children */ Node* successor = bst_next(current); current->data = successor->data; bst_replace(successor, successor->right); } A: I don't really understand the protocol used for deleting here. You seem to not have a binary 'search' tree (no ordering in the tree). But to just make the code simple. You could do something like this: bool b1 = (current->left == NULL); bool b2 = (current->right == NULL); bool b3 = (current->key > prev->key); int decision_case = b1 * 4 + b2 * 2 + b3; switch(decision_case) { case 0: // fill in code here break; ... ... case 7: // fill in code here break; } Also, you should use delete to avoid memory leaks here. Hope that helps. A: Deleting a NULL pointer has no ill effect. So, you should be able to do this with no special cases. The basic part is just: delete current->left; delete current->right;
{ "language": "en", "url": "https://stackoverflow.com/questions/7606185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Arrays with Curiously Recurring Template Pattern? I have a CRTP-based wrapper for a Windows HANDLE: #include <windows.h> template<class T> class HandleT { HANDLE handle; operator HANDLE() const { return this->handle; } static ULONG WaitForMultipleObjects(DWORD count, /* ??? */ objects[]) { return WaitForMultipleObjects(count, ...); } }; class EventHandle : Handle<EventHandle> { //... }; class FileHandle : Handle<FileHandle> { //... }; The trouble I'm having is, I have no idea what to substitute for ??? above. I can't say HandleT<T>, because they can be different kinds of handles, which wouldn't fit into an array. And I don't want to say HANDLE, because then the function wouldn't be working on HandleT objects at all -- the user might as well just avoid calling the wrapper entirely. And I can't use variadic templates, because I'm still in the pre-C++0x world. Is there a known solution to this problem, or do I just have to use a non-ideal solution mentioned above? A: You may mix CRTP and polymorphism. See https://stackoverflow.com/a/13868014/1902095 The idea is to have an interface class, BaseHandle, which would be used as polymorphic pointer within the array in question. HandleT<> would inherit the above class and implement common methods (and those methods that differ by T).
{ "language": "en", "url": "https://stackoverflow.com/questions/7606188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: IllegalStateException when using a custom SQLFunctionTemplate I am attempting to register function within Hibernate so that I can preform a coalesce within a count statement on a Oracle database. As there seems to very little in the way of examples in how to use this Hibernate feature, I have drawn from the small examples I have found on different forums The application server starts with out issue and the log indicates that it is using the new dialect class. 13:59:59,177 INFO [Dialect] Using dialect: org.myprograms.ece.pi.CustomECEOracle10gDialect However, when I attempt to execute the query using the new function I receive the following exception. Now, I am not sure if I am using the regiesterFunction() in the correct manner or even if there is a better way to preform the count(coalesce(x,y)). Any help would be greatly appreciated. 14:01:20,903 SEVERE [application] java.lang.IllegalStateException: No data type for node: org.hibernate.hql.ast.tree.MethodNode \-[METHOD_CALL] MethodNode: '(' +-[METHOD_NAME] IdentNode: 'countCoalesce' \-[EXPR_LIST] SqlNode: 'exprList' \-[DOT] DotNode: 'miscollvar0_.VALUE' +-[ALIAS_REF] IdentNode: 'miscollvar0_.COLL_VAR_VALUE_ID' \-[IDENT] IdentNode: 'value' javax.faces.el.EvaluationException: java.lang.IllegalStateException: No data type for node: org.hibernate.hql.ast.tree.MethodNode \-[METHOD_CALL] MethodNode: '(' +-[METHOD_NAME] IdentNode: 'countCoalesce' \-[EXPR_LIST] SqlNode: 'exprList' \-[DOT] DotNode: 'miscollvar0_.VALUE' +-[ALIAS_REF] IdentNode: 'miscollvar0_.COLL_VAR_VALUE_ID' \-[IDENT] IdentNode: 'value' at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102) at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102) at javax.faces.component.UICommand.broadcast(UICommand.java:387) at org.ajax4jsf.component.AjaxActionComponent.broadcast(AjaxActionComponent.java:55) at org.ajax4jsf.component.AjaxViewRoot.processEvents(AjaxViewRoot.java:321) at org.ajax4jsf.component.AjaxViewRoot.broadcastEvents(AjaxViewRoot.java:296) at org.ajax4jsf.component.AjaxViewRoot.processPhase(AjaxViewRoot.java:253) at org.ajax4jsf.component.AjaxViewRoot.processApplication(AjaxViewRoot.java:466) at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:265) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:83) at org.jboss.seam.web.IdentityFilter.doFilter(IdentityFilter.java:40) at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) at org.jboss.seam.web.MultipartFilter.doFilter(MultipartFilter.java:90) at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) at org.jboss.seam.web.ExceptionFilter.doFilter(ExceptionFilter.java:64) at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) at org.jboss.seam.web.RedirectFilter.doFilter(RedirectFilter.java:45) at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:178) at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290) at org.ajax4jsf.webapp.BaseFilter.processUploadsAndHandleRequest(BaseFilter.java:368) at org.ajax4jsf.webapp.BaseFilter.doFilter(BaseFilter.java:495) at org.jboss.seam.web.Ajax4jsfFilter.doFilter(Ajax4jsfFilter.java:56) at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) at org.jboss.seam.web.LoggingFilter.doFilter(LoggingFilter.java:60) at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) at org.jboss.seam.web.HotDeployFilter.doFilter(HotDeployFilter.java:53) at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) at org.jboss.seam.servlet.SeamFilter.doFilter(SeamFilter.java:158) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:183) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:433) at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:95) at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126) at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:451) at java.lang.Thread.run(Unknown Source) Caused by: java.lang.IllegalStateException: No data type for node: org.hibernate.hql.ast.tree.MethodNode \-[METHOD_CALL] MethodNode: '(' +-[METHOD_NAME] IdentNode: 'countCoalesce' \-[EXPR_LIST] SqlNode: 'exprList' \-[DOT] DotNode: 'miscollvar0_.VALUE' +-[ALIAS_REF] IdentNode: 'miscollvar0_.COLL_VAR_VALUE_ID' \-[IDENT] IdentNode: 'value' at org.hibernate.hql.ast.tree.SelectClause.initializeExplicitSelectClause(SelectClause.java:167) at org.hibernate.hql.ast.HqlSqlWalker.useSelectClause(HqlSqlWalker.java:831) at org.hibernate.hql.ast.HqlSqlWalker.processQuery(HqlSqlWalker.java:619) at org.hibernate.hql.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:672) at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:288) at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:231) at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:254) at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:185) at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136) at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:101) at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:80) at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:98) at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:156) at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:135) at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1652) at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:93) at org.jboss.seam.persistence.EntityManagerProxy.createQuery(EntityManagerProxy.java:81) at org.myprograms.ece.AdminDataLoadValidator.refreshDiscreteVariableValues(AdminDataLoadValidator.java:437) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.jboss.seam.util.Reflections.invoke(Reflections.java:22) at org.jboss.seam.intercept.RootInvocationContext.proceed(RootInvocationContext.java:32) at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:56) at org.jboss.seam.transaction.RollbackInterceptor.aroundInvoke(RollbackInterceptor.java:28) at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68) at org.jboss.seam.core.BijectionInterceptor.aroundInvoke(BijectionInterceptor.java:77) at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68) at org.jboss.seam.core.MethodContextInterceptor.aroundInvoke(MethodContextInterceptor.java:44) at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68) at org.jboss.seam.intercept.RootInterceptor.invoke(RootInterceptor.java:107) at org.jboss.seam.intercept.JavaBeanInterceptor.interceptInvocation(JavaBeanInterceptor.java:185) at org.jboss.seam.intercept.JavaBeanInterceptor.invoke(JavaBeanInterceptor.java:103) at org.myprograms.ece.admindatafileloader.AdminDataLoadValidator_$$_javassist_seam_16.refreshDiscreteVariableValues(AdminDataLoadValidator_$$_javassist_seam_16.java) at org.myprograms.ece.admindatafileloader.AdminDataFileLoaderBean.viewDiscreteVariableBreakdown(AdminDataFileLoaderBean.java:338) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.jboss.seam.util.Reflections.invoke(Reflections.java:22) at org.jboss.seam.intercept.RootInvocationContext.proceed(RootInvocationContext.java:32) at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:56) at org.jboss.seam.transaction.RollbackInterceptor.aroundInvoke(RollbackInterceptor.java:28) at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68) at org.jboss.seam.core.BijectionInterceptor.aroundInvoke(BijectionInterceptor.java:77) at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68) at org.jboss.seam.core.MethodContextInterceptor.aroundInvoke(MethodContextInterceptor.java:44) at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68) at org.jboss.seam.security.SecurityInterceptor.aroundInvoke(SecurityInterceptor.java:163) at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68) at org.jboss.seam.intercept.RootInterceptor.invoke(RootInterceptor.java:107) at org.jboss.seam.intercept.JavaBeanInterceptor.interceptInvocation(JavaBeanInterceptor.java:185) at org.jboss.seam.intercept.JavaBeanInterceptor.invoke(JavaBeanInterceptor.java:103) at org.myprograms.ece.admindatafileloader.AdminDataFileLoaderBean_$$_javassist_seam_12.viewDiscreteVariableBreakdown(AdminDataFileLoaderBean_$$_javassist_seam_12.java) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:335) at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:348) at org.jboss.el.parser.AstPropertySuffix.invoke(AstPropertySuffix.java:58) at org.jboss.el.parser.AstValue.invoke(AstValue.java:96) at org.jboss.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276) at com.sun.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:68) at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88) ... 54 more 14:01:20,907 WARNING [lifecycle] #{adminDataFileLoader.viewDiscreteVariableBreakdown}: java.lang.IllegalStateException: No data type for node: org.hibernate.hql.ast.tree.MethodNode \-[METHOD_CALL] MethodNode: '(' +-[METHOD_NAME] IdentNode: 'countCoalesce' \-[EXPR_LIST] SqlNode: 'exprList' \-[DOT] DotNode: 'miscollvar0_.VALUE' +-[ALIAS_REF] IdentNode: 'miscollvar0_.COLL_VAR_VALUE_ID' \-[IDENT] IdentNode: 'value' javax.faces.FacesException: #{adminDataFileLoader.viewDiscreteVariableBreakdown}: java.lang.IllegalStateException: No data type for node: org.hibernate.hql.ast.tree.MethodNode \-[METHOD_CALL] MethodNode: '(' +-[METHOD_NAME] IdentNode: 'countCoalesce' \-[EXPR_LIST] SqlNode: 'exprList' \-[DOT] DotNode: 'miscollvar0_.VALUE' +-[ALIAS_REF] IdentNode: 'miscollvar0_.COLL_VAR_VALUE_ID' \-[IDENT] IdentNode: 'value' at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118) at javax.faces.component.UICommand.broadcast(UICommand.java:387) at org.ajax4jsf.component.AjaxActionComponent.broadcast(AjaxActionComponent.java:55) at org.ajax4jsf.component.AjaxViewRoot.processEvents(AjaxViewRoot.java:321) at org.ajax4jsf.component.AjaxViewRoot.broadcastEvents(AjaxViewRoot.java:296) at org.ajax4jsf.component.AjaxViewRoot.processPhase(AjaxViewRoot.java:253) at org.ajax4jsf.component.AjaxViewRoot.processApplication(AjaxViewRoot.java:466) at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100) at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:265) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:83) at org.jboss.seam.web.IdentityFilter.doFilter(IdentityFilter.java:40) at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) at org.jboss.seam.web.MultipartFilter.doFilter(MultipartFilter.java:90) at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) at org.jboss.seam.web.ExceptionFilter.doFilter(ExceptionFilter.java:64) at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) at org.jboss.seam.web.RedirectFilter.doFilter(RedirectFilter.java:45) at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:178) at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290) at org.ajax4jsf.webapp.BaseFilter.processUploadsAndHandleRequest(BaseFilter.java:368) at org.ajax4jsf.webapp.BaseFilter.doFilter(BaseFilter.java:495) at org.jboss.seam.web.Ajax4jsfFilter.doFilter(Ajax4jsfFilter.java:56) at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) at org.jboss.seam.web.LoggingFilter.doFilter(LoggingFilter.java:60) at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) at org.jboss.seam.web.HotDeployFilter.doFilter(HotDeployFilter.java:53) at org.jboss.seam.servlet.SeamFilter$FilterChainImpl.doFilter(SeamFilter.java:69) at org.jboss.seam.servlet.SeamFilter.doFilter(SeamFilter.java:158) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:183) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:433) at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:95) at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126) at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:451) at java.lang.Thread.run(Unknown Source) Caused by: javax.faces.el.EvaluationException: java.lang.IllegalStateException: No data type for node: org.hibernate.hql.ast.tree.MethodNode \-[METHOD_CALL] MethodNode: '(' +-[METHOD_NAME] IdentNode: 'countCoalesce' \-[EXPR_LIST] SqlNode: 'exprList' \-[DOT] DotNode: 'miscollvar0_.VALUE' +-[ALIAS_REF] IdentNode: 'miscollvar0_.COLL_VAR_VALUE_ID' \-[IDENT] IdentNode: 'value' at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102) at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102) ... 53 more Caused by: java.lang.IllegalStateException: No data type for node: org.hibernate.hql.ast.tree.MethodNode \-[METHOD_CALL] MethodNode: '(' +-[METHOD_NAME] IdentNode: 'countCoalesce' \-[EXPR_LIST] SqlNode: 'exprList' \-[DOT] DotNode: 'miscollvar0_.VALUE' +-[ALIAS_REF] IdentNode: 'miscollvar0_.COLL_VAR_VALUE_ID' \-[IDENT] IdentNode: 'value' at org.hibernate.hql.ast.tree.SelectClause.initializeExplicitSelectClause(SelectClause.java:167) at org.hibernate.hql.ast.HqlSqlWalker.useSelectClause(HqlSqlWalker.java:831) at org.hibernate.hql.ast.HqlSqlWalker.processQuery(HqlSqlWalker.java:619) at org.hibernate.hql.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:672) at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:288) at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:231) at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:254) at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:185) at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136) at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:101) at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:80) at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:98) at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:156) at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:135) at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1652) at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:93) at org.jboss.seam.persistence.EntityManagerProxy.createQuery(EntityManagerProxy.java:81) at org.myprograms.ece.admindatafileloader.AdminDataLoadValidator.refreshDiscreteVariableValues(AdminDataLoadValidator.java:437) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.jboss.seam.util.Reflections.invoke(Reflections.java:22) at org.jboss.seam.intercept.RootInvocationContext.proceed(RootInvocationContext.java:32) at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:56) at org.jboss.seam.transaction.RollbackInterceptor.aroundInvoke(RollbackInterceptor.java:28) at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68) at org.jboss.seam.core.BijectionInterceptor.aroundInvoke(BijectionInterceptor.java:77) at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68) at org.jboss.seam.core.MethodContextInterceptor.aroundInvoke(MethodContextInterceptor.java:44) at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68) at org.jboss.seam.intercept.RootInterceptor.invoke(RootInterceptor.java:107) at org.jboss.seam.intercept.JavaBeanInterceptor.interceptInvocation(JavaBeanInterceptor.java:185) at org.jboss.seam.intercept.JavaBeanInterceptor.invoke(JavaBeanInterceptor.java:103) at org.myprograms.ece.admindatafileloader.AdminDataLoadValidator_$$_javassist_seam_16.refreshDiscreteVariableValues(AdminDataLoadValidator_$$_javassist_seam_16.java) at org.myprograms.ece.admindatafileloader.AdminDataFileLoaderBean.viewDiscreteVariableBreakdown(AdminDataFileLoaderBean.java:338) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.jboss.seam.util.Reflections.invoke(Reflections.java:22) at org.jboss.seam.intercept.RootInvocationContext.proceed(RootInvocationContext.java:32) at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:56) at org.jboss.seam.transaction.RollbackInterceptor.aroundInvoke(RollbackInterceptor.java:28) at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68) at org.jboss.seam.core.BijectionInterceptor.aroundInvoke(BijectionInterceptor.java:77) at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68) at org.jboss.seam.core.MethodContextInterceptor.aroundInvoke(MethodContextInterceptor.java:44) at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68) at org.jboss.seam.security.SecurityInterceptor.aroundInvoke(SecurityInterceptor.java:163) at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:68) at org.jboss.seam.intercept.RootInterceptor.invoke(RootInterceptor.java:107) at org.jboss.seam.intercept.JavaBeanInterceptor.interceptInvocation(JavaBeanInterceptor.java:185) at org.jboss.seam.intercept.JavaBeanInterceptor.invoke(JavaBeanInterceptor.java:103) at org.myprograms.ece.admindatafileloader.AdminDataFileLoaderBean_$$_javassist_seam_12.viewDiscreteVariableBreakdown(AdminDataFileLoaderBean_$$_javassist_seam_12.java) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:335) at org.jboss.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:348) at org.jboss.el.parser.AstPropertySuffix.invoke(AstPropertySuffix.java:58) at org.jboss.el.parser.AstValue.invoke(AstValue.java:96) at org.jboss.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276) at com.sun.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:68) at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88) ... 54 more My new dialect class package org.myprograms.ece.pi; import org.hibernate.Hibernate; import org.hibernate.dialect.Oracle10gDialect; import org.hibernate.dialect.function.SQLFunctionTemplate; import org.hibernate.dialect.function.StandardSQLFunction; import org.hibernate.engine.Mapping; import org.hibernate.type.Type; public class CustomECEOracle10gDialect extends Oracle10gDialect { public CustomECEOracle10gDialect() { super(); registerFunction( "countCoalesce", new SQLFunctionTemplate(Hibernate.LONG, "count(coalesce(?1, 'null'))") { public Type getReturnType(Type columnType, Mapping mapping) { return Hibernate.LONG; } } ); } } My persistence.xml file <persistence-unit name="ECE"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <jta-data-source>java:/ECEDatasource</jta-data-source> <properties> <property name="hibernate.dialect" value="org.myprograms.ece.pi.CustomECEOracle10gDialect"/> <property name="hibernate.hbm2ddl.auto" value="validate"/> <property name="hibernate.show_sql" value="true"/> <property name="hibernate.show_sql" value="false"/> <property name="hibernate.format_sql" value="true"/> <property name="hibernate.default_schema" value="mySchema"/> <property name="jboss.entity.manager.factory.jndi.name" value="java:/ECEEntityManagerFactory"/> <property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup"/> </properties> My query using the new function Query qyDiscreteVariableValues = entityManager.createQuery( " select " + " misCollVariableValue.value as value, " + " countCoalesce(misCollVariableValue.value) as Total " + " from " + " MisCollVariableValue misCollVariableValue " + " where " + " misCollVariableValue.mdCollVariable = :pMdCollVaraibleId " + " and loadId = :pLoadId " + " group by " + " misCollVariableValue.value " ); The generated SQL, select miscollvar0_.VALUE as col_0_0_, count(miscollvar0_.VALUE) as col_1_0_ from greesc.MIS_COLL_VARIABLE_VALUE miscollvar0_ where miscollvar0_.COLL_VARIABLE_ID=? and miscollvar0_.LOAD_ID=? group by miscollvar0_.VALUE
{ "language": "en", "url": "https://stackoverflow.com/questions/7606189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: NullPointerException when trying to play a sound with MediaPlayer So I have a simple soundboard type application that operates via a ListView. Tap an item, it plays the sound. I have a public static int[] named soundResourceList that has entries such as R.raw.foo, R.raw.bar in the same order of the entries associated with the text in the ListView. This code has worked for many users including myself, however one recently posted a NullPointerException, in particularly from the setOnCompletionListener line. This to me means that MediaPlayer.create returned null, but I can't figure out why it would fail on their device but not everybody else's. public void onListItemClick(ListView parent, View v, int position, long id) { MediaPlayer mp = MediaPlayer.create(getBaseContext(), soundResourceList[position]); mp.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); mp.setOnPreparedListener(new OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mp.start(); } }); } Normally a NPE with MediaPlayer is due to something like not releasing its previous instance, but I already have that issue handled as shown in the code. So what am I missing that might cause the MediaPlayer.create() to fail? A: The create method doc says: Returns a MediaPlayer object, or null if creation failed Since a number of low-level resources might be allocated for each MediaPlayer, it could be that if the GC is busy for a while or doesn't run you'll run out of sound buffers (or whatever) and the MediaPlayer allocation will fail, returning null. If these are all relatively-short-lived audio snippets, you might look into android.media.SoundPool.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: XSLT 1.0 Regular Expression in for loop So I have xml like <depot id="D7"> <address> <number>6000</number> <street>Yonge</street> <city>Toronto</city> <province>ON</province> <postal_code>M2M 2E4</postal_code> </address> </depot> I have hundreds of there depot in xml now in my xsl, I have defined a variable called 'locale' that stores a postal code like "M1C". After this I want to select only those depot where the postal_code is like 'locale'. In other words, If I specify locale to be "M1C", then I should get all the depot whose postal_code contains "M1C", so depot with "M1C A18", "M1C B2C", etc all should be in the result. Currently I have the line below < xsl:for-each select="depot[address[postal_code=$locale]]"> which gives me only depot with exact postal code match and not the ones with "M1C A18", "M1C B2C", etc. I want to use something like <xsl:for-each select="depot[address[postal_code=*$locale*]]"> with wildcards but it does not works. Suggestions? A: Use: depot[starts-with(address/postal_code, $locale)] Here we assume that any depot has a single address/postal_code descendent and that no possible value of $locale is a prefix of any other possible value of $locale. If, for example, the second assumption isn't true, then use: depot[starts-with(address/postal_code, concat($locale, ' '))] True regular expression capabilities are available in XPath 2.0 (such as the matches() function), but they aren't necessary for a simple problem as this one. A: Use this: <xsl:for-each select="depot[contains(address/postal_code,$locale)]" /> to match only depot elements that contain the fragment defined in $locale.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Scanning a single char into an array C Programming I am having a problem scanning chars into an array. Every time I do it will skip the next scan and go to the next. I know what is happening because the input also adds '\n' to the input but I do not know how to remedy the cause of it. Here is some sample code: char charray [MAX], ffs; int inarray [MAX], i; for (i = 0; i < MAX; i++) { charray[i] = getchar(); printf ("%c\n",charray[i]); scanf ("%d", &inarray[i]); printf ("%d\n",inarray[i]); } A: You can do like this. while((c = getchar()) != '\n') { putchar(c); } this may solve your problem. or you can go till EOF also. A: You are reading from the standard input with 2 functions: getchar() and scanf(). You need to understand how they work. getchar() is easy: it returns the next available character in the input stream (or waits for one or returns EOF) scanf("%d", ...) is more complex: first, it optionally discards whitespace (spaces, enters, tabs, ...), then it reads as many characters as possible to represent an integer, and stops at the first character that can't be used for integers, like a '\n'. As you have them in a loop, your getchar() call will get the character that stopped the scanf() and the next scanf() will procedd from there. If your input is something like "q1w22e333r4444" (with MAX == 4), your program will work. If your input is something like q 1 w 22 e 333 r 4444 after the first time through the loop (where charray[0] gets 'q' and inarray[0] gets 1), the getchar() will get '\n' leaving the 'w' "ready" for scanf, which of course fails ... and is then "caught" by the next getchar(); and the "22" gets assigned in the 3rd time through the loop (to inarray[2]). So, you need to review your code. Also, scanf() returns a value. Use that value if (scanf("%d", &inarray[i]) != 1) /* error */; A: You should actually scan a string into the array directly, rather than characters using scanf("%s",&charray); However your code will work if you add a while(getchar() != '\n' ); statement. This will get all characters till the '\n'. charray[i] = getchar(); do{ c = getchar(); }while(c != '\n' && c!= EOF); printf ("%c\n",charray[i]); scanf ("%d", &inarray[i]); do{ c = getchar(); }while(c != '\n' && c!= EOF); printf ("%d\n",inarray[i]);
{ "language": "en", "url": "https://stackoverflow.com/questions/7606198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Random URL JS with Multiple Lists I have a navigation bar and I want to access a random URL from a distinct list associated with each link. Link A would access List A, link B would access List B, and so on. I have been using a javascript code from 1997 that works great for one link: <--code contained in a js file:--> rnd.today=new Date(); rnd.seed=rnd.today.getTime(); function rnd() { rnd.seed = (rnd.seed*9301+49297) % 233280; return rnd.seed/(233280.0); }; function rand(number) { return Math.ceil(rnd()*number); }; var item = 0; var URL = new Array(); URL[item++] = 'listitema.php'; URL[item++] = 'listitemb.php.php'; URL[item++] = 'listitemc.php'; function randomJump() { var random = rand(item) - 1; location.href = URL[random]; }; <--end js file:--> This is accessed with this: <a href="javascript:randomJump()" onmouseover="self.status='';return true"> While this code works well for one link per page, I now need to have it work for multiple links, each with a different reference list. I have no idea how to make this a script that works for each link without interfering with other links. Thank you. A: Here's a small function that works with as many different URL lists as you want: var listA = [ 'listitem-a.php', 'listitem-b.php', 'listitem-c.php' ]; var listB = [ 'listitem-1.php', 'listitem-2.php', 'listitem-3.php' ]; var listC = [ 'listitem-x.php', 'listitem-y.php', 'listitem-z.php' ]; function goRandomURL(list) { window.location = list[Math.floor(Math.random() * list.length)]; } Then, to use listA, you would call: goRandomURL(listA); or put it in a link like this: <a href="#" onclick="goRandomURL(listA)"> or for listB, you would use this: <a href="#" onclick="goRandomURL(listB)"> For your own reference, the javascript Math.random() function returns a random number as a float between 0 and 1 (not including 1) and it's already seeded based on the local environment so you don't need to introduce your own seed or random functions. The random number is then scaled by the length of the array passed in and then rounded down to a whole number for array indexing. This has the effect of selecting a random index to our array. It automatically tracks the length of the array so you are free to add/remove items from the array without changing the code in any way. EDIT - to help you on your current code. In your current code, I see this: var listA = [ 'orange.php'; 'red.php'; 'blue.php'; ]; var listB = [ 'gold.php'; 'silver.php'; 'bronze.php'; ]; var listC = [ 'olive.php'; 'pink.php'; 'purple.php'; ]; It should be this: var listA = [ 'orange.php', 'red.php', 'blue.php' ]; var listB = [ 'gold.php', 'silver.php', 'bronze.php' ]; var listC = [ 'olive.php', 'pink.php', 'purple.php' ]; And this: goRandomURL(list) { window.location = list[Math.floor(Math.random() * list.length)]; } should be this: function goRandomURL(list) { window.location = list[Math.floor(Math.random() * list.length)]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7606199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Relative path in settings.py in django for various settings(MEDIA_ROOT,TEMPLATE_DIRS) in setting.py it is instructed to give absolute path.I have configured apache with mod_wsgi.I have a wsgi script in the folder named apache that redirects to settings.py. import os import sys path = 'D:/Projects/Dan' if path not in sys.path: sys.path.append(path ) os.environ['DJANGO_SETTINGS_MODULE'] = 'Django.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() (don't misunderstand - Django is the name of my project.) Okay my question is - now that we have imported the path to my project to system path in the wsgi script, isn't it more feasible that I give a relative path in settings.py,since that would make deploying easier.If I am wrong please tell me the standard procedure so that I can set all the path in one file other than 3 files(Apache - httpd.conf, mod_wsgi - django.wsgi, django - settings.py). A: Use: import os this_directory = os.path.dirname(__file__) and then: absolute_directory = os.path.join(this_directory, 'relative.txt') BTW, calling your project 'Django' is ill advised given that Django package itself is 'django'. You shouldn't rely on differences in case not causing confusion. In short, Python packages/module names should ever differ just by case. Your site project directory is treated as a Python package and thus the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Paypal error "DEVELOPER ERROR: FILE SYSTEM CHECK FAILED" in iphone device I have developed an application with paypal implementation. When i run this application on iphone simulator it works well. But when i run same application on iphone device, it display "Network error. Pay with PayPal not available. Please try again later." error at the start of application. Also in my console(Log) it will display "DEVELOPER ERROR: FILE SYSTEM CHECK FAILED" error. So please give me solution for that problem. Thanks in advance... A: I have this kind of problem before. And in my case, its due to the iPhone itself. I don't remember where i read it but turns out, paypal does not work in most of jailbreak iphone, depending on how u jailbreak it. They claimed that its a security threat. The only way to test whether its working or not is to restore the iPhone via iTunes and delete all the jailbreak traces or test it with another device which is not jailbroken, of course.. A: PayPal also not very consistent with this error, I got different errors with different SDK versions The only thing I found in PayPal forums: Mobile Payment Library is not supported in jailbroken iPhone - see https://www.x.com/search/site/Mobile%20Payment%20Library%20is%20not%20supported%20in%20jailbroken%20iPhone A: If your phone is not jailbroken and is genuine, please look here for the answer that worked for me -> Paypal error : FILE SYSTEM CHECK FAILED
{ "language": "en", "url": "https://stackoverflow.com/questions/7606207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: asynchronous UIImageView in custom UITableViewCell I would like to know how people implement an asynchronous UIImageView loading, if you have it inside a custom UITableViewCell, I've seen quite some examples using GCD, subclassing UIImageView.. all of them must involves NSURLRequest and NSURLConnection. So how do people do this in a subclass of UITableViewCell that has an UIImageView in it? A: Look at this category: SDWebImage. It's a image downloader for UIImageView. You place you're image view in your cell, and in the - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath method, just use: [myImageView setImageWithURL:[NSURL URLWithString:@"example.com/myimage.jpg"]]; A: I think the simple and ideal way to do this is to do the following steps * *Inside cellForRowAtIndexPath: check if the image is available locally load it, else fire off nsurl request to download it in a separate thread and show a loading indicator image. *On completion of request thread, store the image locally reload tableView. A: Here is a very good tutorial which explains asynchronous loading in general.... http://www.raywenderlich.com/4295/multithreading-and-grand-central-dispatch-on-ios-for-beginners-tutorial You can use the same idea to load your image view..
{ "language": "en", "url": "https://stackoverflow.com/questions/7606208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Opencv: image, retrieved from camera capture is always gray I am always getting a grey screen when showing image using opencv, the image is captured from camera. capture = cvCaptureFromCAM(-1); cvGrabFrame(capture); image = cvRetrieveFrame(capture); cvShowImage("name", image); after this I see the grey screen, even if I do in cycle. But the same code works well on another computer. What is the problem? The same opencv library version is used on both computers. Working in the Visual Studio 2010, C++ Opencv version 2.2.0 EDIT 1: The camera used in both computers is the same. And I have tried to rebuild the opencv on the computer where the problem happens, it didn't help. A: I had the same problem in OpenCvSharp. I don't know what's the cause, but for some reason, calling the "WaitKey" method after displaying the image solved it. CvCapture mov = new CvCapture(filepath); IplImage frame = mov.QueryFrame(); CvWindow win1 = new CvWindow(window name); win1.ShowImage(frame); CvWindow.WaitKey(1); A: Your problem sounds very weird. Try to use cvQueryFrame instead of cvRetrieveFrame() and let me know if it does make a difference. Here is a code of using opencv for face detection, the concept of capturing an image is very similar: int main( int argc, const char** argv ) { CvCapture* capture; Mat frame; //-- 1. Load the cascades if( !face_cascade.load( face_cascade_name ) ){ printf("--(!)Error loading\n"); return -1; }; if( !eyes_cascade.load( eyes_cascade_name ) ){ printf("--(!)Error loading\n"); return -1; }; //-- 2. Read the video stream capture = cvCaptureFromCAM( -1 ); if( capture ) { while( true ) { frame = cvQueryFrame( capture ); //-- 3. Apply the classifier to the frame if( !frame.empty() ) { detectAndDisplay( frame ); } else { printf(" --(!) No captured frame -- Break!"); break; } int c = waitKey(10); if( (char)c == 'c' ) { break; } } }return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7606210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }