text
stringlengths
8
267k
meta
dict
Q: How to run a custom command when run the 'rails server' command? I am using Ruby on Rails 3.1.0 and the DelayedJob gem. In order to automate processes in development mode I would like to "auto"-run the following command rake jobs:work when in my console\terminal I run this other command rails server # and/or # # rails db:create # rails db:migrate # ... Is it possible? How can I do that? A: The gem "foreman" will sort this out for you. Here's the railscast: http://railscasts.com/episodes/281-foreman
{ "language": "en", "url": "https://stackoverflow.com/questions/7550719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reloading GXT grid on pagination events I am having Ext-GWT Grid which is using PagingModelMemoryProxy, BasePagingLoader and PagingToolbar. All is working well until one requirement. I want my grid to reload the data from server when i click on Next, Previous, Last, First or Refresh. What i did is overridden the pagingtoolbar methods and capture the pagination events. Now when user clicks on next it first do pagination event and then server to reload data. When client receives data from server it tell grid to reload it. Here everything is working fine, but as you can see the Load event is getting fired twice. First for pagination event and other when new data arrived from server. Now my question is what should i do to resolve this requirement? I know RpcProxy can work for me but i cant change the server methods and also i dont have normal asynccallback for server calls. Can any one suggest what should i do which will work with PagingModelMemoryProxy, BasePagingLoader only? A: Try this: loader.setFiresEvents(false); In addition, to stop incoming events you can call: event.setCancelled(true); which will aggregate both cancelBubble() and stopPropagation().
{ "language": "en", "url": "https://stackoverflow.com/questions/7550723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Implementing the PSPDFKit I'm working on a project that views PDFs pulled from the internet. I was working with a UIWebView, but then I switched to PSPDFKit because it looks a whole lot better, with additional features. When I use the code below, the view loads, but the PDF does not. [self setSelectedObject:(CateRegulations*)[[theDictionary valueForKey:[[[self.theDictionary allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]objectAtIndex:indexPath.section-1]] objectAtIndex:indexPath.row]]; NSString *path = selectedObject.url; PSPDFDocument *document = [PSPDFDocument PDFDocumentWithUrl:[NSURL fileURLWithPath:path]]; PSPDFViewController *objPdfViewController=[[PSPDFViewController alloc] initWithDocument:document]; [self.navigationController pushViewController:objPdfViewController animated:YES]; [objPdfViewController release]; My debugger reads as follows: 2011-09-25 21:06:29.494 Project[4509:12b03] Error: -[PSPDFDocument rectBoxForPage:]/224 Warning: Returning empty rect. 2011-09-25 21:06:29.495 Project[4509:12b03] Error: -[PSPDFPage displayDocument:page:pageRect:scale:]/92 Warning: Invalid page rect given: {{0, 0}, {0, 0}} 2011-09-25 21:06:29.495 Project[4509:12b03] Error: -[PSPDFViewController scrollToPage:animated:hideHUD:]/1027 Error: Cannot scroll outside boundaries(0), scrolling to last page. 2011-09-25 21:06:29.495 Project[4509:14503] Error: -[PSPDFCache enqueueItem:]/608 Warning: Page is invalid: 0 (pageCount: 0) 2011-09-25 21:06:29.498 Project[4509:12b03] Error: -[PSPDFDocument rectBoxForPage:]/224 Warning: Returning empty rect. 2011-09-25 21:06:29.498 Project[4509:12b03] Error: -[PSPDFPage displayDocument:page:pageRect:scale:]/92 Warning: Invalid page rect given: {{0, 0}, {0, 0}} 2011-09-25 21:06:29.498 Project[4509:12b03] Error: -[PSPDFViewController scrollToPage:animated:hideHUD:]/1027 Error: Cannot scroll outside boundaries(0), scrolling to last page. 2011-09-25 21:06:29.498 Project[4509:14503] Error: -[PSPDFCache enqueueItem:]/608 Warning: Page is invalid: 0 (pageCount: 0) 2011-09-25 21:06:29.531 Project[4509:14503] Error: -[PSPDFDocument pathForPage:]/303 Warning: Path for page 0 is missing! 2011-09-25 21:06:29.532 Project[4509:14503] Error: -[PSPDFGlobalLock openPDFDocumentWithPath:]/50 Error: pdfPath is nil! 2011-09-25 21:06:29.532 Project[4509:14503] Error: -[PSPDFGlobalLock openPDFWithPath:page:]/89 Error: As pdfDocument is nil, aquiring pageRef failed. 2011-09-25 21:06:29.532 Project[4509:14503] Error: -[PSPDFTilingView drawLayer:inContext:]/208 Missing PDF IMAGE FOR <PSPDFDocument uid:2100.2A.pdf files:1 pageCount:0> 2011-09-25 21:06:30.495 Project[4509:18803] Error: __45-[PSPDFCache cacheDocument:startAtPage:size:]_block_invoke_0/802 Warning: startPage:0 to high, resetting to 1. 2011-09-25 21:06:30.496 Project[4509:18803] Error: -[PSPDFCache enqueueItem:]/608 Warning: Page is invalid: 1 (pageCount: 0) 2011-09-25 21:06:30.496 Project[4509:18803] Error: -[PSPDFCache enqueueItem:]/608 Warning: Page is invalid: 0 (pageCount: 0) 2011-09-25 21:06:31.499 Project[4509:18803] Error: __45-[PSPDFCache cacheDocument:startAtPage:size:]_block_invoke_0/802 Warning: startPage:0 to high, resetting to 1. 2011-09-25 21:06:31.500 Project[4509:18803] Error: -[PSPDFCache enqueueItem:]/608 Warning: Page is invalid: 1 (pageCount: 0) 2011-09-25 21:06:31.500 Project[4509:18803] Error: -[PSPDFCache enqueueItem:]/608 Warning: Page is invalid: 0 (pageCount: 0) A: check your url may be it is empty
{ "language": "en", "url": "https://stackoverflow.com/questions/7550724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Add animated GIF to email/sms/whatsapp I was wondering how to get to add some custom designed animated GIF emoticons to native applications in android like SMS/EMAIL and to other applications like Whatsapp? I know how to display an animated Gif in Android using AnimationDrawable object. I just want to know if it's possible to do the following: 1) Add custom animated images to Whatsapp application. 2) Add custom animated images to SMS/EMAIL in some easy way? Just give me hints. I have been looking everywhere. Thanks in advance. A: Unless the application explicitly provides hooks for you to extend its configuration with particular animations/images there is no way to add any content to the existing application APKs. As far as I can tell the whatsapp application and the default email and sms apps do not provide extension hooks, so you won't be able to do this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550725", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why do Python's datetime.strftime('%w') and datetime.weekday() use different indexes for the days of the week? In Python, showing the day of the week as an integer using datetime.strftime() shows a different result than using datetime.weekday(). >>> import datetime >>> now = datetime.datetime.now() >>> now.strftime('%A') 'Sunday' >>> now.strftime('%w') # Day of the week as an integer. '0' >>> now.weekday() # Day of the week as an integer, a different way. 6 With strftime(), the string format %w has Sunday as the first day of the week. With weekday(), it's Monday instead. What's the history of why these two are different? A: Originally, the ISO 8601 standard used 1 .. 7 to represent Monday through Sunday. For convenience, later on the interpretation 0=Sunday was permitted. If you want to use something that is more consistent, try using isoweekday The 0=Monday standard is the European convention. I guess that's no surprise :P A: Maybe weekday is based on locale while strftime is not? Because I have different output: In [14]: d.strftime("%A") Out[14]: 'Sunday' In [15]: d.strftime("%w") Out[15]: '0' In [16]: now.weekday() Out[16]: 0 A: Python's strftime function emulates that in the c library. Thus, the motivation that %w returns 0 for a Sunday comes entirely from that. In contrast, the method date.weekday() returns a 6 for Sunday as it seeks to match the behaviour of the much older time module. Within that module times are generally represented by a struct_time and within this, struct_time.tm_day uses a 6 to represent a Sunday. The correct question then becomes ... why does time.struct_time represent a Sunday as a 6, when the C library's tm struct uses a 0 ?? And the answer is ... because it just does. This behaviour has existed ever since Guido first checked in gmtime and localtime functions in 1993. And Guido cannot be wrong ... so you best ask him.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: multiple recursion I have a doubt that ,inside a block if the same function is called two or more than two times recursively,then what is the order of execution? e.g.:in case of mergesort ,for partition if i do like this mergesort(int a[], int low, int high) { int mid; if(low<high) { mid=(low+high)/2; mergesort(a,low,mid); mergesort(a,mid+1,high); merge(a,low,high,mid); } then (1) will mergesort(a,low,mid), mergesort(a,mid+1,high) and merge(a,high,mid) be called one by one if condition (low (2) Or will the call to merge(a,low,mid) will go on recursively and then after merge(a,mid+1,high) is executed recursively and at last merge(a,low,mid) is executed . I know this is very simple for you skilled guys,but please do a favour to me by answering this. A: merge_main_call_0 | | +-----------------+------------------+ | | + + merge_1_call_1 merge_2_call_4 + + | | +---------+---------+ +---------+---------+ | | | | + + + + merge_1_call_2 merge_2_call_3 merge_1_call_5 merge_2_call_6 (here `if' is false) (here `if' is false) This shows the call tree. The first function will be called first whenever the if is true at some level or recursion. When the if is false in some level or recursion, it will go back to the last function call (the one from which it was called), which will start the execution after the first function call, which will call the second function. The second function then repeats the same thing. In the above diagram merge_1_call_n means that the merger function 1 is called the nth time. When the first time the if condition of will become false in some recursive level it will return back to the last recursive level and start executing from where it left from, which will then call the second function. Similarly, recursively when at this level this function call will return, it will execute the merge function, and then the control returns from this level to the last recursive level. It is very important to understand what a recursion level is. To do this draw the first function call as the left most child of a n-ary tree and the last call as the rightmost child, and try to form a tree like structure. The depth first search (pre-order) will result in the call sequence of the functions. UPDATE For the recursive call process going on, check out the Call Stack and Activation Records A: In your example, if low < high, then the mergesort() function will be called twice and the merge() function once. However, because this function is recursive, calls to mergesort() might call itself more times (depending on the values passed to it). A: Two function calls means that the function will be called two times, if the condition is true. A: Here's an extension of @phoxis's answer showing the call stack (as he mentioned it in his answer). I think understanding the call stack is how you can make sense of the tree: A: In main merge function if if condition is true then first merge() is called. Compiler saves everything on stack and call main merge again. It keeps repeating this until if condition is false. As soon as if condition is false compiler retreat back by popping from stack. It will keep popping from stack until it comes back to the very first merge() saved on stack. After popping and calling this merge it will go on to second merge and will repeat the whole process. Similary with the last merge. So the Order is: First Merge, then keep repeating until if fails, second merge, keep repeating..., third merge
{ "language": "en", "url": "https://stackoverflow.com/questions/7550729", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django Context Processor and Form variables I have a form in my site_base.html which extends to all of my templates. In my site_base.html, there is a dropdown form which allows a user to change his role. Based on the selected role, the templates changes. I've thought to persist this information via a context processor but I'm having problems writing the right logic that will persist the form value. So basically when a user has selected his role, I am using that role_id to populate my urls but I can't do because I will be getting a null value whenever I click on a new link thanks to my logic in the context_processor. I'm kinda new to Python and Django and I'm not sure how I should go about doing this? The good use case in the wild would be Github's account context switcher. form in site_base.html 123 <form name="context" method="post" action="">{% csrf_token %} 124 <div class="input_group"> 125 <select name="role" onchange="contextform();"> 126 <option value="none">Select Context</option> 127 {% for role in request.user.get_or_create_profile.roles.all %} 128 <option value="{{ role.id }}" {% ifequal role.id current_role.id %}selected="selected"{% endifequal %}>{{ role.name }} for {{ role.event }}</option> 129 {% endfor %} 130 </select> 131 </div> 132 {{ current_role }} 133 </form> naive context.processor.py 3 def context_switcher(request): 4 """ 5 Get a user's role 6 """ 7 if 'role' in request.POST: 8 role_id = request.POST.get('role') 9 current_role = Role.objects.filter(id=role_id)[0] 10 else: 11 current_role = '' 12 return {'current_role': current_role} A: Store the value in the session (in a view, not the context processor) as soon as it's set for the first time. request.session['role_id'] = request.POST['role'] Then you can get the actual Role object in your context processor each time: current_role = Role.objects.get(role_id=request.session['role_id'])
{ "language": "en", "url": "https://stackoverflow.com/questions/7550730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to restore the data from DDMS & Ftp Server? I've Backup Contacts, Settings, Browser bookmarks & Media files successfully using this code. These data are stored in DDMS & FTP as files. How can i restore these backedup files by programmatically. Anyone knows mean tell me the way? This is my cursorToCSV method for taking backup. Lot of thanks in Advance. A: Find the code for cursorToCSV and there should be a corresponding reverse method. Use that to restore the backup files.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550731", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to decode GUID in AlbumData.xml (iPhoto) I tried to parse AlbumData.xml and found strange GUID string value, how to convert it to integer value ? eg : f7hWRm%xSMiYVfEynRpo7g = 4.29497e+09 Thanks in advance A: You simply don't. It's an NSString. A suggestion is to change the extension to .plist and open in Xcode. You can then see the data types. Sort of a related thing, iTunes sends a NSDistributedNotificationCenter note whenever its library changes. Does iPhoto do something similar for its AlbumData.xml? I didn't know if I should post this as a new question since it is somewhat relevant to this one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mysql Syntax Error with = any or in I keep getting this error with this delete. Mysql version is 5.0.77. I can't think of anything else that is the issue. I even created a temp table to avoid the issue of modifying tables in the select. :( ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE e.eid IN (SELECT * FROM (SELECT w.eid FROM' at line 3 with the following delete DELETE FROM emp2 e WHERE e.eid IN (SELECT * FROM (SELECT w.eid FROM works2 w, emp2 e2, dept2 d WHERE w.did = d.did AND d.managerid = e2.eid AND e.salary > e2.salary ) AS temp1 ); A: Try losing the alias from the table you are deleting from: DELETE FROM emp2 WHERE eid IN (SELECT ... A: This may work: DELETE e FROM emp2 e JOIN works2 w ON w.eid = e.eid JOIN dept2 d ON w.did = d.did JOIN emp2 e2 ON d.managerid = e2.eid WHERE e.salary > e2.salary or an EXISTS version: DELETE FROM emp2 e WHERE EXISTS ( SELECT * FROM works2 w, emp2 e2, dept2 d WHERE w.did = d.did AND d.managerid = e2.eid AND e.salary > e2.salary AND w.eid = e.eid ) What exactly are you trying to delete?
{ "language": "en", "url": "https://stackoverflow.com/questions/7550733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MVC 3 URL dynamic routing Can you show me how to do that in MVC I have 2 sites use the whole same Producing process, but some are different Struct like: domain.com ----Site1 ----Site2 How can I setup the url like this http://domain.com/Site1/controller1/action1 it will go to controller: site1_controller1 - action: action1 http://domain.com/Site2/controller1/action1 it will go to controller: site2_controller1 - action: action1 Or any good method can be used in this case. Many thanks A: You could consider using MVC areas instead of having a concatenated controller name. An area is just a group of controllers, so you could have an area called Site1 with a controller called controller1 inside it, and then a separate controller2 inside an area called Site2. See http://msdn.microsoft.com/en-us/library/ee671793.aspx for a walkthrough.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting out of URL.Authority? I am new to asp.net and c#. I have set a query string to pass the value to one page to another along with the url path. But once go to this page I will not be able to redirect to any other page. Here is my code: Uri url = System.Web.HttpContext.Current.Request.Url; string urlString = "http://" + url.Authority + "/Projects/SearchResult.aspx/?Keywords=" + TxtSearch.Text; Response.Redirect(urlString); Here is the error: The resource cannot be found. Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly. Requested URL: /Projects/Description.aspx/NewPost.aspx A: The error is simply indicating the your URL in wrong - the reported url /Projects/Description.aspx/NewPost.aspx anyway appears to be wrong - it should be either /Projects/Description.aspx or /Projects/NewPost.aspx. As your code is redirecting to completely different page (/Projects/SearchResult.aspx), you should check that page code for above redirect/transfer. On side note, there are couple of issues in ho you are forming the url: * *Query-string is not passed correctly - you have used trailing slash before question-mark i.e. /?Keywords - you should be using /Projects/SearchResult.aspx?Keywords= *Typically, for passing to url within application, you should use ~ as application root - that way, you don't have to worry about host name & root virtual directory (if any). For example, you can write Response.Redirect("~/Projects/SearchResult.aspx?Keywords=" + TxtSearch.Text);
{ "language": "en", "url": "https://stackoverflow.com/questions/7550751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: problem with # and get i'm trying to send data via GET and one of the fields has the sign # in it (sometimes more than once). Is there a way to encode or escape the # in the GET so i can be able to send all my fields with GET ? (i can only send my data via GET, i'm not allowed to use POST) thanks A: If you have to send this field to PHP via GET (i.e. through AJAX) form the client side, use javascript's encodeURIComponent();. Else if you need to make a GET request from your server to another server, use CURL, it will do the encoding for you. And in the case that you just want to output a hyper reference (link) then use the other answers provided (now deleted, referenced this).
{ "language": "en", "url": "https://stackoverflow.com/questions/7550754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: what's the purpose of *.vsmdi? Do I need to source control it? What's the purose of .vsmdi file? Do I need to check into the source control system? A: The VSMDI file is created by Visual Studio when you create a test project for the first time. It contains a list of all tests that Visual Studio can find in your solution assemblies and allows you to divide your tests into so-called test lists. These test lists can be used to categorize your tests and let you select a subset of tests for execution. You can use this mechanism for running sub-selections. However, you can also (freely) assign multiple test categories to a test, which enables you to achieve the same, in a more flexible way. And with the known issues with VSMDI files, like uncontrolled duplication of these files and obsolete tests being listed with a warning icon, it might seem the better way to do things like this. My overall suggestion is: check-in your default generated .vsmdi file. This will prevent Visual Studio from (re-)generating such files on your own and your team members systems when new test projects are added. Decide on usage of test lists or assigning categories to tests directly based on your usage experience. Test lists are easy to start with, but less suitable is you want to have flexibility for a large set of tests. A: It's used for Testing in Visual Studio. If you don't do testing in Visual Studio, I wouldn't worry about it. But if you do, and you have hundreds of tests it might be worth keeping.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "56" }
Q: Web app SQLite insert ran great in Chrome 11, fails ever since version 12. I have a javascript/jquery function in an offline-capable web app that works great in Chrome 11, but since Chrome 12 has ceased to work. Don't care about other browsers, but getting this working in more recent versions of Chrome is getting more and more critical. In a nutshell, I call a PHP data page (not cross-domain) and get back a JSON array, which gets iterated over, inserting elements of the response into the local SQLite db. The console log raises no flags, and no javascript errors. I see the JSON in the response, and the only part that seems to break is the data insert found in the try block. Anyone know if there was a change in Chrome after version 11 that would prevent interaction with the SQLite db? Any help would be most appreciated. function importAssignmentData() { var import_count = 0; $.get("data.php", function(data) { if (data instanceof Array){ // Data is properly formed as an array. } else{ alert('Data from the server was not properly formed. You may not be logged in.'); } $.each(data, function(index, value) { if (this.order_id == 'authfail'){ alert("You are not logged into the server. Authentication failure."); console.log("Authentication failure."); } else{ if (typeof this.order_id != 'undefined') { // sanity check import_count++; var EMPTY = ""; var order_id = (this.order_id == '') ? EMPTY : this.order_id; var order_code = (this.order_code == '') ? EMPTY : this.order_code; var customer_id = (this.customer_id == '') ? EMPTY : this.customer_id; var customer_name_first = (this.customer_name_first == '') ? EMPTY : this.customer_name_first; var customer_name_last = (this.customer_name_last == '') ? EMPTY : this.customer_name_last; var customer_phone = (this.customer_phone == '') ? EMPTY : this.customer_phone; var customer_email = (this.customer_email == '') ? EMPTY : this.customer_email; var customer_address = (this.customer_address == '') ? EMPTY : this.customer_address; var customer_city = (this.customer_city == '') ? EMPTY : this.customer_city; var customer_state = (this.customer_state == '') ? EMPTY : this.customer_state; var customer_zip = (this.customer_zip == '') ? EMPTY : this.customer_zip; var order_notes_contractor = (this.order_notes_contractor == '') ? EMPTY : this.order_notes_contractor; var measurement_date = (this.measurement_date == '') ? EMPTY : this.measurement_date; try { ODATA.transaction(function (transaction, results){transaction.executeSql("INSERT INTO order_specs (order_id, order_code, customer_id, customer_name_first, customer_name_last, customer_phone, customer_email, customer_address, customer_city, customer_state, customer_zip, order_notes_contractor, measurement_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", [order_id, order_code, customer_id, customer_name_first, customer_name_last, customer_phone, customer_email, customer_address, customer_city, customer_state, customer_zip, order_notes_contractor, measurement_date], nullDataHandler, errorHandler);}); console.log("Order record inserted."); } catch(e) { console.log(e.message); } } else { alert('You are not online, or you may not be logged in properly.'); console.log("Offline attempt to retrieve remote data. No inserts made."); } // end sanity check } // end authfail check }); // end .each var plural = (import_count == 1) ? "" : "s" ; alert('You have ' + import_count + ' active assignment' + plural + '.\nClick List Assignments to view your assignments.'); $('#reload_page').focus(); }); } A: This turned out to be some incompatibility with jQuery 1.5.2. Not sure of the internals or specifics involved, but at this point I do not even care. Upgrading to jQuery 1.6.4 library solved the problem. I will now go comb what little hair I have left - hopefully this will help others out there keep more of theirs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550766", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: jquery: find the index of an element that contains a given string In an HTML I created a "div" with an unique id. Within this "div" I have more "div"s, in which each contains a string. For example: <div id="name"> <div>A</div> <div>B</div> </div> What I want to do is to find the index of a "div" that contains a string, say "A", within the "div" with id="name". I think selector ":contains" should be used in combination with .index() but I can't figure out the right syntax. This is what I've tried: var index = $("#name"):contains(A).index("div"); A: I think you want var index = $('#name div:contains("A")').index(); That will find the element matching the selector div:contains('A') within the element with id = name. As you've probably worked out by now, selectors prefixed with : are meant to be used within the selector string. Many have corresponding jQuery functions that can be chained instead (e.g. :eq() and .eq), but :contains() does not (the function .contains() tests for DOM elements within other elements, rather than looking at text). A: try this var index = $("#name>div:contains(A)").eq(0).index(); http://jsfiddle.net/GhPxD/1/
{ "language": "en", "url": "https://stackoverflow.com/questions/7550768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to copy a directory structure but only include certain files I found a solution for my question in Windows but I'm using Ubuntu: How to copy a directory structure but only include certain files using Windows batch files? As the title says, how can I recursively copy a directory structure but only include some files? For example, given the following directory structure: folder1 folder2 folder3 data.zip info.txt abc.xyz folder4 folder5 data.zip somefile.exe someotherfile.dll The files data.zip and info.txt can appear everywhere in the directory structure. How can I copy the full directory structure, but only include files named data.zip and info.txt (all other files should be ignored)? The resulting directory structure should look like this: copy_of_folder1 folder2 folder3 data.zip info.txt folder4 folder5 data.zip Could you tell me a solution for Ubuntu? A: $ rsync --recursive --include="data.zip" --include="*.txt" --filter="-! */" dir_1 copy_of_dir_1 To exclude dir3 regardless of where it is in the tree (even if it contains files that would match the --includes): --exclude 'dir3/' (before `--filter`) To exclude dir3 only at at specific location in the tree, specify an absolute path, starting from your source dir: --exclude '/dir1/dir2/dir3/' (before `--filter`) To exclude dir3 only when it's in dir2, but regardless of where dir2 is: --exclude 'dir2/dir3/' (before `--filter`) Wildcards can also be used in the path elements where * means a directory with any name and ** means multiple nested directories. To specify only files and dirs to include, run two rsyncs, one for the files and one for the dirs. The problem with getting it done in a single rsync is that when you don't include a dir, rsync won't enter the dir and so won't discover any files in that branch that may be matching your include filter. So, you start by copying the files you want while not creating any dirs that would be empty. Then copy any dirs that you want. $ rsync --recursive --prune-empty-dirs --include="*.txt" --filter="-! */" dir_1 copy_of_dir_1 $ rsync --recursive --include '/dir1/dir2/' --include '/dir3/dir4/' --filter="-! */" dir_1 copy_of_dir_1 You can combine these if you don't mind that your specified dirs don't get copied if they're empty: $ rsync --recursive --prune-empty-dirs --include="*.txt" --include '/dir1/dir2/' --include '/dir3/dir4/' --filter="-! */" dir_1 copy_of_dir_1 The --filter="-! */" is necessary because rsync includes all files and folders that match none of the filters (imagine it as an invisible --include filter at the end of the list of filters). rsync checks each item to be copied against the list of filters and includes or excludes the item depending on the first match it finds. If there's no match, it hits that invisible --include and goes on to include the item. We wanted to change this default to --exclude, so we added an exclude filter (the - in -! */), then we negate the match (!) and match all dirs (*/). Since this is a negated match, the result is that we allow rsync to enter all the directories (which, as I mentioned earlier, allows rsync to find the files we want). We use --filter instead of --exclude for the final filter because --exclude does not allow specifying negated matches with the ! operator. A: I don't have a beautiful one liner, but since nobody else has answered you can always: find . -name 'file_name.extension' -print | cpio -pavd /path/to/receiving/folder For each specific file after copying the directories. (Make sure you're in the original folder first, of course! :) ) A: Here is a one-liner using rsync: rsync -a -f"+ info.txt" -f"+ data.zip" -f'-! */' folder1/ copy_of_folder1/ If you already have a file list, and want a more scalable solution cat file.list | xargs -i rsync -a -f"+ {}" -f'-! */' folder1/ copy_of_folder1/ A: cp -pr folder1 copy_of_folder1; find copy_of_folder1 -type f ! \( -name data.zip -o -name info.txt \) -exec rm -f {} \; * *first time : copy entirely folder1 to copy_of_folder1 *second time : erase all files differents from data.zip and info.txt *At the end, you have your complete structure with only the file data.zip and info.txt
{ "language": "en", "url": "https://stackoverflow.com/questions/7550773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: WCF : How to detect a session is timeout? I write this Interface to create and terminating a session. [ServiceContract(SessionMode = SessionMode.Required)] public interface IOrdersService { [OperationContract(IsInitiating = true, IsTerminating = false)] void EmptyCart(); [OperationContract(IsInitiating = false,IsTerminating = false)] void AddToCart(CartItem cartItem); } it`s work fine. But when a session timeout then how can i detect ?? A: If it is trimmed out, your channel will be faulted both on your client and your server's callback channel, you can listen on faulted event on channel. And once it is faulted, you will need to recreate a channel to recover.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: annotation on current location I'm working on the project in which i added a button on pressing it should take me to my current location on map and should show the blue indicator to indicate the location,here is the code: -(IBAction)gotoLocation { if(curntloc) { MKCoordinateRegion mapRegion; mapRegion.center = mapView.userLocation.coordinate; mapRegion.span.latitudeDelta = 0.0112872; mapRegion.span.longitudeDelta = 0.0112872; [self.mapView setRegion:mapRegion animated: YES]; } else { curntloc = [[CLLocation alloc] initWithLatitude:21.192415 longitude:72.821159]; MKCoordinateRegion mapRegion; mapRegion.center = mapView.userLocation.coordinate; mapRegion.span.latitudeDelta = 0.0112872; mapRegion.span.longitudeDelta = 0.0112872; [self.mapView setRegion:mapRegion animated: YES]; } } This works fine on simulator you can see it in image, but when i try to test it on iPhone it's getting crashed.what may be the possible reasons can any one point out? thanks A: First of all i want to tell you that from simulator you can't get current location. in your code you just used a static lat. long. and for the device i share a link just check. http://pastebin.com/Vv1wvyBh which may be helpful to you :) Thanks. A: So I have found that with the iPhone it is a refresh issue for most of the MKMapView problems. I would suggest either resetting some properties of the map, recreating the map, or making sure that showing the user's location in the map_view is set. Resetting the properties of the map usually include something like location = map.centerCoordinate, map setCenter:location. Umm other then that I think that it could possibly be a memory issue? Something like an annotation being released at a wrong time or maybe the map itself is released?
{ "language": "en", "url": "https://stackoverflow.com/questions/7550777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: rails dynamic nested form data select Rails gurus, do you know of a standard solution to this problem I've been struggling with? In my app, the user can define properties for his objects. So before generating his list of objects (let's say they are books), he can specify which properties he cares about and their potential values, and then for each book he will have to input a legal value for each property. So say I put in for my properties: length (legal values "long", "short") and difficulty ("easy", "hard"). On a different bookshelf, a different list of books could have different properties (cover_color "blue" or "red") So now I am in my book form. "Add new book on this bookshelf." On the partial, I come up with the list of properties relevant to a new book on this bookshelf (length, and difficulty). Then I look up the legal values for each property. I have a select dropdown in which the user can choose one: <% for prop in @book.properties %> <%= prop %> : <%= f.collection_select :prop_value_select, prop.legal_property_values, :id, :name %> <%end %> In my book model, I defined a virtual attribute that will create the "join record" PropertyValue. PropertyValue has legal_property_value_id and book_id. def prop_value_select=(incoming_id_from_form) PropertyValue.create!(:legal_property_value_id => incoming_id_from_form, :book=> self) end The whole scheme works, except my method is only getting called once, for the first property when the form submits, instead of once for each property. I am racking my brain... seems very simple, but what's the standard rails way to do something like this? * *collect all of the properties into an array and generate the models as a callback? *some magic with a partial for each property? Thank you! A: I think the problem is that you are using a nested model, and all your fields will have the same id's, so rails will only store one nested element. You should be using fields_for which allows you to handle a nested model. First you need to specify in your model that it will accept nested attributes. Add the following line class Book has_many :properties accept_nested_attributes_for :properties end and in your view you would write something like <% fields_for :properties do |prop| %> <%= prop %> : <%= f.collection_select ... <% end %> Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pull specific control out of a silverlight listbox given a random index into the list? I have a listbox which uses the following template to bind a list of clips. I would like to pull one of those clips at random and have it play. That is the easy part and is pretty straight forward. I would then like to make an associated image visible. I can't seem to find out how to get the controls associated with the index in the listbox. Any ideas. ` <StackPanel Margin="0,0,0,12" Width="420"> <Button Click="Button_Click" Background="{StaticResource PhoneAccentBrush}" Height="90" Width="420" x:Name="btn"> <StackPanel Orientation="Horizontal" > <Image x:Name="Selected" Width="75" Source="Images/Playing.png" Visibility="Collapsed" /> <TextBlock Text="{Binding Name}" TextWrapping="NoWrap" Width="330" VerticalAlignment="Center" Style="{StaticResource PhoneTextLargeStyle}" /> </StackPanel> </Button> </StackPanel> </DataTemplate> ` A: To find the conrols that have been generated from your template you can use the methods on ItemContainerGenerator. For example, if you want to find the elements at index '5', do the following: ListBoxItem lbi = listBox.ItemContainerGenerator.ContainerFromIndex(5) as ListBoxItem; There are various other methods that allows you to find the container given a bound model item for example. You can then navigate the visual tree, (I wrote a helper called Linq-to-VisualTree that makes this a bit easier) to locate the elements you require. To find the image: var image = lbi.Descendants<Image>().Single() as Image; A: This is a ListBox so have a list of objects bound to its ItemsSource. Add a new "NowPlaying" property to the class of these objects. Bind this property to the Visibility property of the "Selected" Image via a BoolToValueConverter Now you just toggle that new property and need not delve in the Visual Tree to do what the binding system should be doing for you
{ "language": "en", "url": "https://stackoverflow.com/questions/7550787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Context.isPointInPath usage I googled for this but didn't find any example that uses Context.isPointInPath in HTML 5. I know it's supposed to return me true if the point is on the current path, but how exactly do you use it? Should you use it in between context.beginPath() and cotext.closePath() (or fill* for that matter) I tried this: var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.fillRect(0,0, 100,100); ctx.isPointInPath(50,50); // Returned false ctx.isPointInPath(50,0); // Tried it on the actual path, not the filled region, returned false ctx.isPointInPath(50,8); // My canvas had the default 8 offset, returned false ctx.isPointInPath(50,9); // Canvas had a border of 1px, returned false I don't know what went wrong, but all of them returned false and I never had one returning true. Finally, I closed the path and checked for the values, still returned false. A: All of your calls to isPointInPath() are returning false because you aren't actually creating any paths when you are working with your context. The fillRect() function doesn't create a path. It just fills in some pixels on your canvas with whatever color you previously specified. Instead, you will want to use one of the path-modifying functions, such as rect() or moveTo(). For all the details on isPointInPath() and the path functions, refer to the canvas spec here: isPointInPath(): http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-ispointinpath path functions: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#complex-shapes-%28paths%29
{ "language": "en", "url": "https://stackoverflow.com/questions/7550788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Why can't I find SQL Server Management Studio after installation? So I downloaded Microsoft SQL Server 2008 R2 on a new computer I have to be using and when I go to Start -> Programs -> Microsoft SQL Server 2008 R2 I don't see SQL Server Management Studio. I followed the step by step installation and configuration. Why can't I find the program? What am I missing? I can't wait for 3 hours more before answering my own question. I should have been asleep hours ago. Here is the answer: Thought you guys' comments were really helpful. But the solution I had to find by Google searching around. It appears that SQL Server 2008 R2 can be downloaded with or without the management tools. I honestly have NO IDEA why someone would not want the management tools. But either way, the options are here: http://www.microsoft.com/sqlserver/en/us/editions/express.aspx and the one for 64 bit WITH the management tools (management studio) is here: http://www.microsoft.com/sqlserver/en/us/editions/express.aspx From the first link I presented, the 3rd and 4th include the management studio for 32 and 64 bit respectively. Guys, thanks a lot for your insight. It was cool to learn that stuff. A: It appears that SQL Server 2008 R2 can be downloaded with or without the management tools. I honestly have NO IDEA why someone would not want the management tools. But either way, the options are here: http://www.microsoft.com/sqlserver/en/us/editions/express.aspx and the one for 64 bit WITH the management tools (management studio) is here: http://www.microsoft.com/sqlserver/en/us/editions/express.aspx From the first link I presented, the 3rd and 4th include the management studio for 32 and 64 bit respectively. A: Generally if the installation went smoothly, it will create the desktop icons/folders. Maybe check the installation summary log to see if there's any underlying errors. It should be located C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log(date stamp)\
{ "language": "en", "url": "https://stackoverflow.com/questions/7550790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: Category url goes to 404 page in magento I'm new to magento when i list categories in sidebar. when i click the category name means it will go to 404 error page. If you have any idea Please tell me as soon as possible.. and my code is <?php $_categories = Mage::getModel('catalog/category')->load(3)->getChildrenCategories(); if($_categories->count()): $categorycount = 0; foreach ($_categories as $_category): if($_category->getIsActive()): $cur_category=Mage::getModel('catalog/category')->load($_category->getId()); $layer = Mage::getSingleton('catalog/layer'); $layer->setCurrentCategory($cur_category); ?> <li><a href="<?php echo $_category->getURL() ?>" title="<?php echo $this->htmlEscape($_category->getName()) ?>"><span class="categoriesHead"><?php echo $this->htmlEscape($_category->getName()) ?></span> </a> </li> <?php endif; endforeach; endif; ?> A: I had the same issue in 1.5.1 and in my case it was the category url suffix which was expecting a .html suffix but the links were giving me blank. I changed Admin>>System>>Configuration>>Catalog>>Search Engine Optimisations>>category suffix from ".html" to "" (blank) and it's working fine now. A: I spend so much time on this problem.... You might have made your categories root categories and not subcategories. Simply drag and drop them into the default category and see if that gives you a better url. You can see if you are getting a bad url by just appending index.php/name of category in small case/ to the base url A: Try this: Go in admin>>System>>Configuration>>Catalog and under Category permissions select No at Enable option. Then click Save config and clear Magento cache.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Where is best place to post a Ruby on Rails Installer? I've figured out a really simple way to install Ruby on Rails with all the latest modules on Windows & created two installers for it. One with WAMP and one without that. With that it takes only about 5 minutes to install Ruby and Rails + WAMP. As opposed to the hours that it might take to load and compile all the modules. I'd like to share this with as many people as possible because I think more people could learn this great language and framework, if the installation of it wasn't such a hassle! What would be the best place where I could upload these installers and where people who look for such thing would find it? A: Host your project on github, and update/inform the ROR wiki about it, which would help others know about your installations and use them
{ "language": "en", "url": "https://stackoverflow.com/questions/7550794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How does a REST API differ from URI? The MSDN Documentation on BLOB Service REST API leads to the understanding that REST API and URI are same.Can anybody explain the difference between REST API and URI? A: A URI is used to identify a resource on the web (and other places). A RESTful API uses URIs and HTTP GET/POST/PUT/DELETE to perform CRUD (create, read, update, delete) operations on a web service. One of the key identifying characteristics of a REST api is that the URIs are used to directly identify resources rather than web service methods that return resources e.g. REST: http://example.com/api/books/1 Non REST: http://example.com/api/getbook?bookId=1 A: They are not quite the same, your restful API defines a set of URIs used to access resources. So: one API, many URIs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Custom view and main activity i want to use a point array in custom view which is in different class . but that point array is actually declared in main activity . and custom view only extends view so when i use the point array in ondraw() it is undeclared . Actually i want coordinates in an array in ondraw() function and then use them in my main activity where rest of my code resides . and then i also want to add button on that view. Q2. i used another approach where i didn't make new java file for custom view and tried to add two linear layouts in main.xml one for button and one for custom view but here when i load the view which is in main activity it dont get load what will be the syntax thanks . <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <Button android:text="Button" android:id="@+id/btn1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"> <com.faisal.FaisalActivity.DemoView android:id="@+id/demoView1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <com.faisal.FaisalActivity.DemoView android:id="@+id/demoView1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> </LinearLayout> Above is my linear layout ignore the brackets i just removed them strong text A: You can create a setData method in your custom view and and an id to ur custom view in xml. In the onCreate function of the activity class you could use the findViewById(ID OF CUSTOM VIEW) and set the data to the object. This way you can pass the data from the activiy to the view. This a example of a line chart I created, here I pass an array of points to the linechart view which is a custom view.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jsonp result not working on my asp.net-mvc site i am trying to get jsonp call working with jquery and my asp.net-mvc site. I found this article which i tried to copy but i am not getting a breakpoint in my callback: Here is my jquery code: $.ajax({ url: "http://www.mySite.com/MyController/Terms", type: "GET", dataType: "jsonp", timeout: 10000, jsonpCallback: "localJsonpCallback" }); function localJsonpCallback(json) { var terms = json.HTMLText; $("#term2").html(terms); } and here is my controller code: public JsonpResult Terms() { var data = GetData(); return this.Jsonp(data); } where JsonpResult and this.Jsonp are defined as per this page: so I can't seem to get a callback but when I open up firebug script section, I do see a file listed when is the url about and has: Terms?callback=localJsonpCallback and when i look into the content I see the correct json object content: localJsonpCallback({"HTMLText":"PRIVACY POLICY: Your privacy is very important to us"}); so this tells me the data is coming back to the client but the callback doesn't seem to be firing and the text input is not being populated. Can anyone find an issue with what i am doing or have any explanation on why this wouldn'nt work? A: You don't have a success function defined for your ajax request. The jsonpCallback parameter that you are using only defines the name of the query string parameter that will be used by the server to wrap the JSON response into. So try like this: $.ajax({ url: 'http://www.mySite.com/MyController/Terms', type: 'GET', dataType: 'jsonp', timeout: 10000, jsonp: 'jsoncallback', success: function(json) { var terms = json.HTMLText; $('#term2').html(terms); } }); Also checkout the following answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can IP change during session? Can IP change during session? What about different engines (PHP, Django, Ruby, etc) ? PS: I don't quite understand what is 'dynamic ip' and how they are held by internet providers... And how sessions are broken... Update: Should I track IP change for security? I'm currently working with PHP, so if the built in session system lacks security, please provide some code and algorithms A: Just thought I'd add a comment to this though it is an old thread. An IP for a visitor to your website can change for instance when the visitor decides to switch from mobile data to wifi. Maybe he wants to download something from your site and thinks it would be better to use wifi for it. The session can remain the same during the process. A: IPs can change at any time - the idea behind HTTP is that each request is independent. There are only around 3 billion IPv4 addresses available worldwide. Some ISPs (most of them, actually) therefore assign IPs dynamically for each connecting client - so that when this client disconnects, the IP can be reused for someone else. As far as 'sessions' are concerned - it all depends on how the state is held. The most sane approach is to use a cookie - which allows you to connect from arbitrary IP, on an arbitrary medium - at which point, you should not be concerned with IP layers of the HTTP. But again, people are known for doing weird stuff, like using IPs for things they were never meant (in the OSI/IETF sense) for - like identification, authentication, etc.. This is doubly bad, because one IP can commonly mean many customers - for instance, your entire household likely shares the same public IP - what if you and your partner both visit the same site? How can the server tell the two of you apart? @update No, you shouldn't track IP changes for 'security' - the only exception is if you can deal with geoIP features, and want to disable/annoy users of various anonymisation services. Basically, if your users connect directly (and not via proxy/TOR), it would be very likely that they will connect again from a nearby location. If your users connect once from the US, once from Russia - that can mean either that these are two different people (one of whom might've stolen the credentials), or that the user uses an anonymiser of sorts. If the site is a high-value target (banking, finance, central credentials (think Google Account)) - you could geo-lookup the IPs and compare if the distance changed by more than 100km in under an hour more than twice - this is likely fishy, and you can bug the user for extra credentials. Otherwise, you could display the last few IPs - but it's likely an icing on the cake with little real value. @update2 Security is a tricky subject - whenever you're dealing with it, you need to answer two fundamental question: Security of what: what is so valuable that needs protecting * *Privacy of users *Permissions granted to a user *Assets (physical or virtual) And security against what: What is the attack scenario you are concerned about * *Cookie hijacking (firesheep) (just use SSL and be done with it for the most part - there is no way around the problem that HTTP is unencrypted and often over public radio) *Taking over accounts (require additional credentials for really sensitive stuff) *Defacing? A: 1) Yes, an IP address can change during a session. 3) No, I can't think of any security benefit of "tracking IP changes". 2) A "dynamic IP address" is simply the opposite of a "static IP address: a) With dynamic IP's ("DHCP"), the network assigns the address to a host (typically, when you boot up). b) With static IP's, you configure the host with a fixed, unchanging address. c) Dynamic IPs are the norm. They're easier to administer, they relieve the end user of having to do any network configuration, and they mitigate the risks of conflicting network addresses. Here is a good link that might make the distinction between "static" and "dynamic" addressing clearer: http://compnetworking.about.com/od/workingwithipaddresses/qt/staticipaddress.htm
{ "language": "en", "url": "https://stackoverflow.com/questions/7550798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: NSThread Timing Problem with GUI I have a simple thread that runs an infinite loop. Eventually, the loop will check for serial data at a USB port a few thousand times per second, but at the moment, it just writes something to a custom class of NSTextView once every second. int i; for (i=1; i>0; i++) { [lock lock]; [[self textStorage] replaceCharactersInRange:NSMakeRange([[self textStorage] length], 0) withString:@"test\n"]; [lock unlock]; sleep(1); } The issue is that it writes really sporadically. It will do one or two, then wait ten seconds and spit ten of them out at once. If I replace the writing line with an NSLog(@"test"), it logs at nice even intervals. I have another test method in the main thread that accepts input into a text field and puts it into the text view, and doing this seems to update the text view to include the child thread's most recent writes. There shouldn't be anything interfering with it at this point anyway, but I've locked everything everywhere just to be sure. Thanks in advance. A: You should always perform operations that affect the UI from the main thread. You can have the child thread create a temporary object that holds the results, and then use performSelectorOnMainThread:withObject:waitUntilDone: to call another method that will do the necessary modifications on the main thread. NSString * const MDResultKey = @"MDResult"; - (void)someMethod { // int i; for (i=1; i>0; i++) { // if necessary, create an object to hold results NSDictionary *results = [NSDictionary dictionaryWithObjectsAndKeys:@"test", MDResultKey, nil]; [self performSelectorOnMainThread:@selector(updateUIWithResults:) withObject:results waitUntilDone:NO]; sleep(1); } } - (void)updateUIWithResults:(NSDictionary *)results { NSString *result = [results objectForKey:MDResultKey]; [lock lock]; // ? [[self textStorage] replaceCharactersInRange: NSMakeRange([[self textStorage] length], 0) withString:result]; [lock unlock]; // ? } A: I'd personally be pretty wary of calling anything on an NSTextStorage on a background thread. I think NSTextView reacts to any NSTextStorage changes, and any UI code on a non-main thread is going to have unpredictable problems. I would just send the new string to the main thread and call -replaceCharactersInRange: there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: program hangs before goToSleep(); Hi i have this program where it uses voice command to unlock the phone. In this VoiceRecog activity, when i detected command is wrong, it will call goToSleep(1000); which locks the device. However, the program will hang before it goes to sleep. What could be the problem? What should i put for the int value in the method? @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); if(command ==right) .... else pm.goToSleep(10); } I have tried using DevicePolicyManager devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE); devicePolicyManager.lockNow(); but the program still hangs before it locks. A: Only app signed as system app can call goToSleep(), not yours. And at least now, I don't see any good way to force the device to sleep.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Check valid IPv4 Address in Java I am using the sun.net.util.IPAddressUtil package to check whether the string contains a valid IPv4 and IPv6 address or not. Code Snippet is:- String ipv4addr="200"; if(IPAddressUtil.isIPv4LiteralAddress(ipv4addr)) { System.out.println("valid ipv4 address"); } else { System.out.println("not valid"); } But for addresses such as 200 and 300 it is still saying it is a valid IPv4 address, which it isn't. When I used the same package and checked for IPV6 address using :- String ipv6addr="200"; if(IPAddressUtil.isIPv6LiteralAddress(ipv6addr)) { System.out.println("valid ipv6 address"); } else { System.out.println("not valid"); } I get the correct result. However, IPv4 does not seem to be working or may be I am using it incorrectly. Please guide me. I don't want to use regex for IPv4 validation... A: Check out Guava's InetAddresses class which contains static utility methods for working with IP addresses. (As I understand it uses the sun.net.util.IPAddressUtil class behind the scenes.) System.out.println(InetAddresses.isInetAddress("400")); // false A: There's a reason you're getting a "valid" result: 200 is a valid IPv4 address. See, to the computer, an IPv4 address is just a 32-bit number. The dots are entirely for our convenience, because we humans suck at memorizing big precise numbers. But they don't have to be there; there are rules about how an address gets parsed depending on how many parts it has. When an address consists of one number, it's considered a 32-bit number, and each byte is 8 bits of that number. If you were to parse "200" as an IP address, it would be equivalent to 0.0.0.200. Likewise, "2130706433" would be equivalent to 127.0.0.1. There are also standards for when an address has two parts like 0.200 (first part is the first byte, and the second part is a 24-bit number representing the other 3 bytes), and even 0.0.200 (first two numbers are bytes, the last part is 16 bits and takes up the other 2 bytes). The "unusual" formats are leftovers from the days of IP address classes, but almost all software that has to parse addresses will understand them. (If you pop open your browser and go to http://1249739112* or even http://74.125.33128*, for example, Google's home page will come up.) * See the comments for clickable links. Thanks, "link validator". :P See http://download.oracle.com/javase/6/docs/api/java/net/Inet4Address.html or http://www.perlmonks.org/?node_id=221512, or http://en.wikipedia.org/wiki/IPv4#Address_representations, for some more details. Java understands these formats as well (as does .net, as well as any decent OS), and parses the address correctly whether it contains 1, 2, 3, or 4 parts. If you want to check that a would-be address actually looks like "xxx.xxx.xxx.xxx", then you'll probably want to explicitly check that using a pattern, or using a validation library that considers 32-bit numbers as invalid addresses (even though they are valid). I wouldn't bother, though -- if you use the lookup functions provided, you can accept an address in any standard format and it will work. (All this mess changes with IPv6; there's a much stricter format, and you can't just type in some 36-digit number and expect it to work. But the platform still knows how to parse an address, and you should trust it to do so.) A: It's not a good idea to use internal "sun" packaged classes, I'd try using Apache's Validator http://commons.apache.org/validator/ which has IP Address validation. A: If you want to validate if a string is valid IP address representation, the source code of org.apache.http.conn.util.InetAddressUtils uses these regular expressions: IPV4_PATTERN = Pattern.compile( "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$"); IPV6_STD_PATTERN = Pattern.compile( "^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$"); IPV6_HEX_COMPRESSED_PATTERN = Pattern.compile( "^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$"); A: That string is an IPv4 string format that was originally introduced by the aton_inet utility in BSD Unix and has persisted until this day in the various Unix and Linux flavours and elsewhere. https://linux.die.net/man/3/inet_aton The IPAddress Java library will do validation that can be configured to support aton_inet formats or not. The javadoc is available at the link. Disclaimer: I am the project manager. Verify if an address is valid, allow inet_aton style: String str = "200"; IPAddressString addrString = new IPAddressString(str); try { IPAddress addr = addrString.toAddress(); System.out.println("valid address: " + addr.toCanonicalString()); } catch(IPAddressStringException e) { System.out.println(e.getMessage()); } Output: valid address: 0.0.0.200 Verify if an address is valid, do not allow inet_aton style: IPAddressStringParameters parameters = new IPAddressStringParameters.Builder().allow_inet_aton(false).toParams(); addrString = new IPAddressString(str, parameters); try { IPAddress addr = addrString.toAddress(); System.out.println("valid address: " + addr.toCanonicalString()); } catch(IPAddressStringException e) { System.out.println(e.getMessage()); } Output: 200 IP Address error: options do not allow IPv4 address with less than four segments A: After a small research I ended up with something like this public static boolean isValidIP4Address(String ipAddress) { if (ipAddress.matches("^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$")) { String[] groups = ipAddress.split("\\."); for (int i = 0; i <= 3; i++) { String segment = groups[i]; if (segment == null || segment.length() <= 0) { return false; } int value = 0; try { value = Integer.parseInt(segment); } catch (NumberFormatException e) { return false; } if (value > 255) { return false; } } return true; } return false; } which was fine for simple checks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550806", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How To Select multiple cells in DataGridView I have a DataGridView in my Form. The Functionality is as below. * *Clicking on header selects the whole column. *Clicking on any cell other than the column header selects the entire row I have set multiselect to true. I am able to select multiple cells by using the mouse. but I want to do it programmatically. A: If you have multiselect true for your DataGridView then you can loop through the grid and the set the desired row as Selected (Also your dataGridView.SelectionMode should be FullRowSelect) dataGridView.Rows[0].Selected = true;//determine index value from your logic dataGridView.Rows[5].Selected = true; EDIT Instead of row select then you can try this logic, subscribe to the rowheaderclick event wherein you would get the row index for which it was clicked, now loop through the columns and set each cell as selected (similar to above) In the same way for the HeaderClick event you would have the column index available, now loop row wise and set the row indexes selected. datagridview1[columnindex, rowindex].Selected = true For rows the rowindex would be fixed whereas for column select the columnindex would be fixed. Hope this helps you. A: It's important to allow the DataGridView to complete loading its data before attempting to select (multiple) items. You can do that in the DataBindingComplete event handler. Here's a working example: List<int> items = new List<int>() { 2, 4 }; private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) { dataGridView1.ClearSelection(); int lastItem = 0; // Save the last match to scroll to it later bool cellSelected = false; for (int i = dataGridView1.Rows.Count - 1; i >= 0; i--) { if (items.Contains((int)dataGridView1.Rows[i].Cells[0].Value)) { lastItem = i; dataGridView1.Rows[i].Selected = true; if (!cellSelected) // gotta select only one cell { dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells[0]; cellSelected = true; } } } dataGridView1.FirstDisplayedScrollingRowIndex = lastItem; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7550807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Database add item to list view? I download this database script and i was wondering how can i convert it to instead add a item to a list view.. its a really easy understandable database code.. http://www.anotherandroidblog.com/wp-content/uploads/2010/08/AABDatabase.zip Thats the source for it.. also im guessing it could be in here?? /** * retrieves a row from the database with the id number in the corresponding * user entry field */ private void retrieveRow() { try { // The ArrayList that holds the row data ArrayList<Object> row; // ask the database manager to retrieve the row with the given rowID row = db.getRowAsArray(Long.parseLong(updateIDField.getText().toString())); // update the form fields to hold the retrieved data updateTextFieldOne.setText((String)row.get(1)); updateTextFieldTwo.setText((String)row.get(2)); } catch (Exception e) { Log.e("Retrieve Error", e.toString()); e.printStackTrace(); } } A: To add the items from database to a ListView you can have an ArrayList 1.) ArrayList<String> arrList = new ArrayList<String>(); 2.) Fetch items from database and add them to ArrayList if(c.getCount() > 0){ c.moveToFirst(); for (int i = 0; i < c.getCount() - 1; i++) { arrList.add(c.getString(0)); c.moveToNext(); } 3.) Then populate the Adapter with the ArrayList(arrList). 4.) And fill the ListView with the Adapter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I get the "children" or contents of a function? For example, if my script is... function cool() { function yes() { alert('yes'); } function wow() { alert('wow'); } } And I use cool.toString(); then I get the entire function as a string. But what do I have to do to just get the inner-contents as a string: function yes() { alert('yes'); } function wow() { alert('wow'); } A: * *Use toString to get the entire function, like just did in your example *Replace the beginning of the toStringed-function, all the way until (and including) the first { with an empty string. *Remove the last character of the toStringed-function. Like this: cool.toString().replace(/^[^{]*{/, "").slice(0, -1)
{ "language": "en", "url": "https://stackoverflow.com/questions/7550809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Managing website image assets I've got a bunch of images on my site, ranging from icons, to pictures, to html email images, to sprites, etc.. Rather than coming up with more and more complex image names and descriptive folder paths, does anyone have experience with any software that helps manage these images with categories and tagging? It would have to be something simple and light that the engineers on my team could use to easily locate an image asset for a left pointing arrow, even if the name is something like larr.png Thanks! A: Starting from www root folder you should have something like this. img (main images folder) img/sprites (sprites in here) img/icons (icons folder) img/html-email (html email images) Basically, try and keep file and folder names as descriptive as possible so everything is self documenting for example... img_001.jpg ( you don't have any idea what this image could be of ) whereas bear-catching-fish.jpg gives you a clue as to what the image is all about I'm not clear as to what you mean by tagging though. EDIT Just google 'image management software' and you should find what you need such as... Canto Cumulus
{ "language": "en", "url": "https://stackoverflow.com/questions/7550811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to disable/enable asp.net timer control using Javascript? How to disabled/enabled asp.net timer control using Javascript? My code is: (but not working) function timeroff() { var b = document.getElementById('Timer1'); if (b) { b.disabled = true; } } function timeron() { var b = document.getElementById('Timer1'); if (b) { b.disabled = false; } } A: This allows a user to toggle an ASP timer control using ONLY JavaScript. I'm expanding this, but for now, it's working great ... if I want to disable the timer and not have the update panel refresh while working, it's great, not elegant yet, but it works. Note, this works with an update panel and a timer named ID=tmrFillAlerts (see below code) ... I'm listing the most basic required ... I took out the CSS and formatting so it would be easier to follow but with all that included, it looks like this ... The toggles look like this when page loads and you click the user button with timer running ... Then, after clicking "Turn updates OFF" above, you see this and the timer is stopped ... You can see the "Turn updates OFF or ON" above are in the code below as ID=lblFlyOutTimerStatus below. Also, the RED ON/OFF ball above is below as ID=lblAlertsTotal. When the updates are ON ... and you click on the Bell or the Info button, you get a flyout like this thanks to the timer and it is updated every 60 seconds in my case (this shows the bell flyout) The Code Behind C# ... // Loads the DataList from the TIMER component private void udpAlertBar(object sender, EventArgs e) { // Do whatever you want here on timer tick ... // Write the last BELL alert time... lblAlertTime.Text = "Last update time:<br/>" + DateTime.Now.ToString("MM/dd/yyy hh:mm:ss tt"); // Load the BELL and INFO icon drop down lists FillBellInfoDataLists(); // Update red alert ballz .... UpdateAlertBallTotals(); } The ASP page code ... <asp:UpdatePanel id="udpAlertItemUpdater" runat="server"> <ContentTemplate> <!-- NOTE: The update panel must wrap just this area (UPDpnl kills the javascript for some reason otherwise) --------> <asp:Label id="lblTimerState" runat="server" Text="on" /> <ul> <li> <a href="javascript:void(0)" onclick="toggleUpdateTimer()"> <asp:Label ID="lblFlyOutTimerStatus" runat="server" Text="Turn updates OFF" /> </a> </li> </ul> <asp:Timer ID="tmrFillAlerts" runat="server" OnTick="udpAlertBar" Interval="60000" Enabled="true"/> </ContentTemplate> </asp:UpdatePanel> The JavaScript Code ... <script type="text/javascript"> function toggleUpdateTimer() { // Gets the timer control on the page named “tmrFillAlerts” var timerState = $find(“tmrFillAlerts”); // Gets the label I use for an alert ball on an icon on the page … var timerStatusRedAlertBall = document.getElementById(‘lblTimerState’); // Gets the menu item I have on the alert icon that drops down when clicked … var timerStatusFlyOutLabel = document.getElementById(‘lblFlyOutTimerStatus’); // Toggle the timer when the menu item is clicked …. if (timerState.get_enabled() == true) { stopUpdateTimer(); // NOTE: stop the timer, then disable … timerState.set_enabled(false); timerStatusRedAlertBall.innerHTML = “OFF”; timerStatusFlyOutLabel.innerHTML = “Turn Updates ON”;} else { timerState.set_enabled(true); // NOTE: Enable the timer, then start …. startUpdateTimer(); timerStatusRedAlertBall.innerHTML = “on”; timerStatusFlyOutLabel.innerHTML = “Turn Updates OFF”;} } function stopUpdateTimer() { var timer = $find(“tmrFillAlerts”); timer._stopTimer(); } function startUpdateTimer() { var timer = $find(“tmrFillAlerts”); timer._startTimer(); } </script> I stripped out everything but the relevant items to get it working ... otherwise this would have been ten pages long!! Works for me in all browsers at present from an IIS 8.5 running .NET ver: 4.0.30319.42000 It's a work in progress, that was quickly done, but found some cool stuff out there I thought I'd share. Hope it helps! Good luck!! A: The following works as long as the timer is not on a Master page because you will get an error stating "The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).]" when you put this javascript in the header of a Master page. function enableTimer() { var timer = Sys.Application.findComponent(‘<%= Timer1.ClientID %>’); timer.set_enabled(true); } function disableTimer() { var timer = Sys.Application.findComponent(‘<%= Timer1.ClientID %>’); timer.set_enabled(false); } see: http://weblogs.asp.net/andrewfrederick/controlling-the-asp-net-timer-control-with-javascript for more details
{ "language": "en", "url": "https://stackoverflow.com/questions/7550812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to retrieve html elements value via .click jQuery function with data retrieved from MySQL? I have a question to ask. I have a search result that is based on data retrieved from MySQL database. And based on the data retrieved, I have embedded and echo a div and <a> tag to know which <a> is been clicked so that I can use searchresult_details.php to retrieve more details using ajax jQuery. <?php //include database connection file to call the class include('dbconn.php'); //db global connection $db = new DBConfig(); $db -> config(); $db -> conn(); //retrieve the keyword entered in the form in search.php $keyword = $_POST['keyword']; //call searchKeyValue method to retrieve the names whether client or staff searchKeyValue($keyword); function searchKeyValue($keyword) { $result = mysql_query("SELECT result_key, result_value FROM keyvalue WHERE result_value LIKE '%$keyword%'"); while($row = mysql_fetch_array($result)){ //echo $row['result_value']; //echo "<br />"; echo '<div style="background-color:#ffa; padding:20px"><a class="record" value="' . $row['result_value'] . '">' . $row['result_value'] . '</a>' . '</div>'; echo '<input class="tablename" type="hidden" name="tablename" value="' . $row['result_key'] . '" />'; } } ?> However, the <a> will have multiple rows been echoed. I need to retrieve the <a> that is clicked and the value that it is stored in that particular <a> element. I can't be using id in <a> because I think it would be tedious. I was thinking to use class so that in javascript I can use document.getElementsByClassName but I know such function in IE has errors. Any recommendations? A: please check jQuery class selector http://api.jquery.com/class-selector/ A: Take a look at this example. <?php while($stmt->fetch()){?> <td class="other"> <input type="hidden" class="rowid" value="<?php echo $id ?>"/> <?php echo round($other,2); ?> </td>`enter code here` <?php } ?> <script> //jquery code: $(document).ready(function(){ $(".other ").mouseover(function(){ var rowid = $('#rowid').val(); $.get('other.php',{postrowid:rowid}, function(data){ $('#otherResult').html(data); $('#otherResult').show(); $(".other").mouseout(function(){ $('#otherResult').hide(); }); }); }); }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7550814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: reaching particular co-ordinate in projectile motion? As I wanted to animate an image in projectile motion, My code is as follows, but it did not reach the target and give projectile animation, any help please? -(void)timeLine { dTime += 0.1; ................. double s_x = inVel * cos(angle1) ; // the X speed double s_y = inVel * sin(angle1) ; // the Y speed NSLog(@"sx = %i",s_x); NSLog(@"sy = %i",s_y); x = oX + (s_x * dTime); y = oY + ( ( s_y * dTime) - (0.5 * 9.8 * dTime * dTime)); NSLog(@"x = %i",x); NSLog(@"y = %i",y); imageViewForAnimation.x += x; imageViewForAnimation.y -= y; } A: imageViewForAnimation.x += x; imageViewForAnimation.y -= y; These lines don't seem right to me. You are calculating the actual x and y each time, not the difference moved since the last time. I'm also uncertain why one was being added and one was being subtracted, but that's beside the point. Basically, try changing the lines to imageViewForAnimation.x = x; imageViewForAnimation.y = y; Also, you're doing some calculations over and over which only need to be done once. v_x == s_x (or it should within floating point error) as well as v_y == s_y. You only need to calculate v_x and V_y once beforehand rather than calculating them every time you update the coordinates.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: C#, ASP.net application which calls executable to create output file We are developing a web application in ASP.Net and C#. The requirement here is to interact with a third party exe which is developed in Fortran77. This third party exe produces an output file after being provided with some inputs and shuts down.In windows desktop single user application this is easily possible by using System.Diagnostics.Process and the events provided therein. But in web there will be multi-user environment, and many calls will be made to this exe. What are the best possible ways to handle such an exe in web application? * *Is it fine if we invoke exe on each user request as the exe shuts down after generating output file? Or *Is it possible to use windows service? Or *Any other approach? Thanks in advance. -Prasad A: Typically, invoking a different process to do some job (for a request) does not scale well when your number of requests start growing. Said that, if the process invocation is not going to happen frequently then you should be OK. The number of concurrent requests and through-put etc will really depend on your server hardware and the best bet would be to load test the server. As such you should use Process class to launch the process to get the work done. Yet another issue that is possible that your legacy executable does not support multiple instance. It's unlikely but there are quite a few desktop windows application that check for existing instance. So in such, you cannot launch process concurrently and only way would be to create a queuing logic - you can create a in-process queue (in your web application) or create a external application (such as windows service) that will do queuing. There can be alternate approach for this solution that is useful when the time taken for process to complete is large (so that you cannot block your web requests till the job is complete) and/or you need to scale your app to support more load. Essentially idea is use producer-consumer pattern where your web server will add requests to a persisted (e.g. table in database) queue and then you have multiple machines/servers running a job/windows service that would read from this queue and run the process to generate file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ASP.Net MVC 3 CheckBoxList from database i have a table called tb_role id role 1 admin 2 user 3 viewer and for the View is like this : <div style="width:50%; float:right;"> <legend>User Role</legend> <table> <tr> <th>Role</th> </tr> <tr> <td align="center"><input type="checkbox" id="CBRole"/></td> </tr> </table> </div> I want to ask, how to list my checkbox(CBRole) from my table? so my CBRole is listed from my table. thanks a lot EDIT assumed that i have Roles table like this : tb_role RoleId Role_Name 1 SalesCreate 2 SalesEdit 3 AgentCreate 4 AgentEdit i want to list role for Sales in checkbox (SalesCreate and SalesEdit, so its only have 2 checboxes), how to do that ? thanks A: You probably want to have something that looks like the following post on StackOverflow, Enum to CheckBox A: From your controller you populate your view model with these properties: Your RoleViewModel public IList<int> RolesSelected { get; set; } public MultiSelectList Roles { get; set; } From controller that handles the Get call (/roles/edit/1 for example) model.RolesSelected = new List<int>(); //here the code to populate the eventually already selected roles (update case) model.Roles = new MultiSelectList(repository.GetRoles(), "Id", "Name", model.SettoriSelected); then in your view (inside a form tag) you will do something like this @foreach (var item in Model.Roles) { <div class="MyClass"> <label for="@item.Value" class="MyClassForCheck"> <input type="checkbox" id="@item.Value" name="RolesSelected" value="@item.Value" @(item.Selected ? "checked" : "") />@item.Text</label> </div> } in the controller that answer the Post part you will access the RolesSelected with the IDs checked In the example I have put a div, but yuo can change it to what you like obviously. Hope it helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7550819", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: I used the following method to get iphone mac address, but sometimes result is null. This problem can occur in what circumstances? I used the following method to get iphone mac address, but sometimes result is null. This problem can occur in what circumstances? +(NSString *) macAddress{ int mib[6]; size_t len; char *buf; unsigned char *ptr; struct if_msghdr *ifm; struct sockaddr_dl *sdl; mib[0] = CTL_NET; mib[1] = AF_ROUTE; mib[2] = 0; mib[3] = AF_LINK; mib[4] = NET_RT_IFLIST; if ((mib[5] = if_nametoindex("en0")) == 0) { printf("Error: if_nametoindex error/n"); return NULL; } if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) { printf("Error: sysctl, take 1/n"); return NULL; } if ((buf = malloc(len)) == NULL) { printf("Could not allocate memory. error!/n"); return NULL; } if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) { printf("Error: sysctl, take 2"); return NULL; } ifm = (struct if_msghdr *)buf; sdl = (struct sockaddr_dl *)(ifm + 1); ptr = (unsigned char *)LLADDR(sdl); NSString *outstring = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)]; free(buf); return [outstring uppercaseString]; } A: bsd socket related functions won't activate iphone device's network capability *if it is on 3g and has not used network for several minutes. I had problem with dns retrieval and connect() with c socket call. If your sometimes is when your phone is on 3g and turned off(no network activity) for a while, then I would guess it's the same problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Lazy range iteration in javascript using underscore I've caught myself using this in place of a traditional for loop: _.each(_.range(count), function(i){ ... }); The disadvantage being creating an unnecessary array of size count. Still, i prefer the semantics of, for example, .each(.range(10,0,-1), ...); when iterating backwards. Is there any way to do a lazy iteration over range, as with pythons xrange? A: Just a note: _.each(_.range(count), function(i){ ... }); is equivalent to _.times(count, function(i){ ... }); small is beautiful... A: Considering the source of underscore.js says the following about range: Generate an integer Array containing an arithmetic progression I doubt there is a way to do lazy iteration without modifying the source. A: If you don't mind getting your hands dirty, dig into the sources of the older but stable and feature-complete MochiKit's Iter module. It tries to create something along the lines of Python's itertools.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to remove duplicate keys in array I have an array called $myarray - id position status name 4 23 4 john 3 45 3 mike 4 23 0 john 7 25 2 sam etc. i need to filter array by "id" and when similar records found i need to evaluate by "status"key to remove number that's 0 or less than "status" in matching row. Is there some way to do it fast like some function? A: You could use array_multisort(..) to sort by id ASC then status DESC. Then you could walk through the sorted array and delete rows where the id has been seen before. A: This removes all occurences of status=0. If u want to keep these rows, when there is no other matching id, remove the $value['status'] > 0 && $cleanarray = array(); foreach ($myarray as $value) { if ( $value['status'] > 0 && ( !array_key_exists($value['id'], $cleanarray) || $value['status'] > $cleanarray[$value['id']]['status'] ) ) $new_cleanarray[$value['id']] = $value; } A: array_filter() This might be of your use
{ "language": "en", "url": "https://stackoverflow.com/questions/7550826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: rails action_controller Processing by Controller ( #show as */* ) I am sending an ajax request to one of my controller#action but my development log shows Processing by FormsController#show as */* while this should have been FormsController#show as JS as its an ajax request Due to this the its rendering the format that it finds first in my responds to block in the controller Eg:- respond_to do |format| format.html{ } format.js { } end if I send ajax request to my controller it doesn't work as expected as my controller renders html response while it should process JS request. But if the respond_to block is in this way respond_to do |format| format.js { } format.html{ } end It work as expected. I think Processing by FormsController#show as */* is responding to which ever format it finds first in respond_to block. But my concern is why my development log is showing Processing by FormsController#show as */* instead of Processing by FormsController#show as JS when I have sent an ajax request. Am I doing something wrong or missing a small but important piece? A: Update your Rails.js file. I'm assuming you're using jQuery-Rails. Some time ago, Rails AJAX requests didn't automatically set the requested content-type. That has since been addressed, so if you update you shouldn't have */* as the highest-prioritity content-type in your HTTP headers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: VBA for opening and editing multiple Powerpoint files I have a folder with over 200 Powerpoint files and I have been have been struggling with a Macro that opens each of these files, edits them, saves them and closes them in a loop. I have managed to create code for the editing part, however I can't manage to create a code that picks each of the files in the folder. Using "*.pptx" doesn't seem to work and writing code with a specific filename for each of these files is very inefficient. Does anyone have a solution to this? Sub SaveNotesText() Dim oPres As Presentation Dim oSlides As Slides Dim oSlide As Slide Dim oShapes As Shapes Dim oSh As Shape Dim NotesText As String Dim FileNum As Integer Dim PathSep As String #If Mac Then PathSep = ":" #Else PathSep = "\" #End If Set oPres = ActivePresentation Set oSlides = oPres.Slides For Each oSlide In oSlides NotesText = NotesText & "Slide " & oSlide.SlideIndex & vbCrLf Set oShapes = oSlide.NotesPage.Shapes For Each oSh In oShapes If oSh.HasTextFrame Then If oSh.TextFrame.HasText Then NotesText = NotesText & oSh.TextFrame.TextRange.Text End If End If Next oSh NotesText = NotesText & vbCrLf Next oSlide FileNum = FreeFile Open oPres.Path & PathSep & "NotesText.TXT" For Output As FileNum Print #FileNum, NotesText Close FileNum End Sub http://www.pptfaq.com/FAQ00274.htm A: You can use Dir to loop through all the "#.ppt#" files in a folder, ie Public Sub DoFiles() Dim strFileName As String Dim strFolderName As String Dim PP As Presentation 'set default directory here if needed strFolderName = "C:\temp" strFileName = Dir(strFolderName & "\*.ppt*") Do While Len(strFileName) > 0 Set PP = Presentations.Open(strFolderName & "\" & strFileName) 'your code PP.Close strFileName = Dir Loop End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/7550840", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: grep error on installing rvm I'm on OS Lion 10.7.1, installed latest XCode from App Store. I have installed git 1.7.4 from dmg I'm trying to install rvm. I used this command from their homepage bash < <(curl -sk https://rvm.beginrescueend.com/install/rvm) I get some grep errors as shown below. What went wrong? shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory chdir: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory Cloning into rvm... remote: Counting objects: 5542, done. remote: Compressing objects: 100% (2699/2699), done. remote: Total 5542 (delta 3620), reused 3898 (delta 2115) Receiving objects: 100% (5542/5542), 1.87 MiB | 411 KiB/s, done. Resolving deltas: 100% (3620/3620), done. RVM: Shell scripts enabling management of multiple ruby environments. RTFM: HELP: Installing RVM to /Users/kl/.rvm/grep: ^hooks/[[:alpha:]]+_[[:alpha:]]+$: No such file or directory **grep: ^hooks/[[:alpha:]]+_[[:alpha:]]+$: No such file or directory grep: ^hooks/[[:alpha:]]+_[[:alpha:]]+$: No such file or directory grep: ^_: No such file or directory** Correct permissions for base binaries in /Users/kl/.rvm/bin... Copying manpages into place. Notes for Darwin ( Mac OS X ) For Snow Leopard be sure to have Xcode Tools Version 3.2.1 (1613) or later You should download the latest Xcode tools from developer.apple.com. (This is since the dvd install for Snow Leopard contained bugs). If you intend on installing MacRuby you must install LLVM first. If you intend on installing JRuby you must install the JDK. If you intend on installing IronRuby you must install Mono (version 2.6 or greater is recommended). To use an RVM installed Ruby as default instead of the system ruby: rvm install 1.8.7 # installs patch 352: closest supported version rvm system ; rvm gemset export system.gems ; rvm 1.8.7 ; rvm gemset import system # migrate your gems rvm --default 1.8.7 NOTE: As of 1.8.0 RVM once again loads .rvmrc files, by default, after asking your permission to trust it of course. If you do not wish to be enabled, simply set: export rvm_project_rvmrc=0 Within either your /etc/rvmrc or $HOME/.rvmrc file. This will turn off the cd/pushd hooks when sourcing the rvm() function into your shell. Example: echo 'export rvm_project_rvmrc=0' >> $HOME/.rvmrc; (Then close the current shell and open a new one.) Installation of RVM to /Users/kl/.rvm/ is complete. A: holy smokes. this had me pulling my hair out. removed offending line in .bashrc export GREP_OPTIONS=’–color=auto’ installed like a charm.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: identify if java cannot be executed in windows batch script I wrote the below batch script which asks for a JAVA_HOME path if its not present in environment, and then it verifies the java version. but before identifying java version it should also check whether java is present in the path (can be executed) or not. Please help me figure out if java -version can be executed or not and display proper message @echo off setlocal set VERSION5="1.5" IF "%JAVA_HOME%" == "" ( echo Enter path to JAVA_HOME: set /p JAVA_HOME= goto check_java_version ) ELSE ( echo Using %JAVA_HOME% goto check_java_version ) :check_java_version for /f "tokens=3" %%g in ('%JAVA_HOME%\jre\bin\java -version 2^>^&1 ^| findstr /i "version"') do ( set JAVAVER=%%g ) set JAVAVER=%JAVAVER:"=% set JAVAVER=%JAVAVER:java version =% for /f "delims=. tokens=1-3" %%v in ("%JAVAVER%") do ( set VER=%%w ) if not "%VER%" GEQ "5" goto wrong_version set JAVA_BIN=%JAVA_HOME%\jre\bin goto correct_java_version :correct_java_version REM echo JAVA Version is ok. set JAVA_LIB=%cd%/lib %JAVA_BIN%/java -cp %JAVA_LIB%/csm-runtime-1.0.jar;%JAVA_LIB%/groovy-all-1.8.1.jar;%JAVA_LIB%/commons-beanutils-1.8.3.jar;%JAVA_LIB%/csm-dbutil-1.0.jar;%JAVA_LIB%/commons-exec-1.1.jar;%JAVA_LIB%/log4j-1.2.8.jar;%JAVA_LIB%/commons-cli-1.2.jar -Dlog4j.configuration=com/ABC/csm/log4j.xml -Dendorsed_plugins_dir=./plugins com.ABC.csm.CSMMain %* goto end_java_version :wrong_version echo Current JDK Version %VER% echo Expected JDK %VERSION5% or greater. Please fix your SSATOP and try again. goto end_java_version :no_java echo No JDK found in %JAVA_HOME%. goto wrong_version :end_java_version endlocal 1 of the examples of invalid condition would be, instead of providing JAVA_HOME i.e., e:\csm\java I gave it as e:\csm\java\jre\bin which in this case should display proper error message that please provide a JAVA_HOME path A: To check the existence of a program in the PATH, windows batch provides the ~%PATH: option of the SET command. See HELP CALL or HELP FOR. Use this piece of code as a starting point. :ProgInPath set PROG=%~$PATH:1 goto :eof and use it like this call :ProgInPath java.exe IF "%PROG%" == "" ( echo Java.exe not found ) else ( echo. %PROG% ) in this example, if java.exe is in the PATH, it echoes its complete filespec. A: I used the below snippet and it solved my problem :check_java_existence IF EXIST %JAVA_HOME%\jre\bin\java.exe ( echo java exists ) ELSE ( echo java does not exists )
{ "language": "en", "url": "https://stackoverflow.com/questions/7550844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Hide the up or down arrow key when scrolling at the end of the Jscrollpane I used the JScrollPane from http://jscrollpane.kelvinluck.com/ and modified it to hide the arrow key when scrolling at the end (top or bottom). When scrollbar is at the top, the arrowUp should disappear, showing only arrowDown at the bottom and appears again when scrolling down. I've made the arrow image disappear at the top, but the problem is the scroll track does not change but just adds extra space equal to the size of the arrow image at the very bottom. How can I go around this, how do I change it so that when the arrow is hidden at one end, the jspTrack's height is adjusted as well, showing the other arrow on the opposite end without extra space? if (settings.showArrows) { if(isAtTop){ arrowUp.addClass('jspDisabled'); arrowUp.css('display', 'none'); } else{ arrowUp.removeClass('jspDisabled'); arrowUp.css('display', 'block'); } if(isAtBottom){ arrowDown.addClass('jspDisabled'); arrowDown.css('display', 'none'); } else{ arrowUp.removeClass('jspDisabled'); arrowDown.css('display', 'block'); } /*arrowUp[isAtTop ? 'addClass' : 'removeClass']('jspDisabled'); arrowDown[isAtBottom ? 'addClass' : 'removeClass']('jspDisabled');*/ } Thanks all. A: you can control it via css <style> .jspVerticalBar{ background:none; } .jspVerticalBar .jspArrow{ display:block; } .jspVerticalBar .jspDisabled { display:none; } </style> JavaScript: <script> $('.pane').jScrollPane({showArrows:true}); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7550849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I/O hangs after recursive pipe() calls This is a followup to my previous question. I am writing a linux shell, and so I need to deal with the possibility of users inputting multiple pipe commands. It is almost working correctly, except for after calling execvp() on the last command the I/O hangs. My prompt never reappears and I have to ctrl+C to leave the shell. I do not think it is an infinite loop happening, but rather I am not closing my streams correctly. I cannot figure out the correct way to do it. Example - If I do not use a pipe at all, the shell runs correctly: ad@ubuntu:~/Documents$ gcc mash.c -o mash ad@ubuntu:~/Documents$ ./mash /home/ad/Documents> ls a.out bio1.odt blah.cpp controller.txt mash.c bio1.doc blahblah.txt Chapter1Notes.odt mash /home/ad/Documents> However, if I type in: /home/ad/Documents> ls -l | grep sh -rwxr-xr-x 1 ad ad 13597 2011-09-26 00:03 mash -rw-r--r-- 1 ad ad 3060 2011-09-25 23:58 mash.c The prompt does not appear again. main() originally calls execute() with stdin and stdout. Thanks for your time! Code: #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <stdlib.h> int MAX_PATH_LENGTH = 1024; //Maximum path length to display. int BUF_LENGTH = 1024; // Length of buffer to store user input char * delims = " \n"; // Delimiters for tokenizing user input. const int PIPE_READ = 0; const int PIPE_WRITE = 1; void execute(char **argArray, int read_fd, int write_fd){ dup2(read_fd, 0); dup2(write_fd, 1); //Problem when entering only newline character char **pA = argArray; int i = 0; while(*pA != NULL) { if(strcmp(argArray[i],"<") == 0) { int input = open(argArray[i+1], O_RDWR | O_CREAT); pid_t pid = fork(); if(pid == 0) { dup2(input, 0); argArray[i] = 0; execvp(argArray[0], &argArray[0]); printf("Error redirecting input.\n"); exit(1); } wait(pid); } else if(strcmp(argArray[i],">") == 0) { int output = open(argArray[i+1], O_RDWR | O_CREAT); pid_t pid = fork(); if(pid == 0){ dup2(output,1); close(output); argArray[i] = 0; execvp(argArray[0], &argArray[0]); printf("Error redirecting output.\n"); exit(1); } close(output); wait(NULL); } else if(strcmp(argArray[i],"|") == 0) { int fds[2]; pipe(fds); pid_t pid = fork(); if(pid == 0) { dup2(fds[PIPE_WRITE], 1); close(fds[PIPE_READ]); close(fds[PIPE_WRITE]); argArray[i] = 0; execvp(argArray[0], &argArray[0]); printf("%s: command not found.\n", argArray[0]); exit(1); } else { dup2(fds[PIPE_READ], 0); execute(&argArray[i+1], 0, 1); close(fds[PIPE_READ]); close(fds[PIPE_WRITE]); wait(pid); printf("herp\n"); } } *pA++; i++; } pid_t pid = vfork(); if(pid == 0){ execvp(argArray[0], &argArray[0]); printf("%s: command not found.\n", argArray[0]); exit(1); } else { wait(NULL); } } int main () { char path[MAX_PATH_LENGTH]; char buf[BUF_LENGTH]; char* strArray[BUF_LENGTH]; /** * "Welcome" message. When mash is executed, the current working directory * is displayed followed by >. For example, if user is in /usr/lib/, then * mash will display : * /usr/lib/> **/ getcwd(path, MAX_PATH_LENGTH); printf("%s> ", path); fflush(stdout); /** * Loop infinitely while waiting for input from user. * Parse input and display "welcome" message again. **/ while(1) { fgets(buf, BUF_LENGTH, stdin); char *tokenPtr = NULL; int i = 0; tokenPtr = strtok(buf, delims); if(strcmp(tokenPtr, "exit") == 0){ exit(0); } else if(strcmp(tokenPtr, "cd") == 0){ tokenPtr = strtok(NULL, delims); if(chdir(tokenPtr) != 0){ printf("Path not found.\n"); } getcwd(path, MAX_PATH_LENGTH); } else if(strcmp(tokenPtr, "pwd") == 0){ printf("%s\n", path); } else { while(tokenPtr != NULL) { strArray[i++] = tokenPtr; tokenPtr = strtok(NULL, delims); } execute(strArray, 0, 1); } bzero(strArray, sizeof(strArray)); // clears array printf("%s> ", path); fflush(stdout); } } A: This line - dup2(fds[PIPE_READ], 0); - overwrites your current stdin file descriptor with a descriptor referring to the pipe. Once the pipe command completes, any attempt to read from stdin will fail. This line - fgets(buf, BUF_LENGTH, stdin); - doesn't check for error conditions. Finally - you wait for the second process in the pipe to finish before you have started the second one. This is what is causing your deadlock; the "grep" command is waiting for input, but you haven't exec'd the "ls" command yet. You wait for the grep command to finish, but it can't finish because it is waiting for input. In your latest incarnation of the code: When the execute() function is called, it scans the arguments and finds a pipe; it then forks and runs the first command ("ls"): pid_t pid = fork(); if(pid == 0) { dup2(fds[PIPE_WRITE], 1); close(fds[PIPE_READ]); close(fds[PIPE_WRITE]); argArray[i] = 0; execvp(argArray[0], &argArray[0]); printf("%s: command not found.\n", argArray[0]); exit(1); Then it recurses, calling execute() again: } else { dup2(fds[PIPE_READ], 0); execute(&argArray[i+1], 0, 1); // <--- HERE ... this will of course fork and run "grep" before returning. Note that it does so with /both/ the pipe filed descriptors /open/. Therefore, the grep process itself will hold both ends of the pipe open. execute() performs a wait(NULL) before returning; this however will actually wait for the "ls" to finish (since that is the process that completes first). Then it returns, and proceeds: close(fds[PIPE_READ]); close(fds[PIPE_WRITE]); wait(pid); // <--- WRONG, compile with -Wall to see why printf("herp\n"); } I've pointed out one error. Try compiling with "-Wall", or reading the documentation for the wait() function! If you change it to wait(NULL) it will be correct, however, in that case it will block. The reason is that the "grep" command hasn't completed and is still reading input. The reason it is still reading input is because the grep process itself has the write end of the pipe open!! So, grep never sees the "end" of the input coming from the pipe. A simple fix is to close the pipe fds before calling execute() recursively (there remains other problems with your code however, including, as I have already pointed out, that you are trashing your stdin descriptor). A: These two lines have the arguments in the wrong order: dup2(0, read_fd); dup2(1, write_fd); You should be writing: dup2(read_fd, 0); dup2(write_fd, 1); Or: dup2(read_fd, STDIN_FILENO); dup2(write_fd, STDOUT_FILENO); However, whether amended or original, the call to execute is: execute(strArray, 0, 1); which means that these two dup2() calls do nothing (duplicating 0 to 0 and 1 to 1).
{ "language": "en", "url": "https://stackoverflow.com/questions/7550856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Heroku - New Relic Agent not running error on rake db:migrate First time I've seen this error when running a migration on Heroku. heroku rake db:migrate --app myapp (in /app) New Relic Agent not running. I have the New Relic addon in my app addons so would this be an issue with the heroku platform or my app? edit: App is running on the bamboo-ree-1.8.7 stack. A: The answer is that Heroku is telling you that the New Relic Agent is not running in that environment when you run rake, however rake db:migrate is still working, so actually everything is working as it should. Simply run your rake db:migrate, ignore the New Relic message, then heroku restart and everything should be working just fine. A: Seems this was a simple fix. The new relic addon on Heroku stopped working and simply required me to remove and add it back to my application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Sending mail using Gmail public static bool SendMail(string toList, string from, string ccList, string subject, string body) { MailMessage message = new MailMessage(); SmtpClient smtpClient = new SmtpClient(); try { MailAddress fromAddress = new MailAddress(from); message.From = fromAddress; message.To.Add(toList); if (ccList != null && ccList != string.Empty) message.CC.Add(ccList); message.Subject = subject; message.IsBodyHtml = true; message.Body = body; smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; smtpClient.EnableSsl = true; smtpClient.Timeout = 30000; smtpClient.Host = "smtp.gmail.com"; // We use gmail as our smtp client smtpClient.Port = 587; smtpClient.UseDefaultCredentials = true; smtpClient.Credentials = new System.Net.NetworkCredential("myemail@gmail.com", "mypassword"); smtpClient.Send(message); return true; } catch (Exception ex) { return false; } } The code seems ok, but still not working, I am not able to figure out why? any other way to use gmail's smtp to send mail. A: try var client = new SmtpClient("smtp.gmail.com", 587) { Credentials = new NetworkCredential("myusername@gmail.com", "mypwd"), EnableSsl = true }; client.Send("myusername@gmail.com", "myusername@gmail.com", "test", "testbody"); If the UseDefaultCredentials property is set to false, then the value set in the Credentials property will be used for the credentials when connecting to the server. Here you set UseDefaultCredentials as true then it will neglect credentials you given. A: Please try with Port 25. It's working for me. Also remove setting of UseDefaultCredentials. Update : Port 587 also working for me. So I think UseDefaultCredentials is only problem in your code. it should be set to false. public static void SendMail(string ToMail, string FromMail, string Cc, string Body, string Subject) { SmtpClient smtp = new SmtpClient("smtp.gmail.com", 25); MailMessage mailmsg = new MailMessage(); smtp.EnableSsl = true; smtp.Credentials = new NetworkCredential("email","password"); mailmsg.From = new MailAddress(FromMail); mailmsg.To.Add(ToMail); if (Cc != "") { mailmsg.CC.Add(Cc); } mailmsg.Body = Body; mailmsg.Subject = Subject; mailmsg.IsBodyHtml = true; mailmsg.Priority = MailPriority.High; try { smtp.Timeout = 500000; smtp.Send(mailmsg); mailmsg.Dispose(); } catch (Exception ex) { throw ex; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7550863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Uploading files and keeping them safe I'm using php and MYSQL. I've created a members area where people can upload important images (basically for financial record). I was hoping to get some advice as to the best way to store these files. What kind of folder structure would be best? Ex domain.com/Files/UserName/RandomGeneratedName/Files. Also any advice for chmod, .htaccess, .htpassword and any kind of password protection with php. Thanks in advance. A: I would recommend to store them outside the tree. In this way, by default you need to enable access to them, not disable access (just in case you have a bug in your .htaccess/config/code, the access to the files is disabled, not enabled) Second, get rid of the random directory, it doesn't add much to the security, but it complicates the implementation unnecessarily You can use php to check the member credentials, put the appropriate headers (mime type for ex., etag, etc.), and serve the file via passthru or something similar. A: Best way: * *protect the directory with .htaccess *add an index.html to directory "just in case" *use random file names to store them in your directory *use php/mysql to check if user has access rights to your files example: You have a file in domain.com/protecteddir/sdjasdu83299sdnYUsb.dat You can use php/mysql to send to user to a virtual directory to download the file. You can throw the correct file header + file name via php. So even if the file is called sdjasdu83299sdnYUsb.dat the user would download it as "myfinancial.doc" The user will never know what the real file is located nor its name. Your .htaccess file should contain: <Files *> Order Allow,Deny Deny from All </Files> A: you could .htaccess for URL Rewriting and get the index.php file (write this code: ) in folder that save your files, so when anyone want to enter this folder: First: he dont know real address second: due there is a index.php that offer to home page he could not enter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Loging out issue in iphone sdk I have created an tabbar based iphone app, for the login page i used the following method: @protocol LoginViewControllerDelegate; @interface TradeBarcodeViewController: UIViewController{ id<LoginViewControllerDelegate> delegate; } @protocol LoginViewControllerDelegate -(void)loginViewControllerDidFinish:(TradeBarcodeViewController *)loginViewController; @end @implementation TradeBarcodeViewController [self.delegate loginViewControllerDidFinish:self]; @end It is working fine and I can loggin to the tabbar controled app. In one of the tabbar viewconroller there is a button for Logout. I used the following for that: TradeBarcodeViewController *vc = [[TradeBarcodeViewController alloc]init]; [self presentModalViewController:vc animated:NO]; [vc release]; Then it will again navigate to the login page, but if I try to login again it is not working. What went wrong here? Or which method should I use to logout from my app? Thanks. A: if your login page is not in tabbar then when u click logout use this code //here u need to clear the field from database which checks for username and password [tabBar.view removeFromSuperview]; [tabBar release]; tabBar = nil; [self addLoginPage]; Then in addLoginPage function add this LoginPageViewController *loginView = [[LoginPageViewController alloc] init]; navigation=[[UINavigationController alloc]initWithRootViewController:loginView]; [window addSubview:navigation.view];
{ "language": "en", "url": "https://stackoverflow.com/questions/7550869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reverse Engineer Java code using BOUML I've followed all the instructions here here but I can't seem to find the option to Class diagram but can only find reverse engineer to class view. Can someone pls help me? I'm trying to reverse engineer my java code from Eclipse. A: Ok. I tried out the reverse engineering video on Youtube and it worked!
{ "language": "en", "url": "https://stackoverflow.com/questions/7550871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add composite widgets: This widget's parent does not implement HasWidgets I keep getting thrown an error: "This widget's parent does not implement HasWidgets. Of combed the web (including stackoverflow), but can't figure out what's the problem. I know its a problem with the way I add the Download object to the VerticalPanel 'text', however, I don't know why its throwing it, or how to fix it. Furthermore, when I run the application it first succeeds and only throws the error the second time around I try to access the download page. Any help would be greatly appreciated! public class SIXPAC implements EntryPoint, HasWidgets { private VerticalPanel mainPanel = new VerticalPanel() ; private HorizontalPanel menu = new HorizontalPanel() ; private VerticalPanel text = new VerticalPanel() ; private SIXPACServiceAsync services = GWT.create( SIXPACService.class ) ; public void onModuleLoad() { header() ; changePage( "about.txt" ) ; footer() ; RootPanel.get( "sixPac" ).add( mainPanel ) ; mainPanel.setWidth("100%"); } public void header() { menu.add( menu stuff... ) ; mainPanel.add( menu ) ; mainPanel.add( text ) ; } public void footer() { mainPanel.add( footer stuff... ) ; } public void changePage( String token ) { if( token.equals( "download.txt" ) ) // else its download page and need to set up the forms { text.clear() ; try { add( new Download() ) ; } catch( Exception e ) { System.out.println( e ) ; } text.setStyleName( "contentbox" ) ; } } public void add(Widget w) // tried basic implementation of the HasWidgets methods... { text.add( w ) ; } public void clear() { } public Iterator<Widget> iterator() { // TODO Auto-generated method stub return null; } public boolean remove(Widget w) { // TODO Auto-generated method stub return false; } } For the download class I basically removed everything for the sake of testing: package com.sixpac.website.client; import java.util.Iterator; public class Download extends Composite { private static VerticalPanel verticalPanel = new VerticalPanel(); public Download() { verticalPanel.setStyleName("contentbox"); initWidget( verticalPanel ); verticalPanel.setWidth("100%"); verticalPanel.add( new HTML( "<h1>Download</h1>" ) ) ; HorizontalPanel horizontalPanel = new HorizontalPanel(); horizontalPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER); horizontalPanel.setWidth("100%"); verticalPanel.add( horizontalPanel ) ; System.out.println( "creating new login" ) ; Login login = new Login() ; System.out.println( "creating new register" ) ; Register register = new Register() ; horizontalPanel.add( login ) ; login.setSize("75%", "310px"); horizontalPanel.setCellVerticalAlignment(login, HasVerticalAlignment.ALIGN_BOTTOM); horizontalPanel.add( register ) ; register.setSize("90%", "257px"); horizontalPanel.setCellVerticalAlignment(register, HasVerticalAlignment.ALIGN_BOTTOM); setStyleName("gwt"); } public static void downloadOk() { verticalPanel.add( new HTML( "<br/><br/>" ) ) ; verticalPanel.add( new HTML( "<div class=\"contentbox downloadok\">\n\t\n<p>Thank you for downloading SIXPAC Version 0.5 (Beta).</p>\n<p>Please direct all technical questions and bug-reports to Snehit Prabhu (<a href=\"mailto:snehitp@cs.columbia.edu\">snehitp@cs.columbia.edu</a>)</p>\n\t\n<br />\n\t\n<a href=\"#\" class=\"downloadbutton\">Download SIXPAC</a>\n\n<br /><br />\n</div>\n\n\n</div><!--contentbox-->" ) ) ; } } The stack trace: 02:24:14.763 [ERROR] [sixpac] Uncaught exception escaped com.google.gwt.event.shared.UmbrellaException: One or more exceptions caught, see full set in UmbrellaException#getCauses at com.google.gwt.event.shared.HandlerManager.fireEvent(HandlerManager.java:129) at com.google.gwt.user.client.ui.Widget.fireEvent(Widget.java:129) at com.google.gwt.event.dom.client.DomEvent.fireNativeEvent(DomEvent.java:116) at com.google.gwt.user.client.ui.Widget.onBrowserEvent(Widget.java:177) at com.google.gwt.user.client.ui.CustomButton.onBrowserEvent(CustomButton.java:698) at com.google.gwt.user.client.DOM.dispatchEventImpl(DOM.java:1351) at com.google.gwt.user.client.DOM.dispatchEvent(DOM.java:1307) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103) at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71) at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172) at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:337) at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:218) at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136) at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:561) at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:269) at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91) at com.google.gwt.core.client.impl.Impl.apply(Impl.java) at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:213) at sun.reflect.GeneratedMethodAccessor24.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103) at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71) at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172) at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:337) at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:218) at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136) at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:561) at com.google.gwt.dev.shell.ModuleSpace.invokeNativeVoid(ModuleSpace.java:289) at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeVoid(JavaScriptHost.java:107) at com.google.gwt.dom.client.DOMImplStandard.dispatchEvent(DOMImplStandard.java) at com.google.gwt.dom.client.Element$.dispatchEvent$(Element.java:142) at com.google.gwt.user.client.ui.CustomButton.onClick(CustomButton.java:825) at com.google.gwt.user.client.ui.PushButton.onClick(PushButton.java:190) at com.google.gwt.user.client.ui.CustomButton.onBrowserEvent(CustomButton.java:656) at com.google.gwt.user.client.DOM.dispatchEventImpl(DOM.java:1351) at com.google.gwt.user.client.DOM.dispatchEvent(DOM.java:1307) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103) at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71) at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172) at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:337) at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:218) at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136) at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:561) at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:269) at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91) at com.google.gwt.core.client.impl.Impl.apply(Impl.java) at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:213) at sun.reflect.GeneratedMethodAccessor24.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103) at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71) at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172) at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:292) at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:546) at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:363) at java.lang.Thread.run(Thread.java:680) Caused by: java.lang.AssertionError: This UIObject's element is not set; you may be missing a call to either Composite.initWidget() or UIObject.setElement() at com.google.gwt.user.client.ui.UIObject.getElement(UIObject.java:527) at com.google.gwt.user.client.ui.ComplexPanel.add(ComplexPanel.java:94) at com.google.gwt.user.client.ui.VerticalPanel.add(VerticalPanel.java:48) at com.sixpac.website.client.SIXPAC.changePage(SIXPAC.java:140) at com.sixpac.website.client.SIXPAC$3.onClick(SIXPAC.java:69) at com.google.gwt.event.dom.client.ClickEvent.dispatch(ClickEvent.java:54) at com.google.gwt.event.dom.client.ClickEvent.dispatch(ClickEvent.java:1) at com.google.gwt.event.shared.GwtEvent.dispatch(GwtEvent.java:1) at com.google.web.bindery.event.shared.EventBus.dispatchEvent(EventBus.java:40) at com.google.web.bindery.event.shared.SimpleEventBus.doFire(SimpleEventBus.java:193) at com.google.web.bindery.event.shared.SimpleEventBus.fireEvent(SimpleEventBus.java:88) at com.google.gwt.event.shared.HandlerManager.fireEvent(HandlerManager.java:127) at com.google.gwt.user.client.ui.Widget.fireEvent(Widget.java:129) at com.google.gwt.event.dom.client.DomEvent.fireNativeEvent(DomEvent.java:116) at com.google.gwt.user.client.ui.Widget.onBrowserEvent(Widget.java:177) at com.google.gwt.user.client.ui.CustomButton.onBrowserEvent(CustomButton.java:698) at com.google.gwt.user.client.DOM.dispatchEventImpl(DOM.java:1351) at com.google.gwt.user.client.DOM.dispatchEvent(DOM.java:1307) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103) at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71) at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172) at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:337) at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:218) at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136) at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:561) at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:269) at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91) at com.google.gwt.core.client.impl.Impl.apply(Impl.java) at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:213) at sun.reflect.GeneratedMethodAccessor24.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103) at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71) at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172) at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:337) at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:218) at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136) at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:561) at com.google.gwt.dev.shell.ModuleSpace.invokeNativeVoid(ModuleSpace.java:289) at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeVoid(JavaScriptHost.java:107) at com.google.gwt.dom.client.DOMImplStandard.dispatchEvent(DOMImplStandard.java) at com.google.gwt.dom.client.Element$.dispatchEvent$(Element.java:142) at com.google.gwt.user.client.ui.CustomButton.onClick(CustomButton.java:825) at com.google.gwt.user.client.ui.PushButton.onClick(PushButton.java:190) at com.google.gwt.user.client.ui.CustomButton.onBrowserEvent(CustomButton.java:656) at com.google.gwt.user.client.DOM.dispatchEventImpl(DOM.java:1351) at com.google.gwt.user.client.DOM.dispatchEvent(DOM.java:1307) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103) at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71) at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172) at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:337) at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:218) at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136) at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:561) at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:269) at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91) at com.google.gwt.core.client.impl.Impl.apply(Impl.java) at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:213) at sun.reflect.GeneratedMethodAccessor24.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103) at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71) at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172) at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:292) at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:546) at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:363) at java.lang.Thread.run(Thread.java:680) A: The problem is verticalPanel being static in download class. I assume that causes your code to initWidget with a bad reference when called more than once. Try removing static it should work. Also on a different note, you can implement the rest of the haswidget interface methods just like you implemented add ,by passing it through to text instance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Declaring variables before use in old C Recently I had to modify a legacy code that was compiled with a very old version of GCC (somewhere around version 2.3). Within a function, variable had to be declared before being used. I believe this is done C89 standard. This limitation is later removed. My question is: Back then, why did they enforce this ruling? Was there any concern that could jeopardise the integrity of the software? A: Variables still have to be declared before being used -- and they've never had to be declared just at the top of a function. The C89 requirement is that a block consists of an opening {, followed by zero or more declarations, followed by zero or more statements, followed by the closing }. For example, this is legal C89 (and, without the void, even K&R C, going back to 1978 or earlier): int foo(void) { int outer = 10; { int inner = 20; printf("outer = %d, inner = %d\n", outer, inner); } printf("outer = %d, inner is not visible\n", outer); return 0; } C99 loosened this, allowing declarations and statements to be mixed within a block: int foo(void) { int x = 10; printf("x = %d\n", x); int y = 20; printf("y = %d\n", y); return 0; } As for the reason for the original restriction, I think it goes back to C's ancestor languages: B, BCPL, and even Algol. It probably did make the compiler's job a bit easier. (I was thinking that it would make parsing easier, but I don't think it does; it still has to be able to distinguish whether something is a declaration or a statement without knowing in advance from the context.) A: It was mainly to make compilers easier to write. If all the declarations were at the top of the function, it would be easy for the compiler to parse all the locals and determine how much stack is needed. Of course now, compilers are a lot more mature than they were 30 years ago. So it makes sense to get rid of this restriction as it's become a nuisance to programmers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Problem with stringByEvaluatingJavaScriptFromString I wanna to know abt "stringByEvaluatingJavaScriptFromString". According to the apple doc. "The result of running script or nil if it fails." I have a method in which inside a for loop i'm passing a string value to stringByEvaluatingJavaScriptFromString. what will it do ?? will this get response for every string or something else will happen?? I was doing like this... - (void)loadWithStartPoint:(NSString *)startPoint endPoint:(NSMutableArray *)endPoints options:(UICGDirectionsOptions *)options { for (int idx = 0; idx < [endPoints count]; idx ++) { NSString *msg = [NSString stringWithFormat:@"loadDirections('%@', '%@', %@)", startPoint, [endPoints objectAtIndex:idx], [options JSONRepresentation]]; [googleMapsAPI stringByEvaluatingJavaScriptFromString:msg]; } } Inorder to get response to every string what should I do? I think that it should get response to every string that i'm passing here. Please tell me what m doing wrong and how would i manipulate my code to get response to all strings that m passing. Any help would be appreciated .Thnx in advance. A: You should make your javascript method to return a default string or something if even an error occurs in the script. function loadDirections() { try { //Your code goes here which returns some result } catch(err) { var errorFlag = "ERROR"; return errorFlag; } } and then you should alter your Objective C code like below NSString *msg = [NSString stringWithFormat:@"loadDirections('%@', '%@', %@)", startPoint, [endPoints objectAtIndex:idx], [options JSONRepresentation]]; if([msg isEqualToString:@"ERROR") { //Do some error handling } else { //Your actual code goes here } Update for the comment: To solve your javascript asynchronous problem either (1) you can change your design and call the javascript method only after getting response from the first call (2) or else you can use NSTimer which will will give a little time for the execution. In my opinion changing your design as per the first option would be perfect. Have a look at these questions stringByEvaluatingJavaScriptFromString doesn't always seem to work return value javascript UIWebView
{ "language": "en", "url": "https://stackoverflow.com/questions/7550877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Variable Value Changes By Itself I've been pretty confused while programming before, but this one takes the cake. Basically I set the value in one for loop, and in the following iteration it changes to the value of the next one. for (int i = 0; i < 2; ++i) { for (int j = 0; j < numWords[i]; ++j) //numWords [0] = 9, numWords [1] = 7 { stb[i][j].word = const_cast<char*>(is (j + 1,1).c_str()); //is(int,length[opt]) converts int to string, c_str() returns const char *, but I need char * cout << is(j+1,1) << ' ' << stb[i][j].word << '\n'; } } for (int i = 0; i < 2; ++i) { for (int j = 0; j < numWords [i]; ++j) { cout << stb[i][j].word << ' '; } cout << '\n'; } Output: 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 1 1 2 2 3 3 4 4 5 5 6 6 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 My only guess now is something with the const, but it doesn't make sense why it would keep changing all previous array elements... A: This is pretty simple. Your program has undefined behaviour (if my assumptions about is() are correct). is(int, length) returns a std::string by value. You get a pointer to some internal structure in that string by using c_str(). This string is then destructed at the end of the full-expression. This destruction invalidates the pointers that you obtained from c_str(). This means that you fill up the array with pointers to invalid memory. You then read from these pointers to print out the contents of the array. Reading from invalid memory results in undefined behaviour. A possible explanation for the observed behaviour is this: Each string that is returns reuses the same memory. In the first loop you read from the memory before it has been overwritten by another call to is, and so you get the correct value. In the second loop you read from the memory after it has been overritten, and so you get the final value in the array.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Vertically align contained in I have something like this: <tr> <td> <div class="blue">...</div> <div class="yellow">...</div> </td> <td> <div class="blue">...</div> <div class="yellow">...</div> </td> </tr> Here's a example of my current HTML: http://jsfiddle.net/DcRmu/2/ Inside a <tr>, all <td>s have the same height. I want the yellow <div>s inside those <td>s to align vertically along the bottom of <td>; and the blue <div>s to align vertically along the top of <td>. I tried to set vertical-align to bottom and it didn't work. Thanks! A: vertical-align:bottom; should work Example: http://jsfiddle.net/jasongennaro/DcRmu/ EDIT As per the new fiddle You just need to place vertical-align:bottom; on the td not on the div I updated your fiddle: http://jsfiddle.net/jasongennaro/DcRmu/7/ EDIT 2 I reread the question again and I saw the change I want the yellow <div>s inside those <td>s to align vertically along the bottom of <td>; and the blue <div>s to align vertically along the top of <td> To do this, you need to * *set the vertical-align to top on the td *float the divs *give the bottom div a margin equal to the height of the cell minus the sum of the div heights. In this case, 200px - (50px + 50px) = 100px. New CSS tr td{ width:200px; height:200px; background:red; vertical-align:top; } div.blue{ width:50px; height:50px; background:blue; float:left; } div.yellow{ width:50px; height:50px; background:yellow; float:left; clear:both; margin-top:100px; } Working example: http://jsfiddle.net/jasongennaro/DcRmu/9/
{ "language": "en", "url": "https://stackoverflow.com/questions/7550884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: What is meant by singleton object?and what is it usage? Can anyone explain to me what a singleton object is? In many tutorials I found something like "create a sigleton object". Now I am working in iphone game development using cocos2d. I read "Create a singleton object to keep all the Game Center code in one spot" in raywenderlich multiplayer tutorial, and also he says: + (GCHelper *)sharedInstance; This static method to retrive the singleton instance of this class. But I don't know what a singleton is, or how to use it. A: A Singleton object is an object for which there is only a single instance for a given class. The Singleton pattern is used when you want to guarantee that a single instance of a class will be shared across clients in a system. Check out the C2 wiki page for more information. Here are some posts with examples of the use of singletons in objective-c: * *Using the Singleton Pattern in Objective-C *Singletons: You're doing them wrong A: A singleton is an instance of a class that is meant to be the only one of its kind. You usually have a class method that returns a pointer to this single instance or creates it if it didnot exist yet. Some examples of singletons are: NSFileManager defaultManager NSUserDefaults standardUserdefaults NSCharacterSet whitespaceCharacterset Singletons are the generally accepted method to hold model data and code in a central place that you can access from everwhere in your other code. All you need to do is to add the header and get the singleton pointer via class method. See here for a comparison of singleton versus global variables: http://www.cocoanetics.com/2009/05/the-death-of-global-variables/ A: Singleton object means there is only one object throughout your application. If you used any properties in a singleton class and you access this property using object of this class, which is also called singleton object, you will get the same value in you whole application until you change it manually. This concept is generally used to maintain some fix values that your application required like if your application has login process than may be you required logged in username to be carried in your application for use at any point of application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Drag & Drop a pictureBox onto Form I am writing a game. Player can choose items (such as weapon) and drag them to the form. Items are on the side, in PictureBox controls. I have set Form.AllowDrop to True. When I drag one of the items pictureBoxes, the pictureBox doesn't drop, neither even drag. I want to drag a pictureBox on the form, or at least know the position in the form which the player want to drag it in. EDIT: look at the logo above. When you click it and drag (without release) it drags. A: In Winforms you need to change the cursor. Here's a complete example, start a new forms project and drop a picturebox on the form. Set its Image property to a small bitmap. Click and drag to drop copies of the image on the form. public partial class Form1 : Form { public Form1() { InitializeComponent(); this.AllowDrop = true; this.pictureBox1.MouseDown += pictureBox1_MouseDown; } private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { var dragImage = (Bitmap)pictureBox1.Image; IntPtr icon = dragImage.GetHicon(); Cursor.Current = new Cursor(icon); DoDragDrop(pictureBox1.Image, DragDropEffects.Copy); DestroyIcon(icon); } } protected override void OnGiveFeedback(GiveFeedbackEventArgs e) { e.UseDefaultCursors = false; } protected override void OnDragEnter(DragEventArgs e) { if (e.Data.GetDataPresent(typeof(Bitmap))) e.Effect = DragDropEffects.Copy; } protected override void OnDragDrop(DragEventArgs e) { var bmp = (Bitmap)e.Data.GetData(typeof(Bitmap)); var pb = new PictureBox(); pb.Image = (Bitmap)e.Data.GetData(typeof(Bitmap)); pb.Size = pb.Image.Size; pb.Location = this.PointToClient(new Point(e.X - pb.Width/2, e.Y - pb.Height/2)); this.Controls.Add(pb); } [System.Runtime.InteropServices.DllImport("user32.dll")] extern static bool DestroyIcon(IntPtr handle); } A: For the draggable items, you need to call the DoDragDrop method in the MouseDown event. Make sure your form (or target) has the AllowDrop property set to true. For your target, you need to wire the dragging events: private void Form1_DragOver(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Copy; } private void Form1_DragDrop(object sender, DragEventArgs e) { // Examine e.Data.GetData stuff }
{ "language": "en", "url": "https://stackoverflow.com/questions/7550889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android: Deleting characters in EditText with TextWatcher still shows characters in suggestions In my activity I have an EditText to capture a file name. I am using a TextWatcher to prevent users from entering certain characters that I don't want them to use in their filename. Essentially I only want users to enter in the following characters: [a-zA-Z_0-9]. @Override public void afterTextChanged(Editable text) { String textStr = text.toString(); int length = text.length(); if (!Pattern.matches("\\w*", textStr)) { text.delete(length-1, length); } } EDIT: Adding more code in onCreate(...) fileNameEditText = (EditText)findViewById(R.id.UploadPhoto_fileNameEditText); fileNameEditText.addTextChangedListener(this); in layout xml file <EditText android:id="@+id/UploadPhoto.fileNameEditText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="20sp" android:layout_marginRight="10sp" android:layout_toRightOf="@id/UploadPhoto.fileNameLabel"/> This works perfectly by preventing users from entering in things like "\" and ".". The problem that I'm having is that if they type these characters they show up in the word suggestions box. Its kind of annoying because if you try to delete a character using backspace, it deletes from the suggestion first (even though the character doesn't show up in EditText box). How do you prevent the unwanted characters from showing up in the word suggestiong box? See screen shot below. Notice that the "-" (hyphen) appears in the suggestion box, but not in the EditText. Also notice that there is another valid character in the suggestion box after the hyphen that also does not show up in the EditText. This essentially blocks the user from entering in more text until they delete the hyphen, even though its not in the EditText. UPDATE: The same issue arises and can be reproduced by using an InputFilter instead of a TextWatcher. UPDATE: I'd like to clarify that my goal is not to suppress the Suggestions altogether. The issue is that when you prevent specific characters from appearing in the EditText, they still show up in the Suggestions. My goal (which the bounty is for) is to prevent the same specific characters from appearing in the Suggestions. A: You should use an InputFilter to restrict some characters in Edittext InputFilter filter = new InputFilter() { public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { for (int i = start; i < end; i++) { if (!Character.isLetterOrDigit(source.charAt(i))) { return ""; } } return null; } }; edit.setFilters(new InputFilter[]{filter}); A: It seems that the emulator doesn't support the textNoSuggestions, and the corresponding FLAG (TYPE_TEXT_FLAG_NO_SUGGESTIONS). It's realy anoying, but hey: you're not developing for emulator users, you shouldn't be preoccupied with this, it'll work fine on allmost all devices. (Note that this flag is available only from API level 5) A: We can do that in the layout xml file and achive what you have asked in an easy way, insert the line android:numeric="your custom elements" android:digits="your custom elments" android:inputType="your custom elements" when you implement these then you will be able to type the words that you want to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Algorithm: Find all common substrings between two strings where order is preserved Would like to discuss algorithms, no code. Problem: Let S and T be two sequences of elements. Find the common subsequences between them where the order of the elements is preserved. It should have O(n + m) running time where n is the length of S, and m is the length of T. I would also like to make the assumption that for the most part the two sequences will be similar. An optimal solution?: After some research, one solution that appears to be optimal is to first build a generalised suffix tree for the two sequences. Then find the longest common substring and consider this subsequence to be part of the solution. Then either remove this subsequence from the tree or build a new suffix tree with this subsequence removed from the two original sequences to form S' and T'. Then find the longest common substring between S' and T', and so on. To analyze the running time, building the tree takes O(n) and you can find the lengths and starting positions of the longest common substrings of S and T in O(n + m). Are there other (more) practical solutions that someone knows of or can link to? Any published papers considering the same or related problem you all know about? Input and constructive criticism about the above solution? Thanks for all your time! A: My first thought was the use of a suffix tree, and relating it to the LCS problem. But I am not sure what a better solution would be off the top of my head. I did a quick search and came across a few papers and projects that might be useful, but no guarantees. http://dl.acm.org/citation.cfm?id=1625377 (direct link here I believe: http://www.aaai.org/Papers/IJCAI/2007/IJCAI07-101.pdf) http://code.google.com/p/all-common-subsequences/ Sorry, it has been a long day and I am not quite awake enough to attempt a better solution myself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: finding the section of a PE's entrypoint I'm trying to find what section the PE entrypoint points to. I have two questions: * *Is it correct to say that this section is the one such that section.PointerToRawData < AddressOfEntryPoint < section.PointerToRawData + section.SizeOfRawData ? *I see some PE's that have AddressOfEntryPoint > total size of file. How is this possible? Is the AddressOfEntryPoint value wrong? thanks A: Is it correct to say that this section is the one such that section.PointerToRawData < AddressOfEntryPoint < section.PointerToRawData + section.SizeOfRawData ? Not quite, the section you want should be the one such that: section.VirtualAddress < AddressOfEntryPoint < section.VirtualAddress+ section.VirtualSize Then to find the position in the file, use: AddressOfEntryPoint - section.VirtualAddress + section.PointerToRawData
{ "language": "en", "url": "https://stackoverflow.com/questions/7550899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python binding to ImageMagick I am looking for a good Python binding to ImageMagick, but there seem a lot of bindings already. I am not sure that which of these is the right tool for my job. Can you guys recommend me one? Here is the list of my requirements and preferences (in order of importance): * *Must be available on PyPI (to simplify our deployment) *Prefer ctypes over C API extension — we will go PyPy soon *Pythonic API design and naming conventions *Good documentation (especially API references) A: I found the package myself: magickwand is a ctypes-based ImageMagick binding for Python. Yet it has no documentation at all, it still satisfies most of my requirements. Plus: I finally started my own project: Wand.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: backbone.js router doesn't work on IE6 When I use the Router in Backbone.js, IE6 throw a Permission Denied on the following line: if (this.iframe && (frag != this.getFragment(this.iframe.location.hash))) the Backbone.js version is 0.5.3 , I also try some other version, but it is not work also. A: As far as I know backbone.js does not claim to support IE6 A: The Backbone.js router does work in IE6, but it uses hash fragment routing (http://domain/#route) instead of HTML5 history push state routing (http://domain/route)
{ "language": "en", "url": "https://stackoverflow.com/questions/7550912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to display an alert box on a non clickable link button I am having HyperLink on my webfrom in such a way that if proper user login and clicks on the link will navigate him to corresponding page. If not i make that as a non clickable field by using this code if(isAdmin) { // check for admin user Link1.NavigateUrl = "Reports.aspx"; Link1.NavigateUr2 = "Delete.aspx"; } else { Link1.NavigateUrl = "javascript:return void;"; Link1.NavigateUr2 = "javascript:return void;"; } In the else part i would like to display an alert box saying that you are not an authorized user. I also write another code for making that link as non selectable as follows LinkButton1.Attributes["OnClick"] = “return false;”; So can any one tell how can i write alert message in both the cases A: Link1.NavigateUrl = "javascript:alert('hello'); return false;"; OR Link1.Attributes["onclick"] = "alert('hello'); return false"; A: In your else part add: string prompt = "<script type=\"text/javascript\">alert('You are not an authorized user'); </script>"; ClientScript.RegisterStartupScript(typeof (Page), "alert", prompt); Regards
{ "language": "en", "url": "https://stackoverflow.com/questions/7550914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: user process memory mapping — is the bss section always the same size? This may be an older query but I could not find any satisfactory answer so far. To check the memory map of a file I wrote a small hello program. #include <stdio.h> #include <stdlib.h> int main(void) { printf("Hello\n"); return 0; } Now after compilation, when I use command size on its object file I get: # size hello text data bss dec hex filename 1133 492 16 1641 669 hello I checked the size for other files too. I always get bss as 16. Is bss fixed? Is this included in data or it is out of it. I mean is this 16 is included in 492 or not. As far as I understand, bss is uninitialized data segment. A: The size of the BSS section varies between programs. It describes the amount of data that is initialized with 'all bytes zero'. The zeroes are not actually stored in the object file, but the size of the BSS section is stored. The data section contains the initial values of all data structures that are not initialized to 'all bytes zero'; it too varies between programs. It does not include the space included in the BSS section. You'd get a bigger BSS section with a program like this: #include <stdio.h> #include <stdlib.h> #include <time.h> enum { A_SIZE = 100 }; static int a[A_SIZE]; int main(void) { srand(time(0)); for (int i = 0; i < A_SIZE; i++) a[i] = i; for (int i = A_SIZE; i > 0; i--) { int j = rand() % i; // Not good random number generation! int t = a[j]; a[j] = a[i-1]; a[i-1] = t; } for (int i = 0; i < A_SIZE; i++) printf("%d\n", a[i]); return 0; } The code shuffles the numbers from 0 to 99, with some bias in the random number generation (so it isn't a perfect shuffle, but that really isn't the point of the exercise — it is just non-trivial code that uses a static array, even though a local variable would be sufficient). When I run size (on Ubuntu 13.10), I get: text data bss dec hex filename 1593 584 432 2609 a31 shuffle For comparison, on the 'hello' program in the question, I get: text data bss dec hex filename 1200 560 8 1768 6e8 hello The main difference is that the array a occupies 400 bytes; the other 24 bytes of BSS belong to other code. A: Nice article on wikipedia describes what's .bss. This is a segment containing statically allocated variables. Thus, it's size is included in object file size and not fixed. A: Your query related .bss has been answer already; but if you are looking into memory mapping which seems to be purpose as per your query statement may I suggest using utilities like readelf, objdump & nm instead of size for a more detailed diagnostics . Also you may want to explore map files for gcc which can be generated through linker options -Wl,-M to console (stdout) or using -Wl,-Map,<map_file_name> which provide symbol mapping by ld & global storage. P.S: A very well answered query related to .bss on SO : Do .bss section zero initialized variables occupy space in elf file? A: BSS would have been larger if you had for example an un-initialised array: E.g. char bss[100]; Essentially, every static variable that is not initialised goes into BSS.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550916", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Change background colour on table cell and check checkbox I have have a table with the class "pretty". Each row has a checkbox next to it that selects the data using a form. I want to be able to click the cell and have the checkbox ticked/unticked. I have this working using $(document).ready(function () { $('.pretty tr').toggle(function() { $(this).find(':checkbox').attr('checked', true); }, function() { $(this).find(':checkbox').attr('checked', false); }); }); In addition to this I want the cells background colour to change when the checkbox has been selected and unchange if its deselected. I have not had any luck doing this, any idea's? I have tried adding $(this).addClass('cssclassname'); To the above with no luck :( Edit just an update the class "pretty" already has the following css which makes the data in the table differ in colour for each row. It seems when I try the jquery toggleClass function it doesn't apply it over the already existing CSS? table.pretty { background: whitesmoke; border-collapse: collapse; } table.pretty th, table.pretty td { border: 1px silver solid; padding: 0.2em; } table.pretty th { background: gainsboro; text-align: left; } table.pretty caption { margin-left: inherit; margin-right: inherit; } table.pretty tr:nth-child(odd) { background-color:#eee; } table.pretty tr:nth-child(even) { background-color:#fff; } A: See this DEMO An alternative to your Jquery is HERE Lets check the demo HERE . I am not sure it is the best way to do it A: $(document).ready(function () { $('.pretty tr').toggle(function() { $(this).find(':checkbox').attr('checked', true); }, function() { $(this).find(':checkbox').attr('checked', false); }); }); $(this).addClass('class'); will do it...
{ "language": "en", "url": "https://stackoverflow.com/questions/7550919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Application crashes on second run using splash screen In My application, I am using thread to show the splash screen. . . But i have also given the Android Licensing to My Application. Which also uses the thread. . . But While i am installing the Application it runs once.. if i again open it then it got crash. where is the problem ??? the code is as below : package com.EMTPrep.Paramedic.app; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.provider.Settings.Secure; import android.view.Window; import com.android.vending.licensing.AESObfuscator; import com.android.vending.licensing.LicenseChecker; import com.android.vending.licensing.LicenseCheckerCallback; import com.android.vending.licensing.ServerManagedPolicy; import com.EMTPrep.Paramedic.app.R; public class SplashActivity extends Activity { private static boolean DEBUG = false; private static int DURATION; private Handler splashHandler; private Runnable launcherRunnable; private LicenseCheckerCallback mLicenseCheckerCallback;// for the License private LicenseChecker mChecker;// for the License // === A handler on the UI thread. private Handler mHandler; private static final String BASE64_PUBLIC_KEY = "I have puted the Licensing code here";//// for the License // === Generate your own 20 random bytes, and put them here. private static final byte[] SALT = new byte[] { -46, 65, 90, -128, -13, -57, 74, -64, 51, 66, -85, -67, 89, -114, -36, 113, 77, 32, -64, 89 }; // for the License @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.splash); mHandler = new Handler(); // Try to use more data here. ANDROID_ID is a single point of attack. String deviceId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);// for the License // === Library calls this when it's done. mLicenseCheckerCallback = new MyLicenseCheckerCallback();// for the License // === Construct the LicenseChecker with a policy. mChecker = new LicenseChecker(this, new ServerManagedPolicy(this,new AESObfuscator(SALT, getPackageName(), deviceId)),// for the License BASE64_PUBLIC_KEY);// for the License doCheck();// for the License DURATION = Integer.valueOf(getString(R.string.splash_duration)); splashHandler = new Handler(); // ================ Main Code of the Application // launcherRunnable = new Runnable() { // @Override // public void run() { // Intent i = new Intent(SplashActivity.this, MainMenuActivity.class); // i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // startActivity(i); // SplashActivity.this.finish(); // } // }; // if (DEBUG) // { // splashHandler.post(launcherRunnable); // } // else // splashHandler.postDelayed(launcherRunnable, DURATION); // } protected Dialog onCreateDialog(int id) //// for the License { // We have only one dialog. return new AlertDialog.Builder(this) .setTitle(R.string.unlicensed_dialog_title) .setMessage(R.string.unlicensed_dialog_body) .setPositiveButton(R.string.buy_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse( "http://market.android.com/details?id=" + getPackageName())); startActivity(marketIntent); } }) .setNegativeButton(R.string.quit_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }) .create(); } private void displayResult(final String result) { // for the License mHandler.post(new Runnable() { public void run() { // mStatusText.setText(result); setProgressBarIndeterminateVisibility(false); //mCheckLicenseButton.setEnabled(true); } }); } private class MyLicenseCheckerCallback implements LicenseCheckerCallback // for the License { public void allow() { if (isFinishing()) { // Don't update UI if Activity is finishing. return; } // Should allow user access. launcherRunnable = new Runnable() { @Override public void run() { Intent i = new Intent(SplashActivity.this, MainMenuActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); SplashActivity.this.finish(); } }; if (DEBUG) { splashHandler.post(launcherRunnable); } else splashHandler.postDelayed(launcherRunnable, DURATION); displayResult(getString(R.string.allow)); } public void dontAllow() { if (isFinishing()) { // Don't update UI if Activity is finishing. return; } displayResult(getString(R.string.dont_allow)); // Should not allow access. An app can handle as needed, // typically by informing the user that the app is not licensed // and then shutting down the app or limiting the user to a // restricted set of features. // In this example, we show a dialog that takes the user to Market. showDialog(0); } public void applicationError(ApplicationErrorCode errorCode) { if (isFinishing()) { // Don't update UI if Activity is finishing. return; } // This is a polite way of saying the developer made a mistake // while setting up or calling the license checker library. // Please examine the error code and fix the error. String result = String.format(getString(R.string.application_error), errorCode); displayResult(result); } } private void doCheck()// for the License { //mCheckLicenseButton.setEnabled(false); setProgressBarIndeterminateVisibility(true); //mStatusText.setText(R.string.checking_license); mChecker.checkAccess(mLicenseCheckerCallback); } @Override // for the License protected void onDestroy() { super.onDestroy(); mChecker.onDestroy(); } } I think there might be the problem in thread. . . Please help me to solve it. . Thanks Please help me in this. . . And let me tell while i am able to run the application only at once. . . Thanks in advance. A: Can you try splashHandler.postDelayed(new Runnable(), DURATION); ? and put it up to fields private Handler splashHandler = new Handler();
{ "language": "en", "url": "https://stackoverflow.com/questions/7550921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++ cannot create new key in registry I really need your help. I tried everything but the result is always the same, nothing. Please advise. And this is my code #include <windows.h> #include <iostream> #include <windef.h> using namespace std; int main (void) { HKEY hKey; LONG regOpenResult; const char PATH[] = "C:\\Users\\les\\Documents\\visual studio 2010\\Projects\\registryTester\\Debug\\registryTester.exe"; RegCreateKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, NULL,REG_OPTION_VOLATILE, KEY_SET_VALUE, NULL, &hKey, NULL ); RegSetValueExW(hKey, L"regTest", 0, REG_SZ, (BYTE*)PATH, strlen(PATH)); RegCloseKey(hKey); } A: You're using the unicode version of the RegSetValueEx, but passing it a char* string. You should change the declaration of PATH to: const wchar_t PATH[] = L"C:\\Users\\les\\Documents\\visual studio 2010\\Projects\\registryTester\\Debug\\registryTester.exe"; And use wcslen instead of strlen since it's a wchar_t string. Since it's measured in bytes (not characters) and needs to include the null terminator, the size parameter should be wcslen(PATH)*2+2. A: Check the return status of each API call!!!! Use GetLastError () for each failure. Knowing the error should lead you to resolve the problem. Otherwise, you're flying completely blind... Yes, PATH shouldn't be an 8-bit character string if you're calling a 16-bit Unicode API. But it's not necessarily the only problem. And yes, "permissions" could very definitely be an issue if you're using Vista, Windows 7 or higher.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: 'No database channel is available' I have an app which connects to the internet and stores data in an SQL database. I tested with iOS4, it works completely as it should. When I upgrade to the new version though, I get an NSInternalInconsistencyException, with this as the reason: '_obtainOpenChannel -- NSSQLCore 0x951a640: no database channel is available' From what I can gather, my database is being accessed by something when it shouldn't be, though I can't understand where or why. Can anyone help me locate and properly diagnose my problem? A: I found something for this one: I got the error (among some other ones, seemingly randomly appearing) while I was accessing a managed object's relationships in a different thread than the one the managed context was created in. There have been some changes with respect to concurrent access to managed objects in iOS5 (see here http://developer.apple.com/library/ios/#releasenotes/DataManagement/RN-CoreData/_index.html#//apple_ref/doc/uid/TP40010637) - and although the doc states the default behaviour should be as pre-iOS5 it apparently is not true, my code did work without problems in iOS4.2. For now, my workaround was to do all the relationship-access thingies in the main thread, store the data in an array, and access the data I need in the other thread via that array. No more errors at least. This is not the 'nice' solution I suppose, as I should (and will) change the way I concurrently access managed objects, but I'm not going to change that in a hurry now. A: This default concurrency type for NSManagedObjectContext is NSConfinementConcurrencyType, which means it can only be used by a single thread. From the documentation: You promise that context will not be used by any thread other than the one on which you created it. You can instead create a managed object context that is backed by a private queue for multithreaded use: [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType] To use the managed object context from a different thread, use performBlock: (asyncronous) or performBlockAndWait: (synchronous), e.g. __block NSArray *results; [[self managedObjectContext] performBlockAndWait:^{ results = [[self managedObjectContext] executeFetchRequest:request error:&error]; }]; // do something with results The documentation says you don't need to use the block API from the thread that created the managed object context. Another option is to create separate managed object contexts for each thread. See the iOS 5 release notes for more info.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: how to add layouts in android livewallpaper i have created live wallpaper using canvas now i want to add the layout like(relative layout) if its possible? in live wallpaper we can able to use layout? please guide me how to add layout here if its possible? if possible means how can i called that layout in my canvas class? in this canvas how can i overwrite the ondraw mathod? i have searched hole internet i can't able to fine any information. i'm new to android live wallpaper and jave plz guide me. here is my code public class AquariumWallpaperService extends WallpaperService { private float mTouchX = -1; private float mTouchY = -1; int count = 1; public AquaticAnimal animal; public static final String SHARED_PREFS_NAME = "livewallpapertemplatesettings"; @Override public Engine onCreateEngine() { return new AquariumWallpaperEngine(); } class AquariumWallpaperEngine extends Engine { private Aquarium aquarium; public AquariumWallpaperEngine() { this.aquarium = new Aquarium(); this.aquarium.initialize(getBaseContext(), getSurfaceHolder()); } @Override public void onCreate(SurfaceHolder surfaceHolder) { super.onCreate(surfaceHolder); // By default we don't get touch events, so enable them. setTouchEventsEnabled(true); } @Override public void onVisibilityChanged(boolean visible) { if (visible) { this.aquarium.render(); } } @Override public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) { super.onSurfaceChanged(holder, format, width, height); } @Override public void onSurfaceCreated(SurfaceHolder holder) { super.onSurfaceCreated(holder); this.aquarium.start(); } @Override public void onSurfaceDestroyed(SurfaceHolder holder) { super.onSurfaceDestroyed(holder); this.aquarium.stop(); } } this is my canvas class public class Aquarium { private AquariumThread aquariumThread; private SurfaceHolder surfaceHolder; private ArrayList<Renderable> fishes; private Bitmap backgroundImage, backgroundImage1; private Bitmap boble; public Boolean bgchange = false; private Context context; public int count = 1, x = 100, y = 500, x1 = 400, y1 = 500, x2 = 10, y2 = 250; public AquariumWallpaperEngine aqua; public void render() { Canvas canvas = null; try { count++; if (count > 5) { if (count % 8 == 0) { x2++; y--; y1--; } } if (y == -20) { y = 600; y1 = 600; } if (x2 == 700) { x2 = -20; } if (count > 3000) { bgchange = true; } if (count > 6000) { bgchange = false; count = 0; } //System.out.println("count" + count); canvas = this.surfaceHolder.lockCanvas(null); synchronized (this.surfaceHolder) { this.onDraw(canvas); } } finally { if (canvas != null) { this.surfaceHolder.unlockCanvasAndPost(canvas); } } } protected void onDraw(Canvas canvas) { this.renderBackGround(canvas); for (Renderable renderable : this.fishes) { renderable.render(canvas); } }; public void start() { this.aquariumThread.switchOn(); } public void stop() { boolean retry = true; this.aquariumThread.switchOff(); while (retry) { try { this.aquariumThread.join(); retry = false; } catch (InterruptedException e) { // we will try it again and again... } } } public int getLeft() { return 0; } public int getRight() { return this.backgroundImage.getWidth(); } public int getRightbg() { return this.backgroundImage1.getWidth(); } public void initialize(Context context, SurfaceHolder surfaceHolder) { this.aquariumThread = new AquariumThread(this); this.surfaceHolder = surfaceHolder; this.fishes = new ArrayList<Renderable>(); this.context = context; BitmapFactory.Options options = new BitmapFactory.Options(); options.inPurgeable = true; this.backgroundImage = BitmapFactory.decodeResource( context.getResources(), com.thinkpal.live.R.drawable.aquarium, options); this.backgroundImage1 = BitmapFactory.decodeResource( context.getResources(), com.thinkpal.live.R.drawable.waquarium, options); this.boble = BitmapFactory.decodeResource(context.getResources(), com.thinkpal.live.R.drawable.bubble, options); this.addFishes(); } private void addFishes() { Point startPoint = new Point(100, 100); this.fishes.add(new ClownFish(this.context, this, startPoint, 90)); Point startPoint1 = new Point(100, 300); this.fishes.add(new ClownFish(this.context, this, startPoint1, 50)); Point startPoint2 = new Point(200, 200); this.fishes.add(new ClownFish(this.context, this, startPoint2, 15)); } private void renderBackGround(Canvas canvas) { Paint paint = new Paint(); canvas.drawBitmap(this.backgroundImage, 0, 0, null); if (bgchange) { canvas.drawBitmap(this.backgroundImage1, 0, 0, null); } canvas.drawBitmap(this.boble, x, y, null); canvas.drawBitmap(this.boble, x1, y1, null); canvas.drawBitmap(this.boble, x2, y2, null); canvas.drawText("Think palm", x + 10, y + 45, paint); canvas.drawText("Cochin", x1 + 20, y1 + 45, paint); canvas.drawText("Welcome to", x2 + 10, y2 + 45, paint); } } A: YOu could always call getTheme() in WallpaperService and then apply layouts to that, not sure what use it will be to you though. It looks like you've already got everything working, wouldn't really bother with layouts if I were you...
{ "language": "en", "url": "https://stackoverflow.com/questions/7550928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Creating a database in the blackberry device when the app is installed I want to create a database on my blackberry device when my app is installed. I did not find any event (e.g. onInstalled) so that i can create my databse on this event when the app is installed. Apparently there is a method DatabaseFactory.exists() which i can use to check if the database exists or not. But i do not want to check for this every time. I want to create the database when my app is installed and when the app is un-installed then the database should also get deleted. Thanks A: As far as I know RIM API SDK does not provide mechanism to catch install/uninstall events. And even the database is once created it can be deleted/damaged via the filesystem. For instance user deletes database files from the media-card or from the device memory. Just because user does not know what these files contain and assumes these as temporary or something else. It is a good approach to check the database presence before starting work with it. Otherwise user may get blank white screen with text "Exception 1234" and some additional text, or may get a popup with strange message, like "Error: FileNotFoundException...". A: See the SQLiteDemo in the blackberry samples demo then you can get solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: sencha touch:dynamically add/remove components to panels i extended a panel containing -Panel -Toolbar with button and i registered it as a xtype using Ext.reg().There is one more panel in which i want to add the registered xtype and did it. How can i add/remove a component/html content dynamically to the outer panel on button click. Thanks in advance. A: I hope it will help you : var component = ...; var position = 0; component.insert(position, new Ext.Panel({html : "inserted"})); component.doComponentLayout(); A: While an older question, you can use .add or .addDocked http://docs.sencha.com/touch/1-1/#!/api/Ext.Panel-method-add This is far simpler since it allows the panel to add the element and manage the height ect.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating view ,SQL Query performance I am trying to create view, But select statement from this view is taking more than 15 secs.How can i make it faster. My query for the view is below. create view Summary as select distinct A.Process_date,A.SN,A.New,A.Processing, COUNT(case when B.type='Sold' and A.status='Processing' then 1 end) as Sold, COUNT(case when B.type='Repaired' and A.status='Processing' then 1 end) as Repaired, COUNT(case when B.type='Returned' and A.status='Processing' then 1 end) as Returned from (select distinct M.Process_date,M.SN,max(P.enter_date) as enter_date,M.status, COUNT(case when M.status='New' then 1 end) as New, COUNT(case when M.status='Processing' and P.cn is null then 1 end) as Processing from DB1.dbo.Item_details M left outer join DB2.dbo.track_data P on M.SN=P.SN group by M.Process_date,M.SN,M.status) A left outer join DB2.dbo.track_data B on A.SN=B.SN where A.enter_date=B.enter_date or A.enter_date is null group by A.Process_date,A.New,A.Processing,A.SN After this view..my select query is select distinct process_date,sum(New),sum(Processing),sum(sold),sum(repaired),sum(returned) from Summary where month(process_date)=03 and year(process_date)=2011 Please suggest me on what changes to be made for the query to perform faster. Thank you ARB A: It is hard to give advices without seeing the actual data and the structure of the tables. I would rewrite the query keeping in mind these principles: * *Use inner join instead of outer join if possible. *Get rid of case operator inside COUNT function. Build a query so you use conditions in WHERE section not in COUNT. *Try to not use aggregated values in GROUP BY. Currently you use aggregated values New and Processing for grouping. Use GROUP BY by existing table values if possible. *If the query gets too complicated, break it into smaller queries and combine results in the final query. Writing a store procedure may help in this case. I hope this helps. A: For tuning a database query, I shall add few items additional to what @Davyd has already listed: * *Look at the tables and indexing on those tables. Putting the right index and avoiding the wrong ones always speed up the query. *Is there anything in the where condition that is not part of any index? At times we put index on a column and in the query we use a cast or convert on the column. So the underlying index is not effective. You may consider setting the index on the cast/convert of the column. *Look at the normal form conformity or over normalisation. 3. Good luck. A: If your are using Postgresql, I suggest you use a tool like "http://explain.depesz.com/" in order to see more clearly what part of your query is slow. Depending on what you get, you could either optimize your indexes, or rewrite part of your query. If your are using another database, I'm sure a similar tool exists. If none of these ideas help, the final solution would be to create a "materialized query". There are plenty of infos on the web regarding this. Good luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to import web service reference in Android by using Eclipse Indigo? I'm developing an android app and I have to import some web service references; currently I'm using Eclipse Indigo and I didn't find any import web reference option, so can anyone help me how to do it? A: As far as I am aware there isn't any method of automatically creating WSDL service references in Android. Unfortunately you will need to define the classes and methods that access the WSDL services yourself. If your web service is using SOAP then you may want to investigate http://code.google.com/p/ksoap2-android/ as a library to assist you with making the service calls. A: import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; public class DbRequest { public DbRequest() { } public String sendDBRequest(ArrayList<NameValuePair> httpPost) { String result = ""; String url = "http://www.YourURL.com/android/dbservice.php";//For Online Server //String url = "http://10.0.2.2/android/dbservice.php"; //String url = "http://192.168.1.4/android/dbservice.php";//For Local Server InputStream is = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); httppost.setEntity(new UrlEncodedFormEntity(httpPost)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { result = e.toString(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); } catch (Exception e) { result = e.toString(); } return (result); } } Replace the URL Address of your DB Service. It'll call it and will receive string as a result...
{ "language": "en", "url": "https://stackoverflow.com/questions/7550955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Building PJSIP for iOS 4 I am attempting to build the latest stable PJSIP (1.10) for the iPhone and I am running into some errors during my make. I've followed the instructions here, but I am not having any luck. I searched around SO and google and haven't run into anyone else with the same error, so I am a bit stuck. I've created my config_site.h as instructed. ./configure-iphone gives the output I've seen elsewhere, so that portion seems to be working correctly. make dep seems to be working correctly, as does make clean, but I get the following error on my make (which should be the final step before getting an Xcode project I can work with, by my reading at least). if test ! -d ../bin; then mkdir -p ../bin; fi /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/arm-apple-darwin10-gcc-4.2.1 -o ../bin/pjlib-util-test-arm-apple-darwin9 \ output/pjlib-util-test-arm-apple-darwin9/main.o output/pjlib-util-test-arm-apple-darwin9/xml.o output/pjlib-util-test-arm-apple-darwin9/encryption.o output/pjlib-util-test-arm-apple-darwin9/stun.o output/pjlib-util-test-arm-apple-darwin9/resolver_test.o output/pjlib-util-test-arm-apple-darwin9/test.o output/pjlib-util-test-arm-apple-darwin9/http_client.o ../lib/libpjlib-util-arm-apple-darwin9.a /pjproject-1.10/pjlib/lib/libpj-arm-apple-darwin9.a -O2 -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk -framework AudioToolbox -framework Foundation -luuid -lpthread -framework CoreAudio -framework CoreFoundation -framework AudioToolbox -framework CFNetwork -framework UIKit ld: library not found for -luuid collect2: ld returned 1 exit status make[2]: *** [../bin/pjlib-util-test-arm-apple-darwin9] Error 1 make[1]: *** [pjlib-util-test] Error 2 make: *** [all] Error 1 I am running on OS X 10.7.1 with Xcode 4.1 (I've got the beta for iOS 5 installed as well, but the make output doesn't appear to be referencing its folder at all from what I can tell). A: I'm not sure specifically what caused this, but I was able to work around it by building the app on a fresh OS X Lion install with nothing but Xcode 4.1 installed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Static pages (.html) vs ASP.NET pages (.aspx) we are going to develop a media website where we will show current news. For that we have 2 strategies: * *Create window service in C# which will generate static (.html) pages for website (with updated news) as there will be only images and text (no postback or server-side event required) on website and then service will upload affected pages on server. *Create application in ASP.NET (.NET Framework 4.0) and use output caching for few minutes in it (as news updates in every 2-3 minutes). Please suggest which one from above will be more preferable from performance (or other) point of view in my situation. Please also suggest if any other strategy may provide me better solution. Thanks. A: Making static pages will also prevents user to wait until new page is generated on server,so there is no way,only html can understand either new page or itself is generated again.This will cause user to make an interaction with the page (refresh) to find new results,so the cycle ends.You cannot expect user to know when content is changed. As long as the content is dynamic in time interval,you should prefer asp.net solution with AJAX requests.You can make this with single page. DO NOT FORGET that either developing via HTML or aspx or any kind will display your results in HTML output,so unless your page shall use any server content,try asp.net dynamically. I can also assist code,please verify the specs. Best Regards A: Second one will be nice method Problem with the first method: * *HTML page want to be created each time *Created HTML pages what to be deleted or overwritten each time *Whole page want to be recreated (by using AJAX update can be done faster) so comparatively second one is the right method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to reference ruby classes defined in a different project project1: contains app\models\foo.rb (ActiveRecord facade for foo object) project2: I would like to fetch all foo's in project2. How do I reference foo from project1 over here, so that I can avoid code duplication corresponding to fetching information from the same table? A: If you want to share data then ActiveResource should do the trick. I'd recommend watching the Railscast to get you started. If it's just the class code you're trying to share, then I'd say just put it in a gem. A: I think there are 2 approaches to do that: * *Use 2 databases in one Rails app. There are some related questions on stackoverflow. See as example How do i work with two different databases in rails with active records? *Use the Rails ActiveResource to do that. It is a lightweight approach, to use external resources by a REST interface. However, you drive 2 applications, and have calls between them. Depending on the operating system, this may cost more runtime than the other approach.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to display this chinese character? I already set mySQL Collation as utf8_unicode_ci, if I manual insert chinese character in my database, it's successful work to displaying chinese character, but once i use my code, it was display this ã€å¼µç‘žæŒ¯ã€æ±Ÿç¥¥ç¶�.. I had add this <meta http-equiv="Content-Type" content="text/html;charset=utf-8" ></meta> in my header, I had try utf8_encode ,but still the same problem happen. thank you and hope you guy reply me soonest A: Have you set the connection character set / collation? Execute this query immediately after creating a connection SET NAMES 'utf8' A: You have probably forgot to execute this query after connecting SET NAMES utf8 Try it and you'll see A: there 2 steps you should do * *add a query with UTF8 $query = "SET NAMES 'utf8'"; mysql_query($query); *make sure your file is encoded as UTF8, open your script with your favourite editor and save as UTF8 A: To ensure MySQL expects UTF-8 encoding by default from client connections, use the following query: SET NAMES 'utf8' In addition, make sure PHP interprets the string as UTF-8 string. Since PHP does not support multibyte characters, you must use a function to allow PHP to work with UTF-8 strings: utf8_decode() or something.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550966", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Songs are not playing due to Special character in url of the song I am working in android. I am designing a music player which is playing songs from the server. When the URL does not has any special character, the song plays well. But when there are some special characters in the URL then the song does not play. For example, the following url is not working: http://192.168.1.214/MusicApplication/Songs/desert rose sting & enigma.mp3 i am using this code to play my song. mediaPlayer.setDataSource(songURL); mediaPlayer.prepare(); mediaPlayer.start(); i have solved my problem related to the space. please tell me the solution for '&' symbol. A: Use URLEncoder.encode(songUrl, "UTF-8");
{ "language": "en", "url": "https://stackoverflow.com/questions/7550970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Set UITableViewCell data from remote JSON file I have UITableView representing list of cities (100 cities). For each city I want to call specific remote(URL) JSON to get city's weather information and populate response data for each city cell in the UITableView. When I run application, I want to see my table as fast as possible, so I don't need to wait for all json responses. I want that informations got asynchronously (when specific json is loaded, set it's information for corresponding city cell in the UITableView). Note: It is important for me to call seperate remote JSON files. Which technic is the best for this task? A: I would start with the following approach: Create a data structure to hold city information, including: * *path to your data service, *service call "state" (idle, waiting, completed, error), *weather information (from JSON returned by service call) When you first show the table, you will want to: * *initialize your array (of the aforementioned data structure), *initiate each service call asynchronously, *set each row (city) state to waiting. You will also probably want to return a custom UITableCellView with the city name (if you already have it) and a spinning activity indicator. This will be your best option to have a fast load time (not waiting for services to complete) and give some visual indication that the data is loading. Each service call should use the ViewController as its delegate; you will need a key field so that when the services return, they can identify with which row/city they are associated. As each service completes and calls the delegate, it will send the data to the ViewController, which (in turn) will update the array and initiate a UITableView update. The UITableView update is, in my opinion, the most difficult part. Typically cells are drawn or updated when they become visible; the table pre-fetches all visible cells' geometry and then queries the actual contents when it's ready to draw each cell; as a result, your strategy for updating cells will depend on how your table is used. * *If your cell geometry changes, you will most likely need to redraw your entire table; I shudder to think about what 50 simultaneous UITableView redraws will do for your app, so you might need to set a time-threshold to "chunk" updates and handle drawing more intelligently. [theTableView reloadData] will cause the entire table to be re-queried and redrawn. *If your cell geometry does not change, you can try to be more surgical of updating only the visible cells (the non-visible ones aren't an issue since their data will be queried when they become visible). [theTableView visibleCells] returns an array of visible cells; when your service call returns, you could update the data and then search the array to see if the cell in question is visible; if it is, you will probably need to send the specific UITableCellView a setNeedsDisplay message. There is a good explanation of setNeedsDisplay, setNeedsLayout, and 'reloadData' at http://iosdevelopertips.com/cocoa/understanding-reload-repaint-and-re-layout-for-uitableview.html. There is a relevant SO question at How to refresh UITableViewCell? Lastly, you will probably want to implement some updating logic in the service delegate error routine, just so you don't create endlessly spinning activity indicators. A: I do this now while searching multiple servers. I use Core Data, but you can use an NSMutableArray to accumulate your JSON responses. Every time you finish receiving date from one of your servers (for example, when connectionDidFinishLoading executes), take the JSON data object and add it to an NSMutableArray (let's call it weatherResults) (add it using the addObject method). You may want to convert the JSON to an NSDictionary before adding it to the mutable array weatherResults. Assuming your dataSource delegate methods refer to what is in the weatherResults NSMutableArray (for example, getting the number of rows from the size of the array using [weatherResults count]) you can do the following: After inserting the object to the array, you can simply call reloadData in the dataSource controller. You will see the table update as each new JSON results arrives. The results should append to the bottom of the table as they come in. If you want to sort the NSMutableArray each time a JSON results arrives, you can do that too. I do this and the time it takes to resort and reload the table is insignificant on my iPad. If you do not resort, it should be even faster. By the way, in this explanation, I assume that the JSON response contains all of the information that you need to fill in your table cell. That may not be the case. If it's not, you will have to correlate the response with other information you have, such as a list of cities that your program is presenting.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: save pdf problem with Silverlight from Windows Azure Hi I am using http://silverlightpdf.codeplex.com/ code to print pdf from my silverlight application hosted in Windows Azure. I am able to save the pdf from local/development pc, but when I try save the pdf from Azure Server, it is giving following error. Webpage error details User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; GTB7.0; EasyBits GO v1.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C; .NET4.0E; OfficeLiveConnector.1.5; OfficeLivePatch.1.3; FDM) Timestamp: Fri, 19 Aug 2011 04:24:34 UTC Message: Unhandled Error in Silverlight Application The remote server returned an error: NotFound. at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state) at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult) at InspirED.StudentHome.View.NotesTab.Notes.PrintGetResponse(IAsyncResult asynchronousResult) at System.Net.Browser.BrowserHttpWebRequest.<>c_DisplayClassd.b_b(Object state2) at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() at System.Threading.ThreadPoolWorkQueue.Dispatch() at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() Line: 1 Char: 1 Code: 0 URI: http://mystorageaccount.cloudapp.net/somappname.studenttestpage.aspx A: Since you did not post any code I can only guess what the problem is. But according to this page it could be due to. When a container is deleted, a container with the same name cannot be created for at least 30 seconds; the container may not be available for more than 30 seconds if the service is still processing the request. While the container is being deleted, attempts to create a container of the same name will fail with status code 409 (Conflict), with the service returning additional error information indicating that the container is being deleted. All other operations, including operations on any blobs under the container, will fail with status code 404 (Not Found) while the container is being deleted. If not, please post a sample of your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Magento file upload enhancement using jQuery - getting upload to add to cart I’ve (very roughly) integrated jQuery to enhance Magento’s file upload feature, however, I’ve yet to get the uploaded image to save across to the cart, ie, the filename doesn’t appear in the cart and consequently the user receives a validation error that a product option is required. http://hotdiggity.com.au/installs/magento/tshirt.html It’s working successfully on this site: http://topiono.de/index.php/oelbilder-vom-foto/portraits-personen.html Any suggestions would be appreciated please. A: it is because you did not specify the extensions allowed in the file upload field. Example if you are trying to upload a jpg you must put jpg in the allowed extensions or jpeg if you have more then one it would be jpg,jpeg,gif,png
{ "language": "en", "url": "https://stackoverflow.com/questions/7550974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Some (fundamental) questions and clarifications about Git I'm looking into and learning the basics of distributed version control systems, specifically Git. After watching Linus' Tech Talk about Git, I have a few questions that I don't fully understand. It's important to note that I am coming from an SVN, Windows-based background, and so all my questions are framed from that environment. * *How is merging into other people's branches handled? That is, of Joe and Jane both branch from head/master, and Joe wants to merge the changes Jane's made in her branch, how is this done? To make my question more specific - if Joe is in Argentina and Jane is in Russia, how is this done? Does every Git branch come with a server capable of doing these things? Or is a central server still responsible for keeping track of all current branches and where they live? How does Git know where all of these (potentially thousands) of branches live? (Especially in a Windows environment!) *Linus talks about not having backups, saying this is unnecessary, as everyone has a copy of his code. But if he clones a repository, makes a few dozen lines of changes, commits, but never pushes...does he not lose all of his changes if his machine dies? I thought I understand this concept correctly (all commits are local until pushed), but he seems extremely blase about the issue, so I am curious. A: 1) You will have to expose your repo such that peer-to-peer push / pull can be done using any one of the available transfer mechanisms ( ssh, git-daemon, etc.) In Git there is no real concept of server / client, but the general practice is to have a central repository that people push and pull to / from, much like the repo in SVN. Except that instead of the working copies, you have full repos on local as well. Being a DVCS, Git enables you directly collaborate with other people in your team and then push to the central repo. It will be very rare that you will not have such a central repo. 2) Linus must have been talking about backups for pushed code and not work in progress which reside on local repository, similar to how you would have changes in your working directory in SVN. Also note that he must have been talking in context of Linux code, which has hundreds of collaborators and hence he must have mentioned that they need not worry about backups of the repository since everyone has a copy of it. But of course, you can potentially lose your local changes / commits unless you have pushed. A: * *There are multiple protocols git can use to transfer data between repositories: * *Dumb HTTP - The client literally just downloads the required git object files, so any http server works. However, this wastes bandwidth. *Smart HTTP *Fetch Pack over SSH *Fetch Pack over git The last three are all "smart", in that client and server collaborate to avoid transferring unnecessary data. You can also use git bundle to export a binary with your changes, and then manually transfer it to someone else's computer. Your repo doesn't need to know where all the thousands of other branches are. Typically, you will add the few (or one) that you push or pull to/from as a remote. That's basically a shortcut for a repository URL. However, you can still push and pull from other URLs. Regardless of how you fetch the data, you eventually use git merge to merge it in. 2. Yes, Linus means he doesn't need backups of things he's already pushed. Presumably (if he really doesn't have backups), he commits and pushes often. You shouldn't take him too literally, as he is usually going for dramatic effect in his public statements. A: I'll give you a short answer. Lets start with 2). Yes you would lose data. He meant you dont need backups in a traditional sense (make copies of your full directory everytime). If you push its 'backed up'. If you didnt you iwll lose only the data since last push. Pushes are not the same as copy/paste. 1) How is merging into other people's branches handled? Essentially you have a git repository on your computer, either a cloned repo or a brand new one. Then you either need a remote location were you can push (you simply create a 'bare' repository then push to it) or you must have read access for other people to your files (perhaps on lan but pushing to a server is more traditional). With this bare repo or read access for others they can 'pull' your code into their repo and you can do the same. You can pull from anyone in any order even if the people dont know eachother and pulled from ppl you dont know about. The magic in git will figure out where to put everything and not merge something twice. Its pretty good at recognizing conflicts. A: 1) The merging is handled locally - servers do little more than enforcing linear timeline. In order to merge local with remote, your Joe will 'git pull' Jane's branch (over any of the supported protocols - some as simple as filesystem access, some more confusing like git+ssh), resolve any conflicts, and then potentially push his changes to the master (if he has write permissions there) or, publish it for Jane to get. If Jane didn't change anything in the meantime, she can git pull Joe's post-merge code without any manual merging. How does it know - it doesn't, you tell it where the remote branches are. There are hosting providers for git (github.com), you can roll your own on your webserver, and tell Joe/Jane the url via any means 2) Backups are rarely more often than daily. Linus presumably pushes more often than backs up - in fact, I use git as backup for my code regardless - with multiple remotes, I have a remote for my own code that is automatically pushed after each meaningful commit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550982", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: display form on mouse click on table elements using jquery I am using jquery to do the following stuff- I need to display the form right next to the table cell i click on, with some animation. The problem with my code is that the form displays only once, and after that on any more mouse clicks it doesn't. The code is- <script type="text/javascript"> $(document).ready(function(){ $("td").click( function(event) { var div = $("#myform"); div.css( { position:"absolute", top:event.pageY, left: event.pageX}); var delayTimer = setTimeout( function( ) { $that.fadeIn( "slow"); }, 100); div.mouseover( function( event) { if (delayTimer) clearTimeout( delayTimer); }).mouseout( function(){ if (delayTimer) clearTimeout( delayTimer); var $that = $(this); delayTimer = setTimeout( function( ) { $that.fadeOut( "slow"); }, 500) }); }); }); </script> </head> <body> <table width="600" border="2" cellpadding="4"> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </table> <div id="myform"> <form> <input type="text" value="Arjun"/> <input type="submit" value="submit" /> </form> </div> </body> </html> more explanation---- on clicking any td cell, the div tag with id "myform" should display.. with animation A: Your setTimout function refers to $that but you don't have such a thing in that scope: var delayTimer = setTimeout( function( ) { $that.fadeIn( "slow"); // No $that exists here }, 100); I think you meant to say div.fadeIn: var delayTimer = setTimeout(function() { div.fadeIn("slow"); }, 100); You should also set display: none on div before you fade it in or the fade-in won't do anything: div.css({ position: "absolute", top: event.pageY, left: event.pageX, display: 'none' }); And initialize it in your CSS: #myform { display: none; } Live demo: http://jsfiddle.net/ambiguous/dWYfD/
{ "language": "en", "url": "https://stackoverflow.com/questions/7550986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Full Screen Browser window (Like F11) I am creating a web application. How do I change the browser from normal mode to fullscreen mode (like F11), but I don't want to open a popup for this. I want to convert the same window to fullscreen mode. The requirement is: there is a button on the page, and it's a toggle button for changing normal mode to fullscreen mode and fullscreen mode to normal mode A: Try this javascript code below. <script> function fullScreenMode(url) { window.open(url, '', 'fullscreen=yes, scrollbars=auto'); } </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7550989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to turn on multiselect checkbox mode on a grid in ext js I am experimenting with this: http://dev.sencha.com/deploy/ext-4.0.0/examples/grid/infinite-scroll.html I'm trying to make it possible for the grid to have checkboxes beside each row, so that a user can select multiple rows. I tried: SelModel: 'CheckboxSelectionModel', In the configs, it didn't make a difference, I've also removed this line: disableSelection: true, A: You need to create an instance of the selection model class. For example, you can have it in your grid panel's initComponent method: this.selModel= Ext.create('Ext.selection.CheckboxModel'); or you could add the following into grid's config: selModel : Ext.create('Ext.selection.CheckboxModel') If you see the API documentation, the selModel requires a Object and not a string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550992", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Gmail Style Always Visible Menu I am looking to implement something similar to Gmail's always visible menu. I'm not sure what the effect is called. Is this something I can do in JavaScript? If so, can someone point me in the direction of how I can achieve this? A: Yes you can. there are some plugins that do it like: * *Waypoints *jquery floating menu *stickyfloat
{ "language": "en", "url": "https://stackoverflow.com/questions/7550993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dynamic image generation in java? I am developing an android app which would use Facebook API to post picture on to the profile. One problem is that I don't know how to generate image dynamically using some image (from the phone) and text (generated automatically) and combine both to form one dynamic image. Is there any package I can use or is there any way to do it java? A: You need to get your Bitmap, probably loaded from the BitmapFactory and then wrap it in a Canvas object. The Canvas object will allow you to manipulate the Bitmap. Once you are finished with the Bitmap, you can convert it to JPG with the compress method on Bitmap. Detailed instructions on painting with Android - http://groups.google.com/group/android-developers/browse_thread/thread/ac6450c22dc88aff?pli=1 Detailed instructions for writing as a particular format - Image on canvas to JPEG file A: As stated in a comment below, this Java SE approach does not work. Couldn't you simply try to draw the Image? I mean I have no idea how to do this in Android, but in Java SE: BufferedImage created_image = new BufferedImage(hight, width); Graphics2D g2d = (Graphics2D) created_image.getGraphics(); g2d.drawImage(picOfFace1, 0, 0, null); g2d.drawImage(picOfFace2, 50, 0, null); g2d.drawString("First name", 0, 50); g2d.drawString("Second name", 50, 50); g2d.dispose(); return created_image; You create a new Image, draw the pics on the image, draw the String on the image, you're done =)
{ "language": "en", "url": "https://stackoverflow.com/questions/7550994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I scrape the text from a certain DIV using PHP and exlude html tags inside the DIV I have a project I'm working on where I need to scrape the text out of a specific div tag but only the text no html tags. Here is example of the html: <div id="divid1" class="divclass1"> <h1> TEXT INSIDE DIV </h1> </div> I need to scrape the text inside the DIV w/ out the H1 tags. I've tried this numerous ways and just can't get it right. Any suggestions? Thanks! A: use PHP domparser, that is good for this purpose. http://www.php.net/manual/en/domdocument.loadhtml.php A: I would use PHP Simple HTML DOM Parser. http://simplehtmldom.sourceforge.net/ You could say: foreach ($html->find('div[divid1] h1') as $e) echo $e->innertext; This will echo the text within the h1 tag inside #divid1 (but not the tag itself). The documentation is simple, but helps a bunch: http://simplehtmldom.sourceforge.net/manual.htm
{ "language": "en", "url": "https://stackoverflow.com/questions/7550995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I send logout request to radius server with radius client? There is one pptp server and I use radius server for authentication. Sometimes the vpn client is off line with unknow reason , so the radius can not clear the session for client. I want to run one process with radius client to monitor the client, if the client has no heartbeat, the process will send logout request to radius server for client. So i want to know what is the logout request message in radius client? A: You've tagged your question with several languages. Assuming you would like to do this in Python, you can use Pyrad and use one of the method from pyrad.packet.
{ "language": "en", "url": "https://stackoverflow.com/questions/7550998", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: asp.net required field validator A required field validator should fire only after clicking a submit button <asp:RequiredFieldValidator id="req" controltovalidate="txtphone" errormessage="please enter the details"> </asp:RequiredFieldValidator> A: If you are using a button field try by applying Validation Group Property in both the validator and Button as follows <asp:RequiredFieldValidator id="req" runate="Server" controltovalidate="txtphone" errormessage="please enter the details" ValidationGroup="g"> <asp:button id="btn" runat="server" validationgroup="g"> A: Youre missing runatserver on your code Check this: <form id="form1" runat="server"> Phone Number:<br /> <asp:TextBox runat="server" id="txtphone" /> <asp:RequiredFieldValidator runat="server" id="req" controltovalidate="txtphone" errormessage="Please enter your phone number!" /> <br /><br /> <asp:Button runat="server" id="btnSubmitForm" text="Ok" /> </form> Regards
{ "language": "en", "url": "https://stackoverflow.com/questions/7551002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to extract content from a DOM node I have something like this: $objDom = new DOMDocument(); @$objDom->loadHTML($strHeader); echo $objDom->getElementsByTagName('head')->item(0)->c14n(); The code is fine but the tags appear as well. I know I can replace them after but is there a domElement or another method to get this content without the head tags? Update: Maybe simplexml or xpath have a better solution for this ? A: echo $objDom->getElementsByTagName('head')->item(0)->nodeValue Edit: Try http://www.php.net/manual/en/class.domelement.php#101243 A: Use innerHTML like this: echo $objDom->getElementsByTagName('head')->item(0)->innerHTML; See the documentation here: https://developer.mozilla.org/en/DOM/element.innerHTML
{ "language": "en", "url": "https://stackoverflow.com/questions/7551006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AS3 Fastest way to merge multiple arrays I'm trying to write a function where I can specify any amount of array, and the return value will be an array containing the contents of all of the specified arrays. I've done this, but it seems like a really slow and ugly way of doing it: var ar1:Array = [1,2,3,4,5,6,7,8,9]; var ar2:Array = ['a','b','c','d','e','f','g','h']; function merge(...multi):Array { var out:String = ""; for each(var i:Array in multi) { out += i.join(','); } return out.split(','); } trace(merge(ar1, ar2)); Is there an inbuilt and more efficient / nice way of achieving this? The result does not need to be in the same order as the input - completely unsorted is fine. A: I don't know if this method is faster than using loops, but it is a (fancy) quick way to merge 2 arrays. (and it works in Javascript and Actionscript) var arr1:Array = [1,2,3,4,5] var arr2:Array = [6,7,8,9,10] arr1.push.apply(this, arr2); // merge // arr1.push.call(this, arr2); // don't use this. see comment below trace(arr1) // 1,2,3,4,5,6,7,8,9,10 A: You can use concat. If the parameters specify an array, the elements of that array are concatenated. var ar1:Array = [1,2,3,4,5,6,7,8,9]; var ar2:Array = ['a','b','c','d','e','f','g','h']; var ar3:Array = ['i','j','k','l']; var ar4 = ar1.concat(ar2, ar3); // or: ar1.concat(ar2).concat(ar3); To make a single array out of a 2 dimensional array you can use this function: private function flatten(arrays:Array):Array { var result:Array = []; for(var i:int=0;i<arrays.length;i++){ result = result.concat(arrays[i]); } return result; } // call var ar4 = [ar1, ar2, ar3]; var ar5 = flatten(ar4); You can also use varargs to merge multiple arrays: private function merge(...arrays):Array { var result:Array = []; for(var i:int=0;i<arrays.length;i++){ result = result.concat(arrays[i]); } return result; } // call var ar5 = merge(ar1, ar2, ar3); A: function merge(...multi):Array { var res:Array = []; for each(var i:Array in multi) { res = res.concat(i); } return res; } Didnt try it, but something like this would help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7551008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: iOS Using HTML links to fetch data I'm creating an interactive book for learning languages. It has reading, quiz and some simple game. The content of each chapter is an HTML file. The book allows the user to learn about 300 words that exist in the text. Earch word was enclosed in a link like this: < a href="word">word< /a> when the user touch the link, a modal view appears with the translation and information about that word. This is the code I'm using to get the link: - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { // currentWord is the word in the link self.currentWord = [[request URL] lastPathComponent]; // okToCatchLinks is a BOOL that I use to avoid showing the modalview when the page // is loaded for the first time. if (okToCatchLinks){ NSLog(@"Ok to catch links!"); WordViewController *viewController = [[WordViewController alloc] initWithNibName:@"WordViewController" bundle:nil] // I did my homework creating the delegate protocol to dismiss the modal view. viewController.delegate = self; // This is a label in the modalview showing the word in the HTML link. viewController.labelTitle = self.currentWord; // Create a Navigation controller to add the "DONE" dismiss button UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController]; navController.modalPresentationStyle = UIModalPresentationFormSheet; navController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; // show the navigation controller modally [self presentModalViewController:navController animated:YES]; // Clean up resources [navController release]; [viewController release]; } okToCatchLinks = YES; return YES; } With this code I will get the selected word in a string variable. Then I search that word in the DB using CoreData. The HTML is UTF-8 encoded. I have to be able to search for that word in different languages. So if the user click on the word (日本語) or (résumé) I have to be able to find it in the DB. For the data store I converted an CSV file to a .sqlite file. I wonder if there is a better way to do this. Personally I don't like to use < a href=""> to get the link, but I couldn't find any other way to get the current word in a link. Also performing the search of that word in the DB is not clean, because I'm not using any UID for each row. I just compare the string holding the word with the words in the corresponding column of the DB. Is there a more efficient way to do this? To resume: Having a list of words, mark those words in the HTML so the user can touch and retrieve information about that word from a DB. A: Some observations: UIDs: As long as your words are unique, you can use that column as the primary key without using a separate UID. Actually, Core Data will create one for you anyway, so you can use objectWithID to retrieve your word. HTML Links: Your solution with UIWebView, HTML files and links seems feasible to me. However, you could of course also use a UITextView and handle the selections programmatically, working with NSRange. That would perhaps be more complicated, but also more "native". Delegate: You only need a delegate if you want to pass information back to the view that first presented the model view controller (too much homework! ;-)). Just dismiss it from within with [self dismissModalViewControllerAnimated:YES];
{ "language": "en", "url": "https://stackoverflow.com/questions/7551011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's the meaning of tmax of the control parameter in optim of R? I'm new to R and data mining/ machine learning. I'm trying to understand the use of optim with SANN method. I found the documentation of the parameter tmax as follows: tmax is the number of function evaluations at each temperature for the "SANN" method. Defaults to 10. What does that suppose to mean ? In my understanding of SANN, you just need to come up with one candidate solution at each temperature. So I don't know what does this tmax means. Does it mean you can try up totmaxcandidates and then choose the best one to proceed ? A: Try making the temperature function listed in the documentation into an R function so you can experiment: tf <- function(t,temp,tmax) temp / log(((t-1) %/% tmax)*tmax + exp(1)) curve(tf(x,temp=10,tmax=10),from=1,to=1000) curve(tf(x,temp=10,tmax=100),col=2,add=TRUE) curve(tf(x,temp=10,tmax=5),col=4,add=TRUE) (Bottom line: yes, tmax keeps the temperature fixed at a specified temperature for longer. You don't choose the best option from each temperature -- rather, at each step you pick a candidate option and compare it to the previously kept option according to the simulated annealing (Metropolis) rule ...)
{ "language": "en", "url": "https://stackoverflow.com/questions/7551012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to call spring form:checkboxes component in javascript? I am using spring form tags, want to call component in a javascript. A: This is how I solved my problem, var formElements = document.getElementById('form_id'); for (var i = 0; i , formElements .length; i++) { if (formElements [i].type == 'checkbox') { formElements [i].disabled=true; } } A: It's rendered as regular hTML form so using Jquery you can access it as regular HTML form <script type="text/javascript"> $(document).ready(function(){ alert($("#compponentId").val()); }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7551016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }