text
stringlengths
8
267k
meta
dict
Q: Clojure NullPointerException error I'm new in clojure and try to write simple function which get list of numbers and filter only even numbers. I want to do it witout filter or even?, only pure clojure (defn my-even [ilist] (if (= (mod (first ilist) 2) 0) (concat (list (first ilist)) (my-even (rest ilist))) (my-even (rest ilist)) ) ) I try to run it: (my-even '(1,2,3,4,5)) But get error: #<CompilerException java.lang.NullPointerException (NO_SOURCE_FILE:0)> What's wrong? Thank you. A: Your recursive function my-even does not have a base case. What happens when there are no more elements in the list? (first ilist) returns nil and (mod nil 2) throws a NullPointerException. You must somehow test for the empty list. A: As Jonas said, you do not have a base case; in addition to that it is not idiomatic Clojure (or any other Lisp) to put parens on separate lines, also keep the if's predicate on the same line. With destructuring it is a bit more readable: (defn my-even? [coll] (if-let [[first & rest] coll] (if (= (mod first 2) 0) (cons first (my-even? rest)) (my-even? rest)))) A: It's great to see so many people learning Clojure this week :) starting with a fundamental problem like this is a really good start. Hamza and Jonas's answers clearly cover the original question quite well. I would like to offer some unsolicited advice on where to take it from here in the hopes that it will be helpful. Once you have the base recursive form you can turn it into idiomatic Clojure generally by: 1) use tail recursive forms when you can (you already did this) 2) replace direct recursion with the recur call to keep from blowing the stack. (starting with Hamza's working answer) (defn my-even? [coll] (if-let [[first & rest] coll] (if (= (mod first 2) 0) (cons first (my-even? rest)) (recur rest)))) the recur causes the compiler to jump to the start of the stack frame instead of allocating a new one. without this it will blow the stack. 3) in many cases you can eliminate the (defn [] ... (recur)) pattern with a higher order function like map, reduce, filter, for, etc. In this excercise I see you are trying to not use filter or even, so obviously you could write my-filter and my-even and that would be ok ;) 4) extract the divisible parts, (building a list, choosing what to include) into reusable functions and upload any that are generally useful to a clojure contrib project :) 5) think very carefully should you find yourself using (lazy-seq ...) as there is a good chance you are re-inventing the wheel. A: Here is another solution that does not require destructuring, only basic lisp and scheme-like functions. (defn my-even [ilist] (cond (empty? ilist) '() ;; base case (= (mod (first ilist) 2) 0) (cons (first ilist) (my-even (next ilist))) :else (my-even (next ilist))))
{ "language": "en", "url": "https://stackoverflow.com/questions/7584337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Ajax load issue with MVC Pager control We have an MVC pager control on a view, when moving to a new page with the next, previous, or page number, the page loses all of its CSS. The pager ajax loads the view into the div it's sitting in. Here's the view, moving page to page fires the controller action correctly but when the view returns the CSS is gone. Any help is mucho appreciato <%@ Control Language="VB" Inherits="System.Web.Mvc.ViewUserControl(Of PagedList(Of ClarifirePortal.PortalAnnouncement))" %> <%@ Import Namespace="Webdiyer.WebControls.Mvc" %> <script type="text/javascript" > function gotoSearch() { window.location.href = '<%:URL.Action("Search","Home") %>'; } function openDIV(divID) { var ele = document.getElementById(divID); if (ele.style.display == "block") { ele.style.display = "none"; } else { ele.style.display = "block"; } } </script> <br /> <div id="divPortal"> <%If Model IsNot Nothing AndAlso Model.Count > 0 Then%> <br /> <% Using Html.BeginForm("Search", "Home", FormMethod.Post, New With {.id = "PortalForm"})%> <table width="98%"> <tr> <td> <%: ViewData("WebStatus")%><br /><br /> </td> </tr> <tr> <td> <% If ViewData("Enabled") = False Then%> <input type="submit" value="Continue" class="t-button" name="Continue" onclick="gotoSearch(); return false;" /> <% End If%> </td> </tr> <tr> <td> <br /> <br /> <table width="100%" style="border: 2px solid #4675bb;"> <tr> <td> Announcements </td> </tr> <% For Each oAnnouncement As ClarifirePortal.PortalAnnouncement In Model%> <tr> <td align="left" style="width: 500px;"> <a href='void();' onclick='openDIV(<%:oAnnouncement.contentID %>); return false;' class="eMasonLink"> <%: oAnnouncement.DatePosted & "-" & oAnnouncement.Title%></a><br /> <%: oAnnouncement.ShortDescription%> </td> </tr> <%Next%> <tr> <td colspan="1"> <%:Html.AjaxPager(Model, "LoadStatus", "Home", New PagerOptions() With {.PageIndexParameterName = "portalPage", .ShowDisabledPagerItems = False, .AlwaysShowFirstLastPageNumber = True}, New AjaxOptions With {.UpdateTargetId = "divPortal"})%> </td> </tr> </table> </td> </tr> </table> <%End Using%> <%Else %> <br /> <% Using Html.BeginForm()%> ... <%End Using%> <%End If%> </div> A: It was necessary to add a script reference in my view to the unobtrusive ajax file, that fixed it
{ "language": "en", "url": "https://stackoverflow.com/questions/7584338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: on click/completion of select drop down list, show more select drop downs Using JQuery I want the user to select an item from a drop down list and when he completes it, another one appears. There should be a total of 4 drop down lists. JQuery <script> $("select: nth-child(1)").click(function () { $("select: nth-child(2)").show(); }); $("select: nth-child(2)").click(function () { $("select: nth-child(3)").show(); }); $("select: nth-child(3)").click(function () { $("select: nth-child(4)").show(); }); </script> html: <form> <div id="one"> <select> <option value="1">a</option> <option value="2">b</option> </select> </div> <div id="two"> <select> <option value="3">c</option> <option value="4">d</option> </select> </div> <div id="three"> <select> <option value="5">e</option> <option value="6">f</option> </select> </div> <div id="four"> <select> <option value="7">g</option> <option value="8">h</option> </select> </div> </form> A: I have modified your js and css slightly: Show the first select on document.ready() Show the next select on selection of the current one - $(document).ready(function(){ $("select").eq(0).show(); }); $('select').change(function(){ $('select').eq($(this).index('select') + 1).show(); }); An example of this code execution: JSFiddle
{ "language": "en", "url": "https://stackoverflow.com/questions/7584339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Will throwing a WCF Fault in a IsTerminating=true method still close the channel I have a WCF service that is using SessionMode.Required for state. I have a method that will terminal the channel if called (IsTerminating=true). However I only want to terminate if certain conditions are met. If I throw a fault will the channel still close? If so, what is the best way to handle this scenario. A: Yes, the channel is closed after any reply is sent, regardless of whether it was a fault or not. It seems you only have two options to deal with this: * *Don't mark the operation IsTerminating (since it is not Terminating - according to the .Net meaning) and instead create an alternative terminal operation. *Catch all exceptions to prevent the fault being thrown. However, you may then need to come up with an alternative mechanism to communicate faults back to the client.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to make single function here used two time In this code : if (!parms.script) { // no script... load filename execscript(parms, function (data){ var text={'result':'success', 'response':data }; if(typeof(data)!='object') { try { text.response=JSON.parse(text.response); } catch(e) { text={'result':'success','response':data}; } } responsehttp.end(JSON.stringify(text)); }); } else { //parameterised input will replace in script if(query.paraminput!=undefined) { var paraminput=qs.parse(query.paraminput); parms=merge_options(parms, paraminput); } execscript(parms, function (data){ var text={'result':'success', 'response':data }; if(typeof(data)!='object') { try { text.response=JSON.parse(text.response); } catch(e) { text={'result':'success','response':data}; } } responsehttp.end(JSON.stringify(text)); }); } in execscript callback it is called two times , i want to make a single function for executing both call back in if and else . how can i achieve this . i tried making seperate function but responsehttp undefinded error camed. A: The problem is (I suspect) is that you had your common function declared outside the context of your http response handler and, therefore, responsehttp wasn't defined. Instead create it as a closure function inside your outer function's scope: function someCallbackYouDontShowInYourQuestion(req, responsehttp) { // Declare your callback as a closure inside this function, so it // captures responsehttp state function callback(data) { var text={'result':'success', 'response':data }; if(typeof(data)!='object') { try { text.response=JSON.parse(text.response); } catch(e) { text={'result':'success','response':data}; } } responsehttp.end(JSON.stringify(text)); } if (!parms.script) { // no script... load filename execscript(parms, callback); } else { //parameterised input will replace in script if(query.paraminput!=undefined) { var paraminput=qs.parse(query.paraminput); parms=merge_options(parms, paraminput); } execscript(parms, callback); } } A: callback = function (data){ var text={'result':'success', 'response':data }; if(typeof(data)!='object') { try { text.response=JSON.parse(text.response); } catch(e) { text={'result':'success','response':data}; } } responsehttp.end(JSON.stringify(text)); } execscript(parms, callback);
{ "language": "en", "url": "https://stackoverflow.com/questions/7584343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using JQuery to get VH1's "Pop Up Video" effect? I am hoping someone can help me recreate the "VH1 Pop Up video" effect, where the entire bubble scales, and has the Easing effect at the end. I have a list with some display:none DIVs hidden in each item of a list. I was hoping that when user clicks on each list item the hidden DIV would grow and bounce like the first example below. The problem with the first example is that the elements within the requested DIV (in this case: .bubble) don't scale along with the rest of the object, like the second example if I do this: $(this).children(".bubble").show(1000, "easeOutBack"); my bubble grows with a nice easeOutBack, but sub elements within .bubble don't scale (might there be a way to specify "scale this element AND its children"? if I do this: $(this).children(".bubble").effect("scale", {origin:['middle','bottom'], from:{width:0,height:0}, percent: 100, direction: 'horizontal' }, 1000); the bubble and its contents scale nicely, but I don't know how to add the Easing effect. I then tried this: $(this).children(".bubble").show('scale', { percent: 100 }, 1000, "easeOutBack" ); but still no easing. Any help would be much appreciated. A: From a quick jsFiddle, it looks like you can add the easing property to your options object. http://jsfiddle.net/bstakes/3RNSS/ $(this).children(".bubble").effect("scale", { origin:['middle','bottom'], from:{width:0,height:0}, percent: 100, direction: 'horizontal', easing : "easeOutBack" // added easing }, 1000); A: How about chaining the scale effect you already have? Go to 120 percent, then back to 100, doing the second effect much faster. $(this).children(".bubble").effect("scale", {origin:['middle','bottom'], from: {width:0,height:0}, percent: 120, direction: 'horizontal' }, 1000) .effect("scale", {origin:['middle','bottom'], from: {width:0,height:0}, percent: 100, direction: 'horizontal' }, 200);
{ "language": "en", "url": "https://stackoverflow.com/questions/7584344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to detect in a running C++/Qt application if underlying Windows is a 32 or 64 bit version? Possible Duplicate: Detect whether current Windows version is 32 bit or 64 bit Correct way to check if Windows is 64 bit or not, on runtime? (C++) I found some questions on the topic, but not exactly what I need. I'm developing a C++/Qt application that is completely cross-platform except for some precompiled .exe's the app has to run. (Only Windows is relevant to the question). I have 32 and 64 bits Windows versions of these executables. I know that one option would be to package two versions of the whole app, but the change in the code would be so minimal that I'd like to think of other alternatives. So, is there a way to detect at runtime, using C++/Qt features, whether the underlying Windows is a 32 or a 64 bits version? Thanks! A: No, but you can call WINAPI functions to tell you this. Call GetNativeSystemInfo(). If you're running x64, SYSTEM_INFO::wProcessorArchitecture will be PROCESSOR_ARCHITECTURE_AMD64. If 32 x86 bit it will be PROCESSOR_ARCHITECTURE_INTEL
{ "language": "en", "url": "https://stackoverflow.com/questions/7584346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: To extract all the files to a folder before starting installation * *We are creating a setup. In that we want to extract all files to a folder and then we want to install it one after the other. Is there any way to carry this out? *During Installation we want to list the steps to be executed, to the end users, like listed during SQL installation. And highlight the process presently carried out. At present we are using Windows installer's Form design which skips from one form to other for each step carried without displaying the steps going to carry. Thanks, Parameswari A: The file extraction and installation is handled automatically by Windows Installer for MSI packages. You don't need to do anything special. Regarding the installation steps, this is usually done through a custom UI. It's not supported by Visual Studio, but other setup authoring tools offer multiple UI themes that may suit your needs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# Duplicate Data Problem I am having problems with duplicate data being inserted in to the database, am I passing a wrong parameter in the IEnumerable<Location>? It doesn't bring up any errors when I debug the app. IEnumerable<Location> locations = context.Locations.Where(l => l.FacebookID == facebookID); if (locations.Count() == 0) { Location newLocation = new Location(); newLocation.FacebookID = locationID; newLocation.Description = locationValue; IGeoCoder geoCoder = new GoogleGeoCoder(GoogleAPIKey); Address[] addresses = geoCoder.GeoCode(locationValue); if (addresses.Length > 0) { // Let's assume the first one is good enough Address address = addresses[0]; newLocation.Latitude= address.Coordinates.Latitude.ToString(); newLocation.Longitude = address.Coordinates.Longitude.ToString(); // Use location.Latitude and location.Longitude } context.Locations.AddObject(newLocation); context.SaveChanges(); } A: I am guessing you did not mean to do this: newLocation.FacebookID = locationID; But rather this: newLocation.FacebookID = facebookID; Basically you are creating multiple records, with the same facebookId, as you actually used the locationID instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Omniauth not updating OAuth token secret on log in I'm using Omniauth to authenticate users with Twitter and Facebook, going by the "standard" tutorial on the topic (Ryan Bates' screencast, although I'm using Authlogic, not Devise). I can log in using Twitter, but can't handle authenticated requests back because my Twitter access token secret has been changed on Twitter's end, but is not being updated on my application's end. I've tried deleting the authentication, but it just saves the old one for some reason. authentications_controller.rb def create omniauth = request.env['omniauth.auth'] authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid']) if authentication # User is already registered with application flash[:notice] = 'Signed in successfully.' sign_in_and_redirect(authentication.user) elsif current_user # User is signed in but has not already authenticated with this social network current_user.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid'], :token => (omniauth['credentials']['token'] rescue nil), :secret => (omniauth['credentials']['secret'] rescue nil)) current_user.apply_omniauth(omniauth) current_user.save flash[:notice] = 'Authentication successful.' redirect_to root_url else # User is new to this application @user = User.new @user.apply_omniauth(omniauth) if @user.save flash[:notice] = 'User created and signed in successfully.' sign_in_and_redirect(@user) else session[:omniauth] = omniauth.except('extra') redirect_to new_user_path end end end user.rb def apply_omniauth(omniauth) self.email = "foo@example.com" self.login = omniauth['user_info']['nickname'] if login.blank? authentications.build(:provider => omniauth['provider'], :uid => omniauth['uid'], :token => omniauth['credentials']['token'], :secret => omniauth['credentials']['secret']) end Any ideas? Rails 3.0.6 and Ruby 1.8.7 A: Steve, you can try the following: if authentication # Make sure we have the latest authentication token for user if omniauth['credentials']['token'] && omniauth['credentials']['token'] != authentication.token # puts "Found Invalid token" authentication.update_attribute(:token, omniauth['credentials']['token']) end flash[:notice] = "Signed in successfully" sign_in_and_redirect(:user, authentication.user) elsif ... This should basically update the user's access token every time an already registered user tries to login and when a token mismatch occurs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: SQL ANSI joins and the order of tables in it The following query is automatically translated from the "old" syntax to ANSI syntax and gives an error: select * from ods_trf_pnb_stuf_lijst_adrsrt2 lst join ods_stg_pnb_stuf_pers_adr pas on (pas.soort_adres = lst.soort_adres) right outer join ods_stg_pnb_stuf_pers_nat nat on (prs.id = nat.prs_id) <<<prs.id invalid identifier join ods_stg_pnb_stuf_adr adr on (adr.id = pas.adr_id) join ods_stg_pnb_stuf_np prs on (prs.id = pas.prs_id) I guess this is because table prs is referenced before it has been declared. Moving the prs join up in the query solves the problem: select * from ods_trf_pnb_stuf_lijst_adrsrt2 lst join ods_stg_pnb_stuf_pers_adr pas on (pas.soort_adres = lst.soort_adres) join ods_stg_pnb_stuf_np prs <<< this first on (prs.id = pas.prs_id) right outer join ods_stg_pnb_stuf_pers_nat nat on (prs.id = nat.prs_id) <<< now prs.id is known join ods_stg_pnb_stuf_adr adr on (adr.id = pas.adr_id) where lst.persoonssoort = 'PERSOON' and pas.einddatumrelatie is null Is there a way to write this query so that the order is less restrictive, still using the ANSI syntax? A: You simply cannot reference a table unless it has been in the join list earlier. That is normal and expected behavior. Why is this a problem? A: If the broken query was generated by a tool from the old non-ANSI syntax, the tools is generated broken code. However, using ANSI-style joins should yield the same result regardless of the order of tables in the from clause. That is select * from t1 join t2 on t2.id = t1.id left join t3 on t3.id = t1.id will give you the same results (albeit a different ordering of columns in the result set) as select * from t1 left join t3 on t3.id = t1.id join t2 on t2.id = t1.id Note that the from clause can't be reordered in such a way as to break the dependencies implied by the join criteria. However, you may also, restate/refactor the from clause so as to express the query in a different way that will yield the same result set. For instance, the above query is equivalent to select * from t3 right join t1 on t1.id = t3.id join t2 on t2.id = t1.id A: A normal ("INNER") JOIN SELECT ... FROM a JOIN b ON (a.x = b.y) is equivalent to a SELECT with two tables and an appropiate WHERE clause SELECT ... FROM a, b WHERE a.x = b.y For left/right/outer joins, you are still handicapped by "the asymmetric" join syntax. A: I think the original SQL code should be something looks like this, select * from ods_trf_pnb_stuf_lijst_adrsrt2 lst , ods_stg_pnb_stuf_pers_adr pas , ods_stg_pnb_stuf_pers_nat nat , ods_stg_pnb_stuf_adr adr , ods_stg_pnb_stuf_np prs where pas.soort_adres = lst.soort_adres and prs.id(+) = nat.prs_id and adr.id = pas.adr_id and prs.id = pas.prs_id and lst.persoonssoort = 'PERSOON' and pas.einddatumrelatie is null ods_stg_pnb_stuf_np prs is at the end of from clause which is valid in Oracle proprietary joins, But when convert this to ANSI SQL syntax, table prs should be joined first before it was referenced. This is a common mistake that people made when convert Oracle proprietary joins to ANSI SQL syntax. There are some other issues when convert Oracle proprietary joins to ANSI SQL syntax: * *additional join condition was missing. *condition in where clause was broken after moving some conditions to join clause. If your colleague need to rewrite Oracle proprietary joins to ANSI SQL syntax, demos(both in java and C#) listed in this article should be helpful.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery UI Modal Dialog should be fixed on scroll Is there any possibility to fix the modal window for jQuery UI, so when the user is using the scroller on the right side, the side behind scrolls, but the modal window is staying fix? A: Create a css class with the fixed position: .fixed-dialog{ position: fixed; top: 50px; left: 50px; } Then append the class as part of the options when you create the dialog: $( ".selector" ).dialog({ dialogClass: 'fixed-dialog' }); Here is a working Example: http://jsfiddle.net/3hrSv/ The example is not too flashy because I couldn't get jsfiddle to style the dialog. If you would like to center the dialog in the middle of the screen try setting top:50%; left:50%; in your css as suggested by: http://css-tricks.com/320-quick-css-trick-how-to-center-an-object-exactly-in-the-center/ A: Or to apply the CSS when you create it: $("#Modal").dialog({ autoOpen: false, width: 500, height: 'auto', position: [50, 150], create: function (event) { $(event.target).parent().css({ 'position': 'fixed', "left": 50, "top": 150 }); } }); A: If you want all of your dialogs to have this behavior, you can modify your jquery.ui.dialog.css file. Change: .ui-dialog { position: absolute; padding: .2em; width: 300px; overflow: hidden; } To: .ui-dialog { position: fixed; padding: .2em; width: 300px; overflow: hidden; } or, if you want to preserve the original file, just add the line: div.ui-dialog {position:fixed;} to one of your css files referenced by the page, or the style block on the page. A: This is an old question, but I found that James' answer (to revise JQuery's div.ui-dialog to position:fixed) provided one-half of the answer to this question. The other half is this: Be sure that the height of the parent element is 100%. In my case, the body is the parent to my dialogs, so I have this line: <body style='height: 100%; min-height: 100%;'> That, plus James' suggestion to add this to my CSS file: div.ui-dialog {position:fixed;} ... finally got my dialogs to appear at the center of the browser window and stay there while I scroll. Hope this helps future googlers who may pass through here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: Loading any persistent workflow containing delay activity when it is a runnable instance in the store We are trying to load and resume workflows which have a delay. I have seen the Microsoft sample of Absolute Delay for this using store.WaitForEvents and LoadRunnableInstance to load the workflow. However here the workflow is already known. In our case we want to have an event waiting for the store.WaitForEvents after every say 5 seconds to check if there is a runnable instance and if so only load and run that /those particular instances. Is there a way I could know which workflow instance is ready. We are maintaing the workflow id and the xaml associated to it in our database, so if we could know the workflow instance id we could get the xaml mapped to it, create the workflow and then do a LOadRunnableInstance on it. Any help would be greatly appreciated. Microsoft sample (Absolute Delay) public void Run(){ wfHostTypeName = XName.Get("Version" + Guid.NewGuid().ToString(), typeof(WorkflowWithDelay).FullName); this.instanceStore = SetupSqlpersistenceStore(); this.instanceHandle = CreateInstanceStoreOwnerHandle(instanceStore, wfHostTypeName); WorkflowApplication wfApp = CreateWorkflowApp(); wfApp.Run(); while (true) { this.waitHandler.WaitOne(); if (completed) { break; } WaitForRunnableInstance(this.instanceHandle); wfApp = CreateWorkflowApp(); try { wfApp.LoadRunnableInstance(); waitHandler.Reset(); wfApp.Run(); } catch (InstanceNotReadyException) { Console.WriteLine("Handled expected InstanceNotReadyException, retrying..."); } } Console.WriteLine("workflow completed."); } public void WaitForRunnableInstance(InstanceHandle handle) { var events=instanceStore.WaitForEvents(handle, TimeSpan.MaxValue); bool foundRunnable = false; foreach (var persistenceEvent in events) { if (persistenceEvent.Equals(HasRunnableWorkflowEvent.Value)) { foundRunnable = true; break; } } if (!foundRunnable) { Console.WriteLine("no runnable instance"); } } Thanks Anamika A: I had a similar problem with durable delay activities and WorkflowApplicationHost. Ended up creating my own 'Delay' activity that worked essentially the same way as the one out of the box, (takes an arg that describes when to resume the workflow, and then bookmarks itself). Instead of saving delay info in the SqlInstanceStore though, my Delay Activity created a record in a seperate db. (similar to the one you are using to track the Workflow Ids and Xaml). I then wrote a simple service that polled that DB for expired delays and initiated a resume of the necessary workflow. Oh, and the Delay activity deleted it's record from that DB on bookmark resume. HTH A: I'd suggest having a separate SqlPersistenceStore for each workflow definition you're hosting.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584367", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Awk - unterminated regex I am writing a shell script which needs to pull values out of a text file which looks like this: app.full.name /warfilelocation/ warfilename My shell script will be iterating over a list of application names and pulling out either the location or name using AWK. I have tested doing this on the command line using the following: awk "\$1 ~/app.full.name/ { print $2 }" applications.txt which returns what I would expect however when i put this in a shell script I start having issues. I have a function that looks like this: function get_location() { local application=$1 awk "\$1 ~/^$application/ { print \$2 }" applications.txt } But when i call this function i get the following error: awk: $1 ~/^app.full.name awk: ^ unterminated regexp awk: cmd. line:1: app.full.name awk: cmd. line:1: ^ syntax error awk: cmd. line:2: app.full.name/ { print $2 } awk: cmd. line:2: ^ syntax error Does anyone have any ideas what I am doing wrong here. I presume I am not escaping the variable correct but no matter what i try it doesnt seem to work. Thanks in advance A: Use this approach to make awk recognize shell variables: awk -v "v1=$VAR1" -v "v2=$VAR2" '{print v1, v2}' input_file Update $ cat input tinky-winky dipsy laa-laa noo-noo po $ teletubby='po' $ awk -v "regexp=$teletubby" '$0 ~ regexp' input po Note that anything could go into the shell-variable, even a full-blown regexp, e.g ^d.*y. Just make sure to use single-quotes to prevent the shell from doing any expansion. A: The error messages seem to indicate that there is a stray newline at the end of $application, which gives the "line 2" error messages. A: see this: using awk match() function kent$ app=app.ful kent$ echo "app.full.name /warfilelocation/ warfilename"|awk -v a=$app '{if(match($1,a))print $2}' /warfilelocation/ A: It's hard to tell without knowing exactly the value of $application, but it seems like you have a strange character in $application, such as a " or a / or something like that. $ export application=foo/bar $ awk "\$1 ~/^$application/ { print \$1 }" gawk: cmd. line:1: $1 ~/^foo/bar/ { print $1 } gawk: cmd. line:1: ^ parse error I would look at the exact value that you have in $application, and if it contains a /, escape it. One way to do this would be to use: $ export application=`echo foo/bar | sed -e 's;/;\\\\/;g'` $ awk "\$1 ~/^$application/ { print \$1 }"
{ "language": "en", "url": "https://stackoverflow.com/questions/7584371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to create a mesh object in ITK using Python bindings? I am trying to create a Mesh object in Python. I am using the python bindings which are being installed from the following web page. As far as the c++ code is concerned we can do it as follows MeshType::Pointer mesh = MeshType::New(); I am very new to use even ITK. Have no idea how to create it. In the constructor of Mesh in the c++ documentation, it says one necessary argument which is the TPixelType. Unable to locate that as well. Could anybody help me please with this. Thanks A: If I were you I would take a look at the Python bindings that come with ITK 4.0. You can get access to them by turning on the option WRAP_ITK_PYTHON in cmake. Once, you compile ITK with the python bindings turned on you can create 2 mesh types out of the box: import itk meshType2D = itk.Mesh.D2Q.New() meshType3D = itk.Mesh.D3Q.New() alternatively you can explicitly instantiate your classes as follows: import itk meshType2D = itk.Mesh[itk.D, 2, itk.QuadEdgeMeshTraits.D2BBFF] meshType3D = itk.Mesh[itk.D, 3, itk.QuadEdgeMeshTraits.D3BBFF] This will give you 2 and 3 dimensional meshes of double type pixel values with default mesh traits. As far as pixel types in ITK go, these amount to the basic C++ variables types: double, float, unsigned int, etc. These basic types are wrapped in python and can be found in the ITK namespace: itk.D, itk.F, itk.UI, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: placement of facebook like and google + buttons inline? Does anyone have any tricks to aligning these two buttons on a page? By default the iframe version of the facebook like button appears below the google plus button or vice versa. Are there any css tricks to keep them inline? This is my current attempt <div style="float:left;width:100px;"> <!-- Place this tag where you want the +1 button to render --> <g:plusone></g:plusone> <!-- Place this tag after the last plusone tag --> <script type="text/javascript"> (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })(); </script> </div> <div style="float:left;width:auto;"> <iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fmy_site&amp;layout=button_count&amp;show_faces=false&amp;width=350&amp;action=like&amp;font=lucida+grande&amp;colorscheme=light&amp;height=40" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:350px; height:30px;" allowTransparency="true"></iframe> </div> A: Put them in a list - here's what i done (excuse the jsp) <ul class="like-buttons"> <li class="g-plus-one"> <g:plusone count="false"></g:plusone> </li> <li class="twitter-like"> <a href="http://twitter.com/share" class="twitter-share-button" data-url="<%= url %>" data-count="none">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script> </li> <li class="fb-like"> <iframe src="http://www.facebook.com/plugins/like.php?href=<%= facebookUrl %>&amp;layout=standard&amp;show_faces=false&amp;width=450&amp;action=like&amp;font=arial&amp;colorscheme=dark&amp;height=80" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:350px; height:30px; color:#fff!important;" allowTransparency="true"></iframe> </li> And the css: ul.like-buttons{ float: left; list-style: none; margin: 5px 0 20px 0; padding: 0; width: 100%; } ul.like-buttons li{ display: block; float: left; margin-right: 10px; } li.twitter-like{ margin-top: 2px; } A: Probably parent div width is less than sum of this two iframes width. Your FB iframe has width 350px. But like button is smaller. A: You have to include them in a div wrapper. However, your actual is displaying on the same line for me your code : http://jsfiddle.net/HbYn3/ A: Use the following google plus render source: <div style="margin-top: 11px;"><li class='g-plusone' data-size='tall'/></div></div> You can adjust margin with your requirement. It was my requirement. By Kuwar Dheeraj Srivastava at One Click Lyrics India
{ "language": "en", "url": "https://stackoverflow.com/questions/7584374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Struts Validation Framework not working I am trying to validate a form using struts validation framework, but the validation seems to be getting bypassed. I have all the validations setup in validation.xml. I also have some custom form validations in the form's validate() method which are running fine. I have set the validate="false" in the action mapping and calling the form's validate explicitly from the action's doPerform() I am on Struts 1. Here's some code: Inside the action if(validationPassed(changeForm, mapping, request)){ if( !(changeForm.getResultAction().equals("add")) ) if(!businessValidationsPassed(changeForm, request)) errorFlag = true; } else{ errorFlag = true; } private boolean validationPassed(MultiChangeForm form, ActionMapping mapping, HttpServletRequest request ) { ActionErrors errors = form.validate(mapping, request); if (!errors.isEmpty()) { saveErrors(request, errors); return false; } else return true; } struts-config.xml <action path="/multiController" type="com.multi.action.MultiControllerAction" name="MultiChangeForm" scope="session" input="multiUpdateResult.def" validate="false"> <forward name="success" path="/forward/initProcess/cam/multiUpdateResultDef.do"/> <forward name="failure" path="/forward/initProcess/cam/multiUpdateResultDef.do"/> <forward name="error" path="/forward/initProcess/cam/errorDef.do"/> </action> <plug-in className="org.apache.struts.validator.ValidatorPlugIn"> <set-property property="pathnames" value="/WEB-INF/multi/validator-rules.xml,/WEB-INF/multi/validation.xml"/> </plug-in> form's validate() ActionErrors errors = super.validate(actionMapping, request); // custom validations: running ok Am I missing something over here? Any ideas would be really great. Thanks Sahil A: It seems you mixed validate method and validator framework. For validate method we don't need any validation rules(no need xmls). Simply we can write validate method in formBean class and we can add errors to ActionErrors object. Validator framework(xmls) is used to validate on client side. In jsp we provide rules like mask or intRange, FloatRange , email validation.. A: When validation of the form fails, you are sent to the input page specified in the <action> tag, so I don't know why you are calling the validate method manually. Anyways.... what I suspect is that your MultiChangeForm form is extending ActionForm when in fact it should extend ValidatorForm. Are you extending ValidatorForm? A: Found out why validation.xml was getting bypassed. I had put in some comments inside the file. Looking closely at the server console while deploying the app, I found that the server was not able to parse the xml due the above tag. A: The main reason for facing this issue is, validator-rules.xml version doesn't match with the current struts version. when we do upgrade the current struts version , we might have left the validator-rules.xml unmodified. The below link explains the same. http://comments.gmane.org/gmane.comp.jakarta.struts.user/137543 In my case, I am using struts 1.1. But I have downloaded the validator-rules.xml from some external site and used which is not compatible with my struts version. Hence, as a step of solution First, Find the struts.jar used in your application and open the manifest file and find out the Struts version used. Because even in version 1.2 we may have so many variants, we wanna find the exact validator-rules.xml. Secondly, get the relevant validator-rules.xml from downloading the struts in the below mentioned link and use the validator-rules.xml in your application http://archive.apache.org/dist/struts/
{ "language": "en", "url": "https://stackoverflow.com/questions/7584381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android + AM PM in a Time Object? I'm setting a Time Object in Android. How do I set the AM and PM value at creation without relying on 24 hour time? For instance: int hour = 7; // this returns 7am //int hour = 19; this returns 7pm myTime.set(second, minute, hour, day, month, year); Log.i("TIME", "My time is: " + myTime); A: It's not really clear what you're trying to do, but I suspect you want something like: // Assume input of hour12 in range [1, 12] and isPM is a boolean int hour24 = (hour12 % 12) + isPM ? 12 : 0; That's assuming you want an hour of "12" and "AM" to mean midnight. Then use hour24 when setting myTime.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: onerorr callback method does not fire. is an event listener needed? I dynamically create DOM elements based upon the user input using this code (Example 1). I also use php/xhtml to create the same elements on a reload (Example 2). Problem I'm seeing is that my image onerror event only works for the reloaded version. Here I use traditional inline event registration to i_bm_err and it works. However for the javascript version, the onerorr callback method does not fire. My questions: Do I need to add an event Listener? If so, what is the event listener's type? I have tried adding event listeners of type "error" and "onerror", but this did not work. This makes me think that maybe adding and evernt listener is not the issue. Example 1 function o3(a) { return document.createElement(a); } var b=o3('a'); b.innerHTML=c[1].value; b.href=c[2].value; b.name="a1"; b.className="b"; b.target="_blank"; var e=o3('img'); e.className="c"; e.name="bo_im"; e.src=b.href+'favicon.ico'; e.onerror=function(e){e.src='http://www.archemarks.com/favicon1.ico';}; Example 2 PHP / XHTML function bookmarks() { $email = $_SESSION['email']; $query_return = database::query("SELECT * FROM bo WHERE email='$email' ORDER BY name ASC"); while ($ass_array = mysqli_fetch_assoc($query_return)) { $fav=$this->fav($ass_array['url']); echo "<img name=\"bo_im\" class=\"c\" src=\"$fav\"/ onerror=\"i_bm_err(this)\"><a target=\"_blank\" name = \"a1\" class = \"b\" href = \"$ass_array[url]\">$ass_array[name]</a>"; } } Javascript function i_bm_err(a) { a.src='http://www.archemarks.com/favicon1.ico'; } Research: MDN - element.addEventListener In the example above, the value of this within modifyText() when called from the click event is a reference to the table 't'. This is in contrast to the behavior that occurs if the handler is added in the HTML source: A: As @Paul Grime mentioned, you need to attach all your events (error, load etc) prior to setting the src attribute.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Proper Way to Float Elements I have the following HTML: <fieldset> <legend>Details</legend> <div class="form-section first"> <div class="abc"> <div class="editor-label"> <label for .../> </div> <div class="editor-field"> <input type="text" ... /> </div> </div> <div class="def"> ... </div> <div class="ghi"> ... </div> </div> <div class="form-section"> </div> <div class="form-section last"> </div> </fieldset> I have a fieldset that is wrapping all of my form elements. The fieldset contains multiple form sections, which basically hold one "row" of content. The divs in the form sections I want to float to the left: ||||||| ||||||| ||||||| <-- first form section, 3 floated elements ||||||| ||||||||||| <-- second form section, 2 floated elements What is the proper way to float these elements so that: 1) The second form section occurs on its own line. 2) The second form section can apply a top margin. I can't seem to get it right. I need the solution to work in IE7. I tried putting a clear: both on the form-section element but it didn't seem to work right. All 5 elements occurred on the same line instead of 2 separate lines. ** EDIT ** I can somewhat get this to work. My issue is the following: When I float the elements within a container, they essentially have 0 height. This messes up any containers that come after it if they want to apply a top margin. A: for the row of three try: <div style="clear:both; width:100%;"> <div style="float: left;"></div> <div style="float: left;"></div> <div style="float: right;"></div> </div> <div style="clear:both; width:100%; height:10px;"></div> <div style="clear:both; width:100%;"> <div style="float: left;"></div> <div style="float: left;"></div> </div> That should get you the desired output. A: <fieldset> <legend>Details</legend> <div id="section 1"> <span style="height: 500px;">1</span> <span style="height: 500px;">2</span> <span style="height: 500px;">3</span> </div> <div id="section 2" style="margin-top: 50px;"> <span>4</span> <span>5</span> </div> </fieldset>
{ "language": "en", "url": "https://stackoverflow.com/questions/7584396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How should I implement this credit system? I am creating a website where members of the family can book a vacation in the family's sea cottage. Each member is assigned 40 credits each year. A member must have enough credit points to book a vacation. (this credit system makes sure every member has equal opportunity to stay at the cottage) However, not all weeks require the same amount of credit points, and last minute bookings require no credit points. My question is: how should I store the credit points in the database? What is most efficient? Per day/per couple of days/per week? And how do I efficiently check how much credit points are needed for a given date range using mysql? BTW: I am using the Zend Framework and I am familiar with the code etc., I just need some conceptual advice ;) A: I don't know if I understand right the problematic here but : * *You need to store in a "users" table the amount of credit remaining for each user. *You need to have another table with fields like "start period", "end period", "duration", "amount of points needed" *In the duration field, it could be an enum with values like "day", "week", "last_minute". Then the logic will be in your PHP code, but with that, you'll be able to have the right number of credits needed whenever the user wants to use the cottage. A: If I understand your case correctly, I think I would store something like: * *number of remaining credits per user *a default number of credits per day *number of days before that counts as "last minute" *periods of deviating credit cost, with (start date, end date, cost per day) Then, I would calculate the cost to book dynamically from this information whenever the user needs to make a booking. The last minute booking rule can be seen as a special deviating period where start date is now, end date is now+"number of days" and cost is zero. I assume that no-one will book the cottage for a shorter duration than one day. If they will, I would change the use of "day" above to whatever unit of time would be sensible. Just my thoughts. :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7584398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: List Box enable/disable one column Access 2007: Is it possible to enable/disable one column in a List Box on a form. For example: Say you have 2 columns A,B - If Me.A = title Then Me.B.Enabled = True Else Me.B.Enabled = False. If so, where would it go? On Got Focus, On Click?? Thanks A: I'm not sure what you mean by disable, but you can hide a column by adjusting the ColumnWidth. So if you wanted to hide column2: Me.MyListBox.ColumnWidths = (1 in;0;1 in) And to hide column1: Me.MyListBox.ColumnWidths = (0;1 in;1 in)
{ "language": "en", "url": "https://stackoverflow.com/questions/7584399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Overriding a method with an object Why is it possible to override an empty-parentheses method with an object? trait A { def meth = {} def meth_p() = {} } class B extends A { object meth_p } // compiles Overriding the method without parentheses does not compile: class B1 extends A { object meth } // does not compile Neither do any of the following combinations work (without override modifier): class BX extends A { // of course, each declaration should get its own class def meth = {} def meth_p() = {} def meth() = {} def meth_p = {} val meth = {} val meth_p = {} // ... } Is this documented and useful behaviour? I’ve just run into a very subtle bug because of this accidental override. A: This sure as hell looks like a bug. If you do this the other way around it just gets weirder. class A { object m { override def toString = "object m" } } class B extends A { def m() = "def m" } scala> (new A).m res0: object A#m = object m scala> (new A).m() // doesn't compile scala> (new B).m <console>:10: error: ambiguous reference to overloaded definition, both method m in class B of type ()java.lang.String and object m in class A of type object B#m match expected type ? (new B).m ^ scala> (new B).m() java.lang.VerifyError: class B overrides final method m.()LA$m$; at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClassCond(Unknown Source) at java.lang.ClassLoader.defineClass(Unknown Source) at java.lang.ClassLoader.defineClass(Unknown Source) at scala.tools.nsc.interpreter.AbstractFileClassLoader.findClass(AbstractFileClassLoader.scala:52) at java.lang.ClassLoader.loadClass(Unknown Source) at scala.tools.nsc.interpreter.AbstractFileClassLoader.scala$tools$nsc$util$ScalaClassLoader$$super$loadClass(AbstractFileClassLoader.scala:17) at scala.tools.nsc.util.ScalaClassLoader$class.loadClass(ScalaClassLoader.scala:50) at scala.tools.nsc.interpreter.AbstractFileClassLoader.loadClass(AbstractFileClassLoader.scala:17) at java.lang.ClassLoader.loadClass(Unknown Source) at .<init>(<console>:10) at .<clinit>(<console>) at .<init>(<console>:11) at .<clinit>(<console>) at $print(<console>) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.call(IMain.scala:704) at scala.tools.nsc.interpreter.IMain$Request$$anonfun$14.apply(IMain.scala:920) at scala.tools.nsc.interpreter.Line$$anonfun$1.apply$mcV$sp(Line.scala:43) at scala.tools.nsc.io.package$$anon$2.run(package.scala:25) at java.lang.Thread.run(Unknown Source)
{ "language": "en", "url": "https://stackoverflow.com/questions/7584400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Need some changes to the below code This was the code suggested by Reafidy a programmer on stackoverflow. it was working as intended. Need a better optimized code? Now I have to Re-use the same code for a large file. Sub Delete_Duplicate_Codes() ThisWorkbook.Worksheets("Data").Activate Dim vData As Variant, vArray As Variant Dim lRow As Long With ActiveSheet.Range("A3", Cells(Rows.Count, "A").End(xlUp)).Offset(, 52) .FormulaR1C1 = "=RC[-24]&RC[-23]&RC[-19]&RC[-18]&RC[-17]&RC[-16]" ' I know what these meant concatenate A,B,F,G,H,I and I have changed it accordingly vData = .Resize(, 1).Value End With ReDim vArray(1 To UBound(vData, 1), 0) With CreateObject("Scripting.Dictionary") For lRow = 1 To UBound(vData, 1) If Not .exists(vData(lRow, 1)) Then vArray(lRow, 0) = "x" .Add vData(lRow, 1), Nothing End If Next lRow End With Application.ScreenUpdating = False With ActiveSheet .Range("BB3").Resize(UBound(vArray, 1)) = vArray On Error Resume Next .Range("BA34274", .Cells(Rows.Count, "BA").End(xlUp)).Offset(, 1).SpecialCells(xlCellTypeBlanks).EntireRow.Delete On Error GoTo 0 .Columns(52).Resize(, 2).ClearContents ' throwing an error End With Application.ScreenUpdating = True End Sub He helped me and we have used y and z columns for these purpose Now I have to use BA and BB columns for these task. I dont understand where to make the changes. I replaced z with "BB" and y with "BA" columns but its throwing an error application-defined or object-defined at these line .Columns(52).Resize(, 2).ClearContents where I have to make changes and the top 1 and 2 rows are used for headers. The cells starts from 3rd row. Please help me with these code. any help is greatly appreciated I have changed .FormulaR1C1 = "=RC[-24]&RC[-23]&RC[-19]&RC[-18]&RC[-17]&RC[-16]" these to .FormulaR1C1 = "=RC[-52]&RC[-51]&RC[-47]&RC[-46]&RC[-45]&RC[-44]" these I guess it must be right A: You almost had it, it should be: .Columns(53).Resize(, 2).ClearContents But I don't see how it could have thrown an error. Also if you dont like the R1C1 notation you can just use: With ActiveSheet.Range("A3", Cells(Rows.Count, "A").End(xlUp)).Offset(, 52) .Formula = "=A3&B3&F3&G3&H3&I3" vData = .Resize(, 1).value End With You should also leave the spaces, it helps with readability. Sub Delete_Duplicate_Codes() Dim vData As Variant, vArray As Variant Dim lRow As Long With ActiveSheet.Range("A3", Cells(Rows.Count, "A").End(xlUp)).Offset(, 52) .Formula = "=A3&B3&F3&G3&H3&I3" vData = .Resize(, 1).value End With ReDim vArray(1 To UBound(vData, 1), 0) With CreateObject("Scripting.Dictionary") For lRow = 1 To UBound(vData, 1) If Not .exists(vData(lRow, 1)) Then vArray(lRow, 0) = "x" .Add vData(lRow, 1), Nothing End If Next lRow End With Application.ScreenUpdating = False With ActiveSheet .Range("BB3").Resize(UBound(vArray, 1)) = vArray On Error Resume Next .Range("BA34274", .Cells(Rows.Count, "BA").End(xlUp)).Offset(, 1).SpecialCells(xlCellTypeBlanks).EntireRow.Delete On Error GoTo 0 .Columns(53).Resize(, 2).ClearContents End With Application.ScreenUpdating = True End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/7584407", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can you conditionally display links in jqgrid? I have a jqgrid and I have a custom formatter for it which formats and displays links as per my needs. This does work fine but I have a problem. I want to display links conditionally. How can I do that? For Eg. If the person is Admin then show him all links like edit, delete etc (these links map to action methods in controller). But if the person is NonAdmin user then only show View link and hide all other links. I just need a general strategy of how to accomplish this. One of the strategy would be I add a boolean field to my json data which would signify whether the link of edit, delete etc is to be shown or not. Then in my formatter and I can look at the row data and decide whether to return show link or not. Is there any better way of doing this? A: You suggestion with additional data in the JSON response from the server sounds OK. It's important to mention, that you should prevent data editing for non-admins in any way. The hiding or not creating the link for editing is not a security feature, but mostly GUI improvement to prevent actions which are not permitted. If you has some technical problems with the implementation you should include the corresponding code in your question. If you use additionally form editing, then the demo from the answer or another demo from the another answer could be also helpful for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Find overlapping time ranges I'm surprised this hasn't come up yet. In T-SQL, I need to find the intervals (defined by startDateTime and endDateTime) that overlap with daily interval (say 9am-5pm). For example, with table: CREATE TABLE [dbo].[Interval]( [startDateTime] [datetime] NOT NULL, [endDateTime] [datetime] NOT NULL ) Solution would be the procedure that returns only overlapping intervals: CREATE PROCEDURE FindIntervals -- Add the parameters for the stored procedure here @from varchar(5) = '9:00', @to varchar(5) = '17:00' AS BEGIN select * from Interval where ... END GO EDIT: Example intervals: * *Sep 7 2011 8:00 AM - Sep 7 2011 8:30 PM *Sep 7 2011 11:00 AM - Sep 7 2011 1:00 PM *Sep 7 2011 1:00 PM - Sep 7 2011 6:00 PM *Sep 9 2011 8:00 AM - Sep 9 2011 8:30 PM *Sep 9 2011 11:00 AM - Sep 9 2011 1:00 PM *Sep 9 2011 1:00 PM - Sep 9 2011 6:00 PM So, for given interval "nine to five", 2, 3, 5 and 6 should be returned, as they overlap the given input. But, * *Sep 9 2011 8:00 AM - Sep 10 2011 8:30 PM also fits, because it includes entire day. Please, I need help with matching string and datetime values in T-SQL, not abstract "less then"/"greater then" solutions. A: declare @Interval table ( startDateTime datetime, endDateTime datetime ) insert into @Interval values ('2011-09-07T08:00:00', '2011-09-07T08:30:00'), ('2011-09-07T11:00:00', '2011-09-07T13:00:00'), ('2011-09-07T13:00:00', '2011-09-07T18:00:00'), ('2011-09-09T08:00:00', '2011-09-09T08:30:00'), ('2011-09-09T11:00:00', '2011-09-09T13:00:00'), ('2011-09-09T13:00:00', '2011-09-09T18:00:00'), ('2011-09-09T08:00:00', '2011-09-10T08:30:00') declare @from varchar(5) = '09:00' declare @to varchar(5) = '17:00' ;with L(MinDate, MaxDate) as ( select dateadd(day, datediff(day, 0, min(startDateTime)), 0), dateadd(day, datediff(day, 0, max(endDateTime)), 0) from @Interval ), D(fromTime, endTime) as ( select dateadd(day, Number.number, L.MinDate)+cast(@from as datetime), dateadd(day, Number.number, L.MinDate)+cast(@to as datetime) from L inner join master..spt_values as Number on Number.number <= datediff(day, L.MinDate, L.MaxDate) where Number.type = 'P' ) select I.startDateTime, I.endDateTime from @Interval as I where exists (select * from D where I.startDateTime < D.endTime and I.endDateTime > D.fromTime) Result: startDateTime endDateTime ----------------------- ----------------------- 2011-09-07 11:00:00.000 2011-09-07 13:00:00.000 2011-09-07 13:00:00.000 2011-09-07 18:00:00.000 2011-09-09 11:00:00.000 2011-09-09 13:00:00.000 2011-09-09 13:00:00.000 2011-09-09 18:00:00.000 2011-09-09 08:00:00.000 2011-09-10 08:30:00.000 If you expect to have a date range of more than 2048 days you need to replace master..spt_values with a numbers table. Make sure the numbers table starts with 0. SQL Server 2008 version ;with L(MinDate, MaxDate) as ( select cast(min(startDateTime) as date), cast(max(endDateTime) as date) from @Interval ), D(fromTime, endTime) as ( select dateadd(day, Number.number, L.MinDate)+cast(@from as datetime), dateadd(day, Number.number, L.MinDate)+cast(@to as datetime) from L inner join master..spt_values as Number on Number.number <= datediff(day, L.MinDate, L.MaxDate) where Number.type = 'P' ) select I.startDateTime, I.endDateTime from @Interval as I where exists (select * from D where I.startDateTime < D.endTime and I.endDateTime > D.fromTime)
{ "language": "en", "url": "https://stackoverflow.com/questions/7584414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Convert ODT to single XML file I know that standards define two versions of ODT file: - one is a archive of different files, i.e. meta.xml, content.xml etc, - second is one big XML file with all the data. (I know above from http://en.wikipedia.org/wiki/OpenDocument_technical_specification#Document_Representation) The latter version is better for processing, but unfortunately is not produced by OpenOffice. The question is: Do you know any filter, converter, or anything what would help me transform ODT file in archive version into single XML file? The best would be a Java class. A: Both Open Office and Libre Office does can produce ODT files in the "one big XML" format. They are called "Flat ODT" files. Open an ODT file and use "Save as…". From there you can change the file format to "Flat ODT". A: I solved the case by producing XSLT stylesheet that transforms ODT source files into one XML file "more or less" compatible with the standard. Below is the code. <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"> <xsl:param name="meta.file" select="'meta.xml'" /> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()" /> </xsl:copy> </xsl:template> <xsl:template match="office:document-content"> <office:document> <xsl:copy-of select="@*" /> <xsl:variable name="meta" select="document($meta.file)/office:document-meta/office:meta" /> <xsl:copy-of select="$meta" /> <xsl:apply-templates /> </office:document> </xsl:template> </xsl:stylesheet>
{ "language": "en", "url": "https://stackoverflow.com/questions/7584416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Do Arrays take up space even without values in them in .net? I have a program in VB.net that uses a 3D array: Private gridList(10, 900, 900) As GridElement Now, I just used a Memory Profiler on it (because my application is having some major leak issues or something) and apparently, this array (containing at the moment of testing 0-30 elements at one time) is using 94% of the memory currently in use by my application. Even when it is empty it takes up huge amounts of memory. My only assumption is that even empty arrays take up space! This puts a major blow into my plans! My Question: Is there any alternative to this that allows me to still have the same abilities to map i.g. I've been using it like this: Dim cGE as GridElement = gridList(3, 5, 7) but doesn't hog up so much memory for things that aren't using memory? Thanks! A: Do Arrays take up space even without values in them in .net? No. But your array has values in it. And hence takes up space. To avoid keeping a lot of elements in memory when you only access a few of all the possible elements, you need to use a so-called sparse array. In .NET, this is easiest implemented via a Dictionary, where the key in your case would be a three-element structure*, and the value would be a GridElement. * If you’re using an up-to-date version of .NET, then you can model this via a Tuple(Of Integer, Integer, Integer)
{ "language": "en", "url": "https://stackoverflow.com/questions/7584417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Iterate the classes defined in a module imported dynamically I have a module from a child package that is imported dynamically; how can I iterate over the classes that it contains? I have been importing the module and listing the names like this: package = current_module.__name__ package = package[:package.rindex(".")] # get the package package = "%s.sub.%s"%(package,name) # make the name of the child print "(loading package %s)"%package module = __import__(package) # this succeeds for name,obj in inspect.getmembers(module): print name,type(obj) This only prints module attributes and not the class types that the module defines: __builtins__ <type 'dict'> __doc__ <type 'NoneType'> __file__ <type 'str'> __name__ <type 'str'> __package__ <type 'NoneType'> __path__ <type 'list'> imported_package <type 'module'> It seems that my classes are not in the __dict__ unless the fromlist is non-empty! The values in the from-list don't seem to be validated though; [""] seems to work just fine, and suddenly the classes show up! Can anyone explain why this is? (Standard ubuntu python 2.7.1+ (r271:86832) A: Example: to create a dict that maps the names to the classes: dict([(name, cls) for name, cls in mod.__dict__.items() if isinstance(cls, type)]) where mod is the loaded module A: If you define __all__ in the module you are importing, which defines which symbols will be exported, you can iterate by selecting these items specifically. map(module.__dict__.get, module.__all__) A: Method 1: import inspect import mymodule for name, obj in inspect.getmembers(mymodule): if inspect.isclass(obj): do stuff... Method 2: desired_classes = [obj for name, obj in somemodule.__dict__.items() if isinstance(obj, DesiredType)] Method 3: Inside the module you want to iterate on: File: mymodule.py class Dog: VOICE = 'haou' class Cat: VOICE = 'meew' class ImNotIncluded: VOICE = 'what a shame' __all__ = ['Dog', 'Cat'] >>> from mymodule import * >>> Dog.VOICE 'haou' >>> Cat.VOICE 'meew' >>> ImNotIncluded.VOICE Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'ImNotIncluded' is not defined Now to iterate you do: >>> for cls in map(mymodule.__dict__.get, mymodule.__all__): cls ... <class 'mymodule.Dog'> <class 'mymodule.Cat'>
{ "language": "en", "url": "https://stackoverflow.com/questions/7584418", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: Pausing/resuming an upload request using Webdav on Android I'm planing to build a Webdav client for Android and I'm not sure what's the best library to use. Basically I would like to allow the user to pause and resume an upload request to a Webdav server. Is there any way to do that? I' ve looked around and apparently I've got the choice between these libraries: * *Sardine *JackRabbit *Jakarta slide Sardine looks like the most stable solution for now. I've seen nothing about pausing and resuming a request though. A: I'm the original author of Sardine. I created it because Slide and Jackrabbit were too difficult to use and not well supported. The intention of Sardine was always to be run on servers, not mobile devices. Also, the design has always been around making a request and getting a response. Nothing about pausing. I have also heard that there may be issues getting it working on Android (dependencies). That said, I hate to say it, but I think you are pretty much on your own. If you'd like to join the Sardine project to contribute patches to it to make it compatible with Android and support features like pausing, I'd love to have you (assuming you write good code. hehe). A: As far as i remember sardine is not fully compatible with android (some missing dependencies) About your question, i don't think is pause/resume is a part of parsing lib (which sardine i basically is). This behavior is related more with HttpClient. However i think this is even too low abstraction level for it. The best solution would be to implement such mechanism by hand. It's not pretty, and is connected with AIO sockets
{ "language": "en", "url": "https://stackoverflow.com/questions/7584421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Running BAT/CMD file with accented characters in it I have a Windows batch file which has an instruction to execute an EXE file in a location whose path contains accented characters. Following are the contents of the batch file. @echo off C:\español\jre\bin\java.exe -version C:\español\jre\bin\java.exe - This path exists and is proper. I can run this command directly on cmd.exe. But when I run the command from a bat/cmd file it fails saying "The system cannot find the path specified" One way to fix this is by setting code page to 1252 (that works for me). But I'm afraid we'd have to set code pages for any non-English locale and figuring out which code page to use is pretty difficult. Is there an alternative approach to fix this problem? Maybe a command-line option or something else? A: Since you have @echo off you can't see what your batch is sending to the command prompt. Reproducing your problem with that off it seems like the ñ character gets misinterpreted since the output I see is: C:\espa±ol\jre\bin\java -version The system cannot find the path specified. I was able to get it to work by echoing the command into the batch file from the command prompt, i.e. echo C:\español\jre\bin\java.exe -version>>test.bat This seems to translate the character into whatever the command prompt is looking for, though I've only tested it with English locale set so I don't know if it'll work in all situations for you. Also, if you open the batch in a text editor like notepad it looks wrong (C:\espa¤ol\jre\bin\java.exe) A: Use Alt + 0164 for ¤ instead of Alt + 164 ñ in a batch file... It will look odd, but your script should run. A: You can use Visual Studio Code and it will let you select the encoding you want to use. Lower right corner, you select the encoding and will display option "save with encoding". Select DOS and will save the accented chars. A: Another way of doing this, in Windows, is by using wordpad.exe: * *Run wordpad.exe *Write your script as you usually do, with accents *Choose Save as > Other formats *Choose to save it as Text document MS-DOS (*.txt) *Change the file extension from .txt to .bat A: I had the same problem, and this answer solved it. Basically you have to wrap your script with a bunch of commands to change your terminal codepage, and then to restore it. @echo off for /f "tokens=2 delims=:." %%x in ('chcp') do set cp=%%x chcp 1252>nul :: your stuff here :: chcp %cp%>nul Worked like a charm! A: I'm using Notepad++ and it has an option to change "character sets", OEM-US did the trick. ;) A: I also had the same problem. I was trying to create a simple XCOPY batch file to copy a spreadsheet from one folder to another. Its name had the "é" character in it, and it refused to copy. Even trying to use Katalin's and Metalcoder's suggestions didn't work on my neolithic Windows XP machine. Then I suddenly thought: Why not keep things as simple as possible (as I am myself extremely simple-minded when it comes to computers) and just substitute, in the batch file code, "é" with the wildcard character "?". And guess what? It worked!
{ "language": "en", "url": "https://stackoverflow.com/questions/7584423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: Retrieving Family information from Facebook using FQL? Hi I am trying to pull information from Facebook using FQL. I was able to gather info on my friends and the profile users likes however I cant seem to get a list of family information, the code I currently have is below. I was wondering if anyone could help and let me know what I am doing wrong, any help would be great appreciated, thanks <h1>My Family</h1> <?php $user = $facebook->getUser(); $friends = $facebook->api('/me/friends'); $fql_query = array( 'method' => 'fql.query', 'query' => "SELECT profile_id, name, relationship FROM family WHERE profile_id={$user}"); $family = $facebook->api($fql_query); $fam = count($family); echo $fam; for ($i=0;$i<$fam;$i++){ echo "<p>".$family[$i]['name']." ".$family[$i]['relationship']." from ".$family[$i]['sex']." </p>"; } ?> A: You need friends_relationships extended permission to get access to the user's family. https://developers.facebook.com/docs/reference/api/permissions/ also "sex" you have there seems unrelated A: You need user_relationships permission to view the user's family info.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Traceback for regular expression Lets say i have a regular expression: match = re.search(pattern, content) if not match: raise Exception, 'regex traceback' # i want to throw here the regex matching process. If regular expression fails to match then i want to throw in exception Its working and where it fails to match the regular expression pattern, at what stage etc. Is it possible even to achieve the desired functionality? A: I've used Kodos (http://kodos.sourceforge.net/about.html) in the past to perform RegEx debugging. It's not the ideal solution since you want something for run-time, but it may be helpful to you. A: if you need to test the re, you can probably use groups followed by * ... as in ( sometext)* use this along w/ your desired regex, and then you should be able to pluck out your failure locations and then leverage the following, as stated on python.org pos The value of pos which was passed to the search() or match() method of the RegexObject. This is the index into the string at which the RE engine started looking for a match. endpos The value of endpos which was passed to the search() or match() method of the > RegexObject. This is the index into the string beyond which the RE engine will not go. lastindex The integer index of the last matched capturing group, or None if no group was matched at all. For example, the expressions (a)b, ((a)(b)), and ((ab)) will have lastindex == 1 if applied to the string 'ab', while the expression (a)(b) will have lastindex == 2, if applied to the same string. lastgroup The name of the last matched capturing group, or None if the group didn’t have a name, or if no group was matched at all. re The regular expression object whose match() or search() method produced this MatchObject instance. string The string passed to match() or search(). so for a very simple example >>> m1 = re.compile(r'the real thing') >>> m2 = re.compile(r'(the)* (real)* (thing)*') >>> if not m1.search(mytextvar): >>> res = m2.search(mytextvar) >>> print res.lastgroup >>> #raise my exception A: I have something that helps me to debug complex regex patterns among my codes. Does this help you ? : import re li = ('ksjdhfqsd\n' '5 12478 abdefgcd ocean__12 ty--\t\t ghtr789\n' 'qfgqrgqrg', '6 48788 bcfgdebc atlantic__7899 %fg#\t\t ghtu12340\n', '2 47890 bbcedefg arctic__124 **juyf\t\t ghtr89877', '9 54879 bbdecddf antarctic__13 18:13pomodoro\t\t ghtr6798', 'ksjdhfqsd\n' '5 12478 abdefgcd ocean__1247101247887 ty--\t\t ghtr789\n' 'qfgqrgqrg', '6 48788 bcfgdebc atlantic__7899 %fg#\t\t ghtu12940\n', '25 47890 bbcedefg arctic__124 **juyf\t\t ghtr89877', '9 54879 bbdeYddf antarctic__13 18:13pomodoro\t\t ghtr6798') tupleRE = ('^\d', ' ', '\d{5}', ' ', '[abcdefghi]+', ' ', '(?=[a-z\d_ ]{14} [^ ]+\t\t ght)', '[a-z]+', '__', '[\d]+', ' +', '[^\t]+', '\t\t', ' ', 'ght', '(r[5-9]+|u[0-4]+)', '$') def REtest(ch, tuplRE, flags = re.MULTILINE): for n in xrange(len(tupleRE)): regx = re.compile(''.join(tupleRE[:n+1]), flags) testmatch = regx.search(ch) if not testmatch: print '\n -*- tupleRE :\n' print '\n'.join(str(i).zfill(2)+' '+repr(u) for i,u in enumerate(tupleRE[:n])) print ' --------------------------------' # tupleRE doesn't works because of element n print str(n).zfill(2)+' '+repr(tupleRE[n])\ +" doesn't match anymore from this ligne "\ +str(n)+' of tupleRE' print '\n'.join(str(n+1+j).zfill(2)+' '+repr(u) for j,u in enumerate(tupleRE[n+1: min(n+2,len(tupleRE))])) for i in xrange(n): match = re.search(''.join(tupleRE[:n-i]),ch, flags) if match: break matching_portion = match.group() matching_li = '\n'.join(map(repr, matching_portion.splitlines(True)[-5:])) fin_matching_portion = match.end() print ('\n\n -*- Part of the tested string which is concerned :\n\n' '######### matching_portion ########\n'+matching_li + '\n' '##### end of matching_portion #####\n' '-----------------------------------\n' '######## unmatching_portion #######') print '\n'.join(map(repr, ch[fin_matching_portion: fin_matching_portion+300].splitlines(True)) ) break else: print '\n SUCCES . The regex integrally matches.' for x in li: print ' -*- Analyzed string :\n%r' % x REtest(x,tupleRE) print '\nmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwm' result -*- Analyzed string : 'ksjdhfqsd\n5 12478 abdefgcd ocean__12 ty--\t\t ghtr789\nqfgqrgqrg' SUCCESS . The regex integrally matches. mwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwm -*- Analyzed string : '6 48788 bcfgdebc atlantic__7899 %fg#\t\t ghtu12340\n' SUCCESS . The regex integrally matches. mwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwm -*- Analyzed string : '2 47890 bbcedefg arctic__124 **juyf\t\t ghtr89877' SUCCESS . The regex integrally matches. mwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwm -*- Analyzed string : '9 54879 bbdecddf antarctic__13 18:13pomodoro\t\t ghtr6798' SUCCESS . The regex integrally matches. mwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwm -*- Analyzed string : 'ksjdhfqsd\n5 12478 abdefgcd ocean__1247101247887 ty--\t\t ghtr789\nqfgqrgqrg' -*- tupleRE : 00 '^\\d' 01 ' ' 02 '\\d{5}' 03 ' ' 04 '[abcdefghi]+' 05 ' ' -------------------------------- 06 '(?=[a-z\\d_ ]{14} [^ ]+\t\t ght)' doesn't match anymore from this ligne 6 of tupleRE 07 '[a-z]+' -*- Part of the tested string which is concerned : ######### matching_portion ######## '5 12478 abdefgcd ' ##### end of matching_portion ##### ----------------------------------- ######## unmatching_portion ####### 'ocean__1247101247887 ty--\t\t ghtr789\n' 'qfgqrgqrg' mwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwm -*- Analyzed string : '6 48788 bcfgdebc atlantic__7899 %fg#\t\t ghtu12940\n' -*- tupleRE : 00 '^\\d' 01 ' ' 02 '\\d{5}' 03 ' ' 04 '[abcdefghi]+' 05 ' ' 06 '(?=[a-z\\d_ ]{14} [^ ]+\t\t ght)' 07 '[a-z]+' 08 '__' 09 '[\\d]+' 10 ' +' 11 '[^\t]+' 12 '\t\t' 13 ' ' 14 'ght' 15 '(r[5-9]+|u[0-4]+)' -------------------------------- 16 '$' doesn't match anymore from this ligne 16 of tupleRE -*- Part of the tested string which is concerned : ######### matching_portion ######## '6 48788 bcfgdebc atlantic__7899 %fg#\t\t ghtu12' ##### end of matching_portion ##### ----------------------------------- ######## unmatching_portion ####### '940\n' mwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwm -*- Analyzed string : '25 47890 bbcedefg arctic__124 **juyf\t\t ghtr89877' -*- tupleRE : 00 '^\\d' -------------------------------- 01 ' ' doesn't match anymore from this ligne 1 of tupleRE 02 '\\d{5}' -*- Part of the tested string which is concerned : ######### matching_portion ######## '2' ##### end of matching_portion ##### ----------------------------------- ######## unmatching_portion ####### '5 47890 bbcedefg arctic__124 **juyf\t\t ghtr89877' mwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwm -*- Analyzed string : '9 54879 bbdeYddf antarctic__13 18:13pomodoro\t\t ghtr6798' -*- tupleRE : 00 '^\\d' 01 ' ' 02 '\\d{5}' 03 ' ' 04 '[abcdefghi]+' -------------------------------- 05 ' ' doesn't match anymore from this ligne 5 of tupleRE 06 '(?=[a-z\\d_ ]{14} [^ ]+\t\t ght)' -*- Part of the tested string which is concerned : ######### matching_portion ######## '9 54879 bbde' ##### end of matching_portion ##### ----------------------------------- ######## unmatching_portion ####### 'Yddf antarctic__13 18:13pomodoro\t\t ghtr6798' mwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwm
{ "language": "en", "url": "https://stackoverflow.com/questions/7584435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery hover function not working after showing img i have the code below: the first function shows an alternative image on mouse over using the rel atribute the second function takes a hidden div and shows the content in another place on the same page but when i hover the image the image doesn't change, the hover on the hidden div works, but after moving it on click in other place the hover doesn't work. I think it might be the document ready script because i alter the page after ready but i'm not sure, any advise? thank you $(document).ready(function(){ $(function() { $('img[rel]').hover(function() { $(this).attr('tmp', $(this).attr('src')).attr('src', $(this).attr('rel')).attr('rel', $(this).attr('tmp')).removeAttr('tmp'); }).each(function() { $('<img />').attr('src', $(this).attr('rel')); });; }); $(function(){ $('.id2').one("click",function() { var newPara = $('#test').html(); $('#big_photo').append(newPara); }); }); }); A: i think you should consider using sprites for the image switching, since it's a more elegant solution in my opinion. * *you don't need the rel attribute (which isn't a valid img attribute anyway) *you don't have problems loading the second image since it's all loaded at once also $(document).ready(function(){ and $(function() { is the same and you only need one of them so: $(function() { // all your jQuery code }); would suffice. ok, then for swapping src an rel on hover / out, this should work: $('img[rel]').bind('mouseenter mouseleave',function() { var oldSrc = $(this).attr('src'); $(this).attr('src', $(this).attr('rel')).attr('rel', oldSrc); }); demo: http://jsfiddle.net/P37UX/1/
{ "language": "en", "url": "https://stackoverflow.com/questions/7584439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook SEO with image not loading Possible Duplicate: How does Facebook Sharer select Images? I've got an app recently put online. On my Facebook wall, when I type in the URL to my app. Facebook displays available thumbnails. At the moment it's displaying GoDaddy's thumbnails. I'm guessing its because Facebook is caching the images. So I read somewhere about putting image_src on the <head> element. In Rails 3.1 should it be: <link rel="image_src" href="http://www.site_name.com/assets/logo.png" /> Or: <link rel="image_src" href="/assets/logo.png" /> And is using <link rel="image_src" the right meta tag to show the right thumbnail on Facebook? If so, do I have to wait a few hours until the thumbnail displays on Facebook? EDIT I have: <meta property="og:title" content="<%= yield(:title).present? ? yield(:title) : 'Foobar' %>" /> <meta property="og:type" content="website" /> <meta property="og:url" content="<%= request.url %>" /> <meta property="og:image" content="http://www.foobar.com/assets/logo.png" /> <meta property="og:site_name" content="Foobar" /> The Facebook debug page shows an actual image for og:image. But when I type the site's url on a wall, the thumbnail still doesn't appear A: The best way to supply metadata to Facebook is using Open Graph tags. The main documentation is at https://developers.facebook.com/docs/opengraph/ If you just want to get something set up quickly, use the form at 'Step 2' on the Like Button documentation which will produce a set of meta tags to put in to the <head></head> part of your page
{ "language": "en", "url": "https://stackoverflow.com/questions/7584440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using ruby/nokogiri to transform xml to another xml I've never encountered task of transforming XML from one form to another. I hear that XSLT is just for that, but I don't want to go there. So, using only ruby and nokogiri, how can I: remove all item elements but time from initial XML and also rename element time to HammerTime? Initial XML: ... <item> <time>05.04.2011 9:53:23</time> <iddqd>42</iddqd> <idkfa>woot</idkfa> </item> <item> ... Desired result: ... <item> <HammerTime>05.04.2011 9:53:23</HammerTime> </item> <item> ... I figured out how to put data from XML to array using nokogiri's .xpath, but is there a way to make the desired transformation into another XML without manually having to write something like puts "<HammerTime>#{array['time']}</HammerTime>"? A: Here you go: require 'rubygems' require 'nokogiri' doc = Nokogiri::HTML <<-EOHTML <html> <body> <item> <time>05.04.2011 9:53:23</time> <iddqd>42</iddqd> <idkfa>woot</idkfa> </item> </body> </html> EOHTML hammer = doc.at_css "time" hammer.name = 'hammertime' doc.css("iddqd").remove doc.css("idkfa").remove outfile = File.new("output.html", "w") outfile.puts doc.to_html outfile.close A: What do you mean with into another XML without manually having to write something like puts "<HammerTime>#{array['time']}</HammerTime>"? If you want to transform an XML element into another in a language-independent way, you can use XSLT transformations (or stylesheet). Once you have your XSLT file you can apply it with Nokogiri's Nokogiri::XSLT::Stylesheet#apply_to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Django: how to properly use UserProfile? (Django auth extra information) i finally can make my Django+Auth app works. I add the extra information to the user as the docs say. Now, i've a simple question. When i'm building a model that is related to the user, which user should i relate to? To auth.models.User or to my accounts.UserProfile? An example: I've a model for Product, and the Product belongs to a user. Which would be the best option: class Product(models.Model): user = models.ForeignKey(auth.models.User) or class Product(models.Model): user = models.ForeignKey(accounts.UserProfile) I'm currently using auth.models.User, becouse i can issue a get_profile, but some friend told me that i was wrong. Thank you! A: You're doing the right thing. UserProfile is just an extension of the User model. And logically you're making a relation of a object with an object, not a relation of a object with some extra information. Also, as you mentioned, you can always issue the 'get_profile' to get the extra data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: My Play app is very slow I'm a begginer with PlayFramework and I have a few questions about how to put the server to work properly. I have been reading a few tutorials on how to deploy a Play! app and I decided to use the server that comes with it and lighttpd as reverse proxy. (I want to deploy 2 or 3 apps in the same machine with different domain) My app is just like a youtube with only two pages, list videos and upload video. Nothing else is done with the app. I use mysql server for the database. The machine is a VPS with 1024 RAM with Debian, it does not have swap partition. The URL to the app is proselo.info and it is quite slow. I've made a test with ab and you can see the results below: ab -n 150 http://proselo.info/listar Total transferred: 185250 bytes HTML transferred: 124800 bytes Requests per second: 2.01 [#/sec] (mean) Time per request: 498.539 [ms] (mean) Time per request: 498.539 [ms] (mean, across all concurrent requests) Transfer rate: 2.42 [Kbytes/sec] received Any help will be apreciated Thanks A: It's been long time since I posted this question but the problem was that I really did not put it in production mode. Sorry for the inconvenience, now i0ts much better! A: It doesn't look slow when loading from my browser. What else do you have running on your VPS? It may be that you are hitting some limit in your VPS when doing the test (cpu, ram) and that's the reason of the delays.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Unix: assign variable to command I am trying to assign the path of a file to a variable so I am doing something like: PATH = dirname script.sh However I am getting an error. Can someone assist? Thanks. Sincerely, Eric Anderson A: There can be no spaces between the variable name and the equals sign. Also, I think you meant to run the dirname command, so what you would want is something more like this: PATH=$(dirname script.sh)
{ "language": "en", "url": "https://stackoverflow.com/questions/7584453", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problems installing: mysql2 on Mac OS X Lion + Ruby 3 when i'm under my app over rails. and i do: $ bundle install I retrieve this error: Installing mysql2 (0.2.7) with native extensions /Users/workdreamer/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems/installer.rb:533:in `rescue in block in build_extensions': ERROR: Failed to build gem native extension. (Gem::Installer::ExtensionBuildError) /Users/workdreamer/.rvm/rubies/ruby-1.9.2-p180/bin/ruby extconf.rb --with-mysql-config=/usr/local/mysql-5.5.13-osx10.6-x86_64/bin/mysql_config checking for rb_thread_blocking_region()... yes *** extconf.rb failed *** Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options. Provided configuration options: --with-opt-dir --without-opt-dir --with-opt-include --without-opt-include=${opt-dir}/include --with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog --without-make-prog --srcdir=. --curdir --ruby=/Users/workdreamer/.rvm/rubies/ruby-1.9.2-p180/bin/ruby --with-mysql-config extconf.rb:32:in ``': No such file or directory - /usr/local/mysql-5.5.13-osx10.6-x86_64/bin/mysql_config --cflags (Errno::ENOENT) from extconf.rb:32:in `<main>' Ok, the program is right but because /usr/local/mysql-5.5.13-osx10.6-x86_64/bin/mysql_config doesn't exist. What exist is: $: cd /usr/local/mysql mysql/ mysql-5.5.16-osx10.6-x86/ And if i do: $: gem install mysql2 Building native extensions. This could take a while... Successfully installed mysql2-0.3.7 1 gem installed Installing ri documentation for mysql2-0.3.7... Enclosing class/module 'mMysql2' for class Client not known Building YARD (yri) index for mysql2-0.3.7... Installing RDoc documentation for mysql2-0.3.7... Enclosing class/module 'mMysql2' for class Client not known Apparently it's only warnings. What can i do to fix this for ever? Thank you everybody! A: I've created a symlink ln -s /usr/local/mysql/mysql-5.5.16-osx10.6-x86/ /usr/local/mysql-5.5.13-osx10.6-x86_64 It's not a perfect solution but it works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iPhone trying to use a block animation to simulate a card flip, but nothing happens no animation I'm trying to do a card flip animation...but nothing happens. this is what I do 1. create a container view, to hold the two views to animate from. 2. Create the first view. 3. add it to the container. 4. create the second view 3. start the animation block, beginAnimations 4. call setAnimationTransition put in the view container 5. add the second view to the view container 6. commit the animation, my code // create container view CGRect viewRect = CGRectMake(10, 10, 100, 100); UIView* myView = [[UIView alloc] initWithFrame:viewRect]; // create 2 viues to flip between for animation UIImage *i= [ UIImage imageNamed : @"card1.jpg"]; UIImageView *topCard=[ [UIImageView alloc] initWithImage: i ]; topCard.frame= CGRectMake(0,0,100,100); [myView addSubview:topCard]; [self.view addSubview:myView]; i= [ UIImage imageNamed : @"card2.jpg"]; UIImageView *butCard=[ [UIImageView alloc] initWithImage: i ]; butCard.frame= CGRectMake(0,0,100,100); // set up the animation [UIView beginAnimations:@"Flip Top Card" context:nil]; [UIView setAnimationDuration:1]; [UIView setAnimationRepeatCount:0]; [UIView setAnimationRepeatAutoreverses:NO]; [UIView setAnimationCurve:UIViewAnimationCurveEaseOut ]; [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:myView cache:YES]; [myView addSubview:butCard]; // start the animation [UIView commitAnimations]; -Ted A: If this is iOS 4.0 or later you can do: [UIView transitionWithView:myView duration:0.3f options:UIViewAnimationOptionTransitionFlipFromLeft animations:^(void) { self.topCardIsShown = !self.topCardIsShown; self.topCard.hidden = !self.topCardIsShown; self.butCard.hidden = self.topCardIsShown; } completion:^(BOOL finished) { // nothing }]; This assumes that you have added both card views to the myView and have added a @property(nonatomic, assign) BOOL topCardIsShown; to your class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Nested singular resource, not showing up in rake routes I created a search and replace controller, with just an index action. Since it's meant to go under one of my restful controllers created by a scaffold, i setup the following in the routes file: resources :sites do resource :search_and_replace, only: [:index] end However, it does not appear when I run rake routes. If I switch to resources, it does. But the method name is site_search_and_replace_index. The pluralization of resource doesn't feel right either, since this is not around multiple records in a table. A: The index action doesn't exist in a singular resource. This makes sense if you think of the meaning of the action: index of what, there's only one resource? Use show instead: resources :sites do resource :search_and_replace, only: [:show] end A: Are you sure you want to have search and replace as a resource? There might be other options that are more useful: Adding more restful actions
{ "language": "en", "url": "https://stackoverflow.com/questions/7584460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Hibernate union-subclass (table per concrete class) mapping generator of "increment" very slow? My Hibernate hbm file looks something like this with a mysql DB: <hibernate-mapping> <class name="com.company.common.bo.position.Parent" table="Parents" abstract="true"> <id name="id"> <generator class="increment" /> </id> <property name="date" not-null="true" /> <property name="milliseconds" not-null="true" /> <property name="shares"> <column name="shares" precision="19" scale="6" not-null="true" /> </property> <many-to-one name="ticker" column="tickerID" not-null="true" index="_tickerID_date_milliseconds_idx" /> <many-to-one name="auditTrail" column="auditTrailID" not-null="false" cascade="save-update" lazy="false" fetch="select" /> <union-subclass name="com.company.common.bo.position.SubclassA" table="SubclassAs"> <many-to-one name="account" column="accountID" not-null="true" foreign-key="SubclassA_accountID_fk" /> <many-to-one name="portfolio"> <column name="portfolioID" not-null="true"/> </many-to-one> <many-to-one name="individualTrade"> <column name="individualTradeID" not-null="false"/> </many-to-one> <many-to-one name="positionTransfer" column="positionTransferID" cascade="save-update" not-null="false"/> </union-subclass> <union-subclass name="com.company.common.bo.position.SubclassB" table="SubclassBs"> <many-to-one name="individualTrade"> <column name="individualTradeID" not-null="false" /> </many-to-one> <many-to-one name="account" column="accountID" not-null="true" foreign-key="SubclassBs_accountID_fk"/> <many-to-one name="internalExecution" column="executionID" cascade="save-update" not-null="false" /> </union-subclass> <union-subclass name="com.company.common.bo.position.SubclassC" table="SubclassCs"> </union-subclass> </class> So basically i have an abstract class Parent and 3 subclasses (SubclassA, B, C) that extend it. In the database there are 3 tables (for the 3 subclasses). The id generator is "increment" because the union subclass mapping doesn't allow me to use native. So it looks like with increment, the ID is unique among the 3 tables. When I look at the hibernate sql, it basically finds the max ID from all 3 tables, and uses that as the next ID. But the query it uses seems very inefficient. This is what I see it doing: select max(ids_.id) from ( select id from SubclassAs union select id from SubclassBs union select id from SubclassCs ) ids_ Which takes over 12 seconds to run. Each of those tables has more than a million records each. It's unioning every single ID together and then selecting the max out of that. If i do something like this: select max(ids_.id) from ( select max(id) as id from SubclassAs union select max(id) as id from SubclassBs union select max(id) as id from SubclassCs ) ids_ It is much faster, less than one millisecond, because the inner union only gets the max from each table, and then i select just the max out of those 3 records. Is there a way to tell hibernate to do this instead, or is there a better way of using a generator for the ID across these 3 tables? Thanks A: If increment doesn't satisfy you, you can use some other generator strategy, and, since MySQL doesn't support sequences, the next suitable option is a hilo strategy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java array declaration without hard coding the size How can I initialize an array of objects of a class in another class without hardcoding its size? A: Arrays are fixed in length. I would recommend using a Collection. Here is an article on collections: http://en.wikipedia.org/wiki/Java_collections_framework With these, you can add elements by using an Add() command or something similar. As mentioned in the previous answers, an ArrayList or List are collections. A: Use a List. The size does not need to be declared on creation of the List. The toArray() method will return an array representation of the list. There are multiple implementations you can use but the most popular tends to be ArrayList (though it is best to map the implementation to your particular situation). A: Arrays have a fixed size after creation. The size doesn't need to be known at compile-time, but it does need to be known at creation time. For example: public String[] createArray(int size) { // Not hard-coded, but array is not expandable return new String[size]; } If you want a collection which can grow an shrink over time, look at the various List<E> implementations, such as ArrayList<E>. A: Object[] will always be fixed size. If you need a variable length collection, try ArrayList, LinkedList, or one of the many others. Pick the collection carefully, since they all have different performance aspects. A: For mutable arrays other container objects are used. When using a set of objects, an ArrayList or Vector object is used. You can also store objects with an object key e.g. "Name" = "Ben" instead of [0] = "Ben". Vector v = new Vector(); for(int i = 0; i < 100; i++){ Object o = new Object(); // init object v.addElement(o); } for(int i = 0; i < 100; i++){ Object o = v.elementAt(i); // manipulate object } Now you have an arbritairy list of object of undefined length. Size found by using vector.size() method. java.util package is required and part of J2SE 1.3 and higher. A: As noted elsewhere, an array object has a fixed size. If there's some reason you must use an array, you can use one or both of these techniques: * *Make it the larger than you need, leaving the unused entries null. You may want to keep a "slotsUsed" variable. *When the array gets too small, make a bigger one and copy the contents into it. These are both used inside ArrayList. A: You can create a new array and initialize it like this. String[] strArray = {"Initialize","Array","Like","This"}; If you want an array with a dynamic size I would recommend using an ArrayList. A: If you want an array of primitive instead of objects, you can use Trove4j. Otherwise use an ArrayList, or CopyOnWriteArrayList to wrap an array. There are other List implementations but these do not act like arrays for access time. A: Sometimes it is useful, in case you know an upper bound of the objects your application needs, to declare the size of an array as static final int ARRAY_SIZE = 1000; This goes near the beginning of the class so it can be easily changed. In the main code instantiate the array with Object[] objects = new Object[ARRAY_SIZE]; Also in case the array you want to use has the same size as another array consider using Object[] objects = new Object[other_objects.length];
{ "language": "en", "url": "https://stackoverflow.com/questions/7584467", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: CakePHP 2.0 - Cake was unable to write to File cache I'm using CakePHP 2.0 RC-1. After checking out the project from SVN, the application is starting to complain that it can't write cache files to the tmp/cache directory. Since this is local, I know the directory is writeable and I can CLEARLY see that the directories are even filled with files, so the error is a bit strange. Here are some of the errors I've encountered: _cake_core_ cache was unable to write 'cake_dev_nb' to File cache fopen(c:\cake\app\tmp\cache\models\cake_model_default_media) [function.fopen]: failed to open stream: No error [CORE\Cake\Cache\Engine\FileEngine.php, line 127] No error?! Wth? Now, if I look in the FileEngine file, at line 127 it reads: if (!$handle = fopen($this->_File->getPathName(), 'c')) { return false; } By replacing the "c" with "w", no error is encountered and everything works as it should. But, it should not be necessary to modify the core Cake libraries to work around this problem. Let me repeat that on my other computer this works as intended, without editing the core library. Both use the Windows OS and the read/write rights to the tmp/cache-folder is exactly the same. Edit: Here's a site that experiences the error outputs I'm having locally Example site found by Googling. Not my site: http://www.12h30.net/credit/ Any suggestions? Update: Here is why: This is caused if you have a PHP-version that's too low, before 5.2.6, as outlined by "api55" in the comments. Thanks for the reply. Hope this helps you too. A: Just give the right CHMOD (776 works fine for me) to app/tmp A: Well, in my case, when I checked my app, it hadn't the /tmp folder. Then I created the structure (/tmp/cache/models, /tmp/cache/persistent) and all worked well. This happened to me maybe git ignore empty folders, so they weren't created. A: I had a similar problem, it was because I had chown -R www to the app/tmp directory to get Cake to run "properly" without giving everyone write privileges. Looks like during development the only way to use the console and the web is to give everyone write privileges, or add yourself to the www group perhaps. Easy solution: chmod -R 777 app/tmp or chown -R username app/tmp while using the console and chown -R www app/tmp when using the web A: for windows users with the same error/warning: make sure you run the command prompt in elevated mode ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7584472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: Field values gets reset to blank on seam file upload exception I have jsf-seam application in which I am uploading a file using seam:fileUpload using the code below. Also, I have made a entry of multipart-filter to restrict file size to 1 MB. <s:fileUpload id="offerImage" data="#{myBean.data}" contentType="#myBean.contentType}" fileName="#{myBean.fileName}" fileSize="#{myBean.size}" /> <web:multipart-filter create-temp-files="true" max-request-size="1000000" url-pattern="*.seam"/> Everything is working fine, except when user try to upload a file greater than 1 MB, it throws a exception. I am handling this exception as well in pages.xml. <exception class="org.jboss.seam.web.FileUploadException"> <redirect view-id="/create.xhtml"> <message severity="ERROR">Error while uploading Offer Image, due to size limitation.</message> </redirect> Issue here is: All other fields in create.xhtml(other than upload field) gets blank. User should not fill all the fields again, except the file upload. Is there any way, where in I can redirect the user to same xhtml page with all the values filled by user persists when a seamFileUpload exception occurs. Regards, Rajat A: Are you running this page with components in conversation or page scope? If there is "just" an event scoped component your backingbeans will be initialized on each request and because of that you can have empty fields on the next rendering.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584482", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a way to get the IP address of the client/caller in a Shiro Filter in Grails sorry if this is a dumb question. I have some web service calls that are implemented in Grails controllers and we use the Shiro plugin for security. I want to be able to create a whitelist of IP addresses for certain operations that should only come from our own servers or trusted partners. I am finding the documentation a little spares on this subject. My first thought was to try and implement the whitelist here. I wouldn't be surprised if there is a simpler way to do this. I am a bit of a Shiro newb. Could sure use a copy of Shiro for Dummies! class ShiroSecurityFilters { def filters = { all(uri: "/**") { before = { // Ignore direct views (e.g. the default main index page). if (controllerName in ['foo', 'bar']) { return true } // Access control by convention. accessControl() } } } } A: You should have access to the request object in the Filter and you can call request.getRemoteAddr() to access the IP address.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: User relationships are corrupting my sessions in Symfony2 My users have a number of relationships setup in Doctrine but one in particular seems to be causing me a lot of problems, each user can have a number of memberships and each membership has a membership type. For some reason however when I load those memberships it seems to be nuking my session, I login and get presented with a "Your Account" page as I should do but if I refresh the page I get sent back to the login screen. My sessions are stored in the database so I've been checking them to see what happens and this is what I'm seeing: * *Session starts off empty *I login but make sure I get redirected to a page that doesn't load memberships *Session now contains user object and all info about relationships *I visit "Your Account" which loads memberships, they get displayed correctly. *Session has been nuked and is now as it was in step 1 *I refresh the page and get sent back to the login page I've defined my own user provider and I noticed if I set the membership type on each membership to null in refreshUser it starts working so I'm guessing the session is having trouble with that relationship. I'm really struggling to find a solution to this so any help would be really appreciated. EDIT: Been doing some more experimenting and found if I switch to file sessions everything starts working so it must be related to storing sessions in the database. I made the switch using the guide in the Symfony Cookbook. For reference here are the relevant bits from my config.yml: framework: session: default_locale: %locale% auto_start: true storage_id: session.storage.pdo parameters: pdo.db_options: db_table: session db_id_col: session_id db_data_col: session_value db_time_col: session_time session.storage.pdo: class: Symfony\Component\HttpFoundation\SessionStorage\PdoSessionStorage arguments: [@pdo, %session.storage.options%, %pdo.db_options%] pdo: class: PDO arguments: dsn: "mysql:dbname=%database_name%;host=%database_host%" user: %database_user% password: %database_password% Everything else about them seems fine so maybe it's a bug in PdoSessionStorage A: It might be in you equals method that is too strict. if you do $user === $otherUser; and the object have changed (the relation isnt a collection with proxies anymore) it would return false.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Python print statement “Syntax Error: invalid syntax” Why is Python giving me a syntax error at the simple print statement on line 9? import hashlib, sys m = hashlib.md5() hash = "" hash_file = raw_input("What is the file name in which the hash resides? ") wordlist = raw_input("What is your wordlist? (Enter the file name) ") try: hashdocument = open(hash_file,"r") except IOError: print "Invalid file." # Syntax error: invalid syntax raw_input() sys.exit() else: hash = hashdocument.readline() hash = hash.replace("\n","") The version of Python is: Python 3.2.2 (default, Sep 4 2011, 09:07:29) [MSC v.1500 64 bit (AMD64)] on win 32 A: Use print("use this bracket -sample text") In Python 3 print "Hello world" gives invalid syntax error. To display string content in Python3 have to use this ("Hello world") brackets. A: In Python 3, print is a function, you need to call it like print("hello world").
{ "language": "en", "url": "https://stackoverflow.com/questions/7584489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "57" }
Q: Trigger iScroll 4 on all elements with a certain Class The script iScroll4 is triggered in this manner $(document).ready(function() { var myScroll; myScroll = new iScroll('wrapper'); }); That however assumes there is an element with ID 'wrapper'. I would like to trigger this on all elements with the class name "scrollable". I have seen this done on a plugin for this script. Any ideas how to do it here? A: You can assign a different ID with the same class "scrollable" and ... $(document).ready(function() { //Created an array for adding n iScroll objects var myScroll = new Array(); $('.scrollable').each(function(){ id = $(this).attr('id'); myScroll.push(new iScroll(id)); }); }); A: I've answered that in Mobile Site: Lack of horizontal scrolling on iPhone Using jQuery and iScroll, you could make the following: HTML: <html><head> <title>Test</title> <!-- include jquery and iscroll --> </head><body> <div id="divPretendingIsDeviceScreen" style="max-width:320px;overflow:hidden;"> <h1>Header</h1> Lorem ipsum dolor sit amet. <br/><br/> <h2>Another header</h2> text text:<br/> <br/> <div class="divToBeScrolled"> div to be scrolled yay <br />div to be scrolled yay <br />div to be scrolled yay <br />div to be scrolled yay <br />div to be scrolled yay <br />div to be scrolled yay <br />div to be scrolled yay <br /> </div> <h2>Another header</h2> text text:<br/> <br/> <div class="divToBeScrolled"> div to be scrolled yay <br />div to be scrolled yay <br />div to be scrolled yay <br />div to be scrolled yay <br />div to be scrolled yay <br />div to be scrolled yay <br />div to be scrolled yay <br /> </div> <h2>Another header</h2> text text:<br/> <br/> <div class="divToBeScrolled"> div to be scrolled yay <br />div to be scrolled yay <br />div to be scrolled yay <br />div to be scrolled yay <br />div to be scrolled yay <br />div to be scrolled yay <br />div to be scrolled yay <br /> </div> <h2>Another header</h2> text text:<br/> <br/> <div class="divToBeScrolled"> div to be scrolled yay <br />div to be scrolled yay <br />div to be scrolled yay <br />div to be scrolled yay <br />div to be scrolled yay <br />div to be scrolled yay <br />div to be scrolled yay <br /> </div> <br/> <br/> Lorem ipsum dolor sit amet. </div> </body></html> CSS: <style type="text/css"> .scrollerType { overflow:hidden; max-height:200px; /* put max height you want the scroller div to have, normally less than the device's window size, like 200px or so so.*/ } div.divToBeScrolled { overflow:scroll; display:block; } </style> JS/jQUERY: <script charset="utf-8" type="text/javascript"> var snippetName = new Array(); //creates a new array to make the var names for iscroll var selfId = new Array(); //creates a new array to make the names for the scrollers $('.syntaxhighlighter').each(function(index) { //for each '.syntaxhighlighter' and 'index' as counter selfId[index] = 'scrollerId'+index; //creating a new id name for the container $(this).wrap('<div id='+selfId[index]+' class="scrollerType" />'); //wrapping each '.syntaxhighlighter' with the container var timeout = setTimeout(function(){ //yes, timeout. This to support Android mostly snippetName[index] = new iScroll(selfId[index], { //initializing multiple iscroll's each with an index and targeting the selfId //here you declare various options - see "Passing parameters to the iScroll" at iScroll page //this is the best set, i think snap: false, momentum: true, hScrollbar: false, vScrollbar: false, hScroll: true, vScroll: true, desktopCompatibility:true }); //end new iScroll },100); //100ms just bc 0ms or 1ms might not be enough }); //end .each </script> This is the test-case ( http://portableideas.net/myRepo/trunk/stackoverflow/www/questions_7869572.html ) for the other question i've pointed out. A: This is a 2 years old conversation to the time i am writting, still this conversation will stay here as long as StackOverflow still alive. Through search engine i was linked to this conversation as i had similar issue. However, none of these solve my issue. In my own idea building on Franz idea you could easily acheive a perfect and simple solution like this: var contentToScroll; var idNum=1; $('.scrollable').each(function(){ //e.g <li class="scrollable" id="conT1"> Contents</li> //<li class="scrollable" id="conT2"> Contents</li> e.t.c $(this).attr("id", 'conT'+idNum);//assign ids here var id = $(this).attr('id'); idNum++; contentToScroll=new IScroll('#'+id,{scrollbars: true}); }); Dynamically assign IDs to the expected scollable elements individually and tell the iScroll5 to make them scrollabile. This may help someone
{ "language": "en", "url": "https://stackoverflow.com/questions/7584491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get a set of values as a list when grouped by a pair of columns I have a datatable with below values id Name date 1 a 5/3/2011 1 a 6/4/2011 I want to retrieve the values with a list of associated dates for each id/name pair. A: I would suggest you create a class which encapsulates all of that data, and then you can create a List<T> of the appropriate type. You'd create an instance of your new class per entry in the DataTable. If you use a strongly-typed dataset you could use the generated DataRow type instead, if you wanted. (It's not clear what you mean by "store in a list as single entry" - the whole table, or one entry per row?) A: It's difficult to answer with out the context of the usage. Is this going to be used right a way, communicated to other parts of the system. The below assumes that it's not coomunicated to other parts of the system var list = (from e in DataTable.Rows.AsEnumerable() select new { id = e["id"], Name = e["Name"], data = e["data"] }).ToList() A: Create a class that maps onto your table. You can use EntityFramework, LINQ to SQL, nHibernate or a custom ORM to retrieve data from the table as these objects. Select the objects and use the LINQ grouping operator to either create anonymous objects (or another class with the list of dates). public class Foo { public int ID { get; set; } public sring Name { get; set; } public DateTime Date { get; set; } public class Bar { public int ID { get; set; } public string Name { get; set; } public List<DateTime> Dates { get; set; } } public class FooDataContext : DbContext { IDbSet<Foo> Foos { get; set; } } using (var context = new FooDataContext()) { List<Bar> bars = context.Foos .GroupBy( f => new { f.ID, f.Name } ) .Select( g => new Bar { ID = g.Key.ID, Name = g.Key.Name, Dates = g.Select( f => f.Date ) }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7584498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I write HTML in a Word document? How can I write HTML in a Word document using C#? I made a class to help writing a document using System; using System.IO; using Microsoft.Office.Interop.Word; namespace WordExporter { public class WordApplication : IDisposable { private Application application; private Document document; private string path; private bool editing; public WordApplication(string path) { this.path = path; this.editing = File.Exists(path); application = new Application(); if (editing) { document = application.Documents.Open(path, ReadOnly: false, Visible: false); } else { document = application.Documents.Add(Visible: false); } document.Activate(); } public void WriteHeader(string text) { foreach (Section wordSection in document.Sections) { var header = wordSection.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; header.Font.ColorIndex = WdColorIndex.wdDarkRed; header.Font.Size = 20; header.Text = text; } } public void WriteFooter(string text) { foreach (Section wordSection in document.Sections) { var footer = wordSection.Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range; footer.Font.ColorIndex = WdColorIndex.wdDarkRed; footer.Font.Size = 20; footer.Text = text; } } public void Save() { if (editing) { application.Documents.Save(true); } else { document.SaveAs(path); } } #region IDisposable Members public void Dispose() { ((_Document)document).Close(SaveChanges: true); ((_Application)application).Quit(SaveChanges: true); } #endregion } class Program { static void Main(string[] args) { using (var doc = new WordApplication(Directory.GetCurrentDirectory() + "\\test.docx")) { doc.WriteHeader("<h1>Header text</h1>"); doc.WriteFooter("<h1>Footer text</h1>"); doc.Save(); } } } } In the WriteHeader I write some text on the document header, but I need to use HTML. How can I say the contents are HTML? I will also need to insert HTML in the document content... A: I can just insert the html file on the section I want using: range.InsertFile("file.html");
{ "language": "en", "url": "https://stackoverflow.com/questions/7584503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: RequestThrottling issue in Amazon MWS API I am testing API Sample of Amazon MWS API in C# for submit feeds however after setting AWS Secret key , access key etc. in code i am getting error of RequestThrottled , so there is details what is that but could not find any code sample how to resolved that. I would like to upload feed.xml to amazon seller account <?xml version="1.0" encoding="iso-8859-1"?> <AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amzn-envelope.xsd"> <Header> <DocumentVersion>1.01</DocumentVersion> <MerchantIdentifier>M_EXAMPLE_123456</MerchantIdentifier> </Header> <MessageType>Product</MessageType> <PurgeAndReplace>true</PurgeAndReplace> <Message> <MessageID>1</MessageID> <OperationType>Insert</OperationType> <Product> <SKU>56789</SKU> <StandardProductID> <Type>ASIN</Type> <Value>B0EXAMPLEG</Value> </StandardProductID> <ProductTaxCode>A_GEN_NOTAX</ProductTaxCode> <DescriptionData> <Title>Example Product Title</Title> <Brand>Example Product Brand</Brand> <Description>This is an example product description.</Description> <BulletPoint>Example Bullet Point 1</BulletPoint> <BulletPoint>Example Bullet Point 2</BulletPoint> <MSRP currency="USD">25.19</MSRP> <Manufacturer>Example Product Manufacturer</Manufacturer> <ItemType>example-item-type</ItemType> </DescriptionData> <ProductData> <Health> <ProductType> <HealthMisc> <Ingredients>Example Ingredients</Ingredients> <Directions>Example Directions</Directions> </HealthMisc> </ProductType> </Health> </ProductData> </Product> </Message> </AmazonEnvelope> Error getting as per below Caught Exception: Request from SubmitFeed:AKIAJI4PSK4HXY6UCNMA;A2DNAGZJ1EWQLW is throttled. Response Status Code: ServiceUnavailable Error Code: RequestThrottled Error Type: Sender Request ID: fc59c802-04da-4dd3-89a8-db5f525cac39 XML: <ErrorResponse xmlns="http://mws.amazonaws.com/doc/2009-01-01/"><Error><Typ e>Sender</Type><Code>RequestThrottled</Code><Message>Request from SubmitFeed:AKI AJI4PSK4HXY6UCNMA;A2DNAGZJ1EWQLW is throttled.</Message><Detail>System.Object</D etail></Error><RequestId>fc59c802-04da-4dd3-89a8-db5f525cac39</RequestId></Error Response> How can this be resolved? A: As per Amazon's API reference the SubmitFeed operation has a maximum request quota of 15 and a restore rate of a request every 2 minutes. This means that you're allowed to make calls to this operation in burst of 15, but after this you're throttled for 2 minutes, until Amazon allows you to make another request. You can find this better explained in their developer guide where they describe better how they make use of the leaky bucket algorithm. Probably there isn't anything wrong with your feed, but because you made too many requests (probably more than 15) you got throttled. My advice is to build your code in such a way that you take into consideration Amazon throttlening and have a back-off algorithm when you're being throttled (like come back after a "restore rate" period, specific to the type of call you're doing). Also, keep in mind that another limitation MWS has is of 10000 requests per hour across all type of calls.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: How do you do autopostback feature of webforms in asp.net mvc? I have a simple webgrid which displays list. I also have a combobox which contains few items. I want that when user changes the selection, the changed value should be posted to the server. How can I do this? Any code snippets would be helpful. A: Auto-postback in Web Forms was accomplished with some JavaScript. This is not out-of-the-box in MVC, but simple enough to do on your own. Assuming you have jQuery: $(document).ready(function() { $('#someCheckBox').change(function() { $('#yourFormId').submit(); }); }); This is "closest" to how classic Web-Forms work; basically does "When a checkbox with the ID of 'someCheckBox' is checked or unchecked, submit the form with id 'yourFormId'. You can of course change this to your needs. This wasn't included out-of-the-box due to most developers favoring AJAX calls instead of full-blown post-backs, which I would encourage you to do if possible. What might be more preferable is: $(document).ready(function() { $('#someCheckBox').change(function() { $.ajax(/*make an AJAX call*/); }); }); A: You implement it with ajax actions and javascript You can find a example here
{ "language": "en", "url": "https://stackoverflow.com/questions/7584515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Flex 3: how can I simulate the clicking of a certain image (button) Long story short - In order to make something work correctly, I need to simulate the user clicking on an image which doubles as a button and calls yet another function. I've tried simply calling the function, but it didn't work... for some reason, it only seems to work when the user clicks the button. Is it possible to 1) simulate clicks and 2) make the application think that the user clicks on a specific image? Full story - My application (a scheduling application) allows the user to replace one student with another. In order to do this, the user can bring up a list of available students. Once the list is presented, and the user selects a new students name, that new name is supposed to replace the old name. Instead, the text box simply goes blank. Now, if I click a image (which acts like a button) that increases the length of a that scheduled activity by one day, the name appears for whatever reason. I've tried simply calling the function that increases the number of days, but it doesn't work. For some reason, it would appear that only the user clicking the image (button) seems to make the new user name show up in the text box. This is why I would like to simulate the user clicking the "increase by 1 day" image. A: Yes, manually create and dispatch the click event. Something along the lines of this: var clickEvent : MouseEvent = new MouseEvent(MouseEvent.CLICK) // set other relevant properties on the click event myButton.dispatchEvent(clickEvent); However, I suspect this is not the 'best' solution, but more of a work around. It sounds like there is some other problem with your code and how the text is put into the display when it is changed. Without seeing more code or knowing more about your apps layout, it's hard to say for sure.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Issue Using Mockito's When Method I'm struggling trying to teach myself Mockito. Consider the following method, hasInventory(), which should not really run in my way of thinking, but get set up to return true or false as I squirrel-cage my test. Class Warehouse is my "mocked-dependency". public class Warehouse implements IWarehouse { private Map< String, Integer > inventory; public Warehouse() { this.inventory = new HashMap< String, Integer >(); } public final boolean hasInventory( String itemname, int quantity ) throws InventoryDoesNotExistException { if( inventory == null ) throw new InventoryDoesNotExistException(); if( !inventory.containsKey( itemname ) ) return false; int current = ( inventory.containsKey( itemname ) ) ? inventory.get( itemname ) : 0; return( current >= quantity ); } ... In the JUnit test code, the first when() throws an exception because it literally interprets the method call (executing it) and, inventory being nil (see above), InventoryDoesNotExistException is thrown. There are other methods in the mocked-dependency class too, like add() and remove(). @RunWith( MockitoJUnitRunner.class ) public class OrderInteractionTest { private static final String TALISKER = "Talisker"; private Order systemUnderTest = null; @Mock private Warehouse mockedDependency = null; @Before public void init() { //MockitoAnnotations.initMocks( this ); //mockedDependency = mock( Warehouse.class ); this.systemUnderTest = new Order( TALISKER, 50 ); } @Test public void testFillingRemovesInventoryIfInStock() { try { doNothing().doThrow( new RuntimeException() ).when( mockedDependency ).add( anyString(), anyInt() ); doNothing().doThrow( new RuntimeException() ).when( mockedDependency ).remove( anyString(), anyInt() ); when( mockedDependency.hasInventory( anyString(), anyInt() ) ).thenReturn( true ); when( mockedDependency.getInventory( anyString() ) ).thenReturn( 50 ); As I understand it, by the when() method, I'm asking Mockito precisely not to call hasInventory(), but just to return true instead whenever it's called as I test the class ("systemUnderTest"). Can anyone help me get past this point (or get some sense into my brain)? I'm linking mockito-all-1.8.5.jar and JUnit 4. Copious thanks to all who read this. Russ A: Mockito cannot mock final classes or methods. Try removing the final modifier from the hasInventory method. Or better yet, do not mock the Warehouse class, instead mock the IWarehouse interface, whose methods cannot be final, and presumably defines those used by Order. In general, it's preferable to mock interfaces, but it's not mandatory. Not being able to mock final classes or methods is briefly mentioned in the Mockito FAQ, it is due to the runtime class generation technique used for creating the mocks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: SQL Azure Backup & Restore strategy We have a web based (ASP.NET MVC) application that uses SQL Server 2008 for its database. Because the data is important to us (and our clients), we have a Backup & Restore strategy in place which, in a nutshell, looks like this: -Weekly: Full database backup -Nightly: Differential backup -Hourly: Log backup The strategy we use was greatly influenced by listening to a webcast done by Kimberly Tripp (which can be viewed here: https://msevents.microsoft.com/CUI/EventDetail.aspx?culture=en-US&EventId=1032278589&CountryCode=US). Question: Since we are looking into moving the database to SQL Azure, I wanted to know if anyone has put in place a similar Backup & Restore strategy within SQL Azure. Has anyone encountered any known issues with trying to put in place a Backup & Restore strategy with Azure? Thanks for any help on this. A: Backup/restore is a whole different animal in SQL Azure as the traditional backup/restore commands are not available. See the article SQL Azure Backup and Restore Strategy for a good overview and then read Copying Databases in SQL Azure. Also take a look at redgate's (beta) third party tool for SQL Azure Backup. EDIT: Adding a reference to a new blog post that appeared today (Sept 29, 2011): Data backup strategies for Windows and SQL Azure A: In addition to the options that Joe has mentioned you can also use DAC as mentioned here. It is a little out of date as you can now import/export BACPAC files from blob storage in the portal. A: Redgate offers a free tool to backup and restore a database from SQL Azure to SQL Server or Azure Blob Storage: * *SQL Azure Backup A: I wrote a blog post on backing up your SQL Azure DB to a blog file using nothing more complex than some free command line tools and the windows task scheduler, should save you some money and hassle :-) https://iainhunter.wordpress.com/2012/08/21/sql-azure-disaster-recovery/ A: There is one project on codeplex that is making possible to have a worker role to be acting as a backup agent.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: UIColor colorWithRed:green:blue:alpha: always returns white unless one argument is 0 I am using [UIColor colorWithRed:136 green:155 blue:218 alpha:1.0]; to change the background color of my table view cells. But for some reason the background just stays white. If I try [UIColor colorWithRed:0 green:155 blue:218 alpha:1.0]; the color changes. This does not make sense to me. Any advice or tips? A: The parameter aren't a values of 0 to 255 but a float between 0.0 and 1.0: [UIColor colorWithRed:0.0f/255.0f green:155.0f/255.0f blue:218.0f/255.0f alpha:1.0f]; A: The values need to be floats (in the range 0.0 to 1.0), not ints (in the range 0 to 255). + (UIColor *)colorWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha Try: [UIColor colorWithRed:136.0/255.0 green:155.0/255.0 blue:218.0/255.0 alpha:1.0]; A: The params are not integers but floats, so you probably want to divide all color float values with 255. Like this: [UIColor colorWithRed:136.0/255 green:155.0/255 blue:218.0/255 alpha:1.0]; That's why the color changes when you set red to 0 instead of 1 which 136 means in this case. A: Set navigation bar to transparent in iOS 11 (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault]; self.navigationController.navigationBar.shadowImage = [UIImage new]; self.navigationController.navigationBar.translucent = YES; self.navigationController.view.backgroundColor = [UIColor clearColor]; self.navigationController.navigationBar.backgroundColor = [UIColor clearColor]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7584531", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: static initialization in case of dependencies Is the following code safe (given no guarantees of static initialization order?). In some library: class A { A() : x_ = 0 { } int add() { return ++x_; } }; namespace S { static A a_; } #define ADD(varname) \ namespace S { \ static int v_##varname = a_.add(); \ } Macro ADD will be used at multiple places. Is it guaranteed that a_ will be initialized before v_##varname for any ADD macro usage? A: There is a common trick for your case if you want to guarantee: namespace S { A & getA() { static A a; return a; } } // namespace S And static int v_name = getA().add(); A: In the same translation unit/source file only, any uses of ADD after the definition of a_ will be executed after a_ is constructed. In any other translation unit (library or application) all bets are off in terms of ordering of initialization. You can use one of the static local methods if needed. See the FAQ: http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.15
{ "language": "en", "url": "https://stackoverflow.com/questions/7584532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: 2 Image views in Android? I have a relative layout with 2 image views in them, I try and set the xpos of image view 2 and it seems to appear inside image view 1, as if image view 1 is masking it, whats happening? xylophoneHolder = new HorizontalScrollView(context); xylophoneLayout = new RelativeLayout(context); xylophoneHolder.addView(xylophoneLayout); ImageView xylophoneA = new ImageView(context); Bitmap bMap = BitmapFactory.decodeResource(context.getResources(),R.drawable.xylophone_a); xylophoneA.setImageBitmap(bMap); xylophoneLayout.addView(xylophoneA); ImageView xylophoneAPressed = new ImageView(context); Bitmap bMap2 = BitmapFactory.decodeResource(context.getResources(),R.drawable.xylophone_a_pressed); xylophoneAPressed.setImageBitmap(bMap2); xylophoneAPressed.setX(100); xylophoneLayout.addView(xylophoneAPressed); A: I think it is better to use LinearLayout with orientation instead of RelativeLayout, with LinearLayout it is worked for me
{ "language": "en", "url": "https://stackoverflow.com/questions/7584535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How do you port bash aliases to ipython > 0.10? How do you port your bash aliases to IPython version >= 0.11? This question has already been answered for IPython < 0.11, and link for that is here: http://ipython.scipy.org/Wiki/tips A: Here is my solution. Improvements welcome! In your ipython config, add the following lines: (mine is here: ~/.config/ipython/profile_default/ipython_config.py) c = get_config() ## Port bash aliases to ipython import os, string a = os.popen("bash -l -c 'alias'").read() a = a.translate(string.maketrans("=", ' '), '\'"').split('alias ') a = [tuple(x.strip().split(' ', 1)) for x in a] c.AliasManager.user_aliases = [x for x in a if len(x) == 2]
{ "language": "en", "url": "https://stackoverflow.com/questions/7584536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Convert HTML into PDF using Python I am trying to convert HTML into a PDF document in Django and haven't been successful. I have tried using wkhtmltopdf 0.9.9, however Apache throws an error that wkhtmltopdf cannot connect to server. When I use wkhtmltopdf directly, it runs perfectly fine and converts the HTML into a PDF document. I have also tried using unoconv, however the rendered PDF file doesn't have any CSS applied to it. I have also tried using xhtml2pdf. Again I am facing same issue; the rendered PDF file doesn't have any CSS styling applied. I have spent the better part of today and last night trying to solve this issue and I'm still no closer to solving the problem. Let me know if you need any more information A: Configuring Pisa for Django shouldn't be too hard. There are really several examples on the net that show you how to do it and explain how to link to external resources in your templates: * *http://www.arnebrodowski.de/blog/501-Pisa-and-Reportlab-pitfalls.html *django - pisa : adding images to PDF output *http://antydba.blogspot.com/2009/12/django-pisa-polskie-czcionki.html *http://www.20seven.org/journal/2008/11/pdf-generation-with-pisa-in-django.html In your case you should try the link-callback-function mentioned in the first blog post: def fetch_resources(uri, rel): """ Callback to allow pisa/reportlab to retrieve Images,Stylesheets, etc. `uri` is the href attribute from the html link element. `rel` gives a relative path, but it's not used here. """ path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, "")) return path For newer Django-Version you probably should use STATIC_ROOT instead of MEDIA_ROOT Then use fetch resources accordingly in your render-method: pdf = pisa.pisaDocument(StringIO.StringIO( html.encode("UTF-8")), result, link_callback=fetch_resources, encoding="utf-8") A: I suggest you to use pisa, pypdf and html5lib combination, it worked for me. A: A possible, but not so elegant solution, is to run a small scripts which renders the html via a headless browser component (webkit/xvfb on Linux) and then saves it as a pdf.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to update 3 records using only one update? I want to change seqid : * *2 instead of 1 *3 instead of 2 *4 instead of 3 using one update statement. UserID seqid 1 1 1 2 1 3 1 4 A: Make sure you make a backup before running any update in case you get it wrong. Assuming (as per your question) you do not want seqid 4 modified: update MyTable set seqid = seqid + 1 where seqid between 1 and 3 If you just want to increment every seqid, do: update MyTable set seqid = seqid + 1 Edited to add: If you want to see the results of what you are doing before you commit to it (a good idea when making this kind of change): begin tran select seqid, count(*) from Mytable where seqid between 1 and 4 update MyTable set seqid = seqid + 1 where seqid between 1 and 3 select seqid, count(*) from Mytable where seqid between 1 and 4 --rollback tran --commit tran Don't forget to commit if you see the number of Seqids is right and don;t leave the transaction open especially on prod! But this is areally good idea for testing an update or delete when you aren't positive what the affect would be. Another technique to try if you have a complicated update is: update mt set seqid = seqid + 1 --select seqid, seqid+1, * From MyTable mt where seqid between 1 and 3 This way you can run the select and see in advance exactly what every value will be changed to. A: This is the more general case, which makes no assumptions about how the old and new values are related: update foo set seqid = case seqid when 1 then 2 when 2 then 3 when 3 then 4 end where seqid in (2,3,4)
{ "language": "en", "url": "https://stackoverflow.com/questions/7584550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to change libav decoding framerate? Is there any way to change libav decoding frame rate? There are several variables in libav structures responsible for getting frame rate but as I know these all are for reading purposes only (in decoding mode). Among them are: AVStream.duration AVStream.nb_frames AVStream.r_frame_rate AVStream.time_base The former two tell me the number of frames, and the latter two tell me the frame rate. But it seems that I can't just set them or it won't probably cause proper effect. Any suggestions? A: If I understand right, you need the decoded video at a lower framerate than it was encoded. The best solution would be to skip the frame packets before decoding them, at the rate you need (before calling avcodec_decode_video2()). Never tried it, but it should work. This will save unnecesary CPU spent for decoding frames you do not need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: javax.servlet.ServletException: null Recieved the following error whilst testing a small apache strut based web application ive been working on, the crux of the matter is that somehow a null httpservletrequest request parameter was passed to an Actionforward Execute function within an extened Action class?? My knowledge of struts usage is limited so, an explainition of this erranous behaviour is beyond me, any help greatly appreciated. Exception included below.. javax.servlet.ServletException: null org.apache.struts.action.RequestProcessor.processException(RequestProcessor.java:535) org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:433) org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236) org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196) org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:414) javax.servlet.http.HttpServlet.service(HttpServlet.java:689) javax.servlet.http.HttpServlet.service(HttpServlet.java:802) root cause java.lang.NumberFormatException: null java.lang.Integer.parseInt(Unknown Source) java.lang.Integer.parseInt(Unknown Source) org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431) org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236) org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196) org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:414) javax.servlet.http.HttpServlet.service(HttpServlet.java:689) javax.servlet.http.HttpServlet.service(HttpServlet.java:802) note The full stack trace of the root cause is available in the Apache Tomcat/5.5.4 logs. A: Apologies for not getting back to this sooner.. The error described was caused by a missing serviceForm Bean specification within an action mapping in struts-config.xml. The first time the user navigated to the offending web page the ServiceForm bean did not exist, so was created to store relative actionForm values (no errors occured). However when the user tried to navigate back to the web page after being elsewhere, access was attempted to the created serviceForm bean data, which hadn't been specified in the strut.. hence the null pointer crash.. Eg. name="serviceForm" was missing. <action path="/pages/networkconfig/listUIServices" type="com.UIServiceListAction" name="serviceForm" scope="request" validate="false"> <forward name="view" path="/pages/networkconfig/uiservices_list.jsp"/> </action> Hope this explainition is helpful..
{ "language": "en", "url": "https://stackoverflow.com/questions/7584558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Initialise a counter before the first loop This line $.each(data[0].hotel_id, function (index, value) { Loops through hotel_id array executing the inner JS code for each entry in the dictionary setting index to the key in the dictionary and value to the contents. My dictionary: "hotel_id": [{ "hotel_id": ["1"] }, { "hotel_id": ["2"] }, { "hotel_id": ["3"] }, { "hotel_id": ["4"] }], Has all items with the same index, therefore the value of index will always be 'hotel_id', which is no use to i when i try to use it to find the relevant extra data from my other dictionaries. I would initialise a counter before the first loop and increment it on each iteration then use this value to find the associated extra data from the other arrays. See full my js code: http://pastebin.com/jBWEDZrN This is summary from my js code in ajax call(url: 'get_gr',): $.each(data[0].hotel_id, function (index, value) { var $li = $('<li><input name="hotel_id[]" value="' + value.hotel_id + '" style="display:none;"></li>'); var $tooltip = $('<div class="tooltip"></div>').appendTo($li); $li.appendTo('#residence_name'); var info_ru = data[0].residence_u[index]; $.each(info_ru.units, function (index, value) { $tooltip.append(value + ' & ' + info_ru.extra[index] + ' & ' + info_ru.price[index] + '<br>'); }); var info_rp = data[0].residence_p[index]; $.each(info_rp.start_date, function (index, value) { $tooltip.append(value + ' & ' + info_rp.end_date[index] + ' & ' + info_rp.price_change[index] + '<br>'); }); tool_tip() }); This is output php code(url: 'get_gr',): [{ "guide": null, "hotel_id": [{ "hotel_id": ["1"] }, { "hotel_id": ["2"] }, { "hotel_id": ["3"] }, { "hotel_id": ["4"] }], "residence_u": [{ "units": ["hello", "how", "what"], "extra": ["11", "22", "33"], "price": ["1,111,111", "2,222,222", "3,333,333"] }, { "units": ["fine"], "extra": ["44"], "price": ["4,444,444"] }, { "units": ["thanks", "good"], "extra": ["55", "66"], "price": ["5,555,555", "6,666,666"] }], "residence_p": [{ "start_date": ["1111", "2222"], "end_date": ["1111", "2222"], "price_change": ["1111", "2222"] }, { "start_date": ["3333", "444"], "end_date": ["3333", "4444"], "price_change": ["3333", "4444"] }, { "start_date": ["5555", "6666"], "end_date": ["5555", "6666"], "price_change": ["5555", "6666"] }] }] What do i do? Update:(this update is for above output php) I insert several(array) value with json_encode in one row from database table, now want echo they as order with jquery. Output js code is this: 1 hello & 11 & 1,111,111 how & 22 & 2,222,222 what & 33 & 3,333,333, 1111 & 1111 & 1111 2222 & 2222 & 2222 2 fine & 44 & 4,444,444 3333 & 3333 & 3333 4444 & 4444 & 4444 3 thanks & 55 & 5,555,555 good & 66 & 6,666,666 5555 & 5555 & 5555 6666 & 6666 & 6666 4 A: No, your array doesn't have items with the same index. It has items with different indexes, but the value is an object that contains a property with the same name for each object. The index will go from 0 to 3 if the array has four items as in the example. You can use value.hotel_id in the loop to get the array that is the value of the property, for example ["1"]. If the array in the property only ever contains one id, you can just use value.hotel_id[0] to get that id. Example: $.each(data[0].hotel_id, function (index, value) { alert(value.hotel_id[0]); }); http://jsfiddle.net/Guffa/BWLqw/ A: I don't see the point of using each and an anonymous function. I would just use a for loop. for(var n = 0; n < data[0].hotel_id.length; n++) { // put your function code here or call a named func(data[0].hotel_id[n]) } I only use each if I am applying a function that I would reuse elsewhere.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Crystal Reports for VS 2010 Redistributable installed - and not working I have a .net project using a crystal report. I am using VS2010 and targeting the .net 3.5 framework. Everything works on my development machine, but not on the production web server. I have installed the SAP Crystal Reports 32 bit redistributable package (SAP Crystal Reports runtime engine for .NET framework) on my web server. I am still getting an exception saying "Type 'ReportDocument' is not defined." Do I have to do anything other than install the redistributable to get my site to recognize the Crystal Reports objects such as ReportDocument? <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <probing privatePath="bin;bin\HttpModules;bin\Providers;bin\Modules;bin\Support;" /> <dependentAssembly xmlns="urn:schemas-microsoft-com:asm.v1"> <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0" /> </dependentAssembly> <dependentAssembly xmlns="urn:schemas-microsoft-com:asm.v1"> <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35" /> <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0" /> </dependentAssembly> <dependentAssembly xmlns="urn:schemas-microsoft-com:asm.v1"> <assemblyIdentity name="Telerik.Web.UI" publicKeyToken="121fae78165ba3d4" /> <bindingRedirect oldVersion="2008.0.0.0-2020.0.0.0" newVersion="2010.02.0713.35" /> </dependentAssembly> </assemblyBinding> </runtime> A: You should include the following in the 'assemblyBinding' section either manually or by readding your references to CrystalDecision. <dependentAssembly> <assemblyIdentity name="CrystalDecisions.CrystalReports.Engine" publicKeyToken="692fbea5521e1304" culture=""/> <bindingRedirect oldVersion="14.0.2000.0" newVersion="12.0.2000.0"/> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="CrystalDecisions.Shared" publicKeyToken="692fbea5521e1304" culture=""/> <bindingRedirect oldVersion="14.0.2000.0" newVersion="12.0.2000.0"/> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="CrystalDecisions.ReportSource" publicKeyToken="692fbea5521e1304" culture=""/> <bindingRedirect oldVersion="14.0.2000.0" newVersion="12.0.2000.0"/> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="CrystalDecisions.Web" publicKeyToken="692fbea5521e1304" culture=""/> <bindingRedirect oldVersion="14.0.2000.0" newVersion="12.0.2000.0"/> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="CrystalDecisions.Enterprise.Framework" publicKeyToken="692fbea5521e1304" culture=""/> <bindingRedirect oldVersion="14.0.2000.0" newVersion="12.0.1100.0"/> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="CrystalDecisions.Enterprise.InfoStore" publicKeyToken="692fbea5521e1304" culture=""/> <bindingRedirect oldVersion="14.0.2000.0" newVersion="12.0.1100.0"/> </dependentAssembly> A: Sounds like you need to put CrystalDecisions.CrystalReports.Engine as a reference in your solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Triggering a SUBMIT in an asp.net application I need to trigger a submit when saving my image file in SQL 2005 database. A user will upload their image file. My application will then check to see if the image file size is within specific requirements. If so, then save the image into a table where the field is image data type. (if size does not meet requirements, display error message and exit sub). The issue is if I save the image file to the database, the value is saved correctly (however, I have not checked the image size). If I check the image file size first, THEN save it, the value saved is corrupted (incorrect). Is there a way that I can check the file size, then save the file while doing a submit in code-behind? My code is below: Dim iRequiredImageHeight As Integer = 80 Dim iRequiredImageWidth As Integer = 280 Dim imgBytes(FileUpload1.PostedFile.InputStream.Length) As Byte Dim stream As System.IO.Stream = FileUpload1.PostedFile.InputStream stream.InitializeLifetimeService() stream.Read(imgBytes, 0, imgBytes.Length) Dim imgData As System.Drawing.Image = System.Drawing.Image.FromStream(stream) Dim imgWidth As Integer = imgData.PhysicalDimension.Width Dim imgHeight As Integer = imgData.PhysicalDimension.Height If imgHeight > iRequiredImageHeight Or imgHeight > iRequiredImageWidth Then lblLogoMessage.Text = "The image you have uploaded is " & imgHeight & "px height by " & imgWidth & "px width. <br/> Required image size is " & iRequiredImageHeight & "px height by " & iRequiredImageWidth & "px width. <br/> Please resize the image and try again." lblLogoMessage.ForeColor = Drawing.Color.Red lblLogoMessage.Visible = True bLogoFit = False Else Dim LogoFile As String = FileUpload1.FileName.ToString.Trim Dim FileBytes(FileUpload1.PostedFile.InputStream.Length) As Byte FileUpload1.PostedFile.InputStream.Read(FileBytes, 0, FileBytes.Length) Dim SQL As String = "update CorpLogo " SQL += "set HeaderLogoName = @LogoFile, LogoImage = @LogoBytes " SQL += " where isonum='100'" Dim myConn As New SqlConnection(connString) Dim SQLcmd As New SqlCommand(SQL, myConn) SQLcmd.Parameters.AddWithValue("@LogoFile", LogoFile) SQLcmd.Parameters.AddWithValue("@LogoBytes", FileBytes) myConn.Open() SQLcmd.ExecuteNonQuery() myConn.Close() End If A: Just a brief note, since you have solved the problem. A Stream is like a firehose. It moves "water" from one location to another. Once you have pulled from the stream, the bits you are looking for are no longer there, as they are already pulled to a location rather than "held in the stream". In short, a stream is a bridge from one persistant location to another. Once items have cleared the stream, they are no longer there. This is why you cannot get the bits (corruption) after you have gotten the bits.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How do I create a URL to link between apps in Padrino? I have a separate app called "api" that I'd like to link to from my admin app. But if I do a link like: %td=button_to "API", url("/api/users", :attributes, :id => user.id), :method => :get, :class => :button_to It takes me to /admin/api/users, I want to go to api/users/attributes. A: Not sure if I understand but if you are in App2 and you want to render a link from another app you can: Api.url(:users, :attributes, :id => user.id)
{ "language": "en", "url": "https://stackoverflow.com/questions/7584572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: utility to dump memory representation of float? I'm looking for a utility that'll dump how a various number types are stored in RAM. It's easy to write but if there is a ready tool for achieving this, it'll be great. Hopefully it'll take of endianess as well. Syntax could be something like this: hex uint32 big E.g. hex float big 0.012 will show 0xa6 0x9b 0x44 0x3c or in a complete reversed order :-) EDIT: I'm looking for a universal tool and hopefully CLI based. debugger doesn't handle endianess. Thanks, A: Visual Studio has the option to look directly into memory. While debugging, go to Debug -> Windows -> Memory. You can then paste the address of the variables you want to inspect and see the bits.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting A URL Alias is changing the look of the Page OK I a page that is assigned to node/4 and it looks fine: The client wants the URL to read Pictorial Availability or something like that. I change the URL Alias and this is what happens: I know in the content box they have the following: <?php require_once "custom_app/cart/list_preloader.php"; ?> I don't think that is the issue because when you use the default route (node/4) it loads fine. I am trying to figure out why it puts a white space between the header and the start of the content. Anybody have any ideas as to why this would happen? I appreciate any input anyone may have. A: The screenshots weren't really enough for this. Demos links would help in the future. When visiting the page using it's URL alias an additional CSS file is loaded (http://goo.gl/x1iKq) that gives #title a larger height, messing up spacing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Convert dates in JSF for "title" attribute in a table Is it possible in JSF to convert a date value and put it in "title" attribute? In a similar question, JSF Convert dates for title attribute, there was an answer, that it can be done with JSTL's fmt:formatDate, but not in repeating components, such as UIData. I need to do it inside a table (extended HtmlDataTable). For example, the following code correctly displays the date as text value, but not in the title attribute: <h:outputText class="yui-tip" title="#{task[col.attributeName]}" value="#{task[col.attributeName]}"> <f:convertDateTime type="both" dateStyle="medium" timeStyle="short" timeZone="#{userProfileBean.clientTimeZone}" /> </h:outputText> A: The <f:convertDateTime> only converts the value attribute, not other attributes. In this particular case, your best bet is to create a custom EL function for that. First create a final class with a public static method which takes the necessary arguments and delegates to the JSF DateTimeConverter (package/class/method name is free to your choice): package com.example.util; import java.util.Date; import java.util.TimeZone; import javax.faces.component.UIOutput; import javax.faces.context.FacesContext; import javax.faces.convert.DateTimeConverter; public final class Functions { private Functions() { // Hide constructor. } public static String convertDateTime(Date date, String type, String dateStyle, String timeStyle, TimeZone timeZone) { DateTimeConverter converter = new DateTimeConverter(); converter.setType(type); converter.setDateStyle(dateStyle); converter.setTimeStyle(timeStyle); converter.setTimeZone(timeZone); return converter.getAsString(FacesContext.getCurrentInstance(), new UIOutput(), date); } } Define it as a facelet-taglib in /META-INF/functions.taglib.xml (filename is free to choice): <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE facelet-taglib PUBLIC "-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN" "http://java.sun.com/dtd/facelet-taglib_1_0.dtd"> <facelet-taglib> <namespace>http://example.com/util/functions</namespace> <function> <function-name>convertDateTime</function-name> <function-class>com.example.util.Functions</function-class> <function-signature>java.lang.String convertDateTime(java.util.Date, java.lang.String, java.lang.String, java.lang.String, java.util.TimeZone)</function-signature> </function> </facelet-taglib> (note: for Facelets 2.x, you need a XSD instead of a DTD; for an example see this answer) Register it as new taglib in /WEB-INF/web.xml: <context-param> <param-name>facelets.LIBRARIES</param-name> <param-value>/META-INF/functions.taglib.xml</param-value> </context-param> (note: if you already have the facelets.LIBRARIES definied, then you can just add the new path commaseparated; for Facelets 2.x, you need javax.faces.FACELETS_LIBRARIES context param instead) Declare it in the Facelets XHTML file as new XML namespace: <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:uf="http://example.com/util/functions" ... > Finally you can use it as intended: <h:outputText value="foo" title="#{uf:convertDateTime(bean.date, 'both', 'medium', 'short', bean.timeZone)}" /> You can if necessary hardcode the type and styles in the function and give the method a different name which indicates those defaults. If you happen to use JSF utility library OmniFaces, then you can also use its #{of:formatDate()} function instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: c++: class declaration and definition separated inside header causes Duplicate Symbol I usually only have the definitions of my classes inside a header if they are template classes.- If this is the case, i still like to split declaration and definition inside the header like that: template<class T> class Foo { public: Foo(); void fooFunc(); }; template<class T> Foo<T>::Foo() { } template<class T> void Foo<T>::fooFunc() { } that code also compiles. But If I remove the template: class Foo { public: Foo(); void fooFunc(); }; Foo::Foo() { } void Foo::fooFunc() { } i get a duplicate symbol error for Foos functions. I was very sure that this should work and am very surprised that it does not. Is this expected behaviour? If I add an inline before the definition it works too. A: Yes, it's expected behavior. Inline functions are meant to be compiled separately into each call site so duplication is no problem. For template functions, the compiler flags them in the object file such that the linker will basically ignore duplicates, since it can be difficult to predict where the template will or will not be instantiated. But conventional functions are expected to be defined exactly once. If you define one in a header file, it gets compiled into each translation unit that includes the header, leading to a "duplicate symbol" error at link time if you have more than one object file containing a copy of the function. A: I guess the linker knows the difference between a class that's defined in more than one translation unit and a templated class that's defined in more than one translation unit. For the former, it generates a duplicate symbol error, for the latter, it treats the two instances as the same thing and only uses one of them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to get Joomla's breadcrumb to display correct path to K2 item? I'm almost done with developing a quite complex Joomla website and I have a very irritating bug with the breadcrumb. I'll try to explain it the simplest way possible. I mix Joomla Articles and K2 items in order for my website to work as it should. I have the following architecture : About * *Testimonies (K2 category listing) Year X * *Program (Specific article with K2 modules that list the lessons) * *Lesson 1 (K2 item) *Lesson 2... Program Life * *Teachers (Joomla category listing) * *Mr. X (Joomla article) *Mr. Y The user can access the lessons details from the program's page or from a teacher's page. When you access a lesson's page from the program's page the breadcrumb shows 'Home > Year X > Program > Lesson 1' which is perfectly fine. When you try to access a lesson's page from a teacher's page the breadcrumb shows 'Home > About > Testimonies > Lesson 1'... which isn't correct. I use Joomla's breadcrumb module and not K2's. I'm pretty sure important config details are missing from this post but I'd be really really happy to discuss them with you if you need. Regards, Jibou A: Joomla will (always?) add the current menu item to the breadcrumbs. From there further down it's up to the extension what will be shown. So it looks like the links from your teachers page have the "Testimonies" menu item (Itemid) applied and thus Joomla generates breadcrumbs reflecting this menu item. You should make sure the links from within your Joomla article have the matching Itemid for "Year X" -> "Program" attached, then the breadcrumbs should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Adding extra run-time attribs to an activerecord object I have an Agent model which gets its attributes from the underlying database table. However for one particular controller action I would like to add some 'temporary' attributes to the Agent records before passing them on to the view. Is this possible? A: Yes, you can extend your models on the fly. For example: # GET /agents # GET /agents.xml def index @agents = Agent.all # Here we modify the particular models in the @agents array. @agents.each do |agent| agent.class_eval do attr_accessor :foo attr_accessor :bar end end # And then we can then use "foo" and "bar" as extra attributes @agents.each do |agent| agent.foo = 4 agent.bar = Time.now end respond_to do |format| format.html # index.html.erb format.xml { render :xml => @agents} end end In the view code, you can refer to foo and bar as you would with other attributes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Regex for login page URL? Right now, I have this code: string strURL = "aLogin.aspx?test=hello"; string strPattern = "(.*/)?Login.aspx(?.*)?"; bool bIsLoginPage = System.Text.RegularExpressions.Regex.IsMatch(strURL , strPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase); I'm searching for the proper regexp pattern, and I am at a loss. The pattern must fulfill these criteria Login.aspx ==> True lOgIn.AsPx ==> True /Login.aspx ==> True whatever/Login.aspx ==> True whatever/lOgIn.aSpX ==> True WhAtEverLogin.aspx ==> false Login.aspxxxxxx ==> false Login.aspx?xyz=abc&etc ==> true Login.aspxxyz=abc&etc ==> false Login.aspx&xyz=abc&etc ==> false A: What do you think about this? ^(.*[/])?login.aspx([?].*)?$ of course with ignorecase. A: Try string strPattern = "(^|.*/)Login.aspx($|\\?.*)"; and bResult = System.Text.RegularExpressions.Regex.IsMatch(strURL , strPattern, RegexOptions.IgnoreCase); EDIT: Fixed missing escape sequence A: You can do without regex: var target = "Login.aspx"; strURL.Split('?').First().Split('/').Last().Equals(target, StringComparison.OrdinalIgnoreCase);
{ "language": "en", "url": "https://stackoverflow.com/questions/7584595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to implement dynamic intercept url pattern i.e from database in spring security 3.0.5 I am new to spring security so not getting how to proceed for making the Url's to be authenticated should come from database. What things to be added in applicationContext-security.xml and what custom java classes will be needed? Please help me with example. Thanks A: I got the same issue with you. The following links would be helpful. http://static.springsource.org/spring-security/site/faq.html#faq-dynamic-url-metadata http://forum.springsource.org/showthread.php?112799-How-to-dynamically-decide-lt-intercept-url-gt-access-attribute-value-in-Spring-Security How to dynamically decide <intercept-url> access attribute value in Spring Security?
{ "language": "en", "url": "https://stackoverflow.com/questions/7584596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to intercept POST data in an android webview I have an android app that consists of a webview. It needs to allow users to fill in a form on a webpage and then change the data of the form after the user has clicked submit on the form. The form will use the POST request method. So my question is, how can I intercept the POST data from the form, change it's values, then send it along? For example: If there's a web form like this... <form action="http://www.example.com/do.php" method="post"> <input type="text" name="name" /> <input type="text" name="email" /> <input type="submit" /> </form> If the user enters name = Steve and email = steve@steve.com in the form, I want to change the values to name = bob and email = bob@bob.com in the android app and have the new POST be sent to http://www.example.com/do.php. Thanks for your help! A: If you are familiar with JavaScript, I would suggest you use JavaScript. I think it's more convenient and easy. This tour tells you how to use JavaScript in a WebView. A: I wrote a library with a special WebViewClient that offers a modified shouldOverrideUrlLoading where you can have access to post data. https://github.com/KonstantinSchubert/request_data_webviewclient Unfortunately, my implementation works for XMLHttpRequest (AJAX) requests only. But somebody else drafted already how this would be done for form data: https://github.com/KeejOow/android-post-webview Between the two repositories, you should be able to find your answer :) A: if you are submitting the form using postUrl() method then you can override the postUrl method in your WebView object like this. WebView mWebView = new WebView(this){ @Override public void postUrl(String url, byte[] postData) { System.out.println("postUrl can modified here:" +url); super.postUrl(url, postData); }}; LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout); linearLayout.addView(mWebView); A: I think you can use shouldInterceptRequest(WebView view, String url) method of WebViewClient, but it is supported in the API's later than 11. A: overriding onPageStarted callback in your WebView A: I liked the suggestion for public void postUrl(String url, byte[] postData) , but unfortunately it did not work for me. My solution for just intercepting the POST request: * *have a WebViewClient subclass that is set for WebView *override public void onPageStarted(WebView view, String url, Bitmap favicon) to examine the request data and act accordingly (as per requirements) Code excerpt & additional thoughts here: https://stackoverflow.com/a/9493323/2162226
{ "language": "en", "url": "https://stackoverflow.com/questions/7584597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: what the alternative to native libmedia in Android 2.3 i am using native code that uses libmedia.so and it was running fine in android 2.2 but when i tried it in 2.3.3 it got this error : 09-28 16:06:28.206: ERROR/AndroidRuntime(3307): Caused by: java.lang.UnsatisfiedLinkError: Cannot load library: reloc_library[1316]: 1239 cannot locate '_ZN7android11AudioRecordC1EijijijPFviPvS1_ES1_i'... What is the alternative to AudioRecord/libmedia in 2.3 ? A: i found this in the changelog in android_nds_r5 this API only works with 2.3 and above Audio APIs based on the OpenSL ES standard that support playback and recording as well as control over platform audio effects
{ "language": "en", "url": "https://stackoverflow.com/questions/7584599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to draw a circle by following MVC architecture I am new to iOS platform and i heard about MVC archtecture. To draw a circle i just create a separate UIView class and override the drawRect: and able to do this. But now i want to rebuild the same project using MVC architecture.The main aim is to separate my Model part from View & Controller part.So that i can extend my project. So how can i do this? Any sample application for reference? A: I'm not sure what you want to separate. Drawing a circle would generally fit into the "View" part of the MVC architecture, which is what you have already done. Code that would, for instance, change the colour of the circle would live in the "Controller" part, which on iOS is a UIViewController. If you had something storing information on what the circle looked like (i.e. size, colour, etc.), that could be considered part of the model, and can be stored in its own class, pulled in by the view controller and passed to the view when it is neede. Here is a link that may help. http://www.bit-101.com/blog/?p=1969 As for the model side of things, Core Data is a technology that can help. http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/CoreData/cdProgrammingGuide.html#//apple_ref/doc/uid/TP40001075 A: The separation would be the drawing code in drawRect and the size and location in a model with a controller getting the circle attributes from the model and requesting the drawing and passing the attributes to the view. The model might be another class or an API supplied class such as an NSDictionary. By creating a separate model if there were multiple circles the controller could make multiple draw requests, one per model circle. Or there could be multiple views that the circle(s) would be drawn in or different representations such as a text list of the circles attributed in one view and graphic circles in another. Many patterns seem trivial and not particularly useful in the trivial case yet in a real-world program work very well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set PATH environment variable in CMake script? I want to build my sources by Mingw compiler which in not placed on my system PATH. I tried this in the beginning of my script: set(Env{PATH} "c:/MyProject/Tools/mingw/bin/" "c:/MyProject/Tools/mingw/msys/1.0/bin/") And this: set(CMAKE_PROGRAM_PATH "c:/MyProject/Tools/mingw/bin/" "c:/MyProject/Tools/mingw/msys/1.0/bin/") set(CMAKE_LIBRARY_PATH "c:/MyProject/Tools/mingw/bin/" "c:/MyProject/Tools/mingw/msys/1.0/bin/") set(CMAKE_SYSTEM_PROGRAM_PATH "c:/MyProject/Tools/mingw/bin/" "c:/MyProject/Tools/mingw/msys/1.0/bin/") set(CMAKE_SYSTEM_PREFIX_PATH "c:/MyProject/Tools/mingw/bin/" "c:/MyProject/Tools/mingw/msys/1.0/bin/") The first variant doesn't work at all. A suggest that I can't overwrite the value of the environment variable in CMake script. The second script finds my mingw compiler, but catches the error while running gcc (can't find libgmp-10.dll which needs by gcc). This is because the PATH variable is not set to my Mingw. A: You might approach it as if it were a cross compiling toolchain, even if you're not cross compiling from Linux to Windows as in this example: http://www.vtk.org/Wiki/CmakeMingw After you follow that guide you set the mingw toolchain at the command line when calling cmake: ~/src/helloworld/ $ mkdir build ~/src/helloworld/ $ cd build ~/src/helloworld/build/ $ cmake -DCMAKE_TOOLCHAIN_FILE=~/Toolchain-mingw32.cmake then if you're using this a whole lot you can make an alias to limit typing in that ugly -D every time you want to regenerate makefiles: alias mingw-cmake='cmake -DCMAKE_TOOLCHAIN_FILE=~/Toolchain-mingw32.cmake' A: CMAKE_SYSTEM_PROGRAM_PATH is not meant to be modified, use LIST(APPEND CMAKE_PROGRAM_PATH "c:/MyProject/Tools/mingw/bin/" ...) A: Write a script file to start CMake. On Windows make a batch file: @echo off set path=c:\MyProject\Tools\mingw\bin;c:\MyProject\Tools\mingw\msys\1.0\bin "C:\Program Files\CMake 2.8\bin\cmake-gui.exe" On Linux make a bash script: export PATH=$PATH:/your/path
{ "language": "en", "url": "https://stackoverflow.com/questions/7584602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: git-svn dcommit fails because the repository name contains a space When attemping to git svn dcommit to a repository that has spaces in it's name, I get the following error: Committing to http://svn.kuluvalley.com/Meet the Expert/trunk ... http://svn.kuluvalley.com/Meet the Expert/trunk Filesystem has no item: '/!svn/bc/7397/Meet' path not found at /usr/libexec/git-core/git svn line 592 It looks like git svn doesn't support directories with spaces in them. A: I was able to work around the problem of git svn not working for repositories with spaces in them by patching git-svn. I updated the url_path function to: sub url_path { my ($self, $path) = @_; my $url = $self->{url} . '/' . $self->repo_path($path); if ($self->{url} =~ m#^https?://#) { $url =~ s!([^~a-zA-Z0-9_./-])!uc sprintf("%%%02x",ord($1))!eg; $url =~ s!^(https?)%3A//!$1://!; } $url } For windows (x64) users, this function can be found in Editor.pm file, which is located in {Git installation folder}\mingw64\share\perl5\site_perl\Git\SVN\ This ensures that the spaces in the url are encoded correctly. It seems to work for me, but hasn't been tested thoroughly. A: I believe the problem with spaces is fixed in Git >= 1.8.0 (See: #786942). So you should consider to upgrade it. See GitHub Home page: https://github.com/git/git
{ "language": "en", "url": "https://stackoverflow.com/questions/7584605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Disable Hibernate lazy fetching many-to-one associations A topic of many previous questions I see - but not quite as this one however. I understand Hibernates lazy fetching strategies, open-session-in-view etc., but I cant seem to find the solution to this simple little thing, where my association is fetched lazily no matter what. I am not using open session in view, as my web-app was build without it, and is now to complex to "migrate"... Let's say we have a chain of references, say a <- b <- c <- d -> e More often than not, fetching a also means we need b, c and d. So these are set to be always eagerly fetched (by specifying lazy=false in the hibernate mapping file). This WORKS!! However, we now also need to always eagerly fetch the association e, everytime d is fetched. Since e is crucial to perform some logic operations on d. And this is where it stops working... e is associated with d as a many-to-one association on d. Setting this to lazy=false doesn't do the trick, it is still not properly initialized, and accessing properties on e from d causes LazyInitialisationException. Is it wrong of me to expect that this would work? The lazy property is specified in the hbm files using hibernate v. 3.2.6 and Spring version 2.5.6. Hope someone can clarify things for me... By all means, please refer to another post if you find one. I cant seem to find one covering this... A: The lazy attribute of many-to-one associations is set in the class element: <class name="E" laze="false"> ... </class> <class name="D"> <many-to-one name="e" .../> </class> The lazy attribute on many-to-one has the same meaning as for any property: it allows lazy loading of single properties, which only works when the owner itself is a proxy. This is nothing you can use in your case and it is set to false by default anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Join all files in a directory, with a separator I have a directory containing hundreds of files (each having several chars). I want to join them into a single file with a separator, "|". I tried find . -type f | (while read line; do; cat $line; echo "|"; done;) > output.txt But that created an infinite loop. A: You can exclude output.txt from the output of find using -not -name output.txt (or as you already pointed out in the comments below, simply place the output file outside the target directory). For example: find . -type f -not -name output.txt -exec cat {} \; -exec echo "|" \; > output.txt I've also taken the liberty to replace your while/cat/echo with a couple of -exec params so we can do the whole thing using a single find call. A: *To answer the title of the question, since it's the first in google results (the output.txt problem is actually unrelated): This is what I use to join .jar files to run Java app with files in lib/: EntityManagerStoreImpl ondra@lenovo:~/work/TOOLS/JawaBot/core$ ls catalog.xml nbactions.xml nb-configuration.xml pom.xml prepare.sh resources run.sh sql src target workdir ondra@lenovo:~/work/TOOLS/JawaBot/core$ echo `ls -1` | sed 's/\W/:/g' catalog:xml:nbactions:xml:nb:configuration:xml:pom:xml:prepare:sh:resources:run:sh:sql:src:target:workdir The file listing may be of course replaced with find ... or anything. The echo is there to replace newlines with spaces. Final form: java -cp $(echo `ls -1 *.jar` | sed 's/\W/:/g') com.foo.Bar A: I reused Ondra's answer, but with absolute path instead. Command : echo $( \find '/home/user/[path-to-webapp]/WEB-INF/lib' -name '*.jar' -print0) |  \ sed 's#\.jar/#.jar:#g' Note: I use # as sed's separator to not match the last jar in the list. Results: /home/user/[path-to-webapp]/WEB-INF/lib/jar1.jar:home/user/[path-to-webapp]/WEB-INF/lib/jar2.jar[... and so on...]:/home/user/[path-to-webapp]/WEB-INF/lib/last-jar.jar Then, I can use this output in a javac -classpath command.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Return a typedef in C In a .h file I defined: #define PAIR_TYPE(type1, type2)\ typedef struct { \ // added \ after edit type1 first; \ // added \ after edit type2 second; \ // added \ after edit }; // added ; after edit #define MAKE_PAIR(val1, val2) {val1, val2} PAIR_TYPE(char *, uint32_t) mypair; mypair foo(); In the .c file I used it like this: mypair foo() { mypair p; uint32_t bar = calculate(); p = MAKE_PAIR("normal", target); return p; } However I get this error: error: expected expression before ‘{’ token The line it points is: p = MAKE_PAIR("normal", target); I don't know why it says '{' !!! there is no '{' at that line. A: You need more backslashes on the lines after '{' #define PAIR_TYPE(type1, type2)\ typedef struct {\ type1 first;\ type2 second;\ } A: Yes there is! But it is hidden from your eyes by the preprocessor magic. Remember, the preprocessor is evil, and you are certainly over-using it. The preprocessor just does textual substitution, so the code the compiler sees is actually: p = {"normal", target}; And that is not valid C syntax. There, see, the '{'. That syntax is only valid in initialization, not in assignments: mypair a = {"a", 1}; /* ok */ a = {"a", 1}; /* error */ A: In your PAIR_TYPE macro, you need to get rid of the semicolon at the end so that the name you give for the type is part of the typedef. Right now, when you do: PAIR_TYPE(char *, uint32_t) mypair; ..you get: typedef struct { char * first; uint32_t second; }; mypair; ..which has a semicolon between the } and mypair that shouldn't be there. You will also need to use a cast for your MAKE_PAIR macro to work the way you use it. Right now, the line: p = MAKE_PAIR("normal", target); ..expands to: p = {"normal", target}; ..which won't work. But if you add a cast: p = (mypair)MAKE_PAIR("normal", target); ..then the expanded line is: p = (mypair){"normal", target}; ..which can work since the type cast tells the compiler what the fields between the { and } should be. Though note that you're setting the char * in the first field to point at the literal "normal", not copying the string. A: May be if you use c idiom to write macro as shown in the link, you will not have problem that you are experiencing. Please see http://c-faq.com/cpp/multistmt.html for details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dont hide if it hasClass in jQuery Okay, start out saying this is hard to explain with words only. So i have setup a example here: http://jsfiddle.net/AFhvS/2/ I have a code in PHP, that show() the span element with X .sletindtastningfelt if it's filled. In the jsfiddle, it's placed at the bottom in the js field. jQuery(document).ready(function() { $('#smeal-1-1').show(); $('#smeal-1-1').addClass("upstartRemoveClass"); $('#smeal-1-2').show(); $('#smeal-1-2').addClass("upstartRemoveClass"); }); Ok so it appears X infront of the first two input fields now. What it does now is that when you click on one of the 4 tr (input fields), it hides the other X's and keeps the one infront of the field. This is caused by the .end().siblings().find('.sletindtastningfelt').hide(); I wish to change this procedure if it has the class "upstartRemoveClass". So if it has the class upstartRemoveClass it should not hide, like the rest, when you click on a tr (input field) A: Maybe you can use :not(.className): .end().siblings().find('.sletindtastningfelt:not(.upstartRemoveClass)').hide(); A: This just requires a condition: if($("someElement").hasClass("upstartRemoveClass")) { // do something } A: How about using not? Like this: .end().siblings().find('.sletindtastningfelt').not(".upstartRemoveClass").hide(); Does that give you the result you're looking for? A: The answers above using .not() or :not() are valid, but you can also change the logic a bit, and show any .upstartRemoveClass after hiding the rest: $(this).closest('tr') .find('.sletindtastningfelt') .show() .end() .siblings() .find('.sletindtastningfelt') .hide(); $('.upstartRemoveClass').show(); In this case, it will probably not be the best choice, but it can be useful sometimes, for example to remove complexity.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why do I get many repeated compiling messages during a grails build in intelliJ Here's the build console trace when I launch a grails 2.0 app in intellij in debug mode. It didn't used to be so verbose in grails 1.3.4 "C:\Program Files\Java\jdk1.6.0_22\bin\java" -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:57461,suspend=y,server=n -Dgrails.home=C:\grails-2.0.0.M2 -Dbase.dir=C:\apps\myapp "-Dtools.jar=C:\Program Files\Java\jdk1.6.0_22\lib\tools.jar" -Dgroovy.starter.conf=C:\grails-2.0.0.M2/conf/groovy-starter.conf -Xmx1G -Xms356m -XX:MaxPermSize=356m -javaagent:C:\Users\aressler\.IntelliJIdea10\system\groovyHotSwap\gragent.jar -Dfile.encoding=windows-1252 -classpath "C:\grails-2.0.0.M2\lib\org.codehaus.groovy\groovy-all\jars\groovy-all-1.8.2.jar;C:\grails-2.0.0.M2\dist\grails-bootstrap-2.0.0.M2.jar;C:\Program Files (x86)\JetBrains\IntelliJ IDEA 10.5.2\lib\idea_rt.jar" org.codehaus.groovy.grails.cli.support.GrailsStarter --main org.codehaus.groovy.grails.cli.GrailsScriptRunner --conf C:\grails-2.0.0.M2/conf/groovy-starter.conf "-Dserver.port=80 run-app" Connected to the target VM, address: '127.0.0.1:57461', transport: 'socket' | Loading Grails 2.0.0.M2 | Configuring classpath | Configuring classpath. | Environment set to development | Environment set to development. | Environment set to development.. | Environment set to development... | Environment set to development.... | Environment set to development..... | Packaging Grails application | Packaging Grails application. | Packaging Grails application.. | Compiling 3 source files | Compiling 3 source files. | Compiling 3 source files.. | Compiling 1 source files | Compiling 1 source files. | Compiling 1 source files.. | Compiling 1 source files... | Compiling 1 source files.... | Compiling 1 source files..... | Running Grails application This is on a build where I had made no changes from the last restart. Am I wasting lots of time on each restart with it doing wasted extra packaging and compiling? A: Grails 2 is not doing any more work. The reason for the repeated lines is that the new Grails 2 console is telling you that it is still working and progress is being made by adding a new period at the end of the current message. When working in IntelliJ with Grails 2 I use --verbose and --plain-output to get legacy style logging. The Grails 2 console uses JLine for a more rich command line experience but the IntelliJ console isn't exactly comparable. I throw on --stacktrace for good measure as well when using IntelliJ. A: I've created request in IntelliJ tracker to make -plain-output option by default.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JGit: Count objects How can I retrieve the total number of git objects in a repository? (I search something like the git count-objects in JGit.) I made a Java program that calculates statistic values and has to read every object (blob, tree, commit, tag) of a git repository. Something like a progress bar should show the user how many objects already have been processed. So I need the total number of git objects. A: I did not manipulate the Git objects at all, but I suppose you should explore the Repository object, which has methods like getAllRefs() or getObjectDatabase(). From the results, I imagine you could find what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to monitor a directory for changes in Python? Possible Duplicate: Monitoring files/directories with python I am making an API server that allows hot-deploying of code. And yes, there are dozens of questions about re-importing modules. I just want to monitor a directory, and when a change is detected, perform an action. path_to_monitor="c:\\app\\package" def action(): do_something() dm=dir_monitor(path_to_monitor,action) dm.start() I need a solution that is mature and cross-platform. A: You can use a Python thread which uses os.listdir() to list files. If you want to monitor other file properties than the file name, os.stat might help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get a list of physical storage devices? I want to get a list of physical storage devices. I've seen some code but that actually loops and does something like brute force. I want to know what is the general way of getting the list of physical storage disks. I've found CreateFile(). But I cannot understand how to use it properly. I need a non-wmi solution. and it's better if it doesn't query registry. A: I've used the following code, that enumerates all the volumes and then looks for their corresponding physical drives: #include <windows.h> #include <commctrl.h> #include <winioctl.h> typedef struct _STORAGE_DEVICE_NUMBER { DEVICE_TYPE DeviceType; ULONG DeviceNumber; ULONG PartitionNumber; } STORAGE_DEVICE_NUMBER, *PSTORAGE_DEVICE_NUMBER; void PrintVolumes() { char volName[MAX_PATH]; HANDLE hFVol; DWORD bytes; hFVol = FindFirstVolume(volName, sizeof(volName)); if (!hFVol) { printf("error...\n"); return; } do { size_t len = strlen(volName); if (volName[len-1] == '\\') { volName[len-1] = 0; --len; } /* printf("OpenVol %s\n", volName); */ HANDLE hVol = CreateFile(volName, 0, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (hVol == INVALID_HANDLE_VALUE) continue; STORAGE_DEVICE_NUMBER sdn = {0}; if (!DeviceIoControl(hVol, IOCTL_STORAGE_GET_DEVICE_NUMBER, NULL, 0, &sdn, sizeof(sdn), &bytes, NULL)) { printf("error...\n"); continue; } CloseHandle(hVol); printf("Volume Type:%d, Device:%d, Partition:%d\n", (int)sdn.DeviceType, (int)sdn.DeviceNumber, (int)sdn.PartitionNumber); /* if (sdn.DeviceType == FILE_DEVICE_DISK) printf("\tIs a disk\n"); */ } while (FindNextVolume(hFVol, volName, sizeof(volName))); FindVolumeClose(hFVol); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7584627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: compiler-optimization for numerical stability do GCC or similar compilers perform optimizations that are aimed at improving the numerical stability of floating-point operations. It is known that seemingly simply operations like addition or computing the norm of a vector are numerically unstable if implemented in the obvious manner, and, on the other hand, compilers sometimes destroy work-arounds for these problems for the sake of speed optimization. What is the state of the art of optimizing compiler output for numerical stable computation? Anything better than pending? A: Oracle (formerly Sun) compilers for Linux and Solaris. Their C++ and Fortran compilers have support for Interval Arithmetics
{ "language": "en", "url": "https://stackoverflow.com/questions/7584632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: What language or framework commonly uses tags like "" You will see it in the source code of many web sites as follows: <!--ls:begin[stylesheet]--> <!--ls:end[stylesheet]--> It appears to be some method of moving pieces defined in the body of some templating engine to the <head> of the the document (or wherever makes sense). For example, see the HTML for this site: view-source:http://www.theaa.com/ A: Those tags are produced by LiveSite, which is part of TeamSite enterprise CMS now owned by HP. Back in the days the company that found it was called Interwoven, then bought by Autonomy and now days it's HP. http://www.autonomy.com/products/teamsite A: My guess is that this is Live Site. A: Yeah I searched for this same question too... All I found was this but it doesn't mean they aren't using a white-labelled product http://www.limelight.com/web-content-management/
{ "language": "en", "url": "https://stackoverflow.com/questions/7584637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How can I dim the backround view when a custom View is displayed How can I dim my background when custom View is showing? In my Activity I have Relative Layout with some photo in background. When user do some action - FrameLayout appears in center of screen - and then I want make it to act like dialog - dim everything under framelayout. How can I achieve that? A: add this view over it.. it ll help you.. public class TransparentPanel extends LinearLayout { private Paint innerPaint; public TransparentPanel(Context context, AttributeSet attrs) { super(context, attrs); init(); } public TransparentPanel(Context context) { super(context); init(); } private void init() { innerPaint = new Paint(); innerPaint.setARGB(180, 75, 75, 75); } public void setInnerPaint(Paint innerPaint) { this.innerPaint = innerPaint; } @Override protected void dispatchDraw(Canvas canvas) { RectF drawRect = new RectF(); drawRect.set(0, 0, getMeasuredWidth(), getMeasuredHeight()); canvas.drawRoundRect(drawRect, 5, 5, innerPaint); super.dispatchDraw(canvas); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7584641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: SQL Stored Proc eats memory over time I've been trying to diagnosis this 30 MB memory leak in this webservice. It has some bulk gets from SQL using standard stored procs. Each "bulk" returns around 10,000-50,000 rows. The webservice generates its report and sends it to the caller. It seems everytime you call for this report 30 MB of memory gets "eaten" and not released. So if you hit the same call about 1,000 times the 3 GB system runs out of memory. If you recycle the app pool the mem is released. You can sit there for a day and the mem will not be released. So overtime the webserver runs out of memory. I steped through the code, anaylysised hte heck out of it, and finally determined it was these 3 "bulk" gets that get a moderate amount of data. Each takes out 10 MB and doesn't give it back after they're done. The stored procs are fine. The only odd thing about the calls is that it uses LINQ to call the stored procs and translate the data into Poco objects, using an XML map file. I tried changing it so they use a new DataContext every single time the stored proc is called and then set the DataContext to null. I tried setting all sort of objects to null and then calling GC.Collect and the mem is still being eaten and not released until you recycle the app pool. I would appreciate any leads. I suspect this has something to do with LINQ and large data returns. A: That's the ugly side of having garbage collection: developers tend to think they do not need worry about freeing memory anymore. But that's not entirely true! Some class instances have to be Disposed (as it's called in .Net). In fact, every object that implements IDisposable has to have its memory cycle handled by the developer. Streams are a good example. Streams are disposable AND they usually carry a larger amount of data (larger than a simple string). Imagine a service where every 5 seconds you handle a 2KB stream. That's not much right? It's, say, a small XML. But what happens if you do not dispose it? Well, you can do the math yourself, of course, but I'll give you the result: ~33.7 MB of unused junk. Bottom line: get disposed of your disposables.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to stop a thread in my unmanaged DLL made in C# I have a C# DLL that starts a thread for polling an USB device. My problem is that the workerObject and workerThread in the StopListenUSB function are null. public class USBDevice { private Worker workerObject; private Thread workerThread; public void StartListenUSB(int hwnd, uint wm_USER_KEYBOARD) { workerObject = new Worker(); workerThread = new Thread(workerObject.DoWork); workerThread.Start(); } public void StopListenUSB() { workerObject.RequestStop(); workerThread.Join(); } } public class Worker { private volatile bool _shouldStop; public void RequestStop() { _shouldStop = true; } public void DoWork() { while (!_shouldStop) {...} } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7584645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to hide JDialog from JApplet when user switch browser tab? Problem: user starts long operation from applet; JDialog with progress bar is displayed. User open/switch to another browser tab - JDialog is still displayed (and annoys user). JDialog should be hidden when user switch to another tab; and displayed again, when user switch back. Note: I saw question with similar problem, where solution was add windowActivated/deactivated listener. It doesn't work for me, because there are multiple frames in window, and one of them contains applet. When user clicks on another frame, windowDeactivate event is casted, but user still in the same tab. A: Try specifying the applet as the owner of the dialog: JDialog dialog = new JDialog(SwingUtilities.windowForComponent(this)); where "this" is the JApplet. Hopefully this will activate/deactive the dialog every time the parent loses focus. A: Solution: add listeners to all frames <head> ... <script type="text/javascript"> onBlur=function(event) { window.focusFlag = false; }; onFocus=function(event){ window.focusFlag = true; }; function createFocusListeners() { window.focusFlag = true; if (/*@cc_on!@*/false) { // check for Internet Explorer document.onfocusin = onFocus; document.onfocusout = onBlur; } else if (typeof window.addEventListener != "undefined"){ document.getElementById('topFrame').contentWindow.addEventListener('focus',onFocus, false); document.getElementById('topFrame').contentWindow.addEventListener('blur',onBlur, false); document.getElementById('leftFrame').contentWindow.addEventListener('focus',onFocus, false); document.getElementById('leftFrame').contentWindow.addEventListener('blur',onBlur, false); document.getElementById('mainFrame').contentWindow.addEventListener('focus',onFocus, false); document.getElementById('mainFrame').contentWindow.addEventListener('blur',onBlur, false); window.addEventListener('focus',onFocus, false); window.addEventListener('blur',onBlur, false); } }; //main frame is constantly reloaded, must add listener after each reload window.createMainFrameFocusListeners = (function () { if (typeof window.addEventListener != "undefined"){ document.getElementById('mainFrame').contentWindow.addEventListener('focus',onFocus, false); document.getElementById('mainFrame').contentWindow.addEventListener('blur',onBlur, false); } }); </script> </head> <frameset rows="32,*" cols="*" onload="createFocusListeners();"> <frame id="topFrame" src="MenuFrame.jspx" name="topFrame" scrolling="NO" noresize="noresize"/> <frameset rows="*" cols="280,*"> <frame id="leftFrame" src="TreeFrame.jspx" name="leftFrame" scrolling="NO"/> <frame id="mainFrame" src="ListView.jspx" name="mainFrame" scrolling="NO"/> </frameset> </frameset>
{ "language": "en", "url": "https://stackoverflow.com/questions/7584646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Asking ffmpeg to extract frames at the original frame rate On the FFmpeg documentation (here, and here) I read that, by default, FFmpeg chooses to extract frames at 25 frames per second (otherwise you can specify a framerate with the -r option) My problem is that I have a folder with dozens of videos, each of them recorded at different frame rates, so my question is: Is there a way to ask FFmpeg to extract frames from a video at the "native" frame rate (i.e. the original frame rate at which the video was recorded)? In case it matters, I am working with MP4 files A: To get the original frame rate: ffmpeg -i file.mp4 2>&1 | grep -o '[0-9]\{1,3\}\sfps' Example Output: 25 fps You can futher pipe it to sed ... | sed 's/\sfps//' to keep only the 25, and store it into a variable, so you can use that variable to convert the videos e.g. ffmpeg -r $originalFps. grep -o will extract the match, instead of the whole line containing the match. [0-9]\{1,3\} will match one to three digits \sfps will match a white space followed by 'fps'
{ "language": "en", "url": "https://stackoverflow.com/questions/7584647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: jQuery Ajax request in Sharepoint 2007 (SOAP) I have the following web service: SOAP 1.1 The following is a sample SOAP 1.1 request and response. The placeholders shown need to be replaced with actual values. POST /_vti_bin/QuickLinks.asmx HTTP/1.1 Host: myintracomm-design.ec.europa.eu Content-Type: text/xml; charset=utf-8 Content-Length: length SOAPAction: "http://ec.europa.eu/GetSuggestions" <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <GetSuggestions xmlns="http://ec.europa.eu/"> <prefixText>string</prefixText> <count>int</count> </GetSuggestions> </soap:Body> </soap:Envelope> HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-8 Content-Length: length <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <GetSuggestionsResponse xmlns="http://ec.europa.eu/"> <GetSuggestionsResult> <string>string</string> <string>string</string> </GetSuggestionsResult> </GetSuggestionsResponse> </soap:Body> </soap:Envelope> Which I locate by navigating to a url like: http://www.bla.eu/_vti_bin/QuickLinks.asmx?op=GetSuggestions I tried to make an Ajax request to fetch the content lying behind this, by using this code: var productServiceUrl = 'http://myintracomm-design.ec.europa.eu/_vti_bin/QuickLinks.asmx?op=GetSuggestions'; function LoadData() { var soapEnv = '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> \ <soap:Body> \ <GetSuggestions xmlns="http://ec.europa.eu/"> \ <prefixText>sys</prefixTest> \ <count>10</count> \ </GetSuggestions> \ </soap:Body> \ </soap:Envelope>'; $jQuery.ajax({ url: productServiceUrl, type: "POST", dataType: "xml", data: soapEnv, complete: OnLinksFetched, contentType: "text/xml; charset=\"utf-8\"" }); } function OnLinksFetched(xmlHttpRequest, status) { $jQuery(xmlHttpRequest.responseXML) .find('GetSuggestionsResult') .each(function() { var name = $jQuery(this).find('Name').text(); $jQuery("#links").append(name); });} and I added an simple onclick event to a link (just for testing purposes). Unfortunately, I get a bad request error. I tried many combinations of the soap request (as I have no experience in SOAP) but with no success. Decided to post here after 5 days of effort. Thanks in advance for any help. A: You could try adding a request header to your web service call. $.ajax({ url: productServiceUrl, beforeSend: function(xhr) { xhr.setRequestHeader("SOAPAction", "http://ec.europa.eu/GetSuggestions" }, type: "POST", dataType: "xml", data: soapEnv, complete: OnLinksFetched, contentType: "text/xml; charset=\"utf-8\"" });
{ "language": "en", "url": "https://stackoverflow.com/questions/7584649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: java data types to byte array I have a Java class public class MsgLayout{ int field1; String field2; long field3; } I have to write this object as a byte array in a Socket output stream. The three fields (instance variables) have a layout. i.e. field1 must occupy 1 byte, field2 must occupy 4 bytes and field3 must occupy 8 bytes. ByteBuffer bbf = ByteBuffer.allocate(TOTAL_SIZE); bbf.put(Integer.toString(this.getField1()).getBytes(), 0, FIELD1_SIZE); bbf.position(FIELD2_OFFSET); bbf.put(Long.toString(this.getField2()).getBytes(), 0, FIELD2_SIZE); bbf.position(FIELD3_OFFSET); bbf.put(Long.toString(this.getField3()).getBytes(), 0, FIELD3_SIZE); byte[] msg = bbf.array(); Using the above code, I am trying to fit each field in the byte array according to its desired size. But I am getting IndexOutOfBoundException In short, the problem is about how to fit the fields in the layout-defined size. For Example FIELD1_OFFSET = 0, FIELD1_SIZE=1, FIELD2_OFFSET=1, FIELD2_SIZE=4, FIELD3_OFFSET=5, FIELD3_SIZE=8. Now when I convert field1 into String, it does not fit into 1 byte when converted into byte[]. If I do not convert to String, and use putInt(int) it writes 4 bytes into the resulting byte array. A: What your code is currently doing is encoding your numeric fields as strings and then outputting the bytes of those characters. I would suggest using the DataOutputStream class to wrap your SocketOutput stream and write your binary data as so: DataOutput output = new DataOutputStream(socketOutputStream); int field1 = 1; String field2 = "Hello"; long field3 = 5000000000L; output.writeByte(field1); output.writeBytes(field2.substring(0, 3)); output.writeLong(field3); There are a couple assumptions in this code. First I'm assuming for field 2 you want 4 characters serialized as a single byte each. If you want to do any multibyte encoding using something like UTF-8, then you need to do something a little differently. Second, I'm assuming that field 2 will always have at least 4 characters. A: field1 may only have one byte of data, but its string representation will be one or more characters (e.g. "0", "63", "127"). Each character in the String is in fact a char (a two byte value). So I would expect one byte of data to inflate to two to six bytes of data when it goes through a byte->String->byte[] conversion.
{ "language": "en", "url": "https://stackoverflow.com/questions/7584652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Return an item in a nested list (python) I'm doing a lab for a basic programming class in Python, and I can't figure out how to return a number in a list, in another list. I'm supposed to return 4 with "one expression and no parenthesis" [1,[2,[3,4]]] Any ideas? All I've gotten so far is returning [2,[3,4]] and I haven't been able to figure out anything past that. A: >>> a = [1,[2,[3,4]]] >>> a[1] [2, [3, 4]] >>> a[1][1] [3, 4] >>> a[1][1][1] 4 >>> A: One expression: >>> [1,[2,[3,4]]][1][1][1] 4 A: In case you don't know, to access the last element of a list you can use negative index. a[-1] means the first element from the end. It's very useful when you want to print elements with position relative to the end. >>> a = [1,[2,[3,4]]] >>> a[-1] [2, [3, 4]] >>> a[-1][-1] [3, 4] >>> a[-1][-1][-1] 4 Let's say you had a different a. a = [1, 1, 1, 1, 1, 1,[1, 1, 1, 1, 2,[1, 1, 1, 3,4]]] The code above will still give you the last element. >>> a = [1, 1, 1, 1, 1, 1,[1, 1, 1, 1, 2,[1, 1, 1, 3,4]]] >>> a[-1] [1, 1, 1, 1, 2, [1, 1, 1, 3, 4]] >>> a[-1][-1] [1, 1, 1, 3, 4] >>> a[-1][-1][-1] 4
{ "language": "en", "url": "https://stackoverflow.com/questions/7584653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }