text
stringlengths
8
267k
meta
dict
Q: How to improve request time to a WCF Service from Silverlight? I have a Silverlight project in a solution of Silverlight Application. I also have a WCF service hosted in the same solution which exposes some method to the Silverlight app. When I make a call to the service method from Silverlight it takes 4 seconds to reach the service method. Why is it so, and how can I improve this? I have logged time in an object list. I add DateTime.Now object to collection at each step, then I calculate reach time of each step. And I am making the call through Service proxy. A: Are all of your webservices call taking 4 seconds? The first one can be longer because the application is starting, but afterwards, the latency should be limited by the logic of your webservice. Could you use fiddler, firebug or IE Dev tools to better monitor your service calls? A: Basically if you are debugging (which you say you are) there is a massive overhead as DLLs are loaded for the service to run. Open your output window and see how busy your Dev Studio is while starting up the service! The debug environment is not a good indicator of actual performance. * *Refresh your Silverlight app page after running the service once. This will mean Dev studio already has the service DLLs loaded. *Try running your app installed under local IIS to get a better idea of how it will perform, however the only way you will see the real speed issues is to run it from your live site and test the speed there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: IE (again) messes up template, float problem I'm coding my template and everything works and shows well in Chrome and Firefox, but again... Internet Explorer messes the whole thing up. I tried looking for solutions but I'm stuck here. Here is a link to the website. If you can look at it real quick in chrome/firefox and then in IE you know what I mean and maybe you can find the problem. Thanks! Coding is pretty much like this: <div id="leftbox"> left content </div <div id="rightbox"> right content </div> <div id="mainbox"> center content </div> #leftbox {float:left;} #rightbox {float:right} #mainbox {width:xxx; backgroun...} A: I removed the float:right from #rightcolumn and everything "snapped into place". A: Place all #main... blocks into one wrapper. In example #maincolumn don't have floated elements around, so it acts like it is cleared.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Perl how to strip nested bbcode tags? Here is the code: use perl5i::2; my $string = '[size 9]Some larger text. [i]Italic[/i] here.[/size]And [b]bold[/b] text.'; $string =~ s/\[(.+).*?\](.+)\[\/\1\]/$2/gi; $string->say; The result is here: Some larger text. [i]Italic[/i] here.And bold text. Is there a single regex to strip the tags? A: If all you want to do is strip the tags, you don't really need to ensure that the tags match: just remove anything inside square brackets. If checking for nesting really is important, you can simply apply your current substitution repeatedly. A: Do you want to strip all tags? Elements can be nested, but tags can't be nested, so there's nothing to it really. s/\[[^\[\]]*\]//g; A: What about Parse::BBCode? Update: You don't need to output HTML with this module. Try the following instead: #!/usr/bin/perl use strict; use warnings; use Parse::BBCode; my %tags = map { $_ => '%s' } qw( b i u color size font highlight left right center indent email url thread post list img video code php html quote noparse attach bug PGN2 PGN3 threadvb wiki ); my $parser = Parse::BBCode->new ( { tags => \%tags } ); my $string = '[size="9"]Some larger text. [i]Italic[/i] here.[/size]And [b]bold[/b] text.'; my $rendered = $parser->render( $string ); print "$rendered\n"; This way you don't have to parse any text yourself, which is a Good Thing™.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to show running time in terminal? I am using Python for a while and I learned that by some method like timeit() I can estimate the running time of my programe. But, is it any way that when my programe finished in the terminal, it also print out the running time?! (any terminal command do that?!) A: Use the following: $ time your_programm the output is: $ time sleep 1 real 0m1.002s user 0m0.000s sys 0m0.000s showing how much time was spent in kernel and user space and the total time spent. A: The time command does exactly that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SUP101: blackberry I've been following the SUP101 tutorial for both IPhone and Blackberry. http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc01208.0152/doc/html/vhu1236620712162.html I managed to make both work. But, when I tried to launch the SUP101 tutorial for Blackberry on a device I keep getting the following message : SUP101Output: Module 'sup_client_rim' not found. I managed to launch tutorial and simple apps on the blackberry but not SUP101 that have extra jar and COD I think what is happening is that BB plugin for eclipse is not adding the libraries (in the tutorial we have to manually copy the cod files into the simulator) has anybody got an idea how to solve this? or does anybody have a good link on how to test on device? Best regards Jason Rogers A: I have worked on SUP platform for a little longer. I have faced the similar issue. Can u tell me which SUP version you are using and which BB SDK you are build? SO i may able to trace. I have faced the same problem, and after a long trace i found that the Source code i was generating using SUP, was not compatible with the jar file i was using. I have struggled to manage that by checking the jad compatibility and then with various BB SDK versions. Later realized that it was with versions. Also, in build path make sure you are selecting all of the jar files in order and exports and take it one level above the RIM library. Sure it will work. A: I figured this one out after a bit of trial and error The SUP are only used to allow you to compile the project To actually run it on the device, you need to install the .alx files
{ "language": "en", "url": "https://stackoverflow.com/questions/7566495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: li:odd li:even not working I have this piece of code in my Wordpress theme: <script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/jquery.latest.js"></script> <script type="text/javascript"> $(document).ready(function() { $ ('ul li:even').addClass('even'); $ ('ul li:odd').addClass('odd'); }); </script> and in the body part <div id="specs"> <ul> <li><strong>Standby Time</strong> 1100hr</li> <li><strong>Internal Storage</strong> 16GB or 32GBGB</li> <li><strong>Memory Slot</strong> microSD up to 32GB</li> <li><strong>Camera</strong> 8 Megapixel</li> <li><strong>Front Facing Camera</strong> 2 Megapixel</li> <li><strong>Video Camera</strong> Yes, 1080p</li> <li><strong>Camera Flash</strong> 1 x LED</li> <li><strong>Coverage (Band)</strong> Quad</li> </ul> </div> The jQuery doesn't seem to apply odd and even classes. Tried with different versions of jQuery but still nothing. Can someone help me with this problem? A: That should work just fine, but we can also try to rewrite it a bit to also use the best practice of the :even and :odd-selectors according to the jQuery docs: Additional Notes: Because :even is a jQuery extension and not part of the CSS specification, queries using :even cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :even to select elements, first select the elements using a pure CSS selector, then use .filter(":even"). $(document).ready(function() { $('ul li').filter(':even').addClass('even').end() .filter(':odd').addClass('odd'); }); Checklist: * *Is jQuery loaded? (Check you network monitor in Firebug/Chrome) *Do you need the ul filter in the first selector? Selecting on just li would be even more performant since jQuery could utilize getElementsByTagName. A: That jQuery code works just fine. http://jsfiddle.net/V2Nk7/ I'm guessing that jQuery is not being properly included in your page, check the <?php bloginfo('template_url'); ?> is outputing, I would wager that it is causing a malformed URL and the script tag is 404ing. A: its working here http://jsfiddle.net/7ppTM/ make sure jquery is loaded A: Looks like jQuery has either not been loaded correctly or there's a conflict using $ (Prototype?). What does the jQuery <script> line look like when you view source? If it is a library conflict, try changing this line $(document).ready(function() { to jQuery(function($) { Also, as (was) indicated in a comment, you can achieve this effect purely using CSS. See http://reference.sitepoint.com/css/pseudoclass-nthchild A: You've got an unecessary space between $ and the brackets. Try: <script type="text/javascript"> $(document).ready(function() { $('ul li:even').addClass('even'); $('ul li:odd').addClass('odd'); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7566498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Allow any character in URL I want to deliver an URL using Post in HTML/PHP with codeIgniter. So I output my URL's BASE64-Encoded in a hidden field because the URL is crawled from Googles response Page and nearly any character can be in the URL. As I'll only use my website on a local server (it's a SEO tool for my company), I want to enable any character in POST data. I already tried it with $config['permitted_uri_chars'] = '';, but that did not work. I got a 'Disallowed Key Characters' error because the Base64 string contains a =. I'm using CodeIgniter 2 Edit: Fivell's answer was right, thanks. So, for interested people, I took the code from Fivell's link above and wrote a small class for CodeIgniter. To do this, add a file named Base64 to your application/libraries folder and insert this code: <?php class Base64 { function url_encode($url) { $data = base64_encode($url); $data = str_replace(array('+','/','='),array('-','_',''),$data); return $data; } function url_decode($url) { $data = str_replace(array('-','_'),array('+','/'),$url); $mod4 = strlen($data) % 4; if ($mod4) { $data .= substr('====', $mod4); } return base64_decode($data); } } ?> then, you can use it in any controller by loading the library via $this->load->library('base64); and en- or decrypt the url via $this->base64->url_encode($url) or $this->base64->url_decode($url) A: http://www.php.net/manual/ru/function.base64-encode.php#63543 I think that the problem is standart base64 encoding/decoding in php which is not url safe A: This is not a codeigniter issue, base64 is not safe by for POST transfer. I use this pair of function to safely encode/decode the POST data. /** * * Safely encrypts data for POST transport * URL issues * transforms + to spaces * / are param value separators * = are param value separators * * we process the string on reverse * @param string $string */ function my_urlsafe_b64encode($string) { $data = base64_encode($string); $data = str_replace(array('+','/','='),array('-','_','.'),$data); return $data; } /** * * The encoding string had to be specially encoded to be transported * over the HTTP * * The reverse function has to be executed on the client * * @param string $string */ private function urlsafe_b64decode($string) { $data = str_replace(array('-','_','.'),array('+','/','='),$string); $mod4 = strlen($data) % 4; if ($mod4) { $data .= substr('====', $mod4); } return base64_decode($data); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7566500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: TSQL-Join on own table, selecting the latest row only I have a table tbl_Partner (shortened) with two "duplicate" partners: RecordID (GUID) | RISEID (varchar(40)) | UpdateCounter(int) | etc. ... ----------------------------------------------------------- 12345678-9012-3456-7890-123456789012 | RISE123 | 0 87564321-9012-3456-7890-123456789012 | RISE123 | 1 -- other partners with different updatecounters etc. Now I need a view which has the latest data for each partner (highest UpdateCounter) but the first RecordID (lowest UpdateCounter) I tried this SQL already: select (select top 1 recordid from tbl_partner p2 where p2.riseid=p1.riseid order by p2.updatecounter ASC) as RecordID , riseid, updatecounter from tbl_partner p1 order by riseid I get: RecordID (GUID) | RISEID (varchar(40)) | UpdateCounter(int) ----------------------------------------------------------- 12345678-9012-3456-7890-123456789012 | RISE123 | 0 --(old data) 12345678-9012-3456-7890-123456789012 | RISE123 | 1 --(new correct data with the first RecordID) -- other rows/columns omitted How can I select the latest row for each RecordID/RiseID only? (UpdateCounter=1 in this example) For the record: UpdateCounter can be something else than 1 of course and there are other datasets with different values. So I cannot use a simple WHERE updatecounter>0. A: SELECT t1.RecordID,t1.RISEID,t2.UpdateCounter FROM tbl_Partner t1 inner join tbl_Partner t2 on t1.RISEID = t2.RISEID left join tbl_Partner t1_anti on t1.RISEID = t1_anti.RISEID and t1_anti.UpdateCounter < t1.UpdateCounter left join tbl_Partner t2_anti on t1.RISEID = t2_anti.RISEID and t2_anti.UpdateCounter > t2.UpdateCounter where t1_anti.RISEID is null and t2_anti.RISEID is null It's not clear if you want rows to appear for items where only a single row has a particular RISEID. If not, add an extra condition into the join between t1 and t2, such that the UpdateCounter is higher on t2. The two outer joins are to ensure that there is no earlier row than t1 (t1_anti) and no later row than t2 (t2_anti). In the WHERE clause, we ensure that those joins were unsuccessful. Alternate one, using slightly more modern style: ;With OrderedRows as ( Select RecordID,RISEID,UpdateCounter, ROW_NUMBER() OVER (PARTITION BY RISEID ORDER BY UpdateCounter ASC) as rnEarly, ROW_NUMBER() OVER (PARTITION BY RISEID ORDER BY UpdateCounter DESC) as rnLate from tbl_Partner ) SELECT t1.RecordID,t1.RISEID,t2.UpdateCounter FROM OrderedRows t1 inner join OrderedRows t2 on t1.RISEID = t2.RISEID WHERE t1.rnEarly = 1 and t2.rnLate = 1 which may require fewer scans on the table. A: Select Max UpdateCounter select distinct( (select top 1 recordid from tbl_partner p2 where p2.riseid=p1.riseid p2.updatecounter ASC ) )as RecordID,(select Max(updatecounter) from tbl_partner p2 where p2.riseid=p1.riseid ) as MaxUpdateCounter , riseid from tbl_partner p1
{ "language": "en", "url": "https://stackoverflow.com/questions/7566507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I want to know file creation date I have a files list which contain the directory of file. I want to know file creation date of that files. I used fileInof.CreationTime. But It is not displayed creation date. How I can know about this. 'Get file info Dim FileInfoVar As FileInfo = New FileInfo(Server.MapPath("~/Images/A.png")) Dim DateVar as datetime = FileInfoVar.CreationTime It didn't display real creation time. It displays like this 1/1/1611. A: File.GetCreationTime gives you a DateTime object...which is of course a Date and a Time. Reading out the properties of the resulting object should give exactly what you need. Edit: Looking at your editted question I seriously doubt that you are looking at the right file. Did you do a File.Exists first? The result you have now seems a bit weird.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Difference in blocking between sys.log() and console.log() and console.error()? * *Is any one of sys.log(), console.log(), console.error() blocking? (var sys = require("sys");) *How is sys.log() different from console.log(); A: From Firebug Wiki: console.log writes a message to the console. You may pass as many arguments as you'd like, and they will be joined together in a space-delimited line. console.error writes a message to the console with the visual "error" icon and color coding and a hyperlink to the line where it was called. AFAIK they are not blocking. sys.log is not native in the browsers I use. Maybe you can provide more info on that. UPDATE: just noticed your node.js tag... Anyhow, I still don't think any of them is blocking. A: console.error is blocking (it calls sync write in writeError). console.log is non-blocking = process.stdout.write(util.format.apply(this, arguments) + '\n'); sys.log == util.log == puts(timestamp() + ' - ' + msg.toString()); (non-blocking)
{ "language": "en", "url": "https://stackoverflow.com/questions/7566517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: /dev/rfcomm0 goes stale, but I can see Bluetooth device is still sending data I am working with a Bluetooth sensor device on Linux. I use the standard tools to connect to it on a serial port, so: $ sudo rfcomm connect 0 Connected /dev/rfcomm0 to 00:07:80:93:52:3B on channel 1 Press CTRL-C for hangup I have a Java program that reads from /dev/rfcomm0 and processes the data. However, after a while (varying time ~1hr), I can't read any further data, but the device is still connected. I note the following: * *If I open the Bluetooth manager, it shows me that data is still flowing from the device *cat /dev/rfcomm0 shows no output *The connection, still exists. I have to manually close the connection, reconnect and restart my Java app. So essentially, the connection, /dev/rfcomm0, seems to go stale. Is this a simple thing to fix? Will it be my app or is it to do with the serial port? What can the problem be? Many thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7566518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I remove linked library from executable file All. Someone created an executable file. # ldd test_bin libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0x4082d000) libA.so.0 => /usr/lib/libA.so.0 (0x408fe000) libB.so.0 => /usr/lib/libB.so.0 (0x4093e000) libgobject-2.0.so.0 => /usr/lib/libgobject-2.0.so.0 (0x409ad000) libgthread-2.0.so.0 => /usr/lib/libgthread-2.0.so.0 (0x409fe000) librt.so.1 => /lib/librt.so.1 (0x40a0a000) libglib-2.0.so.0 => /usr/lib/libglib-2.0.so.0 (0x40a19000) libdbus-1.so.3 => /usr/lib/libdbus-1.so.3 (0x40b25000) libssl.so.0.9.8 => /usr/lib/libssl.so.0.9.8 (0x40b67000) libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x40bb0000) libpthread.so.0 => /lib/libpthread.so.0 (0x40bc3000) libc.so.6 => /lib/libc.so.6 (0x40be3000) libm.so.6 => /lib/libm.so.6 (0x40d11000) libcrypto.so.0.9.8 => /usr/lib/libcrypto.so.0.9.8 (0x40d87000) /lib/ld-linux.so.3 (0x40000000) libgmodule-2.0.so.0 => /usr/lib/libgmodule-2.0.so.0 (0x40f4e000) libdl.so.2 => /lib/libdl.so.2 (0x40f59000) In this case, I want to merge libB.so into libA.so. So I create libA.so that is covered all APIs provided by libB.so. Then I have to re-link with this library. But I don't have any source for test_bin. How can I remove libB.so linking from executable file without any sources? Is it possible? I just look around binutils. But I haven't found for it. Please give me an advice. A: You could go the easy route and make libB.so and libB.so.0 a symlink to libA.so.0. Doesn't modify the executable, but is a quick and portable solution. A: I don't think it is possible, because even when you make libA.so wrap libB.so (what you described as covers), libA.so still depends on the functions of libB.so, so both have to be linked to your executable. The only workaround that I know it's what @thiton proposed or make libA.so implement libB.so without depending on it, i.e., implement all functions of libB.so or only the ones you need. A: edit executable and replace libA.so.0 with libB.so.0 this works because sizeo of "libA.so.0" is the same as sizeo of "libB.so.0". If u add or remove extra symbol it will break executable for sure.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to call external server page with PHP that includes JS? There is a website which includes a JS code. Normally, when the page is opened by a user this JS code starts manually and provides a link about 10 seconds. I am trying to catch this link. In PHP, I call this page with file_get_contents function, however as you predict link is not there. Is there any way to make a HTTP request to this page and wait until javascript code started. Or can I invoke this JS function by using JQuery maybe? If the question is not clear, I can provide more details. Thanks in advance. A: I'd suggest looking into the javascript on the page and reverse-engineer how the link is dynamically generated. Then you can use regex to extract that info from the string returned by file_get_contents. I can probably help you on the reverse-engineering if you can provide extra information on the page in question (or similar). UPDATE: After some reversing, I found that the mp3 ripper site uses 2 api's: one to push a video to get processed, and one to poke at the current status. First api: http://www.youtube-mp3.org/api/pushItem/?item=http%3A//www.youtube.com/watch%3Fv%3DXXXXXXXX&xy=trve Second api: http://www.youtube-mp3.org/api/itemInfo/?video_id=XXXXXXXX&adloc= XXXXXXXX is the youtube video id. The 2nd api returns JSONP where the padding is a variable assignment (info = {...};). In the json, there's a "h" member that returns a long hash which can be used to ultimately construct the mp3 download file link. But to be a bit ethical, may I suggest looking into another approach (if allowed by your hosting environment)? You can use FFmpeg to convert the video on your own. There's a wrapper class here: YouTube-to-MP3 conversion class A: Javascript is executed on the client and needs an interpreter to execute it. Your PHP server executing HTTP request calls won't interpret any javascript, it will simply just retrieve the HTML. You could use some software like HtmlUnit to make the request and execute the javascript, and then see if you can extract the link after it has finished executing. This will depend on how much access you have to the server you are executing your PHP on. Or you could study the JS files used by the website you are targeting, determine how it is requesting that link and see if you can just get it directly yourself. Bear in mind you are directly working around how the site is intended to work, so this isn't going to be a particularly elegant solution and a single change in their JS could cause your application to fail. This is fair enough as they might have this very process in place to stop people from being able to harvest the links in the manner you are describing. A: file_get_contents only fetches the HTML source of the URL requested, it does not execute the javascript code for you nor simulates the dom with all it's events. The short answer would be, that this can not be easily done. One thing you could do is to parse the source and look for the link in there, like Dave suggested.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to convert string into datetime Using VB.Net When i click the gridview column, that selected column items should appear in the datetime picker GridView Column value is string, datetime picker datatype is datetime Code Private Sub gridview1_CellContentDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles gridview1.CellContentDoubleClick Dim i As Integer i = gridview1.CurrentRow.Index Dim dt As String = gridview1.Item(1, i).Value datetimepicker1.value = CDate(dt) End Sub When i clicked the gridview column, it is showing error as "Conversion from string "25/09/2011" to type 'Date' is not valid" How to solve the above problem Need VB.Net Code Help.... A: This problem is related to locale settings in that the CDATE() function expects date values to be provided in the following format: MM/DD/YYYY (MM = Month, DD = Day, YYYY = Year). This means the code fails in the UK which is DD/MM/YYYY. Passing 25/09/2011 is translated to: * *Month = 25 *Day = 09 *Year = 2011 If the value you're using is a string you'll need to parse the string value to extract the correct values before passing it to the CDate() function: Private Sub gridview1_CellContentDoubleClick(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) _ Handles holidaygrid.CellContentDoubleClick textbox1.Text = DateTime.ParseExact( _ gridview1.Item(1, gridview1.CurrentRow.Index).Value, _ "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString() End Sub A: If you know which date format to expect in advance, use DateTime.ParseExact, e.g.: datetimepicker1.Value = DateTime.ParseExact(dt, "dd/MM/yyyy", CultureInfo.InvariantCulture)
{ "language": "en", "url": "https://stackoverflow.com/questions/7566531", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: When changing schemas must I update the receive pipeline component? There was a failure executing the receive pipeline: Reason: No Disassemble stage components can recognize the data. I had some sort of automate generated schema (.xsd) and needed to add two columns and added those manually. Then I updated the dll:s: schema, map and pipeline. What's wrong? A: If you have increased the version number on your Schemas assembly, or changed the XML#NS root of your schema, then you will need to update your pipeline. Also, try deleting the generated .cs files, rebuild all from scratch, and remember to restart your host process(es). A: I'm assuming that your testing your pipeline with some test message using a FILE adapter (what I typically do!). So, in addition to nonnb's suggestions, ensure that the message you are sending through the receive pipeline also has these two new columns - otherwise the validation of the incoming message will fail (as the schema you've set in the pipeline isn't conformed to by the message) HTH
{ "language": "en", "url": "https://stackoverflow.com/questions/7566533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Shockwave Adobe Flash Player - get video duration in javascript I have a flash video and a embed code which display it. I want to get the video duration in javascript. Is it possible? Embed code is like this: <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="550" height="400" id="myFlashMovie" align="middle"> <param name="movie" value="myFlashMovie.swf" /> <param name=FlashVars value="myVariable=Hello%20World&mySecondVariable=Goodbye"> <!--[if !IE]>--> <object type="application/x-shockwave-flash" data="myFlashMovie.swf" width="550" height="400"> <param name="movie" value="myFlashMovie.swf" /> <param name=FlashVars value="myVariable=Hello%20World&mySecondVariable=Goodbye"> <!--<![endif]--> <a href="http://www.adobe.com/go/getflash"> <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /> </a> <!--[if !IE]>--> </object> <!--<![endif]--> </object> Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/7566535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: error in file input hi guys this error is rendered when i submit my form this error is File 'captured_photo' exceeds the defined ini size i made a trial to change the php.ini to 10M but still has the error $uploaded_photo = $this->createElement('file', 'uploaded_photo') ->setLabel('upload image 2:') ->addFilter(new Zend_Filter_HtmlEntities()) ->addFilter(new Zend_Filter_StripTags()) //->setMaxFileSize(10 * 1024 * 1024) ->addFilter("StringTrim"); //->setRequired(TRUE); $this->addElement($uploaded_photo); A: There are several configuration directives that affect file uploads. They are * *upload_max_filesize *post_max_size (must be larger than upload_max_filesize)
{ "language": "en", "url": "https://stackoverflow.com/questions/7566537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there any difference in following 2 jquery code snippet? Is there any difference in following 2 jquery snippet? Both gives same output but does any one have any advantage over other or they are just one's choice to write like this to do the thing. Snippet 1: div = $("#myDiv"); div.append("<ul>"); $.each(cobj, function(k,v) { div.append("<li><span class='"+v+"'>"+k+"</span></li>"); }); div.append("</ul>"); Snippet 2: $("<ul>").attr("id", "myUL").appendTo("#myDiv"); $.each(cobj, function(k, v) { var li = $("<li>"); $("<span>").text(k).attr("class",""+v}).appendTo(li); li.appendTo("#myUL"); }); A: Both are not good ways to manupulate the DOM tree in terms of performance. I would suggest the following: var ul = $("<ul id='myUL'>"); $.each(cobj, function(k,v) { ul.append("<li><span class='"+v+"'>"+k+"</span></li>"); }); $("#myDiv").append(ul); In this way, browser does not re-render page after each li is appended, the entire list is build offline and then appended with single call. A: In 1 the UL has no ID, whereas in 2 it has ID="myUL"
{ "language": "en", "url": "https://stackoverflow.com/questions/7566539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: files related to process core dump creation in linux kernel just need to look for process core dump creation in linux kernel. Can anybody please point me out what files to see for x86. Specifically, i'll be looking for if the procedure can be tweaked to pass on certain information via proc file system from the user process. The result will be a core dump file which may contain certain additional info. Thanks, Kapil upadhayay A: Core dump generation is in function do_coredump. For setting things via proc filesystem, see how other parameters to that function like core_pattern (search for variable of that name) are implemented.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does google map use Canvas to make distance measurement not SVG? I use chrome debug tool to compare google map and other maps. I found for the distance measurement function, google map use canvas to draw the path and some others use SVG. I assume that maybe this is because canvas is faster. But SVG have many good parts for drawing the path. Is there any other reasons? A: Every SVG element is a DOM element and having 10,000+ SVG paths causes a massive slowdown compared to Canvas. So one possibility is the performance of it. But originally Android did not render/support SVG. That's probably the real reason why Google chose to use Canvas. Today, Tablet Android (3.0+) has SVG support but 1.0-2.3 do not.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566547", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Actor-based distributed concurrency libraries for Ocaml and other languages Question Can anyone recommend a library for Ocaml that offers an actor-based concurrency model for distributed computing? Note here the "actor-based" and "distributed" - I'd like the actor-based model, but also I want seamless handling of distributed actors - I don't want to write the protocol to talk to them. The library should ideally also offer standard patterns such a supervisor trees and so on. Motivation I love Erlang concurrency model and ability to transparently deal with distributed processes and local processes together. However, I find Erlang's syntax to be rather limiting and would like a much more expressive language. I'm considering moving from Erlang to either Scala or Ocaml. I know Scala has the Akka library which seems to offer a nice Scala version of Erlang's concurrency model. I'd like to see what is available on the Ocaml side. Aside I'd also be happy to hear about actor-based concurrency libraries for other languages (particularly C++, Haskell, Python and Ruby). A: You can take a look at parvel -- message passing library/framework for ocaml. It's not yet complete, but already includes some primitives for programming with actors. A: "I'm considering moving from Erlang to either Scala or Ocaml." You should consider scalang, which allows you to program in Scala, but use Erlang's actors. I recently saw a talk on the language by @moonpolysoft (Cliff Moon) at the Strange Loop conference. Cliff Moon developed it for https://boundary.com/ and open-sourced it earlier this year. A: You'll probably spend a lot of time reading about: Scala and F# have akka and MailboxProcessor which are being used in production apps (note: Scala actors and, I think, akka, are very tied to Hotspot; I'm not sure if MailboxProcessor can be used under MONO) Haskell has userspace threads and at least 1 actor implementation which i don't know a lot about For ML and ocaml, some libs which are probably not widely used: poly/ML and oc4mc and netmulticore A: While it may not be the exact same model that Erlang uses, you might want to take a look at JoCaml, which is based on the join calculus. A: Although, it is a very old question things have changed since it was asked. C++ has an actor model implementation which is quite robust. It also provides distributed computing features as asked by OP. The homepage is at http://actor-framework.org/ Further, it can also make us of OpenCL for HPC the module for which is located at github in one of the repositories.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: event to identify Call Answering In Android Hi i am developing call recording application. I want to know call answering event. For example if the user lift the call then i have to start recording. How to know whether he answered a call or not A: http://peacemoon.wordpress.com/2009/08/06/android-listening-to-incomingoutgoing-phone-calls/ case TelephonyManager.CALL_STATE_OFFHOOK: //CALL_STATE_OFFHOOK; // do ur work here(after receiving call) break; A: You need to create a BroadcastReceiver and listen for the TelephonyManager events. ACTION_PHONE_STATE_CHANGED is the one you should listen.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: why "int main(anything_you_type)" doesnt produce any error? Here I have written my name in main argument declaration but still this program works and did not give any warning. #include <stdio.h> int main(Mr32) { printf("why this works?"); return 0; } Whenever I write anything in place of mr32 , The code still works. I really don't know why this is happening. As per C programming standard this is wrong, right? Edit : I have tried -Wall but it does not give any warning. I think here it should be error, because i am not doing as standard C function definition declaration In c every function definition must follow this format return-type function_name ( arg_type arg1, ..., arg_type argN ); This should also appy to main() right ..?? Okay -Wextra shows warning that mr32 is by default int. Then why is the default type of any argument in main() an int? A: In the K&R C definition a parameter without type defaults to int. Your code then corresponds to int main( int Mr32 ) { printf("why this works?"); return 0; } Take a look at this answer for the details: C function syntax, parameter types declared after parameter list Update To summarize: in C89 K&R declarations are still supported * *undeclared parameter types default to int void foo( param ) defaults to void foo( int param ) *unspecified return types default to int foo() defaults to int foo() Note Although this is supported I would never use it: code should be readable A: Obviously you are using a rather lax compiler. This is what the standards king Comeau makes of it: Comeau C/C++ 4.3.10.1 (Oct 6 2008 11:28:09) for ONLINE_EVALUATION_BETA2 Copyright 1988-2008 Comeau Computing. All rights reserved. MODE:strict errors C99 "ComeauTest.c", line 2: error: standard requires that parameter "Mr32" be given a type by a subsequent declaration ("int" assumed) int main(Mr32) ^ 1 error detected in the compilation of "ComeauTest.c". In strict mode, with -tused, Compile failed Hit the Back Button to review your code and compile options. Compiled with C++0x extensions enabled. As to what your compiler is doing that's hard to say since you didn't say what your compiler is. You say you wish to adhere to C89. In that case a parameter with no type information is assumed to have type int. Your main function is interpreted like this: int main(int Mr32) Of course this is still not valid C. Valid main functions in C are: int main(void) int main(int argc, char* argv[]) A: Since this appears to be code for a hosted program, the code is not valid C, unless the specific compiler has documented the behavior of "Mr32". To have a main() function that accepts other parameters than (void) or (int argc, char *argv[]) is implementation-defined behavior (C99 5.1.2.2.1). So if there isn't any documentation about what "Mr32", is supposed to do, the compiler does not follow the standard. Or more specifically, there needs to be documentation of what the int main(int) syntax is supposed to do on this compiler. This is true regardless of K&R style function parameters. I believe the standard is the same for C89, C99 as well as all C++ standards. According to the foot note 9) in the standard, it is acceptable to have another int not named argc, or a typedef equivalent to an int. But in that case there must be a second parameter of type char** as well, which isn't the case here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Help parsing text file in python Really been struggling with this one for some time now, i have many text files with a specific format from which i need to extract all the data and file into different fields of a database. The struggle is tweaking the parameters for parsing, ensuring i get all the info correctly. the format is shown below: WHITESPACE HERE of unknown length. K PA DETAILS 2 4565434 i need this sentace as one DB record 2 4456788 and this one 5 4879870 as well as this one, content will vary! X Max - there sometimes is a line beginning with 'Max' here which i don't need There is a Line here that i do not need! WHITESPACE HERE of unknown length. The tough parts were 1) Getting rid of whitespace, and 2)defining the fields from each other, see my best attempt, below: dict = {} XX = (open("XX.txt", "r")).readlines() for line in XX: if line.isspace(): pass elif line.startswith('There is'): pass elif line.startswith('Max', 2): pass elif line.startswith('K'): pass else: for word in line.split(): if word.startswith('4'): tmp_PA = word elif word == "1" or word == "2" or word == "3" or word == "4" or word == "5": tmp_K = word else: tmp_DETAILS = word cu.execute('''INSERT INTO bugInfo2 (pa, k, details) VALUES(?,?,?)''',(tmp_PA,tmp_K,tmp_DETAILS)) At the minute, i can pull the K & PA fields no problem using this, however my DETAILS is only pulling one word, i need the entire sentance, or at least 25 chars of it. Thanks very much for reading and I hope you can help! :) K A: * *You are splitting the whole line into words. You need to split into first word, second word and the rest. Like line.split(None, 2). *It would probably use regular expressions. And use the oposite logic, that is if it starts with number 1 through 5, use it, otherwise pass. Like: pattern = re.compile(r'([12345])\s+\(d+)\s+\(.*\S)') f = open('XX.txt', 'r') # No calling readlines; lazy iteration is better for line in f: m = pattern.match(line) if m: cu.execute('''INSERT INTO bugInfo2 (pa, k, details) VALUES(?,?,?)''', (m.group(2), m.group(1), m.group(3))) Oh, and of course, you should be using prepared statement. Parsing SQL is orders of magnitude slower than executing it. A: If I understand correctly your file format, you can try this script filename = 'bug.txt' f = file(filename,'r') foundHeaders = False records = [] for rawline in f: line = rawline.strip() if not foundHeaders: tokens = line.split() if tokens == ['K','PA','DETAILS']: foundHeaders = True continue else: tokens = line.split(None,2) if len(tokens) != 3: break try: K = int(tokens[0]) PA = int(tokens[1]) except ValueError: break records.append((K,PA,tokens[2])) f.close() for r in records: print r # replace this by your DB insertion code This will start reading the records when it encounters the header line, and stop as soon as the format of the line is no longer (K,PA,description). Hope this helps. A: Here is my attempt using re import re stuff = open("source", "r").readlines() whitey = re.compile(r"^[\s]+$") header = re.compile(r"K PA DETAILS") juicy_info = re.compile(r"^(?P<first>[\d])\s(?P<second>[\d]+)\s(?P<third>.+)$") for line in stuff: if whitey.match(line): pass elif header.match(line): pass elif juicy_info.match(line): result = juicy_info.search(line) print result.group('third') print result.group('second') print result.group('first') Using re I can pull the data out and manipulate it on a whim. If you only need the juicy info lines, you can actually take out all the other checks, making this a REALLY concise script. import re stuff = open("source", "r").readlines() #create a regular expression using subpatterns. #'first, 'second' and 'third' are our own tags , # we could call them Adam, Betty, etc. juicy_info = re.compile(r"^(?P<first>[\d])\s(?P<second>[\d]+)\s(?P<third>.+)$") for line in stuff: result = juicy_info.search(line) if result:#do stuff with data here just use the tag we declared earlier. print result.group('third') print result.group('second') print result.group('first') A: import re reg = re.compile('K[ \t]+PA[ \t]+DETAILS[ \t]*\r?\n'\ + 3*'([1-5])[ \t]+(\d+)[ \t]*([^\r\n]+?)[ \t]*\r?\n') with open('XX.txt') as f: mat = reg.search(f.read()) for tripl in ((2,1,3),(5,4,6),(8,7,9)): cu.execute('''INSERT INTO bugInfo2 (pa, k, details) VALUES(?,?,?)''', mat.group(*tripl) I prefer to use [ \t] instead of \s because \s matches the following characters: blank , '\f', '\n', '\r', '\t', '\v' and I don't see any reason to use a symbol representing more that what is to be matched, with risks to match erratic newlines at places where they shouldn't be Edit It may be sufficient to do: import re reg = re.compile(r'^([1-5])[ \t]+(\d+)[ \t]*([^\r\n]+?)[ \t]*$',re.MULTILINE) with open('XX.txt') as f: for mat in reg.finditer(f.read()): cu.execute('''INSERT INTO bugInfo2 (pa, k, details) VALUES(?,?,?)''', mat.group(2,1,3)
{ "language": "en", "url": "https://stackoverflow.com/questions/7566551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Convert string date to system datetime in C# I want to convert string date to system datetime in C#. The user enters date through textbox and it should be converted as to datetime. I trid following code but its not working... DateTime ToDate = Convert.ToDateTime(txtToDate.Text); DateTime FromDate = DateTime.Parse(txtFromDate.Text); It shows the following exception "String was not recognized as a valid DateTime." How to do this...??? A: whatever user enters in your textbox that should be in valid date format, otherwise write your own function to make it in valid format. then Convert it into DateTime format . for different format you can check this : http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx for more help you can check similar question on this site : Validate a DateTime in C# A: You could use DateTime.ParseExact(). That way you can specify the format of the input string, so it will be parsed correctly, for example: dateString = "Sun 15 Jun 2008"; format = "ddd dd MMM yyyy"; try { DateTime result = DateTime.ParseExact(dateString, format, CultureInfo.CurrentCulture); } catch (FormatException) { } A: Ask the user to enter his datetime in a particular format into textbox i.e., either "ddMMyyyyhhmmss" or "dd/MM/yyyy hh:mm:ss tt" or "dd-MM-yyyy hh:mm:ss tt" or some other formats and use the help of following code to convert in to a Valid datetime. DateTime ToDate = DateTime.ParseExact(txtToDate.Text, <User DateTime format as String>, System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None) Instead, if the above coding makes complicated then you can try DateTime.TryParse() also A: You can of course parse the user's input and rely on the users to always enter a correct date. But I'd recommend to use a specific control for entering a date, such as the calendar control of the ajax control toolkit. By using such a control, you can prevent invalid input and it's also much easier for the user. If you search for DatePicker or similar, I'm sure you can find lot's of other similar controls. A: First of all you have to validate text box value that it is valid or not, you can use ajax MaskeditExtender control for that and restrict the use enter only require date formate. A: DateTime dt = Convert.ToDateTime(date); here date is in string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it necessary to always Select()... new{Anon}... AsEnumerable...Select(new EntityType{}) every time? I keep running into a pattern whereby I want to select rows from an Entity Collection (EF4) and use the data to create new rows in a different entity collection. The only way I have found to do this is to perform the following steps: var newEntities = (from e in myentities where e.x == y select new { Prop1 = e.Prop1, Prop2 = e.Prop2+e.Prop3, Prop3 = DateTime.Now, Prop4 = "Hardcodedstring"} ) .AsEnumerable() .Select(n=>new OtherEntity{ Prop1 = n.Prop1, Prop2 = n.Prop2, Prop3 = n.Prop3, Prop4 = n.Prop4} ); //insert into database and save If I try to create a new OtherEntity in the select then I get an EF exception. Is this the only way to proceed? Makes the whole thing very cumbersome and seems a complete waste of keystrokes? A: I suggest using Automapper to map from your entities to your domain objects instead of doing the mapping from within the linq query. A: No, that's the only way. Until you run AsEnumerable, ToList, etc. the only methods you can call are methods that are mapped by Entity Framework to SQL syntax. Since the constructor of OtherEntity is not mapped to anything, this is impossible to call it within an Entity context. A: my favorite solution for this is to create a Convertor class, that takes Source parameter (either list or single object) and transfer it (create new instance and assign values to it) to the destination class type List<OtherEntity> lst = Convertor.ConvertToOtherEntity(newEntities );
{ "language": "en", "url": "https://stackoverflow.com/questions/7566555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Any tool to help writing programing article with MS Office Word All! When I use MS office 2010 Word to write an article about Java, I always need to embed some Java code into the document. I wonder whether there is such a plugin for Word, or another software tool, that can help me do such a job. Especially features on code formatting and keywords highlighting are welcome! A: There are several ways to get syntax highlighted text in Word. Here are some I know: Eclipse + OpenOffice Writer (Word should do this as well) * *Mark and copy a code section in Eclipse *Paste into Writer (Ctrl+Shift+V) or Word (Ctrl+Alt+V) as HTML or RTF text Using Notepad++ * *Paste the code section to Notepad++ *Select the appropriate syntax highlighting *Use the NppExport Plugin to export to a RTF file *Open the file with Word A: http://www.ifcx.org/wiki/Wings.html will let you embed live code and execute it in a document, but it requires open office and some plugins. A: There is also Highlight, which can export to multiple formats (including HTML, RTF and even SVG!), and has many themes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JSF 2.0,partially rendered form field input value not updated in the bean I have an Edit product form which is pre-populated with values from DB . User can change one or more values and post the form back. One input field called t:inputFileUpload is rendered only after an ajax request ,if the user opts to change product image.During the final postback of the edit form through a save button,the bean is not updated with the value of t:inputFileUpload field.The relevant portion of the form is below: <h:form> <tr> <td>Product Image*:</td> <td> <h:graphicImage url="#{addItem.prodFileName}" width="100" height="100"/> <br /><h:commandLink value="change image" > <f:ajax render="uploadimage" execute="@this" listener="#{addItem.ChangeImage}"/> </h:commandLink> </td> </tr> <tr > <td> <h:panelGroup id="uploadimage"> <t:inputFileUpload rendered="#{addItem.editImgChange}" label="editImage" value="#{addItem.uploadedFile}" /> <h:messages for="prodimage"/> <h:inputHidden id="hiddeneditimgchange" value="#{addItem.editImgChange}" /> </h:panelGroup> </td> </tr> <h:commandButton value="save" action="#{addItem.EditItem}" /> </h:form> The AddItem bean is request scoped and the relevant part of its code is : @ManagedBean public class AddItem extends AbstractBean{ boolean editImgChange; private UploadedFile uploadedFile; //.. //getters and setters public void ChangeImage(){ this.editImgChange=true; } public String EditItem() { //some logic } } I have read a few similar questions some of whose answers were to make the bean viewscoped.I have tried making the bean ViewScoped ,but it breaks my initial logic of prepopulating the form values. Since i am happy with RequestScoped , I have saved the state of the editImgChange flag ,if its turning off is affecting the updation of the t:inputFileUpload . When i looked at the bean properties all is fine ,the flag is true , but the uploadedFile property is null. A: As per the comments, you used <h:inputHidden value="#{addItem.editImgChange}" /> to save the state. This is not going to work. The rendered attribute is evaluated during apply request values phase, while that hidden value is made available during update model values phase which is thus too late. Since you're already using Tomahawk, use <t:saveState value="#{addItem.editImgChange}" /> instead. Or, just fix the problem which you encountered when making the bean view scoped. I don't forsee why that would be a problem. Perhaps you're using @PostConstruct and expecting that it's invoked on every request. You should then use <f:event type="preRenderView"> instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: dojo.declare: unknown base class - dojo.Stateful So I'm learning Dojo and seeing what I can do with it - I do apologise if this is a stupid question but I can't find a solution. My code: dojo.require("dojo.Stateful"); dojo.declare('W.Model',dojo.Stateful,{ foo:'bar' }); The error: Uncaught Error: declare W.Model: unknown base class. Did you use dojo.require to pull it in? I did use dojo.require to pull it in. What am I missing? Edit - console.log(dojo.Stateful); returns undefined. I am using Google to hot Dojo for me - here: <script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6.0/dojo/dojo.xd.js"></script> Other classes are loading fine, just dojo.Stateful is a problem. A: Do you have the full class declaration in a separate file? Or is this all inline on a page? If you are doing it inline, wrapping the class until the page has loaded will fix the problem: dojo.require("dojo.Stateful"); dojo.ready(function() { var x = new dojo.Stateful(); console.log(x); dojo.declare('some.class', dojo.Stateful, { 'x':'y' }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7566562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trigger the second jquery calendar I have two jquery calendars in my page( #from and #to). My question is how to popup the second calendar("#to"), after selecting the date in first calendar ("#from") popup. Thanks in advance. A: You need to call .datepicker( "show" ) function in onSelect function $( "#from" ).datepicker({ onSelect: function( selectedDate ) { $("#to").datepicker( "show" ); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7566563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: is it possible to access cross site POST method in Extjs4 i try with this code it is possible to access get method but i wont to access post method so how can i do that Ext.define('User', { extend: 'Ext.data.Model', fields: ['id', 'name', 'email'] }); var store = Ext.create('Ext.data.Store', { model: 'User', restful:true, proxy: { type: 'jsonp', url: 'http://localhost:8080/testapp/userreg', callbackKey: 'Callback' }, headers: { 'Content-type': 'application/json', 'Accept': 'application/json' } }); store.load(); is there any way to post cross site data in extjs4 A: If you mean that you want to post data cross-domain...no, you can't. I know that with the new Javascript Api's (XMLHttpRequest2) it can be done but I don't know if that is an option for you right now. A: try use jquery $.ajax({ type: 'POST', url : urlServer+'/ws/Login/', xhrFields: { withCredentials: true }, scope: this, dataType: 'json', data:values, timeout: 10000, success: function(result, request) {
{ "language": "en", "url": "https://stackoverflow.com/questions/7566564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a way to apply a refactoring script just for its side-effects? I've got a library that was changed to introduce a factory method to replace a constructor (the reasons aren't important right now, in the current case it was for improved type inference mostly). Assuming that there is an Eclipse refactoring script for it (so I pretty much have a nice computer-readable description of the change), is there some way to apply that script to a project that only uses that library (i.e. it only has a reference to a compiled version of the library)? For example, I start with this simple class: public class MyContainer<T> { private final T content; public MyContainer(final T content) { this.content = content; } public T getContent() { return content; } } Now I introduce a factory (without making the constructor private, but that isn't really relevant right now), the factory method looks like this: public static <T> MyContainer<T> holding(T content) { return new MyContainer<T>(content); } When I now export a migration script it looks like this: <?xml version="1.0" encoding="UTF-8"?> <session version="1.0"> <refactoring comment="Introduce factory &apos;holding&apos; in &apos;scratch.MyContainer&apos; for constructor &apos;scratch.MyContainer.MyContainer()&apos;&#x0A;- Original project: &apos;scratch&apos;&#x0A;- Original element: &apos;scratch.MyContainer.MyContainer()&apos;&#x0A;- Factory name: &apos;holding&apos;&#x0A;- Owner class: &apos;scratch.MyContainer&apos;" description="Introduce factory for &apos;MyContainer&apos;" element1="/src&lt;scratch{MyContainer.java[MyContainer" flags="589830" id="org.eclipse.jdt.ui.introduce.factory" input="/src&lt;scratch{MyContainer.java" name="holding" project="scratch" protect="false" selection="89 0" version="1.0"/> </session> This should hold enough information to apply the refactoring to another project that references (a current version) of the class via a jar file. But trying to apply the refactoring gives me this error: The refatoring 'Introduce Factory' (org.eclipse.jdt.ui.introduce.factory) cannot be performed, since its input 'scratch.MyContainer.java' does not exist. Note that it explicitly mentions .java, so it's looking for a source file and isn't content with applying the refactoring to the binary type. Note: I don't want to patch the binary library. I just want the callers of the original constructor to be converted to calling the factory method instead. Note 2: Search-and-replace won't help in my specific case. The reason is that I have two constructors, one taking an Object and the other takes a String. They should be mapped on two different factory methods, so I'd need the search-and-replace function to look at the type information of the argument as well. Note 3: even a way to manually specify "replace instantiations of object X with this constructor with calls to this method instead" would be appreciated. Update: There is a bugzilla entry on the Eclipse bugzilla that is about adding a replace invocation refactoring. An implementation of that feature might be able to solve my problem, if "invocation" includes object instantiation via a given constructor. Unfortunately it saw no activity in the last few years (although it was planned for 3.2). A: This is not a way to apply refactoring to callers only but it may get you past your problem. Would it be possible to add to your project a fake MyContainer.java file that has the same signatures as that in the library, apply your refactoring and then discard the java file? You could even use decompiled soure, though you might have to generify it yourself. A: I think you will have to write your own refactoring plugin. The tests for org.eclipse.jdt.ui.tests.refactoring are an interesting place to start. Some interesting reads on the topic: * *http://www.eclipse.org/articles/article.php?file=Article-Unleashing-the-Power-of-Refactoring/index.html *http://www.eclipse.org/articles/Article-LTK/ltk.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7566565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Android NDK and ALSA Hello I have a library that is compiled under the Android NDK. This library for audio uses ALSA. Question - is it possible to play audio in Android through the ALSA? If so, whether it is necessary for this to compile ALSA for NDK? A: There was alsa-lib project in external in android sources. Android itself uses ALSA for playing audio. Android sources are not browsable just now (404).
{ "language": "en", "url": "https://stackoverflow.com/questions/7566568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to continuously monitor the directory using dnotify /inotify command I am new to dnotify/inotify command. Can any one help me how to write a script such that it continuously monitors a directory and indicates that there is some change or modification to it. A: As I said on https://superuser.com/a/747574/28782, I made a helper script that uses inotifywait without some of its direct limitations: inotifyexec Usage example (supposing you've added it in your system path as executable): inotifyexec "echo test" -r . A: Inotify itself is a kernel module accesible via calls from e.g. a C program. https://linux.die.net/man/7/inotify There is an application suite called inotify-tools, which contains: inotifywait - wait for changes to files using inotify http://linux.die.net/man/1/inotifywait and inotifywatch - gather filesystem access statistics using inotify http://linux.die.net/man/1/inotifywatch You can use inotify directly from command line, e.g. like this to continuously monitor for all changes under home directory (may generate lots of output): inotifywait -r -m $HOME And here is a script that monitors continuously and reacts to Apache log activity, copied from the man file of inotifywait: #!/bin/sh while inotifywait -e modify /var/log/messages; do if tail -n1 /var/log/messages | grep httpd; then kdialog --msgbox "Apache needs love!" fi done A: Below is what I use to see operations on an individual file. "-m" causes monitoring vs. exit after just one event. To get timestamps, you need at least 3.13 version of inotify-tools, but if that is not important (or not available on your OS or hard to update to) you can skip the timefmt and format options. "cat /etc/resolv.conf" in another shell leads to the results below: $ inotifywait -m --timefmt '%H:%M' --format '%T %w %e %f' /etc/resolv.conf Setting up watches. Watches established. 12:49 /etc/resolv.conf OPEN 12:49 /etc/resolv.conf ACCESS 12:49 /etc/resolv.conf CLOSE_NOWRITE,CLOSE inotifywait has options for monitoring directories as well, so check the manpage. Add -r for recursive to monitor children of a dir. Here's an example with the commands I typed in a different window shown with "->" prefix: $ inotifywait -mr --timefmt '%H:%M' --format '%T %w %e %f' /home/acarwile/tmpdir Setting up watches. Beware: since -r was given, this may take a while! Watches established. -> cd into directory, no info -> ls in directory 13:15 /home/acarwile/tmpdir/ OPEN,ISDIR 13:15 /home/acarwile/tmpdir/ CLOSE_NOWRITE,CLOSE,ISDIR -> touch newfile 13:16 /home/acarwile/tmpdir/ CREATE newfile 13:16 /home/acarwile/tmpdir/ OPEN newfile 13:16 /home/acarwile/tmpdir/ ATTRIB newfile 13:16 /home/acarwile/tmpdir/ CLOSE_WRITE,CLOSE newfile -> mv newfile renamedfile 13:16 /home/acarwile/tmpdir/ MOVED_FROM newfile 13:16 /home/acarwile/tmpdir/ MOVED_TO renamedfile -> echo hello >renamedfile 13:16 /home/acarwile/tmpdir/ MODIFY renamedfile 13:16 /home/acarwile/tmpdir/ OPEN renamedfile 13:16 /home/acarwile/tmpdir/ MODIFY renamedfile 13:16 /home/acarwile/tmpdir/ CLOSE_WRITE,CLOSE renamedfile -> touch renamedfile 13:17 /home/acarwile/tmpdir/ OPEN renamedfile 13:17 /home/acarwile/tmpdir/ ATTRIB renamedfile 13:17 /home/acarwile/tmpdir/ CLOSE_WRITE,CLOSE renamedfile -> rm renamedfile 13:17 /home/acarwile/tmpdir/ DELETE renamedfile -> cd ..; rmdir tmpdir 13:17 /home/acarwile/tmpdir/ DELETE_SELF After the above, I tried to remake the tmpdir ("mkdir tmpdir") but got no output from that. The new tmpdir is not the same directory as the old tmpdir. Time to just ^C and stop itnotifywait.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: Adding click event to Window or document buggy in IE Using the prevel framework to add a event is done like below pl(window).bind("eventname",handlerFunction); So I did this pl(window).bind("click", function (ev) { if (ev.which == 1) { alert("Clicked"); } }); On clicking the document or window I was able to alert the string, but heck IE8 does not do the same. Is the Library broken or am I wrong with respect to IE. Prevel Javascript framework can be found here https://github.com/chernikovalexey/Prevel here is the code that should get you working http://jsfiddle.net/pKhHJ/ A: The code "ev.which" is specific to firefox. For IE you have to use the code as "ev.keyCode". Try the code as shown below pl(window).bind("click", function (ev) { if(!ev) ev = window.event; var kCode = ev.which || ev.keyCode; if (kCode == 1) { alert("Clicked"); } }); Hope this helps you. A: It's fixed already, as I see.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Geting json response from Google places API in android My simple android application uses google places api to get the latitude and longitude of a place. I am getting the json response from the google api as below { "results" : [ { "address_components" : [ { "long_name" : "Chennai", "short_name" : "Chennai", "types" : [ "locality", "political" ] }, { "long_name" : "Chennai", "short_name" : "Chennai", "types" : [ "administrative_area_level_2", "political" ] }, { "long_name" : "Tamil Nadu", "short_name" : "TN", "types" : [ "administrative_area_level_1", "political" ] }, { "long_name" : "India", "short_name" : "IN", "types" : [ "country", "political" ] } ], "formatted_address" : "Chennai, Tamil Nadu, India", "geometry" : { "bounds" : { "northeast" : { "lat" : 13.23408510, "lng" : 80.33229129999999 }, "southwest" : { "lat" : 12.94592670, "lng" : 80.14878270 } }, "location" : { "lat" : 13.0604220, "lng" : 80.2495830 }, "location_type" : "APPROXIMATE", "viewport" : { "northeast" : { "lat" : 13.14736150, "lng" : 80.37764240 }, "southwest" : { "lat" : 12.97345190, "lng" : 80.12152360 } } }, "types" : [ "locality", "political" ] } ], "status" : "OK" } Now i want to get the this part in the json response, "location" : { "lat" : 13.0604220, "lng" : 80.2495830 } I only get the whole "geometry" part as string through this method JSONObject e = address.getJSONObject(0); e.getString("geometry") How to use the only location values. Any help is appreciated. I'm not sure what is going wrong. A: JSONObject e = address.getJSONObject(0); JSONObject jsonLocation = e.getJSONObject("geometry").getJSONObject("location"); and use String lat = jsonLocation.getString("lat"); String lng = jsonLocation.getString("lng"); to get latitude and longitude. A: You can also get location values as follows: For Longitude: Double lon = ((JSONArray)jsonObject.get("results")).getJSONObject(0) .getJSONObject("geometry").getJSONObject("location") .getDouble("lng"); For Latitude: Double lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0) .getJSONObject("geometry").getJSONObject("location") .getDouble("lat"); A: Try this. It worked for me. JSONObject result = jsonObject.getJSONObject("result"); Double lat = result.getJSONObject("geometry").getJSONObject("location").getDouble("lat"); Double lng = result.getJSONObject("geometry").getJSONObject("location").getDouble("lng");
{ "language": "en", "url": "https://stackoverflow.com/questions/7566585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Custom single KeyValuePair class vs NSMutableDictionary I came into a situation where I had to write a loop with a good amount if iterations and in this loop I had a NSData object that I had to associate with a key. This lead me to search for a simple objective-c _KeyValuePair_ class but coulnt not find one so I wrote my own. Now I'm curious to see if there is any benefit over just using an NSMutableDictinoary holding just 1 key and value. After trying both throughout my project I can't tell much difference on the App UI side or with Instruments Time Profiler. So my questions are: * *Could a single kvpair class be more efficient than a NSMutableDictionary *Does a NSMutableDict allocate any larger amount of space by default then this does *Is there actually a standard single key value pair class that I just missed Some code: for (int i = 0, count = [photoUrls count]; i < count; ++i) { // Example usage of the kvp class NSMutableDictionary *imageRequest = [[NSMutableDictionary alloc] init]; JHKeyValuePair *kvPair = [[JHKeyValuePair alloc] initWithKey:@"DAILY" andValue:[NSNumber numberWithInt:i]; [imageRequest setObject:self forKey:@"delegate"]; [imageRequest setObject:kvPair forKey:@"userInfo"]; [kvPair release]; [imageRequest setObject:[dailySpecialData objectForKey:@"IMAGE_URL"] forKey:@"url"]; [imageDownloader addDownloadRequestToQueue:imageRequest]; [imageRequest release]; } JHKeyValuePair.h @interface JHKeyValuePair : NSObject { id key; id value; } @property (nonatomic, retain) id key; @property (nonatomic, retain) id value; - (id)initWithKey:(id)aKey andValue:(id)aValue; @end JHKeyValuePair.m #import "JHKeyValuePair.h" @implementation JHKeyValuePair @synthesize key; @synthesize value; - (id)initWithKey:(id)aKey andValue:(id)aValue { if ((self = [super init])) { key = [aKey retain]; value = [aValue retain]; } return self; } - (void)dealloc { [key release], key = nil; [value release], value = nil; [super dealloc]; } - (id)copyWithZone:(NSZone *)zone { JHKeyValuePair *copy = [[JHKeyValuePair allocWithZone:zone] init]; [copy setKey:self.key]; [copy setValue:self.value]; return copy; } - (BOOL)isEqual:(id)anObject { BOOL ret; if (self == anObject) { ret = YES; } else if (![anObject isKindOfClass:[JHKeyValuePair class]]) { ret = NO; } else { ret = [key isEqual:((JHKeyValuePair *)anObject).key] && [value isEqual:((JHKeyValuePair *)anObject).value]; } return ret; } @end Edit to fix the initial explanation. Seems I got sidetracked mid-sentance and never came back to finish it. A: If you really want to get speed you are doing a lot of unnecessary retain releases that probably aren't necessary every time you set your key/values. If you use a struct and some basic c code you can achieve something a little quicker but you sacrifice the simple and consistent memory management you get from doing it the objective c way. typedef struct { id key; id value; } Pair; BOOL isEqual(Pair a, Pair b); //... // You will need to clean up after yourself though: void PairRelease(Pair p) { [p.key release]; [p.value release]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7566586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: webdriver-test is unusable On a virtual machine (clean, fresh Ubuntu server 11.04) I created a test website as described in Creating Your First Yii Application and now I want to create simple test using webdriver-test. I set up proper TEST_BASE_URL in protected/tests/WebTestCase.php and created protected/tests/functional/MySimpleTest.php <?php Yii::import( 'ext.webdriver-bindings.CWebDriverTestCase' ); class MySimpleTest extends CWebDriverTestCase { protected function setUp() { parent::setUp( '192.168.57.1', 4444, 'firefox' ); } public function testMySite() { $this->get( TEST_BASE_URL ); $qElem = $this->findElementBy( LocatorStrategy::linkText, 'Users' ); $this->assertNotNull( $qElem, 'There is no "Users" link!' ); $qElem->clickAndWait(); $this->assertTrue( $this->isTextPresent( 'test1@example.com' ), 'The is no "test1@example.com" text on result page!' ); } } Running it looks like this: etam@ubuntu:/var/www/test/protected/tests$ phpunit functional/MySimpleDbTest.php PHPUnit 3.5.15 by Sebastian Bergmann. E Time: 5 seconds, Memory: 5.25Mb There was 1 error: 1) MySimpleTest::testMySite PHPUnit_Framework_Exception: setBrowserUrl() needs to be called before start(). /opt/yii-1.1.8.r3324/framework/test/CWebTestCase.php:61 /var/www/test/protected/extensions/webdriver-bindings/CWebDriverTestCase.php:156 FAILURES! Tests: 1, Assertions: 0, Errors: 1. Notice that it's complaining about setBrowserUrl() from PHPUnit_Extensions_SeleniumTestCase_Driver, which is not the same as one from CWebDriverTestCase. I tried to find out what's going on, but it's too complicated to me. It looks like problems with old and new selenium API existing together, but I'm not sure about it. I'm using: * *Ubuntu server 11.04 *yii 1.1.8.r3324 *webdriver-test 1.1b *phpunit 3.5.15 (repaired as described in bugs.launchpad.net/ubuntu/+source/phpunit/+bug/701544) Please help! A: You need to call the setBrowseUrl() method right after the parent::setup() method because selenium requires this url to resolve relative paths on your test cases. So this way you could call open('full.url.com/someAction') or just open('/someAction') and both would go to the same page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: how to get attribute value from SAX xml Parser in Android? my XML is : <?xml version='1.0' encoding='UTF-8'?> <entry xmlns='http://www.w3.org/2005/Atom' xmlns:media='http://search.yahoo.com/mrss/' xmlns:gd='http://schemas.google.com/g/2005' xmlns:yt='http://gdata.youtube.com/schemas/2007'> <media:group> <media:content url='http://www.youtube.com/v/UBCNwgFlw1A?f=videos&amp;app=youtube_gdata' type='application/x-shockwave-flash' medium='video' isDefault='true' expression='full' duration='217' yt:format='5' /> <media:content url='rtsp://v4.cache7.c.youtube.com/CiILENy73wIaGQlQw2UBwo0QUBMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='217' yt:format='1' /> <media:content url='rtsp://v2.cache6.c.youtube.com/CiILENy73wIaGQlQw2UBwo0QUBMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='217' yt:format='6' /> </media:group> </entry> .java file public void startElement(String arg0, String localName, String arg2, Attributes attributes) throws SAXException { currentElement = true; if (localName.equals("content")) { String videourl = attributes.getValue("url"); Log.v("log_tag", "Video url is : " + videourl); message.setVideourl(videourl); String duration = attributes.getValue("duration"); Log.v("log_tag", "Duration of Video is : " + duration); String formaturl1 = attributes.getValue("format"); Log.v("log_tag", "format of url is : " + formaturl); } } I used SAX parser.and I can get all Atrribute of media:content . But i can't get yt:format value so how i can I get yt:format value in Android. A: Looks like attributes.getValue("yt:format") or attributes.getValue("http://gdata.youtube.com/schemas/2007", "format") should both work. A: you can use attributes.getValue(5);
{ "language": "en", "url": "https://stackoverflow.com/questions/7566591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Converting to NSDate from NSString I am trying to convert a Nsstring object to Nsdate.My code is like this NSString *Time=@"09/26/2011 2:06 AM"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; //[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehaviorDefault]; //Time=[mystr substringToIndex:3]; [dateFormatter setDateFormat:@"MM-DD-YYYY HH:MM"]; NSDate *dateFrom = [dateFormatter dateFromString:Time]; NSLog(@"\n\n\n\nThe date==%@\n\n\n\n\n",dateFrom); But It returns a null value..Any help is Appreciated .Thanks in advance A: Try to replace: [dateFormatter setDateFormat:@"MM-DD-YYYY HH:MM"]; with [dateFormatter setDateFormat:@"MM/dd/yyyy HH:mm a"];
{ "language": "en", "url": "https://stackoverflow.com/questions/7566593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Difficult Regexp I need a regexp which does the following: Heres the name of an HTML input field: lm[0][ti] I need to find the basic name ("lm"). Only if the name contains brackets I need to find the string in the second brackets ("ti"). To get it in portions is easy with the following regexp: ([a-zA-Z\d_]+)\[?([0-9]*)\]?\[?([a-zA_Z\d_]+)\]? It matches all the portions I need. Array ( [0] => lm[0][ti] [1] => lm [2] => 0 [3] => ti ) But if the HTML input name was just "lm", using this regexp I cannot determine that item #4 in the array is a valid name. The array would look like this: Array ( [0] => lm [1] => l [2] => [3] => m ) "m" is not valid for me, I'd like to get this array: Array ( [0] => lm [1] => [2] => [3] => ) or this Array ( [0] => lm ) You can test the regexp here: http://regexp-tester.mediacix.de/exp/regex/ Thanks for support in finding the right regexp... A: Try this: (\w+)(?:\[(\d+)\])?(?:\[(\w+)\])? Input: lm[0][ti] Output: Input: lm Output:
{ "language": "en", "url": "https://stackoverflow.com/questions/7566598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android neighboring cells info I am using Samsung Ace S5830 phone running on Android 2.2 I am facing a problem that when i try to get neighboring cell information it returns me an empty list. but when i get in the service mode of the phone with the code ##197328640## and then click on neighboring cells it shows me the cell information. Can anyone tell me why i am not able to get the neighboring cell information through programming? i am using the following code to get the neighboring cell info. List neighboringList = telephonyManager.getNeighboringCellInfo(); Thanks A: ok, the problem i faced was during to the make of the mobile phone, while i was trying to get this information on the samsung handsets or even LG handsets it doesnt give me the neighboring cells info even if they are available in the phone status and internal settings, but when i tried to use the same code on the sony ericsson phone i was able to receive this information and along with many other which were not available on the samsung or lg handsets... i think it is due to the permissions that in samsung and LG user application cannot access this information but in SE it can. that is what i found if someone has other finding or solution kindly please share. regards,
{ "language": "en", "url": "https://stackoverflow.com/questions/7566599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Delete all portlets site-wide in Plone What's the best (or simplest) way to delete portlets site-wide in plone 4.x? A: It depends. If you have a small amount of local assigned portlets I suggest the manual way. If you have a complex assignment of local portlets you could take this way: 1- create a browser view linked to the site root 2- add this: from Products.Five import BrowserView from Products.CMFCore.utils import getToolByName from zope.component import getMultiAdapter from plone.portlets.interfaces import IPortletManager from plone.portlets.interfaces import IPortletAssignmentMapping from plone.portlets.interfaces import ILocalPortletAssignable class MyView(BrowserView): def __call__(self): ctool = getToolByName(self.context, 'portal_catalog') all_brains = ctool.searchResults() for i in all_brains: obj = i.getObject() if not ILocalPortletAssignable.providedBy(obj): continue for manager_name in ('plone.leftcolumn','plone.rightcolumn'): manager = getUtility(IPortletManager, name=manager_name) assignment_mapping = getMultiAdapter((obj, manager), IPortletAssignmentMapping) for i in assignment_mapping.keys(): del assignment_mapping['assignment_mapping'] Usually retrieving all objects is not a good thing, so you should evaluate carefully the amount of contents and local portlers. That said, this way is a bit aggressive but it will do the job. A: I think you made a small typo: del assignment_mapping['assignment_mapping'] should be: del assignment_mapping[i]
{ "language": "en", "url": "https://stackoverflow.com/questions/7566601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails 3 ArgumentError: wrong number of arguments (3 for 1) After migrate on Rails 3, I have error "ArgumentError: wrong number of arguments (3 for 1)" For line: <%== auto_link(raw(simple_format(h(comment.comment))), :all, :target => '_blank') -%> Backtrace: app/views/logs/_entry.html.erb:94:in `raw' app/views/logs/_entry.html.erb:94:in I got this error only on Production server A: The helper auto_link has been removed in Rails 3.1. You need to install the Gem separately to use it. Also, make sure to check the correct method invocation. Also, you should use <%=, not <%==.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery Plugin Boxy, before boxy loading In vBulletin version 4.1.4, to open a window with attachments, I use the jQuery Plugin, Boxy . It is in the template, threadbit and is working fine. But when the box is loading, I want to show an image that something is happening. After the loading process, this image should be removed. For this process I modified the template code. This works: <code class="html"> <div class="myThemaRating" style="cursor:pointer;"> <span onclick='new Boxy.load( "{vb:raw vboptions.bburl}/misc.php?{vb:raw session.sessionurl}do=showattachments&amp;t={vb:raw thread.threadid}", {title:"Anhang-Dateien im Forum:", closeText:"schliessen", cache:true} )'> <i m g s_c="{vb:stylevar i m g dir_icons}/Icon_6 . png" border="0" alt="{vb:rawphrase x_attachments, {vb:raw thread.attach}}" />&nbsp; </span> </div> </code> But this doesn't: <code> <div class="myThemaRating" style="cursor:pointer;"> <span onclick='new Boxy.load( "{vb:raw vboptions.bburl}/misc.php?{vb:raw session.sessionurl}do=showattachments&amp;t={vb:raw thread.threadid}", {title:"Anhang-Dateien im Forum:", closeText:"schliessen", cache:true }, behaviours:function(r) { $(r).click( $("# myImagesLoad _{vb:raw thread.threadid}").attr({ src: "{vb:stylevar i m g dir_icons}/ajax-loader . gif", alt: "Fenster wird geladen" }) ); } } ' > <i m g s_c="{vb:stylevar imgdir_icons}/1pixel . png" id="myImagesLoad_{vb:raw thread.threadid}" width="10" border="1"> <!-- load image --> <i m g s_c="{vb:stylevar imgdir_icons}/Icon_6 . png" border="0" alt="{vb:rawphrase x_attachments, {vb:raw thread.attach}}" />&nbsp; </span> </div> </code> Does anybody have an idea how I can fix this?
{ "language": "en", "url": "https://stackoverflow.com/questions/7566609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Locking stored procedure I have a stored procedure with a select and an update. I would like to prevent multiple users, from executing it, at the same time, so I don't update, based on an incorrect select. How do I lock it? I've read various solutions (Transaction isolation, xlock), but I haven't been able to figure what I really want, and how to do it. A: The easiest way is to forget about data locks but look at sp_getapplock to control access through the code BEGIN TRY EXEC sp_getapplock ... SELECT ... UPDATE ... EXEC sp_releaseapplock END TRY ... Saying that, with thing like the OUTPUT clause and judicious use of ROWLOCK, UPDLOCK there is a good chance the UPDATE and SELECT can be one statement A: Using the XLOCK table hint in the SELECT query: CREATE TABLE [X]([x] INT NOT NULL) GO INSERT [X]([x]) SELECT 0 GO CREATE PROCEDURE [ATOMIC] AS BEGIN BEGIN TRAN DECLARE @x INT = ( SELECT [x] FROM [X] (XLOCK) ) + 1 UPDATE [X] SET [x] = @x COMMIT TRAN END GO You can then test this by running EXEC [ATOMIC] GO 10000 simultaneously from different sessions. You can test using SELECT [x] FROM [X] The value should be exactly 10 000 times the number of sessions you ran. If the number is less than expected you don't have atomic read + write, or some SPIDs may have been killed due to dead locking.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: get archetype catalog failed(can't load Ahcwagon)-m2e-0.12.1 I'm trying to use m2eclipse api to import projects by archetype. my code is here: RemoteCatalogFactory remoteCatalogFactory = new RemoteCatalogFactory("http:/server1/archetype-catalog.xml", null, true); ArchetypeCatalog catalog = remoteCatalogFactory.getArchetypeCatalog(); List<Archetype> archetypes = catalog.getArchetypes(); for (Archetype archetype : archetypes){ System.out.println(archetype.getArtifactId()); } m2eclipse version is:0.12.1. Got below exception: 1) Error injecting: org.sonatype.maven.wagon.AhcWagon at ClassRealm[plexus.core, parent: null] while locating org.apache.maven.wagon.Wagon annotated with @com.google.inject.name.Named(value=http) 1 error at com.google.inject.internal.InjectorImpl$4.get(InjectorImpl.java:958) at com.google.inject.Scopes$1$1.get(Scopes.java:59) at org.sonatype.guice.bean.locators.LazyQualifiedBean.getValue(LazyQualifiedBean.java:66) at org.sonatype.guice.plexus.locators.LazyPlexusBean.getValue(LazyPlexusBean.java:54) at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:247) ... 38 more Caused by: java.lang.TypeNotPresentException: Type org.sonatype.maven.wagon.AhcWagon not present at org.sonatype.guice.bean.reflect.URLClassSpace.loadClass(URLClassSpace.java:94) at org.sonatype.guice.bean.reflect.NamedClass.load(NamedClass.java:46) at org.sonatype.guice.bean.reflect.AbstractDeferredClass.get(AbstractDeferredClass.java:48) at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:40) at com.google.inject.internal.InjectorImpl$4$1.call(InjectorImpl.java:949) at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:995) at com.google.inject.internal.InjectorImpl$4.get(InjectorImpl.java:945) ... 42 more Caused by: java.lang.ClassNotFoundException: org.sonatype.maven.wagon.AhcWagon at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:50) at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:244) at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:230) at org.sonatype.guice.bean.reflect.URLClassSpace.loadClass(URLClassSpace.java:90) During debug, I found bundleloader is using org.maven.ide.eclipse's bundle classloader to load AhcWagon class. because maven embedder bundle haven't export AhcWagon's package, so can't load it. But my question is: caller(plexus-classworlds.jar) is in maven embedder bundle and AhcWagon(in wagon-ahc.jar) is in the same bundle. Why not use maven embedder's bundle loader to load AhcWagon? Am I something wrong to use this API? That's great! If there is any sample code. Regards Simon A: m2eclipse0.12.1's bug, need to export org.sonatype.maven.wagon in manifest.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to count all nodes based on my specfic criteria using xslt 2.0? This is my XML file. <w:document xmlns:w="w"> <w:body> <w:p> <w:r> <w:pict> <v:shape xmlns:v="v"> <v:textbox> <w:txbxContent> <w:p> <!-- My Ignore case --> <w:r> <w:t>paragraph1 </w:t> </w:r> </w:p> </w:txbxContent> </v:textbox> </v:shape> </w:pict> </w:r> <w:r> <w:t>Normal Paragraph1</w:t> </w:r> </w:p> <w:p> <w:r> <w:t>paragraph2 </w:t> </w:r> </w:p> <w:p> <w:r> <w:t>paragraph3 </w:t> </w:r> </w:p> <w:p> <w:r> <w:t>paragraph4 </w:t> </w:r> </w:p> <w:p> <w:r> <w:t>paragraph5 </w:t> </w:r> </w:p> <w:tbl> <w:tr> <w:tc> <w:p><w:r><w:t>para6</w:t></w:r></w:p> </w:tc> <w:tc> <w:p><w:r><w:t>para7</w:t></w:r></w:p><!-- Assume This is my Current Node --> </w:tc> <w:tc> <w:p><w:r><w:t>para8</w:t></w:r></w:p> </w:tc> </w:tr> </w:tbl> </w:body> </w:document> Logic:1 So, now I want to count all preceding <w:p> nodes only within <w:body> tag. For example, now we have 5 nodes from <w:body>. Logic:2 then if (<w:tbl> inside <w:body>) then count all <w:p> inside the <w:tbl> until the current node will reach. So, the expected final is :7. I have written query for this, but it is counting wrongly. <xsl:value-of select="count($currentNode/preceding::w:p)"/> It is written 8 because it will also count <w:p> inside <w:p>(see, my ignore case on my code). I don't want it. I need the total count like logic1+logic2. A: It sounds like you want to ignore w:p elements that are nested within other w:p elements. If so, then you need to modify for statement to only include w:p element which have no w:p element as an ancestor. <xsl:value-of select="count($currentNode/preceding::w:p[not(ancestor::w:p)])"/> This should return a value of 7, instead of 8. I am assuming the current node is para8 here, by the way. So, assuming the following XML document <w:document xmlns:w="w"> <w:body> <w:p> <w:r> <w:pict> <v:shape xmlns:v="v"> <v:textbox> <w:txbxContent> <w:p><!-- My Ignore case --> <w:r> <w:t>paragraph1 </w:t> </w:r> </w:p> </w:txbxContent> </v:textbox> </v:shape> </w:pict> </w:r> <w:r> <w:t>Normal Paragraph1</w:t> </w:r> </w:p> <w:p> <w:r> <w:t>paragraph2 </w:t> </w:r> </w:p> <w:p> <w:r> <w:t>paragraph3 </w:t> </w:r> </w:p> <w:p> <w:r> <w:t>paragraph4 </w:t> </w:r> </w:p> <w:p> <w:r> <w:t>paragraph5 </w:t> </w:r> </w:p> <w:tbl> <w:tr> <w:tc> <w:p> <w:r> <w:t>para6</w:t> </w:r> </w:p> </w:tc> <w:tc> <w:p> <w:r> <w:t>para7</w:t> </w:r> </w:p> </w:tc> <!-- Assume This is my Current Node --> <w:tc> <w:p> <w:r> <w:t>para8</w:t> </w:r> </w:p> </w:tc> </w:tr> </w:tbl> </w:body> </w:document> If you use the following XSLT <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:w="w"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/"> <xsl:variable name="currentNode" select="//w:p[w:r/w:t = 'para8']" /> Old: <xsl:value-of select="count($currentNode/preceding::w:p)"/> ----- New: <xsl:value-of select="count($currentNode/preceding::w:p[not(ancestor::w:p)])"/> </xsl:template> </xsl:stylesheet> Then the following is returned: Old: 8 ----- New: 7
{ "language": "en", "url": "https://stackoverflow.com/questions/7566621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Testing traffic on a webapp (Spring, Hibernate, Java) I am developing a webapp and am looking into how I can automate testing of the web site such as seeing how it copes with multiple concurrent users / heavy traffic. Could anyone point me in the direction of any software or techniques I could be using to help me do this? I am also looking into how to automate testing things at the front end? For example I have unit tested all of my business logic at the backend, but them am unsure as to what I should be do in order to automate testing of everything else. A: For heavy traffic testing, I've been using JMeter. For front end testing, I'm using Selenium. A: Beside Apache JMeter, which generates artificial load and allows you to test performance, there are two main technologies for testing accurately performance during operation: * *Tagging Systems (like Google Analytics) *Access Log File Analysis With tagging you create an account with Google Analytics and add some JavaScript code to the relevant places of your code, that allows the browser of your visitors to connect to GA and get captured there. The Access log file holds all information about each session. There is a data overload, so data has to be Extracted, Transformed and Loaded (ETL) to a database. The evaluation can be then performed in nearly real-time. You can create some dashboard application that does the ETL and displays the status of you application in nearly real time. A: I had same need some years ago while developing a large scale webapp. I've been using Apache JMeter as for automation testing, and Yourkit Java Profiler for profiling Heap JVM usage and actually found lot of memory leaks! cheers A: Selenium to test the flow and expected results Yorkit to profile CPU and Memory usage => excellent to track concurrency issues and memory leaks Spring Insight to visually understand your application performance / load + * *See the SQL executed for any page request => with drill down to the corresponding source code *Find pages which are executing slowly and drill into the cause *Verify your application's transactions are working as designed Spring Insight is deployable as a stand alone war (Tomcat / tC Server / etc..)
{ "language": "en", "url": "https://stackoverflow.com/questions/7566622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to restrict developers to use reflection to access private methods and constructors in Java? How to restrict developers to use reflection to access private methods and constructors in Java? Using normal Java code we can't access private constructors or private methods outside of a class. But by using reflection we can access any private methods and constructors in a Java class. So how can we give security to our Java code? A: Add checkPermission() method in all of your private method/constructor. checkPermission using sun.reflect.Reflection.getCallerClass(int n) by assert callerClass=selfClass. The getCallerClass returns the class of the method realFramesToSkip frames up the stack (zero-based), ignoring frames associated with java.lang.reflect.Method.invoke() and its implementation. The first frame is that associated with this method, so getCallerClass(0) returns the Class object for sun.reflect.Reflection. public class PrivateConstructorClass { private PrivateConstructorClass() { checkPerMission(); //you own code go below } void checkPerMission() { Class self = sun.reflect.Reflection.getCallerClass(1); Class caller = sun.reflect.Reflection.getCallerClass(3); if (self != caller) { throw new java.lang.IllegalAccessError(); } } } You can try to test reflect, it will fail: public class TestPrivateMain { Object newInstance() throws Exception { final Class<?> c = Class.forName("package.TestPrivate"); final Constructor<?> constructor = c.getDeclaredConstructor(); constructor.setAccessible(true); return constructor.newInstance(); } public static void main(String[] args) throws Exception { Object t = new TestPrivateMain().newInstance(); } } A: Run your application using a SecurityManager and a sufficiently restrictive security policy. There's a short summary in the tutorial and extensive information in the security documentation. A: You (as the developer of the code in question) cannot do that. The end user, who runs the application, could install a SecurityManager that forbids reflection.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: Error when running asp.net MVC application under IIS7 that works when run locally I am trying to modify the Ext.net Mvc sample in this link http://mvc.ext.net/Account/Login/?ReturnUrl=%2f The project is working perfectly when run locally in Visual Studio 2010 but when I deploy it on an IIS 7 server, after I login to the application I get the following error: Can you help me please thanks.. A: Please confirm your Global.asax.cs is correctly configured. http://code.google.com/p/extnet-mvc/source/browse/trunk/Ext.Net.MVC.Demo/Global.asax.cs The 404 error appears be thrown because /Account/Login/ does not exist. Can you confirm your AccountController includes a "Login" handler? Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: HDLC Frames - Octets/modulo 8 doubts I am trying to implement the HDLC frame format type 3 and I have some doubts as regards Octets/Modulo 8 encoding of frames. * *Firstly, Is the HDLC frame transmitted entirely in Octets? *What do they mean by a frame is 'n' Octet in length? Please give an example. *I believe that Octet and Modulo is the same, so assuming that we have a frame X of one byte, what then do they mean by the encoding of X shall be modulo 8. I am getting a little confused with all this, so i need more clarifications. Example and illustration will be of great help. Thanks in Advance. Thanks @clifford and @masoud. Your answer was really helpful. But I have to read this Octet String: What is it? (though it sounds funny because it explained in a simple way), and I came back to read your comments, then I understood all you explained. All the same, wish me a happy coding. A: In HDLC every field length must be modulo 8 for example: A frame of HDLC is like below: [FLAG(8bits)|ADDRESS(8bits)|CONTROL(8/16bits)|INFORMATION(n*8bits)|FCS(8bits)|FLAG(8bits)] each field is modulo 8, even length of INFORMATION must be modulo 8. It means if you want to send a data with length of 1 bit, you must consume a byte(8 bits). If you are looking for some HDLC frame sample, look at this link: Click me! and read this: Click me A: Firstly, Is the HDLC frame transmitted entirely in Octets? That simply means that the data length is a multiple of 8 bits. Yes it is. What do they mean by a frame is 'n' Octet in length? Who is "they"? Cite your reference material. An octet is simply a group of eight bits. It is a less ambiguous term that byte (which can rarely be used refer to a machine word of length other than eight bits). The term octet is widely used in telecommunications, and is also used in languages other than English to mean "byte" (when a byte is eight bits). I believe that Octet and Modulo Not at all, modulo is a mathematical term, used here perhaps inaccurately to mean exactly divisible by (or an exact multiple of) eight. [...] what then do they mean by the encoding of X shall be modulo 8.[?] Again who are "they"? If we can see where you are reading this in context, you may get a better explanation. Edit: I have not gone to the length of referencing ISO 3309 which is the standard defining HDLC frame structure, but the term "Modulo 8" in at least the Wikipedia article is used only in the context of frame sequence numbers, where it simply means that a sequence number increments from 0 to 7, then restarts at 0 (i.e. it is the frame number modulo 8 - or the remainder of frame_num/8 or simple frame_num % 8 in C code. I wonder whether you are confusing terms - again a citation or extract would help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Startup same .exe file with different app.config 's Is there a way (maybe from command line) to start the same exe file twice using a different app config? A: var configMap = new ExeConfigurationFileMap(); configMap.ExeConfigFilename = @"myconfigpath"; var config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None); A: Start it from a separate location, where the filename.exe.config is different. A: THe configuration framework let you load the config from any file but you will have to handle that manually from within your application. Look at ConfigurationManager class A: You can load your process into a separate app domain. This allows you to redirect the configuration file. See http://www.codeproject.com/KB/IP/HostingMultipleServices.aspx for an example of doing this with a Windows service. It'll be similar for any kind of application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hibernate Query selection In a database consider that I have a table with 4000 rows. I am using JTable to list them in front end. During page load, I need to display only First - 20 rows. I have NEXT and PREVIOUS button in top, so that if I click NEXT button, next 20 rows must be fetched from database and loaded in table. In short, on button click, I need to fetch a set of values (for example say 20 rows) dynamically from database. I am using Hibernate. Can anyone suggest me a link or the procedure to do this. Any examples will be clear... Thanks. A: You could use ScrollableResults. Take into account that it might be unsupported by some DB drivers. Or you could use setFirstResult and maxResults, for example: Criteria criteria=session.createCriteria(Item.class); criteria.addOrder(Order.asc("name")); criteria.setFirstResult(100); criteria.setMaxResults(50); List pageResults=criteria.list(); You may also find the answers to this question useful: Using Hibernate's ScrollableResults to slowly read 90 million records
{ "language": "en", "url": "https://stackoverflow.com/questions/7566635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL - How to join two tables without duplicates? I have two tables like the following hotels ------ hotelID hotelName Second table operators --------- opID opName opServices opHotelID a short explanation: In the first table I have a lot of hotels which have an increment id which is unique. The second table contains all the operators offering this hotel with additional services. The opID here is unique too but the opHotelID exists multiple times, because there can be many operators offering the hotel. Now, what I want to get is the following: I want to get the HotelName and an additional Column (called Operators) which lists all the operators offering the hotel. So the result should be like this... 123 - Hotel ABC - OP1,Op2,OP3 instead of this... 123 - Hotel ABC - OP1 123 - HOtel ABC - OP2 123 - Hotel ABC - OP3 Is there a way to do this in one SQL query or how would you solve this problem? I am currently working on a search function and currently i have a simple SELECT query with a left join but this returns a lot of more rows. Now the Search should only display unique HotelIDs and combine the different Operators in one column. Thanks for you help and have a nice day... Bye WorldSignia A: Try this one: SELECT hotels.hotelID, hotels.hotelName, GROUP_CONCAT(operators.opName SEPARATOR ', ') AS opList FROM hotels INNER JOIN operators ON operators.opHotelID = hotels.hotelID GROUP BY(hotels.hotelID) If you want to have the number of operators, you have to use COUNT on the operators ID like that: SELECT hotels.hotelID, hotels.hotelName, GROUP_CONCAT(operators.opName SEPARATOR ', ') AS opList, COUNT(operators.opID) AS nbOperatos FROM hotels LEFT JOIN operators ON operators.opHotelID = hotels.hotelID GROUP BY(hotels.hotelID) A: You can use GROUP_CONCAT A: you should have a simple link table, this will create the many to many relationship for many operators to a hotel operatorhotels --------- opID opHotelID A: if you dont want to change your DB design, you can use this query SELECT hotelID,hotelName,opName FROM hotels h INNER JOIN operators o ON h.hotelID = o.opHotelID GROUP BY h.hotelID,hotelName,opName otherwise, create a mapping table resulting the many to many relation A: You should use GROUP_CONCAT as already suggested. Here's the query: SELECT h.hotelID, h.hotelName, GROUP_CONCAT(o.opName) FROM hotels h INNER JOIN operators o ON h.hotelID = o.opHotelID GROUP BY h.hotelID
{ "language": "en", "url": "https://stackoverflow.com/questions/7566636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery.bind and .trigger without jQuery I want to do the equivalent of this: $(window).bind('resize', function () { myResizeFunction(); }).trigger('resize'); without jquery. The reason being is. This is the only part of code in my javascript library that uses jquery. And i see no point in including jquery if im only using this one command. NOTE: Just to clarify, i want myResizeFunction to run everytime the broswer is resized. A cross-browser solution is prefered! Thanks:) A: Simply use this <script> var resizeMe = function() { myResizeFunction(); } resizeMe(); </script> To hook with resize event of window window.onresize = resizeMe A: As far as I know, jQuery is simply using window.onresize. window.onresize = function() { //stuff }; For your case: window.onresize = myResizeFunction; myResizeFunction(); A: // binding event if(window.addEventListener)window.addEventListener("resize",myResizeFunction,false); else if(window.attachEvent)window.attachEvent("onresize",myResizeFunction); // trigger event handler myResizeFunction(); It's not full equivalent of jQuery .bind and .trigger, but it's valid main usage of resize event
{ "language": "en", "url": "https://stackoverflow.com/questions/7566637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MVC3 where to pu the logout display i'm creating an MVC3 C# application. i createtd a login attribute which only appears when a user chooses to either create,delete,or edit data stored. To logout, i put the HTML code in th layout view, but its displaying on th homepage even if the user did not log in. how do i make it display on all pages after user has logged in, and when user logs out, it is no mor displayed? A: Just check if the user is authenticated @if (Request.IsAuthenticated) { <div>control to logout</div> }
{ "language": "en", "url": "https://stackoverflow.com/questions/7566638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HttpSession safe Where is servlet HttpSession stored? Is it safe to store sensitive information in HttpSession attributes. Can user maliciously modify session attributes? A: Where HttpSession is stored depends on the application server implementation and the configuration selected by the deployer. Usually it is stored in memory, but many application servers allow you to persist it in a database. In any case the session is stored in the server and not in the client. If as user you mean the client, then it is impossible for him/her to modify it, as it is stored server-side.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I pass variable with Ajax link in Rails? I want to pass variable with link_to_remote in Rails 2.3. Following is my code for passing variable. But controller did not get that variable. Anybody can help me ? <%= link_to_remote 'Add new event', :url => {:controller => 'events', :action => 'new' }, :with=> 'event' %><br> A: Hope this would solve your problem,I have not tried. <%= link_to_remote "Add New event", :url => :action => "list", :with => " 'name=' +$('div-id-of-name-text-box').value + '&city=' +$('div-id-of-city-text-box').value + '&country=' +$('div-id-of-country-text-box').value " %> A: Any hash key you add that's not part of the keyword set (controller, action, format) will be appended to your URL as an argument. ie. <%= link_to_remote "Add New Event", :url => {:controller => 'events', :action => 'new', :var => 'event'} %> Would yield /events/new?var=event
{ "language": "en", "url": "https://stackoverflow.com/questions/7566646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Result of XMLHttpRequest dissappears I am trying my hand on PHP. And I've landed at the client-server connectivity. Now I have a server-side script that applies random math to an x and a y value that it gets via an XMLHttpRequest: <?php $farr = array( create_function('$x,$y', 'return "x + y = ".($x+$y);'), create_function('$x,$y', 'return "x - y = ".($x-$y);'), create_function('$x,$y', 'return "x * y = ".($x*$y);'), create_function('$x,$y', '$returnVal = "x / y = "; if($y==0){$returnVal.="NaN (y value = 0)";}else{$returnVal.=($x/$y);}return $returnVal;') ); $x = $_GET["x"]; $y = $_GET["y"]; $i = rand(0,3); try{ $f = $farr[$i]; $result = $f($x,$y); echo "".$result; } catch(Exception $e) { echo "An exception occurred while accessing functions"; } ?> The client calls this script when a user presses the "Send" button on my form: <html> <head> <title> Welcome </title> <script type="text/javascript"> function calculate(x, y){ var xmlhttp; if( x.length==0){ document.getElementById("result").innerHTML = "x is not set"; return; } if(y.length==0){ document.getElementById("result").innerHTML = "y is not set"; return; } if(window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function(){ if(xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementById("result").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET", "math.php?x="+x+"&y="+y, true); xmlhttp.send(null); } </script> </head> <body> <form> x: <input type="text" name="x"/><br/> y: <input type="text" name="y"/><br/> <input type="submit" value="Send" onclick="calculate(x.value, y.value)"/> <input type="reset" value="Reset"/> <p>Result: <div id="result">something</div></p> </form> </body> </html> It is intended that the result is placed in the div at the end of the form. However, I see the result for a brief amount of time, and then it's gone again. I suspect the page from reloading, but isn't that the purpose of the XMLHttpRequest, that only the part in the onreadystatechanged callback get's refreshed? And not the whole page? A: that's because you are using a submit button.. change <input type="submit" to <input type="button"
{ "language": "en", "url": "https://stackoverflow.com/questions/7566648", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Progress Dialogs with Sound in Android I have searched around for possible answers, but did not find one that came close to what I require. I am after creating a progress dialog in Android, the standard one with the spinning disk. However, what I want is for the dialog to play a looped sound sample as it spins which stops when its dismissed. How would you go about doing this? All the best Andrew. A: When you first show() your ProgressDialog start a looping MediaPlayer. MediaPlayer mAlarmPlayer=MediaPlayer.create(this, R.raw.alarm_1); mAlarmPlayer.setLooping(true); mAlarmPlayer.start(); when you will dismiss() your ProgressDialog just call: mAlarmPlayer.stop(); mAlarmPlayer.release();
{ "language": "en", "url": "https://stackoverflow.com/questions/7566655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dictionary or KeyedCollection? I have a class (SomeClass) which contains a property Name of string type. And I need to store an array of that class and find its items by their names. For this purpose there are two types of collections: KeyedCollection and Dictionary. My question is: What difference between them and in such case It is better to use KeyedCollection and Dictionary? Thanks for any help in explanation. A: None of the previous comments address the most important difference between the two: KeyedCollection keeps your items in the order in which they are added (the first item added is at index 0 and the last added is at the last index). Dictionary does not (or at least it is never guaranteed to do so). This extra benefit of KeyedCollection does have a small performance cost. Under the covers, you pay the cost of maintaining both a Dictionary and a List. A: A KeyedCollection allows mutable keys and ways to manage change in key. Dictionary does not allow changes to key. Secondly, if you have a collection which needs lookup, the logic to extract key from entity remains in one place - whereas maintaining dictionary will need to put key extraction logic at each place where items are added/removed from dictionary. A: By default a KeyedCollection creates a Dictionary under the covers. If the Key also has meaning as part of the Value and also defines uniqueness then that is the purpose of a KeyedCollection. If you want to modify the dictionary backing then use this ctor: protected KeyedCollection( IEqualityComparer<TKey> comparer, int dictionaryCreationThreshold) A: A KeyedCollection should be used when the key is on the item itself. By default, KeyedCollection is a Collection<TItem> wrapper around a dictionary. When you use small collections and/or you prefer retrieving items directly, the KeyedCollection provides a constructor that takes a dictionaryCreationThreshold parameter, that indicates at what collection count to switch to Dictionary. Another aspect in KeyedCollection is that you can choose to switch the key property (as long as their types match). This can be good for double keyed items etc. Performancewise, I don't think wrapping a dictionary has much overhead except if you generate a bunch of KeyedCollection instances, or if you use really large collections (there are some internal null checks to determine if there is a dictionary). One thing I'd hope to see in KeyedCollection is unabstracting it, but you can make a generic concrete type just as easy. A: Here is good explanation about differences between Dictionary and KeyedCollection: http://geekswithblogs.net/NewThingsILearned/archive/2010/01/07/using-keyedcollectionlttkey-titemgt.aspx Main points are: * *KeyedCollection is abstract, so you can't use it directly. *KeyedCollection is useful for cases, when key is in entity itself, then you can encapsulate key retrieval within collection implementation. *There are generic implementations for KeyedCollection (not in the framework though), which allow you to paste key retrieval delegate in collection constructor, so you don't have to repeat it each time you add item. Update: as long as original link to article was removed, adding link to web archive: https://web.archive.org/web/20200228045828/http://geekswithblogs.net/NewThingsILearned/archive/2010/01/07/using-keyedcollectionlttkey-titemgt.aspx A: You can't use KeyedCollection because it's abstract: http://msdn.microsoft.com/en-us/library/ms132438.aspx. This means you can't create an object of it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "65" }
Q: mongodb map reduce value.count In mongodb, I have a map function as below: var map = function() { emit( this.username, {count: 1, otherdata:otherdata} ); } and reduce function as below: var reduce = function(key, values) { values.forEach(function(value){ total += value.count; //note this line } return {count: total, otherdata: values[0].otherdata}; //please ignore otherdata } The problem is with the line noted: total += value.count; In my dataset, reduce function is called 9 times, and the supposed map reduced result count should be 8908. With the line above, the returned result would be correctly returned as 8908. But if I changed the line to: total += 1; The returned result would be only 909, about 1/9 of the supposed result. Also that I tried print(value.count) and the printed result is 1. What explains this behavior? A: short answer : value.count is not always equal to one. long answer : This is the expected behavior of map reduce : the reduce function is aggreagating the results of the map function. However, it does aggregate on the results of map function by small groups producing intermediate results (sub total in your case). Then reduce functions are runned again on these intermediate results as they were direct results of the map function. And so on until there is only one intermediate result left for each key, that's the final results. It can be seen as a pyramid of intermediate results : emit(...)-| |- reduce -> | emit(...)-| | | |- reduce ->| emit(...)-| | | | | | emit(...)-|- reduce -> | | | |-> reduce = final result emit(...)-| | | emit(...)--- reduce ------------ >| | emit(...)-----------------reduce ->| The number of reduce and their inputs is unpredicatable and is meant to remain hidden. That's why you have to give a reduce function which return data of the same type (same schema) as input. A: The reduce function does not only get called on the original input data, but also on its own output, until there is a final result. So it needs to be able to handle these intermediate results, such as [{count: 5}, {count:3}, {count: 4}] coming out of an earlier stage.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Surely schedulers aren't this harmful? Don't we have better APIs? I'm wondering what APIs are available to avoid the following problem. Casting my mind back to Operating System lectures on my old CS course, the topic was multiprocess scheduling and concurrent I/O. Here's what the lecturer gave as an example of what would happen: Two processes, X and Y have some work to do. There's one processor/bus/whatever and the scheduler distributes timeslices between X and Y, naively, as follows: * *X gets timeslice 1 *Y gets timeslice 2 *X gets timeslice 3 *... This was described as being "fair", however it seems to me grossly unfair. Consider two cases under this scheme * *If X and Y are both going to take 10 seconds each, now both will take 20 seconds. *If X requires 10 seconds and Y requires 100 seconds, then X will take 20 seconds and Y will take 110 seconds. If the scheduler was simply "do all of X then all of Y" then in the first case X would take 10 seconds and Y would take 20 seconds; in the second case X would take 10 and y would take 110. How a system which makes nobody better-off and somebody worse-off be a good idea? The only argument in the "fair" system's favour is that if we did all of Y before any of X then a small job X would be delayed by a large job Y and we need to keep both jobs "responsive". For the second case, part of me sees the natural "best" way as being to say "X is 10 times smaller, therefore absent any explicit preference, it should get 10 times as many timeslices as Y". (It's a bit like giving pedestrians right of way before cars on the grounds that they put less strain on the roads, but I digress.) Under this scheme, X finishes in 11 seconds and Y finishes in 110 seconds. Real world consequence: my mp3 loads and plays without appreciable extra delay even though a massive file copy is happening in the background. Obviously there is a whole universe of strategies available and I don't want to argue the suitability of any particular one, my point is this: all such strategies require knowledge of the size of the job. So, are there OS APIs (Linux, or even Windows) which allow one to specify hints of the amount of work an operation will take? (NB you could claim disk I/O incorporates this implicitly but while(not_done){read_chunk();} would render it meaningless -- the kind of API I'm thinking of would specify megabytes at file open time, clock cycles at thread creation time, or something along these lines.) A: If all tasks represent work that will have no value until they are run to completion, then the best approach is to run all the jobs in some sequence so as to minimize the cost of other things' (or peoples') having to wait for them. In practice, many tasks represent a sequence of operations which may have some individual value, so if two tasks will take ten seconds each, having both tasks be half done at the ten-second mark may be better than having one task completed and one task not even started. This is especially true of tasks are producing data which will be needed by a downstream process which is performed by another machine, and the downstream process will be able to perform useful work any time it has received more data than it has processed. It is also somewhat true if part of the work entails showing a person that something useful is actually happening. A user who watches a progress bar count up over a period of 20 seconds is less likely to get unhappy than one whose progress bar doesn't even budge for ten seconds. A: The only argument in the "fair" system's favour is that if we did all of Y before any of X then a small job X would be delayed by a large job Y and we need to keep both jobs "responsive". That's exactly the rationale. Fair scheduling is fair in that it tends to distribute computing time, and therefore delays, equally among processes asking for it. So, are there OS APIs (Linux, or even Windows) which allow one to specify hints of the amount of work an operation will take? Batch systems do this, but, as you concluded yourself, this requires knowledge of the task at hand. Unix/Linux has the nice command which gives a process lower priority; it's a good idea to let any long running, CPU-bound process on a multitasking machine be "nice" so it doesn't hold up short and interactive tasks. ionice does the same for IO priority. (Also, ever since the early 1970s, Unix schedulers have dynamically raised the priority of processes that do not "eat up" their slices, so interactive processes get high CPU priority and stay responsive without CPU-bound ones holding everything up. See Thompson and Ritchie's early papers on Unix.) A: In common operating systems you typically don't care about the delay of the task but you try to maximize the throughput - in 110 seconds will both X and Y be done, period. Of course, some of the processes can be interactive and therefore the OS takes the extra overhead of context switches between processes to keep the illusion of computation in parallel. As you said, any strategy that should minimalize task's completion time would require to know how long it will take. That's very often a problem to find if the task is more than just copy a file - that's why sometimes the progress bar in some application goes to 99% percent and stays there for a while doing just the few last things. However, in real-time operating systems you often have to know task's worst case execution time or some deadline until the task must be finished - and then you are obligated to provide such "hint". The scheduler must then do a little bit smarter scheduling (moreover if there are some locks or dependencies included), on multiprocessors is the process sometimes NP-complete (then the scheduler uses some heuristics). I suggest you read something about RTOSes, Earliest Deadline First scheduling and Rate Monotonic scheduling.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's the max. length of a Facebook uid? I've seen multiple sizes and I don't want to waste server memory on a MySQL field which is reserving too much space for too many characters. What's the biggest they can get and will this ever change? A: This is how integer overflows, integer->string migrations etc happen, by making datatypes too restrictive. Splash out on a few bytes for a 128b varchar and save yourself the hassle down the road. If your user base gets so massive that you need to be worrying about how many bytes you will save by crunching data types of UIDs, consider yourself a huge success and that is a problem you will be happy to solve. Short answer, I dont think anyone will be able to answer your question, "ever" is a long time and who knows how many entities facebook will have enslaved by then. I'll end with a quote from one who said it best; We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. —Donald E. Knuth A: How could you ever be sure that this will never change? Better make it a varchar. A: Currently, Facebook UIDs are 64 bits integers. But I can't guarantee that won't change one day. A: The Facebook UID will never change because it is a unique identifier in their database. If it changed then facebook would cease to work
{ "language": "en", "url": "https://stackoverflow.com/questions/7566672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "37" }
Q: datatemplate in silverlight c#.net i am creating a datatemplate for items in listbox and loading it using (DataTemplate)XamlReader.Load(template), where template is string template = String.Concat(@ "<DataTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'> <Border BorderBrush='#334873' BorderThickness='1,1,1,1' Width='450'> <TextBox Height='72' HorizontalAlignment='Left' Margin='10,10,0,0' TextChanged="OnTextChanged" VerticalAlignment="Top" Width="460" />" ................... "</Border></DataTemplate>"); i m getting error because of "OnTextChanged" event registerd. I want to register a event in the template code. How to do it? A: To give you an answer: as you are using a Template it's rather difficult to map an event this way because the template doesn't know where it's put into. So OnTextChanged doesn't mean a thing in this context. You should consider bindings instead. As you allready use a DataTemplate the usual story would be to Bindd the TextBox-Text property to some model-property <TextBox Height='72' HorizontalAlignment='Left' Margin='10,10,0,0' Text="{Binding MyTextProperty}" VerticalAlignment="Top" Width="460" />" Of course the DataContext here should have a property MyTextProperty but without your code (where you use the template) I can give no further details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566673", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: File transformation, is it possible to add autoincrement to a setting In our automatic build we use MSBuild in combination with web.config transformation to create an acceptance config and a production config. We have added attributes to change config settings for example to change the cdn url's. <add key="cdn1url" value="http://cdn.acceptance.oursite.com/" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" /> Does anybody know if it is possible to add an autoincrement attribute? We want to add +1 to the version attribute (for css/img/js caching) on every production build. An other option could be the Teamcity build number, but I am not sure if that is possible A: * *You already have the Current or even Next Version number as msbuild property value - see 3 *You do not have it -> see PS at the bottom and then back to 3 *You can do it using FileUpdate task by providing a regexp and replacement text with a new version number: <FileUpdate Files="@(FilesToUpdate)" Regex="regex here" ReplacementText="$(NextVersionNumber)" /> PS: By using RegexMatch task you can extract current version and then by incrementing it you'll get a value for the $(NextVersionNumber) proeprty.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Error: Persistent store migration failed, missing source managed object model. I'm getting the following message error: Error: Persistent store migration failed, missing source managed object model. I've copied a xCode project from the company mac to my mac (same configuration: Snow Leopard, XCode 3.2 I've cleaned the project, deleted the build folder in finder, deleted Library/Application support/myApp folder deleted Library/Preferences/MyApp...plist file I still get the error. What's wrong with it ? thanks A: Quit the XCode Completely and reopen Xcode
{ "language": "en", "url": "https://stackoverflow.com/questions/7566676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can boolean properties' accessors be synthesized according to the coding guidelines (ex: isEnabled getter)? I've read the Coding Guidelines for Cocoa for accessor methods and it invites you to write getter methods for instance variables expressed as adjective (ex: enabled) as isEnabled instead of simply enabled.. is there a way to instruct the @synthesize keyword to produce such a getter or should you always write the getter method declaration and implementation by hand letting the @synthesize keyword generate only the setter method? I know they are just guidelines, but I think it is better to adhere to the behavior suggested by the official docs :) A: You can do the following: @property (nonatomic, getter=isEnabled) BOOL enabled; This will use isEnabled as the name for the getter method. You will just @synthesize it as normal: @synthesize enabled; A: As @Douwe Maan mentioned in his answer, "you can set the getter/setter method names in the @property declaration and just @synthesize it" to let the compiler take care of the getter and setter method definitions. But, if you want to have your own implementations of getter or setter or both, you can very well "implement the methods in your implementation file and omit the @synthesize line". You can "both @synthesize the property and add your own implementations of getter/setter methods", in which case compiler will just use your getter/setter method implementations without generating them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why curl prints XML response? I'm using curl to do post request, for some reason it prints xml response, which is something that I don't want to happend. how can I get rid of this behaviour? /** * Send post request **/ function post_request($sendHttpUrl, $data) { $ch = curl_init($sendHttpUrl); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml')); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); return $response; } A: You've set the RETURNTRANSFER flag on the wrong variable. Alter $curl to $ch. A: You have a typo in line: "curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); " It should read: curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
{ "language": "en", "url": "https://stackoverflow.com/questions/7566686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get CKA_ID from public/private Key pair of USB Token? I have a USB token contain certificate, public/private key pair, how can i get #define CKA_ID Key identifier for public/private key pair (default empty). From PKCS 11 document using C++? A: * *First find the certificate with CKO_CERTIFICATE. (C_FindObjectsInit, C_FindObjects, C_FindObjectsFinal) 2.Get the CKA_ID using C_GetAttributeValue
{ "language": "en", "url": "https://stackoverflow.com/questions/7566689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Replace the C socket API in C++ on z/OS I am including sys/socket.h, I still get compile time errors telling me that AF_INET is not defined. but still i am facing the issues getting the C sockets API to work properly in C++. please help me... A: check out the z/OS UNIX System Services sockets section in the z/OS XL C/C++ Programming Guide. Make sure you're including the necessary header files and using the appropriate #defines.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Could i extension the ModelStateDictionary Class in MVC3 in the ModelStateDictionary class there are only AddModelError and Add function , i want extention the class, add the method like AddModeSuccess,AddModelWarning. i have a look at the MVC3 source code and found there a lot of thing need add. i don't want to modify the MVC3 code, i just want to add a extention. how could i do? public void Add(KeyValuePair<string, ModelState> item) { ((IDictionary<string, ModelState>)_innerDictionary).Add(item); } public void Add(string key, ModelState value) { _innerDictionary.Add(key, value); } public void AddModelError(string key, Exception exception) { GetModelStateForKey(key).Errors.Add(exception); } public void AddModelError(string key, string errorMessage) { GetModelStateForKey(key).Errors.Add(errorMessage); } A: You could add them as extension methods to the ModelStateDictionary class: public static class ModelStateExtensions { public static void AddModelSuccess(this ModelStateDictionary modelState, ... some parameters) { ... } public static void AddModelWarning(this ModelStateDictionary modelState, ... some parameters) { ... } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7566701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: how to call date on cell selected from datepickerview in iphone hi friend i have to make date application i have groped tableview.i have one section and two row when my application start i am showing default date on both cell on first cell i was showing today day+1 and on nextcell i am showing today day+6 they i can see but - (id)init { [super initWithStyle:UITableViewStyleGrouped]; NSDate *todaysDate = [NSDate date]; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *dateComponents = [[NSDateComponents alloc] init]; [dateComponents setDay:1]; app.selectionData.fromDateSelected = [gregorian dateByAddingComponents:dateComponents toDate:todaysDate options:0]; [dateComponents release]; [gregorian release]; //this is for 6day NSDate *todaysDate1 = [NSDate date]; NSCalendar *gregorian1 = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *dateComponents1 = [[NSDateComponents alloc] init]; [dateComponents1 setDay:6]; app.selectionData.toDateSelected = [gregorian1 dateByAddingComponents:dateComponents1 toDate:todaysDate1 options:0]; [dateComponents1 release]; [gregorian1 release]; return self; } but know i want if the first cell selected date is changed from date pickerview and second cell date is less than the first cell selected date then change the second cell date automatically to first cell selected date+5 please help me how to solve it what the change i have to do in my code wher i am show by default this for once time on this this is my code on run time this code i writemin my firstview controller class where i am show this date when my application start in tableviewcellrowAtindexpath NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"dd/MM/yyyy"]; NSString*fromDate = [dateFormat stringFromDate:app.selectionData.fromDateSelected]; // NSString *toDate = [dateFormat stringFromDate:targetDate1]; NSString *toDate = [dateFormat stringFromDate:app.selectionData.toDateSelected]; if ([indexPath row] == 0 && [indexPath section] == 1) { cell.textLabel.text=@"From Date"; cell.detailTextLabel.text=fromDate; NSLog(@"this is for fromDate:%@",fromDate); } if ([indexPath row] == 1 && [indexPath section] == 1) { cell.textLabel.text=@"To Date"; cell.detailTextLabel.text=toDate; } [dateFormat release]; dateFormat = nil; this is code od dateview where i put my datepicker from here i selected date - (void)viewDidLoad { // if(datePicker != nil && [datePicker retainCount] > 0) // { // [datePicker release]; // // datePicker = nil; //} datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 40, 0, 0)]; [datePicker addTarget:self action:@selector(DateChangeForFinalPayMent) forControlEvents:UIControlEventValueChanged]; datePicker.datePickerMode = UIDatePickerModeDate; datePicker.date = [NSDate date]; datePicker.minimumDate = [NSDate date]; [self.view addSubview:datePicker]; [super viewDidLoad]; // Do any additional setup after loading the view from its nib. } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } -(void)DateChangeForFinalPayMent{ if ([selectionData type] == 0) [selectionData setFromDateSelected:[datePicker date]]; else [selectionData setToDateSelected:[datePicker date]]; // [super viewWillDisappear:animated]; } A: I wrote an example project for you that does this Basically - look at the delegate method of the picker view controller. It sends back a new date - and from that date you can calculate the second date and reload your table view. A: This is the code to get date from datepicker. 1st select the date & then select the cell you need to update. NSString *dateString = nil; -(void)DateChangeForFinalPayMent:(id)sender { NSLocale *usLocale = [[[NSLocale alloc]initWithLocaleIdentifier:@"en_US"] autorelease]; NSDate *pickerDate = [self.datePicker date]; NSString *selectionString = [[NSString alloc] initWithFormat:@"%@", [pickerDate descriptionWithLocale:usLocale]]; NSLog(@"string =%@",selectionString); dateString = selectionString; [selectionString release]; } On selecting the cell Perform this operation - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { selectedIndex = indexPath.row; NSArray *array = [NSArray arrayWithObject:indexPath]; [tablview reloadRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationFade]; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //some condition over here if(selectedIndex == indexPath.row) cell.textLabel = dateString; //some condition over her } You use this code according to your implementation..
{ "language": "en", "url": "https://stackoverflow.com/questions/7566702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Delete Site from Archiv Widget I created a Page in WP and i found it in the Archiv-Widget. Is there a way to create a Page and don't show it in the Archiv? I use WP 3.0.5 A: There isn't a way of excluding items using the built-in archive widget, unfortunately.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Working with large Backbone collections We're designing a backbone application, in which each server-side collection has the potential to contain tens of thousands of records. As an analogy - think of going into the 'Sent Items' view of an email application. In the majority of Backbone examples I've seen, the collections involved are at most 100-200 records, and therefore fetching the whole collection and working with it in the client is relatively easy. I don't believe this would be the case with a much larger set. Has anyone done any work with Backbone on large server-side collections? * *Have you encountered performance issues (especially on mobile devices) at a particular collection size? *What decision(s) did you take around how much to fetch from the server? *Do you download everything or just a subset? *Where do you put the logic around any custom mechanism (Collection prototype for example?) A: Like Elf said you should really paginate loading data from the server. You'd save a lot of load on the server from downloading items you may not need. Just creating a collection with 10k models locally in Chrome take half a second. It's a huge load. You can put the work on another physical CPU thread by using a worker and then use transient objects to sent it to the main thread in order to render it on the DOM. Once you have a collection that big rendering in the DOM lazy rendering will only get you so far. The memory will slowly increase until it crashes the browser (that will be quick on tablets). You should use object pooling on the elements. It will allow you to set a small max size for the memory and keep it there. I'm building a PerfView for Backbone that can render 1,000,000 models and scroll at 120FPS on Chrome. The code is all up on Github https://github.com/puppybits/BackboneJS-PerfView. It;s commented so theres a lot of other optimizations you'd need to display large data sets. A: * *Yes, at about 10,000 items, older browsers could not handle the display well. We thought it was a bandwidth issue, but even locally, with as much bandwidth as a high-performance machine could throw at it, Javascript just kinda passed out. This was true on Firefox 2 and IE7; I haven't tested it on larger systems since. *We were trying to fetch everything. This didn't work for large datasets. It was especially pernicious with Android's browser. *Our data was in a tree structure, with other data depending upon the presence of data in the tree structure. The data could change due to actions from other users, or other parts of the program. Eventually, we made the tree structure fetch only the currently visible nodes, and the other parts of the system verified the validity of the datasets on which they dependent independently. This is a race condition, but in actual deployment we never saw any problems. I would have liked to use socket.io here, but management didn't understand or trust it. *Since I use Coffeescript, I just inherited from Backbone.Collection and created my own superclass, which also instantiated a custom sync() call. The syntax for invoking a superclass's method is really useful here: class Dataset extends BaseAccessClass initialize: (attributes, options) -> Dataset.__super__.initialize.apply(@, arguments) # Customizations go here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: How can I extract sprocs/tables/functions from a specific schema? I need to extract all the tables, stored procs and functions from an SQL Server 08 db that are under a particular schema. I could filter the displayed items in Management Studio and then do Script As -> Drop/Create for each of them, but I would really like to avoid this as there are quite a few items in the schema. Is there a way to do this? Edit: I've had a look at this question (possible duplicate I just found). I'd rather not use an external tool as suggested, since this is at work and I'd need to get approval to use one. Nor do I want one big Create Database script - I need separate scripts for each table/sproc/function. A: select object_name(obj.object_id), sch.name, co.definition from sys.objects obj join sys.schemas sch on sch.schema_id = obj.schema_id left join sys.sql_modules co on co.object_id = obj.object_id where sch.name = 'DBO' --here goes your schema name --The syscoments table was used back in sql 2000 and you should not use it anymore - but when so it is the sys.syscomments table A: Visual Studio 2010 Premium includes database project tooling support that allows you to perform database schema comparisons between databases (where you can filter to only a specified database schema) and extract all the objects (and configuration) in a live database to a VS2010 database project, creating a script per object. See Working with Database Projects. A: Something based on SELECT [text] FROM [syscomments]
{ "language": "en", "url": "https://stackoverflow.com/questions/7566723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FastReport processing click on the field The question is how to handle a click on the field and call the procedure from the main program. A: Yes, it is. I don't know what you mean with the field and what version of FastReport you are using, but I'll try to show you the principle of interaction with the report objects (this can be done for any of the report objects in a preview window). However the TfrxReport.OnClickObject event differs with FastReport versions so depending on what version you are using this might differ little bit. The following example (written with version 4.12) interacts with Memo1, what is the Text object (TfrxMemoView) placed in design time on the report frxReport1. The rest of what you need is to write the code for OnClickObject event handler in your main form. procedure TForm1.frxReport1ClickObject(Sender: TfrxView; Button: TMouseButton; Shift: TShiftState; var Modified: Boolean); begin // comparing names is not so efficient, so for many controls I would use // rather Sender.Tag and set the Tag property at report design time and // use case Sender.Tag of construction if Sender.Name = 'Memo1' then // is the Sender my Memo1 text object ? begin if fsBold in (Sender as TfrxMemoView).Font.Style then // is Memo1 font bold ? begin (Sender as TfrxMemoView).Font.Style := []; // then set it to default ShowMessage('You just set memo text font to default'); // display message end else begin (Sender as TfrxMemoView).Font.Style := [fsBold]; // else set it to bold ShowMessage('You just emphased your memo text font'); // display message end; Modified := True; // setting Modified to True causes the report to refresh end; end; A: If you need put another text, try one option: (Sender as TfrxMemoView).Text := 'Hi friend'; or: TfrxMemoView(Sender).Text := 'Hi friend';
{ "language": "en", "url": "https://stackoverflow.com/questions/7566724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Fluent NHibernate - always drop table Hi I start learn Fluent NHibernate. I am using this tutorial http://www.d80.co.uk/post/2011/02/20/Linq-to-NHibernate-Tutorial.aspx. Here is my sample code: public class Account { public virtual int Id { get; set; } public virtual string Nick { get; set; } public virtual string Password { get; set; } } public class AccountMap:ClassMap<Account> { public AccountMap() { Id(x => x.Id); Map(x => x.Nick); Map(x => x.Password); } } public class NHiberanteHelper { private static ISessionFactory _sessionFactory; private static ISessionFactory SessionFactory { get { if (_sessionFactory == null) InitializeSessionFactory(); return _sessionFactory; } } private static void InitializeSessionFactory() { _sessionFactory = Fluently.Configure() //NHibernate bude pouzivat ovladace pre MS SQL 2008 .Database(MsSqlConfiguration.MsSql2008 .ConnectionString( @"Server=JAN-MSI\SQLEXPRESS;Database=SimpleNHibernate;Trusted_Connection=True;").ShowSql() ) //urci NHibernatu kde ma hladat mapovacie subory .Mappings(m=>m.FluentMappings.AddFromAssemblyOf<Account>()) //ak tabs nie su v DB vytvori .ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true)) //vytvori jeden session pre cely life-time apps .BuildSessionFactory(); } public static ISession OpenSession() { return SessionFactory.OpenSession(); } } class Program { static void Main(string[] args) { using (var session = NHiberanteHelper.OpenSession()) { using (var trans = session.BeginTransaction()) { var account = new Account { Nick = "dfdwf", Password = "xxx" }; session.Save(account); trans.Commit(); } } Console.ReadKey(); } } Problem is that this Fluent configuration always drop table in database. I need only check if table doesnt exist so create table not always when code run drop table. A: Your call to new SchemaExport(cfg).Create(true, true) is exporting the configuration to the database. This will drop and re-create it (it's not clever enough to work out the differences and just execute them. You could use SchemaUpdate, which will update the schema instead. Here's a blog post about it: http://geekswithblogs.net/dotnetnomad/archive/2010/02/22/138094.aspx I would always prefer to update tables myself or use something like Redgate's SQLCompare to update a schema whilst preserving data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JAX-WS Client can't connect after redeployment (NullPointerException in SymbolTable) When we redeploy our webapplication with an jax-ws client, the client can not connect to the webservice. While connecting to the server it throws this exception: java.lang.NullPointerException: null at com.ctc.wstx.util.SymbolTable.findSymbol(SymbolTable.java:385) ~[woodstox-core-asl-4.0.8.jar:4.0.8] at com.ctc.wstx.sr.StreamScanner.parseLocalName(StreamScanner.java:1833) ~[woodstox-core-asl-4.0.8.jar:4.0.8] at com.ctc.wstx.sr.BasicStreamReader.handleNsAttrs(BasicStreamReader.java:2963) ~[woodstox-core-asl-4.0.8.jar:4.0.8] at com.ctc.wstx.sr.BasicStreamReader.handleStartElem(BasicStreamReader.java:2907) ~[woodstox-core-asl-4.0.8.jar:4.0.8] at com.ctc.wstx.sr.BasicStreamReader.handleRootElem(BasicStreamReader.java:2049) ~[woodstox-core-asl-4.0.8.jar:4.0.8] at com.ctc.wstx.sr.BasicStreamReader.nextFromProlog(BasicStreamReader.java:2029) ~[woodstox-core-asl-4.0.8.jar:4.0.8] at com.ctc.wstx.sr.BasicStreamReader.next(BasicStreamReader.java:1100) ~[woodstox-core-asl-4.0.8.jar:4.0.8] at com.sun.xml.internal.ws.util.xml.XMLStreamReaderFilter.next(XMLStreamReaderFilter.java:81) ~[na:1.7.0-ea] at com.sun.xml.internal.ws.streaming.XMLStreamReaderUtil.next(XMLStreamReaderUtil.java:78) ~[na:1.7.0-ea] at com.sun.xml.internal.ws.streaming.XMLStreamReaderUtil.nextContent(XMLStreamReaderUtil.java:99) ~[na:1.7.0-ea] at com.sun.xml.internal.ws.streaming.XMLStreamReaderUtil.nextElementContent(XMLStreamReaderUtil.java:89) ~[na:1.7.0-ea] at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.hasWSDLDefinitions(RuntimeWSDLParser.java:231) ~[na:1.7.0-ea] at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.parse(RuntimeWSDLParser.java:141) ~[na:1.7.0-ea] at com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser.parse(RuntimeWSDLParser.java:120) ~[na:1.7.0-ea] at com.sun.xml.internal.ws.client.WSServiceDelegate.parseWSDL(WSServiceDelegate.java:256) ~[na:1.7.0-ea] at com.sun.xml.internal.ws.client.WSServiceDelegate.<init>(WSServiceDelegate.java:219) ~[na:1.7.0-ea] at com.sun.xml.internal.ws.client.WSServiceDelegate.<init>(WSServiceDelegate.java:167) ~[na:1.7.0-ea] at com.sun.xml.internal.ws.spi.ProviderImpl.createServiceDelegate(ProviderImpl.java:95) ~[na:1.7.0-ea] at javax.xml.ws.Service.<init>(Service.java:77) ~[na:1.7.0-ea] After restarting TomCat the client could successfully connect to the sever again. (Tested with JDK 6 and JDK 7) A: We'll use spring-ws instead, tested with redeploying without a problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Change the text of UISwitch I want to change the switch control text YES/NO in place of ON/OFF , i am not know is it possible or not. if its possible and any one know about it please help me? Thanks A: I think its not possible to change the text of switch in proper way, but every problem has minimum one solution so for your problem you have to create the custom switch control for help download the code from here 1 : http://www.xprogress.com/post-30-uiswitch-tutorial-example-how-to-use-the-switch-in-xcode-for-iphone-sample-included/ 2 : http://www.catamount.com/blog/1063/uicustomswitch-customizing-uiswitch-color-it-change-labels/ 3 : help check this also http://www.xprogress.com/post-30-uiswitch-tutorial-example-how-to-use-the-switch-in-xcode-for-iphone-sample-included/ Thanks, Raj A: There is no way to change this two values in easy way. You can look here: http://www.catamount.com/blog/1063/uicustomswitch-customizing-uiswitch-color-it-change-labels/ but this solution make custom UISwitch which got other graphics A: I currently use this open source library called RCSwitch . Much more robust than the others mentioned.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: load does not work with certain url's I use a web service that lets me easily create a contact form and manages the messages for me. I have this direct link from them that works fine and opens a new page with the contact form. This is the link: http://apps.cyberth.com/webform/?event=form.show&formId=8957&key=B5220027CF I use jQuery in my site to load pages into divs and elsewhere on the site this piece of code works just fine: $('#news').load("news.html #news"); But using an near identical snip of code with the form url no longer works: $("#contactForm").load("http://apps.Cyberth.com/webform/?event=form.show&formId=8957&key=B5220027CF"); What can be causing this? I read that it might be a security issue preventing jQuery Ajax from loading pages not stored on the local server. Also how can I isolate what the issue is in the future? A: as cross-domain requests are not allowed by browsers due to same-origin-policy. one way is to make a web proxy, e.g call your server proxy from the client like $.ajax({ url:'/your/domain', //other params success:function(data){ //data received that is sent by the server } }); on your server side, which ever language/technology you are using make a request to the desired service, in you case it is http://apps.Cyberth.com/webform/?event=form.show&formId=8957&key=B5220027CF then send the response to the client side. here are some useful links http://devlog.info/2010/03/10/cross-domain-ajax/ http://json-p.org/ http://msdn.microsoft.com/en-us/library/dd573303%28v=vs.85%29.aspx http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-cross-domain-ajax-request-with-yql-and-jquery/ http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/ A: AJAX can not cross domain for security reason.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to wrap create and sqlalchemy-migrate alter statments in a transaction I'm trying some db schema changes to my db, using the sqlalchemy table.create and sqlalchemy-migrate table.rename methods, plus some insert into select statments. I want to wrap all of this in a transaction. I can't figure out how to do this. This is what I tried: engine = sqlalchemy.engine_from_config(conf.local_conf, 'sqlalchemy.') trans = engine.connect().begin() try: old_metatadata.tables['address'].rename('address_migrate_tmp', connection=trans) new_metatadata.tables['address'].create(connection=trans) except: trans.rollback() raise else: trans.commit() But it errors with: AttributeError: 'RootTransaction' object has no attribute '_run_visitor' (I tried using sqlalchemy-migrate column.alter(name='newname') but that errors, and does not work in a transaction, and so leaves my db in a broken state. I also need to rename multiple columns, and so I decide to roll my own code.) A: Ah - I need to simply use the connection that the transaction was created on. engine = sqlalchemy.engine_from_config(conf.local_conf, 'sqlalchemy.') conn = engine.connect() trans = conn.begin() try: old_metatadata.tables['address'].rename('address_migrate_tmp', connection=conn) new_metatadata.tables['address'].create(bind=conn) except: trans.rollback() raise else: trans.commit()
{ "language": "en", "url": "https://stackoverflow.com/questions/7566738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get content of httpWebresponse in proper string form? Sometimes I am getting kind of garbled response from several web sites. Here is my code: Stream responseStream = response.GetResponseStream(); buffer = new Byte[256];// int bytesRead; while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0) { outStream.Write(buffer, 0, bytesRead); //resp=resp+ .UTF8.GetString(buffer, 0, bytesRead); resp=resp + Encoding.ASCII.GetString(buffer); //resp is string } when I request from www.google.co.in I get following characters in resp string: ?\b\0\0\0\0\0??}y?F?????????Z??????{7m???oX?\r?Y???33??d;y????n?0? How should I overcome this problem? Is it related to encoding? A: The response I received was GZip-compressed, so I just decompressed the response stream as shown below: Stream responseStream = response.GetResponseStream(); responseStream = new GZipStream(responseStream, CompressionMode.Decompress); now one can read the stream using the code I provided above. @Kalyan Thanks for your help!!! A: Refer to How to use the GetResponseStream method in C# and also Usage of HttpWebResponse and HttpWebRequest for getting an idea about reading contents from HttpWebResponse. Hope it will help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQLite, how to entities associations without foreign keys? I am trying to figure out the way of creating table without a foreign key under sqlite. I would like to avoid the use of foreign key due its incompatibility under some applications I am working now. Could anyone please show a simple example with maybe two tables? Thank you. Simple example: How do I select all tracks from one specific artist? CREATE TABLE artist( artistid INTEGER PRIMARY KEY, artistname TEXT ); CREATE TABLE track( trackid INTEGER, trackname TEXT, trackartist INTEGER ); A: You can have relationships between tables without declaring a foreign key. You simply do SELECT a.*, t.* FROM artist a INNER JOIN track t ON a.artistid = t.trackartist; (substituting the actual columns you want in place of a.*, t.*). You can do this without declaring that trackartist is a foreign key to artist(artistid). If you do make that declaration, the difference is that SQLite will ensure that you never put a value in trackartist that is not a valid artistid and that you never change or remove an artistid that is used in trackartist. Foreign keys are a mechanism to maintain the integrity of the association between tables but you can "create" any association you want in a SELECT statement independent of any primary or foreign keys declared in the database. A: If you don't specify a foreign key, then there is no foreign key. SELECT t.trackname, t.trackid FROM track t INNER JOIN artist a ON a.artistid = t.trackartist WHERE a.artistname = 'Alex'
{ "language": "en", "url": "https://stackoverflow.com/questions/7566742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Memory management with NSThread I have an app that needs to signal continuously a word in morse code. I did this by creating an NSThread and running some code inside the selector with a "while loop". Here is the code: @implementation MorseCode -(void)startContinuousMorseBroadcast:(NSString *)words{ if (!(threadIsOn)) { threadIsOn = YES; s myThread = [[NSThread alloc] initWithTarget:self selector:@selector(threadSelector:) object:words]; [myThread start]; } if (morseIsOn) { morseIsOn = NO; } else{ morseIsOn = YES; } } -(void)threadSelector:(NSString *)words{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; while (![myThread isCancelled]) { // ///it Does some code here } //end While NSLog(@"Cleaning the pool"); [pool drain]; } @end When exiting the application (the user presses the button), in the applicationDidEnterBackground the following selector is executed: -(void)cleanUpMorseObject{ //this is defined in the MorseCode class, same as threadSelector if (threadIsOn) { NSLog(@"cleanUpMorseObject, threadIsOn"); threadIsOn = NO; morseIsOn = NO; [myThread cancel]; [myThread release]; } } The application responds correctly to the event, I’ve checked with nslog. And then [MorseCode release] is called. The code looks like this: -(void)applicationDidEnterBackground{ //this happens in the ViewController [theMorse cleanUpMorseObject]; //theMorse is an instance of MorseCode [theMorse release]; } The problem: Although I call [myThread release] and then [theMorse release] the retainCount of the theMorse is still above 0 (It doesn’t call the dealloc). The Leaks Instrument doesn’t say I have a leak, but if I open and close the application for like 10 times eventually the Iphone resets. Also in the debugger eventually I see the “Received memory warning. Level=2”. Also I never see the NSLog before the pool drain… The app doesn't run in the background. Any ideas? Thank you A: You really should schedule the sending of the message on the RunLoop, the probably easiest way being to schedule a timer (repeat infinitely, and short repeat period like FLT_EPSILON or similar) instead of using threads for that. Working with threads is complicated and as everyone should avoid it (as Apple stated in its Concurrency Programming Guide, and as most documentation said, "Threads are evil" ;)). That's because multithreading is a vast and complicated subject, that needs synchronizations, resources protection, being aware of dead locks, critical sections & so on, good and adapted memory mgmt, and much much more. In general if you need to do stuff in the background: * *Use mechanisms already in place (like asynchronous implementation of some operations and being signalled by delegate methods or notifications) if available *Use methods like performInBackground: *Use NSOperationQueues *Use GCD *And only in last resort and if there are no other options (or for really specific cases), use NSThread. This will avoid you a lot of issues as all the other, higher APIs will take care of a lot of things for you. Moreover, using threads for this task like you do is likely to use much more CPU (will probably reach 100% usage quickly) as there won't be any time left for the task scheduler (that also why even GCD that takes care of all stuff like that is way better than NSThreads, and scheduling the sending in the RunLoop is even better for the CPU if you don't need strong RT constraints) A: First, retainCount can never return 0. It is a useless method. Don't call it. Secondly, leaks only detects objects that are no longer referenced. If a thread is still running, it isn't leaked. Finally, a thread doesn't stop when you call cancel. It just sets a flag that you have to check via isCancelled to see if it is time to stop work in the thread. Are you doing that? OK -- easy stuff answered. Next? Try build and analyze. Then use the Allocations instrument and turn on reference count tracking. Then see what is calling retain an extra time. A: I decided to give up the NSThread class and used another aproach: -(void)playSOSMorse{ if ([myTimer isValid]) { [myTimer invalidate]; [myTimer release]; myTimer = nil; } myTimer = [[NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(tymerSelector) userInfo:nil repeats:NO] retain]; //the timer calls a selector that performs a selector in background } -(void)tymerSelector{ [self performSelectorInBackground:@selector(threadSelector2) withObject:nil]; } -(void)threadSelector2 { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; //some code here [pool drain]; //calls another selector on the main thread to see if it needs to fire the timer again and restart the cycle [self performSelectorOnMainThread:@selector(selectorOnMainThread) withObject:nil waitUntilDone:NO]; } -(void)selectorOnMainThread{ [myTimer invalidate]; [myTimer release]; myTimer = nil; if (morseIsOn) { //this is a boolean that if it is true (YES) calls the timer again [self playSOSMorse]; } } I hope this helps somebody :) Thank you
{ "language": "en", "url": "https://stackoverflow.com/questions/7566744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Regular expression to match only two numbers I have such string: something: 20 kg/ something: 120 kg I have this regex ("[0-9]{1,2} kg", string), but it returns 20kg both times. I need to return 20kg only in first case. A: Try this: (?<!\d)\d{1,2}\s+kg The (?<!...) is a negative look behind. So it matches one or two digits not preceded by a digit. I also changed the literal space with one or more space chars. Seeing you've asked Python questions, here's a demo in Python: #!/usr/bin/env python import re string = 'something: 20 kg/ something: 120 kg' print re.findall(r'(?<!\d)\d{1,2}\s+kg', string) which will print ['20 kg'] edit As @Tim mentioned, a word boundary \b is enough: r'\b\d{1,2}\s+kg'
{ "language": "en", "url": "https://stackoverflow.com/questions/7566749", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to display Image on top of every view in android (eg. Like cracked screen app in market) I want to create something like Better Cracked Screen. The cracked screen remains top of everything. I am not able to get how to make such thing which resides top of everything. Behavior : For example when cracked screen is displayed, and if i press home button then it shows me the home but the cracked screen remains as it is(here on top of home).. doesnot matter whereever you move.. cracked screen appears intact.. Search Results so far : Google API Demos : Translucent GLSurfaceView Can anyone guide me how can i achieve this task ? Or can anyone please provide me a sample code for this ? A: Use android.permission.SYSTEM_ALERT_WINDOW. That will allow you to create a window that is placed on top of all application windows. A key insight to have here is that you can not work on a View level to solve this. A View hierarchy is drawn inside a window, so to place something on top of all windows, you need another window. A: I would guess it is an ImageView that is created as the last part of your xml files (meaning it is on top of the stack/ above all other elements). And the Image in this ImageView is mostly transparent so that you see the elements below it
{ "language": "en", "url": "https://stackoverflow.com/questions/7566752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: sfDoctrineGuardPlugin and admin filters I have an admin that uses sfDoctrineGuardPlugin. I also have another table, sf_guard_user_profile, that extends the sf_guard_user table, to include more fields, such as address, age etc My problem is, I am embedding the profile (sf_guard_user_profile) information into the sf_guard_user record when viewing the records in the admin generated module. This works fine, but I'd like to then be able to use some of the filters from the sf_guard_user_profile table. I have tried to add these into the generator.yml file, but I this throws an error generator.yml ................... filter: display: [username, email_address, address_1, is_active ] Widget "address_1" does not exist. address_1 is a field in sf_guard_user_profile Is this possible to do? Thanks A: Ok, so I had to do a little bit of work in the sfGuardUserFormFilter class, $this->widgetSchema['age'] = new sfWidgetFormInputText(array( 'label' => 'Age' )); //Type of validator for filter $this->validatorSchema['age'] = new sfValidatorPass(array ('required' => false)); public function getFields() { $fields = parent::getFields(); $fields['age'] = 'age'; return $fields; } public function addAgeColumnQuery($query, $field, $value) { $rootAlias = $query->getRootAlias(); $query->where('p.age LIKE ?', '%'.$value.'%'); //remember to return the $query! return $query; } I could then use the age field in the generator.yml file. Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7566754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: multi-thread opening file hangs when fanotify is on I use this fanotify sample to monitor open/access perms on the whole file system(/): http://git.infradead.org/users/eparis/fanotify-example.git. Then I have a test program with multiple threads, each thread iterate the sample foder and open/close the files in it, sometimes my program hangs at open(). OS: Ubuntu 2.6.38-11 x86_64. Is it a bug of fanotify that it does not support multiple-thread opening? The code of my test program: #include <stdlib.h> #include <stdio.h> #include <pthread.h> #include <ctype.h> #include <unistd.h> #include <dirent.h> #include <string.h> #include <sys/stat.h> #include <errno.h> #include <fcntl.h> #include <dirent.h> //open file function void open_file( char* file ) { int fd = -1; fd = open( file, O_WRONLY, 0x666 ); if( fd >= 0 ) { printf("open:%s\n", file ); close( fd ); } } //iterate directory function void printdir(char *dir, int depth) { DIR *dp; struct stat statbuf; char pathbuf[2048] = {0}; struct dirent entry; struct dirent *entryPtr = NULL; //printf("opendir %s\n", dir ); usleep( 300 ); if((dp = opendir(dir)) == NULL) { if( errno != ENOTDIR ) { fprintf(stderr,"cannot open directory: %s\n", dir); perror("open fial"); } return; } readdir_r( dp, &entry, &entryPtr ); while( entryPtr != NULL) { snprintf(pathbuf,2000, "%s/%s\0", dir, entry.d_name ); printf("iteraotr:%s\n", pathbuf ); lstat( pathbuf, &statbuf ); if(S_ISDIR( statbuf.st_mode )) { /* Found a directory, but ignore . and .. */ if(strcmp(".",entry.d_name) == 0 || strcmp("..",entry.d_name) == 0) { } else { //printf("%d,%s\n",depth, entry->d_name); printdir( pathbuf, depth+1); } } else { //printf("%*s%s\n",depth,"",entry->d_name); open_file( pathbuf ); } readdir_r( dp, &entry, &entryPtr ); } closedir(dp); } //thread function void* iterator_dir( void* data ) { char* path = (char*)data; printf("In iterator_dir(): %s\n", path ); printdir( path, 0 ); return NULL; } pthread_t threadID[10] = {0}; //main function int main( int argc, char** argv ) { if( argc < 3 ) { printf("Usage: %s <thread_num> <file>\n", argv[0] ); exit(0); } if( isdigit( (char)*argv[1] ) == 0 ) { printf(" Thread num is 0 - 9\n"); exit(0); } int thread_num = atoi( argv[1] ); char* res; pthread_attr_t attr; pthread_attr_init(&attr); int i = 0; for( i = 0; i < thread_num; ++i ) { pthread_create( &threadID[i], &attr, &iterator_dir, argv[2]); } for( i = 0; i < thread_num; ++i ) { pthread_join( threadID[i] , &res ); } } 2011-09-28 Edit: I comment the open file operation, only keep the iterate directory part. The application still hangs. This is the output of strace: enter code here pid 10692] open("/home/byang//.config/menus", O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC <unfinished ...> [pid 10691] write(1, "1213966080 opendir /home/byang//"..., 56) = 56 ......... [pid 10689] madvise(0x7f3c48dbc000, 8368128, MADV_DONTNEED) = 0 [pid 10689] _exit(0) = ? Process 10689 detached [pid 10688] <... futex resumed> ) = 0 [pid 10688] futex(0x7f3c47db99d0, FUTEX_WAIT, 10692, NULL <unfinished ...> It hangs here, when I close the fanotify, it continues... [pid 10692] <... open resumed> ) = 11 [pid 10692] getdents(11, /* 4 entries */, 32768) = 128 [pid 10692] lstat("/home/byang//.config/menus/applications.menu", {st_mode=S_IFREG|0644, st_size=233, ...}) = 0 10688 is the parent thread; 10689,10691,10692 are the child threads that iterating the directories. It seems that 10692 are waiting the reply from fanotify? A: It's a bug of Kernel's fanotify. I posted a patch to Linux-Kernel: When multiple threadsiterate the same direcotry, some thread will hang. This patch let fanotify differentiate access events from different threads, prevent fanotify from merging access events from different threads. http://marc.info/?l=linux-kernel&m=131822913806350&w=2 ------------------------------- diff -r -u linux-3.1-rc4_orig/fs/notify/fanotify/fanotify.c linux-3.1-rc4/fs/notify/fanotify/fanotify.c --- linux-3.1-rc4_orig/fs/notify/fanotify/fanotify.c 2011-08-29 12:16:01.000000000 +0800 +++ linux-3.1-rc4/fs/notify/fanotify/fanotify.c 2011-10-10 12:28:23.276847000 +0800 @@ -15,7 +15,8 @@ if (old->to_tell == new->to_tell && old->data_type == new->data_type && - old->tgid == new->tgid) { + old->tgid == new->tgid && + old->pid == new->pid) { switch (old->data_type) { case (FSNOTIFY_EVENT_PATH): if ((old->path.mnt == new->path.mnt) && @@ -144,11 +145,19 @@ return PTR_ERR(notify_event); #ifdef CONFIG_FANOTIFY_ACCESS_PERMISSIONS - if (event->mask & FAN_ALL_PERM_EVENTS) { - /* if we merged we need to wait on the new event */ - if (notify_event) - event = notify_event; - ret = fanotify_get_response_from_access(group, event); + //if overflow, do not wait for response + if(fsnotify_isoverflow(event)) + { + pr_debug("fanotify overflow!\n"); + } + else + { + if (event->mask & FAN_ALL_PERM_EVENTS) { + /* if we merged we need to wait on the new event */ + if (notify_event) + event = notify_event; + ret = fanotify_get_response_from_access(group, event); + } } #endif diff -r -u linux-3.1-rc4_orig/fs/notify/notification.c linux-3.1-rc4/fs/notify/notification.c --- linux-3.1-rc4_orig/fs/notify/notification.c 2011-08-29 12:16:01.000000000 +0800 +++ linux-3.1-rc4/fs/notify/notification.c 2011-10-10 12:27:09.331787000 +0800 @@ -95,6 +95,7 @@ BUG_ON(!list_empty(&event->private_data_list)); kfree(event->file_name); + put_pid(event->pid); put_pid(event->tgid); kmem_cache_free(fsnotify_event_cachep, event); } @@ -132,6 +133,14 @@ return priv; } +bool fsnotify_isoverflow(struct fsnotify_event *event) +{ + if(event==q_overflow_event) + { + return true; + } + return false; +} /* * Add an event to the group notification queue. The group can later pull this * event off the queue to deal with. If the event is successfully added to the @@ -374,6 +383,7 @@ return NULL; } } + event->pid = get_pid(old_event->pid); event->tgid = get_pid(old_event->tgid); if (event->data_type == FSNOTIFY_EVENT_PATH) path_get(&event->path); @@ -417,6 +427,7 @@ event->name_len = strlen(event->file_name); } + event->pid = get_pid(task_pid(current)); event->tgid = get_pid(task_tgid(current)); event->sync_cookie = cookie; event->to_tell = to_tell; diff -r -u linux-3.1-rc4_orig/include/linux/fsnotify_backend.h linux-3.1-rc4/include/linux/fsnotify_backend.h --- linux-3.1-rc4_orig/include/linux/fsnotify_backend.h 2011-08-29 12:16:01.000000000 +0800 +++ linux-3.1-rc4/include/linux/fsnotify_backend.h 2011-10-10 12:27:48.587369000 +0800 @@ -238,6 +238,7 @@ u32 sync_cookie; /* used to corrolate events, namely inotify mv events */ const unsigned char *file_name; size_t name_len; + struct pid *pid; struct pid *tgid; #ifdef CONFIG_FANOTIFY_ACCESS_PERMISSIONS @@ -378,6 +379,8 @@ struct fsnotify_event_private_data *priv, struct fsnotify_event *(*merge)(struct list_head *, struct fsnotify_event *)); +/*true if the event is an overflow event*/ +extern bool fsnotify_isoverflow(struct fsnotify_event *event); /* true if the group notification queue is empty */ extern bool fsnotify_notify_queue_is_empty(struct fsnotify_group *group); /* return, but do not dequeue the first event on the notification queue */
{ "language": "en", "url": "https://stackoverflow.com/questions/7566755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why is my log showing a partial rendered twice Rails I want to show an easier example of the same thing: Started GET "/greetings/new" for 127.0.0.1 at 2011-09-29 15:30:46 +0700 Processing by GreetingsController#new as JS Board Load (0.6ms) SELECT "boards".* FROM "boards" WHERE "boards"."id" = 12 LIMIT 1 User Load (0.9ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1 Upload Load (0.2ms) SELECT "uploads".* FROM "uploads" WHERE ("uploads".uploadable_id = 1 AND "uploads".uploadable_type = 'User') LIMIT 1 Rendered greetings/_greeting_form.html.erb (108.9ms) Rendered greetings/_greeting_form.html.erb (4.1ms) Rendered greetings/new.js.erb (116.9ms) Completed 200 OK in 302ms (Views: 126.5ms | ActiveRecord: 1.7ms) The log shows that the _greeting_form.html.erb is being rendered twice. The partial is rendered with an Ajax call to the controller. Controller: def new @greeting = Greeting.new @user = current_user || User.new respond_to do |format| format.js {render :action => 'new'} end end new.js.erb if($('#boxGreeting').length == 0){ $('#buttons').after($(" <%=escape_javascript(render 'greeting_form', :user => @user, :greeting => @greeting) %>").fadeIn('fast')); } else { $('#boxGreeting').replaceWith("<%=escape_javascript(render 'greeting_form', :user =>@user, :greeting => @greeting)%>"); } A: You are calling render 'greeting_form' twice in your new.js.erb. If you look into the output .js file in your browser you will see that the partial appears twice. The browser will later evaluate your javascript if-clause and use either the first or the second of the pre-rendered "greeting_form" partials. You can avoid parsing it twice by assigning the render result to a variable and then use this variable within the if or else part: var greeting_form = " <%=escape_javascript(render 'greeting_form', :user => @user, :greeting => @greeting) %>"; if($('#boxGreeting').length == 0) { $('#buttons').after($(greeting_form).fadeIn('fast')); } else { $('#boxGreeting').replaceWith(greeting_form); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7566757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Embed Groovy in an Android Java App Basically, I need to run Groovy Scripts to manipulate Java objects, and GroovyShell / GroovyScriptEngine seems to be the best way to do so. Is it possible to embed Groovy inside a Java App? I tried placing the groovy-all-1.8.2.jar into my Android Java App's libs folder, referenced it then hit compile but I got a bunch of errors. How do I do this? A: I don't believe this will work. Groovy converts scripts to bytecode, and as the Dalvik bytecode is different to the Java bytecode that Groovy expects, I believe it will have problems... The Discobot from a few years ago has been resurrected though, and great progress is being made so there is hope on the horizon. But that doesn't help you today... A: In near future it will be possible: http://skillsmatter.com/podcast/home/groovy-android/ A: I have found it recelty. You can find the solution from http://melix.github.io/blog/2014/06/grooid.html. Check it http://glaforge.appspot.com/article/groovy-2-3-3-and-groovy-2-4-beta-1-with-android-support too! A: Since 09/2011, Discobot seems to be stuck. The last results seem to be : most of it works, but this is very slow. Groovy 2.0 is out now, and Guillaume Laforge (insider) says it could helps - especially because of the @CompileStatic new feature of Groovy 2.0. Since then, Groovy 2.0.1...2.0.4, it looks that static compilation got a lot of bugfixes. But for now, on the official website of Groovy, Android is not discussed, nobody seems to really be in charge (see wiki and wiki). A: Here is an example of what you are trying to accomplish. https://github.com/melix/grooidshell-example It is pretty slow since it has to first compile to class files on the android device and then convert them to dex, but it will accomplish what you are looking for. A: A better choice for running scripts on Android is SnapScript. It does not rely on Bytecode and is fully supported on Android.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566763", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Grails: derived fields in domain classes Suppose I have a domain class branch which has several members: … static hasMany = [ members:Member ]; … Now suppose I want to have the number of members of that branch readily available, to have it displayed in the list and view actions, so perhaps storing that information into a variable in the domain class itself would be a good idea? … Integer memberCount = members.size(); static constraints = { memberCount(editable:false); } … (Is this the correct syntax?) Edit: This is not the correct syntax. I cannot assess the size of the members list, as it doesn’t exist yet and grails will complain about size() not being applicable to null objects. What else could I try? However, as memberCount is now a variable in the domain class, it is possible to assign a value to it upon creation of the Branch (which is contra-intuitive) and it will not be updated automatically once a new Member is added. It is of course possible to reach the desired result in a different way. I could manipulate the view.gsp and list.gsp in the /Branch directory, add some additional <td>s there etc. But that does not seem very elegant to me. Basically, I think what I am looking for is some way to tell grails that a certain variable is derived, should not be setable by the user, but update whenever necessary. Is there such way? A: You can add any property you don't want persisted to the transients static list: static transients = ['memberCount'] See this page in the manual Also, this StackOverflow question answers the same question Also, a better way to do derived properties may be to use the Derived Properties feature of GORM
{ "language": "en", "url": "https://stackoverflow.com/questions/7566770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Searching by regexp when constructing LINQ expression using Expression classes Here is the post which describes the way to create an Expression<Func<MyClass, bool>> predicate dynamically. Here is a snippet: var param = Expression.Parameter(typeof(string), "p"); var len = Expression.PropertyOrField(param, "SomeText"); var body = Expression.Equal( len, Expression.Constant("Text")); var lambda = Expression.Lambda<Func<string, bool>>( body, param); I wonder how do I apply a regexp to a string instead of Equality. Is there a possibility? A possible pseudo code would be like: var param = Expression.Parameter(typeof(string), "p"); var len = Expression.PropertyOrField(param, "SomeText"); var body = Expression.Regexp( len, @"\D+"); var lambda = Expression.Lambda<Func<string, bool>>( body, param); A: You can use Expression.Call(Type type, string methodName, Type[] typeArguments, params Expression[] arguments) to call your test method that checks for regular expression. List<string> lista = new List<string>() { "aaaa", "aaabb", "aaacccc", "eee" }; var param = Expression.Parameter(typeof(string), "s"); var pattern = Expression.Constant("\\Aa"); var test = Expression.Call(typeof(Regex), "IsMatch", null, param, pattern); var lambda = Expression.Lambda<Func<string, bool>>(test, param); IEnumerable<string> query = lista.Where(lambda.Compile()); foreach (string s in query) { Console.WriteLine(s); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7566772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Knockoutjs: Expanding the SimpleGrid to Support Sorting How would you modify the knockout.js simpleGrid plug-in to support column sorting? I have got the following code: http://jsfiddle.net/NaveenVelaga/QSRBR/9/ A: Use KnockoutSimpleSortableGrid found at https://shiljopaulson.github.io/Knockout.simpleSortableGrid/ and it contains samples in it A: I have had a fiddle with the supplied code. I have modified the simpleGrid code to expect a sorting function in the column data. This way we can wire up the template to sort on click via the supplied function. http://jsfiddle.net/QSRBR/39/ This is a simple solution which needs to be expanded to include bi directional sorting logic (second click sorts in reverse direction)
{ "language": "en", "url": "https://stackoverflow.com/questions/7566774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is MediaPlayer OnCompletion fired the first time a media is played? I have spent lots of hours trying to figure this out: When MediaPlayer is loaded and started the first time, its OnCompletion is called. This is a problem because I have some code that skips to the next track when the previous track is finished. I have solved it using a flag in the OnCompletion listener, but why is it like that? This snippet is from the play() method in my service: mp.setDataSource(mCurrentMediaFile); mp.prepare(); mDuration = mp.getDuration(); int seek = mDuration * position / 1000; mp.seekTo(seek); mp.start(); For some reason, onCompletion is called right after returning from the play() method even though it's the first track being played after the service is created. A: The only reason I see for such behaviour, in the provided code, is a bad seek value from the line int seek = mDuration * position / 1000;. Log the value out to check it out. A: You should try placing your mp.seekTo code in the onPrepared callback. If the seek value is taken in to effect before the onPrepared callback, the seek value gets reset by the MediaPlayer. Lastly, the media needs to be buffered correctly before knowing what position to seek to. The onPrepared callback ensures this. Hope that helps! A: In my case, I've figured out that after mp.start() had been called, mp raised an error with the code -38, triggered the onCompletion call. To fix this just implement onCompletionListener and return true, as below code: mediaPlayer.setOnErrorListener { p0, p1, p2 -> Log.d("MP", "Error code: p1 $p1 - p2 $p2") true } https://developer.android.com/reference/android/media/MediaPlayer.OnErrorListener Returning false, or not having an OnErrorListener at all, will cause the OnCompletionListener to be called. Still can't get why the error happened and which error has value of (-38). Couldn't believe this issue has wandered around for more than 10 years...
{ "language": "en", "url": "https://stackoverflow.com/questions/7566781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to get value from outside of the function in javascript? How can I get a var value from another function? jQuery: $(document).ready(function() { function GetBiggestValue() { var value = 0; $('#tagCloud li a').each(function() { if (value < $(this).attr('value')) { value = $(this).attr('value'); } }); var FullValue = value; } function Abc(){ console.log(FullValue); } Abc(); }); HTML: <ul id="tagCloud"> <li><a href="#" value="1">Val 1</a></li> <li><a href="#" value="2">Val 2</a></li> <li><a href="#" value="3">Val 3</a></li> <li><a href="#" value="4">Val 4</a></li> </ul> A: You cannot access variables from other contexts than your own or one of the parent contexts. The FullValue variable is private to the GetBiggestValue() function because you used the var statement to define the variable. The correct procedure in your case would be to return value from the GetBiggestValue() function (although one might come up with another solution using a variable outside GetBiggestValue() to store the value). $(document).ready(function() { function GetBiggestValue() { var value = 0; $('#tagCloud li a').each(function() { if (value < $(this).attr('value')) { value = $(this).attr('value'); } }); return value; } function Abc(){ console.log(GetBiggestValue()); } Abc(); }); A: May be you want to use this value anywhere. So call GetBiggestValue() function and assign it a variable. function GetBiggestValue() { var value = 0; $('#tagCloud li a').each(function() { if (value < $(this).attr('value')) { value = $(this).attr('value'); } }); return value; } var FullValue = GetBiggestValue(); function Abc(){ console.log(FullValue); } A: Just return the value from the GetBiggestValue function: function GetBiggestValue() { var value = 0; $('#tagCloud li a').each(function() { if (value < $(this).attr('value')) { value = $(this).attr('value'); } }); return value; } function Abc(){ console.log(GetBiggestValue()); } A: declare outside the function var value = 0; $(document).ready(function() { function GetBiggestValue() { value = 0; $('#tagCloud li a').each(function() { if (value < $(this).attr('value')) { value = $(this).attr('value'); } }); } function Abc(){ console.log(value); } Abc(); }); or return value
{ "language": "en", "url": "https://stackoverflow.com/questions/7566782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: bbPress and Wordpress integration please login to post I have integrated bbPress with Wordpress and it works fine on the development server but when I moved to production server, it is now asking me to log on before posting new topic even though I was logged on in Wordpress side. I didn't have to log on separately with development server to post in the forum. Is there something I need to change? EDIT: I found the answer! I had to add www in front of meta_value for url under object_type bb_option under bbpress_meta table!!! A: It could be a cookie issue. Make sure you have both installations set the cookie domain to be .yoursite.com - notice the . at the start, and the path to be /
{ "language": "en", "url": "https://stackoverflow.com/questions/7566783", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to read a text file from a remote server location I have a text file with the name textfile1.txt in C: location and this file conatains in a server machine and the machine ip is 1.127.0.0, I want to read this text file in my java application and display the content, Please help me in this, Thanks in Advance, Thanks, Kiran A: Put the file in a shared folder on the server, and use standard java IO to reference that filepath, e.g. \\<your server ip>\shared\textfile1.txt. A: You could copy the file to your local machine and read it from there. This answer could help you do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Colorbox showing up beneath iFrame containing flash video I have a page that contains the colorbox plugin and it also has an iframe that contains a youtube embedded video. In FF my colorbox appears above the flash video only in chrome my iframes appear above the colorbox if this makes sense? I've tried adding wmode=transparency to my flash videos and giving my colorbox a much higher z-index which both havent helped, is it possible to lay objects over an iframe? A: The correct value is wmode=transparent. Be sure you are adding both as param name : <param name="wmode" value="transparent"></param> and in the embed: wmode="transparent"
{ "language": "en", "url": "https://stackoverflow.com/questions/7566796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }