text
stringlengths
8
267k
meta
dict
Q: TFS Web create my own theme How can i create new design for tfs? I am looking for any guide or tutorial. I am looking to change layout colors etc.. so i am able to go to profile ,options, theme and select MyNewShinyTheme. Thank you for your comments A: This is a one-stop-shop for answering your complete question (assuming you have SharePoint 2010 deployed as part of your TFS system): http://blogs.msdn.com/b/sharepointdev/archive/2011/02/03/working-with-sharepoint-2010-themes.aspx A: browsing to the location of installed tfs i have been able to modify the theme.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Issue calling a funciton using setTimeout Our application has an issue with tracking google analytics requests. Internal links are not tracked in firefox unless the method that is used to send the request to google is called via a setTimeout. So I had this code working but have been away for a few months to find that a colleague completely changed the config file and removed the setTimeout call. Now when I put the code back in (with additional new variables) I get a js error in the browswer saying that callGA is not defined. Here is my code: function trackPageview(id, countryCity, unique, bu, bg, areaClick, uri) { setTimeout("callGA('" + id + "','" + countryCity + "','" + unique + "','" + bu + "','" + bg + "','" + areaClick + "','" + uri +"')", 1); } function callGA(id, countryCity, unique, bu, bg, areaClick, uri) { _gaq.push([ '_setAccount', id ]); _gaq.push([ '_setCustomVar', 1, 'Location', countryCity, 3 ]); _gaq.push([ '_setCustomVar', 2, 'Unique', unique, 3 ]); _gaq.push([ '_setCustomVar', 3, 'BU', bu, 3 ]); _gaq.push([ '_setCustomVar', 4, 'BG', bg, 3 ]); _gaq.push([ '_setCustomVar', 5, 'Portlet', areaClick, 3 ]); if (uri) { _gaq.push([ '_trackPageview', uri ]); } else { _gaq.push([ '_trackPageview' ]); } }; trackPageviews is being called in a number of locations. I have put an alert in here and its fine, the issue is on the setTimeout line. Any help would be much appreciated. A: It's best not to quote the action in setTimeout. It uses the eval(), which is a bit messy (and poor practice). It's better to use an anonymous function. setTimeout(function() { callGA(id,countryCity,unique,bu,bg,areaClick,uri) }, 1); A: Why not put the callGA function inside the setTimeout? function trackPageview(id, countryCity, unique, bu, bg, areaClick, uri) { setTimeout(function (id, countryCity, unique, bu, bg, areaClick, uri) { _gaq.push([ '_setAccount', id ]); _gaq.push([ '_setCustomVar', 1, 'Location', countryCity, 3 ]); _gaq.push([ '_setCustomVar', 2, 'Unique', unique, 3 ]); _gaq.push([ '_setCustomVar', 3, 'BU', bu, 3 ]); _gaq.push([ '_setCustomVar', 4, 'BG', bg, 3 ]); _gaq.push([ '_setCustomVar', 5, 'Portlet', areaClick, 3 ]); if (uri) { _gaq.push([ '_trackPageview', uri ]); } else { _gaq.push([ '_trackPageview' ]); } } , 1); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7598543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trigger javascript confirm based on server side logic (ASP.NET) Is there a way to make the following code works? Basically, when I click on btnOne, If a is true, i expect it to popup the confirm box. And If i press yes, then it will execute btnTwo method. Otherwise, it will not do anything. At the moment, it doesn't do the popup and i am not sure why. Can someone please point me in the right direction? or possibly let me know other way of achieving this. Any information would be much appreciated. For example: public void btnTwo(object sender, EventArgs e) { //Do some processing } public void btnOne(object sender, EventArgs e) { if( a == true ) btnTwo.Attributes["onClick"] = "return confirm('test');" btnTwo(sender, new EventArgs()); } A: I think you are mixing to much client and server side? Could you check "a" (hidden field) on client side? Or after check value in code behind add start up script with confirm and then on yes "click" second button in javascript. Protected Sub btnSecond_Click(sender As Object, e As System.EventArgs) Handles btnSecond.Click Me.lblInfo.Text = "SecondClick is done!" End Sub Protected Sub btnFirst_Click(sender As Object, e As System.EventArgs) Handles btnFirst.Click a = 10 Dim action As String = "<script> if(confirm('sure ?')){ document.getElementById('" & btnSecond.ClientID & "').click()} </script>" If (a > 5) Then Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "startConfirm", action) End If End Sub And markup: <form id="form1" runat="server"> <div> <asp:Button runat="server" ID="btnFirst" /> </br> <asp:Button runat="server" ID="btnSecond" /> <asp:Label runat="server" ID="lblInfo" /> </div> </form> A: Make sure that the code is being reached, and use OnClientClick instead: protected void Page_Load(object sender, EventArgs e) { bool a = true; if (a) btnTwo.OnClientClick = "return confirm(\"Are you sure?\");"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7598552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mercurial pager extension Mercurial's pager extension doesn't use the pager for hg status, is this a bug? Also, when using hg glog -p, the pager is used, but this doesn't conform to the guide: "If no pager is set, the pager extension uses the environment variable $PAGER. If neither pager.pager, nor $PAGER is set, no pager is used." I have no $PAGER set. A: Please see hg help pager: pager extension - browse command output with an external pager [...] Below is the default list of commands to be paged: [pager] attend = annotate, cat, diff, export, glog, log, qdiff Setting pager.attend to an empty value will cause all commands to be paged. [...] So it's documented behavior: the status command is not paged by default.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to create Cover Flow in J2ME Is it possible to create iPhone like cover flow in J2ME (specially Nokia)? If yes, what could be the logic to create it? A: J2ME Polish can be configured to provide lists in a cover-flow like UI (see here). You might also be able to persuade LWUIT to produce something like coverflow, but I have less experience there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Finding a list of divs with a specific class in Watir We have n-number of divs on the page with the same class name. <div class="errors"> </div> <div class="errors"> Foo is invalid </div> What we'd like to do is to check and see if any of the divs with the "error" class on them have the message "Foo is invalid". We can do this @browser.div(:class => 'errors', :index => 2) But that doesn't cover the case where the message is in the first or n-th div. What would be great is if we can get all the matching divs back as an array, flatten it out, and then do our assertions. Or perhaps get back the number of divs that match so that we can iterate over them. We are on Watir 1.9.2 A: If you upgrade to Watir 2.0 or if you use watir-webdriver gem, this would return all divs that have class errors and text (exactly) Foo is invalid (if that is what you want to do): browser.divs(:class => "errors", :text => "Foo is invalid") A: It's easy to get bogged down with a complex solution. Start with general (even inefficient) steps first and then streamline the code once the basic solution is working. This will work in Watir 1.9.2: @divs_with_error = [] #create a new array for the divs with class == "error" @divs_invalid = [] #create a new array for the divs with text == "Foo is invalid" browser.divs.each do |div| #for each div on the page if div.class == "error" #if the class == "error" @divs_with_error << div #add it to our array end end @divs_with_error.each do |div| #for each div in the @divs_with_error array if div.text == "Foo is invalid" #if the text == "Foo is invalid" @divs_invalid << div #add it to our next array end end If this collects the data you are looking for, you can simplify it into a single block: @divs_with_error = [] #create a new array browser.divs.each do |div| if ((div.text == "Foo is invalid") && (div.class == "error")) @divs_with_error << div end end You may need to use div.text.include? if there is other text in the failing div elements. You can also use the collect! method with the arrays to save some more space. As always, rather than collecting the entire div element, you can collect certain attributes only: @divs_with_error << [div.text, div.index] @divs_with_error << div.class Hope that helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7598564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Passing multiple model to controller and bind the data to viewpage how can i Pass multiple model to controller and bind the data to viewpage i have list page in that page contains two tabs, one for active list and another one In active list. how can i create a model and bind the data to viewpage. how can i bind the data to view page, i used strong typed model public class MyViewModel { public IEnumerable<SomeViewModel> Active { get; set; } public IEnumerable<SomeViewModel> InActive { get; set; } } this is my view page code <% foreach (var model in Model) { %> <tr> <td> <%= Html.ActionLink(model.TITLE, "Detail", new { id = model.EVENT_ID })%> </td> I got an error Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compiler Error Message: CS1061: 'System.Collections.Generic.IEnumerable<EventListing.Models.MyViewModel>' does not contain a definition for 'Active' and no extension method 'Active' accepting a first argument of type 'System.Collections.Generic.IEnumerable<EventListing.Models.MyViewModel>' could be found (are you missing a using directive or an assembly reference?) Source Error: Line 221: </thead> Line 222: <tbody> Line 223: <% foreach (var model in Model.Active) Line 224: { %> Line 225: <tr> A: You could have a view model that contains the two lists as properties: public class MyViewModel { public IEnumerable<SomeViewModel> Active { get; set; } public IEnumerable<SomeViewModel> InActive { get; set; } } and then pass an instance of MyViewModel to the view from the controller action.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Color java class if I get color of text , I got : java.awt.Color[r=234,g=152,b=28] which should correspond to orange but when I perform the assertion : this is not working assertEquals(Color.ORANGE.ToString(),myText.getColor()); expected :java.awt.Color[r=255,g=0,b=0] but was : java.awt.Color[r=234,g=152,b=28] any idea ? A: You are comparing String and Color objects. Correct assertion is assertEquals(Color.ORANGE, myText.getColor()); Also the java.awt.Color.orange is new Color(255, 200, 0);. A: And anyway in java/awt/Color.java source ORANGE is defined as: /** * The color orange. In the default sRGB space. */ public final static Color orange = new Color(255, 200, 0); /** * The color orange. In the default sRGB space. * @since 1.4 */ public final static Color ORANGE = orange;
{ "language": "en", "url": "https://stackoverflow.com/questions/7598567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to improve accuracy of accelerometer and compass sensors? i am creating an augmented reality app that simply visualices a textview when the phone is facing a Point of Interest (wich gps position is stored on the phone). The textview is painted on the point of interest location in the screen. It works ok, the problem is that compass and accelerometer are very "variant", and the textview is constantly moving up and down left and right because the innacuracy of the sensors. there is a way to solve it? A: Our problem is same. I also had same problem when I create simple augmented reality project. The solution is to use exponential smoothing or moving average function. I recommend exponential smoothing because it only need to store one previous values. Sample implementation is available below : private float[] exponentialSmoothing( float[] input, float[] output, float alpha ) { if ( output == null ) return input; for ( int i=0; i<input.length; i++ ) { output[i] = output[i] + alpha * (input[i] - output[i]); } return output; } Alpha is smoothing factor (0<= alpha <=1). If you set alpha = 1, the output will be same as the input (no smoothing at all). If you set alpha = 0, the output will never change. To remove noise, you can simply smoothening accelerometer and magnetometer values. In my case, I use accelerometer alpha value = 0.2 and magnetometer alpha value = 0.5. The object will be more stable and the movement is quite nice. A: You should take a look at low-pass filters for you orientation data or sensor fusion if you want to a step further. Good Luck with your app. JQCorreia A: I solved it with a simple trick. This will delay your results a bit but they surly avoid the inaccuracy of the compass and accelerometer. Create a history of the last N values (so save the value to an array, increment index, when you reach N start with zero again). Then you simply use the arithmetic average of the stored values. A: Integration of gyroscope sensor readings can give a huge improvement in the stability of the final estimation of the orientation. Have a look at the steady compass application if your device has a gyroscope, or just have a look at the video if you do not have a gyroscope. The integration of gyroscope can be done in a rather simple way using a complementary filter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: What to do when SVN Checkout stops working Today, my SVN repository on CodePlex stopped working. Trying to do a fresh checkout, I get the following error: Command: Checkout from https://digger.svn.codeplex.com/svn, revision HEAD, Fully recursive, Externals included Error: PROPFIND of '/svn': 207 Multi-Status (https://digger.svn.codeplex.com) I've posted a support request on CodePlex, but other than that, are there steps to resolve this type of SVN error? (All Update and Commit operations also fail, but have been working fine for months before today). A: The Codeplex team suggested that I convert over to Mercurial, as it was an unrecoverable bug with their SVN Bridge setup. Instead, we just reset the entire repository and recommited everything.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598578", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to create Android apps using Delphi I have been asked to research on how to make an android app using Delphi, Now I am not sure that this can be done. I have not come across tutorials on the same. Somebody please clarify on this issue. A: Free Pascal is now able to produce code for the Java platform - so it might be feasible to create Delphi code which can be compiled to Java bytecode with FPC and then converted for the Dalvik VM. The FPC backend for the Java Virtual Machine (JVM) generates Java byte code that conforms to the specifications of the JDK 1.5 (and later). While not all FPC language features work when targeting the JVM, most do (or will in the future) and we have done our best to introduce as few differences as possible. This FPC JVM backend is not related to Project Cooper by RemObjects, nor does FPC now support the Oxygene language. A: Two choices to follow at present - check out Delphi for Android which is in design/beta phase: http://lenniedevilliers.blogspot.com/ Or, use Prism http://www.embarcadero.com/products/prism (and check out their Oxygen for Java coming soon http://www.remobjects.com/oxygene/java.aspx which is in Beta) A: One way is to use a combination of Delphi, Sencha and PhoneGap by leveraging the Raudus framework. You can try the RaudusEmployee.apk example on your phone and see if this method will work for you. http://www.raudus.com/samples/ This is not a native application, but similar to many new HTML5 applications. A: With DWS as backend script compiler and the soon to come Smart Mobile Studio (aka OP4JS) component library and RAD interface it will be possible to make apps running with HTML5 in android applications (and iOS or any other html5 compatible system). By using object pascal, all Delphi and freepascal users will have a short learning curve and a high code reuse factor. There are some samples using only the DWS backend here : taming-the-flock-with-object-pascal taming-html5-verlets-with-object-pascal Update : More samples can now be found on their homepage. A: First steps with native Android applications made with Lazarus/FPC are here. A: Delphi XE5 is now released with Android support. http://www.embarcadero.com/products/rad-studio/create-android-apps A: Delphi cannot create Android apps at present. This is being worked on for a future release. Update: As of the release of XE5, Delphi now supports Android development for certain ARM hardware using the mobile Delphi compiler.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: JSON ajax response outputed to screen Our server is located in europe. Now and then an american based user reports a problem when he uses the $.getJSON function. His browser just displays the json response instead of catching it and passing it to javascript. The ajax call just looks like: $.getJSON(url, function(json_data){ ... }); Any ideas? More info: * *The the same user has the problem in FF and IE. *I use Ruby On Rails render :json. which response type is application/json. A: Try using the $.ajax() method so you can handle errors and debug the success callback. $.ajax({ type: "GET", contentType: "application/json; charset=utf-8", data: {}, dataType: "json", url: url, success: function(json_data) { // parse json_data object }, error: function (xhr, status, error) { // check for errors } }); Aside from that using an XHR viewer like Firebug or Chrome's built-in utility (CTRL+SHIFT+I) can be very helpful. XHR DOM reference: http://www.w3schools.com/dom/dom_http.asp
{ "language": "en", "url": "https://stackoverflow.com/questions/7598580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: developing sql application using local database I am starting an application (c#, .net) that will interact with a Microsoft SQL database. I need the ability for multiple clients to access the data concurrently so I an going to use a service based database (.mdf). Is it possible to develop the application using a local database (.sdf) and then easily switch it over to a service based database when it comes time for deployment? Is that how this type of development it typically done? A: You can control the data source by providing connection string to your database in .config file. You can even create Debug and Release versions of your .config file with different connection strings. Debug can point to your local machine and Release to production. A: Development shops vary, but it is pretty common to develop apps using SQL Express locally and then use a full installation of SQL Server for the production environment. The only thing I would advise is make sure that the DB you chose for your dev environment supports the same features as what you expect in production. For example don't use SQL Express on your dev box when you expect to use Oracle in production. A: If the database schema in both backends is exactly the same than the only thing you will need to do is change the connection string when you are ready to move to the service based database. Be aware that the slightest change in the schema can (and probably will) cause problems. A: You want to use SQL Compact Edition (as you said database file extension is .sdf), right? You can use MSSQL Express Edition instead, as it acts more like full MSSQL Server, and is still free and not so hard to install on developer's machine (I personally prefer this option). There are differences between the two (as explained here: http://blog.sqlauthority.com/2009/04/22/sql-server-difference-between-sql-server-compact-edition-ce-and-sql-server-express-edition/). If you don't want features like triggers/procedures/views in your database, you can still use CE, though. A: If you have multiple clients then you should use SQL Server Express (.mdf file) - SQL Server Compact (.sdf file) is useful when you are building an application that is going to be deployed on client machines and will run standalone, e.g. windows forms application with a local database. SQL Server Compact is just an alternative for MS Access .mdb files or SQLite, the so called "embedded databases", while SQL Server Express is a real database server (albeit with some limitations to render it unsuitable for large commercial applications) and should be used in the cases where multiple clients use central database, e.g. web applications and smart client apps (the latter could also make use of a local embedded database though).
{ "language": "en", "url": "https://stackoverflow.com/questions/7598582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Drop Time stamp while pulling data from oracle table to java Currently I am getting date from oracle table as string which is giving me date as well as timesstamp. Is there a way I can drop timestamp and just get the date from table. Currently in my java code Date is declare as string which pulls date and timestamp.Thank you setDate(rset.getString(1)); A: Using ResultSet#getDate() will return just the date component, as a java.sql.Date (which has hours, minutes, seconds, and milliseconds set to zero). You can turn that Date object into a string afterwards. I would, however, recommend storing date information as a Date, not as a String. A: Be careful of using the term "timestamp". Timestamp is a datatype in Oracle. If you're asking how do you eliminate the 'time' portion of the date. You can use the TRUNC() function in Oracle. Or you could NOT use a string on the Java side, use a date instead and set the format to not show the time portion. A: java.time If your JDBC driver supports JDBC 4.2 or later, it may be able to handle the java.time types which supplant the old java.util.Date/.Calendar and java.sql types. Call the setObject method on a PreparedStatement and getObject on the ResultSet. Date-only types will appear in Java as java.time.LocalDate. Time-of-day-only types will appear in Java as java.time.LocalTime. A timestamp (a date-time) will appear as an java.time.Instant. If your driver does not yet offer this support, fall back to using the java.sql types as shown in the correct Answer by Matt Ball. Then immediately convert to java.time types. Perform your business logic in java.time types; use java.sql types only for data-exchange with database. Look to new methods added on the old classes for convenient conversions. LocalDate ld = myJavaSqlDate.toLocalDate() ; LocalTime lt = myJavaSqlTime.toLocalTime() ; Instant instant = myJavaSqlTimestamp.toInstant() ; Going the other direction, look at the valueOf or from methods.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: declaring global variables in vb The user clicks a button, a new form is generated where the user enters his/her password? How can I keep an in-memory copy of the username? For instance in web forms, I can just use Session ("User"). How can I replicate this with winforms? Thanks A: You could use a static (Shared in VB .NET) object Example Public Class SessionInformation Public Shared Property UserPassword As String End Class You can then access this by calling SessionInformation.UserPassword Since there seems to be some concerns revolving around whether or not this is a valid implementation I will explain why this is not the best idea. This creates a single instance of SessionInformation which means that if it is changed anywhere in the program it affects the rest of the program. Maintaining object persistence can be difficult if you aren't using a database (SQL, Access, a file, etc...) to maintain an out of memory copy of the object that you want to retrieve at a later date. The easiest way to implement this would be to use a SQLCE database that live in your application folder and using standard T-SQL to store the information that you need. However in the case of a password this may be non-ideal due to security issues. Or the better way for logging in and out user would be to make use of the System.Security.Principal Namespace to create a user for your application. A: You don’t need an equivalent to the Session object in web applications. Sessions are only needed because web applications actually have to access variables across process boundaries (= a session in a web application encompasses multiple requests of a user to a web server, and historically each request started a new application!). In a “normal” application, this isn’t the case – any non-local variable will do. In your particular case, it would make sense for the password form to have a property that contains the username. The user then enters their username and password and the caller of this password form can retrieve the username: ' The caller looks something like this: Dim pw As New PasswordForm() pw.ShowDialog() ' Display the dialog, and wait until the user has dismissed it. Dim theUsername = pw.Username Inside the PasswordForm, there is something like this: Public ReadOnly Property Username() As String Get ' Return the value of the username textbox field. Return UsernameInput.Text End Get End Property We could get more sophisticated but this will do. If you need to reuse the username across the application, chances are that you also need to share other information about the user (what are they working on? …). This, in short, is the state of the application and there is usually an object which represents that state. This would be the right place to store the username as well. If your application only has one other form (the “main dialog”), then just use a private variable inside that form to store the username. No need for a global variable. A: Just have a public variable on the forms, never unload the form, and get the data from that form using formname.variablename (define it as public at form level). This even can be achieved with controls if you set them to public. BEFORE THE FLAMES: this solves OP problems, whenever if this is optimal, good or anything else, is another problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# login to website and download source using WebRequest - Issue with cookies I need to login to a website a download the source code from various pages when logged in. I am able to do this quite easily when using the Windows Forms WebBrowser class, however this is not appropiate and I need to be able to do this with WebRequest or one of the others. Unfortunately it doesn't like how I am handling the cookies. I am using the following code and get the following response: {"w_id":"LoginForm2_6","message":"Please enable cookies in your browser so you can log in.","success":0,"showLink":false} string url2 = "%2Fapp%2Futils%2Flogin_form%2Fredirect%2Fhome"; string login = "username"; string password = "password"; string w_id = "LoginForm2_6"; string loginurl = "http://loginurl.com"; string cookieHeader; WebRequest req = WebRequest.Create(loginurl); req.Proxy = WebRequest.DefaultWebProxy; req.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; req.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; req.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; req.Method = "POST"; string postData = string.Format("w_id={2}&login={0}&password={1}&url2={3}", login, password, w_id, url2); byte[] bytes = Encoding.ASCII.GetBytes(postData); req.ContentLength = bytes.Length; using (Stream os = req.GetRequestStream()) { os.Write(bytes, 0, bytes.Length); } WebResponse resp = req.GetResponse(); cookieHeader = resp.Headers["Set-cookie"]; string pageSource = ""; using (StreamReader sr = new StreamReader(resp.GetResponseStream())) { pageSource = sr.ReadToEnd(); } richTextBox1.Text = pageSource; If anyone could tell me where I'm going wrong, it would be greatly appreciated. Also, to let you know, if I use the following with the webbrowser class, it works in fine: b.Navigate(fullurl, "", enc.GetBytes(postData), "Content-Type: application/x-www-form-urlencoded\r\n"); A: I know this is old to reply, but the user Matthew Brindley answered similar question with a completely working example. The question is about accessing to the source code of a website that requires user login previously. All done from a C# application using WebRequest and WebResponse
{ "language": "en", "url": "https://stackoverflow.com/questions/7598606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SpringIntegration message size to big, how to split I have a SprintIntegration system with a JMS endpoint. The size limit for messages is 4mb. I have results which are larger then that, how do I get SI to split that up into several messages? /A A: In Spring Integration, you can use a Splitter to split your messages to not exceed e.g. 4MB. <int:splitter id="splitter" ref="splitterBean" method="split" input-channel="inputChannel" output-channel="outputChannel" /> <beans:bean id="splitterBean" class="your.MessageSplitter"/> or by using a @Splitter annotation. When a message comes in to the splitter, you would apply the splitting logic inside your.MessageSplitter, and return a List<YourMessage>: public class MessageSplitter { public List<YourMessage> split( HugeMessage hugeMessage ) { List nicelySizedMessages = new ArrayList<YourMessage>(); // splitting logic... that would parse "hugeMessage" and split it to // nicelySizedMessages.add( ... ) "YourMessage"s return nicelySizedMessages; } } Spring Integration would take this list and would forward YourMessages from the list one by one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dynatree with ASP.NET MVC Has anybody got any examples of using the Dynatree plugin with MVC? I have been wrestling with it without much progress. I have an action method which returns a JsonResult (but selects all columns in the underlying table, not sure if this is the problem) and in my initajax call , all I'm doing is calling this method. If it's not too much trouble, I am looking for sample View and Controller action methods. Thanks in advance for any help A: You need to create an object to serialize the nodes eg. public interface ITreeItem { } /// <summary> /// Tree Item Leaf. /// </summary> public class TreeItemLeaf :ITreeItem { /// <summary> /// Gets the Title. /// </summary> public string title; /// <summary> /// Gets the Tooltip. /// </summary> public string tooltip; /// <summary> /// Gets the key. /// </summary> public string key; /// <summary> /// Gets the Data. /// </summary> public string addClass; /// <summary> /// Gets the Children. /// </summary> public IList<ITreeItem> children; /// <summary> /// Gets the rel attr. /// </summary> public string rel; /// <summary> /// Gets the State. /// </summary> public bool isFolder; /// <summary> /// Gets the State. /// </summary> public bool isLazy; /// <summary> /// Initializes a new instance of the <see cref="TreeItemLeaf"/> class. /// </summary> public TreeItemLeaf() { children = new List<ITreeItem>(); } /// <summary> /// Initializes a new instance of the <see cref="TreeItemLeaf"/> class. /// </summary> /// <param name="type">The type of node.</param> /// <param name="id">The Id of the node.</param> /// <param name="title">The Title of the node.</param> /// <param name="tooltip">The Tooltip of the node.</param> public TreeItemLeaf(String type, Guid id, String title, String tooltip) { key = id.ToString(); this.title = title; isFolder = false; isLazy = false; this.tooltip = tooltip; children = new List<ITreeItem>(); } } /// <summary> /// Tree Item. /// </summary> public class TreeItem : TreeItemLeaf { /// <summary> /// Gets the State. /// </summary> public new bool isFolder; /// <summary> /// Initializes a new instance of the <see cref="TreeItem"/> class. /// </summary> public TreeItem() : base() { } /// <summary> /// Initializes a new instance of the <see cref="TreeItem"/> class. /// </summary> /// <param name="type">The type of node.</param> /// <param name="id">The Id of the node.</param> /// <param name="title">The Title of the node.</param> /// <param name="tooltip">The tooltip of the node.</param> public TreeItem(String type, Guid id, String title, String tooltip) : base(type, id, title, tooltip) { isFolder = true; isLazy = true; } } Once you have this, you can return a Json(IList<ITreeItem>) which you will need to build up from your results.. If you go to the Dynatee demo http://wwwendt.de/tech/dynatree/doc/samples.html , you can use Firefox/Firebug to study the HTTP requests to see exactly what is being passed in and returned. My tree in the view is as follows : // --- Initialize first Dynatree ------------------------------------------- $("#tree").dynatree({ fx: { height: "toggle", duration: 500 }, selectMode: 1, clickFolderMode: 1, children : @Html.Raw(String.Format("{0}", ViewData["tree"]).Replace("\"children\":[],", "")), onLazyRead: function (node) { node.appendAjax({ url: "@Url.Action("treedata", "tree")", type: "GET", data: { "id": node.data.key, // Optional url arguments "mode": "all" }, error: function(node, XMLHttpRequest, textStatus, errorThrown) { } } }); }, //.... cut short for brevity I am embeding the initial tree state in the "children:" part. And the Ajax reading is being set up in the "onLazyRead:" part. My Ajax call is: public JsonResult TreeData(FormCollection form) { return GetTreeData(Request.QueryString["id"], Request.QueryString["uitype"]); } The GetTreeData() function returns Json(ITreeItem); I would recommend you use Firefox/Firebug and its "NET" function to see what is going and coming back. Hope that helps. A: I've just found Dynatree and I'm using it on my MVC project. Here's an example of how I did it. I decided to just put the data directly in the View like the basic example. My data is a list of cities within California, grouped by county. My controller simply passes a view model to my View and the view model has a CitiesAvailable property: public IEnumerable<City> CitiesAvailable { get; set; } My list of City objects is grabbed from the database (EF4) and the actual City object is the following: In my View I create a ul containing the list of counties and their cities (I'm using Razor but webforms should be easy enough to figure out): <div id="tree"> <ul id="treedata" style="display: none;"> @foreach (var county in Model.CitiesAvailable.Select(c => c.County).Distinct().OrderBy(c => c)) { <li data="icon: 'false'">@county <ul> @foreach (var city in Model.CitiesAvailable.Where(c => c.County == county).OrderBy(c => c.Name)) { <li data="icon: 'false'" id="@city.Id">@city.Name</li> } </ul> </li> } </ul> </div> Then in my JavaScript I use the following: $("#tree").dynatree({ checkbox: true, selectMode: 3, fx: { height: "toggle", duration: 200 } }); It works great! Here's a sample of the output with a few items checked: Let me know if anything doesn't make sense. Note, I use data="icon: 'false'" in my li elements because I don't want the icons. A: You can simply convert the object to json string, and send it to server as text this is the js code: var dict = $("#tree").dynatree("getTree").toDict(); var postData = JSON.stringify(dict["children"]); $.ajax({ type: "POST", url: "/UpdateServer/SaveUserTree", data: {tree:postData}, dataType: "html" }); And this is the controller code: [HttpPost] public void SaveUserTree(string tree = "") { HttpContext.Application["UserTree"] = tree; } You can send this string data back to client if (HttpContext.Application["UserTree"] != null) ViewBag.TreeData = new HtmlString(HttpContext.Application["UserTree"].ToString()); And finally, you can initial the tree, in the View with this data: var treeData= @(ViewBag.TreeData) $(function(){ // --- Initialize sample trees $("#tree").dynatree({ children: treeData }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7598621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I set the classpath in NetBeans? Can someone tell me where and how I set the classpath in NetBeans? I would like to add a .jar file. A: * *Right-click your Project. *Select Properties. *On the left-hand side click Libraries. *Under Compile tab - click Add Jar/Folder button. Or * *Expand your Project. *Right-click Libraries. *Select Add Jar/Folder. A: Maven The Answer by Bhesh Gurung is correct… unless your NetBeans project is Maven based. Dependency Under Maven, you add a "dependency". A dependency is a description of a library (its name & version number) you want to use from your code. Or a dependency could be a description of a library which another library needs ("depends on"). Maven automatically handles this chain, libraries that need other libraries that then need other libraries and so on. For the mathematical-minded, perhaps the phrase "Maven resolves the transitive dependencies" makes sense. Repository Maven gets this related-ness information, and the libraries themselves from a Maven repository. A repository is basically an online database and collection of download files (the dependency library). Easy to Use Adding a dependency to a Maven-based project is really quite easy. That is the whole point to Maven, to make managing dependent libraries easy and to make building them into your project easy. To get started with adding a dependency, see this Question, Adding dependencies in Maven Netbeans and my Answer with screenshot.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "46" }
Q: Open fails, fopen doesn't Whenever I use open I get the permission denied error. But when I use fopen it opens the file fine. What is wrong with my code? mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; char *filename = "dataread.txt"; rec = open(filename ,O_WRONLY | O_CREAT | O_TRUNC,mode); if(rec == -1) { perror("\nopen error 1:"); exit(1); } Error: open error 1:: Permission denied With fopen I don't get this error. A: I added an int rec=0; var declaration and the necessary includes files and then compiled your code. It runs with no errors as a normal user in my Fedora 15 laptop. Check the dir/file permissions you are running this on, the problems does not seem to be in the code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Alternatives for temporary tables in Oracle * *Create a temporary table inside a stored procedure, say '#Temp'. *Insert values into 'Temp' table using a select statement, eg. Insert Into #Temp Select * from Employees. *Now extract data from this Temp table, eg. Select * from #Temp where #Temp.Id = @id & so on. How to do this in Oracle inside a stored procedure? A: Create a global temporary table. CREATE GLOBAL TEMPORARY TABLE <your_table> ON COMMIT PRESERVE ROWS # If needed. Depends on your needs. AS SELECT <your_select_query>; You can then select from the table as needed for the duration of your procedure. http://www.oracle-base.com/articles/8i/TemporaryTables.php http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:15826034070548 A: What is the business problem you are trying to solve? It is exceptionally rare that you need to use temporary tables in Oracle. Why wouldn't you simply SELECT * FROM employees WHERE id = p_id_passed_in; In other databases, you often create temporary tables because readers block writers so you want to create a separate copy of the data in order to avoid blocking any other sessions. In Oracle, however, readers never block writers, so there is generally no need to save off a separate copy of the data. In other databases, you create temporary tables because you don't want to do dirty reads. Oracle, however, does not allow dirty reads. Multi-version read consistency means that Oracle will always show you the data as it existed when the query was started (or when the transaction started if you've set a transaction isolation level of serializable). So there is no need to create a temporary table to avoid dirty reads. If you really wanted to use temporary tables in Oracle, you would not create the table dynamically. You would create a global temporary table before you created the stored procedure. The table structure would be visible to all sessions but the data would be visible only to the session that inserted it. You would populate the temporary table in the procedure and then query the table. Something like CREATE GLOBAL TEMPORARY TABLE temp_emp ( empno number, ename varchar2(10), job varchar2(9), mgr number, sal number(7,2) ) ON COMMIT PRESERVE ROWS; CREATE OR REPLACE PROCEDURE populate_temp_emp AS BEGIN INSERT INTO temp_emp( empno, ename, job, mgr, sal ) SELECT empno, ename, job, mgr, sal FROM emp; END; / SQL> begin 2 populate_temp_emp; 3 end; 4 / PL/SQL procedure successfully completed. SQL> select * 2 from temp_emp; EMPNO ENAME JOB MGR SAL ---------- ---------- --------- ---------- ---------- 7623 PAV Dev 7369 smith CLERK 7902 800 7499 ALLEN SALESMAN 7698 1600 7521 WARD SALESMAN 7698 1250 7566 JONES MANAGER 7839 2975 7654 MARTIN SALESMAN 7698 1250 7698 BLAKE MANAGER 7839 2850 7782 CLARK MANAGER 7839 2450 7788 SCOTT ANALYST 7566 3000 7839 KING PRESIDENT 5000 7844 TURNER SALESMAN 7698 1500 7876 ADAMS CLERK 7788 1110 7900 SM0 CLERK 7698 950 7902 FORD ANALYST 7566 3000 7934 MILLER CLERK 7782 1300 1234 BAR 16 rows selected. As I said, though, it would be very unusual in Oracle to actually want to use a temporary table.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: added new boolean field to an existing django Mongoengine model, but after can not filter for this field First my django model was like this: class List(Document): owner = ReferenceField('User') name = StringField() users = ListField(ReferenceField('User')) created_at = DateTimeField(default=datetime.datetime.now) After I added a new filed is_cancelled and now it is like that: class List(Document): owner = ReferenceField('User') name = StringField() users = ListField(ReferenceField('User')) created_at = DateTimeField(default=datetime.datetime.now) is_cancelled = BooleanField(default = False) I use mongoengine for django mongodb ORM. But now when i want to make a filter query: List.objects.filter(is_cancelled=False) returns [] I make all is_cancelled fields to False with django object: for x in List.objects.all(): x.is_cancelled = False x.save() But I'm still getting an empty list for the query above. I'm looking a django objects' is_cancelled filed and I see is_cancelled = False l = List.objects.all()[0] l.is_cancelled False But when I look from mongodb shell. There is no filed as is_cancelled. db.list.find() { "_cls" : "List", "_id" : ObjectId("4e8451598ebfa80228000000"), "_types" : [ "List" ], "created_at" : ISODate("2011-09-29T16:24:28.781Z"), "name" : "listname", "users" : [ { "$ref" : "user", "$id" : ObjectId("4e79caf78ebfa80c00000001") }, { "$ref" : "user", "$id" : ObjectId("4e79e4df8ebfa80b64000001") }, { "$ref" : "user", "$id" : ObjectId("4e7aeb898ebfa80b64000001") }, { "$ref" : "user", "$id" : ObjectId("4e79ce028ebfa80c00000004") } ] } How can I fix this query A: Voila! This is my answer: https://github.com/hmarr/mongoengine/issues/282 There is a bug at the mongengine BooleanField with a value of False. But they have fixed it with this patch: https://github.com/hmarr/mongoengine/pull/283 A: It is because mongoDB is a schema-less database. Although you have defined the field is_canceled in your model, that does not mean all existing documents are going to be updated with this new field. Within a collection, each document is not required to follow the same structure. If you want the is_canceled field in each of your existing documents you will need to write an update script to iterate through each document in your collection and add that field. Otherwise, only new documents you create with this new model will contain the field is_canceled. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Too many navigation controllers? I think I'm doing something ridiculously wrong with my project. I'm making a project that basically is a set of view controllers with videos on some of them, images on the others. I created a mockup, but I think I'm pushing Navigation Controller too much doing what it's not supposed to be used for. Here is what I did: I created four view controllers and a navigation controller. The third view controller has a MPMoviePlayer as a subview. I remove it from the view on any transition from its super view controller, however it came to me that, if I'll have a hundred of these view controllers, being on the 100th of them means having 99 views unloaded. Isn't that a really sick problem or I'm freaking out without any reason? Because I don't really know how to do it the other way. Thank you. A: Are you moving strictly one-way, ie, only ever pushing view controllers and never popping them? This is pretty bad practice, although with proper memory management you could get a very large number of VCs in the stack before your app crashes. If you're jumping around between four VCs in a way that's not a back-and-forth stack (like a navigation controller) or using a global control like a Tab Bar, you're probably better off removing the previous view from its superview and replacing it with the new view. For example, in your app delegate: -(void)switchToView:(UIViewController*)newVC { if (self.currentVC!=nil) [self.currentVC.view removeFromSuperview]; self.currentVC = newVC; [self.window addSubview:newVC.view]; } A: A UIViewController will unload it's view when it needs to. If you were 100 levels deep you would only have a few views still loaded. That is why it is important to implement viewDidUnload and set your IBOutlets to nil.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FFMPEG progress bar in java Is there a way I can get the FFMPEG progress bar like this ffmpeg-progress bar in java or at least use the script shown in the link to work in my Java file? A: You can use the BSD-licensed JLine library to enable advanced console features. The class jline.Terminal allows you to clear and re-draw the current line of text.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Building a static version of Python on Ubuntu 11.04 After looking at a similar question, it appears that I am supposed to be able to build a static version of Python thusly: ./configure --disable-shared LDFLAGS="-static -static-libgcc" CPPFLAGS="-static" However, running make configured as above eventually barfs up some warnings and an error: gcc -pthread -static -static-libgcc -Xlinker -export-dynamic -o python \ Modules/python.o \ libpython2.7.a -lpthread -ldl -lutil -lm <SNIP> libpython2.7.a(posixmodule.o): In function `posix_initgroups': Python-2.7.2/./Modules/posixmodule.c:3981: warning: Using 'initgroups' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking /usr/bin/ld: dynamic STT_GNU_IFUNC symbol `strcmp' with pointer equality in `/usr/lib/x86_64-linux-gnu/gcc/x86_64-linux-gnu/4.5.2/../../../libc.a(strcmp.o)' can not be used when making an executable; recompile with -fPIE and relink with -pie collect2: ld returned 1 exit status I'm stuck. It appears to be asking me to recompile libc. I thought -static-libgcc would be enough, but apparently it is not. Does anyone know what is going on here, and how to achieve my goal of building a static python on Ubuntu 11.04?
{ "language": "en", "url": "https://stackoverflow.com/questions/7598643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: fullCalendar - addEventSource with the color option I have a function that dynamically adds events to the calendar. function AddEventSourceDetailed(act_id) { $('#calendar').fullCalendar('addEventSource', function (start, end, callback) { var startTime = Math.round($('#calendar').fullCalendar('getView').start.getTime() / 1000); var endTime = Math.round($('#calendar').fullCalendar('getView').end.getTime() / 1000); time = endTime - startTime; //alert(time); if (time <= 604800) { $.ajax({ type: 'POST', url: '/Employee/GetScheduleDetailedArray/', async: false, dataType: "json", data: { // our hypothetical feed requires UNIX timestamps start: Math.round(start.getTime() / 1000), end: Math.round(end.getTime() / 1000), id: '@Model.selectedUserId', act: act_id }, success: function (doc) { callback(doc); }, error: function (xhr, status, error) { document.appendChild(xhr.responseText); } }); //end ajax } else { callback(); } }); } The problem is I can't figure our how to assign a color to the event source when adding it this way. ====EDIT===== Okay I found a hackish way to change the inside background color of events, I use the eventAfterRender and it's element object to compare it to a list of events that I have colors associated with. I hope this will kind of help someone until I find out a better way $('#calendar').fullCalendar({ height: 600, width: 700, header: { right: 'prev,next today', center: 'title', left: 'month,agendaWeek,agendaDay' }, eventAfterRender: function (event, element, view) { for (x = 0; x < activityColors[0].length; x++) { if (event.id == activityColors[0][x]) { element.children().css({ "background-color": "#" + activityColors[1][x] }) } } } }); A: You can use: $('#calendar').fullCalendar( 'addEventSource', { url: "/url/goes/here", color: '#05ABBD' }); A: in your function, whats the a result of that ajax call? By what you have in code ( success:function (doc) {callback(doc);} ), I guess on success you are receiving array of events encoded in json, so only thing you need for adding colors is to define fields color, backgroundColor, borderColor, textColor in your server-side script for every event. Hope this helps. Jan EDIT: I also noticed that you are calling callback() function in else branch, which is really redundant. Without parameters, its pointless to call callback, because it will do nothing (callbacks parameter is array of events to be added to fullcalendar, so no paramater = no events to add = same as it wasnt even called).
{ "language": "en", "url": "https://stackoverflow.com/questions/7598644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using Utility flip as a menu for mulitple controllers So I'm fairly new to xcode, and I'm still trying to figure out how all the controllers work together. I'm currently writing an app that has multiple screens, like you would organize with a tabcontroller. However, i don't actually have room on my screen for the tab at the bottom. Looking around at the other templates, I found the utility application starter code. I really like how it just has the little i at the bottom and then flips around to an entirely different controller. Is it possible to use the flipController as a menu(with icons like the home screen), and flip back to any one of a number of controllers based on what was pressed? I know that if it's possible, It'd have to do with code in the delegator, but so far I haven't been able to find anything on the internet, and I haven't had any luck tinkering with it. Any help would be greatly appreciated. A: Switching UIViewControllers on a button tap? Yeah, I think iOS might be capable of such a feat! A cursory glance at the template for a Utility Application in Xcode shows three main classes, the app delegate, the main view controller, and a flipside view controller. In the app delegate, the root view controller for the window is instantiated and set when the application finishes launching. Something like this: MyRootViewController *myvc = [[MyRootViewController alloc] initWithNibName:@"MyRootView" bundle:nil]; self.window.rootViewController = myvc; [myvc release]; In MyRootViewController, you'll see a method, probably -(IBAction)showInfo:(id)sender, which instantiates and modally presents the flipside view controller. This message is sent by tapping a button, connected in the .xib file. MyFlipsideViewController *mfvc = [[MyFlipsideViewController alloc] initWithNibName:@"MyFlipsideView" bundle:nil]; mfvc.delegate = self; // by setting the root view controller as the delegate, // your flipside controller can send messages to MyRootViewController mfvc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; // set how the controller's view should be displayed [self presentModalViewController:mfvc animated:YES]; [mfvc release]; MyFlipSideViewController is presented, and its view is displayed modally on screen. To switch back, the flipside controller sends its delegate (MyRootViewController) the -(IBAction)flipsideViewControllerDidFinish:(id)sender message, informing it that it can flip the view back. In that method, MyFlipsideViewController is dismissed. There are probably tons of ways to implement the kind of application you describe (many way better than what I'm about to describe), but if you want to mimic the utility application template, you can make a root view controller which acts as a delegate to a series of other view controllers. It should have a method like -showInfo:(id)sender, although it would be nice if it could show different controllers based on the button pressed. One way you can do this is by giving each button a specific tag, then using a switch, like so: MyFlipsideViewController *controller = nil; switch ([sender tag]) { case 1: controller = [[MyFlipsideViewController alloc] initWithNibName:@"OneFlipsideView" bundle:nil]; break; case 2: controller = [[MyFlipsideViewController alloc] initWithNibName:@"AnotherFlipsideView" bundle:nil]; break; default: @throw [NSException exceptionWithName:@"Unrecognized object" reason:@"I don't know how to handle a button with that tag." userInfo:nil]; break; } controller.delegate = self; controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; [self presentModalViewController:controller animated:YES]; [controller release]; You can use MyFlipsideViewController with a variety of different views based on the button tag, or you can instantiate different controllers and present them--just make sure they have a delegate property which points at MyRootViewController. Moving between views is really the bread and butter of iOS programming. I personally recommend iOS Programming: The Big Nerd Ranch Guide--I think reading it will give you a very solid understanding of the MVC pattern in iOS programming. I'm no expert, though (as anyone reading the code above can tell), so I'd say trust the book over me. Especially when it comes to those release calls.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Commons email example hanging on send() I'm trying to get this example for the Apache Commons email library to work. Here is my code: SimpleEmail email = new SimpleEmail(); email.setHostName("smtp.gmail.com"); email.setSmtpPort(465); email.setAuthenticator(new DefaultAuthenticator("username@gmail.com", "password")); email.setTLS(true); try { email.setFrom("username@gmail.com"); email.setSubject("TestMail"); email.setMsg("This is a test mail ... :-)"); email.addTo("username@gmail.com"); System.out.println("Sending..."); email.send(); System.out.println("Email sent!"); } catch (Exception e) { System.out.println("Email not sent!"); e.printStackTrace(); } As you can see it's basically unchanged from the example, except I have to use port 465 instead of 587 because 587 causes a Connection refused exception (based on this question). Now this code is hanging on the email.send() line. The only output I get is: Sending... But no exceptions are thrown. Do I need to open a port in my firewall? (I might not be able to do that as I'm trying to do this from work). Thanks! Edit After a long time I get this exception: org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.gmail.com:465 ... Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1 A: Based on your edits and answer to my comment, you shouldn't look for your problems in Java code, but in the firewall or your network configuration. A: You need to set the following (because you are using SSL) Properties props = new Properties(); props.put("mail.smtp.auth", true); props.put("mail.smtp.starttls.enable", true); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.timeout" , "10000"); props.put("mail.smtp.connectiontimeout" , "10000"); props.put("mail.smtp.socketFactory.port", 465); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false");
{ "language": "en", "url": "https://stackoverflow.com/questions/7598650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: List layout issue inside a ScrollView I have a layout problem - my ScrollView does not fill the whole screen, instead - the bottom half of the screen is not used with the scroll (my list updates dynamicly) <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <EditText android:id="@+id/newRecipeIngredientEditTextId" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:hint="Ingredient info" android:layout_toLeftOf="@+id/naddIngredientButtonId"></EditText> <Button android:text="@string/addNew" android:layout_width="wrap_content" android:id="@+id/naddIngredientButtonId" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentRight="true"></Button> <ScrollView android:layout_height="match_parent" android:layout_width="match_parent" android:id="@+id/scrollView12" android:layout_below="@+id/newRecipeIngredientEditTextId" android:layout_alignParentLeft="true" android:layout_alignParentBottom="true"> <ListView android:layout_width="match_parent" android:id="@android:id/android:list" android:layout_height="match_parent"></ListView> </ScrollView> </RelativeLayout> A: Change RelativeLayouts width and height to Fill_Parent. And change ScrollView's Also
{ "language": "en", "url": "https://stackoverflow.com/questions/7598651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Which API is used for encryption of hibernation files on Windows? The following is quoted from the "Security improvements" section of this article. "In response to our public complaint regarding the missing API for encryption of Windows hibernation files, Microsoft began providing a public API for encryption of hibernation files on Windows Vista and later versions of Windows..." However, googling failed to reveal more information such as the name of the API. Perhaps I am googling on the wrong terms... Does anybody has any ideas? A: From IRP_MN_DEVICE_USAGE_NOTIFICATION System components send this IRP to ask the drivers for a device whether the device can support a special file. Special files include paging files, dump files, and hibernation files. If all the drivers for the device succeed the IRP, the system creates the special file. The system also sends this IRP to inform drivers that a special file has been removed from the device. Of course, this only matters if you write a Crash Dump Filter Driver like TrueCrypt and handle file system driver operations like IRP_MJ_READ/IRP_MJ_WRITE and encrypt the file data somehow. A: I'm pretty sure MS uses BitLocker to encrypt the system volume including system and hibernation files. http://technet.microsoft.com/en-us/library/cc734125%28WS.10%29.aspx The necessary file to include is called fveapi.dll
{ "language": "en", "url": "https://stackoverflow.com/questions/7598656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to catch create db signal from django I'm working in django project. I have 1 postgresql sql file that need to run only one time after db created. Built-in django signal not quite suit with my case. So I try to write custom django signal but I'm not sure how to start with this case. Does anyone has a good guide. ? :) A: The Django docs on signals have improved dramatically, so take a look there if you haven't already. The process is pretty simple. First create your signal (providing_args lets you specify the arguments that will get passed when you send your signal later): import django.dispatch my_signal = django.dispatch.Signal(providing_args=["first_arg", "second_arg"]) Second, create a receiver function: from django.dispatch import receiver @receiver(my_signal) def my_callback(sender, first_arg, second_arg, **kwargs): # do something Finally, send your signal wherever you like in your code (self as sender is only applicable within your model class. Otherwise, just pass a the model class name): my_signal.send(sender=self, first_arg='foo', second_arg='bar')
{ "language": "en", "url": "https://stackoverflow.com/questions/7598659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to create setup for excel addin? I have a created an excel addin application in vb.net using vs2010.The application is working fine while running from IDE. Now I want to create a setup for the application to install the same addin in other system. How can I do this? I created a setup project and added the dll of the addin and created setup file. When I installed it in other machine, installation was succesful. However I could not see the addin in excel when i opened it. Can someone help me on this? A: The list of Excel Add-ins displayed in the "Available Add-Ins" dialog is rebuilt at Excel startup. It's based on Excel built-in add-ins and 3rd party customer add-ins. The locations of the 3rd party add-ins, the ones you are interested in installing, are in two places; per user and per machine locations. The per machine location is used by all accounts on the PC, and that's located in <program files>\Microsoft Office\<Office version>\Library. The per user location is at <root drive:>\users\<user name>\AppData\Roaming\Microsoft\AddIns. If you install in the per-machine location, then the user would need admin rights to install there. There is also a 3rd addin location, that is previous addins that were manually loaded and stored in the user's XLB setting file. The XLB file is a binary file and not something that an installer would touch.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: htaccess: Redirect from subdomain.test.com/~user77 to www.testing.com I want to redirect from a temporary URI like http://subdomain.test.com/~user77/ to http://www.testing.com This is a temporary URI and points to the same webserver. All requests like http://subdomain.test.com/~user77/index.php http://subdomain.test.com/~user77/lib/javascript.js should be redirected to http://www.testing.com/index.php http://www.testing.com/lib/javascript.js How can I achieve this? I have the following htaccess code RewriteCond %{HTTP_HOST} ^http://subdomain.test.com/~user77/$ [NC] RewriteRule ^(.*)$ http://www.testing.com/$1 [R=301,L] But it doesn't seem to work. If I input subdomain.test.com/~user77 I see the same URL (subdomain.test.com/~user77). What I'm doing wrong? UPDATE: Full htaccess: ##### # # Example .htaccess file for TYPO3 CMS - for use with Apache Webserver # # This file includes settings for the following configuration options: # # - Compression via TYPO3 # - Settings for mod_rewrite (URL-Rewriting) # - PHP optimisation # - Miscellaneous # # If you want to use it, you have to copy it to the root folder of your TYPO3 installation (if its # not there already) and rename it to '.htaccess'. To make .htaccess files work, you might need to # adjust the 'AllowOverride' directive in your Apache configuration file. # # IMPORTANT: You may need to change this file depending on your TYPO3 installation! # # Lines starting with a # are treated as comment and ignored by the web server. # # You should change every occurance of TYPO3root/ to the location where you have your website in. # For example: # If you have your website located at http://mysite.com/ # then your TYPO3root/ is just empty (remove 'TYPO3root/') # If you have your website located at http://mysite.com/some/path/ # then your TYPO3root/ is some/path/ (search and replace) # # You can also use this configuration in your httpd.conf, but then you have to modify some lines, # see the comments (search for 'httpd.conf') # # Questions about this file go to the matching Install mailing list, see # http://typo3.org/documentation/mailing-lists/ # #### ### Begin: Compression via TYPO3 ### # Compressing resource files will save bandwidth and so improve loading speed especially for users # with slower internet connections. TYPO3 can compress the .js and .css files for you. # 1) Uncomment the following lines and # 2) Set $TYPO3_CONF_VARS['BE']['compressionLevel'] = '9' #<FilesMatch "\.js\.gzip$"> # AddType "text/javascript" .gzip #</FilesMatch> #<FilesMatch "\.css\.gzip$"> # AddType "text/css" .gzip #</FilesMatch> #AddEncoding gzip .gzip ### End: Compression via TYPO3 ### ### Begin: Browser caching of ressource files ### # Enable long browser caching for JavaScript and CSS files. # This affects Frontend and Backend and increases performance. # You can also add other file extensions (like gif, png, jpg), if you want them to be longer cached, too. <FilesMatch "\.(js|css)$"> <IfModule mod_expires.c> ExpiresActive on ExpiresDefault "access plus 7 days" </IfModule> FileETag MTime Size </FilesMatch> ### End: Browser caching of ressource files ### ### Begin: Settings for mod_rewrite ### # You need rewriting, if you use a URL-Rewriting extension (RealURL, CoolUri, SimulateStatic). <IfModule mod_rewrite.c> # Enable URL rewriting RewriteEngine On # Change this path, if your TYPO3 installation is located in a subdirectory of the website root. #RewriteBase / # Rule for versioned static files, configured through: # - $TYPO3_CONF_VARS['BE']['versionNumberInFilename'] # - $TYPO3_CONF_VARS['FE']['versionNumberInFilename'] # IMPORTANT: This rule has to be the very first RewriteCond in order to work! RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.+)\.(\d+)\.(php|js|css|png|jpg|gif|gzip)$ $1.$3 [L] # Stop rewrite processing, if we are in the typo3/ directory. # For httpd.conf, use this line instead of the next one: # RewriteRule ^/TYPO3root/(typo3/|t3lib/|fileadmin/|typo3conf/|typo3temp/|uploads/|favicon\.ico) - [L] RewriteRule ^(typo3/|t3lib/|fileadmin/|typo3conf/|typo3temp/|uploads/|favicon\.ico) - [L] # Redirect http://example.com/typo3 to http://example.com/typo3/index_re.php and stop the rewrite processing. # For httpd.conf, use this line instead of the next one: # RewriteRule ^/TYPO3root/typo3$ /TYPO3root/typo3/index.php [L] RewriteRule ^typo3$ typo3/index_re.php [L] # If the file/symlink/directory does not exist => Redirect to index.php. # For httpd.conf, you need to prefix each '%{REQUEST_FILENAME}' with '%{DOCUMENT_ROOT}'. RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-l # Main URL rewriting. # For httpd.conf, use this line instead of the next one: # RewriteRule .* /TYPO3root/index.php [L] RewriteRule .* index.php [L] </IfModule> ### End: Settings for mod_rewrite ### ### Begin: PHP optimisation ### # If you do not change the following settings, the default values will be used. # TYPO3 works fine with register_globals turned off. # This is highly recommended, if your web server has it turned on. #php_flag register_globals off ### End: PHP optimisation ### ### Begin: Miscellaneous ### # Make sure that directory listings are disabled. #Options -Indexes ### End: Miscellaneous ### # Add your own rules here. # ... RewriteCond %{HTTP_HOST} ^http://subdomain.test.com/$ [NC] RewriteRule ^~user77/(.*)$ http://www.testing.com/$1 [R=301,L] A: Try the following: RewriteCond %{HTTP_HOST} ^http://subdomain.test.com/$ [NC] RewriteRule ^~user77/(.*)$ http://www.testing.com/$1 [R=301,L] A: You already have Rewrite Rules further up for your TYPO3 software. I would try testing by tempoarly removing those rules to see if you are even getting to the lines you are placing at the bottom. You can test the redirects at http://www.internetofficer.com/seo-tool/redirect-check/
{ "language": "en", "url": "https://stackoverflow.com/questions/7598668", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: adding a web form aspx page to WCF project i need to build a project that has a WCF .svc service and some web pages in the same c# project. Is there any problem in doing this? if I create a project of type WCF project using Visual studio 2010, it lets me add web forms to it. Once I publish to IIS, i should be able to hit the .svc url and .aspx urls seamlessly under the same root url. Any problem in doing this in the long run? A: No, no problems. This ought to work. If you want to use MVC then it's probably better to start from that template and add SVC components. Do think about authentication and authorization upfront.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Scan a specific div and show the 3 most used words Here is my markup: <body> <div id="headbox"> <p>Whatever...</p> </div> <div id="feed"> <div> <p>I hate cats</p> </div> <div> <p>I like cats</p> </div> <div> <p>I like cats</p> </div> <div> <p>I like cats</p> </div> </div> </body> The deal is I need a script that counts all words which appear in the <div id="feed">. The output should be wrapped in <p> tags or <span> tags. <h3>The top 3 used words in this feed:</h3> 1.&nbsp;<p>cats</p>&nbsp;4x 2.&nbsp;<p>like</p>&nbsp;3x 3.&nbsp;<p>hate</p>&nbsp;1x This would be the output. As you can see the word (or better the letter) I was not considered. Every word under 3 letters will be not considered by the counting. A: Just loop through the innerHTMLs, split the text on spaces, and use each value of the resulting array to add to or update a master array indexed by the words found with values being the counts of the words. A: Split the inner text of the target element by whitespace, count the word frequency, sort by most frequent, and format the top 3 per your requirements. Something like this (untested): var getMostFrequentWords = function(words) { var freq={}, freqArr=[], i; // Map each word to its frequency in "freq". for (i=0; i<words.length; i++) { freq[words[i]] = (freq[words[i]]||0) + 1; } // Sort from most to least frequent. for (i in freq) freqArr.push([i, freq[i]]); return freqArr.sort(function(a,b) { return b[1] - a[1]; }); }; var words = $('#feed').get(0).innerText.split(/\s+/); var mostUsed = getMostFrequentWords(words); // Now you can prepare "mostUsed.slice(0,3)" as the top 3 words/count. You'll need to modify it to reject words shorter than 3 characters but you get the idea. A: var text = document.getElementById('myDiv').textContent.split(' '); var words = {}; text.forEach(function(n, i, ary){ if(n.length > 3) { words[n] = (words[n] || 0) + 1; } }); That's what I would do to sort the words. And in the HTML somewhere I will have an ol element for auto-numbering var ol = document.getElementById('myOl'); var sorted_words = []; for(var i in words) if(words.hasOwnProperty(i) { sorted_words.push([i, words[i]]); } sorted_words.sort(function(a, b){ return b[0] - a[0]; }) .reverse() .slice(0, 3) .forEach(function(n, i, ary){ var li = document.createElement('li') .appendChild(document.createElement('p')) .textContent = n[1] + " " + n[0] + "x"; ol.appendChild(ul); }); Something like this should work...
{ "language": "en", "url": "https://stackoverflow.com/questions/7598671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Dimension of a 1 x m Matrix? R suprises me almost every day again and again: m <- matrix( 1:6, ncol=2 ) while( dim(m)[1] > 0 ){ print(m); m <- m[-1,] } gives: [,1] [,2] [1,] 1 4 [2,] 2 5 [3,] 3 6 [,1] [,2] [1,] 2 5 [2,] 3 6 Error in while (dim(m)[1] > 0) { : argument is of length zero Does R has a problem with 1xn matrices or where is my mistake? > nrow( m[-c(2,3), ] ) NULL > dim( m[-c(2,3), ] ) NULL > m[-c(2,3), ][,1] Error in m[-c(2, 3), ][, 1] : incorrect number of dimensions > str( m[-c(2,3), ] ) int [1:2] 1 4 Any idea how to easily fix the initial example, which is close to my actual problem? BTW: This loop is the bottleneck of my algorithm. Hence, efficient solutions are appreciated. Many thanks! A: The default behaviour of [ subsetting is to convert to a simpler structure, if applicable. In other words, once you subset to a 1xn matrix, the object gets converted to a vector. To change this behaviour, use the drop=FALSE argument to [: m <- matrix( 1:6, ncol=2 ) while( dim(m)[1] > 0 ){ print(m); m <- m[-1, , drop=FALSE] } [,1] [,2] [1,] 1 4 [2,] 2 5 [3,] 3 6 [,1] [,2] [1,] 2 5 [2,] 3 6 [,1] [,2] [1,] 3 6 For more information, see ?"["
{ "language": "en", "url": "https://stackoverflow.com/questions/7598674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: use controller method from model class in cakephp In my cakephp project, I use afterSave() method of a model class. In this method, I want to call another method that is located in app_controller file. class MyModel extends AppModel { var $name = 'MyModel'; function afterSave($created) { $this->MyController->updateData(); } } Here updateData() is located in app_controller file, which is extended by MyController controller. The above code does not work, so how can i actually call updateData() in this case.. Please guide. Thanks A: This is strongly NOT recommended but it can be done anyway... You should try as deizel says and move that method to AppModel or any other particular model... you may use this function App::import() check the book here to see how to use it in your example: class MyModel extends AppModel { var $name = 'MyModel'; function afterSave($created) { App::import('Controller', 'My'); $something = new MyController; $something->updateData(); } } This is the correct way to load a class inside another place where it shouldn't be... Still you may use include or required and create an instance of the class since this is php.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can I use an OAuth2 service in a unattended workflow? The 'flow' for OAuth2, involves getting the user to say 'yes this is OK'. The token that comes back is temporary. But I'm trying to create a unattended service. Will the refresh token always work? I get the feeling that it too is going expire. A: Adrian, This depends on who is implementing OAuth2. In the description of the refresh token, the expiry is not discussed as part of the specification. The spec later goes on to state somewhat ambiguously that a value error of invalid_grant can be returned if: The provided authorization grant (e.g. authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client. This would seem to imply that it is possible for a refresh token to expire. The document also mentions that it is possible to exchange "credentials with a long-lived access token or refresh token", thus grouping them into the same expiry class. The latest version of the spec can be found at: https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2 As for the Google specific implementation Refresh tokens are valid until the user revokes access. The refresh token will be valid for all time, with the only exception coming when the user revokes that permission. For Google OAuth2, a user can revoke permission either through a web GUI or using an OAuth revoke endpoint.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JSTree: Dynamically adding Node-Array as children to a Node I am using XML data plugin to load initial JSTree. Is there a way to add a whole different tree as children from XML via an Ajax call to one of the Child-Nodes? The create_node allows to add one node at a time. Any help would be great. A: You can use ajax call to 'add' data to a node. Please read about ajax config section * *Make its status close so the ajax will be called. *Then on the server side you return as much data as you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jqGrid pager stopped working I've been experimenting with jqGrid 4.1.2 the last couple of days, activating more and more of it's built in functionality along the way. Somewhere along the way the pager stopped working, and I cannot figure out what is wrong. When the grid loads I can see the data for the first page fine, but when I switch pages the data remains the same. Only the counter changes. If I select 100 in the number of rows dropdown-list, I can see all data. I've compared to the examples at http://www.trirand.com/blog/jqgrid/jqgrid.html and everything seems to match, but I confess I'm not the best JavaScript coder there is. Here's the offending code: <script type="text/javascript" language="javascript"> jQuery(document).ready(function() { jQuery("#testgrid").jqGrid({ url:'/Main/DynamicGridData/', mtype:'POST', datatype:'json', colNames: [ 'CustomerId', 'RecordStartUtc', 'RecordEndUtc', 'Id', 'Name', 'Status', 'AudioTitle', 'ServerId', 'ServerName', 'ApplicationInstanceId', 'ApplicationInstanceName', 'ApplicationName', 'ChannelId', 'ChannelFullName', ], colModel: [ { name: 'CustomerId', index: 'CustomerId', width: 0, align: 'left' }, { name: 'RecordStartUtc', index: 'RecordStartUtc', width: 0, align: 'left' }, { name: 'RecordEndUtc', index: 'RecordEndUtc', width: 0, align: 'left' }, { name: 'Id', index: 'Id', width: 0, align: 'left' }, { name: 'Name', index: 'Name', width: 0, align: 'left' }, { name: 'Status', index: 'Status', width: 0, align: 'left' }, { name: 'AudioTitle', index: 'AudioTitle', width: 0, align: 'left' }, { name: 'ServerId', index: 'ServerId', width: 0, align: 'left' }, { name: 'ServerName', index: 'ServerName', width: 0, align: 'left' }, { name: 'ApplicationInstanceId', index: 'ApplicationInstanceId', width: 0, align: 'left' }, { name: 'ApplicationInstanceName', index: 'ApplicationInstanceName', width: 0, align: 'left' }, { name: 'ApplicationName', index: 'ApplicationName', width: 0, align: 'left' }, { name: 'ChannelId', index: 'ChannelId', width: 0, align: 'left' }, { name: 'ChannelFullName', index: 'ChannelFullName', width: 0, align: 'left' }, ], pager:'#gridpager', rowNum:25, rowList:[25,50,75,100], sortname:'Id', sortorder:'Asc', viewrecords:true, imgpath:'/Content/themes/base/images', caption:'Test Grid', autowidth:true, width:'100%', height:'100%', hoverrows:false }); jQuery("#testgrid").jqGrid( 'navGrid','#gridpager', {view:true,edit:false,add:false,del:false},{},{},{}, {multipleSearch:true,multipleGroup:false},{closeOnEscape:true} ); }); </script> <table id="testgrid"></table> <div id="gridpager"></div> Thanks in advance, // Linus A: Not in a place to test your code but try changing your "sortorder" value 'Asc' to all lower case. If you are implementing server side paging then add this property: loadonce: false; ref: http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options Also test on your server side code if the request is coming in for the second page at all!
{ "language": "en", "url": "https://stackoverflow.com/questions/7598684", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JNA arrays and Pointer I'm working on a project at the moment that requires me to receive a call in Java from a C library. Basically I call a C function that takes a function pointer, the C function then uses the function pointer as a callback. I'm using JNA to pass a Java object (I'll call it the Callback object from now on) as the callback function. The callback object has a single method that receives a C structure (called Frame) that contains a 16 element byte array as well as other variables. I've wrapped this structure in a Java class in the standard JNA way, like this: class Frame extends Structure { public short port; public short flags; public Pointer name // this is a pointer to the byte array public int rateDivisor; } The callback mechanism works fine! The callback object receives a Frame object from C, but when I try to get the byte array from the Pointer using name.getByteArray(0, 16) the application crashes with an Access Violation Exception. However, if I replace the Pointer with a byte array: class Frame extends Structure { public short port; public short flags; public byte[] name = new byte[16]; public int rateDivisor; } Then the code works fine! There's a good reason why I don't want to use this code however. Every time I call the function the returned Frame is actually the same object (it's just being reused) but the byte array is a new object. This callback function is being called many times a second which causes the garbage collector to goes crazy gobbling up thousands of temporary arrays. This project is performance critical so I really don't want any temporary objects in this part of the application. My guess is that by using a byte array in the Frame class I'm causing JNA to create a new copy of the C byte array. What I want to do is have a pointer to the C byte array therefore removing the need to copy the data, hence the experimentation with JNA Pointer. My question is why can't I get the byte array from the Pointer? Any help would be much appreciated :) (Note: The thing that makes this even more difficult is that I don't have access to the C source code!!) A: The reason is probably as simple as that : name is not a pointer in the C structure counterpart. Let me show you two examples : C: typedef struct{ char * name; }MyCStruct; maps to Java : class MyJStruct extends Structure{ Pointer name; } But in this other scenario (in which I think you got yourself into): C: typedef struct{ char name[16]; }MyCStruct; maps to Java : class MyJStruct extends Structure{ byte[] name = new byte[16]; } In the first case the C structure holds a pointer and it's sizeof is the size of a pointer (4 or 8Bytes depending on 32/64bits), in the second case it holds the whole array which mean it's size is 16 Bytes. This explains the difference between the two Java mappings : JNA needs to know how to read the structure fields and it explains too why you get an error while calling name.getByteArray(0, 16) as this exectute the following : * *take the first 4 Bytes following the flags field *treat it as a pointer *go into ram to the pointed adress and read 16 Bytes Which crashed since the memory zone pointed is probably out of program reach. You can check it yourself in C : if sizeof(struct Frame) is 24 then the struct holds the whole array if it's 12 (or 16) then it holds a 32 bits pointer (or a 64 bits pointer) Official documentation about this matter is pretty clear but hard to find, so here you go : http://twall.github.com/jna/3.3.0/javadoc/overview-summary.html you'll find about it under "Nested arrays" and I really encourage you to read the section just below "Variable-sized structures" hope this helps regards A: Change the input parameter of your callback to Pointer. Maintain your own private Pointer->Frame map (with or without weak references), and only create a new Frame based on the input pointer if there isn't one already. e.g. Map frames = new HashMap<Pointer,Frame>(); void callback(Pointer p) { Frame f = frames.get(p); if (f == null) { f = new Frame(p); frames.put(p, f); } // do whatever... } A: (New answer to meet StackTrace expectations ; see comment to my previous answer) Well I'm not sure if there is a nice and clean way to do it ... hence I'll point out a nice game called the Memory and Pointer game Keep in mind you might need it these ways (C) : Frame nativeLibFunc(...); //1 Frame * nativeLibFunc(...); //2 void nativeLibFunc(Frame f); //3 void nativeLibFunc(Frame * fptr);//4 The worst case in my opinion will be the third since you can't do it without the normal mapping explained before. Next worst case is the first since you won't get a location in RAM but the direct result at the top of the stack, hence reading it requires you to trick JNA to be able to fetch the Pointer and read what comes after the memory zone you want to skip (Java): class MyMicroFrame extends Structure { public short port; public short flags; //public byte[] name = new byte[16]; ==> commented out, ignored //public int rateDivisor; ==> commented out, read manually, see below } //... MyMicroFrame mmf = NativeLib.INSTANCE.nativeLibFunc(...); int rateDivisor = mmf.getPointer().getInt(20); I think you got the idea. if your structure is bigger, just split it in small parts avoiding the zones you want to skip an re-join them by manually navigating in the memory pointed by the first part. Things to keep in mind while working this way : * *Pointer size 32/64 bits -- 4 or 8 Bytes see com.sun.jna.Native.POINTER_SIZE *Structure alignement which I've not checked on this answer
{ "language": "en", "url": "https://stackoverflow.com/questions/7598685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Oracle SQL create duplicated rows with join I would like to create duplicated rows as an output: first I would like to have the row, and then the same row again joined with another table, like this: table A with fieldA (and lots of others) table B with fieldB (and lots of others) and the output: fieldA1 (and all the fileds from tableA) fieldA1 fieldB1 (and all the fields from tableA and tableB joined) filedA1 fieldB2 fieldA2 fieldA2 fieldB8 filedA2 fieldB9 . . . I was thinking about using union, but then I would have to duplicate the very complicated select of tableA to get the rows of tableA and tableB (tableA is union of other tables, I just simplified it for the question). Is there any 'cleaner' solution to this? I know it is an unusual question, so I would appriciate any thougts or ideas. Thank you very much in advance! A: Modify Benoit's answer to use a common table expression: WITH A as ( your select for "A" ) SELECT A.fieldA, B.fieldB, A.*, B.* FROM A LEFT JOIN B ON 1 = 0 UNION ALL SELECT A.fieldA, B.fieldB, A.*, B.* FROM A JOIN B ON (join condition) A: Use: SELECT A.*, B.* FROM A LEFT JOIN B ON 1 = 0 UNION ALL SELECT A.*, B.* FROM A INNER JOIN B ON (join condition)
{ "language": "en", "url": "https://stackoverflow.com/questions/7598690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java, convert(cast) Serializable objects to other objects I'm using Session.save() method (in Hibernate) to persist my entity objects which returns an object of type java.io.Serializable. The returned value is the generated primary key for the entity. The generated primary key is of type long (or bigint). The question is that: How can I convert or cast the returned value to long? Serializable result = session.save(myEntityObject); //This line of code fails. long r = (long)result; A: Try casting the result (since it's not a primitive) to Long instead of long. Long r = (Long)result; long longValue = r.longValue(); A: Try long r = Long.valueOf(String.valueOf(result)).longValue(); A: Have you tried using a debugger and breaking at that line to see what "result" is exactly? It could be BigDecimal or Long or ... Alternatively, cant you just call the primary key getter method on the object - I'd have hoped it would be set by that point. HTH, Chris A: Try using long r = ((Long) result).getLong() instead. A: You should have specified the type of error you are getting ! Anyways this should work.. long r = Long.valueOf(result) A: Above answer not worked for me. I misunderstood the function of statelessSession.get(...). The second parameter should be the primitive value of the primary-key if it is a non-composte key. If the Entity has a composite key you should pass the entity itself (with filled pk) as second argument. I was confused, because I thought that I need to pass always an entity as second argument to statelessSession.get (because it works for multi-key-entitys).
{ "language": "en", "url": "https://stackoverflow.com/questions/7598692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: android map refresh button/menu option? May I know how to implement button or menu option to get immediate update of user location on mapview, something like refresh button? Thank you very much! A: You may implement android.location.LocationListener interface This will keep track of the User's Current Location. On a click of mouse you may invoke last location from this Listener. LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1l,100,locationListener);
{ "language": "en", "url": "https://stackoverflow.com/questions/7598699", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding ViewController for MainWindow I am new to iOS programming, just to warn you! I'm using Xcode 4.2 to build a simple app. I have followed this Tutorial to create a MainWindow.xib after creating and empty application. I want to show a scrollView where I can scroll horizontally between 2 pages (which I have done in tutorials, and therefore not worried about). What I do need help with is this: as far as I understand, I would need to do the logic for my MainWindow.xib in the didFinishLaunchingWithOptions method. I want to know how to abstract the code into another viewController. I would also like to know if this is the correct method to handle the logic, or if I'm misunderstanding something here (most likely). A: There's a particularly easy to follow document by Apple about adding a view controller to the main window. Read it here!
{ "language": "en", "url": "https://stackoverflow.com/questions/7598700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jasper reports data filtering I'm working with jasper reports, supplying data through the JRMapCollectionDataSource. To be specific, each row is smth like this: {"id"->"21552", "name"->"", "date"->"22.03.2013"} Now I need to include to the report only those records, where id is greater than 10, for instance. What shall I do? I've discovered filterexpression tag, but it only works with subdata sets. Then, how I can apply it to the main dataset? When I'm trying to put filterexpression inside the jasperReport tag, iReports fails with error: thanks a lot for your response, I've tried to do so. I report gives me exception:org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'property'. One of '{"http://jasperreports.sourceforge.net/jasperreports":group, "http://jasperreports.sourceforge.net/jasperreports":background, "http://jasperreports.sourceforge.net/jasperreports":title, "http://jasperreports.sourceforge.net/jasperreports":pageHeader, "http://jasperreports.sourceforge.net/jasperreports":columnHeader, "http://jasperreports.sourceforge.net/jasperreports":detail, "http://jasperreports.sourceforge.net/jasperreports":columnFooter, "http://jasperreports.sourceforge.net/jasperreports":pageFooter, "http://jasperreports.sourceforge.net/jasperreports":lastPageFooter, "http://jasperreports.sourceforge.net/jasperreports":summary, "http://jasperreports.sourceforge.net/jasperreports":noData}' is expected. A: Filter expressions are not limited to sub-datasets. Simply put the filterExpression tag inside the jasperReport tag and it will be applied to the main dataset. Placement is important, it seems. The filter expression must come before any content, but after the fields are declared.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Binary run length encoding I have a web form, for the contents of which I would like to generate a short representation in Base64. The form, among other things, contains a list of 264 binary values, the greater part of which are going to be 0 at any single time. (They represent regions on a geographical map). Even in Base64, this 264-bit number generates a long, intimidating string. I want to implement run-length encoding, as efficiently as possible. Can you help me with this? I've googled binary RLE, but have found nothing of use. What I've tried this far - running RLE on the binary string using decimal counts and "A" as a separator denoting a change between 0 and 1, then converting the result from base 11 to base 64. For example: 00000000001111111000000010000000000000000000000001111111110001111010101000000000000000000000000000000000000111111111110111000000000000111111100000001000000000000000000000000111111111000111101010100000000000000000000000000000000000011111111111011100 becomes 10A5A5AA22A7A1A2AAAAAAA34A9AA1A10A5A5AA22A7A1A2AAAAAAA34A9AA1A which in turn becomes CNnbr/FxkgbbOw0LNAKgk65P8SdvaTG+t74o or, in base 62, 6imo7zq1pqr2mqglTHzXwJRAksm7fvHZHWQK It's better, but I still can't help but doubt if I'm doing something wrong - is using the digit "A" as a separator is the best way to do this? And another update: Thanks to @comingstorm, I have shortened the compressed string some more. ILHHASCAASBYwwccDASYgAEgWDI= As I mentioned it in the comments, real usage cases would generally result in an even shorter string. A: Since you're coding bits, you probably want to use a bit-based RLE instead of a byte-based one. In this context, you should consider Elias gamma coding (or some variant thereof) to efficiently encode your run lengths. A reasonable first approximation for your encoding format might be: * *first bit = same as the first bit of the uncompressed string (to set initial polarity) *remaining bits: Elias coded lengths of successive bit runs (alternating 1 and 0) Since you know how many bits are in your uncompressed string, you don't need a termination code; you can just add any necessary binary padding as arbitrary bits. Note that it is always possible for the run-length "compression" to expand your bit string; if you're concerned about this, you can add another initial bit to indicate whether your data is in compressed or uncompressed format, limiting your compression overhead to 1 bit. A: 264 bit, that are just 33 byte, and that are in base64 just 44 byte. I think this (very small) amount of information is hardly compressable. The sparse representation nulvinge refers too just stores the non zero elements and their values (as you have just 0/1), i.e. in your case just the index of the non zero bits. But as you have 264 possible bits - you need 9 bits for the index, which means, in case you have more than 29 non zero entries, you need already more than original. Maybe your question is formulated wrong, but I dont see how 264 bits can lead to an intimidating base64 string (How do you generate it - maybe you translate not the 264 bits, but 264 ASCIIs chars (with the value 0 and 1) - that would explain your long result string?). A: An alternative that I think is more what you want is a sparse matrix: http://en.wikipedia.org/wiki/Sparse_matrix
{ "language": "en", "url": "https://stackoverflow.com/questions/7598705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Are there "tagged" collections in Java? Are there "tagged" collections in Java? To clarify, I want to essentially classify each element in the list with some sort of Object (e.g. a String) so I can reference different objects in the list by a tag that I specify, not by Object type or element contents. EDIT: A HashMap will not work as the order of the items in the list is also deemed to be important. My understanding is that a HashMap is not practical when the order of the list matters in some way. If I am incorrect on this matter, by all means please correct me. A: You're looking for a Map. This data structure maps keys to values. A: if each key in a Map maps to a Set of objects, you'll be able to easily look up every object with a particular tag(key) A: No, as far as I know there are no "tagged" collections in the standard Java libraries. But you could use a Map<Tag,Set<String>> to tag strings. A: You could use a map Map<String, Object> = new HashMap<String, Object>(); You can replace String with whatever you want. The one problem you might run into though, is if you want to categorize multiple objects with the same "tag". For instance, a "Cat" tag might apply to multiple, unique cat objects and a hashMap would only let you have one Cat object pointed to by the "Cat" tag. If that's what you want to do (multiple objects pointed to by one tag), you will need to declare the map as: Map<String, List<Object>> = new HashMap<String, List<Object>>(); That will create a HashMap holding a list for each object so you can have multiple objects pointed to by one tag. A: If you're not restricted to what's in the JDK, consider use of Guava Multimaps. They provide pre-built support for a map of sets. A: Perhaps a Map is what you need A: This is not detailed enough. We don't know if: - multiple tags per item are allowed - multiple items per tag are allowed I'm going to go for the widest solution, where both of these are true. First thing you need is your Tag class (I suggest an enum) public enum Tag { TAG1, TAG2, TAG3; // add your tags here } Then your collection will be a Map where the key is your object, and the value your list of tags for each object. Map<Object, List<Tag>> items = new HashMap<Object, List<Tag>>(); Of course, you can replace "Tag" with a String, if you want to allow any tag and not just known tags. And depending what you want to do with your collection, you may want to reverse it: Map<Tag, List<Object>> = new HashMap<Tag, List<Object>>(); I suggest first writing your test cases (unit-tests) listing your specifications, and the design of your collection will appear organically from them (TDD). A: If order is important then use a LinkedHashMap. A: See SortedMap and TreeMap. A: sounds like you want a hashmap
{ "language": "en", "url": "https://stackoverflow.com/questions/7598706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SlimDX Line.GLLines what it does? What is this property of calss line in slimdx? GLLines = true / false This is class that I'm talking about: http://slimdx.org/docs/#T_SlimDX_Direct3D9_Line
{ "language": "en", "url": "https://stackoverflow.com/questions/7598708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery datepicker - defaultDate (dynamically) from another datepicker I have two datepickers at the moment, one for a start date, and another for an end date. When you select the first date, I'd like the default value of the second datepicker to be set to the same date. If I use the setDate it works and sets the value just fine, but the default value won't change - if I set the defaultDate when the datepicker is loaded, it works, but if I try to set it on the fly it doesn't. Here's my code: if($('#startDate').val().length == 10 && $("#endDate").val().length != 10) { $("#endDate").datepicker("defaultDate", $("#startDate").datepicker("getDate")); } (edit) for clarification, I don't want to set the date - the user needs to do that, but I'd like the datepicker to go straight to the same date as the start date, to save them having to trawl through numerous pages. Here's the (kinda) working code: http://jsfiddle.net/c8H5y/ Any suggestions would be very welcome, thank you! A: This should do it: $("#dep_date").datepicker({ dateFormat: 'dd/mm/yy', onSelect: function(dateText, inst) { var date = $.datepicker.parseDate('dd/mm/yy', dateText); var $ret_date = $("#ret_date"); $ret_date.datepicker("option", "defaultDate", date); } }); $("#ret_date").datepicker({ dateFormat: 'dd/mm/yy', }); jsFiddle
{ "language": "en", "url": "https://stackoverflow.com/questions/7598710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Extending ListView onTouchListener I don't know if I simply couldn't find the class, but I need to do something more with the TouchEvent on a ListView. I tried creating another OnTouchListener but by setting it on the ListView all the other functionalities are gone. I tried finding the old listener and then simply repass the touch event to it, but there is no getOnTouchListener method... How would I accomplish this task? Can I add another touch listener? Can I intercept the event and repass it afterwards? Thanks !
{ "language": "en", "url": "https://stackoverflow.com/questions/7598713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to know where to publish if user account has more than one profile this may be simple, but I guess it isn't, and really Facebook docs are not really useful since they aren't translate to my mother language, making hard to achieve my goal. ok, I have a script to enable my webapp to post to my feed on Facebook, but I've a personal feed, a app page and a test page. How do I tell my script, based on login that I want to post on my test page and not on my personal profile? this is the code I'm using to login var appID = 'MY_APP_ID'; var path = 'https://www.facebook.com/dialog/oauth?'; var queryParams = ['client_id=' + appID, 'redirect_uri=' + dominio, 'response_type=token']; var query = queryParams.join('&'); var url = path + query; window.open(url); // FB.init({appId: appID, status: true, cookie: true, xfbml: true}); // var accessToken = ""; FB.Event.subscribe('auth.login', function(response) { if (response.session) { accessToken = response.session.access_token; console.log(accessToken); } else { console.log(response); } login(); }); FB.Event.subscribe('auth.logout', function(response) { document.getElementById('login').innerHTML = ""; document.getElementById('login').style.display = "none"; }); FB.getLoginStatus(function(response) { if (response.session) { accessToken = response.session.access_token; console.log(response.session); } else { console.log(response); } login(); }); function login() { FB.api('/me/accounts?access_token='+accessToken+'', function(response) { console.log(response); if(response.name) { document.getElementById('login').style.display = "block"; document.getElementById('login').innerHTML = "Ligado ao Facebook como "+response.name; } }); $('body').criar_paineis_edicao(accessToken); } and this one to actually publish if(accessToken) { console.log("com token"); FB.api('/me/feed?access_token='+accessToken+'', 'post', parametros, function(response) { if (!response || response.error) { $.each(response.error, function(name, value) { alert(value); }); window.location.reload(); } else { alert('Conteudo também publicado no Facebook'); window.location.reload(); } }); } EDIT console.log(response); produces this Object data:array[2] 0: Object access_token: "my token" category: "Computers/Internet" id: "my first id" name: "my name" __proto__: Object 1: Object access_token: "my token_2" category: "Application" id: "my second id" name: "my name" __proto__: Object lenght: 2 A: Post to /{<id}/feed where {id} is the page or user id where you want to post - /me will always refer to the user whose access token you're using
{ "language": "en", "url": "https://stackoverflow.com/questions/7598719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: what exceptions this code may throw ? I want to know which kind of exceptions can be thrown by this code so i can catch them instead of just catching the generic exception (trying to reproduce errors to cause exception is difficult here cause it takes a lot of time to set up the request used ) JAXBContext jc = JAXBContext.newInstance(QueryReport.class); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.valueOf(true)); marshaller.marshal(requestService, out); is = new ByteArrayInputStream(out.toByteArray()); JAXBReader jcReader = new JAXBReader("QueryReport"); log.debug("\n# XML QueryRequest Response: " + jcReader.read(is).asXML()); so if anyone has an idea of which exceptions maybe thrown here. Thanks A: Eclipse, Netbeans or any other modern IDE will tell you precisely which exceptions are raised. I'm guessing you'll see at least ClassNotFoundException, IOException and JAXBExceptions. A: Assuming you are talking about unchecked exceptions, there's generally a good reason the API designers decided to not make them checked exceptions. But if you must absolutely catch them, then you should read the API for the methods you are using. A: From the code block you've shown, the possible exeception will be JAXBException from calling JAXBContext and ClassNotFoundException if QueryReport.class cannot be located from the classpath and IOException if call to ByteArrayInputStream failed. You can use your IDE to wrap the relevant portion of code with generated try/catch block, with the Exception it see fit for the syntax block. A: Why do you need to catch them separately? What are you going to do differently for each one? If the answer is "nothing", then just catch them generically. If you haven't already, read the sections on exceptions in Effective Java, and/or read "Effective Java Exceptions" (different author). If I'm preaching to the choir - my apologies. At some level near the top of your program you'll probably want to catch unchecked exceptions - things like NullPointerException. A: If you explicitly need to catch any exceptions then these will be checked. This means you only need to catch exceptions that the compiler tells you. A: Are you using an IDE? Eclipse (via the compiler) will tell you exactly what exceptions will be thrown, and even generate the boilerplate catch blocks for those exceptions. Or, you can look at the API for each of the method calls to see what the possible exceptions are. A: If you don't enclose this code block into any try block, the compiler will tell you which exceptions must be caught or thrown by the method. Any other exception that might be thrown by this code will be a runtime exception, which is a sign of a programming error, and which should thus not be caught, because it would just hide a bug rather than force you to fix it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: ASP.NET MVC - Linq Query with Count returns anonymous type. How to display in view? So I'm writing a query as follows: Dim assSummary = From a In db.Assignments Join ur In db.UserRegions On a.Origin.ID Equals ur.Region.ID Where ur.User.ID = usrid Group By a.Status.Description _ Into AssCount = Count() _ Select AssCount, Description In the controller I can return the data easily as follows: For Each c In assSummary MsgBox(c.Description & " " & c.AssCount) Next If I pass the object through to the view using Viewdata("assSummary") = assSummary, how do I display the data? Every method I've tried results in messages about 'VB$AnonymousType_7(Of Integer,String) and I don't know how to retrieve the data from the anonymous type. A: In the directives of your page view, you can turn option strict off and use the late-bound dynamic functionality against the anonymous types as follows: <%@ Page Language="VB" ContentType="application/rss+xml" CompilerOptions="/optionstrict-" Inherits="System.Web.Mvc.ViewPage" %> See http://www.thinqlinq.com/Default/Binding-Anonymous-Types-in-MVC-Views.aspx for a fuller sample/explanation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Load url with parameters via ajax in jQuery Mobile Problem I cannot load linked pages with parameters via Ajax in jQuery mobile. Like: http://www.sampleurl.com/tool.dll?name=first&more=parameters Details I'm using jQuery Mobile 1.0b3 I don't refer to in-page navigation with hashtags. I intend to load another webpage (separate html file). So as far as I know there shouldn't be a problem with JQM searching the linked website within the current page. In some cases I have to reference a DLL which is returning the HTML document as response. Unfortunately I cannot access these pages with jQuery Mobile using Ajax. To give an example: I am on the following website http://www.sampleurl.com/tool.dll?name=first&more=parameters and I want to access another website like this: <a href="/tool.dll?name=second&more=parameters"> Link </a> This is not working with Ajax enabled. I have to force non-ajax with the attribute rel="external". Is it not possible to access liks with parameters in JQM this way? I'd like to use the built-in loading notification for pages. What am I missing? Unfortunately I haven't found a solution in similiar questions. Code samples <!-- This is working, but will not get me a loading notification on mobile devices --> <a rel="external" data-ajax="false" href="/tool.dll?name=this%20one&more=parameters"> Link </a> <!-- This is not working --> <a href="/tool.dll?&name=second&more=parameters"> Link </a> <!-- Neither is this working --> <a href="http://www.sampleurl.com/tool.dll?name=this%20one&more=parameters"> Link </a> New insights (edit) For some reason JQM is stuck at loading the page because of this line within the website: <input type="date" name="date" id="date" value="" /> The issue is the attribute type="date"! With an text-field the page loads fine via ajax. The page itself is working fine with jQuery Mobile. The date-input just prevents the page from loading via ajax. I haven't found a solution for this problem, yet. The empty value attribute is not the problem. A: Explanation This issue is not related to GET parameters and the ajax request. The problem is caused by the datepicker plugin for jQuery Mobile, when included in the landing page. If you have to include the script always, you will need to disabled the use of ajax via: rel="external" data-ajax="false" Solution Landing page <!-- Do not include the datepicker script in the landing page --> <div data-role="page" id="pg_1"> <div data-role="header"> <h1>Ajax page test with date input field</h1> </div> <div id="content_div" data-role="content"> <p> <a data-role="button" href="loadme.html">To the calendar</a> </p> </div> </div> Calendar page <head> <!-- include datepicker only on the target page --> <!-- renamed and modified version of the datepicker experiment from JQM --> <script type="text/javascript" src="jquery.ui.datepicker.js"></script> <script type="text/javascript" src="jquery-mobile-calendar.js"></script> </head> <body> <div data-role="page" id="pg_2"> <div data-role="header"> <h1>Ajax page test with date input field</h1> </div> <div id="content_div" data-role="content"> <p> <input type="date" name="date" value="" /> <a data-role="button" href="index.html">Back</a> </p> </div> </div> </body> A: yes you can but into 2 steps: First by dividing your url into two parts first till and before the ? and the other part which is the data which comes after the ? and to do this you have to use javascript reg-expression, do some research. Second using ajax in jquery mobile in the url (attribute) part you will put the first part you got it using javascript reg-expression and the second part in the data (attribute) part A: did you try with $.mobile.loadPage? you can find the documentation about this method here jquerymobile api methods $.mobile.loadPage so, you can try to do somethig like this: <a href="#" onclick="loadNewContain();"> Link </a> <script> function loadNewContain() { $.mobile.loadPage('http://www.sampleurl.com/tool.dll?&name=first&more=parameters'); } </script> :) A: I think you should try: <a href="/tool.dll?name=second&more=parameters"> Link </a> Without the ?&... that should do the trick. HTML doesn't recognize ?& as a valid parameter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to target .NET 4.0 under mono I have mono 2.10 installed which is said to support 4.0 i have a site running, a simple hello world that is built (i develop in on a windows box with vs 2010 and then upload to a linux box) with 3.5. I want to put the site under 4.0. I changed it on visual studio and on the windows box it works. on linux i have the error Unrecognized attribute 'targetFramework' SO, which steps are needed to change the target from 3.5 to 4.0? EDIT: Am not using monodevelop. Am creating the site on a windows machine with visual studio and then copying the entire website folder to the linux box. After that i open the site url and thats it. WHen should i run the dmcs compiler? AFAIK the site is compiled automatically when it runs for the first time ? A: Although it is correct that you use dmcs to compile .NET 4 apps on Mono, I do not think that this is your problem. It sounds to me like you are trying to serve a compiled ASP.NET app on Linux. Your problem is probably that you need to call mod-mono-server4 from Apache but are likely running mod-mono-server2. You should have a line in your httpd.conf or mod-mono.conf that looks like the following: MonoServerPath default /usr/bin/mod-mono-server4 Check out this page, specifically the troubleshooting section. The instructions are a little dated so you have to change the digit '2' to '4' but it is a good explanation of what is going on. This page might also help you setup the right configuration. A: Using mono 2.10, you either run dmcs or gmcs -sdk:4 when compiling your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: C# REST Client Example? Ive been looking everywhere, and nothing seems to work. Im trying to connect to my REST (WCF) Service. It works fine in firefox using the following: http://localhost:1337/WCF.IService.svc/rest/Services?CostCentreNo=1&Filter=1 Where rest is the endpoint address; Services?CostCentreNo=1&Filter=1 is the template with params Below is the Server contract point. [OperationContract] [WebGet(UriTemplate = "/Services?CostCentreNo={CostCentreNo}&Filter={Filter}")] List<Services> GetServices(Int32 CostCentreNo, Int32 Filter); Can I get a working example of connecting to this please from c#.. A: Create your own proxy by extending System.ServiceModel.ClientBase<IYourServiceContract>. Each of your methods on the REST service is exposed through the Channel property, so you can then wrap these. [ServiceContract] public interface IMyServiceContract { [OperationContract] [WebGet(UriTemplate = "/ping")] string Ping(); } public class ProxyClient : ClientBase<IMyServiceContract>, IMyServiceContract { #region Implementation of IMyServiceContract public string Ping() { return Channel.Ping(); } #endregion } public class Test { // This assumes you have setup a client endpoint in your .config file // that is bound to IMyServiceContract. var client = new Client(); System.Console("Ping replied: " + client.Ping()); } Unfortunately, this is aimed at WCF consumption and doesn't work perfectly with REST, i.e. it doesn't expose the HTTP headers, which are necessary for a RESTful implementation. A: Try this for JSON: String resonse = String.Empty; HttpClient client = new HttpClient(); using (HttpResponseMessage httpResponse = client.Get("your_uri")) { response = httpResponse.Content.ReadAsString(); } This code requires the Microsoft.Http and Microsoft.Http.Extensions dlls from the WCF Rest Toolkit - http://aspnet.codeplex.com/releases/view/24644. A: For a generic/dynamic solution with sample source see http://www.nikhilk.net/CSharp-Dynamic-Programming-REST-Services.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7598731", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Reverse engeering cross domain POST requests which use Ext.Ajax.request I'm working with a script which seems to use Ext.Ajax.request (with ExtJS 3) to send cross-domain requests - some of them POST requests. Considerations are being made to move away from ExtJS3 (perhaps move away from ExtJS in general) but a quick attempt at using XMLHttpRequest didn't work; how can I find out what technique is being used to send those cross domain requests? A: I'm currently using ExtJS 3.3.1, I haven't made the switch to 4 yet but will most likely when a new project comes about. Without looking at the Ext source I can tell you they are using JSONP to accomplish this task, it is the only way to make a cross-domain AJAX call because JavaScript has to abide by the same-origin policy. Are you trying to do a pure JS implementation of JSONP? Or are you using a JS library already? Edit Per our comments... they are making POST requests. That's not possible with JSONP. So as far as I can tell, they are using iframe trickery similar. It's the same trick used to "AJAX" upload files on older browsers. This link explains it in more detail. Also, the same method (iframe to, POST, upload a file) is used in Valum's file uploader. It's much easier to follow then the ExtJS source. A: The Ext JS 3.4 online documentation will provide you with the Ext.Ajax class inheritance model which can be used to trace the source code correlate to the Ext.Ajax.request method invocation. However, rather than spending more time and resources in re-creating the wheel, I would suggest implementing the native Ext JS Ext.data.ScriptTagProxy class into your pre-existing stores via the proxy config option, to facilitate your cross-domain requests for remote stores. Below is an abbreviated example of what I'm referring to. Example var myJsonStore = new Ext.data.JsonStore ({ autoLoad : true, proxy : new Ext.data.ScriptTagProxy ({ url : 'http://www.cross-domain.com/file.php' }), fields : ['myIdColumn','myCharColumn','myDateColumn'] }); ADDITION Because you intend on moving away from using Ext JS please checkout the ACD (AJAX Cross Domain) library. A: JSONP is a bit of a hack, but usable. However, consider using CORS if you control the domains being crossed. CORS involves placing a header (Access-Control-Allow-Origin) in the responses from the web site: http://enable-cors.org/ It's supported by IE 8+ (with caveat, natch), Firefox, and WebKit browsers. The IE caveat is this: IE uses a different request object (XDomainRequest) for CORS requests. If you have to support Opera you'll need to use JSONP or a polyfill (something like https://github.com/gimite/web-socket-js/, which requires Flash). If you don't control the domains in question, you can try asking them to support CORS. A: You can try to use jsonp Jquery example: $.ajax({ url: "test.php", dataType: "jsonp" success: function(data){ console.log(data) } }); Or if you have access to the requested content you can set the Access-Control-Allow-Origin header. PHP example: header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
{ "language": "en", "url": "https://stackoverflow.com/questions/7598733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Pipe console.writeLine() messages to a text file I wonder what the best approach is in implementing a logger which essentially eats all Console.WriteLine() messages and spits out a text file of all these messages. I know I could use a StringBuilder and populate it with all the messages by doing .AppendLine wherever Console.WriteLine occurs...but I am looking for something more magical than that. Some way using which I don't have to write as many lines of code as Console.WriteLines in existing code. And in case you missed the tags, this is for a C#4.0 console application. A: Instead of using Console.Write in your code, use Trace.Write. Then in the config file, append the ConsoleTraceListener to the trace listeners. This technique will allow you to trace, and the trace framework will output it both to the console and whatever trace listener you set up (probably TextWriterTraceListener in your case). Some 3rd party lib (log4not goes into my mind) allows an encapsulation of all logging mechanisms too. A: I assume what you want is a stream that writes to standard out and to a file. That is, you want everything to still show up on the console, but you also want it to be written to a file. (If you just wanted to redirect output to a file, you could do that from the command line.) You need to create your own TextWriter-derived class, and have it do the actual output. You call Console.SetOut to make the console write to your TextWriter. class ConsoleLogger: TextWriter { private TextWriter ConsoleOutputStream; private StreamWriter LogOutputStream; public ConsoleLogger(string logFilename) { ConsoleOutputStream = Console.Out; // Initialize your log file LogOutputStream = new StreamWriter(logFilename); } public void Write(string s) { ConsoleOutputStream.Write(s); LogOutputStream.Write(s); } // Other Write functions format their arguments and call Write(string). } And in the program that uses this: private ConsoleLogger MyLogger; const string LogFilename = "ConsoleLog.txt"; void Main() { MyLogger = new ConsoleLogger(LogFilename); Console.SetOut(MyLogger); } You don't have to override all the TextWriter methods. As the documentation says, "A derived class must minimally implement the TextWriter.Write(Char) method to make a useful instance of TextWriter." I've done something similar to this, and it works quite well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Disable javascript's domain restrictions in FF 7.0 I am developing a small html + JS app for my own use and being ability to access IFrame's content or opened windows' contect with Javascript would greatly improve my productivity. Is it possible to disable the cross domain restrictions imposed by Firefox 7.0, so that I will be able to modify contents of what is displayed in an iframe? A: I think I remember a similar issue a while ago in FF. This is worth a try: There's a file in your user profile called prefs.js. On my machine its located: C:\Users\simon\AppData\Roaming\Mozilla\Firefox\Profiles\aoagj1zo.default In the file are a bunch of lines like this: user_pref("accessibility.typeaheadfind.flashBar", 0); user_pref("app.update.lastUpdateTime.addon-background-update-timer", 1317146699); Try adding this line: user_pref("capability.policy.default.XMLHttpRequest.open", "allAccess"); You should probably close FF, edit this file, then reopen FF.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android views, intents and layout problems This is my first question, but I've been reading a lot of posts in here trying to get this right. But I just can't figure it out! So I'm hoping for assistance! I'm working on a Android application from where I enter a searchphrase in a autocomplete field. From here I would like the application to change to another layout xml file which contains a listview of the results. When you click a item, it will go to yet another layout xml file. I got all the http posts and functions ready and working, but the thing that gives me a headache is the switching layout part. I been trying this so far: setContentView(R.layout.newlayout); Which works the way it should, it does change the layout but of course with problems. If I press the backbutton on my phone, it just closes the app instead of going back to the previous layout. If I create a back button and set it's onclick to do a setContentView(R.layout.previouslayout); it goes back to the other layout, but it does not preserve the input data in the searchform, furthermore it does not reload the function for fetching the tags for the autocomplete. BIG problem! I'm guessing, that I have to use some kind of intent, or activity manager but I don't know how that works, and how would I send data along with the start of a new activity for my list view and product view? A: To show another layout you should use call startActivity from within your activity. To put data along the call use putExtra: int value = 1; Intent i = new Intent(this, Test.class); i.putExtra("var", value); startActivity(i); You should also create a class for each layout and use setContentView to choose the correct layout: public class Test extends Activity{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); int var2 = (int)getIntent().getExtras().get("var"); setContentView(R.layout.newlayout); ... } } A: Despite using intent or another activity, you can also use ViewFlipper. Example http://www.androidpeople.com/android-viewflipper-example
{ "language": "en", "url": "https://stackoverflow.com/questions/7598741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Column mapping with Abstract class (TPT with existing tables) I am developing against existing DB, having problem mapping my abstract class to my table as TPT., which raised an error saying "invalid column name "ID"". Simple class as follows public abstract class Member { [DisplayName("ID")] public string ID { get; set; } [DisplayName("Date Applied")] public System.DateTime? DateApplied { get; set; } [DisplayName("Date Membered")] public System.DateTime? DateMembered { get; set; } [DisplayName("Member Type")] public int MemberTypeFlag { get; set; } } public class Person : Member { [DisplayName("Last Name")] public string LastName { get; set; } [DisplayName("First Name")] public string FirstName { get; set; } [DisplayName("Date Of Birth")] public System.DateTime DateOfBirth { get; set; } } And mapped to my custom table as follows public class MapMember : EntityTypeConfiguration<Member> { public MapMember() : base() { HasKey(b => b.ID).Property(b => b.ID).HasColumnName("ID"); Property(b => b.DateApplied).HasColumnName("DTM_APPLIED"); Property(b => b.DateMembered).HasColumnName("DTM_MEMBERED"); Property(b => b.MemberTypeFlag).HasColumnName("MBR_TYPE_FLG"); ToTable("MBR"); } } public class MapPerson : EntityTypeConfiguration<Person> { public MapPerson() : base() { Property(p => p.LastName).HasColumnName("LNAME"); Property(p => p.FirstName).HasColumnName("FNAME"); Property(p => p.DateOfBirth).HasColumnName("DOB"); Property(p => p.FirstName).HasColumnName("FNAME"); ToTable("MBR_PERSON"); } } However Invalid column name "ID" raised upon db.savechanges(). Please advise. Thanks A: This error will occur if the primary key column in your MBR_PERSON table (which must be foreign key to the MBR table at the same time) does not have the column name ID (the name of the key column in table MBR). In TPT mapping the primary key columns of the root table for the abstract entity must have the same name as the primary key columns of the tables for the derived entities.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Manipulating Dynamic object on C# I have a C# class that inherits from DynamicObject and using serialization is creating me an instance for a given xml. My issue: Now i have to generate one dynamic object from two equal (with same structure) xml files selecting some type of elements from the second xml only. Do you have any link to any article where i could find techniques to do this? A: Here you can find some documentation:Creating and Using Dynamic Objects I think you can also use linq to xml for selecting the things that you need from the xml's.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to access global Sinatra configs inside custom Liquid template tags? I'm trying to create a custom Liquid template tag like this: class ScriptLoader < Liquid::Tag def initialize(tag_name, filename, tokens) super @file = filename end def render(context) settings.cdn_url << 'script/' << @file end end Liquid::Template.register_tag('script', ScriptLoader) The above code is in an external file location at : (project_dir)/tags/scriptloader.rb This file is being included in the app.rb startup file. The problem though is that the settings variable is empty, even after adding the configs in the app.rb file using the set method. The response when calling {% script 'myfile' %} in my templates: Liquid error: undefined method `cdn_url' for Sinatra::Application:Class Any ideas or guidance would be greatly appreciated! Thanks! A: Ok, so I've managed to work around the issue. I created a config object in app.rb that loads the configs from a file, iterates over them and calls the set() method for each. This also stores the config key=>value sets in a class constant hash. I can access the values like this: class ScriptLoader < Liquid::Tag def initialize(tag_name, filename, tokens) super @file = filename end def render(context) MyObject::CONFIG[:cdn_url] << 'script/' << @file end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7598747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Run a build script So I have this build script I need to "run" or "install"? It's a .proj file. The directions are to run this script using MSBuild. How would I do this? Thanks! A: Open a Visual Studio Command Prompt. msbuild <filename> <filename> is the path to the file. A: Run using multiple concurrent processes (one per CPU), could be useful for "heavy" projects in case when you have multi-CPU computer: msbuild /m /nr:false ProjectName.csproj
{ "language": "en", "url": "https://stackoverflow.com/questions/7598748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Change the URL in the address bar using jQuery I have written the following to do AJAX requests in my app: $(document).ready(function () { $('ul#ui-ajax-tabs li:first').addClass('selected'); $('#ui-ajax-tabs li a').click(function (e) { e.preventDefault(); $("#ui-ajax-tabs li").removeClass("selected"); $(this).parents('li').addClass("loading"); var url = $(this).attr("href"); var link = $(this); console.log(url); $.ajax({ url: url, success: function (responseHtml) { $('div#ui-tab-content').html($(responseHtml).find('div#ui-tab-content > div#ui-ajax-html')); $(link).parents('li').addClass('selected'); $("#ui-ajax-tabs li").removeClass("loading"); }, error: function () { $('div#ui-tab-content').html('<div class="message error">Sorry that page doesn\'t exist</div>'); $(link).parents('li').addClass('selected'); $("#ui-ajax-tabs li").removeClass("loading"); } }); }); }); However I also want to change the url in the address bar to match what I just loaded in. I have looked around at some demos using the new HTML5 History API @ http://html5demos.com/history but it's not making any sense. Could someone show an example of how I could use the new history stuff in my code? Would be really appreciated. Thanks. Thanks A: The only way to change the URL (without hashes) and staying in the same page is by using HTML5. And you're better off using a plugin than writing your own. In your case, you would need to 'push' a new History state whenever you call the Ajax page. Maybe you can take a look at this plugin History.js: https://github.com/browserstate/History.js/ Its usage is very simple, as you can see in the Docs. (function(window,undefined){ // Prepare var History = window.History; // Note: We are using a capital H instead of a lower h if ( !History.enabled ) { // History.js is disabled for this browser. // This is because we can optionally choose to support HTML4 browsers or not. return false; } // Bind to StateChange Event History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate var State = History.getState(); // Note: We are using History.getState() instead of event.state History.log(State.data, State.title, State.url); }); // Change our States History.pushState({state:1}, "State 1", "?state=1"); // logs {state:1}, "State 1", "?state=1" History.pushState({state:2}, "State 2", "?state=2"); // logs {state:2}, "State 2", "?state=2" History.replaceState({state:3}, "State 3", "?state=3"); // logs {state:3}, "State 3", "?state=3" History.pushState(null, null, "?state=4"); // logs {}, '', "?state=4" History.back(); // logs {state:3}, "State 3", "?state=3" History.back(); // logs {state:1}, "State 1", "?state=1" History.back(); // logs {}, "Home Page", "?" History.go(2); // logs {state:3}, "State 3", "?state=3" })(window);
{ "language": "en", "url": "https://stackoverflow.com/questions/7598753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Handling Exceptions in Tasks and Parallel loops. (Threading - TPL) I want to know if you think this is a good way to handle exceptions thrown by Parallel Loops (Parallel.ForEach and/or Parallel.For) inside Tasks. I think it isn't so bad, but your opinion can be usefull to me! Hope you can throw some light on me! (I used VS2010 and, of course, Framework 4.0) class Program { private static ConcurrentQueue<Exception> _exceptions = new ConcurrentQueue<Exception>(); private static readonly ExceptionManager _exceptionManager = new ExceptionManager(); static void Main() { var process = new SomeProcess(_exceptions); var otherProcess = new SomeOtherProcess(_exceptions); var someProcess = new Task(() => { process.InitSomeProcess(); process.DoSomeProcess(); }); var someOtherProcess = new Task(() => { otherProcess.InitSomeOtherProcess(); otherProcess.DoSomeOtherProcess(); }); someProcess.Start(); someOtherProcess.Start(); try { someProcess.Wait(); someOtherProcess.Wait(); } catch ( Exception ex) { _exceptionManager.Manage(ex); } finally { Console.WriteLine(); foreach ( var exception in _exceptions ) { _exceptionManager.Manage(exception); } _exceptions = new ConcurrentQueue<Exception>(); //Delete exceptiones to prevent manage them twice (maybe this could be one in a more elegant way). } Console.ReadKey(); } } public class ExceptionManager { public void Manage(Exception ex) { Console.WriteLine("Se dió una {0}: {1}", ex.GetType(), ex.Message); } } public class SomeProcess { private readonly ConcurrentQueue<Exception> _exceptions; public SomeProcess(ConcurrentQueue<Exception> exceptions) { _exceptions = exceptions; } public void InitSomeProcess() { Parallel.For(0, 20, (i, b) => { try { Console.WriteLine("Initializing SomeProcess on {0}.", i); throw new InvalidOperationException("SomeProcess was unable to Initialize " + i); } catch (Exception ex) { _exceptions.Enqueue(ex); } }); Console.WriteLine("SomeProcess initialized :D"); } public void DoSomeProcess() { Parallel.For(0, 20, (i, b) => { try { Console.WriteLine("Doing SomeProcess on {0}.", i); throw new InvalidOperationException("SomeProcess was unable to process " + i); } catch (Exception ex) { _exceptions.Enqueue(ex); } }); Console.WriteLine("SomeProcess done :D"); } } public class SomeOtherProcess { private readonly ConcurrentQueue<Exception> _exceptions; public SomeOtherProcess(ConcurrentQueue<Exception> exceptions) { _exceptions = exceptions; } public void InitSomeOtherProcess() { Parallel.For(0, 20, (i, b) => { try { Console.WriteLine("Initializing SomeOtherProcess on {0}.", i); throw new InvalidOperationException("SomeOtherProcess was unable to Initialize " + i); } catch (Exception ex) { _exceptions.Enqueue(ex); } }); Console.WriteLine("SomeOtherProcess initialized :D"); } public void DoSomeOtherProcess() { Parallel.For(0, 20, (i, b) => { try { Console.WriteLine("Doing SomeOtherProcess on {0}.", i); throw new InvalidOperationException("SomeOtherProcess was unable to process " + i); } catch (Exception ex) { _exceptions.Enqueue(ex); } }); Console.WriteLine("SomeOtherProcess done! :D"); } } A: if you think this is a good way to handle exceptions thrown by Parallel Loops ... inside Tasks. Hard to tell for 'SomeProcess'. This depends on a combination of your business rules and technical issues. The TPL has an excellent mechanism to collect exceptions inside Tasks and pro[agate them to the caller, so think about what you really need. Edit, after the formatting was fixed: If you are really sure that your loop should continue with the next item after an exception then your enqueue approach looks acceptable. Again, it depends on what the loop is doing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Oracle SQL Return all records within days of date I am hoping that somebody can help me out with this question. The following SQL returns just the records in a given table that are specifically 20 days from current. Last_Mod_Date = TO_DATE(SYSDATE - 20) Using similar theory can somebody help me determine how to return all records within the past 20 days range? Thanks! A: select * from table where Last_Mod_Date >= trunc(sysdate-20); A: SELECT * FROM MY_TABLE WHERE TO_DATE(my_ts_field) BETWEEN TO_DATE(SYSDATE-20) AND TO_DATE(SYSDATE) A: Change the comparison to greater-than-or-equal: Last_Mod_Date >= TO_DATE(SYSDATE-20)
{ "language": "en", "url": "https://stackoverflow.com/questions/7598757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: c++ const symbols inflating linked file In C++ is legal to put a const in the header file, usually the C way would be to put the extern declaration in the header and the definition in just one compilation unit, but in C++, the former technique leads to an increased binary since the symbols are not removed while linking (tested with gnu ld and visual studio). Is there a good way to do these things? I can only think of a define or the C way, but the later might give room to less optimizations... piotr@gominola:0:/tmp$ g++ -c b.cc piotr@gominola:0:/tmp$ g++ -c a.cc piotr@gominola:0:/tmp$ nm a.o | c++filt | grep COOK 0000000000000000 r AI_LIKE_COOKIES piotr@gominola:0:/tmp$ nm b.o | c++filt | grep COOK 0000000000000000 r AI_LIKE_COOKIES piotr@gominola:0:/tmp$ g++ -o a a.o b.o piotr@gominola:0:/tmp$ nm a | c++filt | grep COOK 0000000000400610 r AI_LIKE_COOKIES 0000000000400618 r AI_LIKE_COOKIES piotr@gominola:0:/tmp$ cat a.h #ifndef a_h #define a_h //const double A = 2.0; //extern const double AI_LIKE_COOKIES; const double AI_LIKE_COOKIES = 5.0; #endif piotr@gominola:0:/tmp$ cat a.cc #include "a.h" using namespace std; extern void f(); //const double AI_LIKE_COOKIES = 2.0; int main(int argc, char *argv[]) { f(); } piotr@gominola:0:/tmp$ cat b.cc #include "a.h" void f() { } piotr@gominola:0:/tmp$ A: Objects declared const and not explicitly declared extern have internal linkage in C++. This means that each translation unit gets it's own copy of the object. However, as they have internal linkage and so can't be named from other translation units, the compiler can detect if the object itself is not used - and for basic const objects this just means if it's address is never taken; it's value can be substituted as needed - and omit it from the object file. gcc will perform this optimization even at -O1. $ g++ -O1 -c a.cc $ g++ -O1 -c b.cc $ g++ -o a a.o b.o $ nm a.o | c++filt | grep COOK $ nm b.o | c++filt | grep COOK $ nm a | c++filt | grep COOK $ A: There are two real choices you have. You can define a constant with external linkage, or not. With internal linkage, you'll only a copy in each translation unit that actually uses the constant, assuming optimization is turned on. Internal linkage: // a.h const double AI_LIKE_COOKIES = 5.0; External linkage: // a.h extern const double AI_LIKE_COOKIES; // a.c const double AI_LIKE_COOKIES = 5.0; However, you may be asking, "what about inlined constants?" Unfortunately, floating point operands can't really be inlined. Whenever you use a floating point constant in a function, that value gets stored as a constant in memory. Consider the two functions: // In func1.c double func1(double x) { return x + 5.7; } // In func2.c double func2(double x) { return x * 5.7; } In all likelihood, both files will contain a constant 5.7 somewhere, which is then loaded from memory. No optimization is really performed*. You get two copies of 5.7, just as if you had done this: extern const double CONSTANT_1, CONSTANT_2; const double CONSTANT_1 = 5.7; const double CONSTANT_2 = 5.7; double func1(double x) { return x + CONSTANT_1; } double func2(double x) { return x * CONSTANT_2; } * Note: On some systems, you get smaller code if you know that the constant will be linked into the same binary image rather than loaded from a library. Recommendation: Use an extern in the header file, and define the constant in one translation unit. The code likely won't be any slower and barring link-time optimizations, this is the only good way to make sure only one copy ends up in the final product. It sounds like a lot of fuss over eight bytes, though... Assembler: Here's a function: double func(double x) { return x + 5.0; } Here's the assembler, on x86_64: _Z4funcd: .LFB0: .cfi_startproc .cfi_personality 0x3,__gxx_personality_v0 addsd .LC0(%rip), %xmm0 ret .cfi_endproc .LFE0: .size _Z4funcd, .-_Z4funcd .section .rodata.cst8,"aM",@progbits,8 .align 8 .LC0: .long 0 .long 1075052544 Notice the symbol LC0, which is a constant containing the value 5.0. Inlining has done nothing but make the symbol invisible so it doesn't show up in nm. You still get a copy of the constant sitting around in every translation unit which uses the constant. A: Putting the const in each header implicitly makes it internal linkage so it's duplicated in every translation unit. The "C way" is the normal way of dealing with this I believe. You can also define "constants" with trivial inline functions (see std::numeric_limits<T>::max()) A: It's logical behaviour. If you need to make your module dependent on external name include extern instead. In most cases it's not needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why is passenger not finding my rails root I have a rails application that i need to be in a subdirectory of an existing application I am trying to deploy this rails application to a sub directory using the help of this link Here is my application here and as you can see i am getting this error (The directory "/srv/www/www.transprintusa.com" does not appear to be a valid Ruby on Rails application root) . my public folder is here /srv/www/www.transprintusa.com/design/design.transprintusa.com/releases/20110217203009/public/ or with the sym link /srv/www/www.transprintusa.com/design/design.transprintusa.com/ here is my VHOST <VirtualHost 184.106.111.142:80> ServerAdmin jom@jom.com ServerName transprintusa.com ServerAlias www.transprintusa.com DocumentRoot /srv/www/www.transprintusa.com/ ErrorLog /srv/www/www.transprintusa.com/logs/error.log CustomLog /srv/www/www.transprintusa.com/logs/access.log combined <Directory "/srv/www/www.transprintusa.com/"> AllowOverride all Options -MultiViews </Directory> RailsBaseURI /design <Directory /srv/www/www.transprintusa.com/design/design.transprintusa.com/releases/20110217203009/public/> Options -MultiViews </Directory> </VirtualHost> I even ran this symlink command i ran also ln -s /srv/www/www.transprintusa.com/design/design.transprintusa.com/releases/20110217203009/public/ /srv/www/www.transprintusa.com/design maybe i am missing something obvious and i just dont see it A: Okay - followup on my comment. I'd create the symlink like this (run it from "/srv/www/www.transprintusa.com"): ln -Ts design/design.transprintusa.com/releases/20110217203009/public/ rails That'll make a symlink called "rails" in your "/srv/www/www.transprintusa.com" directory (I'm not calling it "design", 'cause it looks like the design subdirectory already exists - that might have been part of your problem). Then give that symlink as the RailsBaseURI: RailsBaseURI /rails <Directory /srv/www/www.transprintusa.com/rails> Options -MultiViews </Directory> And that's it - restart your server and see if it goes. Hope that helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7598761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to send a file from an applet to an gwt server? I'm trying to send a file from an applet to my server GWT. In another application, JSF, I would open an HTTP connection with my servlet. How do I make whit an GWT server? I tried to insert my servlet in web.xml but it seems to be ignored. I need to use a RemoteService? How can I do? The following code of the applet and servlet mapping in web.xml. URL urlDoServlet = new URL("http://192.168.3.100:8080/gwtapp/conection?action=send"); HttpURLConnection conexaoComServlet = (HttpURLConnection) urlDoServlet.openConnection(); conexaoComServlet.setDoOutput(true); conexaoComServlet.setDoInput(true); conexaoComServlet.setUseCaches(false); conexaoComServlet.setDefaultUseCaches(false); File doc = new File(file); conexaoComServlet.setRequestMethod("POST"); conexaoComServlet.setRequestProperty("Content-Type", "application/octet-stream"); FileInputStream fis = new FileInputStream(doc); BufferedInputStream bis = new BufferedInputStream(fis); BufferedOutputStream bos = new BufferedOutputStream(conexaoComServlet.getOutputStream()); int read; byte[] buffer = new byte[8192]; while((read = bis.read(buffer)) != -1) { bos.write(buffer, 0, read); } bis.close(); fis.close(); bos.flush(); bos.close(); // get the answer. ObjectInputStream ois = new ObjectInputStream(conexaoComServlet.getInputStream()); boolean bool = (Boolean) ois.readObject(); ois.close(); conexaoComServlet.getResponseMessage(); conexaoComServlet.disconnect(); <servlet> <servlet-name>ConectionServlet</servlet-name> <servlet-class>br.com.gwtapp.server.servlets.ConectionFileServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>conectionServlet</servlet-name> <url-pattern>/gwtapp/conection</url-pattern> </servlet-mapping> A: try replace <url-pattern>/gwtapp/conection</url-pattern> by <url-pattern>/conection</url-pattern> and tell us if that works :) A: I've found a new implementation for that with caarlos0 and raduq-santos: public class DispatchServletModule extends ServletModule { @Override public void configureServlets() { serveMyServlet(); } private void serveMyServlet() { serve("proj/servlet/MyServlet").with(MyServlet.class); } } and on my applet... new URL(path + "proj/servlet/MyServlet");
{ "language": "en", "url": "https://stackoverflow.com/questions/7598763", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: java - connect parent and child IDs and make the full path directories I have been given an answer in question: Create folders from folder id and parent id in java It was very useful but I do not understand the last part of the answer: "Finally, just grab the folder with id 0 and start building your Files on the disk, using folder.getChildren() as a convenient way to move down the tree. Check out the javadoc on the File object, you will particularly want to use the mkdirs() method." I don't even know where to being to implement it. Does anyone understand it? Thank You A: Once your tree of Folder instances has been built, the root of the tree is the Folder with ID 0. Start with this folder, and create a directory in the file system for each of its children, recursively: /** * Creates a directory in parentDirectory for every child of the given folder, * recursively. */ public void createDirectoriesForChildren(Folder folder, File parentDirectory) { for (Folder childFolder : folder.getChildren()) { File directory = new File(parentDirectory, childFolder.getName()); directory.mkdirs(); createDirectoriesForChildren(childFolder, directory); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7598766", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: jQuery validate textarea:filled i have the following form fields... <textarea name="anchors[]" id="anchors1" cols="45" rows="5" class="linkbox"></textarea> <textarea name="anchors[]" id="anchors2" cols="45" rows="5" class="linkbox"></textarea> <textarea name="urls[]" id="urls1" cols="45" rows="5" class="linkbox"></textarea> <textarea name="urls[]" id="urls2" cols="45" rows="5" class="linkbox"></textarea> which i'm trying to validate so that if say anchors2 is filled in, then urls2 must also be filled in, however i can't for the life of me get the following to work!... var validator = $("#projectform").validate({ rules: { project_label: "required", keywords: "required", urls2: { required: "#anchors2:filled" } }, messages: { project_label: "Enter a project label", } ,errorElement: "div" ,submitHandler: function(form) { $('input[type=submit]').attr('value', 'Please wait'); $('input[type=submit]').attr('disabled', 'disabled'); this.form.onsubmit(); return false; } }); When i click submit the project_label and keywords fields validate(or not) as would be expected, however i see nothing with regards to the anchors[] and urls[] fields. I have css set on the textarea.error to give a visual indiciation too but i don't see that either when attempting to validate. It should be noted that the following doesn't work either, which may shed some light? urls1: "required", A: The validation plugin requires that you use the element name, not the id. In order to do this, I had to change the name to remove the []. So rename your textarea, and try again - like so: HTML: <textarea name="url2newname" id="urls2" cols="45" rows="5" class="linkbox"></textarea> Javascript Snippet: rules: { project_label: "required", keywords: "required", urls2newname: { required: "#anchors2:filled" } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7598771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to handle text wrapping in CSS? Possible Duplicate: Auto-size dynamic text to fill fixed size container Please take a look at this: The text "parenthood" is one word, yet it falls on 2 lines because there isn't enough space for it to fit in the containing div. Before adding this property to the div: word-wrap: break-word; The word parenthood simply ran off screen which is no good since I want the user to be able to read the titles. But if it falls on 2 lines it doesn't look much better either. The reason why the obvious solution of decreasing text size won't work is because these boxes are dynamically generated by the back end. So sometimes a title could be small and sometimes huge. Is there a way to have that text resize to fit perfectly each time? A: I don't think this can be handled with just css, but if you are looking to add some JS/jQuery to accomplish the task then I guess this thread should help you: Auto-size dynamic text to fill fixed size container
{ "language": "en", "url": "https://stackoverflow.com/questions/7598775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Jquery .outerHeight() after .append() Im trying to run .outerHeight() function on element that i just appended to html via .append() $("#someid").append("<ul id='#otherid'><li>something</li></ul>"); var h = $("#otherid").outerHeight(); After this "h" has wrong value. I think that it is caused by "append" not applying css to created elements. .outerHeight() runs correctly if i will put it in "setTimeout" but not right after "append". Do you know how to get correct value of outerHeight after element was just appended? A: The reason for that is probably due to the fact that the appended elements do not have their CSS rules applied yet and are not counting towards the total height. Try using a delay (like settimeout) to make things work right. var h = $("#otherid").delay(300).outerHeight(); A: Instead: id='#otherid' try: id='otherid' $("#someid").append("<ul id='otherid'><li>something</li></ul>"); var h = $("#otherid").outerHeight();
{ "language": "en", "url": "https://stackoverflow.com/questions/7598781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Filtering Encoded XSS in Classic ASP ok. I am dealing with a Classic ASP app written on VBScript. I am trying to filter possible XSS that might come via encoded Query string. I have a simple XSS elimination function in place [getUserInput]. This looks for special charactors like < > / ' .... and replaces them with blank space. That works pretty well. But, when I input something that is encoded via Server.URLEncode (VBScript) or escape (Javascript), obviously my above filter does not work. I want to know the recommended solutions that are in place to prevent this Unicode converted input that makes my page vulnerable to XSS. Repro steps: <% Response.Write getUserInput(Request("txt1")) + "<br/>" Response.Write Server.URLEncode(getUserInput(Request("txt1"))) + "<br/>" 'the below line is where I am trying to decode and echo the input Response.Write URLDecode2((getUserInput(Request("txt1")))) + "<br/>" Response.Write "<br/>" %> <html> Try any of the below two encoded strings in the input box and hit the button. </br></br> alert('hi') </br> %3Cscript%3Ealert%28%27hi%27%29%3C%2Fscript%3E <br/> alert(document.cookie) </br> %3Cscript%3Ealert%28document.cookie%29%3C%2Fscript%3E <br/> </br> <form method="get" name="form1" id="form1" action="#" onSubmit="CallOnLoad()"> <input type='text' name='txt1' id='txt1' /> <button name='btn' type='submit' id='btn'>Hitme</button> </form> </html> <% function getUserInput(input) dim newString newString=input newString = replace(newString,"--","") newString = replace(newString,";","") newString = replace(newString,chr(34),"'") newString = replace(newString,"'","") newString = replace(newString,"=","=") newString = replace(newString,"(","[") newString = replace(newString,")","]") newString = replace(newString,"'","''") newString = replace(newString,"<","[") newString = replace(newString,">","]") newString = replace(newString,"/*","/") newString = replace(newString,"*/","/") getUserInput = newString end function %> <% 'URLDecode2 - source code from http://www.motobit.com/tips/detpg_URLDecode/ Function URLDecode2(ByVal What) Dim Pos, pPos What = Replace(What, "+", " ") on error resume Next Dim Stream: Set Stream = CreateObject("ADODB.Stream") If err = 0 Then on error goto 0 Stream.Type = 2 'String Stream.Open Pos = InStr(1, What, "%") pPos = 1 Do While Pos > 0 Stream.WriteText Mid(What, pPos, Pos - pPos) + _ Chr(CLng("&H" & Mid(What, Pos + 1, 2))) pPos = Pos + 3 Pos = InStr(pPos, What, "%") Loop Stream.WriteText Mid(What, pPos) Stream.Position = 0 URLDecode2 = Stream.ReadText Stream.Close Else 'URL decode using string concentation on error goto 0 Pos = InStr(1, What, "%") Do While Pos>0 What = Left(What, Pos-1) + _ Chr(Clng("&H" & Mid(What, Pos+1, 2))) + _ Mid(What, Pos+3) Pos = InStr(Pos+1, What, "%") Loop URLDecode2 = What End If End Function %> I am required to host the app on IIS 7.5/Win 2008 R2. Simple/elegant advices please? How To: Prevent Cross-Site Scripting in ASP.NET is a good article, but it does not quiet to my scenario as I am dealing with Classic ASP. Thanks. A: I am trying to filter possible XSS This is largely a waste of time. This breed of XSS is an output-stage issue, caused by inserting data into HTML without HTML-escaping it. Despite the many efforts of deeply misguided “anti-XSS” tools and function, this problem simply cannot be handled by filtering at the input phase. At input time it is not known where data will end up, which data will need to be HTML-escaped (as opposed to injected into other text contexts like SQL or JavaScript), and what processing will be done to that data before it ends up on the page—in your example's case you're demonstrating this with URL-decoding, but it could be anything. To correct problems caused by < and &, you need to remember to call Server.HTMLEncode on every string you inject into your output page, so that they'll be converted into &lt; and &amp; respectively. This is safe and will also allow users to use any character at will without some of them disappearing. (Imagine trying to post this message to SO with all the <s removed!) That way you don't need to worry about encoded versions of <, because by the time you come to put them on the page you will have decoded them, and can apply the correct form of encoding, namely HTML-escaping. This is not really anything to do with Unicode. Non-ASCII characters can be included in a page without any issues; it is only <, &, and in attribute values the quote character being used as a delimiter, that present any danger when injected into HTML. There used to be a problem with over-long UTF-8 sequences, where a < could be smuggled in an invalid sequence of top-bit-set bytes that would get through HTML-encoding unchanged. Then IE (and Opera) would treat it as a real <. Whilst it's still a good idea to filter overlongs if you are working with UTF-8 in a language that has native byte strings rather than Unicode, it's not the necessity it once was as all current major browsers treat overlongs correctly, as non-functional invalid sequences. Using correct HTML-escaping, your example might look like this (omitted the unchanged URLDecode2 function): <p> <%= Server.HTMLEncode( Request("txt1") ) %> <br/> <%= Server.HTMLEncode( URLDecode2(Request("txt1")) ) %> </p> <p> Try any of the below two encoded strings in the input box and hit the button. </p> <ul> <li>&lt;script>alert('hi')&lt;/script></li> <li>%3Cscript%3Ealert%28%27hi%27%29%3C%2Fscript%3E</li> <li>&lt;script>alert(document.cookie)&lt;/script></li> <li>%3Cscript%3Ealert%28document.cookie%29%3C%2Fscript%3E<li> </ul> <form method="get" action="this.asp"> <input type="text" name="txt1" value="<%= Server.HTMLEncode( Request("txt1") ) %>"/> <input type="submit" value="Hitme"/> </form> (In ASP.NET 4.0 there is a handy <%: shortcut to do <%= Server.HTMLEncode for you; unfortunately not so in Classic ASP.) A: You should use Unescape. Function getUserInput(input) dim newString '*********************** newString=Unescape(input) '*********************** newString = replace(newString,"--","") 'etc ... 'etc ... 'etc ... End Function A: When you have strings to parse in your xml builder asp. You could create it like so: <description><![CDATA[ "& descriptionString &"]]></description> You could use a HTML stripping function to strip out unneeded html or escaping html tags: Function stripHTML(strHTML) Dim objRegExp, strOutput Set objRegExp = New RegExp with objRegExp .Pattern = "<(.|\n)+?>" .IgnoreCase = True .Global = True end with 'Replace all HTML tag matches with the empty string strOutput = objRegExp.Replace(strHTML, "") Set objRegExp = Nothing 'Replace all < and > with &lt; and &gt; strOutput = Replace(strOutput, "<", "&lt;") strOutput = Replace(strOutput, ">", "&gt;") stripHTML = strOutput 'Return the value of strOutput End Function Another one for preventing SQL injection. Parse for example requests.querystrings to it from Form get/post. function SQLInject(strWords) dim badChars, newChars, tmpChars, regEx, i badChars = array( _ "select(.*)(from|with|by){1}", "insert(.*)(into|values){1}", "update(.*)set", "delete(.*)(from|with){1}", _ "drop(.*)(from|aggre|role|assem|key|cert|cont|credential|data|endpoint|event|f ulltext|function|index|login|type|schema|procedure|que|remote|role|route|sign| stat|syno|table|trigger|user|view|xml){1}", _ "alter(.*)(application|assem|key|author|cert|credential|data|endpoint|fulltext |function|index|login|type|schema|procedure|que|remote|role|route|serv|table|u ser|view|xml){1}", _ "xp_", "sp_", "restore\s", "grant\s", "revoke\s", _ "dbcc", "dump", "use\s", "set\s", "truncate\s", "backup\s", _ "load\s", "save\s", "shutdown", "cast(.*)\(", "convert(.*)\(", "execute\s", _ "updatetext", "writetext", "reconfigure", _ "/\*", "\*/", ";", "\-\-", "\[", "\]", "char(.*)\(", "nchar(.*)\(") newChars = strWords for i = 0 to uBound(badChars) Set regEx = New RegExp regEx.Pattern = badChars(i) regEx.IgnoreCase = True regEx.Global = True newChars = regEx.Replace(newChars, "") Set regEx = nothing next newChars = replace(newChars, "'", "''") SqlInject = newChars end function
{ "language": "en", "url": "https://stackoverflow.com/questions/7598783", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: .Net Code Signing - Can I use an AD Certificate? I am working on an internal project which uses a bunch of OLEDB Providers some of them has a UI. The biggest challenge is that I need to request uiAccess=true in the manifest which only is possible on windows if the code is digitally signed. This application is only used internally. I am assuming AD's Primary Domain Controller already acts as CA for all the machines in the domain and is fully trusted. And it possible to generate code signing certificate for some purposes like SQL server and Infopath. Does any one know if I can use a code signing certificate Issued by my AD/PDC to sign my WPF application (not click-Once) and achieve this goal. Appreciate any guidance in this direction. A: Yes you can. You need to set up an Enterprise Root Certification Authority. Once you have your own CA, you can issue certificates for any purpose, including code-signing certificates. You can even set up your own timestamping server. Note that these certificates will only be accepted by clients that trust your CA, but if your applications are only used internally, that will not be a problem. This document might get you started: * *Building an Enterprise Root Certification Authority in Small and Medium Businesses
{ "language": "en", "url": "https://stackoverflow.com/questions/7598785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Using Java 7 SDK features in Java 6 I am interested in using some of the NIO2 features in the Java 7 SDK if available (specifically, the file system watchers), however I do not want to compile my classes for Java 7 and exclude Java 6 runtimes. Mostly because I want retain compatibility with Mac OS X, and also because I don’t want to force my users to upgrade. Is this possible? What is the best way to do it? Any links or examples? Here are some ways I can imagine: compiling a class file with a different compiler and loading it dynamically based on the Java version? Or maybe using reflection? Or maybe there’s just a compiler setting for Java 7 to generate Java 6-compatible classes? I am looking for a solution that doesn’t turn into an ugly mess :), so ideally I can write two implementations of an interface, one using the new features and one without, and then select one dynamically instead of having to do reflective calls all over the place. A: Just build with -target 1.6 and organize your code so you can catch the ClassNotFoundExceptions and NoClassDefFoundErrors cleanly around the modules that use 1.7. Maybe load them with a separate class-loader for example. A: You can build for java 1.6 easily as toolkit has pointed out. However, you need to make sure that you don't accidentally access any methods which don't exist in java 6. This will cause a runtime exception in your production code. If you're using maven, you can use the maven-enforcer-plugin which makes sure that no java 1.7 classes or method calls sneak into your code built for 1.6. An example would be the change from java 1.4 to 1.5. I was building with 1.5 with a target of 1.4, and I accidentally used: new BigDecimal(5); This compiled fine, and ran fine for me. But because the client was still using 1.4, it failed. Because this constructor doesn't exist in 1.4. It was introduced in 1.5. Another solution would be to build a couple of jars, one with the new nio stuff, one with the old stuff, and detect at installation time whether or not the user was running java 1.7. If so, add the jar that contains the appropriate implementation. A: For some elements that were added in Java 7, you might be able to find Java 6 jsr jars that give you the functionality. I do not believe this will be the case for the File System Watcher however. A: In terms of file system watchers, before Java 7 I used to just poll a file's properties every few seconds or so to check it hadn't changed. It's not exactly nice, but practically it uses no noticeable resources and from an end user's perspective appears to work the same. If you're after a more comprehensive library, check out http://commons.apache.org/jci/commons-jci-fam/index.html - I believe that does something similar, though I've never used it. Specifying source 1.7 and target 1.6 I'm pretty sure won't work, I tried it for a different reason a while back and from memory the JVM complained about incompatible flags (my guess is because of the new invokedynamic in 7.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7598789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Is there a similar object to session with windows form I'm a little new to windows forms. I would like a way to persist data across my windows form application. I am using a static dictionary that I setup in my program.cs file. I do not wat to pass this data manually from form to form in the constructor. Thank you. A: maybe you want to have a singleton class that holds that information ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7598790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Am I missing something, when filtering this observable collection? I have a routine which parses data from an xml feed. ... matches.Add(_item); } And shortly after this I want to only include the items which match my where clause if (this.MatchType == FixtureType.Played) { matches = matches.ToList().Where( m => m.matchResult == "D" ).ToObservableCollection(); } after this if I put a breakpoint on, I notice that matches now contains the items I am looking for. The problem now is that the control that is databound to the observablecollection still has the preliminary data. A: The problem is that there are 2 ObservableCollection instances in this scenario * *The original one which the control is bound to *The new one you created with the ToObservableCollection call In order to get the new results to display in the Control you need to rebind it to the new ObservableCollection instance. That or modify the original instance inline. var results = matches.Where(m => m.matchResult == "D").ToList(); matches.Clear(); foreach (var cur in results) { matches.Add(cur); } A: That is because your control reefers to the old instance of matches, you are creating a new observable collection and assigning that to matches, but your control is not bound to the matches variable, but to the value matches had when it was bound. You should instead modify matches and remove all those items not matching your condition. A: I would ask why are you having a programmatic variable to Bind to. Using an MVVM framework such as MVVM Light sorts out these kinds of scenarios very nicely. Just have a property in the view model and bind you view to that, when ever you then update the view model the page will be automatically updated, simples. There are many examples of this, including the databound template in the DEV tools (which implements basic notifypropertychanged behaviours) a better way is to upscale to MVVM light (http://mvvmlight.codeplex.com) or further with the likes of Calburn.Micro (http://caliburnmicro.codeplex.com/)
{ "language": "en", "url": "https://stackoverflow.com/questions/7598792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Setting DJANGO_SETTINGS_MODULE under virtualenv? I want the environment variable DJANGO_SETTINGS_MODULE to change depending on what I say for workon. It seemed to me that I want to set it in .virtualenvs/postmkvirtualenv but my trial had no effect. ftpmaint@millstone:~$ cat ~/.virtualenvs/postmkvirtualenv #!/bin/bash # This hook is run after a new virtualenv is activated. export DJANGO_SETTINGS_MODULE=newproject.settings ftpmaint@millstone:~$ echo $DJANGO_SETTINGS_MODULE az.settings ftpmaint@millstone:~$ workon newproject (newproject)ftpmaint@millstone:~$ echo $DJANGO_SETTINGS_MODULE az.settings Could someone set me straight; where should I put that export? In addition, will it restore when I deactivate? And if not, is there some natural way to restore it? A: One way I've done that before is by appending an export statement to the end of ./bin/activate export DJANGO_SETTINGS_MODULE="myproject.settings" A: You were on the right track, but you want to use the postactivate hook instead of postmkvirtualenv. It won't restore automatically on deactivate. Thankfully there is postdeactivate hook that you can use to manually restore any environmental variables that you changed on activate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Add to favorites function? I have this problem understanding how to save data in order to have an "add to favorites" function to my app. The app has an UITableView and the data is stored in a Plist. From there it goes into a DetailView containing an UIImageView and an UITextView. I want to be able to bookmark the items i like and display them in a separate view. Here is a piece of the code to make it easier to see: //BooksLibraryDao.h #import <Foundation/Foundation.h> @interface BooksLibraryDao : NSObject { NSString *libraryPlist; NSArray *libraryContent; } @property (nonatomic, readonly) NSString *libraryPlist; @property (nonatomic, readonly) NSArray *libraryContent; - (id)initWithLibraryName:(NSString *)libraryName; - (NSDictionary *)libraryItemAtIndex:(int)index; - (int)libraryCount; @end //BooksLibraryDao.m #import "BooksLibraryDao.h" @implementation BooksLibraryDao @synthesize libraryContent, libraryPlist; - (id)initWithLibraryName:(NSString *)libraryName { if (self = [super init]) { libraryPlist = libraryName; libraryContent = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:libraryPlist ofType:@"plist"]]; } return self; } - (NSDictionary *)libraryItemAtIndex:(int)index { return (libraryContent != nil && [libraryContent count] > 0 && index < [libraryContent count]) ? [libraryContent objectAtIndex:index] : nil; } - (int)libraryCount { return (libraryContent != nil) ? [libraryContent count] : 0; } - (void) dealloc { if (libraryContent) [libraryContent release]; [super dealloc]; } @end //BooksTableViewController.h #import <UIKit/UIKit.h> #import "BooksLibraryDao.h" #import "BooksListingViewCell.h" #import "BooksAppDelegate.h" @interface BooksTableViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource> { IBOutlet UITableView *booksTableView; BooksLibraryDao *dao; IBOutlet BooksListingViewCell *_cell; } @end //BooksTableViewController.m #import "BooksTableViewController.h" #import "DetailViewController.h" #import "BooksListingViewCell.h" #import "BooksNavController.h" @implementation BooksTableViewController #define CELL_HEIGHT 70.0 #pragma mark - #pragma mark Initialization /* - (id)initWithStyle:(UITableViewStyle)style { // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. self = [super initWithStyle:style]; if (self) { // Custom initialization. } return self; } */ #pragma mark - #pragma mark View lifecycle - (void)viewDidLoad { [super viewDidLoad]; self.tableView.backgroundColor = [UIColor clearColor]; } - (void)viewWillAppear:(BOOL)animated { dao = [[BooksLibraryDao alloc] initWithLibraryName:@"TestData"]; self.title = @"Books"; [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES]; } #pragma mark - #pragma mark Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [dao libraryCount]; } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"LibraryListingCell"; BooksListingViewCell *cell = (BooksListingViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { [[NSBundle mainBundle] loadNibNamed:@"BooksListingView" owner:self options:nil]; cell = [_cell autorelease]; _cell = nil; } cell.titleLabel.text = [[dao libraryItemAtIndex:indexPath.row] valueForKey:@"title"]; cell.smallImageView.image = [UIImage imageNamed:[[dao libraryItemAtIndex:indexPath.row] valueForKey:@"smallImage"]]; cell.backgroundColor = [UIColor colorWithRed:9 green:9 blue:9 alpha:.7]; cell.textLabel.backgroundColor = [UIColor clearColor]; cell.textLabel.textColor = [UIColor colorWithRed:.1 green:.1 blue:.1 alpha:1]; cell.selectedBackgroundView = [[[UIImageView alloc] init] autorelease]; UIImage *selectionBackground; selectionBackground = [UIImage imageNamed:@"cell.png"]; ((UIImageView *)cell.selectedBackgroundView).image = selectionBackground; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { DetailViewController *controller = [[DetailViewController alloc] initWithBookData:[dao libraryItemAtIndex:indexPath.row] nibName:@"DetailViewController" bundle:[NSBundle mainBundle]]; controller.title = [[dao libraryItemAtIndex:indexPath.row] valueForKey:@"title"]; [self.navigationController pushViewController:controller animated:YES]; [controller release]; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return CELL_HEIGHT; } #pragma mark - #pragma mark Table view delegate #pragma mark - #pragma mark Memory management - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Relinquish ownership any cached data, images, etc. that aren't in use. } - (void)viewDidUnload { // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand. // For example: self.myOutlet = nil; } - (void)dealloc { [super dealloc]; } @end //DetailViewController.h #import <UIKit/UIKit.h> #import <MessageUI/MessageUI.h> #import <MessageUI/MFMailComposeViewController.h> #import <QuartzCore/QuartzCore.h> @interface DetailViewController : UIViewController <MFMailComposeViewControllerDelegate>{ IBOutlet UIImageView *bookImageView; IBOutlet UILabel *titleLabel; IBOutlet UITextView *authorTextView; IBOutlet UITextView *descriptionTextView; IBOutlet UILabel *message; NSDictionary *bookData; } @property (nonatomic, retain) UIImageView *bookImageView; @property (nonatomic, retain) UILabel *titleLabel; @property (nonatomic, retain) UITextView *descriptionTextView; @property (nonatomic, retain) UITextView *authorTextView; @property (nonatomic, retain) IBOutlet UILabel *message; -(IBAction)showPicker:(id)sender; -(void)displayComposerSheet; -(void)launchMailAppOnDevice; -(IBAction)showAuthor; -(IBAction)showDesc; -(IBAction)showImage; - (id)initWithBookData:(NSDictionary *)data nibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil; @end //DetailViewController.m #import "DetailViewController.h" @implementation DetailViewController @synthesize bookImageView, titleLabel, descriptionTextView, authorTextView; @synthesize message; - (id)initWithBookData:(NSDictionary *)data nibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { bookData = data; } return self; } - (void)viewDidLoad { bookImageView.image = [UIImage imageNamed:[bookData valueForKey:@"bookImage"]]; titleLabel.text = [bookData valueForKey:@"title"]; descriptionTextView.text = [bookData valueForKey:@"description"]; authorTextView.text = [bookData valueForKey:@"author"]; [super viewDidLoad]; } A: You've got one of a few options for implementing favourites (really depends mostly on whether your data is persistent). * *(A) You can add a marker for each item you display in your table, which marks it as a favourite - then just refer to the same data set but filter it for said marker. Or... *(B) You can create an additional list holding a copy of each item you want to mark as a favourite and then refer to that new list as your datasource. If your data isn't persistent, you could still use method A and when data is refreshed only retain the marked records before you insert the new, fresh data. Hope that makes sense!
{ "language": "en", "url": "https://stackoverflow.com/questions/7598794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: About shortcut/feature in xcode 4 Hi guys (and probably girls). I'm newcomer to xcode land. TextMate have a feature to jump to specific file. For example if I press cmd+t a window appears and there I can type the name of file I'm looking for (this feature search only files in current projecet). When I hit enter voalla I get the file open and ready to edit. Is there a such feature in Xcode 4 ? A: Yes, there is. cmd + shift + o would be the sequence.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Totally unable to find jp.sourceforge.pdt_tools.formatter I would like to add a PHP formatter to my Eclipse Helios (3.6 SR2) installation, but I'm not able to find any place to download a jp.sourceforge.pdt_tools.formatter (any version which can added to the Helios SR2)... I searched 1 hour on google, on torrent sites, download programs like emule, on megaupload and other shared files system, but no result. On the official website (http://de.sourceforge.jp/projects/pdt-tools/) project is closed and I can't find it on any site on the web... If anyone has this jar file and can share it, it would be very helpful. Thanks in advance A: The only files I'm still able to find to download are here: http://sourceforge.jp/users/atlanto/pf/eclipse/files/?id=477 v1.2.1 works in Eclipse Indigo with PDT 3.0. A: Try Eclipse PHP Development Tools project. A: @KRavEN Atlanto (the original author) is not maintaining the formatter plugin anymore so i've integrated the formatter from that plugin into my PDT extensions: https://github.com/pulse00/PDT-Extensions. You'll find the updatesite for it on http://pulse00.github.com/p2/
{ "language": "en", "url": "https://stackoverflow.com/questions/7598796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to delete from the 64 bit registry under XP? I'm making an application, and i need to write some stuff in the registry, and later edit them if neccessary. I'm writing to the 64 bit registry using KEY_WOW64_64KEY. I created my Key Software\MyApp and here some other values 5 or 6. My problem is the following. I have the following code to read every values, under a key void ReadAndDeleteValues( HKEY hKey ) { //TCHAR achKey[ MAX_KEY_LENGTH ]; // buffer for subkey name //DWORD cbName; // size of name string TCHAR achClass[ MAX_PATH ] = TEXT(""); // buffer for class name DWORD cchClassName = MAX_PATH; // size of class string DWORD cSubKeys=0; // number of subkeys DWORD cbMaxSubKey; // longest subkey size DWORD cchMaxClass; // longest class string DWORD cValues; // number of values for key DWORD cchMaxValue; // longest value name DWORD cbMaxValueData; // longest value data DWORD cbSecurityDescriptor; // size of security descriptor FILETIME ftLastWriteTime; // last write time DWORD i, retCode; TCHAR achValue[ MAX_VALUE_NAME ]; DWORD cchValue = MAX_VALUE_NAME; // Get the class name and the value count. retCode = RegQueryInfoKey( hKey, // key handle achClass, // buffer for class name &cchClassName, // size of class string NULL, // reserved &cSubKeys, // number of subkeys &cbMaxSubKey, // longest subkey size &cchMaxClass, // longest class string &cValues, // number of values for this key &cchMaxValue, // longest value name &cbMaxValueData, // longest value data &cbSecurityDescriptor, // security descriptor &ftLastWriteTime // last write time ); if ( cValues > 0 ) printf( "\nNumber of values: %d\n", cValues ); for ( i = 0, retCode = ERROR_SUCCESS; i < cValues; i++ ) { cchValue = MAX_VALUE_NAME; achValue[ 0 ] = '\0'; retCode = RegEnumValue( hKey, i, achValue, &cchValue, NULL, NULL, NULL, NULL ); if ( retCode == ERROR_SUCCESS ) { DWORD cbData = 8192; DWORD dwRet; DWORD type = 0; wchar_t PerfData[ 2048 ] = { 0 }; memset( PerfData, 0, wcslen( PerfData ) ); dwRet = RegQueryValueEx( hKey, achValue, NULL, &type, ( LPBYTE )PerfData, &cbData ); if ( dwRet == ERROR_SUCCESS ) ;//do nothing else printf( "\n\nRegQueryValueEx Failed!" ); _tprintf( TEXT( "\n #%.3d - [ %-30s ]" ), i + 1, achValue ); RegDeleteValue( hKey, achValue ); }//if }//for }//ReadValues It works fine, so i thought, i just place RegDeleteValue there and every Value will be deleted. Unfortunately this is not what's happening. This API will delete only 2-3 values, then returns. If i run it again, then it will delete 2-3 values again and returns again, but i don't know why???? Theoratically if i a find a vale, i can delete, so i don't understand, why is this happening. Could someone help me correct my code? Thanks! A: Your program deletes only a few values because of the classic 'deleting from array' mistake, like in this pseudocode: // this program will not remove all elements for (int i = 0, n = arraySize; i < n; ++i) array_remove(array, i); // step 1, i=0: 1 2 3 4 5 6 // ^ removed // step 2, i=1: 2 3 4 5 6 // ^ removed // step 3, i=2: 2 4 5 6 // ^ removed // step 4, i=3: 2 4 6 // ^ RegEnumValue returns error and the loop exits A correct way will be something like: while (cValues > 0) { /* delete registry value at index 0 */ --cValues; } To quickly fix your code, replace the second parameter of RegEnumValue() with 0.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a way to know the time remaining for the alarm to go off or the elapsed time since alarm started from API Assume I set alarm to off after 8 hours from now using AlarmManager. I exit the App and open it back. Now I want to know the time remaining for the alarm to go off or the elapsed time since alarm started. Is there a way to know this from Android API. Of course one way is by the calculation of (currentTime - Alarm started time). But if the user changes his device time then it's a problem. Thanks A: Is there a way to know this from Android API. No, sorry. Of course one way is by the calculation of (currentTime - Alarm started time). But if the user changes his device time then it's a problem. The alarm will behave the same as your proposed logic, AFAIK. If you use an RTC or RTC_WAKEUP alarm, it will go off at your stated time, regardless of whether or not the time on the device changed. Conversely, if you use ELAPSED_REALTIME or ELAPSED_REALTIME_WAKEUP, then whether the time on the device changed is irrelevant.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to loop through a map and assign the value to an array in C++? I have a map<id,age>,; how to get the age of each <id,age> pair, and assign the age to a C-style array in C++? what is the efficient way to do it? I mean how to fill the C-style array in the same order as map? A: If you decide to stick with the fixed array approach //Assuming both id and age are integers map<int,int> myMap; // Your id and age map map<int,int>::iterator it; int myList[100]; int i = 0; for(it = myMap.begin(); (i < 100 && it != myMap.end()); it++) { myList[i++] = (*it).second; } A MUCH better approach is to use a vector instead of an array //Assuming both id and age are integers map<int,int> myMap; // Your id and age map map<int,int>::iterator it; vector<int> myList; for(it = myMap.begin(); it != myMap.end(); it++) { myList.push_back((*it).second); } A: If you can use c++11 you can use a lambda expression. map<id,age> m; std::list<age> l; std::for_each(m.begin(), m.end(), [&l](std::pair<id,age> p){ l.push_back(p.second); }); A: I don't think what you're asking makes a lot of sense, but in the interest of just fiddling with C++ containers (Note:: not using any C++0x features) http://ideone.com/Kf2du Edit In response to the excellent comments by David Rodríguez, I have edited the code to avoid copying (see also https://ideone.com/7Oa5n): #include <map> #include <list> #include <algorithm> #include <iterator> #include <vector> typedef std::map<std::string, int> map_t; int getage(const map_t::value_type& pair) { return pair.second; } int main() { map_t agemap; agemap["jill"] = 13; agemap["jack"] = 31; std::list<int> agelist(agemap.size()); std::transform(agemap.begin(), agemap.end(), agelist.begin(), getage); // or: std::vector<int> v; std::transform(agemap.begin(), agemap.end(), std::back_inserter(v), getage); } By popular demand, and just to spell it out: int age_array[10]; std::transform(agemap.begin(), agemap.end(), age_array, getage); or even int *dyn_array = new int[agemap.size()]; std::transform(agemap.begin(), agemap.end(), dyn_array, getage); // ... delete[] dyn_array; A: You've stated you want a C array and I'll answer particularly your request. std::map<int,int> some_map; int * c_array=new int[some_map.size()]; size_t k=0; for (std::map<int,int>::iterator i=some_map.begin(); i != some_map.end(); ++i) { c_array[k++]=(*i).second; } delete[] c_array; As others have stated, the standard for C++ would be the vector. I would add, you would want to reserve the proper space before-hand since you already know it. It can be reserved via the c-tor for a vector. std::map<int,int> some_map; std::vector<int> some_vector(some_map.size()); for (std::map<int,int>::iterator i=some_map.begin(); i != some_map.end(); ++i) { some_vector.push_back((*i).second); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7598800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: GWT RPC Failure Call I am getting this error - [WARN] 404 - POST /gwtmaps/mapService (127.0.0.1) 1404 bytes Request headers Host: 127.0.0.1:8888 Connection: keep-alive User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.186 Safari/535.1 Accept: */* Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Content-Length: 163 Origin: http:/ /127.0.0.1:8888 X-GWT-Module-Base: http:/ /127.0.0.1:8888/gwtmaps/ X-GWT-Permutation: HostedMode Content-Type: text/x-gwt-rpc; charset=UTF-8 Referer: http: //127.0.0.1:8888/GWTMaps.html?gwt.codesvr=127.0.0.1:9997 Response headers Content-Type: text/html; charset=iso-8859-1 Content-Length: 1404 failure with my gwt.xml file <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 1.6.2//EN" "http://google-web-toolkit.googlecode.com/svn/tags/1.6.2/distro-source/core/src/gwt-module.dtd"> <module rename-to='gwtmaps'> <!-- Inherit the core Web Toolkit stuff. --> <inherits name='com.google.gwt.user.User'/> <!-- Inherit the default GWT style sheet. You can change --> <!-- the theme of your GWT application by uncommenting --> <!-- any one of the following lines. --> <!-- <inherits name='com.google.gwt.user.theme.clean.Clean'/>--> <inherits name='com.google.gwt.user.theme.standard.Standard'/> <!-- <inherits name='com.google.gwt.user.theme.chrome.Chrome'/> --> <!-- <inherits name='com.google.gwt.user.theme.dark.Dark'/> --> <!-- Other module inherits --> <inherits name="com.google.gwt.maps.GoogleMaps" /> <script src="http://maps.google.com/maps?gwt=1&amp;file=api&amp;v=2&amp;sensor=false" /> <!-- Specify the app entry point class. --> <entry-point class='com.mymaps.client.GWTMaps'/> <servlet class = "com.mymaps.server.MapServiceImpl" path="/mapService"/> <!-- Specify the paths for translatable code --> <source path='client'/> <source path='shared'/> and web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"> <welcome-file-list> <welcome-file>GWTMaps.html</welcome-file> </welcome-file-list> <!-- Servlets --> <servlet> <servlet-name>MapService</servlet-name> <servlet-class> com.mymaps.server.MapServiceImpl </servlet-class> </servlet> <servlet-mapping> <servlet-name>MapService</servlet-name> <url-pattern>/com.mymaps.MapService/gwtmaps/mapService</url-pattern> </servlet-mapping> <!-- Default page to serve --> </web-app> any ideas? i keep trying new theorys but cant get any to show a success. Thanks! A: You may need to add the @RemoteServiceRelativePath annotation to the client-side, synchronous interface of your service. For example: @RemoteServiceRelativePath("mapService") public interface MapService extends RemoteService { ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7598802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Silverlight: disable automatic first-row selection after DataGrid binding I have a Silverlight DataGrid, a DataPager and a PagedCollectionView. After the PagedCollection view is bound to the DataGrid, the first row of the DataGrid is selected. This behaviour does not happen, if i am using an ObservableCollection. But due to the DataPager, I need to use the PagedCollectionView. I am using Silverlight 5 RC, and the SL 4 Toolkit. Example of Usage: View: <sdk:DataGrid x:Name="gridSomeItems" ItemsSource="{Binding SomeItems, Mode=TwoWay}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}" CanUserSortColumns="True"> <sdk:DataGrid.Columns> <sdk:DataGridTextColumn Header="Column1" Width="*" Binding="{Binding Column1}" /> </sdk:DataGrid.Columns> </sdk:DataGrid> <sdk:DataPager Source="{Binding Path=ItemsSource, ElementName=gridSomeItems}"/> ViewModel: public class SomeViewModel : ViewModelBase { public SomeViewModel(IDataAccess dataAccess) { _dataAccess = dataAccess; _dataAccess.GetSomeItemsCompleted += GetSomeItemsCompleted; _dataAccess.GetSomeItems(); } public PagedCollectionView SomeItems { get; set; } public SomeItem SelectedItem { get; set; } private void GetSomeItemsCompleted(GetSomeItemsCompletedEventArgs e) { SomeItems = new PagedCollectionView(e.Result.SomeItems); RaisePropertyChanged("SomeItems"); } } A: The best workaround is to set a _isLoading flag. The following code would be the correct code for the ViewModel: public class SomeViewModel : ViewModelBase { private bool _isLoading; public SomeViewModel(IDataAccess dataAccess) { _dataAccess = dataAccess; _dataAccess.GetSomeItemsCompleted += GetSomeItemsCompleted; _isLoading = true; _dataAccess.GetSomeItems(); } public PagedCollectionView SomeItems { get; set; } public SomeItem SelectedItem { get; set; } private void GetSomeItemsCompleted(GetSomeItemsCompletedEventArgs e) { SomeItems = new PagedCollectionView(e.Result.SomeItems); SomeItems.CurrentChanged += CurrentItemChanged; RaisePropertyChanged("SomeItems"); SomeItems.MoveCurrentTo(null); _isLoading = false; } private void CurrentItemChanged(object sender, System.EventArgs e) { if (!_isLoading) { SelectedItem = SomeItems.CurrentItem as SomeItem; // Do something more... } } } Please have a look at the row SomeItems.MoveCurrentTo(null); - This command really sets the CurrentItem of the PagedCollectionView to null (not selected). It is still a workaround... Would be great if anybody came up with a better solution. A: Not sure why that is happening unless you are somehow setting the SelectedItem property in your code somehow. A simple solution to the problem would be to use a Behavior on the DataGrid that sets the SelectedIndex to -1 when the loaded event fires. A: The first thing that comes to mind is that you need to do something like: private PagedCollectionView someItems; public PagedCollectionView SomeItems { get { return someItems; } set { if (someItems != value) { someItems = value; RaisePropertyChanged("SomeItems"); } } } And implement that same strategy for SelectedItem. A: I solved the situation by putting the MoveCurrentTo(null) inside the PageIndexChanged event. Like that: * *XAML <data:DataPager x:name="pager" PageIndexChanged="dataPagerGroup_PageIndexChanged" /> *C# private void PageIndexChanged(object sender, EventArgs e) { (this.pager.Source as PagedCollectionView).MoveCurrentTo(null); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7598807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: DBD::mysql::st fetchrow_array failed: fetch() without execute() fetchrow_hashref working fine, but when i use fetchrow_array getting following Error. #!/usr/bin/perl use warnings; use DBI; $DB_name = 'database'; $DB_user = 'root'; $DB_pwd = ''; my $dsn = 'dbi:mysql:avm:localhost:3306'; $dbh = DBI->connect($dsn,"$DB_user","$DB_pwd"); print "\nConnection error: $DBI::errstr\n\n"; $sth = $dbh->prepare("SELECT * FROM tblmanufacturer"); $sth->execute(); while ( ($id,$name) = $sth->fetchrow_array() ) { print "$id\t\t $name \n"; } $sth->finish(); $dbh->disconnect(); DBD::mysql::st fetchrow_array failed: fetch() without execute() at A: I always use "die" on error at both "execute" and "prepare". $sql = $dbh->prepare( $query ) or die "Unable to prepare $query" . $dbh->errstr; $sql->execute() or die "Unable to execute '$query'. " . $sql->errstr; A: Check the return value of execute() and/or print "$DBI::errstr\n\n" and see if execute is failing. print $sth->execute(),"\n"; A: Another way is to capture the errors with a error handler, do what ever you need to them (send it to your log file, print them, die or continue executing the script). This eliminates the need of " or die() " after every method. Documentation about the HandleError method can be found here. For starters take this simple example: #!/usr/bin/perl use strict; use warnings; use DBI; my $DB_name = 'database'; my $DB_user = 'root'; my $DB_pwd = ''; my $dsn = 'dbi:mysql:avm:localhost:3306'; my ($sth, $id, $name); my $dbh = DBI->connect($dsn,$DB_user,$DB_pwd, { PrintError => 0, ShowErrorStatement => 1, HandleError => \&dbi_error_handler,} ); $sth = $dbh->prepare("SELECT * FROM tblmanufacturer"); $sth->execute(); while ( ($id,$name) = $sth->fetchrow_array() ) { print "$id\t\t $name \n"; } $sth->finish(); $dbh->disconnect(); sub dbi_error_handler { my( $message, $handle, $first_value ) = @_; # print to your log file, call your own logger etc ... # here it will die() to be similar to "or die()" method, but the line number is incorect die($message); # if you return false it will check/execute RaiseError and PrintError return 1; } P.S. There is no reason to encapsulate yout string variables in quotes here :($dsn,"$DB_user","$DB_pwd");, don't do it, for more info about that, read this. A: I got this error in apache fcgid due to reusing $sth before I was finished with it. I was only seeing it in the apache error log. Putting in "or die ..." after prepare and execute statements did nothing to help, and the script appeared to work fine anyway (in normal use there was only one row fetched, but there was a possibility of more) as it had done what was expected before the error was encountered. Errors were just appearing in the Apache log. Simple fix, renamed $sth to $osth and problem went away. If you are seeing this error and re-using statement handles, try using unique statement handles to see if the problem goes away. # rename to $ostmt my $stmt="SELECT ..."; # rename to $osth my $sth=$dbh->prepare($stmt) or die "Unable to prepare $stmt" . $dbh->errstr; $sth->execute() or die "Unable to execute '$stmt'. " . $sth->errstr; while( my ( $f1, $f2 ... ) = $sth->fetchrow_array() ){ # redeclare $stmt and $sth below using my $stmt, my $sth $stmt="SELECT ..."; $sth=$dbh->prepare($stmt) or die "Unable to prepare $stmt" . $dbh->errstr; $sth->execute($f1) or die "Unable to execute '$stmt'. " . $sth->errstr; my ( @stuff ) = $sth->fetchrow_array(); # ... # do lots of stuff # ... # output fcgi content } # error kicks in here It was considerably more involved than the sample above but the error was very unhelpful so I'm leaving this answer in case it helps someone else.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Precisely measure execution time of code in thread (C#) I'm trying to measure the execution time of some bits of code as accurately as possible on a number of threads, taking context switching and thread downtime into account. The application is implemented in C# (VS 2008). Example: public void ThreadFunc () { // Some code here // Critical block #1 begins here long lTimestamp1 = Stopwatch.GetTimestamp (); CallComplex3rdPartyFunc (); // A long lTimestamp2 = Stopwatch.GetTimestamp (); // Critical block #1 ends here // Some code here // Critical block #2 begins here long lTimestamp3 = Stopwatch.GetTimestamp (); CallOtherComplex3rdPartyFunc (); // B long lTimestamp4 = Stopwatch.GetTimestamp (); // Critical block #2 ends here // Save timestamps for future analysis. } public int Main ( string[] sArgs ) { // Some code here int nCount = SomeFunc (); for ( int i = 0; i < nCount; i++ ) { Thread oThread = new Thread ( ThreadFunc ); oThread.Start (); } // Some code here return ( 0 ); } I'd like to measure the execution time of the above two critical code blocks as accurately as possible. The two calls marked as A and B are potentially long function calls that may sometimes take several seconds to execute but in some cases they may complete in a few milliseconds. I'm running the above code on a number of threads - somewhere between 1 to 200 threads, depending on user input. The computers running this code have 2-16 cores - users use lower thread counts on the weaker machines. The problem is that A and B are both potenitally long functions so it's very likely that at least one context switch will happen during their execution - possibly more than one. So the code gets lTimestamp1, then another thread starts executing (and the current thread waits). Eventually the current thread gets back control and retrieves lTimestamp2. This means that the duration between lTimestamp1 and lTimestamp2 includes time when the thread was not actually running - it was waiting to be scheduled again while other threads executed. The tick count, however, increases anyway, so the duration is now really Code block time = A + B + some time spent in other threads while I want it to be only Code block time = A + B This is especially an issue with a larger number of threads, since they'll all get a chance to run, so the above timings will be higher while all other threads run before the thread in question gets another chance to run. So my question is: is it possible to somehow calculate the time when the thread is not running and then adjust the above timings accordingly? I'd like to eliminate (subtract) that 3rd term entirely or at least as much of it as possible. The code runs millions of times, so final timings are calculated from a lot of samples and then averaged out. I'm not looking for profiler products, etc. - the application needs to time these the marked parts as accurately as possible. The functions A and B are 3rd party functions, I cannot change them in any way. I'm also aware of the possible fluctuations when measuring time with nanosecond precision and possible overhead inside those 3rd-party functions, but I still need to do this measurement. Any advice would be greatly appreciated - C++ or x86 assembly code would work as well. Edit: seems to be impossible to implement this. Scott's idea below (using GetThreadTimes) is good but unfortunately GetThreadTimes() is a flawed API and it almost never returns correct data. Thanks for all the replies! A: You can use Stopwatch.Start() and Stopwatch.Stop() methods to pause/continue time measurement, it does not reset Elapsed/ElapsedMilliseconds value so perhaps you can leverage this. Regarding thread context switches - I believe there are no ways to handle it in managed code so this is not possible to exclude time when thread was suspended EDIT: An interesting article with benchmarks: How long does it take to make a context switch? A: This can be done with the Native API call GetThreadTimes. Here is a article on CodeProject that uses it. A second option is use QueryThreadCycleTime. This will not give you the time, but it will give you the number of cycles the current thread has been executing. Be aware you can't just directly convert cycles->seconds due to the fact that many processors (especially mobile processors) do not run at a fixed speed so there is no constant number you could multiply by to get the elapsed time in seconds. But if you are using a processor that does not vary its speed it then would be a simple math problem to get wall clock time from the cycles.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How can I handle Node.js dependencies in a project on git with NPM? I've run into this scenario quite a few times and still haven't found the answer. I'm starting a new Node.js project, and this project will be dependent on some other libraries. For sake of argument, let's say that some are purely JS libraries that could be added as git submodules in the new project, but some have pieces that need some extra effort (such as system dependencies that npm installs, or C libraries that must be compiled). What's the best way to start this project and add it to git, with the following two requirements: * *Other people's libraries aren't committed to our own repo, and are instead submodules or are pulled in dynamically and installed by npm. *Not needing to have a big list of instructions that have to be followed just to clone the repo and have a working environment. Running git submodules update --init --recursive is fine, running an npm command to read package.json and install the dependencies is fine (does such a command exist?), but forcing everyone to run through an "npm install __" of every single dependency isn't ok, and I'd rather not use 'make' or 'ant' to do that if I don't have to. Any thoughts of the best way to do this? It seems like such a simple, basic thing, but I couldn't find a single example of what I'm trying to do. Edit: Grammar A: edit Ignore below, but left for reference. Sometimes I don't think clearly in the morning :) make a package.json file, add your dependencies and your install simply becomes: npm install from your project directory. git ignore all the added projects. npm submodule foo It installs the packages into node_modules via git submodule so github, etc will recognize that they're link. This works whenever the npm package has a git URI included. Unfortunately a good number don't, so you're out of luck on those. Also, note that when you do this, npm won't work on the module any longer, e.g. you can't update via npm, you have to do it via git Or you could just do something like: ./modules.js modules.exports = [ 'express@1.0', 'jade@2.0', 'stylus@3.0' ]; ./make #!/usr/bin/env node var modules = require( './modules' ) , spawn = require('child_process').spawn; for( var i=0, l=modules.length; i<l; i++ ){ spawn( 'npm', [ 'install', modules[i] ] ); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7598814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: HttpDelete request with JSON payload in Android I need to call a web service to delete data, and I need to do it using HttpDelete. The service takes a JSON object as parameter. I have done HttpPost before, using SetEntity, but this is not available with HttpDelete. It's a call like http://url/DELETE/service and something like { id: "xxxxxxx", id2: 11 } as parameter. I can't find any good info on this. Any ideas? A: RFC2616 doesn't specify anything about a entity on an HTTP DELETE request. I would say your best bet is to pass the values you need in the path of your request. http: //url/DELETE/service/xxxxxx/11 A: You can not send a body in a HTTP DELETE request. If you need to do that, there is probably something wrong with your REST design. Why not http://url/srvice/xxxxxx/11 instead of http://url/DELETE/service with a body ? A: The id is most likely passed in the url OR possibly could be passed in a header value. Here's an example: HttpDelete httpdelete = new HttpDelete(targetURL); httpdelete.setHeader("id",id); // If not in the url, this could be where the id is set. A: There are use cases when this would be awesome. One I'm running into now is a need for a "bulk delete". Basically, for efficiency reasons, deleting one entry at a time is way slower than it would be to delete multiple entries at once. I'm forced to use POST and be un-RESTful. In my opinion, this is a design flaw in REST, or at least a design limitation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: java.lang.RuntimeException: java.net.UnknownHostException: Host is unresolved: I am having a problem while parsing XML file,i used newsRSS parser as a reference.but i am getting this error in the real device.how to display an error message like alert for the user and let him stay on the app without crashing? this is the peace of the code that do the connection and parsing: protected Config_Parser(String feedUrlString,Context context){ this.context = context; try { this.feedUrl = new URL(feedUrlString); } catch (MalformedURLException e) { throw new RuntimeException(e); } } protected InputStream getInputStream() { try { return feedUrl.openConnection().getInputStream(); } catch (IOException e) { Log.e("Error", "error happned"); return null; //throw new RuntimeException(e); } } how may i handle this error with sending alert to the user without crashing or exiting the application? Thanks for help :) A: If this works in the emulator and not on your device it is most likely because you do not have InternetConnection on your device or the Feed URL that you are trying to access is not accessible from the Network that your device is connected too. A: i already has this problem , the host is unresolved means that the url is unreachable , or your connection is tooo Sloow . try to test your programm with another Internet Connexion which has a good Bandwidth : Also , check that your Emulator display the icon of 3G .
{ "language": "en", "url": "https://stackoverflow.com/questions/7598817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error when attempting to open .xib in XCodeInterfaceBuilder I downloaded the Red Laser MonoTouch sample and ran the project in MonoDevelop, I had to first update the solution file so that it would load up in MonoDevelop. When I try to view one of the .xib files in the Xcode Interface builder I get the error: Error updating Xcode project. Could not generate outlet 'overlayController' in class 'RedLaserSample.RLSampleViewController' as its type 'RedLaserSample.OverlayController' could not be resolved to Obj-C. Details: MonoDevelop.MacDev.ObjCIntegration.ObjectiveCGenerationException: Could not generate outlet 'overlayController' in class 'RedLaserSample.RLSampleViewController' as its type 'RedLaserSample.OverlayController' could not be resolved to Obj-C at MonoDevelop.MacDev.ObjCIntegration.NSObjectTypeInfo.GenerateObjcType (System.String directory) [0x001bf] in /private/tmp/source/monodevelop/main/src/addins/MonoDevelop.MacDev/ObjCIntegration/NSObjectTypeInfo.cs:116 at MonoDevelop.MacDev.XcodeSyncing.XcodeSyncedType.SyncOut (MonoDevelop.MacDev.XcodeSyncing.XcodeSyncContext context) [0x00000] in /private/tmp/source/monodevelop/main/src/addins/MonoDevelop.MacDev/XcodeSyncing/XcodeSyncedType.cs:62 at MonoDevelop.MacDev.XcodeSyncing.XcodeMonitor.UpdateProject (IProgressMonitor monitor, System.Collections.Generic.List`1 allItems, MonoDevelop.MacDev.XcodeIntegration.XcodeProject emptyProject) [0x00318] in /private/tmp/source/monodevelop/main/src/addins/MonoDevelop.MacDev/XcodeSyncing/XcodeMonitor.cs:138 at MonoDevelop.MacDev.XcodeSyncing.XcodeProjectTracker.UpdateXcodeProject (IProgressMonitor monitor) [0x00000] in /private/tmp/source/monodevelop/main/src/addins/MonoDevelop.MacDev/XcodeSyncing/XcodeProjectTracker.cs:315 A: You need to add [Register ("OverlayController")] to your OverlayController class. A: If your OverlayController file is under a different project folder than the RLSampleViewController, which holds a reference to the OverlayController. Make sure that RLSampleViewController and OverlayController are in the same level or under same project folder. We have resolved the same issue by just simply moving the files directly under the project not a project folder. Please also refer to Registration and Namespaces in the Xamarin XIB Code Generation Documentation Page
{ "language": "en", "url": "https://stackoverflow.com/questions/7598818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Correct Singleton Pattern Objective C (iOS)? I found some information in the net to create a singleton class using GCD. Thats cool because it's thread-safe with very low overhead. Sadly I could not find complete solutions but only snippets of the sharedInstance method. So I made my own class using the trial and error method - and et voila - the following came out: @implementation MySingleton // MARK: - // MARK: Singleton Pattern using GCD + (id)allocWithZone:(NSZone *)zone { return [[self sharedInstance] retain]; } - (id)copyWithZone:(NSZone *)zone { return self; } - (id)autorelease { return self; } - (oneway void)release { /* Singletons can't be released */ } - (void)dealloc { [super dealloc]; /* should never be called */ } - (id)retain { return self; } - (NSUInteger)retainCount { return NSUIntegerMax; /* That's soooo non-zero */ } + (MySingleton *)sharedInstance { static MySingleton * instance = nil; static dispatch_once_t predicate; dispatch_once(&predicate, ^{ // --- call to super avoids a deadlock with the above allocWithZone instance = [[super allocWithZone:nil] init]; }); return instance; } // MARK: - // MARK: Initialization - (id)init { self = [super init]; if (self) { // Initialization code here. } return self; } @end Please feel free to comment and tell me if I've missing something or doing something completely wrong ;) Cheers Stefan A: Keep it simple: +(instancetype)sharedInstance { static dispatch_once_t pred; static id sharedInstance = nil; dispatch_once(&pred, ^{ sharedInstance = [[self alloc] init]; }); return sharedInstance; } - (void)dealloc { // implement -dealloc & remove abort() when refactoring for // non-singleton use. abort(); } That is it. Overriding retain, release, retainCount and the rest is just hiding bugs and adding a bunch of lines of unnecessary code. Every line of code is a bug waiting to happen. In reality, if you are causing dealloc to be called on your shared instance, you have a very serious bug in your app. That bug should be fixed, not hidden. This approach also lends itself to refactoring to support non-singleton usage modes. Pretty much every singleton that survives beyond a few releases will eventually be refactored into a non-singleton form. Some (like NSFileManager) continue to support a singleton mode while also supporting arbitrary instantiation. Note that the above also "just works" in ARC. A: // See Mike Ash "Care and Feeding of Singletons" // See Cocoa Samurai "Singletons: You're doing them wrong" +(MySingleton *)singleton { static dispatch_once_t pred; static MySingleton *shared = nil; dispatch_once(&pred, ^{ shared = [[MySingleton alloc] init]; shared.someIvar = @"blah"; }); return shared; } Be aware that dispatch_once is not reentrant, so calling itself from inside the dispatch_once block will deadlock the program. Don't try to code defensively against yourself. If you are not coding a framework, treat your class as normal then stick the singleton idiom above. Think of the singleton idiom as a convenience method, not as a defining trait of your class. You want to treat your class as a normal class during unit testing, so it's OK to leave an accessible constructor. Don't bother using allocWithZone: * *It ignores its argument and behaves exactly like alloc. Memory zones are no longer used in Objective-C so allocWithZone: is only kept for compatibility with old code. *It doesn't work. You can't enforce singleton behavior in Objective-C because more instances can always be created using NSAllocateObject() and class_createInstance(). A singleton factory method always returns one of these three types: * *id to indicate the return type is not fully known (case where you are building a class cluster). *instancetype to indicate that the type returned is an instance of the enclosing class. *The class name itself (MySingleton in the example) to keep it simple. Since you tagged this iOS, an alternative to a singleton is saving the ivar to the app delegate and then using a convenience macro that you can redefine if you change your mind: #define coreDataManager() \ ((AppDelegate*)[[UIApplication sharedApplication] delegate]).coreDataManager A: If you want to unit test your singleton you also have to make it so that you can replace it with a mock singleton and/or reset it to the normal one: @implementation ArticleManager static ArticleManager *_sharedInstance = nil; static dispatch_once_t once_token = 0; +(ArticleManager *)sharedInstance { dispatch_once(&once_token, ^{ if (_sharedInstance == nil) { _sharedInstance = [[ArticleManager alloc] init]; } }); return _sharedInstance; } +(void)setSharedInstance:(ArticleManager *)instance { once_token = 0; // resets the once_token so dispatch_once will run again _sharedInstance = instance; } @end
{ "language": "en", "url": "https://stackoverflow.com/questions/7598820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: return responseText from jQuery.get() I tried to do something like this : var msg = $.get("my_script.php"); I thought msg would be set to the text returned by my_script.php,i.e. the responseText of the jqXHR object. It apparently doesn't work like that as msg is always set to "[object XMLHttpRequest]" Is there a quick 1 line way to do what I want? Thanks. A: You can always use: var msg; $.get("my_script.php", function(text) { msg = text; }); If for some reason the response is text, the remote script might be changing the content-type to something like JSON, and thus jQuery tries to parse the string before outputting to you. A: After some testing, I ended up finding a solution. I need the call to be synchronous, $.get shorthand function is always asynchonous, so I will need to use $.ajax, like this: var msg = $.ajax({type: "GET", url: "my_script.php", async: false}).responseText; I don't think there is a better way to do this, thanks for your answers. A: The return value is simply the jqXHR object used for the ajax request. To get the response data you need to register a callback. $.get("my_script.php", function(data) { var msg = data; alert(msg); }); A: The response text is available in the success callback; do what you need to do with it there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7598821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Alternative of php's explode/implode-functions in c# are there a similar functions to explode/implode in the .net-framework? or do i have to code it by myself? A: There are two methods that correspond to PHP's explode and implode methods. The PHP explode's equivalent is String.Split. The PHP implode's equivalent is String.Join. A: String.Split() will explode, and String.Join() will implode. A: The current answers are not fully correct, and here is why: all works fine if you have a variable of type string[], but in PHP, you can also have KeyValue arrays, let's assume this one: $params = array( 'merchantnumber' => "123456789", 'amount' => "10095", 'currency' => "DKK" ); and now call the implode method as echo implode("", $params); your output is 12345678910095DKK and, let's do the same in C#: var kv = new Dictionary<string, string>() { { "merchantnumber", "123456789" }, { "amount", "10095" }, { "currency", "DKK" } }; and use String.Join("", kv) we will get [merchantnumber, 123456789][amount, 10095][currency, DKK] not exactly the same, right? what you need to use, and keep in mind that's what PHP does, is to use only the values of the collection, like: String.Join("", kv.Values); and then, yes, it will be the same as the PHP implode method 12345678910095DKK You can test PHP code online using http://WriteCodeOnline.com/php/
{ "language": "en", "url": "https://stackoverflow.com/questions/7598826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "48" }
Q: Coldfusion TemplateClassLoader hold on to class loader instances? I have a "OutOfMemoryError: PermGen space" error on my CF 8 server. In my app 1000 templates were loaded into the same local variable (for testing purpose), so once the next one is loaded, the prior one should be available for GC - but this does not happen. I got a memory dump and looked at it with jhat. What I saw was it loads the thousand templates, each with it's own TemplateClassLoader instances. In the TemplateClassLoader it self there is a static reference to all TemplateClassLoader instances (again this is from the jhat). Probably because of this, the instances are hold in memory, so the class objects can not be GC in permgen. This "holding on memory" only happens if I call a cfscript function in the template once is loaded. If I just load the template but not calling the function, the class objects are GCed and no OOM error occurs. Any idea what's happening on the (appeared) static reference on the TemplateClassLoader? A: I have that figured out. In the CF admin page Server Settings > Caching there is a field "Maximum number of cached templates". It controls how many templates should be in a LRU cache. If a template is in that cache, there is a strong reference to the java class object and can not be GCed. In my CF setup it uses a default value of 1024. This is why in my test the 1000 unique templates none get GCed. There is a bit more info here: http://blogs.sanmathi.org/ashwin/2006/07/12/tangling-with-the-template-cache/
{ "language": "en", "url": "https://stackoverflow.com/questions/7598834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Alternative of VMRuntime.getRuntime().setMinimumHeapSize in Gingerbread I know there's a VMRuntime.getRuntime().setMinimumHeapSize in Android 2.1/2.2 for developer to adjust the starting heap size of the application, and it is one of the most effective solution sfor solving the OutOfMemory error during BitmapFactory.decodeStream() However, since Android 2.3, this VMRuntime class is removed from official API, does anyone knows the alternative API of this function in 2.3? A: and it is one of the most effective solution sfor solving the OutOfMemory error during BitmapFactory.decodeStream() Really? Setting the minimum heap size may reduce GC churn, but I would love to see links to places where it helped with OutOfMemoryErrors. However, since Android 2.3, this VMRuntime class is removed from official API, does anyone knows the alternative API of this function in 2.3? There is none. That behavior is no longer exposed. A: you can't increase the heap size dynamically. you can request to use more by using android:largeHeap="true" in the manifest. also, you can use native memory, so you actually bypass the heap size limitation. here are some posts i've made about it: * *How to cache bitmaps into native memory *JNI bitmap operations , for helping to avoid OOM when using large images and here's a library i've made for it: * *https://github.com/AndroidDeveloperLB/AndroidJniBitmapOperations A: Similar answer to increase the heap size of the application You cannot use VMRuntime post 2.2 but this functionality shall solve your purpose
{ "language": "en", "url": "https://stackoverflow.com/questions/7598835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }