text
stringlengths
8
267k
meta
dict
Q: EditText with Currency format I have a EditText in which I want to display currency: input.setInputType(InputType.TYPE_CLASS_NUMBER); input.addTextChangedListener(new CurrencyTextWatcher()); with: public class CurrencyTextWatcher implements TextWatcher { boolean mEditing; public CurrencyTextWatcher() { mEditing = false; } public synchronized void afterTextChanged(Editable s) { if(!mEditing) { mEditing = true; String digits = s.toString().replaceAll("\\D", ""); NumberFormat nf = NumberFormat.getCurrencyInstance(); try{ String formatted = nf.format(Double.parseDouble(digits)/100); s.replace(0, s.length(), formatted); } catch (NumberFormatException nfe) { s.clear(); } mEditing = false; } } I want to user to see a number-only keyboard, that is why I call input.setInputType(InputType.TYPE_CLASS_NUMBER); on my EditText. However, it does not work. I see the numbers as typed in without any formatting. BUT: If I DO NOT set the inputType via input.setInputType(InputType.TYPE_CLASS_NUMBER), the formatting works perfectly. But the user must use the regular keyboard, which is not nice. How can I use the number keyboard and also see the correct currency formatting in my EditText? Thanks. A: Try add this property in you xml declaration for you edit text: android:inputType="numberDecimal" or number or signed number See more info about android:inputType here. A: It is better to use InputFilter interface. Much easier to handle any kind of inputs by using regex. My solution for currency input format: public class CurrencyFormatInputFilter implements InputFilter { Pattern mPattern = Pattern.compile("(0|[1-9]+[0-9]*)?(\\.[0-9]{0,2})?"); @Override public CharSequence filter( CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { String result = dest.subSequence(0, dstart) + source.toString() + dest.subSequence(dend, dest.length()); Matcher matcher = mPattern.matcher(result); if (!matcher.matches()) return dest.subSequence(dstart, dend); return null; } } Valid: 0.00, 0.0, 10.00, 111.1 Invalid: 0, 0.000, 111, 10, 010.00, 01.0 How to use: editText.setFilters(new InputFilter[] {new CurrencyFormatInputFilter()});
{ "language": "en", "url": "https://stackoverflow.com/questions/7627148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: c# pass file pointer to unmanaged c++ dll to use for stdout Please bear with me - I'm a c# developer with little experience with C++, and this is a steep learning curve! From a c# console app, I'm calling some methods from an unmanaged C++ dll. The DLL writes to the stdout stream, although this was not being picked up by the c# console. I found the following code, which I added to the C++ dll, which now successfully sends the contents of "printf" to the c# console. #include <windows.h> #include <stdio.h> #include <fcntl.h> #include <io.h> void redirect_stdout() { int hConHandle; long lStdHandle; FILE *fp; // allocate a console for this app AllocConsole(); // redirect unbuffered STDOUT to the console lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen( hConHandle, "w" ); *stdout = *fp; setvbuf( stdout, NULL, _IONBF, 0 ); } AOK so far: What I'd like to do is capture the stdoutfrom the DLL to a c# stream, rather than send it to the console. I tried the method detailed here (Redirect stdout+stderr on a C# Windows service), which does capture the output, however the app "crashes" when the program closes ("vshost.exe has stopped working"). (Note: setting Console.SetOut() on the stream captures the c# output, not the c++ output). So I thought what if I use the "Filestream.SafeFileHandle.DangerousGetHandle()" method to get a handle to the filestream from c#, and pass this into the C++ method redirect_stdout() method: void redirect_stdout(FILE *passedInHandle) { // allocate a console for this app AllocConsole(); *stdout= *passedInHandle; setvbuf( stdout, NULL, _IONBF, 0 ); } When I run the above version, the output from the DLL is no longer piped to the c# Console, however, the filestream on the c# side is always empty. Can any expert give guidance to have the STDOUT write its output to the c# filestream? I'm sure I've made some stupid error about how to achieve this or I am not understanding how to achieve what I am trying to do. Thank you for your time and input - really appreciated! [EDIT] OK - I've played a bit more and modified the C++ method as such: void redirect_stdout(int passedInHandle) { int hConHandle; long lStdHandle; FILE *fp; // allocate a console for this app AllocConsole(); hConHandle = _open_osfhandle(passedInHandle, _O_TEXT); fp = _fdopen(hConHandle, "w"); *stdout = *fp; setvbuf( stdout, NULL, _IONBF, 0 ); } This also successfully populates the c# stream, however when the c# Console app closes, the app crashes with the error "vshost.exe has stopped working". This is the same error as when I use the method from Redirect stdout+stderr on a C# Windows service Very odd find: If I run the console app "outside of visual studio" (eg, double click on the .exe in the bin folder), there is no crash! So I guess my next question is: how do I track down the source of this crash? Is it VS related? It occurs in either debug or release mode when running from VS, and no crash when run outside of VS. I am at a loss as to how to debug this one! A: You might consider using named pipes: i.e communication between c++ and c# through pipe http://www.switchonthecode.com/tutorials/interprocess-communication-using-named-pipes-in-csharp Hopefully, that should work...
{ "language": "en", "url": "https://stackoverflow.com/questions/7627152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Caching at repository layer in Asp.net application using Caching Application Block In one of my webapplication, I am trying to cache some reference entities so as to reduce database hits. I am using Caching application block to implement the caching. I am new to it, and I am not sure about its implementation. I have written a sample repository to utilize it. I want all of you to please have a look and comment on it. public class StatusRepository { ICacheManager statusCahce = CacheFactory.GetCacheManager(); //I am not sure whether I should initilise statusCache object here. public StatusEntity Get(byte statusId) { StatusCollection statusCollection = (StatusCollection)statusCahce.GetData("Statuses"); if (statusCollection != null) { return (StatusEntity)statusCollection.StatusList.First(p=>p.StatusId==statusId); } else { // HIT Database to get the entity } } public StatusCollection GetStatusList() { StatusCollection statusCollection = (StatusCollection)statusCahce.GetData("Statuses"); SqlHelper sql = new SqlHelper(true); if (statusCollection != null) //We have it in cache { return statusCollection; } else //Hit Database { //Hit Database to get the StatusCollection and add that collection to cache statusCahce.Add("Statuses", statusCollection); return statusCollection; } } } } } Please let me know, how can I improve it. Please also let me know, How much data can we have in cache. A: Something like this might be of use?
{ "language": "en", "url": "https://stackoverflow.com/questions/7627157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: UISearchBar Issue on Table Loaded by SQLite Query First of all, I'm new to this so excuse my any simplest question. I'm trying to view data and filter it which is very common. So I use different tutorials. First, I loaded data from my SQLite database, then I used custom cell tutorials and customized my cells. But I got stuck in UISearchBar. The tutorial I followed uses an NSArray to fill the table which is declared in code-behind. Since my SQLite methods gets the data from database to an Array, I thought if I copy this array to the array in filtering methods, that would work.But it didn't. Here is some code with explanations: -(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText { if ([searchText length] == 0) { [displayItems removeAllObjects]; [displayItems addObjectsFromArray:allItems]; } else { [displayItems removeAllObjects]; for (NSString *string in allItems) { NSRange r = [string rangeOfString:searchText options:NSCaseInsensitiveSearch]; if (r.location != NSNotFound) { [displayItems addObject:string]; } } } [tableViewScreen reloadData]; } Code above is for filtering and I tried to copy the array that I used to fill the table to allItems array like this: MyProjectAppDelegate *appDelegate = (MyProjectAppDelegate *)[[UIApplication sharedApplication] delegate]; allItems = appDelegate.mySqliteArray; Or like this: allItems = [[NSArray alloc] initWithArray:appDelegate.mySqliteArray]; But none of them did work. I'd like to point my problem again,I have a method that gets the data into an array in AppDelegate class, and in my TableView class, I want to copy that array to another.P.S. mySqliteArray is mutable array and allItems array is not.And also, my cells are created by custom cell class, and there are 2 labels in each row. A: Since I was defining an array that has objects created by my defined class, I later realized that I was mistaken to carry objects but not strings.So I updated my code like this and succeeded to create the needed array: for (MyClass *object in appDelegate.mySqliteArray) { [allItems addObject:[NSString stringWithFormat:@"%@", object.objectName]]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7627160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get ID of element that called a function How can I get the ID of an element that called a JS function? body.jpg is an image of a dog as the user points his/her mouse around the screen at different parts of the body an enlarged image is shown. The ID of the area element is identical to the image filename minus the folder and extension. <div> <img src="images/body.jpg" usemap="#anatomy"/> </div> <map name="anatomy"> <area id="nose" shape="rect" coords="280,240,330,275" onmouseover="zoom()"/> </map> <script type="text/javascript"> function zoom() { document.getElementById("preview").src="images/nose.jpg"; } </script> <div> <img id="preview"/> </div> I've done my research and have come to Stack Overflow as a last resort. I'm prefer a solution that doesn't involve jQuery. A: You can code the handler setup like this: <area id="nose" shape="rect" coords="280,240,330,275" onmouseover="zoom.call(this)"/> Then this in your handler will refer to the element. Now, I'll offer the caveat that I'm not 100% sure what happens when you've got a handler in an <area> tag, largely because I haven't seen an <area> tag in like a decade or so. I think it should give you the image tag, but that could be wrong. edit — yes, it's wrong - you get the <area> tag, not the <img>. So you'll have to get that element's parent (the map), and then find the image that's using it (that is, the <img> whose "usemap" attribute refers to the map's name). edit again — except it doesn't matter because you want the area's "id" durr. Sorry for not reading correctly. A: I know you don't want a jQuery solution but including javascript inside HTML is a big no no. I mean you can do it but there are lots of reasons why you shouldn't (read up on unobtrusive javascript if you want the details). So in the interest of other people who may see this question, here is the jQuery solution: $(document).ready(function() { $('area').mouseover(function(event) { $('#preview').attr('src', 'images/' + $(event.srcElement).attr('id')); }); }); The major benefit is you don't mix javascript code with HTML. Further more, you only need to write this once and it will work for all tags as opposed to having to specify the handler for each separately. Additional benefit is that every jQuery handler receives an event object that contains a lot of useful data - such as the source of the event, type of the event and so on making it much easier to write the kind of code you are after. Finally since it's jQuery you don't need to think about cross-browser stuff - a major benefit especially when dealing with events. A: Pass a reference to the element into the function when it is called: <area id="nose" onmouseover="zoom(this);" /> <script> function zoom(ele) { var id = ele.id; console.log('area element id = ' + id); } </script> A: I'm surprised that nobody has mentioned the use of this in the event handler. It works automatically in modern browsers and can be made to work in other browsers. If you use addEventListener or attachEvent to install your event handler, then you can make the value of this automatically be assigned to the object the created the event. Further, the user of programmatically installed event handlers allows you to separate javascript code from HTML which is often considered a good thing. Here's how you would do that in your code in plain javascript: Remove the onmouseover="zoom()" from your HTML and install the event handler in your javascript like this: // simplified utility function to register an event handler cross-browser function setEventHandler(obj, name, fn) { if (typeof obj == "string") { obj = document.getElementById(obj); } if (obj.addEventListener) { return(obj.addEventListener(name, fn)); } else if (obj.attachEvent) { return(obj.attachEvent("on" + name, function() {return(fn.call(obj));})); } } function zoom() { // you can use "this" here to refer to the object that caused the event // this here will refer to the calling object (which in this case is the <map>) console.log(this.id); document.getElementById("preview").src="http://photos.smugmug.com/photos/344290962_h6JjS-Ti.jpg"; } // register your event handler setEventHandler("nose", "mouseover", zoom); A: You can use 'this' in event handler: document.getElementById("preview").onmouseover = function() { alert(this.id); } Or pass event object to handler as follows: document.getElementById("preview").onmouseover = function(evt) { alert(evt.target.id); } It's recommended to use attachEvent(for IE < 9)/addEventListener(IE9 and other browsers) to attach events. Example above is for brevity. function myHandler(evt) { alert(evt.target.id); } var el = document.getElementById("preview"); if (el.addEventListener){ el.addEventListener('click', myHandler, false); } else if (el.attachEvent){ el.attachEvent('onclick', myHandler); } A: i also want this to happen , so just pass the id of the element in the called function and used in my js file : function copy(i,n) { var range = document.createRange(); range.selectNode(document.getElementById(i)); window.getSelection().removeAllRanges(); window.getSelection().addRange(range); document.execCommand('copy'); window.getSelection().removeAllRanges(); document.getElementById(n).value = "Copied"; } A: For others unexpectedly getting the Window element, a common pitfall: <a href="javascript:myfunction(this)">click here</a> which actually scopes this to the Window object. Instead: <a href="javascript:nop()" onclick="myfunction(this)">click here</a> passes the a object as expected. (nop() is just any empty function.) A: If you setup a listener like this: buttons = document.getElementsByClassName("btn-group") for(let i=0;i<buttons.length;i++){ buttons[i].addEventListener("click", (e) => { btnClicked(e);},false); } then you can get the id like this: function btnClicked(e){ console.log(e.target.id) } A: First Way: Send trigger element using this <button id="btn01" onClick="myFun(this)">B1</button> <button id="btn02" onClick="myFun(this)">B2</button> <button id="btn03" onClick="myFun(this)">B3</button> <script> function myFun(trigger_element) { // Get your element: var clicked_element = trigger_element alert(clicked_element.id + "Was clicked!!!"); } </script> This way send an object of type: HTMLElement and you get the element itself. you don't need to care if the element has an id or any other property. And it works by itself just fine. Second Way: Send trigger element id using this.id <button id="btn01" onClick="myFun(this.id)">B1</button> <button id="btn02" onClick="myFun(this.id)">B2</button> <button id="btn03" onClick="myFun(this.id)">B3</button> <script> function myFun(clicked_id) { // Get your element: var clicked_element = document.getElementById(clicked_id) alert(clicked_id + "Was clicked!!!"); } </script> This way send an object of type: String and you DO NOT get the element itself. So before use, you need to make sure that your element already has an id. You mustn't send the element id by yourself such as onClick="myFun(btn02)". it's not CLEAN CODE and it makes your code lose functionality. A: Let's say, you have a button like this: <button id="btn1" onclick="doSomething()">Do something</button> In the function, you can reach the id with this way: function doSomething() { let callerElementId = event.srcElement.id; console.log(callerElementId); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7627161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "89" }
Q: Mapping XML responses to data records ( Smartgwt) I have subclassed RestDatasource to create my own data source. This is the constructor to my Datasource public CustomDS (){ setDataProtocol(DSProtocol.POSTMESSAGE); setDataFormat(DSDataFormat.XML); DataSourceTextField firstNameField = new DataSourceTextField("firstName", "First Name"); DataSourceTextField lastNameField = new DataSourceTextField("lastName", "Last Name"); DataSourceTextField userIDField = new DataSourceTextField("id", "User ID"); setFields(firstNameField, lastNameField, userIDField); setXmlRecordXPath("/qm:GetResultsResponse/*"); XmlNamespaces ns = new XmlNamespaces(); ns.addNamespace("qm", "someurl"); setXmlNamespaces(ns); } This is the xml response <?xml version="1.0" encoding="UTF-8"?> <qm:GetResultsResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:qm="someurl" xmlns:warehouse="someurl"> <records xsi:type="warehouse:User" id="id1" firstName="fname1" lastName="Reddy"> <voiceUserProperties languageId="en-US"/> </records> <records xsi:type="warehouse:User" id="id2" firstName="fname3" lastName="Reddy"> <voiceUserProperties languageId="en-US"/> </records> <records xsi:type="warehouse:User" id="id3" firstName="fnam4" lastName="Reddy"> <voiceUserProperties languageId="en-US"/> </records> </qm:GetResultsResponse> QUESTION In the transformResponse() method , response.getDataAsRecordList().getLength() returns 3, But i cant seem to have the records filled out with the required attributes(ie firstName, id , lastName). Does anyone see anything wrong here ? EDIT: As suggested i changed the datasource to extend from DataSource and not RestDataSource. I still have this problem. If i remove xsi:type="warehouse:User" from the XML , this works fine. Any ideas on this ? A: If you're trying to parse a custom format like you've shown, don't subclass RestDataSource, subclass just DataSource. RestDataSource has a lot of settings on it specific to the message format it expects, which has a lot more structure than what you're trying to parse. .. now that you're using DataSource instead - if you can, get rid of the xsi:type declarations, as they are wasted bytes. However if you grab a nightly build (from smartclient.com/builds) you will see that these declarations are now ignored when processing XML unless the type refers to a particular DataSource that you've declared.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to get data from facebook graph api in jquery I am trying to get json data using facebook graph api through jquery. I am using the code below. I am trying to get json data using $.getJSON function but it displays this error in firebug NetworkError: 400 Bad Request - https://graph.facebook.com/me/home?access_token=mytoken here is my code <!DOCTYPE HTML> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"> </script> <script type="text/javascript" src="script/script.js"></script> <script> $(function(){ //$('fb').fbWall(); var url = "https://graph.facebook.com/me/home?access_token=mytoken"; var html = "<ul>"; $.getJSON(url, function(json){ //console.log(json); $.each(json.data, function(i,fb){ html += "<li>" + fb.id + "</li>"; }); }); html += "</ul>"; $('.fb').animate({opacity: 0}, 500, function() { $('.fb').html(html); }); $('.fb').animate({opacity:1}, 500); }); </script> <!-- <link type="text/css" rel="stylesheet" href="styles.css" /> --> <style> .fb { width: 400px; height: 400px; border:1px solid red; } </style> <title>title</title> </head> <body> <div class="fb"> </div> </body> </html> where am I making mistake? A: If you go to the URL you posted directly, it is returning the error: { "error": { "message": "(#606) Queries for multiple source_ids require a non-zero viewer that has granted read_stream permission", "type": "OAuthException" } } It means you need to prompt for read_stream permission to read the users feed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: New ASP.NET MVC project contains membership functionality but no database I created ASP.NET MVC 3 project and it has functionality to create users and login/logout. However I don't see a database that its trying to work with. I assumed that a mdf file would be added to App_Data folder but I don't see it there. When I try to register a user, it cannot find a sql server. Connection string in web.config has: <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI; AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" /> A: Ensure that you have SQL Server express installed on the machine. Beyond that your other option is to create a database in SQL Server and use the aspnet_regsql tool in the Framework folder to generate the tables needed to back the membership functionality. Once you have done that change your connection string to point to the correct SQL instance and you should be up and running no problem. A: I just setup a MVC3 project. If you run the application for the first time, and you click on login, then register a user, the application will create a sql express database in your App_Data folder called ASPNETDB.MDF. I'm pretty sure that you're going to need to have SQL Express installed and running for this feature to work automagically. If you don't want that to happen. You always create a database on your local SQL server install, run the Aspnet_regsql.exe tool against that database and create the asp.net membership tables there. All you would have to do after that is to change the web.config's connection string to point to the database that you just created. Good luck, and hope this information helps you some.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I replace the string exactly using gsub() I have a corpus: txt = "a patterned layer within a microelectronic pattern." I would like to replace the term "pattern" exactly by "form", I try to write a code: txt_replaced = gsub("pattern","form",txt) However, the responsed corpus in txt_replaced is: "a formed layer within a microelectronic form." As you can see, the term "patterned" is wrongly replaced by "formed" because parts of characteristics in "patterned" matched to "pattern". I would like to query that if I can replace the string exactly using gsub()? That is, only the term with exactly match should be replaced. I thirst for a responsed as below: "a patterned layer within a microelectronic form." Many thanks! A: As @koshke noted, a very similar question has been answered before (by me). ...But that was grep and this is gsub, so I'll answer it again: "\<" is an escape sequence for the beginning of a word, and ">" is the end. In R strings you need to double the backslashes, so: txt <- "a patterned layer within a microelectronic pattern." txt_replaced <- gsub("\\<pattern\\>","form",txt) txt_replaced # [1] "a patterned layer within a microelectronic form." Or, you could use \b instead of \< and \>. \b matches a word boundary so it can be used at both ends> txt_replaced <- gsub("\\bpattern\\b","form",txt) Also note that if you want to replace only ONE occurrence, you should use sub instead of gsub.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627170", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: C# MVC Send an email attachment of a print screen image This is for printing screen, using System.Drawing; using System.Drawing.Imaging; Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); Graphics graphics = Graphics.FromImage(printscreen as Image); graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size); printscreen.Save(@"filepath", ImageFormat.Jpeg); I tried putting this in my controller but it does not recognize Screen as anything. This is for attaching, System.Net.Mail.Attachment attachment; attachment = new System.Net.Mail.Attachment("you attachment file"); mMailMessage.Attachments.Add(attachment); Can I just add the filepath like this?: new System.Net.Mail.Attachment("filepath"); A: It's a Windows code and can run on WinForm not on client browser.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627173", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: NSSearchPathForDirectoriesInDomains explanation confused I have just been studying this code which checks if a file exists: NSString *path; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"SomeDirectory"]; path = [path stringByAppendingPathComponent:@"SomeFileName"]; if ([[NSFileManager defaultManager] fileExistsAtPath:path]) { but I'm a bit confused. by the following line: NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); Ok I Understand that the Method NSSearchPathForDirectoriesInDomains returns a path depending on the arguments which you pass into this method. But this user (whoever wrote the code) is blindly passing in a whole class! (refering to NSDocumentDirectory, NSUserDOmainMask). The only thing he pass correctly is the BOOL YES. I check the apple docs and it says this: NSSearchPathForDirectoriesInDomains Creates a list of directory search paths. NSArray * NSSearchPathForDirectoriesInDomains ( NSSearchPathDirectory directory, NSSearchPathDomainMask domainMask, BOOL expandTilde ); I have search for NSSearchPathDirectory and NSSearchPathDomainMask in apple docs and they suggest I have to pass a number This would suggest a number needs to be passed into the method? Can somebody explain that line please? thanks A: Read documentation of Foundation framework constants here: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html#//apple_ref/doc/c_ref/NSDocumentDirectory It's correct usage, because those are not classes but constants! NSSearchPathDomainMask Search path domain constants specifying base locations for the NSSearchPathDirectory type. enum { NSUserDomainMask = 1, //this one NSLocalDomainMask = 2, NSNetworkDomainMask = 4, NSSystemDomainMask = 8, NSAllDomainsMask = 0x0ffff, }; typedef NSUInteger NSSearchPathDomainMask; NSSearchPathDirectory These constants specify the location of a variety of directories. enum { NSApplicationDirectory = 1, NSDemoApplicationDirectory, NSDeveloperApplicationDirectory, NSAdminApplicationDirectory, NSLibraryDirectory, NSDeveloperDirectory, NSUserDirectory, NSDocumentationDirectory, NSDocumentDirectory, // this one NSCoreServiceDirectory, NSAutosavedInformationDirectory = 11, NSDesktopDirectory = 12, NSCachesDirectory = 13, NSApplicationSupportDirectory = 14, NSDownloadsDirectory = 15, NSInputMethodsDirectory = 16, NSMoviesDirectory = 17, NSMusicDirectory = 18, NSPicturesDirectory = 19, NSPrinterDescriptionDirectory = 20, NSSharedPublicDirectory = 21, NSPreferencePanesDirectory = 22, NSItemReplacementDirectory = 99, NSAllApplicationsDirectory = 100, NSAllLibrariesDirectory = 101 }; typedef NSUInteger NSSearchPathDirectory;
{ "language": "en", "url": "https://stackoverflow.com/questions/7627177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to prevent registration of DLL in the GAC I have a dll say DLLA(Version3) installed in GAC. When a lower version of the same dll ,say DLLA(version 2) is trying to install into GAC, I need to prevent it because there is already an higher version of the same in GAC. How do I do this? A: The GAC will manage multiple versions of the same DLL, this is not a problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I make a tooltip point at a specific label in C#? In my application I want to use a tooltip to point at a label to get the users attention: toolTip.IsBalloon = true; toolTip.Show("message", label1); The problem is that the balloon isn't pointing at the specified label. What should I do? A: This is a known bug. Try calling it twice for a hack work-around: toolTip.Show(string.Empty, label1, 0); toolTip.Show("message", label1); A: You can do something like this.. more specific (i.e) how much time the tool tip will be displayed... When MouseLeave public class MouseLeave { public void mouseLeave(Label label1, ToolTip ttpTemp) { ttpTemp.Hide(label1); } } when mouse enter public class MouseOver { public void mouseOver(Label label1, ToolTip ttpTemp) { ttpTemp.AutoPopDelay = 2000; ttpTemp.InitialDelay = 1000; ttpTemp.ReshowDelay = 500; ttpTemp.IsBalloon = true; ttpTemp.SetToolTip(label1, "Message1"); ttpTemp.Show("message1", label1,label1.width,label1.height/10,5000); } } A: Tooltip works with MouseHover and MouseLeft [just imagine in this way] If the mouse come over the Label, the tooltip will be displayed, when the mouse left, tooltip will dissappear. and the code should be: ToolTip t = new ToolTip(); t.IsBalloon = true; t.ToolTipTitle = "Title"; t.SetToolTip(label1, "Text"); just ToolTipTitle is optional :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7627185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Can you use a Where Clause in WPF - XAML Binding? I want to bind an image source to a List item, but I need the binding to select an image from the list based on an argument - select the image from the List based on a boolean value within the list. e.g. Images List has a number of fields: Images.Src Images.IsMainImage (True/False) etc. I want my Binding to select the image from the List, based on IsMainImage = True. Is it possible or can I only do this with a Converter? I was hoping there would be some sort of way to use LINQ in the Binding or something like that. A: All you can do is to use the converter or hide the items loaded into the ItemsControl using a trigger (it means they are present in the ItemsControl, but not visible) - it should not be a big deal if there aren't too many of the items. Maybe it would be possible to write a custom Binding class which would take a LINQ expression in string form, compile it ad use it to process the bound collection, but that would be colossal overkill. And would potentially lead to bad programming practices (coding more business logic into the XAML).
{ "language": "en", "url": "https://stackoverflow.com/questions/7627186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: count elements using javascript Possible Duplicate: JQuery - How do I count the number of elements selected by a selector? I know you can determine if an object exists using var nextfooter = $('footer.newcontent')[0]; but using the same sort of syntax could I return the number of elements found? A: Why not simply: var numberOfElements = $('elementSelector').length; Reference: * *length at the Mozilla Developer Center. A: You can use $('selector').length or $('selector').size() A: If you're using jQuery, you can retrieve the number of objects found using the size function: var nextfooter = $('footer.newcontent'); var count = nextfooter.size(); A: Code: var count = $('footer.newcontent').length; References: * *Calling the jQuery object: http://api.jquery.com/jQuery/ *Getting data from the jQuery result object: http://api.jquery.com/Types/#jQuery
{ "language": "en", "url": "https://stackoverflow.com/questions/7627190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Replacements for `target="_blank"`? I am using target="_blank" in most of google gadgets so that the link opens in a new window, rather than in small gadget space, but it is polluting the browser with windows and I am looking for a solution so that the window would open to the current browsing window (like normal browsing without extra window clutter. Please, note that "without-target-blank" the link opens to the small gadget space (not the goal) but to open to the browsing space. Any way to do that without target="_blank"? A: Sounds like you're trying to work around the default Google Gadgets behavior? Have you tried target="_top" A: You can also use Javascript like so to open in a new tab: <a href="http://www.link.com" onclick="window.open(this.href); return false;">LINK</a>
{ "language": "en", "url": "https://stackoverflow.com/questions/7627191", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Appending HTML Content with Attributes to a jQuery Selector I want to add DIV tags with attributes within a selected element. I understand that the normal way of inserting HTML content according to the jQuery website is to: $('#selected_element').append('<DIV id=' + A + '>{HTML CONTENT}</DIV>'); However, I also need to add mouse events on the DIV tags at the same time. I note that there is a way that looks like this: $('#selected_element').append($('<DIV>', { mouseover: function(){alert('mouseover');}, mouseout: function(){alert('mouseout');} })); How do I combine the two methods to add both content and attributes? A: var $div = $('<div>{content}</div>').attr('attrName', 'attrVal').hover( function() { alert('mouseover'); }, function() { alert('mouseout'); } ); $('#selected_element').append($div);
{ "language": "en", "url": "https://stackoverflow.com/questions/7627202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Strange behaviour while interating JSON array of objects using jQuery This is my sample JSON response: [{"id":11137,"name":"Agra"},{"id":11138,"name":"Albizzate"}] and i need to iterate each array object and print id and name: $.ajax({ url: '{{ path('ajax_provinces') }}', type: 'POST', dataType: 'json', data: {region_id: this.value}, success: function(provinces) {}, error: function() { alert("error"); }, complete: function(provinces) { $('select#regions ~ span > img').fadeOut('slow'); $.each(provinces, function(key, val) { alert(key + ": " + val); }); } }); The problem is i'm gettig strange results: function names, function bodies and other internal stuff from jQuery. It seems like it's iterating through jQuery library functions! Any clue what's going on? A: The problem is that the complete callback doesn't get passed the returned data as an argument: complete(jqXHR, textStatus) A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). (from the docs) Presumably the weird key/values you're seeing are the attributes of the jqXHR object. You need to handle the returned data in success, not complete. My understanding is that complete is generally used for actions that should happen regardless of whether the AJAX request successfully returned data (e.g. hiding a loading animation). A: You need to handle the returned data in success, not complete. Complete is used when you need to trigger a function after AJAX call is complete. On success you will get the data sent from server as success:function(data){ /// data is JSON object. Now iterate it here var i; for(i in data){ alert('the Id ='+data['id']+' the name '+data['name']); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7627209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Match and substitute whole visual range in vim I wanted to visually mark a few lines and then surround the whole range with <p> and </p>. After a lot of fiddling I have come up with this substitute command that seams to work: :'<,'>s/^\(\_.*\)\%V/<p>\1<\/p>/ Is there a better way of doing this or could someone explain why it works? \_. matches every characters including end-of-line. The ^ (start-of-line) and the \%V (match visual range) seams to behave strange. For example the documentation suggest that you use two \%V to surround your expression but that does not seams to be necessary. Using no \%V or having only one at the start matches the whole buffer. Removing the ^ causes the last line to be matched and substituted separately. A $ at the end seams to be unnecessary also. A: 1. Use surround vim You can use surround.vim, in visual mode: s<pEnter E.g. vat (visual select 'around' tag), s<p surround with <p>...</p> Breakdown: * *vat (visually select a tag; do any visual selection you wanted) *s< (surround with tag), in this case, p 2. Use ex commands with the range markers Edit: without surround you would be able to either :C-u'<iEnter<p>Esc :'>aEnter</p>Esc 3. Use yank and XML filetype plugin inserting register contents: Or much simpler: dO<p>1C-r"Esc Note that at 1 my XML filtetype plugin (I think it is default) automatically provided the closing tag (</p>) so we can just insert the yanked contents using C-r" --- without even leaving insert mode!
{ "language": "en", "url": "https://stackoverflow.com/questions/7627211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Facebook OAUTH2 and PHP/JSDK I have registered with auth.login in order to do an ajax call back to my server and update login counts. it doesnt work as the php sdk is resolutely refusing to see that the user is properly logged in. JS code: window.fbAsyncInit = function () { var channelurl='http://'+window.location.hostname+'/channel.html'; FB.init({ appId : window.appid, status: true, cookie: true, xfbml: true, channelURL : channelurl, // channel.html file oauth : true // enable OAuth 2.0 }); FB.Event.subscribe('auth.login', function (response) { $("#fbconnecttext").html("<a>Logging in...</v>"); $.ajax({ url: "fbupdatelogincount", type: "GET", cache: false, success: function (html) { window.setTimeout('$("#fbconnecttext").html("")', 10000); var rec = JSON.parse(html); window.numlogins = rec["numlogins"]; FB.api('/me', function (response) { if (window.numlogins > 1) { $("#fbconnecttext").html(window.welcomebacktext.replace("%s", response.first_name)); $("#fbadminimg").attr("src", "common-images/smiley"); } else { alert(window.firstlogintext.replace("%s", response.first_name)); } }); } }); }); FB.Event.subscribe('auth.logout', function (response) { $("#fbconnecttext").html(window.fbconnecttext); $("#fb-like").show(); FB.XFBML.parse($('#fb-like').is()); }); FB.Event.subscribe('auth.sessionChange', function (response) {}); }; (function(d){ var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;} js = d.createElement('script'); js.id = id; js.async = true; js.src = "http://connect.facebook.net/en_US/all.js"; d.getElementsByTagName('head')[0].appendChild(js); }(document)); } The php page require_once("utils.php"); logText("In fbUpdatelogincount"); if(fbAuthentication()){ logText("authenticated in fbUpdatelogincount"); $r=fbUpdateStats(); if(isset($_REQUEST["field"])) echo $r[$_REQUEST["field"]]; else echo json_encode($r); } echo ""; And finally the fbAutentication code: function fbAuthentication(){ global $facebook; $facebook = new Facebook(array( 'appId' => getSetting("fb:app_id"), 'secret' => getSetting("fb:secret") )); if($facebook->getUser()){ try { global $fb_isadmin,$fb_me; $fb_me = $facebook->api('/me'); $fb_isadmin=strstr(getSetting("fb:admins"),$facebook->getUser())!=false; fbUpdateStats(); return true; } catch (FacebookApiException $e) { /* exception handling todo */ } return true; }else logText("No Valid user"); return false; } The main issue is the ajax call firing up the url fbupdatelogincount but the PHP side saying "nope, no one is logged in". Any ideas? Same setup worked fine prior to 3.1.1 A: This doesn't seem to be documented anywhere, but it seems that passing the application secret to the auth.login event causes it to fire successfully. Try this: FB.Event.subscribe('auth.login', function(response) { // callback }, { secret:'<?php print $facebook->getApiSecret(); ?>' }); The original issue has since been fixed by Facebook. A: I finally found another solution : in my ajax call back I added the accesstoken as a GET parameter, decoded it at the php url and then called $facebook->setAccessToken($at). Works fine now. So it IS a bug in the new SDKs working together. What a day... ;) – FB.Event.subscribe('auth.authResponseChange', function (response) { FB.XFBML.parse(document.getElementById('fb-like')); if (response.authResponse) { FB.api('/me', function(response) { // $("#fbconnecttext").html('<a class="fbUserName">'+response.first_name+'</a>'); }); $.ajax({ url: "fbupdatelogincount?accesstoken="+response.authResponse.accessToken, type: "GET", success: function (html) { if (html) { var rec = JSON.parse(html); window.numlogins = rec["numlogins"]; FB.api('/me', function (response) { if (window.numlogins > 1) { $("#fbconnecttext").html(window.welcomebacktext.replace("%s", response.first_name)); $("#fbadminimg").attr("src", "common-images/smiley"); } else { alert(window.firstlogintext.replace("%s", response.first_name)); } }); } } }); }else{ //logged out } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7627212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: css rule inheritance in wicket parent-child pages I have a problem resolving css classes in wicket parent child pages. I have a wicket base page (BasePage) and a child page (ChildPage) extending BasePage. The div in BasePage is like, <div class="container-fluid"> <wicket:child/> </div> and in ChildPage <wicket:extend> <div class="sidebar"> .......... </div> </wicket:extend> in my base page css I have INCLUDED a css file in which there is a css rule like .container-fluid > .sidebar { float: left; width: 220px; } the div container-fluid is in BasePage and sidebar div in ChildPage. Bu the problem is after rendering the child page, it does not find the sidebar class and the page is not showing properly. But if you put the sidebar class css in ChildPage,it works. But if I have to put all child css specifically ,it will be a messy work in future where is a lot fo child page and the css will be redundant. any clue ? A: The BasePage/ChildPage relationship mostly exists in Java - when the final page is rendered, it should be rendered as a single entity. For example, if you were inserting your CSS via an IHeaderContributor, it would not make a difference if it were in the ChildPage or BasePage - it would get entered at the same point. The CSS you have is very restrictive. The > character implies a direct child (not a descendent). As Draevor indicated, Wicket inserts a lot of extra markup in Development Mode. It is generally not a good idea to mix restrictive CSS or Javascript with Wicket Components. Or, rather, be very careful about it. I wonder, perhaps the "extra" div that is inserted by Wicket is skipped when the CSS is inserted via the child page? That doesn't make sense, but it would be an interesting experiment. A: Have you looked at the source? Maybe there's some additional markup being inserted by wicket. To be on the safe side, simply remove the > from your CSS declaration and it should work even if you have something in between the divs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Falsy? How does the && operator cause a 0 to return 0 rather than NaN? I read that sometimes the && operator is used to "short circuit" JavaScript into believing that a return value of 0 is 0 and not NaN because 0 is a falsy number in JavaScript. I've been looking around to figure out what all this means. Can someone explain it to a layman? For example: function sign(number) { return number && number / Math.abs(number); } Will return 0 if number is 0. A: This sounds like an answer that I saw earlier, but cannot find now (a link would be helpful), but you've got the wrong end of the stick here. Given a situation like: foo = 0 ; bar = foo && 2 / foo; On line two, foo will be evaluated. It is 0 and therefore a false value. The left hand side of && (foo) will be returned and assigned to bar. Now if we have foo = 1: foo = 1 ; bar = foo && 2 / foo; Again, foo will be evaluated. It is a true value, so the right hand side of && will be evaluated and returned. 2 / foo is 2 so 2 is assigned to bar. "Short circuit" just means that as soon as part of && fails then it returns the part the failed without evaluating anything to the right. A: In JavaScript, the boolean operators && and || don't necessarily return a boolean. Instead, they look at the "truthiness" of their arguments and might short circuit accordingly. Some values like 0, the empty string "" and null are "falsy". Short circuiting just means skip the evaluation of the right hand side of an expression because the left hand side is enough to provide the answer. For example: an expression like var result = 100 / number; will give you NaN when number = 0, but: var result = number && 100 / number; Will give you 0 instead of a NaN since 0 is falsy. In a boolean context false && anything is false, so there's no point in evaluating the right hand side. Similarly: // supposed msg is a potentially empty string var message = msg || "No message"; Will give you msg if the string msg is not empty (truthy) since true || anything is true. If msg is empty, it gives you "No message instead". A: I think I understand what you mean, however, it's not. var some_bool = (func_a() && func_b()); Now, when func_a returns false, func_b indeed doesn't get called. However, when it returns NaN (which is, just like 0, equal to false) it still returns false!
{ "language": "en", "url": "https://stackoverflow.com/questions/7627224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Incorrect filename on WWW::Mechanize submission As far as I can read from the WWW::Mechanize documentation, you can do the following to submit a file from a string: $mech->submit_form( fields => { 'UploadedFile' => [[ undef, 'test2.txt', Content => $content ], 1], } ); This should submit a file with name text2.txt, containing the text in $content (in this case, 'The file is a lie.'). The request failed with an internal server error, however, so I examined the request that was sent, and found this: --xYzZY Content-Disposition: form-data; name="UploadedFile"; filename="ARRAY(0x9567570)" The file is a lie. --xYzZY That is clearly not the filename I specified, so I wonder: Am I doing something wrong, or is the module bugged? A: This is a bug in HTML::Form. I have reported it to the author. In the mean time, if you have HTML::Form version 6.00, you can fix things temporarily by commenting out line 1442 in HTML/Form.pm which reads $old = $self->file unless defined $old;
{ "language": "en", "url": "https://stackoverflow.com/questions/7627227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: XML parsing tool I need to make some XML manipulation within OpenStreetMap project. Input will be XAPI tag search result (XML file), which I can save and load locally. I need to extract a parameter from a tag in one file and save it as a differently named parameter of a differetly named tag in another file. The output can also be text only for copy&paste into RawEditor. For illustration a simplified samlpe input file: <?xml version='1.0' encoding='UTF-8'?> <osm version="0.6" generator="Osmosis SNAPSHOT-r26564"> <tag-to-be-ignored id="253657034" version="2"> <tag k="created_by" v="Merkaartor 0.12"/> </tag-to-be-ignored> <way id="86815694" version="2" timestamp="2010-11-28T09:35:28Z" uid="134948" user="alik" changeset="6476298"> <nd ref="952980925"/> <nd ref="953396365"/> <tag k="dibavod:id" v="416520000100"/> <tag k="source" v="dibavod"/> </way> <another-tag-to-be-ignored></another-tag-to-be-ignored> </osm> Desired output: <relation> <member type="way" ref="86815694" role=""/> <tag k="key" v="name"/> </relation> There are multiple "way" tags in input file all desired to be included in the output. There are also multiple tag (other than "way") to be ignored. Is there a Windows tool for this? If not, what would be the easiest way to code this as a standalone executable (command-line tool?) or a web script? I have some very limited programming skills. Thanks for help in advance! A: This is what XSLT and XQuery were made for.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How do compilers treat variable length arrays This might seem like a beginner's question, but I am interested in the way that a compiler normally creates arrays of variable-dimensions, like in the following program. #include<iostream> int main(){ int n; std::cin>>n; int a[n]; } From what I've learnt, in C all the initializer values must be constant, so that the compiler knows how much memory to reserve inside the function, normally by subtracting the stack pointer in order to accomodate the number of elements the array holds. This makes sense to me. However, I don't quite understand how compilers treat the above program, since it seems to work with G++(MinGW) , but fails with Cl, Microsoft's C++ compiler. I suspect that GCC allocates memory on the heap trough a non-standard extension, but I am not sure of this. Also, Microsoft's compiler is not renowned for being standards-compliant, so I wouldn't be surprised if it may actually be wrong in the way it treats the above program. A: There's absolutely no problem with "subtracting the stack pointer" at run-time, by a run-time value. And that is how the compilers normally implement variable-length arrays. They "subtract the stack pointer" at run-time, when the actual array size is already known. That's all there is to it. (There's no need to allocate memory on heap and I don't know what made you suspect this in GCC.). Such functionality was available long before VLAs became part of the language. The [non-standard] function alloca does exactly that. The only difference is that the memory allocated by alloca is automatically deallocated when the function exits, while the local VLAs must obey standard block-based lifetime rules. The latter is not a problem at all, since block nest in a stack-like fashion. In other words, for a run-time value n the declaration int a[n]; is essentially translated into something like int *a = alloca(n * sizeof *a); plus some extra household data to support the functionality of sizeof etc (and, of course, automatic restoration of the original stack pointer value at the end of the enclosing block). A: No version of C++ allows variable length array. Only C99 allows it. GCC allows it as an extension. A: int main(){ int n; std::cin>>n; int a[n]; } This is not legal C++. G++ accepts Variable Length Array's as an extension but VLAs are not part of the C++ standard. They are part of the C99 standard which GCC supports(I am not sure to what extent) but MSVC doesn't. A: In the C99 version of the C standard, variable length arrays are permitted. However, they are not permitted in any version of C++; you're seeing a G++ extension. Note that Microsoft's C compiler does not fully support C99; since G++ supports C99 it's easy enough to apply the VLA support to C++ as an extension. As to how the compiler usually implements VLAs, it's the same as alloca() (except that it has to keep the size around for sizeof) - the compiler saves the original stack pointer, then adjusts it down by however many bytes it calculates that it needs. The downside is function entry and exit is a bit more complicated as the compiler needs to store where to reset the stack pointer to rather than just adjusting by fixed constants.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: exception NoClassDefFoundError from deploy spring project with maven assembly i'm trying to build an executable jar with dependencies for a spring project. my pom: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.xxx</groupId> <artifactId>xxx</artifactId> <version>3.0.x-SNAPSHOT</version> </parent> <groupId>com.mindcite</groupId> <artifactId>mindcite-rdfizer-tool</artifactId> <version>3.0.4-SNAPSHOT</version> <packaging>jar</packaging> <name>compony :: project</name> <dependencies> <dependency> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.5.2</version> </dependency> </dependencies> <build> <sourceDirectory>src</sourceDirectory> <resources> <resource> <directory>conf</directory> </resource> </resources> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-eclipse-plugin</artifactId> <version>2.8</version> <configuration> <wtpversion>2.0</wtpversion> <buildcommands> <buildcommand>org.eclipse.jdt.core.javabuilder</buildcommand> <buildCommand> <name>org.eclipse.ajdt.core.ajbuilder</name> <arguments> <aspectPath>org.springframework.aspects</aspectPath> </arguments> </buildCommand> <buildCommand> <name>org.springframework.ide.eclipse.core.springbuilder</name> </buildCommand> </buildcommands> <additionalProjectnatures> <projectnature>org.eclipse.jdt.core.javanature</projectnature> <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature> </additionalProjectnatures> </configuration> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <artifactId>maven-assembly-plugin</artifactId> <executions> <execution> <id>make-assembly</id> <phase>package</phase> <goals> <goal>attached</goal> </goals> </execution> </executions> <configuration> <descriptors> <descriptor>assembly/package.xml</descriptor> </descriptors> </configuration> </plugin> </plugins> </build> </project> my assembly descriptor: <?xml version="1.0" encoding="UTF-8"?> <assembly> <id>full</id> <formats> <format>jar</format> </formats> <includeBaseDirectory>false</includeBaseDirectory> <dependencySets> <dependencySet> <unpack>false</unpack> <scope>runtime</scope> <outputDirectory>lib</outputDirectory> </dependencySet> </dependencySets> <fileSets> <fileSet> <directory>${project.build.outputDirectory}</directory> <outputDirectory>/</outputDirectory> <useDefaultExcludes>false</useDefaultExcludes> </fileSet> <fileSet> <directory>icons</directory> <outputDirectory>icons</outputDirectory> <includes> <include>**/*</include> </includes> </fileSet> <fileSet> <directory>conf</directory> <outputDirectory>conf</outputDirectory> <includes> <include>**/*</include> </includes> </fileSet> </fileSets> </assembly> when i run i get exception: Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/context/support/ClassPathXmlApplicationContext what am i doing wrong? i don't want maven to create a jar file with all the dependencies jar outside the lib folder. A: after playing with that for two days, the solution was: because i put all the dependencies jar in a lib file (in the assembly file) <dependencySets> <dependencySet> <unpack>false</unpack> <scope>runtime</scope> <outputDirectory>lib</outputDirectory> </dependencySet> </dependencySets> i needed to create the class path myself, in the pom file: <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <manifest> <mainClass>myMainclass</mainClass> <addClasspath>true</addClasspath> <classpathPrefix>lib/</classpathPrefix> </manifest> <manifestEntries> <Class-Path>conf/</Class-Path> </manifestEntries> </archive> </configuration> </plugin> A: Add spring-context dependency: <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>2.5.2</version> </dependency> You can also declare the spring version in the properties on top of pom.xml and reference it, such as: <properties> <spring.version>2.5.2</spring.version> </properties> And then use: <version>${spring.version}</version> A: Adi, You are missing org.springframework.context.support jar <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>2.5.2</version> </dependency> A: From the assembly descriptor you provided, you explicitly defining that, it should generate all dependency into lib/ folder. However, it is a very common way to put library jars into lib/ folder. And usually in that case, you will provide a simple script to start the program which include all the jars under lib/*.jar as classpath. There is one more alternative, you can generate MANIFEST with classpath defined inside. The exact solution is basically context dependent and most likely depends on how you would like to delivery the binary distribution. A: A ClassNotFoundException usually means that the class in question is not in the CLASSPATH. The class loader can't find it. You're assuming that something is in the CLASSPATH, but it's not. The solution is to check your assumptions and figure out how to make all the necessary classes available in the CLASSPATH at runtime.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Modifying Arduino code to read serial to control shift register I am needing to send a MIDI signal through the midi2serial converter. I am using THIS shift register, in order to control 32 individual LEDs. How do I modify the shift register code to accept the MIDI serial signal to light specific LEDs in the matrixs? I'm hoping to modify the code in http://arduino.cc/en/Tutorial/ShftOut12 to meet my needs. I'm confused about a) how the MIDI signal going into the MIDI-to-serial converter looks coming out the other end. (That is, does each MIDI message turn into an array, or what?) Each MIDI signal will be something like (144, 60, 124) and b) how do the shift register sketch respond to the MIDI signal? I need something like: if ( First bit = 144) { if (second bit = 60) { ...light LED #1... } if (second bit = 61) { ...light LED 2... } etc., etc. } A: May be try having the arduino send the raw serial data from the midi2serial to the computer, so you can check what it looks like (note it will be converted to ASCII if you use arduino serial monitor). then in the arduino use the Serial.Read command the read the serial into an array, then search through the array for 144, then use the shift register code to light(next byte value - 60).
{ "language": "en", "url": "https://stackoverflow.com/questions/7627245", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Retroactively remove commonly ignored files from Mercurial? I started a new project and did a half dozen local commits in Mercurial before I remembered to copy my .hgignore file into the working directory. So, now I have a bunch of binary and debug symbol files that I'd like to retroactively prune out. I haven't pushed this project to a remote, so I could just trash the hg folders and start over, that is an option. However is there some kind of extension to HG that reads .HgIgnore and prunes these files out of the changesets? A: You could run your repository through the convert extension and use the --filemap option to prune out files and directories that you have ignored in your hgignore file in the converted repository. That will preserve your history and you'll end up with a "clean" repository to carry on working with.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Java Generics in combination with interface inheritance I have a problem with generics in Java in combination with interface inheritance. Here is an exampe: public interface Type0 { } public interface Type1 extends Type0 { void method(); } public interface SomeInterface0<T extends Type0> { T get(); } public interface SomeInterface1<T extends Type1> extends SomeInterface0<T> { } Now, when I try to use field of type SomeInterface1 without type parameter java comiler treats type of SomeInterface1.get() method result as Type0. And can't compile something like this: ... SomeInterface1 si1; ... si1.get().method(); So, why SomeInterface1<T extends Type1> has a default vlue for T = Type0 ? A: When leaving out generic parameters, almost all of the generics logic is skipped. Determining the type of T will not be 'smart' and just look at the way T is defined within that class/interface. If you want to use the generics logic, you should provide generic parameters instead of leaving them out - they can still be very, well, 'generic': SomeInterface2<? extends Type1> si1; si1.get().method(); A: Since you're not using a type parameter when declaring the object of type SomeInteface1, the java compiler has no idea what actual class/interface it'll return when you invoke get(). The only thing that's certain is that it's an interface that extends Type0 (given the declaration of SomeInterface0). When you call get(), the compiler is checking the signature of the interface where get() is declared, so the only methods it knows can be called (without explicit type parameter being given), are the methods declared in Type0. Let me know if I was too confusing, I'll try to clear up the answer! :P
{ "language": "en", "url": "https://stackoverflow.com/questions/7627253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Best way to implement Failover Pattern for Java Clients We are designing a Java client (will be deployed on Tomcat, Windows 2008 R2) which needs to subscriber for some JMS topics on Sonic MQ. Client wants to have to redundancy for this Java client and at any point of time, only one subscriber should be subscribed for topics. Our requirement is similar to the this post. Is there's any standardized open source project which is built for this purpose or we have to write our own code to check the server health (time-consuming)? What's the best way to implement this Java Client. We are exploring the below technologies for consuming JMS messages: * *Spring Integration *Apache Camel Are we going in the right direction? We should be able to start/stop the subscriptions to the topics on fly. A: Apache Camel have something like this out of the box check this. It implements EAI Load Balancer pattern. You can choose "Failover" Policy. seems to be using Exception to decide which processor to go next. Other way to do can be to implement simple custom jms based hearbeats among subscribers to keep track of each other health and balance load or failover. Each Subscriber can keep track of what they are suppose to process. For example from the link you provided each subscriber knows the subject it is listening to and keep receiving hearbeat from other subscriber in case of heartbeat failure failover listener will start taking messages for failed listener. I think you can use JMS Message Selector to implement filters. A good reference to start with can be this old article on Javaworld.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to access database from Ubuntu Possible Duplicate: Import/Exporting databases from one machine to another I am on Ubuntu. I can access files (phpmyadmin folder) in xampp (I used it in Windows). What files do I need to copy from xampp or maybe there is .sql file somewhere, so I could copy database which was in Windows and use it on Ubuntu (I have already installed LAMP in Ubuntu). Thanks. A: it's this folder C:\xampp\mysql\data but as far as i know it won't work , the best this todo is to login to the windows and export it to .sql files
{ "language": "en", "url": "https://stackoverflow.com/questions/7627259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Why those different string formats on TimeSpan on XAML? I'm going crazy. Can someone explain me why these string formats formatting the same thing are so different? <DataGridTextColumn Header="Max Time" IsReadOnly="True" Binding="{Binding MaxTime, StringFormat=hh\\:mm\\:ss, TargetNullValue=---}"> <DataGridTextColumn Header="Min Time" IsReadOnly="True"> <DataGridTextColumn.Binding> <Binding Path="MinTime" StringFormat="{}{0:hh':'mm':'ss}" TargetNullValue=" --- "/> </DataGridTextColumn.Binding> </DataGridTextColumn> Of course each one do not work on the other. EDIT: The more I work with WPF the more I feel it's not a mature enought product. A: I'm no expert in formatting TimeSpan so I can't tell you exactly why they produce the same result but you can read up about it here: Custom TimeSpan Format Strings Of course each one do not work on the other. They do work the same way, the thing is just that you should use one backslash within the double quotes. The following <Binding Path="MinTime" StringFormat="hh\\:mm\\:ss" TargetNullValue=" --- "/> comes out to hh\\\\:mm\\\\:ss. So instead you should write <Binding Path="MinTime" StringFormat="hh\:mm\:ss" TargetNullValue=" --- "/> The following two Bindings should produce the same result <DataGridTextColumn Header="Max Time" IsReadOnly="True" Binding="{Binding Path=MaxTime, StringFormat=hh\\:mm\\:ss, TargetNullValue=' --- '}"/> <DataGridTextColumn Header="Min Time" IsReadOnly="True"> <DataGridTextColumn.Binding> <Binding Path="MinTime" StringFormat="hh\:mm\:ss" TargetNullValue=" --- "/> </DataGridTextColumn.Binding> </DataGridTextColumn> And so should the following two <DataGridTextColumn Header="Max Time" IsReadOnly="True" Binding="{Binding Path=MaxTime, StringFormat={}{0:hh':'mm':'ss}, TargetNullValue=' --- '}"/> <DataGridTextColumn Header="Min Time" IsReadOnly="True"> <DataGridTextColumn.Binding> <Binding Path="MinTime" StringFormat="{}{0:hh':'mm':'ss}" TargetNullValue=" --- "/> </DataGridTextColumn.Binding> </DataGridTextColumn>
{ "language": "en", "url": "https://stackoverflow.com/questions/7627261", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: DES Cryptography in C# I've been trying to find out the correct way to encrypt a byte[16] variable using DES algorithm. Here's the scenario: * *The data should be encrypted in 8-byte parts. the key for encryption is: byte[] {11, 11, 11, 11, 11, 11, 11, 11} *First 8 bytes is encrypted using Instance Vector = new byte[8] (8 bytes with 0 value). *the encrypted result will be the IV for the next 8 bytes. (is this CBC?) *that last 8 byte is the result I should send. With this information, I have implemented the Encrypt method as follows: public static byte[] Encrypt(byte[] data) { var dataChunk = new byte[8]; var IV = new byte[8]; var result = new byte[8]; var key = new byte[] { 11, 11, 11, 11, 11, 11, 11, 11 }; for (int counter = 0; counter < data.Length / 8; counter++) { // Copy the next 8-byte chunk. Array.Copy(data, counter * 8, dataChunk, 0, 8); var des = System.Security.Cryptography.DES.Create(); des.Key = key; des.IV = IV; des.Padding = PaddingMode.None; ICryptoTransform cryptoTransform = des.CreateEncryptor(key, IV); // Encrypt the datra chunk. cryptoTransform.TransformBlock(dataChunk, 0, 8, result, 0); // Set the new IV. Array.Copy(result, IV, 8); } return result; } Is this the correct way of encrypting data using DES cryptography? A: You don't need to create an encryptor for each block. The encryptor itself implements the operation modes (CBC, ...) and padding. So you need something like this: byte[] input = ... byte[] key = ... byte[] iv = ... using (DES des = DES.Create()) { des.Mode = CipherMode.CBC; des.Padding = PaddingMode.None; using (ICryptoTransform encryptor = des.CreateEncryptor(key , iv)) { byte[] output = encryptor.TransformFinalBlock(input, 0, input.Length); } } I'm omitting the warning of using DES here. You might also want to take a look at CryptoStream afterwards for an even easier en- and decryption ... A: I can't help you with the C#, but I can attempt to address your last question: whether this is the "correct way" to encrypt. Well, that answer depends on what you're expecting to do. What you've implemented is a mode known as CBC-MAC; it doesn't allow the receiver to recover the message (and hence it's not really "encryption" at all); one clue to this is that the message is 16 bytes, but the "encrypted" message is only 8 bytes. It does have the property that it is difficult for someone in the middle to modify the message and to come up with the correct 8 byte MAC value (assuming they don't have the key); hence, things like this are often used as cryptographically strong integrity checks. Now, CBC-MAC does have problems with length extension attacks; if you don't care about length extension attacks (all your messages are 16 bytes), this might not be important to you? Is CBC-MAC the right thing for your application? Well, I don't know the answer to that; the key questions for you: * *What are you trying to do? Are you trying to "encrypt" a message (so that the other side can recover it)? Or, are you trying to prove that the message was sent by someone with the key? *Are you trying to be compatible with someone else? Has that someone else specified this "encryption" method? *ortag decided to omit the warnings for DES, but I think I'll include them - DES can be broken with not totally unreasonable amounts of work; it's probably safe against your kid sister and maybe even joe average hacker, but if your adversary has access to a some computer resources, he can break this. If this is a concern, you'll want to switch to a stronger cipher, such as AES
{ "language": "en", "url": "https://stackoverflow.com/questions/7627266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use AS3 code with Haxe without any modification? I am going to use a lot of AS3 code in a Haxe project. I use latest version of Haxe. I really want to use it without any modification. Is there any standard way to do it? Any tools? A: You can compile your AS3 code to an SWC and then include the SWC in your Haxe project. A: There is also a very experimental AS3 to Haxe converter in the official Haxe repository: http://code.google.com/p/haxe/source/browse/#svn%2Fother%2Fas3hx
{ "language": "en", "url": "https://stackoverflow.com/questions/7627267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CakePHP Admin Panel and Front End I am new to CakePHP. These days, I create an application some like hotscripts. I need an admin panel for site manager to add new articles/apps and front end for public visitors. I am looking for a solution for this. I have alread made the router_prefix to admin. For example, in the CategoriesController. public function admin_add() { } public function view($id) { } As I know, this is one of the solution. In the CategoriesController, I set $this->Auth->allow('view'); so that visitors can visit this page without login. My question is, is this really a solution for admin and front product? Thanks in advance! public $components = array( 'Auth' => array( 'authorize' => 'controller', 'loginRedirect' => array( 'admin' => true, 'controller' => 'dashboards', 'action' => 'index', ), 'loginError' => 'Invalid account specified', 'authError' => 'No Permission', ), Thank you Anh Pham!!! I followed your suggestion and add this code to AppController. I now have no idea what is admin param means in loginRedirect? Could you explain this to me? A: is this really a solution for admin and front product? Yes, you will have to put $this->Auth->allow('view'); in beforeFilter, and remember to call the app controller beforeFilter also (most likely you set the Auth setting there). So it'll look like this: function beforeFilter() { parent::beforeFilter(); $this->Auth->allow('view'); } Edit: the 'admin' there is the prefix: it means after the login, it will redirect to yoursite.com/admin/dashboards. If you don't set admin=>true, it will redirect to yoursite.com/dashboards. It's just a common practice to use prefix for group-based access control. (Later on, if you have more than 1 group of logged-in user: admin, sub-admin, and so on, you'll need to set Auth to restrict the access level; but it's pretty simple). A: I would suggest you look into Croogo. It's a CMS built on CakePHP.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: multiple submit buttons and css tabpanel I have a ASP.NET Ajax web query form which is made of 4 tab panels. Each of these panels have its own textbox and Submit button so that it can perform a particular query against the database. E.g. one is searching data by Month, another by Name... When a form only contains ONE submit button, if user hit the Enter key from within the textbox, the postback is fired and all is well. But when there are multiple submit buttons, how can I control which one is "On" and which textbox is to be taken in account. I mean when user click on the actual Submit button all is fine (again!). But Enter key confuses the page. Ideally, I would like to add a CSS class to each button, and when a particular panel is on display, this class will be set "active" by means of javascript global variable. Is there a better way? Does one have any working sample? A: On load, try setting the Submit Button's Enabled property equal to the Panel's Visibility property. Button1.Enabled = Panel1.Visible; Button2.Enabled = Panel2.Visible; Button3.Enabled = Panel3.Visible; Button4.Enabled = Panel4.Visible; That way only one button at a time is enabled.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to populate a ListBox with external API response? I am making a request to an API, the only option I get is async get response var r = (HttpWebRequest)WebRequest.Create(url); r.BeginGetResponse(new AsyncCallback(ResponseMethod), state); So, I built everything I need to get the data, and it is working. But the data is received in a different thread. My ListBox is bound to StreamItems that exists in my MainViewModel. public ObservableCollection<StreamItemViewModel> StreamItems { get; private set; } But I am in a different thread, so I cannot directly access this property to add new values to it. When I try: StreamItems.Add(new StreamItemViewModel { Content = responseContent }); I get: UnauthorizedAccessException - Invalid cross-thread access. How can I add values that I got from the request? A: You have to do this on the UI thread - for that you can use Dispatcher.BeginInvoke(): Dispatcher.BeginInvoke(() => { StreamItems.Add(new StreamItemViewModel { Content = responseContent }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7627278", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Overlapping event areas I got a square component inside a canvas which when clicked shows a glow effect-indicating selection-while clicking somewhere else this effect is removed-indicating deselection The problem is that the canvas always dispatches the "deselect" event, even if the mouse if over the square. I worked around this by defining a circumstantial function which removes the child's width,height from the parent's "clickable" area. Is there a better way to tell the canvas to dispatch his event only if not over the child ? Explanatory image A: Hard to tell without any code, but my guess is, you should stop propagation of the click event in the listener for the square component: event.stopPropagation(); That way, the stage will not be notified of the click on the square and may not send your "deselect" event.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Eclipse: Refactoring-renaming GWT uibinder java bean does not rename template ui.xml file When using Eclipse Google plugin, when you create a gwt uibinder pair, you get a java bean file and its corresponding .ui.xml template file. I believe I used to be able to do this in Eclipse Helios: Right-click on the java bean of a uibinder set, refactor to rename it, I could config the refactor dialog to also rename the .ui.xml template file. Recently, I have been using Eclipse 3.7.0 and latest GPE. I am no longer able to do that. May be I forgot how to do it. Somebody please remind me how - thanks. e.g. rename the uibinder pair Hello.java, Hello.ui.xml to Bello.java, Bello.ui.xml Perhaps, it had never been possible in the first place and I had remembered wrongly. A: I've not noticed that capability, and I just tried it out, and renaming either the java or the ui.xml leaves you with an error until you rename the other file. Note that it isn't a given that the file.java code is mapped to file.ui.xml, since the design could use @UiTemplate to link file.java to somethingelse.ui.xml. That might be the reason for this not to work. Changing a ui.xml file name automatically like that could cause a big cascade of changes. But there is some refactoring. What the refactoring is capable of doing it tracking changes to @UiField names. If I rename (using Alt-R) a field in my file.java file that has been annotated with @UiField, the ui:field in the ui.xml file is changed as well. Now here's a tricky bit. Let's say I have foo.java, foo.ui.xml, and foo2.java, with foo2.java using the foo.ui.xml UI template (via the @UiTemplate annotation). The ui.xml file has a Button call bar, so each of foo.java and foo2.java have @UiField("bar") Button bar. Follow me so far? In Eclipse, I open foo.java, and using Alt-R I change bar to baz. The ui.xml file has its ui:field="bar" changed to ui:field="baz", and all annotations within foo.java that reference bar (such as @UiField and @UiHandler) are updated to reference baz. But the code in foo2.java is not changed, and there is now an error I need to fix. foo2.java still expects to see a button called bar inside of foo.ui.xml. Similarly, if I open foo2.java, and using Alt-R I change bar to baz, the ui:field="bar" in foo.ui.xml is not changed, and you now have an error. Not sure if any of this is documented somewhere. Maybe you vaguely remembered this refactoring.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why this source code doesn't work in Grails 1.3.7? I'm a novice in Grails and I came across this question. And I thought of testing this link as one of the answer suggest. I downloaded it and when I ran the grails app, I get an error message stating that the version is low and I need to upgrade it. And I did the same using grails upgrade command. After doing this also, when I run the code I get a big error like this : at groovy.lang.MetaClassImpl.invokeMethodOnGroovyObject(MetaClassImpl.java:1123) at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1017) at groovy.lang.ExpandoMetaClass.invokeMethod(ExpandoMetaClass.java:1070) at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:886) at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:66) at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:44) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:153) at _GrailsRun_groovy$_run_closure5.doCall(_GrailsRun_groovy:149) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:266) at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:51) at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:44) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:149) at _GrailsRun_groovy$_run_closure5.call(_GrailsRun_groovy) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90) at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233) at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1058) at groovy.lang.ExpandoMetaClass.invokeMethod(ExpandoMetaClass.java:1070) at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:886) at groovy.lang.MetaClassImpl.invokePropertyOrMissing(MetaClassImpl.java:1104) at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1060) at groovy.lang.ExpandoMetaClass.invokeMethod(ExpandoMetaClass.java:1070) at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:886) at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:66) at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:44) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:149) at _GrailsRun_groovy.runInline(_GrailsRun_groovy:116) at _GrailsRun_groovy.this$4$runInline(_GrailsRun_groovy) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90) at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233) at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1058) at groovy.lang.ExpandoMetaClass.invokeMethod(ExpandoMetaClass.java:1070) at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:886) at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1003) at groovy.lang.ExpandoMetaClass.invokeMethod(ExpandoMetaClass.java:1070) at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:886) at groovy.lang.DelegatingMetaClass.invokeMethod(DelegatingMetaClass.java:149) at org.codehaus.gant.GantMetaClass.invokeMethod(GantMetaClass.java:127) at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:66) at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:44) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:161) at _GrailsRun_groovy$_run_closure1.doCall(_GrailsRun_groovy:59) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90) at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233) at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1058) at groovy.lang.ExpandoMetaClass.invokeMethod(ExpandoMetaClass.java:1070) at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:886) at groovy.lang.DelegatingMetaClass.invokeMethod(DelegatingMetaClass.java:149) at org.codehaus.gant.GantMetaClass.invokeMethod(GantMetaClass.java:127) at groovy.lang.Closure.call(Closure.java:282) at groovy.lang.Closure.call(Closure.java:295) at sun.reflect.GeneratedMethodAccessor52.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90) at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233) at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1058) at groovy.lang.ExpandoMetaClass.invokeMethod(ExpandoMetaClass.java:1070) at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:886) at groovy.lang.DelegatingMetaClass.invokeMethod(DelegatingMetaClass.java:149) at org.codehaus.gant.GantMetaClass.invokeMethod(GantMetaClass.java:127) at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:39) at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:40) at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:54) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:124) at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16_closure18.doCall(GantBinding.groovy:185) at sun.reflect.GeneratedMethodAccessor66.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSite.invoke(PogoMetaMethodSite.java:225) at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:51) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:149) at org.codehaus.gant.GantBinding$_initializeGantBinding_closure5_closure16_closure18.doCall(GantBinding.groovy) at sun.reflect.GeneratedMethodAccessor65.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90) at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233) at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1058) at groovy.lang.ExpandoMetaClass.invokeMethod(ExpandoMetaClass.java:1070) at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:886) at groovy.lang.Closure.call(Closure.java:282) at groovy.lang.Closure.call(Closure.java:277) And this error message continues. I don't know whether the source code has an error in it. Since a novice in Grails I couldn't figure out what this error message states. Can anyone explain me this. And where I went wrong? Thanks in advance. A: You left out the top part of the stacktrace, so it's hard to know what's going on since what you're showing is fairly generic. Regardless, since the code hasn't been updated in over three years and is running a very old version of Grails (1.0.1), simply running grails upgrade won't do much, even if it doesn't fail like you saw. There are too many important changes between 1.0.1 and 1.3.7. If you do want to play with that code you should contact the author. But keep in mind that he doesn't even use gravl himself anymore - he recently switched to WordPress.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting items in GridView after it's been bound I have a UserControl AutomatedFeedGridView.ascx which is essentially a GridView. It has a public property Category which is passed in on the page using the control. The problem I have is that I want to filter based on a dropdown list on the calling page. Below is the codebehind for the AutomatedFeedGridView control: // The feed category public Feeds.FeedCategory Category { get; set; } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { List<AutomatedFeed> x = Feeds.GetAutomatedFeed(Category); gvAutomatedFeed.DataSource = x; gvAutomatedFeed.DataBind(); } else { List<AutomatedFeed> x = (List<AutomatedFeed>)gvAutomatedFeedCategory.DataSource; foreach (AutomatedFeed y in x) { // if condition is not met, hide y } } So on the first load, the GridView is bound to a List of AutomatedFeed objects. On any subsequent calls (caused by a postback on the page containing the control) I want to run some code to filter out some of the items in the GridView. The problem is this line: List<AutomatedFeed> x = (List<AutomatedFeed>)gvAutomatedFeedCategory.DataSource; I've tried all of the solutions here but none of them seem to work, I always get an Object reference not set to an instance error. Am I missing something or am I doing this in completely the wrong way? I know I could easily just make another call to Feeds.GetAutomatedFeed(Category) but there must be a better way to do it than to make another stored procedure call? A: you can store data source in session as Session["x"] = x ; when page post back retrieve it back as List<AutomatedFeed> x = List<AutomatedFeed>)Session["x"]; UPDATE: DataSource property will be null unless you explicitly re-assign and re-bind it on every postback. You could use Session, Cache, or ViewState to keep the DataSource. But it will take more memory. A: The control is only generated and populated after the page.load, so it will not contain any data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using contains on a String in Java I have a string called trips. In this string there are 3 values chosen by the enemy player. I want the buttons which equals one of those values to change their color. for(int i = 0; i <=Lobby.baanlengte;i++){ if ((trips.contains(Speler1[i].getActionCommand()))) { System.out.println("Trips bevat"+i); Speler1[i].setBackground(Color.gray); } } Say the string trips is 3,11,14, I want the buttons 3, 11 and 14 to change their color. These buttons actually change but 1 and 4 also change since these numbers are in 11 and 14, which is not what I want. If anyone knows how to solve this, I would appreciate that. A: You should first split the input string using the delimiter ,, then compare each part using a .equals comparison. A: Don't use a String as a container of other Strings. Use a java.util.Set<String>: Set<String> trips = new HashSet<String>(); // ... if (trips.contains(Speler1[i].getActionCommand())) { System.out.println("Trips bevat"+i); Speler1[i].setBackground(Color.gray); } This will have additional advantages: * *it will avoid duplicates in the set of players *it will allow you to add and remove players from the set easily Note: variables in Java should always start with a lower-case letter. A: Split the string up to array see documentation: http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#split(java.lang.String) String trips_array[] = trips.split(","); for(int i = 0; i < trips_array.length; i++){ Speler1[i].setBackground(Color.gray); } A: Solved this. The String had some blank spaces. After replacing them with nothing everything worked as it should work. Thanks for the help :) String trips is for example [ 13, 14, 16]. trips = trips.replace("[", " "); trips = trips.replace("]", " "); trips = trips.replace(" ", ""); String parts[] = trips.split(","); for(int i = 0; i <= Lobby.baanlengte; i++){ for (String item : parts){ if(item.equals(Speler1[i].getActionCommand())){ Speler1[i].setBackground(Color.gray); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7627305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error 324 Empty_response only on free webhost with fpassthru, readfile, file_get_contents i'm a little confused. $l = $_REQUEST['l']; $arr = get_headers($l); foreach($arr as $a => $b){ if($a == "6"){ $r = str_replace('Location: ', '', $b); } } readfile($r); this code works fine on my local apche server but when i try it on a free web host (000webhost) i get an empty response. even when i echo a random string it doesn't give a response until i remove the readfile. i have also tried replacing the readfile with file get contents as well as the combination of fopen and fpassthru. ideas? A: It seems like the readfile() functionality is currently disabled on the web host you're using, try using another host which support this functionality or you better ask the free host support team to activate this functionality.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I set a value in memcache to expire at a specific time? I have a google app engine apps (created using python). I want to add a value to memcache but would like for the value to expire every midnight (PST) How do I do this? A: You can set an item's expiration time either as absolute epoch time, or as a relative time-to-expire of up to one month. See http://code.google.com/appengine/docs/python/memcache/functions.html There's a second alternative. If you have a set of known keys that you'd like to expire at a given time each day, use a cron job.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: When installing a custom Visual Studio template, do you have to install the interop stuff? I want to install a custom project template with my tool. The template uses a Wizard, so I'm including an assembly and putting it into the GAC on the target machine. Now, this assembly has lots of dependencies like Interop.IWshRuntimeLibrary.dll, EnvDTE, and such. Should I redistribute these assemblies, or I can be sure the target machine can find them? A: No, you should not redistribute EnvDTE at least since this would be illegal. Look in the redist.txt file under the directory where Visual Studio is installed for a list of microsoft files that you are allowed to redistribute. EnvDTE is always available on a machine with Visual Studio installed. When it comes to Interop.IWshRuntimeLibrary.dll I don't exactly know what it is, but I think that youmay be allowed to redistribute automatically generated interops, but probably not the DLL it "wraps". Found a post about this here. Also worth checking is what the redistributable MSI that comes with the VS SDK contains, since you may redistribute this MSI and install it as part of your program.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: More storage in a Firefox addon with Add-on SDK I want to develop an addon with the addon builder. I read that with simple storage one can have about 5 megabytes for his addon, but 5 mgb won't do it for my app. I need more. What could I do? A: You cannot do much given the Add-on SDK API. Instead you could break out of the sandbox and create a file in user's profile directory (see File I/O code snippets). E.g. something along these lines to read the file myData.txt from user's profile: var {Cu, components} = require("chrome"); var {FileUtils} = Cu.import("resource://gre/modules/FileUtils.jsm"); var {NetUtils} = Cu.import("resource://gre/modules/NetUtil.jsm"); var file = FileUtils.getFile("ProfD", ["myData.txt"]); NetUtil.asyncFetch(file, function(inputStream, status) { if (!components.isSuccessCode(status)) { // Handle error! return; } // The file data is contained within inputStream. // You can read it into a string with var data = NetUtil.readInputStreamToString(inputStream, inputStream.available()); console.log(data); }); Note that the unusual syntax to import modules is due to bug 683217.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Delegate call is very slow in ipad app I have a view composed of two table views (custom split view) divided by a splitter image. When a user clicks an item on the right view, a modal view pops up and the user edits some values. Once he clicks submit, the edited values must be updated in the respective columns of the table views, on both sides, after a backend web service acknowlegdes success. I call a delegate method on the custom split view to do the update. The delegate call is very slow, so that I have an activity indicator placed on the table view, but it is not coming on screen during refresh. The updated data comes up properly after some time. If I comment the fetch code, the activity indicator likewise comes up after a while. So obviously the delegate call is very slow. The user gets confused if we don't show any activity happening in the screen during table reload. * *Why is the activity indicator added to table views not getting displayed? *Is there any better approach than what I did so that the user knows some operation is happening in the background so that he can wait? A: Don't wait in the delegate. That will block the UI and the activity indicator. Return from the delegate method immediately, and use another asynchronous networking callback to finish the update of your tableview element.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: LDAP: error code 49 - cannot bind the principalDn I'm a newbie to ApacheDS.I just created a new partition in ApcheDS. When i try to register my connection factory i get above error..(with OracleAQ ) My code is; // ldap settings env.put(Context.INITIAL_CONTEXT_FACTORY, AQjmsConstants.INIT_CTX_FACTORY); env.put(Context.PROVIDER_URL, "ldap://localhost:10389/"); env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system,dc=acme,dc=com"); env.put(Context.SECURITY_CREDENTIALS, "secret"); env.put(Context.SECURITY_AUTHENTICATION, "simple"); My LDIF file looks like; dn: dc=acme,dc=com objectClass: organization objectClass: dcObject objectClass: top dc: acme o: Acme,Inc dn: cn=OracleContext,dc=acme,dc=com objectClass: orclContext objectClass: top cn: OracleContext dn: cn=db1,cn=OracleContext,dc=acme,dc=com objectClass: orclContext objectClass: top cn: db1 dn: cn=OracleDBConnections,cn=db1,cn=OracleContext,dc=acme,dc=com objectClass: orclContext objectClass: top cn: OracleDBConnections dn: cn=OracleDBQueue,cn=db1,cn=OracleContext,dc=acme,dc=com objectClass: orclContext objectClass: top cn: OracleDBQueue What is the wrong with my connection parameters? any help would be appreciate? Thanks, A: Change the bind DN to uid=admin,ou=system instead of uid=admin,ou=system,dc=acme,dc=com (this DN is invalid as per your current server data) A: The issue was, i haven't created a user entry for that particular new partition..I solved it now..
{ "language": "en", "url": "https://stackoverflow.com/questions/7627317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: PHP RegEx match string with random number at end Currently learning PHP with RegEx and I want to extract the DAX value from a website. Got the website source with file_get_contents and then cleaned up the tags with strip_tags. The block that contains the string i want is this one: Dax5.502-2,4% but i just need the value 5.502 The regex code I have so far is '/@Dax\d.\d\d\d[+-]\d,\d[%]$/' But it doesnt work. can anyone tell me how to do this correctly. Thanks :) A: "/Dax(.*)-/" your result will be the number A: /^Dax([0-9].[0-9]{3})/ With that (which is all you need), your result will be the number. A: You do not need to use a regular expression to parse the formatted string, sscanfDocs looks like a more fitting way to parse the float value (Demo): $str = 'Dax5.502-2,4%'; sscanf($str, 'Dax%f', $value); echo $value; # 5.502
{ "language": "en", "url": "https://stackoverflow.com/questions/7627318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 2 class instances, 1 line If I have two PHP classes Rappers and Rockers, is this the best way to create an instance of both? $musicians = new Rappers() && new Rockers(); Update: More specific as to how I wanted to use this is to instantiate another class along with the Hybrid framework which is wrapped entirely in a class called Hybrid. This line would be inside a WordPress theme's functions.php file: $theme = new Hybrid() && new Response(); A: $musicians = array(new Rappers(), new Rockers()); or $rappers = new Rappers(); $rockers = new Rockers(); A: The best way would be: $rappers = new Rappers; $rockers = new Rockers; You can't assign multiple class instances to a single variable it just doesn't make sense A: This is not possible in PHP, as it doesn't support multiple inheritance. If you're talking about a collection of both, you can simply add objects of both classes to an array. PHP is not a strictly typed language. A: You can do this if one line code is what you want list($rappers,$rockers) = array(new Rappers(),new Rockers()); or $mussicians = array(new Rappers(),new Rockers()); list($rappers,$rockers) = $mussicians; A: You can do this on one of your class: class Rappers extends Rockers then $musicians = new Rappers(); I hope this answer helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7627323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Can't stop recording? Possible Duplicate: Stop Recording and Context I can't understand what's wrong ?!!! When the phone rings then recording starts. But when the call ends I get NullPointerException, because MediRecorder is null, but recording is still going until I shut the window with an error. My problem the same as this Sound Recorder Widget doesnt stop recording public class Call extends BroadcastReceiver { private MediaRecorder mRecorder; public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); if(null == bundle) return; String state = bundle.getString(TelephonyManager.EXTRA_STATE); if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING)) { mRecorder = new MediaRecorder(); mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); mRecorder.setOutputFile("/sdcard/Record.3gp";); mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); try {mRecorder.prepare();} catch (IOException e){} mRecorder.start(); // if I stop recording here, then everything is fine /* try {Thread.sleep(300000);} catch (InterruptedException e) {e.printStackTrace();} mRecorder.stop(); mRecorder.release(); mRecorder = null; */ } if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_IDLE)) { if(mRecorder != null) // But this always false. if I remove this condition - { mRecorder.stop(); // - then here NullPointerException mRecorder.release(); mRecorder = null; } } } } LogCat: 10-01 07:13:28.054: ERROR/AndroidRuntime(553): Uncaught handler: thread main exiting due to uncaught exception 10-01 07:13:29.134: ERROR/AndroidRuntime(553): java.lang.RuntimeException: Unable to start receiver xxx.xxx.xxx.Call: java.lang.NullPointerException 10-01 07:13:29.134: ERROR/AndroidRuntime(553): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2646) 10-01 07:13:29.134: ERROR/AndroidRuntime(553): at android.app.ActivityThread.access$3100(ActivityThread.java:119) 10-01 07:13:29.134: ERROR/AndroidRuntime(553): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1913) 10-01 07:13:29.134: ERROR/AndroidRuntime(553): at android.os.Handler.dispatchMessage(Handler.java:99) 10-01 07:13:29.134: ERROR/AndroidRuntime(553): at android.os.Looper.loop(Looper.java:123) 10-01 07:13:29.134: ERROR/AndroidRuntime(553): at android.app.ActivityThread.main(ActivityThread.java:4363) 10-01 07:13:29.134: ERROR/AndroidRuntime(553): at java.lang.reflect.Method.invokeNative(Native Method) 10-01 07:13:29.134: ERROR/AndroidRuntime(553): at java.lang.reflect.Method.invoke(Method.java:521) 10-01 07:13:29.134: ERROR/AndroidRuntime(553): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860) 10-01 07:13:29.134: ERROR/AndroidRuntime(553): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 10-01 07:13:29.134: ERROR/AndroidRuntime(553): at dalvik.system.NativeStart.main(Native Method) 10-01 07:13:29.134: ERROR/AndroidRuntime(553): Caused by: java.lang.NullPointerException 10-01 07:13:29.134: ERROR/AndroidRuntime(553): at xxx.xxx.xxx.Call.onReceive(Call.java:49) 10-01 07:13:29.134: ERROR/AndroidRuntime(553): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2637) 10-01 07:13:29.134: ERROR/AndroidRuntime(553): ... 10 more 10-01 07:13:33.184: ERROR/audio_input(31): unsupported parameter: x-pvmf/media-input-node/cap-config-interface;valtype=key_specific_value 10-01 07:13:33.184: ERROR/audio_input(31): VerifyAndSetParameter failed A: You're declaring a new instance of a MediaRecorder object in your "if phone is ringing" statement using the same name as your class MediaRecorder object, which is then lost as soon as you leave the scope of that if statement. Simply remove the MediaRecorder declaration in front of the line MediaRecorder mRecorder = new MediaRecorder(); and you should be good to go. A: The problem is you are instantiating a new MediaRecorder inside your if statement which is masking the MediaRecorder mRecorder class member. So Change: if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING)) { MediaRecorder mRecorder = new MediaRecorder(); ..... } to this: if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING)) { mRecorder = new MediaRecorder(); ..... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7627327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: exec-maven-plugin not detecting class in src/main/java I have a project that fails with: Caused by: java.lang.ClassNotFoundException: app.Main at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:283) at java.lang.Thread.run(Unknown Source) It's not detecting anything in src/main/java relative to the pom file. This is in Eclipse. Please help with this. I truly have no clue why it is behaving like this. Other projects execute fine. It throws the same error regardless of any class specified in app or without a package. A: There are no classes in src/main/java. Those go in target/classes. You need to compile before running exec:java: mvn compile exec:java -Dexec.mainClass=app.Main
{ "language": "en", "url": "https://stackoverflow.com/questions/7627328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Remove image background with Javascript/jQuery I came across this site http://skincity.se/sv/product/1198/md-formulations-vit-a-plus-hand-body-creme and wanted to copy the way they have removed the background color from the product images. How do they do it? It seems they are doing it on the frontend, since all images are with white background color... A: I thought you were right about JavaScript, until I tried disabling it and refreshing the page - if you try that, you'll find that the effect remains. It's actually some CSS trickery. The grayish background is actually above the image - it has a black background with an opacity of 0.08. It appears to be a gray background, when in fact it is a semi-transparent foreground. Hope that helps! A: They are placing a semi-transparent overlay overtop the image. See their CSS: #primary-image-node-overlay { background-color: black; opacity: 0.08; filter: alpha(opacity = 8) !important; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7627329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: FileExists() returns false, even if file exists I want to check if a dll in System32 directory (Windows 7) exists. But even if it exists, FileExists() returns false. LoadLibrary returns a valid handle. In this case, I only want to check, if the files exists and visualize this information. Do you have a any tips to solve this? A: Most likely this is down to file redirection. You have a 64 bit machine but from the 32 Delphi process, Windows\system32 actually redirects to Windows\Syswow64. So when you think you are asking for the existence of a file in Windows\system32, the system is actually reporting the existance (or otherwise) of a file in Windows\Syswow64. If you really do need to see into the true 64 bit system32 then you need to disable file redirection. You can do this with the Wow64DisableWow64FsRedirection() function. Don't forget to switch it back on with Wow64RevertWow64FsRedirection(). Beware that disabling the redirector has wide reaching effects and can result in very strange behaviour so do so with care. A: You are almost certainly not specifying the full or valid relative path of the file in your FileExists call. LoadLibrary will search certain locations (those where dlls are expected to reside) for you, but FileExists will not. Supply the complete and correct path and FileExists will work correctly. A: Not much information to go on, the code you are using might help, but could this be a 64 bit issue and that the dll is actually in the SysWOW64 folder? See here for a good description of the how this works. A: This is the most ridiculous reason, but if it can help just one person... Make sure you didn't accidentally name the file something.dll.dll. I just had a situation where I installed an application on a clients computer, and then the application couldn't find config.txt located in the same directory. This had been working fine on other computers, so of course I was stumped. Turns out the "show file extensions" setting was turned off on this clients computer, and the file had actually been named config.txt.txt... in my defence, I spend 90% of the time on OSx, and 9.99% on my own Windows system, with "show file extensions" enabled since ages ago.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: OpenSSL memory BIO and partial cipher blocks I'm using OpenSSL in an architecture which requires me to perform encryption and decryption locally. The decryption function gets a buffer which was encrypted on the other side of the connection. The encryption/decryption process usually works fine, but for the case where the buffer contains a partial cipher block. I guess my issue boils down to this: Let s be an SSL object and buf be a memory buffer or encrypted data. What I do in order to decrypt it (minus error handling, thread safety, memory safety, etc.) is along the lines of int decDataBufSize = 1000000; //approximation of length of decrypted data int8_t* decData = (int8_t*)malloc(decDataBufSize*sizeof(int8_t)); //room for the decrypted data to be written into BIO* bio = BIO_new_mem_buf(encData, decDataBufSize); //set up BIO pointing to the encrypted data int decDataLength; BIO_set_close(bio, BIO_NOCLOSE); //This means OpenSSL doesn't try to free the encrypted data buffer int totalDecData = 0; for(int remaining_length = buffie->getBuffer()->limit() ; remaining_length > 0 ; ) { SSL_set_bio(ssl, bio, bio); remaining_length -= BIO_pending(bio); int decDataLength = SSL_read(ssl, decData + totalDecData, decDataBufSize - totalDecData); totalDecData += decDataLength; remaining_length += BIO_pending(bio); } return decData; This seems to be working fine but for the case where I have a part of a block in the buffer. I know that, had I worked with a socket instead of a memory BIO, I'd get an SSL_ERROR_WANT_READ, but in my case I get a most laconic SSL_ERROR_SSL (decryption failed or bad record mac). Is there any way I could verify in advance that I have a full block? Thanks in advance A: Apparently the solution lies in BIO_get_mem_data. Something along the lines of: #define DEC_BUF_SIZE 1000000 static int buffer_length; static int8_t* partial_block; int8_t* decrypt(int8_t* ecnData) { int decDataBufSize = 1000000; //approximation of length of decrypted data int8_t* decData = (int8_t*)malloc(decDataBufSize*sizeof(int8_t)); //room for the decrypted data to be written into if (buffer_length == 0) /*prepend the contents of partial_block to encData somehow*/; BIO* bio = BIO_new_mem_buf(encData, decDataBufSize); //set up BIO pointing to the encrypted data int decDataLength; BIO_set_close(bio, BIO_NOCLOSE); //This means OpenSSL doesn't try to free the encrypted data buffer int totalDecData = 0; for(int remaining_length = buffie->getBuffer()->limit() ; remaining_length > 0 ; ) { buffer_length = BIO_get_mem_data(bio,&partial_block); SSL_set_bio(ssl, bio, bio); remaining_length -= BIO_pending(bio); int decDataLength = SSL_read(ssl, decData + totalDecData, decDataBufSize - totalDecData); totalDecData += decDataLength; remaining_length += BIO_pending(bio); } return decData; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7627333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to generate thumbnail images from a PDF file with JQuery / ASP.Net MVC I am working on project that allows the user to upload pdf files , store them in SQL Database , manipulate them (Comment, Highlight, Bookmark, Draw, Copy Text/Table/Image)and generate the files from HTML Pages . To do the work , I chose to work using iTextSharp, it makes the work easier. Back to the file uploaded ,I worked on the file uploading part , I have developed the work using ASP.Net MVC, and It works very well, but I want to add some features buy making the files uploaded appear like docs on the page using thumbnails of every doc. I wonder to know How can I generate thumbnails for pdf and add them to ASP.Net MVC . I tried out this API , but it's not work very well with ASP.Net MVC http://www.tallcomponents.com/pdfthumbnail-overview.aspx I find this code using JQuery that generate thumbnails from images that are already uploaded , this code is part of long code . I thought about using this script by adding another function that generates Images from PDF files , then using this code to making Popup thumbnails from the last image . $(".ImagePopLink").click(function(e) { e.preventDefault(); var $ID = $(this).html(); var $imagebase = $("#hidImageBase").val(); var $imagesource = $imagebase + "?ID=" + $ID; var $imagelink = "<img style=\"width: 400px\" src=\"" + $imagesource + "\" />"; $("#divImg").html($imagelink); $("#divImg").load(); $("#PopWindow").css({ "left": $.mouseX(e), "top": $.mouseY(e) + 5 }); $("#PopWindow").show(); }); $("#Close").click(function(e) { e.preventDefault(); $("#PopWindow").css({ "left": "0px", "top": "0px" }); $("#PopWindow").hide(); }); A: A couple of years ago I had to do the same thing and solved everything with Aspose PDF for .Net. By that time it was nothing compared to what it is now and I was able to do exactly what you want, so my guessing is that by now it is even more powerful. The only problem is that it's not free, but it is not so expensive either. Check it out, or Download their trial version. Good luck! Hanlet
{ "language": "en", "url": "https://stackoverflow.com/questions/7627335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Self-destructing class containing a window I've created a print preview class, PPREVIEW, containing a print preview window, which is supposed to popup over my app's main window, while disabling it. When user closes preview window, it is supposed to enable main window and destroy PPREVIEW object. I'd like to use it in the following way: PPREVIEW *p=new PPREVIEW; //next, preview window is created, user interaction begins p->ShowPreview(<parameters>); //but this function returns delete p; Since ShowPreview does return, the above line would destroy object while window is still visible. If it was a modal dialog box, this would be possible, since DialogBox function doesn't return at that point. I thought i could put "delete this" somewhere upon destruction of the print preview window. Naturally WM_DESTROY comes to mind. But MSDN states at http://msdn.microsoft.com/en-us/library/windows/desktop/ms632620%28v=vs.85%29.aspx the following: "it can be assumed that during processing of WM_DESTROY child windows still exist", so there's still possibility some of them will refer to instance's variables (and they do, i was getting random access violation errors when i tried that, so i backed out). Currently i've opted to: - create some global variable, - in WM_DESTROY of print preview window i put EnableWindow(MainWindow, TRUE) and set that global variable to FALSE. - Then, upon main window's WM_ENABLE event i'm testing global variable for FALSE and deleting object. But this is quite unelegant and requires that i program this behavior for every window that uses print preview, so i decided to pursue previous approach, which is: create, use, possibly self-delete. I need either: - information when exactly could i use "delete this" in PPREVIEW window procedure, if this approach isn't unwise for some reason i am unaware of - an idea how to make ShowPreview method to not return, mimicking DialogBox behavior. - other suggestions that achieve my goal Please assist. A: * *Your ShowPreview function should call ShowWindow() to show the preview window. It should also do whatever is needed to the main form, e.g. disabling it. *When your preview window receives WM_CLOSE it should delete the C++ object that wraps it. Some part of this process also needs to call DestroyWindow() on the underlying window handle. The default handling of WM_CLOSE would do this, but perhaps you would want this in the C++ object's destructor. A: If you want ShowPreview to be modal, you'll need to run a sub-message-loop. You can find some examples here, including a reverse-engineered version of what DialogBox uses internally. Alternately, you can simply have the WM_DESTROY of the preview window both re-enable the main window and delete your PPREVIEW * (in which case ShowPreview won't be modal, but it will be self-contained). You have to be careful here not to touch the PPREVIEW * (or, from within PPREVIEW's member functions, not to call any other members or access any member variables) after the DestroyWindow() call though - this in particular means you cannot access member variables in your message handler after the DefWindowProc() call
{ "language": "en", "url": "https://stackoverflow.com/questions/7627338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In Javascript, how to explain 0 == "" returning true? Possible Duplicate: Why is 0 == “” true in JavaScript The following is done in Firebug: >>> 0 == "" true >>> "" == false true But how did the "" get converted to 0? I think the reason they both returned true was that "" gets converted to 0, and in the first case, it becames 0 == 0, and in the second case, first to "" == 0 and then 0 == 0 and so both cases returned true, but how did "" get converted into 0? The Javascript Definitive Guide says the string is converted to a number, but how specifically?
{ "language": "en", "url": "https://stackoverflow.com/questions/7627342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android: Edittext- get current line In an edittext is there a method for getting the current line of the cursor? If not I will write my own method, but just wanted to check. If I do write my own method would the best method be to go through every character in the edittext until selectionstart and count the number of \n's using a For loop, or is there a better way? Thanks! A: I can't find a simple way to get this information either, so your approach seems about right. Don't forget to check for the case where getSelectionStart() returns 0. You can make the code reusable by putting it in a static utility method, like this: private int getCurrentCursorLine(Editable editable) { int selectionStartPos = Selection.getSelectionStart(editable); if (selectionStartPos < 0) { // There is no selection, so return -1 like getSelectionStart() does when there is no seleciton. return -1; } String preSelectionStartText = editable.toString().substring(0, selectionStartPos); return countOccurrences(preSelectionStartText, '\n'); } The countOccurrences() method is from this question, but you should use one of the better answers to that question (e.g. StringUtils.countMatches() from commons lang) if feasible. I have a full working example that demonstrates this method, so let me know if you need more help. Hope this helps! A: Just to let people know: There is a better way to do this then Doug Paul has suggested by using the getLineForOffset(selection): public int getCurrentCursorLine(EditText editText) { int selectionStart = Selection.getSelectionStart(editText.getText()); Layout layout = editText.getLayout(); if (!(selectionStart == -1)) { return layout.getLineForOffset(selectionStart); } return -1; } A: find the last index of "\n"using method lastindex=String.lastindexof("\n") then get a substring using method String.substring(lstindex,string.length).and you will get the last line in two lines of code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Prevent a using-statement from happening I want to have a custom view mode, to show online user text and not online user some other text. But I want to do it like the Html.BeginForm(), in a using statement. I have made a class witch can write text at the start of the using and text, but I cant get it to stop the text in the {} from happening. @using (AuthorizedContent(Html, "Adminstrator")) { <text>Only the administrator should see this</text> } with public static Test AuthorizedContent(this HtmlHelper helper, String roleName) { return null; var test = new Test(helper); return test; } public class Test : IDisposable { private HtmlHelper _helper; public Test(HtmlHelper helper) { _helper = helper; this.StartTag(); } public void StartTag() { var writer = _helper.ViewContext.Writer; writer.Write("Hello"); } public void EndTag() { var writer = _helper.ViewContext.Writer; writer.Write("Hello"); } void IDisposable.Dispose() { this.EndTag(); } } A: You cannot prevent the body of the using from rendering in a Razor page. If you want to prevent something from rendering use an if condition: @if (AuthorizedContent(Html, "Adminstrator")) { <text>Only the administrator should see this</text> } or looking at the name of this method maybe you are trying to reinvent something that already exists: @if (User.IsInRole("Adminstrator")) { <text>Only the administrator should see this</text> }
{ "language": "en", "url": "https://stackoverflow.com/questions/7627349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iphone dealloc property I run the analyse build on Xcode, and get a warning for a leak because of an object that is a property and instance var .h UIView *_transparentView; } @property (nonatomic, retain) UIView *transparentView; .m @synthesize transparentView = _transparentView; self.transparentView = [[UIView alloc] initWithFrame:transparentViewFrame]; - (void)dealloc { [_transparentView release]; so I release the ivar on dealloc, but how to release the property?, [self.transparentview release] ?? A: As Tom has answered replace the line that assigns the "transparentView" with: self.transparentView = [[[UIView alloc] initWithFrame:transparentViewFrame] autorelease]; when you any value to a retained property you should you should release the assigned value if you are done with it, and release the property when deallocating the class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mvc3 - how do i trigger framework validation prior to submission so that it also displays error messages for required fields? I have a form that is used like a wizard using JQuery. The only problem I have is that the user can click the next button to go to the next wizard step but the validation does not capture any required fields unless a user has edited the data. So, if you just click next, it does not pick up the errors or show any error messages. If i put a value in the input field and then remove it, an error is shown prior to submission. How can I force the framweork validation to execute and find required fields that have not been touched? Thanks A: On the click of the "next button" simply call the Validate method of jquery validation plugin. (assuming you are using unobtrusive validation of mvc)
{ "language": "en", "url": "https://stackoverflow.com/questions/7627355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to convert Cloudera Hadoop "vbox" VMDK to VirtualBox VDI Hi guys : I am trying to run the Cloudera Hadoop VM in Virtual box. * *First, I noted that the download is a .vmdk file. Of course, this suffix is for VMWare, so that was a bit odd. *Luckily, I found a tutorial on how to convert the cloudera vmdk into a virtual box file here : http://www.ubuntugeek.com/howto-convert-vmware-image-to-virtualbox-image.html. However, when I tried to convert the vmdk file to a virtual box file by using convertdd, and ultimately got a message that "Failed to write to disk image "cdh.vdi" VERR_DISK_FULL" *So my question is , how do you run the Cloudera Hadoop VM in vbox ? I found a site http://www.facebook.com/note.php?note_id=108313592002 here, but it does not appear to work (this site suggests loading the VMDK image as a new hard disk, but "new" hard disks are not enabled in my fresh virtual box install). I only get "remove" and "refresh" options in my VBox disk manager. OUTPUT FROM VBOX CONVERTING TO CDH ~/Development$ VBoxManage convertdd /tmp/vh.bin cdh.vdi Converting from raw image file="/tmp/vh.bin" to file="cdh.vdi"... Creating dynamic image with size 5475663872 bytes (5222MB)... VBoxManage: error: Failed to write to disk image "cdh.vdi": VERR_DISK_FULL :~/Development$ ls A: * *VBox supports VMDK since v2.0 AFAIR. *VBox UI of Virtual Media Manager changed in 4.0 version, so there is no direct option of adding hard disk in Virtual Media Manager (there used to be one -- strange decision in my opinion). Although, you can create a new virtual machine in Virtualbox, and in the stage of choosing disk, choose existing one (VMDK) so you don't need to convert VMDK to VDI (there is a dropdown, but besides, also a button to choose a hard disk file not listed yet in Virtual Media Manager. A: Here is a guide from Cloudera themselves: http://www.cloudera.com/blog/2009/07/cloudera-training-vm-virtualbox/ A: I created a new VM using Red Hat 64b. Chose existing drive and opened the vmdk file. Gave it 2G Ram and it started up fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Gui - JPanel adding JComponent into GridLayout cell I'm trying to display a frame using GridLayout, but one of my panels isn't displaying. The JPanel that I'm having trouble with (gridPanel) is supposed to have a 50 by 50 GridLayout and each cell in that grid is supposed to have a Square object added to it. Then that panel is supposed to be added to the frame, but it doesn't display. import java.awt.*; import javax.swing.*; public class Gui extends JFrame{ JPanel buttonPanel, populationPanel, velocityPanel, gridPanel; JButton setupButton, stepButton, goButton; JLabel populationLabel, velocityLabel; JSlider populationSlider, velocitySlider; Square [] [] square; public Gui() { setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); //Set up JButtons buttonPanel = new JPanel(); setupButton = new JButton("Setup"); stepButton = new JButton("Step"); goButton = new JButton("Go"); buttonPanel.add(setupButton); buttonPanel.add(stepButton); buttonPanel.add(goButton); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 1; c.gridwidth = 2; //2 columns wide add(buttonPanel, c); //Set up populationPanel populationPanel = new JPanel(); populationLabel = new JLabel("Population"); populationSlider = new JSlider(JSlider.HORIZONTAL,0, 200, 1); populationPanel.add(populationLabel); populationPanel.add(populationSlider); c.fill = GridBagConstraints.LAST_LINE_END; c.gridx = 0; c.gridy = 2; c.gridwidth = 2; //2 columns wide add(populationPanel, c); //Set up velocityPanel velocityPanel = new JPanel(); velocityLabel = new JLabel(" Velocity"); velocitySlider = new JSlider(JSlider.HORIZONTAL,0, 200, 1); velocityPanel.add(velocityLabel); velocityPanel.add(velocitySlider); c.fill = GridBagConstraints.LAST_LINE_END; c.gridx = 0; c.gridy = 3; c.gridwidth = 2; //2 columns wide add(velocityPanel, c); //Set up gridPanel JPanel gridPanel = new JPanel(new GridLayout(50, 50)); square = new Square[50][50]; for(int i = 0; i < 50; i++){ for(int j = 0; j < 50; j++){ square[i][j] = new Square(); gridPanel.add(square[i][j]); } } c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; c.gridwidth = 2; //2 columns wide add(gridPanel, c); } /** * Create the GUI and show it. For thread safety, * this method should be invoked from the * event-dispatching thread. */ private static void createAndShowGUI() { //Create and set up the window. Gui frame = new Gui(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Display the window. frame.pack(); frame.setVisible(true); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } } Square class import java.awt.*; import javax.swing.*; public class Square extends JComponent{ public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.BLACK); g.fillRect(10, 10, 10, 10); } } A: The reason you are not seeing anything are two-fold (though not entirely sure if the second is intentional, guessing on that part :) * *JComponent is a bare-bone container, it has no ui delegate and no inherent size - it's up to your code to return something reasonable for min/max/pref *the painting rect is hard-coded to "somewhere" inside, which might or might be inside the actual component area Following is showing (border just to see the boundaries) public static class Square extends JComponent { public Square() { setBorder(BorderFactory.createLineBorder(Color.RED)); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.BLACK); g.fillRect(0, 0, getWidth(), getHeight()); } @Override public Dimension getPreferredSize() { return new Dimension(10, 10); } @Override public Dimension getMaximumSize() { return getPreferredSize(); } @Override public Dimension getMinimumSize() { return getPreferredSize(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7627368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Programmatically added UI items order next to each other There is a UIScrollView and I'd like to programmatically put subviews in it. It's ok, but how can I lay automatically the subviews next to each other? Thanks in advance! A: The position of the subviews is dictated by their frame property. So you need to set their frames such that they line up next to each other. If they are all the same size you can do with some simple math and CGRectMake(). If they will have different sizes, you can use CGRectDivide() to break a large rect into smaller rects. CGRectInset() is also useful, in case you want some padding between them. A: You can't. The view hierarchy in UIKit--like the view hierarchy in most UI frameworks--uses explicit layout. Your comment asks about HTML-like floating; the box model stuff that HTML/CSS uses was designed to serve a very different goal (flowing document layout) than what UIKit is for, and so there's no real analogy in the framework. UIViews do support automatic re-layout on resize/frame change of the parent view (you can say whether a subview should resize, how, and where it should be "pinned" to), through the autoresizing mask property, but I don't think that's what you're asking for. You could, if you were inclined, build a set of methods, perhaps as a category on UIView, that let you add subviews that had their frame origins adjusted automatically based on existing subviews.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: re-order alphabet sorting in Perl I am trying to fix sorting in Armenian alphabet, because all standard Unix tools and programming languages sort letters and words as a result for only 1 of the 2 major dialects (Western). Translating this into technical problem is to re-order one of the chars "ւ", to put it in different place among letters, let's say to make it the last character so that words are ordered correctly for the order dialect (Eastern). Linguistically speaking in Eastern dialect this "ւ" symbol is not written "standalone" but is a part of letter that's written with 2 chars "ու". Current sorting puts letter "ու" behind "ոք" or "ոփ" 2-letter constructs. Basically, it should be totally similar if you wanted to make e. g. letter "v" be on place of letter "z" in Latin alphabet. I am trying to use something like #!/usr/bin/perl -w use strict; my (@sortd, @unsortd, $char_u, $char_x); #@unsortd = qw(աբասի ապուշ ապրուստ թուր թովիչ թոշակ թոք); @unsortd = qw(ու ոց ոք ոփ); @sortd = sort { $char_u = "ւ"; $char_x = split(//, @unsortd); if ($char_u gt $char_x) { 1; } else { return $a cmp $b; } } @unsortd; print "@sortd\n"; but that does not scale for whole words, just 2 letter forms are fixed. UPDATE: I was able to solve this using tr function to map letters to numbers as shown in Perlmonks A: You should have a look at the Unicode::Collate::Locale module if you haven't done so already. use Unicode::Collate::Locale; my $collator = Unicode::Collate::Locale->new(locale => "hy"); @sortd = $collator->sort(@unsortd); print join("\n", @sortd, ''); This prints: ու ոց ոք ոփ (I'm not sure this is the output you're expecting, but that module and Unicode::Collate has quite a lot of information, it might be easier to create a custom collation for your needs based on that rather than rolling your own.) A: For standard alphabets Unicode::Collate::Locale as suggested by @mat should be the first choice. On the other hand, if you have very specific needs `index' can be used as follows. To sort single characters (note that missing characters would be first): my $alphabet_A = "acb"; sub by_A {index($alphabet_A,$a) <=> index($alphabet_A,$b)}; ... my @sorted = sort by_A @unsorted; For words, one can include a loop in the definition of by_A. For the following to work define the function min() and fine-tune the case of words of different lengths: sub by_A { $flag=0; foreach my $i (0..min(length($a),length($b))-1) { return ($flag) if ($flag); $flag = ($flag or index($alphabet_A,substr($a,$i,1)) <=> index($alphabet_A,substr($b,$i,1))); } return $flag; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7627371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can I make a custom pygtk tooltip stay on when the cursor is over it? Please look at the following snippet : import gtk def callback(widget, x, y, keyboard_mode, tooltip): hbox = gtk.HBox(False, 8) button = gtk.Button('Exit Tooltip') label = gtk.Label('Tooltip text') hbox.pack_start(label) hbox.pack_start(button) hbox.show_all() tooltip.set_custom(hbox) return True label = gtk.Label('Test label') label.set_has_tooltip(True) label.connect('query-tooltip', callback) Here I've created a custom tooltip with a close button in it. Now I want it to stay until i click that close button. Searching google was not that helpful. besides I would also like to know the signals/events that are emitted when a tooltip is being closed. Similar problems are handled smoothly for JQuery/JavaScript/Ajax tooltips etc. but for gtk/pygtk there is no luck :( Thanks in advance ... A: I had this issue as well, and as far as I know, there isn't any way to determine how long a tooltip stays up. What I did (and recommend to you) is that you make your own "tooltip" and set it's background color to yellow, or whatever color you want, via an eventbox. Make sure you don't show it yet. This is just a simplified code, as you will need to position and size this in your project yourself. color = gtk.gdk.rgb_get_colormap().alloc_color('black') ebTooltip = gtk.EventBox() btnTooltip = gtk.Button("Close") ebTooltip.add(btnTooltip) ebTooltip.modify_bg(gtk.STATE_NORMAL, color) Now, you just need to hide and show this eventbox via your callbacks. To show it, call... ebTooltip.show() And, to hide it (probably on the "clicked" event of your close button)... ebTooltip.hide() Hope that solves your issue!
{ "language": "en", "url": "https://stackoverflow.com/questions/7627372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: No mouse-scrolling in Pane objects? The following Pane object does not scroll when the mouse wheel is used. Does anyone experience the same behaviour? Is it the default behaviour? Any idea why? Could it be platform-specific? CreateDialog[Pane[Column[Range[30]], {300, 200}, Scrollbars -> True]] My platform: Win7-64, Mathematica 8.0.1 A: An alternative solution: Needs["GUIKit`"] ref = GUIRun[ Widget["Panel", { Widget["ScrollPane", { "viewportView" -> Widget["List", { "visibleRowCount" -> 4, "items" -> Script[Range[30]] }] }] }] ]; The problem with Pane is that the MouseWheel event is not bound, as it is in GUIKit. Using this technique you could also do Bind["MouseWheel" ...] to any other action.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Difference between prefix/postfix increment in Objective-C method call? I understand the difference between prefix and postfix notation in plain C. I was, however, wondering if the same rules applied to Objective-C method calls like [myObject foo:++i]; and [myObject foo:i++]; Or is the "inner C expression" always evaluated first, the two method calls thus yielding the same result? A: Yes, the same rules apply. Obj-c is a strict superset of c so all things that work in c will work the exact same in Objective-c. ++i Will increment i before the method is called so those 2 methods will not yield the same result (assuming, or course, that the result depends on the value of i). One is called after i is incremented, the other is called before. A: Why not actually try it and find out? The result is as would be expected the prefix version operates before the method call. The postfix operates after the method call. A: it's the same as C. ObjC is a superset of C.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Trying to get property of non-object php error Possible Duplicate: Call to a member function on a non-object - works localhost but not online don't know how to solve this problem, it's basic but can't find a solution. I use two files: connect.php and user.php. in connect.php is a Connect class: class Connect{ var $logged; function login($username, $password){ ..more code.. if($pass==$password){ $this->logged=true; // db connection is fine, this works // checked it with echo $this->logged; } } } and when i call it from another file, user.php like this: $user=new Connect; $user->login(); echo $user->logged; // ERROR Trying to get property of non-object Why is this code not working, but it works offline (locally)??? A: You've got a couple of problems: * *When you call $user->login, PHP is assuming you're accessing an object property, not the function; you need $user->login() (note the ()), which will call the method. *Your example is missing a }. Demo: <?php class Connect{ var $logged; function login($username, $password){ $pass = 'test'; if($pass == $password){ $this->logged = true; } } } $user = new Connect; $user->login('test','test'); print_r($user); ?> http://codepad.org/AVw0k9sY Outputs: Connect Object ( [logged] => 1 ) 1 is what true prints. A: To access a class property from outside the class, you need to declare it as 'public': class Connect{ public $logged;
{ "language": "en", "url": "https://stackoverflow.com/questions/7627380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Use external button for rich:fileUpload I'm using the component rich:fileUpload for uploading files to my server the problem is that those files go along with a form that the user fills, so I wanna use one external button for doing this. The user select the files to upload, fill the form and then click a "Submit" button at the bottom of the page. This upload the file with the form. I've tried it like this: I'm able to hide the button inside the panel of fileUpload so the user don't click on it. <rich:fileUpload id="fileUploadId" style="width: 100%; height: 130px;" fileUploadListener="#{documentsBean.listener}" maxFilesQuantity="1" uploadButtonClass="display-none" uploadButtonClassDisabled="display-none"> </rich:fileUpload> And what I've tried with the button is <a4j: commandButton id="uploadFormButton" value="Attach" onclick="#{rich:component('fileUploadId')}.submitForm();" oncomplete="#{rich:component('fileUploadId')}.clear(); return false;"/> But it doesn't work. A: I don't know if there is a way to do exactly what you want, but here is another solution you can use : <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:rich="http://richfaces.org/rich" xmlns:a4j="http://richfaces.org/a4j" xmlns:st="http://spectotechnologies.com/jsf" xmlns:t="http://myfaces.apache.org/tomahawk"> ... <h:form enctype="multipart/form-data"> ... your fields ... <t:inputFileUpload value="#{bean.document}" /> <h:commandButton value="Submit" actionListener="#{bean.onButtonSubmitClick}" /> </h:form> </html> and the bean : @ManagedBean @RequestScoped public class Bean { private UploadedFile m_oDocument; public void setDocument(UploadedFile p_oDocument) { m_oDocument = p_oDocument; } @UploadedFileNotEmpty @UploadedFileSize(max="10000000") @UploadedFileExtension(accept="doc,docx,pdf,txt,rtf,xls,xlsx,zip,rar,jpg,jpeg,jpe,bmp,gif,png,csv,ppt,pptx,odp,pic,odt,ods") public UploadedFile getDocument() { return m_oDocument; } public void onButtonSubmitClick(ActionEvent p_oEvent) { ... } } Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7627385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Weird dispatch_async memory behavior I have the following dispatch_async code: dispatch_async(openGLESContextQueue, ^{ [(EAGLView *)self.view setFramebuffer]; // Replace the implementation of this method to do your own custom drawing. static const GLfloat squareVertices[] = { -0.5f, -0.33f, 0.5f, -0.33f, -0.5f, 0.33f, 0.5f, 0.33f, }; static const GLubyte squareColors[] = { 127, 127, 0, 127, 0, 255, 255, 255, 0, 0, 0, 0, 255, 0, 255, 255, }; static float transY = 0.0f; glClearColor(0.5f, 0.5f, 0.5f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.0f, (GLfloat)(sinf(transY)/2.0f), 0.0f); transY += 0.075f; glVertexPointer(2, GL_FLOAT, 0, squareVertices); glEnableClientState(GL_VERTEX_ARRAY); glColorPointer(4, GL_UNSIGNED_BYTE, 0, squareColors); glEnableClientState(GL_COLOR_ARRAY); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); [(EAGLView *)self.view presentFramebuffer]; }); And when in Instruments, and even though the animation is running fine, I get tons of "64 bytes malloc"s that never get freed. Anyone know why? A: I was finally able to solve the problem using semaphores: if (dispatch_semaphore_wait(frameRenderingSemaphore, DISPATCH_TIME_NOW) == 0) { dispatch_async(openGLESContextQueue, ^{ [(EAGLView *)self.view setFramebuffer]; glClearColor(0.5f, 0.5f, 0.5f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.0f, (GLfloat)(sinf(transY)/2.0f), 0.0f); transY += 0.075f; glVertexPointer(2, GL_FLOAT, 0, squareVertices); glEnableClientState(GL_VERTEX_ARRAY); glColorPointer(4, GL_UNSIGNED_BYTE, 0, squareColors); glEnableClientState(GL_COLOR_ARRAY); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); [(EAGLView *)self.view presentFramebuffer]; dispatch_semaphore_signal(frameRenderingSemaphore); }); } I guess the dispatch queue was getting flooded without time to handle every opengl redraw. This way, it will only process one redraw at a time, asynchronously. Curiously, it has no side effects on the frame rate! :D Thanks :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7627386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding WHERE to a Simple LINQ Query returns zero results (but shouldn't) I've got the following query: var Query = db.ReportCommon .Where(x => x.ReportType == category) .Where(x => x.ReportDateTime >= dateStart) .Where(x => x.ReportDateTime < dateEnd); category is a variable that I pass in (i.e. 'Short', 'Standard' etc); dateStart and dateEnd are DateTime values. This query returns results as expected (approximately 300 odd). But when I add the following line I get zero results when in reality I should get approximately 2 or 3 less results: .Where(x => x.PartnerRef.ToUpper() != "TEST"); There are only about 3 entries where the PartnerRef field does contain 'Test' or 'test' or 'TEST' the others are either NULL or contain different Partner Refs (like 'DSW'). Why is this happening and how can I fix it? A: Are you sure the values of category, dateStart, and dateEnd are the same? Also, if you use .Where(x => x.PartnerRef.ToUpper() == "TEST"); do you get the 2 or 3 records you expect? You might also want to try running this in LINQPad, which will allow you to experment and see the SQL that EF is generating. A: You need to check the SQL generated, but in SQL terms NULL != "TEST" evaluates to UNKNOWN, not TRUE, and so those results wouldn't be returned. You may be hoping that EF is clever enough to spot this pitfall and emit NULL checks into the SQL, but given everything in your question it may appear that it isn't. Can't explain why the other PartnerRef values aren't being returned - it all points to some other external factor you haven't identified in the question. A: I'm not sure what is happening with your code. However, if in a certain entry "PartnerRef" is null, than PartnerRef.ToUpper() would throw a null reference exception. Can it be you are handling that exception somewhere, but result remains empty, because the query was never fulfilled? A: LINQ to Databases doesn't need the .ToUpper because sql queries are not case sensitive. You might try profiling the generated SQL to find out why your query is failing. Post your SQL if you still need help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Log4j in Websphere I recently take over a web application project using websphere and log4j running under AIX. To create a development environment, I setup all the components in windows, using eclipse to compile a WAR file and deploy it. All is working fine except that log file is not created. I changed the log file in log4j.properties from something like in below and and give everyone full access permission to the directory: log4j.appender.F1.File=/abc/def/logs/admin.log to log4j.appender.F1.File=c:/logs/admin.log What else can I check? I create a simple standalone testapp which use the same log4j.properties and it can create the log file, but when the servlet deployed to websphere, it doesn't work. Please help! Thanks! A: Ok, I think this article should help you. It seems that WebSphere CE uses log4j by default and controls it with a global properties file. There is a section on how to use application-specific properties files. A: Here is what I try and do to troubleshoot similar issues. * *Turn on log4j debugging to see where it actually picks up the file from. You need evidence of which file is picked up (so turning the debug on is a worthwhile activity) This provides you information with what log4j is trying to do to locate the configuration file. -Dlog4j.debug=true *I would not hardcode the log4j location in the code. Instead I would use the log4j.configuration System property and state that in the JVM arguments. This way even I don't need to touch my code. -Dlog4j.configuration=file:///home/manglu/log4j.properties I would use this approach irrespective of the runtime server that I use (be it Tomcat or WAS CE or WAS) Hope this helps A: I suggest you use environment variables set on your server like this : You must access the admin console of your server. Under custom properties Server_path=/abc/def/logs In your log4j, use this : {$server_path}/log.txt Make sure the user running the app has access to that directory.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: UIView + Swipe Gestures info i've just implemented a swipe gesture in my UIView, and I want it to 'move' according to the gesture. Long story short, I need to get the current "X and Y" coordinates during the swipe, to move the UIView. Currently I have a "Swipe Gesture" linked to my UIView, an IBAction linked to the Swipe and the working following code: - (IBAction)mostrar_contas:(UIGestureRecognizer*)sender { campo.text=@"OK"; } BTW: the 'campo' thing is a test UITextField. Thanks. A: Check out UIPanGestureRecognizer - it gives you continuous feedback for current translation and velocity. A: CGPoint location = [sender locationInView:myView]; EDIT: I'm not entirely sure if this works with a UISwipeGestureRecognizer. A UIPanGestureRecognizer, as suggested by seejaneworkit might be the better choice in this case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Table alias in ActiveRecord? I have the following to find posts. @posts = Post.find(:all, :select => "DISTINCT *", :include => [:user, {:track => :artist}], :conditions => ["user_id IN (?) AND NOT track_id = ?", users, @track.id], :group => "track_id", :order => 'id desc', :limit => '5') I would like to add the subselect (SELECT COUNT(*) FROM posts P2 WHERE P2.user_id = P1.user_id AND P2.id > P1.id AND P2.track_id <> 34) <= 1 in my conditions clause, to restrict the number of posts per user. How do I set the alias P1 to the "initial" posts table? Using rails 2.3.11 A: You can add a from parameter: :from => 'posts P1', find (ActiveRecord::Base)
{ "language": "en", "url": "https://stackoverflow.com/questions/7627390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do you make a picture bring up a print dialog box when clicked on? I have a coupon I have on my website and I want my users to click on the coupon and then be able to print it. Is there any way to do this? A: You'd need to forward your users on to a page containing just the image and add a bit of javascript if you just want the image printed and nothing else: <html> <head> <title>Title</title> </head> <body onload="window.print();"> <img src="/image.jpg" /> </body> </html> A: Add an onclick event to your image. <img src="..." onclick="window.print()" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7627391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set spinnerMode in codebehind I could not find a way to set spinnerMode in codebehind. Spinner sets it's spinnerMode property automatically as dialog by default theme. How do I set it while I'm creating a new spinner on code behind? A: in android >= 3.0 (API 11) you can use this : Spinner spinner = new Spinner(this,null,android.R.style.Widget_Spinner,Spinner.MODE_DROPDOWN); A: The answer is in the Android Spinner docs A: Spinner spinner = new Spinner(this.Context, SpinnerMode.Dialog);
{ "language": "en", "url": "https://stackoverflow.com/questions/7627394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: session expire time in CodeIgniter In CodeIgniter config.php file,we can set session expire time in seconds $config['sess_expiration'] = 300;. Now I have two part for my web site,user part and admin part.I need user session expires after 10 minutes(600sec) and admin session expires after 5 minutes(300sec) . Is there any easy way to do it? A: I think the easiest is to replace the current CI_Session instance within your admin with a new instance having those options passed in the $params array in the constructor. The other variant would be that you extend the CI_Session class with your own variant which offers a method to change expiration time or can deal with a second config item which it's processes conditionally.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use only one connection string accross one solution? I have a solution where I have more than 10 projects and in each project I need to connect to database. Is there anyway to centralize and get connection string only from one web.config file? A: Just put the connection strings inside the Web.config. Library projects don't have their own config files; instead, they use the AppDomain's configuration file, which in your case would be the Web.config. A: If you really have a Data Layer as you've indicated, it should be the only module/project that needs a connection string. A: inside your web.config put <configuration> <connectionStrings configSource="connstrings.config"/> </configuration> create a file in the root directory of your website called connstring.config and put the following inside it <?xml version="1.0"?> <connectionStrings> <add name="local" connectionString="Data Source=dbserver;Initial Catalog=databasename;Integrated Security=True;Pooling=false;Connect Timeout=5;" providerName="System.Data.SqlClient" /> </connectionStrings> create class in your project called Database.cs and put the following in it using System.Configuration; public class Database { public class ConnStrings { public static string local = ConfigurationManager.ConnectionStrings["local"].ConnectionString; } } now whenever you need the conn string, you can use Database.ConnStrings.local
{ "language": "en", "url": "https://stackoverflow.com/questions/7627405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Node js.. create a proxy server which will monitor & log the traffic I basically want to set up a proxy server using Node.js which will capture the outgoing requests and the incoming response and dump it in a file.. A: Googling "node proxy server" reveals some modules you could use. There's node-http-proxy and node proxy. As for the file dump you would simply need to use fs to open/create and write to the file. A: Is Winston what you need? I use it for my logging, so I know it is very flexible. Perhaps of most interest to you is the Loggly support so you can output logs to another service.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Rails how to view a txt file? How is it possiable to open an view a txt file with rails? Example I have test.txt: Test test test test Then I have my test.html.erb: Here I want to view test.txt A: You can either render an arbitrary file or use send_file: 3.1 or < 3.1 A: Another possibility is: Here is the test.txt file: <%= File.read("test.txt") %> A: Here is the test.txt file: <%= File.read(File.join(Rails.root, 'your_folder','your_folder','test.txt'))%> A: In some cases (when the file is not small and loading it is connected with a delay), I prefer to load the page content and then to use jQuery ajax request to load the file content. For example, let's say I have a model with file path attribute. In the view layout I am doing something like this: <pre data-source=" <%= (@file.path) %>"></pre> Then in the corresponding js file I am loading the context like this: $(document).ready -> $.ajax( url: $("pre").data("source") context: document.body ).done (response) -> $("pre").html response return return Of course you can check the jQuery ajax documentation for more options. For example, you can render the pre tag with loading like this: <pre data-source=" <%= (@file.path) %>"><div class="loading"></pre> or use other jQuery animations as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use basic authentication with httparty in a Rails app? The command line version of 'httparty' with basic authentication works simple and great: httparty -u username:password http://example.com/api/url But now I'm looking for the way I can add the basic auth to a HTTParty.get call from within a Rails app. First of all, for testing purposes, I want to hard code the login credentials in the Controller. Just to make sure it works. But I can't find any documentation or examples how you can pass these along. A HTTParty.get without credentials works fine: @blah = HTTParty.get("http://twitter.com/statuses/public_timeline.json") But I don't see how I can make a variation on this that accepts the -u username:password part. The next challenge for me (am very new to Ruby/Rails) is to get the user credentials from a user form and pass it along dynamically, but most important for me now it to get the hard coded version to work. A: auth = {:username => "test", :password => "test"} @blah = HTTParty.get("http://twitter.com/statuses/public_timeline.json", :basic_auth => auth) A: Two points, * *If you are hitting Twitter's api, unless I'm mistaken I don't think they allow basic auth anymore :( So you may want to look into something like OmniAuth for OAuth sign-in. You don't need HTTParty or a sign-in form for this, you link to the Twitter sign-in and the user enters credentials there, then Twitter sends a callback request to your app once authenticated. OmniAuth does most of the work for you, you just pull the info you need out of what it gives you in the callback route. *But even so, you will still need the OAuth 'consumer key' and 'consumer secret' which are specific to your application (how Twitter authorizes your application, as distinguished from the user). And you don't want these, nor any auth keys, in your source code. A typical way of doing this is stick them into a config/omniauth.yml file which is not checked in to source control: twitter: key: CONSUMER_KEY secret: CONSUMER_SECRET And then load them in an initializer config/initializers/omniauth.rb : consumers = YAML.load("#{Rails.root}/config/omniauth.yml") Rails.application.config.middleware.use OmniAuth::Builder do provider :twitter, consumers['twitter']['key'], consumers['twitter']['secret'] end You could take a similar approach with loading basic auth username/passwords, just stick them in some object that you'll have access to from wherever you make the HTTParty calls.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "82" }
Q: Generating pure javascript/css files using JSF 1.2/Facelets I need to generate a pure JavaScript file or pure css file dynamically using JSF 1.2/Facelets. When I mean 'pure' I mean without any markup like xml, html open/close tags. Is this possible? If so what settings do I need to use for the facelets output mechanism. To give you a bit of history, I am trying to use the TinyMCE editor in my jsf application and to configure the list of images, it is supplied with a file name. The file is read and parsed on the client side and need to be just javascript and nothing else. A: If memory serves, JSF 1.2 Facelets mandate producing XHTML. I imagine it is technically possible to do what you want even if you might have to resort to transforming the resultant XML (e.g. using XSLT) in a servlet Filter. It would be significantly easier to do using a JSP in the same application: <%@ page language="java" contentType="text/javascript; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%> <%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%> <f:view> var foo = '<h:outputText value="#{bar.baz}" escape="false" />'; </f:view>
{ "language": "en", "url": "https://stackoverflow.com/questions/7627422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to pass Enum as argument Possible Duplicate: Iterating through an enumeration in Silverlight? I came up with a handy little function that gets me the count of an enum (I know it won't work properly with all enums). Rather than hard coding the Enum into the function such that I have to write a seprate function for each Enum I want to use it with, I wanted to pass the enum in as an argument but I am having difficulty figuring out how to do this. Here is the code: private enum MyColors { Red, Green, Blue } private Int32 GetEnumCount() { Int32 i = 0; while (Enum.IsDefined(typeof(MyColors), (MyColors)i)) { i++; } return i; } UPDATE I came up with this as the answer in the end: private Int32 GetEnumCount(Type enumType) { Int32 i = 0; while (Enum.IsDefined(enumType, i)) { i++; } return i; } A: As an alternative (although clearly this has already been answered) if you start the first one with 0 then add one on at the end called count then you can use that, eg: enum MyColour { Blue = 0, Red, Green, ColourCount } A: This can be done, but there's some additional work needed to make it work with unusal enums: private static ulong GetEnumContiguousCount(Type enumType) { var underlyingType = Enum.GetUnderlyingType(enumType); ulong i; for (i = 0; Enum.IsDefined(enumType, Convert.ChangeType(i, underlyingType, null)); ++i) {} return i; } Demo: http://ideone.com/Serji A: You should take the enum Type as an argument, and remove the cast to (MyColors). In non-Sliverlight, you can also just replace your function with Enum.GetValues(typeof(MyEnum)).Length
{ "language": "en", "url": "https://stackoverflow.com/questions/7627423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iPhone iOS 4 UITimePicker force 24 hour view I got a UITimePicker in my app, and I want to use it to select a certain number of hours and minutes after a user event. (for example 3 hours 15 minutes after 7PM) This is why I want to show the date in 24 hour format, otherwise the user might get confused. Is there a way to force the timepicker to show 24 hour view, independent of the clock format for the locale? Or do I just pick another locale? UIDatePicker *timePicker; NSDateFormatter *timePickerFormatter; [self.view addSubview:timePicker]; float tempHeight = timePicker.frame.size.height; timePicker.frame = CGRectMake(0,150 ,self.view.frame.size.width , tempHeight); timePicker.hidden = YES; timePickerFormatter= [[NSDateFormatter alloc]init ]; [timePickerFormatter setDateFormat:@"HH:mm"]; //formats date for processing Thank you! Update: I found the answer like this: timepicker.datePickerMode = UIDatePickerModeCountDownTimer; This effectively accomplishes what I'm trying to do by displaying 0 to 23 hours and 0 to 59 minutes, no further customization required! Sorry for asking about the 24 hour format, this is what the Android app that I'm porting over was using! A: Did you try to use the calendar and locale properties of UIDatePicker? That should be the solution for your problem, because as the documentation explains (read the UIDatePicker class reference): UIDatePickerModeTime The date picker displays hours, minutes, and (optionally) an AM/PM designation. The exact items shown and their order depend upon the locale set. An example of this mode is [ 6 | 53 | PM ]. [EDIT] after further investigation, it seems the NSLocale can't override the AM/PM setting… (I had that information by… simply searching here in Stackoverflow! And your question has already been asked and answered many times before) A: For visualization I use: [self.datePickerView setLocale:[NSLocale localeWithLocaleIdentifier:@"ru_RU"]]; You may use your own locale. And for NSDateFormatter I Use: [_dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]]; It is no longer breaks my applications.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: load balancing purely dynamic web app on tomcat I have a web app which is purely dynamic in nature (think of a public API). So I do not need any static file serving or static file caching optimizations. I need to move from one tomcat to multiple ones, due performance and availability needs. I am using apache mod_proxy_http right now, and trying mod_proxy_ajp recently. However, I feel apache is too heavy for this, and I wonder if other products (haproxy, nginx, proud etc.) would fit my needs better in terms of performance and features (limiting requests, queueing etc.). Only feature that I use in mod_proxy now is to map incoming url to different contexts (e.g. /abc should go to /def). What would be your recommendation ? (think of 150 req/s load, 50-1000ms of processing time for each request, bound by db io -separate mysql box- and network io -service call-) Thanks. Mete
{ "language": "en", "url": "https://stackoverflow.com/questions/7627426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Include JS files in a xhtml file that was included using ui:include I will ilustrate my question using an example: outerfile.xhtml: <h:head> <h:outputScript library="js" name="jquery-1.6.2.js" /> <h:outputScript library="js" name="outer.js" /> </h:head> <h:body> <h:panelGroup id="inner_panel"> <ui:include src="innerfile.xhtml" /> </h:panelGroup> </h:body> innerfile.xhtml: <ui:composition ... > <h:head> <h:outputScript library="js" name="jquery-1.6.2.js" /> <h:outputScript library="js" name="inner.js" /> </h:head> <h:body> <h:panelGroup> I Am Text in The Inner File! </h:panelGroup> </h:body> </ui:composition> My questions: * *Is it okay to declare the js files in the inner file the way I did? *Do I need (And Should I) declare the common (jquery-1.6.2.js) again in the inner file? *What happens if I un-render and the re-render inner_panel using AJAX? Will the inner-included headers be reloaded? A: Is it okay to declare the js files in the inner file the way I did? No. You should not specify the <h:head> in the include as well. This would only result in invalid HTML. As you have right now will result in: <html> <head> <script></script> </head> <body> <head> <script></script> </head> <body> </body> </body> </html> (rightclick page in browser and do View Source to see it yourself, w3-validate if necessary) Fix it accordingly in innerfile.xhtml: <ui:composition ... > <h:outputScript library="js" name="jquery-1.6.2.js" target="head" /> <h:outputScript library="js" name="inner.js" target="head" /> <h:panelGroup> I Am Text in The Inner File! </h:panelGroup> </ui:composition> This will result in valid HTML. The scripts declared by <h:outputScript target="head"> will just end up in the <head> automatically, if not already declared before. Like as in real HTML, there should be only one <h:head> and <h:body> in the entire view, including any templates and include files. Do I need (And Should I) declare the common (jquery-1.6.2.js) again in the inner file? Not if the parent file has it already declared as <h:outputScript>. But redeclaring it in the include doesn't harm. It won't be duplicated anyway if it's already been declared before. What happens if I un-render and the re-render inner_panel using Ajax? Will the inner-included headers be reloaded? This only works if you don't use target="head". Whether they will be reloaded from the server, depends on whether it's already been requested by the browser before and already present and valid in the browser cache. But basically, the browser will be told again to load it, yes. With Firebug you can easily determine it. A: The right way to write it is use target="head" inside your h:outputScript declaration on innerfile.xhtml: <ui:composition ... > <h:outputScript library="js" target="head" name="jquery-1.6.2.js" /> <h:outputScript library="js" target="head" name="inner.js" /> <h:panelGroup> I Am Text in The Inner File! </h:panelGroup> </ui:composition> In that way all your resource declarations will be put inside the outer . Multiple declarations of the same resource with the same library/resource name will not render the same declaration multiple times, because the renderer for h:outputScript has some code that detect that and ignore the duplicate entries. Note things are different if you render a h:outputScript that does not reference a javascript file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Cannot install rmagick gem in Lion: gems can't find ruby.h I've got a clean instal of Mac OS X Lion, and I've installed the Developer Tools. I'm trying to install some ruby gems and the ones which need native extensions aren't building. sudo gem install rmagick For example will not build. I get back this error: Building native extensions. This could take a while... ERROR: Error installing rmagick: ERROR: Failed to build gem native extension. /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby extconf.rb mkmf.rb can't find header files for ruby at /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/ruby.h It looks like the ruby.h header file has moved in Lion, but I don't know how to point ruby gems to it. I've also updated rubygems itself with sudo gem update --system But the issue persists. Ideas? A: First, if you're still using sudo gem, you should probably switch to RVM, which manages lots of rubies and gemsets, all in your home directory so there's no permission problems, and cleanly switches between them. RVM: http://rvm.beginrescueend.com Second, even though you say you "installed the Developer Tools" you may not have gotten XCode and all the libraries. These days XCode for Lion is available on the Mac App Store -- for free, thankfully, though it was $4.99 for a few months, and annoyingly, the Leopard and Snow Leopard compatible versions of XCode are not on the Mac App Store. XCode: http://itunes.apple.com/us/app/xcode/id448457090?mt=12 Third, rmagick depends on ImageMagick. The easiest way to get that these days is via HomeBrew (MacPorts had its day, but everybody's brewing now). HomeBrew: Link After all that, the following should work (and just now worked for me on my Lion laptop): brew install imagemagick gem install rmagick
{ "language": "en", "url": "https://stackoverflow.com/questions/7627436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: array of pointers to member functions: make it work In the following code I am getting the error: a value of type (double*)(const double& arg) const cannot be assigned to an entity of type pt2calculateA Any suggestions on how to make it work? class myClass { private: typedef double (*pt2calculateA)(double); pt2calculateA calculateA[2]; public: myClass () { calculateA[0] = &calculateA1; //->error calculateA[1] = &calculateA2; //->error } double calculateA1(const double& arg) const { ... } double calculateA2(const double& arg) const { ... } } A: myClass::calculateA1() is not a function; rather, it is a member function. So the types are naturally not compatible. The type of &myClass::calculcateA1 is double (myClass::*)(const double &) const, which is a pointer-to-member-function (PTFM). Note that you can only use a PTMF together with a pointer to an object instance (i.e. a myClass*). If you change your typedef, you could at least store the pointers correctly: typedef double (myClass::*pt2calculateA)(const double &) const; You'll have to say &myClass::calculateA1, etc., to take the address. In C++11, you can initialize the array in the initializer list: myClass() : calculateA{&myClass::calculateA1, &myClass::calculateA2} { } A: Try this: class myClass { private: typedef double (myClass::*pt2calculateA)(const double&) const; pt2calculateA calculateA[2]; public: myClass () { calculateA[0] = &myClass::calculateA1; calculateA[1] = &myClass::calculateA2; } double calculateA1(const double& arg) const { // ... } double calculateA2(const double& arg) const { // ... } }; A: Not only the parameter type differs between the typedef and the actual functions, but also one is a function pointer while the other is a member function pointer. myClass::calculateA1 has type double (myClass::*)(const double& arg) const. A: pt2calculateA is declared as a pointer-to-function, not a pointer-to-member-function. see here
{ "language": "en", "url": "https://stackoverflow.com/questions/7627442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: std::get_time and other locale functionality not working correctly on Windows In my attempts to make libc++ and its tests work on Windows, I have come to a problem I can't seem to wrap my head around. The following code is taken from libc++ test code, and passes on Mac (aand probably FreeBSD as well), but not with MinGW-w64 nor MSVC 2010 SP1. #include <iomanip> #include <iostream> #include <cassert> template <class CharT> struct testbuf : public std::basic_streambuf<CharT> { typedef std::basic_string<CharT> string_type; typedef std::basic_streambuf<CharT> base; private: string_type str_; public: testbuf() {} testbuf(const string_type& str) : str_(str) { base::setg(const_cast<CharT*>(str_.data()), const_cast<CharT*>(str_.data()), const_cast<CharT*>(str_.data()) + str_.size()); } }; #if _WIN32 #define LOCALE_en_US_UTF_8 "English_USA.1252" #else #define LOCALE_en_US_UTF_8 "en_US.UTF-8" #endif int main() { testbuf<char> sb(" Sat Dec 31 23:55:59 2061"); std::istream is(&sb); is.imbue(std::locale(LOCALE_en_US_UTF_8)); std::tm t = {0}; is >> std::get_time(&t, "%c"); std::cout << t.tm_sec << "\n"; std::cout << t.tm_min << "\n"; std::cout << t.tm_hour << "\n"; std::cout << t.tm_mday << "\n"; std::cout << t.tm_mon << "\n"; std::cout << t.tm_year << "\n"; std::cout << t.tm_wday << "\n"; assert(t.tm_sec == 59); assert(t.tm_min == 55); assert(t.tm_hour == 23); assert(t.tm_mday == 31); assert(t.tm_mon == 11); assert(t.tm_year == 161); assert(t.tm_wday == 6); } The test passes for Mac/FreeBSD, but the different element are all 0 for Windows. This is true for MinGW-w64+libc++ and MSVC10+Microsoft's STL. Is this just crappy locale support in Windows or is there a wrong implementation-dependent assumption (input format) at play here I can fix or work around? A: I'm not convinced you have the right locale string. They seem to be really badly documented, although there's what looks like a good list here. Perhaps "american_us.1252"? (These strings are all implementation-defined, of course.) A: The problem exposed here is not - Wrong locale names - Wrong std::tm values But lies exactly in the fact that the %c format specifier does not do what's expected here on Windows. This is easy to fix, by specifying the format in full. In this case, what I used was: "%a %b %d %H" ":" "%M" ":" "%S %Y" It still has problems with the %Y part (tm_year is still zero)...
{ "language": "en", "url": "https://stackoverflow.com/questions/7627445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Importing packages in Google App Engine I know this issue has been mentioned before and there were solutions for this. One of solutions that I tried with my problem was this one but it didn't work. My problem is with importing Jinja2 template package. It seems my app finds the root package folder successfully but then it fails with finding any Jinja2 modules like these: from jinja2.environment import Environment from jinja2.exceptions import TemplateNotFound from jinja2.loaders import FileSystemLoader So I suppose that may be I need to include path_fix into some of Jinja2 modules? Though it may work I suppose it's at least a bad solution. So, how can I properly import packages?
{ "language": "en", "url": "https://stackoverflow.com/questions/7627451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JSoup get absolute url of an image with special characters i am working with JSoup and Android to get image urls from some site but some urls contains special characters like (é,è,à...) example : http://www.mysite.com/détail du jour.jpg the element.attr("abs:src") returns the same url as above till now no problem to retrieve the url but when i submit this url in the code below it returns file not found (i grabbed this function from an example on the internet) : public Object fetch(String address) throws MalformedURLException,IOException { try { URL url = new URL(address); Object content = url.getContent(); return content; } catch (Exception e) { return null; } } i think the problem is in the url format because when i get the real address of the image in google chrome : http://www.mysite.com/d%C3%A9tail%20du%20jour.jpg and submit it in the code like : URL url = new URL("http://www.mysite.com/d%C3%A9tail%20du%20jour.jpg"); the image loads correctly so how to get this formatted url from JSoup? thanks A: You need to use URLEncoder for the extracted url from the JSoup. Something like: URL url = new URL(URLEncoder.encode(address)); The spaces between will be replaced with special character values %something
{ "language": "en", "url": "https://stackoverflow.com/questions/7627454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Drop down list inside iframe I just figure it out that if I put my drop down menu inside iframe, all my menus from it will be covered by iframe. The problem is - I dunno how long menu is gonna be, so I can't set the height, and actually I don't want to make it really long. Question: is it possible that drop down menus kinda come out from iframe and appear on parent window? for example: <ul id="myMenu"> <li><a href="#" onmouseover="mopen('m1')">Home</a> <div id="m1" onmouseover="mcancelclosetime()"> <a href="#">link1</a> <a href="#">link2</a> <a href="#">link3</a> </div> </li> </ul> this my menu inside iframe file, I want to display div Home in parent window when you rollover the Home link. thank you everyone in-advance. Any suggestion will be helpful. A: You can use Javascript to set the parent frame's <iframe> element's style.height to an appropriate value. A: What you are asking is not possible. However, you can achieve what you wanna do by converting your main page to iframes and leaving the menu in the main page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use of java image in pythonic OpenCV I'm fetching some images via HTTP: val ostream = new ByteArrayOutputStream() ImageIO.write(imageurl, imageType, ostream) val istream = new ByteArrayInputStream(ostream.toByteArray) (it is actually scala, but this code itself using Java libs, so there is no scala specific magic). Then I'm pushing istream to database (in my case it is GridFS, which is a part of MongoDB). And now I need to use it image (bytearray) in OpenCV (w/ python bindings): db = Connection(myserver,myport).DB fs = GridFS(db) bytearray = fs.get(id).read() Given that, how can I create Mat for use in OpenCV functions? A: Probably you need imdecode function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to switch between activity in android if one of activity is called by an handler My problem borns when i call Intent i = new Intent(c.getApplicationContext(),ActivityMulti.class); c.startActivity(i); It generates the exception mentioned below: 10-02 17:54:26.037: ERROR/AndroidRuntime(905): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{package.com/package.ActivityMulti}: java.lang.InstantiationException: package.ActivityMulti This is called in an handler generate like this: Message msg = handler.obtainMessage(); Bundle b = new Bundle(); msg.setData(b); handler.sendMessage(msg); The second Activity is a simple one: public class ActivityMulti extends Activity{ public ActivityMulti(Bundle savedInstanceState){ super.onCreate(savedInstanceState); init(); } private void init(){ TextView tv = new TextView(this); tv.setText("This is activity multi"); setContentView(tv); //ImageButton info = (ImageButton)findViewById(R.id.info); //info.setImageResource(R.drawable.info2); //this.setContentView(R.layout.view_multi); } } Why that exception is generated? Can you help me? EDIT: This is my manifest: . . . <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".ActivityMulti"></activity> </application> </manifest> EDIT 2: I Solved! the problem was in constructor of the second Activity.. There is no need of it! public class ActivitySingle extends Activity{ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); init(); } private void init(){ TextView tv = new TextView(this); tv.setText("This is activity single"); setContentView(tv); //ImageButton info = (ImageButton)findViewById(R.id.info); //info.setImageResource(R.drawable.info2); //this.setContentView(R.layout.view_multi); } } A: Have you added the activity you are starting in the Manifest file? It's not important if you are starting it from Handler, since you have provided the right context for using .startActivity(). I think you have missed to add the activity in the manifest.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to constraint one column with values from a column from another table? This isn't a big deal, but my OCD is acting up with the following problem in the database I'm creating. I'm not used to working with databases, but the data has to be stored somewhere... Problem I have two tables A and B. One of the datafields is common to both tables - segments. There's a finite number of segments, and I want to write queries that connect values from A to B through their segment values, very much asif the following table structure was used: However, as you can see the table Segments is empty. There's nothing more I want to put into that table, rather than the ID to give other table as foreign keys. I want my tables to be as simple as possible, and therefore adding another one just seems wrong. Note also that one of these tables (A, say) is actually master, in the sense that you should be able to put any value for segment into A, but B one should first check with A before inserting. EDIT I tried one of the answers below: create table A( id int primary key identity, segment int not null ) create table B( id integer primary key identity, segment int not null ) --Andomar's suggestion alter table B add constraint FK_B_SegmentID foreign key (segment) references A(segment) This produced the following error. Maybe I was somehow unclear that segments is not-unique in A or B and can appear many times in both tables. Msg 1776, Level 16, State 0, Line 11 There are no primary or candidate keys in the referenced table 'A' that match the referencing column list in the foreign key 'FK_B_SegmentID'. Msg 1750, Level 16, State 0, Line 11 Could not create constraint. See previous errors. A: You can create a foreign key relationship directly from B.SegmentID to A.SegmentID. There's no need for the extra table. Update: If the SegmentIDs aren't unique in TableA, then you do need the extra table to store the segment IDs, and create foreign key relationships from both tables to this table. This however is not enough to enforce that all segment IDs in TableB also occur in TableA. You could instead use triggers. A: You can ensure the segment exists in A with a foreign key: alter table B add constraint FK_B_SegmentID foreign key (SegmentID) references A(SegmentID) To avoid rows in B without a segment at all, make B.SegmentID not nullable: alter table B alter column SegmentID int not null There is no need to create a Segments table unless you want to associate extra data with a SegmentID. A: As Andomar and Mark Byers wrote, you don't have to create an extra table. You can also CASCADE UPDATEs or DELETEs on the master. Be very carefull with ON DELETE CASCADE though! For queries use a JOIN: SELECT * FROM A JOIN B ON a.SegmentID = b.SegmentID Edit: You have to add a UNIQUE constraint on segment_id in the "master" table to avoid duplicates there, or else the foreign key is not possible. Like this: ALTER TABLE A ADD CONSTRAINT UNQ_A_SegmentID UNIQUE (SegmentID); A: If I've understood correctly, a given segment cannot be inserted into table B unless it has also been inserted into table A. In which case, table A should reference table Segments and table B should reference table A; it would be implicit that table B ultimately references table Segments (indirectly via table A) so an explicit reference is not required. This could be done using foreign keys (e.g. no triggers required). Because table A has its own key I assume a given segment_ID can appear in table A more than once, therefore for B to be able to reference the segment_ID value in A then a superkey would need to be defined on the compound of A_ID and segment_ID. Here's a quick sketch: CREATE TABLE Segments ( segment_ID INTEGER NOT NULL UNIQUE ); CREATE TABLE A ( A_ID INTEGER NOT NULL UNIQUE, segment_ID INTEGER NOT NULL REFERENCES Segments (segment_ID), A_data INTEGER NOT NULL, UNIQUE (segment_ID, A_ID) -- superkey ); CREATE TABLE B ( B_ID INTEGER NOT NULL UNIQUE, A_ID INTEGER NOT NULL, segment_ID INTEGER NOT NULL, FOREIGN KEY (segment_ID, A_ID) REFERENCES A (segment_ID, A_ID), B_data INTEGER NOT NULL );
{ "language": "en", "url": "https://stackoverflow.com/questions/7627465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Trying to create a re-usable text-box (text with a square background-colour) in SVG 1.1? I'm trying to create (what I thought would be!) a simple re-usable bit of SVG to show three lines of text, with a background colour - to simulate a 'post-it' note. I have found some useful code here to get the Bounds of the Text http://my.opera.com/MacDev_ed/blog/2009/01/21/getting-boundingbox-of-svg-elements which I am using. So: I'm creating an group of text elements like this in the 'defs' section of my SVG: <svg id="canvas" width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <g id="post_it"> <text x="0" y="30" id="heading" class="heading">My Heading</text> <text x="0" y="45" id="description" class="description">This will contain the description</text> <text x="0" y="60" id="company" class="company">Very Big Company Ltd.</text> </g> And I'm displaying the text with a 'use' element like this: <use id="12345" class="postit" xlink:href="#post_it" onclick="showId(this);"/> I'm using the onclick to trigger a call to the following javascript function (defined in 'defs' section): function showId(elem) { post_it_rect=getBBoxAsRectElement(elem); document.getElementById('canvas').appendChild(post_it_rect); } (The 'getBBoxAsRectElement(elem)' is from the link I posted). As this stands; this works just fine - however if I change my 'use' element to position the text in a different place like this: <use x="100" y="100" id="12345" class="postit" xlink:href="#post_it" onclick="showId(this);"/> Now, the text displays in the correct place, but the resultant 'background-color' (actually a 'rect' element with opacity of 0.5) still shows on the top-left of the svg canvass - and the function used to calculate the rect is returning '-2' rather than '100' ('-98'?) as I need (I think). What do I need to do to line up the 'rect' elements and the text elements ? The author of the (very helpful article btw) script provides a more advanced script to draw a box round any 'bb' in an SVG, but I couldn't get this to work (missing 'transform' functions?). I'm using Firefox 7.x to render the SVG ; and I'm loading a .svg file (ie, not embedded in html etc) straight from disk to test this). A: Yes, you may need to compensate yourself for the x and y attributes on the <use> element for the time being, I'll try to find some time to update the blogpost and script. Here's a draft SVG 1.1 test that among other things checks that the effect of the x and y attributes are included in the bbox. The line starting [myUse] is the one that tests this case, if it's red then that subtest failed. Chromium and Opera Next both pass that subtest, while Firefox nightly and IE9 doesn't. Note that the test itself has not gone through full review yet, and that it may still change.
{ "language": "en", "url": "https://stackoverflow.com/questions/7627469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sharing SQL CE 4.0 db and Entity Framework 4.0 between web project and winforms project I have a web based application developed using MVC 3, Entity Framework 4.0 and SQL CE 4.0. It is used for showing off analysis results and data in charts on a web site. There is little to no data additions from web users in any way. My second project is part of the same solution and is a basic Win Forms application in C#. Its main purpose is to analyse raw data and update the database for the web site. When I am happy with the system I am likely to automate this part. I wanted to have a process where I ran the Win Forms based tools to update the database, then deployed the web project to the server, effectively updating the DB on the server. The problem begins with referencing the Entity Framework objects in the Web App from the Win Forms project. The SQL CE db and Code First implementation of EF 4.0 resides inside the web project. I reference that project from the Win Forms project and for a short time I can use it for development. When I try to build the project and use the Win Forms app the reference goes away and everything fails. I have no idea why this is happening. Any insight would be helpful. Doug
{ "language": "en", "url": "https://stackoverflow.com/questions/7627470", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cannot find class [org.apache.commons.dbcp.BasicDataSource] I am getting this exception when trying to start my spring MVC hibernate app. SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.apache.commons.dbcp.BasicDataSource] for bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/spring/appServlet/mysql_persistence_info.xml]; nested exception is java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1235) My /WEB-INF/spring/appServlet/mysql_persistence_info.xml is <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost/MyrDB"/> <property name="username" value="user"/> <property name="password" value="user"/> <!-- connection pooling details --> <property name="initialSize" value="1"/> <property name="maxActive" value="5"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> <property name="annotatedClasses"> <list> <!-- all the annotation entity classes --> </list> </property> </bean> </beans> I have all jar files required in classapath. I am using STS. I have commons-dbcp.jar and all the rest of the jar files too. A: For me, just adding commons-dbcp-1.4.jar to my classpath did not work. Had to add commons-pool-1.6.jar as well. This post describes the reason. There is a download link too in that post. A: Please make sure that commons-dbcp-1.4.jar file is inside of your lib folder. you should copy past it in eclipse. See this image A: did a clean directory of tomcat from eclipse and it worked without downloading the jar file
{ "language": "en", "url": "https://stackoverflow.com/questions/7627490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }