text
stringlengths
8
267k
meta
dict
Q: Ruby: sort array of hashes, even though key may not exist In a rails application, I have an array of hashes which I can sort easily with just array_of_hashes.sort_by { |hash| hash[:key_to_sort] } But what if not every array member has a key :key_to_sort? Then the sort will fail "comparison of String with nil failed". Is there a way to allow the sort to continue? Or is there another way to do this? A: It depends what you want to do when a hash doesn't have sorting key. I can imagine two scenarios: 1) exclude the hash from sorting arr.delete_if { |h| h[:key_to_sort].nil? }.sort_by { |h| h[:key_to_sort] } 2) place the hash at the beginning/end of the array: arr.sort_by { |h| h[:key_to_sort] || REALLY_SMALL_OR_LARGE_VALUE }
{ "language": "en", "url": "https://stackoverflow.com/questions/7570263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How does Java derive the the Initialization vector from SecretKeySpec for AES? I'm trying to encrypt some text using AES on .net and have it read on Java. The sample code I got for the encryption looks like this: byte[] key = ... SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); How does Java get the key and the IV from the SecretKey object? I need to provide them for .net and have found no information on it. A: You may provide the IV to the cipher in Java using an instance of IvParameterSpec passed to Cipher.init. If you don't, a random IV will be generated and made available by the getIV method of Cipher.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Check that a PostgreSQL database is new Is there a "simple way" to check that the database is new and doesn't have any modifications? When I'm referring to a new database I mean a recently created database (e.g. create database newdb) Perhaps using psql to execute some SQL statement to check information in pg_catalog Thanks in advance. A: I think that simplest way is to compare sql dump of both databases (implicit template is template1): pg_dump -Fp -f templatedb.sql template1 pg_dump -Fp -f mydb.sql mydb diff templatedb.sql mydb.sql Note that template1 db has its own comment: COMMENT ON DATABASE template1 IS 'Default template database'; A: Without more investigation, I suggest the following query SELECT n.nspname as "Schema", c.relname as "Name", CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence' WHEN 's' THEN 'special' END as "Type", pg_catalog.pg_get_userbyid(c.relowner) as "Owner" FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('r','v','S','') AND n.nspname <> 'pg_catalog' AND n.nspname <> 'information_schema' AND n.nspname !~ '^pg_toast' AND pg_catalog.pg_table_is_visible(c.oid) ORDER BY 1,2; This is the query that psql uses to display the contents of the \d command. If the result of this query is nothing, than the database has no tables, views,... I assume that en empty database is a sign of a newly created database. Note that the result from the query above excludes pg_catalog, so changes in settings or similar will not be returned.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP regex question for use in DB I am new to this and had a question. I have 2 input boxes with times. The values that i get back are 3h 20m 31s. How do i take this and turn this into 3:20:31 so i can use it in my database ? A: No need to use regexes. If you have fixed format you can just do $input = "3h 20m 31s"; $input = str_replace("h ",":",$input); $input = str_replace("m ",":",$input); $input = str_replace("s","",$input); Or if you are keen for regexes: $input = "3h 20m 31s"; $regex = "/^\D*(\d+)\D*(\d+)\D*(\d+)\D*$/"; $matches = array(); preg_match($regex, $input,$matches); echo implode(":",array_slice($matches,1))
{ "language": "en", "url": "https://stackoverflow.com/questions/7570268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I ignore some unit-tests without lowering the code-coverage percentage? I have one class which talks to DataBase. I have my integration-tests which talks to Db and asserts relevant changes. But I want those tests to be ignored when I commit my code because I do not want them to be called automatically later on. (Just for development time I use them for now) When I put [Ignore] attribute they are not called but code-coverage reduces dramatically. Is there a way to keep those tests but not have them run automatically on the build machine in a way that the fact that they are ignored does not influence code-coverage percentage? A: Whatever code coverage tool you use most likely has some kind of CoverageIgnoreAttribute or something along those lines (at least the ones I've used do) so you just place that on the method block that gets called from those unit tests and you should be fine. A: What you request seems not to make sense. Code-Coverage is measured by executing your tests and log which statements/conditions etc. are executed. If you disable your tests, nothing get executed and your code-coverage goes down. A: I do not know if this is applicable to your situation. But spontaneously I am thinking of a setup where you have two solution files (.sln), one with unit/integration tests and one without. The two solutions share the same code and project files with the exception that your development/testing solution includes your unit tests (which are built and run at compile time), and the other solution doesn't. Both solutions should be under source control but only the one without unit tests are built by the build server. This kind of setup should not need you to change existing code (too much). Which I would prefer over rewriting code to fit your test setup. A: TestNG has groups so you can specify to only run some groups, automatically and have the others for usage outside of that. You didn't specify your unit testing framework but it might have something similar.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Compiling Ruby 1.9.2 under Linux (Ubuntu) and Rubygems I already installed Ruby 1.9.2 with Rubygems successfully on my main machine. Now on my server I'm again in this job. Last time I had a problem, which came up right now as well: gem install rails ERROR: Loading command: install (LoadError) no such file to load -- zlib ERROR: While executing gem ... (NameError) uninitialized constant Gem::Commands::InstallCommand I knew how to fix this, but forgot it. I found an article here on stackoverflow (which I cannot find again) that tells me to compile some native ruby extension first. In the source code you have to go into a dir, where you find dirs for zlib, linecache and so on. Those you have to compile and you're done: everything then works. Can somebody tell me again how to do this? Sorry, Google and the Stackoverflow search didn't help this time. Thanks. Yours, Joern A: * *use RVM to install a ruby - its really incredible stuff *you didnt used flags on the ruby compilation (--with-zlib-dir=/...zlib_path...) A: I found the thread again! Has anyone tried installing ruby & rubygems from source on ubuntu In the 3rd answer of Evgeny you find exactly what I was searching for!
{ "language": "en", "url": "https://stackoverflow.com/questions/7570272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem with append in $.each I have 3 output in following jQuery.each(), i want echo(append) each a of they in one tag li. Like: This is output $.each(): how & hello & hi I want this: <ol> <li> <a href="">how</a> </li> <li> <a href="">hello</a> </li> <li> <a href="">hi</a> </li> </ol> But following jquery code append all 3 times in the a li, as:(i not want this) <ol> <li> <a href="">howhellohi</a> </li> <li> <a href="">howhellohi</a> </li> <li> <a href="">howhellohi</a> </li> </ol> This is my jquery code: $.ajax({ type: "POST", dataType: "json", url: 'get_residence', data: dataString_h, cache: false, success: function (respond) { $.each(respond.data, function (index, value) { $('ol li').append('<a href="" class="tool_tip" title="ok">' + value.name[index] + '</a>'); }); }, "error": function (x, y, z) { alert("An error has occured:\n" + x + "\n" + y + "\n" + z); } }); This is my respond in jquery code: { "data": [{ "name": "how", "star_type": "5-hotel", "site": "www.sasaas.assa", "service": ["shalo", "jikh", "gjhd", "saed", "saff", "fcds"], "address": "chara bia paeen" }, { "name": "hello", "star_type": "4-motel", "site": "www.sasasa.asas", "service": ["koko", "sili", "solo", "lilo"], "address": "haminja kilo nab" }, { "name": "hi", "star_type": "3-apparteman", "site": "www.saassaas.aas", "service": ["tv", "wan", "hamam", "kolas"], "address": "ok" }] } How can fix it? A: Change value.name[index] in your code to value.name because that's actually the correct code. That's actually why you use .each() A: I think this is the logic you're after: $.each(respond.data, function (index, value) { $('ol li').eq(index).append('<a href="" class="tool_tip" title="ok">' + value.name[index] + '</a>'); }); This will add the data to the proper list item, not the same data to all list items. A: Your code seems correct to me, the problem might lie in value.name[index] which seems to be always equal to howhellohi. If you alert value.name[index] what do you get?If you get always howhellohi the problem is in your server side function
{ "language": "en", "url": "https://stackoverflow.com/questions/7570273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JavaScript indexOf() - how to get specific index Let's say I have a URL: http://something.com/somethingheretoo and I want to get what's after the 3rd instance of /? something like the equivalent of indexOf() which lets me input which instance of the backslash I want. A: If you know it starts with http:// or https://, just skip past that part with this one-liner: var content = aURL.substring(aURL.indexOf('/', 8)); This gives you more flexibility if there are multiple slashes in that segment you want. A: let s = 'http://something.com/somethingheretoo'; parts = s.split('/'); parts.splice(0, 2); return parts.join('/'); A: Try something like the following function, which will return the index of the nth occurrence of the search string s, or -1 if there are n-1 or fewer matches. String.prototype.nthIndexOf = function(s, n) { var i = -1; while(n-- > 0 && -1 != (i = this.indexOf(s, i+1))); return i; } var str = "some string to test"; alert(str.nthIndexOf("t", 3)); // 15 alert(str.nthIndexOf("t", 7)); // -1 alert(str.nthIndexOf("z", 4)); // -1 var sub = str.substr(str.nthIndexOf("t",3)); // "test" Of course if you don't want to add the function to String.prototype you can have it as a stand-alone function by adding another parameter to pass in the string you want to search in. A: If you want to stick to indexOf: var string = "http://something/sth1/sth2/sth3/" var lastIndex = string.indexOf("/", lastIndex); lastIndex = string.indexOf("/", lastIndex); lastIndex = string.indexOf("/", lastIndex); string = string.substr(lastIndex); If you want to get the path of that given URL, you can also use a RE: string = string.match(/\/\/[^\/]+\/(.+)?/)[1]; This RE searches for "//", accepts anything between "//" and the next "/", and returns an object. This object has several properties. propery [1] contains the substring after the third /. A: Another approach is to use the Javascript "split" function: var strWord = "me/you/something"; var splittedWord = strWord.split("/"); splittedWord[0] would return "me" splittedWord[1] would return "you" splittedWord[2] would return "something" A: It sounds like you want the pathname. If you're in a browser, keep an a element handy... var _a = document.createElement('a'); ...and let it do the parsing for you. _a.href = "http://something.com/somethingheretoo"; alert( _a.pathname.slice(1) ); // somethingheretoo DEMO: http://jsfiddle.net/2qT9c/ A: In your case, you could use the lastIndexOf() method to get the 3rd forward slash. A: Here's a very cool way of handling this: How can I remove all characters up to and including the 3rd slash in a string? My preference of the proposed solutions is var url = "http://blablab/test/page.php"; alert(url.split("/")[3]); //-> "test" A: Inestead of using indexOf it is possible to do this this way: const url = 'http://something.com/somethingheretoo'; const content = new URL(url).pathname.slice(1);
{ "language": "en", "url": "https://stackoverflow.com/questions/7570276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: kernel crash with kmalloc I am trying to assign memory using kmalloc in kernel code in fact in a queueing discipline. I want to assign memory to q->agg_queue_hdr of which q is a queueing discipline and agg_queue_hdr is a struct, so if assign memory like this: q->agg_queue_hdr=kmalloc(sizeof(struct agg_queue), GFP_ATOMIC); the kernel crashes. Based on the examples of kmalloc I saw from searching, I now changed it to: agg_queue_hdr=kmalloc(sizeof(struct agg_queue), GFP_ATOMIC); with which the kernel doesn't crash. Now I want to know how can I assign memory to the pointer q->agg_queue_hdr? A: Make sure q is pointed to a valid area of memory. Then you should be able to assign q->agg_queue_hdr like you had it to begin with. A: Why don't you modify your code with below way, which would avoid kernel panic. if (q->agg_queue_hdr) { q->agg_queue_hdr = kmalloc(sizeof(struct agg_queue), GFP_ATOMIC); } else { printk("[+] q->agg_queue_hdr invalid \n"); dump_stack(); // print callstack in the kernel log. } When disassembing "q->agg_queue_hdr", "ldr" instruction will works where kernel panic occurs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Code snippet over a black background in Emacs Muse I have the following Emacs Muse snippet: <src lang="cc"> int a = 1; </src> This "htmlizes" the code within the angle brackets (adding color to keywords, etc.). The problem is that my font faces are optimized for a black Emacs background. Does anyone know how to tell Muse to output the code over a black background? Thanks. A: This is really not problem of Muse, but of htmlize package. It looks for face-background property of given face, so you need to check, which background is set for default face and for font-lock-* faces... Please, check also htmlize's version
{ "language": "en", "url": "https://stackoverflow.com/questions/7570284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I navigate to an internal link and execute jquery function? I´m a very new to jquery. I´m using this jquery code fragment and it´s working fine. But I would like to navigate from anywhere on the website and still have the function work: function showselectedbox(theselectedbox) { $(".pageboxes").each(function (index) { if ($(this).attr("id") == theselectedbox) { $(this).show(200); } else { $(this).hide(600); } }); } <a id="myHeader1" href="javascript:showselectedbox('mynewboxes1');" >show this one only</a> <div class="pageboxes" id="mynewboxes1">Div #1</div> <a id="myHeader2" href="javascript:showselectedbox('mynewboxes2');" >show this one only</a> <div class="pageboxes" id="mynewboxes1">Div #1</div> ... more of the same. I also build a tabbed menu for the navigation, and would like the selected link marked. <div id="metaltop-teal"> <ul> <li class="first active"><a id="myHeader1" href="javascript:showonlyone('mynewboxes1');" >show this one only</a></li> <li><a id="myHeader2" href="javascript:showonlyone('mynewboxes2');" >show this one only</a></li>... </ul> </div> Is there also another way to format the url? e.g: <a href="url" ...>link to page</a> Thanks A: you should put your javascript in a .js file and then include the file in your other files: <script src="yourfile.js" type="text/javascript"></script> now you can refer to your javascript function freely. Remember to include your .js-file AFTER you include jquery, or your script won't work. EDIT: To have code execute upon pageload, I'd use $('document').ready() This ensures that the code isn't executed until all elements of the DOM is loaded. This way, you avoid trying to manipulate elements that aren't there. This is especially important when using eventhandlers such as click(). For live() and delegate() which also are attached to elements created later, this is not so important. Firstly you make a line: $('document').ready(function(){ after that line, you put anything to execute when the page is loaded. To finish this block, you write }); And after that you put your functions etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Data Binding in if statements In an aspx page i have: <asp:HyperLink ID="HyperLink" runat="server" style="cursor:pointer; text-decoration:none;" NavigateUrl='<%#String.Format("~/storefront.aspx?CatalogID={0}",Eval("CatalogID"))%>'> <asp:Label id="lblCustItem" Runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "CustItem")%>' width="15%"> </asp:Label> </asp:HyperLink> And now I am trying to do: <%if (Eval("Integration").ToString() == "Y") { %> <asp:HyperLink ID="HyperLink1" runat="server" style="cursor:pointer; text-decoration:none;" NavigateUrl='<%#String.Format("~/integration/vendorframe.aspx?CatalogID={0}",Eval("CatalogID"))%>'> <asp:Label id="CustItemlbl" Runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "CustItem")%>' width="15%"> </asp:Label> </asp:HyperLink> <%} %> <%else { %> <asp:HyperLink ID="HyperLink" runat="server" style="cursor:pointer; text-decoration:none;" NavigateUrl='<%#String.Format("~/storefront.aspx?CatalogID={0}",Eval("CatalogID"))%>'> <asp:Label id="lblCustItem" Runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "CustItem")%>' width="15%"> </asp:Label> </asp:HyperLink> <%} %> the page errors out on the second segment of code. So my question is, am i doing something wrong, and is there a better way to use an if statement, like the conditional if, but i do need to run a new instance of string.format thats why I was thinking that wasn't an option. Error Message: Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control. A: One solution is to use an Inline If: Text='<%# (Eval("Integration").ToString() == "Y") ? DataBinder.Eval(Container.DataItem, "CustItem") : "" %>' It's not pretty, but it'll get the job done. A: This worked for me. Within the Formview. <div id="PermDiv" runat="server" visible='<%#(Eval("Permissions").Equals("Edit") ? true : false ) %>'></div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7570287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to split string using Substring I have a string like '/Test1/Test2', and i need to take Test2 separated from the same. How can i do that in c# ? A: Try this: string toSplit= "/Test1/Test2"; toSplit.Split('/'); or toSplit.Split(new [] {'/'}, System.StringSplitOptions.RemoveEmptyEntries); to split, the latter will remove the empty string. Adding .Last() will get you the last item. e.g. toSplit.Split('/').Last(); A: Using .Split and a little bit of LINQ, you could do the following string str = "/Test1/Test2"; string desiredValue = str.Split('/').Last(); Otherwise you could do string str = "/Test1/Test2"; string desiredValue = str; if(str.Contains("/")) desiredValue = str.Substring(str.LastIndexOf("/") + 1); Thanks Binary Worrier, forgot that you'd want to drop the '/', darn fenceposts A: Use .Split(). string foo = "/Test1/Test2"; string extractedString = foo.Split('/').Last(); // Result Test2 This site have quite a few examples of splitting strings in C#. It's worth a read. A: string[] arr = string1.split('/'); string result = arr[arr.length - 1]; A: string [] split = words.Split('/'); This will give you an array split that will contain "", "Test1" and "Test2". A: If you just want the Test2 portion, try this: string fullTest = "/Test1/Test2"; string test2 = test.Split('/').ElementAt(1); //This will grab the second element. A: string inputString = "/Test1/Test2"; string[] stringSeparators = new string[] { "/Test1/"}; string[] result; result = inputString.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries); foreach (string s in result) { Console.Write("{0}",s); } OUTPUT : Test2
{ "language": "en", "url": "https://stackoverflow.com/questions/7570289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can we modify close buttons to alert view UILocalnotification dialog I have a task to develop the application with UILocalnotification and modify button of alert dialog box. How can we modify close button with user custom name to UILocalnotification alertview dialog? A: You can modify only view button title, pressing which will open your app.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: why I have two different result when I execute this javascript closure code my code : var n; function f(){ var v = "kevin"; n = function(){ return v; } } execute in FireBug: n(); the result is "kevin" execute in Chrome & IE9: document.writeln(n); ======>show "undefine" document.writeln(n()); ======>show nothing I want to know what exactly the brows doing when execute the code. Thanks. That code is a demo of the book "Object Oriented JavaScript", Chapter 3, Closure 2# A: The variable n is not given a value (i.e., is not assigned to that function) until the function f() has been executed - which doesn't happen in the code you show. So document.writeln(n); should show "undefined", while document.writeln(n()); should be an error since n is not a function. I don't know why it works in FireBug - have you already executed f() when you try it?
{ "language": "en", "url": "https://stackoverflow.com/questions/7570304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Using the Lists web service in SharePoint 2007, how can I update the Author value programatically? I have a process that uploads a file to a SharePoint form list and would like the Author (Created By) column to be the user who created the file and not the process user. I have been trying the UpdateListItems method of the Lists web service and can update other fields but not the Author field. Here is a sample of the CAML text I have been trying. <Batch OnError="Continue" ListVersion="1"> <Method ID="1" Cmd="Update"> <Field Name="ID">3396</Field> <Field Name="Author"><USERID>;#<USERNAME></Field> <Field Name="Created_x0020_By"><DOMAIN>\<USERLOGIN></Field> </Method> </Batch> Any help or ieda would be greatly appreciated. A: You can update Author field after you clear ReadOnly attribute with UpdateList() method. After it you can set Author field by UpdateListItems() method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting a value of an array index using variable variable I have a recursive array depth of which is variable, and I want to be able to take a string with a separator and convert that string to an index in that array, For example $path = 'level1.level2.level3'; will be converted to get the value 'my data' from the array below $data['level1']['level2']['level3'] = 'my data'; I thought the quickest way to get this would be to use variable variables, but when I try the following code $index = "data['level1']['level2']['level3']"; echo $$index; I get the follwing error PHP Notice: Undefined variable: data['level1']['level2']['level3'] All other ways I can think of doing this are very inefficient, could someone please shed some light on this, is it possible using variable variables for arrays in PHP? Any other efficient workaround? Many thanks. A: You'll have to loop the array, you won't manage to do this using variable variables, as far as I know. This seems to work though: <?php function retrieve( $array, $path ) { $current = $array; foreach( explode( '.', $path ) as $segment ) { if( false === array_key_exists( $segment, $current ) ) { return false; } $current = $current[$segment]; } return $current; } $path = 'level1.level2.level3'; // will be converted to get the value 'my data' from the array below $data['level1']['level2']['level3'] = 'my data'; var_dump( retrieve( $data, $path ) ); A: It is a tricky one this, here is the most efficient way I can think of: function get_value_from_array ($array, $path, $pathSep = '.') { foreach (explode($pathSep, $path) as $pathPart) { if (isset($array[$pathPart])) { $array = $array[$pathPart]; } else { return FALSE; } } return $array; } Returns the value, or FALSE on failure. A: Try $index = "data"; echo $$index['level1']['level2']['level3']; instead, because $index should be only variable name A: Something like this: eval('$data[\''.implode("']['",explode('.',$path))."'] = 'my data';"); ...but don't ever, ever tell anyone I told you to do this. A: You can use eval function like so: $data['level1']['level2']['level3'] = 'my data'; eval("\$index = \$data['level1']['level2']['level3'];"); echo $index;
{ "language": "en", "url": "https://stackoverflow.com/questions/7570307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error with Entity Framework 4 and MVC 3 I have a database with 3 tables: * *Subjects *Members *Topics Then I added the connection string to web.config and created an EF with the following classes: namespace MySite.Models { public class MySiteDBModel : DbContext { public DbSet<Topic> Topics { get; set; } public DbSet<Subject> Subjects { get; set; } public DbSet<Member> Members { get; set; } public DbSet<TopicDataModel> TopicDataModel { get; set; } protected override void OnModelCreating(DbModelBuilder mb) { mb.Conventions.Remove<PluralizingTableNameConvention>(); } } public class Topic { [Key] public int TopicID { get; set; } public int SubID { get; set; } public int MemberID { get; set; } public string TDate { get; set; } public string Title { get; set; } public string FileName { get; set; } public int Displays { get; set; } public string Description { get; set; } public virtual Subject Subject { get; set; } public virtual Member Member { get; set; } public virtual ICollection<TopicView> TopicView { get; set; } } public class Subject { [Key] public int SubID { get; set; } public string SubName { get; set; } public virtual ICollection<Topic> Topic { get; set; } } public class Member { [Key] public int MemberID { get; set; } public string FLName { get; set; } public string Email { get; set; } public string Pwd { get; set; } public string About { get; set; } public string Photo { get; set; } public virtual ICollection<Topic> Topic { get; set; } } public class TopicDataModel { [Key] public int TopicID { get; set; } public string SubName { get; set; } public string FLName { get; set; } public string TDate { get; set; } public string Title { get; set; } public int Displays { get; set; } public string Description { get; set; } } } Now when I am trying to query the database with the this code: public ActionResult Index() { var topics = from t in db.Topics join s in db.Subjects on t.SubID equals s.SubID join m in db.Members on t.MemberID equals m.MemberID select new TopicDataModel() { TopicID = t.TopicID, SubName = s.SubName, FLName = m.FLName, TDate = t.TDate, Title = t.Title, Displays = t.Displays, Description = t.Description }; return View(topics.ToList()); } I got this Error: The model backing the 'MySiteDBModel' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data. Please help me!!!!!! A: You need to set some controls on how EF is handling changes to your data model. Julie Lerman has a good blog post on Turning Off Code First Database Initialization Completely. Also, here is a good overview - Inside Code First Database Initialization
{ "language": "en", "url": "https://stackoverflow.com/questions/7570309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Zxing change the action intent I added the Zxing library to my android app but there is a problem. When you already have a bar code scanner installed it presents you with a popup. I don't want this to happen and changed the the action intent. This is working, but when I open my app for the first time and select the bar code scanner it crashes. When I open it for the second time everything works fine. Can anybody please help me? A: I've already answered this a few times on the mailing list. As I said, you need to pay attention to ActivityNotFoundException. 09-27 16:52:54.046 E/AndroidRuntime( 4949): Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {nl.everybodylikespenguins/com.google.zxing.client.android.HelpActivity}; have you declared this activity in your AndroidManifest.xml? 09-27 16:52:54.046 E/AndroidRuntime( 4949): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1404) 09-27 16:52:54.046 E/AndroidRuntime( 4949): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1378) 09-27 16:52:54.046 E/AndroidRuntime( 4949): at android.app.Activity.startActivityForResult(Activity.java:2789) 09-27 16:52:54.046 E/AndroidRuntime( 4949): at android.app.Activity.startActivity(Activity.java:2895) 09-27 16:52:54.046 E/AndroidRuntime( 4949): at com.google.zxing.client.android.CaptureActivity.showHelpOnFirstLaunch(CaptureActivity.java:595) 09-27 16:52:54.046 E/AndroidRuntime( 4949): at com.google.zxing.client.android.CaptureActivity.onCreate(CaptureActivity.java:169) 09-27 16:52:54.046 E/AndroidRuntime( 4949): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 09-27 16:52:54.046 E/AndroidRuntime( 4949): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2544) Android throws this when you start an intent for which there is no app, and that's what's happening here. You need to handle this yourself by catching the exception and, maybe, sending the user to Market to download. This is exactly what the code in android-integration in zxing does, which is why I also already told you to look at that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I use part of a larger image as a marker in OpenLayers? Is it possible to use part of a larger image as a marker with OpenLayers? Like this (in google maps): var icon = new google.maps.MarkerImage( "img/marker_sprite.png", new google.maps.Size(26, 44), new google.maps.Point(0, 44) ); A: The basic recipe for adding a marker to a map in OpenLayers starts with adding a Marker layer to your map, which you can do like this: var markers = new OpenLayers.Layer.Markers("Markers"); map.addLayer(markers); Then you will need to add markers to that layer, which goes something like this: var position = new OpenLayers.LonLat(longitude, latitude); position.transform(new OpenLayers.Projection("EPSG:4326", map.getProjectionObject()); var icon = new OpenLayers.Icon("img/marker_sprite.png", new OpenLayers.Size(26, 44)); var marker = new OpenLayers.Marker(position, icon); markers.addMarker(marker); Unfortunately it's not possible, as far as I know, so set the origin for the marker within the image file so you can just use part of the image. Well you can, but only if the part you want is in the corner, which isn't very helpful.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Open physical drive from Linux I'd like to open SD card as physical drive on Linux. Somethink like: CreateFile("PHYSICALDRIVE0",...) On MS Windows. How can I do it? A: All devices are represented as files under the /dev directory. These files can be opened exactly like regular files, e.g. open(/dev/sdb, ...). Disk-like devices are also symlinked in the directories /dev/disk/by-id/, /dev/disk/by-path, and /dev/disk/by-uuid, which makes it much easier to find to matching device file. A: Type df, to list all your filesystems mounted or unmounted. Once you know its address(everything in Linux is a file, so it will look like /dev/sda# or something like that) you can mount it with the mount command: mount /path/to/drive /folder/to/mount/to A: You open the block device special file (typically something like /dev/sdb) and then you can read/write blocks from it. The interface is not clearly documented, it is a bug that there is no block(4) man page. The sd(4) man page does help a bit though. The ioctls described there are probably valid for (some) other block devices as well. Nowadays nearly all block devices appear as a "scsi drive" regardless of whether they are actually attached by scsi or not. This includes USB and (most) ATA drives. Finding the right device to open may be a big part of the problem though, particularly if you have hotplug devices. You might be able to interrogate some things in /sys to find out what devices there are.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: The right way to plot multiple y values as separate lines with ggplot2 I often run into an issue where I have a data frame that has a single x variable, one or more facet variables, and multiple different other variables. Sometimes I would like to simultaneously plot different y variables as separate lines. But it is always only a subset I want. I've tried using melt to get "variable" as a column and use that, and it works if I want every single column that was in the original dataset. Usually I don't. Right now I've been doing things really roundabout it feels like. Suppose with mtcars I want to plot disp, hp, and wt against mpg: ggplot(mtcars, aes(x=mpg)) + geom_line(aes(y=disp, color="disp")) + geom_line(aes(y=hp, color="hp")) + geom_line(aes(y=wt, color="wt")) This feels really redundant. If I first melt mtcars, then all variables will get melted, and then I will wind up plotting other variables that I don't want to. Does anyone have a good way of doing this? A: With reshape2 being deprecated, I updated @kohske answer using pivot_longer from tidyverse package. Pivoting is explained here and involves specifying the data to reshape, second argument describes which columns need to be reshape (use - to exclude that column). Third is names_to gives the name of the variable that will be created from the data stored in the column names. Finally values_to gives the name of the variable that will be created from the data stored in the cell value, i.e. count. They also have more complex examples like numbers in column names e.g. wk1 wk2 etc. # new suggestion library(tidyverse) # I subset to just the variables wanted so e.g. gear and cab are not included mtcars.long <- mtcars %>% select("mpg","disp", "hp", "wt") %>% pivot_longer(-mpg, names_to = "variable", values_to = "value") head(mtcars.long) # # A tibble: 6 x 3 # mpg variable value # <dbl> <chr> <dbl> # 1 21 disp 160 # 2 21 hp 110 # 3 21 wt 2.62 # 4 21 disp 160 # 5 21 hp 110 # 6 21 wt 2.88 ggplot(mtcars.long, aes(mpg, value, colour = variable)) + geom_line() Chart is: A: ggplot always prefers long format dataframe, so melt it: library(reshape2) mtcars.long <- melt(mtcars, id = "mpg", measure = c("disp", "hp", "wt")) ggplot(mtcars.long, aes(mpg, value, colour = variable)) + geom_line() There are many other options for doing this transformation. You can see the R-FAQ on converting data from wide to long for an overview.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Remove pattern from database I have a MySQL table with over 3 million rows that includes peoples names and the state they are from e.g. "Smith (SC)" I would like to remove the state info and have "Smith". Since there are many difference last names and states used I was wondering if there was any trick to make this easier and just remove the parentheses and the text contained inside of them. Any advice would be greatly appreciated. A: Test with a select to make sure you're getting good results: SELECT LastName, LEFT(LastName, LOCATE('(', LastName) - 1) AS CorrectedLastName FROM YourTable WHERE LOCATE('(', LastName) <> 0 Once you're confident in the results: UPDATE YourTable SET LastName = LEFT(LastName, LOCATE('(', LastName) - 1) WHERE LOCATE('(', LastName) <> 0 A: Make a backup first, then try Update <tablename> set name =substr(name,1, instr(name,'(')); substr is for oracle but check the mysql equivalent
{ "language": "en", "url": "https://stackoverflow.com/questions/7570320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Generate PDF from Plone content types I need to create PDFs from content types (made with dexerity if that matters) so that the user creates a new document and after filling the form a PDF is generated and ready to be downloaded. So basically after creating/modifying the document a PDF should be created and stored in ZODB (actually I'm using blobs) so that I could link the view with a "Download as PDF". I've seen PDFNode but it doesn't seem to be what I'm looking for. There's also Produce & Publish but it's a webservice(?) and the company I'm going to develop this for doesn't want (for privacy) to send data outside their datacenters. Any idea? A: It seems that you are searching for these: * *Reportlab (official site) for a custom solution *collective.sendaspdf for an ootb solution A: I actually do this sort of thing a lot on a project of mine. I used Products.SmartPrintNG and fop for it though and didn't do it the standard way that the product uses(I think it uses javascript to initiate the conversion.. weird). Couple things: * *I had to sanitize the output since fop is pretty touchy *used lxml *mine uses archetypes Anyways, my event handler for creating the PDF ends up looking something like this: from Products.SmartPrintNG.browser import SmartPrintView from lxml.cssselect import CSSSelector from lxml.html import fromstring, tostring import re san_re = re.compile('(?P<width>width\=("|\')\d{1,5}(px|%|in|cm|mm|em|ex|pt|pc)?("|\'))') class Options(object): def __init__(self, __dict): self.__dict = __dict def __getattr__(self, attr): if self.__dict.has_key(attr): return self.__dict[attr] raise AttributeError(attr) def sanitize_xml(xml): selector = CSSSelector('table,td,tr') elems = selector(xml) for el in elems: if el.attrib.has_key('width'): width = el.attrib['width'] style = el.attrib.get('style', '').strip() if style and not style.endswith(';'): style += ';' style += 'width:%s;' % width del el.attrib['width'] el.attrib['style'] = style return xml def save_pdf(obj, event): smartprint = SmartPrintView(obj, obj.REQUEST) html = obj.restrictedTraverse('view')() xml = fromstring(html) selector = CSSSelector('div#content') xml = selector(xml) html = tostring(sanitize_xml(xml[0])) res = smartprint.convert( html=html, format='pdf2', options=Options({'stylesheet': 'pdf_output_stylesheet', 'template': 'StandardTemplate'}) ) field = obj.getField('generatedPDF') field.set(obj, res, mimetype='application/pdf', _initializing_=True) field.setFilename(obj, obj.getId() + '.pdf') A: Produce and Publish Lite is self-contained, open-source code and the successor to SmartPrintNG. http://pypi.python.org/pypi/zopyx.smartprintng.lite/ A: use z3c.rml, works very well to produce pdf from an rml template, instead of converting from html which can be tricky.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: JBoss RESTeasy JAX-RS JAXB schema validation with Decorator I am trying to validate all incoming XML files that come over my (contract first) REST interface in an application running inside JBoss AS 7. I have written a @Decorator for Pretty-Printing (as by the example in the JBoss RESTeasy documentation) and an analogous one for switching on XML schema validation for the unmarshaller. Unfortunately, the decorator for the unmarshaller is never called. Here is the code for the Pretty Decorator: import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.xml.bind.Marshaller; import org.jboss.resteasy.annotations.Decorator; @Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Decorator(processor = PrettyProcessor.class, target = Marshaller.class) public @interface Pretty {} And the implementation: import java.lang.annotation.Annotation; import javax.ws.rs.core.MediaType; import javax.xml.bind.Marshaller; import javax.xml.bind.PropertyException; import org.apache.log4j.Logger; import org.jboss.resteasy.annotations.DecorateTypes; import org.jboss.resteasy.spi.interception.DecoratorProcessor; @DecorateTypes({ "text/*+xml", "application/*+xml", MediaType.APPLICATION_XML, MediaType.TEXT_XML }) public class PrettyProcessor implements DecoratorProcessor<Marshaller, Pretty> { private static final Logger LOGGER = Logger.getLogger(PrettyProcessor.class); @Override public Marshaller decorate(Marshaller target, Pretty annotation, Class type, Annotation[] annotations, MediaType mediaType) { LOGGER.debug("Pretty."); try { target.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); } catch (PropertyException e) { } return target; } } Now the annotation for the Validate (that does not work): import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.xml.bind.Unmarshaller; import org.jboss.resteasy.annotations.Decorator; @Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Decorator(processor = ValidateProcessor.class, target = Unmarshaller.class) public @interface Validate {} The implementation: import java.lang.annotation.Annotation; import javax.ws.rs.core.MediaType; import javax.ws.rs.ext.Provider; import javax.xml.XMLConstants; import javax.xml.bind.Marshaller; import javax.xml.bind.PropertyException; import javax.xml.bind.Unmarshaller; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import org.apache.log4j.Logger; import org.jboss.resteasy.annotations.DecorateTypes; import org.jboss.resteasy.spi.interception.DecoratorProcessor; import org.xml.sax.SAXException; @DecorateTypes({ "text/*+xml", "application/*+xml", MediaType.APPLICATION_XML, MediaType.TEXT_XML }) public class ValidateProcessor implements DecoratorProcessor<Unmarshaller, Validate> { private static final Logger LOGGER = Logger.getLogger(ValidateProcessor.class); @Override public Unmarshaller decorate(Unmarshaller target, Validate annotation, Class type, Annotation[] annotations, MediaType mediaType) { target.setSchema(getSchema()); LOGGER.debug("Set validation schema."); System.out.println("Set validation schema."); return target; } } And the code of the REST interface: import javax.annotation.security.RolesAllowed; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.xml.ws.WebServiceException; @Path("/{mdvt}/{ouid}/order") public interface OrderResource { @RolesAllowed({ "mpa" }) @POST @Path("/update") @Consumes({MediaType.APPLICATION_XML, MediaType.TEXT_XML}) @Produces(MediaType.APPLICATION_XML) @Pretty public Response update(@Context SecurityContext sec, @PathParam("ouid") String ouID, @PathParam("mdvt") long masterDataVersionTag, @Validate UpdateOrdersRequest uor) throws WebServiceException; } On the same REST method, (update) the @Pretty Decorator gets called while the @Validate does not. What am I doing wrong here? I have found an old bug Decorator for Jaxb unmarshaller doesn't work which is closed. The comments there say that everything works, and the code above is almost exactly the one from there, including the solution. Nevertheless, nothing works for the Unmarshaller. A: Finally this problem was resolved for JBoss AS 7. The problem lies in the Resteasy implementation which is buggy until version 2.3.5.Final. See https://issues.jboss.org/browse/RESTEASY-711 but ignore the mentioned workaround, it does not work until version 2.3.5. The working solution is to download the Restwasy distribution version 2.3.5.Final or above, extract it and look for resteasy-jboss-modules-2.3.5.Final.zip Extract this file in the root of JBoss AS 7.1.1 and resteasy will be updated to the new version. After this step, all of the above code just works. Thanks to Bill Burke to point me to the solution, A: You could implement a MessageBodyReader that sets an Schema on the JAXB Unmarshaller to perform validation. For sample code check out my answer to a similar question: * *Validate JAXBElement in JPA/JAX-RS Web Service
{ "language": "en", "url": "https://stackoverflow.com/questions/7570326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to post in Google+ wall I want to share some information in Google+ wall from my application. For that I go through the Google+ API. In that API they are mentioning how to get access token of a particular user, but they do not mention how to post in users wall using the access token. A: If you use wordpress there is a plugin that allows you to post automatically to google plus WP Plugin Post to Google Plus however it's not free, cheap but not free. You can probably debug it since it's php and see how they do that. A: You can now do this. See google's developer docs below: https://developers.google.com/+/domains/posts/creating The only thing to be aware of is that the Google+ Domains API only allows creation of restricted posts, and only allows comments to be added to restricted posts. A: Writing to Google+ Profile Streams is restricted to just domains. For example, If you own a company named xyz co and has a domain xyz.com. You can used Google+ Domains API to write to streams. Though that will be restricted to people using same domain and using Google G Suit App for business and is not available for normal Google's gmail.com email ID. The Google+ Domains API only allows creation of restricted posts, and only allows comments to be added to restricted posts. For example Jon and Misha are working as employee in xyz co and has associated company mail id jon@xyz.com and misha@xyz.com then they can post to associated domain streams in Google+. Though these post will not be visible publicly and are restricted to be visible to members belonging to same domain. If any post has to be made public, then you have to do that task manually Ref. If you are looking to post information on Google+ for some business or celebrity then you must are looking for Google+ Page API, which allows you to write post on business page. Though they have restricted here with partners application form that need to be approved for having your access to Pages API, which is very stringent and difficult to get approved. The Google+ pages API allows social media management companies to add Google+ page management features into their tool. Access to this API is available through a whitelist, and access is granted to partners on a company by company basis dependent on fit with this API. If you are a social media management company interested in getting access to this API, please complete the form below with details about your company's platform. Please answer all questions below accurately; any inaccurate information that misrepresents your tool can affect your company's access to this API. If your company is a fit for this API's functionality, the Google+ team will reach out to the contact provided in this form with next steps. Please do not submit multiple entries to this form. Other method to post in Google+ is via their Share button, Interactive Posting & Embedded Posting to Google+ Ref. A: Well, Google+ doesn't have a "wall," it has "Streams." The proper term might help you find better search results. Either way, unless you're a Google partner, the news isn't good: The API is currently limited to read-only access. From the API website: Note: The Google+ API currently provides read-only access to public data. All API calls require either an OAuth 2.0 token or an API key. Because it's read-only, you will not be able to update or post any information anywhere through the API -- you can only use it to pull basic information like profile and activity details. Given that access to the API may change over time, I'll try to keep this answer up to date with information about news or changes related to write access. News & Updates 2015-04-28: Google+ Domains API was announced way back in August 2013, but somehow I missed its relevance to Google+. The Google+ Domains API allows Google Apps customers and ISVs to take advantage of enhanced Google+ APIs to build tools and services that can be used in a variety of ways. No, it does not provide full write access to a user's Google+ profile, but it does give you minor advantages over the Google+ API v1, at least within a domain. This one's mainly for mobile app developers. 2015-01-21: I have revisited many of the sources linked in this answer and searched for news regarding API changes, but Google has been quiet. 2014-03-12: Various discussion threads on Google+ about write access (or lack thereof): * *Discussion thread by Jeff Dwyer *In-depth discussion of the topic by Thor Mitchell (the Google+ team member mentioned in Update 6) 2013-12-03: The issue thread from UPDATE 1 has finally been responded to by a Google+ project member. Additional discussion regarding write-access to Streams is taking place intermittently on the Developing with Google+ community page. 2013-07-05: A developer named Eric Leroy has built an "unofficial" JavaScript library that provides read/write extension to the Google+ API. * *via Google+ XHR Hack = w+ (Add/Post) 2013-05-14: A "social media management company" can gain additional API access by attempting to become a Google+ Pages API Partner. * *Google+ Pages API Partner Application Form *More third party tools to help manage your Google+ page - An announcement from Eduardo Thuler *Original Google announcement of third party management tools Here's an excerpt from the Partner Application Form: The Google+ pages API allows social media management companies to add Google+ page management features into their tool. Access to this API is available through a whitelist, and access is granted to partners on a company by company basis dependent on fit with this API. Other articles explaining the lack of a write API: * *http://mashable.com/2012/08/02/google-to-developers-wont-screw-you/ 2013-01-04: Google just announced Google+ History. You can use it to write "moments" (which are private by default) but can then be made public by sharing them directly to your stream and/or your profile. One of the moment types is CommentActivity. 2012-10-08: There's now a duplicate bug post with only a few comments, but you can check there for future updates as well. 2012-06-25: I came across the issue tracker post for Google+ Write Access. The enhancement request status is "New" and priority is "Medium" as of June 25th, 2012. There are some links of interest in the comments. A: This might help: I have made this bookmarklet to post links to pages that I liked to my stream: javascript:location='https://plusone.google.com/_/+1/confirm?hl=en&url='+location The URL is self-explanatory. If your post content can be served via URL then you can post it like that. The only difficulty is to automate the posting callback from Google but I do not need it, should not be too hard. A: //Follow this : https://developers.google.com/+/mobile/ios/share/ -(void)shareGoogle{ [signIn authenticate]; [signIn trySilentAuthentication]; } -(void)refreshInterfaceBasedOnSignIn { if ([[GPPSignIn sharedInstance] authentication]) { // The user is signed in. NSLog(@"%@", [[GPPSignIn sharedInstance] authentication]); [self didTapShare:nil]; } else { self.signInButton.hidden = NO; // Perform other actions here } } - (IBAction) didTapShare: (id)sender { [GPPShare sharedInstance].delegate = self; id<GPPNativeShareBuilder> shareBuilder = [[GPPShare sharedInstance] nativeShareDialog]; // Set any prefilled text that you might want to suggest [shareBuilder setPrefillText:@"message"]; [shareBuilder attachImage:[UIImage imageWithData:imageData]]; [shareBuilder open]; likeShareBtn.userInteractionEnabled = FALSE; } - (void)finishedSharingWithError:(NSError *)error { NSString *text; if (!error) { text = @"Success"; } else if (error.code == kGPPErrorShareboxCanceled) { text = @"Canceled"; } else { text = [NSString stringWithFormat:@"Error (%@)", [error localizedDescription]]; } NSLog(@"Status: %@", text); } -(void)presentSignInViewController:(UIViewController *)viewController { // This is an example of how you can implement it if your app is navigation-based. [[self navigationController] pushViewController:viewController animated:YES]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7570327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "92" }
Q: Re-throw exception in task (TPL) loses stack trace I've code that rethrows an exception. When I later read the exception from task.Exception, its stacktrace points to the location where I re-threw the exception (line n and not line m, as I expected). Why is this so? bug in TPL or more likely something I have overlooked. As I workaround I can wrap the exception as the inner-exception in a new exception. internal class Program { private static void Main(string[] args) { Task.Factory.StartNew(TaskMethod).ContinueWith(t => Console.WriteLine(t.Exception.InnerException)); Console.Read(); } private static void TaskMethod() { try { line m: throw new Exception("Todo"); } catch (Exception) { line n: throw; } } } A: Unfortunately, due to the way TPL stores exceptions until the task finished executing, the original stack trace is lost. Running your sample code in LINQPad shows that the exception was thrown at at System.Threading.Tasks.Task.Execute(), which is obviously not correct. As a crude workaround, you could store the original stack trace (it being a simple string) on the Data property of the original exception, and you'll be able to access it then: private static void TaskMethod() { try { throw new Exception("Todo"); } catch (Exception ex) { ex.Data["OriginalStackTrace"] = ex.StackTrace; throw; } } Then you'll have the original stack trace stored in the OriginalStackTrace value of the Data dictionary: It's not really what you want, but I hope it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Logo only showing in Safari I've been scratching my head for the last 40 minutes trying to figure out why the logo on the below site is only working in Safari. http://www.jaygeorge.co.uk/catalyst-jrshairdressing/ The logo should be in the top left. The site is a WordPress site and the code I've used to drag in the logo is here: <a href="<?php echo get_option('home'); ?>/"><img src="<?php bloginfo('template_directory') ?>/img/logo.png" alt="JR's Hairdressing" title="JR's Hairdressing" /></a> If you hover over the logo and copy the image link you'll see that the link is correct. A: Looks like the image file itself is the issue. Try the normal bad-image troubleshooting stuff: Open and resave it. Make sure it's RGB. Try a gif instead, etc. A: Hard to tell what's actually causing the error, but I've found in situations like this simply opening the image in Paint/Photoshop/Gimp, re-saving it and re-uploading usually fixes the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Retrieving the interface–to–IP address mapping table I know the index of network interface returned by WinAPI's GetBestInterface. How do I get interface properties (IPv4 address) based on interface's index? Here is the working C++ code, but I need it in C#. PMIB_IPADDRTABLE pAddrTable; PMIB_IPADDRROW pAddrRow; in_addr ia; CBasePage::OnSetActive(); m_edit1.SetFont(&m_font); m_edit1.SetWindowText(""); GetIpAddrTable((PMIB_IPADDRTABLE) m_pBuffer, &m_ulSize, TRUE); m_pBuffer = new BYTE[m_ulSize]; if (NULL != m_pBuffer) { m_dwResult = GetIpAddrTable((PMIB_IPADDRTABLE) m_pBuffer, &m_ulSize, TRUE); if (m_dwResult == NO_ERROR) { pAddrTable = (PMIB_IPADDRTABLE) m_pBuffer; for (int x = 0; x < pAddrTable->dwNumEntries; x++) { pAddrRow = (PMIB_IPADDRROW) &(pAddrTable->table[x]); ia.S_un.S_addr = pAddrRow->dwAddr; m_strText.Format(" IP address: %s\r\n", inet_ntoa(ia)); m_edit1.ReplaceSel(m_strText); m_strText.Format(" Interface index: %lu\r\n", pAddrRow->dwIndex); m_edit1.ReplaceSel(m_strText); ia.S_un.S_addr = pAddrRow->dwMask; m_strText.Format(" Subnet mask: %s\r\n", inet_ntoa(ia)); m_edit1.ReplaceSel(m_strText); ia.S_un.S_addr = pAddrRow->dwBCastAddr; m_strText.Format("Broadcast address: %s\r\n", inet_ntoa(ia)); m_edit1.ReplaceSel(m_strText); m_edit1.ReplaceSel("\r\n"); } } else { m_strText.Format("GetIpAddrTable() failed. Result = %lu\r\n", m_dwResult); m_edit1.ReplaceSel(m_strText); } delete [] m_pBuffer; } I've tried the example on pinvoke but it returns 0.0.0.0 for all the interfaces. A: It works for me: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using System.Net; namespace IpInfo { [StructLayout( LayoutKind.Sequential, CharSet=CharSet.Ansi )] struct MIB_IPADDRROW { public int _address; public int _index; public int _mask; public int _broadcastAddress; public int _reassemblySize; public ushort _unused1; public ushort _type; } class Program { [DllImport("iphlpapi.dll", SetLastError=true)] public static extern int GetIpAddrTable(IntPtr pIpAddrTable, ref int pdwSize, bool bOrder); static void Main(string[] args) { IntPtr pBuf = IntPtr.Zero; int nBufSize = 0; // get the required buffer size GetIpAddrTable( IntPtr.Zero, ref nBufSize, false ); // allocate the buffer pBuf = Marshal.AllocHGlobal( nBufSize ); try { int r = GetIpAddrTable(pBuf, ref nBufSize, false); if (r != 0) throw new System.ComponentModel.Win32Exception(r); int entrySize = Marshal.SizeOf(typeof(MIB_IPADDRROW)); int nEntries = Marshal.ReadInt32(pBuf); int tableStartAddr = (int)pBuf + sizeof(int); for (int i = 0; i &lt nEntries; i++) { IntPtr pEntry = (IntPtr)(tableStartAddr + i * entrySize); MIB_IPADDRROW addrStruct = (MIB_IPADDRROW)Marshal.PtrToStructure(pEntry, typeof(MIB_IPADDRROW)); string ipAddrStr = IPToString(IPAddress.NetworkToHostOrder(addrStruct._address)); string ipMaskStr = IPToString(IPAddress.NetworkToHostOrder(addrStruct._mask)); Console.WriteLine("IP:" + ipAddrStr + " Mask:" + ipMaskStr); } } finally { if (pBuf != IntPtr.Zero) { Marshal.FreeHGlobal(pBuf); } } } // helper function IPToString static string IPToString(int ipaddr) { return String.Format("{0}.{1}.{2}.{3}", (ipaddr >> 24) & 0xFF, (ipaddr >> 16) & 0xFF, (ipaddr >> 8) & 0xFF, ipaddr & 0xFF); } } } Produces output like this on my machine: IP:127.0.0.1 Mask:255.0.0.0 IP:192.168.1.3 Mask:255.255.255.0 A: Have you tried the functions provided by .NET for this: * *NetworkInterface.GetAllNetworkInterfaces static function *NetworkInterface.GetIPProperties method *IPInterfaceProperties.UnicastAddresses property *IPInterfaceProperties.GetIPv4Properties method
{ "language": "en", "url": "https://stackoverflow.com/questions/7570331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use a custom type from RIA services with lightswitch? I have a service class that is passed to lightswitch using RIA services. The service class uses a custom type instead of native lightswitch or SQL types. public class MyService : DomainService { [Query(IsDefault = true)] public IQueryable<MyRecord> GetMyRecordData() { return ... } } public class MyRecord { [Key] public int Id {get; set;} public string Text {get;set;} public MyCustomType Custom {get;set;} } public struct MyCustomType { public MyCustomType (int val1, int val2) : this () { Val1 = val1; Val2 = val2; } public int Val1 {get; private set;} public int Val2 {get; private set;} } How to have lightswitch use this custom type for its display ? A: Custom types are not supported as entity members unless they implement the IList interface. Even in the case of an IList implementation, you would not be allowed to provide a list of complex types, just simple .NET types. So there's no way to pass an instance of MyCustomType as a supported entity member. Unfortunately Microsoft has taken the RIA spec offline, but you can still find a copy here. See section 4.11 for an explanation of this limitation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Difficulty posting Actions to Timeline I've tried building the basis of our next app following Facebook's Open Graph Tutorial but for some reason I'm getting errors thrown at me regardless of how I try POSTing an action. I'll go as in-depth as I can here as I hope it'll be very useful for all developers getting to grips with the new Timeline. I've defined a battle action and a hero object using the default settings when setting up each. transcendgame is my namespace. $id is the userid of the Facebook user (I've tried using /me/, the direct id has always been less problematic in the past for me). $herourl is an urlencoded string pointing to a separate webpage with the following content: <head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# transcendgame: http://ogp.me/ns/fb/transcendgame#"> <meta property="fb:app_id" content="[my id]"> <meta property="og:type" content="transcendgame:hero"> <meta property="og:url" content="http://apps.facebook.com/transcendgame/"> <meta property="og:title" content="Hercules"> <meta property="og:description" content="As this game is still in development, you can ignore this feed post!"> <meta property="og:image" content="[an image url]"> The application canvas page contains the following code. It should POST a new action event to the user's timeline, but is consistently giving me "Error occured". I have also tried it with the sample hero object (samples.ogp.me...) with the same problem. <script> function doTest() { FB.api('/<?=$id?>/transcendgame:battle' + '?hero=<?=$herourl?>','post', function(response) { if (!response || response.error) { alert('Error occured'); } else { alert('Post was successful! Action ID: ' + response.id); } }); } </script> <a href="#" onclick="doTest(); return false">Test fb post</a> I'm calling the JS SDK and running fb.init correctly. I honestly don't know where the problem even lies, let alone how to fix it. EDIT: I've correctly added the user's access token to the API call: FB.api('/me/transcendgame:battle' + '?hero=<?=$herourl?>&access=<?=$token?>','post', However, I'm getting the following error: Type: OAuthException Message: (#3502) Object at URL [url] has og:type of 'game'. The property 'hero' requires an object of og:type 'transcendgame:hero'. This is odd, as the webpage definitely does have og:type set correctly, as listed earlier in this question. Is this some Facebook hiccup I need to work around? SECOND EDIT: Fixed the final problem. The og:url I had assumed to point back to the URL of the app's canvas, but it needs to reference itself instead. For instance, if your object is on mydomain.com/object1.php then the code must be: <meta property="og:url" content="http://www.mydomain.com/object1.php"> Hope this helps others. A: I have the same problem and I changed the callback to be more helpful: var fb_url = '/me/YOUR_NAMESPACE?key=value'; FB.api(fb_url,'post', function(response) { console.log(response); if (!response || response.error) { var msg = 'Error occured'; if (response.error) { msg += "\n\nType: "+response.error.type+"\n\nMessage: "+response.error.message; } alert(msg); } else { alert('Post was successful! Action ID: ' + response.id); } } ); UPDATE I finally got a post to the timeline, and the change I had to make was to use the BETA version of JavaScript SDK. ( https://developers.facebook.com/support/beta-tier/ ) Use this: <script src="//connect.beta.facebook.net/en_US/all.js#appId=xxx&amp;xfbml=1"></script> Instead of this: <script src="//connect.facebook.net/en_US/all.js#appId=xxx&amp;xfbml=1"></script> A: i had some difficultly posting initially as well. My problem lied the configuration settings of the action. Make sure that your actions are set to be for the exact object. Here are some screens of what I have set up and working: If these settings are correct, check the error code that comes back from facebook, post it here and i can help you further. A: Regarding the final point on og:url -- that's correct. You can generally consider the OG URL to be the "primary key" of an Object in the Graph. A: To clear up some possible confusion, the og:url doesn't "HAVE" to be the same URL as the url of your object1.php page. The important thing to note is that regardless of the URL that you reference there, it has to have the META tags in the html &lt;head&gt; of the page. I, for example, put the URL of a canvas page in there so that when someone clicks the hyperlink in the action on the timeline it opens that page. As long as the META information from the 'Get Code' link for the Object is in the head, you won't get the error.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Testing WinForms MVP and Event mechanism with moq I've been using MVP pattern in my application. But I have problems with testing my method which are called after button is clicked. Here is the code: public interface IControl { bool Enabled { get; set; } string Text { get; set; } } public interface IButton : IControl { event EventHandler Click; } public class Button : System.Windows.Forms.Button, IButton { } public interface IForm : IControl { void Show(); void Close(); } public interface IView : IForm { IButton Button1 { get; } } public partial class View : Form, IView { public View() { InitializeComponent(); } #region IView Members public IButton Button1 { get { return button1; } } #endregion } public class Presenter { IView view; public Presenter(IView view) { this.view = view; this.view.Button1.Click += ButtonClick; this.view.Show(); } private void ButtonClick(object sender, EventArgs e) { view.Button1.Text= "some text"; } } The problem is that I don't know how to write test so that my ButtonClick method get called. I tried like this: var view = new Mock<IView>(); view.Setup(x => x.Button1).Returns(new Mock<IButton>().SetupAllProperties().Object); Presenter presenter = new Presenter(view.Object); view.Raise(x => x.Button1.Click+= null, EventArgs.Empty); Assert.AreEqual("some text", view.Object.Button1.Text); I think that problem is in this line: this.view.Button1.Click += ButtonClick; It seems that Click event doesn't remember ButtonClick method. How to make Click to be stub to work just normal. Any suggestion is welcome. Thanks in advance. Regards, Vajda EDIT: I was able to do that when I created SubscribeOnClick(EventHandler click); method in my IButton interface instead of event EventHandler Click. And I made some ButtonMock where I remembered method. But still, if someone knows for better solution, please share with me. A: Maybe it's not a bad idea to use the command pattern here. Your IView is very implementation specific because it has a prescribed number of controls that should have a Click event (I know it is an example, but still...). A simple implementation of the command pattern would be to let IView have a List<Action> that is supplied by the presenter, and let a specific implementation of a view decide how to fire these actions, e.g. by doing this.button1.Click += (sender, e) => this.Actions[0](); A mock object would not need to have a Click event (which may not even be supported by Moq, I'm not sure). You could just have it fire one of its actions. A: I Changed my IButton interface to this one: public interface IButton : IControl { voie SUbscribeOnClick(EventHandler click); } public class ButtonStub : IButton { EventHandler click; public bool Enabled { get; set; } public void SubscribeOnClick(EventHandler click) { this.click = click; } public string Text { get; set; } public void RaiseClickEvent() { click(this, EventArgs.Empty); } } This way I was able to make stub class which have private event where I can subscribe and after that call method which fires event when needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why do I get "Too many open files" errors? I find myself having to explicitly call System.gc() in my Groovy scripts to prevent errors like the one below. Why doesn't the garbage collector do this for me? Is there something I can do to cause it to garbage collect to prevent these errors (maybe JAVA_OPTS)? Caught: java.util.concurrent.ExecutionException: org.codehaus.groovy.runtime.InvokerInvocationException: java.io.IOException: Cannot run program "ls": java.io.IOException: error=24, Too many open files at groovyx.gpars.GParsPool.runForkJoin(GParsPool.groovy:305) at UsageAnalyzer$_run_closure2_closure6.doCall(UsageAnalyzer.groovy:36) at groovyx.gpars.GParsPool$_withExistingPool_closure1.doCall(GParsPool.groovy:170) at groovyx.gpars.GParsPool$_withExistingPool_closure1.doCall(GParsPool.groovy) at groovyx.gpars.GParsPool.withExistingPool(GParsPool.groovy:169) at groovyx.gpars.GParsPool.withPool(GParsPool.groovy:141) at groovyx.gpars.GParsPool.withPool(GParsPool.groovy:117) at groovyx.gpars.GParsPool.withPool(GParsPool.groovy:96) at UsageAnalyzer$_run_closure2.doCall(<removed>) at UsageAnalyzer.run(<removed>) This stack trace is from a parallel program but it happens in sequential programs as well. A: As you're using groovy, you can use the convenient methods such as File.withReader(), File.withWriter(), File.withInputStream(), InputStream.withStream() to ensure resources get closed cleanly. This is less cumbersome than using Java's try .. finally idiom, as there's not need to explicitly call close(), or declare a variable outside the try block. e.g. to read from a file. File f = new File('/mumble/mumble/') f.withReader{ r -> // do stuff with reader here } A: Definitely look for any place you open files or streams and make sure you close them. It's often beneficial to wrap them like this: final InputStream in = ...; try { // Do whatever. } finally { // Will always close the stream, regardless of exceptions, return statements, etc. in.close(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7570353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to open PDF file in android emulator I would like to know how to open a PDF file? What all changes do we need to make in the manifest file. Can I open it in a browser? What all permissions would be required for it? A: If there is an application installed that handles the application/pdf mime type then you can open it. You cannot specify that it only be opened in browser unless browser is the only application that handles it. Following is the code snippet for opening a pdf file Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(path, "application/pdf"); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); try { startActivity(intent); } catch (ActivityNotFoundException e) { Toast.makeText(OpenPdf.this, "No Application Available to View PDF", Toast.LENGTH_SHORT).show(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7570355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using multipe update statements from CSV vs using intermediate table I want to update about 10,000 records. The update information is in multiple CSV files. One way to update my table is * *Create intermediate table and update my primary table from this table (more work) *Use CSV to SQL utility which creates multiple UPDATE statements (this is tempting) My question is, is it safe to create thousand of Update Statements like this? Can it be problematic and possibly corrupt my data? It does take a lot of time to complete the action. One such online tool is this UPDATE MyTable SET change_field = 'ABC' WHERE other_field = '1'; UPDATE MyTable SET change_field = 'ABC' WHERE other_field = '2'; UPDATE MyTable SET change_field = 'DEF' WHERE other_field = '3'; A: There shouldn't be any problem running a large number of statements like that unless the database you are using has some kind of limitation specifically documented. In general, though, running 10,000 update statements would not be considered much of a load for most databases. You might want to consider running the statements in a transaction so that if there are problems you can roll back the changes. It would be good to make sure that other_field has an index on it. Otherwise, the update statements could be slow if the table is very large (each update would likely require a full table scan if there is no index on that field).
{ "language": "en", "url": "https://stackoverflow.com/questions/7570357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why doesn't my knockoutjs observableArray data update trigger anything? The idea of this page is, I have a text field which, when you enter three or more characters, fires an ajax query to search the list of users. That part works fine, and the console.log() call demonstrates I'm getting good data back and assigning it to the .users field of my view model. The problem is, that doesn't trigger any of the observable behavior. Up in the HTML I have a template that is bound with foreach: users, and I have a span bound on userCount, neither of which update. However, if I type viewModel.users().length on the console, I get the right value. But I've somehow broken observability. var viewModel = { users: ko.observableArray([]), term: ko.observable('') }; ko.dependentObservable( function() { if (this.term().length > 2) { $.get('http://mydatasource.com/path/?term=' + this.term(), function(data) { viewModel.users(data); console.log(viewModel.users()); }) } }, viewModel); viewModel.userCount = ko.dependentObservable( function() { return this.users().length; }, viewModel ); ko.applyBindings(viewModel); EDIT: Just modified my ajax getting dependentobservable function to: ko.dependentObservable( function() { if (this.term().length > 2) { $.get('http://mydatasource.com/path/?term=' + this.term(), function(data) { viewModel.users([]); $.each(data, function(i, item) { console.log(item.label); viewModel.users.push({value: ko.observable(item.value), label: ko.observable(item.label)}); } ); }) } }, viewModel); No difference at all. But I can see the properly-returned label values in the console, and again, viewModel.users().length gives me answers I'm happy with. EDIT: I replaced my view with the one @RP Niemeyer provided in a fiddle, and it worked... SO it's something about my view. Here's what I had: <input data-bind="value: term, valueUpdate: 'afterkeydown'"><br/> <h2><span data-bind="value: userCount"></span> Users Listed</h2> <table data-bind="foreach: users"> <tr><td data-bind="text: label"></td><td data-bind="text:value"></td></tr> </table> <div data-bind="text: ko.toJSON(viewModel)"></div> A: Looks fine from the code you posted. Maybe post some of your view or try to repro based on this fiddle: http://jsfiddle.net/rniemeyer/FDZJx Update: used your view: http://jsfiddle.net/rniemeyer/FDZJx/2/. Still looks fine. Your first input element was not closed, but it didn't cause me a problem. Possibly causes a problem in the browser that you are using.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get android:versionName with shell command I want to get the versionName from the AndroidManist.xml file with a shell command. I've been trying to use grep and with: grep versionName ./AndroidManifest.xml I'm getting this line: android:versionName="1.0"> Is it possible to narrow it down to 1.0 somehow? Thanks in advance A: Try this : perl -e 'while($line=<>) { if ($line=~ /versionName\s*=\s*"([^"]+)"/) { print "$1\n";}}' <AndroidManifest.xml You may want to put this into a file : Ex: VersionNum.pl #!/usr/bin/perl #get the filename from command line $file = shift or die; #open the file and read it into $lines var open(IN,$file) or die; $lines=join("",<IN>); close(IN); #search the $line var for match and print it if ($lines =~ m/android:versionName\s*=\s*"([^"]+)"/mgs) { print "$1\n"; } Then simply chmod 755 VersionNumber.pl and use it with VersionNumber.pl AndroidManifest.xml A: A shorter version could be derived from your original suggestion: grep versionCode AndroidManifest.xml | sed -e 's/.*versionName\s*=\s*\"\([0-9.]*\)\".*/\1/g'
{ "language": "en", "url": "https://stackoverflow.com/questions/7570363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: when exactly does the wcf autocomplete execute? I would like to know if I have a WCF service that has a TransactionScopeRequired but I don't use a transactional binding... Is possible to return a message first and later the transaction could make a rollback? In other workds... which executes first? the returning of the message or the commit? Thanks in advance. A: the transaction is committed when the service operation finishes executing, and before the response is returned.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Removing/undefining a class method that's included by another module I'd like to remove a class method that gets added to my class via the include function. For example: class Foo include HTTParty class << self remove_method :get end end This doesn't work, it says "get" isn't a method on Foo. Basically, the "get" method is provided the HTTParty module and I'd like to remove it. I've tried several attempts with no luck. Things I've read/tried: * *Removing/undefining a class method *http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/15408 *http://split-s.blogspot.com/2006/01/removing-methods-from-module.html A: Use undef instead of remove_method: require 'httparty' class Foo include HTTParty class << self undef :get end end Foo.get #=> NoMethodError: undefined method `get' for Foo:Class Cancels the method definition. Undef can not appear in the method body. By using undef and alias, the interface of the class can be modified independently from the superclass, but notice it may be broke programs by the internal method call to self. http://web.njit.edu/all_topics/Prog_Lang_Docs/html/ruby/syntax.html#undef
{ "language": "en", "url": "https://stackoverflow.com/questions/7570366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Define an xsd enumeration once to be used in multiple places? I want to use the following enumaration in multiple places, but as you can see now, it is tied to one complex type, how do I extract it out so I can define it once and use it in multiple places. <xs:complexType name="MessageType"> <xs:sequence> <xs:element name="Control" type="ControlType" minOccurs="1" maxOccurs="1" /> <xs:element name="LOS" type="LOSTYPE" minOccurs="0" maxOccurs="1" /> <xs:element name="UID" type="UIDTYPE" minOccurs="1" maxOccurs="1" /> <xs:element name="RS" type="RSTYPE" minOccurs="0" maxOccurs="1" /> </xs:sequence> <xs:attribute name="BL" type="xs:string" use="optional"></xs:attribute> <xs:attribute name="BLM" use="optional"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value="One" /> <xs:enumeration value="Two"/> <xs:enumeration value="Three"/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:complexType> Basically, I want to extract the BLM enumeration attribute out so I can define it once and use it multiple places if need so I don't have to repeat it. DRY in a nutshell :) A: You can create a named xs:simpleType out of it. <xs:simpleType name="myEnum"> <xs:restriction base="xs:string"> <xs:enumeration value="One" /> <xs:enumeration value="Two"/> <xs:enumeration value="Three"/> </xs:restriction> </xs:simpleType> And then use it with <xs:attribute name="BLM" use="optional" type="myEnum"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/7570369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Java hibernate Detached criteria, count / having, query can someone help me out with a query ? Here´s the deal: I have two tables 1- Group of users 2- Users One group has a lot of users, but the thing is, the table groups holds the number of users it has on table users. But it happens that sometimes this number is invalid, I want to find the casees where the number in the table group is less then the users in the table users. The SQL query would be like that: select id_group, count(user) from user inner join user having count(user) < group.number_of_users In hibernate I cant do that, so far I got into this DetachedCriteria dc = DetachedCriteria.forClass(Group.class); dc.createAlias("userCollection", "uc"); dc.setProjection(Projections.count("uc.idUser")); dc.add(Restrictions.lt("????????", "??????????"); Thanks in advance A: Why don't you do a DetachedCriteria that is the count? Then you dc.add(Restrictions.lt(detachedCriteria, "??????????");
{ "language": "en", "url": "https://stackoverflow.com/questions/7570370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Keyword local completion doesn't work with loaded buffers in Vim When I want to autocomplete with CTRL-N from other buffers, vim doesnt find any matches. I have no idea how to find out what's the problem. My complete settings are the default: complete=.,w,b,u,t,i. It only works for the active buffer. I even tried to :set complete+=U but no success... How could I track this down ? My vim version is MacVim (7.3, snapshot 61). A: Seems like Supertab plugin was responsible for the annoyance. (See the comments above) A: In my case it was sparkup ftplugin. Had to add let g:sparkupNextMapping = '<c-g>n' (or whatever key you like) to my .vimrc before I load the bundle.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating SHA1 Hash from NSString How can I create a SHA1 from a NSString. Let's say the NSString is set up as: NSString *message = @"Message"; I can use PHP to create a SHA1 hash with sha($message). But unfortunately it doesn't work like that within Objective-C. A: I have this in a category on NSString (available at https://github.com/hypercrypt/NSString-Hashes): #import <CommonCrypto/CommonDigest.h> ... - (NSString *)sha1 { NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding]; uint8_t digest[CC_SHA1_DIGEST_LENGTH]; CC_SHA1(data.bytes, (CC_LONG)data.length, digest); NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2]; for (int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) { [output appendFormat:@"%02x", digest[i]]; } return output; } Starting with Xcode 10.0, you should use import CommonCrypto instead since it is now natively available in Swift! If you have recently migrated to Xcode 10.0 and use the old approach, this can be your cue to make the change: Command CompileSwift failed with a nonzero exit code A: It took me a while to port @hypercrypt solution to Swift so I decided to share it with others that might have the same problem. One important thing to note is that you need CommonCrypto library, but that library does not have Swift module. The easiest workaround is to import it in your bridging header: #import <CommonCrypto/CommonCrypto.h> Once imported there, you do not need anything else. Just use String extension provided: extension String { func sha1() -> String { var selfAsSha1 = "" if let data = self.dataUsingEncoding(NSUTF8StringEncoding) { var digest = [UInt8](count: Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0) CC_SHA1(data.bytes, CC_LONG(data.length), &digest) for index in 0..<CC_SHA1_DIGEST_LENGTH { selfAsSha1 += String(format: "%02x", digest[Int(index)]) } } return selfAsSha1 } } Notice that my solution does not take effect of reserving capacity what NSMutableString has in original post. However I doubt anyone will see the difference :) A: try this: #import <CommonCrypto/CommonDigest.h> -(NSData *) selector { unsigned char hashBytes[CC_SHA1_DIGEST_LENGTH]; CC_SHA1([dataToHash bytes], [dataToHash length], hashBytes); NSData *data = [[NSData alloc] initWithBytes:hashBytes length:CC_SHA1_DIGEST_LENGTH]; } A: I quite like hypercrypt's answer, but I've been encouraged to post my comment. You could look at CC_SHA1, or this related SO question. A: - (NSString *)sha1:(NSString *)str { const char *cStr = [str UTF8String]; unsigned char result[CC_SHA1_DIGEST_LENGTH]; CC_SHA1(cStr, strlen(cStr), result); NSString *s = [NSString stringWithFormat: @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7], result[8], result[9], result[10], result[11], result[12], result[13], result[14], result[15], result[16], result[17], result[18], result[19] ]; return s; } A: Here's a concise and highly optimized NSString category: @implementation NSString (PMUtils) - (NSString *)sha1Hash { NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding]; NSData *hash = [data sha1Hash]; return [hash hexString]; } @end @implementation NSData (PMUtils) - (NSString *) hexString { NSUInteger bytesCount = self.length; if (bytesCount) { static char const *kHexChars = "0123456789ABCDEF"; const unsigned char *dataBuffer = self.bytes; char *chars = malloc(sizeof(char) * (bytesCount * 2 + 1)); char *s = chars; for (unsigned i = 0; i < bytesCount; ++i) { *s++ = kHexChars[((*dataBuffer & 0xF0) >> 4)]; *s++ = kHexChars[(*dataBuffer & 0x0F)]; dataBuffer++; } *s = '\0'; NSString *hexString = [NSString stringWithUTF8String:chars]; free(chars); return hexString; } return @""; } - (NSData *)sha1Hash { unsigned char digest[CC_SHA1_DIGEST_LENGTH]; if (CC_SHA1(self.bytes, (CC_LONG)self.length, digest)) { return [NSData dataWithBytes:digest length:CC_SHA1_DIGEST_LENGTH]; } return nil; } @end A: I'm seeing a few different possible improvements to the answers in this post. * *Never make an unprefixed category. What if you implement -[NSString sha1Hash] in your library, and another library in the same app implements the same method with slightly different semantics? Which one is used will be random, and lead to hard-to-diagnose errors. *If you want a string, there is base64-encoding in the standard library nowadays. Less work than manually building hex stringification. Here's my solution, adapted from the excellent SocketRocket library's SRHash.m: // NSString+Sha1Digest.h #import <Foundation/Foundation.h> @interface NSString (LBDigest) - (NSString *)lb_digestString; @end @interface NSData (LBDigest) - (NSString *)lb_digestString; @end // NSString+SHA1Digest.m #import "NSString+Sha1Digest.h" #import <CommonCrypto/CommonDigest.h> static NSData *LBSHA1HashFromBytes(const char *bytes, size_t length) { uint8_t outputLength = CC_SHA1_DIGEST_LENGTH; unsigned char output[outputLength]; CC_SHA1(bytes, (CC_LONG)length, output); return [NSData dataWithBytes:output length:outputLength]; } static NSData *LBSHA1HashFromString(NSString *string) { size_t length = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; return LBSHA1HashFromBytes(string.UTF8String, length); } @implementation NSData (LBDigest) - (NSString *)lb_digestString; { return [LBSHA1HashFromBytes(self.bytes, self.length) base64EncodedStringWithOptions:0]; } @end @implementation NSString (LBDigest) - (NSString *)lb_digestString; { return [LBSHA1HashFromString(self) base64EncodedStringWithOptions:0]; } @end
{ "language": "en", "url": "https://stackoverflow.com/questions/7570377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "43" }
Q: Help getting my route working for jQuery UI Tabs with AJAX I have my jQuery UI Tabs working right now but need help implementing the Ajax side. What I need help with is getting #tab-2 to show information (@user.messages) from the MessagesController in a layout that's in profile_messages.erb in the messages view. My application.js: $(function() { $( "#tabs" ).tabs({ ajaxOptions: { error: function( xhr, status, index, anchor ) { $( anchor.hash ).html( "Couldn't load this tab. We'll try to fix this as soon as possible. " + "If this wouldn't be a demo." ); } } }); }); MessagesController: def profile_messages @question = Question.all(params[:user_id]) respond_to do |format| format.html format.xml {render :xml => @question} end end My profile show.html.erb: <div id="tabs"> <ul id="infoContainer"> <li><a href="#tabs-1"></a></li> <li><%= link_to "Messages", message_path(@message, :render => "false") %></a></li> <ul> <div id="tabs-1"> </div> </div> My profile_messages.erb: <div id="tabs-2"> <% for 'message' in @user.messages %> <div class="message"> </div> <% end %> </div> So how can I get profile_messages to load as a tab? A: I was able to get things working (almost!) due to loads of help here on SO. For some more code, check out this other question: Exclude application layout in Rails 3 div
{ "language": "en", "url": "https://stackoverflow.com/questions/7570378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Avoiding map.get(key) method I have the following code but i saw that retrieving values from a Map while iterating over the Map keys with keySet() is a mistake even with findBugs i get the warning WMI_WRONG_MAP_ITERATOR for(String elementId : mapElements.keySet()){ element = mapElements.get(elementId); doSomething(element); } so why exactly is this not good and how can i fix it ? Thanks. A: If you're iterating over everything in a map, you might as well do: for (Map.Entry<String, String> entry : mapElements.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); // Use the key and the value } Or if you don't really need the key, just iterate over the values: for (String value : mapElements.values()) { doSomething(value); } EDIT: syntax A: Retrieving values from a map while iterating over the map itself is not an issue - what becomes an issue is when you are modiying the map while simultaneously iterating over it. In your case , this doesnt seem to be the case , so this is itself not dangerous. When you iterate over a map , the iterator you get is based on a snapshot of all map entries at the time you obtain the iterator. Upon subsequent midification , this iterator's behaviour becomes undefined. This is what is not good. But again, in your case this does not apply because you are not updating the map. A: Another point is that looking up the value of each key may be expensive if the map is large. So Jon Skeet's suggestion is more efficient. However, I admit the code for iterating over a map's entry set is a bit clumsy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Getting Mockito and Powermock to throw error correctly I have the following code @PrepareForTest({Mongo.class, XYMongo.class, DB.class}) public class XYMongoTest extends UnitTest{ String host = Play.configuration.getProperty("mongo.host"); int port = Integer.parseInt(Play.configuration.getProperty("mongo.port")); String name = Play.configuration.getProperty("mongo.name"); @Test public void testRetrieveMongoDBSuccessful() throws UnknownHostException, MongoException, Exception { Mongo mongoMock = mock(Mongo.class); DB mockDB = mock(DB.class); PowerMockito.whenNew(Mongo.class).withArguments(host, port).thenReturn(mongoMock); when(mongoMock.getDB(name)).thenReturn(mockDB); XYMongo.getMongoDB(); verify(mongoMock.getDB(name)); } @Test public void testRetrieveMongoDBFailUnkownHost() throws Exception { try { PowerMockito.mockStatic(Mongo.class); PowerMockito.whenNew(Mongo.class).withArguments(host, port).thenThrow(new UnknownHostException("Test Exception")); XYMongo.getMongoDB(); PowerMockito.verifyNew(Mongo.class).withArguments(host, port); } catch (Exception e) { assertEquals("Test Exception", e.getMessage()); } }} The first test passes fine and the second fails with the test error being Failure, expected:<[Test Exception]> but was:<[ Missing method call for verify(mock) here: -> at org.powermock.api.mockito.internal.invocationcontrol.MockitoNewInvocationControl.expectSubstitutionLogic(MockitoNewInvocationControl.java:65) Example of correct verification: verify(mock).doSomething() Also, this error might show up because you verify either of: final/private/equals()/hashCode() methods. Those methods cannot be stubbed/verified. ]> Any ideas on how to fix this? Tried everything I can think of. Thanks Paul A: The error is actually coming from testRetrieveMongoDBSuccessful(); it looks like you've got the verify() not-quite-right, but Mockito can't tell you that until the next time you interact with it. Try replacing the last line of testRetrieveMongoDBSuccessful() with: verify(mongoMock).getDB("name");
{ "language": "en", "url": "https://stackoverflow.com/questions/7570386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What could cause Java to keep running after return I have this problem when I do some special GUI interaction. Here is my situation: I use one dialog. I don't call System.exit() but leave the application later with a return. Normally the JVM then exists when it sees that no more non-deaemon threads are running. But after using this dialog, it does not work. I am 100% shure that a dispose() is called on the dialog in question and also on the main frame of the application. I get this both in an IDE and when running from the command line. I can kill it with a button press in the IDE, or with Ctrl-C from the command line. But it would of course be better if the JVM correctly terminates itself before delivering the application. Any clues, is this a known problem? I am using JDK 1.7, but the problem show already up in JDK 1.6. Best Regards P.S.: Just reading: http://download.oracle.com/javase/1.4.2/docs/api/java/awt/doc-files/AWTThreadIssues.html There have been similar issues in the past. Maybe this is a new issue. The issues in the past were: Other packages can create displayable components for internal needs and never make them undisplayable. See 4515058, 4671025, and 4465537. I will try some along an explicit setVisible(false) of the pop up menu. A: Are you sure the pop up is destroyed and not just hidden? I believe the default action is to hide, and setting the default close operation to JFRAME.EXIT_ON_CLOSE might solve it. Another way of diagnosing the problem could be to use a profiler, such as the one shipped with Netbeans. Use live view and a debug point just before application should terminate, and you can inspect the live objects. A: The default action when you close a frame is to just hide it. The UI thread is still alive. If you want the JVM to exit when you close the frame you make (possibly your "popup"?), you have to explicitly say so, e.g. by doing frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); , more docs here. Possibly you only need the DISPOSE_ON_CLOSE as the defaultCloseOperation. An other alternative is to add a windowListener to the frame, and decide the proper action yourself when the frame is closed. A: Sounds like at least one thread is blocking and can't respond to an interrupt. Perhaps using .getState() on the thread in question may shed some light on the problem. http://download.oracle.com/javase/6/docs/api/java/lang/Thread.html#getState%28%29 A: I had the same problem, calling dispose() in a EventQueue.invokeLater(new Runnable() {...} resolved it for me
{ "language": "en", "url": "https://stackoverflow.com/questions/7570391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JQuery UI Tabs - Clicking a tab will enable/disable buttons - looking to temporarily disable tab click I have five tabs right now: New Reports, Old Reports, Judges, Users, and Other Settings. When Judges or Users is clicked, there's a list of users or judges as well as a button that allows you to "Add New User" or "Add New Judge". When one is clicked, that button becomes invisible and some text boxes appear. After you save (or decide to cancel) your new judge or user, the "Add New" button reappears. This all works quite well aside from the fact that if you click the "Judges" or "Users" tab again, the "Add New Button" will appear again even if you're in the process of adding a new one. I'm trying to figure out the best way to prevent this from happening. So far I've tried adding $(this).attr('disabled', 'disabled'); to the click event for Judges and Users, but I don't think that's exactly the right approach. Any ideas? Code: <div id="tabs" style="width:800px;margin: 0 auto;"> <ul> <li><a href="#tabs-1" onClick="$('#newJudgeLink').hide(); $('#newUserLink').hide();">New Reports</a></li> <li><a href="#tabs-2" onClick="$('#newJudgeLink').hide(); $('#newUserLink').hide();">Old Reports</a></li> <li><a href="#tabs-3" onClick="$('#newJudgeLink').show(); $('#newUserLink').hide();">Judges</a></li> <li><a href="#tabs-4" onClick="$('#newJudgeLink').hide(); $('#newUserLink').show();">Users</a></li> <li><a href="#tabs-5" onClick="$('#newJudgeLink').hide(); $('#newUserLink').hide();">Other Settings</a></li> </ul> <div style="float:right;"><button id="newUserLink" style="display:none;" onClick="return false;">Add New User</button></div> <div style="float:right;"><button id="newJudgeLink" onClick="return false;" style="display:none;">Add New Judge</button></div> A: well first I would recommend binding click events in the traditional Jquery fashion instead of using onClicks embedded in your HTML. So what you could do is show() your save button when the tab is clicked, hide it if itself is clicked, and show it when the save/submit/cancel (i dont see them up there) button is clicked like so: $("a[href$=#tabs]").click(function(){ $("a[href$=#tabs]").removeClass("active"); $(this).addClass("active"); if ($(this).attr("href") == "#tabs-3" && !($(this).hasClass("active"))){ $('#newJudgeLink').show(); $('#newUserLink').hide(); } else if ($(this).attr("href") == "#tabs-4" && !($(this).hasClass("active"))){ $('#newUserLink').show(); $('#newJudgeLink').hide(); } else{ $('#newJudgeLink').hide(); $('#newUserLink').hide(); } }); $("#yourSaveButton,#yourCancelButton").click(function(){ if ($("a.active").attr("href") == "#tabs-3"){ $('#newJudgeLink').show(); $('#newUserLink').hide(); } else{ $('#newUserLink').show(); $('#newJudgeLink').hide(); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7570393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Nexys2 VGA pattern I am running Nexys2-1200 board (with a spartan3).It comes with a preloaded configuration that displays a VGA test pattern, that works fine. I'd be curious to have the complete VHDL code of this pattern. I can't find it on Digilent website... Anyone ? A: Looking really quick at the site for the nexys2 board: http://www.digilentinc.com/Products/Detail.cfm?Prod=NEXYS2 I see this "Nexys2 Board verification Project - (for 1200K boards)" entry in the support documents section. I would guess that this contains the source for the design that comes with the board. In fact when I look into that zip file I see source and documentation for a vga demo. The general advice would be to carefully look at all of the reference designs and projects that come with a board and make sure the feature you are looking for is not rolled in with another project.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: SQL Server query to consolidate dates I am trying to create a key based on an id plus a code plus a start date which spans a range of dates and consolidates id + code until another id + code comes along. Here is the data: ID CODE EFFECTIVE TERM 9950 H0504402 07/01/2007 08/31/2007 9950 H0504404 09/01/2007 01/31/2008 9950 H0504402 02/01/2008 01/21/2009 9950 H0504402 03/01/2009 01/21/2010 9950 H0504404 02/01/2010 02/11/2011 9950 H0504404 03/01/2011 NULL The result I am trying to get is: KEY EFFECTIVE TERM 9950_H0504402_20070701 07/01/2007 08/31/2007 9950_H0504404_20070901 09/01/2007 01/31/2008 9950_H0504402_20080201 02/01/2008 01/21/2010 9950_H0504404_20100201 02/01/2010 NULL SQL Server 2005. Any help is much appreciated, under the gun as usual and brain dead on this one. Thanks. A: declare @t table(id int, code char(8), effective datetime, term datetime) insert @t values (9950, 'H0504402', '07/01/2007', '08/31/2007'), (9950 ,'H0504404' ,'09/01/2007', '01/31/2008'), (9950 ,'H0504402' ,'02/01/2008', '01/21/2009'), (9950 ,'H0504402' ,'03/01/2009', '01/21/2010'), (9950 ,'H0504404' ,'02/01/2010', '02/11/2011'), (9950 ,'H0504404' ,'03/01/2011', NULL) ;with cte as ( -- add rownumber (rn) select id, code, effective, term, row_number() over (order by effective) rn from @t ), b as ( -- add group (r) select *, 1 r from cte where rn = 1 union all select cte.* , case when b.id <> cte.id or b.code <> cte.code then r + 1 else r end from cte join b on b.rn + 1 = cte.rn ), c as ( -- find last and first row select id, code, min(effective) over (partition by r) effective, term, row_number() over (partition by r order by rn desc) nrn ,rn, r from b ) -- convert columns to look like description select cast(id as varchar(9))+ code + '_' + convert(char(8), effective,112) [KEY], effective, term from c where nrn = 1 order by rn option (maxrecursion 0)-- added to prevent problems in a production environment Test here: https://data.stackexchange.com/stackoverflow/q/113660/
{ "language": "en", "url": "https://stackoverflow.com/questions/7570397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to check if the page is loading inside facebook canvas and change the layout accordingly I'm working on creating flash games site and want to make the facebook application version of it. As the site width is bigger than canvas default width I'm trying to find the way to check if the site is loading inside facebook canvas and change the width accordingly. Please, help me to find the solution. A: If a user accesses your site via your Facebook canvas iframe app, the request to your server will include a "signed_request" param. You can check for this param to determine if the user's inside the Facebook canvas or not. Also note that you don't really need to do this anymore if you set the Canvas Width to Fluid: You can set your Canvas Width to "Fixed (760px)", the default setting, which makes your app have a fixed width of 760 pixels. You can also set your width to "Fluid" which means that we set the iframe width to 100%. Your content will then be left-aligned and resize to fill the page as the user changes the width of their browser.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Extract current date, parse it and add 7 days I'd like to do this : * *Extract the current date; *Parse it as DD/MM/YYYY; *Add to it 7 days; How can I do it on C#? I hope there are specific methods for do it (without extraxt, split, arrange arrays, join, ecc...). SOLUTION TAKEN DateTime dt = DateTime.Parse(System.DateTime.Now.ToString()); txtArrivo.Text = dt.ToString("dd/MM/yyyy"); txtPartenza.Text = dt.AddDays(7).ToString("dd/MM/yyyy"); A: It is as simple as that: DateTime inSevenDays = DateTime.Today.AddDays(7); No need to parse anything. A: I'm not quite sure what you mean by "Extract the actual data". But I'm assuming your getting the value back in a string form. If so then you can do the following string data = ...; DateTime date = DateTime.Parse(data).AddDays(7); Or to be more precise you can do the following string data = ...; DateTime date = DateTime.ParseExact( data, "dd/MM/yyyy", CultureInfo.InvariantCulture).AddDays(7); A: Use DateTime to parse it and then use AddDays(7) to add 7 days to the DateTime object A: Here you go for Ex st is the string where you have the date: string st = "12/01/2011"; DateTime dt = DateTime.Parse(st).AddDays(7); Console.Write(dt.ToString("MM/dd/yyyy"); A: CultureInfo provider = CultureInfo.InvariantCulture; string dateString = "05/01/2009"; try { dateValue = DateTime.ParseExact(dateString, "dd/MM/yyyy", provider); dateValue = dateValue.AddDays(7); } catch { // something wrong } A: If you are sure that the dates are always in DD/MM/YYYY format, then use: DateTime date = DateTime.ParseExact(dateString, "dd/MM/yyyy", null).AddDays(7);
{ "language": "en", "url": "https://stackoverflow.com/questions/7570409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: SSIS 2008 - Getting the identity field I have to read in a text file that has a header row and some details with SSIS. I have two tables (one for the header and one for the details) that I need to get the data into. I need to insert the header and get the identity for that row, so I can insert that value into the detail rows. How can I accomplish this? Currently, I'm reading in the header row and putting it into the database with an OLE DB Destination task. A: You have three options. First, write all data to destination. Then read all data from file again, use Merge Join component to match rows with the ones you wrote in database, get identity column, insert into detail table. Drawback is that You have to read the same file two times. Second, read all data and write to both header and detail tables, but your destination header table should have one additional column (identity). Then issue one update statement to update FK from detail table to header table (identity). Third, in case You are fine with writing row by row into database, You can make a loop over source data and in that loop: write header data, do execute sql task to read last identity, derived column to update identity column in pipeline, write detail data. This solution is very slow. (this way, watch for getting identity columns correctly, or use sp to insert data so that sp ccan return identity for You to eliminate mentioned execute task)
{ "language": "en", "url": "https://stackoverflow.com/questions/7570424", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to show results while a php script is still running so I have tried Show results while script is still executing but for some reason it doesnt work, so here is what I have so far : ob_start(); include "../../common.php"; set_time_limit (0); $start = (string) $_GET['start']; $end = (string) $_GET['end']; for($i = $start; strcmp($i, $end); $i = bcadd($i, 1)){ echo $i; ob_flush(); } ob_end_flush(); UPDATED CODE *note that this code doesnt work yet! set_time_limit(0); $start = $_GET['start']; $end = $_GET['end']; for(;$start < $end;$start++){ $content = file_get_contents("[some internal page]"); echo $content; usleep(10); flush(); } A: Try adding a call to flush() after the call to ob_flush(). This will only work if your server is configured to be able to do it, and does not guarantee that the client will handle it sensibly, but it is your best bet. One sticking point I have come across here is that is you have zlib.output_compression configured you absolutely cannot do this, full stop. The zlib output compression process is started before any of your code is executed and cannot be controlled by your script at run time with ini_set() and the like. A: You typically need to call both flush() and ob_flush(). See: http://php.net/manual/en/function.flush.php Also, you cannot do anything about the browser's buffer on the client side. The browser will buffer data as long or as little as it wants. Some servers may also not support flushing their buffer. A: After ob_flush(); add flush(); That actually flushes the write buffer and output buffers. ob_flush flushes into the write buffer, flush() then pushes it out to the client. Usually at least.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Table Zebra, styling TR and COL in IE9 I wrote what I thought was very elegant css and table that does zebra formatting with very little bandwidth and no javascript, but it doesn't work in IE9. How it should look: How it looks in IE9: Source Code: <!DOCTYPE html> <html> <head> <title>SQLFlight HD Status</title> <style type="text/css"> table { border-collapse:collapse; border-spacing:0; } th { background:black; color:white; } tr:nth-child(odd), col:nth-child(odd) { background:rgba(200,200,200,0.5); } tr:nth-child(even) { background:rgba(255,255,255,0.5); } td,th { padding: 4px 10px; } </style> </head> <body> <table> <col/><col/><col/><col/><col/><col/> <thead> <tr> <th>Drive</th><th>Label</th><th>Size</th><th>Used</th><th colspan="2">Free</th> </tr> </thead> <tbody> <tr> <td>C:</td><td>OS</td><td>136 GB</td><td align="right">74 GB</td> <td align="right">62 GB</td><td align="right">46 %</td> </tr> <tr> <td>E:</td> <td>Data2</td> <td>394 GB</td> <td align="right">280 GB</td> <td align="right">114 GB</td> <td align="right">29 %</td> </tr> <tr> <td>F:</td><td>Data3</td><td>164 GB</td><td align="right">100 GB</td><td align="right">64 GB</td><td align="right">39 %</td> </tr> </tbody> </table> </body> </html> I like elegant, low bandwidth solutions without a ton of convoluted markup. I assume that the issue is this snippet: tr:nth-child(odd), col:nth-child(odd) { background:rgba(200,200,200,0.5); } I'm assuming that all the browsers I have tested, except IE9, combine the tr and col styling, but IE9 only allows tr styling or col styling, but not both at the same time. So is there a way to code my white, light gray, and lighter gray with just three lines of CSS like I have done here that also works in IE9? Keep in mind that I don't want to have to add a bunch of class tags or style tags to my HTML either. Am I right that it is just the combining of tr and col background styling that is failing in IE9? or is something else not working in IE9? Any feedback, explanation of what's happening plus any simple solutions will be greatly appreciated. Thanks. A: can't you just use something like this: tr:nth-child(odd) { background:rgba(200,200,200,0.5); } tr:nth-child(odd) td:nth-child(even) { background:rgba(200,200,200,0.8); } tr:nth-child(even) td:nth-child(even) { background:rgba(255,255,255,0.5); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7570435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: height of a div to match the height of the viewport I have a div like this. <div> ... </div> I want its height to be the height of the view port (not of the page) is it possible to do this via CSS or do I have to write some javascript ? A: Yes, it's possible. CSS percentage height will work as long as the parent element has a height defined. Assuming this is your markup: <html> <body> <div></div> </body> </html> This CSS will cause the <div> to have the full height of the viewport: html, body, div { height: 100%; } If you wanted the <div> to expand with its content, the CSS would change as follows: html, body { height: 100%; } div { min-height: 100%; } A: if your have set your viewPort to a certain height, you can just give your div height:100%;.. A: If the div is anywhere in the document, you would need to use javascript. With jQuery is quite simple: $("#my-div").height($(window).height());
{ "language": "en", "url": "https://stackoverflow.com/questions/7570438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: android dev: item in listview can not get focus correctly I face a listview focus problem. There is a button above the listview(not listview header). And I set listview.setItemsCanFocus to true. When I scroll using trackball, the items in listview can not get focused correctly. I post the layout file and code, hope this helps. package com.gaocx.trackballtest; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; public class MainActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ListView listView = (ListView) findViewById(R.id.listviewId); Button headerBtn = new Button(this); headerBtn.setWidth(LayoutParams.FILL_PARENT); headerBtn.setHeight(LayoutParams.WRAP_CONTENT); headerBtn.setText("ListView Header"); listView.addHeaderView(headerBtn); findViewById(R.id.layoutid1).setFocusable(true); Button button1 = (Button)findViewById(R.id.button1); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "Button1", 2000).show(); } }); Button button2 = (Button)findViewById(R.id.button2); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "Button2", 2000).show(); } }); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1); for (int i = 0; i < 20; ++i) { adapter.add("value" + i); } listView.setAdapter(adapter); listView.setItemsCanFocus(true); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Toast.makeText(MainActivity.this, "Value" + arg2, 2000).show(); } }); } } The layout file: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/layoutid1"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="left" android:text="@string/hello" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" android:text="@string/hello" android:id="@+id/button1" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" android:text="@string/hello" android:id="@+id/button2" /> </LinearLayout> <ListView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/listviewId"/> </LinearLayout> I think this is a listview bug and post it on android report bug page. But I am rejected, and the android team ask me to post here for help.. So any help would be appreciated. thanks a lot. A: make buttons and listView both clickable you need add for each Button next attribute: android:focusable="false" Thats all :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7570441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ms Excel VBA: Set a sorting combo box I am new to VBA although I have some experience in Visual Basic. I have a Microsoft Excel 2010 worksheet. Row 29 has the headers of a table and the data is from row 30 and so on. This table has like 20 columns. I'm trying to insert a combo in this Worksheet with three options, so when you choose the first, it will apply descending sorting to all the table according to column R and then column S. If you choose the second, it will apply descending sorting according to column S and then column R. If you choose the first it will apply descending sorting according to column A. Column S and Column R will be hidden. I hope you guys can help me out. Thank you and sorry for my English. A: Just to put a picture to words, I assume you have an excel sheet that looks similar like this: (Keeping columns S and R visible for this example) You want to add a combo box that will sort columns based on the value selected in the combo box that will be like so: * *Option 1: Sort descending on column R, then S *Option 2: Sort descending on column S, then R *Option 3: Sort descending on column A. First thing, if you haven't already done so, is add the Developer Tab to Excel. Next, put cells from the table in a Named Range. If the rows in this table will change, then make sure you create a dynamic named range. (Dynamic Named Ranges are a little tricky, but very useful for dynamic data) Add the combo box by clicking Insert from the Developer Tab and select combo box from Form Controls (NOTE: An ActiveX combobox is a completely different type of control. You could come to the same result using it, but the code would be different.) Drag the combobox somewhere on the worksheet: Now add the options values to the combo. You should go somewhere in your workbook and add the values for you combo box (e.g. Sheet2, Cells A1, A2 & A3). Return to your sheet where the table and combo box reside. Right-click on the combo box and select Format Control. The input range range should be the cells containing your sorting options. It look something like this: Sheet2!$A$1:$A$3 Right click on the combo box again and select Assign Macro. Give the Macro a name and put the Macro in This Workbook Click New. You will be taken to the Visual Basic Editor. Here you can apply your sorting code: Option Explicit Sub DropDown2_Change() Dim comboValue As String Dim Key1ColumnIndex As Integer Dim Key2ColumnIndex As Integer 'You can get the name by doing something like this in the immediate window: "? Sheet1.Shapes(1).OLEFormat.Object.Name" comboValue = Sheet1.Shapes("Drop Down 2").ControlFormat.List(Sheet1.Shapes("Drop Down 2").ControlFormat.ListIndex) Select Case comboValue Case "Option1" Key1ColumnIndex = 18 Key2ColumnIndex = 19 Case "Option2" Key1ColumnIndex = 19 Key2ColumnIndex = 18 Case "Option3" Key1ColumnIndex = 1 Key2ColumnIndex = 1 End Select Range("DataValues").Sort Key1:=Range("DataValues").Cells(1, Key1ColumnIndex), _ Order1:=xlDescending, Header:=xlNo, DataOption1:=xlSortNormal, _ Key2:=Range("DataValues").Cells(1, Key2ColumnIndex), order2:=xlDescending End Sub You should be now be good to go. If you need a working example, take a look at the sample sheet I created here; note that it does not have a dynamic name range for the table.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the best way to sort lines in jQuery? I have a TR's ( or divs with class - it doesnt matter ) like that I want to sort the lines by SCORE. Name | Age |Score ----------------------------------- John 26 90 paul 25 75 ringo 25 77 I know there is already a plugin for jquery that sorts tables but i want to build my own. I dont have a problem finding the values in the score column - thats easy. my question is how to sort and display the new results ? i have thought of something 1) take all the tr's elements to array of jQuery elements . 2) by .each sort the array 3) delete the old content 4)by .each loop - 'append' each TR by the order of the appearence in the array. Is there a better way ? A: I've previously written an efficient algorithm for sorting tables (answer). I've adjusted the function for this case: function sortTable(){ var tbl = document.getElementById("myTable").tBodies[0]; var store = []; for(var i=0, len=tbl.rows.length; i<len; i++){ var row = tbl.rows[i]; var sortnr = parseFloat(row.cells[2].textContent || row.cells[2].innerText); if(!isNaN(sortnr)) store.push([sortnr, row]); } store.sort(function(x,y){ return x[0] - y[0]; }); for(var i=0, len=store.length; i<len; i++){ tbl.appendChild(store[i][1]); } store = null; } To sort the table, use `sortTable(); Explanation of code: * *Two variables are created: HTMLTableSectionElement tbl and Array store. *A loop walks through all elements of the tBody (=rows), and pushes a new array in store, consisting of two elements: [sortnr, row]. sortnr holds the numeric value of the second cell of the row, which is used for the sort function (look ahead) row is a reference to HTMLTableRowElement, used later to move the rows. *store.sort(..) sorts the array store according to sortnr (as defined above, #2 of this explanation). *A loop walks through the sorted array, and appends the rows at the end of the table (tbl.appendChild moves the node from the previous location) Note that elements which don't have a valid number at the 3rd column (cell index 2) aren't moved at all. These stay at the top of the table. If you want to have the invalid rows located at the end, use: for(var i=store.length-1; i>=0; i--){ tbl.insertBefore(store[i][1], tbl.rows[0]); } Question by Royi Namir (at comments) youre the man. just one more question : you wrote 'tbl.appendChild moves the node from the previous location' , and i thoguth to my self that the action is appendChild - but behind the scenes it moves(!) the element. I read about it and they said that if its the same object then it moved. but how dows he knows that its the same object? he doesnt have any ID or something to recognize ... Answer: (Real life example:) Say, you see a apple laying on the table. If you want that same apple to be at the floor, what would you do? pick up the apple and put it at the floor. The same applies to appendChild: When you request the node to be appended, the script engine wants to place the node to be placed in the tree. Consequently, the previous node will be removed, because » appendChild does not copy nodes. « To copy nodes, the function element.cloneNode() exists. A: If for example you wanted to have your table ordered alphabetically by rows, and every second row was a non-useful partner of the previous (or didn't contain appropriate data) - you could do this (variation on Rob W's answer). function sortTable(){ var tbl = document.getElementsByTagName('table')[1].tBodies[1]; // magic numbers are bad var store = []; var len = tbl.rows.length / 2; // Assumes even rows. Loops become invalid otherwise. for(var i=0; i<len; i++){ var row = tbl.rows[2*i]; var sortnr = (row.cells[1].textContent || row.cells[1].innerText || row.cells[1].innerHTML); store.push([sortnr, row, tbl.rows[(2*i) + 1]]); } store.sort(function(a, b){ a = a[0].toLowerCase(); // make sort case insensitive (waste resources?) b = b[0].toLowerCase(); if (a < b) return -1 if (a > b) return 1 return 0 }); for(var i=0, len=store.length; i<len; i++){ tbl.appendChild(store[i][1]); // sorted line tbl.appendChild(store[i][2]); // its partner } store = null; } sortTable();
{ "language": "en", "url": "https://stackoverflow.com/questions/7570445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery mobile collapsible div not styling correctly Using this: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Page Title</title> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.css" /> <script src="http://code.jquery.com/jquery-1.6.3.min.js"></script> <script src="http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.js"> </script> </head> <body> <div data-role="collapsible" data-theme="a" data-content-theme="a"> <h3>Header swatch A</h3> <p>I'm the collapsible content with a themed content block set to "A".</p> </div> </body> </html> I find that the expanding collapsible does not have the theme styling expected - in fact it has none. On viewing the source of the page and comparing it will the example page on jQuery mobile (http://jquerymobile.com/test/docs/content/content-collapsible.html) it appears that the following classes are missing from dynamically created div that wraps around the expanding paragraph below the header within the collapsible: ui-btn-up-a ui-corner-bottom The code running the example page is their own internal code and not the same as is used for deployment so I'm guessing there is something in theirs that is not in the beta release that dynamically creates the classes. The question is whether anybody knows what the error is and how to solve this? A: The Google code CSS file has relative references to images. url(images/icons-18-white.png); That's rarely helpful. Try hosting the CSS file locally and changing the references to match your file structure. Also, unless you're using firebug to view source, you won't see the classes. Using a browser's "View Source" option shows you the code delivered by the server, not the code created by javascript. Update: Just did a copy / paste locally, and everything works fine. So it's not the code, gotta be something with your setup. Update 2: Looking at your question, I realized you want the -content- to be themed. If you need that, you have to assign a data-role="content" to the content. A: Okay the answer is: "Theming collapsible content requires jquery 1.6.4" The referenced version is in the log for the rc1 release which was posted two days after I posted the above problem. I was using an older version, viewing the source on the jquery example page this wasn't obvious as there is no version control reference immediately apparant just: <script src="../../js/jquery.js"></script> I'm not sure who would vote up the image path solution offered by Mike as being an answer to this question as it doesn't answer the question posted. So if you upgrade your jq mobile you will need to upgrade your jquery to take advantage of what's on offer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java media control ala Youtube I'm looking to write a Java control that acts like the media control on youtube. It should have a download progress, current playback state and let the user scrub around on the video. Has anyone done this in Java or will I need to roll this myself? A: You can try JavaFx. Take a look here A: I found a decent GPL one in the Cortado video player java applet. http://www.flumotion.net/cortado/
{ "language": "en", "url": "https://stackoverflow.com/questions/7570452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Split Paragraphs Java: i want first 50 words in one variable from string I have String explanation = "The image-search feature will start rolling out in the next few days, said Johanna Wright, a Google search director. "Every picture has a story, and we want to help you discover that story she said."; there are total number of words are 300 In Java, how do I get the first 50 words from the string? A: Here you go, perfect explanation: http://www.aliaspooryorik.com/blog/index.cfm/e/posts.details/post/show-the-first-n-and-last-n-words-232 A: Depending on your definition of a word, this may do for you: Search for the 50:th space character, and then extract the substring from 0 to that index. Here is some example code for you: public static int nthOccurrence(String str, char c, int n) { int pos = str.indexOf(c, 0); while (n-- > 0 && pos != -1) pos = str.indexOf(c, pos+1); return pos; } public static void main(String[] args) { String text = "Lorem ipsum dolor sit amet."; int numWords = 4; int i = nthOccurrence(text, ' ', numWords - 1); String intro = i == -1 ? text : text.substring(0, i); System.out.println(intro); // prints "Lorem ipsum dolor sit" } Related question: * *How to find nth occurrence of character in a string? A: Split the incoming data with a regex, bounds check, then rebuild the first 50 words. String[] words = data.split(" "); String firstFifty = ""; int max = words.length; if (max > 50) max = 50; for (int i = 0; i < max; ++i) firstFifty += words[i] + " "; A: You can try something like this (If you want the first 50 words): String explanation="The image-search feature will start rolling out in the next few days, said Johanna Wright, a Google search director. "Every picture has a story, and we want to help you discover that story she said." String[] words = explanation.split(" "); StringBuilder sb = new StringBuilder(); for (int i = 0; i < Math.min(50, words.length); i++) { sb.append(words[i] + " "); } System.out.println("The first 50 words are: " + sb.toString()); Or something like this if you want the first 50 characters: String explanation="The image-search feature will start rolling out in the next few days, said Johanna Wright, a Google search director. "Every picture has a story, and we want to help you discover that story she said." String truncated = explanation.subString(0, Math.min(49, explanation.length()));
{ "language": "en", "url": "https://stackoverflow.com/questions/7570456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Print the IPMI commands coming from IPMC IPMI -> Intelligent Platform Management Interface, IPMC -> Intelligent Platform Management Controller IPMC is connected to the Processor through a serial cable. The ipmi_serial driver in the kernel communicates with the IPMC to send messages in both directions. There are 2 types of messages 1. IPMI driver to IPMC -> The driver sends IPMI command and IPMC sends ACK corresponding to it. 2. IPMC to IPMI driver -> IPMC sends events and driver sends the ACK corresponding to it. In the driver code, ipmi_serial.c i have enabled the debug flag so that the messages send in the first type is logged. This is done during runtime as follows. echo 0x06 > /sys/module/ipmi_serial/parameters/debug But for the second types is there a way to enable the messages to be logged?
{ "language": "en", "url": "https://stackoverflow.com/questions/7570459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to force layoutSubviews of UIView? I have a custom UIView which has a dedicated, manually set frame for portrait and landscape orientation because autoresizingMasks just don't work in my case. I set this frame in: - (void)viewWillAppear:(BOOL)animated And it works as expected. My problem is now, that my UIView furthermore has subviews that also have a dedicated position for portrait/landscape. I position these subviews in: - (void)layoutSubviews If I now leave my viewController in e.g. portrait orientation, rotate to landscape on another viewController and then come back to this viewController I see that my view got resized correctly, but the subviews of my view, which get positioned in layoutSubviews are not repositioned yet but are resized in an animated fashion after the view already appeared. I do nothing in viewDidAppear and I already tried calling - (void)layoutIfNeeded As well as: - (void)setNeedsLayout In viewWillAppear, but it doesn't seem to change anything. Any ideas what I'm doing wrong? A: I would suggest setting the initial frame in viewDidLoad then changing the view frame for orientation changes in - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration You don't need any explicit animations in layoutSubviews (not sure if you had any, but it sounded like it) as any frame changes will be synced to the rotation animation. When off screen the orientation should still be rotated, so your views should be positioned correctly when transitioned back on screen again. I also recommend watching WWDC 2010 Session 123 "Building Animation Driven UI" which covers this stuff in much more detail. A: At swift 3 @iOS 10.1 override func viewWillAppear(animated: Bool){ super.viewWillAppear(animated) view.setNeedsLayout() } runs perfect A: Had a similar problem today. I solved it by first calling * *-setNeedsLayout: Set the flag that the view needs layout, and afterwards calling *-layoutIfNeeded: Check the flag immediately and - as it was set manually before - as result layoutSubviews is called. Don't know if this is the best way, but it works ;) A: For me what worked is [self.view setNeedsDisplay] . This calls redraw on the whole view. You can also redraw a selected view by calling setNeedsDisplay on the particular view, which I did in my case and it worked perfectly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "61" }
Q: Updating existing classes with new EDMX model I am working with an existing EDMX model where I had to add a new column to DB. I have updated the model from DB and now I can see the new column in the model. However, I have to update the Classes with the newly added column and add get; set; methods etc,. Is there an automate way to update this via Visual Studio but still retain the existing code and add the new property in? This is the first time I'm using EDF an find it hard to get my head around it. Many thanks in advance A: Did you use the ADO.NET DbContext Generator to create model classes for you? That's how I do it. If you do that then, generally speaking, those classes will recreate correctly if you add a new column to a corresponding DB table. Any code related to some generated I put in a separate viewmodel or other custom-built model that isn't subject to being overwritten when those are regenerated. Then there's just some minor mods to my viewmodels if the DB changes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to extract data between a particular tag from a string in Perl? For example, from the following string <?xml version="1.0"?><root><point><message>hello world 1</message></point><point><data><message>hello world 2</message></data></point></root> if I want to extract message, the result should be hello world 1 hello world 2 Is there an easy way to do this? All I can think of is to first find out the position of and and then generate substrings in a loop. Is there a better way? A: Your data is not XML, so I guess you'll have to use a regular expression for that: perl -n -E'say $1 while m{<message>(.*?)</message>}g' your_file_here.xml If your file was proper XML, then XML::Twig would work nicely. You could even use the xml_grep tool that comes with it to do just what you want. update: with valid XML you can then do xml_grep --text_only message mes.xml or xml_grep2 --text_only '//message' mes.xml # xml_grep2 is in App::xml_grep2 or perl -MXML::Twig -E'XML::Twig->new( twig_handlers => { message => sub { say $_->text; }, }) ->parsefile( "mes.xml")' A: Use an XML parser. XML::Parser in Subs mode seems good enough. A: Use an XML parser. I like XML::LibXML. use strict; use warnings; use feature qw( say ); use XML::LibXML qw( ); my $xml = <<'__EOI__'; <?xml version="1.0"?><root> <point><message>hello world 1</message></point> <point><data><message>hello world 2</message></data></point> </root> __EOI__ my $parser = XML::LibXML->new(); my $doc = $parser->parse_string($xml); my $root = $doc->documentElement(); say $_->textContent() for $root->findnodes('//message');
{ "language": "en", "url": "https://stackoverflow.com/questions/7570463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Facebook Style Dynamic Dropdown menu on Windows Forms I would like to have a Facebook style dynamic drop down menu on windows forms using csharp. Any idea how to implement it? TextChanged event of text box can be used but I don't know how to visualize it. For the ones who doesn't use facebook here is the description. Normally there is no drop down menu, but when you start typing, it shows automatically your friends whose names are matching and as soon as text is changed it updates content of dropdown menu. Note: If it helps, devexpress tools also can be used. Thanks&Regards, -AFgone A: Simply use a textbox and a combobox. Start with the combobox invisible and displayed on top of the textbox. As soon as text is entered, make the combobox visible and set the focus to it. Some sample code: public partial class Form1 : Form { public Form1() { InitializeComponent(); comboBox1.Visible = false; comboBox1.Size = textBox1.Size; comboBox1.Location = textBox1.Location; } private void textBox1_TextChanged(object sender, EventArgs e) { if (textBox1.Text.Length > 0) { comboBox1.Text = textBox1.Text; comboBox1.Visible = true; comboBox1.Focus(); textBox1.Enabled = false; // todo: fill combo } } private void comboBox1_Leave(object sender, EventArgs e) { comboBox1.Visible = false; textBox1.Text = ""; textBox1.Enabled = true; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7570469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: opening images with Python PIL I am using a sample NEF and expecting a 4288×2848 image, but get 160x120 with the code below. Is this as expected in that PIL doesn't support NEF? from PIL import Image image="./blah.nef" im=Image.open(image) im.size A: You're getting the JPEG thumbnail embedded in the NEF. It's pretty cool that it got far enough into the file to find the thumbnail. A: Did you check the Python Image Library's documentation? I don't see the Nikon RAW format (NEF) in the list of supported image formats. You'll need to find a library or application that explicitly supports this format, such as UFRaw. A: I know the question's old, but you can use rawpy nowadays: #!/usr/bin/env python3 import rawpy import imageio with rawpy.imread('blah.nef') as raw: rgb = raw.postprocess(gamma=(1,1), no_auto_bright=True, output_bps=16) # Extract individual bands for fun R = rgb[:,:,0] G = rgb[:,:,1] B = rgb[:,:,2]
{ "language": "en", "url": "https://stackoverflow.com/questions/7570474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Not Working in Other Pc's Hi i have the following code which works fine in my machine but when i give my install set in other machines application is been crashed and giving me error . And the functionality i am trying to achive is I am backing schema and data for few tables into an output folder and if the user checks the Schema_checkbox then the backup file should delete the lines till schema and just leave the data bit . So finally it will contain data but not schema . This bit is working fine on my machine but not in support desk who installed my exe. My code : if (Schema_checkbox.Checked) { DisplayMainWindow("Schema not required selected"); Logger.Log("Schema not required selected " + DateTime.Now); FileHelper.CopyFileContent(outputFileName); DisplayMainWindow(" Only table data is backup excluding schema"); Logger.Log(" Only table data is backup excluding schema" + DateTime.Now); } public void CopyFileContent(string filePath) { try { StringBuilder sb = new StringBuilder(); string newText = null; using (StreamReader tsr = new StreamReader(filePath)) { do { string textLine = tsr.ReadLine() + "\r\n"; { if (textLine.StartsWith("INSERT INTO")) { newText += textLine + Environment.NewLine; } } } while (tsr.Peek() != -1); tsr.Close(); } File.WriteAllText(filePath, newText); } catch (Exception ex) { Logger.Log("Exception" + ex); MessageBox.Show("Error Occured" + ex); } } Error Message : 27/09/2011 14:46:34 Started backing Table data 27/09/2011 14:46:54 Exception is : System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown. at System.String.GetStringForStringBuilder(String value, Int32 startIndex, Int32 length, Int32 capacity) at System.Text.StringBuilder.GetNewString(String currentString, Int32 requiredLength) at System.Text.StringBuilder.Append(String value) at ErikEJ.SqlCeScripting.Generator.GenerateTableContent(String tableName, Boolean saveImageFiles) at ErikEJ.SqlCeScripting.Generator.GenerateTableData(String tableName, Boolean saveImageFiles) at ErikEJ.SqlCeScripting.Generator.GenerateTableScript(String tableName, String outputFolder, Boolean isBackupReq) at ErikEJ.SqlCeScripting.Generator.GenerateSchemaGraph(String connectionString, List`1 tables, String outputFolderPath, Boolean isDataBackupReq) at SqlDatabaseDataExport.MainForm.BackupScriptLocation() A: If the file you try to open is very big, you can reach a limit where your system will run low in memory. I suggest you that you open the stream to read the file and then and other stream to write into the other file with a buffer (use StringBuilder). This way, your newText won't reach a very high level of memory because you will control the size with the StringBuilder. Also, it's always better when concatenate a lot of string to use a StringBuilder instead of String because the String use more memory. At the end of my suggestion, you just need to delete the original file and rename the output file with the name of the first file. That's it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570482", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Benchmark C++ vs Java, Unrealistic results I did a simple test, I know C++ is faster but the results of my test is unrealistic. C++ code is: #include <stdio.h> #include <windows.h> unsigned long long s(unsigned long long n) { unsigned long long s = 0; for (unsigned long long i = 0; i < n; i++) s += i; return s; } int main() { LARGE_INTEGER freq, start, end; QueryPerformanceFrequency(&freq); QueryPerformanceCounter(&start); printf("%llu\n", s(1000000000)); QueryPerformanceCounter(&end); double d = (double) (end.QuadPart - start.QuadPart) / freq.QuadPart * 1000.0; printf("Delta: %f\n", d); return 0; } Java code is: public class JavaApplication5 { public static long s(long n) { long s = 0; for (long i = 0; i < n; i++) { s += i; } return s; } public static void main(String[] args) { long start = System.nanoTime(); System.out.println(s(1000000000)); long end = System.nanoTime(); System.out.println((end - start)/1000000); } } C++ compiler: gcc 4.4.0 and Java: jdk 1.6.0 Java: 2795 ms C++ : 0.013517 ms It says C++ is 206777 times faster than Java! No way! What is wrong in my test? A: Show the compiler options you used. And your REAL code (#include <stdio> isn't your real code). Your C++ compiler is much smarter than your Java compiler (this is true on average and in your case, but not every C++ compiler is smarter than every Java compiler), and it precomputed the result. The only thing you're timing is the printf call. On most of the tasks Java is used for, it performs about as well as C++. VM languages (Java, C#) have additional costs related to JIT compilation, but also benefit from more efficient memory allocation and inlining across shared libraries. And C++ is much much faster at accessing OS syscalls. Beyond that, C++ memory layouts can be carefully tuned for cache behavior; you don't get that level of control in managed languages. Which of these factors has more influence is completely application-specific. Anyone making a blanket statement that "C++ is faster in general than Java" or "Java is faster in general than C++" is an idiot. Averages don't matter. Performance on YOUR application matters. And here is my proof, that gcc is precomputing the answer. On this code: #include <stdio.h> #include <windows.h> unsigned long long s(unsigned long long n) { unsigned long long s = 0; for (unsigned long long i = 0; i < n; i++) s += i; return s; } int main( int argc, char** argv ) { LARGE_INTEGER freq, start, end; QueryPerformanceFrequency(&freq); QueryPerformanceCounter(&start); printf("%llu\n", s(1000000000)); QueryPerformanceCounter(&end); double d = (double) (end.QuadPart - start.QuadPart) / freq.QuadPart * 1000.0; printf("Delta: %f\n", d); QueryPerformanceCounter(&start); printf("%llu\n", s(atol(argv[1]))); QueryPerformanceCounter(&end); d = (double) (end.QuadPart - start.QuadPart) / freq.QuadPart * 1000.0; printf("Delta: %f\n", d); return 0; } With gcc-4.3.4, using the command-line ./g++-4 -omasoud-gcc.exe -O3 masoud.cpp: bash-3.2# ./masoud-gcc 1000000000 499999999500000000 Delta: 0.845755 499999999500000000 Delta: 1114.105866 By comparison, MSVC++ 16.00.40219.01 for x64 (2010 SP1), command-line cl /Ox masoud.cpp: > masoud 1000000000 499999999500000000 Delta: 229.684364 499999999500000000 Delta: 354.275606 VC++ isn't precomputing the answer, but 64-bit code does execute the loop more than three times faster. This is the speed that Java ought to approach. More fun facts: gcc precomputes the answer faster than the code it generates to calculate it out. Compile time for gcc: real 0m0.886s user 0m0.248s sys 0m0.185s A: I guess that gcc compiled your s method into: unsigned long long s(unsigned long long n) { return n*(n+1)/2; } ...while the java JIT did not. I'm no expert but gcc optimization process may contain more passes than what the JIT can do in a reasonable time. That's also why a gcc compilation may take ages while a java program launches itself immediatly (altough the JIT has to compile, link and optimize everything before the program can be run). The java compiler (javac) does very few optimization, like constant folding, but that's pretty much all. Every major optimization (inlining, etc) is done by the JIT, so if it does not want the user to wait too long before launch, it must hurry. On the other hand, since gcc compiles and optimize everything statically, it can take as long as it needs. EDIT: It should be simple to know if there is a difference in optimizations: run your two programs with s(1000) and then with s(100000000000000). If I'm true, the c++ program may take the exact same time for both calls, while the java one while take longer to complete in the second case. A: First of all, you probably don't want the respective print functions to be part of your benchmark unless you really care how fast those are. There's not a straight answer as to whether Java or C++ is faster...it depends. Java can be faster when the compiler can do some optimizations that would not be available for C++. So it depends on what specifically you are doing and what the compiler options are.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can you factor out branching from tight loop? My question is: How can I add features to my processing loop without the overhead of checking the true/falseness of the user settings to navigate the branches? The settings are the same for all iterations on the loop. Do modern processors with branch prediction make this unnecessary? My programs over follow this pattern: * *User adjusts settings, checkboxes, sliders, numerical entries. *Data is processed when an update is triggered * *Apply settings to local variables *Run loop over a large dataset * *add if statements to bypass unused code from the user settings. *return from loop *return transformed data How can you template or inline out all permutations ahead of time? example: bool setting1 = true; bool setting2 = false; vector<float> data; for(int i=0;i<100000;i++) data.push_back(i); for(int i=0;i<100000;i++) { if (setting1) { doStuff(data[i]); .... } if (setting2) { doMoreStuff(data[i]); ..... } .... //etc } I know this is a silly example. But I'd like to know what pattern scales when there are lots of branches. A: Use templates for the main loop. template <bool A, bool B> void loop() { while (1) { if (A) // will get compiled out if A == false { doStuff(data[i]); .... } if (B) { doMoreStuff(data[i]); ..... } .... //etc } } When you change settings: (you could probably make this less code) if (setting1) { if (setting2) loop<1,1>; else loop<1,0>; } else { if (setting2) loop<0,1>; else loop<0,0>; } You want to stay in loop() until settings change. This should be used with care as it can lead to bloat. Profiled the answers (G++ O2 optimization): %Time 46.15 0.84 0.84 fb() (blackbear) 38.37 1.53 0.69 fa() (OP) 16.13 1.82 0.29 fc() (pubby8) A: Firstly, unless the operations are incredibly cheap compared to the cost of an iteration of the loop (branches + loop overhead), simply don't worry about it and do whatever is most readable. Premature optimisation is the root of much evil; don't just assume things will be slow, do some profiling so that you know. If you do find yourself genuinely spending more time iterating than doing useful work - that is, your overhead is too high - you need to find a sensible way to reduce the overhead; so, to select between different loop bodies/implementations optimised for particular combinations of inputs. Factoring the conditions out of the loop, to make multiple loops, might initially seem like a good idea, however if most of the settings are mostly enabled and your actual operations are cheap enough to make the overhead an issue at all, you may find the performance largely unchanged - each of the new loops has a per-iteration cost! If that is the case, a way forward might be to use templates or other means to instantiate variants of the loop body for the most common combinations of inputs, select at a high level between loops calling those when a suitable one is available, and fall back to the generic case when it is not. A: You can avoid the overhead this way (supposing settingx doesn't affect settingy): if(setting1) { for(int i=0;i<100000;i++) { // ... } } if(setting3) { for(int i=0;i<100000;i++) { // ... } } if(setting3) { for(int i=0;i<100000;i++) { // ... } } But, in my opinion, the best solution is keeping your code. Today's branch prediction units are very powerful, and considering that you'll loop many thousands of times with every branch having the same result, you can afford a few cycles of warm up ;) EDIT: I compared our approaches to the problem with a simple console program (sources, it's c# though). The loop is executed 1000000 times and I used trigonometrical functions together with double precision floating point operations. Test 2 is the solution I showed above, and the three letters are the value of setting1, setting2 and setting3. Results are: test 1 - fft: 13974 ms test 2 - fft: 14106 ms test 1 - tft: 27728 ms test 2 - tft: 28081 ms test 1 - ttt: 41833 ms test 2 - ttt: 41982 ms I also did a test run with all three test functions empty to prove loop and calling overhead is minimal: test 1 - fft: 4 ms test 2 - fft: 4 ms test 1 - tft: 8 ms test 2 - tft: 8 ms test 1 - ttt: 12 ms test 2 - ttt: 12 ms Effectively, my solution is about 1% slower. The second point of my answer, though is proven to be correct: loop overhead is completely trascurable. A: If the size of the dataset is known at compile time, then the compiler can potentially perform: * *loop unrolling If it is a mathematical operation * *vectorization can come into play You can also do the logic inside-out: if (epic-setting) { //massive for loop } It is bad for memory locality, as one person said. Branch prediction will help you a good deal, if and only if the cost of the missed branch is less than the speedup given (for a large dataset, it should help, not hurt). If your data operation is fully parallel, ie, you are running SIMD, you could investigate threading out the operations: e.g., open up 3 threads, and have all 3 take the i % t operation, t being the thread index, i being the data index. (You can partition the data different ways). For a large enough data set, presuming you don't have synch operations, you will see a linear speedup. If you are writing this for a specialized system, e.g., an industrial computer with a given CPU, and you can assume you will always have that CPU, you can optimize much more heavily for what that CPU can support. Things like exact cache size, depth of pipeline, etc, can all be coded in. Unless you can assume that, it's sketchy to try and assume on those counts.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trying to connect two tables but unable I've done more complex queries and I am stumped. table: STEPS (id, rank, description) ELEMENTS (element, element_id, year_code) The tables relate by STEPS.id = ELEMENTS.element_id where ELEMENTS.year_code = 2010 I want to retrieve a step, by its rank, but it needs to check the element table to make sure I pull the appropriate step, because there could be two steps with the same rank, but that is where the year_code comes into play, there is no duplicate ranks for the same year. So I want to view the step where steps.rank = 1.2.4 and elements.year_code = 2010 any help is appreciated The steps table holds all the steps and the elements table keeps track of what year the step belongs to. A: I don't have a link field, so I'm just going to use elements.step_id to link the fields. Adjust the query to your field names. SELECT s.* FROM steps s INNER JOIN elements e ON (e.steps_id = s.id) WHERE s.rank = '1.2.4' AND e.year_code = '2010' Or perhaps you meant: SELECT s.* FROM steps s INNER JOIN elements e ON (e.steps_id = s.id) WHERE s.rank IN ('1','2','4') AND e.year_code = '2010' A: SELECT s.id, s.rank, s.description FROM STEPS s INNER JOIN ELEMENTS E ON s.id = e.element_id WHERE s.rank = '1.2.4' AND e.year_code = 2010
{ "language": "en", "url": "https://stackoverflow.com/questions/7570488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Handler pattern in Project Silk I am looking at the source for the Project Silk project and there is a "handler" pattern that I have not seen before. First - this link from 2009 alludes to it but leaves me hanging What the sample shows is a one method class where each class represents one method for each method in a related repository class. The classes are named like method names. public class GetFillupsForVehicle { private readonly IFillupRepository _fillupRepository; public GetFillupsForVehicle(IFillupRepository fillupRepository) { _fillupRepository = fillupRepository; } public virtual IEnumerable<FillupEntry> Execute(int vehicleId) { try { var fillups = _fillupRepository .GetFillups(vehicleId) .OrderBy(f => f.Date) .ToList(); return new ReadOnlyCollection<FillupEntry>(fillups); } catch (InvalidOperationException ex) { throw new BusinessServicesException(Resources.UnableToRetireveFillupsExceptionMessage, ex); } } } Could someone explain this pattern or point me to something that I could read to learn more? Thanks, Paul A: Please refer to this information about Project Silk which will be more relevant now to adopt. In the code snippet which I have reposted from the PDF document provided by Microsoft on the Project Silk will help you understand how its being consumed. According to me its being considered more as scaffolding towards triggering the event at Business Domain level. Also refer to this specific post which might be throwing light where they are heading to. public ActionResult Add(int vehicleId) { var vehicles = Using<GetVehicleListForUser>() .Execute(CurrentUserId); var vehicle = vehicles.First(v => v.VehicleId == vehicleId); var newFillupEntry = new FillupEntryFormModel { Odometer = (vehicle.Odometer.HasValue) ? vehicle.Odometer.Value : 0 }; var fillups = Using<GetFillupsForVehicle>() .Execute(vehicleId) .OrderByDescending(f => f.Date); var viewModel = new FillupAddViewModel { VehicleList = new VehicleListViewModel(vehicles, vehicleId) {IsCollapsed = true}, FillupEntry = newFillupEntry, Fillups = new SelectedItemList<Model.FillupEntry>(fillups), }; ViewBag.IsFirstFillup = (!fillups.Any()); return View(viewModel); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7570492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get OnUtteranceCompleted to be called? I have been surfing the web (read google/ android developer document, read stackoverflow's similar questions, read book) and very closely followed the examples. The Text-to-Speech "speak" works great. But I just can't get OnUtteranceCompleted to be called. It must be so simple that I am not seeing the answer. Please help! Here's my code after several interactions. Or could someone be kind enough to provide a full source code (not snippets) of one that actually works to see if it works on my emulator/ actual device? public class testActivity extends Activity implements OnInitListener, OnUtteranceCompletedListener { ... protected void checkTtS() { Intent checkIntent = new Intent(); checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA); startActivityForResult(checkIntent, TTS_DATA_CHECK_CODE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { .... if (requestCode == TTS_DATA_CHECK_CODE) { if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) { // success, create the TTS instance mTts = new TextToSpeech(this, this); .... // Implements TextToSpeech.OnInitListener. public void onInit(int status) { // status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR. if (status == TextToSpeech.SUCCESS) { int result = mTts.setLanguage(Locale.FRANCE); result = mTts.setOnUtteranceCompletedListener(this); HashMap<String, String> params = new HashMap<String, String>(); params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"stringId"); mTts.speak("Text to Speak",TextToSpeech.QUEUE_FLUSH, params); .... public void onUtteranceCompleted(String uttId) { Toast.makeText(getBaseContext(), "onutterancecompleted", Toast.LENGTH_SHORT).show(); } A: have you checked the value of int result after the setOnUtteranceCompletedListener call. if(result == TextToSpeech.ERROR) then utterance listener was not set A: Your code probably should look like this: public void onUtteranceCompleted(String uttId) { if (uttId.equals("stringId")) { Toast.makeText(getBaseContext(), "onutterancecompleted", Toast.LENGTH_SHORT).show(); } } And you should also take a look at this article, there is a clear description of how onUtteranceCompleted works. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting the document object of an iframe I'm trying to get the document object of an iframe, but none of the examples I've googled seem to help. My code looks like this: <html> <head> <script> function myFunc(){ alert("I'm getting this far"); var doc=document.getElementById("frame").document; alert("document is undefined: "+doc); } </script> </head> <body> <iframe src="http://www.google.com/ncr" id="frame" width="100%" height="100%" onload="myFync()"></iframe> </body> </html> I have tested that I am able to obtain the iframe object, but .document doesn't work, neither does .contentDocument and I think I've tested some other options too, but all of them return undefined, even examples that are supposed to have worked but they don't work for me. So I already have the iframe object, now all I want is it's document object. I have tested this on Firefox and Chrome to no avail. A: Try the following var doc=document.getElementById("frame").contentDocument; // Earlier versions of IE or IE8+ where !DOCTYPE is not specified var doc=document.getElementById("frame").contentWindow.document; Note: AndyE pointed out that contentWindow is supported by all major browsers so this may be the best way to go. * *http://help.dottoro.com/ljctglqj.php Note2: In this sample you won't be able to access the document via any means. The reason is you can't access the document of an iframe with a different origin because it violates the "Same Origin" security policy * *http://javascript.info/tutorial/same-origin-security-policy A: This is the code I use: var ifrm = document.getElementById('myFrame'); ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument; ifrm.document.open(); ifrm.document.write('Hello World!'); ifrm.document.close(); contentWindow vs. contentDocument * *IE (Win) and Mozilla (1.7) will return the window object inside the iframe with oIFrame.contentWindow. *Safari (1.2.4) doesn't understand that property, but does have oIframe.contentDocument, which points to the document object inside the iframe. *To make it even more complicated, Opera 7 uses oIframe.contentDocument, but it points to the window object of the iframe. Because Safari has no way to directly access the window object of an iframe element via standard DOM (or does it?), our fully modern-cross-browser-compatible code will only be able to access the document within the iframe. A: For even more robustness: function getIframeWindow(iframe_object) { var doc; if (iframe_object.contentWindow) { return iframe_object.contentWindow; } if (iframe_object.window) { return iframe_object.window; } if (!doc && iframe_object.contentDocument) { doc = iframe_object.contentDocument; } if (!doc && iframe_object.document) { doc = iframe_object.document; } if (doc && doc.defaultView) { return doc.defaultView; } if (doc && doc.parentWindow) { return doc.parentWindow; } return undefined; } and ... var el = document.getElementById('targetFrame'); var frame_win = getIframeWindow(el); if (frame_win) { frame_win.targetFunction(); ... } ... A: In my case, it was due to Same Origin policies. To explain it further, MDN states the following: If the iframe and the iframe's parent document are Same Origin, returns a Document (that is, the active document in the inline frame's nested browsing context), else returns null.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "52" }
Q: Being both Serializable and IsSerializable in GWT I've got some DTOs in a project separate from my GWT project, and am trying to use them as DTOs inside the GWT project. They implement Serializable for use with another service. Currently, because I do not wish to reference them all in the GWT RPC service interface method signatures, I have to do the technique of "tricking" GWT into whitelisting the classes for serialization by making dummy methods that do nothing and are never called. I don't want to create separate IsSerializable classes in the GWT project in order to not duplicate code, but dummy methods aren't desirable either. One alternative I have thought of would be to add (a) GWT jar(s) as a dependency to the project containing my DTOs so that they may implement both Serializable and IsSerializable. Searches on the topic of being both Serializable and IsSerializable only brings up discussions on choosing between the two. Can a class implement both Serializable and IsSerializable without complications? A: Which version of GWT are you using? If it's recent (> 1.4) then, as far as I understand, GWT documentation says that you can directly use your Serializable objects: the GWT Team felt that the community was generally aware of these issues but preferred the convenience of being able to use the standard java.io.Serializable interface rather than to have their classes implement the isSerializable marker interface, although both marker interfaces to denote serializable classes are supported in GWT 1.4 and later. Considering this, the GWT Team made changes to the GWT RPC system to support the use of java.io.Serializable for data transfer objects (commonly referred to as DTOs) that would be transferred over the wire. However, there is one condition to enable support for java.io.Serializable in the new GWT RPC system. A: I tried implementing both IsSerializable and Serializable, since I want to be able to save my DTOs into Http session and replicate them thru a cluster. Also I like the idea of allowing old clients (with non valid policies) to be able to use the new services (of course the ones with same signature) that IsSerializable provides. But GWT goes crazy (the client deserializer tries to instantiate a class named as a String content) when falling back to 1.3.3 behaviour (no valid policy) and having both interfaces implemented in the DTOs. As soon as I get rid of Serializable, GWT RPC system works ok again. EDIT: Strangely enough I tried again after removing Serializable and put it back in my DTO. And it worked. I was always testing in development mode, maybe a bug with the plugin?
{ "language": "en", "url": "https://stackoverflow.com/questions/7570500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Set NavController title independently of TabBar title I'm working through the fairly typical process of building view controllers and their associated navigation controllers programmatically, and then adding the navigation controllers to a tabBarController. self.tabBarController = [[[UITabBarController alloc] init] autorelease]; [self.tabBarController setHidesBottomBarWhenPushed: YES]; FirstViewController * firstView = [[[FirstViewController alloc] init] autorelease]; firstView.title = @"First"; firstView.tabBarItem.image = [UIImage imageNamed:@"icon_first_view.png"]; UINavigationController * firstViewNav = [[[UINavigationController alloc] initWithRootViewController:firstView] autorelease]; [tabBarController setViewControllers:[NSArray arrayWithObjects: firstViewNav, nil]]; That works fine, and the NavigationController title and the TabBar title will say "First". Now, I would like to change the Navigation Controller title to say "FooBar", and leave the tab bar title as "First". I've tried: firstViewNav.navigationItem.title = @"FooBar"; But that doesn't seem to change it. If I change the title on the actual ViewController managed by this nav controller (firstView.title), then both the TabBar title and the Navbar title both change, which is not desired. Any ideas? A: As answered here: self.title sets navigationController and tabBarItem's title? Why? self.title = @"Title for TabBarItem"; // TabBarItem.title inherits the viewController's self.title self.navigationItem.title = @"Title for NavigationBar"; A: Add a Tab Bar Item to the navigation controller, and set the title of the TabBarItem to what you want the tab bar label to read. I normally do this in the NIB but it should work if you do it programmatically. Set the title of the navigation item to what you want in the text of the nav bar. You can also change this text when the view will appear, for example, if you want it to change. As you discovered, do NOT set the title of the view controller, as that will override both other values. A: just hide the NavigationBar and add a toolbar with the title you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: FQL for getting online friends list- Objective c I am creating an iPhone app using Facebook api. I have created the app and now I'm getting friends name, uid, sex and profile picture.I have followed the steps in the https://developers.facebook.com And I need to get the online friends list from my account. I think I need to get get permission first. How can do that? please help Thanks A: You'll need to prompt your users to grant the user_online_presence and/or friends_online_presence permissions. Then you can get the user's friends' online statuses by querying for the user.online_presence field via an FQL Call. A: Find out what permissions you need and use the api to ask for the user to grant them (this example asks for the publish_stream permission): //This is an array filled with permissions you need NSArray* permissions = [[NSArray arrayWithObjects:@"publish_stream", nil] retain]; facebook = [[Facebook alloc] initWithAppId:@"yourappid" andDelegate:self]; if (![facebook isSessionValid]) { NSLog(@"Sending facebook connect request"); [facebook authorize:permissions]; } else { NSLog(@"There is already an active FB session"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7570508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I hide my Oracle table? Here's the scenario (simplified example): I have an Oracle user/schema called ABC. ABC owns a table called TRN. Client side code connects to the database as ABC and selects from ABC.TRN. So far so good. However, I don't want the client code to specify the Oracle schema name. Now I think I have removed all references in the client code that refer to schema but I want to test this to make sure. So I want to create a new user/schema called DEF which will be used by the client to connect to the database. When the client application select from ABC.TRN, it must give an error. However if the client application selects from TRN (no schema name), it must return the data. Is there some way to do this? Note that DEF must be on the same database as ABC, there is only one table TRN table (owned by ABC) and I cannot use database links. I have tried creating a new XYZ user with a synonym pointing to ABC.TRN and giving it select rights on ABC.TRN. Then I created the DEF user with a synonym pointing to XYZ.TRN and gave DEF has select rights on XYZ.TRN. This works but Oracle is clever enough to know that if DEF has rights to select from XYZ.TRN then it also has rights to select from ABC.TRN, thereby defeating the purpose of this exercise as I want this case to give an error. Over to you... A: There is no easy way to do this. One approach would be political: institute code reviews, perhaps with automated searches of the code base, and just slap wrists when people do this. The architectural approach would be similar to your three schema structure, but with a subtle twist: the schema in the middle uses views. So, schema ABC owns tables and grants permissions on them to schema XYZ. Schema XYZ builds simple views against those tables (SELECT *, no WHERE clauses) and grants permissions on the views to schema DEF. Schema DEF can only select from XYZ objects. Of course, all that effort still won't prevent develoeprs from coding SELECT * FROM xyz.whatever. In which case I refer you to my first suggestion 8-) Actually there is one, really really evil way to do this. Use synonyms in the app facing schema (DEF)and then change the name of the data owning schema (ABC). Of course, you should only attempt this stratagem if your install scripts are fully paramterized, with no hard-coded schema names of their own. A: Do you really need to throw an error? Or do you simply need to verify that the application is not using fully qualified names (i.e. ABC.TRN)? Assuming that you're merely interested in verifying that the application is not using fully qualified names and that throwing the error was merely the mechanism you thought of to notify you, you can probably verify the code by querying V$SQL while the application is running. V$SQL lists all the SQL statements in the shared pool in Oracle. If you query that table regularly while your application is running, you'll see all the SQL statements it issues. You can then log any statements that use fully qualified names. For example CREATE OR PROCEDURE look_for_abc_trn AS BEGIN FOR x IN (SELECT * FROM v$sql WHERE upper(sql_fulltext) LIKE '%ABC.TRN%') LOOP INSERT INTO log_of_bad_sql( sql_fulltext, <<other columns>> ) VALUES( x.sql_fulltext, <<other columns>> ); END LOOP; END; If you run that procedure every few minutes while your application is running, you'll see any SQL that is using the fully qualified name and log that statement in the LOG_OF_BAD_SQL table. Every few minutes is probably overkill for a well-written system, you just need to ensure that it is run more frequently than statements are aged out of the shared pool. If you have an application that doesn't use bind variables appropriately, that may need to be every few minutes in order to avoid missing anything. A: How about ALTER SESSION? ALTER SESSION SET CURRENT_SCHEMA = schema That would allow you to log in as a user, to whom select rights have been granted to a table owned by schema X, and execute an SP that changes the session to schema X. The front-end code would not know that this had happened. However, if your front-end code specifies schema X: select * from X.tableName I don't think it will raise an error. Perhaps you could explain why it's important that the client-code receive an error when it uses the correct current schema name? Is it possible to create a new schema, transfer ownershp of the old schema's objects, and then drop the old schema, and then use the approach above? P.S. See AFTER LOGON triggers: http://psoug.org/reference/system_trigger.html P.P.S. Since you have elaborated upon your requirements: ... the table may be a synonym using a database link or the table might be hosted by in multiple schemas, each for a different release. It should be left to the database to resolve the actual location of the object referred to by client application. If the location of the object is not in the CURRENT_SCHEMA but in some other schema, both of which happen to have tables called CUSTOMER, for example, the database engine won't know that the statement sent to it by the client app should be referencing the other schema if the tablename is not so qualified. That implies a level of meta-knowledge the engine doesn't have, though it gives the developer the tools to create such intelligence in the form of stored procedures and triggers and grant/revoke control over objects. Your best chances of success in putting this intelligence in the back end would be to revoke all direct rights to tables and views and require client apps to access objects via stored procedures, because the database engine per se doesn't know about things like application release levels. I see no purely DECLARATIVE way to accomplish it. It would have to be procedural in large part. Your own back-end logic would have to assume responsibility for arbitrating between objects of the same name in different schemas. That said, features llike AFTER LOGON triggers and ALTER SCHEMA should prove helpful to you. A: You can't do it. Synonyms are nothing but pointers to other schemas' objects. You grant access to the actual object, not the synonym. From the Oracle docs: http://download.oracle.com/docs/cd/B28359_01/server.111/b28310/views003.htm Synonyms themselves are not securable. When you grant object privileges on a synonym, you are really granting privileges on the underlying object, and the synonym is acting only as an alias for the object in the GRANT statement.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: JSF 2.0 Navigation Not Working I am using Netbeans 7.0, Glassfish 3.1, JSF 2.0 I am trying to navigate from one view to another in a step-wise user registration process (with three steps). Each step corresponds to a view and these views are in different folders but all have the same name, i.e register.xhtml. i have tried implicit navigation whereby i specify the absolute path of the views in a managed bean event listener and also using the faces-config.xml navigation cases. The problem is that i can navigate from the first step/view to the next step/view without a problem. Navigating to the third view however results in a com.sun.faces.context.FacesFileNotFoundException the file structure is like /extensions/assm/registration/individual/register.xhtml /extensions/assm/registration/address/register.xhtml /extensions/assm/registration/systemuser/register.xhtml extract of faces-config.xml for navigating from address to systemuser <navigation-rule> <from-view-id></from-view-id> <navigation-case> <from-outcome>gotosystemuser</from-outcome> <to-view-id>/extensions/aasm/registration/systemuser/register.xhtml</to-view-id> </navigation-case> </navigation-rule> anyone out there know where i am getting it wrong? A: com.sun.faces.context.FacesFileNotFoundException means that JSF is not able to locate the view. The view id you have specified in the navigation-rule is not good (somehow). A view is identified by the path with everything after the context root, including the / at the beginning. But you also have to include the URL pattern that's mapped with the Faces Servlet in web.xml. e.g. if in your web.xml if you have <servlet-name>Faces Servlet</servlet-name> <url-pattern>/jsf/*</url-pattern> then you have to also include that as the View ID. So, with the view id will be /jsf/folder1/folder2/page.xhtml But with JSF 2.0 you don't need to do all that navigation-rule in the faces-config file. In JSF 2.0 to navigate to another page all you need to do is return the view id from the action method. @ManagedBean @ViewScoped public class MyBean { public String axnMethod() { return "view-id"; //this will result in navigation to view represented by view-id }
{ "language": "en", "url": "https://stackoverflow.com/questions/7570512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PowerShell Parameter only in Get-Help When I run get-help get-process -detailed I get the full help. What would I run if I just wanted to know what the get-process -id parameter does? Is there a way to drill down like that? A: yes, use the -Parameter flag > Get-Help Get-Process -Parameter id The parameter flag can also use wildcards. To see help on all parameters > Get-Help Get-Process -Parameter * Just so you're aware you can do a Get-Help on Get-Help. > Get-Help Get-Help -detailed Hope that helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7570514", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to copy rows in PowerPoint 2003 with VBA? I need to copy rows in PowerPoint 2003 (just to re-use their formatting). Tried to do: Dim oPPTRow As PowerPoint.Row Set oPPTRow = oPPTFile.Slides(SlideNum).Shapes(1).Table.Rows(2) oPPTFile.Slides(SlideNum).Shapes(1).Table.Rows.Add (-1) oPPTFile.Slides(SlideNum).Shapes(1).Table.Rows(oPPTTable.Rows.Count) = oPPTRow But it doesn't work. Is there any other way to achieve the same? A: The Rows.Add method lets you insert a new row before any row you like. The newly inserted row will pick up the formatting of the row you inserted it ahead of. Try this (be sure to select a tabel shape first): Sub AddNewRow() Dim oTbl As Table Dim oSh As Shape Set oSh = ActiveWindow.Selection.ShapeRange(1) Set oTbl = oSh.Table With oTbl .Rows.Add (2) End With End Sub Passing -1 as the parameter to .Add forces PPT to add the row at the end of the table; the new cells will all be formatted the same as the cells above them (that is, the cells in the row that was previously the bottom row). If you need to pick up formatting from some other row, I think you may need to do something like: Sub AddNewRow() Dim oTbl As Table Dim oSh As Shape Dim x As Long Dim lNewRow As Long Set oSh = ActiveWindow.Selection.ShapeRange(1) Set oTbl = oSh.Table With oTbl .Rows.Add (-1) lNewRow = .Rows.Count ' format the new row to match the cells in row two With .Rows(lNewRow) ' step across the row cell by cell For x = 1 To oTbl.Columns.Count ' pick up row two formatting oTbl.Cell(2, x).Shape.PickUp ' apply it to new row's cell x .Cells(x).Shape.Apply ' do the same for cell's text formatting oTbl.Cell(2, x).Shape.TextFrame.TextRange.Font.Name = oTbl.Cell(2, x).Shape.TextFrame.TextRange.Font.Name ' Use above pattern to pick up/apply font bold, ital, size, color etc as needed Next End With End With End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/7570517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# - How to proccess data from Process.StandardOutput when the data is around 400 MB I am trying to retrieve list of files from a server with the windows command - "DIR /S/B" The output is huge (around 400 MB). Now when I tried retrieve it with below approach, its taking hours to process. Is there any faster way to do it. string path = args[0]; var start = DateTime.Now; System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + "dir /s/b " + path ); procStartInfo.RedirectStandardOutput = true; procStartInfo.UseShellExecute = false; procStartInfo.CreateNoWindow = true; System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo = procStartInfo; proc.Start(); //string [] result = proc.StandardOutput.ReadToEnd().Split('\n'); ; StreamWriter writer = new StreamWriter("FileList.lst"); while (proc.StandardOutput.EndOfStream != true) { writer.WriteLine(proc.StandardOutput.ReadLine()); writer.Flush(); } writer.Close(); A: Why not use DirectoryInfo.GetFiles? I'm guessing quite a bit of your time now is being eaten up by the command executing, not the .NET code. It'll take dir a long time to write that much data to a stream in sequence. You then use String.Split which is also going to choke on that much data. By using DirectoryInfo.GetFiles, you should be able to get all the file names in a single line (and you could also get other information about the files this way): var files = (new DirectoryInfo(path) .GetFiles("*.*", SearchOption.AllDirectories) .Select(fi => fi.Name); If you're really only concerned about filenames, you could use: var fileNames = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories); A: You're reinventing the wheel. Add a reference to System.IO and use the DirectoryInfo and FileInfo classes. A: When you say recieve, do you simply mean list the files in the directory? If so, can you not use the Directory.GetFiles() method? // Only get files that begin with the letter "c." string[] dirs = Directory.GetFiles(@"c:\", "c*"); Console.WriteLine("The number of files starting with c is {0}.", dirs.Length); foreach (string dir in dirs) { Console.WriteLine(dir); } From MSDN
{ "language": "en", "url": "https://stackoverflow.com/questions/7570519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Warning while loading XML feed from other site $xmlDoc = new DOMDocument(); $url = 'http://domain.com/london/rss'; $key='item'; if($xmlDoc->load($url)) { $items = $xmlDoc->getElementsByTagName($key); if($items) { for($i=0; $i<$items->length; $i++) { foreach($items->item($i)->childNodes as $childnode){ echo $childnode->nodeValue; } } } } I use the above code to grab the details from the remote xml, but while load the xml it displays the below warning message in the client server. Same code is working fine in my local machine and other servers. Warning: DOMDocument::load() [domdocument.load]: Document is empty in http://domain.com/london/rss, line: 1 in /var/sites/d/mydomain.com/public_html/loadXML.php on line 5 Warning: DOMDocument::load() [domdocument.load]: Start tag expected, '<' not found in http://domain.com/london/rss, line: 1 in /var/sites/d/mydomain.com/public_html/loadXML.php on line 5 A: I think the error is quite self-explanatory: the document does not exist or is empty. Most likely, you get a 404 error (file not found) or the result is not an XML document. Put the URL into the browser's address bar - and see what you get. I used your example with url http://twitter.com/statuses/user_timeline/ookl.xml and it worked just fine - without any errors.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: yahoo finance api problems converting money symbols From years we use http://download.yahoo.com/d/quotes.csv?s=USDARS=X&f=l1 to retrieve conversions between money symbols. Since 9/25/2011 retrieve always 0.00. Any Ideas? Thanks a lot! A: You forgot the .finance in the URL. http://download.finance.yahoo.com/d/quotes.csv?s=USDARS=X&f=l1
{ "language": "en", "url": "https://stackoverflow.com/questions/7570524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ios singleton class crashes my app I have a problem with an singleton pattern. I have read the following tutorials about singleton classes and have created my own. http://www.galloway.me.uk/utorials/singleton-classes/ http://www.johnwordsworth.com/2010/04/iphone-code-snippet-the-singleton-pattern/ The first time i build & run the app it works like it should. No problems at all! But when i rebuild the app the singleton class does not work properly anymore. The first init works like it should but when i call it again after a button click it crashes my app. My singleton class: BPManager.h @interface BPManager : NSObject { NSString *dbPath; } @property (nonatomic, retain) NSString *dbPath; + (id)bpManager; - (void)initDatabase:(NSString *)dbName; - (int)getQuestions; @end BPManager.m static BPManager *sharedMyManager = nil; @implementation BPManager @synthesize dbPath; - (void)initDatabase:(NSString *)dbName { dbPath = dbName; } -(int)getQuestions { NSLog(@"getQuestions"); } - (id)init { if ((self = [super init])) { } return self; } + (BPManager *) bpManager { @synchronized(self) { if(sharedMyManager != nil) return sharedMyManager; static dispatch_once_t pred; // Lock dispatch_once(&pred, ^{ // This code is called at most once per app sharedMyManager = [[BPManager alloc] init]; }); } return sharedMyManager; } - (void)dealloc { [dbPath release]; [super dealloc]; } When i call the following code when building my interface, the app creates the singleton: BPManager *manager = [BPManager bpManager]; [manager initDatabase:@"database.db"]; Note: At this point i can create references to the class from other files as well. But when i click on a button it seems to loose his references. But when a button is clicked, the following code is ecexuted: BPManager *manager = [BPManager bpManager]; int count = [manager getQuestions]; The app should get the sharedInstance. That works, only the parameters (like dbPath) are not accessible. Why is that? Edit: after some research, i have changed the method to: + (BPManager *) bpManager { @synchronized(self) { if(sharedMyManager != nil) return sharedMyManager; static dispatch_once_t pred; // Lock dispatch_once(&pred, ^{ // This code is called at most once per app sharedMyManager = [[BPManager alloc] init]; }); } return sharedMyManager; } But the problem is not solved A: How about @interface BPManager : NSObject @property (nonatomic, copy) NSString *dbName; @property (nonatomic, assign) int questions; -(id) initWithDBName:(NSString*) dbName { @end #import "BPManager.h" @implementation BPManager @synthesize dbName=_dbName, questions; +(BPManager *)singleton { static dispatch_once_t pred; static BPManager *shared = nil; dispatch_once(&pred, ^{ shared = [[BPManager alloc] initWithDBName:@"database.db"]; }); return shared; } -(id) initWithDBName:(NSString*) dbName { self = [super init] if (self) self.dbName = dbName; return self; } -(void)dealloc { [_dbName release]; [super dealloc]; } @end BPManager *manager = [BPManager singleton]; int count = [manager questions]; The static is private to the implementation file but no reason it should be even accessible outside the singleton method. The init overrides the default implementation with the default implementation so it's useless. In Objective-C you name the getter with the var name (count), not getCount. Initializing a class twice causes an undefined behaviour. No need to synchronize or check for if==nil when you are already using dispatch_once, see Care and Feeding of Singletons. NSString should always use copy instead retain in @property. You don't need the dealloc because this is going to be active forever while your app is running, but it's just there in case you want to use this class as a non singleton . And you probably are as good with this class being an ivar in your delegate instead a singleton, but you can have it both ways. A: I'm not sure whether it's the (complete) answer, but one major flaw is that you're using instance variables (self, super) in a class method, +(id)bpManager; I'm actually surprised it let you compile that at all. Change the @synchronized(self) to @synchronized(sharedMyManager), and the [[super alloc...] init] to [[BPManager alloc...] init]. And, writing that just made me realize that the problem looks like accessing a subclassed method on an object instantiated as the superclass, but that should have been overwritten in the dispatch. Shouldn't you really only need one of those anyway, why double-init like that? (And while we're there, that's a memory leak - init'd in the if() and then overwritten in the closure without releasing it.) A: The solution of Jano must work well. I use this way too to create singleton object. And I don't have any problem. For your code, I think that if you use @synchronized (it's not necessary cause your have dispatch_once_t as Jano said), you should not call return in @synchronized. + (BPManager *) bpManager { @synchronized(self) { if(sharedMyManager == nil) { static dispatch_once_t pred; // Lock dispatch_once(&pred, ^{ // This code is called at most once per app sharedMyManager = [[BPManager alloc] init]; }); } } return sharedMyManager; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7570528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: curl succeeds but wget gives 502 error for a request on custom port $ curl http://localhost:7810/test hello world! $ $ $ wget http://localhost:7810/test --2011-09-27 07:04:06-- http://localhost:7810/test Resolving <snipped> Connecting to <snipped> connected. Proxy request sent, awaiting response... 502 Bad Gateway 2011-09-27 07:04:06 ERROR 502: Bad Gateway. $ It seems that wget is looking at port 80 even though I specified 7810. How can I work around this issue? A: You have a config file, possibly ~/.wgetrc, where a proxy is specified.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Dcu in Delphi XE2 Is the *.dcu files in delphi xe2 for firemonkey application are independent from platforms. here. for both 32bit and 64 bit and other operating systems. If so how is the dcu files are designed. is it something similar to the previous(delphi 1-delphi xe) or something like an intermediate language(like java or .net) is this new dcu going to make the decompilation of dcu files easier. The main intention of this question is to know some details about the pros and cons about the new dcu files for firemonkey. A: Is the *.dcu files in delphi xe2 for firemonkey application are independent from platforms. here. for both 32bit and 64 bit and other operating systems. No they are not; Delphi XE2 generates different .dcu files for different platforms, and .dcu files for each platform are created in separated folders. A: To make it somewhat more insightful, some background info: DCU's are more or less a combination of the following parts * *The object code, which is normal statically compiled relocatable object code, just like what C or C++ would generate. *debug code inclusive (a Topview variant if I'm not mistaken) *A precompiled header(interface) in some form. *unspecialized generics in some representation (*) *cross-unit inlinable code (tree representation?) I don't know if all these 4 are separate sections or that they are interleaved. My guess is that 1+2 are combined (since that allows more generic routines in the linker) and there is a "rest" with 3+4+5 and maybe some other metadata. Since headers might depend on OS specific types and symbols in system unit and OS specific units, even in theory only the most self contained units could be crossplatform. Probably not worth the effort to bother. As far as decompilation goes, it is pretty much the same as the general decompilation problem, with a few twists: * *not yet finally linked (object) code is slightly easier decompilable *code with attached debug code is slightly easier decompilable. *however the DCU format is version dependent and proprietary. *the entire decompilation process is very compiler and -version dependent. In short, it is probably not a bit easier than earlier Delphi compilers or even a static lib + header files of a random C++ compiler.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery getJSON callback can't be a variable I'm trying to create a function which uses the jQuery function getJSON but I'm running in to a problem. The first part of the callback can't be variable, jQuery always interprets it as a string. My code: $(document).ready(function () { function getName(callbackName, callbackVal){ $.getJSON("json_server.php",{callbackName:callbackVal}, function(result){ //Do stuff }); } getName("name", "john"); }); Which results in the following request URL: ".../json_server.php?callbackName=john" instead of ".../json_server.php?name=john" I already tried escaping it but that only results in errors. What am I doing wrong, any suggestions? A: the problem has nothing to do with jQuery. that's how js objects works, the key can be a string or a literal, not a variable A: Construct the object in the following way var x = {} x[callbackName] = callbackVal; $.getJSON("json_server.php",x, function(result){ //Do stuff }); The [] syntax lets you define properties by name. In this case you will assign the value of callbackVal to the property which is named the value of callbackName A: You could just pass an object: function getName(data){ $.getJSON("json_server.php",data, function(result){ //Do stuff }); } getName({"name": "john"}); Or build it in the function like this: function getName(callbackName, callbackVal){ var data = {}; data[callbackName] = callbackVal; $.getJSON("json_server.php",data, function(result){ //Do stuff }); } getName("name", "john");
{ "language": "en", "url": "https://stackoverflow.com/questions/7570536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: why try...catch requires EXACT type thrown I can do this, no problem: long lngval = 3L; int i = lngval; but if I try this: try { throw 3L; } catch(int i) { cout << "caught " << i << endl; } I get an unhandled exception. This seems inconsistent. what is the reason for no type conversion in this case? A: In the first case, the compiler can tell exactly what you want to do: convert a long to an int. In the second case, the compiler has to assume that you might have a construct like this: try { try { throw 3L; } catch (int i) { /* P */ } } catch (long l) { /* Q */ } The idea is that the compiler can never know whether there might be a catch (long l) lurking outside the current context, so it's never safe to just pick the first possible conversion. This is also why it's common to use a class hierarchy when throwing exceptions rather than random types like int or long: it makes it easy to add more or less specification to your exception handlers in such a way that the compiler can be sure of your intentions (via the is-a relationship). A: catch does not necessarily need the exact type. It is common and good practice to use exceptions derived from std::exception (found in <stdexcept>). The reason is that you can then catch polymorphically, i.e. you do not need to know the exact type (see also Difference: std::runtime_error vs std::exception()) and that we have a convention to handle this. Either you use one of the ones provided by the standard (e.g. std::range_error), or if nothing suits your problems [enough], specialize std::exception: #include <stdexcept> class moores_law_stopped : public std::exception { public: virtual ~moores_law_stopped() throw() {} virtual const char *what() const throw() { return "moores law stopped. duck under your table."; } }; #include <iostream> int main () { try { throw moores_law_stopped(); } catch (std::exception const &e) { std::cerr << "oh oh: " << e.what() << std::endl; } } Output: oh oh: moores law stopped. duck under your table. The convention is to catch by reference or const reference, so that you get polymorphic behavior without fearing object slicing. A: The catch statement catches an object (or a scalar variable in your cases) given its type, so if the type mismatch, it passes to the next catch statement (if there is one) or to the default exception receiver. In your case, you could have a second catch statement catching long, and maybe somewhere else, so your catch statement won't catch anything. To catch any exception, just use catch() {} :) A single tip, better use exception class, or subclass it for you own need :) A: You can also throw 3; - no problem. int and long are different types. It's an advantage of the exception handling that you can tell the exceptions apart from looking at their type (one central try block can handle exceptions of various kinds from various places / a try block can handle just some kinds of exceptions, letting others propagate). Also, it is recommended to throw one of the standard exceptions or derive a class from one of those. Then you could just catch (const std::exception&) if you just want to handle the exception and don't care about the particular type. A: You can catch multiple types in one try-catch block. In order for the compiler to know which catch block to throw to, it must be able to match the exact type. Or it can have a default catch block -- catch (...) {}, but you won't be able to get at the value thrown in that case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: List properties of a DependencyObject? I got a collection of custom DependencyObjects that I created. But I think that it doesn't matter wherever the DependencyObject comes from. The thing is that I'd like the list its properties but when I'm looking at the C#doc for DependencyObject I can't find anything related to the properties... :/ How can I do it ? (nb : I got fields (string, int, etcetc..) as properties in my DependencyObject, and I got DependencyProperties too. Ultimatly I'd like to list only the DependencyProperties but it's not an obligation !) Thx in advance and sry for my langage, im french -_- (and sry for my president too...) A: You can do this using reflection, since DependencyProperties are (usually?) stored in public static fields of type DependencyProperty: private static IEnumerable<DependencyProperty> GetDependencyProperties(DependencyObject o) { return from field in o.GetType().GetFields(BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Static) where field.FieldType == typeof(DependencyProperty) select (DependencyProperty)field.GetValue(null); } It uses FlattenHierarchy to return all DependencyProperties, including those defined in parent classes. If you want only DependencyProperties defined directly in os class, remove the FlattenHierarchy flag.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570547", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Have a webpage size grow with an expanding HTML textarea I've seen it on several websites and was wondering if it something that is build in to HTML/DOM or that would have to use JavaScript. I have a re sizable textarea, but I want the webpage to grow as the user grows the text area. Right now, if they expand horizontally, they can only expand the size of the page, then stop, scroll to the right and grow it horizontally a little more. Is there an easy way to allow the page to expand with the textarea? A: With jquery it is as simple as: $("textarea").resizable({ resize: function() { $("body").css('width',YOUR_UPDATE_CALCULATED_WIDTH+'px'); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7570549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Data Validation in MVVM light What is the best way to do data validation. Is it a good practice to do validation in view models or should the validation be done in models? and also, what is the best way to implement numeric(decimal) text-box in WPF with MVVM. I am using MVVM Light toolkit. A: To be able to provide meaningful messages to the user, it is best to make the properties of your ViewModel that should be bound to a TextBox of type string and implement IDataErrorInfo on your ViewModel. In my projects, I am using it like this. I created an interface IValidateable (please forgive the name...) which implements IDataErrorInfo. My ViewModel implements this interface: public interface IValidateable : IDataErrorInfo { ObservableCollection<Tuple<string, ValidationError>> InvalidProperties { get; } bool IsValid { get; } } All my text boxes use the following style: <Style TargetType="{x:Type TextBox}"> <Style.Triggers> <Trigger Property="Validation.HasError" Value="true"> <Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}" /> </Trigger> </Style.Triggers> <Setter Property="Validation.ErrorTemplate"> <Setter.Value> <ControlTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="90*" /> <ColumnDefinition Width="20" /> </Grid.ColumnDefinitions> <Border BorderBrush="Red" BorderThickness="1" CornerRadius="2.75" Grid.Column="0"> <AdornedElementPlaceholder Grid.Column="0" /> </Border> <TextBlock Foreground="Red" Grid.Column="1" Margin="0" FontSize="12" VerticalAlignment="Center" HorizontalAlignment="Left"> * </TextBlock> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> This will show a tool tip if the value entered doesn't conform to my rules. Furthermore, I created a small validation engine which allows to assign rules to the properties of the view model and a base class that automatically validates the property value when a new value is set. The interface members of IValidateable are used to display a meaningful error message to the user when he tries to save an invalid object. A: Implement IDataError Info on the class and that will implement two properties Error and this[string columnName] you can implement the second property with your binding errors that you want public class MainViewModel:ViewModelBase,IDataErrorInfo { public string Error { } public string this[string columnName] { get { string msg=nulll; switch(columnName) { case "MyProperty": //that will be your binding property //choose your validation logic if(MyProperty==0||MyProperty==null) msg="My Property is required"; break; } return msg; } } Also set ValidateOnError=true on the fields A: If you use IDataErrorInfo for Viewmodel validation - DO NOT FORGET the following: if your viewmodel has properties other then typeof string and the input in your view can not be converted to the property type - then your input never reach the viewmodel and so the validation - and the user in front of the view is just thinking: "wtf why i dont see any validation error!"
{ "language": "en", "url": "https://stackoverflow.com/questions/7570550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Why Aren't Deletes Cascading With This NHibernate Configuration File? I have the below NHibernate file, however I am not allowed to delete a Question because of a foreign key constraint on either of the two Answer tables. The desired behavior is to delete Answers once corresponding Questions are deleted and cascade settings are set on the Answers element. Below is the configuration file, can anyone see what the problem is <?xml version="1.0" encoding="utf-8"?> <hibernate-mapping xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" namespace="Test.Domain" assembly="Test.Domain" xmlns="urn:nhibernate-mapping-2.2"> <class name="Question" abstract="true"> <id name="Id" type="Int32"> <generator class="hilo" /> </id> <discriminator /> <property name="Text" length="500" /> <property name="Note" length="2000" /> <property name="DateRun" /> <many-to-one name="ChoiceType" column="ChoiceTypeId" /> <bag name="Answers" inverse="true" cascade="all,delete-orphan"> <key column="QuestionId" on-delete="cascade" /> <one-to-many class="Answer" /> </bag> </class> <class name="Answer" abstract="true"> <id name="Id" type="Int32"> <generator class="hilo" /> </id> <many-to-one name="Question" column="QuestionId" /> <many-to-one name="Group" column="GroupId" /> <property name="Comment" /> </class> <class name="Choice"> <id name="Id" type="Int32"> <generator class="hilo" /> </id> <property name="Text" length="500" /> </class> <class name="ChoiceType"> <id name="Id" type="Int32"> <generator class="hilo" /> </id> <property name="Name" /> <property name="Type" /> <list name="Choices" cascade="all,delete-orphan"> <key column="ChoiceTypeId" /> <list-index column="ChoicesPos" /> <one-to-many class="Choice" /> </list> </class> <class name="Division"> <id name="Id" type="Int32"> <generator class="hilo" /> </id> <property name="Name" /> </class> <union-subclass name="FreeTextAnswer" extends="Answer"> <property name="Text" length="500" /> </union-subclass> <union-subclass name="MultipleChoiceAnswer" extends="Answer"> <many-to-one name="Choice" column="ChoiceId" /> </union-subclass> <subclass name="MultipleChoiceQuestion" extends="Question" /> <subclass name="FreeTextQuestion" extends="Question" /> </hibernate-mapping> A: Isn't it cascade="all-delete-orphan" ... with a hyphen, as opposed to two enum values? A: Your answers collection mapping should look like this: <bag name="Answers" inverse="true" cascade="all-delete-orphan"> <key column="QuestionId"/> <one-to-many class="Answer" /> </bag> I removed on-delete="cascade". When you you want to remove one answer from the question you will have to 'chase pointers'. Set reference to question to NULL, in addition to removing it from answers collection: answer.Question = null;
{ "language": "en", "url": "https://stackoverflow.com/questions/7570561", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a fallback URL using .htaccess and integrate it with other rules I have a directory structure like this... .../htdocs/domain/example/ <==> http://example.com/home/ .../htdocs/domain/example1/ <==> http://example1.com/home/ .../htdocs/domain/example2/ <==> http://example2.com/home/ And I also have a default file area... .../htdocs/domain/default I would like a request for... http://example.com/home/logo.jpg ==> .../htdocs/domain/example/logo.jpg BUT if the file doesn't exist it should return ==> .../htdocs/domain/default/logo.jpg A: Answering my own question... I added this .htaccess file in /htdocs/domain/ RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([a-zA-Z]+)/(.*)$ /default/$2 [L] I basically says if you encountewr a file that isn't found then try in /default I found that I created a recursive issue if I placed the default stuff in /htdocs/domain so I just place those in /htdocs/default
{ "language": "en", "url": "https://stackoverflow.com/questions/7570565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: set text(number) to Edit Field through its setchangelistener Hi I want to accept number in edit field up to two decimal.So I am setting listener to it Then I am checking whether number is two decimal or more and if it is more than two decimal then i am truncating the number and again trying to set the truncated number.But it showing 104 error at this place interestRate.setText(text).My code is interestRate=new EditField(); interestRate.setChangeListener(new FieldChangeListener() { public void fieldChanged(Field field, int context) { String text=interestRate.getText().toString(); code here-- interestRate.setText(text); } }; So my question is whether text can be set from its listener or not A: Looks like you just need to use some condition check in order not to get in an infinite loop: interestRate=new EditField(); interestRate.setChangeListener(new FieldChangeListener() { public void fieldChanged(Field field, int context) { String text = interestRate.getText().toString(); // code here to create a truncated text if (!truncated.equals(text)) { // next time we will not get here // because truncated will be equal to text interestRate.setText(text); } } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7570570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: XMLHttpRequest cannot load I am trying to access resourced from multiple servers using AJAX, and I am running into this problem: XMLHttpRequest cannot load http://first.mydomain.com. Origin http://second.mydomain.com is not allowed by Access-Control-Allow-Origin. With the following code for ( i in domains ) { var url = 'http://'+domains[i]+'/mgmt/json/queue_status.php'; requests[i]=new request(url); break; } function request(url) { var queues = {}; http_request = new XMLHttpRequest(); http_request.open("GET", url, true, 'username', 'password'); http_request.onreadystatechange = function () { var done = 4, ok = 200; if (http_request.readyState == done && http_request.status == ok) { queues = JSON.parse(http_request.responseText); var queuesDiv = document.getElementById('queues'); print_queues(queues, queuesDiv); } } http_request.send(null); } I have added the following to response page being requested. header('Access-Control-Allow-Origin: *'); I have tried explicitly naming the requester too with no success. Thanks PS: The above code I am sure ins't perfect but function fine when only trying to requests the resource of the host server. A: username and password are not allowed in cross origin requests. Throws an INVALID_ACCESS_ERR exception if either user or password is passed as argument and the origin of url does not match the XMLHttpRequest origin. source: http://www.w3.org/TR/XMLHttpRequest2/#the-open-method Just pass the password and username as a get variable instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Policy File Check closes socket I have created a flex app that uses sockets. I published the flex app in a web application that runs on glassfish server. Now from that flex app i create a socket connection to a C# server and start sending/receiving data. The problem is that after i create the socket connection to C# server the flex app first checks the policy file, and after it get's it, it closes the socket, without keep the connection alive. This is my C# server: TcpListener tcpListener = new TcpListener(IPAddress.Parse("172.17.41.211"), 12345); TcpClient tcpclient = tcpListener.AcceptTcpClient(); Socket client = tcpclient.Client; while (client.Available > 0) { int bytes = 0; byte[] m_aBuffer = new byte[1024]; bytes = client.Receive(m_aBuffer, m_aBuffer.Length, SocketFlags.None); String str = Encoding.ASCII.GetString(m_aBuffer, 0, bytes); if (str.StartsWith("<policy-file-request/>")) { sendBytes = Encoding.ASCII.GetBytes("<cross-domain-policy><allow-access-from domain=\"172.17.41.211\" to-ports=\"12345\"/></cross-domain-policy>\0"); client.Send(sendBytes); } } while (client.Connected) { Thread.Sleep(200); sendBytes = Encoding.ASCII.GetBytes("message to client"); client.Send(sendBytes, sendBytes.Length, SocketFlags.None); } Now the flex client looks like: private var socket:Socket = new Socket(); socket.addEventListener(Event.CONNECT, onConnect); socket.addEventListener(Event.CLOSE, onClose); socket.addEventListener(ProgressEvent.SOCKET_DATA, onData); socket.addEventListener(ErrorEvent.ERROR, errorHandler); socket.addEventListener(IOErrorEvent.IO_ERROR, errorHandler); socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, errorHandler); ... socket.connect("172.17.41.211", 12345); ... Now after i create the connection and it gets the policy from server it closes this socket, so to be able to use this connection i have to call again socket.connect("172.17.41.211", 12345)); After i do this, i can use normally the connection. Can someone suggest why this happens and maybe is possible to not have closed the connection ? A: You don't send the policy file through the socket itself. It needs to be on a different channel. For instance, if you connect to some ip/port, by default flash will try to connect to the same ip but on port 843 and look for the master policy file. You can also set it manually using Security.loadPolicyFile(someURL). More information can be found here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Oracle SQL loader Error while loading really huge log files I have a python script which loops through log files in a directory and uses oracle sqlloader to load the log files to the oracle database. the script works properly and even the sqlloader.. But after loading around some 200k records,the loading fails with this exception.. Record 11457: Rejected - Error on table USAGE_DATA. ORA-12571: TNS:packet writer failure SQL*Loader-926: OCI error while uldlfca:OCIDirPathColArrayLoadStream for table USAGE_DATA SQL*Loader-2026: the load was aborted because SQL Loader cannot continue. Specify SKIP=11000 when continuing the load. SQL*Loader-925: Error while uldlgs: OCIStmtExecute (ptc_hp) ORA-03114: not connected to ORACLE SQL*Loader-925: Error while uldlgs: OCIStmtFetch (ptc_hp) ORA-24338: statement handle not executed I am not sure why this is hapenning.. I have checked the data files corresponding to the table's table space and it has auto extend set to true. What else could be the reason? in the "sqlldr" command i have rows=1000 and Direct=True, so it commits for every 1000 records loaded, i have tested by varying this number, still getting same error. sqlldr arisdw/arisdwabc01@APPDEV24 control=Temp_Sadish.ctl direct=true rows=1000 data=C:/_dev/logs/sample/data/mydata1.csv; A: Post your controlfile contents. What version of Oracle are you using? The ORA-42338 error is the one I would focus on. Are you doing any sort of data transformation in your job? Calling functions or similar?
{ "language": "en", "url": "https://stackoverflow.com/questions/7570574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: onClick inside fragment called on Activity i am encapsulating stuff into a fragment at the moment and run into a problem that is hard to google. Inside my fragment are some buttons with onClick attributes but they are called on the Activity rather the fragment from the android system - this makes encapsulating a bit clumsy. Is there a way to have the reflection stuff from onClick to call on the fragment? The only solution to this I see at the moment is not to use onClick in the xml and set click-listeners inside the fragment via code. A: I spoke to some googlers @ #adl2011 - they recognize the problem and perhaps there will be a fix of that in the future. Until then - one should use .setOnClick in the Fragment. A: It works for me Add import: import android.view.View.OnClickListener; Fragment.java ... @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = (ViewGroup) inflater.inflate(R.layout.fragment, container, false); Button mButton = (Button) rootView.findViewById(R.id.button); mButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { } }); return rootView; } A: ISSUE: 1.In XML onClick attribute will call activity's public method. 2.Fragment's public method not called. 3.Fragment reusability. SOLUTION: In Fragment's layout add this to the View. android:onClick="onFragmentViewClick" In each activity the fragment may belong.. public void onFragmentViewClick(View v) { Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.container); if (fragment != null && fragment.isVisible()) { if (fragment instanceof SomeFragment) { ((SomeFragment) fragment).onViewClicked(v); } } } In the Fragment include this method.. public void onViewClicked(View v) { switch (v.getId()) { case R.id.view_id: Log.e("onViewClicked", "yehhh!!"); break; } } A: The problem is that when layout's are inflated it is still the hosting Activity that is receiving the button clicks, not the individual Fragments. I prefer using the following solution for handling onClick events. This works for Activity and Fragments as well. public class StartFragment extends Fragment implements OnClickListener{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_start, container, false); Button b = (Button) v.findViewById(R.id.StartButton); b.setOnClickListener(this); return v; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.StartButton: ... break; } } } Then problem is gone. A: You could have the listener that is being called in the activity forward the call onto a listener in the fragment. You should have a reference to the fragment inside of the FragmentActivity to pass the call on. You will have to cast to call the method or have your fragment implement an interface you define. I know that isn't the best solution but it will work. You could also use the tag of a button to specify the method name to call if you wanted. Hope this helps a bit. A: Try this... @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootView = inflater.inflate(R.layout.activity_ipadditional_users, container, false); FloatingActionButton button7 = (FloatingActionButton) rootView.findViewById(R.id.fab_ip_additional_user); button7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getActivity(), IPAdditionalUsersEdit.class); startActivity(intent); } }); return rootView;
{ "language": "en", "url": "https://stackoverflow.com/questions/7570575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "45" }