text
stringlengths
8
267k
meta
dict
Q: Why is no serial data available on my Arduino? I've run the simple serial program on my Arduino Uno, which just echos whatever you type to it. This works perfectly when run in the Arduino Sketch IDE (v22). int incomingByte = 0; // for incoming serial data void setup() { Serial.begin(115200); // opens serial port, sets data rate } void loop() { // send data only when you receive data: if (Serial.available() > 0) { // read the incoming byte: incomingByte = Serial.read(); // say what you got: Serial.print("I received: "); Serial.println(incomingByte, DEC); } } (Code taken from http://arduino.cc/en/Serial/Available) However, I prefer not to use the Arduino IDE and would rather compile my C++ code with avr-g++, so I wrote this, which should function exactly the same as above: extern "C" { #include <avr/io.h> } #include <HardwareSerial.h> extern "C" void __cxa_pure_virtual() { while(1); } int main (void) { int incomingByte = 0; Serial.begin(115200); while (1) { if (Serial.available() > 0) { incomingByte = Serial.read(); //print as an ASCII character Serial.print("received: "); Serial.println(incomingByte, DEC); } } return 1; } I compile and run it, but it doesn't work. I never see my text echoed back to me. I tried printing out the value of Serial.available() in the while(1) loop, and it's always zero. Whenever I type on the keyboard, I see the RX LED light up, but nothing happens after that. I can edit my code to successfully call Serial.println() as long as it's outside the Serial.available() conditional. I've confirmed that my baud rate in my serial software is also set to 115200. And yes, my serial software is pointing to the right serial port. What am I missing? A: Arduino's original glue code looks like this: #include <WProgram.h> int main(void) { init(); setup(); for (;;) loop(); return 0; } The init() stuff is missing in your code. init() is defined in $ARDUINO_HOME/hardware/arduino/cores/arduino/wiring.c, you can either link against it directly or just copy the code of init() into your code. A: You probably have not properly initialized the UART port on the chip. This has to be done manually for microcontrollers, and the Arduino IDE was probably doing it for you. Check the AVR datasheet for your chip, specifically the serial port section. A: Found the answer to my own question: It turns out the HardwareSerial.h library relies on interrupts. This is something that is automagically taken care of for you when building with the Arduino IDE. If you aren't using the Arduino IDE (like me), then you must remember to enable interrupts on your own. Just #include <avr/interrupt.h>, and call sei(); to turn on interrupts before you try to use the Serial Library. cheers!
{ "language": "en", "url": "https://stackoverflow.com/questions/7592848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How can I get image file size which selected by UIImagePickerController? I want to know that the image file size in IPhone PhotoAlbum which selected by UIImagePickerController. I've tried this code with 1,571,299 byte jpeg image. UIIamge *selectedImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"]; NSData *imageData; if ( /* PNG IMAGE */ ) imageData = UIImagePNGReprensentation(selectedImage); else imageData = UIImageJPEGReprensentation(selectedImage); NSUInteger fileLength = [imageData length]; NSLog(@"file length : [%u]", fileLength); But when I run the code, it print 362788 byte. Is there anybody who know this? A: If you have code like this to take a picture: UIImagePickerController *controller = [[[UIImagePickerController alloc] init] autorelease]; controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; controller.delegate = self; [self presentModalViewController:controller animated:YES]; Then you can retrieve a file size of the picked image in the following way: NSURL *assetURL = [info objectForKey:@"UIImagePickerControllerReferenceURL"]; ALAssetsLibrary *library = [[[ALAssetsLibrary alloc] init] autorelease]; [library assetForURL:assetURL resultBlock:^(ALAsset *asset) { NSLog(@"Size: %lld", asset.defaultRepresentation.size); } failureBlock:nil]; If the source type is UIImagePickerControllerSourceTypeCamera, you must save the in-memory image to disk before retrieving its file size. A: As some commenters have said, even if we assume the methodology is correct you are reprocessing the image anyway so the byte sizes will not match. I use the following method for JPG images, ymmv for PNG: + (NSInteger)bytesInImage:(UIImage *)image { CGImageRef imageRef = [image CGImage]; return CGImageGetBytesPerRow(imageRef) * CGImageGetHeight(imageRef); } The above, as a commenter noted, does return the uncompressed size however. A: here is in Swift 4 extension UIImage { var memorySize: Int { guard let imageRef = self.cgImage else { return 0 } return imageRef.bytesPerRow * imageRef.height } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7592850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Maven Application got 5 Modules and 6 POM.xml files I am working on existing Maven Project Which has got 5 modules like <modules> <module>sideware</module> <module>xmlmodule</module> <module>business</module> <module>service</module> <module>helper</module> </modules> Each Module has got a one POM.xml file as well as and one main Pom.xml I am using Eclipse to run the POM.xml files as Maven install Please tell me do i need to run the Each POM.xml indivudally ?? Or can i run the Parent POM.xml file once ?? Thank you A: I think it is sufficient to run the parent POM. See the question What is the "reactor" in Maven? about the plugin that implements that for Maven. So you have the following options (at least): * *Build the parent POM, which will build all modules as well. *Build a module individually, and it will build its dependencies automatically. Here is a small experiment I have done on my own: * *Build automatically == false. *Build a multi-module Maven project, and add there 2 modules. *Insert some code into the modules. *Run mvn install inside eclipse As a result, I get the following output in the console: [INFO] Scanning for projects... [INFO] Reactor build order: [INFO] MultiModuleExample [INFO] Unnamed - com.tsi.mli:sideware:jar:0.0.1-SNAPSHOT [INFO] Unnamed - com.tsi.mli:business:jar:0.0.1-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] Building MultiModuleExample [INFO] task-segment: [install] [INFO] ------------------------------------------------------------------------ [INFO] [site:attach-descriptor {execution: default-attach-descriptor}] [INFO] [install:install {execution: default-install}] [INFO] Installing C:\projekte\setools-work\build\example-build-projekte\indigo-full\ws\multi-module-example\pom.xml to C:\Users\mliebelt\.m2\repository\com\tsi\mli\multi-module-example\0.0.1-SNAPSHOT\multi-module-example-0.0.1-SNAPSHOT.pom [INFO] ------------------------------------------------------------------------ [INFO] Building Unnamed - com.tsi.mli:sideware:jar:0.0.1-SNAPSHOT [INFO] task-segment: [install] ... The directory structure I have got is: multi-module-example/ business/ src/ target/ .classpath .project pom.xml sideware/ ... src/ .project pom.xml
{ "language": "en", "url": "https://stackoverflow.com/questions/7592857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Breaking up a csv file and recreating the arrays I don't need the you to do my work, just point me in the right direction. I'm new to php and I think I can figure it out, I just need pointed in the correct direction on this. I have a csv file with business info (company, address, city, email, etc.) Some of the records have more than one email address in the email field. Each value is separated by a semi-colon (;), What I want to do is end up with each row having one email record. If there was 3 email addresses in the original row, I need 3 rows each with one of the email addresses when I am done. Most of the records have just one email address, but some have as many as 12 email addresses. I know there are data normalcy issues here, but I am building a conversion utility to feed another application. Again, I'm not looking for the final code, though I wouldn't turn it down ;), I am just looking to be pointed in the right direction. Thanks for the help... Jeff A: at first, use fgetcsv() to read the file. this wil aotomatically plit the rows and columns: while (($data = fgetcsv($handle, 1000, ","))) { // do something } the you have to know wich field is the email-field (wich should be field 3 according to your list (3 not 4 because $data is a zero-based array)). use explode() to split up the mail-adresses: $emails = explode(";", $data[3]); after that, you just have to nest the loops: while (($data = fgetcsv($handle, 1000, ","))) { $company = $data[0]; $address = $data[1]; $city = $data[2]; $emails = explode(" ", $data[3]); foreach($emails as $email){ // do something with $company, $address, $email... } } A: here is a tip. You have a CSV like this (company, address, city, email, etc.) And you said you had multiple emails separated by a DIFFERENT character, a semi-colon. Then you could think the field address to ve a "semi-colon"-separated value (a CSV but using a ; instead of a ,) like this email = (email1; email2; email3; etc.) Tell me if you need more help
{ "language": "en", "url": "https://stackoverflow.com/questions/7592858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to receive Application ID from C2DM? I have completed my application and launched in android market.Now I want to add notification. I registered in C2DM and received a mail.But I am so confused. Please anybody tell me the procedure for receiving Registration ID from C2DM?
{ "language": "en", "url": "https://stackoverflow.com/questions/7592859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Creating statecharts in Visio using c# Can anyone point me to an example of how to programatically create a statechart in visio? I can create blank pages, drop shapes, open template etc, but when I try to add transitions it complains that the page is not the right type. Can't find a sample anywhere. Alternatively: I can save the user actions to create the chart as a macro. Can I run that programatically? Thanks. < edit > Step away from the PC for 2 minutes and you realise you should have put the code snippet in the question and not try to put it in comments. Forest: meet trees... Visio.Document umlStencil = visioApp.Documents.OpenEx(@"UMLSTA_M.vss", (short)VisOpenSaveArgs.visOpenDocked); Visio.Page page = visioDoc.Pages.Add(); Visio.Shape s1 = page.Drop(umlStencil[@"State"], 5.0, 5.0); Visio.Shape s2 = page.Drop(umlStencil[@"State"], 5.0, 5.0); Visio.Shape transition = page.Drop(umlStencil[@"Transition"], 1.0, 1.0); As you can see, pretty similar to the snippet in the answer below. < / edit > A: This is the code that I ran with Visual Studio 2010 against both Visio 2007 and Visio 2010. var visioApp = new Visio.Application(); // Load the UML Statechart stencil (docked) var stencil_open_flags = Visio.VisOpenSaveArgs.visOpenDocked; var umlStencil = visioApp.Documents.OpenEx(@"UMLSTA_M.vss", (short)stencil_open_flags); // create a new empty doc based on the UML Model Template var doc = visioApp.Documents.AddEx("UMLMOD_U.VST", Visio.VisMeasurementSystem.visMSUS, 0, 0); var page = doc.Pages.Add(); // Find and manually change the diagram's title var watermark = page.Shapes["Watermark Title"]; var LockTextEdit_cell = watermark.CellsU["LockTextEdit"]; LockTextEdit_cell.FormulaForceU = "GUARD(0)"; watermark.Text = "MyTitle"; LockTextEdit_cell.FormulaForceU = "GUARD(1)"; // Find the masters we need var state_master = umlStencil.Masters["State"]; var transition_master = umlStencil.Masters["Transition"]; // Drop the masters into the page var s1 = page.Drop(state_master, 5.0, 5.0); var s2 = page.Drop(state_master, 1.0, 1.0); var transition = page.Drop(transition_master, 3.0, 3.0);
{ "language": "en", "url": "https://stackoverflow.com/questions/7592860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to resolve Phonegap error while Building the app all I made a sample application with the help of Phonegap, while building the app it gives me two error . Error1: error: 'NSEC_PER_MSEC' undeclared (first use in this function) Error2: Command /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/llvm-gcc-4.2 failed with exit code 1 by the way I am using Xcode 3.2.5 (4.2), can any buddy know this answer then plz tell me.. it is for the xcode 4.3 only?? b/c on this link http://www.phonegap.com/start they run their application through xocde 4.3 A: Ran into the same problem - seems there is a typo in their production code. You need to change 'NSEC_PER_MSEC' to 'NSEC_PER_SEC' and it should work fine... A: Just comment that line.. of code because it has no actual use to test I had the same error and was resolved by commenting :P.. and it runs on ios 4.2 smoothly...
{ "language": "en", "url": "https://stackoverflow.com/questions/7592861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Showing Timer in android My objective is to display a simple timer clock on my screen where it starts from 20 and goes on decreasing and when it becomes 0 I want to start an action. How to achieve this ? Thanks in advance A: I don't know how you want to display it but you can do this also just by taking a TextView and keep changing its Text every second. static int i = 20; new CountdownTimer(20000, 1000) { public void onTick(long millisUntilFinished) { i = i-1; mTextField.setText(String.valuOf(i)); } public void onFinish() { //do your stuff here } }.start();
{ "language": "en", "url": "https://stackoverflow.com/questions/7592863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Rails 3.1 asset:precompile task failing with "bad URI" error Here is the whole error from rake assets:precompile --trace ** Invoke assets:precompile (first_time) ** Execute assets:precompile rake aborted! bad URI(is not URI?): Tasks: TOP => environment Not much to go on. A: Turned out to be largely user error and my lack of understanding of how the /environment files are called. I had a section to parse the CLOUDANT_URL environment variable from Heroku which of course is not available during precompile phase. This probably should have been more obvious to me. I moved this out into a separate initializer which has an if Rails.env.production? block wrapping it. I hope that is a reasonable way to handle this. Thanks everyone for your help. A: This message is most likely because you have an illegal character in one of your asset paths or names. By illegal, I mean a character that needs to be encoded to be used in a URL. I would have thought Rails would do this, but I cannot say for sure without digging into the code. Have a look for things like spaces and extended characters in filenames, and see if removing these solves the problem. You can the method URI.encode(string) to encode these if that is the case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7592870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android: Item Text not showing in listView I've been trying for a long time, and I think I have the code in place, but something is wrong because the item is not being added to the listView. Follows my code: public class EditDoctors extends Activity implements OnClickListener { SimpleAdapter adapter; List<HashMap<String, String>> painItems = new ArrayList<HashMap<String, String>>(); ListView editDoc; int[] to; String[] from; EditText addDoc, docPos; String row1, row2; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.editdoc); addDoc = (EditText) findViewById(R.id.newDoc); docPos = (EditText)findViewById(R.id.docPos); editDoc = (ListView) findViewById(R.id.editDoc); TextView textview = new TextView(this); textview.setText("This is the Songs tab"); Button adddocs = (Button)findViewById(R.id.addbutton); adddocs.setOnClickListener(this); from = new String[] { "row_1", "row_2" }; to = new int[] { R.id.row1, R.id.row2 }; adapter = new Adapter(this, painItems, R.layout.mylistlayout,from, to); editDoc.setAdapter(adapter); } public class Adapter extends SimpleAdapter { HashMap<String, String> map = new HashMap<String, String>(); View row; public Adapter(Context context, List<? extends Map<String, String>> data, int resource, String[] from, int[] to) { super(context, data, resource, from, to); } } private void addItem() { HashMap<String, String> map = new HashMap<String, String>(); map.put("row_1", row1); map.put("row_2", row2); painItems.add(map); adapter.notifyDataSetChanged(); } @Override public void onClick(View arg0) { row1 = addDoc.getText().toString(); Toast.makeText(this, row1, Toast.LENGTH_SHORT).show(); row2 = docPos.getText().toString(); adapter.notifyDataSetChanged(); addItem(); } } This should create a 2-lined listItem, but it doesn't, the lines are empty(no text). The Toast you see in the OnClickMethod returns the text just fine, but the item I add has nothing in it. Thanks in advance. A: I was using the Data Binding example from the book Hello Android by Ed Burnette (great book). I changed the item layout from A RelativeLayout to a LinearLayout; however, I did not add an orientation when I made the change. Once I added android:orientation="vertical" everything worked fine. Two hours of my life on this one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7592871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Create a variable of an instance object of a class at runtime in VB.NET I am trying to create new variables inside a class after creating its object at runtime. The problem is that I don't know the variable names or the value beforehand so I have to create the new variables at runtime. For e.g. - Public Class Test Public Sub Test() End Sub Public Function Fval(ByVal Field As Object) As Object Return Field(1) End Function End Class ''Creating the object of Test class Public Class ExecTest Public Sub Main(ByVal args() As String) Dim obj as New Test() Dim des As ScriptControlClass = New ScriptControlClass() des.Language = "VBScript" des.AddObject("TS", obj, True) Dim xx as Object = des.Eval("Fval(ABC)") End Sub End Class Edit: This is a more elaborate explanation of my code. If you observe that in the Eval function I have tried to evaluate Fval(abc). Now the object array abc is not declared in the Test class because it existence is not known beforehand. What I want to do is create an object array abc of length 2 and populate it with some values and when Fval(abc) is called then then the value of index 1 should be the return value of Eval function. A: You can not add anything to a type in .NET after the type is created. A type is really fixed. You can create create a new type at runtime that inherits from Test, but that will be a lot of work both to create and to access the members of that type. A much more useful approach is to create a Dictionary(Of T, V) in the Test class and store the values in that dictionary with the name of the variable as the key in the dictionary. A: Hm, in my opinion that doesn´t make sense. Because i dont know the Background. But i would try to add a List object to your Test class. In this List you could add what ever you want at runtime. i only know the code in C# so you need to translate it: List<Object> List = new List<Object>(); then you could use: List.add(variable) i hope this helps a little bit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7592879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can we Obtain Version Number of application from App Store for iPhone? Instead of using a web-service to get current application version number and comparing it in my code for popping up update alert, Is there any way to obtain the application version number from App-Store / i-Tunes directly? After going through all the comments correct me if i am wrong. * *We should not show a Local Notification(as alert) to User regarding availability of new update programatically? I went though HIG Guidelines, but could not fing such creteria. So little confused in deciding. A: Alert updates like this will certainly be against Apple guidelines. For iOS devices, application alerts are displayed by the App store app with a badge displaying the number of updates available. There is nothing a developer needs to do. If you are worried about the user missing your app update, rest assured that iOS users keep an eye on the app-store app & know that all updates come through it. However, there are hacky ways by which you can figure out that this is your first run after an update without contacting any web service or iTunes/App store. One of the hacks known to me: Fetch the library directory path- NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); NSString *libPath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil; libPath would be something like - /var/mobile/Applications/8CFB747F-9446-44CB-98B9-C6FF1CF7BF93/Library This random string before /Library changes with every update. You can save this string in NSUserDefaults, and compare the path with the saved string on every launch. If the strings are found to be different, it implies that this is your first run after the update. Display the update alert! Then update the saved string with the new one. A: Yes. You could do an HTTP request to the itunes.apple.com server, while mimicking the User Agent string of iTunes, for your app's URL in the App store, and parse the returned HTML or XML you get back to find the version string, which may or may not be acceptable to Apple's approval team. But that's unlikely to be worth it, and it also presents an uncommon and unexpected user experience.
{ "language": "en", "url": "https://stackoverflow.com/questions/7592880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: jax-rs : parse the ArrayList from Java using JQuery I have an ArrayList returned from my CXF Rest service, but I am unable to parse it to display the details on the client side using JQuery. Appreciate any help thanks, Bob **Sample Code:** This is how my code looks : @GET @Path("/{id}") @Produces("application/json") public Response getDetails(@PathParam("id") Long id) { // data is retreied from database. List<UserBO> userBOList = new ArrayList<UserBO>(); Response response = Response .status(Response.Status.OK) .entity(userBOList) .build(); return response; } =================================================================== My Javascript code: var url = "http://localhost:8080/user/1"; $("#submit").click(function(){ $.ajax({ type: "GET", url: url, beforeSend: function(xhrObj){ xhrObj.setRequestHeader("Origin","null"); }, contentType : "application/json", dataType : "json", success: function(data) { alert( "Data Saved : " + data ); } }); }); A: you can loop through an array in JavaScript like this: for (a in Array){ var item = Array[a]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7592884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Send encrypted id/password from a jsp form to a controller I have a jsp with a 'login' link. On click of Login, a div appears on the top of page. I need to submit my id\password through an ajax call to a spring controller (java) which will then validate it. Can this Form Submit be secured or encrypted in some way ? (I can use only javascript for this) A: To submit the form safely you just have to set the form submit method as 'POST'. Otherwise you can create a new form in javascript function like: function toPost(getString) { // create form element var newForm = document.createElement("form"); newForm.action = <url to post data>; newForm.method = 'POST'; // Hidden field to be send var newH = document.createElement("input"); // set any desired name here newH.name = <name to be set>; newH.type = 'hidden'; newH.value = <value to post>; newForm.appendChild(newH); newForm.submit(); } If you want to send more than one fields than add more fields according to your need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7592887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: simple shopping basket written in ASP What i need a simple shopping basket written in ASP. I have looked around and there are some great full-blown ecommerce solutions out there, but they are beyond my needs and abilities. What I am looking for is an ASP based Shopping cart, in which No database required Simple shopping experience for up to a dozen products Object Oriented design CSS style semantically correct Easy integration with 3rd party payment processor Supports downloadable soft goods I want to use my own (payment method) checkout button They provide functionality to add items into a shopping cart, capture user information and forward to a 3rd party payment processor. A: I would say for you to check on www.hotscripts.com What do you want, if not static pages/content, would have to use a database. About easy integration with third party payments system you should be able to get that information from the third party itself. you would be better off with a full system anyway (i think). check hot scripts for waht you are looking for, I am sure you can find something there cheers PC
{ "language": "en", "url": "https://stackoverflow.com/questions/7592888", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: architecture help with a website in php I am helping to make a website in PHP which is an ERP purpose website. We made mockups of a form to collect user details which is split into 4 screens facebook style where the end user keeps clicking next after filling in each partial form. Finally they get the preview and confirmation receipt is generated. How should I go about this in the backend, I am sure that after the preview I will write the values to the Mysql db and generate a receipt. My question is how do I go about storing the values before the preview? A: you can use php sessions to store the variables in a session and then at the end store them all in the database. http://php.net/manual/en/features.sessions.php A: You cannot really answer your question in isolation. It really depends on how your user is going to use the system, whether the information they enter should be persistent, and even whether you know who the user is? Assuming you know who the user is, and you want to keep failed sessions, my suggestion would be to store the partial responses in a database so you can always access them later. You can then populate or re-populate the form as you wish. You should also have a "start again" button in this scenario. More information would help give a better answer. A: You can just have one form per screen/page and send these values as parameters to the next page via post or get - it's the most simple way A: It is also possible to keep all the form markup on single page and divide form into steps using formToWizard jquery plugin. http://www.jankoatwarpspeed.com/post/2009/09/28/webform-wizard-jquery.aspx This way user has all data available when users clicks and back and forth during the steps and you can just have single submit button.
{ "language": "en", "url": "https://stackoverflow.com/questions/7592889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sign up a new account from mobile app to rails devise app I am using HTTP authentication to sign_in and sign_out. It works great. However, I want to allow users to sign_up for a new account from my mobile app and then send that over using POST and in JSON format. What do I have to do to make this work? I am using Devise for authentication for my Rails app. A: You can POST an http-request with your username/password parameters to your login controller action (which could be as simple as requesting /login?user=foo&pass=bar), specifying .json format (using respond_to). You may need to include the CSRF, too. And I'm assuming here, since you didn't specify the mobile platform or post any code, that you've got the 'making the actual request' part down.
{ "language": "en", "url": "https://stackoverflow.com/questions/7592891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Get Database Results from a Multiplayer game I hope you can help me or at least point me to the direction. Everything has been programmed in c#, but client applications can be in whatever language, just need to know tcp protocol used for communicating with servers. I made a server application, which include a lobby and a game server. You can mount as many game server as you need (actually, I have three, just for test, each one with a different kind of game). The client application connects to lobby for authentication, nd other little things, and request for a game ... after this it's redirected to the appropiate game server. All the information processed during the game, statistics, chats, ... is saved in a PostgreSQL database (you can configure this for use MySQL, MS SQL). Now, the players would like to make some queries to get past info about themself, or stats, or whatever ... my question is: ¿Should I keep players query directly the database, I mean obtain the results from the database server (sending the respective sotre procedure command to get the results)? or (due to they keep an active alive connection with lobby server by socket (and anothers with game server)) ¿Do I receive the request and send the results of each query via lobby server using the permanent active connection socket? ¿Which one is the most performance or even secure? or ¿Will you recommend another suggestion? It's good to say that 5.000 - 10.000 concurrent connections or even more are expected on all game servers. .- I forgot to mention that some queries can has large results, I mean, 500/2000 records (rows) with some columns. .- Forgot to say that I was thinking to set the queries via socket, processing and packaging the query in the server and sending the result to player(s) zipped (compressed). Thanks in advance E/R A: You should absolutely not have the players clients directly submitting queries to your database servers; your game servers should have their own protocol for queries that the clients submit, and the 'game query servers' should sanity-check those queries before building the actual SQL. Under no circumstances should you be building queries directly from user-submitted info, though. A: Most secure is ovbiously the solution where the user does not know the SQL-Server, that is where the lobby server handles all connections and communication (assuming no exploitable bugs on either server ofc). Also you have more control over the implementation of security, having one user (the lobby server), most likely in the same domain, who gets read and execute permissions for exactly only the databases he needs to have those permissions for. Performance < Security, therefore the question regarding performance really does not matter much, but then performance is really also rather a matter of your implementation anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/7592894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to get float value as it is from the text box in objective c Can any one please help me how to get float value as it is from text box for Ex: I have entered 40.7 rateField=[[rateField text] floatValue]; I am getting rateField value as 40.7000008 but I want 40.7 only. please help me. thanks in advance Thanks Every body, I tried all the possibilities but I am not able to get what I want. I am not looking to print the value to convert into string.I want to use that value for computation. If i use Number Formatter again when i am converting from number to float it is giving same problem.So i want float value only but it should be whatever i have given in the text box it should not be padded with any values.This is my requirement.Please help me. thanks&regards Balu Thanks Every body, I tried all the possibilities but I am not able to get what I want. I am not looking to print the value to convert into string.I want to use that value for computation. If i use Number Formatter again when i am converting from number to float it is giving same problem.So i want float value only but it should be whatever i have given in the text box it should not be padded with any values.This is my requirement.Please help me. thanks&regards Balu A: This is ok. There is not guaranteed that you will get 40.7 if you will use even double. If you want to output 40.7 you can use %.1f or NSNumberFormatter A: Try using a double instead. Usually solves that issue. Has to do with the storage precision. double dbl = [rateField.text doubleValue]; A: When using floating point numbers, these things can happen because of the way the numbers are stored in binary format in the computers memory. It's similar to the way 1/3 = 0.33333333333333... in decimal numbers. The best way to deal with this is to use number formatters in the textbox that displays the value. A: You are already resolved float value. Floating point numbers have limited precision. Although it depends on the system, float relative error due to rounding will be around 1.1e-8 Non elementary arithmetic operations may give larger errors, and, of course, error progragation must be considered when several operations are compounded. Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118.... So if you're using those numbers for output, you should use some rounding mechanism, even for double values.
{ "language": "en", "url": "https://stackoverflow.com/questions/7592900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to wait for one task to finish before calling another without blocking? Trying to do something like this: Task task1 = Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite, task1Data, 0, task1Data.Length, null, TaskCreationOptions.AttachedToParent); Task task2 = Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite, task2Data, 0, task2Data.Length, null, TaskCreationOptions.AttachedToParent); But correct me if I'm wrong but isn't there a chance task2 could execute while or before task1 executes? I want something like ContinueWith where the code doesn't block but task2 still does not execute until task1 completes. I tried doing Task task2 = new Task(...) so I could call task1.ContinueWith(task2); but it wouldn't compile. I'm pretty sure I have to use FromAsync (which runs automatically). I think putting task1.Wait(); between the two lines would work but wouldn't that block? Trying to stay away from blocking.. Any advice? A: task1.ContinueWith(t=>Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite, task2Data, 0, task2Data.Length, null, TaskCreationOptions.AttachedToParent));
{ "language": "en", "url": "https://stackoverflow.com/questions/7592903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting error while packaging the code for ipad device using flashbuilder This is vengatesh. I am developing mobile application for android devices and apple ipad, using flashbuilder 4.5 premium.After the completion of code , I can easily create apk file for android devices but I couldn't be able to create ipa file for APPLE devices.While packaging , I got some java exception error like "Exception in threa "main" java.lang.NullPointerException" Please guide me on this issue . I am in urgency to complete my project for ipad devices i used the my indexedarray as for( var j:int = 0; j<controlsXML.length(); j++) { if(sectionXML[i].@Name == controlsXML[j].@SectionName) { indexedArray.push({controlName:controlsXML[j].@Name,Horder:controlsXML[j].@HOrder,Vorder:controlsXML[j].@VOrder}); } } indexedArray.sortOn(["Horder","Vorder"],[Array.NUMERIC,Array.NUMERIC]); A: Try these links will helpful for you: http://va.lent.in/blog/2011/03/25/air2-6-app-for-ios/ http://www.adobe.com/devnet/air/articles/packaging-air-apps-android.html http://tv.adobe.com/.../build-your-first-mobile-application-in-flash-builder-45/ http://help.adobe.com/en_US/as3/iphone/WS789ea67d3e73a8b2-48bca492124b39ac5e2-7ffb.html http://help.adobe.com/en_US/air/build/WSfffb011ac560372f2fea1812938a6e463-8000.html http://www.riagora.com/2010/12/tips-for-flex-mobile-apps/ http://www.adobe.com/devnet/flex/articles/mobile_development_hero_burrito.html http://tv.adobe.com/watch/adc-presents/flex-mobile-part-2-navigation-and-lists/ http://www.yeahbutisitflash.com/?p=986 http://www.instructables.com/id/How-to-use-Adobes-iPhone-Packager-without-an-Appl/ Are you following all the steps of packaging correctly?
{ "language": "en", "url": "https://stackoverflow.com/questions/7592904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Arabic style writing implementation in textfield of IPhone/IPad I am doing an application where I am trying to implement the arabic style of writing in textfield and textview here i have used a line: [self.textfiled setBaseWritingDirection:UITextWritingDirectionRightToLeft]; but I am getting an warning: "method not found". Please suggesst me some solution. A: Have you tried entering Arabic text in the text field after setting the keyboard language to Arabic? I recall that it automatically sets the direction from right to left by detecting the character entered. You would not be required to call this method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7592906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how i can solve this error "A PHP Error was encountered"? Please give some idea. how to solve the error? echo "<td class='bold'>Race Category<span class='star'>*</span></td>"; $array_all=array('name'=>'race_category','value'=>$s_race_category,'type'=>'RACE_CATEGORY','style'=>"class='selectbox'",'javascript'=>'','default'=>''); echo "<td>"; echo $this->model_students->getAll($array_all); echo "</td>"; The error: A PHP Error was encountered Severity: Notice Message: Undefined variable: s_race_category Filename: templates/forms.php Line Number: 46 A PHP Error was encountered Severity: Notice Message: Undefined variable: s_programme Filename: templates/forms.php Line Number: 124 A: The severity says "Notice", meaning they won't break your page but they indicate something else. In this case you probably haven't defined your variables before you use them. try assigning a value to the variables like: $s_race_category = ""; $s_programme = ""; You are seeing these notices because of the PHP error reporting level, you can read more about it here
{ "language": "en", "url": "https://stackoverflow.com/questions/7592917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: asp.net 4.0 update database from xml automatically daily at 12am Basically I want to update tours table in the database from XML automatically daily at specific time. For instance System Daily update my database table from XML at 12AM. Is it possible with ASP.NET 4.0 if yes then how i can implement this? Thanks in Advance. A: Use windows scheduled task instead of asp.net for repeating tasks. you can create console aplication and run it using task sheduler * *Schedule SyncToy to Run Automatically With Task Scheduler in Windows 7 if you want to do it using asp.net try Quartz.net * *Quartz.net setup in an asp.net website
{ "language": "en", "url": "https://stackoverflow.com/questions/7592919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Runtime exception catching different between inside and outside of MSVS I am calling the following function some where in program that will throw an exception public static List<Templates> LoadTemplates() { // ... // System.Threading.Thread.CurrentThread.ManagedThreadId == 1 // ID written to log file System.IO.Directory.GetFiles("does_not_exist_directory"); // ... } And I try to catch the exception in the default Program.cs try { // System.Threading.Thread.CurrentThread.ManagedThreadId == 1 Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } catch (Exception ex) { MessageBox.Show("ERROR CAUGHT"); } finally { // do clean up } When run in MSVS, the exception get caught as expected. But when run by double-clicking the .exe in the output directory the exception display in a message dialog stating EDIT: To catch the error when running the .exe from output directory, the code must be compiled with handling the Application.ThreadException event Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); Application.Run(new Form()); But then MSVS will behave undesirably by showing the MSVS native "Troubleshooting Tips" borderless message dialog "Unhandled Exception". How can I ensure that it behaves the same in and out of MSVS? A: The code you have shown will only catch exceptions in the same thread. It's really hard to tell without seeing the offending code and it's context. You can subscribe to a couple of events to catch all of those: * *AppDomain.UnhandledException *Application.ThreadException please read/note the docs (the first one should do) - there are some caveats. A: It looks like your LoadTemplates call is made in an own Thread. I assume you don't see the MessageBox in Debug mode. You will see the Visual Studio exception window. To solve this problem try to use the AppDomain.CurrentDomain.UnhandledException event: [STAThread] static void Main() { Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { MessageBox.Show("Unhandled exception"); } A: Pertaining to the behaviour of exceptions in and out of MSVS, Carsten was right to point me to the code in MSDN but woni helped me realise the situation better. (It might be otherwise, but) It appears that MSVS hooks its internal event handler to the application when it is run from inside MSVS and that handler is run before my handler in the application. Hence when a unhandled exception occurs, MSVS will show its native "troubleshooting tips" dialog box pointing to the error line. At this point, if I click continue (F5) to continue execute the code, MSVS will re-throw the exception and this time it will be caught by my own handlers. Outside of MSVS, no other handlers are subscribed so it just runs my handlers directly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7592920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: can we load excel 2010 using SSIS 2008? can we load Excel 2010 using SSIS 2008? since in Excel connection manager we have excel version option there we have microsoft excel 2007 as last option,if we want to load excel 2010, how do we do it using ssis 2008? A: Yes, 2007 is valid for 2007 format going forward Excel Connection Manager Editor Option Description Excel 97-2003 File was created using Excel 97 or later. Excel 3.0 File was created using Excel 3.0. Excel 4.0 File was created using Excel 4.0. Excel 5.0 File was created using Excel 95 (7.0).
{ "language": "en", "url": "https://stackoverflow.com/questions/7592922", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Randomize UIImageViews through code I have 8 images on my View. 4 on left n 4 on right side on the view. i need to match images every time from ones on left to ones on right. I have done this statically by creating 8 image views in the interface builder and connecting it to the outlets created. Now i have to dynamically randomize the image views so tat the match doesn't become obvious. like for the 1st left topmost imageview the match will always be at the bottom most in the right side image view. i tried creating image views in 2 formats UIImageView *image1 = [[UIImageView alloc] initWithFrame:CGRect(111, 135,140,130)]; image1.image = [UIImage imageNamed:@"iMac.png" also UIImageView *image1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"iMac.png"]]; image1.frame = CGRect(111,135,140,130); images are not displayed on the screen at all. Please correct me if i have gone wrong in the code A: Just Replace image1.frame = CGRect(111,135,140,130); with image1.frame = CGRectMake(111,135,140,130);
{ "language": "en", "url": "https://stackoverflow.com/questions/7592925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to view content of variable of type LPVOID I have a C function that takes a parameter of type LPVOID. The values that gets passed in is \0 seperated array of characters. How can I cast the parameter to see the incoming value in visual studio / windbg? A: You can do this in a script. Something like the following would work, which assumes char * strings and that the list ends in double NULLs (like a MULTI_SZ): $$ Print a MULTI_SZ value in the debugger. Note that $$ this script assume a char* string $$ Grab the argument to the script r @$t0 = ${$arg1} $$ while *str != NULL .while (by(@$t0) != 0) { $$ Print the string da @$t0 $$ There's no strlen in this language, so find the NULL .while (by(@$t0) != 0) { r @$t0 = @$t0 + 1 } $$ String points to the NULL. Add one. r @$t0 = @$t0 + 1 } Save to a text file and then run the following in WinDBG: 0:000> $$>a<c:\dumps\multisz.txt 0x012210ec 012210ec "Foo" 012210f0 "Bar" 012210f4 "FooBar" A: Simply casting to char* should work. void f(LPVOID s) { char* ss = (char*) s; // put breakpoint here or watch the variable for(char* r = ss; *r != '\0'; r += (strlen(r)+1)) { // iterate the string printf("%s \n", r); } } A: There is no cast that would allow you to observe that in watch windows. For VS you will have to open up a memory window on the address at the beginning of the null separated block. In WinDbg command db <my_address> dumps raw memory along with ASCII conversion. If block is larger than 128 bytes, then add option l to the command. E.g this will print out first 0x200 bytes for local variable pVoid: db poi pVoid l200 A: again a very late a answer but dpa in windbg can be leveraged to print the list lpvoid:\>dir /b lpvoid.cpp lpvoid:\>type lpvoid.cpp #include <stdio.h> #include <windows.h> int somefunc(LPVOID blah) { printf("%s\n",*(PCHAR *)blah); return 0; } int main (void) { PCHAR foo[] = { "yay" , "boy" , "dog" , "cat" , "monkey" , "weedinducedweird o" }; somefunc( foo); return 0; } lpvoid:\>cl /Zi /nologo lpvoid.cpp lpvoid.cpp lpvoid:\>dir /b *.exe lpvoid.exe lpvoid:\>lpvoid.exe yay set a bp on somefunc or if you do not have symbols on address lik bp 401020 use dpa on the argument (blah here) or use dpa @esp+8 lpvoid:\>cdb -c "bp somefunc \"dpa poi(blah) l?6;q\";g;q" lpvoid.exe | grep -A 6 yay 0013ff60 00417c60 "yay" 0013ff64 00417c64 "boy" 0013ff68 00417c68 "dog" 0013ff6c 00417c6c "cat" 0013ff70 00417c70 "monkey" 0013ff74 00417c78 "weedinducedweirdo" quit: assuming no symbols here lpvoid:\>cdb -c "bp 401020 \"dpa (@esp+8) l?6;q\";g;q" lpvoid.exe | grep -A 6 ya y 0013ff60 00417c60 "yay" 0013ff64 00417c64 "boy" 0013ff68 00417c68 "dog" 0013ff6c 00417c6c "cat" 0013ff70 00417c70 "monkey" 0013ff74 00417c78 "weedinducedweirdo" quit:
{ "language": "en", "url": "https://stackoverflow.com/questions/7592930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: solving T(n) = 2T(n/2) + log n I am trying to solve T(n) = 2T(n/2) + log n substituted n = 2^k T(2^k) = 2T(2^(k-1)) + k T(2^k) = 2^2 T(2^(k-1)) + 2(k-1) + k after k steps T(2^k) = 2^k T(1) + 2^(k-1) + 2 * (2^(k-2)) +....+k So basically I need to sum a term of i*2^i where i = 1 to log n - 1. And I could not find an easy way to sum these terms. Am I doing something wrong ? Is there any other way to solve this recursion ? would master theorem work her ? if yes than how ? Thanks. A: Wolfram|Alpha gives a closed form solution: for a constant c_1 that is fixed by the initial condition. By the way, log(n)/log(2) = lg(n), where lg is the base two logarithm. A: first you should define a recursive export,say T(1) then: since T(2^k) = 2T(2^(k-1)) + k; * we define g(k) = T(2^k)/2^k; then * come into: g(k) = g(k-1) + k/2^k = g(1) + sum(i/2^i); i=2,3,4...k where g(1) = T(1)/2 = c; where you could then unfold the sum expression and define it = y; then unfold the expression of y/2; y-y/2 is a geometric progression, so youcan solve it as I worked out, sum = 3/2 - (k+2)/2^k; so T(n) = 2^k * g(k) = (3/2+c)*n - (2+logn)
{ "language": "en", "url": "https://stackoverflow.com/questions/7592931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Get requested value(URL) when using @RequestMapping annotations When I map multiple values to @RequestMapping(like Multiple Spring @RequestMapping annotations), can I get the requested value(URL)? Like this: @RequestMapping(value={"/center", "/left"}, method=RequestMethod.GET) public String getCenter(Model model) throws Exception { String requestedValue = getRequestedValue(); // I want this. // I want to do something like this with requested value. String result; if (requestedValue.equals("center") result = "center"; else if (requestedValue.equals("left") result = "left"; return result; } A: From Spring 3.1.0, you can use URI Template Patterns with Regular Expressions. @RequestMapping(value={"/{path:[a-z-]+}"}, method=RequestMethod.GET) public String getCenter(@PathVariable String path) throws Exception { // "path" is what I want } A: From Spring 3.1.0, you can use ServletUriComponentsBuilder @RequestMapping(value={"/center", "/left"}, method=RequestMethod.GET) public String getCenter(Model model) throws Exception { UriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentRequest(); String requestedValue = builder.buildAndExpand().getPath(); // I want this. System.out.println(requestedValue); // I want to do something like this with requested value. String result="fail"; if (requestedValue.equals("center")) result = "center"; else if (requestedValue.equals("left")) result = "left"; return result; } A: You can have the Request (HttpServletRequest) itself as an parameter of the handler method. So you can then inspect the request url to get the "value". @RequestMapping(value={"/center", "/left"}, method=RequestMethod.GET) public String getCenter(Model model, HttpServletRequest request) throws Exception { String whatYouCallValue = request.getServletPath(); .... Javadoc: https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletRequest.html#getServletPath-- Btw: if I understand you right, you want to have different urls, not different values. A: Use RequestParam annotation. You can also add a parameter of type HttpServletRequest to your method and then getParameters from that. A: Addition to the best answer @Hugh_Lee: This method will work for all not mapped requests. If you want to use this method just for two (or several) cases only, e.g. "/center" and "/left", you may do following. Rename "center" to "positionCenter", "left" to "positionLeft" (or add another common word). So the code would be like this: @RequestMapping(value={"/{path:position+[A-Za-z-]+}"}, method=RequestMethod.GET) public String getCenter(@PathVariable String path) throws Exception { // "path" is what I want } A: Following regex will make your method to be executed only for the urls /center and /left. And you can get the value with @PathVariable annotation. @GetMapping("/{path:^center$|^left$}") public ResponseEntity<?> whatIsThePath(@PathVariable String path){ // path is either "center" or "left" }
{ "language": "en", "url": "https://stackoverflow.com/questions/7592933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: How to start InputMethodService using Broadcastreceiver or Intent in android? We have an 'InputMethodService' as a stand alone application now what we want to start this InputMethodService for a particular activity in another application. We tried using broadcast receiver but it is giving following error: Intent myService = new Intent(context, Cs_key.class); context.startService(myService); LOGCATE: - 29 11:06:51.624: ERROR/AndroidRuntime(24087): FATAL EXCEPTION: main 09-29> 09 11:06:51.624: ERROR/AndroidRuntime(24087): java.lang.RuntimeException: Unable to start receiver com.ashwin.demo.keyboard.KeyboardReceiver: java.lang.SecurityException: Not allowed to start service Intent { cmp=com.ashwin.demo.keyboard/.Cs_key } without permission android.permission.BIND_INPUT_METHOD 09-29 11:06:51.624: ERROR/AndroidRuntime(24087): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2821) 09-29 11:06:51.624: ERROR/AndroidRuntime(24087): at android.app.ActivityThread.access$3200(ActivityThread.java:125) 09-29 11:06:51.624: ERROR/AndroidRuntime(24087): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2083) 09-29 11:06:51.624: ERROR/AndroidRuntime(24087): at android.os.Handler.dispatchMessage(Handler.java:99) 09-29 11:06:51.624: ERROR/AndroidRuntime(24087): at android.os.Looper.loop(Looper.java:123) 09-29 11:06:51.624: ERROR/AndroidRuntime(24087): at android.app.ActivityThread.main(ActivityThread.java:4627) 09-29 11:06:51.624: ERROR/AndroidRuntime(24087): at java.lang.reflect.Method.invokeNative(Native Method) 09-29 11:06:51.624: ERROR/AndroidRuntime(24087): at java.lang.reflect.Method.invoke(Method.java:521) 09-29 11:06:51.624: ERROR/AndroidRuntime(24087): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 09-29 11:06:51.624: ERROR/AndroidRuntime(24087): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 09-29 11:06:51.624: ERROR/AndroidRuntime(24087): at dalvik.system.NativeStart.main(Native Method) 09-29 11:06:51.624: ERROR/AndroidRuntime(24087): Caused by: java.lang.SecurityException: Not allowed to start service Intent { cmp=com.ashwin.demo.keyboard/.Cs_key } without permission android.permission.BIND_INPUT_METHOD 09-29 11:06:51.624: ERROR/AndroidRuntime(24087): at android.app.ContextImpl.startService(ContextImpl.java:832) 09-29 11:06:51.624: ERROR/AndroidRuntime(24087): at android.content.ContextWrapper.startService(ContextWrapper.java:336) 09-29 11:06:51.624: ERROR/AndroidRuntime(24087): at android.content.ContextWrapper.startService(ContextWrapper.java:336) 09-29 11:06:51.624: ERROR/AndroidRuntime(24087): at com.ashwin.demo.keyboard.KeyboardReceiver.onReceive(KeyboardReceiver.java:18) 09-29 11:06:51.624: ERROR/AndroidRuntime(24087): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2810) menifestfile <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.ashwin.demo.keyboard"> <uses-permission android:name="android.permission.BIND_INPUT_METHOD"/> <application android:label="@string/app_name" > <service android:name="Cs_key" android:exported="true" android:permission="android.permission.BIND_INPUT_METHOD"> <intent-filter> <action android:name="android.view.InputMethod" /> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> <meta-data android:name="android.view.im" android:resource="@xml/method" /> </service> <receiver android:name=".KeyboardReceiver" android:permission="android.permission.BIND_INPUT_METHOD"> <intent-filter> <action android:name="android.intent.action.TIME_SET"></action> </intent-filter> </receiver> </application> </manifest>
{ "language": "en", "url": "https://stackoverflow.com/questions/7592939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why do I get the error "CalendarService class not found" despite having the gdata-calendar-2.0.jar file? I have the gdata-calendar-2.0.jar file, but I get the error "CalendarService class not found". CalendarService myService = new CalendarService("example"); A: Have you included the library in your project? You should place it in the libs\ folder of your project, and then in Eclipse you need to add it to the Java Build path. Right click on the project, goto properties, Java Build Path, then pick the libraries tab and add your Jar.
{ "language": "en", "url": "https://stackoverflow.com/questions/7592942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to save date in nuserdefaults in iPhone? I am saving my date selected from datepicker in nuserdefaults. When I select the date from date picker say 9.52 AM and click on the save button the date selected is getting saved in userdefaults and in SQLite. If I select another date to set another alarm say 9.54 AM and click on the save button, both the dates are getting saved in SQLite but the problem is the earlier 9.52 date is getting overrided by 9.54 in nsuserdefaults and so the notification for the last added date in userdefaults is shown. I want that if I select 9.52AM and then click save and then select 9.54 AM and click save both the time should be saved in userdefaults and the notification for 9.52AM should be shown first. A: I think you add date objects to array and than add to NSUserDefaults if ([[NSUserDefaults standardUserDefaults] valueForKey:@"date"]==nil) { [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"date"]; [[NSUserDefaults standardUserDefaults] synchronize]; NSLog(@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"date"]); } else { NSArray *array = [[NSUserDefaults standardUserDefaults] objectForKey:@"date"]; NSMutableArray *array_dates = [[NSMutableArray alloc] init]; for(int i =0;i<[array count];i++) { [array_dates addObject:[array objectAtIndex:i]]; } [array_dates addObject:YourpresentdateObject]; [[NSUserDefaults standardUserDefaults] setObject:array_dates forKey:@"date"]; [[NSUserDefaults standardUserDefaults] synchronize]; NSLog(@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"date"]); } A: You will have to use different keys when you save the date using NSUserDefaults. Something like- //Use whatever format you are using to save the date [[NSUserDefaults standardUserDefaults] setInteger:952 forKey:@"alarm1"]; [[NSUserDefaults standardUserDefaults] setInteger:954 forKey:@"alarm2"]; You are currently using the same key, which is why it overwrites the value. A: If you don't want to override dates than use different keys for both the alarm.
{ "language": "en", "url": "https://stackoverflow.com/questions/7592944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MEF Child Container Module Not Initializing I have a simple container hierarchy with a parent container which is defined in the Shell MEFBootstrapper using a Directory catalog, and child container(s) which get created off the parent with a distinct catalog. My child containers also use DirectoryCatalog (different path than parent), and I can see that the container has assembly and part information during runtime. However, the Initialize() method for the modules located in the child containers are never called. My goal is to use the child containers as session constructs, allowing the user to create new sessions and toggle between them. But if I cannot get the constituent modules to initialize (and place their views into the regions), I am kind of stuck. I had thought to raise an event from my session manager using event aggregator to allow the modules to listen for the event and self-initialize, but that doesn't seem to work either. i. Why isn't Initialize getting called on modules loaded into a child container ii. How can I "trigger" Initialize from the container instance (outside of the module context?) Can you iterate over the assemblies in the container and trigger Initialize that way??? [from MefBootstrapper in shell project] protected override DependencyObject CreateShell() { ExportProvider ep = this.Container as ExportProvider; this.Container.ComposeExportedValue(ep); [from the service that manages my sessions (containers)] [ImportingConstructor] public SessionService(ExportProvider provider) { [constructor for new sessions (containers)] private void Init(ComposablePartCatalog catalog, ExportProvider provider, string name, int callId, bool useContextProxy) { this._Name = name; this._CallID = callId; this.startTime = DateTime.Now; this.appHost = new CompositionContainer(catalog, new ExportProvider[] { provider }); } ===== Was asked to include my module code whose initialize method is not called (despite being loaded into the container in question...I can even lazy instantiate the module, but calling Initialize() directly causes the injection operation to fail in the method proper. namespace Module1 { //, InitializationMode = InitializationMode.OnDemand [ModuleExport("Module1.ModuleInit", typeof(Module1.ModuleInit))] public class ModuleInit : IModule { private readonly IRegionManager _regionManager; public IServiceLocator _serviceLocator; [ImportingConstructor] public ModuleInit(IRegionManager regionManager, IServiceLocator serviceLocator) { _regionManager = regionManager; _serviceLocator = serviceLocator; } #region IModule Members public void Initialize() { // Use View Discovery to automatically display the MasterView when the TopLeft region is displayed. _regionManager.RegisterViewWithRegion(RegionNames.TopLeftRegion, () => _serviceLocator.GetInstance<MasterView>()); } #endregion } } A: I downloaded your code and had a look at it. I immediately found the problem. The bootstrapper is actually getting exports thanks to a DirectoryCatalog like this: DirectoryCatalog catalog = new DirectoryCatalog("."); this.AggregateCatalog.Catalogs.Add(catalog); This means that you will get the exports from the assemblies in this directory. So you simply need to copy all the the assemblies with the exported types in the directory ".", that is to say the executing directory (Debug/bin). Just copy Module1 and Module2 in the bin directory and everthing will compose gracefully :) Actually I found that the post-build events supposed to copy the modules in the bin directory were not working. Maybe because your renamed something. So if you want it automatically copy the assemblies after building just replace the actual post-build event by this one: copy "$(TargetDir)\$(TargetFileName)" "$(TargetDir)\..\..\..\Shell\bin\$(ConfigurationName)\" A: I already had this problem many times and resolving it is really simple. Remove the constructor from the your module. Prism modules are not activated the same way it does for classical exported types, therefore modules cannot use ImportingConstructor to import the services you need. Instead intitialize them with the ServiceLocator within the Initialize method. This will work: [ModuleExport("Module1.ModuleInit", typeof(Module1.ModuleInit))] public class ModuleInit : IModule { private readonly IRegionManager _regionManager; public void Initialize() { _regionManager = ServiceLocator.Current.GetInstance<IRegionManager>(); _regionManager.RegisterViewWithRegion(RegionNames.TopLeftRegion, () => _serviceLocator.GetInstance<MasterView>()); } } I also think that this behavior is kind of disturbing. A: I had this same problem where my modules Initialize() method was not being called... I realized I had left off the "override" keyword on my Initialize method that was declared virtual in the Module base class that all of my modules inherit from... added "override" and it worked!
{ "language": "en", "url": "https://stackoverflow.com/questions/7592945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Ruby TCP "bot" using EventMachine - implementing a command dispatcher I've crafted a basic TCP client using EventMachine. Code: # run.rb EventMachine::run do EventMachine::connect $config_host, $config_port, Bot end # bot.rb module Bot def post_init # log us in and do any other spinup. sleep(1) send_data $config_login + "\n" EventMachine.add_periodic_timer($config_keepalive_duration) { send_data $config_keepalive_str + "\n" } @valid_command = /^<#{$config_passphrase}:([^>:]+):(#\d+)>(.*)$/ end def receive_data(data) if(ma = @valid_command.match(data)) command, user, args = ma[1,3] args.strip! command.downcase! p "Received: #{command}, #{user}, #{args}" # and.. here we handle the command. end end end This all works quite well. The basic idea is that it should connect, listen for specially formatted commands, and execute the command; in executing the command, there may be any number of "actions" taken that result in various data sent by the client. But, for my next trick, I need to add the ability to actually handle the commands that Bot receives. I'd like to do this using a dynamic library of event listeners, or something similar to that; ie, I have an arbitrary number of plugins that can register to listen for a specific command and get a callback from bot.rb. (Eventually, I'd like to be able to reload these plugins without restarting the bot, too.) I've looked at the ruby_events gem and I think this makes sense but I'm having a little trouble of figuring out the best way to architect things. My questions include... * *I'm a little puzzled where to attach ruby_events listeners to - it just extends Object so it doesn't make it obvious how to implement it. *Bot is a module, so I can't just call Bot.send_data from one of the plugins to send data - how can I interact with the EM connection from one of the plugins? I'm completely open to any architectural revisions or suggestions of other gems that make what I'm trying to do easier, too. A: I'm not sure exactly what you're trying to do, but one common pattern of doing this in EM is to define the command handlers as callbacks. So then the command logic can be pushed up out of the Bot module itself, which just handles the basic socket communication and command parsing. Think of how a web server dispatches to an application - the web server doesn't do the work, it just dispatches. For example something like this EM::run do bot = EM::connect $config_host, $config_port, Bot bot.on_command_1 do |user, *args| # handle command_1 in a block end # or if you want to modularize it, something like this # where Command2Handler = lambda {|user, *args| #... } bot.on_command_2(&Command2Handler) end So then you just need to implement #on_command_1, #on_command_2, etc. in your Bot, which is just a matter of storing the procs to instance vars; then calling them once you parse the passed commands out of your receive_data. A good, very readable example of this in production is TwitterStream.
{ "language": "en", "url": "https://stackoverflow.com/questions/7592947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iPhone selects a Shift key when focusing on a HTML input field. How to turn this off? When I'm focus on an input field on an iPhone, the Shift key is turned on to make sure that the input starts with upper case. Is there a way to turn off this functionality and not have the Shift key when I focus on a field? I understand why this might be good in some cases but in my case this is a user name or email field, most of which don't start with upper case letter. Update: The answer lead me to Safari Web Content Guide page which I'll be referencing more often from now on. A: You can solve it by setting autocapitalize as off <input type="text" name="test1" autocapitalize="off"/> and also Set the autocorrect attribute of your textbox as off to turn off the auto correct feature. <input type="text" name="test1" autocorrect="off"/> A: There is a proprietary attribute for that: autocapitalize (on/off) <input type="email" name="username" autocapitalize="off"> Please note that this is not a W3C standard and will result in invalid code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7592948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: DeviceAdmin policies PASSWORD_QUALITY_NUMERIC not working I am working on DeviceAdmin policies implementation, followed below link for implementation http://developer.android.com/reference/android/app/admin/DevicePolicyManager.html#PASSWORD_QUALITY_NUMERIC , In that if we selected PASSWORD_QUALITY_NUMERIC password Quality from spinner, while setting password, it should ask for at least one digit but not showing any information to input digit, simply accepting ALPHABETIC, not asking for at least 1 number.I hope this is not expected behaviour,may be i am wrong Please let me know Am i misunderstand PASSWORD_QUALITY_NUMERIC?.If i selected PASSWORD_QUALITY_ALPHABETIC, i tried to give only digits, this time asking for at least 1 letter. Thanks in advance :D A: This is working as intended. From my comment on the bug: "The request for password quality is a request for the quality to be at least as good as requested. A password with letters is better than a password with numbers, so it is fine for the user to enter a purely alphabetic password in this case."
{ "language": "en", "url": "https://stackoverflow.com/questions/7592949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set the time limit in online exam I am doing online examination project, in that my requirement is to set one questions in one page,the maximum time limit for the question is 60 seconds, count down. how to set the time limit in jsp .can any one help me. A: This can easily done using javascript.I hope you are not trying to avoid javascript. You can find how to do it here. In case you are looking for something else maybe you would like to check this out A: I don't know much about JSP but you can try this Javascript... <html> <head> <script language="javascript"> var Timer; var TotalSeconds; function CreateTimer(TimerID, Time) { Timer = document.getElementById(TimerID); TotalSeconds = Time; UpdateTimer() window.setTimeout("Tick()", 1000); } function Tick() { TotalSeconds -= 1; if(TotalSeconds ==-1) { alert("Time Up"); // Show alert Plus redirect any other page } else { UpdateTimer() window.setTimeout("Tick()", 1000); } } function UpdateTimer() { Timer.innerHTML = TotalSeconds; } </script> </head> <body> <div id='timer' /> <script type="text/javascript">window.onload = CreateTimer("timer", 60);</script> </body> </html> Save this as an HTML page and check if this is what you need... Hope this helps A: You can set it by using javascript. You will find timer and its related stuff on the internet. You have to just set the time and provide the URL. Then it will forward the page accordingly. I hope this help you to understand the solution. A: While I agree, that the time limit countdown must be done via JavaScript, there also must be a server-side time check, because JavaScript can be easily disabled. Create a time mark when student gets the question and compare it to a time mark when he posts an answer. Hint: You may use System.currentTimeMillis() function to get current server time in milliseconds (1 sec = 1000 ms). A: +1 for @Bravo. But I prefer you buy available online scripts in market as starting point for it. This will save you time, cost and testing efforts. Below is one of the fine scripts that I worked it and it worked like charm. Using this as base I developed a online testing portal of over 1000 users using computer adaptive test. http://codecanyon.net/item/online-skills-assessment/9379895 It is a good starting point for people looking to develop Online Exam System
{ "language": "en", "url": "https://stackoverflow.com/questions/7592950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Moving image for android <--------------------------- image direction --------------------------------------- ------------------------------> Image.PNG <--------------------------------------- []--------------------------------------------------------------{}----------------------[] {} xxxxxxx Image.PNG xxxxxxxx Image.PNG xxxxxxxX {} Image.PNG xxxxx[] {} ------------------------------------------------------------{}----------------------[] -------------------------------------------------------> end ^ beginnin (of the image) I am using an image that runs contineously in one place from one side to another (see picture) like a marquee but instead of text I use an image, it this possible? else how will I incorporate this image to my activity. Help... Thanks.. A: You can use android canvas. Draw bitmap on android canvas and check for condition that if(x>canvas.getHeight()||x<0) {x=0}else{increment or decrement accordingly}
{ "language": "en", "url": "https://stackoverflow.com/questions/7592957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Custom UITableView I have successfully made a iPhone app that uses a UITableView. I would like to start adding some life to the app. How do I customize the table? For example, change the height of the cells, add custom images to the cell, color, and So on.... Any good advice? A: try this tutorial http://www.aboutobjects.com/tutorials.html http://adeem.me/blog/2009/05/24/iphone-sdk-tutorial-part-4-tips-for-uitableview-design-change-design-add-header-footer-add-background-images-tips/ A: UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:CellIdentifier]; if(cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton; cell.selectionStyle = UITableViewCellSelectionStyleNone; UILabel *label; label = [[[UILabel alloc] initWithFrame:CGRectMake(5, 0.5, 240.0, 25.0)] autorelease]; label.tag = WHAT_TAG; label.font = [UIFont boldSystemFontOfSize:14.0]; label.textAlignment = UITextAlignmentLeft; label.textColor = [UIColor blueColor]; label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight; label.backgroundColor = [UIColor clearColor]; [cell.contentView addSubview:label]; } Just try this use a label to overwrite the table cell and by customizing the label you can customize the tabel cell. Hope it helps... A: You may also check Apples own sample code. Especially the tableViewSuite is very nice and demonstrates all the main features in a clear understandable way. It also shows best practice from Apple... http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UITableView_Class/Reference/Reference.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7592960", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Defining (embedding) Javascript I would like to collect all possible ways with which JavaScript can be defined in the web page for execution. So far I know the basic part: * * script tag * external script * element attributes that start with "on" * inside some tag: WIDTH="&{barWidth};%" ALIGN="LEFT" * CSS IE: style="left:expression(document.body.clientWidth/2-oDiv.offsetWidth/2);" * DHTML behavior in IE * in links: href="javascript:alert('Hi')" Thanks! A: In links, <a href="javascript:alert('Hi')"> A: I think the only one left is in the href attribute of anchors links like: <a href="javascript:alert('hello, world!');">Say Hello</a> This is how bookmarklets work. This document describes all ways of embedding: http://docstore.mik.ua/orelly/webprog/jscript/ch12_02.htm A: More fugly things: CSS expressions in IE — allows defining CSS properties as JavaScript expressions, which are evaluated on every possible DOM-event (on every mouse move, scroll step and so on). DHTML Behaviors in IE — can bind .htc-files with JScript to HTML elements through CSS. XBL bindings, Mozilla's invention, can be defined via CSS as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7592961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Multi-Table Inheritance in Django. I'm not sure I understand Im not sure I understand the advantage/purpose of multi-table inheritance… but it may be what I'm looking for. Im dealing with Restaurants. My current logic is that I have a Company model which is likely (but not always) a Restaurant. Sometimes a Company can be a "parent" company, in-which case the Company model has a one-to-many with a Branch model. Both the Company and Branch models would have common fields, such as street address, contact info. If the Company has only one "branch" I can assume it's the Restaurant itself and so I don't need to attach a Branch object to the Company. Does this make sense? I know im repeating myself with with the street address [...] but it seems like an elegant way to store the data if I were to read the db directly. Im not sure if multi-table inheritance is what I need. I just can't wrap my head around it by only looking at https://docs.djangoproject.com/en/dev/topics/db/models/#multi-table-inheritance. edit: also open to taking any suggestions on a better db layout if im doing it wrong. A: Model inheritance is useful in general because you do queries like Company.objects.all() to return all companies (including restaurants) and also Restaurant.objects.all() to return only restaurant companies. Just like 'regular' inheritance, it might be helpful to include common fields in a parent (Company) model on all the children models (Restaurant). For example, all Companies might have an address field, but only Restaurants might have a food_type field. I've documented links to a few snippets that implement a "subclassing queryset" which basically lets you do a query like Company.objects.all() and have it return to you results like [<Company> < Restaurant>, <Company>, <Company>, < Restaurant> ]. Check out the link: http://jazstudios.blogspot.com/2009/10/django-model-inheritance-with.html The downside of this multi-table approach is that it introduces an extra join in your query between the Company parent table and the child Restaurant table. An alternatieve would be to create an abstract model. This creates a separate table for Company and for Restaurant with redundant fileds. With multi-table inheritance, if we wanted to look up the address field on a Restaurant instance, we would be referencing (behind the scenes) the related Company model. With abstract inheritance, there would actually be an address field on the Restaurant table. Also, using the abstract inheritance, I don't think you can do Company.objects.all() and expect that it will return instances that were added as Restaurants, nor can you use the subclassing querysets from the snippits linked above. Hope this helps, Joe
{ "language": "en", "url": "https://stackoverflow.com/questions/7592966", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: want access resultset of first query for second query This is java program for SQL statement. I have two queries. Result of the first query is required for second query. How do I call it in second query? These results are values for xml tags. I need to get first query result for this tag child1.setAttributeNS(xlink,"xlink:type",""); but this is located in 2nd query and if i try to merge those 2 query I get eror resultset closed. while(rs1.next()){ int i=0,j=0 ,locid,supid; int lc[]=new int[100]; int sp[]=new int[100]; lc[i] = rs1.getInt(2); sp[j] = rs1.getInt(1); lcid=lc[i++];*/ for(i=0;i<loc[i];i++){ for(j=0;j<sup[j];j++){ lcid=lc[i]; spid=sp[j]; System.out.print(spid +" "); System.out.println(lcid); String s = (lc[i]==1 ? "simple" : (lc[i]>1 ? "extended" : null)); System.out.println(s); }}} String querystring= " "; rs = stmt.executeQuery(querystring ); while(rs.next()){ Element child1 = doc.createElement("slink"); / Element element = doc.createElement("loc"); A: You need to create a brand new and separate Statement for the second ResultSet. Everytime you get a new ResultSet out of a single Statement, every previously opened one will namely be closed. Replace rs = stmt.executeQuery(querystring ); by Statement stmt2 = connection.createStatement(); rs = stmt2.executeQuery(querystring); Don't forget to add stmt2.close() to the finally block. Unrelated to the concrete problem, have you considered just JOINing the both queries and using Javabeans to represent the model? This way you end up with a single query and more self-documenting code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7592969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I turn the output of asp:SiteMapPath into a list? I'm extremely unfamiliar with both .NET and VB.NET and can't quite figure out how to do this. Say I have code like this: <div class="breadcrumb"> <asp:SiteMapPath ID="SiteMapPath1" runat="server"></asp:SiteMapPath> </div> It outputs a bunch of <span>s with > as separators, something like this: <div class="breadcrumb"> <span id="ctl00_SiteMapPath1"> <a href="#ctl00_SiteMapPath1_SkipLink"> <img alt="Skip Navigation Links" height="0" width="0" src="/Bonfield/WebResource.axd?d=PEpmmIw6qvhaEC3hEwXGjgvJKlzc3DOMu_e-zW-n6pfl6YR-iYjwmlvrYPb689EslKxysA7aoh_x_ALjLs5QXiz7NG41&amp;t=634245478914809245" style="border-width:0px;" /> </a> <span> <a href="/Bonfield/Default.aspx">Home</a> </span> <span> &#187; </span> <span>Showcase</span><a id="ctl00_SiteMapPath1_SkipLink"></a></span> </div> How can I turn that into a list like: <ul> <li>Home</li> <li>Showcase</li> </ul> A: You may have solved this by now but you could use this function to loop through all the items in the rootnode of a sitemap and their descendants and build up a nested list. You can remove If item.HasChildNodes Then sb.Append(ListChildNodes(item)) if you are only interested in the top level Public Function SiteMap() As String Return ListChildNodes(System.Web.SiteMap.RootNode) End Function Private Function ListChildNodes(ByVal node As System.Web.SiteMapNode) As String Dim sb As New System.Text.StringBuilder sb.Append("<ul>") For Each item As SiteMapNode In node.ChildNodes sb.Append(String.Concat("<li><a href=""", item.Url, """>", item.Title, "</a></li>")) If item.HasChildNodes Then sb.Append(ListChildNodes(item)) Next sb.Append("</ul>") Return sb.ToString End Function For those who would like the C# version: public string SiteMap() { return ListChildNodes(System.Web.SiteMap.RootNode); } private string ListChildNodes(System.Web.SiteMapNode node) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append("<ul>"); foreach (SiteMapNode item in node.ChildNodes) { sb.Append(string.Concat("<li><a href=\"", item.Url, "\">", item.Title, "</a></li>")); if (item.HasChildNodes) sb.Append(ListChildNodes(item)); } sb.Append("</ul>"); return sb.ToString(); } Then in your code you can just call to output the string to the page. <h1>Site Map</h1> <%=SiteMap()%> </div> A: While you can't get rid of the span tags, you CAN accomplish what you want. I ran into this same issue because I was using a purchased CSS/HTML site template the client wanted, but the entire thing was based on <ul>'s and <li>'s. Refactoring the CSS would have been too painful, so I found this solution that worked well without any changes to the CSS code. You'll do two things: * *Override the default Node template with one that uses <li> tags *Wrap the whole thing in a <ul> tag Here's an example: <ul style="list-style-type: none;"> <asp:SiteMapPath ID="SiteMapPath1" runat="server" > <NodeTemplate> <li> <a href='<%# Eval("url") %>' title='<%# Eval("description") %>'><%# Eval("title") %></a> </li> </NodeTemplate> </asp:SiteMapPath> </ul> A: The closest I can think of is putting you sitemap into a <asp:menu> control. This will however output as an html table, but visually it will show up a list: <asp:Menu ID="leftNavigation" runat="server" DataSourceID="SiteMapDataSource1" StaticDisplayLevels="1" MaximumDynamicDisplayLevels="1"> </asp:Menu> <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" ShowStartingNode="false" /> Play around with all the styling and formatting options to get your desired output. See here for a detailed walkthrough. Oh, and of course you could also look into using a treeview with a sitemap instead (see the same page). A: While a little involved, this is a solution that actually removes the spans and renders a clean list. First, get rid of those excess spans by modifying the SiteMapPath. I have derived a class NakedSiteMapPath that does this. It still allows the usage of explicit spans in templates, if needed: /// <summary> /// A SiteMapPath, that does not render span elements. /// </summary> /// <remarks> /// To still allow explizit spans inside the node templates, immediately prefix the opening and closing span elements /// with the literal /// prefix "<!--KEEP NEXT SPAN-->" (without the double quotes) /// Example: /// <code> /// <PathSeparatorTemplate><!--KEEP NEXT SPAN--><span class="icon icon--greater"><!--KEEP NEXT SPAN--></span> /// </PathSeparatorTemplate> /// </code> /// Those spans (opening and closing) will be kept, but the prefix removed in the rendered output. /// </remarks> /// <devdoc> /// The MSDN doc has a nice example about a customized breadcrumb with a dropdown menu here: /// https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sitemappath%28v=vs.110%29.aspx /// </devdoc> [AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)] [ToolboxData("<{0}:NakedSiteMapPath runat=server></{0}:NakedSiteMapPath>")] public class NakedSiteMapPath : SiteMapPath { /// <summary> /// Outputs server control content to a provided <see cref="T:System.Web.UI.HtmlTextWriter" /> object and stores /// tracing information about the control if tracing is enabled. /// </summary> /// <param name="writer">The <see cref="T:System.Web.UI.HtmlTextWriter" /> object that receives the control content.</param> public override void RenderControl(HtmlTextWriter writer) { //Render to a local string, then remove all unnecessary spans StringBuilder myStringBuilder = new StringBuilder(); TextWriter myTextWriter = new StringWriter(myStringBuilder); HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter); base.RenderControl(myWriter); string html = myStringBuilder.ToString(); //Remove all spans, except those opening and closing spans wich have been marked with the literal comment "<!--KEEP NEXT SPAN-->" const string matchOpenExceptSkipPrefix = @"(?<!\<\!--KEEP NEXT SPAN--\>)<span>"; const string matchCloseExceptSkipPrefix = @"(?<!\<\!--KEEP NEXT SPAN--\>)</span>"; html = Regex.Replace(html, matchOpenExceptSkipPrefix, String.Empty); html = Regex.Replace(html, matchCloseExceptSkipPrefix, String.Empty); html = html.Replace(@"<!--KEEP NEXT SPAN-->", String.Empty); //finally, write the naked html out. writer.Write(html); } } With that, the spans are gone. To have custom links, like the li elements, you will need to use the templates, as others already have proposed. Here's an example ASPX page part with the NakedSiteMapPath: <ol class="breadcrumb" role="navigation" aria-labelledby="pagebreadcrumbs"> <my:NakedSiteMapPath runat="server" PathDirection="RootToCurrent" RenderCurrentNodeAsLink="False"> <PathSeparatorTemplate><!--KEEP NEXT SPAN--><span class="icon icon--greater"><!--KEEP NEXT SPAN--></span></PathSeparatorTemplate> <CurrentNodeTemplate> <li class="active" aria-selected="true"> <asp:Literal Text='<%# Eval("Title") %>' runat="server" /> </li> </CurrentNodeTemplate> <NodeTemplate> <li> <asp:HyperLink ID="lnkPage" Text='<%# Eval("Title") %>' NavigateUrl='<%# Eval("Url") %>' ToolTip='<%# Eval("Description") %>' runat="server" /> </li> </NodeTemplate> </my:NakedSiteMapPath> </ol> A: The best option for this is to convert the SiteMapPath to use Templates. In the <NodeTemplate> you can place <li> elements with the format you need. In the <PathSeparatorTemplate> you can place the separator. Wrapp the SiteMapPath control with the <ul> tags and that should do it. Example: <ul class="breadcrumb"> <asp:SiteMapPath ID="SiteMapPath1" PathSeparator="" runat="server"> <NodeTemplate> <li> <a href='<%# Eval("url") %>' title='<%# Eval("description") %>'><%# Eval("title") %></a> </li> </NodeTemplate> <PathSeparatorTemplate> <span class="divider">/</span> </PathSeparatorTemplate> </asp:SiteMapPath> </ul> This is excelent option when using Bootstrap and ASP.NET
{ "language": "en", "url": "https://stackoverflow.com/questions/7592970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How do I before_filter a Module::Class::method? I have a custom Module on my Rails project, and I want it to be a before_filter, is there a way I can do? before_filter TokenGenerator::Generator.generate_token("mytoken") A: You can use a block as a before_filter: before_filter do |controller| TokenGenerator::Generator.generate_token("mytoken") end Or you could create a separate class: class TokenFilter def self.filter(controller) TokenGenerator::Generator.generate_token("mytoken") end end #... before_filter TokenFilter Or the usual method: before_filter :token_generator #... private def token_generator TokenGenerator::Generator.generate_token("mytoken") end A: You could create a delegator method to generate_token, then use the delegator method with the before filter... before_filter :generate_token def generate_token TokenGenerator::Generator.generate_token("mytoken") end
{ "language": "en", "url": "https://stackoverflow.com/questions/7592974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Transparency with Python Image Library I'm trying to place a PNG watermark with partial transparency on top of a Facebook profile pic (jpg) using the Python Image Library. The part that should be transparent simply comes off as white. Here's my code: con = urllib2.urlopen('facebook_link_to_profile_pic') im = Image.open(cStringIO.StringIO(con.read())) overlayCon = urllib2.urlopen('link_to_overlay') overlay = Image.open(cStringIO.StringIO(overlayCon.read())) im.paste(overlay, (0, 0)) im.save('name', 'jpeg', quality=100) I've tried a few different ways, but haven't gotten anything to work. Any help is appreciated. A: The 3rd option to paste is a mask (see the docs). It accepts an RGBA image, so the simplest solution is to use your overlay image again: im.paste(overlay, (0, 0), overlay).
{ "language": "en", "url": "https://stackoverflow.com/questions/7592981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to upload hard coded image in php I want to upload a particular image without using upload controls. My problem is that I am not able to pass the hard coded image path to upload.php. upload.php: <?php //i want to assign my image path here can any one tell me how to do that echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Stored in: " . $_FILES["file"]["tmp_name"]; ?> A: When you post a file, it get's uploaded to a temp folder wich is somewhere in your server. It depends on your server configuration. If it is a shared server, the temp folder might be shared with other users as well. What you need to do is use the php function move_uploaded_file($temp_file, $destination) to copy it to the new path. If you don't do this, the temp file will get eventually deleted.
{ "language": "en", "url": "https://stackoverflow.com/questions/7592988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Differences in LINQ vs Method expression Why the Linq expression IL results in omission of the Select projection whereas the corresponding method expression keeps the Select projection ? I suppose these two pieces of code does the same. var a = from c in companies where c.Length >10 select c; // var b = companies.Where(c => c.Length > 10).Select(c => c); //IL - LINQ IEnumerable<string> a = this.companies. Where<string>(CS$<>9__CachedAnonymousMethodDelegate1); //IL IEnumerable<string> b = this.companies.Where<string> (CS$<>9__CachedAnonymousMethodDelegate4).Select<string, string> (CS$<>9__CachedAnonymousMethodDelegate5); Then why the difference in IL? EDITED : then why var a = from c in companies select c; result in SELECT projection even inside IL. it can also be omitted right ? A: The C# compiler is clever and remove useless statement from Linq. Select c is useless so the compiler remove it. When you write Select(c=>c) the compiler can't say that's the instruction is useless because it' a function call and so it doesn't remove it. If you remove it yourself IL become the same. EDIT : Linq is a "descriptive" language : you say what you want and the compiler transforms it well. You don't have any control on that transformation. The compiler try to optimize function call and don't use Select because you don't do projection so it's useless. When you write Select(c => c) you call a function explicitely so the compiler won't remove it. var a = from c in companies select c; var a = c.Select(elt=>elt); Select is usefull in this example. If you remove it a has the type of c; otherwise a is an IEnumerable A: @mexianto is of course correct that this is a compiler optimization. Note that this is explicitly called out in the language specification under "Degenerate Query expressions." Also note that the compiler is smart enough to not perform the optimization when doing so would return the original source object (the user might want to use a degenerate query to make it difficult for the client to mutate the source object, assuming that it is mutable). 7.16.2.3 Degenerate query expressions A query expression of the form from x in e select x is translated into ( e ) . Select ( x => x ) [...] A degenerate query expression is one that trivially selects the elements of the source. A later phase of the translation removes degenerate queries introduced by other translation steps by replacing them with their source. It is important however to ensure that the result of a query expression is never the source object itself, as that would reveal the type and identity of the source to the client of the query. Therefore this step protects degenerate queries written directly in source code by explicitly calling Select on the source. It is then up to the implementers of Select and other query operators to ensure that these methods never return the source object itself. A: In your second example, the call to Select is not redundant. If you would omit the Select call, the query would just return the original collection, whereas Select returns an IEnumerable. In your first example, Where already returns an IEnumerable and the select clause doesn't do any work, so it is omitted. A: Because in the query version there is no actual select projecting 'c' into something else, it is just passing on 'c' as-is. Which results in only a call to 'Where'. In the second variation, you explicitly call 'Select' and thus do a projection. Yes, you are only returning the same objects, but the compiler will not see this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7592996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Convert SID to Username in C# In .net, I can create a NTAccount using domain and username, and get it's SID. But I cannot convert the SID back to NTAccount using translate function. new SecurityIdentifier(stringSid).Translate(typeof(NTAccount)).ToString(); And this two way conversion code has no problem running on Domain Controller. Maybe some configuration wrong? A: SecurityIdentifier.Translate() method works only on domain accounts so perhaps your computer not attached to domain. To resolve local SIDs into account name you can use Win32 API function LookupAccountSid() look here for example. A: Instead of using the SecurityIdentifier, you can use an easier and more general use of DirectoryServices in .NET. In codeproject, there is a nice sample of this: http://www.codeproject.com/KB/cs/getusersid.aspx The code is: private string GetSid(string strLogin) { string str = ""; // Parse the string to check if domain name is present. int idx = strLogin.IndexOf('\\'); if (idx == -1) { idx = strLogin.IndexOf('@'); } string strDomain; string strName; if (idx != -1) { strDomain = strLogin.Substring(0, idx); strName = strLogin.Substring(idx+1); } else { strDomain = Environment.MachineName; strName = strLogin; } DirectoryEntry obDirEntry = null; try { Int64 iBigVal = 5; Byte[] bigArr = BitConverter.GetBytes(iBigVal); obDirEntry = new DirectoryEntry("WinNT://" + strDomain + "/" + strName); System.DirectoryServices.PropertyCollection coll = obDirEntry.Properties; object obVal = coll["objectSid"].Value; if (null != obVal) { str = this.ConvertByteToStringSid((Byte[])obVal); } } catch (Exception ex) { str = ""; Trace.Write(ex.Message); } return str; } private string ConvertByteToStringSid(Byte[] sidBytes) { StringBuilder strSid = new StringBuilder(); strSid.Append("S-"); try { // Add SID revision. strSid.Append(sidBytes[0].ToString()); // Next six bytes are SID authority value. if (sidBytes[6] != 0 || sidBytes[5] != 0) { string strAuth = String.Format ("0x{0:2x}{1:2x}{2:2x}{3:2x}{4:2x}{5:2x}", (Int16)sidBytes[1], (Int16)sidBytes[2], (Int16)sidBytes[3], (Int16)sidBytes[4], (Int16)sidBytes[5], (Int16)sidBytes[6]); strSid.Append("-"); strSid.Append(strAuth); } else { Int64 iVal = (Int32)(sidBytes[1]) + (Int32)(sidBytes[2] << 8) + (Int32)(sidBytes[3] << 16) + (Int32)(sidBytes[4] << 24); strSid.Append("-"); strSid.Append(iVal.ToString()); } // Get sub authority count... int iSubCount = Convert.ToInt32(sidBytes[7]); int idxAuth = 0; for (int i = 0; i < iSubCount; i++) { idxAuth = 8 + i * 4; UInt32 iSubAuth = BitConverter.ToUInt32(sidBytes, idxAuth); strSid.Append("-"); strSid.Append(iSubAuth.ToString()); } } catch (Exception ex) { Trace.Warn(ex.Message); return ""; } return strSid.ToString(); } There is also a conversion from SID bytes to String in the article.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Zoom effect on Android SurfaceView I am developing a Car Race Game. I am able to move, stop, accelerate. But i want that when i press screen then car(bitmap of car image) should look like, it had jumped on its place.I am using surfaceviewto draw view I do not want to use 3D openGL. Any help is much appreciated A: finally i used.On touch event, i create a bigger bitmap and draw it on same place. So it will give zoom effect Bitmap bitmapToZoom; // Create a Bitmap // Now zoom it bitmapToZoom=Bitmap.createScaledBitmap(bitmapToZoom, bitmapToZoom.getWidth()+30,bitmapToZoom.getHeight()+30, null); //now draw it again canvas.drawBitmap(bitmapToZoom, 0,0,null); So now finally, Zooming actor on touch code will be like this. Class Name ZoomonTouc.java import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.RectF; import android.view.MotionEvent; import android.view.SurfaceView; public class ZoomonTouc extends SurfaceView { public Bitmap mMyChracter; public ZoomonTouc(Context context) { super(context); mMyChracter = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher); setWillNotDraw(false); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawBitmap(mMyChracter, mMyChracter.getWidth()/2, mMyChracter.getHeight()/2, null); invalidate(); } @Override public boolean onTouchEvent(MotionEvent event) { RectF rectF = new RectF(mMyChracter.getWidth()/2, mMyChracter.getHeight()/2, mMyChracter.getWidth() + 100, mMyChracter.getHeight() + 100); if (rectF.contains(event.getX(), event.getY())) { mMyChracter = Bitmap.createScaledBitmap(mMyChracter, mMyChracter.getWidth() + 10, mMyChracter.getHeight() + 10, false); } return true; } } To test it properly create one activity and set above surface to activity background setContentView(new ZoomonTouc(this));
{ "language": "en", "url": "https://stackoverflow.com/questions/7593010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: What does '=>' mean? What does => means? Here's a code snap: Dispatcher.BeginInvoke((Action)(() => { trace.Add(response); })); A: it's lambda expression which is the simplified syntax of anonymous delegate. it reads 'goes to'. equivalent to Dispatcher.BeginInvoke((Action)delegate() { trace.Add(response); }); A: => is lambda expression operator which indicate that the code is lambda expression. ( param ) => expr(int x) = > { return x + 1 }; or param => exprx=> x + 1;> What is Lambda expression ? * Lambda expression is replacement of the anonymous method avilable in C#2.0 Lambda expression can do all thing which can be done by anonymous method. * Lambda expression are sort and function consist of single line or block of statement. Read more : Lambda Expressions A: => is an operator called Lambda Operator It is used for creating a lambda expression A: It's the lambda operator => A: It is a lambda operator which reads like "goes to" A: This "=>" means the use of lambda expression syntax in C#. This syntax is available since Visual Studio 2008 in .NET 3.5 (C# 3.0). This is the MSDN official documentation of lambda expression in C#. The code above is the same as anonymous delegate in already available since C# 2.0 Your code: Dispatcher.BeginInvoke((Action)(() => { trace.Add(response); })); is translated into: Dispatcher.BeginInvoke(new delegate () { trace.Add(response); }); Those two codes essentially have the same semantics. A: It's worth noting that a single expression lambda doesn't need the {} around the body, nor does it need a semicolon, so you can simplify your code (slightly) to. Dispatcher.BeginInvoke((Action)(() => trace.Add(response) ));
{ "language": "en", "url": "https://stackoverflow.com/questions/7593012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Blackberry Sound Graphic Analyser In my BB application I need to play/record sound and simultaneously show a Sound Graphic Analyser(as shown in image attached) within the application.I have searched forums but have found nothing significant. I want to show graphics as shown when playing or recording music dependending upon the pitch of the sound. Is this possible? A: As far as I know there is no API in RIM SDK to obtain such data upon playing a media file. But you can analyze the sound file contents by yourself, draw diagram and implement "cursor" (vertical green line on your image) that will be based on the time passed after start of the sound playing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Paypal API - accepting credit cards outside US I am using the Paypal Website Payment Pro API with DirectPay. Is it possible to accept credit cards from outside the US? Do I have a better option? A: Yes this is possible. As A user from outside the US I can perfectly use it. Paypal accepts these creditcards. Usually it is still Mastercard & Visa. A: Yes. I'm from Chile, south-america and I use PayPal all the time. There are more fees an comitions, but what are you gonna do.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AJAX, WCF, and Authentication woes I'm working on a site which is not publicity accessible. That is, it's on the internet, but you must login to access the site, you can't register or anything, it provides a service for a particular industry. We are moving some of our functionality to a mobile site, a real cut down version targeted specifically to day-to-day requirements, that suit the screen size without having to zoom and scroll etc. This is all fine. The site is rather chatty in some area's, and rather than doing ASP.NET Post Backs, we will be doing a lot of AJAX with jQuery, what we would like to do is off-load some of the tasks to other servers and provide WCF services for getting/putting data. My question is, what is the best way of locking down these WCF services so that they cannot be accessed out-side of the initial website, and you have to be logged in to touch them. My thoughts were to have a handler which is what we would touch from the website, and the handler would make a call to the WCF service which would only be exposed to our internal servers. This means the WCF service wouldn't need to be publicly exposed, but the handler would be under our existing domain and existing forms authentication. If that makes sense. Is this a good approach or should I go down the route of using time-stamps and tokens to authenticate the requests to publicly exposed WCF services. Edit: WCF, RESTful Web Services and custom authentication ^this is the closest thing I could find to what I need to do, but wanted to know if there's a better solution for something that isn't, and never will be public facing. A: Using HTTP module, you can add a custom authentication to a IIS-hosted WCF service. You can then implement OAuth 2 Bearer token protection passed via HTTP header or query parameter. It's essentially passing time-limited password along, so you need to do this over https, but it can easily be consumed by jQuery or anything that can use https. The module can set the Principal info on the current thread, which you can access from WCF. For the rest of OAuth 2, see Facebook's Authentication.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do you read multiple lines using readLine in Groovy through SpringSource Eclipse? I am trying to read multiple inputs from the console in Groovy 1.7.10 in Spring Source Suite 2.7.1 (multiple in.readLine()), but the console only seems to allow me to input the first entry, puts in a blank for the second entry and moves to let me enter the third entry, puts in a blank for the fourth entry etc. The following is the code that I'm using. System.in.withReader {reader -> print "w: " def w = reader.readLine() print "x: " def x = reader.readLine() print "y: " def y = reader.readLine() print "z: " def z = reader.readLine() } The output that I am getting is as follows. w: 1 x: y: 2 z: As you can see, it lets me enter the first line, puts a blank for the second, and lets me enter the third input, and puts a blank for the fourth. Does this have to do with me pressing "enter" when entering my input? I would think not since readLine() is supposed to read a line and retrieve the text upto but not including the carriage returns. Any help is appreciated. Thanks, Juan A: Assuming you are on Java 6+, can you try using the Console class to read the lines? def values = System.console().with { [ 'w', 'x', 'y', 'z' ].inject( [:] ) { map, val -> map << [ (val):readLine( "$val: " ) ] } } println "Got w=$values.w x=$values.x y=$values.y z=$values.z" Not sure if Console works inside STS though... A: I'm guessing this is on Windows ... there appears to be a method readLine(boolean ignoreLF), but it is not visible, or otherwise doesn't work. I'm running into this issue as well. For now, just run an extra call to reader.readLine() each time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: file path problem I am working on the dll project which contain 3 module.All these module include comman header file.I have the include folder path like mf/cv/include.now In the property dialog box I have give the path in c/c++>>general>>additional inclde Directories like .,..\include,..\cv\include in all the 3 module. I the 2 module its work perfectely,but in the last module fatal error occur that fatal error C1083: Cannot open include file: 'abc.h': No such file or directory So I am not not able to understand what the problem in the path bacause this path work for all the module expect one. A: (By 3 modules, I assume you mean 3 projects. If you meant 3 C++ files, you shouldn't be encountering this include problem.) Instead of "..\include", try going into the property editor for that field and use the macros like $(SolutionPath)cv\include. If you examine the macros it should tell you exactly where that target will be.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Where can I download JNLP.jar? How can I run the examples in the link? Where can I get the JNLP developer pack? A: C:\Program Files\Java\jdk1.6.0_27\sample\jnlp\servlet In other words, in the sample\jnlp\servlet directory of your JDK. A: You can also find the javax.jnlp.* classes in lib/javaws.jar under your JRE installation. A: The classes shown at the link are primarily of the JNLP API. It is automatically on the run-time class-path of apps launched using Java Web Start. As to how to add them to the compile-time class-path, see the tips in (the build files of) these demos. A: It's really hard to get there. The JAR tar balls, such as jnlp-servlet.jar, are located in lib. A: You find the JNLP developers pack here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to save filename with space on Iphone I am trying to save file in document directory using NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *filename=[NSString stringWithFormat:@"abc 1.pdf",]; NSString *pdfLocation = [documentDirectory stringByAppendingPathComponent:filename]; I am opening this file using a web view NSURL *url = [NSURL URLWithString:pdfLocation]; NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:url]; [self.webView loadRequest:urlRequest]; [urlRequest release]; This fails if the the file name has a space.How should I save file so that space in the filename is maintained. A: UIWebView expects a file URL in this case. Change the line to: NSURL *url = [NSURL fileURLWithPath:pdfLocation];
{ "language": "en", "url": "https://stackoverflow.com/questions/7593030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Doubt in implementing Service I have written a service To delete data from a table when data inputed into it(tblTest) as given below public class service_helper extends Service { private DatabaseAdapter dbAdapter; @Override public IBinder onBind(Intent arg0) { return null; } @Override public void onCreate() { super.onCreate(); Toast.makeText(this,"Service created ...", Toast.LENGTH_LONG).show(); dbAdapter = new DatabaseAdapter(this); dbAdapter.open(); String sqlTransaction = "Select test from tblTest where test > ?"; dbAdapter = new DatabaseAdapter(this); dbAdapter.open(); Cursor cursorTransaction = dbAdapter.ExecuteRawQuery(sqlTransaction, "-1"); for (int i = 0; i < cursorTransaction.getCount(); i++) { String sql = "DELETE FROM tblTest WHERE test=" + i + " "; dbAdapter.ExecuteQuery(sql); } } @Override public void onDestroy() { super.onDestroy(); Toast.makeText(this, "Service destroyed ...", Toast.LENGTH_LONG).show(); } } I have Started the service in the on create of main activity as given below startService(new Intent(this, service_helper.class)); The problem is that I can't do anything in my applicaion because of the service got stated.I cant navigate from my main form.Is it the Right way to implement Service ? Will any one help me A: you need to implement callback to get back to ur activity kindly refer Service call backs to activity in android link Hope it will help u. A: I have written that deletion in a runnable thread and called in the service
{ "language": "en", "url": "https://stackoverflow.com/questions/7593032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to close the default media player? I have started the default media player using the following code: Intent intent = new Intent(); intent.setAction(android.content.Intent.ACTION_VIEW); File file = new File(Environment.getExternalStorageDirectory()+("/background.mp3")); intent.setDataAndType(Uri.fromFile(file), "audio/*"); startActivity(intent); But, when the file is played completely, I want to exit the media player. How do we close the default media player which is started by 'intent'? I have tried using the "startActivityForResult()"... But i don't know where to set the "result" A: you should have to use finish() after statring ur activity... edit use mp.release(); private static final String TAG = "VideoPlayer"; private MediaPlayer mp; private SurfaceView mPreview; private SurfaceHolder holder; private ImageButton mPlay; private ImageButton mPause; private ImageButton mReset; private ImageButton mStop; private String current; /** * Called when the activity is first created. */ public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); // Set up the play/pause/reset/stop buttons mPreview = (SurfaceView) findViewById(R.id.surface); mPath = (EditText) findViewById(R.id.path); mPlay = (ImageButton) findViewById(R.id.play); mPause = (ImageButton) findViewById(R.id.pause); mReset = (ImageButton) findViewById(R.id.reset); mStop = (ImageButton) findViewById(R.id.stop); mPlay.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { playVideo(); } }); mPause.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if (mp != null) { mp.pause(); } } }); mReset.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if (mp != null) { mp.seekTo(0); } } }); mStop.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if (mp != null) { mp.stop(); mp.release(); } } }); A: MediaPlayer Player2; Player2= MediaPlayer.create(this, R.raw.music); Player2.start(); button click event{ Player2.stop(); } In this example i have use Mediaplayer and i have get my resource from raw folder (res/raw.music.mp3). i have use stop(); method of media player to stop it For more here A: Thanks all for your reply, I got the problem... I had used: File file = new File(Environment.getExternalStorageDirectory()+("/background.mp3")); in my code. The Environment.getExternalStorageDirectory() was the problem!!! When i replaced it with "/sdcard/background.mp3" it works properly...
{ "language": "en", "url": "https://stackoverflow.com/questions/7593034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to achieve temeplatization in C as it is possible in C++ I want to write a function in C that will accept any type of data types like int, char, float, or any other data type and do some operation on them. As this is possible in C++, is it possible in C? A: It wouldn't be pretty. Take a look at this page for an example. Lots of macro usage. A: About the only thing you can do in C is macros, the poor cousins of templates. For example: #define max(a, b) ((a) < (b) ? (b) : (a)) Note that this has a huge problem... the macro arguments are evaluated more than once. For example: max(i+=1, i); expands to: ((i+=1) < (i) ? (i+=1) : (i)); And the result of that expression could be all kinds of interesting things on various compilers. So, macros are really a poor substitute for templates. You can make 'functions' that are type agnostic with them. But they come with a number of hurdles and pitfalls that make them practically useless for anything really significant. They are also rather 'hairy' and make your code a lot harder to understand than templates do. The max example I just gave may not seem that hairy (though the doubled evaluation of arguments is certainly a surprising and difficult to deal with thing), but here is an example of declaring something like a templated vector type with macros, and it is obviously hairy. A: You can create and accept a union, or you can take a pointer to the data using the generic void*. C doesn't, however, support templating as in C++. A: Yes, it can be achieved by using macros. See http://www.flipcode.com/archives/Faking_Templates_In_C.shtml A: You can arrange a cheat using ... e.g. with varargs function A: I guess it must be a void pointer void *p; Just typecast and use it. what you have asked is the limitation of c thats why it is introduced in c++ After reading your comment i guess you need an argument to send the datatype of variable func( void *p, int ) \\ second argument must be a datatype use sizeof to find the datatype
{ "language": "en", "url": "https://stackoverflow.com/questions/7593036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jquery-ui sortable: elements dragged behind when using multiple sortables I have a series of nested sortable elements exhibiting some strange behaviour with z-indexes. Basically, on some occasions elements are dragged behing the parent containers. It appears only after parent element has been sorted. It also looks like the behind problem is only on elements further down the list. So I can drag to a "higher" sortable, but dragging to a "lower" sortable and the drag element is suddenly behind. Details: Given sortable list A each element in A in turns contains a connect sortable list B (as in the B lists in each A are all connected) After sorting an element in A, elements dragged from the sortable living in this list are now behind the other A elements. I have played around with the various z-index options via both CSS and Jquery to no avail. A: I know this is an old thread but I had a slightly different solution. After apending it to the body my element lost all of it's CSS properties. My workaround was creating my own custom helper object. Javascript: appendTo: 'body', helper: function(event, $item){ var $helper = $('<ul class = "styled" id="' + event.originalEvent.target.id + '"><li>' + event.originalEvent.target.innerText + '</li></ul>'); return $helper; }, CSS .styled li{ margin-left: 0px; } .styled{ cursor:move; text-align:left; margin-left: 0px; padding: 5px; font-size: 1.2em; width: 390px; border: 1px solid lightGrey; background: #E6E6E6 url(https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/smoothness/images/ui-bg_glass_75_e6e6e6_1x400.png) 50% 50% repeat- font-weight: normal; color: #555; list-style-type: none; } A: I found a workaround for this problem. When defining your sortables, use: appendTo: "body" helper: "clone" This breaks the dragged elements totally out of the nested sortable z-ordering and solves the problem. A: Pretty late response, but for anybody who follows in the future I have found that if you are moving multiple elements, you can override the sort and stop functions to set the elements' z-index. For example: sort: function(event, ui) { $(this).css('z-index', 1000); }, stop: function(event, ui) { $(this).css('z-index', 0); } This would update the current element's z-index property assuring that it is always on top. You could therefore extend this idea to grouped elements. Imagine: sort: function(event, ui) { $('.element-group').each(function(index) { $(this).css('z-index', 1000); }); }, stop: function(event, ui) { $('.element-group').each(function(index) { $(this).css('z-index', 0); }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7593048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Storing sensitive information in a class protected variable considered safe? Please note: I have limited this script to show basic structure. It is not functional. class AuthController { protected $dump = NULL; private function recall() { $dump = $this->query('SELECT * FROM table WHERE access="id" ORDER BY id ASC LIMIT 1'); $this->dump = mysql_fetch_array($dump); } } $user = new AuthController($id); Keep in mind the dump would contain an array of. 1.) id (auto assortment). 2.) unique name. 3.) salt - (random salt hashed with password). 4.) password (hashed). Now, to my questions and purpose. I must dump the users data into a variable to prepare the password for a test to see if the password matches the hashed one stored with the user in the database. An alternative to this would be to use two queries. The first which would retrive the salt associated with the user in the db - (use salt to prepare password to match with hash). And the second query would pass the prepared password along with the users id or unique name to see if a match occurs. I think this is unnecessary use of a database resource; when this information can be stored for later use. One must ask, is this a risk from a security stand point? A: Everything you do on the server side without interaction with the user can be considered safe. It would not do to start worrying about the information the server has in memory because we would go crazy. If someone knows what's in your servers memory, he's gained full access to your system anyways (or his name is John Skeet). Make sure: * *Your error reporting is well configured, meaning no displaying of errors on any live or staging environment *Your interaction with the user is always safe (validation, escaping, quoting, etc.) *You don't store plain text information about the user in cookies
{ "language": "en", "url": "https://stackoverflow.com/questions/7593049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Visual Studio 2008 SP1 assembly reference confusion I am using Visual Studio 2008 SP1 on Windows XP SP3 to develop some .NET Compact Framework 3.5 SP1 solution for Windows CE 6. I want to use SQL Server Compact 3.5 SP2 in my solution, however I notice something very strange with how Visual Studio treats assembly references. I have installed both "SQL Server Compact 3.5 SP2 for Windows Desktop" (SSCERuntime_x86-ENU.msi) and "SQL Server Compact 3.5 SP2 for Windows Mobile" (SSCEDeviceRuntime-ENU.msi). The former puts two versions of the System.Data.SqlServerCE assembly and one version of the System.Data.SqlServerCe.Entity assembly into Windows XP's GAC, while the latter does not seem to put any assembly into Windows XP's GAC. Here already, it looks strange because GAC reports the versions of the two assemblies to be 3.5.1.0 and 3.5.0.0 for System.Data.SqlServerCE, and 3.5.1.0 for System.Data.SqlServerCE.Entity, whereas in the installation directories of SQL Server Compact 3.5 SP2 ("C:\Program Files\Microsoft SQL Server Compact Edition\v3.5" and "C:\Program Files\Microsoft SQL Server Compact Edition\v3.5\Desktop"), Windows Explorer reports both assemblies to be version 3.5.8080.0. Now I know that 3.5.0.0 is supposed to be for vanilla SQL Server Compact 3.5 (i.e. no SP) and 3.5.1.0 is supposed to be for SP1, not SP2. I did not install either vanilla or SP1, so why are they even there? Furthermore, in Visual Studio 2008 SP1, when I try to add the System.Data.SqlServerCE assembly from the "C:\Program Files\Microsoft SQL Server Compact Edition\v3.5\Devices" directory, Visual Studio 2008 SP1 reports a version number of 3.5.1.0 in the Properties panel. This version number seems to be retrieved from the GAC'ed assembly, which shouldn't even be for .NET Compact Framework. The real version number in "C:\Program Files\Microsoft SQL Server Compact Edition\v3.5\Devices" is supposed to be 3.5.8080.0, again. I know that it is possible to use private deployment, as described at http://msdn.microsoft.com/en-us/library/gg213826.aspx, but I'm still bothered by the fact that Visual Studio seems to be referencing the wrong platform-version of the assembly altogether when I don't specifically resort to private deployment. Maybe I just don't understand how Visual Studio works in conjunction with GAC. Can somebody enlighten me? Is there a way to "fix" this without resorting to private deployment? A: The File Version is 3.5.8080.0. The Assembly Version is 3.5.1.0. You can confirm this by opening the properties of the file in Explorer, and switching to the "Version" tab (well, you can for the Desktop files which also report themselves as 3.5.8080.0, but are in fact 3.5.1.0. You can't for the Devices files, but the same explanation applies) Visual Studio doesn't interact with the GAC at all when it comes to referencing assemblies (in fact, see the related question Why does the .NET tab in the 'Add Reference' dialog in Visual Studio not list the contents of the GAC?)
{ "language": "en", "url": "https://stackoverflow.com/questions/7593059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: django generic one-to-one relations, with cascading deletes I'm trying to emulate an inheritance model using django's generic relations. So far, this is what I've come up with: class Base(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey() ... other stuff class Meta: unique_together = ("content_type", "object_id") class SubClass1(models.Model): ... properties for this class _base = generic.GenericRelation(Base) @property def base(self): return self._base.all()[0] From what you can see here (hopefully, at least), the SubClass1 should have a one-to-one relationship with Base, which is why I went through all the work of creating that _base field and then covering it with the base property. Having that generic relation will automagically wire up cascading deletes, which is what I want (and I have a post-delete signal that will wire up the delete from the other direction). There could be any number of subclasses off of Base, and the thing that makes me feel gross is having to copy&paste the _base and its covering property. I've also got a custom object manager that goes with this, and potentially other things that essentially should all behave the same within each subclass of Base. Is there a good way to go about encapsulating this common functionality so I don't have to copy&paste it for each sub class? A: Why not have a BaseSubClass, and then inherit from that. So based on your example: class BaseSubClass(models.Model): _base = generic.GenericRelation(Base) class Meta: abstract = True @property def base(self): return self._base.all()[0] class SubClass1(BaseSubClass): # fields
{ "language": "en", "url": "https://stackoverflow.com/questions/7593064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to overload operator +() for a class The following is a class that contains a operator+ method. I understand the feetInches::operator+(const feetInches &other) const part of it but in the method definition, why is there an extra feetInches and what does it represent here? class feetInches { public: feetInches(int inFeet = 0, int inInches = 0); feetInches operator+(const feetInches &other) const; void print() const; private: int feet; int inches; }; feetInches feetInches::operator+(const feetInches &other) const { feetInches temp; temp.feet = feet + other.feet; temp.inches = inches + other.inches; return temp; } A: Declaring a function const means you can't modify the this object (unless of course you try to modify mutable fields, but that's a different story). Therefore, to return something which is the sum of two feetInches, you must create a new feetInches object and return that. // return type scope resolution parameter type // | | | // | | | feetInches feetInches::operator+(const feetInches &other) const { // return value - you can't modify this (because method is const), so you must create // | a third object feetInches temp; temp.feet = feet + other.feet; temp.inches = inches + other.inches; return temp; } EDIT: As a comparison, consider overloading operator +=: feetInches& feetInches::operator+=(const feetInches &other) { feet = feet + other.feet; inches = inches + other.inches; return *this; } Because in this case the this object is changed, the operator is no longer constant. You also operate on members of this, not a temporary object. On return, you return a reference to this. A: shouldn't it be: feetInches temp = *this; A: The temp feetInches is the object you return from the addition. It's the result. A: The operator + must return a new object. The temp object is this new object. A: Note this is a const function. Its members can't modified. Therefore a temp object is used to hold the result. A: The semantics of an operator+ in C++ are to add 2 objects together and return a brand new result, without modifying either of the objects you are adding. The extra temp instance is that brand new result. A: You are implementing binary operator+, the definition of which takes two elements (untouched) and generates a third element with the result of the addition. The reason for the extra feetInches object in the code is that you don't want to modify the left hand side object. As of understanding the operator, maybe it could be simpler if you considered the implementation: feetInches operator+( feetInches const & other ) const { return feetInches( feet+other.feet, inches+other.inches ); } The original code just splits that single statement into 4 different statements: construction of the object (must be a named variable to be used later), setting the two fields, and returning the object. Alternatively, the recommended approach to operator overloading would be slightly different: class feetInches { int feet, inches; public: feetInches( int feet = 0, int inches = 0 ) : feet(feet), inches(inches) {} // Implement += internally [*] feetInches& operator+=( feetInches const & rhs ) { feet += rhs.feet; inches += rhs.inches; return *this; } }; // Implement + as a free function taking the first element by value: feetInches operator+( feetInches lhs, feetInches const & rhs ) { lhs += rhs; // Reuse += implementation, no need to repeat return lhs; } As of the reasons: * *Flexibility: Allows for operator+ and operator+= with a single implementation *Type symmetry: Allows the compiler to perform implicit conversions in both operands * *1 + obj, obj + 1 will both work with that single implementation, in the member function approach, 1 + obj cannot be resolved by the compiler, as it cannot convert the first element before calling the member function *Efficiency: Taking the first argument by value means that temporaries used as first argument can be optimized away. Note that in the modified version there are still three objects: the original left hand side, the copy as first argument of operator+ that gets returned and the right hand side, we have not removed the object. Also, this implementation for this particular type requires an extra copy in the operator+ return statement (the copy from the argument to the return value cannot be elided), but for more complex types that can be moved, the return statement will move the contents of the object. More on operator overloading here [*] This is a design decision, operator+= can be implemented as a free function, but it can be argued (at least I do) that semantically += is an operation of the first argument.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why use non-member begin and end functions in C++11? Every standard container has a begin and end method for returning iterators for that container. However, C++11 has apparently introduced free functions called std::begin and std::end which call the begin and end member functions. So, instead of writing auto i = v.begin(); auto e = v.end(); you'd write auto i = std::begin(v); auto e = std::end(v); In his talk, Writing Modern C++, Herb Sutter says that you should always use the free functions now when you want the begin or end iterator for a container. However, he does not go into detail as to why you would want to. Looking at the code, it saves you all of one character. So, as far as the standard containers go, the free functions seem to be completely useless. Herb Sutter indicated that there were benefits for non-standard containers, but again, he didn't go into detail. So, the question is what exactly do the free function versions of std::begin and std::end do beyond calling their corresponding member function versions, and why would you want to use them? A: One benefit of std::begin and std::end is that they serve as extension points for implementing standard interface for external classes. If you'd like to use CustomContainer class with range-based for loop or template function which expects .begin() and .end() methods, you'd obviously have to implement those methods. If the class does provide those methods, that's not a problem. When it doesn't, you'd have to modify it*. This is not always feasible, for example when using external library, esspecially commercial and closed source one. In such situations, std::begin and std::end come in handy, since one can provide iterator API without modifying the class itself, but rather overloading free functions. Example: suppose that you'd like to implement count_if function that takes a container instead of a pair of iterators. Such code might look like this: template<typename ContainerType, typename PredicateType> std::size_t count_if(const ContainerType& container, PredicateType&& predicate) { using std::begin; using std::end; return std::count_if(begin(container), end(container), std::forward<PredicateType&&>(predicate)); } Now, for any class you'd like to use with this custom count_if, you only have to add two free functions, instead of modifying those classes. Now, C++ has a mechanisim called Argument Dependent Lookup (ADL), which makes such approach even more flexible. In short, ADL means, that when a compiler resolves an unqualified function (i. e. function without namespace, like begin instead of std::begin), it will also consider functions declared in namespaces of its arguments. For example: namesapce some_lib { // let's assume that CustomContainer stores elements sequentially, // and has data() and size() methods, but not begin() and end() methods: class CustomContainer { ... }; } namespace some_lib { const Element* begin(const CustomContainer& c) { return c.data(); } const Element* end(const CustomContainer& c) { return c.data() + c.size(); } } // somewhere else: CustomContainer c; std::size_t n = count_if(c, somePredicate); In this case, it doesn't matter that qualified names are some_lib::begin and some_lib::end - since CustomContainer is in some_lib:: too, compiler will use those overloads in count_if. That's also the reason for having using std::begin; and using std::end; in count_if. This allows us to use unqualified begin and end, therefore allowing for ADL and allowing compiler to pick std::begin and std::end when no other alternatives are found. We can eat the cookie and have the cookie - i. e. have a way to provide custom implementation of begin/end while the compiler can fall back to standard ones. Some notes: * *For the same reason, there are other similar functions: std::rbegin/rend, std::size and std::data. *As other answers mentions, std:: versions have overloads for naked arrays. That's useful, but is simply a special case of what I've described above. *Using std::begin and friends is particularly good idea when writing template code, because this makes those templates more generic. For non-template you might just as well use methods, when applicable. P. S. I'm aware that this post is nearly 7 years old. I came across it because I wanted to answer a question which was marked as a duplicate and discovered that no answer here mentions ADL. A: Whereas the non-member functions don't provide any benefit for the standard containers, using them enforces a more consistent and flexible style. If you at some time want to extend an existing non-std container class, you'd rather define overloads of the free functions, instead of altering the existing class's definition. So for non-std containers they are very useful and always using the free functions makes your code more flexible in that you can substitute the std container by a non-std container more easily and the underlying container type is more transparent to your code as it supports a much wider variety of container implementations. But of course this always has to be weighted properly and over abstraction is not good either. Although using the free functions is not that much of an over-abstraction, it nevertheless breaks compatibility with C++03 code, which at this young age of C++11 might still be an issue for you. A: Using the begin and end free functions adds one layer of indirection. Usually that is done to allow more flexibility. In this case I can think of a few uses. The most obvious use is for C-arrays (not c pointers). Another is when trying to use a standard algorithm on a non-conforming container (ie the container is missing a .begin() method). Assuming you can't just fix the container, the next best option is to overload the begin function. Herb is suggesting you always use the begin function to promote uniformity and consistency in your code. Instead of having to remember which containers support method begin and which need function begin. As an aside, the next C++ rev should copy D's pseudo-member notation. If a.foo(b,c,d) is not defined it instead tries foo(a,b,c,d). It's just a little syntactic sugar to help us poor humans who prefer subject then verb ordering. A: Consider the case when you have library that contain class: class SpecialArray; it has 2 methods: int SpecialArray::arraySize(); int SpecialArray::valueAt(int); to iterate over it's values you need to inherit from this class and define begin() and end() methods for cases when auto i = v.begin(); auto e = v.end(); But if you always use auto i = begin(v); auto e = end(v); you can do this: template <> SpecialArrayIterator begin(SpecialArray & arr) { return SpecialArrayIterator(&arr, 0); } template <> SpecialArrayIterator end(SpecialArray & arr) { return SpecialArrayIterator(&arr, arr.arraySize()); } where SpecialArrayIterator is something like: class SpecialArrayIterator { SpecialArrayIterator(SpecialArray * p, int i) :index(i), parray(p) { } SpecialArrayIterator operator ++(); SpecialArrayIterator operator --(); SpecialArrayIterator operator ++(int); SpecialArrayIterator operator --(int); int operator *() { return parray->valueAt(index); } bool operator ==(SpecialArray &); // etc private: SpecialArray *parray; int index; // etc }; now i and e can be legally used for iteration and accessing of values of SpecialArray A: To answer your question, the free functions begin() and end() by default do nothing more than call the container's member .begin() and .end() functions. From <iterator>, included automatically when you use any of the standard containers like <vector>, <list>, etc., you get: template< class C > auto begin( C& c ) -> decltype(c.begin()); template< class C > auto begin( const C& c ) -> decltype(c.begin()); The second part of you question is why prefer the free functions if all they do is call the member functions anyway. That really depends on what kind of object v is in your example code. If the type of v is a standard container type, like vector<T> v; then it doesn't matter if you use the free or member functions, they do the same thing. If your object v is more generic, like in the following code: template <class T> void foo(T& v) { auto i = v.begin(); auto e = v.end(); for(; i != e; i++) { /* .. do something with i .. */ } } Then using the member functions breaks your code for T = C arrays, C strings, enums, etc. By using the non-member functions, you advertise a more generic interface that people can easily extend. By using the free function interface: template <class T> void foo(T& v) { auto i = begin(v); auto e = end(v); for(; i != e; i++) { /* .. do something with i .. */ } } The code now works with T = C arrays and C strings. Now writing a small amount of adapter code: enum class color { RED, GREEN, BLUE }; static color colors[] = { color::RED, color::GREEN, color::BLUE }; color* begin(const color& c) { return begin(colors); } color* end(const color& c) { return end(colors); } We can get your code to be compatible with iterable enums too. I think Herb's main point is that using the free functions is just as easy as using the member functions, and it gives your code backward compatibility with C sequence types and forward compatibility with non-stl sequence types (and future-stl types!), with low cost to other developers. A: How do you call .begin() and .end() on a C-array ? Free-functions allow for more generic programming because they can be added afterwards, on a data-structure you cannot alter. A: Ultimately the benefit is in code that is generalized such that it's container agnostic. It can operate on a std::vector, an array, or a range without changes to the code itself. Additionally, containers, even non-owned containers can be retrofitted such that they can also be used agnostically by code using non-member range based accessors. See here for more detail.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "219" }
Q: pyvnc2swf not working? outputs video of duration 0sec i need to convert video from swf to flv. im using pyvnc2swf : edit.py but it's not working. shows no errors but outputs a file with one blank frame. here is the command: /usr/share/pyvnc2swf/edit.py -o outlet.flv -s 1 1.swf output: Using pygame 1.9.1release there is no soundcard Input movie: version=7, size=718x351, framerate=24fps, frames=1, duration=0.0s. Output movie size: 718x351 Scanning source swf file: 1.swf... .1 frames written (duration=0.0s) A: i got the answer on my own : pyvnc2swf is working perfectly but it won't work with the swf's which are interative(require clicking etc). u can only convert simple swf's to flv.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593087", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Merging two columns of fields in MySQL Possible Duplicate: Merge date from one datetime and time from another datetime How can I physically merge two MySQL column/fields into one column/field without losing any data on it Specifically I will be combining a DATE and TIME column/field thanks A: By "merge", do you mean "add"? It sounds like you've got the date and time in separate fields, and so putting them together is the same thing as adding them. If that's the case, you can use the MySQL's ADDTIME() function: mysql> SELECT ADDTIME(aDate, aTime) FROM aTable; If you mean to concatenate them, then MySQL has a CONCAT() function... But it doesn't seem suited for your purpose. --edited-- If it's another column you're after, it's a two step process: -- Add the column mysql> ALTER TABLE aTable ADD COLUMN aDateTime DateTime DEFAULT NULL; -- Insert the data mysql> UPDATE aTable SET aDateTime = ADDTIME(aDate, aTime); But after this point, you'll have to maintain it in all three columns. That is, aDateTime won't automatically update when you add/change aDate or aTime. A: Add your timestamp field, initialize it with the timestamp function, and then once you feel safe, drop the old columns. Something like this: alter table your_table add timestamp_column timestamp; update your_table set timestamp_column = timestamp(date_column, time_column); -- Pause and make sure everything is okay. -- Take your time, the database will wait. alter table your_table drop column date_column; alter table your_table drop column time_column; alter table your_table modify timestamp_column timestamp not null; A: i dont wanna if you want to create a new field but just in case you wanna do it alter table t add yournewfield datetime not null; UPDATE table t SET younerwfield = addtime(t.date,t.time);
{ "language": "en", "url": "https://stackoverflow.com/questions/7593097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: does not find rjs file I am using rails 2.3.8 and I'll load a modal dialog box using a partial called _show_venue.html.erb. Inside this partial I add link_to_remote to edit each venue. _show_venue.html.erb :: <table> <tr> <th>Country</th> <th>Place</th> <th>Color</th> </tr> <% @venues.each do |venue| %> <tr> <td><%=h venue.country_id %></td> <td><%=h venue.place %></td> <td><%=h venue.color %></td> <td><%= link_to_remote 'Edit', :url => {:controller => 'venues', :action => 'edit', :id=>venue.id } %></td> </tr> <% end %> </table> And this is my controller code :: def edit @venue = Venue.find(params[:id]) end edit.js.rjs :: page.replace_html 'edit_venue', :partial => 'edit_form' page<< "$j ('#event_actions').dialog({ title: 'Edit venue modal: true, width: 500, close: function(event, ui) { $j ('#event_actions').dialog('destroy') } });" But when I run this, it could not find edit.js.rjs file. Why did this happen? Anyone can explain it? A: Rename your file edit.js.rjs to edit.rjs Edited I think you have to do it other way as you want dynamic object @venue, Try following def edit @venue = Venue.find(params[:id]) render :update do |page| page.replace_html 'edit_venue', :partial => 'edit_form', :object => @venue page<< "$j ('#event_actions').dialog({ title: 'Edit venue modal: true, width: 500, close: function(event, ui) { $j ('#event_actions').dialog('destroy') } });" end end your link should be as follows [you have to write :method ] <%= link_to_remote 'Edit', :url => {:controller => 'venues', :action => 'edit', :id=>venue.id }, :method=>'put' %> you can also try 'post' if above doesn't work A: You should do the following changes to you controller method: respond_to do |format| format.js end so that it will find the edit.js.rjs and render it. Edit: The 404 HTTP status which was the main problem was because of a missing route. A route to match venues/:id/edit should solve the problem. A: rename edit.js.rjs to edit.js.erb Add the following to the end of your edit method: respond_to do |format| format.js format.html end restart your server
{ "language": "en", "url": "https://stackoverflow.com/questions/7593099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is (mono) asp.net slower than php? I have a simple hello world written in asp.net, php and regular html. They are being served by nginx using fastcgi for php5 and xsp (mono 2.6.7, fastcgi-mono-server2.exe 2.6.5.0). I am using a simple .NET script to make async web request. What i found was in the span of 1000ms * *php: 250-400 *asp: 120-140 *html: 600-900 *8k png: 250-300 With a simple hello world app php is consistently 2-3x faster. Why is this? i always thought asp.net would be faster (and php startup would be slow). But it appears per request asp is significantly slower. Now i understand i am not actually comparing execution speed since its hello word and not complex code. What is the difference between the two backends to make this significant difference? Here is the code i use to test the request. A: Because fastcgi is not well implemented. I am using mono xsp web server, its recommended to use as dev server only but it works pretty good in production Here is Article about performance tests Its in Russian but scroll down there is a table where you can take some information
{ "language": "en", "url": "https://stackoverflow.com/questions/7593100", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Android - skia decode error for images I have been trying to decode an image as follows: String dat = jobJect.getString("dat"); client = new DefaultHttpClient(); String url2 = url1 + dat; request = new HttpGet(url2); request.setHeader("Cookie", "hcsid=" + GlobalConfig.hcSid); response = client.execute(request); BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity( response.getEntity()); InputStream im = bufHttpEntity.getContent(); OutputStream out = null; final ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE); CameraActivity.copy(im, out); out.flush(); final byte[] data = dataStream.toByteArray(); mBitMap = BitmapFactory.decodeByteArray(data, 0, data.length); Although I get an image, it doesn't get decoded and throws this error: 09-29 11:27:38.675: DEBUG/skia(14907): --- decoder->decode returned false I'm following this code which handles a skia error: http://code.google.com/p/shelves/source/browse/trunk/Shelves/src/org/curiouscreature/android/shelves/util/ImageUtilities.java But it doesn't solve the issue. Can anyone please help? A: Check this bug report: http://code.google.com/p/android/issues/detail?id=9064
{ "language": "en", "url": "https://stackoverflow.com/questions/7593104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Clipping of sound files + Blackberry Is it somehow possible to clip a sound file i between ? In my application I have to provide the user the ability to create a ringtone out of a sound file and the user will enter the start and end time of the region within the file he wants to clip .Is this possible? A: Parse mp3 (or other sound) binary format and do whatever you want with this file. Information on mp3 and other file formats can be found via google.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Developing a new dexterity widget and field I need to develop a dexterity content type with a particular field/widget. This widget is like a multiselection widget but I need to give the possibility to upload a file for every choosen option. Something like this: [] option 1 Upload a file: [ ] [ Browse ] [X] option 2 Upload a file: [ ] [ Browse ] [] option 3 Upload a file: [ ] [ Browse ] Any idea/pointer on how to implement this on dexterity? I think it has to do with z3c.form mostly. Any example of similar widget/field is welcome, as any pointer to existing packages :) I would also manage the vocabulary TTW, if possible, so users with a particular role can update the list. A: Though I haven't used this myself I suspect you could look at collective.z3cform.datagridfield and the related demo code on github for pointers on how to use subforms and widget factories.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sql Query statement under microsoft access i have 2 tables: Employee: ID SalaryPerDay overTimeHoursPrice ..... ..... Schedule: ID EmployeeID Date Attending (boolean) loan discount overTimeHours with many to one relationship i want a query to return [employee name] and [sum(loan)] and [sum(discount)] and [sum(overTimeHours)] and [count(attending)] where attending = true and [count(attending) * SalaryPerDay] and [sum(overTimeHours)* overTimeHoursPrice ] and [(count(attending) * SalaryPerDay) + (sum(overTimeHours)* overTimeHoursPrice) - (sum(discount)) - (sum(loan))] 1- where Date >= [date1] And Date <= [date2] 2- where Date >= [date1] And Date <= [date2] And EmployeeName = [name] (date1 and date2 and name are parameters) A: Something like this should do the trick.... SELECT emp.EmployeeName, sum_loan, sum_discount, sum_overTimeHours, count_attending, (count_attending*SalaryPerDay) as totalDayPay, (sum_overTimeHours*overTimeHoursPrice) as totalOverTimePay, ((count_attending*SalaryPerDay) + (sum_overTimeHours*overTimeHoursPrice) - sum_discount - sum_loan) as grandTotal FROM Employee emp INNER JOIN (SELECT EmployeeID, sum(loan) as sum_loan, sum(discount) as sum_discount, sum(overTimeHours) as sum_overTimeHours, sum(iif(Attending,1,0)) as count_attending FROM Schedule WHERE Date >= {date1} and Date <= {date2} GROUP BY EmployeeID ) sch ON emp.ID = sch.EmployeeID WHERE emp.EmployeeName = {name} Note the two WHERE clauses. You can adjust these as needed to achieve your two different parameterized restrictions. Edit #1: Due to some uncertainty about the actual numeric value of the "boolean" stored in the Schedule.Attending field, I've adjusted the query above to account for the boolean value explicitly. To accomplish this, I've made use of the MSAccess-specific expression function, IIF(). This is a much more robust solution than just assuming that the field will contain either a 1 or a 0. Edit #2: I should also note that the syntax varies slightly depending on where you're using it. The above is the "standard sql" syntax for the derived table (that's the subquery that's inside parenthesis following the INNER JOIN keywords). If you're running this query through an ODBC connection, then the syntax above is valid. However, If you're trying to create a Query within Access itself, you'll need to use square brackets with a trailing period [ ]. instead of parenthesis ( ) around the subquery. So instead of: SELECT ... FROM Employee emp INNER JOIN (SELECT ... ) sch ON ... use this: SELECT ... FROM Employee emp INNER JOIN [SELECT ... ]. sch ON ... A: I think you want: SELECT e.EmployeeName, Sum(s.loan) AS SumOfloan, Sum(s.discount) AS SumOfdiscount, Sum(s.overTimeHours) AS SumOfoverTimeHours, Sum(Abs([Attending])) AS Attnd, Sum([SalaryPerDay]*Abs([Attending])) AS SalyAttnd, Sum([overTimeHoursPrice]*[overtimehours]) AS OTCost, Sum(([SalaryPerDay]*Abs([Attending])+[overTimeHoursPrice]*[overtimehours])-([loan]-[discount])) AS Due FROM Employee e INNER JOIN Schedule s ON e.ID = s.EmployeeID WHERE s.Date Between [date1] And [Date2] AND EmployeeName = [Name] GROUP BY e.ID, e.EmployeeName Note that a Boolean is either 0 or -1, so [SalaryPerDay]*Abs([Attending] = Salary * 1, if attending or 0, if not attending.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Translate Code Snippet from C# to VB I need to translate line 4 in the code snippet below into VB. For some reason I cannot get this done tonight. I am either too tired or having a brain drain... Can you help? var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description); provider.ClientIdentifier = ClientCredentials.ClientID; provider.ClientSecret = ClientCredentials.ClientSecret; var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication); Translation tools have gotten me this far, but it's not right. Dim provider As NativeApplicationClient = New NativeApplicationClient(GoogleAuthenticationServer.Description) provider.ClientIdentifier = ClientCredentials.ClientID provider.ClientSecret = ClientCredentials.ClientSecret Dim auth As OAuth2Authenticator(Of NativeApplicationClient) = New OAuth2Authenticator(Of NativeApplicationClient)(provider, GetAuthorization) The GetAuthorization method has the following signature. Private Function GetAuthorization(ByVal arg As NativeApplicationClient) As IAuthorizationState A: You need AddressOf Dim auth As OAuth2Authenticator(Of NativeApplicationClient) = New OAuth2Authenticator(Of NativeApplicationClient)(provider, AddressOf GetAuthorization) A: Refer to this Website for the Translation of any code from C# to VB and the code after conversion is Dim provider = New NativeApplicationClient(GoogleAuthenticationServer.Description) provider.ClientIdentifier = ClientCredentials.ClientID provider.ClientSecret = ClientCredentials.ClientSecret Dim auth = New OAuth2Authenticator(Of NativeApplicationClient)(provider, GetAuthentication) A: You are trying to use OAuth2Authenticator to GetAuthorization and the two are different, maybe that's your problem. A: AddressOf never calls the function, you need to use Dim getAuth As Func(Of NativeApplicationClient, IAuthorizationState) = AddressOf GetAuthorization Dim auth As New OAuth2Authenticator(Of NativeApplicationClient)(provider, getAuth)
{ "language": "en", "url": "https://stackoverflow.com/questions/7593125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to modify a java timer interval after scheduling it for a fixed rate in android? I have a service which has one Timer. I call timer.scheduleAtFixedRate() in the onStart() callback method. But I have to alter the timer interval depending on the value of a variable. I found no function for timer to alter its interval. So I thought to cancel the timer and re-schedule when that condition is met. But I am checking the condition with in the timerTask itself. So when I tried to cancel the timer in the TimerTask, it throws IllegalStateException. Can anybody give me some solution? A: A timer can only be scheduled once. If IllegalStateException isn't happening when you call cancel(), but when you try to reschedule the timer, just reinstantiate the timer and then schedule it. Otherwise, I'm not sure. A: Netiher Timer.cancel() nor TimerTask.cancel() throws IllegalStateException. That is thrown when you try to schedule a task on a cancelled Timer. Solution: don't cancel the Timer; cancel the TimerTask.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Php, session id control doesnt work? here is the code drives me crazy:) <?php $deger=0; if (session_id() == '') { session_start(); $deger=1; } else{ $deger=0; } $row = mysql_fetch_row($result); $counter =$row[2]; if($deger==1){ $counter--; } echo $counter; ?> This basic code drives me crazy. the deger==1 condition always returns true and keeps decrementing the counter. What I would like to do is check the session if the session is new decrement it only once. after that dont decrement the value. Am I missing something here? I am new to php maybe I am missing something. I look forward to your answers thanks. A: There is always a user session, but not always a php session. So if you did not do a session_start() yet, you can check that with something like this: if (isset($_SESSION]['loggedin'])){ $deger = 0; } else { $deger = 1; session_start(); $_SESSION['loggedin'] = true; } Wherever you start the session, also fill the $_SESSION var. A: i think you have to call session_start(); before any chacks like if (session_id() == '') cause theres really nothing in session_id when session has not been started. this code i one used is working for me (may be not perfect): session_start(); $user = (isset($_SESSION['user']) && $_SESSION['user'] != '' ? $_SESSION['user'] : null); if ($user == null) { //it's a not logged in user //checking users credentials and if it's ok $_SESSION['user'] = $uid; //or whatever you want to use to identify a user } else { //it's logged in user }
{ "language": "en", "url": "https://stackoverflow.com/questions/7593135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Regular Expressions to find C# class and method names I'm writing an impact analysis tool that will parse a bunch of selected file types and find the class and method calls inside the file (in this case a .cs file). I have managed to write a regular expression that will find if a line of code is a method call. Regex re = new Regex( @"\b(public|private|internal|protected)\s*" + "(static|virtual|abstract)?\s*[a-zA-Z]*\s[a-zA-Z]+\s*" + "\((([a-zA-Z\[\]\<\>]*\s*[a-zA-Z]*\s*)[,]?\s*)+\)"); However; I can't figure out how to get the Method name out of the regular expression. It recognises a line as a Match but how do i pull out the actual method name. Any help on this would be amazing. Furthermore; I'm not sure if this is how it's actually done but is there any other (up to date) c# file parsers that will be able to provide me a list of method names and class names from the file? A: You can put the part that represents a method into a group like this: (?<method>[a-zA-Z]+) Then you can access it like this: Match match = regex.Match(line); if (match.Success) { string method = match.Groups["method"].Value; } However, your regex at the moment has various problems in terms of matching method names: * *It doesn't handle generics (generic methods, parameters or return values) *It doesn't handle identifiers with digits or _ in *It doesn't handle methods with the default access modifier *It will match string literals containing something looking like a method declaration To get method names out of a C# file, you really need something which understands C#. Note that the Roslyn project may well make this sort of thing a lot easier - we'll see when the first preview comes out, very soon now... A: Your pattern can be modified to capture method name by adding a group. Here's the complete code: string method_pattern = @"\b(public|private|internal|protected)\s*" + @"\b(static|virtual|abstract)?\s*[a-zA-Z]*(?<method>\s[a-zA-Z]+\s*)" + @"\((([a-zA-Z\[\]\<\>]*\s*[a-zA-Z]*\s*)[,]?\s*)+\)"; while ((line = file.ReadLine()) != null) { Regex expression = new Regex(method_pattern); Match match = expression.Match(line); if (match.Success) { string result = match.Groups["method"].Value; MessageBox.Show(result); } } A: Here's how you can match method names of a C# class. Regex Expression: \b(public|private|internal|protected|void)\s*s*\b(async)?\s*\b(static|virtual|abstract|void)?\s*\b(async)?\b(Task)?\s*[a-zA-Z]*(?<method>\s[A-Za-z_][A-Za-z_0-9]*\s*)\((([a-zA-Z\[\]\<\>]*\s*[A-Za-z_][A-Za-z_0-9]*\s*)[,]?\s*)+\) Usage: private void FindMethods(string input) { try { const string methodPattern = @"\b(public|private|internal|protected|void)\s*s*\b(async)?\s*\b(static|virtual|abstract|void)?\s*\b(async)?\b(Task)?\s*[a-zA-Z]*(?<method>\s[A-Za-z_][A-Za-z_0-9]*\s*)\((([a-zA-Z\[\]\<\>]*\s*[A-Za-z_][A-Za-z_0-9]*\s*)[,]?\s*)+\)"; foreach (Match m in Regex.Matches(input, methodPattern, RegexOptions.IgnorePatternWhitespace)) { Console.WriteLine(m.Value); Console.WriteLine(m.Groups["method"].Value); } } catch (ArgumentException ex) { // Syntax error in the regular expression } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7593136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: LINQ select after grouping I'm trying to return a result set from a grouped query and I can't get the select right. In LinqPad the cursor jumps to "ItemID" in Grouped.Key.ItemID with the error: 'int' does not contain a definition for 'ItemID' and no extension method 'ItemID' accepting a first argument of type 'int' could be found Here's the query: from B in Bids join I in Items on B.ItemID equals I.ItemID group new {B, I} by I.ItemID into Grouped select new { ItemID = Grouped.Key.ItemID, ItemName = Grouped.Key.ItemName, Bids = Grouped.Key.B } I would like the return set to have records comprised of the ItemID, ItemName and all of the associated Bid records. Thanks very much, BK A: That says exactly what is written. Groupped.Key will contain I.ItemID, but not the whole I. So you can't write Groupped.Key.ItemID. Consider: from B in new [] { new { ItemID = 1, BidValue = 30 } } join I in new [] { new { ItemID = 1, ItemName = "x" } } on B.ItemID equals I.ItemID group new { B, I } by I into Groupped select new { ItemID = Groupped.Key.ItemID, ItemName = Groupped.Key.ItemName, Bids = (from g in Groupped select g.B).ToList() } A: Well, assuming you have foreign keys setup in the database from bid -> item there is no need for all this joining an grouping. Your items will already have a collection of bids in them. So you can do things like: var x = db.Items.Single(i=>ItemId == 1); // get one item foreach (bid b in x.Bids) // iterate through all the bids {} If you really want to have them in an anonymous type, this will do: from i in db.items select new { i.ItemID, i.ItemName, i.Bids } That is the beauty of Linq2Sql. Try to let go of writing SQL in Linq but instead use the more object oriented approach. A: The Grouped.Key refers to the field(s) that you specied in the grouped by x clause. As a result in your query, the Key = I.ItemID. In your example, instead of thinking from the SQL perspective where you have to flatten out heirarchies, embrace the OO nature of LINQ and object graphs. Adapting your example a bit and setting LINQPad to use C# Statements, I think you will end up with more of what you are looking for. Note: The Dump() extension method is specific to LINQPad to output the results and shows the resulting heirarchy. var bids = new [] { new { ItemID = 1, BidValue = 30 } , new {ItemID=1, BidValue=45}}; var items = new [] { new { ItemID = 1, ItemName = "x" }, new {ItemID = 2, ItemName="y"} }; var query = from i in items select new { i.ItemID, i.ItemName, Bids = from b in bids where b.ItemID == i.ItemID select b }; query.Dump(); That being said, your categories indicate LINQ to SQL. If your model is in LINQ to SQL or EF, you may be able to do this even easier by using the mapped associations: var query = from i in dc.Items select new { i.ItemID, i.ItemName, i.Bids }; query.Dump(); A: In this groupby, ItemID is the Key. ItemID does not have a B property. group new {B, I} by I.ItemID into Grouped Here's an improved version of your query which accesses the group properly. from b in Bids join i in Items on b.ItemID equals i.ItemID group b by i into groupedBids select new { Item = i, Bids = groupedBids }; Here's a version that uses GroupJoin to do the same thing. from i in Items join b in Bids on i.ItemID equals b.ItemID into groupedBids select new { Item = i, Bids = groupedBids }; Here's a version that does the join in the database and the group locally. You might do something like this since LinqToSql must re-query by the key of a group to get each group's elements (known as the n+1 problem with groupby). from x in ( from i in Items join b in Bids on i.ItemID equals b.ItemID select new {Item = i, Bid = b} ).ToList() group x.b by x.i into groupedBids select new { Item = groupedBids.Key, Bids = groupedBids };
{ "language": "en", "url": "https://stackoverflow.com/questions/7593141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Playback MP3 data buffer using AudioQueue Service : Prime failed (-50) These days I was struggling for finding the way to playback network audio stream (in MP3 packet format) using AudioQueue Service on iPhone. To achieve this target successively, I firstly got the common local MP3 file to playback using AudioQueue, and it does work. And then, I replaced the AudioFileReadPackets with stdio function fread, and everytime I fread the same amount of mp3 packets like AudioFileReadPackets ever did, to simulate the audio stream coming from network. However, this time, the error came: 2011-09-28 14:21:28.245 SunFlower[1554:207] Prime: Exiting because mConverterError is -50 (0x11940 req, 0x0 primed) 2011-09-28 14:21:28.253 SunFlower[1554:207] Prime failed (-50); will stop (72000/0 frames) Does someone know what's the cause for this "Prime failed (-50)" error? Help zzzzzzz *********************************************************************************************************************************************************************. To explain what I did on the replacing work, I’d like to show you the main changed part of the code, there are two part: "before replacing" and "after replacing" * *Before replacing (playbak local MP3 file): 1) The audio queue runloop callback static void HandleOutputBuffer(void *aqData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer) { AQPlayerState *pAqData = (AQPlayerState *) aqData; UInt32 numBytesReadFromFile; UInt32 numPackets = pAqData->mNumPacketsToRead; UInt32 i = 0; printf("HandleOutputBuffer::Start!\n"); //If the audio queue is stopped, returns immediately if(pAqData->mIsRunning == 0) { printf("HandleOutputBuffer::Error Return!\n"); return; } //Read a packet of audio data from file stream AudioFileReadPackets(pAqData->mAudioFile, false, &numBytesReadFromFile, pAqData->mPacketDescs, pAqData->mCurrentPacket, &numPackets, inBuffer->mAudioData); //Enqueue the audio packet into the audio queue if(numPackets > 0) { printf("HandleOutputBuffer::Step 1!\n"); inBuffer->mAudioDataByteSize = numBytesReadFromFile; AudioQueueEnqueueBuffer(pAqData->mQueue, inBuffer, (pAqData->mPacketDescs ? numPackets : 0), pAqData->mPacketDescs); pAqData->mCurrentPacket += numPackets; } else { printf("HandleOutputBuffer::Step 2!\n"); AudioQueueStop(pAqData->mQueue, false); pAqData->mIsRunning = false; } } 2) Open audio file OSStatus AqOpenAudioFile(char *filePath, AQPlayerState *pAqData) { CFURLRef audioFileURL; OSStatus result; UInt32 maxPacketSize; UInt32 propertySize = sizeof (maxPacketSize); audioFileURL = CFURLCreateFromFileSystemRepresentation(NULL, (const UInt8 *) filePath, strlen (filePath), false); result = AudioFileOpenURL(audioFileURL, kAudioFileReadPermission, 0, &(pAqData->mAudioFile)); CFRelease(audioFileURL); AudioFileGetProperty(pAqData->mAudioFile, kAudioFilePropertyPacketSizeUpperBound, &propertySize, &maxPacketSize); DeriveBufferSize(pAqData->mDataFormat, maxPacketSize, 0.5, &(pAqData->bufferByteSize), &(pAqData->mNumPacketsToRead)); return result; } 3) Create audio queue OSStatus AqCreateAudioQueue(AQPlayerState *pAqData) { UInt32 dataFormatSize = sizeof (AudioStreamBasicDescription); OSStatus result; bool isFormatVBR; UInt32 cookieSize = sizeof (UInt32); bool couldNotGetProperty; AudioFileGetProperty(pAqData->mAudioFile, kAudioFilePropertyDataFormat, &dataFormatSize, &(pAqData->mDataFormat)); result = AudioQueueNewOutput(&(pAqData->mDataFormat), HandleOutputBuffer, pAqData, CFRunLoopGetCurrent(), kCFRunLoopCommonModes, 0, &(pAqData->mQueue)); //Configurate the VBR property if any isFormatVBR = (pAqData->mDataFormat.mBytesPerPacket == 0 || pAqData->mDataFormat.mFramesPerPacket == 0); if(isFormatVBR) { pAqData->mPacketDescs = (AudioStreamPacketDescription*)malloc(pAqData->mNumPacketsToRead * sizeof(AudioStreamPacketDescription)); } else { pAqData->mPacketDescs = NULL; } //Set Metadata for Audio Queue couldNotGetProperty = AudioFileGetPropertyInfo(pAqData->mAudioFile, kAudioFilePropertyMagicCookieData, &cookieSize, NULL); if (!couldNotGetProperty && cookieSize) { char* magicCookie = (char *)malloc(cookieSize); AudioFileGetProperty(pAqData->mAudioFile, kAudioFilePropertyMagicCookieData, &cookieSize, magicCookie); AudioQueueSetProperty(pAqData->mQueue, kAudioQueueProperty_MagicCookie, magicCookie, cookieSize); free(magicCookie); } //Set the playback gain AudioQueueSetParameter(pAqData->mQueue, kAudioQueueParam_Volume, AQ_PLAYBACK_GAIN); } 2. After replacing (playbak mp3 data buffer get by fread): In order to make the code porting smoothly, I copied the run-time value of critical variables, like pAqData->bufferByteSize, pAqData->mNumPacketsToRead, pAqData->mDataFormat…etc. And directly initialize these variables using the copied value in the replaced code. The intent of this behavior is to discard involking the interfaces of AudioToolbox framework like: AudioFileOpenURL, AudioFileGetProperty, AudioFileReadPackets… And then, we can use the stdio function fread to get the mp3 packet directly. The changed code is shown below: 1) The audio queue runloop callback (In previous code, the AudioFileReadPackets read 338 packets, and totally 129792 bytes, I copied these values directly into the replaced code) static void HandleOutputBuffer(void *aqData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer) { AQPlayerState *pAqData = (AQPlayerState *) aqData; UInt32 numBytesReadFromFile; UInt32 numPackets = pAqData->mNumPacketsToRead; UInt32 i = 0; printf("HandleOutputBuffer::Start!\n"); //If the audio queue is stopped, returns immediately if(pAqData->mIsRunning == 0) { printf("HandleOutputBuffer::Error Return!\n"); return; } //Read a packet of audio data using fread memset(audio_buffer, 0, 327680); memset(inBuffer->mAudioData, 0, 327680); pAqData->mPacketDescs->mStartOffset = 0; pAqData->mPacketDescs->mVariableFramesInPacket = 0; pAqData->mPacketDescs->mDataByteSize = 384; numBytesReadFromFile = fread(audio_buffer, sizeof(uint8_t), 129792, source_file); numPackets = 338; memcpy(inBuffer->mAudioData, audio_buffer, 327680); //Enqueue the audio packet into the audio queue if(numPackets > 0) { printf("HandleOutputBuffer::Step 1!\n"); inBuffer->mAudioDataByteSize = numBytesReadFromFile; AudioQueueEnqueueBuffer(pAqData->mQueue, inBuffer, (pAqData->mPacketDescs ? numPackets : 0), pAqData->mPacketDescs); pAqData->mCurrentPacket += numPackets; } else { printf("HandleOutputBuffer::Step 2!\n"); AudioQueueStop(pAqData->mQueue, false); pAqData->mIsRunning = false; } } 2) Open audio file(use fopen to replace AudioFileOpenURL) OSStatus AqOpenAudioFile(char *filePath, AQPlayerState *pAqData) { CFURLRef audioFileURL; OSStatus result; UInt32 maxPacketSize; UInt32 propertySize = sizeof (maxPacketSize); source_file = fopen(filePath, "r"); memset(audio_buffer, 0, 327680); fread(audio_buffer, sizeof(uint8_t), 32, source_file); pAqData->bufferByteSize = 327680; pAqData->mNumPacketsToRead = 338; return result; } 3) Create audio queue(Directly initialize the pAqData->mDataFormat with the value assigned in local MP3 playback mode) OSStatus AqCreateAudioQueue(AQPlayerState *pAqData) { UInt32 dataFormatSize = sizeof (AudioStreamBasicDescription); OSStatus result; bool isFormatVBR; UInt32 cookieSize = sizeof (UInt32); bool couldNotGetProperty; memset(&(pAqData->mDataFormat), 0, sizeof(AudioStreamBasicDescription)); pAqData->mDataFormat.mSampleRate = 48000; pAqData->mDataFormat.mFormatID = 778924083;//mp3 ID pAqData->mDataFormat.mFramesPerPacket = 1152; pAqData->mDataFormat.mChannelsPerFrame = 2; result = AudioQueueNewOutput(&(pAqData->mDataFormat), HandleOutputBuffer, pAqData, CFRunLoopGetCurrent(), kCFRunLoopCommonModes, 0, &(pAqData->mQueue)); //Configurate the VBR property if any isFormatVBR = (pAqData->mDataFormat.mBytesPerPacket == 0 || pAqData->mDataFormat.mFramesPerPacket == 0); if(isFormatVBR) { pAqData->mPacketDescs = (AudioStreamPacketDescription*)malloc(pAqData->mNumPacketsToRead * sizeof(AudioStreamPacketDescription)); } else { pAqData->mPacketDescs = NULL; } //Set the playback gain AudioQueueSetParameter(pAqData->mQueue, kAudioQueueParam_Volume, AQ_PLAYBACK_GAIN); } A: Guys: I found the root cause! The problem came from the function HandleOutputBuffer (The changed one)! Because every time, the function fread 338 packets of mp3 data (not just 1 packet), therefore, [pAqData->mPacketDescs] is not a single variable, it's actually an array with the size of 338 array items. So, we have to initialize the all 338 array items. So, we need to change the code: static void HandleOutputBuffer(void *aqData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer) { ... pAqData->mPacketDescs->mStartOffset = 0; pAqData->mPacketDescs->mVariableFramesInPacket = 0; pAqData->mPacketDescs->mDataByteSize = 384; ... } into static void HandleOutputBuffer(void *aqData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer) { ... for (i = 0; i < 338; i++) { pAqData->mPacketDescs[i].mStartOffset = PACKET_SIZE * i; pAqData->mPacketDescs[i].mVariableFramesInPacket = 0; pAqData->mPacketDescs[i].mDataByteSize = PACKET_SIZE; } ... } Finally, the problem fixed!
{ "language": "en", "url": "https://stackoverflow.com/questions/7593142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Trouble with threads in OSX and Ruby 1.9.2 Running the following code in IRB: t = Thread.new { loop { puts 'Hi' } } I receive a single hi and then no more output. Only if I begin pressing the enter key do I receive output as expected until I discontinue pressing enter. If I do t.join, everything acts as expected The problem happens in IRB, pry and ripl using ruby 1.9.2-p180 and 1.9.2-p290 under rvm 1.8.0 in OSX 10.7 and rvm 1.6.20 in OSX 10.6 readline is installed via rvm pkg install readline Thank you for any insight A: Some versions of readline on OSX are blocking. If you experience the behavior above, you can disable readline by putting IRB.conf[:USE_READLINE] = false in .irbrc
{ "language": "en", "url": "https://stackoverflow.com/questions/7593149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Disabling a toolbarbutton when there is no page to go back - Firefox extension I need to disable a toolbar button when there is no page to go back in history object. Similar to the browser back button. How can I do this? A: You use tabbrowser.sessionHistory property: gBrowser.sessionHistory.addSHistoryListener(myListener); Your listener should check whether gBrowser.sessionHistory.index is 0 (nothing to go back) and set button.disabled property appropriately. Either that or you simply make your button observe the browser's back button using <observes> tag: <toolbarbutton ...> <observes element="Browser:Back" attribute="disabled"/> </toolbarbutton> This makes sure that the disabled attribute for your button is copied over from the Browser:Back command.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: which one is better approach one large svc file or multiple small svc files in WCF I have one data intensive application where in I have one svc file which creates the C# reference file roughly of size 3mb and around 70 endpoints. Will it be good to break them in multiple svc files or is it ok to have one single svc file?
{ "language": "en", "url": "https://stackoverflow.com/questions/7593154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: duplicate entries in tableview I have implemented the table view in my iphone app. In this I am using the date picker to put date entries in table view. But some time user by mistake set to put the entry which is already existing. How should I put the validation so that duplicate entry don't exist. Please provide me some idea or solution. Thanks alot. A: Before refreshing tableview to display your new entry inserted, you should check your array from which you are populating your table. Try compare there & decide wether its already exists. if its is don't add. Hope this helps. A: Before adding a new entry I would just take all the entries I have so far and put them in an NSMutableSet or NSSet For example lets say all your elements are in the array myArray then: NSSet* mySet; [mySet addObjectsFromArray:myArray]; and then check the new Object with if (![mySet containsObject: newObject]) { //do whatever you need to } else { //the object is already contained } A: try this one; before reloading the table put this operation in your array NSSet *uniqueNames = [NSSet setWithArray:HistoryArray]; storyArray = [[NSMutableArray alloc] initWithArray:[uniqueNames allObjects]];
{ "language": "en", "url": "https://stackoverflow.com/questions/7593156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Do arguments put forward for avoiding the use of triggers hold true for ISV products? I've read the various accounts / opinions on the use of triggers here and elsewhere on the web and am trying to be careful not to create a duplicate question here. Much of the reasoning put forward against the use of triggers is the unknown, unseen side effects they may have for others interacting with the data. It seems to me that this would be more prevalent in an enterprise scenario where many departments may hang various applications off a company's database and unseen business rules of one department should not be hidden in triggers which could affect others or become outdated. I am building a product which incorporates an accounting system. I am finding a combination of triggers and computed fields very useful for maintaining fields such as invoice totals (including and excluding gst) statuses of transactions (like invoice partly paid, fully paid, partly authorised for payment and so on). I have justified the use of some very specific (atomic) triggers to enforce the most general of accounting rules, on the grounds that the "business" logic they enforce isn't really business logic but data integrity which will ease some reporting requirement for us or third parties in the future and that our database must survive in the wild with all manner of qualified (or not) "I.T. support" poking around at it. Our average user doesn't really understand the architecture or nature of a computer system and would naively trust anyone to help them with their computer system, based on their ability to turn on the computer or surf the web. I don't want, for example, an invoice status to be broken because some unknown "I.T. guru" or business owner's nephew, thinks he needs to delete a few rows from a table or change a payment amount manually. Do you think the generally accepted aversion to the use of triggers is more prevalent in an enterprise scenario or is it every bit as relevant to ISVs shipping a database with their product? A: It depends. When used in a database application or RDBMS supported client-server or n-tier application for something like logging actions on a table, I have found triggers useful in both an enterprise and ISV scenario. I would avoid using them in transactions or to implement business logic as they invariably complicate any issues in your app which might be affected (as it is easy to forget they are there or overlook their side effects) Also, some MPP databases, such as EMC Greenplum, do not allow user defined triggers, so if your app may ever need to scale-out this will also complicate matters. The general aversion you speak of is based on the issues they can present and these are valid concerns regardless of whether you are writing enterprise software or if you are an ISV
{ "language": "en", "url": "https://stackoverflow.com/questions/7593157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: http.get randomly says "getaddrinfo: Name or service not known" To generate offline reports, my Rails app needs to download charts from the Google Charts API. PROBLEM: It works fine most of the time, but sometimes (randomly) it fails and says getaddrinfo: Name or service not known When I get the error, I just relaunch the generation and usually it is successful. Is it usual? Is there a best practice to protect against this? Maybe a re-entrant algorithm, or a more high-level method? Current code: require 'net/http' charts.each_with_index do |path, index| Net::HTTP.start("chart.googleapis.com") do |http| resp = http.get(path) open("tmp/charts/chart" + index.to_s + ".png" ,"wb") do |file| file.write(resp.body) end end end A: ... it seems, you are overloading your DNS mechanism. Try this: require 'net/http' Net::HTTP.start("chart.googleapis.com") do |http| charts.each_with_index do |path, index| resp = http.get(path) open("tmp/charts/chart" + index.to_s + ".png" ,"wb") do |file| file.write(resp.body) end end end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7593160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Object of abstract class type "Animal" is not allowed: (C++) I'm trying to store things into vector but there're few problems. These are my code. Animal.cpp #include "Animal.h" #include "Cattle.h" #include "Sheep.h" #include <iostream> #include <string> using namespace std; Animal::Animal(int newid, double newweight, int yy, int mm, int dd, double newaccDose, char newsex) { id = newid; weight = newweight; yy = yy; mm = mm; dd = dd; dose = newaccDose; sex = newsex; } Animal::Animal() { id = 0; weight = 0; yy = 0; mm = 0; dd = 0; dose = 0; sex = ' '; } Animal::~Animal(){} double Animal::getDaysDifference(){ jdate dateOfBirth(dd,mm,yy); jdate now; double diff = now-dateOfBirth; return diff; } void Animal::addAnimal(){ int select=0; int id; cout << "1. Cattle 2. Sheep" << endl; cout << "Select a type of animal: "; cin >> select; if(select==1){ Cattle* c1; cout << "Please answer following questions" << endl; cout << "Type the animal's ID: "; cin >> id; c1->setID(id); //vector<Animal> vec; //vector<Animal>::iterator vec_ite; }else if(select==2){ Sheep* s1; cout << "Please answer following questions" << endl; cout << "Type the animal's ID: "; cin >> id; s1->setID(id); } else{ cout << "Invalid number please try again" << endl; } } First off, in the code above, Cattle* c1 and Sheep* s1, it doesn't have an error. and even if I code like s1->setID(id) it's fine. However, Cattle.cpp #include "Cattle.h" Cattle::Cattle(int newid, double newweight, int yy, int mm, int dd, double newdose, char newsex, string newcategory) : Animal(id, weight, yy,mm,dd, dose, sex) { id = newid; weight = newweight; dose = newdose; sex = newsex; Cattle::category = newcategory; } Cattle::Cattle(){ id = 0; weight = 0; dose = 0; sex = ' '; Cattle::category = ""; } Cattle::~Cattle(){} string Cattle::getCategory(){ return category; } double Cattle::calcDose(){ Cattle* c1; if(c1->getDaysDifference() < 90 || c1->getCategory() == "Meat"){ c1->dose = 0; return c1->dose; } else if(c1->getCategory() == "Dairy"){ if (c1->weight < 250 || c1->dose > 200){ c1->dose = 0; } else{ c1->dose = c1->weight * 0.013 + 46; } return c1->dose; } else if(c1->getCategory() == "Breeding"){ if (c1->weight < 250 || c1->dose > 250){ c1->dose = 0; } else{ c1->dose = c1->weight * 0.021 + 81; } return c1->dose; } else { cout << "It is not valid category" << endl; } } Animal.h #ifndef ANI_H #define ANI_H #include <vector> #include "Treatment.h" #include "jdate.h" class Animal{ protected: int id; double weight; int yy; int mm; int dd; double dose; char sex; //Treatment treatArray[]; public: Animal(); Animal(int newid, double newweight, int yy, int mm, int dd, double newdose, char newsex); ~Animal(); virtual double calcDose() = 0; void addAnimal(); double getDaysDifference(); }; #endif DrugAdmin.cpp (main) #include <iostream> #include "Animal.h" #include "Cattle.h" using namespace std; int main(){ Animal* a1=new Animal; delete a1; a1->addAnimal(); } The problem is here, when I try to define Animal* a1=new Animal; delete a1; it says Object of abstract class type "Animal" is not allowed: I've Googled and Binged here and there, and I figured out I cannot define the abstract base class itself but subclasses. So I tried the same thing in Cattle.cpp using Cattle c1=new Cattle; but it doesn't work either.. I'm really not sure what's wrong with that.. Could you help me please? Cheers A: virtual double calcDose() This says "It is possible to calcDose() for everything which is an Animal, and different Animals may do it differently..." = 0; "... but there is no 'generic' way to do it for Animals; each one must specify its own method". You may not construct an unspecified sort of Animal because, by definition, a key piece of information is missing: how to calcDose for it. This is all well and good. Chances are, you don't really want to construct an unspecified Animal, for the same reason that in real life, you wouldn't go to a farm (Zoo? Pet store?) to buy "an animal" without having any specific preconception of what kind of Animal you want. The type Animal exists so that you can omit the information about what kind of Animal something is when it is appropriate to do so. Creating the instance is not one of those times, in your case. Also, addAnimal makes absolutely no sense as a member function of Animal, no matter how much you might think it does. There are three fundamental problems: 1) since it's a non-static member function, you already require an Animal to call the function. That's kind of a catch-22. 2) You don't have anywhere to add the animal to. You need some kind of container. 3) Conceptually, making a list of Animals is not the animals' responsibility. It's the responsibility of whoever needs the list. 4) In general, it is good policy to have clean separation between the code that asks the user for information, and the code which acts upon that information. Write a free (meaning, not part of a class) function that asks for the information, constructs the Animal and returns that pointer; then in the calling code, store the pointer in a container. Except you don't really want to use raw pointers for this anyway. You should be using some kind of smart pointer, or else putting the pointers into one of the boost ptr_container s. A: Animal is an abstract class, which means it has pure virtual function(s). This is the pure virtual function in Animal. virtual double calcDose() = 0; Object of an abstract class cannot be created. It is true not only in C++, rather in all object oriented languages whichever support pure virtual function (some languages, such as C#, calls it abstract method.) If you remove the pure specifier which is =0 part in the declaration, as marked below: virtual double calcDose() = 0; //^^^^ this is called pure specifier then it will become virtual function (as opposed to pure virtual function). Now, you've to define the virtual function, and you can create objects of Animal then, as it is no more an abstract class. A: In Animal, you have: virtual double calcDose() = 0; So that class is abstract and cannot be instantiated. You can only construct objects of classes that derive from it and implement that method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Curved box into css? Can this box be created using only css, or at least 90% css with corner pieces, or would it be best to just redesign it? A: .panel { background-color: #2B2B2B; -webkit-border-radius: 10px; /* CSS3 Property for webkit design engine used browser */ -moz-border-radius: 10px; /* CSS3 Property for Mozilla */ -o-border-radius: 10px; /* CSS3 Property for Opera */ border-radius: 10px; /* CSS3 Property for Modern Browsers */ padding: 25px; } A: You can simply use CSS3: div{ border-radius: 5px; /* 5px rounded corner on all corners */ } If you want to use a more browser-support friendly method, you can use background images, or a method like that that Spiffy Corners provides, using small divs to recreate the effect. A: Have a look at SpiffyCorners for example or google for css rounded corners A: It is very possible, see here however if you decide to use corner pieces for compatability you can jsut use: <div id="box"> <div style="clear:both;"> <div id="topleft" style="float: left;"></div><div></div><div id="topright" style="float: right;"></div> </div> <div id="content"></div> <div style="clear:both;"> <div id="bottomleft" style="float: left;"></div><div></div><div id="bottomright" style="float: right;"></div> </div> </div> A: entirely with css. not exact, but very similar http://jsfiddle.net/jalbertbowdenii/EBfbZ/
{ "language": "en", "url": "https://stackoverflow.com/questions/7593167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Chromium closes WebSocket with no explanation I have Chromium 12.0.742.112 (90304) and I'm trying to set up a simple WebSocket server with it. I receive a handshake request like: Upgrade: WebSocket Connection: Upgrade Host: akira:22222 Origin: http://akira:22222 Sec-WebSocket-Key1: ;39LP*eC48 n /r0P6 v6548 Sec-WebSocket-Key2: 1 0 r 362547 4 4 G followed by 8 key bytes, in this case 88 09 F9 EE 21 13 F4 0D. I've verified that these are the same keys Chromium shows in the Network console tab. I calculate the first two keys as: Key1: 3948066548 / 4 = 987016637 Key2: 1036254744 / 12 = 86354562 and send my response: 000001 48 54 54 50 2F 31 2E 31 20 31 30 31 20 57 65 62 HTTP/1.1 101 Web 000011 20 53 6F 63 6B 65 74 20 50 72 6F 74 6F 63 6F 6C Socket Protocol 000021 20 48 61 6E 64 73 68 61 6B 65 0D 0A 55 70 67 72 Handshake..Upgr 000031 61 64 65 3A 20 57 65 62 53 6F 63 6B 65 74 0D 0A ade: WebSocket.. 000041 43 6F 6E 6E 65 63 74 69 6F 6E 3A 20 55 70 67 72 Connection: Upgr 000051 61 64 65 0D 0A 53 65 63 2D 57 65 62 53 6F 63 6B ade..Sec-WebSock 000061 65 74 2D 4F 72 69 67 69 6E 3A 20 68 74 74 70 3A et-Origin: http: 000071 2F 2F 61 6B 69 72 61 3A 32 32 32 32 32 0D 0A 53 //akira:22222..S 000081 65 63 2D 57 65 62 53 6F 63 6B 65 74 2D 4C 6F 63 ec-WebSocket-Loc 000091 61 74 69 6F 6E 3A 20 77 73 3A 2F 2F 61 6B 69 72 ation: ws://akir 0000A1 61 3A 32 32 32 32 32 2F 73 6F 63 6B 65 74 0D 0A a:22222/socket.. 0000B1 0D 0A FF F4 2E 12 9D DC 12 C2 56 40 B8 09 F3 84 ..........V@.... 0000C1 CA EF .. .. .. .. .. .. .. .. .. .. .. .. .. .. ..############## Chromium just closes the socket without even printing a message in the JS console. I can't tell what I'm doing wrong? The server-side code is in Lua (thus why the above hex dump is indexed starting from 1): require('crypto') local handshake = { "HTTP/1.1 101 Web Socket Protocol Handshake", "Upgrade: WebSocket", "Connection: Upgrade", "Sec-WebSocket-Origin: " .. request.header.origin, "Sec-WebSocket-Location: " .. request.header.origin:gsub('http:', 'ws:') .. "/socket", '\r\n'} log.debug("Request header:\n%s\n", table.concat(request.rawheader, '\n')) local client = response.socket client:settimeout(10) local keys = {request.header.sec_websocket_key1, request.header.sec_websocket_key2} local sum = {} for i, k in ipairs(keys) do local nspc = 0 sum[i] = '' k:gsub('%d', function(n) sum[i] = sum[i] ..n end) k:gsub(' ', function() nspc = nspc + 1 end) log.debug("Key%d: %s / %d = ", i, sum[i], nspc) sum[i] = tostring(tonumber(sum[i]) / nspc) log.debug("%s\n", sum[i]) end local key = assert(client:receive(8)) local bytes = {key:byte(1, #key)} local keydump = {} for i = 1, #bytes do keydump[i] = ('%02X'):format(bytes[i]) end log.debug("Key3: %s\n", table.concat(keydump, ' ')) local resp = crypto.evp.digest('md5', table.concat(sum) .. key, true) handshake = table.concat(handshake, '\r\n') .. resp client:settimeout(0.1) log.debug("Send handshake:\n%s\n", rena.debug.hexdump(handshake)) client:send(handshake) repeat local res, err = client:receive('*l') if res then log.debug("R: %s\n", res) end local res, err = client:send("Test " .. tostring(os.time()) .. '\n') if res then socket.sleep(1) elseif err == 'timeout' then log.debug("WS: Timed out\n") elseif err == 'closed' then log.debug("WS: Closed\n") else log.error("WS: Error: %s\n", tostring(err)) end until not res (This script is loaded by the server script which presets some variables such as request and response, and uses LuaCrypto for MD5). Everything looks right (though I notice all the examples show nice ASCII characters for the binary keys whereas mine are mostly unprintable), but it just closes the socket. Unfortunately Chromium is the only browser I have that supports WebSocket at all (unless there's some way to enable it in Firefox 6?), so I can't check in anything else. A: Well I found the issue. The first two keys are meant to be concatenated as 32-bit integers (into a single 64-bit integer), not as ASCII strings: - sum[i] = tostring(tonumber(sum[i]) / nspc) + sum[i] = ('%08X'):format(tonumber(sum[i]) / nspc) - local resp = crypto.evp.digest('md5', table.concat(sum) .. key, true) - handshake = table.concat(handshake, '\r\n') .. resp + local challenge = '' + (sum[1] .. sum[2]):gsub('..', function(byte) + challenge = challenge .. string.char(tonumber(byte, 16)) + end) + + challenge = challenge .. key + log.debug("Ch: %s\n", challenge:tohex()) + + local resp = crypto.evp.digest('md5', challenge, true) + handshake = table.concat(handshake, '\r\n') .. resp With that Chromium accepts the connection. I've filed a bug to complain about the lack of error message with an incorrect hash.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: how to set the locale according to the currency code selected is there a way to set the locale according to the currency code selected .i can get a list of currency codes.now if i select a currency code say USD ,then i should be able to get the locale identifier "en-US" and set the locale accordingly.The purpose is to format all currencies used in my application to this locale. how to do this? i now set the normal string to currency string using the code NSLocale* locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"ja_JP"] autorelease]; NSDecimalNumber *someAmount = [NSDecimalNumber decimalNumberWithString:unformattedString]; NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init]; [currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle]; [currencyFormatter setLocale:locale]; for that i have to get the locale identifier(in this case @"ja_JP"). in my app i have an option to change the currency.if euro is set then the locale identifier changes
{ "language": "en", "url": "https://stackoverflow.com/questions/7593171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: parsing nested JSON String objects with JQuery/PHP? This is the page I'm working on.... http://fremontchurch.net/json_test/ This is the json http://fremontchurch.net/json_test/posts.php I'm trying to to have a list of tracks names listed and linked through simple html link <a href="URL_GOES_HERE">TRACK NAME GOES HERE</a> to its url i got everything else in order its just the nested part keeps coming up "[object Object],[object Object],[object Object]"... and so on... each nest has two items a track name and url... what would be the correct way to do this? heres one object from my json... { "id":"All Things Are Possible", "key":"All Things Are Possible", "doc":"All Things Are Possible", "album":"All Things Are Possible", "artwork":"http://godsgypsychristianchurch.net/music_artwork/DEFAULT_COVER2.png", "baseurl":"http://www.godsgypsychristianchurch.net/music", "church":"Atlanta GA", "des":"All Things Are Possible from the Atlanta GA Church, Pastor Nick White", "tracks":[ {"name":"1 Intro", "url":"/Atlanta%20GA/All%20things%20are%20possible/01%20Intro.mp3"}, {"name":"2 Wo si O Drom", "url":"/Atlanta%20GA/All%20things%20are%20possible/02%20Wo%20si%20O%20drom.mp3"}, {"name":"3 Nas Murrgo Shov", "url":"/Atlanta%20GA/All%20things%20are%20possible/03%20Nas%20murrgo%20shov.mp3"}, {"name":"4 To Cho Vos", "url":"/Atlanta%20GA/All%20things%20are%20possible/04%20To%20cho%20vos.mp3"}, {"name":"5 Tu Son Kai Sastridas", "url":"/Atlanta%20GA/All%20things%20are%20possible/05%20Tu%20son%20kai%20sastridas.mp3"}, {"name":"6 Now I Am Strong", "url":"/Atlanta%20GA/All%20things%20are%20possible/06%20Now%20I%20am%20strong.mp3"}, {"name":"7 Sorr Nevee", "url":"/Atlanta%20GA/All%20things%20are%20possible/07%20Zorr%20nevee.mp3"}, {"name":"8 Preaching", "url":"/Atlanta%20GA/All%20things%20are%20possible/08%20Preaching.mp3"}, {"name":"9 Arkadyan Amey", "url":"/Atlanta%20GA/All%20things%20are%20possible/09%20Arkadyan%20amey.mp3"}, {"name":"10 O Christo Ka Wudarr", "url":"/Atlanta%20GA/All%20things%20are%20possible/10%20O%20Christo%20ka%20wudarr.mp3"}, {"name":"11 Eloi, Eloi", "url":"/Atlanta%20GA/All%20things%20are%20possible/11%20Eloi%2C%20Eloi.mp3"}, {"name":"12 Amadow Dell", "url":"/Atlanta%20GA/All%20things%20are%20possible/12%20Amadow%20Dell.mp3"}, {"name":"13 Sastiar Amey Devla", "url":"/Atlanta%20GA/All%20things%20are%20possible/13%20Sastiar%20amey%20Devla.mp3"}, {"name":"14 Tu Skepeese", "url":"/Atlanta%20GA/All%20things%20are%20possible/14%20Tu%20skepeese.mp3"}, {"name":"15 Dov Ma Godgee", "url":"/Atlanta%20GA/All%20things%20are%20possible/15%20Dov%20ma%20godgee.mp3"}, {"name":"16 The Lord is my strength", "url":"/Atlanta%20GA/All%20things%20are%20possible/16%20The%20Lors%20is%20my%20strength.mp3"} ] } heres all my code to the html/jquery/php <html> <body> <div id="content"> </div> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ var url="posts.php"; $.getJSON(url,function(json){ $.each(json.posts,function(i,post){ $("#content").append( '<div class="post">'+ '<h1>'+post.album+'</h1>'+ '<p><img src="'+post.artwork+'"width="250"></img></p>'+ '<p><strong>'+post.church+'</strong></p>'+ '<p>Description: <strong>'+post.des+'</strong></p>'+ '<p>Base url: <em>'+post.baseurl+'</em></p>'+ '<p>Tracks: <li>'+post.tracks+'</li></p>'+ '<hr>'+ '</div>' ); }); }); }); </script> </body> </html> please reply will full code because I'm kinda new to this kind of coding and sometimes i done know where to put it... any help will be very much appreciated, thank you... A: You need to loop over each item in post.tracks and collect that information into a string before including it, something like this: $.each(json.posts,function(i,post){ var content, trackInfo = '', tracks = post.tracks; // loop over the tracks and collect info $.each(tracks, function (i) { trackInfo += '<a href="' + tracks[i].url + '">' + tracks[i].name + '</a> '; }); content = '<div class="post">'+ '<h1>'+post.album+'</h1>'+ '<p><img src="'+post.artwork+'"width="250"></img></p>'+ '<p><strong>'+post.church+'</strong></p>'+ '<p>Description: <strong>'+post.des+'</strong></p>'+ '<p>Base url: <em>'+post.baseurl+'</em></p>'+ '<p>Tracks: <li>'+ trackInfo +'</li></p>'; '<hr>'+ '</div>' $("#content").append(content); }); Working example here: http://jsfiddle.net/3SFE4/ A: In the same way you're using each to iterate over the posts, you can use each to iterate over the tracks. I've included full code below. <html> <body> <div id="content"> </div> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ var url="posts.php"; $.getJSON(url,function(json){ $.each(json.posts,function(i,post){ // Here we generate a fragment for the tracks. var tracks = ''; $.each(post.tracks, function(j, track) { tracks += '<a href="' + track.url + '">' + track.name + '</a>'; }) $("#content").append( '<div class="post">'+ '<h1>'+post.album+'</h1>'+ '<p><img src="'+post.artwork+'"width="250"></img></p>'+ '<p><strong>'+post.church+'</strong></p>'+ '<p>Description: <strong>'+post.des+'</strong></p>'+ '<p>Base url: <em>'+post.baseurl+'</em></p>'+ 'tracks' + '<hr>'+ '</div>' ); }); }); }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7593174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Trouble with Android Facebook SDK on Java, Android I create app for working with facebook. I download Android Facebook SDK from GitHub, than I create a new Android project for sdk in Eclipse (when I'm creating a new project for sdk, i selected "create from existing source"). Than I added to my project this facebook project ("build path", etc). But when I want to create a new Facebook object, I got unhandled error. It is code: Facebook fb=new Facebook(APP_ID); Where have I do mistake? Error log: - 09-29 05:23:21.295: ERROR/AndroidRuntime(1256): java.lang.NoClassDefFoundError: com.facebook.android.Facebook 09-29 05:23:21.295: ERROR/AndroidRuntime(1256): at com.nda.mailinglist.SimpleAndroidMailingListActivity.onContextItemSelected(SimpleAndroidMailingListActivity.java:80) 09-29 05:23:21.295: ERROR/AndroidRuntime(1256): at android.app.Activity.onMenuItemSelected(Activity.java:2174) 09-29 05:23:21.295: ERROR/AndroidRuntime(1256): at com.android.internal.policy.impl.PhoneWindow$ContextMenuCallback.onMenuItemSelected(PhoneWindow.java:2731) 09-29 05:23:21.295: ERROR/AndroidRuntime(1256): at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:139) 09-29 05:23:21.295: ERROR/AndroidRuntime(1256): at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:855) 09-29 05:23:21.295: ERROR/AndroidRuntime(1256): at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:129) 09-29 05:23:21.295: ERROR/AndroidRuntime(1256): at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:884) 09-29 05:23:21.295: ERROR/AndroidRuntime(1256): at android.widget.AdapterView.performItemClick(AdapterView.java:284) 09-29 05:23:21.295: ERROR/AndroidRuntime(1256): at android.widget.ListView.performItemClick(ListView.java:3285) 09-29 05:23:21.295: ERROR/AndroidRuntime(1256): at android.widget.AbsListView$PerformClick.run(AbsListView.java:1640) 09-29 05:23:21.295: ERROR/AndroidRuntime(1256): at android.os.Handler.handleCallback(Handler.java:587) 09-29 05:23:21.295: ERROR/AndroidRuntime(1256): at android.os.Handler.dispatchMessage(Handler.java:92) 09-29 05:23:21.295: ERROR/AndroidRuntime(1256): at android.os.Looper.loop(Looper.java:123) 09-29 05:23:21.295: ERROR/AndroidRuntime(1256): at android.app.ActivityThread.main(ActivityThread.java:4363) 09-29 05:23:21.295: ERROR/AndroidRuntime(1256): at java.lang.reflect.Method.invokeNative(Native Method) 09-29 05:23:21.295: ERROR/AndroidRuntime(1256): at java.lang.reflect.Method.invoke(Method.java:521) 09-29 05:23:21.295: ERROR/AndroidRuntime(1256): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860) 09-29 05:23:21.295: ERROR/AndroidRuntime(1256): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 09-29 05:23:21.295: ERROR/AndroidRuntime(1256): at dalvik.system.NativeStart.main(Native Method) A: Facebook sdk project should be on same drive in which you have your project. For example if you have your project code in C: drive but you have placed facebook sdk in D: drive then it wont work. Both should be in same drive.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# error in application I implemented my site and suddenly im catching an error in the global.asax application_error which states the following: Error Caught in Application_Error event Error in: http://www.mydomain.com/styles/data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs= Error Message:A potentially dangerous Request.Path value was detected from the client (:). SOURCE: System.Web FORM: QUERYSTRING: TARGETSITE: Void ValidateInputIfRequiredByConfig() STACKTRACE: at System.Web.HttpRequest.ValidateInputIfRequiredByConfig() at System.Web.HttpApplication.ValidateRequestExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) I know this is the data for an image , but i cant find out how and why this is happen. Any ideas? Chr. A: It's an illegal URL: http://www.mydomain.com/styles/data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs The colon is a special character (signifiying protocol separator, port separator, or password separator) As Hasan mentions, you can turn this validation off. But in truth, you should avoid having URLs like this that are just just completely invalid. Instead, URL-encode it (the part after "data"). A: It could be caused by a CSS minifier tool incorrectly altering data:image URLs: Why would CSS data-URIs be logged as 404 requests?
{ "language": "en", "url": "https://stackoverflow.com/questions/7593177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: JQuery AJAX response handling Probably some simple derp but I just can't figure this out, I'm using almost identical code in a different solution and it works. Javascript: $('#drop').click(function(e) { e.preventDefault(); $('#login').slideToggle(1000); }); $('#sub').click(function(e) { e.preventDefault(); $('#info').html('<img src="img/load.gif" />') $.post('login.php', {user: document.getElementById('user').value, pass: document.getElementById('pass').value}, function(response) { if (response == 'ok') { $('#login').slideUp(500); $('#info').html(''); $('#joocy').html('<img src="img/load.gif" />').load('manage.php'); } else if (response == 'error') { $('#info').html('Invalid user/pass'); } }); }); PHP: if ($row = mysql_fetch_array($result)) { echo 'ok'; } else { echo 'error'; } Response is being sent back but the if-clause isn't catching it. typeof() returns string. EDIT: else if (response === 'error ') // notice the space in the string This works, can anyone explain why the space is appended to the returnstring? SOLVED: There was a space after PHP closing tag. Thanks for your time everyone! :) A: You probably have a space after the closing '?>' tag in your php script. Try either removing all whitespace after, or the closing tag altogether. A: Maybe the output contains other characters like e.g. a BOM. What does $.post('login.php', {user: document.getElementById('user').value, pass: document.getElementById('pass').value}, function(response) { if (response == 'ok') { $('#login').slideUp(500); $('#info').html(''); $('#joocy').html('<img src="img/load.gif" />').load('manage.php'); } else if (response == 'error') { $('#info').html('Invalid user/pass'); } var tmpText = "" + response.length + ": "; for(var tmpI=0; tmpI<response.length; tmpI++) { tmpText += response.charCodeAt(tmpI) + " "; } $("<fieldset></fieldset>").text(tmpText).appendTo("#info"); }); print? A: may the additional space is added from the php side of the code, you can use trim if($.trim(response)==='error') { // }
{ "language": "en", "url": "https://stackoverflow.com/questions/7593183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Change Solr search directory to my custom named index directory In the /data directory of solr, suppose, I have three folders named as index, custom, spellCheck. So, the problem is when I open up localhost:8983/solr/admin and try to search, solr makes a search only in the index folder. I want solr to search in the 'custom' folder inside the /data folder. Can it be done? If I see the 'schema browser', and go through the schema information, there is a 'directory' property such as, directory: org.apache.lucene.store.NIOFSDirectory:org.apache.lucene.store.NIOFSDirectory@ /home/mypc/softwares/apache-solr-3.4.0/example/solr/data/index lockFactory=org.apache.lucene.store.NativeFSLockFactory@6c5482 I think that /solr/data/index directory should point to /solr/data/custom, for the search to work. A: Solr uses index directory as the fixed name, so i don't think it can be customized unless you modified the code. solr.core.dataDir -- The core's data directory (i.e. the directory under which that core's index directory are located) If you need the search to work only on the custom directoy, you can try creating a symlink. A: You can also use the index.properties file to point to which directory Solr loads. It goes in the data directory and it has a index property pointing to the directory name to be used instead of 'index' That's worked for me without issue. I believe this was done to help make replication work seamlessly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to save a long type data with Persistent Object on Blackberry? I have a class DataContext to save data by Persistent Object. DataContext data = new DataContext(); data.set("edit",myEditField.getText(); // ok but data.set("date",myDateField.getDate()); // not accept for save long type. How can I save myDateField with Persistent object ? A: BlackBerry persistent objects can only store objects and a long is a primitive. Just use the Long wrapper object and store that with your PersistentObject.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL ORDER BY dilemma with numbers I have a table which holds a varchar datatype. It holds 128 characters max. I'm trying to order it alphabetically, and it works out fine, except for one little thing. When I try to save a mixture of numbers and letters, it returns the 'literal' alphabetical order, which means 11 comes first before 2. I have read almost all of the answers in the internet, but they are all workarounds that cannot work specifically for my problem. Examples of values I want to put in order Apartment House Dog Cat 18 years old 2 years old 1 year old But I want it to look like this. 1 year old 2 years old 18 years old Apartment Cat Dog House It spans on a large database and I can't just split the numerical values apart from the text ones. Also users who can use the program can modify it with Alphanumeric characters. Any suggestions about my problem? Thanks. A: Here is something I tried in SQL Server. It's neither elegant nor fit for production, but it may give you an idea. SELECT StringValue, CAST(SUBSTRING(StringValue, StartPos, EndPos - StartPos) AS INT) AsNumber, SUBSTRING(StringValue, StartPos, EndPos - StartPos) NumberToken, SUBSTRING(StringValue, EndPos, 1000) Rest, StartPos, EndPos FROM (SELECT StringValue, PATINDEX('[0-9]%', StringValue) StartPos, PATINDEX('%[^0-9]%', StringValue) EndPos FROM (SELECT 'abc123xyz' StringValue UNION SELECT '1abc' UNION SELECT '11abc' UNION SELECT '2abc' UNION SELECT '100 zasdfasd') Sub1 ) Sub2 ORDER BY AsNumber, Rest Result: StringValue AsNumber NumberToken Rest StartPos EndPos abc123xyz 0 abc123xyz 0 1 1abc 1 1 abc 1 2 2abc 2 2 abc 1 2 11abc 11 11 abc 1 3 100 zasdfasd 100 100 zasdfasd 1 4 A: I would approach this as follows... First, write an expression to convert the numeric stuff to integers, something like select CAST(SUBSTRING(<field>',1,instr(<field>',' ') as INT),<field> I would then use a UNION ALL statement, something like this SELECT CAST(SUBSTRING(<field>',1,instr(<field>',' ') as INT),<field>,A.* FROM <table> A WHERE <field> LIKE <regular expression to get fields beginning with numbers> UNION ALL SELECT 999999,<field>,A.* FROM <table> A WHERE <field> NOT LIKE <regular expression to get fields beginning with numbers> ORDER BY 1,2,3 The numbers will appear first, in numeric order. Sine all of the alpha data has the same numeric key, it will appear sorted alphabetically after the numbers... Just be sure to make the alpha dummy key (999999) is large enough to be after all the numeric ones... I don't have mySQL on this machine, but hopefully this gives you enough of a start to solve it A: you should probably get away by doing something like this: order by right(replicate(' ',30)+Column_name,30) A: Try this order by: ORDER BY RIGHT(REPLICATE('0',128)+value,128) My test: DECLARE @T TABLE ( value VARCHAR(128) ) INSERT INTO @T VALUES('Apartment'), ('House'), ('Dog'), ('Cat'), ('18 years old'), ('2 years old'), ('1 year old'), ('12 horses'), ('1 horse') SELECT * FROM @T ORDER BY RIGHT(REPLICATE('0',128)+value,128) RESULTS: Cat Dog House 1 horse 12 horses Apartment 1 year old 2 years old 18 years old If you find a case that this doesn't work please post it along with the sort order you would like and I can see if there's a fix.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Eclipse not compile my servlet I have eclipse project with many packages. I move one .java file from one package to another and then I try to compile. Compile was successful but this file hasn't been compiled. I restart eclipse but this problem still appear. I create new test class ant this class weren't compile again. I use Eclipse Indigo on Mac OSX 10.6.8 Can someone help me. Thanks in advance. A: Moving: If you have moved the file within eclipse, you have been asked if all references should be updated. This you have to answer with "yes", as long as there are no (red) errors shown. If you moved the file in the finder, move it back and do it again within eclipse. Make sure the new destination is in your src-folder. Rebuilding project: Go to the "Project"-menu and disable the menu "Build automatically". Then choose "Build all" from the same menu (make sure you selected your project in the "Package Explorer". Afterwards enable "Build automatically" again. Check for errors: Go into the "Problems"-panel and check if there is a message about any problems within your project. If so, try to fix them or post them here. If it is still not working and no errors are shown, go further: Check your project SetUp: Right-click your Project and select the "Properties" menu from the appearung context-menu. Go to the menu "Java Build Path" in the appearing window and select the tab "Source" on the right site. Check if all your source folder are visible there. If not, add them there. Repeat the steps above then. A: I suppose your setting for the java build path is not correct. To check this right click on your project and select properties from the context menu. In the dialog click 'Java Build Path' / Tab Source and make sure that all folders containing your sources files are listed here, otherwise they will be ignored.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Find tag and put a word in an element with jQuery What I want: if inside tag <li> there is no tag <a>, then - insert word "Empty" into <div class="tooltip"> </div>. How can do i do it with jQuery? <ol> <li><input name="hotel_id[]" value="14" style="display:none;"> <div class="tooltip" style="top: 439px; left: 717px; display: none; "> </div> <a href="" class="tool_tip" title="ok">Hello</a></li> <li><input name="hotel_id[]" value="5" style="display:none;"> <div class="tooltip" style="opacity: 0.9; top: 439px; left: 717px; display: none; "> </div> <a href="" class="tool_tip" title="">How</a></li> <li><input name="hotel_id[]" value="4" style="display:none;"> <div class="tooltip" style="top: 439px; left: 717px; display: none; opacity: 0.9; "> </div> <a href="" class="tool_tip" title="">Are</a></li> <li><input name="hotel_id[]" value="3" style="display:none;"> <div class="tooltip" style="opacity: 0.9; top: 439px; left: 717px; display: none; "> </div> <a href="" class="tool_tip" title="">Help</a></li> <li><input name="hotel_id[]" value="2" style="display:none;"> <div class="tooltip" style="top: 439px; left: 717px; display: none; "> // I want append here word "Empty" that there is not tag a in li </div></li> <li><input name="hotel_id[]" value="1" style="display:none;"> <div class="tooltip" style="top: 439px; left: 717px; display: none; "> // I want appen here word "Empty" that there is not tag a in li </div></li> </ol> A: look after :not and :has: $("li:not(:has(a))").find(".tooltip").html("Empty").removeAttr("style"); I remove the style attribute on .tooltip, if you dont need that just change it to show() instead to show the .tooltip: $("li:not(:has(a))").find(".tooltip").html("Empty").show(); Demo: http://jsbin.com/uyuwoy/edit A: This would work: $('ol li').not(':has(a)').find('.tooltip').html('Empty');
{ "language": "en", "url": "https://stackoverflow.com/questions/7593196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }