text
stringlengths
8
267k
meta
dict
Q: Send contents of a dynamically-generated survey page over email I have an installation of survey web app LimeSurvey set up for a coworker's project. It works great. I've customized the HTML, CSS (with a separate print stylesheet), and JavaScript to our liking. I need the user to able to send the contents of a dynamically-generated page of questions (in our case actually "recommendations", but still "questions" to the system) either in the body of an email, or as an attachment. This content contains a number of divs with simple formatted (some bolding) text content. Preferably this email would use the print stylesheet I've defined, but really anything readable would do. I would use an existing service like EcoSafe, but that service visits the given URL itself and converts it to a PDF. This means they get the front page of the survey rather than the dynamically-generated page content the user sees. I've searched and found some talk of PHP libraries that can send formatted emails, but I have little-to-no PHP experience. I'm thinking maybe I can use JavaScript or JQuery to grab the contents of the page and then a server-side tool to send that content in an email...but I don't quite know where to start. I have full access to our web server and so can install any libraries or scripts necessary. Or if there's even a way to do this with mailto: links, that could be sufficient. Anybody have ideas on how to send the contents of a dynamically-generated page in an email? Thanks in advance. A: EDIT: As Cheekysoft points out in the comments, this code as written is not secure and would allow a malicious user to send any arbitrary email content through your app. In other words, do not use the code below as-is. I ended up using a combination of jQuery and PHP to get the job done. * *On my survey page I added a small form to collect the user's email address. *I used jQuery to POST this form and the contents of the page's wrapper tag to a PHP script. *In that PHP script, I used Emogrifier to add in-line tags to the HTML passed in by jQuery using a stylesheet as reference (because most email clients, including Gmail, don't allow using linked styleheets). *Then (still in the PHP script) I sent the actual email using SwiftMailer (thanks for pointing me towards it, Marc B) and a Google Apps account's SMTP functionality. Works great! In case it will help anyone in the future, here's the PHP script (sanitized): <?php /***** INITIALIZE *****/ /* Import libraries */ require_once 'swiftmailer/swift_required.php'; require_once 'emogrifier/emogrifier.php'; /* Email stylesheet location */ $stylesheet = 'http://example.com/email.css'; /* SMTP Account Info */ $smtpusername = "sender@gmail.com"; $smtppassword = "senderpassword"; $smtpserver = "smtp.gmail.com"; $smtpport = 465; $smtpsecurity = "ssl"; /***** RETRIEVE THE DATA *****/ /* Retrieve the passed-in variables */ /* HTML for the email body */ $html = $_POST['content']; /* Recipient mail address */ $address = $_POST['address']; /* Recipient name */ $name = $_POST['name']; if ($name==NULL || $name=="") { $name = "You"; } /***** MODIFY THE HTML *****/ // Get stylesheet contents as a string $css = file_get_contents($stylesheet); // Convert stylesheet into in-line styles using Emogrifier - http://www.pelagodesign.com/sidecar/emogrifier/ $converter = new Emogrifier($html, $css); $content = $converter->emogrify(); /***** CREATE THE MESSAGE *****/ /* Create the message */ $message = Swift_Message::newInstance() //Give the message a subject ->setSubject("Results for $name") //Set the From address with an associative array ->setFrom(array('sender@gmail.com' => 'Sender Name')) //Set the To addresses with an associative array ->setTo(array($address => $name)) //Give it a body ->setBody($content, 'text/html') ; /***** SEND THE EMAIL *****/ //Create the Transport $transport = Swift_SmtpTransport::newInstance($smtpserver, $smtpport, $smtpsecurity) ->setUsername($smtpusername) ->setPassword($smtppassword) ; //Create the Mailer using your created Transport $mailer = Swift_Mailer::newInstance($transport); //Send the message $result = $mailer->send($message); if ($result == "1") { echo "<span class='sendstatus success'>Email sent successfully. </span>"; } else { echo "<span class='sendstatus failure'>An error occurred. Result code: $result </span>"; } ?> And here's the jQuery form (simplified a bit): <div id="emailresults"> <form id="emailRecsForm" action="http://example.com/emailresults/emailrecs.php"> <!-- THIS PAGE WHERE THE PHP ABOVE IS LOCATED --> <h3><img src="email-icon.png" /> Email Your Results</h3> <label for="name">Name</label><input type="text" id="name" name="name" placeholder="Recipient's name (optional)" /> <label for="address">Email address</label><input type="text" id="address" name="address" class="required email" placeholder="recipient@address.org" /> <div id="submitdiv"><input type="submit" class="submit" value="Send Results" /></div> </form> <!-- the result of the send will be rendered inside this div --> <div id="result"></div> </div> <script> /* attach a submit handler to the form */ $("#emailRecsForm").submit(function(event) { /* stop form from submitting normally */ event.preventDefault(); $( "#submitdiv" ).empty().append('<span class="sendstatus working"><img src="/images/loadwheel.gif" alt="Sending..."></img></span>'); /* get some values from elements on the page: */ var $form = $( this ), name = $form.find( 'input[name="name"]' ).val(), address = $form.find( 'input[name="address"]' ).val(), html = $('.container').html(), url = "http://example.com/emailrecs.php"; /* Send the data using post and put the results in a div */ $.post( url, { name: name, address: address, content: html }, function( data ) { $( "#submitdiv" ).empty().append('<br />').append( data ).append('<input type="submit" class="submit" value="Send Results" />'); $form.find( 'input[name="name"]' ).val(""); $form.find( 'input[name="address"]' ).val(""); } ); }); </script> A: You can use included system from LimeSurvey. * *Construct some part of your body with Expression Manager: example :"Your answer to {QuestionCode.question} was {QuestionCode.NAOK}" in some equation question type (more easy to use it after) *Use 'Send basic admin notification email to:' par to put the email adress : you can use EM too : for example {if(Q1.NAOK=='Y','yesadress@example.org','adress@example.org')} ... *Use Email template/Basic admin notification to put all your needed content. Denis
{ "language": "en", "url": "https://stackoverflow.com/questions/7561451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Unmodified DropDownList in UpdatePanel causes Event Validation error in FireFox Background I have an ASP.net UserControl that is a simple user input form. It uses an UpdatePanel and UpdaetProgress to display a "working" gif after they click submit. We have gotten reports that the submit button sometimes doesn't do anything in FireFox, IE 8, and Safari. When looking into that, I couldn't reproduce any problems in IE, but found that in FireFox, the submit button got the following script error which was preventing the postback: Error: Sys.WebForms.PageRequestManagerServerErrorException: Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation. Source File: http://localhost:1127/ScriptResource.axd?d=ZYU-uPMJ_AcQgBrmkW_WO13JlNZSAb9cMptxJsQIH1LnA8NC31pa7PAk8l5lYCB8LDDwft7xwh7Z107MKgt7KHHBeQaeEncnAFKLJ04CaHgelsuOOv072-1ZBvMW7N_x0&t=3693a5e0 Line: 1111 Problem To figure out what was causing the error, I gradually whittled down my code until I had almost nothing left. What I found was that when I select from a DropDownList in an UpdatePanel, the button gets this error (in FireFox only). If I remove the DropDownList, don't make a selection, or remove the UpdatePanel, the submit button posts back correctly (any 1 of those). Example Create an ASP.net 3.5 project and place the code below in an aspx page. Set a break point in your Page_Load or OnClick event handler in the code behind. Run it, make a selection from the DropDownList and then ClickSubmit. Notice the breakpoints are not hit. <form id="form1" runat="server"> <div> <asp:ScriptManager runat="server"> </asp:ScriptManager> <div id="Div1" class="form-layout membership payment"> <asp:UpdatePanel ID="UpdatePanel1" runat="server" RenderMode="Inline"> <contenttemplate> <table cellpadding="0" cellspacing="0" border="0" class="form_table payment"> <tr> <th align="right" valign="top"> State <span class="reqd">*</span> </th> <td> <asp:DropDownList Width="75px" ID="ddlState" CssClass="txt" runat="server" AutoPostBack="false"> <asp:ListItem Value="" Text="--Select--" /> <asp:ListItem>AB </asp:ListItem> <asp:ListItem>AL </asp:ListItem> </asp:DropDownList> </td> </tr> </table> <div class="clear-left pad-bottom"> </div> <asp:Label ID="lblCreditCardError" CssClass="creditCardError" runat="server"> </asp:Label> <table cellpadding="0" cellspacing="0" border="0" class="form_table"> <tr> <th align="right" valign="top"> </th> <td> <asp:HiddenField ID="HFSubmitForm" runat="server" Value="0" /> <asp:Button ID="btnTest" runat="server" OnClick="btnSubmitCC_Click" /> </td> </tr> </table> </contenttemplate> </asp:UpdatePanel> </div> </div> </form> I don't think using markup should matter anyway, but I tried adding the items to the DropDownList using binding in an if(!IsPostBack) block in the Page_Load method, but it didn't change anything. A: I'm not sure if this causes your issue, but try to format the DropDownList-Items correctly: <asp:DropDownList Width="75px" ID="ddlState" CssClass="txt" runat="server" AutoPostBack="false"> <asp:ListItem Text="--Select--"></asp:ListItem> <asp:ListItem Text="AB"></asp:ListItem> <asp:ListItem Text="AL"></asp:ListItem> </asp:DropDownList> A: First off, you are missing this under your UpdatePanel: <Triggers> <asp:AsyncPostBackTrigger ControlID="btnTest" /> </Triggers> Second... either bind the list options in code-behind, turn off event validation for this page, or call RegisterForEventValidtion() for each of your options, I believe. I'm a little sketchy on this last one since I've never really used it. I was able to get your code working by simply adding the AsyncPostBackTrigger and then binding the DDL in code-behind. Finally, it's possible that you are simply missing these unhandled exceptions while debugging because you are expecting something from the browser... but really it should appear to the browser that nothing has happened. Pull up EventViewer to see unhandled ASP.NET exceptions. The exception is stopping execution before you get the event handler. A: @Tim Schmelter- Ahhh that explains it. (Replying in an answer so I can show code and make sure your answer is clear) Here's what ASP.NET sends to the browser: <SELECT style="WIDTH: 75px" id=ddlState class=txt name=ddlState> <OPTION selected value="">--Select--</OPTION> <OPTION value="AB&#13;&#10; ">AB</OPTION> <OPTION value="AL&#13;&#10; ">AL</OPTION> </SELECT> &#l3;&#l0 is /r/n. In IE, this whole value displayed above is included in the HTML, but in FireFox it's reduced down to a single space (e.g. "AB "). When it's passed back to the server it sees the selected option's value is not one that was originally included. I had compared the HTML sent to what was in FireFox but I looked at the above HTML in Visual Studio's XML Visualizer which also removed them so I didn't notice the difference.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: XML StringWriter empty I have some XML in a XMLDocument and I want to put it into a StringWriter, but it always becomes empty(?) instead. I've tried inspecting the variables with debug, but I'm still clueless as to what's going on. Here's what I have: XmlDocument xmlInput = new XmlDocument(); /* after this executes, xmlInput has lots of data in it */ xmlInput.LoadXml(...); XslCompiledTransform transform = new XslCompiledTransform(); /* I'm pretty sure Template.xslt is being found and loaded correctly */ transform.Load(Server.MapPath("/Files/Template.xslt")); using (System.IO.StringWriter sb = new System.IO.StringWriter()) { XmlWriterSettings xSettings = new XmlWriterSettings(); xSettings.ConformanceLevel = ConformanceLevel.Fragment; xSettings.Encoding = Encoding.UTF8; /* PROBLEM: After this line, StringWriter sb is {} */ using (XmlWriter xWriter = XmlWriter.Create(sb, xSettings)) { transform.Transform(xmlInput, xWriter); } /* xmlText is empty string "" after this line */ String xmlText = sb.ToString(); /* ... does more stuff ... */ } Can I have some help? I'm really not sure where to go from here to get this working. EDIT: Even more investigation: using (var stringWriter = new StringWriter()) { using (var xmlTextWriter = XmlWriter.Create(stringWriter)) { /* Prints lots of data to the screen */ Response.Write(xmlInput.InnerXml); xmlInput.WriteTo(xmlTextWriter); /* Doesn't print anything to the screen */ Response.Write(stringWriter.GetStringBuilder().ToString() ); } } BUT, flushing does the trick xmlInput.WriteTo(xmlTextWriter); xmlTextWriter.Flush(); /* prints lots of data */ Response.Write( stringWriter.GetStringBuilder().ToString() ); A: It turns out that the XSLT file I was trying to apply required the XML to be wrapped in a certain element. But the flush() trick helped a lot.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Self SSL - Invalid Certificate I used Self SSL for the first time today to create a certificate for our exchange-OMA/OWA. I have imported the certificate into trusted root certificate authorities on my local computer so that it will not prompt that the certificate is not from a trusted source. I am however still getting a certificate error "Invalid Certificate", the IE8 browser bar turns red with a security warning. When I view the certificate it does not display any error and says the certificate is fine. Can anyone tell me why I am getting this error? is it normal for self signed certificates or is the certificate really invalid some how? Thank you A: Make sure that the CN ("Common Name") attribute matches in your URL and certificate. For example, if you created your certificate using the CN=localhost, but you are accessing it in IE using something like https://machine.domain.topleveldomain, then IE will complain that machine.domain.topleveldomain is not the same as localhost. I believe it does a string comparison. Make sure that the certificate was installed in the Trusted Root Certification Authorities (TRCA) under the Local Computer physical store. If all is installed correctly, then there is one more possibility. Windows has a "feature" that wipes out untrusted certificates (untrusted according to mircosoft) from the TRCA. You can disable this feature first and then reinstall the certificate. Open up gpedit.msc and drill down to Computer Configuration > Administrative Templates > System > Internet Communication Management > Internet Communication Settings > Turn off Automatic Root Certificates Update. Enable Turn off Automatic Root Certificates Update. Microsoft provides some details about what that feature does---its a security feature where your TRCA is compared against microsoft's database of valid root certificates. If it is still not working after you turn that feature off, then there is a problem with the way in which you created that certificate. You can make a certificate using makecert. http://msdn.microsoft.com/en-us/library/bfsktky3(v=vs.80).aspx If your computer's fully qualified name is: machine.domain.com, you can do this: makecert -n "CN=machine.domain.com" c:\file.cer Eventually you can access your resources by: https://machine.domain.com Hope this helps. I have had my fair share of self-signed certificate woes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Placing C++ class in another file: compilation error I am learning about C++ classes and I realized that if I tried to move my class declaration and definition of class Date from main.cpp to another c++ file, say test.cpp and compiled the two files I got an error saying Date was not declared. Why is that? A: This is why you have header files. You need a header file test.h that contains only the class definition (that is mostly function declarations) and test.cpp that contains the actual function definitions (the code). In main.cpp you'll have to #include "test.h". A: Well, you would have to declare your class in test.h and include it in main.cpp so that the compiler knows where to look for it and you can then define your class in test.cpp
{ "language": "en", "url": "https://stackoverflow.com/questions/7561468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook 'like' button Is it possible to have the very simple facebook like button, and a count (like they use for sharing content) when adding a button to like a facebook page? I want to keep it nice and condensed, but the code offered by facebook included a title and a thumbnail. Edit To make it clear, I am looking for a 'become a fan of my facebook page' rather than a 'please share this page with your mates' button. A: The like box is your only option for this, but as you say, it's styled slightly different to a standard like button. This is by design and can't be overridden.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ColdFusion Conditional RecordCount Alright SO users... Here's a seemingly impossible to go wrong conditional statement. It is very simple, however, I cannot figure out why it won't work the way it is expected to. <cfoutput query="checkForAd"> <!--- also used the line <cfif RecordCount eq 0> ---> <cfif checkForAd.RecordCount eq 0> <!--- Display some message. (Perhaps using a table, undecided) ---> <cfelse> <!--- Display some other message. (Happens to be a table) ---> </cfif> </cfoutput> When the RecordCount returns a number greater than 0, the else case displays properly. When RecordCount returns 0, nothing is displayed and the form continues along its path. I've become very frustrated as this should be quite simple... A: As nykash has pointed out, the body of a cfoutput query (or a cfloop query) never executes if there are no records, so doing a check for a zero recordcount will never be true inside of one. However, I find the following example a more readable one: <cfif NOT checkForAd.RecordCount > <!--- Display some message. ---> </cfif> <cfoutput query="checkForAd"> <!--- loop through data ---> </cfoutput> It might not seem much in isolation, but I think it's a bit cleaner and easier to see what's going on, especially when combined with other code. Specifically on the RecordCount check, if I care about the specific number then I'll use EQ (or NEQ/GT/etc) but if I only care about "having records" vs "not having records" then I use the implicit boolean conversion that CFML provides to simplify the code. This really makes it easier to identify when I'm using the common binary choice or a more significant one, so navigating through the code is easier. A: The output won't return any results if the query set is empty. Try: <cfif checkForAd.RecordCount eq 0> <!--- Display some message. (Perhaps using a table, undecided) ---> <cfelse> <cfoutput query="checkForAd"> <!--- Display some other message. (Happens to be a table) ---> </cfoutput> </cfif> I assume that you're looking to return a number of records... if you were just returning one, the query="checkForAd" isn't necessary. You can simply reference the query & variables in a <cfoutput></cfoutput>. Edit Here's one way to access a query variable: QueryName["ColumnName"][RowNum] (As you look to expand your coding, there's a lot you can do with query variables. There's a great rundown of the different approaches at ColdFusion and getting data from MySQL)
{ "language": "en", "url": "https://stackoverflow.com/questions/7561471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Rails model inheritance & routing class User < ActiveRecord::Base has_many :queued_workouts, :conditions => "queue_position IS NOT NULL", :order => "queue_position ASC" has_many :workouts end class Workout < ActiveRecord::Base end class QueuedWorkout < Workout # Have to give this its own class because acts_as_list always updates the # queue_position when operating on user.workouts acts_as_list :column => :queue_position, :scope => :user end I have routes for Workouts, but do not need them for QueuedWorkouts. Every once in a while I run into a case where I pass a QueuedWorkout instead of a Workout into url_for. In my specific case this is happening in WorkoutObserver. Right now I'm doing class WorkoutObserver < ActiveRecord::Observer def after_update(workout) workout = Workout.find(workout.id) if workout.is_a? QueuedWorkout twitter_status = "some stuff " + short_url_for(workout) # Helper method for generating urls outside controllers & views .... end end which, of course, is an awful solution. Is there a better way to tell the Rails router to generate Workout urls for QueuedWorkouts? A: You can do: resources :queued_workout, :controller => "workout"
{ "language": "en", "url": "https://stackoverflow.com/questions/7561473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Apply TextDecorations to a CollapsibleSection I have CollapsibleSection objects that are dynamically being created in code. I would like to simply say: CollapsibleSection section = new CollapsibleSection(); section.TextDecoration = TextDecorations.Strikethrough; This is proving more difficult that I thought. Does anyone have some insight on a simple way to strikethrough the entire content of a collapsible section? I'm missing something still. Here's what I have so far: public static readonly DependencyProperty TextDecorationProperty = DependencyProperty.RegisterAttached("TextDecoration", typeof(TextDecoration), typeof(CollapsibleSection)); In my method where I am creating my CollapsibleSection I have this: CollapsibleSection cs = new CollapsibleSection(); if (flagIsTrue) { section.SetValue(TextDecorationProperty, TextDecorations.Strikethrough); } These CollapbsibleSection's are used to populate a FlowDocument. I get this exception: 'System.Windows.TextDecorationCollection' is not a valid value of property 'TextDecoration'. What am I doing wrong? A: You can use an attached property. This can be done in Code or XAML <Expander Header="test" TextBlock.TextDecorations="Strikethrough"> <TextBlock>This is some random text</TextBlock> </Expander> A: I got the attached property to not throw an error by changing the parameter from typeof(TextDecoration) to typeof(TextDecorationCollection) but the property never seemed to actually attach to the UIElement so I bagged it and just ended up setting the properly at the Paragraph level. Thank you for your help though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Changing login name to svn repository from eclipse Using Eclipse I added a SVN repository & imported a project using another person's login and automatically checked remember login. One can't always wait for IT people. Now I have my very own name and would like to switch logins. Can this be done without uninstalling the world? I'm using WIndow 7. Thanks. A: Did you try to: * *Open SVN repository view *Right click on the repository of the project you checked out *Select Location Properties... *Change use credential Otherwise, the other solution is to: * *Right click on your project *Team --> Disconnect --> Also delete SVN Metadata *Team --> Share Project --> And you the right location with your credential A: I'm not sure of how Eclipse's SVN implementation works, but for for most SVN clients you can force Subversion to forget its previous credentials by trashing the directory %APPDATA%\Subversion\auth
{ "language": "en", "url": "https://stackoverflow.com/questions/7561487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jquery plugin re-inits when method is called This is my first stab at trying to create a JQuery plugin, so I apologize for my noobbery. My issue is that I believe the plugin is re-initializing when I try to call a public method. It's a simple plugin that creates a div and fills it with tiles, the method .reveal() should remove the tiles. Plugin declaration: (function($){ $.fn.extend({ //pass the options variable to the function boxAnimate: function(options) { //Set the default values, use comma to separate the settings, example: var defaults = { bgColor: '#000000', padding: 20, height: $(this).height(), width: $(this).width(), tileRows:25, tileHeight:$(this).height()/25, tileCols:25, tileWidth:$(this).width()/25, speed: 500 } var options = $.extend(defaults, options); this.reveal = function(){ var lastTile = $('.backDropTile:last').attr('id'); var pos1 = lastTile.indexOf("_"); var pos2 = lastTile.lastIndexOf("_"); var lCol = parseInt(lastTile.substr(pos2+1)); var lRow = parseInt(lastTile.substr(pos1+1,(pos2-pos1)-1)); alert(lCol+' '+lRow+' #bdTile_'+lRow+'_'+lCol); for(lRow;lRow>=0;lRow--){ //Iterate by col: for(lCol;lCol>=0;lCol--){ $('#bdTile_'+lRow+'_'+lCol).animate({ opacity: 0 }, 100, function() { $('#bdTile_'+lRow+'_'+lCol).remove(); }); } } alert(lCol+' '+lRow); } return this.each(function(index) { var o = options; //Create background: $(this).prepend('<div id="backDrop" style="color:white;position:absolute;z-index:998;background-color:'+o.bgColor+';height:'+o.height+'px;width:'+o.width+'px;"></div>'); //create boxes: //First iterate by row: for(var iRow=0;iRow<o.tileRows;iRow++){ //Iterate by col: for(var iCol=0;iCol<o.tileCols;iCol++){ $('#backDrop').append('<span class="backDropTile" id="bdTile_'+iRow+'_'+iCol+'" style="z-index:998;float:left;background-color:green;height:'+o.tileHeight+'px;width:'+o.tileWidth+'px;"></span>'); } } }); } }); })(jQuery); Usage: $(document).ready(function() { $('#book').boxAnimate(); $('#clickme').click(function() { $('#book').boxAnimate().reveal(); }); }); So I pretty much know what my problem is, but I'm not familiar enough with creating jQuery plugins to fix it. It's seems like the more I read, the more confused I become as it appears to be many ways to achieve this. A: I like to separate my plug-ins into four sections. 1: $.fn implementation that iterates the jQuery element collection and attaches the plug-in. 2: The plug-in "constructor" or init. 3: The plug-in default options 4: The plug-in instance methods or implementation. Here's how I would have structured your plug-in. I think this is more comprehensible than what you've provided. (function($){ // constructor or init task var boxAnimate = function(el, options) { this.element = $(el); this.options = options; if (this.options.height == 'auto') this.options.height = this.element.height(); if (this.options.width == 'auto') this.options.width= this.element.width(); if (this.options.tileHeight == 'auto') this.options.tileHeight = this.options.height/25; if (this.options.tileWidth == 'auto') this.options.tileWidth = this.options.width/25; //Create background: this.element.prepend('<div id="backDrop" style="color:white;position:absolute;z-index:998;background-color:'+this.options.bgColor+';height:'+this.options.height+'px;width:'+this.options.width+'px;"></div>'); //create boxes: for(var iRow=0;iRow<this.options.tileRows;iRow++){ for(var iCol=0;iCol<this.options.tileCols;iCol++){ $('#backDrop').append('<span class="backDropTile" id="bdTile_'+iRow+'_'+iCol+'" style="z-index:998;float:left;background-color:green;height:'+this.options.tileHeight+'px;width:'+this.options.tileWidth+'px;"></span>'); } } } // default options boxAnimate.defaults = { bgColor: '#000000', padding: 20, height: 'auto', width: 'auto', tileRows:25, tileHeight: 'auto', tileCols:25, tileWidth: 'auto', speed: 500 }; // instance methods boxAnimate.prototype = { reveal: function() { var lastTile = $('.backDropTile:last').attr('id'); var pos1 = lastTile.indexOf("_"); var pos2 = lastTile.lastIndexOf("_"); var lCol = parseInt(lastTile.substr(pos2+1)); var lRow = parseInt(lastTile.substr(pos1+1,(pos2-pos1)-1)); for(var row=lRow;row>=0;row--) { for(var col=lCol;col>=0;col--) { $('#bdTile_'+row+'_'+col).animate({ opacity: 0 }, 1000, function() { $('#bdTile_'+row+'_'+col).remove(); }); } } } } // $.fn registration $.fn.boxAnimate = function(options) { return this.each(function() { var el = $(this); var o = $.extend({}, boxAnimate.defaults, options) if (!el.data('boxAnimate')) el.data('boxAnimate', new boxAnimate(el, o)); }); } })(jQuery); $('#book').boxAnimate(); $('#clickme').click(function(e) { $('#book').data('boxAnimate').reveal(); e.preventDefault(); }); A: When you assign a method inside the plugin "constructor" like you do here: this.reveal = function(){} you are assigning it as a static method of the jQuery.prototype.boxAnimate object. That means you can call it on the object that will be returned from the constructor: $('#element').boxAnimate().reveal(); or: var instance = $('#element').boxAnimate(); instance.reveal(); If you wish to place it inside the $.data object instead (personally recommended), you can do like this instead (inside the this.each loop): $.data(this, 'boxAnimate', { reveal: function() { // some code } }); Example: http://jsfiddle.net/AyffZ/ A: First, read this tutorial: http://docs.jquery.com/Plugins/Authoring Second, your problem is certainly the usage: $(document).ready(function() { $('#book').boxAnimate(); // First Init $('#clickme').click(function() { $('#book') .boxAnimate() // Second Init .reveal(); }); }); The tutorial I linked explains multiple ways to include methods on plugins. You can also use the jQuery UI widget factory, which provides hooks for including methods.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python 3 gives wrong output when dividing two large numbers? a = 15511210043330985984000000 # (25!) b = 479001600 # (12!) c = 6227020800 # (13!) On dividing ans = int(a/(b*c)) or ans = int((a/b)/c) we get ans equal to 5200299 instead of 5200300 A: Try using integer division instead of float division. >>> 15511210043330985984000000 / (479001600 * 6227020800) 5200299.999999999 >>> 15511210043330985984000000 // (479001600 * 6227020800) 5200300 A: Your problem (not using integer arithmetic) has been swept under your carpet for you by Python 3.2: Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> 15511210043330985984000000 / (479001600 * 6227020800) 5200300.0 >>> repr(15511210043330985984000000 / (479001600 * 6227020800)) '5200300.0' >>> int(15511210043330985984000000 / (479001600 * 6227020800)) 5200300 Python 3.1.3 (r313:86834, Nov 27 2010, 18:30:53) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> 15511210043330985984000000 / (479001600 * 6227020800) 5200299.999999999 >>> repr(15511210043330985984000000 / (479001600 * 6227020800)) '5200299.999999999' >>> int(15511210043330985984000000 / (479001600 * 6227020800)) 5200299 I'm puzzled: presumably you used int() because you realised that it was producing a float answer. Why did you not take the (obvious?) next step of rounding it, e.g. [3.1.3] >>> int(round(15511210043330985984000000 / (479001600 * 6227020800))) 5200300 ? A: In Python 3.x / means floating point division and can give small rounding errors. Use // for integer division. ans = a // (b*c)
{ "language": "en", "url": "https://stackoverflow.com/questions/7561498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: iOS payment gateway Possible Duplicate: Selling something inside an application I'm really new to Objective-C programming, and I'm very interested in developing an iOS app. One of the major problems I am facing and that I've been researching is the opportunity of selling third-party products throughout my app. Haven't found anything about iOS payment gateways, and know if it is done through Apple IAP, they get 30% of the profit. Looking something like Amazon's app checkout. Thanks A: You MUST use Apple's In-App Purchase system in order to sell anything from within your apps. You may not create your own payment system. Additionally, you cannot sell real-world items from within your app... whatever the user buys can only be used within the app itself (points, etc). And lastly, it is against Apple's Review Guidelines to put links to your own payment portal on your site. So, to summarize you must 1) use Apple's In-App Purchase system and 2) can only sell virtual items that can be used within your app.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ProcessBuilder does not stop I am trying to decode an mp3 file to a wav file by using the ProcessBuilder class under Linux. For some reason the process does not stop so that I have to cancel it manually. Could somebody give me a hint on this. I think that the quoted code is very easy to reproduce: import java.io.*; public class Test { public static void main(String[] args) { try { Process lameProcess = new ProcessBuilder("lame", "--decode", "test.mp3", "-").start(); InputStream is = lameProcess.getInputStream(); FileOutputStream fileOutput = new FileOutputStream("test.wav"); DataOutputStream dataOutput = new DataOutputStream(fileOutput); byte[] buf = new byte[32 * 1024]; int nRead = 0; int counter = 0; while((nRead = is.read(buf)) != -1) { dataOutput.write(buf, 0, buf.length); } is.close(); fileOutput.close(); } catch (Exception e) { e.printStackTrace(); } } } Output of jstack "main" prio=10 tid=0x0000000002588800 nid=0x247a runnable [0x00007f17e2761000] java.lang.Thread.State: RUNNABLE at java.io.FileInputStream.readBytes(Native Method) at java.io.FileInputStream.read(FileInputStream.java:236) at java.io.BufferedInputStream.fill(BufferedInputStream.java:235) at java.io.BufferedInputStream.read1(BufferedInputStream.java:275) at java.io.BufferedInputStream.read(BufferedInputStream.java:334) - locked <0x00000000eb5b1660> (a java.io.BufferedInputStream) at java.io.FilterInputStream.read(FilterInputStream.java:107) at Test.main(Test.java:17) A: You need to drain both the output (via getInputStream()) and error (via getErrorStream()) streams of the process, otherwise it may block. Quoting the Process documentation: Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock. (which applies to both the error and output streams) You'll probably need to drain each stream in different threads because each may block when it has no data. A: It might be a lot easier for you to use a LAME Java wrapper like LAMEOnJ. That way you avoid spawning off processes and you can just interact with lame as if it were a Java library.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to add include and lib paths to configure/make cycle? I need a place to install libraries in a linux box I have no su access to. I'm using ~/local[/bin,/lib,/include], but I don't know how can I tell ./configure to look for libraries there (particularly, I'm trying to compile emacs, which needs libgif, which doesn't come in my distro). I tried adding export PATH=$PATH:~/local/bin export LD_LIBRARY_PATH=~/local/lib export C_INCLUDE_PATH=~/local/include export CPLUS_INCLUDE_PATH=~/local/include to .bashrc but it doesn't seem to work. A: This took a while to get right. I had this issue when cross-compiling in Ubuntu for an ARM target. I solved it with: PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib ./autogen.sh --build=`config.guess` --host=armv5tejl-unknown-linux-gnueabihf Notice CFLAGS is not used with autogen.sh/configure, using it gave me the error: "configure: error: C compiler cannot create executables". In the build environment I was using an autogen.sh script was provided, if you don't have an autogen.sh script substitute ./autogen.sh with ./configure in the command above. I ran config.guess on the target system to get the --host parameter. After successfully running autogen.sh/configure, compile with: PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib CFLAGS="-march=... -mcpu=... etc." make The CFLAGS I chose to use were: "-march=armv5te -fno-tree-vectorize -mthumb-interwork -mcpu=arm926ej-s". It will take a while to get all of the include directories set up correctly: you might want some includes pointing to your cross-compiler and some pointing to your root file system includes, and there will likely be some conflicts. I'm sure this is not the perfect answer. And I am still seeing some include directories pointing to / and not /ccrootfs in the Makefiles. Would love to know how to correct this. Hope this helps someone. A: Set LDFLAGS and CFLAGS when you run make: $ LDFLAGS="-L/home/me/local/lib" CFLAGS="-I/home/me/local/include" make If you don't want to do that a gazillion times, export these in your .bashrc (or your shell equivalent). Also set LD_LIBRARY_PATH to include /home/me/local/lib: export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/me/local/lib A: You want a config.site file. Try: $ mkdir -p ~/local/share $ cat << EOF > ~/local/share/config.site CPPFLAGS=-I$HOME/local/include LDFLAGS=-L$HOME/local/lib ... EOF Whenever you invoke an autoconf generated configure script with --prefix=$HOME/local, the config.site will be read and all the assignments will be made for you. CPPFLAGS and LDFLAGS should be all you need, but you can make any other desired assignments as well (hence the ... in the sample above). Note that -I flags belong in CPPFLAGS and not in CFLAGS, as -I is intended for the pre-processor and not the compiler. A: for example, build git usig $HOME/curl package=git version=2.17.0 tarUrl=https://mirrors.edge.kernel.org/pub/software/scm/git/$package-$version.tar.gz install(){ ./configure --prefix=$HOME LDFLAGS="-L$HOME/lib" CFLAGS="-I$HOME/include" make -j 2 make install } if [ -e $package-$version.tar.gz ]; then echo "cache" else wget --no-check-certificate ${tarUrl} tar -xvf $package-$version.tar.gz fi cd ./$package-$version install A: To add to the other answers, sometimes you also have to set PKG_CONFIG_PATH export PKG_CONFIG_PATH=~/local/lib/pkgconfig A: To change environment only for current command from Carl Norum's suggestion:    LDFLAGS+="-L<directory>" CFLAGS+="-I<directory>" make ("make" command should be at the end)    For example:      LDFLAGS+="-L/usr/lib" CFLAGS+="-I/usr/include/gstreamer-1.0 -I/usr/include/opencv4 -I/opt/nvidia/deepstream/deepstream-6.1/sources/includes" make
{ "language": "en", "url": "https://stackoverflow.com/questions/7561509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "106" }
Q: ColdFusion Error - I am getting an error on a web site that got moved to a new server? I moved a web site that works perfectly on multiple other servers onto a new server. We just patched the server, but I am still getting the following error: ColdFusion is not defined ColdFusion.Ajax.importTag('CFAJAXPROXY'); ColdFusion is not defined var _cf_customers=ColdFusion.AjaxProx.../GlobalAdmin/customers.cfc','jsApp'); Our ColdFusion version is: 9,0,0,251028 Because this site works on other Windows machines quite well, my guess is that this is a simple patch or update. Can you help? UPDATE -- This is the updated version of CF installed: 9,0,1,274733 A: You don't need a MAPPING to CFIDE, you need a web server virtual directory. IE: the CFIDE dir neds to be browsable, rather than accessible to CF code. So make sure in IIS or Apache or whatever that you have a virtual directory for CFIDE. That said, your CFIDE dir should not be browsable on a production machine, really. It's a bit of a security risk. A: Is your ColdFusion installation exactly the same? IE was your old server a Standalone installation or an EAR / WAR installation? This can effect where the installer puts the /cfide/ dir.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: wxPython: SplitterWindow and SetMaxSize for one Subwindow I am quiet new to wxPython, so I hope there is nothing basic I am overlooking: I want to use a SplitterWindow to split up my Frame's content in two resizable subwindows (A and B), but I want one of the windows (B) to have a MaxSize set. Unfortunately, this poses a problem: * *When I resize (enlarge), the whole frame (I am trying to adapt to the the wxPython terminology here; normally, I would say: resize the window), I would hope once the maxSize of the of Window B is reached, Window A would automatically be enlarged to fill the whole content of the frame. Sadly, it does not. *How do make sure that I am not able to move the sash to the left (decrease size of Window B)? In the current situation, Window B just moves to the left (does not change width) and exposes the blue background of the WindowSplitter. Here's my code: import wx class MainWindow(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, title=title, size=(500,300)) # Create View self.loadView() #self.SetAutoLayout(1) self.GetSizer().Fit(self) self.Centre() self.Show() def loadView(self): splitter = wx.SplitterWindow(self, wx.ID_ANY, style = wx.SP_BORDER, size=(500, 300)) splitter.SetBackgroundColour('#0000ff') panelLeft = wx.Panel(splitter, size=(200,100)) panelLeft.SetBackgroundColour('#00ff00') panelRight = wx.Panel(splitter, size=(200,100)) panelRight.SetBackgroundColour('#ff0000') panelRight.SetMaxSize((200, -1)) splitter.SplitVertically(panelLeft, panelRight) self.SetSizer(wx.BoxSizer(wx.HORIZONTAL)) self.GetSizer().Add(splitter, 1, wx.EXPAND) app = wx.App(False) frame = MainWindow(None, "Test") app.MainLoop() A picture speaks a thousand words: The blue area is part of the splitter, but not filled up by Window A. Any help/hint in the right direction is appreciated. Thanks, Daniel A: I no longer actively work with wx so cannot test a solution. However I believe what you are looking for is SetSashGravity(0.5) The default behaviour of a SplitterWindow is that upon a Resize event, only the Right or Bottom window will be resized. And in your case you have imposed a maximum size upon that window. See the docs for SetSashGravity
{ "language": "en", "url": "https://stackoverflow.com/questions/7561513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Google Visualization Pie Chart onclick event not firing in IE8 I'm using the Google Visualization API to draw a pie chart with some data. I'm also adding an onclick event, which works perfectly in Chrome. But the event does seem to be firing at all in IE8. No error--it just doesn't fire at all. The chart renders perfectly in all browsers--but the onclick event is not working in IE8 (and possibly other versions of IE--haven't yet tested). Any ideas? var dataTable = new google.visualization.DataTable(); dataTable.addColumn('string'); dataTable.addColumn('number'); $.each(obj_json_data,function(){ dataTable.addRow([this.Name,this.Number]); }); var options = {cht: 'p3', chs: '600x225', labels:'name', legend:'none', chds:'0,160', enableEvents:true, chdls:'000000,14'}; var chart = new google.visualization.ImageChart(document.getElementById('chart_container')); chart.draw(dataTable, options); // Assign event handler google.visualization.events.addListener(chart, 'onclick', mouseEventHandler); function mouseEventHandler(event) { alert('You just clicked ' + event.region); } A: In line: google.visualization.events.addListener(chart, 'onclick', mouseEventHandler); Try pointing the listener to the 'select' event instead of the 'onclick' event. A: It's not 'onclick', it's 'click' event
{ "language": "en", "url": "https://stackoverflow.com/questions/7561516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Forcing a program to run a procedure when returning back to a screen i have 2 screens. Screen 1 calls screen 2. When the user returns back to screen 1 how can i force it to run a procedure? A: If you have an Activity per screen, you can reimplement the onResume method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FancyBox, getting ajax to fire on window load/click I'm trying to get a fancybox window to come up on click after an ajax call. I can do that fine with $(document).ajaxStop(function() { //FancyBox image zoom functionality jQuery script $("a.aboutContentImage").fancybox({ 'zoomOpacity': true, 'zoomSpeedIn': 300, 'zoomSpeedOut': 300, 'overlayShow': true, 'frameWidth': 800, 'frameHeight': 600 }); }); I should note that a.aboutContentImage is not present on the page until after that ajax call. Then after the windows has opened, I need to load in some text from an ajax call. I've tried $("a.aboutContentImage").live("click", function(e) { // ajax here }); But there's some sort of compatibility issue with trying to put an event listener on a fancybox object. A: First, why not just add the text to the image title? Fancybox automatically add the title into a caption. If you need to do something else, then try using the Fancybox onComplete callback (ref)? I haven't tested this, but it should work: $(document).ajaxStop(function() { //FancyBox image zoom functionality jQuery script $("a.aboutContentImage").fancybox({ 'zoomOpacity': true, 'zoomSpeedIn': 300, 'zoomSpeedOut': 300, 'overlayShow': true, 'frameWidth': 800, 'frameHeight': 600, 'onComplete' : function(){ // do whatever here var txt = $('#text').text(); $('#fancybox-title-float-main') .append(txt) .show(); } }); }); Adding to the #fancybox-title-float-main will add on text to the end of whatever is in the title attribute. So you may want to use .html() instead of .append() or whatever.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dojo Form Validation Across Tabs Hi I am having an issue with form validation with dojo's form dijit where I have two or more tabs in the form. If I have a field that is invalid on tab 2 but I'm positioned on tab1 when i validate (by pressing the submit/ok button), the validate method does execute but it cannot find the wrong dijit (switch to the correct tab) and focus on it. The invalidMessage appears but is positioned at the top left of the window instead of where it should be. Is there a way to accomplish this or a workaround applicable for dojo 1.6? Any information you could provide would be greatly appreciated, thanks. A: If you are using the dijit.form.Form (which it seems like you are), I think the easiest way to do this would be override the validate function of the form. Take a look at the dijit.form.Form's original validate function definition (in _FormMixin.js): validate: function(){ // summary: // returns if the form is valid - same as isValid - but // provides a few additional (ui-specific) features. // 1 - it will highlight any sub-widgets that are not // valid // 2 - it will call focus() on the first invalid // sub-widget var didFocus = false; return dojo.every(dojo.map(this.getDescendants(), function(widget){ // Need to set this so that "required" widgets get their // state set. widget._hasBeenBlurred = true; var valid = widget.disabled || !widget.validate || widget.validate(); if(!valid && !didFocus){ // Set focus of the first non-valid widget dojo.window.scrollIntoView(widget.containerNode || widget.domNode); widget.focus(); didFocus = true; } return valid; }), function(item){ return item; }); }, You could change around the if(!valid && !didFocus){ condition to look up which tab the widget that failed validation is on and switch to it. A: This works for me. It just checks if the parent is a tab (in a bit ugly way, so suggestions are welcome) and if it is, gets its parent and activates the tab. It extends scrollIntoView, because that looks the right function to me. This means if you scroll a widget into view on a tab, the tab gets automaticly activated. Just make sure this code is run somewhere. define([ "dojo/_base/window", "dojo/aspect", "dojo/dom", "dojo/dom-class", "dojo/window", "dijit/registry" ], function (baseWindow, aspect, dom, domClass, win, registry) { //extend scrollintoview to make sure, if the element resides on a tab, the tab is activated first. aspect.around(win, "scrollIntoView", function (originalScrollIntoView) { return function (node, pos) { node = dom.byId(node); var doc = node.ownerDocument || baseWindow.doc, body = baseWindow.body(doc), html = doc.documentElement || body.parentNode; if (node == body || node == html) { return; } var widget = registry.byNode(node.domNode || node); if (typeof widget != "undefined" && widget != null) { if (typeof widget.getParent != "undefined") { var par = widget.getParent(); if (domClass.contains(node.domNode || node, 'dijitTabPane')) { if (typeof par.selectChild != "undefined") { try { par.selectChild(widget); } catch (e) { } return; } } if (domClass.contains(par.domNode, 'dijitTabPane')) { this.scrollIntoView(par.domNode); } } } } return originalScrollIntoView(node, pos); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7561533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to pass a value from Master page to content page in asp.net 4 I have no idea why this won't work but I have a function on a master page that gets the logged in user and then displays information about that user on the master page. I want to be able to pass one property (the user Role to the other pages to use for logic flow. I can't seem to get the content pages to recognize the property. The error message is 'System.Web.UI.MasterPage' does not contain a definition for 'Role' and no extension method 'Role' accepting a first argument of type 'System.Web.UI.MasterPage' could be found (are you missing a using directive or an assembly reference?)' Any ideas? public partial class SiteMaster : System.Web.UI.MasterPage { private string role = "Manager"; public string Role { get { return role; } set { role = value; } } protected void Page_Load(object sender, EventArgs e) { ...get current logged in user data and display appropriate fields in the master page. } } Content Page <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Portal.aspx.cs" Inherits="Portal" ClientIDMode="AutoID" %> <%@ MasterType VirtualPath="~/Site.Master" %> <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %> content page.cs protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { string testRole = Master.Role; } } A: The "Master" property on Page returns the type System.Web.UI.MasterPage. You need to cast it to your specific type (SiteMaster) before you can call that class's functions. SiteMaster siteMaster = Master as SiteMaster; if (siteMaster != null) { myVar = siteMaster.Role; } A: You'll need to cast Master to the type of your master page - SiteMaster... string testRole = ((SiteMaster)Page.Master).Role
{ "language": "en", "url": "https://stackoverflow.com/questions/7561543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Want to use LINQ instead of foreach but it doesn't work In the following code foreach loop works fine, but when I try to use LINQ instead of using foreach it doesn't work no exception no error. This code is working : public static IEnumerable<PatternInfo> LoadPatterns() { var directoryInfo = new DirectoryInfo(PatternFullPath); var dirs = directoryInfo.EnumerateDirectories(); var result = new List<PatternInfo>(); foreach (var info in dirs) { result.Add(new PatternInfo { PatternName = info.Name, TemplateFileNames = GetTemplateFiles(info.FullName) }); } return result; } But this one not : public static IEnumerable<PatternInfo> LoadPatterns() { var directoryInfo = new DirectoryInfo(PatternFullPath); var dirs = directoryInfo.EnumerateDirectories(); var patterns = dirs.Select(info => new PatternInfo { PatternName = info.Name, TemplateFileNames = GetTemplateFiles(info.FullName) }); return patterns; } Any advice will be helpful. A: The difference between the two is that in the first code sample you have a List<PatternInfo>, all items in the list are populated already - then you return this list as IEnumerable<PatternInfo>. In the second example you have a IEnumerable<PatternInfo> - this will only load the patterns when you iterate over the enumeration for the first time. If you want the second version to be equivalent (eager loading of the patterns) then add a ToList(): return patterns.ToList(); A: Well, enumerables are lazy until someone starts enumerating over them, so: foreach (var item in LoadPatterns()) { ... } The .Select statement in your second example simply returns a new IEnumerable<T> but until there is some code that consumes/loops over this enumerable nothing will actually execute. A: LINQ is deferred execution. You're returning the statement, but it doesn't get evaluated until you do something to iterate over the IEnumerable you're returning. What is the code that calls LoadPatterns()?
{ "language": "en", "url": "https://stackoverflow.com/questions/7561544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: List of Spring Runtime Exceptions Does anyone know where I can find a list of Spring's (3.0.x) runtime exceptions? I'm talking about exceptions like DataRetrievalFailureException; there's a whole set of these runtime exceptions that you can throw. A: Alright, I was able to find them by loading up the source for Spring in my IDE, and seeing all the classes that extend the NestedRuntimeException abstract class. Keep in mind that some of these are abstract classes themselves, and so you will have to use the appropriate concrete implementation: * *AopConfigException *AopInvocationException *ApplicationContextException *BadSqlGrammarException *BeanCreationException *BeanCreationNotAllowedException *BeanCurrentlyInCreationException *BeanDefinitionParsingException *BeanDefinitionStoreException *BeanDefinitionValidationException *BeanExpressionException *BeanInitializationException *BeanInstantiationException *BeanIsAbstractException *BeanIsNotAFactoryException *BeanNotOfRequiredTypeException *BeansException *BootstrapException *BshScriptUtils.BshExecutionException *CannotAcquireLockException *CannotCreateRecordException *CannotCreateTransactionException *CannotGetCciConnectionException *CannotGetJdbcConnectionException *CannotLoadBeanClassException *CannotSerializeTransactionException *CciOperationNotSupportedException *CleanupFailureDataAccessException *ConcurrencyFailureException *ConversionException *ConversionFailedException *ConversionNotSupportedException *ConverterNotFoundException *DataAccessException *DataAccessResourceFailureException *DataIntegrityViolationException *DataRetrievalFailureException *DataSourceLookupFailureException *DeadlockLoserDataAccessException *DuplicateKeyException *EjbAccessException *EmptyResultDataAccessException *FactoryBeanNotInitializedException *FatalBeanException *HandlerMethodInvocationException *HeuristicCompletionException *HibernateOptimisticLockingFailureException *HttpClientErrorException *HttpMessageConversionException *HttpMessageNotReadableException *HttpMessageNotWritableException *HttpServerErrorException *HttpStatusCodeException *IllegalTransactionStateException *IncorrectResultSetColumnCountException *IncorrectResultSizeDataAccessException *IncorrectUpdateSemanticsDataAccessException *InvalidDataAccessApiUsageException *InvalidDataAccessResourceUsageException *InvalidIsolationLevelException *InvalidMetadataException *InvalidPropertyException *InvalidResultSetAccessException *InvalidResultSetAccessException *InvalidTimeoutException *InvocationFailureException *JaxRpcSoapFaultException *JaxWsSoapFaultException *JdbcUpdateAffectedIncorrectNumberOfRowsException *JdoOptimisticLockingFailureException *JmxException *JndiLookupFailureException *JobMethodInvocationFailedException *JpaOptimisticLockingFailureException *JRubyScriptUtils.JRubyExecutionException *LobRetrievalFailureException *MailAuthenticationException *MailException *MailParseException *MailPreparationException *MailSendException *MaxUploadSizeExceededException *MBeanConnectFailureException *MBeanExportException *MBeanInfoRetrievalException *MBeanServerNotFoundException *MessageConversionException *MetaDataAccessException *MethodInvocationException *MultipartException *NestedTransactionNotSupportedException *NonTransientDataAccessException *NonTransientDataAccessResourceException *NoSuchBeanDefinitionException *NotAnAtAspectException *NoTransactionException *NotReadablePropertyException *NotWritablePropertyException *NullValueInNestedPathException *ObjectOptimisticLockingFailureException *OptimisticLockingFailureException *PermissionDeniedDataAccessException *PessimisticLockingFailureException *PropertyAccessException *RecordTypeNotSupportedException *RecoverableDataAccessException *RemoteAccessException *RemoteConnectFailureException *RemoteInvocationFailureException *RemoteLookupFailureException *RemoteProxyFailureException *ResourceAccessException *RestClientException *SchedulingException *ScriptCompilationException *SerializationFailedException *SoapFaultException *SQLWarningException *SqlXmlFeatureNotImplementedException *TransactionException *TransactionSuspensionNotSupportedException *TransactionSystemException *TransactionTimedOutException *TransactionUsageException *TransientDataAccessException *TransientDataAccessResourceException *TypeMismatchDataAccessException *TypeMismatchException *UnableToRegisterMBeanException *UnableToSendNotificationException *UncategorizedDataAccessException *UncategorizedSQLException *UnexpectedRollbackException *UnsatisfiedDependencyException *XmlBeanDefinitionStoreException
{ "language": "en", "url": "https://stackoverflow.com/questions/7561550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Rails 3 Ruby 1.9.2: UTF-8 characters show garbled in console and view My database table has a column with utf8_general_ci collation. The database.yml has encoding: utf8 The config/application.rb has: config.encoding = "utf-8" When I use mysql command line and directly query the field it shows: 3√5^2 = 5^(2/3); 5^(2/3) = 3√5^2 When I use rails console (or just show in a view) and output the field it shows: 3√5^2 = 5^(2/3); 5^(2/3) = 3√5^2 As you can see the sqrt sign is messed up. What am I doing wrong? A: After a long research I found the solution. It seems like the columns in question were double encoded. They used to have Latin1 collation and were not converted correctly to UTF8. A proposed solution to change the column to a BLOB and then back to TEXT with UTF8 did not work: ALTER TABLE t1 CHANGE c1 c1 BLOB; ALTER TABLE t1 CHANGE c1 c1 TEXT CHARACTER SET utf8; What did eventually work was: mysqldump -uuser -ppassword --opt --quote-names --skip-set-charset --default-character-set=latin1 dbname1 table1 > dump.sql mysql -uuser -ppassword --default-character-set=utf8 dbname1 < dump.sql
{ "language": "en", "url": "https://stackoverflow.com/questions/7561552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android hellospinner tutorial I am doing the HelloSpinner tutorial and I am getting error markers under two areas (lines 4 and 6 of the onCreate method...i marked them )and I cant figure out why? I have used the code from the tutorial and I have not varied from their instructions. Here is my code... package com.android.HelloSpinner; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.Toast; import android.widget.AdapterView.OnItemSelectedListener; public class Activity1 extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Spinner spinner = (Spinner) findViewById(*R.id*(<-this is an error).spinner); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, (*R.array*(<-this is an error).planets_array, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new MyOnItemSelectedListener()); } public class MyOnItemSelectedListener implements OnItemSelectedListener { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { Toast.makeText(parent.getContext(), "The planet is " + parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show(); } public void onNothingSelected(AdapterView parent) { // Do nothing. } } }////end of class Activity1 here is my main.xml file in layout <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:padding="10dip" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="10dip" android:text="@string/planet_prompt" /> <Spinner android:id="@+id/spinner" android:layout_width="fill_parent" android:layout_height="wrap_content" android:prompt="@string/planet_prompt" /> </LinearLayout> and her is my strings.xml file from my values folder <?xml version="1.0" encoding="utf-8"?> <resources> <string name="planet_prompt">Choose a planet</string> <string-array name="planets_array"> <item>Mercury</item> <item>Venus</item> <item>Earth</item> <item>Mars</item> <item>Jupiter</item> <item>Saturn</item> <item>Uranus</item> <item>Neptune</item> </string-array> </resources> A: The R class is a generated class based on the all the resources in your res/ directory. The R class should be located in the 'gen' subdirectory of your project. So you can poke at it and see what it actually contains. Here's more details on the R class: http://developer.android.com/guide/topics/resources/accessing-resources.html See also: Android - How to regenerate R class? A: None of the above worked for me. Somehow I ended up with spinner1 in my main.xml andI had to do change the java code to use this name. Spinner spinner1 = (Spinner) findViewById(R.id.spinner1); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.planets_array, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner1.setAdapter(adapter); This was a GUESS based on looking at some other api code from spinner1.java) but after looking at my main.xml it was obvious: Spinner android:id="@+id/spinner1" The reason I ran into this is because I was playing with the elements of the main.xml manually, and added the spinner to the page before editing the xml. Hence, the system names it spinner1. Hope this helps someone avoid the headaches I ran into here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How Do You Handle Expired Access Tokens for the New OpenGraph Publish Actions Feature? It looks like, even when you have publish_actions permission, the access_token still expires after a few hours. If the goal of publish_actions is to be able to do things for the user in the background without having to ask for permissions over and over again, how do we renew the token without input from the user? I also read here: https://developers.facebook.com/docs/beta/opengraph/actions/: Note - Apps can also use an App Access Token to publish actions for authenticated users. But that doesn't work for me either, I get: {"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException"}} EDIT The App Access Token does work, but in the API URL you have to change "me" to the user's ID (e.g. https://graph.facebook.com/me => https://graph.facebook.com/<some user id>) A: There are very very few cases where you need the offline_access permission. To post OG actions, the user must be present in your app. You may not post actions on their behalf when they're not present and performing actions in your app. As such, you can use the JS SDK to keep the user token fresh. Just run FB.getLoginStatus() asynchronously on each page, and it will ensure you always have a valid access token as long as the user has auth'd your app and is signed into Facebook. A: Sounds like you found your answer :). You could ask for the offline_access permission (generatea a non expiring user token) if you did want to use the user token instead of the app token although I would recommend using the app token where possible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NodeJS - multiple objects split across multiple files but in the same namespace I am writing a multiplayer board game server in NodeJS, and I have several different objects like Game, User, Board etc. Currently, all of these objects reside in a single 'sever.js' file which is executed by NodeJS. As my project grows, this single file is becoming increasingly crowded and hard to navigate. What I would like is to split these objects into multiple js files, but without having to use the require function all over the place. I wish to continue creating objects like this - game = new Game(); And not this - game = new (require('game')).Game() -- Edit: What is the correct NodeJS way of doing things? A: Well, there are a few small things you can do. First, when you define your class in another file (to be required) you define module.exports directly, i.e. module.exports = function Game() {...}; And, then instead of: game = new (require('game')).Game() You can do: game = new (require('game')); Or, what I prefer, is to define all the requirements at the top: var Game = require('game'), User = require('user'); // Use them: new Game(); new User(); You could create some fancy loader that traverses the directly and automatically requires all JS files, but I really don't think it's worth it. A: You can use global. in Game.js: global.Game = function(){}; in User.js: global.User = function(){}; in main.js: require('Game.js'); require('User.js'); var game = new Game(); var user = new User(); A: You can load them at the beginning: var Game = require('game').Game; // Do a bunch of stuff var game = new Game(); However, I personally wouldn't. Can't say exactly why I don't like the idea, but I don't.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How can I word wrap long strings in Annotations in AppKit's mapview? I am working with the mapview in AppKit. I have a map with pins which, when tapped, bring up an annotation with text in them. When the strings are too long, they cut off with elipses. I'd like to make the text wrap to the next line instead of cutting off. Here is the code. In the .m I import the .h, synthesize the stuff from the .h. I also create the strings here. Would I create variable here that I assign the height to? Or is there a property which allows me to word wrap? #import "AdoptingAnAnnotation.h" @implementation AdoptingAnAnnotation @synthesize latitude; @synthesize longitude; @synthesize coordinate; - (id) initWithLatitude:(CLLocationDegrees) lat longitude:(CLLocationDegrees) lng { latitude = lat; longitude = lng; return self; } - (CLLocationCoordinate2D) coordinate { CLLocationCoordinate2D coord = {self.latitude, self.longitude}; return coord; } - (NSString *) title { return @"Some Text"; } - (NSString *) subtitle { return @"Some More Text, a bunch of it, a niiiiice long string. Some More Text."; } @end and then in the view controller. Do I apply some attribute here? AdoptingAnAnnotation *museumTaxiAnnotation = [[[AdoptingAnAnnotation alloc] initWithLatitude:41.891036 longitude:-87.607663] autorelease]; [myMapView addAnnotation:museumTaxiAnnotation]; Please help! Im really new with xCode and kinda got rushed into this project. A: You'll have to create your own view controller for the popover and use that when displaying. This question should help you: How do I display a UIPopoverView as a annotation to the map view? (iPad)
{ "language": "en", "url": "https://stackoverflow.com/questions/7561566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Whats wrong with this CSS/HTML code? Possible Duplicate: CSS not modifying link properties What's wrong with this code? When I scroll over the navigation, everything pops up. Additionally, I cant get the color of the text to be white (when I scroll over it, its white but when I back off, it stays black. Also, check the bottom of my page, both columns are messed up…both should be equal width and length and should sit right next to each other. Thanks for your help. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <style type="text/css"> body html { margin:0; padding:0; color:#101010; font-family: helvetica; } p { margin:10px 0 0 20px; font-size: 13px; line-height: 1.3em; padding-bottom: 10px; } p a{ text-decoration: none; color: #4e6f8c; } #wrapper { width:960px; margin:0 auto; padding: 0px; background:#fff; } #header { padding:5px 10px; background:#fff; height:518px; } #nav { padding:5px 10px; background:#fff; width: 960px; height: 35px; position: absolute; top: 370px; font-size: 18px; color: #000; } #nav ul { margin:0; padding:0; list-style:none; position: absolute; bottom: 5px; } #nav li { display:inline; margin:0; padding:0; width:160px; float:left; } #nav li:hover { background-color: #24389b; height: 25px; } #nav a { color: #fff; text-decoration: none; } #nav a:link { color: #000; text-decoration: none; } #nav a:visited{ color: #ffffff; text-decoration: none; } #nav a:hover { color: #ffffff; text-decoration: none; } #nav a:focus { color: #ffffff; text-decoration: none; } #nav a:active { color: #ffffff; text-decoration: none; } #topcontent p { color: #444444; } } #leftcontent { float:left; width:480px; height: 1%; background:#fff; } h2 { margin:10px 0 0 20px; color: #24389b; font-size: 19px; padding-bottom: 8px; } #rightcontent { float:right; width:480px; background:#fff; height: 1%; } #footer { clear:both; padding:5px 10px; background:#fff; } #footer p { margin:0; } * html #footer { height:1px; } </style> </head> <body> <div id="wrapper"> <div id="header"><img src="pold.png" alt="Pold Logo" /></div> <div id="nav"> <ul> <li><a href="Research">Research</a></li> <li><a href="Research">Publications</a></li> <li><a href="Research">Software</a></li> <li><a href="Research">People</a></li> <li><a href="Research">Volunteer</a></li> <li><a href="Research">Resources</a></li> </ul> </div> <div id="topcontent"> <p>The interests of our lab are generally centered around the study of learning and memory, decision making, and executive control. Much of our work is focused on basic cognitive and neural mechanism, but we are also heavily involved in translational research not the mechanisms of neuropsychiatric disorders. </p> </div> <div id="leftcontent"> <h2>Funded Projects</h2> <p><a href="url">The Cognitive Atlas</a><br />(funded by NIMH RO1MH0822795)<br />The Cognitive Atlas project aims to develop anontology for cognitive processes through social <br />collaborative knowledge building.</p> </div> <div id="rightcontent"> <h2>Center Grants</h2> <p><a href="url">Consortium for Neuropsychiatric Phenomics</a><br />(funded by NIH, PI: R. Bilder)<br />This Roadmap Interdisciplinary Research Consortium is leveraging the new discipline of phonemics to understand neuropsychiatric disorders at multiple levels, from genes to neural systems to </p> </div> <div id="footer"> </div> </div> </body> </html> A: Everything 'pops up' because you've got a height declaration in the hover attribute but not the original li definition: #nav li:hover { background-color: #24389b; height: 25px; } The problem with columns is almost certainly because you've got the left to float left and the right hand one to float right - as far as I can remember, it will probably work best if you set them both to float left (there are lots of tutorials on 2 column liquid CSS designs; you should be able to adapt one to your needs) I agree with @Joseph for your link colour issue - that's simple to fix. A: Little hard to tell what's going on... especially without seeing a demo of some kind, but as far as your hover text problem goes, you have the following: #nav a:hover { color: #ffffff; text-decoration: none; } The problem is you are not wanting it to change the text when you hover over the link. you want it to change color when you hover over the li like with your other rule. Therefore, it should be like this: #nav li:hover a { color: #ffffff; text-decoration: none; } And Like I said, for the other stuff you should provide some kind of demo we can work with (and it might not be a bad idea making it a whole other question.) EDIT After seeing sg3s' comment I went back to see if there's a more compatible way and... there is! #nav a { color: white; text-decoration: none; display:block; } that mostly gets it... it's not perfect though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: jQuery Ajax passing value on php same page I am kinda confused on it, when trying to send value on the same page. <script> $("select[name='sweets']").change(function () { var str = ""; $("select[name='sweets'] option:selected").each(function () { str += $(this).text() + " "; }); jQuery.ajax({ type: "POST", data: $("form#a").serialize(), success: function(data){ jQuery(".res").html(data); $('#test').text($(data).html()); } }); var str = $("form").serialize(); $(".res").text(str); }); </script> <div id="test"> <?php echo $_POST['sweets']; ?> </div> <form id="a" action="" method="post"> <select name="sweets" > <option>Chocolate</option> <option selected="selected">Candy</option> <option>Taffy</option> <option>Caramel</option> <option>Fudge</option> <option>Cookie</option> </select> </form> Well it will display if its in the top of html tag but if its inside the body it will display null. A: You should wrap your code with $(document).ready(function(){ // your code here }); This way, it will only run when the browser finishes processing the structure of your HTML. UPDATE There was a lot of debug stuff on your code, try this (requires Firebug to see the output of the ajax request): <script> $(document).ready(function(){ $("select[name='sweets']").change(function () { jQuery.ajax({ type: "POST", data: $("form#a").serialize(), success: function(data) { // Check the output of ajax call on firebug console console.log(data); } }); }); }); </script> A: Here is the working code for you. To send ajax request to the same page you can keep url parameter empty, which you are already doing. If you are trying to make the script behave differently when $_POST has value then use isset as I have used below. <?php if(isset($_POST['sweets'])) { echo $_POST['sweets']; exit; } ?> <script> $(function(){ $("select[name='sweets']").change(function () { var str = ""; $("select[name='sweets'] option:selected").each(function () { str += $(this).text() + " "; }); jQuery.ajax({ type: "POST", data: $("form#a").serialize(), success: function(data){ jQuery(".res").html(data); $('#test').html(data); } }); var str = $("form").serialize(); $(".res").text(str); }); }); </script> <div id="test"> </div> <form id="a" action="" method="post"> <select name="sweets" > <option>Chocolate</option> <option selected="selected">Candy</option> <option>Taffy</option> <option>Caramel</option> <option>Fudge</option> <option>Cookie</option> </select> </form>
{ "language": "en", "url": "https://stackoverflow.com/questions/7561569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Why would you use a !! operator I came across abit of ruby in a example def role?(role) return !!self.roles.find_by_name(role.to_s.camelize) end Why would you ever use !!? Is it not the same as return self.roles.find_by_name(role.to_s.camelize) Does adding the double exclamation mark add something to the evaluation? A: Disclaimer: Not a ruby programmer but having a stab at this. !!, double bang or "not not", might convert the value to a boolean. One ! returns the boolean opposite and another bang thereafter will flip it to its normal boolean value. A: This is a double negation which results in a boolean: irb(main):016:0> !1 => false irb(main):013:0> !0 => false irb(main):014:0> !nil => true irb(main):015:0> !!nil => false A: You use it if you only want the boolean, not the object. Any non-nil object except for boolean false represents true, however, you'd return the data as well. By double negating it, you return a proper boolean. A: Yes in your case you can be sure that the function is returning only true or false. If you would omit !! you would return a list of roles A: with this little trick you get the actual boolean value of an expression, e.g.: !! 3 => true !! nil => false !! 0 => true In Ruby anything that isn't nil or false , is true! In your example code this trick makes sure that you never return anything else but true or false If you would omit the !! , you would return the list of roles, or nil
{ "language": "en", "url": "https://stackoverflow.com/questions/7561572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Node.js: How Many Redis Clients? In Node.js, would it be best to do a createClient() for each individual HTTP request or user, or would it be better to re-use the same client for all requests? Do you still get the speed of several parallel clients with just one? A: In Node.js, would it be best to do a createClient() for each individual HTTP request or user, or would it be better to re-use the same client for all requests? You should reuse the redis client connection and persist it during the lifetime of your program since establishing a new connection have some initial overhead which can be avoided with already connected client. Do you still get the speed of several parallel clients with just one? You might get some performance improvements with a pool of several parallel clients (limited number, not dedicated connection for each individual HTTP request or user), but the question is how would you deal with the concurrency of executed commands. Although redis is built to handle hundreds or thousands of simultaneously connected clients, connection pooling is something which, I think, should be controlled by the client library you are using. However you should use two parallel connections if you are simultaneously using redis for listening on some pub/sub channel and at the same time executing normal commands.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: ActiveX component can't create object: 'CDONTS.Newmail' I'm getting this error on a windows 2003 server: Microsoft VBScript runtime error '800a01ad' ActiveX component can't create object: 'CDONTS.Newmail' I really don't want to have to change the code to something else. is there some way i can get CDONTS to work onw indows 2003. A: You can install and run CDONTS on Windows 2003 - you'll need to download the DLL (try http://www.thevbzone.com/d_DLL.htm) and then install it by running: C:\Inetpub\WebDlls>regsvr32 cdonts.dll Then do an iisreset and you should find your scripts can create CDONTS.NewMail as they could on Windows NT and 2000.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: login to facebook chat using asmack on android with the new access token I have a FB chat client developed for Android. I've been using facebook android-sdk to obtain the access token from a user. Using asmack, user was logged into the chat. Token was in the form: 226409362971500|3b29bc82baa7901a9baca042.4-72793766|9eb417f06fc376897222938295a0dd0c The code I used was: XMPPConnection xmpp = new XMPPConnection(config); SASLAuthentication.registerSASLMechanism("DIGEST-MD5", SASLDigestMD5Mechanism.class); SASLAuthentication.supportSASLMechanism("DIGEST-MD5", 0); xmpp.connect(); xmpp.login("226409362971500", "3b29bc82baa7901a9fbaca042.4-72793766|9eb417f06fc376897222938295a0dd0c", "Application"); Now it seems that Facebook has changed the token format. I have tried logging in with the old token, but I always get XMPPException. I've tried loggin in with the new access token: xmpp.login(token, "Application"), but still no luck. Any idea how to solve this?
{ "language": "en", "url": "https://stackoverflow.com/questions/7561579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can i get Apache to log who started/stopped it? I need Apache2.2 to log the username of anyone who tries to start or stop it. How do i go about it? A: This could be achived by sudo, not allowing users to log in as root directly and allow them only specific action, and each action can be logged.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Configure SSL on a Microsoft.Web.Administration.Application object? I'm having a little trouble figuring out how to programatically enable the "Require SSL" check box and change the "Client Certificates" option to "Require" in IIS Application using Microsoft.Web.Administration. All of the questions on the net I've found relate to configuring it on the web site itself, but I need only need to turn it on for a few Applications hosted on the site. Anyone have experience doing this? I tried this to start: application.EnabledProtocols = "http,https"; serverManager.CommitChanges(); But I got an error: Filename: \?\C:\Windows\system32\inetsrv\config\applicationHost.config Error: Cannot write configuration file Which is odd, because from what I've read, I gather that file maintains IIS configuration, but it doesn't exist in Windows (I can't open it in TextPad), but it does exist in the command prompt and I can more it. A: Did more searching, found this, ended up writing this: ServerManager serverManager = new ServerManager(); Configuration config = serverManager.GetApplicationHostConfiguration(); ConfigurationSection accessSection = config.GetSection("system.webServer/security/access", siteName + "/" + vdRelativePath); accessSection["sslFlags"] = "Ssl,SslRequireCert"; Where siteName and vdRelativePath are "Default Web Site" and "/Application/Path". You can use config.GetLocationPaths() to find the right path if "Default Web Site/Application/Path" doesn't work for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: nodejs proxy not responding I have a node.js app that serve static files (html, js, css). Among the static files, some ajax request are done (with /TEST in the request). I need those request to be proxied to another server running on localhost:213445. The static pages are correctly displayed but when it comes to proxied request it hangs forever... My code is: var express = require("express"); var httpProxy = require('http-proxy'); var fs = require('fs'); // Create https server var app = express.createServer({ key: fs.readFileSync('privatekey.pem'), cert: fs.readFileSync('certificate.pem') }); // Handle static files app.use(express.static(__dirname + '/public')); // Proxy request app.all('/TEST/*',function(req, res){ // Remove '/TEST' part from query string req.url = '/' + req.url.split('/').slice(2).join('/'); // Create proxy var proxy = new httpProxy.HttpProxy(); proxy.proxyRequest(req, res, { host: 'localhost', port: 21345, enableXForwarded: false, buffer: proxy.buffer(req) }); }); // Run application app.listen(10443); A: I have the same issue. If you comment out the // Handle static files app.use(express.static(__dirname + '/public')); you will see that the the proxy works. Not sure how to fix it if express.static is used Marak Squires responded to the bug report! This is an express problem. The Connect / Express middlewares are doing non-standard things to your response object, breaks streaming. Try using the raw request module instead of http-proxy. If you need proper middleware stack, check out https://github.com/flatiron/union A: As described on the http-proxy issue 180 the trouble is related to the non-standard things done by connect mentioned above: Use npm to install connect-restreamer and make this the final item in your app.configuration of express: app.use(require('connect-restreamer')()); Then do something like: var httpProxy = require('http-proxy'); var routingProxy = new httpProxy.RoutingProxy(); app.get('/proxy/', function (req, res) { routingProxy.proxyRequest(req, res, { target: { host : host, port : port } }); }) This will pass the whole URL, including "/proxy/" to the target host. You can rewrite/modify the headers of the req before they go into the proxyRequest() if you, e.g. want to mimic the request coming from a specific CNAME virtual host or different URL string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Unrecognized pref_type 0 for NullProfileSettings pref name default_non_connection_tab I get the error "error": { "message": "SETTINGS: Unrecognized pref_type 0 for NullProfileSettings pref name default_non_connection_tab.", "type": "Exception" } when trying to view this feed https://graph.facebook.com/10150331381804198/feed?access_token=[correct access token] Does anyone know what this means? A: I think facebook Open Graph still not support any connections(ex. feed, posts). Because probably it's now Beta season. A: Incorrect object id (e.g. page, user, ...)
{ "language": "en", "url": "https://stackoverflow.com/questions/7561590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Initializing static fields in C# for use in enum pattern My question is actually about a way to work around how C# initializes static fields. I need to do this, in my attempt to duplicate a Java style enum. The following is an example of the code that shows the problem: A base class for all my enums to inherit from public class EnumBase { private int _val; private string _description; protected static Dictionary<int, EnumBase> ValueMap = new Dictionary<int, EnumBase>(); public EnumBase(int v, string desc) { _description = desc; _val = v; ValueMap.Add(_val, this); } public static EnumBase ValueOf(int i) { return ValueMap[i]; } public static IEnumerable<EnumBase> Values { get { return ValueMap.Values; } } public override string ToString() { return string.Format("MyEnum({0})", _val); } } A sample of an enumerated set: public sealed class Colors : EnumBase { public static readonly Colors Red = new Colors(0, "Red"); public static readonly Colors Green = new Colors(1, "Green"); public static readonly Colors Blue = new Colors(2, "Blue"); public static readonly Colors Yellow = new Colors(3, "Yellow"); public Colors(int v, string d) : base(v,d) {} } This is where the problem is: class Program { static void Main(string[] args) { Console.WriteLine("color value of 1 is " + Colors.ValueOf(2)); //fails here } } The above code fails because EnumBase.ValueMap contains zero items, because none of the constructors for Color have been called yet. It seems like this shouldn't be that hard to do, it is possible in Java, I feel like I must be missing something here? A: That pattern basically isn't going to work. Having a single dictionary isn't going to be a good idea, either - I suspect you want to make your EnumBase abstract and generic: public abstract class EnumBase<T> where T : EnumBase<T> That could then have a protected static member which can be effectively "published" through each derived class: public abstract class EnumBase<T> where T : EnumBase<T> { protected static T ValueOfImpl(int value) { ... } } public class Color : EnumBase<Color> { // static fields // Force initialization on any access, not just on field access static Color() {} // Each derived class would have this. public static Color ValueOf(int value) { return ValueOfImpl(value); } } This then forces you to access the Color class itself... at which point the fields will be initialized, due to the static initializer. There are quite a few things to be done to make all of this work, unfortunately :( A: I believe what you were trying so say in code is simply: public enum Colors { [Description("Red")] Red = 0, [Description("Green")] Green = 1, [Description("Blue")] Blue = 2 //etc... } You can easily read the Description attribute using reflection.. You can even create an extention methods for the Colors enums if you want and implement something similar to ValueOf as an extention method A: You're missing the point of a static member. A static member is a member of the type, not the instance. When you call Colors.ValueOf() you are only accessing the type, an instance has not been created of that type - the instance constructors won't be called at all. You could create an extension method for the Color enum if you just want to be able to define some behaviours. You could get the enum from a value simply by casting from its int base: public enum Color { Red = 0, Green = 1, Blue = 2, Yellow = 3 } public static class ColorExtensions { public static string GetString(this Color color) { return string.Format("MyEnum({0})", color); } } Console.WriteLine("color value of 1 is " + ((Color)1).GetString()); You'll also find a number of useful methods in the System.Enum class (http://msdn.microsoft.com/en-us/library/system.enum.aspx). There are methods there to parse from string or to get a collection of all the possible enum values. A: This can be done, and it is actually quite useful. You get type safety when setting variables and the ability to search dynamically. I'd prefer to see less code in the child class, but none the less, it works well. You could also expand upon this and grow the number of fields in the EnumBase and also override operators and the ToString methods, etc. You could also throw more generics into the mix. It's Enums on steroids. Edited: Read bottom of entry EnumBase: public class EnumBase { public int Val { get; private set; } public string Description { get; private set; } private static readonly Dictionary<int, EnumBase> ValueMap = new Dictionary<int, EnumBase>(); protected EnumBase(int v, string desc) { Description = desc; Val = v; } protected static void BuildDictionary<T>() { var fields = typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static); foreach (var field in fields) { ValueMap.Add(((EnumBase)field.GetValue(null)).Val, (EnumBase)field.GetValue(null)); } } public static EnumBase ValueOf(int i) { return ValueMap[i]; } } Colors: public sealed class Colors : EnumBase { public static readonly Colors Red = new Colors(0, "Red"); public static readonly Colors Green = new Colors(1, "Green"); public static readonly Colors Blue = new Colors(2, "Blue"); public static readonly Colors Yellow = new Colors(3, "Yellow"); public Colors(int v, string d) : base(v, d) { } static Colors() { BuildDictionary<Colors>(); } } Usage: //example of type safety var i = Colors.Blue.Val; //example of dynamic search Console.WriteLine(Colors.ValueOf(1).Description); Edited: The above code doesn't work if you inherit from EnumBase more than once (which is a huge problem). The static methods aren't inherited, i.e. all child classes will just add more records to the static base class Dictionary. If the use case is strong enough, you can reuse the code instead of trying to use inheritance: public sealed class Colors { public int Val { get; private set; } public string Description { get; private set; } private static readonly Dictionary<int, Colors> ValueMap = new Dictionary<int, Colors>(); static Colors() { BuildDictionary<Colors>(); } private static void BuildDictionary<T>() { var fields = typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static); foreach (var field in fields) { ValueMap.Add(((Colors)field.GetValue(null)).Val, (Colors)field.GetValue(null)); } } public static Colors ValueOf(int i) { return ValueMap[i]; } private Colors(int v, string desc) { Description = desc; Val = v; } public static readonly Colors Red = new Colors(0, "Red"); public static readonly Colors Green = new Colors(1, "Green"); public static readonly Colors Blue = new Colors(2, "Blue"); public static readonly Colors Yellow = new Colors(3, "Yellow"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7561596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How has this view and control been done? The image is attached below. Basically it is the popular photo editing app Snapseed. When you touch drag on an image that is being edited a table like view animates in to visibility on top of the image with its options as seen below in the image. The neatest part is that it vanishes on removing the finger from the screen and you perform the selection from one of the 5 options below in that table like view by continuing to touch drag in the upward or downward direction immediately after touch dragging on the image to make the menu appear. Once selection is made, it passes back the selection to the parent and vanishes. Any ideas on how this might have been done? A: The view with the buttons is probably hidden until the view with the image detects a touch, whereupon it executes the touchesBegan:withEvent: method, which is part of the UIResponder class. Most views subclass UIResponder, so this is a built-in method, along with touchesEnded:withEvent:. When touchesEnded:withEvent: executes, the button view is dismissed. (It either hides immediately or it animates the alpha value until is disappears.) More info Here is some code from the kal Calendar by Keith Lazuka. This code looks at the position where the touch ended to determine what "tile" on the calendar is hit. I suppose the same thing could be used here to determine which "button" is selected in your example. - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self receivedTouches:touches withEvent:event]; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { [self receivedTouches:touches withEvent:event]; } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; CGPoint location = [touch locationInView:self]; UIView *hitView = [self hitTest:location withEvent:event]; //[self receivedTouches:touches withEvent:event]; if ([hitView isKindOfClass:[KalTileView class]]) { KalTileView *tile = (KalTileView*)hitView; if (tile.belongsToAdjacentMonth) { if ([tile.date compare:[KalDate dateFromNSDate:logic.baseDate]] == NSOrderedDescending) { [delegate showFollowingMonth]; } else { [delegate showPreviousMonth]; } self.selectedTile = [frontMonthView tileForDate:tile.date]; } else { //self.selectedTile = tile; } } self.highlightedTile = nil; } The key to this is in the first three lines of code in the touchesEnded method. hitTest:withEvent: is an instance method of UIView that tells you which view was hit when the touchesEnded event fires, based on the point location where the touches ended occurs. As you can see in this example code, it does return a UIView instance (or something subclassing UIView). Once you know which view was identified, to code can be written to take the desired action. A: It could be a simple UIView, added as subview, shown with bringSubviewToFront. What happens when you tap on the image again while the menu is shown?
{ "language": "en", "url": "https://stackoverflow.com/questions/7561598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Define Self as multiple attributes in Django I'm new to Django and building my first app. I want locations in my Admin section to be displayed by a combination of different attributes from the model. Currently they are shown by the icon by using the following code. def __unicode__(self): return self.icon I want to be able to add my other two attributes to this code so that the result will look like. "Icon(Attribute1, Attribute2)" How can I edit the code to do this? A: If I have understood you correctly then the following should produce the result that you are looking for (but you'll need to edit the attribute names): def __unicode__(self): return u"{0} ({1}, {2})".format(self.icon, self.attrib1, self.attrib2)
{ "language": "en", "url": "https://stackoverflow.com/questions/7561600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Automapper: How to get source property name from PropertyMap How do I get the name of the source property from the property map in this code: IEnumerable<PropertyMap> propertyMapList = Mapper.FindTypeMapFor<TFrom, TTo>().GetPropertyMaps(); foreach (PropertyMap propertyMap in propertyMapList) { ////..... } A: This should work in AutoMapper v1 (haven't tried in v2 yet). foreach (PropertyMap propertyMap in propertyMapList) { var resolver = propertyMap.GetSourceValueResolvers().First(); var getter = (IMemberGetter) resolver; var info = getter.MemberInfo; } This assumes that it's just a bog-standard map from one property to another, it won't work otherwise. So, obviously, you'll want to add error checking around the cast, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: vim spell check: ignore capitalized words? How can I tell Vim's spell checker to ignore words which have a leading capital? It's annoying that, for example, MyWidget is flagged as a spelling error. A: You can define a syntax element to ignore spell checking. " Ignore CamelCase words when spell checking fun! IgnoreCamelCaseSpell() syn match CamelCase /\<[A-Z][a-z]\+[A-Z].\{-}\>/ contains=@NoSpell transparent syn cluster Spell add=CamelCase endfun autocmd BufRead,BufNewFile * :call IgnoreCamelCaseSpell() Note that the autocmd is necessary to make sure that the syntax rules are loaded after the syntax definitions for the file type have been loaded (as the syntax rules wipe out any existing syntax rules). However I'll personally prefer to add them (with zg) as good, so I can check there is no typo rather than ignoring everything. A: There is a patch available for vim that adds this functionality https://github.com/btucker-MPCData/vim/commit/8801705b7a4a64db39de65ea56e982132488ebde Showing the 'Spelng' part of the token is incorrect A: Was also recently searching for good solution on smart spell check for vim/nvim. The best seems to be the coc-spell-check(https://github.com/iamcco/coc-spell-checker) after comparing with other plugins. It basically gives you same experience as vscode's spell check. The exception words list is typically stored under ~/.config/nvim/coc-settings.json's cSpell.userWords object. A: Just add MyWidget and all the other class names into your personal dictionary. Lookup vim help file to find out the personal dictionary name. Automate this away into a script.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Object hasn't in property - php soap wsdl Every time I try to make a call to my webservice, through the wsdl, I get the error message shown here. I think it's probably an issue within the the WSDL defintion, because I am not really sure what I am doing within the WSDL definition to begin with: PHP Fatal error: SOAP-ERROR: Encoding: object hasn't 'in' property in /www/zendserver/htdocs/dev/csc/csc.php on line 10 I have a very simple web service, located at: http://192.168.1.2:10088/csc/csc.php <?php function EchoText($text){ return $text; } $server = new SoapServer("http://192.168.1.2:10088/csc/csc.wsdl", array('uri' => "http://192.168.1.2:10088/csc/csc.php")); $server->addFunction('EchoText'); $server->handle(); ?> I have an interfacing page, which is what I access and then get the error shown above, located at: http://192.168.1.2:10088/csc/request.php <?php try{ $client = new SoapClient("http://192.168.1.2:10088/csc/csc.wsdl", array('trace'=>1)); $result = $client->EchoText("test"); echo $result; } catch (Exception $e) { print_r($e); } >? I have my WSDL, located at: http://192.168.1.2:10088/csc/csc.wsdl <?xml version="1.0" encoding="UTF-8" standalone="no"?> <wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://192.168.1.2:10088/csc/csc.wsdl" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="csc" targetNamespace="http://192.168.1.2:10088/csc/csc.wsdl"> <wsdl:types> <xsd:schema targetNamespace="http://192.168.1.2:10088/csc/csc.wsdl"> <xsd:element name="EchoText"> <xsd:complexType> <xsd:sequence> <xsd:element name="in" type="xsd:string"/> </xsd:sequence> </xsd:complexType> </xsd:element> <xsd:element name="EchoTextResponse"> <xsd:complexType> <xsd:sequence> <xsd:element name="out" type="xsd:string"/> </xsd:sequence> </xsd:complexType> </xsd:element> <xsd:element name="EchoTextFault"> <xsd:complexType> <xsd:all> <xsd:element name="errorMessage" type="xsd:string"/> </xsd:all> </xsd:complexType> </xsd:element> </xsd:schema> </wsdl:types> <wsdl:message name="EchoTextRequest"> <wsdl:part element="tns:EchoText" name="parameters"/> </wsdl:message> <wsdl:message name="EchoTextResponse"> <wsdl:part element="tns:EchoText" name="parameters"/> </wsdl:message> <wsdl:portType name="csc"> <wsdl:operation name="EchoText"> <wsdl:input message="tns:EchoTextRequest"/> <wsdl:output message="tns:EchoTextResponse"/> </wsdl:operation> </wsdl:portType> <wsdl:binding name="cscSOAP" type="tns:csc"> <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <wsdl:operation name="EchoText"> <soap:operation soapAction="http://192.168.1.2:10088/csc/csc/EchoText"/> <wsdl:input> <soap:body use="literal"/> </wsdl:input> <wsdl:output> <soap:body use="literal"/> </wsdl:output> </wsdl:operation> </wsdl:binding> <wsdl:service name="csc"> <wsdl:port binding="tns:cscSOAP" name="cscSOAP"> <soap:address location="http://192.168.1.2:10088/csc/csc.php"/> </wsdl:port> </wsdl:service> </wsdl:definitions> This post is a continuation of PHP - create and call SOAP web service - error
{ "language": "en", "url": "https://stackoverflow.com/questions/7561604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android, why ever use Button views, since every view can have an onclicklistener I am curious, why would I ever use Button or ImageButton, when TextViews, ImageViews, and everything else all can have onclicklisteners, all can have src's and background attributes, states and everything else that a Button or ImageButton offers I might be missing something, so please reveal what it is A: There's no differences, except default style. ImageButton has a non-null background by default. Also, ImageButton.onSetAlpha() method always returns false, scaleType is set to center and it's always inflated as focusable. Here's ImageButton's default style: <style name="Widget.ImageButton"> <item name="android:focusable">true</item> <item name="android:clickable">true</item> <item name="android:scaleType">center</item> <item name="android:background">@android:drawable/btn_default</item> </style> A: Each one has different styles, that's it. You can create a simple TextView and users still can click on it and you can respond to those clicks... but TextView does not offer by default any visual feedback. In fact, a Button is just a TextView with a set of selector drawables.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MongoDB regex query to find unicode replacement character I am trying to manually fix some documents in my Mongo database which contain the Unicode replacement character (looks like a question mark, see http://www.fileformat.info/info/unicode/char/fffd/index.htm). I already fixed the issue why these characters ended up there but would like to keep the old data too. So all I want is a simple query which returns all documents containing this character. What I came up with so far is db.songs.find({artist: /\ufffd/}); to find all songs with an artist name containing the replacement character. No luck so far. A: Seems it doesn't like \uXXXX in the regexp. Try: db.songs.find({artist: new RegExp("\ufffd")}); A: To bump an old thread :D for regex you need to escape the backslash otherwise it will escape the u instead: db.songs.find({artist: /\\ufffd/});
{ "language": "en", "url": "https://stackoverflow.com/questions/7561609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Which of these parts goes into the model vs. controller? I have 5 tasks that a step of my application needs to perform. * * Receive a CSV file as part of a user upload. * Parse each row in the CSV to a canonical representation. * Create an ORM POCO relating to that representation. * Save each item to the database. * Send an email to an email address defined in each POCO. I have a repository already for the database ORM stuff, and I've at least got it figured out that the controller probably shouldn't be new'ing up an SmtpClient by itself, but how much 'glue' goes into the controller? Is exposing any more details than my snippet below a code smell? public ActionResult Index(HttpPostedFileBase file) { var result = model.HandleFileUpload (file); if (result.Success) { return SuccessAction("Success"); } else { return FailureAction("Failure"); } } If this does all belong in the model, what's the type of work I'm doing called, if I'm just "gluing" lower-level things together? A: The thin controller you describe looks pretty good to me. It's easily testable, and makes it easy for you to adhere to Single Responsibility Principle by creating a set of loosely-coupled service classes in your model, each of which handle a different step of your process. This also allows you to make use of the code outside of the confines of your MVC application, should the need arise. So, I would envisage you having a FileHandler class implementing your HandleFileUpload method. This would define the steps of the process, perhaps calling out to FileParser, Repository, and EmailSender classes, each of which could be consumed via interfaces and dependency-injected into your FileHandler. What's the type of work you're doing? Developing maintainable software of which you can be proud :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7561612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Android, how can i encapsulate an AsyncTask class with network connections Im starting with android (3 days ago) and i cant get the solution for what i want. So, i read a lot of threads here about asyncTask and now im sure i got confused. First of all, this is my first question so i hope i get this at least right. What i want is to have a class to connect to some server and the a result from it. After that analyses the json or xml. so this is what i did. this is my activity class (called from main one) public class LogIn extends Activity implements OnClickListener { Button btn =null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login); btn = (Button) findViewById(R.id.btn_login); btn.setOnClickListener( this); } public void onClick(View view) { HttpResponse response; Intent data = new Intent(); //---get the EditText view--- EditText txt_user = (EditText) findViewById(R.id.et_un); EditText txt_pwd = (EditText) findViewById(R.id.et_pw); // aca tengo q llamar al conectar y chequear en BD ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); postParameters.add(new BasicNameValuePair("usr", txt_user.getText().toString())); postParameters.add(new BasicNameValuePair("pass", txt_pwd.getText().toString())); String URL="whatever"; try { response= new ConectServer(URL, postParameters).execute().get(); LeerAutentificacionXml l= new LeerAutentificacionXml(response); String s=l.Transformar(); data.setData(Uri.parse(s.toString())); setResult(RESULT_OK, data); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //---set the data to pass back--- // data.setData(Uri.parse(txt_user.getText().toString()+ " " + Uri.parse(txt_pwd.getText().toString()))); // setResult(RESULT_OK, data); //---closes the activity--- finish(); } } and this is my class that connect to web services. public class ConectServer extends AsyncTask <Void, Void, HttpResponse> { private String URL=null; private ArrayList<NameValuePair> postParameters=null; /** Single instance of our HttpClient */ private HttpClient mHttpClient; /** The time it takes for our client to timeout */ public static final int HTTP_TIMEOUT = 30 * 1000; public ConectServer(String url, ArrayList<NameValuePair> p) { this.URL=url; this.postParameters=p; } private HttpClient getHttpClient() { if (mHttpClient == null) { mHttpClient = new DefaultHttpClient(); final HttpParams params = mHttpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT); HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT); ConnManagerParams.setTimeout(params, HTTP_TIMEOUT); } return mHttpClient; } /** * Performs an HTTP Post request to the specified url with the * specified parameters. * * @param url The web address to post the request to * @param postParameters The parameters to send via the request * @return The result of the request * @throws Exception */ @Override protected HttpResponse doInBackground(Void... params) { // TODO Auto-generated method stub HttpResponse response = null; try { HttpClient client = getHttpClient(); HttpPost request = new HttpPost(this.URL); UrlEncodedFormEntity formEntity; formEntity = new UrlEncodedFormEntity(this.postParameters); request.setEntity(formEntity); response = client.execute(request); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return response; } public void onPreExecute() { super.onPreExecute(); } protected void onPostExecute(HttpResponse response) { super.onPostExecute(response); }} I read about some design patter with listener but first i would like to understand better why this is not working. Im getting an error from server and i would like to know if this is correct or which big newby fail is going on. Thx in advance. A: Calling asyncTask.get() waits for the AsyncTask to finish and then returns the result. It basically defeats the purpose of the AsyncTask - the whole point of AsyncTask is that long-running task executes in the background thread and UI thread is not blocked during this time. When you call .get() it blocks the UI thread waiting for background thread to finish. So, don't use get() and move ll actions that should happen when result is available to onPostExecute(..). Something like this: protected void onPostExecute(HttpResponse response) { super.onPostExecute(response); LeerAutentificacionXml l= new LeerAutentificacionXml(response); String s=l.Transformar(); data.setData(Uri.parse(s.toString())); } Of course, you will have to pass some references (data?) to AsyncTask (via constructor or otherwise). A: Try to encapsulate all of your network code in the async task, so you can call it like this: EditText txt_user = (EditText) findViewById(R.id.et_un); EditText txt_pwd = (EditText) findViewById(R.id.et_pw); new LoginTask(txt_user.getText(), txt_pwd.getText(), this).execute(); with LoginTask being something like the following, based on the code in your question: public class LoginTask extends AsyncTask<Void, Void, String> { // The URL probably won't change, so keep it in a static field private final static String URL = "http://...."; private final String username; private final String password; private final Activity activity; /* * Pass all data required to log in and handle the result here. */ public LoginTask(final String username, final String password, final Activity activity) { this.username = username; this.password = password; this.activity = activity; } /* * Do all the network IO and time-consuming parsing in here, * this method will be invoked in its own thread, not blocking the UI. */ @Override protected String doInBackground(Void... params) { HttpClient client = getHttpClient(); try { HttpEntity formEntity = new UrlEncodedFormEntity(Arrays.asList( new BasicNameValuePair("usr", username), new BasicNameValuePair("pass", password))); HttpPost request = new HttpPost(URL); request.setEntity(formEntity); HttpResponse response = client.execute(request); LeerAutentificacionXml l= new LeerAutentificacionXml(response); return l.Transformar(); } catch (IOException ex) { // properly log your exception, don't just printStackTrace() // as you can't pinpoint the location and it might be cut off Log.e("LOGIN", "failed to log in", ex); } finally { client.getConnectionManager().shutdown(); } } private HttpClient getHttpClient() { return null; // insert your previous code here } /* * This again runs on the UI thread, so only do here * what really needs to run on the UI thread. */ @Override protected void onPostExecute(String response) { Intent data = new Intent(); data.setData(Uri.parse(response)); activity.setResult(Activity.RESULT_OK, data); } } Even if you don't think of the log in as being a "long-running task", anything involving network IO by definition is such a task as it might hang, time out, etc due to reasons beyond your control. There's nothing wrong with having multiple classes that do network IO, as long as you carefully encapsulate the details like the above LoginTask example does. Try to write two, three AsyncTask classes of this type and then see if you can extract common parts into a common "web stuff" AsyncTask. Don't do it all at once, though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I ensure that nobody can download a video off my site? I'm creating a site that shows videos. I'm using the VideoJS player(HTML 5 with a flash fallback - http://videojs.com/) and am using .mp4 files. My client is concerned that someone may be able to steal/download the video files. What can I do to ensure nobody can download the video files? A: Since the video has been sent to the client, there will always be a way to get at that information. Trying to stop a user from doing this will only frustrate them. The only way to have a user not be able to save a file is to not send it to them. If your site is popular enough, someone will write a video grabber for it. A: Well first off, you want to clarify with your client that actually they do want people to download the video, because if people couldn't download it then they can't watch it. The issue is that you don't want people to store a copy that they could then edit or share offline or whatever. This might sound to them like nit-picking, but it's pretty crucial to understand. For starters, once they understand this they might decide "you know what, I don't care about this after all". Second, there is no way to entirely stop people from saving an offline copy of your files. You can make things a little harder, but because there is no way to entirely stop them you really have to decide whether or not you even want those videos online. If after all that you are still wanting to put the videos online with some minimal protection, then what you could do is not directly embed the videos in the HTML but rather have JavaScript on the page talk to your server and request a video. A: I think it depends on what your client wants to protect. Here are some possible solutions: If your client's video is intellectual property and should not be watched without permission, you need to use DRM. HTML5 doesn't support DRM, so you need to use Silverlight (or maybe Flash). With DRM, anyone who has the video file can't watch it without permission. If your client just wants to make sure that users have to go to their website in order to watch the video, you can simply make it harder to download the video or embed it on other website. You can use for example CAPTCHA + session to make sure that it's the human who's visiting the website and watching the video, not a bot crawling the website and downloading the video. This will increase the cost of user downloading video or competitor stealing video but it's not totally unbreakable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Counter that doesn't reset when the page is closed I'm looking for some simple script to display what the title says. Some sort of counter (like a timer) that starts incrementing when the user clicks a button and stops when clicked again or when the page is closed. BUT it has to save the last value to start adding from there when opened again later. I hope it's not too hard to solve since I am just starting with PHP and Javascript. It is for an art project so any help will be very appreciated. Greetings from Argentina! A: For this I'd have a very simple database which stores the last time value and the state of the clock. It can be queried on page load to find out if the counter is on or off and resume from the stored time. Hope this gives you an idea of what needs to be done. Good luck with the project :).
{ "language": "en", "url": "https://stackoverflow.com/questions/7561623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What are WebClient's BaseAddress and QueryString properties used for? I am trying to instantiate a WebClient as follows: WebClient wc = new WebClient(); wc.BaseAddress = "http://contoso.com"; wc.QueryString.Add("ctNm", "some name"); wc.QueryString.Add("port", "title"); wc.QueryString.Add("rx", "1"); wc.QueryString.Add("own", "userx"); wc.QueryString.Add("asOfDt", "02/23/2011"); Since I already defined everything I need for my web request (I mean, I have BaseAddress and QueryString defined), I thought I was going to find some sort of method that would allow me to issue the request without passing in any additional parameters. To my surprise, all methods in WebClient (DownloadData, DownloadFile, DownloadString,OpenRead, etc.) require a Uri or a string as parameter. What's the point in having a BaseAddress and a QueryString properties that you can add values to if you still have to construct the URL manually in order to issue the request? Am I using the wrong tool here? Should I be using WebRequest instead? A: If you wanted then to access http://contoso.com/test.html with those query parameters, you could write: wc.DownloadString("test.html"); In other words, BaseAddress and QueryString are best used when you're downloading multiple pages from the same site. Otherwise, construct your own absolute Uri using the Uri or UriBuilder classes, and pass in the fully formed Uri to DownloadString (or whatever method you need to call). A: From http://msdn.microsoft.com/en-us/library/system.net.webclient.baseaddress.aspx: The BaseAddress property contains a base URI that is combined with a relative address. When you call a method that uploads or downloads data, the WebClient object combines this base URI with the relative address you specify in the method call. If you specify an absolute URI, WebClient does not use the BaseAddress property value. So BaseAddress is doing the generic thing on the WebClient it is supposed to do for all methods that can be called. Multiple methods can be called after each other re-using this single one time configured web client instance. The method itself is responsible for giving the path to its execution relative to the BaseAddress, or an absolute path overriding the pre-configured BaseAddress. Sounds logical to me :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7561624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Automatically save textbox contents I have a textbox that a user can type some text into. The area that the textbox is in can get re-loaded with different HTML depending on what the user does, and I want the textbox to "remember" what the user typed into it when he comes back. The problem starts with the fact that there are many different ways that the user can navigate away from the textbox - he can load many different HTML segments into my operational area, each erasing the textbox. Is there a way for me to universally save textbox contents when it is getting unloaded? Is there an equivalent of onUnload() event for textbox? There are two ways I can see that would solve my problem: * *Setup textbox watchdog functions that update text stored in memory whenever user types anything. *Add a saveText() call to every function that reloads the operational area. Neither of these is particularily appealing. Is there a more elegant way of doing this? Thanks, A: The onchange is what you're looking for. When the user exits the textbox, the change event is fired. onchange is a better choice than onblur or focusout, because blur and focusout also fire when the contents of the text field hasn't changed. A basic example: var textarea = document.getElementById("myTextfield"); textarea.onchange = function(ev){ call_function_that_saves(this.value); } An unload event for non-embedded elements doesn't exist. Consider what would happend when such an event handler exists, and a huge page unloads..
{ "language": "en", "url": "https://stackoverflow.com/questions/7561625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Syncing two iOS devices over bluetooth I'm not sure if this one is even possible, but I thought that I should ask. I need an event to be triggered on two (or more) ios devices at the exact same time. Right now I use Bluetooth to trigger the event on all devices, however, as expected, there is a small (or not so small, depending on many factors) delay. Is there a way to achieve this? Or should I forget it? A: Depending on how demanding your requirements are, you could use something like the NTP protocol to synchronise the device clocks, and then send a specific time at which each device should trigger the event.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Process Items in an Array in Parallel using Ruby (and open-uri) I am wondering how i can go about opening multiple concurrent connections using open-uri? i THINK I need to use threading or fibers some how but i'm not sure. Example code: def get_doc(url) begin Nokogiri::HTML(open(url).read) rescue Exception => ex puts "Failed at #{Time.now}" puts "Error: #{ex}" end end array_of_urls_to_process = [......] # How can I iterate over items in the array in parallel (instead of one at a time?) array_of_urls_to_process.each do |url| x = get_doc(url) do_something(x) end A: I hope this gives you an idea: def do_something(url, secs) sleep secs #just to see a difference puts "Done with: #{url}" end threads = [] urls_ary = ['url1', 'url2', 'url3'] urls_ary.each_with_index do |url, i| threads << Thread.new{ do_something(url, i+1) } puts "Out of loop #{i+1}" end threads.each{|t| t.join} Perhaps creating a method for Array like: class Array def thread_each(&block) inject([]){|threads,e| threads << Thread.new{yield(e)}}.each{|t| t.join} end end [1, 2, 3].thread_each do |i| sleep 4-i #so first one ends later puts "Done with #{i}" end A: module MultithreadedEach def multithreaded_each each_with_object([]) do |item, threads| threads << Thread.new { yield item } end.each { |thread| thread.join } self end end Usage: arr = [1,2,3] arr.extend(MultithreadedEach) arr.multithreaded_each do |n| puts n # Each block runs in it's own thread end A: A simple method using threads: threads = [] [1, 2, 3].each do |i| threads << Thread.new { puts i } end threads.each(&:join) A: There's also a gem called Parallel which is similar to Peach, but is actively updated. A: There is a gem called peach (https://rubygems.org/gems/peach) which lets you do this: require "peach" array_of_urls_to_process.peach do |url| do_something(get_doc(url)) end
{ "language": "en", "url": "https://stackoverflow.com/questions/7561629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: What's the need of Informal Protocols? I've read the online docs about formal and informal protocols on Apple's documentation site, but I missed the point about informal protocols. I mean, * *a class cannot conform to an informal protocol, it conforms to it by default since informal protocols are almost always categories of the NSObject class. *If you want to implement an informal protocol, you must redeclare the methods you want to implement in your interface file. *Another class cannot check if you conform to the informal protocol (the class must check if it responds to some selectors, but the same can be done without the need of an informal protocol). So, what's the point of having an informal protocol? I can't really understand where they could be useful given the three points above and given that you could do the same things without them. I'm sure I'm missing something, maybe you can help. EDIT: after a while, I still do not see why informal protocols where used, apart from a logical point of view, i.e. group together some methods. Any idea? A: You’ve got the grouping together a set of related methods part right. An informal protocol lists which (optional) methods can be implemented if a class needs to ‘conform’ to that informal protocol. The other reason is the compiler and the target platform ABI. Consider a delegating class whose objects accept a delegate. Internally, methods in the delegating class would do something like: id delegate; … if ([_delegate respondsToSelector:@selector(someMethod:hey:ho:)]) { [_delegate someMethod:42 hey:@"hey" ho:@"ho, let's go"]; } Without an informal protocol, the compiler would emit warnings for the excerpt above because it wouldn’t be aware that someMethod:hey:ho: exists, its return type and its parameter types. More importantly, without knowing the method signature, the compiler would have to guess the return type and the argument types in order to prepare the call site, and this guess could very well be a mismatch. For example, looking at the message being sent in the excerpt above the compiler could guess that the method accepts an integer, an NSString, and another NSString as arguments. But what if the method is originally supposed to accept a floating point number as the first argument? Passing an integer argument (in this case, the argument is stored in a standard register) is different from passing a 64-bit floating point argument (in this case, a SSE register). And what if the method actually supports variable arguments in the last argument instead of a single string? The compiler wouldn’t prepare the call site accordingly, which would lead to crashes. Generating the assembly of the excerpt above helps illustrate this problem: movl $42, %edx leaq L__unnamed_cfstring_(%rip), %rax leaq L__unnamed_cfstring_3(%rip), %rcx movq -16(%rbp), %rdi movq L_OBJC_SELECTOR_REFERENCES_(%rip), %rsi movq %rcx, -24(%rbp) movq %rax, %rcx movq -24(%rbp), %r8 callq _objc_msgSend As you can see, 42 was stored in register EDX. However, if we add an informal protocol stating that the first parameter is of type float: @interface NSObject (DelegateInformalProtocol) - (id)someMethod:(float)number hey:(id)hey ho:(id)ho; @end then the compiler prepares the call site differently: movabsq $42, %rax cvtsi2ssq %rax, %xmm0 leaq L__unnamed_cfstring_(%rip), %rax leaq L__unnamed_cfstring_3(%rip), %rcx movq -16(%rbp), %rdi movq L_OBJC_SELECTOR_REFERENCES_(%rip), %rsi movq %rax, %rdx callq _objc_msgSend As you can see, 42 was stored in register XMM0. And if we change the informal protocol so that the last argument is variadic: @interface NSObject (DelegateInformalProtocol) - (id)someMethod:(int)number hey:(id)hey ho:(id)ho, ...; @end then the compiler prepares the call site in another manner: movl $42, %edx leaq L__unnamed_cfstring_(%rip), %rax leaq L__unnamed_cfstring_3(%rip), %rcx movq -16(%rbp), %rdi movq L_OBJC_SELECTOR_REFERENCES_(%rip), %rsi movq %rcx, -24(%rbp) ## 8-byte Spill movq %rax, %rcx movq -24(%rbp), %r8 ## 8-byte Reload movb $0, %al callq _objc_msgSend Note the movb $0, %al instruction. That’s required by the x86_64 ABI: when calling a variadic function, the caller must store in AL the number of floating-point registers that have been used. In this case, none, hence $0. In summary, informal protocols, besides grouping related methods, help the compiler identify the signature of a method and correctly prepare the call site before sending a message. However, given that Objective-C now supports optional methods in a formal protocol declaration, informal protocols aren’t needed any longer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: OAuth 2.0: Benefits and use cases — why? Could anyone explain what's good about OAuth2 and why we should implement it? I ask because I'm a bit confused about it — here's my current thoughts: OAuth1 (more precisely HMAC) requests seem logical, easy to understand, easy to develop and really, really secure. OAuth2, instead, brings authorization requests, access tokens and refresh tokens, and you have to make 3 requests at the very start of a session to get the data you're after. And even then, one of your requests will eventually end up failing when the token expires. And to get another access token, you use a refresh token that was passed at the same time as the access token. Does that make the access token futile from a security point of view? Plus, as /r/netsec have showed recently, SSL isn't all entirely secure, so the push to get everything onto TLS/SSL instead of a secure HMAC confuses me. OAuth are arguing that it's not about 100% safety, but getting it published and finished. That doesn't exactly sound promising from a provider's point of view. I can see what the draft is trying to achieve when it mentions the 6 different flows, but it's just not fitting together in my head. I think it might be more my struggling to understand it's benefits and reasoning than actually disliking it, so this may be a bit of an unwarranted attack, and sorry if this could seem like a rant. A: First, as clearly indicated in OAuth authentication OAuth 2.0 is not an authentication protocol. Authentication in the context of a user accessing an application tells an application who the current user is and whether or not they're present. A full authentication protocol will probably also tell you a number of attributes about this user, such as a unique identifier, an email address, and what to call them when the application says "Good Morning". However, OAuth tells the application none of that. OAuth says absolutely nothing about the user, nor does it say how the user proved their presence or even if they're still there. As far as an OAuth client is concerned, it asked for a token, got a token, and eventually used that token to access some API. It doesn't know anything about who authorized the application or if there was even a user there at all. There is a standard for user authentication using OAuth: OpenID Connect, compatible with OAuth2. The OpenID Connect ID Token is a signed JSON Web Token (JWT) that is given to the client application along side the regular OAuth access token. The ID Token contains a set of claims about the authentication session, including an identifier for the user (sub), the identifier for the identity provider who issued the token (iss), and the identifier of the client for which this token was created (aud). In Go, you can look at coreos/dex, an OpenID Connect Identity (OIDC) and OAuth 2.0 Provider with Pluggable Connector. Answer from this post vonc A: I would answer this question slightly differently, and I will be very precise and brief, mainly because @Peter T answered it all. The main gain that I see from this standard is to respect two principles: * *Separation of concerns. *Decoupling authentication from the web application, which usually serves business. By doing so, * *You can implement an alternative to Single SignOn: If you have multiple applications that trust one STS. What I mean, one username for all applications. *You can enable your web application (The client) to access resources that belong to the user and do not belong to the web application (The client). *You can mandate the authentication process to a third party that you trust , and never worry about user authenticity validation. A: Background: I've written client and server stacks for OAuth 1.0a and 2.0. Both OAuth 1.0a & 2.0 support two-legged authentication, where a server is assured of a user's identity, and three-legged authentication, where a server is assured by a content provider of the user's identity. Three-legged authentication is where authorization requests and access tokens come into play, and it's important to note that OAuth 1 has those, too. The complex one: three-legged authentication A main point of the OAuth specs is for a content provider (e.g. Facebook, Twitter, etc.) to assure a server (e.g. a Web app that wishes to talk to the content provider on behalf of the client) that the client has some identity. What three-legged authentication offers is the ability to do that without the client or server ever needing to know the details of that identity (e.g. username and password). Without (?) getting too deep into the details of OAuth: * *The client submits an authorization request to the server, which validates that the client is a legitimate client of its service. *The server redirects the client to the content provider to request access to its resources. *The content provider validates the user's identity, and often requests their permission to access the resources. *The content provider redirects the client back to the server, notifying it of success or failure. This request includes an authorization code on success. *The server makes an out-of-band request to the content provider and exchanges the authorization code for an access token. The server can now make requests to the content provider on behalf of the user by passing the access token. Each exchange (client->server, server->content provider) includes validation of a shared secret, but since OAuth 1 can run over an unencrypted connection, each validation cannot pass the secret over the wire. That's done, as you've noted, with HMAC. The client uses the secret it shares with the server to sign the arguments for its authorization request. The server takes the arguments, signs them itself with the client's key, and is able to see whether it's a legitimate client (in step 1 above). This signature requires both the client and the server to agree on the order of the arguments (so they're signing exactly the same string), and one of the main complaints about OAuth 1 is that it requires both the server and clients to sort and sign identically. This is fiddly code and either it's right or you get 401 Unauthorized with little help. This increases the barrier to writing a client. By requiring the authorization request to run over SSL, OAuth 2.0 removes the need for argument sorting and signing altogether. The client passes its secret to the server, which validates it directly. The same requirements are present in the server->content provider connection, and since that's SSL that removes one barrier to writing a server that accesses OAuth services. That makes things a lot easier in steps 1, 2, and 5 above. So at this point our server has a permanent access token which is a username/password equivalent for the user. It can make requests to the content provider on behalf of the user by passing that access token as part of the request (as a query argument, HTTP header, or POST form data). If the content service is accessed only over SSL, we're done. If it's available via plain HTTP, we'd like to protect that permanent access token in some way. Anyone sniffing the connection would be able to get access to the user's content forever. The way that's solved in OAuth 2 is with a refresh token. The refresh token becomes the permanent password equivalent, and it's only ever transmitted over SSL. When the server needs access to the content service, it exchanges the refresh token for a short-lived access token. That way all sniffable HTTP accesses are made with a token that will expire. Google is using a 5 minute expiration on their OAuth 2 APIs. So aside from the refresh tokens, OAuth 2 simplifies all the communications between the client, server, and content provider. And the refresh tokens only exist to provide security when content is being accessed unencrypted. Two-legged authentication Sometimes, though, a server just needs to control access to its own content. Two-legged authentication allows the client to authenticate the user directly with the server. OAuth 2 standardizes some extensions to OAuth 1 that were in wide use. The one I know best was introduced by Twitter as xAuth. You can see it in OAuth 2 as Resource Owner Password Credentials. Essentially, if you can trust the client with the user's credentials (username and password), they can exchange those directly with the content provider for an access token. This makes OAuth much more useful on mobile apps--with three-legged authentication, you have to embed an HTTP view in order to handle the authorization process with the content server. With OAuth 1, this was not part of the official standard, and required the same signing procedure as all the other requests. I just implemented the server side of OAuth 2 with Resource Owner Password Credentials, and from a client's perspective, getting the access token has become simple: request an access token from the server, passing the client id/secret as an HTTP Authorization header and the user's login/password as form data. Advantage: Simplicity So from an implementor's perspective, the main advantages I see in OAuth 2 are in reduced complexity. It doesn't require the request signing procedure, which is not exactly difficult but is certainly fiddly. It greatly reduces the work required to act as a client of a service, which is where (in the modern, mobile world) you most want to minimize pain. The reduced complexity on the server->content provider end makes it more scalable in the datacenter. And it codifies into the standard some extensions to OAuth 1.0a (like xAuth) that are now in wide use.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "291" }
Q: Dynamic library problems with Python and libstdc++ Executive summary: a Python module is linked against a different version of libstdc++.dylib than the Python executable. The result is that calls to iostream from the module crash. Backstory I'm creating a Python module using SWIG on an older computer (running 10.5.8). For various reasons, I am using GCC 4.5 (installed via MacPorts) to do this, using Python 2.7 (installed via MacPorts, compiled using the system-default GCC 4.0.1). Observed Behavior To make a long story short: calling str( myObject ) in Python causes the C++ code in turn to call std::operator<< <std::char_traits<char> >. This generates the following error: Python(487) malloc: *** error for object 0x69548c: Non-aligned pointer being freed *** set a breakpoint in malloc_error_break to debug Setting a breakpoint and calling backtrace when it fails gives: #0 0x9734de68 in malloc_error_break () #1 0x97348ad0 in szone_error () #2 0x97e6fdfc in std::string::_Rep::_M_destroy () #3 0x97e71388 in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string () #4 0x97e6b748 in std::basic_stringbuf<char, std::char_traits<char>, std::allocator<char> >::overflow () #5 0x97e6e7a0 in std::basic_streambuf<char, std::char_traits<char> >::xsputn () #6 0x00641638 in std::__ostream_insert<char, std::char_traits<char> > () #7 0x006418d0 in std::operator<< <std::char_traits<char> > () #8 0x01083058 in meshLib::operator<< <tranSupport::Dimension<(unsigned short)1> > (os=@0xbfffc628, c=@0x5a3c50) at /Users/sethrj/_code/pytrt/meshlib/oned/Cell.cpp:21 #9 0x01008b14 in meshLib_Cell_Sl_tranSupport_Dimension_Sl_1u_Sg__Sg____str__ (self=0x5a3c50) at /Users/sethrj/_code/_build/pytrt-gcc45DEBUG/meshlib/swig/mesh_onedPYTHON_wrap.cxx:4439 #10 0x0101d150 in _wrap_Cell_T___str__ (args=0x17eb470) at /Users/sethrj/_code/_build/pytrt-gcc45DEBUG/meshlib/swig/mesh_onedPYTHON_wrap.cxx:8341 #11 0x002f2350 in PyEval_EvalFrameEx () #12 0x002f4bb4 in PyEval_EvalCodeEx () [snip] Suspected issue I believe the issue to be that my code links against a new version of libstdc++: /opt/local/lib/gcc45/libstdc++.6.dylib (compatibility version 7.0.0, current version 7.14.0) whereas the Python binary has a very indirect dependence on the system libstdc++, which loads first (output from info shared in gdb): 1 dyld - 0x8fe00000 dyld Y Y /usr/lib/dyld at 0x8fe00000 (offset 0x0) with prefix "__dyld_" 2 Python - 0x1000 exec Y Y /opt/local/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python (offset 0x0) (objfile is) /opt/local/bin/python 3 Python F 0x219000 dyld Y Y /opt/local/Library/Frameworks/Python.framework/Versions/2.7/Python at 0x219000 (offset 0x219000) 4 libSystem.B.dylib - 0x9723d000 dyld Y Y /usr/lib/libSystem.B.dylib at 0x9723d000 (offset -0x68dc3000) (commpage objfile is) /usr/lib/libSystem.B.dylib[LC_SEGMENT.__DATA.__commpage] 5 CoreFoundation F 0x970b3000 dyld Y Y /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation at 0x970b3000 (offset -0x68f4d000) 6 libgcc_s.1.dylib - 0x923e6000 dyld Y Y /usr/lib/libgcc_s.1.dylib at 0x923e6000 (offset -0x6dc1a000) 7 libmathCommon.A.dylib - 0x94af5000 dyld Y Y /usr/lib/system/libmathCommon.A.dylib at 0x94af5000 (offset -0x6b50b000) 8 libicucore.A.dylib - 0x97cf4000 dyld Y Y /usr/lib/libicucore.A.dylib at 0x97cf4000 (offset -0x6830c000) 9 libobjc.A.dylib - 0x926f0000 dyld Y Y /usr/lib/libobjc.A.dylib at 0x926f0000 (offset -0x6d910000) (commpage objfile is) /usr/lib/libobjc.A.dylib[LC_SEGMENT.__DATA.__commpage] 10 libauto.dylib - 0x95eac000 dyld Y Y /usr/lib/libauto.dylib at 0x95eac000 (offset -0x6a154000) 11 libstdc++.6.0.4.dylib - 0x97e3d000 dyld Y Y /usr/lib/libstdc++.6.0.4.dylib at 0x97e3d000 (offset -0x681c3000) 12 _mesh_oned.so - 0x1000000 dyld Y Y /Users/sethrj/_code/_build/pytrt-gcc45DEBUG/meshlib/swig/_mesh_oned.so at 0x1000000 (offset 0x1000000) 13 libhdf5.7.dylib - 0x122c000 dyld Y Y /opt/local/lib/libhdf5.7.dylib at 0x122c000 (offset 0x122c000) 14 libz.1.2.5.dylib - 0x133000 dyld Y Y /opt/local/lib/libz.1.2.5.dylib at 0x133000 (offset 0x133000) 15 libstdc++.6.dylib - 0x600000 dyld Y Y /opt/local/lib/gcc45/libstdc++.6.dylib at 0x600000 (offset 0x600000) [snip] Note that the malloc error occurs in the memory address for the system libstdc++, not the one the shared library is linked against. Attempted resolutions I tried to force MacPorts to build Python using GCC 4.5 rather than the Apple compiler, but the install phase fails because it needs to create a Mac "Framework", which vanilla GCC apparently doesn't do. Even with the -static-libstdc++ compiler flag, __ostream_insert calls the std::basic_streambuf from the system-loaded shared library. I tried modifying DYLD_LIBRARY_PATH by prepending /opt/local/lib/gcc45/ but without avail. What can I do to get this to work? I'm at my wit's end. More information This problem seems to be common to mac os x. Notice how in all of the debug outputs show, the address jumps between the calls to std::__ostream_insert and std::basic_streambuf::xsputn: it's leaving the new GCC 4.5 code and jumping into the older shared library code in /usr/bin. Now, to find a workaround... A: Solved it. I discovered that this problem is not too uncommon when mixing GCC versions on the mac. After reading this solution for mpich and checking the mpich source code, I found that the solution is to add the following flag to gcc on mac systems: -flat_namespace I am so happy. I wish this hadn't taken me a week to figure out. :) A: Run Python in GDB, set a breakpoint on malloc_error_break. That will show you what's being freed that's not allocated. I doubt that this is an error between ABIs between the versions of libstdc++.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Minimize database interactions with caching I was looking at this: http://dev.mysql.com/doc/refman/5.1/en/query-cache.html It's an amazing way of caching stuff, but it happens on the database side, it would be great if there was some kind of code for PHP that would do the same for you. I mean you would send your queries to that intermediary layer, it would look at your queries, decides if it needs to connect to the db again or not. Has anyone made anything like that for PHP? Do you think it's a good idea? A: For any caching it is important that the actual caching and invalidation are done by the same application (e.g. the sql-server). While it probably isn't difficult to write some client-side query-cache this does absolutely make no sense in most cases as the client-cache would not be notified (by the sql-server) when the cached data becomes outdated. But actually the query-cache is that layer you suggest. As mysql's query-cache doesn't know anything about your application-logic, it has to invalidate the cache by other criteria (e.g. the table changed). This can result in poor performance if used as the only cache (especially on fast-changing tables). Therefore you should use some sophisticated caching engine on your client with respect to your application logik. A: I wrote a blog post that goes into a lot of details on this topic at http://www.joeyrivera.com/2009/caching-using-phpzend_cache-and-mysql/. It talks about why you should cache and how to implement caching with zend cache. Communicating with the db is usually slow so you should always cache when possible. Caching to ram will net you greater performance results as ram is faster than the file system using something like memcache but if you don't have that available then just use file system caching instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Object (KeyEvent key) to String (Java) I have something similar to the following: An object with the value of KeyEvent.VK_G. How can I get the key letter from that object (as a String)? A: By using KeyEvent.getKeyChar() (see http://download.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html#getKeyChar()). A: Is this what you want to do? int someKeyCode = KeyEvent.VK_G; Object someKeyCodeObject = new Integer(someKeyCode); String keyString = KeyEvent.getKeyText((Integer)someKeyCodeObject); Which would give "G" in this case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Multiple Choice on iOS I'm taking the plunge into my first iOS app (for fun), and have decided to make myself a flash-cards type app to study with. Basically, show a picture and under it have a few selections to choose from, with one being the right answer. This is the basic functionality that I would like to have. I've been through the iOS videos and a few open courseware courses and I'm ready to start but I'm absolutely drawing a blank as to where to begin.. Anyone have an idea for such a beginner as me? :) A: A very vague question. But then a simple start to solving this would be to use a UIImageView for the picture and a UITableView/UIPickerView below for the options. Read up more on the mechanisms of the tableview/pickerview delegate methods. Read those class references on Apple's documention: UITableView here and UIPickerView here. Also read up on data structures like NSArray and NSMutableArray to understand how to use them when you deal with populating data into your table or picker and manipulate it. A: I would use a UIImageView as the picture and use either a UITableView, UIPickerView, or UIButtons for the answer choices. Then, just have your answer choices randomly gather answers from a SQLite database, otherwise your users could memorize the quiz! A: The way I would do this, is create a plist with an array of dictionaries. For each dictionary, have 4 keys: 1- Question (String) -> The question itself 2- Array (of NSStrings) - > list of options 3- Index (Number) of correct option 4- Image (String) -> Image name So once you have bunch of these, create a UIViewController, put a UIImageView in it, a UILabel, and a UITableView. Then do this repeatedly for each question you want to display: Hook up UIImageView with UIImage (you can get the name of that image from the dictionary).Then, hook up the label with name of the question, and popualte the tableview with options. Then listen for UITableViewDidSelect call back, check if the answer is correct or not, and then reset the entire view controller with the next question. Btw, you will need an array with keeps track of what choice the user made so at the end of the quiz you can come back and refer to it. Hope that helps, it may sound complicated but it's pretty straightforward once you get your head around it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make custom dictionary for Hunspell I have a question about building a custom dictionary for hunspell. I'm using a general English dictionary and affix file right now. How can I add user-specified words to that dictionary for each of my users? A: I'm trying to do the same but haven't found enough information to begin yet. However, you may want to look at hunspell - format of Hunspell dictionaries and affix files . UPDATE If you are working with .NET, you can download Hunspell .NET port. Using it is fairly easy too. var bee = new Hunspell(); bee.Load("path_to_en_US.aff"); bee.Load("path_to_en_US.dic"); bee.Add("my_custom_word1"); bee.Add("my_custom_word2"); var suggestions = bee.Suggest("misspel_word"); A: The secret to getting hunspell to work (at least for me) was to figure out the locations it would search that were owned by me, and put the custom dictionaries there. Also bear in mind that the dictionaries are in a specific format, so you need to obey those rules. Running hunspell -D will show you the search path. On MacOS, mine includes /Users/scott/Library/Spelling so I created that directory and put mine there. Let's say you want to call your dictionary mydict and your input datafile of words is called dict.txt. We'll use the path I just showed. First, copy the default .aff file. You will see it when you run hunspell -D as described above. For me, it's in /Library/Spelling/en_US/. So cp /Library/Spelling/en_US.aff /Users/scott/Library/Spelling/mydict.aff Then, every time you update your input list (dict.txt), do this: DICT=/Users/scott/Library/Spelling/mydict.dic cd ~/doc/dict cat dict.txt | sort | uniq > dict.in wc -l dict.in > $DICT cat dict.in >> $DICT rm dict.in To run hunspell, just specify both dictionaries. So for me, because I want a list of misspellings, I use hunspell -l -d scott,en_US <filename> A: create your own word-list and affix file for your language, if that doesn't exist. Well, for papiamentu - Curaçao's native language - such dictionary doesn't exist. But I had a hard time finding out how to create such files, so I am documenting it here: http://www.suares.com/index.php?page_id=25&news_id=233 A: I am implementing this type of feature as well. Once you've created the Hunspell object with an associated dictionary you can add individual words to it. Keep in mind though that these words will only be available for as long as the Hunspell object is alive. Every time you access a new object you will have to add all the user defined words again. A: Have a look at the documentation in openoffice http://www.openoffice.org/lingucomponent/ specially this document http://www.openoffice.org/lingucomponent/dictionary.html It's a good starting point
{ "language": "en", "url": "https://stackoverflow.com/questions/7561648", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: Python how to join list of lists using join function I am new to Python. Have a question regarding join function. masterlist = [ ('ap172', ['33', '212-583-1173', '19 Boxer Rd.', 'New York', 'NY', '10005']), ('axe99', ['42', '212-582-5959', '315 W. 115th Street, Apt. 11B', 'New York', 'NY', '10027']) ] I want to print each element of list delimited by pipe. If I try: for i in masterlist: mystring = '|'.join(i) print mystring The error is: TypeError: sequence item 1: expected string, list found So I am trying: for i in masterlist: mystring = i[0] mystring += '|'.join(i[1]) print mystring and I get: ap17233|212-583-1173|19 Boxer Rd.|New York|NY|10005 axe9942|212-582-5959|315 W. 115th Street, Apt. 11B|New York|NY|10027 So it works but would like to know if there is a better way to join the above masterlist using join function? A: I think splitting up the tuples in the for loop would be cleaner. for identifier, data in masterlist: print "%s%s" %(identifier, '|'.join(data)) A: from itertools import chain for symbol, items in masterlist: print "|".join(chain( [symbol], items)) A: To get what you got you can try for i in masterlist: print i[0] + '|'.join(i[1]) To get what I think your after you can try this for i in masterlist: print i[0] + '|' + '|'.join(i[1]) There are many many ways to do this, these are just 2. A: for i in masterlist: print '|'.join([i[0]] + i[1])
{ "language": "en", "url": "https://stackoverflow.com/questions/7561650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: For a Grails app to scale well, do you need to use EJBs? I've been working on a project in Grails and wondering if Enterprise Java Beans would be needed for it to scale on a Tomcat Cloud Server. I'm using basic GORM for persistence, and a mysql backend. A: No, EJBs are not needed to scale.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Linkedin Api The remote server returned an error: (401) Unauthorized I am working on the Linkedin Api. In my OAuthLinkedin.cs, I have the following: public string WebResponseGet(HttpWebRequest webRequest) { StreamReader responseReader = null; string responseData = ""; try { responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()); responseData = responseReader.ReadToEnd(); } catch { throw; } finally { webRequest.GetResponse().GetResponseStream().Close(); responseReader.Close(); responseReader = null; } return responseData ; } My code is able to get a oauthToken, oauthTokenSecret WebResponseGet(HttpWebRequest webRequest) is where it fails. Status: System.Net.WebExceptionStatus.Protocol error The remote server returned an error: (401) Unauthorized. It is able to get a token secret after requesting permission to access linkedin. but I am not sure abt this unauthorized error. is it some permission issue. where do I check this Thanks Sun A: Here are a couple of things that you can try to identify the source of your problem: * *Use this OAuth test console and compare the header that you're generating to the one that this tool generates: https://developer.linkedin.com/oauth-test-console If your header is wrong, then LinkedIn will return a 401 status *If you're posting XML to LinkedIn in your request, then make sure the content type (webRequest.ContentType) is "application/xml" and not "application/x-www-form-urlencoded", otherwise, LinkedIn will return a 401 status. A: It was happening with me too but i figured it out what i was doing it wrong. Whenever you create Signature, make Token and TokenSecret empty. it worked for me because it was getting old token and token secret from browser request. //Generate Signature string sig = this.GenerateSignature(uri, this.ConsumerKey, this.ConsumerSecret, this.Token, this.TokenSecret, method.ToString(), timeStamp, nonce, out outUrl, out querystring);
{ "language": "en", "url": "https://stackoverflow.com/questions/7561654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: minimal checks to find repeats in a list Given a sequence (d1, d2, ..., dn), I want to evaluate the product (1 - Dij) for all i != j where Dij = 1 if di = dj and 0 otherwise. The code I have only checks Dij when i prod = 1; for (int i=1; i<n; ++i) { for (int j=i; j<=n; ++j) { prod *= (1 - Dij); } } I know I can stop when I get Dij=1, but what I'm trying to do is get a minimal expression of the Dij's to check. This way I have one expression and then I can use difference sequences and evaluate it. So I know that I can do i<j instead of i != j. So I want to expand out this product and get something like this for n=3: (1 - D12) (1 - D13) (1 - D23) = 1 - D12 - D13 - D23 + D12*D13 + D12*D23 + D13*D23 - D12*D13*D23 But there is more that I can do. This expression is actually always equal to 1 - D12 - D13 - D23 + 3 * D12*D13 - D12*D13*D23 My questions are: * *Why is D12 * D13 = D12 * D23? This is always true (meaning it doesn't matter what the d sequence is) but I don't really get why because it seems to me that this means D13 = D23 which isn't always true (it depends on the d sequence). This is the relation that helps make the expression smaller. *How can I find all the relations like this and get a minimal expression? Is the expression above minimal? I don't even know. A: You are trying to determine if D contains any duplicates or not. Ultimately, that requires you to compare every entry with each other, which is simply enumerating all unique combinations of two elements. That ends up being N*(N-1)/2. You can do a little better by sorting D first and then searching for duplicate adjacent pairs (O(N*log(N)), or, assuming you are sticking to a bounded range of integers, you can reduce it to linear time with a bit vector, or if you are feeling adventurous, a radix sort. A: I can answer 1 for you. Consider these two cases: Case 1: D13 = D23 Here you can just multiply by D12 on both sides to get D12 * D13 = D12 * D23. Case 2: D13 != D23 This means that either d1 = d3 XOR d2 = d3 but not both. Therefore we know that d1 != d2. This implies that D12 = 0. Therefore D12 * D13 = 0 * D13 = 0 = 0 * D23 = D12 * D23 The problem with your logic when you think this implies D13 = D23 is that you cannot divide by 0, and D12 might be 0 (as always happens in the second case). Your second question is interesting, and I do not know the answer off the top of my head, but here are some observations that may be helpful. Draw the numbers 1, 2, ..., n in a row: 1 2 3 ... n Given an expression D_(i1,j1) * D_(i2,j2) * ... * D_(ik,jk), make an arc from i1 to j1 and i2 to j2 and so on. This turns that row into a graph (vertices are numbers, edges are these arcs). Each connected component of that graph represents a subset of the number 1, 2, ..., n, and taken as a whole this gives us a set partition of {1, 2, ..., n}. Fact: Any two terms that have the same corresponding set partition are equal. Example: D12 * D23 = D12 * D13 --------- | | 1 -- 2 -- 3 = 1 -- 2 3 Sometimes this fact will mean the degree is the same, as in the case above, and sometimes the degree will decrease as in D12 * D13 * D23 --------- | | 1 -- 2 -- 3 The upshot is that now you can express the product (1 - Dij) as a sum over set partitions: \prod_{i<j} ( 1 - Dij ) = \sum_{P set partition of \{1,2,...,n\}} c_P * m_P where the monomial term is given by mP = mP1 * mP2 * ... * mPk when P = P1 union P2 union ... union Pk and if Pi = { a < b < c < ... < z } then m_Pi = Dab * Dac * ... * Daz Finally, the coefficient term is just c_P = \prod (#P1)! (#P2)! ... (#Pn)! Having worked this out, I'm now certain this belongs on http://math.stackexchange.com rather than here. A: I haven't followed the math, but isn't this something you would code using a hashtable, or possibly even a sparse bit-array if you know the size of the di are bounded? Just iterate over the list, filling in your data structure with a "1" at the position corresponding to the value of di - if it's already 1, return 0. If you complete (in n steps), return 1. It should be O(n).
{ "language": "en", "url": "https://stackoverflow.com/questions/7561655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why escaping 'w' ('\w') character reverses memory representation of a int variable? Consider the following code sample: int i1 = 'w\"'; int i2 = '\w\"'; int i3 = 'w"'; int i4 = 'w\"'; Note: MSVS SP1 2005 C++ compiler, just default debug compilation/linkage settings. x86 machine. The compiler outputs warning C4129: 'w' : unrecognized character escape sequence and everything else is just fine. The raw memory representation of the given variables are as follows: i1 -> 22 77 00 00 i2 -> 77 22 00 00 i3 -> 22 77 00 00 i4 -> 22 77 00 00 Why i2 has reverse order? Whats going on?? A: It's a bug in the compiler. I suggest you file a bug on Microsoft Connect (though I wouldn't bet on them fixing it any time soon). It also occurs with real escape sequences such as \n or \x6e, so it has nothing to do with the invalid escape sequence \w. In VS 2008 and VS 2010, the output of this program: #include <stdio.h> int main(void) { int x[] = {'abn"', 'abn\"', 'ab\x6e"', 'ab\x6e\"'}; for (int i = 0; i < sizeof(x)/sizeof(x[0]); i++) printf("%08x\n", x[i]); return 0; } is this: 61626e22 61626e22 61626e22 2261626e This shows that for some strange reason, the compiler moves the quotation mark (the 22) to the beginning of the multicharacter character constant, but only when it's escaped and when the constant has another escaped character in it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to change the page/plot two figures I am developing a tool that should produce 3 plots. Two of those are related and therefor I have created them using the the pyplot.subplot. The third one needs more space, and I would like to create it on a single chart. It is clear to me, that I could plot two figures. But I would like to know how to get them showed in this same window, So that they can be accessed with these arrows. A: You can control the positions and dimensions with subplots_adjust : http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.subplots_adjust
{ "language": "en", "url": "https://stackoverflow.com/questions/7561658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP captcha Image I am using a captcha image verifier in my PHP form. The form uses a cookie to check the verfication code entered by the user. Is there anyother way to do this other than using a cookie? A: Cookies are a very bad idea in this case. Instead, you should use a variable set in the $_SESSION PHP superglobal. At the top of your captcha-input page, add this (minimal version): session_start(); $_SESSION['captchaCode'] = /* whatever */ session_start() documentation can be found here. Then, when the form is submitted, check that the value submitted from the form is the same as the one in $_SESSION['captchaCode']: session_start(); if($_SESSION['captchaCode'] == $_POST['captchaCode']) { // Do interesting things } Do bear in mind that this is a very simple, generic way of doing it. If you're using reCAPTCHA or Securimg then they will have their own ways of validating the captchas they generate. A: I don't use cookies, you can just see if what they enter matches directly with what you have in the database of captcha entries; that is if you have a database of possible captchas? A: Here is a script that is very easy to use and setup. This script just creates the image but it is not tough to incorporate the verification. You can download the script here to verify the captach image use either php or javascript to make sure the post value is equal to $_SESSION['security_number'] and your done.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Linq query to linq extension methods How to write this linq query using extension methods? var products = from p in db.Products join ps in (from pss in db.ProductSpecs where pss.spec_name== "Price" select pss ) on p.id equals ps.product_id into temp from t in temp.DefaultIfEmpty() orderby t.spec_value select p; Thanks for help! A: Get yourself a copy of LinqPad, paste the query into it, execute it and then click on the Lambda tab. It will show you the Method syntax.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Appending to the end of a file in a concurrent environment What steps need to be taken to ensure that "full" lines are always correctly appended to the end of a file if multiple of the following (example) program are running concurrently. #!/usr/bin/env python import random passwd_text=open("passwd.txt","a+") u=("jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/sh", "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/sh", "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/sh") for i in range(random.randint(1,2)): print >> passwd_text, random.choice(u) passwd_text.close() And: Can an "all or nothing" append be guaranteed (on linux/unix) even if the the disk becomes full, or "ulimit -f" has been set? (Note similar question: How do you append to a file?) A: You have to lock the file in order to ensure that nobody else is writing to it at the same time. See File Locking and lockfile or posixfile for more details. UPDATE: And you cannot write more data into the file if the disk is full. I am not sure about Python's implementation of output re-direction, but write system call can write less bytes than requested. A: I think the discussion of this "bug" in python's normal open function suggests that you don't get the POSIX atomic guarantee, but you do if you use with io.open('myfile', 'a') as f: f.write('stuff') http://docs.python.org/2/library/io.html#io.open if the operating system implements its write sys call correctly... http://bugs.python.org/issue15723
{ "language": "en", "url": "https://stackoverflow.com/questions/7561663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Haskell beginner question (defining pairs, similar to Http statuses) I'm a Haskell beginner and have to define a series of known statuses that consist of an Int and a String / ByteString, similar to HTTP Statuses I will never have to get a status code from a status message. However I will have to get a status message for a given status code. I've had a look at Network.HTTP.Types and they define distinct 'variables', "status200", "status201", etc. for every possible status code (similar to "FoodTwo.hs" below). What are the (performance?) implications if I just defined a function that returns status messages for status codes, as shown in "FoodOne.hs" below? On top of that, in languages like C# or Java one would probably declare a static dictionary, similar to FoodThree.hs - I somehow doubt this is the Haskell way? Why? -- FoodOne.hs statusMessage :: Int -> String statusMessage 30 = "BBQ ready" statusMessage 40 = "Beverages served" statusMessage rest = "Unknown Food Status" -- FoodTwo.hs data FoodStatus = FoodStatus { fstatusCode :: Int, fstatusMessage :: String } status30 = FoodStatus 30 "BBQ ready" status40 = FoodStatus 40 "Beverages served" -- FoodThree.hs statusMessages = [(30,"BBQ ready"),(40,"Beverages served")] A: -- FoodOne.hs statusMessage :: Int -> String statusMessage 30 = "BBQ ready" statusMessage 40 = "Beverages served" statusMessage rest = "Unknown Food Status" Most compilers are will compile this to a linear search, so it will have linear runtime cost. -- FoodTwo.hs data FoodStatus = FoodStatus { fstatusCode :: Int, fstatusMessage :: String } status30 = FoodStatus 30 "BBQ ready" status40 = FoodStatus 40 "Beverages served" This approach is not comparable to the others: it doesn't provide status lookup given a (dynamically-known) Int. However, for statically-known Ints, it is the fastest: the lookup is done once at compile-time and therefore has constant runtime cost, regardless of how many different constants there are. -- FoodThree.hs statusMessages = [(30,"BBQ ready"),(40,"Beverages served")] Doing naive lookup in this list (e.g. by the built-in lookup function) will involve linear search, and therefore have linear runtime cost. -- FoodFour.hs import Data.Map as M statusMessages = fromList [(30, "BBQ ready"),(40,"Beverages served")] message n = fromMaybe "Unknown Food Status" (M.lookup n statusMessages) The Data.Map module implements balanced search trees, and each lookup takes logarithmic time in the number of different statuses. You might also consider Data.IntMap, which also takes logarithmic time, but has better constants. -- FoodFive.hs import Data.Array as A (statusLo, statusHi) = (30, 40) statusMessages = listArray (statusLo, statusHi) [ Just "BBQ ready" , Nothing , Nothing , {- ... -} , Just "Beverages served" ] message' n = guard (statusLo <= n && n <= statusHi) >> statusMessages ! n message = fromMaybe "Unknown Food Status" . message' The Data.Array module implements immutable arrays, and each lookup takes constant time. If your array is sparse, however, this may have higher memory costs than the alternatives. These are all the Haskell way. Choose the one with the right tradeoffs between developer annoyance, speed, and memory consumption for you, just as you would in any other language. A: -- FoodThree.hs statusMessages = [(30,"BBQ ready"),(40,"Beverages served")] This can easily be used in Haskell: fromCode n = fromMaybe "No such error" $ find ((==) n . fst) statusMessages Or you can use Data.Map: import qualified Data.Map as Map import Data.Maybe (fromMaybe) codemap = Map.fromList statusMessages fromCode n = fromMaybe "No such error" $ Map.lookup n codemap A: Would something like the following serve? data FoodStatus = BBQ_READY | BEVERAGES_SERVED | ... instance Show FoodStatus where ... toCode status = ... fromCode num = ... This is pretty much FoodOne.hs but more abstract and thus more manipulable. You are free to implement fromCode however you wish, optimizing for performance as needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Jquery - Add img title to thumbnails I'm having problems grabbing the title tag from an image in a slider and inserting it somewhere else on my page. It's only grabbing the first title from the first image and not the subsequent ones. My script: var imgTitle = $('.nivoSlider img').attr('title') $('a.nivo-control').append('<p>' + (imgTitle) + '</p>'); I know I have to use .each someplace but I don't know where. Thanks A: Use .map() to get an array of titles. Then use the index parameter in your call to .each() to get the corresponding title: var titles = $('.nivoSlider img').map(function() { return this.title; }).get(); $('a.nivo-control').each(function(i) { $(this).append("<p>" + titles[i] + "</p>"); }); A: Try this for example: $('.nivoSlider img').each( function() { alert($(this).attr('title')); }); I think you will get all the images title attributes
{ "language": "en", "url": "https://stackoverflow.com/questions/7561673", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unmount a network volume? How do I unmount a network volume? NSWorkspace thinks they're neither removable nor unmountable. unmountAndEjectDeviceAtPath: @"/Volumes/the network volume in question" causes nothing whatsoever to happen. There's probably some easy way to do this, sitting right under my nose, but I can't find it. I don't want to resort to making an Applescript telling the Finder to Eject network volumes and calling it from Cocoa because that's just incredibly icky. (my dev platform is Tiger, by the way) A: Is calling unmount(2) fair-game? (How odd, most Unix systems name the system call umount(), not unmount(), and the manpage frequently calls it umount() despite the name and Synopsis sections fairly clearly using unmount().) Is the mount in use by anything else? Check lsof(1) or fuser(1) output to see which processes, if any, have that filesystem currently open. (Maybe adding a simple chdir("/"); just before your unmount call would do it?) A: You can also use diskutil which handles more situations than unmount(): std::string command = std::string("diskutil unmount \"") + currentMountPoint + "\""; int ret = system( command.c_str() ); Note the double quotes around the mount point, most likely something like /Volumes/Untitled, but also something like /Volumes/NO NAME
{ "language": "en", "url": "https://stackoverflow.com/questions/7561679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Setting the href attribute replaces the text of the link EDIT: I am not talking about the status bar display, I'm talking about the text you click on to follow the link. /EDIT I looked through a few similar posts and didn't find an answer. I have a link that I want displayed. www.mylink.com I want the href of the link to change every time the link is clicked. href="www.mylink.com?R=340978" The query string changes to a random number after each click to prevent the browser from caching the page. It's expected that the page will be changing frequently and be viewed frequently to assess those changes. So I want people to see "www.mylink.com" but the link to lead to "www.mylink.com?R=34532" I thought I would achieve this with an onclick event that would apend a new random number and set the href attribute to the new link, however this is also changing the text that is displayed. <script type="text/javascript"> var baseLink = "http://myDevLink/library/ea26098f-89d1-4305-9f75-afc7937f8336/25/test/036b602b-0bde-e011-957b-1cc1dee8bacd.html"; var link = ""; // Prime the link $(document).ready(function() { NewRandomParam(); }); function NewRandomParam() { // Make sure one of the warning messages isn't displayed instead of the link if (document.getElementById("link") != null) { // Add a random number param to the query string to prevent the user from opening a cached version of the page link = baseLink + "?R=" + Math.floor(Math.random() * 1000000); document.getElementById("link").setAttribute("href", link); } } </script> <body> <div id="divContent" style="display:inline; border:0px" class="tab"> <pre style="margin-top: 0;" > <font face="tahoma"> <a href="" id="link" onclick=NewRandomParam(); target="_blank">http://myDevLink/library/ea26098f-89d1-4305-9f75-afc7937f8336/25/test/036b602b-0bde-e011-957b-1cc1dee8bacd.html</a> </font> </pre> </div> </body> </html> As you can see from the above code, there is no query string on what should be displayed however when I view the page the value of the href is displayed with the query string. If I do a view source the correct url is there and should be displayed but it isn't. Please enlighten me on where I'm being dumb. A: The solution was a combination of things suggested here plus having to reset the links text to what I wanted it. Here is what worked. <script type="text/javascript"> var baseLink = "<%= this.link %>"; var link = ""; $(document).ready(function () { // Add a timestamp param to the query string to prevent the user from opening a cached version of the page $('#link').mouseenter(function () { var date = new Date(); link = baseLink + "?Timestamp=" + date.getTime(); $("#link").attr("href", link); $("#link").text(baseLink); }); }); </script> Thanks to all of you. A: Random numbers aren't a good idea here. There's always the chance of getting a duplicated number. Just use date.getTime() which should be "random" enough for your purposes. Changing the href should NOT be changing the text in the link. They're sometimes the same text, but that's by putting the same information in two places (inside the href attribute) and as text inside the <a>linkname</a> tag itself. Changing one should never affect the other, unless you've got some other code that keeps things synced. If you mean you want the change what's displayed in the window status bar when the link's hovered, good luck. most browsers have mechanisms to prevent such fiddling in the first place, as changing the status bar text was heavily abused by spammers and scammers. A: <script type="text/javascript"> $(document).ready(function() { var baseLink = "http://myDevLink/library/ea26098f-89d1-4305-9f75-afc7937f8336/25/test/036b602b-0bde-e011-957b-1cc1dee8bacd.html"; var link = ""; $('#link').mouseenter(function() { link = baseLink + "?R=" + Math.floor(Math.random() * 1000000); $("#link").attr("href", link); }); }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7561685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PowerBuilder 11.5 on Windows 7 - Database profiles not visible After I installed PB 11.5 on Windows 7, I am not able to see list of database vendors (Oracle, SQL Server, etc.) in the "Database Profiles" screen. Only the ODBC connection is visible. Is this related to security settings on laptop that prevented the correct install for PB? I also installed PB 10.5 on the same machine and it works fine. Thanks for your help. A: This is usually related to which database drivers were installed. Maybe an uninstall/reinstall with a careful review of the database drivers selected would solve the problem. The other potential problem is that you don't have PowerBuilder Enterprise, but you have Professional or Desktop instead. You'd have to contact Sybase about buying an upgrade if that is your problem. Good luck, Terry.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why do we not pass POD by reference in functions? I've always been told that we should not pass POD by reference. But recently I've discovered that a reference actually takes no memory at all. So why do we choose to write: void DoSomething(int iNumber); instead of: void DoSomething(const int& riNumber); is it not more efficient? A: Actually in this case (using int) passing by value is probably more efficient, since only 1 memory-read is needed instead of 2, to access the passed value. Example (optimized using -O2): int gl = 0; void f1(int i) { gl = i + 1; } void f2(const int& r) { gl = r + 1; } int main() { f1(1); f2(1); } Asm .file "main.cpp" .text .p2align 2,,3 .globl __Z2f1i .def __Z2f1i; .scl 2; .type 32; .endef __Z2f1i: LFB0: pushl %ebp LCFI0: movl %esp, %ebp LCFI1: movl 8(%ebp), %eax incl %eax movl %eax, _gl leave ret LFE0: .p2align 2,,3 .globl __Z2f2RKi .def __Z2f2RKi; .scl 2; .type 32; .endef __Z2f2RKi: LFB1: pushl %ebp LCFI2: movl %esp, %ebp LCFI3: movl 8(%ebp), %eax movl (%eax), %eax incl %eax movl %eax, _gl leave ret LFE1: .def ___main; .scl 2; .type 32; .endef .p2align 2,,3 .globl _main .def _main; .scl 2; .type 32; .endef _main: LFB2: pushl %ebp LCFI4: movl %esp, %ebp LCFI5: andl $-16, %esp LCFI6: call ___main movl $2, _gl xorl %eax, %eax leave ret LFE2: .globl _gl .bss .align 4 _gl: .space 4 A: Not passing PODs by reference seems like a too general rule. PODs can be huge, and passing references to it would be worth. In your particular case, an int is the same size than the pointer that most -if not all- implementations use in the background to actually implement references. There is no size difference between passing an int or a reference, but now you have the penalty of an extra level of indirection. A: Passing by reference is passing by pointer in disguise. With small data, it can be faster to access it as values rather than having to deference the pointer several times. A: Because it is a meaningless efficiency gain 99.999% of time, and it changes the semantics. It also prevents you from passing in a constant value. For example: void Foo(int &i) { } Foo(1); // ERROR! This would work however: void Foo(const int &i) { } Foo(1); Also, it means that the function can modify the value of i such that it is visible to the caller, which may well be a bad thing (but again, you could certainly take a const reference). It comes down to optimizing the parts of your program where it matters and making the semantics of the rest of the code as correct as possible. a reference actually takes no memory at all. Not sure who told you that, but it's not true. A: Depends what you mean by efficiency. The main reason we pass objects by constant reference is because doing so by value will invoke the object's copy constructor, and that can be an expensive operation. Copying an int is trivial. A: There is no right answer, or even obvious general preference. Passing by value can be faster in some instances, and very importantly, can eliminate side effects. In other cases, passing by reference can be faster, and allow information to be more readily returned from a given function. This holds for POD data types. Keep in mind, a struct can be a POD, so size considerations vary between PODs even. A: The real answer is habit. We have an ingrained culture of attempting macro optimizations on our code (even if it rarely makes any real difference). I would be surprised if you can show me code were passing by value/reference (an integer) makes any difference. Once you start hiding the type via template we start using const reference again (because it may be expensive to copy some types). Now if you had asked about generic POD then there could be a cost difference as POD can get quite large. There is small advantage in the first version that we do not need an extra identifier if we are mutating the original value. void DoSomething(int iNumber) { for(;iNumber > 0; --iNumber) // mutating iNumber { // Stuff } } // No real cost difference in code. // Just in the amount of text we need to read to understand the code // void DoSomething(int const& iNumber) { for(int loop = iNumber;loop > 0; --loop) // mutating new identifier { // Stuff } } A: No it is not. The example with int is simply the same. It matters when you have "heavier" objects.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Rails CMS with custom types I come from the .NET world and have some PHP background as well. I'm currently developing in Ruby on Rails and I'm using Rails 3.1 and Ruby 1.9.2. I've been researching about Rails CMSs, but haven't had much luck with what I've been looking for. The one feature that I'm looking for is the ability to create custom types with custom fields, as I can do with both Sitecore and N2CMS on .NET, and both Drupal and Joomla on PHP. Are there any good alternatives on Ruby on Rails that possess this ability? If not, is it easily achievable in any Rails CMS? A: Check out Locomotive. It has Custom content types. A: I went through this same struggle, and just ended up building something on my own from scratch on top of Rails—it was a lot easier than I thought it'd be. For example, all of my normal pages get routed like this: get '/:slug' => 'page#show', as 'page_path' But I also have custom data types such as 'events'. These are their own model, and as I only interact with them via ajax at this point: get '/events/:year/:month' => 'events#get_by_year_and_month, :as => 'get_events_by_year_and_month' All of the content editing is protected by Devise, behind the :admin namespace: namespace :admin do resources :pages resources :events end And so on. If you're not comfortable enough with HTML and CSS to build a nice UI for the admin stuff, it may not be a great idea, but there are plenty of templates and examples out there. A: I recently built a site using a CMS called Refinery. http://www.refinerycms.com. In Refinery, you can build your own engines to handle custom types / fields as needed. Here is their quick start guide on how to achieve this: http://refinerycms.com/guides/getting-started-with-refinery#extending-refinery-with-your-first-engine The only downside to Refinery (imo) is that if you expose part of the code so you can customize it (you do this by copying parts (views, controllers, etc.) out of the Gem and into your normal Rails app directory structure), it then gives you a stumbling block when updating the Refinery Gem a newer version.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561695", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Javascript's geometrical methods: Zero isn't exactly zero, is it? In a simple geometric program written in Javascript and Canvas, when I set the angle to 270° (1½π), I expected the Math.cos(θ) to go to zero. The vector is straight down from the center, there's no x distance on a cartesian grid. Instead, I get this: demo_angle = 270 ang = demo_angle * Math.PI / 180 x = Math.cos(ang) console.log(x) > -1.836909530733566e-16 To see the output of the math functions, view the console. The source code is visible (in coffeescript) one level up in the URL. I've had to define in my code "Any number whose absolute value is smaller than 1e-15 should be considered zero," but that's really unsatisfying. Needless to say, when I try doing math with the x value that small, especially since I'm trying to use x as the denominator in a slope calculation and then doing some quadratic manipulations, I eventually come up with figures that exceed Number.MAX_VALUE (or Number.MIN_VALUE). I know floating point mathematics is, at the assembly language level, something of a dark art, but results like this just seem weirder than is acceptable. Any hints on what I should do? A: The problem is not that "zero isn't exactly zero". On the contrary, zero is exactly zero. The issue that you're encountering is that 3π/2 is not representable as a floating point number. So you're actually taking the cosine of a value that is not quite equal to 3π/2. How big is this representation error? About 1.8e-16, which is the source of the error you see in the cosine. Some languages get around this problem by providing functions like sinpi and cospi that implicitly scale their arguments by a factor of π; that's one way to deliver exact results. Obviously, that's not an option for you because javascript doesn't have such functions. You could roll your own if you want, taking advantage of the symmetries of these functions, or you can simply clamp "nearly zero" values to zero, as you are now. Neither is particularly satisfactory, but both will probably work for your purposes. A: The problem is that Math.PI isn't exactly equal to Pi, but is instead the number of the form m*2^e with 2^52 <= m < 2^53 closest to it. Then multiplying by 270 introduces a small round-off error. Then dividing by 180 causes some more round-off error. So your ang value is not exactly equal to 3*Pi/2, and as a result, what you get back is not the 0 you expect. The calculation itself is actually done very accurately.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561698", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: number as consecutive bits What would be the fastest way to represent a number as a set of consecutive bits? Number range: 1-32, output to be stored in unsigned 32 bit variable. input : 1 output: 10000000000000000000000000000000 input : 5 output: 11111000000000000000000000000000 input : 16 output: 11111111111111110000000000000000 input : 31 output: 11111111111111111111111111111110 I am using C language, but if you can give a faster example in assembly it is welcome. My current code is this: uint get_bitmap_left(uint num) { if (num== 1) return(0x80000000); if (num== 2) return(0xC0000000); if (num== 3) return(0xE0000000); if (num== 4) return(0xF0000000); if (num== 5) return(0xF8000000); if (num== 6) return(0xFC000000); if (num== 7) return(0xFE000000); if (num== 8) return(0xFF000000); if (num== 9) return(0xFF800000); if (num==10) return(0xFFC00000); if (num==11) return(0xFFE00000); if (num==12) return(0xFFF00000); if (num==13) return(0xFFF80000); if (num==14) return(0xFFFC0000); if (num==15) return(0xFFFE0000); if (num==16) return(0xFFFF0000); if (num==17) return(0xFFFF8000); if (num==18) return(0xFFFFC000); if (num==19) return(0xFFFFE000); if (num==20) return(0xFFFFF000); if (num==21) return(0xFFFFF800); if (num==22) return(0xFFFFFC00); if (num==23) return(0xFFFFFE00); if (num==24) return(0xFFFFFF00); if (num==25) return(0xFFFFFF80); if (num==26) return(0xFFFFFFC0); if (num==27) return(0xFFFFFFE0); if (num==28) return(0xFFFFFFF0); if (num==29) return(0xFFFFFFF8); if (num==30) return(0xFFFFFFFC); if (num==31) return(0xFFFFFFFE); if (num==32) return(0xFFFFFFFF); returrn(0); } A: return 0xFFFFFFFF << (32 - num);
{ "language": "en", "url": "https://stackoverflow.com/questions/7561702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Design approach for controller What is the design approach if 3 war files sharing same service and busniess logic layer.How i should use Controller here. if i am not using application server,I mean not packing into ear file. What is the alternative for the controller? Regards, Raju komaturi A: It's fine to keep your controller in their respective war file in the design phase, but your project putting these together needs to repack those wars into one common war file - which lets you map all paths in the same web.xml. If you're using Maven and its WAR plugin it can handle this task for you. I'm not sure exactly what you define as Controller, but if you're referring to Springs, e.g., annotated Controllers, then they can most certainly be used this way. Same with regular servlets.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: The mystery arguments passed by setTimeout in Firefox Possible Duplicate: Firefox setTimeout(func, ms) sending default parameters to callback I have been wondering this for a long time. When I type in the following line in FF, then I get: var timer = setTimeout(function () {console.log(arguments)}, 500); arguments outputs an array with a random number in it, and this number is different from the value of the timer. When I try on Chrome, the arguments is an empty array. Anyone has noticed this? A: From https://developer.mozilla.org/en/window.setTimeout: Gecko passes an extra parameter to the callback routine, indicating the "lateness" of the timeout in milliseconds.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Unresolved dependency on sbt-android-plugin 0.6.0-SNAPSHOT? I just followed the steps at Build Scala Android apps using Scala and when I ran sbt inside the project folder I got the following unresolved dependency error: [info] Loading project definition from /Users/macarse/Documents/scalatest/project/plugins [info] Updating {file:/Users/macarse/Documents/scalatest/project/plugins/}default-dd299a... [warn] module not found: org.scala-tools.sbt#sbt-android-plugin_2.9.1;0.6.0-SNAPSHOT [warn] ==== typesafe-ivy-releases: tried [warn] http://repo.typesafe.com/typesafe/ivy-releases/org.scala-tools.sbt/sbt-android-plugin_2.9.1/0.6.0-SNAPSHOT/ivys/ivy.xml [warn] -- artifact org.scala-tools.sbt#sbt-android-plugin_2.9.1;0.6.0-SNAPSHOT!sbt-android-plugin_2.9.1.jar: [warn] http://repo.typesafe.com/typesafe/ivy-releases/org.scala-tools.sbt/sbt-android-plugin_2.9.1/0.6.0-SNAPSHOT/jars/sbt-android-plugin_2.9.1.jar [warn] ==== local: tried [warn] /Users/macarse/.ivy2/local/org.scala-tools.sbt/sbt-android-plugin_2.9.1/0.6.0-SNAPSHOT/ivys/ivy.xml [warn] -- artifact org.scala-tools.sbt#sbt-android-plugin_2.9.1;0.6.0-SNAPSHOT!sbt-android-plugin_2.9.1.jar: [warn] /Users/macarse/.ivy2/local/org.scala-tools.sbt/sbt-android-plugin_2.9.1/0.6.0-SNAPSHOT/jars/sbt-android-plugin_2.9.1.jar [warn] ==== public: tried [warn] http://repo1.maven.org/maven2/org/scala-tools/sbt/sbt-android-plugin_2.9.1/0.6.0-SNAPSHOT/sbt-android-plugin_2.9.1-0.6.0-SNAPSHOT.pom [warn] -- artifact org.scala-tools.sbt#sbt-android-plugin_2.9.1;0.6.0-SNAPSHOT!sbt-android-plugin_2.9.1.jar: [warn] http://repo1.maven.org/maven2/org/scala-tools/sbt/sbt-android-plugin_2.9.1/0.6.0-SNAPSHOT/sbt-android-plugin_2.9.1-0.6.0-SNAPSHOT.jar [warn] ==== Scala-Tools Maven2 Repository: tried [warn] http://scala-tools.org/repo-releases/org/scala-tools/sbt/sbt-android-plugin_2.9.1/0.6.0-SNAPSHOT/sbt-android-plugin_2.9.1-0.6.0-SNAPSHOT.pom [warn] -- artifact org.scala-tools.sbt#sbt-android-plugin_2.9.1;0.6.0-SNAPSHOT!sbt-android-plugin_2.9.1.jar: [warn] http://scala-tools.org/repo-releases/org/scala-tools/sbt/sbt-android-plugin_2.9.1/0.6.0-SNAPSHOT/sbt-android-plugin_2.9.1-0.6.0-SNAPSHOT.jar [warn] :::::::::::::::::::::::::::::::::::::::::::::: [warn] :: UNRESOLVED DEPENDENCIES :: [warn] :::::::::::::::::::::::::::::::::::::::::::::: [warn] :: org.scala-tools.sbt#sbt-android-plugin_2.9.1;0.6.0-SNAPSHOT: not found [warn] :::::::::::::::::::::::::::::::::::::::::::::: [error] {file:/Users/macarse/Documents/scalatest/project/plugins/}default-dd299a/*:update: sbt.ResolveException: unresolved dependency: org.scala-tools.sbt#sbt-android-plugin_2.9.1;0.6.0-SNAPSHOT: not found Project loading failed: (r)etry, (q)uit, (l)ast, or (i)gnore? What am I missing? A: For sbt 0.11.0: * *Follow instructions from @Debilski's answer to publish android-plugin to local. *rm -rvf project/plugins/ *Create a file project/plugins.sbt, the content of this file is addSbtPlugin("org.scala-tools.sbt" % "sbt-android-plugin" % "0.6.0-SNAPSHOT") *Now you should be able to run sbt under that project *android:package-debug to compile/package the hello world program g8 created. *android:install-device to install the APK on the android device. A: sbt-android-plugin has not been made public in version 0.6.0-SNAPSHOT. A quick fix would be to install it locally. git clone https://github.com/jberkel/android-plugin.git cd android-plugin sbt update sbt publish-local Of course, this works only as long as the github repository’s master branch points to version 0.6.0-SNAPSHOT. (If it doesn’t anymore, then I may suspect that 0.6.0 has been published.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7561723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: MySQL - Joining with an or statement? I have a query where I want to join to another table if the field has either one value or another. How would I go about doing that? Should I use an or statement? (Is that even possible?) Or will an IN statement suffice? SELECT table1.field1,table2.field2 FROM table1 INNER JOIN table2 ON table1.field1 = table2.field2 OR table2.field2 = 0 Basically the field in table 2 can either be a match from table 1 or the number 0, I want to make the match on either or. So if there is no match from table1 field and table2 field but there is a 0 in table2 field then I want to join the table. Hope that makes sense. Or would this work/be better? SELECT table1.field1,table2.field2 FROM table1 INNER JOIN table2 ON table1.field1 IN(table2.field2,0) A: I'd think about it slightly differently and start with table2. SELECT table1.field1, table2.field2 FROM table2 LEFT JOIN table1 ON table2.field2 = table1.field1 WHERE table2.field2 = 0 OR table1.field1 IS NOT NULL
{ "language": "en", "url": "https://stackoverflow.com/questions/7561728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JSON format inconsistency There are two JSON format that i came across: Format A: [ {"topic": {"category":"testCategory","created_at":"2011-09-27T05:41:42Z", "size":5,"title":"testTitle2", "id":1, "posts":[ {"number":1,"created_at":"2011-09-27T05:41:42Z", "text":"text2","id":1,"topic_id":1}, {"number":0,"created_at":"2011-09-27T05:41:42Z", "text":"sentence1","id":2,"story_id":1} ] } } ] Format B: [ {"category":"testCategory","created_at":"2011-09-27T05:41:42Z", "size":5,"title":"testTitle2", "id":1, "posts":[ {"number":1,"created_at":"2011-09-27T05:41:42Z", "text":"text2","id":1,"topic_id":1}, {"number":0,"created_at":"2011-09-27T05:41:42Z", "text":"sentence1","id":2,"story_id":1} ] } ] When my restKit client gets format B she is pleased but when she gets format A i get the following error: ... Could not find an object mapping for keyPath: '' ... My restKit configurations is at the bottom. So i fixed it by making my rails 3.1 server send her a format B JSON. But now, restKit sends the server a format A JSON and he is stump as he should be. Why does restKit won't receive format A but sends formats A? Is there a way to make restKit send a format B JSON? Or, maybe is there a way to make rails send format B and receive format A? my restKit configurations: -(void)initRestKit{ RKObjectManager* objectManager = [RKObjectManager objectManagerWithBaseURL:@"http://localhost:3000/"]; objectManager.objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:@"WTF.sqlite"]; // Setup our object mappings RKManagedObjectMapping* topicMapping = [RKManagedObjectMapping mappingForClass:[Topic class]]; storyMapping.primaryKeyAttribute = @"topicID"; storyMapping.setDefaultValueForMissingAttributes = YES; [storyMapping mapKeyPathsToAttributes: @"id", @"topicID", .... @"created_at", @"dateCreated", nil]; RKManagedObjectMapping* postMapping = [RKManagedObjectMapping mappingForClass:[Post class]]; sentencesMapping.primaryKeyAttribute = @"postID"; [sentencesMapping mapKeyPathsToAttributes: @"id", @"postID", ... @"text", @"text" , nil]; //setup relationships [storyMapping mapRelationship:@"posts" withMapping:postMapping];//topic -> (posts) -> post // Register our mappings with the provider [objectManager.mappingProvider setMapping:topicMapping forKeyPath:@"topic"]; [objectManager.mappingProvider setMapping:postMapping forKeyPath:@"post"]; // Set Up Router [objectManager.router routeClass:[Topic class] toResourcePath:@"/topics.json" forMethod:RKRequestMethodPOST]; [objectManager.router routeClass:[Topic class] toResourcePath:@"/topics/(topicID).json"]; [objectManager.router routeClass:[Post class] toResourcePath:@"/topics/(topic.topicID)/posts.json" forMethod:RKRequestMethodPOST]; [objectManager.router routeClass:[Post class] toResourcePath:@"/topics/(topic.topicID)/(post.postID).json"]; } -(void)sendTopic{ RKObjectManager *manager =[RKObjectManager sharedManager]; [manager postObject:self.topic delegate:nil block:^(RKObjectLoader *loader) { RKObjectMapping* sendTopicMapping = [RKManagedObjectMapping mappingForClass:[Topic class]]; [sendTopicMapping mapKeyPathsToAttributes: @"id", @"topicID", .... @"title", @"title", nil]; RKManagedObjectMapping* postPostMapping = [RKManagedObjectMapping mappingForClass:[Post class]]; [postPostMapping mapKeyPathsToAttributes: @"id", @"postID", .... @"text", @"text" , nil]; [sendTopicMapping mapRelationship:@"posts" withMapping:postPostMapping]; [manager.mappingProvider setMapping:sendTopicMapping forKeyPath:@"topic"]; loader.serializationMapping = [sendTopicMapping inverseMapping]; }]; } A: Since you seem to control both ends of the process, you also have control over what gets sents. The two JSON snippets you provide are actually two DIFFERENT data structures. (A) is an array which contains two objects, each containing a number of member elements. (B) is an array which contains two objects which have a 'patient' key and a value which is another object containing a multitude of different key/value pairs. e.g. your system is generating two different data structures, and your service is expecting only one of those structures - and rightfully has no idea how to deal with the 'bad' one, even though it appears to contain the proper data. A: I solved it if anyone is interested: in rails i changed the modle so it will send the restKit client nested json(Format A) like this: class Topic < ActiveRecord::Base has_many :posts accepts_nested_attributes_for :posts self.include_root_in_json = true end I made the post method attributes nested like this: -(void)sendTopic{ RKObjectManager *manager =[RKObjectManager sharedManager]; [manager postObject:self.topic delegate:nil block:^(RKObjectLoader *loader) { RKObjectMapping* sendTopicMapping = [RKManagedObjectMapping mappingForClass:[Topic class]]; [sendTopicMapping mapKeyPathsToAttributes: @"topic[id]", @"topicID", .... @"topic[title]", @"title", nil]; RKManagedObjectMapping* postPostMapping = [RKManagedObjectMapping mappingForClass:[Post class]]; [postPostMapping mapKeyPathsToAttributes: @"post[id]", @"postID", .... @"post[text]", @"text" , nil]; [sendTopicMapping mapRelationship:@"posts" withMapping:postPostMapping]; [manager.mappingProvider setMapping:sendTopicMapping forKeyPath:@"topic"]; loader.serializationMapping = [sendTopicMapping inverseMapping]; }]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7561730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQLAlchemy, sqlite and fork() What is the best way to use fork() in a SQLAlchemy + sqlite project? The SQLAlchemy documentation mentions that one should call create_engine() in the child but doesn't mention any other caveats, of which I am sure there are plenty (write locks, busy_timeout, dispose/connection-issues, etc). Would the design issue of whether to use transactions or scoped sessions matter? A: SQLite does not support write concurrency so only one client can write to a single database at any point in time. With that constraint in place, the only gain you will get from using transactions is the ability to roll them back. If you plan to use multiple databases, make sure you don't drag yourself into a deadlock where two processes hold a transactional write lock in one database and try to simultaneously obtain one in the other. A: sqlite will handle all of the database locking for you; this is not something that you can or should think about on the client side of the database connection.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MFMessageComposeViewController setting the UINavigationItem titleView I'm having a problem overriding the title view of MFMessageComposeViewController's navigation item. Here is the code: MFMessageComposeViewController *messageViewController = [[MFMessageComposeViewController alloc] init]; messageViewController.body=@"SMS Body"; CGRect frame = CGRectMake(0, 0, 100.0, 45.0); UILabel *label = [[UILabel alloc] initWithFrame:frame]; label.text=@"Title"; messageViewController.navigationItem.titleView=label; [label release]; [self.navigationController presentModalViewController:messageViewController animated:YES]; [messageViewController release]; I have also tried: messageViewController.navigationController.navigationItem.titleView=label; I should also point out that this is for iOS 4, in iOS 5 I use the new setTitleTextAttributes method which works great. Thoughts? A: I believe this semi-hack should produce the desired effect. Since we know that MFMessageComposeViewController is a subclass of UINavigationController, the view that you are actually seeing must be managed by a private controller class. You should be able to modify that controllers navigation item in order to achieve what you want. messageViewController.topViewController.navigationItem.titleView = label; In my testing, this only worked with the titleView. If you just try to set the title, it will work for a couple seconds, but then gets overriden back to the title of the email. As with any other sort of UIKit hacks, this could stop working at any time, and it may only work on particular OS versions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Resource Files how to name them? I am playing around with resource files and have run into a problem. I have a folder called Languages. When I make a resource file and say call it "R.resx" I can call this resource file up in my classes. If I rename this file(or delete and make a new resource file) and call it R.en.resx I cannot call this resource file up in my class anymore. Does the first language need to be in R.resx where the rest would be R.language.resx? A: Step 6 To create resource files for additional languages, copy the file in Solution Explorer or in Windows Explorer, and then rename it using one of the following patterns: For global resource files: name.language.resx name.language-culture.resx For local resource files: pageOrControlName.extension.language.resx pageOrControlName.extension.language-culture.resx So yes, you are correct in your assumption that the base resource file would be the first language. EDIT: var temp = Properties.Resources.ResourceManager.BaseName.Replace("YourNamespace.Properties.",""); You may have to also do this (to get rid of the language part after the name chunk): temp = temp.Replace(".thelanguagechunk",""); This code would get you the "name" chunk you are after by itself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cannot find protocol declaration NSObject I am about to try and pass a value that the suer selectes in a subview back to the mainview of my application. I have been doing abit of reading about how to do it, and am currently following a fairly informative tutorial here I am starting from step 18 and implementing this into my code as it seems fairly straight forward... however I have this error in my secondview.h file where I am declaring my protocol as follows. #import <UIKit/UIKit.h> @protocol PassSearchData <nsobject> //this is where I get the "Cannot find protocol declaraton for 'nsobject' error @required - (void) setSecondFavoriteColor:(NSString *)secondFavoriteColor; @end @interface VehicleResultViewController : UITableViewController <NSXMLParserDelegate> { //... //Delegate stuff for passing information back to parent view id <PassSearchData> delegate; } //.. //Delegate stuff for passing information back to parent view @property (retain) id delegate; //.. @end </PassSearchData></nsobject></uikit/uikit.h> //more errors here also.. A: As Malcolm Box mentioned in the comment, NSObject (and most source code, for that matter) is case-sensitive. Also, I'm not sure what the last line with </PassSearchData></nsobject></uikit/ uikit.h> is supposed to be. I'd suggest something like the following: #import <UIKit/UIKit.h> @protocol PassSearchData <NSObject> @required - (void) setSecondFavoriteColor:(NSString *)secondFavoriteColor; @end @interface VehicleResultViewController : UITableViewController <NSXMLParserDelegate> { //... //Delegate stuff for passing information back to parent view id <PassSearchData> delegate; } //.. //Delegate stuff for passing information back to parent view @property (assign) id <PassSearchData> delegate; // not retain ? //.. @end That code should probably compile, but that doesn't necessarily mean it's problem-free. Traditionally, delegates are not retained, because of the problem of retain cycles. So I changed the declaration of the delegate property from retain to assign.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What's the easiest way to scrape a Wikipedia table into a graph? What's the easiest way to quickly take a column like these marathon times and display them as a graph? Just an ad-hoc momentary view is sufficient; fancy formatting, editing, or saving as a file type isn't a concern. A: Selecting, copying, and pasting into Open office's calc worked for me. Formatting is a bit weird, but that's easily fixable. A: * *drag-select the table contents *copy *open Excel 97 *click Edit, Paste special..., Text *select first through last cells in column A *click Chart Wizard icon *click Finish (for default chart; axis labels need work)
{ "language": "en", "url": "https://stackoverflow.com/questions/7561768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: NSMutableDictionary losing data? sprite.extraData Is a NSMutaleDictionary. In one method, I do this: [sprite.extraData setObject:@"HELLO" forKey:@"NAME"]; Now, in a different method, I do this: for (CCSprite *anim in animations) { NSLog(@"%@",[anim.extraData objectForKey:@"NAME"]); } Where sprite is a child of the NSMutableArray animations. When I try to print the name, I get (null). Why is that? A: Did you initialize the extraData of sprite? Make sure you do something in the CCSprite init file like: extradata = [[NSMutableDictionary alloc] init];
{ "language": "en", "url": "https://stackoverflow.com/questions/7561770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Automated web UI testing in Node.js Are there any automated web testing libraries for Node.js, preferably headless? A: You should also check out PhantomJS and CasperJS. Together, it's a testing framework in pure JavaScript with a headless WebKit browser. It works in Linux, OS X and Windows. A: Selenium now has JavaScript bindings for Node.js. You can use a headless driver along with the Selenium bindings. (Check out ghostdriver.) Basically all you have to do is install Node.js, set up your driver and then get your Selenium module with npm selenium-webdriver. I have some more detailed instructions and screenshots in my tutorial, here. A: Zombie is a headless full-stack testing framework for Node.js. There's a full list of testing modules on the Node.js GitHub wiki. A: Selenium WebDriver can use headless mode with a configuration for Chrome: let { Builder} = require('selenium-webdriver') let {Options} =require('selenium-webdriver/chrome') let options = new Options() let driver = new Builder().forBrowser('chrome').setChromeOptions(options.headless()).build() By the way, you can also use CukeTest for writing your UI automation script.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: how to switch arrays from which a uitableview is populated Hello im constructing an iphone app the requires the user to switch tableviews depending on which button is selected at the top. I have five different tableviews each populated from an array in a plist file. My question is how do i tell this uitableview to switch to another array. Thanks! A: You can have a dictionary or array of your arrays (the data) and a property/iVar for the "current" array. When they select a different option, you change the value of current array and call [tableView reloadData]; That will cause the table view call backs to trigger and reload all the data. All the table view callbacks should get their data from current array. For example, let's say we had three data sets, "cars", "computers", and "devices". // defined as property in header to handle retain/release @property (retain) NSArray *current; // construct your data on load or init NSArray *cars = [NSArray arrayWithObjects:@"porsche", @"corvette", @"pacer", nil]; NSArray *computers = [NSArray arrayWithObjects:@"PC", @"iMac", nil]; NSArray *devices = [NSArray arrayWithObjects:@"iPhone", @"iPad", @"iPod", nil]; NSMutableDictionary *data = [[NSMutableDictionary alloc] init]; [data setObject:cars forKey:@"cars"]; [data setObject:computers forKey:@"computers"]; [data setObject:devices forKey:@"devices"]; // when they select computers, change the current array to computers array [self setCurrent: [data objectForKey:@"computers"]]; // since you changed which dataset to use, trigger for the table view to reload. [tableView reloadData]; // all table view callbacks work off of current array A: Your tableView datasource returns values for the number or sections and rows in sections, and UITableViewCell for each row. All you need to do is make sure the data from the appropriate array is used to return the correct values. For example, if you have 5 arrays (array1, array2, etc.), so could also declare another array property to which you assign the array from which you want to return data: self.dataArray = self.array1 , say, when the first button is pressed then use self.dataArray to return values in your datasource methods. A: On button action perform this way. -(void)ButtonPressed:(id)sender { switch([sender tag]) { case 0: { self.resultArray = [NSArray arrayWithObjects:@"ABC",@"MNO",nil]; //self.resultArray = //sameArrayAssigned to it break; } default: break; } [self.tableView reloadData]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7561784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript Image Rotator Problems My code is very self explanatory. It is suppose to, after the page loads all necessary images, start looping through the same 5 images for the banner, with a 5 second delay in between. But, it doesn't do anything when the page loads. <script type="text/javascript"> var counter = 0; var bannerList = new Array(); bannerList[0] = "/portfolio/1.jpg" bannerList[1] = "/portfolio/2.jpg" bannerList[2] = "/portfolio/3.jpg" bannerList[3] = "/portfolio/4.jpg" bannerList[4] = "/portfolio/5.jpg" function bannerRotator(){ if(counter > 4){ counter = 0; } document.getElementById("slide").src = bannerList[counter]; counter = counter + 1; var t=setTimeout("bannerRotator()", 2000); } </script> Along with: <body onLoad="bannerRotator();"> Can anyone see where I'm going wrong? Thanks for any help! A: you could use setInterval instead of setTimeout and use a simple modulo % to make it rotate. eg: setInterval(function(){ changeImage( bannerList[counter++ % bannerList.length]); }, 5000); A: while (counter <= 4){ var t=setTimeout("changeImage(bannerList[counter])", 5000); counter = counter + 1; if (counter > 4){ counter = 0; } } that, my friend, is an infinite loop and is always suspect... it will never reach 5. the reason why it crashes (at least for me) is because it doesn't wait for the timeout to end before it loops again. You might consider using something like this: Also, you can't pass parameters as a string (e.g. the "changeImage(bannerList[counter])"). You need to concatenate like so: var t=setTimeout("changeImage('"+bannerList[counter]+"')", 1000); Then to actually make it loop, you want to put another call to the timeout inside the changeImage function (so it does it after the time and not all five at the same time). This will mean that both counter and bannerList need to be global. Then with a little js monkey business you get the following version: var counter = 0; var bannerList = new Array(); function bannerRotator(){ bannerList[0] = "portfolio/1.jpg" bannerList[1] = "portfolio/2.jpg" bannerList[2] = "portfolio/3.jpg" bannerList[3] = "portfolio/4.jpg" bannerList[4] = "portfolio/5.jpg" var t=setTimeout("changeImage('"+bannerList[counter]+"')", 1000); } function changeImage(newImgLoc){ document.getElementById("slide").src = newImgLoc; setTimeout("changeImage('"+bannerList[++counter%bannerList.length]+"')", 1000); } You can see a demo here: Demo if you want to actually see images changing, you'll need to plug their absolute paths. A: try changing "onLoad" to "onload"... see if that helps A: try setTimeout("changeImage(bannerList[counter])", 5000); instead of var t=setTimeout("changeImage(bannerList[counter])", 5000); so you output the function, now it sets it to a variable //EDIT <img id="slide" src="portfolio/4.jpg"> is your output in firebug it does change the pictures in your demo A: The problem is that doing someElement.src = 'http://...'; doesn't do anything. It sets a property on the object someElement but it does not change the HTML attribute (it does for some attributes on some elements, e.g. someLink.href = or someInput.name =, but those are special cases). What you should be doing is using the setAttribute() method, e.g.: var counter = 0; function changeImage(newImgLoc){ document.getElementById("slide").setAttribute('src', newImgLoc); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7561787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I can not see the jquery ui icon but the text inside the span was displayed I can not see the jquery ui icon but the text inside the span was displayed. Anyway to troubleshoot this. When I used firebug, I don't see the css code when highlighting the span tag. <TITLE> Test </TITLE> <link rel="stylesheet" type="text/css" href=""file:///C:/test/css/custom-theme/jquery-ui-1.8.16.custom.css"> <SCRIPT type="text/javascript" src="jquery-ui-1.8.16.custom.min.js"></SCRIPT> <SCRIPT type="text/javascript" src="jquery.layout-latest.js"></SCRIPT> <SCRIPT type="text/javascript" src="jquery-1.6.2.min.js"></SCRIPT> <div id="top" class="north"> <span class="ui-icon ui-icon-arrow-1-w" style="float:left;">This is a test</span> </div> A: You have two double quotes after the href= in your <link> tag.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Encrypting NSString with SHA1 hash Someone asked me if I can help them out with a small project. Everything was working out perfect until I ran into an SHA-1 encryption. I have been working on it for several days but cannot figure out a way how to tackle this problem. The goal is to encrypt an NSString, sending it to a remote PHP script and receiving an answer back from the server. I managed the sending and receiving part but cant figure out the 'hard part' The string needs to be encoded on the client side and needs to be checked on the receiving side, so it needs to be decoded there (not my problem). Is there a possibility on achieving this, so can a SHA-1 hash be decoded provided the receiving side knows its de-/en-cryption algorithm? A: SHA creates a non-reversible signature of the data it processes, it is not encryption per-se, it is hashing (Secure Hash Algorithm). It can be used as part of an authentication protocol. If both sides have a shared value and want to endure they both have the same value but don't want to send the value (it could be seen by an advisory) a hash can be used. The initiator hashes (SHA-1) the shared value, send the hash to the other side. The receiver hashes their copy of the shared value and compares the hashes. There are many ways this an be accomplished such as only sharing the hash value, @Greg mentions this method. More importantly, @Greg mentions that one should not re-invent security methods. I will add that if security is important get a proven security professional's help. When I develop a secure product I always have it reviewed. A: If the receiver knows what the string should be (like a password), then you can SHA1 hash the password on the sender, send it to the receiver, which can check it against the locally-computed SHA1 hash of the known password. However, this approach also has problems and you probably shouldn't be inventing cryptographic protocols yourself. Or, if you're passing some bit of information that the server doesn't already know, then you'll need a completely different approach.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Incorrect syntax near '.'. - C# When I attempt to run the following the code,I got an error.What might be the problem? protected void Button1_Click(object sender, EventArgs e) { SqlConnection cnn = new SqlConnection("server=.; database=YEDEK; Integrated Security=True; "); cnn.Open(); SqlCommand cmd = cnn.CreateCommand(); cmd.CommandText = "insert Personel (Name,Surname,Tel) values ('"+txtName.Text+"','"+ txtSurname.Text+"','"+txtTel.Text+"') "; SqlParameter p1 = new SqlParameter("txtName.Text", SqlDbType.NVarChar); p1.Value = "txtName.Text"; cmd.Parameters.Add(p1); SqlParameter p2 = new SqlParameter("txtSurname.Text", SqlDbType.NVarChar); p2.Value = "txtSurname.Text"; cmd.Parameters.Add(p2); SqlParameter p3 = new SqlParameter("txtTel.Text", SqlDbType.Char); p3.Value = "txtTel.Text"; cmd.Parameters.Add(p3); cmd.ExecuteNonQuery(); cnn.Close(); } Here is my error message: Incorrect syntax near '.'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near '.'. Source Error: Line 44: //cmd.Parameters.Add(p3); Line 45: Line 46: cmd.ExecuteNonQuery(); Line 47: //} Line 48: //catch (SqlException ex) A: Your parameters are not in the correct syntax. A proper parameter would be like so: new SqlParameter("@SomeParamName", SqlDbType.VarChar) It looks like you are trying to directly insert the values from your controls into the parameter. In this situation you would do this: var param = new SqlParameter("@Name", SqlDbType.VarChar); param.Value = txtName.Text; The parameter names should match your stored procedure definition. A: You either should use SqlParameter or concatenate string. The former is better, as it prevents SQL injection attack. Also, do not quote properties of controls you're using (like p1.Value = "txtName.Text"). Below is how it can be done proper way: SqlConnection cnn = new SqlConnection("server=.; database=YEDEK; Integrated Security=True; "); cnn.Open(); SqlCommand cmd = cnn.CreateCommand(); cmd.CommandText = "INSERT INTO Personel (Name, Surname, Tel) VALUES (@Name, @Surname, @Tel) "; SqlParameter p1 = new SqlParameter("@Name", SqlDbType.NVarChar); p1.Value = txtName.Text; cmd.Parameters.Add(p1); SqlParameter p2 = new SqlParameter("@Surname", SqlDbType.NVarChar); p2.Value = txtSurname.Text; cmd.Parameters.Add(p2); SqlParameter p3 = new SqlParameter("@Tel", SqlDbType.Char); p3.Value = txtTel.Text; cmd.Parameters.Add(p3); cmd.ExecuteNonQuery(); cnn.Close(); A: cmd.CommandText = "insert Personel (Name,Surname,Tel) values (@Name, @Surname, @Tel) "; Looks more logical, and you have to make sure your sommand parameters match the variable names as well. A: Tejs is correct, remove DOTS from your paramnames. You should also change your insert statement to (I removed the dots too) cmd.CommandText = "insert Personel (Name,Surname,Tel) values(@txtNameText,@txtSurnameText,@txtTelText) "; Please rename those params, they are badly named! A: I think the problem here is that you already build a sql statement without parameters with this line of code: cmd.CommandText = "insert Personel (Name,Surname,Tel) values ('"+txtName.Text+"','"+ txtSurname.Text+"','"+txtTel.Text+"') "; This results is a directly working sql statement (without parameters): "insert Personel (Name,Surname,Tel) values ('ValueOfTxtName','ValueOfTxtSurname','ValueOfTxtName' )" You need to replace your sql statement to something like this: "insert Personel (Name,Surname,Tel) values ( @Name,@Surname,@Tel)" and then add the parameters conform to Tejs suggestion.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Problem when loading images with AJAX I'm using a jquery plugin to load images from flickr. I'm trying to distribute these images into 3 columns as they come in, the goal being to place each image in the shortest column so that the columns are close to equal length at the end. The script works great most of the time in IE. It was less dependable in Firefox but seems better now. In Chrome however it totally fails. I have narrowed the problem down to the fact that while the script is running it thinks the images have zero dimensions. The dimensions don't appear until some later point, but I want to distribute the images as they come in, not do a big reshuffle at the end. Why does occur even when I use the Image object? And how can I get around this problem? A: maybe you should try to get the image dimantion with the load() event $('img').load( function() { alert( $(this).width() ); }); A: var myimg = document.getElementById('myimage'); if I give this dude a new source, the img.onload event will fire, so I need to put the code that should fire after load in the onload event handler. myimg.onload = function(){ //do some crap } myimg.src = someAjaxCall();
{ "language": "en", "url": "https://stackoverflow.com/questions/7561812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Transparent PNGs don't retain transparency after being transformed (Django + PIL) I'm using sorl-thumbnail, PIL, and Django on a webserver to dynamically create thumbnails in templates. PIL is installed with PNG support, but for some reason the transformations are creating some really bizarre artifacts on the transparent portions of the images. I used this gist on Github to install the required dependencies: https://raw.github.com/gist/1225180/eb87ceaa7277078f17f76a89a066101ba2254391/patch.sh Here is the template code that generates the images (I don't think this is where the problem is, but can't hurt to show you): {% thumbnail project.image "148x108" crop="center" as im %} <img src='{{ im.url }}' /> {% endthumbnail %} Below is an example of what happens. Any help is greatly appreciated! Before After A: Either: * *add format='PNG'. *add THUMBNAIL_PRESERVE_FORMAT=True to the settings. *or use the custom engine as described here: http://yuji.wordpress.com/2012/02/26/sorl-thumbnail-convert-png-to-jpeg-with-background-color/ """ Sorl Thumbnail Engine that accepts background color --------------------------------------------------- Created on Sunday, February 2012 by Yuji Tomita """ from PIL import Image, ImageColor from sorl.thumbnail.engines.pil_engine import Engine class Engine(Engine): def create(self, image, geometry, options): thumb = super(Engine, self).create(image, geometry, options) if options.get('background'): try: background = Image.new('RGB', thumb.size, ImageColor.getcolor(options.get('background'), 'RGB')) background.paste(thumb, mask=thumb.split()[3]) # 3 is the alpha of an RGBA image. return background except Exception, e: return thumb return thumb in your settings: THUMBNAIL_ENGINE = 'path.to.Engine' You can use the option now: {% thumbnail my_file "100x100" format="JPEG" background="#333333" as thumb %} <img src="{{ thumb.url }}" /> {% endthumbnail %} A: It looks like your resulting image is a JPEG. The JPEG format does not support transparency. Try changing your thumbnail template to this: {% thumbnail project.image "148x108" crop="center" format="PNG" as im %} A: I'd suggest you rather look into how sorl's PIL backend handles scaling. I imagine it creates some helper image to apply additional effects on and then tells PIL to scale the original onto that. You need to make sure that the destination is using the RGBA mode to support transparency and that it starts with its alpha set to zero (and not pure white or pitch black or something similar). If your image is using an indexed palette then it's possible it does not get converted to RGBA. In indexed mode PNGs store the transparent color index in their metadata but the process of creating the thumbnail will alter pixels due to antialiasing so you cannot preserve indexed transparency in: source = Image.open('dead-parrot.png') source.convert('RGBA') dest = source.resize((100, 100), resample=Image.ANTIALIAS) dest.save('ex-parrot.png')
{ "language": "en", "url": "https://stackoverflow.com/questions/7561815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: HTTP Post Connection Guarantee I have an application that speaks to a server on a regular basis using HTTP POST. I am trying to make the connection as failsafe as possible, so the application will not try to send a thing if it does not have a working data connection. How can I detect a connection loss during the middle of a NSURLConnection? The timeout does not work without a minimum time of 240, so that is out of the question. I could use an NSTimer, but it still hangs because the NSURLConnection seems to take up the main thread not allowing any changes. Some sort of delgate maybe? My code is as follows: -(NSData*) postData: (NSString*) strData //it's gotta know what to post, nawmean? { //postString is the STRING TO BE POSTED NSString *postString; //this is the string to send postString = @"data="; postString = [postString stringByAppendingString:strData]; NSURL *url = [NSURL URLWithString:@"MYSERVERURLHERE"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; NSString *msgLength = [NSString stringWithFormat:@"%d", [postString length]]; //setting prarameters of the POST connection [request setHTTPMethod:@"POST"]; [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request addValue:msgLength forHTTPHeaderField:@"Content-Length"]; [request addValue:@"en-US" forHTTPHeaderField:@"Content-Language"]; [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]]; //[request setTimeoutInterval:10.0]; NSLog(@"%@",postString); NSURLResponse *response; NSError *error; NSLog(@"Starting the send!"); //this sends the information away. everybody wave! NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; NSLog(@"Just finished receiving!"); if (urlData == nil) { if (&error) { NSLog(@"ERROR"); NSString *errorString = [NSString stringWithFormat:@"ERROR"]; urlData = [errorString dataUsingEncoding:NSUTF8StringEncoding]; } } return urlData; } A: Sure your main thread is blocked when using sendSynchronousRequest:. That is very bad practice for if the user loses the internet connection, the UI will be completely out of order. Apple writes in the documentation: Important: Because this call can potentially take several minutes to fail (particularly when using a cellular network in iOS), you should never call this function from the main thread of a GUI application. I strongly advise to use the asynchronous methods connectionWithRequest:delegate:. You can easily catch the interruption in connection:didFailWithError:. Believe me, it's not that hard, but well worth the effort.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }