text
stringlengths
8
267k
meta
dict
Q: problem loading page in iframe in c# I am having the same problem as in this question. I am using below code <td> <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="test.aspx">Add Hotel Detail</asp:HyperLink> </td> <td> <iframe id="frame1" style="height:800px; width:900px;" src="AdminControlPanel.aspx"> </iframe> </td> But with <asp:HyperLink>,Target attribute is not showing the frame id A: If you want to embed code into the page but separate it out then consider moving the content of the iframe into a UserControl. This will let you create a reusable control that you can drop onto a page. You can use Public Properties to pass data into the UserControl and also set up custom Events so that the external page can subscribe and receive information when things happen inside it. There is a small learning curve but it is very useful once you get your head around it. A: It is indeed possible to open the specified url in a named frame by setting the frame name in the target attribute. See: HTML target Attribute <td> <asp:HyperLink ID="HyperLink1" runat="server" Target="frame1" NavigateUrl="http://..."> Add Hotel Detail </asp:HyperLink> </td> <td> <iframe name="frame1" id="frame1" style="height:800px; width:900px;" src="AdminControlPanel.aspx"> </iframe> </td>
{ "language": "en", "url": "https://stackoverflow.com/questions/7526961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Name Of the program not seen in Downloads I'm facing a problem in executing the code i've written in eclipse for Blackberry...I cannot see the name of the file in downloads when i tried to execute the eclipse code..To resolve this i went for dese options 1)I've again created another workspace in eclipse and copied that code.. 2)Cleaned the project and also bat file But still im not able to find the name of the file in downloads of Blackberry simulator .. What might be the reason for it? A: * *Does your application class contain public static main(String[] args) method? *Clean your simulator filesystem (folder) before running your application A: If you are using a simulator for an OS6 device, your application will appear on the home screen, not in the downloads folder. Is that the problem?
{ "language": "en", "url": "https://stackoverflow.com/questions/7526967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Google differentiates between www.domain.com and domain.com with Omniauth/OpenID I have Facebook, Aol, Yahoo and My OpenID working correctly with Omniauth using either www.my-domain.com and my-domain.com for the same account. Sadly, Google treats these separately and if after registering with www.my-domain.com and then trying to re-signin with my-domain.com, it returns with a new UID and then I display a message saying that an account already exists with that email address. I could write a hack but before I do, does anyone have some info that may help me? I've googled but haven't come across anything. Thank you -ants A: To answer my own question, yes, Google does differentiate between those two urls. You have to use Google's Webmaster Tools to get these domains approved by Google, choose a preference from one of those URLs and then in your web server, set a Redirect 301 so that www.my-domain.com and my-domain.com will always point to the right place
{ "language": "en", "url": "https://stackoverflow.com/questions/7526970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to redirect both stdout and stderr to a file I am running a bash script that creates a log file for the execution of the command I use the following Command1 >> log_file Command2 >> log_file This only sends the standard output and not the standard error which appears on the terminal. A: If you want to log to the same file: command1 >> log_file 2>&1 If you want different files: command1 >> log_file 2>> err_file A: You can do it like that 2>&1: command > file 2>&1 A: The simplest syntax to redirect both is: command &> logfile If you want to append to the file instead of overwrite: command &>> logfile A: Use: command >>log_file 2>>log_file A: Please use command 2>file Here 2 stands for file descriptor of stderr. You can also use 1 instead of 2 so that stdout gets redirected to the 'file'
{ "language": "en", "url": "https://stackoverflow.com/questions/7526971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "354" }
Q: force c++ program to show 'synchronized' output to MATLAB command window using dos() I'm executing my c++ compiled program in MATLAB with dos('myprog.exe'). myprog produces some output that it is printed to the MATLAB command window only after myprog.exe finishes execution. Is there a way to force MATLAB print the output when it is produced by myprog.exe and not at the end? A: ANSWER Make sure that you are flushing correctly the output buffers in your c++ program. In my experience it sometimes helps to insert additional flushing commands (not just end of lines commands) to your code: std::cout << std::endl; NOTE You might also try to call your program like this: [status,result] = dos('myprog.exe','-echo') [status,result] = system('myprog.exe','-echo') The matlab help says: "'echo' forces the output to the Command Window, even though it is also being assigned into a variable." However this might not work because (again matlab help): "Console programs never execute in the background. Also, the MATLAB software always waits for the stdout pipe to close before continuing execution. " This means, that matlab might wait until your program finishes its execution before it shows you the console output. In that case there's nothing you can do about it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Server control behaving oddly I have a server control that I have written, which generally works fine. However when I add in the highlighted line, it adds in not one but two <br /> elements, which is not what I am after. mounting=new DropDownLabel(); mounting.ID="mountTypeList"; mounting.Attributes.Add("class", "mounting"); mounting.Values=Configuration.MountTypes.GetConfiguration().Options; mounting.Enabled=Utilities.UserType == UserType.Admin; mounting.Value=value.Reference; td1.Controls.Add(mounting); **td1.Controls.Add(new HtmlGenericControl("br"));** var span=new HtmlGenericControl("span"); span.Attributes.Add("class", "mountDescription"); span.ID="mountDescription"; td1.Controls.Add(span); Any thoughts on what I am doing wrong? ETA: I have resolved the situation by adding the br using jquery, which I am using there anyway. But the behaviour I saw is surely wrong. If I add an element, it should add that element, not twice that element. A: HtmlGenericControl will generate the with the opening and closing tags <br> and </br> instead you could use new LiteralControl("<br/>") which should do what you desire. EDIT To get around this you will need your own implementation of the HtmlGenericControl and extend it for such cases which don't have opening and closing tags associated. public class HtmlGenericSelfClosing : HtmlGenericControl { public HtmlGenericSelfClosing() : base() { } public HtmlGenericSelfClosing(string tag) : base(tag) { } protected override void Render(HtmlTextWriter writer) { writer.Write(HtmlTextWriter.TagLeftChar + this.TagName); Attributes.Render(writer); writer.Write(HtmlTextWriter.SelfClosingTagEnd); } public override ControlCollection Controls { get { throw new Exception("Self-closing tag cannot have child controls"); } } public override string InnerHtml { get { return String.Empty; } set { throw new Exception("Self-closing tag cannot have inner content"); } } public override string InnerText { get { return String.Empty; } set { throw new Exception("Self-closing tag cannot have inner content"); } } } Found Here
{ "language": "en", "url": "https://stackoverflow.com/questions/7526985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Custom Cell not getting redrawn three20 i have an awkward problem where calling to [self invalidateModel]; does not redraw my custom cells. I have a TTTableViewController with an action sheet that allows to order the display of a table when pressed. The data gets redrawn correctly but the cells are not redrawn. Instead there are reused. To illustrate better : In my - (void)layoutSubviews { of my CustomTableItemCell class i have this : if (bookmarked) { UIImage *bookmark = [UIImage imageNamed: @"bookmarked@2x.png"]; TTImageView *bookmarkView = [[TTImageView alloc] init]; bookmarkView.defaultImage = bookmark; bookmarkView.frame = CGRectMake(297, 0, 16, 27); [self.contentView addSubview:bookmarkView]; TT_RELEASE_SAFELY(bookmarkView); } Basically if I get a bookmarked item, I want to display a ribbon on the right of my cell. This ribbon gets display correctly. When I reorder my cell with the action sheet method and call invalidateModel, the first cell which didn't have any ribon gets putten at a place where was previously a ribbonned item but without redrawing the cell, thus giving a ribon to an item without ribbon. Code source : This is my createDatasource function of my TTTableViewController : - (void)createModel { self.dataSource = [ServiceRequestDetailedDataSource viewDataSource:self.typeOfAction andOrderBy:orderBy]; // If dataSource nil, show an empty Message if (self.dataSource == nil) { [self showEmpty:YES]; } } This is my action sheet action of my TTTableViewController that change the orderBy and calls invalidate model : -(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { if (buttonIndex == 0) { self.orderBy = @"portfolio"; [self invalidateModel]; } Any tips would be great, I am really stuck here :'( A: Maybe [self reload] would help you update cells view. Call it after model invalidation A: Found it, just use reuseidentifier. My bad.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: nginx: how to always return a custom 404 page for the default host I have nginx 0.8.53 configured with some virtual hosts which work as desired. However, due to nginx's "best match" on virtual hosts, I need to add a default host to catch all requests that aren't for a specific virtual host. I would like the default host to return a custom 404 page that I created instead of the default nginx 404 page. I assumed I needed something like: # The default server: server { listen 80 default_server; server_name everythingelse; # Everything is a 404 location / { return 404; } error_page 404 /opt/local/html/404.html; } But this still returns the default nginx 404 page. It seems the return 404 ignores the error_page config. A: Very few directives in nginx take a filesystem path. You want something like: # The default server. server { listen 80 default_server; server_name everythingelse; root /opt/local/html; error_page 404 /404.html; # Everything is a 404 location / { return 404; } # EDIT: You may need this to prevent return 404; recursion location = /404.html { internal; } } A: Here what I have in my conf to make it work: # The default server. server { listen 80 default_server; server_name everythingelse; error_page 404 /404.html; # Everything is a 404 location / { return 404; #return the code 404 } # link the code to the file location = /404.html { #EDIT this line to make it match the folder where there is your errors page #Dont forget to create 404.html in this folder root /var/www/nginx/errors/; } } A: Move the error_page directive up the conf to before you call return 404. This should work: # The default server. # server { listen 80 default_server; server_name everythingelse; error_page 404 /error_docs/404.html; # Everything is a 404 location / { return 404; } # Custom Error Page location /error_docs { alias /opt/local/html/; log_not_found off; access_log off; } } This will use the same custom one for all sites (servers). You need to add the error docs location. http { error_page 404 /error_docs/404.html; ... # The default server. # server { listen 80 default_server; server_name everythingelse; # Everything is a 404 location / { return 404; } # Custom Error Page location /error_docs { alias /opt/local/html/; log_not_found off; access_log off; } } } A: Since both root and error_page are valid directives at http block scope, one can leverage the inheritance behavior of nginx configuration. To share custom error pages between all my vhosts (so that requests on unknown vhosts or inexistent resources in known vhosts get my custom error pages as a response according to error_page definition), I use the following recipe. 1. Add those three lines to /etc/nginx/nginx.conf # … root /var/www/whatever # Used by undefined hosts error_page 403 404 =404 /404.html error_page 502 503 504 =500 /500.html # … 2. Create /etc/nginx/sites-available/catchall with the following snippet as a «catch all» default virtual server. server { listen 80 default_server; listen [::]:80 default_server; # SSL rules here if required server_name _; } 3. Create 404.html and 500.html files in each document root where a custom error has to be used (or link the ones in /var/www/whatever), otherwise defaults will be used instead. That said, not all directives can inherit from a higher level scope, and even worse, some inheritance is unintuitive and doesn't behave as you might expect. * *Understanding the NGINX Configuration file structure and configuration context *Interesting SO thread: Location nesting (Using Debian9 and nginx/1.10.3) A: Before the server block, you are probably using the include instruction : include /etc/nginx/conf.d/*.conf; server { listen 80; ... } I had the same issue, and fixed it by removing the include line: server { listen 80; ... } A: In NGINX v1.14 (released in 2019-12-26) you cannot use location = /404.html. Removing the = (equals sign) works: server { listen 80; server_name everythingelse; error_page 404 /404.html; location / { return 404; } location /404.html { root /opt/local/html; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7526996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: How to compare and sum values of multiple periods using LINQ in VB.Net I have the following example datatable: Value1 Value2 Customer Product Date 100 50 1000 100 1.8.2010 50 20 1000 101 5.1.2010 200 60 1000 100 6.2.2011 180 100 1001 100 7.3.2010 500 700 1000 100 1.1.2010 300 300 1001 100 4.4.2011 250 600 1000 100 3.3.2011 And now the user should be able to compare multiple periods. In this example the user chose two periods: 1.1.2010 - 31.12.2010 and 1.1.2011 - 31.12.2011. The result of the example should be: Customer Product SumValue1Period1 SumValue2Period1 SumValue1Period2 SumValue2Period2 1000 100 600 750 450 660 1000 101 50 20 0 0 1001 100 300 100 300 300 How can I do this? A: Take a look at http://msdn.microsoft.com/en-us/vbasic/bb737908 Specifically, the 'GroupBy - Nested' example. It shows using LINQ to group by 'customer's orders, first by year, and then by month.' You situation should be more straight forward since it's just the date range. A: Since you have known number of columns, you can group data by Customer and products and then take conditional sum from grouping and it will make different columns of the resultant query. Please have a look at following LinqPad program. Sorry, I'm not familiar with VB.Net so I have coded it in C#, but you'll get the fair idea: void Main() { var Period1Start = new DateTime(2010,1,1); var Period1End = new DateTime(2010,12,31); var Period2Start = new DateTime(2011,1,1); var Period2End = new DateTime(2011,12,31); List<Item> lst = new List<Item> { new Item{ Value1 = 100, Value2 = 50, Customer = 1000, Product = 100 , Date = new DateTime(2010,8,1)}, new Item{ Value1 = 50, Value2 = 20, Customer = 1000, Product = 101 , Date = new DateTime(2010,5,1)}, new Item{ Value1 = 200, Value2 = 60, Customer = 1000, Product = 100 , Date = new DateTime(2011,2,6)}, new Item{ Value1 = 180, Value2 = 100, Customer = 1001, Product = 100 , Date = new DateTime(2010,7,3)}, new Item{ Value1 = 500, Value2 = 700, Customer = 1000, Product = 100 , Date = new DateTime(2010,1,1)}, new Item{ Value1 = 300, Value2 = 300, Customer = 1001, Product = 100 , Date = new DateTime(2011,4,4)}, new Item{ Value1 = 250, Value2 = 600, Customer = 1000, Product = 100 , Date = new DateTime(2011,3,3)} }; var grp = lst.GroupBy(x=>new{x.Customer, x.Product}). Select(y=> new { Customer = y.Key.Customer, Product = y.Key.Product, SumValue1Period1 = y.Where(x=>x.Date >= Period1Start && x.Date<= Period1End).Sum(p=>p.Value1), SumValue2Period1 = y.Where(x=>x.Date >= Period1Start && x.Date<= Period1End).Sum(p=>p.Value2), SumValue1Period2 = y.Where(x=>x.Date >= Period2Start && x.Date<= Period2End).Sum(p=>p.Value1), SumValue2Period2 = y.Where(x=>x.Date >= Period2Start && x.Date<= Period2End).Sum(p=>p.Value2) }); Console.WriteLine(grp); } // Define other methods and classes here public class Item { public int Value1{get;set;} public int Value2{get;set;} public int Customer{get;set;} public int Product{get;set;} public DateTime Date{get;set;} }
{ "language": "en", "url": "https://stackoverflow.com/questions/7526997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Webservices in BlackBerry I am trying to make an application that will connect to a web service and call functions from it. I have worked on HTTP connections that will hit the server. This one will send me data. But can I hit a web service and call functions from it on Blackberry? I don't have such information yet haven't tried it. So the question is, how to connect to a web service and call functions from it? A: You won't be able to directly call functions on the server from the BB, so you'll have to define calls on the server where your app would provide the information needed for your server side script to perform the necessary operations. As a simple example, maybe your app sends something to the server to a login URL with a payload that has the username and password. The server would then take over and perform all of the necessary validation and come back with a simple "authenticated" or "denied" response. Your app didn't actually do anything other than provide the information that would be needed for the server to do its magic.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526999", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I read keyboard input on a Winform? I've tried using the KeyUp and KeyDown events to read keyboard input but as soon as I place other controls on the Winform, the keys are not read. How do I make sure that the keys are read? A: You could set KeyPreview = true on your form to catch keyboard events. EDITED to let you understand: private void Form1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.A) e.SuppressKeyPress = true; } Stupid sample that receives keyboard events and drop if A was pressed. If focus is in a textbox, you'll see that text is written, but not A!! EDITED AGAIN: I took this code from a VB.NET example. In your usercontrol, use the text box's "Keypress" event to raise a "usercontrol event". This code would be in your custom usercontrol: 'Declare the event Event KeyPress(KeyAscii As Integer) Private Sub Text1_KeyPress(KeyAscii As Integer) RaiseEvent KeyPress(KeyAscii) End Sub A: See: http://msdn.microsoft.com/en-us/library/system.windows.forms.form.keypreview.aspx set KeyPreview = true and your KeyUp and KeyDown will recognize all keyboard input. A: As marco says set KeyPreview to true on your form to catch the key events in the entire form rather than just a control. Use the KeyPress event ... KeyUp/Down are more for the framework than your code. KeyDown is good if you want to disable a key ... numeric only fields etc. In general KeyPress is the one you're after. If you want to prevent the keystrokes from propogating to other controls set KeyPressEventArgs.Handled = true. http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v=VS.90).aspx Have you wired up the event handler? MyForm.KeyDown += MyHandler; You can also do this in the properties pane ... click the event icon ... A: If you are looking for your Form itself to read the keyboard input, you already have your answer from other correspondents. I am adding this contribution for the possibility that you might want to add key handling to other controls or user controls on your form. My article Exploring Secrets of .NET Keystroke Handling published on DevX.com (alas, it does require a registration but it is free) gives you a comprehensive discussion on how and why all the various keyhandling hooks and events come into play. Furthermore, the article includes a "Keystroke Sandbox" utility for free download that actually lets you see which controls are receiving which key handling events. Here is one illustration from the article to whet your appetite:
{ "language": "en", "url": "https://stackoverflow.com/questions/7527000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Convert PDF documents to TIFF using iTextSharp Using iTextSharp, I want to convert PDF documents into Tiff. Is there any example? Thanks for your time. A: I think you can't do that with iTextSharp and someone agrees with me. Take a look at Ghostscript: with a little work you can achieve your goal.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sending a FILE pointer to a function for reading I've been working on this thing for hours on end and I have searched and searched and my code still does not work right. How do I read my FILE from a function within main using argv[] as the file that I want read? #include <stdio.h> #include <stdlib.h> #include <errno.h> FILE words(FILE *filesToRead) { const char *Open; Open = (char *)filesToRead; filesToRead = fopen(Open, "rt"); int line; while ((line = fgetc(filesToRead)) != EOF) { printf("%c", line); } fclose(filesToRead); } int main(int argc, char *argv[]) { char *ah = argv[]; words(ah); return 0; } A: Try this: void words(char *filename) { FILE *filesToRead = fopen(filename, "rt"); /* ... */ } int main(int argc, char *argv[]) { if (argc > 1) words(argv[1]); return 0; } To be honest (and please don't be offended) the way your code looks it seems you have skipped a few chapters in the C book you are using. A: argv[] is an array of char *s. For example, if you call your program from the command line as: my_prog.exe foo bar Then: * *argc will be 3; *argv[0] will point to "my_prog.exe" *argv[1] will point to "foo" *argv[2] will point to "bar" So inside your main() function, if you are expecting one argument you will need to check the value of argc is 2 and then read your argument out of argv[1].
{ "language": "en", "url": "https://stackoverflow.com/questions/7527005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Converting Web Page with Google map into PDF I am using iTextSharp library for converting my .aspx page into PDF. I am using Table, labels and Google map in my page. Every thing converts into PDF except Google map. In PDF file it shows Google map code instead of showing Map. I could not understand, how to fix this problem ? Any help to fix this A: So you're using iTextSharp to parse HTML, right? Unfortunately iText and iTextSharp's HTML parsers are still in their infancy and Google's maps use both iframes and JavaScript, neither of which are supported in the parser. You can see a list of supported HTML tags here. I would not be surprised if adding a JavaScript interpreter is not even on the to-do list.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how combine between two arraylist if has same value sorry if i confusing, i have two arraylist as below al1 - [Consignment, Bank, Custodian, Rejected, Bank] al2 - [[2, 0, 0, 0, 0, 0, 0], [6, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0], [4, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0]] 1st element al2 is for 1st element al1, and so on so my case is i have to check al1 there is any duplicate value, if have have combine the value in al2 so expected result is al1 - [Consignment, Bank, Custodian, Rejected] al2 - [[2, 0, 0, 0, 0, 0, 0], [6, 1, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0], [4, 0, 0, 0, 0, 0, 0]] i'm trying but would like to get fast solution thanks in advance A: Finally I found the solution shown below: for( int i=0; i < al1.size(); i++ ){ for( int j = al1.size()-1; j > i; j-- ){ if( al1.get(i).equals(al1.get(j)) ){ ArrayList temp1 = (ArrayList)al4.get(i); ArrayList temp2 = (ArrayList)al4.get(j); for(int k=0;k<temp1.size();k++){ if(!temp2.get(k).equals("0")){ temp1.set(k, temp2.get(k)); } } al1.remove(j); al4.remove(j); al4.set(i, temp1); } } } A: I provide a solution based on the nature of Set. Hope it helps. new_alt1 and new_alt2 are the answers that you want. HashSet dupTester = new HashSet(); ArrayList new_al1 = new ArrayList(); ArrayList new_al2 = new ArrayList(); for (int i=0; i<alt2.size();i++){ int lastSize = 0; dupTester.add(alt2.get(i)); if (dupTester.size() > lastSize) { new_alt1.add(alt1.get(i)); new_alt2.add(alt2.get(i)); } lastSize = dupTester.size(); } A: Consider this instead. It is more code, but it is faster and easier to understand. Also recommend that you return the map instead of modifying the arrays as your initial problem states... void combineDuplicates(ArrayList<String> a, ArrayList<ArrayList<Integer>> b) { LinkedHashMap<String, ArrayList<Integer>> m = new LinkedHashMap<String, ArrayList<Integer>>(); for (int i = 0; i < a.size(); ++i) { ArrayList<Integer> existing = m.get(a.get(i)); if (existing == null) { // not a repeat occurrence m.put(a.get(i), b.get(i)); } else { // repeat occurrence; add newcomer to existing plusEquals(existing, b.get(i)); } } // now we have the unique strings in order of occurrence associated // with int array so its time to unpack onto the parameters a.clear(); b.clear(); for (Map.Entry<String, ArrayList<Integer>> e : m.entrySet()) { a.add(e.getKey()); b.add(e.getValue()); } } private void plusEquals(ArrayList<Integer> target, ArrayList<Integer> values) { assert target.size() == values.size(); for (int i = 0; i < target.size(); ++i) { target.set( target.get(i) + values.get(i) ); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7527012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: gwt developer console running outofmemory right away been using the gwt plugin in eclipse for about a year, has worked pretty fine. However, i recently upgraded to OSX lion, and i also upgraded intellij to latest version. Now, i have a standard gwt project. I have historically been able to start it with the devconsole, change stuff and reload page in firefox. (using firefox5 currently) But now, i can only start it, but as soon as i reload page, devconsole crashed. Yesterday it just hung, this morning i upgraded to GWT2.4 and now i just get permgen space outofmemory on first reload. I have the memory settings set to 1024m! If someone could give me pointers it would me much appreciated... A: I experienced that same issue after upgrading to Lion. I believe it has something to do with the memory management of OSX, not Eclipse or GWT. It was a source of huge inconvenience to me, and the benefits of the Lion upgrade weren't enough to justify dealing with an impaired capacity for development, so I rolled back to Snow Leopard. That resolved the problem. I've since tried (unsuccessfully) going back to Lion and using different browser combinations, including Safari and Chrome, but Firefox still seems to be the best choice if you're using Lion- Chrome is exceptionally slow with GWT (oddly), and Webkit in general seems to not support some of the features GWT offers, so Safari's out. I say go back to Snow Leopard, unless there's something preventing you from doing so. Good luck, and please keep us updated if you figure out a workaround. A: Answering my own question since i've found well, not an answer but a workaround. In intellij, i changed the agent (only using one in development to speed things up) from gecko1_8 to safari, and used chrome. As i mentioned, the console crashed in firefox on every reload, in Chrome i'm at 30 page reloads/recompiles and not a single console crash! It also recompiles faster than in FF. Have no idea why it works so crappy in FF though... A: You can fix it - just add -XX:MaxPermSize=384m for jvm.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: unable to return my sql connection object from web service to asp.net project This my web service code : using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Data.Sql; using System.Data.SqlClient; namespace DBwebService { /// <summary> /// Summary description for WebService1 /// </summary> [WebService(Namespace = "http://kse.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService] public class WebService1 : System.Web.Services.WebService { string ConnectionString = "Data Source=Shumaila-PC;Initial Catalog=kse;Persist Security Info=True;User ID=sa;Password=sa"; public SqlConnection Conn; [WebMethod] public void SqlConn() { Conn = new SqlConnection(ConnectionString); // Conn.Open(); } //catch (SqlException ex) //{ // //Console.WriteLine( "Connection Unsuccessful " + ex.Message); //} } } I need to return my sql connection object so that i can call it in my asp.net pid roject. but when i did public SqlConnection SqlConn() and return.Conn(); this gives me the following error Server Error in '/' Application. Parser Error Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately. Parser Error Message: Could not create type 'DBwebService.WebService1'. Source Error: Line 1: <%@ WebService Language="C#" CodeBehind="WebService1.asmx.cs" Class="DBwebService.WebService1" %> Source File: /WebService1.asmx Line: 1 Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1 --. Metadata contains a reference that cannot be resolved: 'http://localhost:50387/WebService1.asmx'. The content type text/html; charset=utf-8 of the response message does not match the content type of the binding (application/soap+xml; charset=utf-8). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly. The first 1024 bytes of the response were: ' Server Error in '/' Application. Parser Error '. The remote server returned an error: (500) Internal Server Error. If the service is defined in the current solution, try building the solution and adding the service reference again. A: My God are you serious? You should not even think to return a connection from a service. you should return the data you load with a query which is executed using that connection. that is, move all the logic of what you want to do with the connection in the calling code inside a DAL class library and return the results only. A: HMM come to think of it connection object is not serialized you have to declare your object as serialize-able only to do the above task, only primitive types are auto serialize-able. A: Your web service should expose a method which accepts the signup data as an argument to the method. The service can then commit that data to the database and then return an Ack/Nack response to the UI.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Image not displaying in local host in my asp site I am loading an asp image into my site and its showing in the design view but when I run it on the local host it wont display the image. <div><asp:Image ID="Image1" runat="server" src="~/images/FusionChart.png" /></div> the image is stored in "images" folder within the root and the image name is the exact same as in the div so Im confused as to why is wont display. Any help would be appreciated. A: Change the src attribute name to ImageUrl property name A: Seems like your path is incorrect. Please read this article, may be help you http://msdn.microsoft.com/en-us/library/ms178116.aspx If not there is different <asp:Image ID="Image1" runat="server" ImageUrl="~/images/FusionChart.png"/> <img src="~/images/FusionChart.png" alt=""/>
{ "language": "en", "url": "https://stackoverflow.com/questions/7527026", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: to_char in vb.net I am using to_char to trim the time part in date, when I am running below query in oracle it is showing right output that is skipping time span. but same when I am filling up in dataset and displaying in grid view time span also appears in output. StrSql.Append("select") StrSql.Append(" to_char(ABC.birth_date, 'DD/MM/yyyy') AS DOB,") StrSql.Append("from abc") Can anyone please help me to come out with this issue???? I tried TRIM,TRUNC,TO_DATE but no use. thax in advance. A: I don't know any SQL way, but you can try to get the data as-is and fetch it with VB.net's DateTime class (http://msdn.microsoft.com/de-de/library/system.datetime.aspx#Y114).
{ "language": "en", "url": "https://stackoverflow.com/questions/7527027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FirebirdSQL queries gets stuck at 12:00PM I'm running Firebird 2.5 (and have also tried earlier versions) on Windows. Every day after 12:00PM running insert/update queries on one specific table hang, but complete successfully by 12:35 or so, no matter when started. It does seem that Firebird is doing some kind of maintenance on the table and it takes half an hour to complete, during which time the table cannot be written to (but the reads are fast). The table itself is really small, some 10000 rows, compared to millions of rows we have in other tables - and other tables do not get stuck. I haven't been able to find any reason or solution. I tried dumping the table and restoring it, which didn't help, I tried switching between superserver and classic, changed versions with no success. Has anyone experienced a problem like this? A: No. Firebird doesn't have any internal maintenance procedures bind to some specified time of a day. Seems, there is some task on your server scheduled to run at 12:00 PM. Or there are network users of the server who start doing some heavy access at 12:00 PM. A: The only maintenance FB does is "garbage collection" (geting rid of old record versions) and this is done on "when needed" basis (usually when records were selected, see the GCPolicy in firebird.conf) not on some predefined time. Do you experience this hang only on during these certain hours or is it always slow to insert to that table? Have you checked the server load during the slowdown (ie in the task manager, is the CPU maxed out)? Anyway, here is some ideas to check: * *What constraints / triggers do you have on the table? If they involve some extensive checks (ie against the other tables which contain millions of rows) this could be the reason inserts take so long. *Perhaps there is some other service which is triggered at that time? Ie do you have a cron job to make backup of the DB at that time? Or perhaps some other system service which runs at that time with higher priority slows down the server? *Do you have trace service active for the table? See fbtrace.conf in FireBird root directory. If it is active, extensive logging might be the cause of slowdown, if it isn't active, using it might help you to find the cause. *What are the setings for ForcedWrites / UnflushedWrites (see firebird.conf)? Does changing them make difference? *Is there something logged for this troublesome timeframe in firebird.log? A: To me it looks like you have a process which starts at 12:00 and does something which locks the entire table. Use the monitoring table or the trace manager to see if there is any connection or active transaction which looks suspicious. I also think your own transaction are started with the WAIT clause without a LOCK TIMEOUT, you might want to change this to NO WAIT or WAIT with a LOCK TIMEOUT, so that your transactions either fail immediately or after the timeout. A: My suggestion is to use the TRACE API in 2.5 to track down what is happening near or around that time. That should help get you more information as to what is happening. I use this for debugging http://upscene.com/products.misc.fbtm.php kinda buggy itself, but when it is working it is a god send. A: Are some Client-Connections going DOWN at 12:00 PM? I had a similar problem on a 70.000 records sized table: Client "A" has a permanently open DB Connection like "select * from TABLE". This is a "read only transaction" but reason enough for the server to generate Record-Versions. Why? Client "B" made massive Updates to this Table, the Server tries to preserve the world like it was when "A" startet her "select". This is normal for Transaction able DB-Servers, and its implemented by creating Record Copies of the record-data before its updated. So in my case for this TABLE 170.000 Record Versions existed. You can measure this by gstat -r -t TABLE db.fdb | grep versions If Client "B" goes down, the count of Record-Versions is NOT growing any more. Client "A" is the guilty one, freezing all this versions, forces the server to hold it. Finally if Client "A" goes down (or for example a firewall rule cuts all pending connections) Firebird is happy to start the process of getting rid of the now useless Record-Versions. This "sweep"?! is bad programmed (even 2.5.2) cpu is 3% it do only <10.000 Versions / Minute so this TABLE has a performance of about 2%.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: "git push heroku master" fails with the error: "Connection to ... closed by remote host" I am trying to deploy my first Heroku application. Every time I "git push heroku master", I get this... (specific directory/file names edited out) C:\Documents and Settings\Alex\My Documents\Business\Software\...>git push heroku master Enter passphrase for key '/c/Documents and Settings/Alex/.ssh/...': Counting objects: 1671, done. Compressing objects: 100% (1522/1522), done. Writing objects: 100% (1668/1668), 4.35 MiB | 32 KiB/s, done. Total 1668 (delta 67), reused 0 (delta 0) Connection to 10.102.25.251 closed by remote host. fatal: The remote end hung up unexpectedly It always finishes sending all the objects, then Heroku hangs up prematurely and the push is unsuccessful. Has anyone else seen this before??? I'm running Windows XP, git 1.7.0.2.mysysgit.0 with OpenSSH_4.6p1. Please tell me if I'm forgetting any important details. A: That looks like you're behind some kind of corporate firewall and it's blocking your requests - the 10.102.25.251 is not one of Heroku's A: this is seems like you network setting error try to run command in VPN or change your proxy settings. A: I think the problem may have been a poor Internet connection. I tried again the next morning morning, and on the second try, "git push" went through.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to perform doubleClick event on an array of button I have created an array of buttons. Now what I want is on double click of each of the buttons I want to display a toast which shows the text of the button which is clicked. I did it for singleClick but I don't know how to do it for doubleClick. The code I have written for an Array of buttons: LinearLayout layoutVertical = (LinearLayout) findViewById(R.id.liVLayout); LinearLayout rowLayout = null; LayoutParams param = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1); //Create Button for (int i = 0; i<6; i++) { rowLayout = new LinearLayout(this); rowLayout.setWeightSum(7); layoutVertical.addView(rowLayout, param); for(int j=0; j<7; j++) { m_pBtnDay[i][j] = new Button(this); m_pBtnDay[i][j].setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL); rowLayout.addView(m_pBtnDay[i][j], param); m_pBtnDay[i][j].setTextSize(12); //save button position m_pBtnDay[i][j].setTag(new CalendarForm(i , j)); } } A: One way I can think of is by using Gesture Detection yourButton.setOnTouchListener(touchListener); . // Gesture detection gestureDetector = new GestureDetector(new GestureListener()); View.OnTouchListener touchListener = new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { // The onTouch method has a View parameter which is a reference to the touched view. Cast // this to Button to get its caption: String caption=((Button)v).getText(); if (gestureDetector.onTouchEvent(event)) { return true; } return false; } }; . private class GestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onDown(MotionEvent e) { return true; } // event when double tap occurs @Override public boolean onDoubleTap(MotionEvent e) { float x = e.getX(); float y = e.getY(); Log.d("Double Click", "Tapped at: (" + x + "," + y + ")"); return true; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7527031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Missing shared Library for Android app What do I have to do to include an external library to my Android application? I know, it's similar to a problem what I found here very often, but I don't want to use Google Maps API, I want to use another library, in this case it's apache commons. I followed every step and compared them to different manuals or tutorials: * *I imported 'commons-lang-2.4jar' to the libs-folder in my project, *I added this 'commons-lang-2.4jar' to the Referenced Libraries, *I added the use to the manifest-file: <uses-library android:name="org.apache.commons.lang"/> But I get these popular errors: Console: [2011-09-23 10:53:41 - TestProject] Installation error: INSTALL_FAILED_MISSING_SHARED_LIBRARY [2011-09-23 10:53:41 - TestProject] Please check logcat output for more details. [2011-09-23 10:53:41 - TestProject] Launch canceled! LogCat: 09-23 08:53:39.904: ERROR/PackageManager(71): Package test.project requires unavailable shared library org.apache.commons.lang; failing! In case of the problem with Google Maps API I know my emulator needs the API, so I would guess my emulator now needs this library? But no device would have it - so I need to include it?! (tried to check this library in properties "order and export" via eclipse, but no success) A: Remove <uses-library android:name="org.apache.commons.lang"/> This is only for Android Project Libraries not a plain old Jar file. Jar files will have their classes extracted and put into your apk by just including them in the build path.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a link that has a textbox "auto-filled"? How do I create a link that when the user clicks, it will bring him to the Google page as shown below (with the To field completed): Right now, what I've managed is to simply link him to https://mail.google.com/mail/#compose and this is what he will see: Similarly, is there a way to achieve this on hotmail as well? A: https://mail.google.com/mail/?view=cm&tf=1&to=someone@gmail.com&fs=1 This shows the composition screen. To get the whole gmail interface, remove &tf=1. If you also want to preset a subject, just add &su=YourSubject to the query string A: The data is sended by POST, I think. Try to trace the HTTP Header when clicking on the link that redirects to the already filled page, with the Firefox Addon "Live HTTP Headers" for example. If the third line starts with POST, look at the last line before "HTTP/1.1 200 OK", this is the sended POST data. You will probably find the auto filled mail adress there. If so, you can do a javascript POST request to the given URL: http://www.bennyn.de/programmierung/javascript/http-post-request-mit-javascript.html, or you can use a framework like jQuery. A: This does not answer your question but if you are to request a person to send an email then it is best to use the mailto: in your links so that it uses the computers default mail service. I am unaware if this uses web-based mail but it will open up the computers default mailing program (And it stops you from having to account for every different email service). And I tested Dennis's answer, and it does work for me. What do you mean by 'It ain't working', any error messages? anything that can help solve the issue?
{ "language": "en", "url": "https://stackoverflow.com/questions/7527039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to hide whole loading process of page and show ready page to users? I'm having following problem: my PHP page generates navigation menus from db like <ul> menus then with the help of JS shows it like multi-level menu. The problem is, it shows whole loading process. At first user sees something like that: Then How to hide whole loading process of page, or is there any other solution for this issue? A: hide it in css, #loading { display: block; background: url(loading.gif) no-repeat center center; } #container { display: none; } and, in javascript show it again (this code uses jquery) $(function(){ $('#loading').fadeOut(250, function(){ $('#container').show(); }); }); of course you can do this like anyhow you want, hide and show anything in css, then on document ready, switch it over to the content. by hiding the loading div, and showing the content. A: Set the style on display:none; until your page is completely loaded. A: Generally this is done by showing/hiding a div or two over the top of your content. You can get a fancy loading gif from http://www.ajaxload.info/ to get you started. Then you'll want to place a DIV on your page: <div id="loading"> <p><img src="loading.gif" /> Please Wait</p> </div> You'll want this hidden by default, so you'd need to add this CSS: #loading { display:none; } You'd also want to setup the display for this too: #loading { display:none; position:fixed; left:0; top:0; width:100%; height:100%; background-image:url("transparentbg.png"); } #loading img {position: absolute; left:50%; top:50%} The file transparentbg.png would be a 25x25 black PNG set to about 80% opaque. Next you would need a way to show and hide this with jQuery: function showLoading() { $("#loading").show(); } function hideLoading() { $("#loading").hide(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7527042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: what is the alternative for the deprecated cachemanager class in android I see that cachemanager is a deprecated class in Android sdk. So what is the substitiute of cachemanager. I see a way with the data storage techniques. but how are they supposed to implement the cache algorithm. Does everyone has to write there own Cachemanagers. A: I guess it depends on what kind of cache you are looking for. ICS adds a built-in HTTP response cache, see this blog post for more info. If you are looking for a more general disk cache then the ICS source code has a nice class called DiskLruCache (not available in the public APIs though). It has been back ported and released by a 3rd party though: DiskLruCache.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: how to Check datetime entered I have a textBox where the user enters a datetime using a calendar, I am checking for whether the text box is empty or not by if ((string.IsNullOrEmpty(txt_SendAt.Text) == false) How can I check whether the datetime entered is less or = to the current datetime A: if ((string.IsNullOrEmpty(txt_SendAt.Text) == false && DateTime.Parse(txt_SendAt.Text) <= DateTime.Now ) A: DateTime enteredDateTime; if (!DateTime.TryParse(txt_SendAt.Text, out enteredDateTime)) { Debug.WriteLine("User entered date time in wrong format"); }else { if(enteredDateTime <= DateTime.Now) { // less or equal } } A: Use one of the Parse or TryParse static methods of the DateTime class to convert the string to a DateTime and compare it to the current DateTime. DateTime input; if(DateTime.TryParse(txt_SendAt.Text, CultureInfo.InvariantCulture, DateTimeStyles.None, out input)) { if(input <= DateTime.Now) { // your code here } } else { //not a valid DateTime string } A: Parse or TryParse the text to DateTime, then compare to DateTime.Now A: A few steps here, first check something is entered, as you have done, secondly, check it is actually a date, and lastly check against the desired date, as such: var input = DateTextBox.Text; if (!string.IsNullOrEmpty(input)) { DateTime date; if (DateTime.TryParse(input, out date)) { if (date <= DateTime.Now) { //bingo! } } } Notice the TryParse for checking proper formatting of the input string as a date - using only Parse is a sure way to make your app go BANG! A: You can parse your string input to a DateTime using the DateTime.Parse method, then run your comparison in the normal way. Remember, Parse methods will throw a FormatException if the input is not directly castable to the required type. It may make more sense to go for the TryParse method if you have, for example, a free-text input. var inputDate = DateTime.Parse(txt_SendAt.Text); if (inputDate > DateTime.Now) { Console.WriteLine("DateTime entered is after now."); } else if (inputDate < DateTime.Now) { Console.WriteLine("DateTime entered is before now."); } A: if (!(string.IsNullOrEmpty(txt_SendAt.Text) && Datetime.Parse(txt_SendAt.Text)<=Datetime.Now) { /*code */ } else { /*code */ }
{ "language": "en", "url": "https://stackoverflow.com/questions/7527047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get data From Status bar and disable it? I am creating a custom lock screen so that in my activity the Status bar won't be there. At the mean time i want to get the the status bar notifications such as missed calls, new chat messages, new emails, new voice-mail, etc... How to implement this? please give me a hint
{ "language": "en", "url": "https://stackoverflow.com/questions/7527049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to COUNT values and and use it as a variable in a Stored Procedure Basically, What i am trying to do is ; The number of classes required is a variable. EG. The user could put 5 , 4 as a minimum. Since i am new, i cant upload pictures, But here is a picture of my ER diagram, to get a idea of the table structures. I am using sql server 2005 A: First off your question is poorly phrased; it is difficult to get a sense of what it is you are trying to achieve. To get the number of rows from a dataset which meet the required condition, then use SELECT COUNT(0) FROM Tablename Where WhereCondition. I can't see your ER diagram so I'll hypothesise; this should return attendance by class. DECLARE @Students TABLE (id int, StudentName nvarchar(max)); DECLARE @Classes TABLE (id int, ClassName nvarchar(max)) DECLARE @StudentClassAttendance TABLE (ClassAttendanceID int, StudentId int, ClassId int, StartTime datetime) SELECT sca.StudentID, s.StudentName, COUNT(sca.ClassAttendanceID), c.ClassName FROM @Students s INNER JOIN @StudentClassAttendance sca ON sca.StudentId = s.Id INNER JOIN @Classes c ON c.Id = sca.ClassId GROUP BY sca.StudentID, s.StudentName, ClassName
{ "language": "en", "url": "https://stackoverflow.com/questions/7527052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to set the python -O (optimize) flag within a script? I'd like to set the optimize flag (python -O myscript.py) at runtime within a python script based on a command line argument to the script like myscript.py --optimize or myscript --no-debug. I'd like to skip assert statements without iffing all of them away. Or is there a better way to efficiently ignore sections of python code. Are there python equivalents for #if and #ifdef in C++? A: #!/usr/bin/env python def main(): assert 0 print("tada") if __name__=="__main__": import os, sys if '--optimize' in sys.argv: sys.argv.remove('--optimize') os.execl(sys.executable, sys.executable, '-O', *sys.argv) else: main() A: -O is a compiler flag, you can't set it at runtime because the script already has been compiled by then. Python has nothing comparable to compiler macros like #if. Simply write a start_my_project.sh script that sets these flags.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Best way to handle and deploy XQuery stored procedures? Is there a tool for deploying things into exist? if I've got a bundle of, say, schemas and XQuery stored procedures? Is there a way of, say, bundling those into a zip or tar file and uploading them or deploying them into eXist? Alternatively what is the best way of storing these things in a version controlled way (in a git repo, say) and deploying them to the eXist server? Ideally, it'd be nice to be able to have a simple script in a scripting language so you can simply call "deploy.py" or whatever and it'd take everything from the repository and load it into the XML database. A: The EXpath packaging system specifies a format for generating a ZIP file with XQuery procedures (and other content) and deploying it into multiple XQuery databases. See the specification. You should be able to use the Python zipfile module to generate these if you're inclined to use Python (though personally, I do so from a makefile). Unfortunately, the process for checking currently installed package versions to upgrade if necessary is not standardized; I have a solution for BaseX, but nothing for eXist immediately at hand. However, eXist's implementation is well-documented, and you should have little trouble working with it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527056", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I retrieve the new timeline data from the API? At the f8-conference Facebook just announced the new timeline view. This is based on the new Open-Graph model The question is, how is this data retrieved via the API? Retrieval should address a number of complexities: * *The filtered nature should be just like in the online view, i.e. not everything from the ticker should show up *Even more, the granularity of the timeline view should be reflected just like on the webpage (more detail today, less detail in the past, but the option to dig deeper at any time) *The aggregation view of app data should be supported *The cover image should be part of the data Right now, it is not obvious to me if this is or will be possible at all. A: In answer to agam360’s further question in the comments, But how can we get that "Cover Photos" Id? (looping though all of the Graph data?!) Use FQL, and take name="Cover Photos" into the WHERE condition of your query too. (But keep in mind that this album name is locale dependend, so if you should be querying the data in another locale than english, you’ll have to adapt the search term.) A: Partial answer to the fourth bullet: There is a new photo album called "Cover Photos" with the cover image on position 1. Unfortunately, there doesn't seem to be a way to find the positioning coordinates that define the viewport on the image. {edit} There's now a cover field on a user which returns the cover photo and the x/y offset needed to display it the same way it's displayed on Facebook {/edit}
{ "language": "en", "url": "https://stackoverflow.com/questions/7527059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: maven can't find archetype in my repository I'm trying to create my own maven archetype. For now, I'm going through this tutorial [here][1] without success. I'm able to build the archetype project okay, but when I try to generate a project from that archetype I get the error below. Maven can't seem to find the archetype I created. Can any one spot my problem? Is there some other recomended tutorial for createing a maven archetype? Thanks. Maven version 3.0.3 Build Error: AR3Y35-LAPTOP:EclipseWS Albert$ mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app -DarchetypeGroupId=com.myarch.archetypes -DarchetypeArtifactId=component-archetype -DinteractiveMode=false [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building Maven Stub Project (No POM) 1 [INFO] ------------------------------------------------------------------------ [INFO] [INFO] >>> maven-archetype-plugin:2.0:generate (default-cli) @ standalone-pom >>> [INFO] [INFO] <<< maven-archetype-plugin:2.0:generate (default-cli) @ standalone-pom <<< [INFO] [INFO] --- maven-archetype-plugin:2.0:generate (default-cli) @ standalone-pom --- [INFO] Generating project in Batch mode [WARNING] Specified archetype not found. [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 3.389s [INFO] Finished at: Fri Sep 23 02:33:55 PDT 2011 [INFO] Final Memory: 7M/81M [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:2.0:generate (default-cli) on project standalone-pom: The desired archetype does not exist (com.myarch.archetypes:component-archetype:1.0) -> [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException AR3Y35-LAPTOP:EclipseWS Albert$ prototype pom.xml <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.myarch.templates</groupId> <artifactId>component-template</artifactId> <version>1.0-SNAPSHOT</version> </parent> <groupId>${groupId}</groupId> <artifactId>${artifactId}</artifactId> <version>${version}</version> <name>${group}</name> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> </project> archetype.xml <archetype xmlns="http://maven.apache.org/plugins/maven-archetype-plugin/archetype/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/plugins/maven-archetype-plugin/archetype/1.0.0 http://maven.apache.org/xsd/archetype-1.0.0.xsd"> <id>component-archetype</id> <sources> <source>src/main/java/App.java</source> </sources> <testSources> <source>src/test/java/AppTest.java</source> </testSources> <allowPartial>true</allowPartial> </archetype> A: I needed to include -DarchetypeVersion={my.archetype.version} in the mvn archetpe:generate command A: In my case the problem was that: - update-local-catalog goal created file ~/.m2/repository/archetype-catalog.xml - generate goal searches for file ~/.m2/archetype-catalog.xml copying the file was a workaround. Not sure how I've fixed this. Sure now with maven 3.5.4 everything is ok. A: For using a customized archetype, there has to be an entry made in the archetype-catalog.xml file which resides in the .m2/repository/archetype-catalog.xml in your home directory. For doing so, you need to install the archetype by using the following command: mvn install archetype:update-local-catalog After that, you will be able to use your new archetype while creating a new Maven project with the mvn archetype:generate command. A: It's telling you : [WARNING] Specified archetype not found. Did you install your archetype with mvn install before trying to use it ? A: Executing the mvn install resolves the problem, after executing that from idea the problem got resolved. A: From my own experience, You have to search for your groupId is accessible in the below link or not http://repo.maven.apache.org/maven2/archetype-catalog.xml I found out I had typo error then I've got error.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Include ExtJS control into my div I am trying to use this example to include this im my web-site. The matter is, if I try to copy it into my application, these controls fit all page. How can I include ExtJS controls into my div? A: The ExtJS Portal demo uses an Ext.Viewport control to maximize the application to the entire browser window. To have the portal or parts inside another element or control, exchange the Viewport control with a Ext.Container or a Ext.Panel. A: You should use renderTo propery to specify id of element, where control should be rendered.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Draggable element should stay in the stop moving point when page is refreshed When the element (id="draggable") stop dragging, the position of the element will be sent to the database via 'mapDemo.php'. Currently the element will go back to the start moving point if refreshing the page . What I want to do is the element should stay in the stop moving point when page is refreshed. Below is my code, what change should I do to solve this problem? Thanks for any help. <script type="text/javascript"> $(function() { $( "#draggable" ).draggable({ stop: function(){ var position = $(this).position(); $.ajax({ type:"post", url:"mapDemo.php", data: { top: position.left, left: position.top }, cache:false }); } }); }); </script> <div class="demo"> <div id="draggable" class="ui-widget-content"> <p>Drag</p> </div> </div> A: If you save the position when its dropped, you need to just restore this position when the page loads. ie, you could add this line $('#draggable').css({top:200,left:100}); with top and left read from wherever you save the data to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: android activity method call I am new to android development. Today I tried something that I created a project called androidPickerviws. In that project I created two activities and in Timepicker.java activity there is method called displayTime(hours,minute);. Now my doubt is can I use this method displayTime() in Datepicker.java activity. If so, how can I do it.. Here iam providing my Timepicker.java activity code package picker.view; // imports... public class Timepicker extends Activity{ public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); LinearLayout linearlayout=new LinearLayout(this); linearlayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams layoutparams=new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); LayoutParams params=new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT); final TimePicker timepicker=new TimePicker(this); linearlayout.addView(timepicker, params); Button ok=new Button(this); ok.setText("OK"); linearlayout.addView(ok, params); addContentView(linearlayout,layoutparams); ok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { final int hours=timepicker.getCurrentHour(); final int minute=timepicker.getCurrentMinute(); displayTime(hours,minute); } private void displayTime(int hours, int minute) { if(hours==0) Toast.makeText(getBaseContext(), "Time saved is 12 : "+minute+" AM", Toast.LENGTH_SHORT).show(); else if(hours<12) Toast.makeText(getBaseContext(), "Time saved is "+hours+" : "+minute+" AM", Toast.LENGTH_SHORT).show(); else if(hours==12) Toast.makeText(getBaseContext(), "Time saved is "+hours+" : "+minute+" PM", Toast.LENGTH_SHORT).show(); else Toast.makeText(getBaseContext(), "Time saved is "+(hours-12)+" : "+minute+" PM", Toast.LENGTH_SHORT).show(); } }); } } A: I got the answer we can call like that but we have to mark that method as public and should placed output side of all the methods but inside of the class. The modified code is follows package picker.view; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.LinearLayout; import android.widget.TimePicker; import android.widget.Button; import android.widget.Toast; public class Timepicker extends Activity{ public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); /* setContentView(R.layout.timepicker); final TimePicker timepicker=(TimePicker) findViewById(R.id.timePicker1); Button ok=(Button) findViewById(R.id.button1);*/ LinearLayout linearlayout=new LinearLayout(this); linearlayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams layoutparams=new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); LayoutParams params=new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT); final TimePicker timepicker=new TimePicker(this); linearlayout.addView(timepicker, params); Button ok=new Button(this); ok.setText("OK"); linearlayout.addView(ok, params); addContentView(linearlayout,layoutparams); ok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { final int hours=timepicker.getCurrentHour(); final int minute=timepicker.getCurrentMinute(); displayTime(hours,minute); } }); } public void displayTime(int hours, int minute) { if(hours==0) Toast.makeText(getBaseContext(), "Time saved is 12 : "+minute+" AM", Toast.LENGTH_SHORT).show(); else if(hours<12) Toast.makeText(getBaseContext(), "Time saved is "+hours+" : "+minute+" AM", Toast.LENGTH_SHORT).show(); else if(hours==12) Toast.makeText(getBaseContext(), "Time saved is "+hours+" : "+minute+" PM", Toast.LENGTH_SHORT).show(); else Toast.makeText(getBaseContext(), "Time saved is "+(hours-12)+" : "+minute+" PM", Toast.LENGTH_SHORT).show(); } } A: You could put your code code in a static method inside a "Utils" class: public class Utils { private static void displayTime(Context context, int hours, int minute) { if(hours==0) { Toast.makeText(context, "Time saved is 12 : "+minute+" AM", Toast.LENGTH_SHORT).show(); } else if(hours<12) { Toast.makeText(context, "Time saved is "+hours+" : "+minute+" AM", Toast.LENGTH_SHORT).show(); } else if(hours==12) { Toast.makeText(context, "Time saved is "+hours+" : "+minute+" PM", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(context, "Time saved is "+(hours-12)+" : "+minute+" PM", Toast.LENGTH_SHORT).show(); } } } And then call it in your activities with: Utils.displayTime(this, 12, 45);
{ "language": "en", "url": "https://stackoverflow.com/questions/7527067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to merge module in dll project and define .def file I have a code of dll which were created by MS Visual Studio 6.0 and and quite old build environment and it contain various modules in it,and platform was Pocket PC 2003(ARMV4). Now I have to convert the solution platform at WIN32 on vs2008.So first I have to convert all the module(all the subproject were static library in vc++) in vs2008.and now we have to merge all the module in one project(dll).So how to merge all the project and how to define single .def file for the main project.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to document and use enum-like data types in Python? Let's assume that the current code is using strings for parameters and you want to document their valid values. Example def MyFunc(region = None): if region in ['A','B','C', None]: # dosomething else: # complain about invalid parameter Now the question is how can I improve this design in order to solve two problems: * *be able to use the auto-complete functionality in IDEs to auto-complete with possible values for the parameter. *document the list of valid values for the parameter (currently the code is documented using doxygen) A: Here is a similar question: How can I represent an 'Enum' in Python? It suggests implementing something like: class MyClass : A = 0 """The Letter A""" B = 1 """The Letter B""" C = 2 """The Letter C""" D = 3 """The Letter D""" variable = MyClass.A # Ok variable = MyClass.E # Error With this you get your IDE auto-complete as well. (Which contrary to S.Lott's opinion, I use all the time... old java habit I guess). It's considered poor style to use a docstring to restate the obvious, and I think in this case makes the code readability worse. For more information on docstrings: http://www.python.org/dev/peps/pep-0257/ If you're curious why there is no enum type in Python, you might check out the PEP: http://www.python.org/dev/peps/pep-0354/ A: Enums are supported as of 3.4: https://docs.python.org/3.4/library/enum.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7527077", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Difference between "memory cache" and "memory pool" By reading "understanding linux network internals" and "understanding linux kernel" the two books as well as other references, I am quite confused and need some clarifications about the "memory cache" and "memory pool" techniques. 1) Are they the same or different techniques? 2) If not the same, what makes the difference, or the distinct goals? 3) Also, how does the Slab Allocator come in? A: Regarding the slab allocator: So imagine memory is flat that is you have a block of 4 gigs contiguous memory. Then one of your programs reqeuests a 256 bytes of memory so what the memory allocator has to do is choose a suitable block of 256 bytes from this 4 gigs. So now you your memory looks something like <============256bytes=======================> (each = is a contiguous block of memory). Some time passes and a lot of programs operating with the memory require more 256 blocks or more or less so in the end your memory might look like: <==256==256=256=86=68=121===> so it gets fragmented and then there is no trace of your beautiful 4gig block of memory - this is fragmentation. Now, what the slab allocator would do is keep track of allocated objects and once they are not used anymore it will say that the memory is free when in fact it will be retained in some sort of List (You might wanna read about FreeLists). So now imagine that the first program relinquish the 256 bytes allocated and then a new would like to have 256 bytes so instead of allocating a new chunk of the main memory it might re-use the lastly freed 256 bytes without having to go through the burden of searching the physical memory for appropriate contiguous block of space. This is how you essentially implement the memory cache. This is done so that memory fragmentation is reduced overall because you might end up in situation where memory is so fragmented that it is unusable and the memory-manager has to do some magic to get you block of appropriate size. Where as using a slab allocator pro-actively combats (but doesn't eliminate) the problem. A: Linux memory allocator A.K.A slab allocator maintains the frequently used list/pool of memory objects of similar or approximate size. slab is giving extra flexibility to programmer to create their own pool of frequently used memory objects of same size and label it as programmer want,allocate, deallocate and finally destroy it.This cache is known to your driver and private to it.But there is a problem, during memory pressure there are high chances of allocation failures which could be not acceptable in some drivers, then what to do better always reserve some memory handy so that we never feel the memory crunch, since kmem cache is more generic pool mechanism we need some one who can always maintain minimum required memory and that's our buddy memory pool . A: Lookaside Caches - The cache manager in the Linux kernel is sometimes called the slab allocator. You might end up allocating many objects of the same size over and over so by using this mechanism you just can allocate many objects in the same size and then use them later, without the need to allocate many objects over and over. Memory Pool is just a form of lookaside cache that tries to always keep a list of memory around for use in emergencies, so when the memory pool is created, the allocation functions (slab allocators) create a pool of preallocated objects so you can acquire them when you need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527080", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: multi-upload images in ror which is the best way to handle multi-upload via AJAX in a RoR 3 app? I read a lot of stuff about swfupload, pupload and so on, a suggestion about the best way to attempt is welcome! Thanks A: have you tried swfupload? Its easy to use with rails3 + paperclip/attachment_fu The article is written with rails 2 there are small fixes that you need to do then this will work fine. Take a look on following link. http://jimneath.org/2008/05/15/swfupload-paperclip-and-ruby-on-rails.html A: I'd go with Uploadify + Carrierwave. Here is a good tutorial for a Rails 3 application: Multifile upload with uploadify and carrierwave
{ "language": "en", "url": "https://stackoverflow.com/questions/7527081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dual-Side Templating vs. Server-Side DOM Manipulation I'm making an app that requires dynamic content be fully rendered on the page for search engine bots - a problem, potentially, should I use JS templating to control the content. Web spiders are supposedly getting better at indexing RIA sites, but I don't want to risk it. Also, as mobile internet is still spotty in most places, it seems like a good practice to maximize the server load initially to ensure that basic functionality/styles/dynamic content show up on your pages, even if the client hasn't downloaded any JS libraries. That's how I stumbled upon dual-side templating: Problem: How can you allow for dynamic, Ajax-style, rendering in the browser, but at the same time output it from the server upon initial page load? c. 2010: Dual-Side Templating A single template is used on both browser and server, to render content wherever it’s appropriate – typically the server as the page loads and the browser as the app progresses. For example, blog comments. You output all existing comments from the server, using your server-side template. Then, when the user makes a new comment, you render a preview of it – and the final version – using browser-side templating. I want to try dual-side templating with Node.js and Eco templates, but I don't know how to proceed. I'm new to JavaScript and all things Node. Node-Lift is said to help, but I don't understand what it's doing or why. Can someone provide a high level overview of how you might use dual-templating in the context of a mobile web app? Where does server-side DOM manipulation with jQuery and JSDOM fit in to the equation? TIA A: Dav Glass gave a great talk about this last year: http://www.youtube.com/watch?v=bzCnUXEvF84 And here is a blog article that goes over some of the details: http://www.yuiblog.com/blog/2010/04/09/node-js-yui-3-dom-manipulation-oh-my/
{ "language": "en", "url": "https://stackoverflow.com/questions/7527083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Scrolling a scrollbar with the TK GUI How can a TkScrollbar be scrolled with code? Neither .scroll nor .autoscroll are recognised. test = TkScrollbar.new(root).pack('side'=>'right', 'fill'=>'y') test.scroll(1) test.autoscroll Edit: Forgot the link to the doc: http://ruby-doc.org/stdlib/libdoc/tk/rdoc/classes/Tk/Scrollbar.html A: I have no experience with ruby and tk, but with other tk bindings (python and tcl, to be precise), when you want to scroll something programmatically you don't move the scrollbar, you directly scroll whatever it is you want scrolled. The scrollbar will update itself to reflect the changes. You scroll an object by using its xview and yview methods. I assume (but don't know for a fact) those are exposed in the ruby bindings.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to query MongoDB from R? I want to get a MongoDB query from R. With the mongo shell, I would query with: db.user.find({age:{$gt:21}}) However, In R-Mongo, I haven't found how to describe this query. Thanks A: If you are using RMongo, the query would be: dbGetQuery(mongo, "user","{'age':{'$gt': 21}}}") The result of dbGetQuery() will be a Data Frame. A: If you are using rmongodb (there is a similar package called Rmongo): r <- mongo.find(mongo, "test.user", list(age=list('$gt'=21L))) the BSON query object can also be built like so: buf <- mongo.bson.buffer.create() mongo.bson.buffer.start.object(buf, "age") mongo.bson.buffer.append(buf, "$gt", 21L) mongo.bson.buffer.finish.object(buf) query <- mongo.bson.from.buffer(buf) r <- mongo.find("mongo", "test.user", query) A: I have also written light interface to R of the pymongo package (the official API for python) https://github.com/RockScience/Rpymongo/blob/master/Rpymongo.r It mimics as close as possible the functions and arguments on the official page of the API http://api.mongodb.org/python/current/api/pymongo/collection.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7527088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Multiple select in Mobile Safari I have a multiple select with the first option as "All" and other options. What I'm trying to do is when "All" is selected, A, B, C, D will deselect but A, B, C, D is selected, "All" is unselected. HTML: <select name="filter" id="filter-select" multiple="multiple"> <option id="All" value="All">All</option> <option id="A" value="A">A</option> <option id="B" value="B">B</option> <option id="C" value="C">C</option> <option id="D" value="D">D</option> <option id="E" value="E">E</option> <option id="F" value="F">F</option> <option id="G" value="G">G</option> <option id="H" value="H">H</option> </select> JavaScript: function UnselectAll() { var select = document.getElementById('filter-select'); if(select.options[select.selectedIndex].id != 'All' ) { select[0].selected = false; } else { for(var x = 0; x < select.length; x++) { select[x].selected = false; } } } document.getElementById('filter-select').addEventListener('change', UnselectAll, false); My problem is that as you select the options, they will not display the unselection till you scroll out of view within the select box. Please assist. Thanks A: Small typo - You are clearing 0 together with other options, so one little change will help : for(var x = 1; x < select.length; x++) {
{ "language": "en", "url": "https://stackoverflow.com/questions/7527096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Currency formatting using Western digits I need to be able to display currency amounts where the currency is of the user's preferred locale, but using only Western digits. For example, if the user's chosen locale for the currency is ar_AE (for the United Arab Emirates) then the amount should be displayed as AED 1,234.56 or something similar, using the correct currency name and number of decimal places, but using Western digits. At the moment, I'm using NumberFormat.getCurrencyInstance(locale) which formats the text using Arabic glyphs. What options do I have? I'm looking for a general solution which won't require me to have specific knowledge of any given currency. A: If you want a currency formatter with number formatting according to the English locale, but using the default locale's currency, I would try something like this: NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.ENGLISH); nf.setCurrency(Currency.getInstance(Locale.getDefault())); A: You might use DecimalFormat like this: System.out.println(new DecimalFormat( "AED #0.00" , new DecimalFormatSymbols( Locale.ENGLISH)).format( 1.23 )); Edit: to use the locale for currency too, try this: System.out.println(Currency.getInstance( Locale.GERMANY ).getCurrencyCode() + " " + new DecimalFormat( "#0.00" , new DecimalFormatSymbols( Locale.GERMANY )).format( 1.23 )); Prints: EUR 1,23
{ "language": "en", "url": "https://stackoverflow.com/questions/7527098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery slow fade element on interval and fade back in if user hovers I'm using jQuery to show some notifications to the user which will appear on screen using the jQuery append method. Once they appear on screen I want to wait say 5 seconds and THEN slowly begin to fade the element out before removing it from the DOM. It should only begin its fade after 5 seconds and not start fading straight away. If a user hovers the element then it should fade the element back in and then when the user removes hover then it should begin fading out again. I have this so far: setTimeout(function() { $(".Notification").fadeOut("slow", function () { $(this).remove(); }); }, 5000); So this fades out the element after the time out but how do I make it so when a user hovers the element it fades back in. When the user removes hover it will begin fading out again (note: we don't need to wait anymore just reverse the fade everytime they hover the element unless it gets to the end of its fade and is removed) Can anyone help? I presume it's just a simple case of wrapping the fadeOut part with some additional code but I'm struggling and would appreciate some help. Also their could be multiple notifications appearing on the page so they all need to fade out based on their own appearance on screen and not fade them all out at the same time. Effectively this is mimicking the new mail box you see in the bottom right of your screen when using Microsoft Outlook. Thanks A: Actually, you don't need a setTimeout. jQuery has got a .delay() function for animations. /* Initial delay and fading out for 5s */ $(".Notification").delay(5000).fadeOut(5000); /* If hover, stop the ongoing (or delayed) fadeout, and fadein fast */ $(".Notification").mouseenter(function(){ $(this).stop(true, false).fadeIn(500); }); /* If mouseout, set the element to fadeout slowly after 5s */ $(".Notification").mouseleave(function(){ $(this).delay(5000).fadeOut(5000); }); I haven't tried this actual example, but something like this should do it. A: assign your setTimeout to a variable. Call clearTimeout on this variable when the user hovers over it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# Com OLE Server I am trying to figure out the best way to interact with an OLE Server using C# .NET i have found some code that enables interaction with COM+ that appears to work for the OLE server but I wonder if there is a more elegant or simpler way? I require that it be late bound. Code (as pilfered from elsewhere on the net) // Code start Type excel; object[] parameter = new object[1]; object excelObject; try { //Get the excel object excel = Type.GetTypeFromProgID("Excel.Application"); //Create instance of excel excelObject = Activator.CreateInstance(excel); //Set the parameter whic u want to set parameter[0] = true; //Set the Visible property excel.InvokeMember("Visible", BindingFlags.SetProperty, null, excelObject, parameter); Obviously in my case I am putting the name of my ole server in where Excel.Application is, but I have seen cases in EARLY binding where you can call the function directly off the object without having to go via 'InvokeMember' Is this possible? Can I use Type to cast as object as my type? Thanks. A: If you are using .NET 4.0 you can use dynamic instead of object and invoke the members as if they were there. This will then be checked at runtime, and if the name is correct, execute it. //Get the excel object var excel = Type.GetTypeFromProgID("Excel.Application"); //Create instance of excel dynamic excelObject = Activator.CreateInstance(excel); excelObject.Visible = true; A: Try having a look at this from the add references. It gives you useful access to Excel. Microsoft.Office.Core Microsoft.Office.Interop.Excel using Excel = Microsoft.Office.Interop.Excel; ... if (openFileDialog.ShowDialog() == DialogResult.OK) { Excel.Application app; Excel.Workbook workbook; app = new Excel.ApplicationClass(); app.AutomationSecurity = Microsoft.Office.Core.MsoAutomationSecurity.msoAutomationSecurityForceDisable; workbook = app.Workbooks.Open( openFileDialog.FileName, 0, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); return workbook; } Cells and worksheets etc can be accessed like this: Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets.Item[1]; worksheet.Cells.Item[6, 1]).Value;
{ "language": "en", "url": "https://stackoverflow.com/questions/7527114", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Search in many-to-many relationship with Doctrine2 This is probably an easy one but I can't figure it out nor find an answer. I have a simple Article and ArticleTag Entities with many to many relationship. How can I get all articles with a certain tag (or tags)? My following tries: $qb = $repository->createQueryBuilder('a') // ... ->andWhere('a.tags = :tag') ->setParameter('tag', 'mytag') // ... or ->andWhere(':tag in a.tags') ->setParameter('tag', 'mytag') ...didn't work. Thanks! A: And the winner is ... drumroll, please ... $qb = $repository->createQueryBuilder('a') // ... ->andWhere(':tag MEMBER OF a.tags'); ->setParameter('tag', $tag); // ... Thanks to everyone who has taken the time to read and think about my question! A: I think you can adаpt this example (from documentation): $query = $em->createQuery('SELECT u.id FROM CmsUser u WHERE EXISTS (SELECT p.phonenumber FROM CmsPhonenumber p WHERE p.user = u.id)');
{ "language": "en", "url": "https://stackoverflow.com/questions/7527118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: redeem code for app in iTunes Store, still valid when new version accepted? i've recently uploaded my first app on iTunes Store, it's been accepted and now it's on-line. i've downloaded some promo code (redeem) and eMailed away to let them download it free and try it. but now i saw there was a (little) error in my app and wanted to submit a new corrected version. my question is: what happen if apple accepts my new version, will the redeem code still work, is someone has not used it before? i know that developer can ask 50 redeem for every version of an app, so i guess that they are linked just to that version... has someone here an experience about that? thanks, luca A: The promo codes are still valid (but only for the rest of the 28-day-period after they've been requested) after the update is live. See iTunes Connect Promo Codes & App Updates.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mongodb: how to debug map/reduce on mongodb shell I am new to MongoDB, I am using map/reduce. Can somebody tell me how to debug while using map/reduce? I used "print()" function but on MongoDB shell, nothing is printed. Following is my reduce function: var reduce = function(key, values){ var result = {count: 0, host: ""}; for(var i in values){ result.count++; result.host = values[i].host; print(key+" : "+values[i]); } return result; } when I write the above function on shell and the press Enter after completing, nothing gets printed on the shell. Is there anything else I should do to debug? Thanks A: Take a look at this simple online MongoDB MapReduce debugger which allows to get aggregation results on sample data as well as perform step-by-step debugging of Map / Reduce / Finalize functions right in your browser dev environment. I hope it will be useful. http://targetprocess.github.io/mongo-mapreduce-debug-online/ A: There is a dedicated page on the mongodb website which is your answer : http://www.mongodb.org/display/DOCS/Troubleshooting+MapReduce and obviously your reduce is wrong : the line result.count++ will end up containing the number of elements contained in the array values which (in map reduce paradigm) does not mean anything. Your reduce function is just returning a "random" hostname (because mapreduce algo is not predicable on the reduce content at any step) and a random number. Can you explain what you want to do ? (my guess would be that you want to count the number of "something" per host) A: It seems that print() statements in reduce functions are written to the log file, rather than the shell. So check your log file for your debug output. You can specify the log file by using a --logpath D:\path\to\log.txt parameter when starting the mongod process.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Convert NSString UPPERCASE into Capitalized I have some strings like NAVJYOT COMPLEX, NEAR A ONE SCHOOL, SUBHASH CHOWK , MEMNAGAR, Ahmedabad, Gujarat, India. I want to convert them so the first character is uppercase and remaining are lowercase, e.g: Navjyot Complex, Near A One School, Subhash Chowk, Memnagar, Ahmedabad, Gujarat, India. So please help me convert those strings. Thanks in advance. A: use This one NSString *str1 = @"ron"; NSString *str = [str1 capitalizedString]; A: nsstring has the following method capitalizedString it returns: "A string with the first character from each word in the receiver changed to its corresponding uppercase value, and all remaining characters set to their corresponding lowercase values." http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7527128", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Getting Graphics-Object or Bitmap from BrowserField on Blackberry I would like to get the Bitmap of the content of a webpage as it is displayed in the BrowserField. Therefore I'd need the Graphic-object of the browser field. But the paint-method is protected unfortunately. Is there a way to get this? Thank's A: Normally, if you want to do some custom drawing with a field ie. draw into the field's graphics context, you'd subclass Field and override the paint method. However, when it comes to BrowserField, you can't do that because it's declared final. There is a workaround for this, though. You can subclass a Manager and add your BrowserField to an instance of that manager. So, for example, if you want to add your BrowserField instance to a VerticalFieldManager, you can use the following code to get access to the Graphics object the browser will be drawn into. In this sample code, you'll see that I use the graphics object and manager's superclass implementation to draw into a bitmap. Then, that bitmap is drawn to the screen. VerticalFieldManager vfm = new VerticalFieldManager() { // Override to gain access to Field's drawing surface // protected void paint(Graphics graphics) { // Create a bitmap to draw into // Bitmap b = new Bitmap(vfm.getVirtualWidth(), vfm.getVirtualHeight()); // Create a graphics context to draw into the bitmap // Graphics g = Graphics.create(b); // Give this graphics context to the superclass implementation // so it will draw into the bitmap instead of the screen // super.paint(g); // Now, draw the bitmap // graphics.drawBitmap(0, 0, vfm.getVirtualWidth(), vfm.getVirtualHeight(), b, 0, 0); } }; And, there you have a Bitmap containing the contents of the manager. Should note, though, that this has the potential to consume a lot of memory.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: IE9 CSS hack for background-position? I need an IE9 CSS hack to be able to set the background-position property differently for IE9. I have tried with several different ones that didn't work and from what I read somewhere, the background property is not possible to "hack" at least the same way as the other. I basically need this to only apply to IE9: #ABB_ABContent .subnav li.selected { background-position: center 17px; } Any suggestions? A: If you can't find anything else, there's always conditional comments: <!--[if IE 9]> IE9-specific code goes here <![endif]--> This would have to live in your HTML code, rather than your stylesheet, but you could use it to include an additional CSS file for IE9. Alternatively, you may want to look up the Modernizr library. This is a small Javascript tool which you add to your site, which detects what features your browser supports, and allows you to write your CSS to target specific features (or their absence). If there's something about IE9 that it doesn't support which you're trying to work around, this may be the best solution. I'm still puzzled as to what problem you're trying to solve though. A: <!--[if IE 9]> <link rel="stylesheet" type="text/css" href="your path" /> <![endif]-->
{ "language": "en", "url": "https://stackoverflow.com/questions/7527132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Drag and drop XCodeProj into another XCodeProj not giving me the option to copy I'm trying to "install" core plot 0.4. The first instruction is to drag and drop the XCodeProj file into my own project. I do this. Normally when I drag and drop images or the such like it asks me if I want to copy the file into my own project. However for some reason its not asking me, its just creating a reference. I'm not sure what the difference is, and whether it will still work or not with a reference, its just the first instruction (http://recycled-parts.blogspot.com/2011/07/setting-up-coreplot-in-xcode-4.html) says to click the "copy into folder" checkbox. However that whole dialogue doesn't come up. I drag and drop and it puts the xcodeproj into mine without anything happening! confused lol Thanks A: Edit: My solution works, but the reason it works is in this answer: https://stackoverflow.com/a/5373575/264947 -- This is what I did to fix it: * *Close Xcode. *Open Xcode and create a new workspace. *File > Add files to "Workspace". *Add the first project. *Build to make sure it builds correctly. *File > Add files to "Workspace". *Add the second project. *Build to make sure it builds correctly. *Drag one project into another. Now, be careful with the next step: Erase the second standalone project but choose **REMOVE REFERENCES. ** There. Now you should have one project as a dependent of another project.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TimePicker - how to get AM or PM? I want to set an alarm based on a user's selection in TimePicker. TimePicker is set to AM/PM mode. In order to know if a user wants his alarm to set to 10 AM or 10 PM, how should I get the AM/PM value? The listener TimePickerDialog.OnTimeSetListener passes only hours and minutes. A: I did it using Calendar, and that should work on all versions: public void onTimeSet(TimePicker view, int hourOfDay, int minute){ String am_pm = ""; Calendar datetime = Calendar.getInstance(); datetime.set(Calendar.HOUR_OF_DAY, hourOfDay); datetime.set(Calendar.MINUTE, minute); if (datetime.get(Calendar.AM_PM) == Calendar.AM) am_pm = "AM"; else if (datetime.get(Calendar.AM_PM) == Calendar.PM) am_pm = "PM"; String strHrsToShow = (datetime.get(Calendar.HOUR) == 0) ?"12":Integer.toString( datetime.get(Calendar.HOUR) ); ((Button)getActivity().findViewById(R.id.btnEventStartTime)).setText( strHrsToShow+":"+datetime.get(Calendar.MINUTE)+" "+am_pm ); } Notice the use of Calendar.HOUR_OF_DAY and Calendar.HOUR if you go to the documentation of both you'd know the trick. A: Here I'm taking the current date and time from the system and updating it with date and time picker dialog private int mMonth,mYear,mDay,mHour,mMin; public static final int DTPKR = 1; public static final int TMPKR = 2; // Getting the current date and time into DatePicker dialog public void getCurrentDate(){ final Calendar c = Calendar.getInstance(); mYear = c.get(Calendar.YEAR); mMonth = c.get(Calendar.MONTH); mDay = c.get(Calendar.DAY_OF_MONTH); } public void getCurrentTime(){ final Calendar c = Calendar.getInstance(); mHour = c.get(Calendar.HOUR_OF_DAY); mMin = c.get(Calendar.MINUTE); } Now create the dialogs and update the values //Creating dialogs protected Dialog onCreateDialog(int id) { switch (id) { case DTPKR: return new DatePickerDialog(this,lisDate, mYear, mMonth, mDay); case TMPKR: return new TimePickerDialog(this,lisTime,mHour, mMin, false); } return null; } //setting date and updating editText DatePickerDialog.OnDateSetListener lisDate = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { mYear = year; mMonth = monthOfYear; mDay = dayOfMonth; etDate.setText(new StringBuilder() .append(mDay).append("/").append(mMonth+1).append("/").append(mYear)); getCurrentDate(); } }; //setting time and updating editText TimePickerDialog.OnTimeSetListener lisTime=new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { mHour=hourOfDay; mMin=minute; String AM_PM ; if(hourOfDay < 12) { AM_PM = "AM"; } else { AM_PM = "PM"; mHour=mHour-12; } etTime.setText(mHour+":"+mMin+" "+AM_PM); getCurrentDate(); } }; A: Above answers are right i found simplest way to find AM PM. TimePickerDialog.OnTimeSetListener onStartTimeListener = new OnTimeSetListener() { public void onTimeSet(TimePicker view, int hourOfDay, int minute) { String AM_PM ; if(hourOfDay < 12) { AM_PM = "AM"; } else { AM_PM = "PM"; } mStartTime.setText(hourOfDay + " : " + minute + " " + AM_PM ); } }; A: On callback from public void onTimeSet(TimePicker view, int hourOfDay, int minute) call below function private String getTime(int hr,int min) { Time tme = new Time(hr,min,0);//seconds by default set to zero Format formatter; formatter = new SimpleDateFormat("h:mm a"); return formatter.format(tme); } The functions return something like this 1:12 PM A: Not sure if it'll help but I am kind of working on the same thing. See my reply here TimePickerDialog and AM or PM A: You can get AM/PM from Timepicker using following method. Timepicker is a viewgroup.That's why we can get its child view index 2 which demonstrates AM/PM is actually a button. So we can get its text. Mycallback=new OnTimeSetListener() { public void onTimeSet(TimePicker view, int hourOfDay, int minute) { ViewGroup vg=(ViewGroup) view.getChildAt(0); Toast.makeText(TimePickerDemoActivity.this, hourOfDay+":"+minute+":"+((Button)vg.getChildAt(2)).getText().toString(), 5000).show(); } }; A: I would've preferred to leave this as a comment, but I don't have enough reputation. By far the most succinct way to get AM or PM is using the ternary operator: String am_pm = (hourOfDay < 12) ? "AM" : "PM"; A: I think callback will be called with hour in 24-format because. Dialog uses TimePicker internally. And TimePicker has getCurrentHour moethod, which returns hour in 0-23 format. A: e.g : TimePicker sellerTime = (TimePicker) findViewById(R.id.sellerTime); Integer.toString(((sellerTime.getCurrentHour().intValue()) > 12) ? ((sellerTime.getCurrentHour().intValue()) - 12) : (sellerTime.getCurrentHour().intValue())
{ "language": "en", "url": "https://stackoverflow.com/questions/7527138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: How to create custom dialog which contain different UI in windows phone 7 I want to show any screen as a dialog. This is my main requirement, but if this is not possible second thing is: I have to create one custom dialog which contain different UI. From above any one of requirement I have to fulfill. A: The Coding4Fun Windows Phone Toolkit contains classes that you can use to display a modal/popup prompt for displaying information or getting input from the user.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iPhone MIMChartLib Chart Drawing: How can i set the Y-axis starting from 18000 but not 0? I am now using MIMChartLib to developer Iphone Chart, But i am having trouble about the line chart, for example here is my CSV Time;NAME;value001;value002;value003;value004; 01:00.0;ABCABC;1837;1837.2;1836.5;1831 02:00.0;ABCABC;1836.7;1837;1836.5;1836.7 03:00.0;ABCABC;1827;1827.2;1816.5;1826.9 04:00.0;ABCABC;1837;1837.2;1836.5;1836.9 05:00.0;ABCABC;1837;1837.2;1836.5;1836.9 How can i set the Y axis to be 18000, but not start from zero. otherwise,the chart will show really really small. here is preview: here is my code /* Date;Time;Currency;Bid;Ask 14/9/2011;00:03.0;LLGUSD;1836.5;1837 */ [MIMColor InitColors]; NSString *csvPath1 = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"myTableBar.csv"]; //LineGraph *lineGraph=[[LineGraph alloc]initWithFrame:CGRectMake(100, 20, 220, 380)]; LineGraph *lineGraph=[[LineGraph alloc]initWithFrame:Chartarea.frame]; lineGraph.needStyleSetter=YES; lineGraph.xIsString=YES; lineGraph.anchorType=CIRCLEBORDER; //OTHER anchorType [lineGraph readFromCSV:csvPath1 titleAtColumn:1 valueInColumn:[NSArray arrayWithObjects:@"1",@"3", nil]]; [lineGraph displayYAxis]; [lineGraph displayXAxisWithStyle:5]; //OTHER styles FOR X-Axis Labels [lineGraph drawWallGraph]; [self.view addSubview:lineGraph]; Thank you very much!! A: go this link https://github.com/ReetuRaj/MIMChart-Library in YAxisBand.m file u have this method it work for me..... -(void)setScaleForYTile:(float)value withNumOfLines:(int)numOfHorLines { pixelPerYTile=18000000.0; //pixelPerYTile=value; HorLines=numOfHorLines; [self setNeedsDisplay]; } A: go this link https://github.com/ReetuRaj/MIMChart-Library In MIMLineGraph.m go to the function -(void)_findScaleForYTile and REMOVE the following code minOfY=[MIM_MathClass getMinFloatValue:[_yValElements objectAtIndex:0]]; for (int i=1; i<[_yValElements count]; i++) { float minOfY1=[MIM_MathClass getMinFloatValue:[_yValElements objectAtIndex:i]]; if(minOfY1<minOfY) minOfY=minOfY1; } and set the value of minOfY directly as zero instead of doing the above calculation minOfY = 18000000.0; NOTE: in MIMChartLib minimum value plotted in yaxis will be the smallest value that you give in CSV file for plotting..so if u need to start yaxis from 18000000.0 then if the minimum value in your CSV file is the same then MIMCHART will automatically set the starting value of yaxis as 18000000.0
{ "language": "en", "url": "https://stackoverflow.com/questions/7527140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get the ipod path or save the document files path ipod? I am working in iphone technology. How to get the path in iphone or ipod. I get the path only particular app.What is the coding for get the full documents directory. I am using following code,that is work and display for particular directory - (void)listFiles { int count, i; NSError *err; NSArray *directoryContent; NSArray *myPathList = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [myPathList objectAtIndex:0]; NSLog(documentsDirectory); directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error: err]; count = (int)[directoryContent count]; for (i=0; i<count; i++) { self.listData = directoryContent; //[directoryContent release]; // tableview = [tableview stringByAppendingString:[directoryContent objectAtIndex:i]]; // tableview = [tableview stringByAppendingString:@"\n"]; } } A: On iOS each app is restricted to an application sandbox. That sandbox restricts your application from accessing any portion of the filesystem other than what Apple allows you to access. So the following code would produce the Documents directory for your specific application, but in general there is not any "full documents directory". In other words there is no way to access documents belonging to another application. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0];
{ "language": "en", "url": "https://stackoverflow.com/questions/7527144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Change default configuration on Hadoop slave nodes? Currently I am trying to pass some values through command line arguments and then parse it using GenericOptionsParser with tool implemented. from the Master node I run something like this: bin/hadoop jar MYJAR.jar MYJOB -D mapred.reduce.tasks=13 But this only get applied on the Master!! Is there any way to make this applied on the slaves as well? I use Hadoop 0.20.203. Any help is appreciated. A: But this only get applied on the Master!! Is there any way to make this applied on the slaves as well? According to the "Hadoop : The Definitive Guide". Setting some of the property on the client side is of no use. You need to set the same in the configuration file. Note, that you can also create new properties in the configuration files and read them in the code using the Configuration Object. Be aware that some properties have no effect when set in the client configuration. For example, if in your job submission you set mapred.tasktracker.map.tasks.maximum with the expectation that it would change the number of task slots for the tasktrackers running your job, then you would be disappointed, since this property only is only honored if set in the tasktracker’s mapred-site.html file. In general, you can tell the component where a property should be set by its name, so the fact that mapred.task.tracker.map.tasks.maximum starts with mapred.tasktracker gives you a clue that it can be set only for the tasktracker daemon. This is not a hard and fast rule, however, so in some cases you may need to resort to trial and error, or even reading the source. You can also configure the environment of the Hadoop variables using the HADOOP_*_OPTS in the conf/hadoop-env.sh file. Again, according to the "Hadoop : The Definitive Guide". Do not confuse setting Hadoop properties using the -D property=value option to GenericOptionsParser (and ToolRunner) with setting JVM system properties using the -Dproperty=value option to the java command. The syntax for JVM system properties does not allow any whitespace between the D and the property name, whereas GenericOptionsParser requires them to be separated by whitespace. JVM system properties are retrieved from the java.lang.System class, whereas Hadoop properties are accessible only from a Configuration object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Prevent a process from starting and block its launching My problem is the next : When an user hold search's button on an android phone, and this, while a progress bar is in action, the following error message is displayed: ERROR / AndroidRuntime ( 16794 ): java.lang. SecurityException: Requesting codes from com.google.android.voicesearch (with uid 10028) to be run in process com.xxxx.myApplication (with uid 10088) Thus, further to this message I tried several things: kill the process ' com.google.android.voicesearch ' : JAVA code : if (event.getKeyCode() == KeyEvent.KEYCODE_SEARCH) { if (!event.isLongPress() && !Utils.getMyProgress().isShowing()) { searchProducts(); } else { android.os.Process.killProcess(android.os.Process.getUidForName("com.google.android.voicesearch")); } return true; } Unsuccessfully! Thus the idea is to prevent the process 'com.google.android.voicesearch' from being started every time the user of the telephone maintainings for a long time the key(touch) "to look for" of its telephone (example on htc, this key(touch) exists. Rather, a physical and not tactile key(touch)!) Maybe is it possible to block the launch of this process ('com.google.android.voicesearch') in the in the manifest.xml, while my application is launched : manifest.xml : <application android:debuggable="false" android:enabled="false" android:killAfterRestore="false" android:process="com.google.android.voicesearch"> </application> Any idea ? Thanks for answers ! A: In order to implement search with assistance from the Android system (to deliver search queries to an activity and provide search suggestions), your application must provide a search configuration in the form of an XML file called the searchable configuration. It configures certain UI aspects of the search dialog or widget and defines how features such as suggestions and voice search behave. This file is traditionally named searchable.xml and must be saved in the res/xml/ project directory. According to this page, you only have to remove the voice entries from that file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error when deploying site of a maven multi module project with FTP I have a multi module project. When I launch mvn site:deploy, the deployment of the base module works fine, but it fails to create the directory of the module sites on the FTP server: [INFO] Error uploading site Embedded error: Required directory: '/myremoteftprepository/myproject-mymodule' is missing When I create the missing directory by hand, it works fine, but I would like to avoid that. It is surprising that the deploy command do not create it. Do you how to force this directory creation? Is it a bug in the wagon-ftp plugin? FYI, here is my POM: <build> <extensions> <!-- Enabling the use of FTP --> <extension> <groupId>org.apache.maven.wagon</groupId> <artifactId>wagon-ftp</artifactId> <version>1.0</version> </extension> </extensions> </build> I have chosen to include the javadoc with: <reporting> <plugins> <!-- include javadoc in the site --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>2.8</version> <configuration> <show>public</show> </configuration> </plugin> </plugins> </reporting> and <distributionManagement> <site> <id>site</id> <name>maven site</name> <url>ftp://ftp.blabla.org/myremoteftprepository</url> </site> </distributionManagement> and my settings.xml is good. A: You should not launch the site:deploy goal, but rather the site-deploy Maven lifecycle phase e.g. like that mvn clean install site-deploy and also make sure that the latest version of your wagon transport is used (2.2). Also for javadoc plugin you should configure it as reporting plugin under the configuration of the maven site plugin. A: With the most recent version of wagon-ftp (2.2), it works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: div with dynamic min-height based on browser window height I have three div elements: one as a header, one as a footer, and a center content div. the div in the center needs to expand automatically with content, but I would like a min-height such that the bottom div always at least reaches the bottom of the window, but is not fixed there on longer pages. For example: <div id="a" style="height: 200px;"> <p>This div should always remain at the top of the page content and should scroll with it.</p> </div> <div id="b"> <p>This is the div in question. On longer pages, this div needs to behave normally (i.e. expand to fit the content and scroll with the entire page). On shorter pages, this div needs to expand beyond its content to a height such that div c will reach the bottom of the viewport, regardless of monitor resolution or window size. </div> <div id="c" style="height: 100px;"> <p>This div needs to remain at the bottom of the page's content, and scroll with it on longer pages, but on shorter pages, needs to reach the bottom of the browser window, regardless of monitor resolution or window size.</p> </div> A: to get dynamic height based on browser window. Use vh instead of % e.g: pass following height: 100vh; to the specific div A: As mentioned elsewhere, the CSS function calc() can work nicely here. It is now mostly supported. You could use like: .container { min-height: 70%; min-height: -webkit-calc(100% - 300px); min-height: -moz-calc(100% - 300px); min-height: calc(100% - 300px); } A: Just look for my solution on jsfiddle, it is based on csslayout html, body { margin: 0; padding: 0; height: 100%; /* needed for container min-height */ } div#container { position: relative; /* needed for footer positioning*/ height: auto !important; /* real browsers */ min-height: 100%; /* real browsers */ } div#header { padding: 1em; background: #efe; } div#content { /* padding:1em 1em 5em; *//* bottom padding for footer */ } div#footer { position: absolute; width: 100%; bottom: 0; /* stick to bottom */ background: #ddd; } <div id="container"> <div id="header">header</div> <div id="content"> content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/>content<br/> </div> <div id="footer"> footer </div> </div> A: I found this courtesy of ryanfait.com. It's actually remarkably simple. In order to float a footer to the bottom of the page when content is shorter than window-height, or at the bottom of the content when it is longer than window-height, utilize the following code: Basic HTML structure: <div id="content"> Place your content here. <div id="push"></div> </div> <div id="footer"> Place your footer information here. </footer> Note: Nothing should be placed outside the '#content' and '#footer' divs unless it is absolutely positioned. Note: Nothing should be placed inside the '#push' div as it will be hidden. And the CSS: * { margin: 0; } html, body { height: 100%; } #content { min-height: 100%; height: auto !important; /*min-height hack*/ height: 100%; /*min-height hack*/ margin-bottom: -4em; /*Negates #push on longer pages*/ } #footer, #push { height: 4em; } To make headers or footers span the width of a page, you must absolutely position the header. Note: If you add a page-width header, I found it necessary to add an extra wrapper div to #content. The outer div controls horizontal spacing while the inner div controls vertical spacing. I was required to do this because I found that 'min-height:' works only on the body of an element and adds padding to the height. *Edit: missing semicolon A: No hack or js needed. Just apply the following rule to your root element: min-height: 100%; height: auto; It will automatically choose the bigger one from the two as its height, which means if the content is longer than the browser, it will be the height of the content, otherwise, the height of the browser. This is standard css. A: If #top and #bottom have fixed heights, you can use: #top { position: absolute; top: 0; height: 200px; } #bottom { position: absolute; bottom: 0; height: 100px; } #central { margin-top: 200px; margin-bot: 100px; } update If you want #central to stretch down, you could: * *Fake it with a background on parent; *Use CSS3's (not widely supported, most likely) calc(); *Or maybe use javascript to dynamically add min-height. With calc(): #central { min-height: calc(100% - 300px); } With jQuery it could be something like: $(document).ready(function() { var desiredHeight = $("body").height() - $("top").height() - $("bot").height(); $("#central").css("min-height", desiredHeight ); }); A: You propably have to write some JavaScript, because there is no way to estimate the height of all the users of the page. A: It's hard to do this. There is a min-height: css style, but it doesn't work in all browsers. You can use it, but the biggest problem is that you will need to set it to something like 90% or numbers like that (percents), but the top and bottom divs use fixed pixel sizes, and you won't be able to reconcile them. var minHeight = $(window).height() - $('#a').outerHeight(true) - $('#c').outerHeight(true)); if($('#b').height() < minHeight) $('#b').height(minHeight); I know a and c have fixed heights, but I rather measure them in case they change later. Also, I am measuring the height of b (I don't want to make is smaller after all), but if there is an image in there that did not load the height can change, so watch out for things like that. It may be safer to do: $('#b').prepend('<div style="float: left; width: 1px; height: ' + minHeight + 'px;">&nbsp;</div>'); Which simply adds an element into that div with the correct height - that effectively acts as min-height even for browsers that don't have it. (You may want to add the element into your markup, and then just control the height of it via javascript instead of also adding it that way, that way you can take it into account when designing the layout.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7527152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "42" }
Q: wrong number of arguments (0 for 1) (ArgumentError) I am using devise as an authentication system and created a scenario. Scenario: Home page have a login page When I go to the home page And user is not logged in Then I should see "Sign In" for step definition When /^user is not logged in$/ do signed_in? == false end i had also added Devise helpers to the cucumber world. World(Devise::Controllers::Helpers) and cucumber is generating this error: And user is not logged in # features/step_definitions/web_steps.rb:260 wrong number of arguments (0 for 1) (ArgumentError) ./features/step_definitions/web_steps.rb:261:in `/^user is not logged in$/' features/manage_home_page.feature:13:in `And user is not logged in' Why is it generating and how to fix it? Update the definition of signed_in? method is # Return true if the given scope is signed in session. If no scope given, return # true if any scope is signed in. Does not run authentication hooks. def signed_in?(scope=nil) [ scope || Devise.mappings.keys ].flatten.any? do |scope| warden.authenticate?(:scope => scope) end end its defined in Devise and i added that helper to cucumber by writing this code World(Devise::Controllers::Helpers) into cucumber's paths.rb file. A: Try this instead When /^user is not logged in$/ do user_signed_in?.should be_false end UPDATED I think you need to do something like this When /^user is not logged in$/ do |user| #check here user not logged in end or You could try modifying your feature to Scenario: Home page has a login page Given I am on the home page And I am not logged in Then I should see "Sign In" Then in the steps Given /^user is not logged in$/ do visit('users/sign_out') # this will ensure that the user is not logged in end A: I've had problems similar to this which turned out to be the test line matching another step definition somewhere else in my code. It seems unlikely here but do you have anything else which could match to And user is not logged in but which requires an argument?
{ "language": "en", "url": "https://stackoverflow.com/questions/7527157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: addthis make magento bundle product error I got a problem about magento bundle products here. The price won't get updated everytime I make come options change on the products. And I also can't add it to the cart. I've spent several days to find the problem and finally I realize that the problem comes from this addthis snippet that I insert <!-- AddThis Button BEGIN --> <div class="addthis_toolbox addthis_default_style "> <a class="addthis_button_facebook_like" fb:like:layout="button_count"></a> <a class="addthis_button_tweet"></a> <a class="addthis_button_google_plusone" g:plusone:size="medium"></a> <a class="addthis_counter addthis_pill_style"></a> </div> <script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=xa-4e770a31017c7f26"></script> <!-- AddThis Button END --> I put that addthis snippet on my default/template/catalog/product/view.phtml files. I guess it might caused by some conflict between magento's default theme script with the script from addthis. Can anyone help me on this?? or maybe give me a better alternatives other than addthis thank you very much :) A: I had same problem! Try replacing <a class="addthis_button_tweet"></a> with: IFRAME snippet available from https://dev.twitter.com/docs/tweet-button That should work! :) A: I have always been a 'seeder' of stockoverflow, get the information i need then bolt. But i thought id share this little tid bit. Simple tweak i found it in a slightly different place. "app/design/frontend/default/MYTHEME/template/ajax/catalog/product/view.phtml" i just commented out <a class="addthis_button_tweet></a> from there and BOOM. you have no idea the lengths i went to before finding this. Thanks For people looking to solve this problem, i tried just about everything i could find, modifying option.phtml, effects.js, scpoptions.phtml, produt.js etc... and all along it was twitter
{ "language": "en", "url": "https://stackoverflow.com/questions/7527159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MSVC: __declspec(dllexport) does not symbols I have a small issue when it comes to writing a DLL in MSVC (the 2010 version in particular). My program consists of the main part and a DLL. The DLL contains a function that is __declspec(dllexport) int test_function(void) { return 42; } The file is compiled using a DLL project (not using pre-compiled headers, I have chosen a empty DLL project). Now, when I want to list the exported symbols using the dumpbin tool, the test_function is not listed under exports. Is there a specific setting that forces __declspec(dllexport) to actually export symbols? Any help is welcome. Thank you! A: That should do it. If this is the whole code, check the following: 1) You are actually checking the correct dll. Look at the timestamp. Double-check the location and the name. 2) You are compiling the specified cpp (I take it your definition is in the cpp file). Just because the file is in the directory doesn't mean it gets compiled, make sure it is added to the project. 3) Make sure your function is not excluded from the compilation unit by preprocessor directives. Also look for other symbols and try to see what differences are there between the symbols that get exported and your function. If this fails, you should move __declspec(dllexport) to your .h file and the definition (without __declspec(dllexport) ) to your .cpp. It might not be exported because the compiler might try to optimize it out by inlining it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: dropdownlist in footer row of gridview being clear on postback I am using a dropdownlist in footer row of gridview(ASP.Net) and I fill that on rowdatabound event,first time it works fine but when the form is postbacked,dropdown gets cleared. It can be solved by refilling it on each postback,but I want that only single time code binding call fulfill my need, means is there any way to stop from being null on postback. looking for your kind solutions and suggestions Thnx in advance...... Supriya Code: protected void gvProjects_RowDataBound(object sender, GridViewRowEventArgs e) { try { if (gvProjects.Rows.Count > 0 && e.Row.RowIndex != -1) { string proj_Id = Convert.ToString(gvProjects.DataKeys[e.Row.RowIndex].Value); if (e.Row.RowType == DataControlRowType.DataRow) { DropDownList ddlProject = (DropDownList)e.Row.FindControl("ddlProject"); if (ddlProject != null && ddlProject.Items.Count == 0) { objMaster.FillProjects(ddlProject); ddlProject.SelectedValue = proj_Id; } } } } catch (Exception excep) { lbl_msg.Text = excep.Message; } } It's called whenever the grid is binded,can it be avoided. A: protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { FillDropdown(); } } A: With this code you will avoid filling the dropdownlist located in the gridview footer in each rowdatabound: protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType != DataControlRowType.Footer) { //do the binding for the normal rows } } As you can see, the rowdatabound will be only executed on the header and normal rows but not in the footer. Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7527163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spring MVC 3: open ModelAndView in a new tab I am submitting a form in jsp. After running the underlying logic spring mvc returns view. There are 2 conditions. i.e. if(condition1){ mav = new ModelAndView("jspPageName1"); return mav; }else{ mav = new ModelAndView("jspPageName2"); return mav; } I want jspPageName1 to be open in a new tab and jspPageName2 will be opened in the same tab. A: If you are referring to browser tabs it can't be done from Spring. You can on a link level specify <a href="#" target="_blank"/> to trigger a link opening in a new tab/window. Remember though, a users local browser configuration always has precedence of any server settings.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What to choose for Yii based website: subdomains pointing to modules or separate yii-applications I'm making a website on yii which has several separate parts, each on it's own subdomain like themes.example.com, events.example.com etc with main page example.com where these parts are listed. I will also need to authenticate users across subdomains. So i'm thinking what would be better: making each part as a yii module or making a separate yii application for each of these parts? A: I think in your case it would be better to use modules. At least to have a single webroot directory. Using separate yii application would be appropriate for console part of your project. See this link for more information: The directory structure of the Yii project site A: Well, The features you are trying to accomplish from Yii its called "Parameterizing Hostnames". You need to create a module based structure in Yii. At first you need to create a virtual host from apache and redirect that to your Yii project. On you Yii framework you need to change the URL manager from config. 'components' => array( ... 'urlManager' => array( 'rules' => array( 'http://admin.example.com' => 'admin/site/index', 'http://admin.example.com/login' => 'admin/site/login', ), ), ... ), To know more about Parameterizing Hostnames
{ "language": "en", "url": "https://stackoverflow.com/questions/7527176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to analyze log files with regexp? alternatives? I want to analyze some logs for some statisics of usage. Basically what I wanna do is use regexp to ease the pain of analysis So I have a text file with logs something along this 2011-09-17 09:16:33,531 INFO [someJava.class.special] sendRequest: fromGevoName=null, ctrlPageId=fooBar, actionId=search, 2011-09-17 09:16:33,976 INFO [someJavaB.class] fooBar 2011-09-17 09:16:33,982 DEBUG [someOtherJava.class] abc blabala 2011-09-17 09:16:33,987 INFO [someJava.class.special] sendRequest completed: fromGevoName=XYZ, toPageId=fooBar, userId=someUser .... I want to count the occurrences of all words at position [someJava.class.special] ctrlPageId=.... in this case fooBar and only this occurrences. There are many different fooBar and I want to count how often one occurred. My idea was to replace with a matching group and repeat it, something along this ((?s).*\[someJava.class.special\] sendRequest: fromGevoname=.* ctrlPageId=([^,]*)(?-s).*)* and replace it with the matching group \2 Afterwards analyse the list in excel. But my greptool does not repeat the regexp, it only matches once. I use grepWin, is there maybe a different tool / regexp for this? Well it basically was a problem of wingrep or grepwin. The modifier (?s) which enables linebreaks on dots or disables it (?-s) does not work if you use it repeatedly. So I exchanged the regexp with something along this: ([\n-\[\(\]\.,:0-9a-zA-Z]).*\[someJava.class.special\] sendRequest: fromGevoname=.* ctrlPageId ([^,]*)(?-s).* so basically i exchanged the first linebreakmatching dot with all symbols which might occur in the string including linebreaks. It works... i'm sure there is a better solution, always open for it A: I'm not sure I understand, but if the output you are looking for is: someJava fooBar Something like this should work (php script): <?php $log = file_get_contents('file.log') preg_match_all("#\[(?<className>\w+)\.class(.special)?\](.*?)ctrlPageId=(?<controllerName>\w+)#i", $log, $m); for ($i=0; $i < count($m[0]); $i++) { echo $m['className'][$i] . ' ' . $m['controllerName'][$i] . "\n"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7527178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there any way to open new tab(or popup, or window) with certain html content in silverlight? I have a grid filled with some data in my silverlight4 app. I want to have "Show this as html" button for the grid. I can generate the html, export it to savefile dialog, but that's not what i need, because in this way user has to perform more actions, like: * *click 'export' *enter filename *wait for download *find file open it in browser Is there any way to create tab, or window, or popup with certain html content in it? (so it would be like * *click 'show as html' ?) Thanks in advance, Ilya. A: The problem is that you can't save it anywhere locally without user interaction (or elevated privileges).... so don't save it locally. I can think of two options: 1. * *Write the data back to the server *Open a normal popup web browser window, pointing a generated temp HTML page. To open another HTML browser window from Silverlight you can use HtmlWindow.Navigate specifying _blank as the target type. 2. * *Use the ability of Silverlight to execute any Javascript to open a popup with the content. From Silverlight you can use ScriptObject.Invoke to execute arbitrary Javascript.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does the use of nosql (say mongodb) increase development productivity? I develop 3 to 4 Spring Roo applications a year currently with Hibernate and MySQL. It has been stated here at Stackoverflow that relational databases are not the best fit for a typical object oriented webapplication . If your DB is 3NF and you don’t do any joins (you’re just selecting a bunch of tables and putting all the objects together, AKA what most people do in a web app), MongoDB would probably kick ass for you. There are various reasons for this. One is productivity as objects are mapped to a relational schema ("joins" etc.). Would the use of MongoDB or CouchDB increase development productivity given the same level of expertise as with MySQL? A: I think it really depends on the web application. Non-relational databases (NoSQL) excel where you either * *Don't want a schema (want to be able to store different sorts of data in the same table), and/or *Don't have too complex of relation between objects. NoSQL can definitely make it easier to get off the ground faster, because you can just throw stuff in however you want, but on the downside as things get more complex sometimes you want a little more forced organization. Foreign keys are something I really miss when working with Mongo, just being able to (using an ORM) hop from one object to a related one or set of them is great. (Yes in many NoSQL dbs you can store documents, but at some point you need to use a separate table for something.) I would highly recommend NoSQL for a brochure style website, where the client is just entering text fields, or a twitter-style site, where largely you are storing lots of one type of data with few attributes. But if you're going to be creating a CMS with revisions and workflow and such, you're going to want the ability to have explicit relations in SQL. Which brings me to my answer: use the right tool for the job. A trained developer would be able to make some sites faster and better with SQL, and other sites faster and better with a non-relational database. But try out MongoDB or CouchDB and get a feel for it, that way you'll have a better intuition on when to use what. (We use both at my job (not at the same time!) depending on the project)
{ "language": "en", "url": "https://stackoverflow.com/questions/7527184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: java inputstream What is an InputStream's available() method is supposed to return when the end of the stream is reached? The documentation doesn't specify the behavior. A: ..end of the stream is reached Don't use available() for detecting end of stream! Instead look to the int returned by InputStream.read(), which: If no byte is available because the end of the stream has been reached, the value -1 is returned. A: Theoretically if end of stream is reached there are not bytes to read and available returns 0. But be careful with it. Not all streams provide real implementation of this method. InputStream itself always returns 0. If you need non-blocking functionality, i.e. reading from stream without being blocked on read use NIO instead. A: The JavaDoc does tell you in the Returns section - an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking or 0 when it reaches the end of the input stream. (from InputStream JavaDoc) A: From the Java 7 documentation: "an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking or 0 when it reaches the end of the input stream." So, I would say it should return 0 in this case. That also seems the most intuitive behaviour to me. A: Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes. The available method for class InputStream always returns 0. http://download.oracle.com/javase/6/docs/api/java/io/InputStream.html#available%28%29
{ "language": "en", "url": "https://stackoverflow.com/questions/7527188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What's the best way of adding a custom centre button to a tab bar? Many apps have a standard tab bar with a custom button in the centre which performs some special function. Some examples can be found here: http://mobile-patterns.com/custom-tab-navigation What's the best way of implementing this? A: I got Franciso's code working with a few minor tweaks. I placed the code in the application didFinishLaunchingWithOptions method of a standard Tab Bar Application template in Xcode 4.1. I believe Xcode 4.2 may have a different template. UIImage *buttonImage = [UIImage imageNamed:@"tabItemOff.png"]; UIImage *highlightImage = [UIImage imageNamed:@"tabItemSelected.png"]; UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom]; button.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height); [button setBackgroundImage:buttonImage forState:UIControlStateNormal]; [button setBackgroundImage:highlightImage forState:UIControlStateHighlighted]; CGFloat heightDifference = buttonImage.size.height - self.tabBarController.tabBar.frame.size.height; if (heightDifference < 0) button.center = self.tabBarController.tabBar.center; else { CGPoint center = self.tabBarController.tabBar.center; center.y = center.y - heightDifference/2.0; button.center = center; } [self.tabBarController.view addSubview:button]; A: Here you can see how to implement that button. I am gonna paste the code so it stays here forever: UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom]; button.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height); [button setBackgroundImage:buttonImage forState:UIControlStateNormal]; [button setBackgroundImage:highlightImage forState:UIControlStateHighlighted]; CGFloat heightDifference = buttonImage.size.height - self.tabBar.frame.size.height; if (heightDifference < 0) button.center = self.tabBar.center; else { CGPoint center = self.tabBar.center; center.y = center.y - heightDifference/2.0; button.center = center; } [self.view addSubview:button]; Hope it helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7527192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Default load in combobox If I want to load for example a default country when the combobox shows up ("Country: Lebanon"), how do I do so? I am using VS2008 (C#). Thank you. A: Add some items to the Combobox...it is just a sample, you can run a loop also to add items. combobox1.Items.Add("USA"); combobox1.Items.Add("England"); combobox1.Items.Add("Kenya"); combobox1.Items.Add("South Africa"); Now your Combobox has four items. To select a specific country try this: combobox1.Text = "USA"; To select a on the index basis, try this: combobox1.SelectedIndex = 0; // For USA Hope it helps. A: You can use another method to add items in comboBox: comboBox1.Items.Insert(0, "Egypt"); //the first item is the item index and the second is the item object. A: You would usually just set myCombo.SelectedValue = "Whatever value" as soon as the form is loaded. A: Use one of SelectedValue, SelectedIndex, SelectedItem or SelectedText properties of the ComboBox control. A: You could try this: myCombo.SelectedIndex = lebanonsIndex; A: You can set selected index in Form load event If Lebanon is first in comboboxItem selectedIndex = 0; Example: private void Form1_Load(object sender, EventArgs e) { comboBox1.SelectedIndex = 0; } A: You can set it by using IndexOf in the Items collection comboBox1.SelectedIndex = comboBox1.Items.IndexOf("Lebanon");// case sensitive A: This could work. Copy this code in your app.config file within appsettings. < add key="DefaultCountry" value="Lebanon" /> and copy this at ur win form where you want to view it. combobox1.Text = System.Configuration.ConfigurationManager.AppSettings["DefaultCountry"].ToString();.<add key="DefaultCountry" value="Lebanon"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/7527194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery Menu, Prevent constant loading I have made a jQuery menu, Looks great, works a treat. The only problem I have is when a user mouse's over it, It tends to "Bounce" quite a bit on a few mouseOver and mouseOuts, becoming slightly annoying and to a point where we may have to scrap it. Does anyone know a way to stop it, or certainly slow it down. An example is here : http://jsfiddle.net/rtcjr/ Thanks in advance. A: To stop animation use jquery stop() And maybe http://cherne.net/brian/resources/jquery.hoverIntent.html plugin helps you: hoverIntent is a plug-in that attempts to determine the user's intent... like a crystal ball, only with mouse movement! It works like (and was derived from) jQuery's built-in hover. However, instead of immediately calling the onMouseOver function, it waits until the user's mouse slows down enough before making the call.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem with mysql query I am creating a playlist table. I want to print tracklist from database. I have this sequence of data stored in database. album | track | singer ---------------------- A | 1 | X A | 1 | Y A | 2 | X A | 3 | Z This way that is if track 1 has sung by both x and y combinely than I have stored that in separate record. But at time of print I want to print in differect style...Like album | track | singer ---------------------- A | 1 | X, Y A | 2 | X A | 3 | Z What query should I fire to print it in desired schema, that is grouping it according to singer. A: Use select album, track, GROUP_CONCAT(singer) from YourTable group by album, track
{ "language": "en", "url": "https://stackoverflow.com/questions/7527199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting styles for subcontrols of usercontrol Say I have a user control like this: <UserControl x:Class="StyleTest.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <Grid> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <Button Grid.Row="0">Style please</Button> <Button Grid.Row="1">Style please</Button> </Grid> And I want to set all buttons in this control to background=green. But I don't want to affect other buttons in my program and I don't want to modify the code of the control. What I found right now is this: <Window x:Class="StyleTest.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:loc="clr-namespace:StyleTest" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <Style x:Key="UserControlStyles" TargetType="Button"> <Setter Property="Background" Value="green" /> </Style> </Window.Resources> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Button Grid.Column="0">no Style please</Button> <loc:UserControl1 Grid.Column="1"> <loc:UserControl1.Resources> <Style TargetType="Button" BasedOn="{StaticResource UserControlStyles}" /> </loc:UserControl1.Resources> </loc:UserControl1> </Grid> But this would imply that I have to add this code to every instance of the control, and some extra code, if I want to style e.g. foreground color of TextBoxes also. What I am looking for is something similar to this: <Style TargetType="Buttons that are childs of UserControl1"> <Setter Property="Background" Value="green" /> </Style> Is there a way of doing this? I don't think that a control template would be sufficient, because I don't want to redesign the whole control, I just want to set the color of the buttons. A: In App.xaml you could add this style which will be applied to all instances of UserControl1 <Style TargetType="StyleTest:UserControl1" > <Style.Resources> <Style TargetType="Button"> <Setter Property="Background" Value="green" /> </Style> </Style.Resources> </Style> A: If I understand correctly, you just need to modify your UserControl so that you add the style there, instead of in the Window control <UserControl x:Name=UserControl1 ...> <UserControl.Resources> <Style TargetType="Button"> <Setter Property="Background" Value="green" /> </Style> </UserControl.Resources> I just saw that you said you don't want to modify the control. You mean that you can't modify the xaml of the UserControl? Why not?
{ "language": "en", "url": "https://stackoverflow.com/questions/7527202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Hide selected TabIItems in WPF TabControl I'm using the TabControl in WPF as a sort of equivalent to the ASP.Net multiview control. I need to make two of the four tabitem headers hidden. What would be the best method of doing this in XAML? A: I fixed this by adding DataTriggers to my Template. If my tab is DeTached (Hidden) I set the Visibility property to Collapsed. If it's visiable again I simply set the Visibility property to Visible again. <DataTrigger Binding="{Binding IsDetached}" Value="True"> <Setter Property="Visibility" Value="Collapsed" /> </DataTrigger> <DataTrigger Binding="{Binding IsDetached}" Value="False"> <Setter Property="Visibility" Value="Visible" /> </DataTrigger> Edit: Updated based on @Miklós Balogh feedback. Thanks, improved my code as well, haha. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7527211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to develop android applications on the device? Is there a way to develop android applications on the devices themselves? If I want to write some code for a linux machine I usually do that on a linux machine. It would be nice to develop android applications on the device (say a Nexus S) (type the code) and then build, compile and test them on the device themselves. Can this be done? A: You mention testing 'on the device themselves'. Practically speaking, the emulators supplied with the SDK function in exactly the same way as the physical devices. It also means that you essentially have access to all of the devices the emulator supports, not just the phone/tablet you own or have access to. As for a device-based IDE (if that is what you're after), I haven't seen anything beyond a couple of WP7 proof-of-concepts. A: There is an IDE to develop Android apps in Android devices recently launched: AIDE - Android IDE - Java, C++
{ "language": "en", "url": "https://stackoverflow.com/questions/7527212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What kind of iteration should I use for LinkedList? I know that traversing LinkedList by indexing is bad, because list.get(n) is executed in linear time O(n). Thus i shouldn't use indexing. I looked at the AbstactList.Itr that is returned by iterator() call, it uses get(cursor) too. I'm confused. As pointed out by @axtavt , LinkedList.iterator() actually calls listIterator() which returns AbstactList.ListItr which extends AbstactList.Itr and it only adds implementations of ListIterator interface. Thus the machinery for getting next element is still the same as in AbstactList.Itr. `AbstactList.Itr's next(); calls get(n) on the specified list. A: The best iteration over any List (actually even any Iterable) is the for each loop: for(Element e : myList){ // do something } A: The foreach loop is very efficient, and easy: List<String> list = new LinkedList<String>(); list.add("First"); list.add("Second"); list.add("Third"); list.add("Fourth"); for(String s : list) { System.out.println(s); } A: You should use a foreach loop if you can - that's the most efficient: List<Item> myList = ...; for (Item item : myList) { ... } If you need to modify the list inside the loop, or traverse through multiple collections in one loop, use an iterator: List<Item> myList = ...; Iterator<Item> it = myList.iterator(); while (it.hasNext()) { Item item = it.next(); ... } And if you need to traverse backwards, or something else specific to linked lists, use listIterator: ListIterator<Item> it = myList.listIterator(); ... A: LinkedList inherits not only from AbstractList, but also from AbstractSequentialList which in turn implements iterator() like this: public Iterator<E> iterator() { return listIterator(); } and the ListIterator returned by LinkedList is smart about using sequential access. So whether you use foreach, iterator() or listIterator(), you are always dealing with the same smart iterator type. A: You can use iterator, which returned by iterator method. It doesn't require O(n) time to go to next item. It uses ListIterator implementation from LinkedList so it's fast. A: You can use the Iterator, it gives you a faster access. A sample code for a list: List<String> list = new LinkedList<String>(); list.add("First"); list.add("Second"); list.add("Third"); list.add("Fourth"); Iterator it = list.iterator(); while(it.hasNext()) { System.out.println(it.next()); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7527217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Finding a record in one of 2 tables In PostgreSQL 8.4.8 database I have 2 tables: noreset and track. They have exactly same column names and contain records identified by unique id. A record can be present only in one of the tables, for example: # select qdatetime, id, beta_prog, emailid, formfactor from noreset where id='20110922124020305'; qdatetime | id | beta_prog | emailid | formfactor ---------------------+-------------------+-----------+------------------+------------ 2011-09-22 11:39:24 | 20110922124020305 | unknown | 4bfa32689adf8189 | 21 (1 row) # select qdatetime, id, beta_prog, emailid, formfactor from track where id='20110922124020305'; qdatetime | id | beta_prog | emailid | formfactor -----------+----+-----------+---------+------------ (0 rows) I'm trying to come up with a join statement, which would find a record by id in one of the both tables. The background is that I have a PHP-script, which was always using 1 table, but now suddenly I'm requested to search in both tables. Can this be done? Is it a full outer join? I'm confused how to specify the column names in my SQL query (i.e. I must prepend a table id, but which one?)... A: You should use union: select qdatetime, id, beta_prog, emailid, formfactor, 'noreset' as tableOrigin from noreset where id='20110922124020305' union select qdatetime, id, beta_prog, emailid, formfactor, 'track' as tableOrigin from track where id='20110922124020305' (union remove duplicate lines, if you want all use union all) If you are goint to use this very often is better to make a view: CREATE VIEW yourviewname as select qdatetime, id, beta_prog, emailid, formfactor, 'noreset' as tableOrigin from noreset union select qdatetime, id, beta_prog, emailid, formfactor, 'track' as tableOrigin from track and then your query would be: SELECT qdatetime, id, beta_prog, emailid, formfactor FROM yourviewname WHERE id='20110922124020305'
{ "language": "en", "url": "https://stackoverflow.com/questions/7527220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: color of apache wicket component I have the following code: <html xmlns="http://www.w3.org/1999/xhtml" xmlns:wicket="http://wicket.apache.org/dtds.data/wicket-xhtml1.4-strict.dtd" xml:lang="en" lang="en"> <body> <wicket:panel> <div wicket:id="serviceListContainer"> <table> <tr wicket:id="serviceListView"> <td> <span wicket:id="service.name"></span> </td> <td> <span wicket:id="service.state"></span> <!-- I WANT TO COLOR THIS PART IN RED! --> </td> </tr> </table> </div> </wicket:panel> </body> </html> How can I change the color of the output text that will replace "service.state"? I tried with <font color="red"> but it didn't make any difference. Thanks! A: Other answers have indicated how you can add the style="..." attribute in the HTML template. If, on the other hand, that you do not wish to do this statically (say, you need to calculate the color and then add it to the component), you should add an AttributeModifier to the Component1. Example (untested): Label l = new Label("service.state", ...); IModel<String> colorModel = new AbstractReadOnlyModel<String>() { public String getObject() { return "color: red;"; // Dummy example } }; // Some model, holding a string representation of a CSS style attribute (e.g., "color: ...;") based on some date and/or calculation l.add(new AttributeModifier("style", true, colorModel); You could even use a SimpleAttributeModifier if you don't need the pull-based model: Label l = new Label("service.state", ...); String styleAttr = "color: red;"; l.add(new SimpleAttributeModifier("style", styleAttr)); 1) Provided that setRenderBodyOnly(true) has not been called. That would remove the wrapping <span> element from the output. A: From W3Schools: The <font> tag is deprecated in HTML 4, and removed from HTML5. The World Wide Web Consortium (W3C) has removed the tag from its recommendations. In HTML 4, style sheets (CSS) should be used to define the layout and display properties for many HTML elements. Use styles, even if it is inline styling, instead: <span style="color:red">this is red text</span> If you're using Wicket you'll want to make sure you're not using setRenderBodyOnly(true) on the Component with id service.state, as this would strip the <span> tag with the style. A: <span wicket:id="service.state" style="color:red"></span> or better is to use proper css classes
{ "language": "en", "url": "https://stackoverflow.com/questions/7527230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ANTLR @header, @parser, superClass option and basic file io (Java) I want to use parser actions with basic file io (Java), e. g. PrintWriter in an ANTLR grammar. Must I use the superClass option or can I use @header? In both cases how can I declare the PrintWriter-object and how must I handle the exceptions? A: The option superClass=... is used to let your Parser extend a custom class. So, I don't think that is what you're after. Everything inside the @header section will be placed at the start of your Parser class. This is used to import classes: @header { import java.io.PrintWriter; } Note that @header {...} is short for @parser::header {...}. You can also define: @lexer::header {...} for your lexer. And inside @member {...} (or: @parser::member {...}, @lexer::member {...}) sections, you can add instance variables and methods that can be used inside either the Parser or Lexer: @header { import java.io.PrintWriter; } @members { PrintWriter writer; } A small demo of a grammar whose parser will write the parsed numbers to a specific writer: grammar T; @header { import java.io.PrintWriter; } @members { PrintWriter writer; public TParser(TokenStream input, String fileName) { super(input); try { writer = new PrintWriter(fileName); } catch(Exception e) { e.printStackTrace(); } } } parse : numbers EOF ; numbers : (NUM { writer.println("parsed: " + $NUM.text); writer.flush(); } )+ ; NUM : '0'..'9'+; WS : ' ' {skip();}; which can be tested with: import java.io.File; import org.antlr.runtime.*; public class Main { public static void main(String[] args) throws Exception { String source = "42 500000000 666"; TLexer lexer = new TLexer(new ANTLRStringStream(source)); TParser parser = new TParser(new CommonTokenStream(lexer), "log.txt"); parser.parse(); } } If you run the class above, a file called log.txt has been created containing: parsed: 42 parsed: 500000000 parsed: 666 Note that there is a strict order of all these @... and options {...} etc. instances: * *grammar definition *options block (no @ sign!) *tokens block (no @ sign!) *@header block *@members block grammar T; options { // options here } tokens { // imaginary tokens here } @header { // ... } @members { // ... } EDIT ANTLRStarter wrote: How can I add code which is executed at the end of the the lexer/parser class? There's no built-in functionality for such a thing. But you can easily create a custom method wrapUp() in your parser: @members { // ... private void wrapUp() { // wrap up your parser in here } } and then automatically call that method from the entry point of your grammar like this: parse @after {this.wrapUp();} : numbers EOF ; Any code placed in the @after {...} block of a rule is executed when everything in the rule is properly matched.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Save button click event getting fired up on refreshing the page once done with binding the data to a gridview through save button in asp.net I am working on a web application using C# and ASP.NET. I am binding the data to the gridview through the textboxes in the same page and I wrote the binding method in my "Save" button click event. Now, it's really strange thing to find that the grid view is getting bound again with duplicate rows once I refresh the page up on saving the data to the gridview from textboxes through "save" button_click event. I have tried loading the page on firefox, chrome and IE 8....but the result is negative.... Could anyone let me know why is it happening and guide me to resolve it.... This is my C# code: string con = ConfigurationSettings.AppSettings["ConnectionStrings"]; protected void Page_Load(object sender, EventArgs e) { tbladdasset.Visible = false; btnsaveasset.Enabled = false; lblErrMsg.Text = ""; if (!IsPostBack) { bindassets("", ""); ViewState["sortOrder"] = ""; } } private void bindassets(string sortExp, string sortDir) { try { SqlConnection con1 = new SqlConnection(con); con1.Open(); SqlCommand cmd = new SqlCommand("select Description,CONVERT(VARCHAR(10), RecievedDate, 101) as DateRecieved,cost,Modelno,Quantity from Asset", con1); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); con1.Close(); if (dt.Rows.Count > 0) { DataView dv = dt.DefaultView; if (sortExp != string.Empty) { dv.Sort = string.Format("{0} {1}", sortExp, sortDir); } grdvAssets.DataSource = dv; grdvAssets.DataBind(); } else { lblErrMsg.Text = "No data found..."; } btnsaveasset.Enabled = false; tbladdasset.Visible = false; } catch { lblErrMsg.Text = "Failed to connect server..."; } } protected void btnaddnew_Click(object sender, EventArgs e) { tbladdasset.Visible = true; btnsaveasset.Enabled = true; lblErrMsg.Text = ""; txtdescription.Text = ""; txtdtrecieved.Text = ""; txtcost.Text = ""; txtmodelno.Text = ""; txtquantity.Text = ""; } protected void btnsaveasset_Click(object sender, EventArgs e) { if (txtdescription.Text != "" && txtdtrecieved.Text != "" && txtcost.Text != "" && txtmodelno.Text != "" && txtquantity.Text != "") { try { string desc= txtdescription.Text; DateTime dtrecd = Convert.ToDateTime(txtdtrecieved.Text); string cost = txtcost.Text; string modelno = txtmodelno.Text; double quantity = Convert.ToDouble(txtquantity.Text); SqlConnection sqlcon = new SqlConnection(con); sqlcon.Open(); string save = "Insert into Asset(Description,Recieveddate,cost,Modelno,Quantity)values(@desc,@date,@cost,@modelno,@quantity)"; SqlCommand cmd = new SqlCommand(save, sqlcon); cmd.CommandType = CommandType.Text; cmd.Parameters.Add("@desc", desc); cmd.Parameters.Add("@date", dtrecd); cmd.Parameters.Add("@cost", cost); cmd.Parameters.Add("@modelno", modelno); cmd.Parameters.Add("@quantity", quantity); cmd.ExecuteNonQuery(); sqlcon.Close(); bindassets("", ""); btnsaveasset.Enabled = false; txtdescription.Text = ""; txtdtrecieved.Text = ""; txtcost.Text = ""; txtmodelno.Text = ""; txtquantity.Text = ""; lblErrMsg.Text = "data inserted successfully.."; } catch { lblErrMsg.Text = "Please enter valid data and try again..."; } } else { lblErrMsg.Text = "Please enter valid data and try again..."; } } protected void grdvAssets_Sorting(object sender, GridViewSortEventArgs e) { bindassets(e.SortExpression, sortOrder); } public string sortOrder { get { if (ViewState["sortOrder"].ToString() == "desc") { ViewState["sortOrder"] = "asc"; } else { ViewState["sortOrder"] = "desc"; } return ViewState["sortOrder"].ToString(); } set { ViewState["sortOrder"] = value; } } Anyone please help me.....Thanks in advance.. A: that's a common problem. check similar SO questions: Webforms Refresh problem, How to stop unwanted postback. if a few words, web browser refresh button just sends the last request to the server in your case that's a "Save" button click event, thus it gives duplicate rows. use Response.Redirect, this way the last request will be just navigation to the page, so the refresh will not cause undesired effects. EDITED I see you have added some code. here's a workaround for you. the fact that you are saving data to database helps a lot. first thing on page load event no need to check if page IsPostBack, just call the bindassets("", ""); method. as for save button click event. no need to call the bindassets("", ""); it will be called from page load. protected void btnsaveasset_Click(object sender, EventArgs e) { if (txtdescription.Text != "" && txtdtrecieved.Text != "" && txtcost.Text != "" && txtmodelno.Text != "" && txtquantity.Text != "") { try { string desc= txtdescription.Text; DateTime dtrecd = Convert.ToDateTime(txtdtrecieved.Text); string cost = txtcost.Text; string modelno = txtmodelno.Text; double quantity = Convert.ToDouble(txtquantity.Text); SqlConnection sqlcon = new SqlConnection(con); sqlcon.Open(); string save = "Insert into Asset(Description,Recieveddate,cost,Modelno,Quantity)values(@desc,@date,@cost,@modelno,@quantity)"; SqlCommand cmd = new SqlCommand(save, sqlcon); cmd.CommandType = CommandType.Text; cmd.Parameters.Add("@desc", desc); cmd.Parameters.Add("@date", dtrecd); cmd.Parameters.Add("@cost", cost); cmd.Parameters.Add("@modelno", modelno); cmd.Parameters.Add("@quantity", quantity); cmd.ExecuteNonQuery(); sqlcon.Close(); //bindassets("", ""); btnsaveasset.Enabled = false; txtdescription.Text = ""; txtdtrecieved.Text = ""; txtcost.Text = ""; txtmodelno.Text = ""; txtquantity.Text = ""; lblErrMsg.Text = "data inserted successfully.."; } catch { lblErrMsg.Text = "Please enter valid data and try again..."; } } else { lblErrMsg.Text = "Please enter valid data and try again..."; } Response.Redirect("nameofpage.aspx", false);//does a charm. browser refresh button will repeat last action and from now on that's a Response.Redirect("nameofpage.aspx", false). thus no duplicate records } A: if (!IsPostBack) { Bind(); //bind data to grid }
{ "language": "en", "url": "https://stackoverflow.com/questions/7527243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: I am getting No such property while giving target step in soapui I am taking the value from the one response and coamparing that value with one integer and based on the boolean i am navigating to the other step. It is showing No such property: testrunner. Please let me know why this is happening.. if (cardScheme == '20172') testRunner.runTestStepByName( "Submit Order 1" ) else testRunner.runTestStepByName( "Submit Order" ) A: Groovy is case-sensitive language. You are using somewhere testrunner instead of testRunner.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: VBScript Sending Email with High Importance I used VBScript to write a function to send email automatically. With .Configuration.Fields .Item(cdoSendUsingMethod) = cdoSendUsingPort .Item(cdoSMTPServer) = "SMTPHOST.redmond.corp.microsoft.com" .Item(cdoSMTPServerPort) = 25 .Item(cdoSMTPAuthenticate) = cdoNTLM .Item("urn:schemas:httpmail:importance") = sMailPriority .Update When I want to send email with high important, I set the sMailPriority to 2. When I test with the Gmail, it worked. But when I using outlook2010, it didn't work. A: Some e-mail clients requires different headers to set e-mail priority. Try to add all of these fields. .Item("urn:schemas:httpmail:importance") = sMailPriority .Item("urn:schemas:httpmail:priority") = 1 'sMailPriority .Item("urn:schemas:mailheader:X-Priority") = 1 'sMailPriority
{ "language": "en", "url": "https://stackoverflow.com/questions/7527249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Stop location.hash of frame's parent from reloading page I have a frameset with to frames left/right. The content of the frame left the one below. As you can see, I want to update the hash/fragment identifier of the left frame's parent (the uppermost window) location. However, this leads to reloading the whole frameset in Safari/Chrome. In Firefox, the whole frameset is not reloaded, but the browsers displays "loading" continuously. Background: The left frame shows a navigation. A click in an entry loads another HTML page in the right frame and should also update the hash in the location of the browser window so the user can bookmark pages. How can I make this work? <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Left</title> </head> <body> <script type="text/javascript" charset="utf-8"> function go() { window.document.write('foo'); // replace document with 'foo' window.parent.location.hash = '#foo'; } </script> <h1>Left</h1> <p> <a href="#" onclick="javascript:go(); return false;">Go</a> </p> </body> </html> A: You might want to try changing: onclick="javascript:go(); return false;" ...to something like: onclick="void(javascript:go(););" A: Instead of using window.parent.location.hash just try something like this: JS: function go() { window.document.write('foo'); // replace document with 'foo' } HTML: <a href="#foo" onclick="go()">Go</a>
{ "language": "en", "url": "https://stackoverflow.com/questions/7527250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Browser compatibility/support table for JavaScript methods/properties I found a few days ago a nice site with a big table with all the javascript proprieties/methods and the availability to all major browser. My problem is that I can't find that site any more. Where can I find such a list? UPDATE: Of course I've searched history and google before. Anyway here is the site I was looking for in case someone is interested: https://kangax.github.io/compat-table/es5/ A: My bet would be quirksmode or pointedears.de ? A: sounds like this is what you're looking for (or maybe this or this or this) A: There's loads of these. A couple I found with a 2 second google search: http://caniuse.com/ http://www.quirksmode.org
{ "language": "en", "url": "https://stackoverflow.com/questions/7527269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: How do I use custom fields in Mantis' Roadmap? I'd like to have an effort estimate for upcoming versions of my software in its Roadmap in Mantis Bug Tracker. I could figure out easily how to add a custom fields (integer type, called "days to complete") to issues, and how to show it on the "view issues" page. But I couldn't find out how to add something to the roadmap showing the sum of days to complete for non-resolved issues. Is there a built-in way to do this? My guess is no, that would take some php coding inside Mantis. But maybe someone did that already? Edit: I had a look at the Time Tracking feature. It doesn't look like what I want. A: The display of the Roadmap is driven by a Custom Function, which you can override in any way you see fit (and yes that means writing some PHP code, but without altering the MantisBT core). To achieve what you want, you should override custom_function_default_roadmap_print_issue(). Please refer to the MantisBT documentation for further details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: The underlying connection was closed: An unexpected error occurred on a send I am trying to use DoDirectPayment method in my website. This is the sample I am referring: using com.paypal.sdk.services; using com.paypal.sdk.profiles; using com.paypal.sdk.util; using com.paypal.soap.api; namespace ASPDotNetSamples { public class DoDirectPayment { public DoDirectPayment() { } public string DoDirectPaymentCode(string paymentAction, string amount, string creditCardType, string creditCardNumber, string expdate_month, string cvv2Number, string firstName, string lastName, string address1, string city, string state, string zip, string countryCode, string currencyCode) { com.paypal.soap.api.DoDirectPaymentReq req = new com.paypal.soap.api.DoDirectPaymentReq(); NVPCallerServices caller = new NVPCallerServices(); IAPIProfile profile = ProfileFactory.createSignatureAPIProfile(); // Set up your API credentials, PayPal end point, API operation and version. profile.APIUsername = "sdk-three_api1.sdk.com"; profile.APIPassword = "xxxxxxxxxxxxx"; profile.APISignature = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; profile.Environment = "sandbox"; caller.APIProfile = profile; NVPCodec encoder = new NVPCodec(); encoder["VERSION"] = "51.0"; encoder["METHOD"] = "DoDirectPayment"; // Add request-specific fields to the request. encoder["PAYMENTACTION"] = paymentAction; encoder["AMT"] = amount; encoder["CREDITCARDTYPE"] = creditCardType; encoder["ACCT"] = creditCardNumber; encoder["EXPDATE"] = expdate_month; encoder["CVV2"] = cvv2Number; encoder["FIRSTNAME"] = firstName; encoder["LASTNAME"] = lastName; encoder["STREET"] = address1; encoder["CITY"] = city; encoder["STATE"] = state; encoder["ZIP"] = zip; encoder["COUNTRYCODE"] = countryCode; encoder["CURRENCYCODE"] = currencyCode; // Execute the API operation and obtain the response. string pStrrequestforNvp = encoder.Encode(); string pStresponsenvp = caller.Call(pStrrequestforNvp); NVPCodec decoder = new NVPCodec(); decoder.Decode(pStresponsenvp); return decoder["ACK"]; } } } This is the link: https://cms.paypal.com/cms_content/US/en_US/files/developer/nvp_DoDirectPayment_cs.txt When I pass appropriate parameter and try to run the code I get this error: "The underlying connection was closed: An unexpected error occurred on a send." on line: pp_response = (DoDirectPaymentResponseType)caller.Call("DoDirectPayment", pp_Request); The SOAP service call is inside the dll. Can anybody guide me what is happening and how to resolve it? A: That is because that sample seems to be outdated, read up more on the stuff here: * *https://www.x.com/developers/paypal/sandbox *https://www.x.com/developers/api-endpoints *https://www.x.com/developers/paypal/documentation-tools/api
{ "language": "en", "url": "https://stackoverflow.com/questions/7527273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: sql databases Northwinds , pubs , AdventureWorks or some others? Technology : Microsoft SQL Server 2008 Aim : Master SQL Server 2008 using Microsoft's databases I am looking for a tutorial where I get a lot of exercises to do, so that I can master SQL Server 2008. Isn't it a good idea to choose Microsoft's databases such as Northwinds , pubs , AdventureWorks. Which one is good? Can you give me a link to exercises if you choose between the databases? I am focused on the set of exercises rather than tutorials. Just questions are enough . :) A: If you are a beginner you can start with tutorials in w3schools. You can first learn basics by creating your own simple database, executing queries. The standard available DataBases which you have mentioned above will also be helpful. 1) http://www.sqlcourse2.com/index.html 2)http://www.quackit.com/sql_server/tutorial/ 3)http://www.1keydata.com/sql/sql-commands.html A: You can check these. 1) http://www.sqlcourse2.com/index.html 2) http://www.sqlcourse.com/index.html 3) http://www.scribd.com/doc/3144852/SQL-Exercise 4) http://infolab.stanford.edu/~ullman/fcdb/slides/slides6.pdf 5) http://www.programmerinterview.com/index.php/database-sql/practice-interview-question-1/
{ "language": "en", "url": "https://stackoverflow.com/questions/7527275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iOS - UITableViewCell initialization fail, EXC_BAD_ACCESS i've a simple View that is the third level of a UINavigationController, it show an empty table from a nib, here is the code of the .m file: #import "ThirdLevel.h" @implementation ThirdLevel @synthesize lista, categoria; - (void)viewDidLoad { [super viewDidLoad]; NSLog(@"Categoria: %@", categoria); } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Overriden to allow any orientation. return NO; } - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc. that aren't in use. } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } // Customize the number of rows in the table view. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 20; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 100; } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //newtableView.separatorColor = [UIColor clearColor]; static NSString *CellIdentifier = "Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } } - (void)buttonPressed:(id)sender { NSLog(@"premuto"); } - (void)dealloc { [super dealloc]; } @end When i run it, the device crash and the debugger say that there is a EXC_BAD_ACCESS at this line: cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; i've the same code in the second level of the UINavigationController and it work fine, realy don't understand what's wrong. Thanks for any help :) A: static NSString *CellIdentifier =@"Cell"; not static NSString *CellIdentifier = "Cell"; more over return cell;//not found on ur code A: May be you should return cell in this method: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //newtableView.separatorColor = [UIColor clearColor]; static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } return cell; } Updated: And as mentioned @AppleVijay add @ when initializing CellIdentifier
{ "language": "en", "url": "https://stackoverflow.com/questions/7527278", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: array size > 0 although no key is set short question. given the following example: $arr = array(); $arr[0] = false ?: NULL; var_dump($arr[0]); var_dump($arr[1]); var_dump(isset($arr[0])); var_dump(isset($arr[1])); var_dump(count($arr)); the resulting output is: NULL NULL bool(false) bool(false) int(1) why does the resulting array have a size of 1 instead of 0 and is there any way to prevent this from happening when using the ternary operator? is it a bug or intended behaviour? btw, I'm running php 5.3.3-7, but can't test it on a different version at the moment. A: isset() returns false if the variable is not set, or the variable is equal to NULL. In this case, $arr[0] is explicitly set to NULL. This is semantically different to actually unset()ing it: the variable is still set, it's just set to an empty value. In short: working as intended. It's an unfortunate side effect of different functions doing slightly different things. As a sidenote, using foreach on this array will actually return the 0 => NULL key/value pair as well, as you might expect from the value returned by count().
{ "language": "en", "url": "https://stackoverflow.com/questions/7527280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Entity relationships design with JPA2 I have two entities, User and UserSetting. The obvious relationship between these two has User as the first rate entity which contains a set / list of UserSettings so when a User is loaded the settings get loaded too. E.g User 1-->* UserSetting Trouble is that's not what I want. At the moment users only have a few settings but that won't always be the case and when a user is active in the system they typically only need access to a small subset of all their settings. What I want is to load individual user settings on demand. The obvious choice is to make the UserSetting list lazy load but that won't work as I want to use the User in a detached state. My current "solution" is to include the User in the UserSetting object but that feels wrong as it makes the relationship UserSetting *-->1 User which feels like the UserSetting is the dominant entity. Is this the best solution? Assuming my current solution is the best I can get will a delete of the User still cascade correctly? A: There's 2 points here * *First, if your User entity has an association towards UserSettings and that association can contain a lot of members which are not needed all the time, the right thing to do is configure it as lazyLoaded by default (via JPA2 mapping config) and then force an eager fetch on it only when you need to (i.e. in those situations you mentioned where you need the values of that assocation on a detached User Entity). Look at "join fetch" to see how to do this, it should be something like: SELECT u FROM User u JOIN FETCH u.userSettings *If there's only a subset of those UserSettings that are needed often, you could make two associations in the User entity, such as userSettingsMain and userSettingsExtra, both lazy loaded by default, and just join fetch the one you needed on a certain detached User entity. Or, as a more advanced thing, you can make a Map association on the user settings, and have different keys for the important UserSetting, and the extra ones (such as i1, i2,... e1, e2, etc) and then eagerly fetch only those sets of keys that are needed, but this only works (at least at the moment) with EclipseLink JPA2, Hibernate's implementation just throws a big exception on Map associations (see my question here: Hibernate JPQL - querying for KEY() in Map association error on this)
{ "language": "en", "url": "https://stackoverflow.com/questions/7527284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I access the properties of my object using STAssertTrue How do I access the properties of my object using STAssertTrue in unit tests? I don't have access to the properties of my object and I want to do a comparison? A: You can access object properties as usual, so I guess you are talking about missing code completion... I think is an xcode bug, if you want code completion, you have to type before a call to STAssertTrue() (or any others OCUnit macro), like: NSString *foo = [myObject fooString]; STAssertTrue([foo length] > 1, nil);
{ "language": "en", "url": "https://stackoverflow.com/questions/7527285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Add endpoint header security WCF programmatically I've this web.config file to configure client proxy from a external service this service required authentication on the messages header, I've the service well configured on my web.config but for now I'm try create the proxy with this configuration on code,with propose change dynamically the user and password. <cliente> <endpoint address="https://wwwww.hhhahdhadhs.askadadasda" binding="basicHttpBinding" bindingConfiguration="MyConfiguration" contract="PROXY_ACSS_SERVICES.RegistoPrescricaoMedicamentos"> <headers> <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"> <wsse:UsernameToken> <wsse:Username>MyUser</wsse:Username> <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">87726655434</wsse:Password> </wsse:UsernameToken> </wsse:Security> </headers> </endpoint> </cliente> <basicHttpBinding> <binding name="PrescricaoMedicamentos" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> <security mode="Transport"> <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> <message clientCredentialType="Certificate" algorithmSuite="Default" /> </security> </binding> </basicHttpBinding> My problem is create the header where defined the username and password, <headers> <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"> <wsse:UsernameToken> <wsse:Username>MyUser</wsse:Username> <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">87726655434</wsse:Password> </wsse:UsernameToken> </wsse:Security> </headers> Thanks in advance EDIT Ladislav Mrnka after I create the proxy programmatically receive this message 'The request channel timed out attempting to send after 00:00:59.9829990. Increase the timeout value passed to the call to Request or increase the SendTimeout value on the Binding. The time allotted to this operation may have been a portion of a longer timeout.' This is my proxy configuration BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportWithMessageCredential); binding.Name = "PrescricaoMedicamentos"; binding.CloseTimeout = new TimeSpan(0, 1, 0); binding.OpenTimeout = new TimeSpan(0, 1, 0); binding.ReceiveTimeout = new TimeSpan(0, 10, 0); binding.SendTimeout = new TimeSpan(0, 1, 0); binding.AllowCookies = false; binding.BypassProxyOnLocal = false; binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard; binding.MaxBufferSize = 65536; binding.MaxBufferPoolSize = 524288; binding.MaxReceivedMessageSize = 65536; binding.MessageEncoding = WSMessageEncoding.Text; binding.TextEncoding = System.Text.Encoding.UTF8; binding.TransferMode = TransferMode.Buffered; binding.UseDefaultWebProxy = true; binding.ReaderQuotas = new XmlDictionaryReaderQuotas() { MaxDepth = 32, MaxStringContentLength = 8192, MaxArrayLength = 16384, MaxBytesPerRead = 4096, MaxNameTableCharCount = 16384 }; binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName; return binding; } I wondering if is possible add a static header to all messages in code.. Something like AddressHeader.CreateAddressHeader( 'authentication header') and apply this headers on my EndpointAddress configuration. This kind of approach substitute literal my first code <headers> <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"> <wsse:UsernameToken> <wsse:Username>myusername</wsse:Username> <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">mypass</wsse:Password> </wsse:UsernameToken> </wsse:Security> </headers> A: If the service correctly implements user name token profile change the security settings in your binding to: <security mode="TransportWithMessageCredential"> <message clientCredentialType="UserName" /> </security> And once you create a proxy set credentials by: proxy.ClientCredentials.UserName.UserName = ...; proxy.ClientCredentials.UserName.Password = ...;
{ "language": "en", "url": "https://stackoverflow.com/questions/7527288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Allocate and initialize pointer in local function I want to allocate memory and fill it to the pointer, that are one of the function parameter, but I think that I don't get some important thing, help me please. So, If I do that everything works fine: void alloc(char **p, int n) { *p = new char[n]; } int main() { char * ptr = NULL; int n = 10; alloc(&ptr, n); for(int i = 0; i<(n - 1); i++) ptr[i] = '1'; ptr[n - 1] = '\0'; printf("%s", ptr); return 0; } Now I want to initialize the allocated memory also into the function void alloc(char **p, int n) { *p = new char[n]; for(int i = 0; i<(n - 1); i++) *p[i] = '1'; *p[n - 1] = '\0'; } int main() { char * ptr = NULL; int n = 10; alloc(&ptr, n); printf("%s", ptr); return 0; } Program crashes. I don't get why. Please, can someone explain? A: Try (*p)[i] and (*p)[n - 1] instead. The precedence rules cause *p[i] to be evaluated as *(p[i]). A: Try this: ((*p)[i]) = '1'; you have a problem with operator's evaluation order. A: Probably because this: *p[i] is interpreted as if you had written this: *(p[i]) not as if you had written this, which is what you probably meant: (*p)[i] A: This should do the trick, void alloc( char*& p, int n ) { p = new char[n]; std::fill_n( p, n - 1, '1' ); p[n - 1] = '\0'; } If you insist on using a pointer as argument, change all of the p in the function to (*p) (and don't forget to check for a null pointer and do something reasonable if you're passed one. All things considered, however, you'd be better off using std::string—this function wouldn't even be necessary, as you could write std::string( n, '1' ). A: Try this #include <stdio.h> // for NULL void alloc(char **p, int n) { *p = new char[n]; for(int i = 0; i<(n - 1); i++) *((*p) + i) = '1'; *((*p) + n - 1) = '\0'; } int main() { char * ptr = NULL; int n = 10; alloc(&ptr, n); printf("%s", ptr); // never forget delete pointers delete [] ptr; return 0; } A: Its a precedence of operators issue. Try this in your alloc function: for(int i = 0; i<(n - 1); i++) (*p)[i] = '1'; (*p)[n - 1] = '\0';
{ "language": "en", "url": "https://stackoverflow.com/questions/7527293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Putting html within a php array I'm having problems with the syntax for a php array. <?php $pages = get_pages(array('child_of' => $post->ID, 'sort_column' => 'menu_order')); $data = array(); foreach($pages as $post){ setup_postdata($post); $fields = get_fields(); $data[] = '<p>'.$fields->company_name.'</p><img src="'.$fields->company_logo."' />'; } wp_reset_query(); // the js array echo 'var marker_data = ' . json_encode($data) . ';'; // Instead of implode ?> Specifically this line: $data[] = '<p>'.$fields->company_name.'</p><img src="'.$fields->company_logo."' />'; I'm getting all kinds of errors with adding the img tag, how would I format it correctly? A: $data[] = '<p>' . $fields->company_name . '</p><img src="' . $fields->company_logo. '" />'; You just changed the '" to "' which was wrong :) A: Change that line $data[] = '<p>'.$fields->company_name.'</p><img src="'.$fields->company_logo."' />'; to $data[] = '<p>'.$fields->company_name.'</p><img src="'.$fields->company_logo.'" />'; The problem is after the $fields->company_logo. You have enter "' instead of '"
{ "language": "en", "url": "https://stackoverflow.com/questions/7527294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to prevent dialog to open twice I had button in my app, on doubleClick of my button I open a dialog. Sometimes when I doubleClick the button in a fast way then the dialog opens twice, as a result of which the user has to cancel the dialog twice. So can anyone suggest me how can I prevent this dialog to open twice on doubleClick of my button? A: May be this will help you: Take a count variable i.e., count=0;. In button click validate condition such that if(count==0) show dialog and make count to 1. (with this dialog will not open second time) while dismissing dialog make count to 0 again. I think this will work Hope it helps. A: The current way should be to use an DialogFragment. With that, you don't need extra code logic, if you just use your tags and skip loading if that Fragment with tag already exists: FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); Fragment prev = getSupportFragmentManager().findFragmentByTag("TAG_DIALOG"); if (prev == null) { ft.addToBackStack(null); // Create and show the dialog. DialogFragment newFragment = ImageDialog.newInstance(b); newFragment.show(ft, "TAG_DIALOG"); } A: make a field for your dialog, like private Dialog m_dialog = null; and in your onClick listener check it's status: if ((m_dialog == null) || !m_dialog.isShowing()){ m_dialog = new Dialog(...); // initiate it the way you need m_dialog.show(); } edit btw, if you don't need to initialize dialog every time you may separate if() clause like this: if (m_dialog == null){ m_dialog = new Dialog(...); // initiate it the way you need m_dialog.show(); } else if (!m_dialog.isShowing()){ m_dialog.show(); } A: When the Button is pressed, disable it using Button.setEnabled(false). When the dialog finishes, re-enable the Button using a DialogInterface.OnDismissListener. This way you don't have to hold a global reference to your dialog. A: You should create dialog variable before onClick. For example: private fun onFilterClick() { val dialog = FilterDialogFragment() btn_filter.setOnClickListener { if (!dialog.isAdded) dialog.show(supportFragmentManager, dialog.tag) } } A: I was facing the same problem for last 2 days and after a lots of hit and trial I found a small problem in my code that I was not dismissing the dialog which I opened in onPostExecute() of my AsyncTask to do some extra work after AsyncTask Work. When I called myCustomDialog.dismiss() everything worked fine. A: boolean isBusy = false; View.OnClickListener ShowDialog_Click(){ return new View.OnClickListener() { @Override public void onClick(View view) { if(isBusy){ return; } isBusy = true; //show dialog } }; } dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { dialog.dismiss(); isBusy = false; } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7527296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: posting pickle dumps string with urllib I need to post data to a Django server. I'd like to use pickle. (There're no security requirements -> small intranet app.) First, I pickle the data on the client and sending it with urllib2 def dispatch(self, func_name, *args, **kwargs): dispatch_url = urljoin(self.base_url, "api/dispatch") pickled_args = cPickle.dumps(args, 2) pickled_kwargs = cPickle.dumps(kwargs, 2) data = urllib.urlencode({'func_name' : func_name, 'args' : pickled_args, 'kwargs': pickled_kwargs}) resp = self.opener.open(dispatch_url, data) Recieving the data at the server works, too: def dispatch(request): func_name = request.POST["func_name"] pickled_args = request.POST["args"] pickled_kwargs = request.POST["kwargs"] But unpickling raises an error: cPickle.loads(pickled_args) Traceback (most recent call last): File "<string>", line 1, in <fragment> TypeError: must be string, not unicode Obviously the urllib.urlencode has created a unicode string. But how can I convert it back to be able to unpickling (laods) again? By the way, using pickle format 0 (ascii) works. I can convert to string before unpickling, but I'd rather use format 2. Also, recommendations about how to get binary data to a Django view are highly appreciated. A: Obviously the urllib.urlencode has created a unicode string. urllib.urlencode doesn't return Unicode string. It might be a feature of the web framework you use that request.POST contains Unicode strings. Don't use pickle to communicate between services it is not secure, brittle, not portable, hard to debug and it makes your components too coupled.
{ "language": "en", "url": "https://stackoverflow.com/questions/7527302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }