text
stringlengths
8
267k
meta
dict
Q: Rails: Devise Authentication from an ActiveResource call My two rails applications(app1, app2) are communicating using active resource. app1 calls app2 create a user inside app2. app2 would create the user and would like app1 then redirect the user to app2's authenticated pages. going from app1 to app2 would invariably ask the user to log in. I was looking for a way to avoid this login step in app2, instead make the user log in during the first active resource call to create user, and somehow get the authentication token written. Authentication is done using Devise. Is there anything built into Devise that support this? Is passing around the authentication token the way to go? A: You are trying to implement a form of Single Sign-On service (SSO) (sign in with app1, and be automatically authenticated with app2, app3...). It is unfortunately not a trivial task. You can probably make it work (maybe you already did), but instead of trying to reinvent the wheel, why not instead integrate an existing solution? Or even better, a standard protocol? It is actually relatively easy. CAS server RubyCAS is a Ruby server that implements Yale University's CAS (Central Authentication Service) protocol. I had great success with it. The tricky part is getting it to work with your existing Devise authentication database. We faced the same problem, and after some code diving, I came up with the following, which works like a charm for us. This goes in your RubyCAS server config, by default /etc/rubycas-server/config.yml. Of course, adapt as necessary: authenticator: class: CASServer::Authenticators::SQLEncrypted database: adapter: sqlite3 database: /path/to/your/devise/production.sqlite3 user_table: users username_column: email password_column: encrypted_password encrypt_function: 'require "bcrypt"; user.encrypted_password == ::BCrypt::Engine.hash_secret("#{@password}", ::BCrypt::Password.new(user.encrypted_password).salt)' enter code here That encrypt_function was pain to figure out... I am not too happy about embedding a require statement in there, but hey, it works. Any improvement would be welcome though. CAS client(s) For the client side (module that you will want to integrate into app2, app3...), a Rails plugin is provided by the RubyCAS-client gem. You will need an initializer rubycas_client.rb, something like: require 'casclient' require 'casclient/frameworks/rails/filter' CASClient::Frameworks::Rails::Filter.configure( :cas_base_url => "https://cas.example.com/" ) Finally, you can re-wire a few Devise calls to use CAS so your current code will work almost as-is: # Mandatory authentication def authenticate_user! CASClient::Frameworks::Rails::Filter.filter(self) end # Optional authentication (not in Devise) def authenticate_user CASClient::Frameworks::Rails::GatewayFilter end def user_signed_in? session[:cas_user].present? end Unfortunately there is no direct way to replace current_user, but you can try the suggestions below: current_user with direct DB access If your client apps have access to the backend users database, you could load the user data from there: def current_user return nil if session[:cas_user].nil? return User.find_by_email(session[:cas_user]) end But for a more extensible architecture, you may want to keep the apps separate from the backend. For the, you can try the following two methods. current_user using CAS extra_attributes Use the extra_attributes provided by the CAS protocol: basically, pass all the necessary user data as extra_attributes in the CAS token (add an extra_attributes key, listing the needed attributes, to your authenticator in config.yml), and rebuild a virtual user on the client side. The code would look something like this: def current_user return nil if session[:cas_user].nil? email = session[:cas_user] extra_attributes = session[:cas_extra_attributes] user = VirtualUser.new(:email => email, :name => extra_attributes[:name], :mojo => extra_attributes[:mojo], ) return user end The VirtualUser class definition is left as an exercise. Hint: using a tableless ActiveRecord (see Railscast #193) should let you write a drop-in replacement that should just work as-is with your existing code. current_user using an XML API on the backend and an ActiveResource Another possibility is to prepare an XML API on the users backend, then use an ActiveResource to retrieve your User model. In that case, assuming your XML API accepts an email parameter to filter the users list, the code would look like: def current_user return nil if session[:cas_user].nil? email = session[:cas_user] # Here User is an ActiveResource return User.all(:params => {:email => email}).first end While this method requires an extra request, we found it to be the most flexible. Just be sure to secure your XML API or you may be opening a gapping security hole in your system. SSL, HTTP authentication, and since it is for internal use only, throw in IP restrictions for good measure. Bonus: other frameworks can join the fun too! Since CAS is a standard protocol, you get the added benefit of allowing apps using other technologies to use your Single Sign-On service. There are official clients for Java, PHP, .Net and Apache. Let me know if this was of any help, and don't hesitate to ask if you have any question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I increase the speed of plotting in python? I have a 256x256 numpy-array of data which is constantly being changed. on every iteration I take a snapshot to make a movie. snapshot is a 3d surface plot made using matplotlib. The problem is that plotting costs me >2 seconds on every iteration which is about 600 seconds for 250 iterations. I had the same program running in MATLAB and it was 80-120 seconds for the same number of iterations. The question: are there ways to speed up matplotlib 3d surface plotting or are there faster plotting tools for python? Here is some of the code: ## initializing plot fig = plt.figure(111) fig.clf() ax = fig.gca(projection='3d') X = np.arange(0, field_size, 1) Y = np.arange(0, field_size, 1) X, Y = np.meshgrid(X, Y) ## the loop start_time = time.time() for k in xrange(250): it_time = time.time() field[128,128] = maxvalue field = scipy.ndimage.convolve(field, kernel) print k, " calculation: ", time.time() - it_time, " seconds" it_time = time.time() ax.cla() ax.plot_surface(X, Y, field.real, rstride=4, cstride=4, cmap=cm.hot, linewidth=0, antialiased=False) ax.set_zlim3d(-50, 150) filename = "out_%d.png" % k fig.savefig(filename) #fig.clf() print k, " plotting: ", time.time() - it_time, " seconds" print "computing: ", time.time() - start_time, " seconds" A: For 3D plotting in general, I would advise mayavi. It can be a bit daunting at first, but it is worth the effort. It is certainly much faster than matplotlib for plotting one shot of 3D data. For plotting many times with a savefig call, I'm not sure... A: GNUplot (accessed through it's various python interfaces) may be faster. At least I knew someone a few years ago with a similar problem to yours and after testing a number of packages they went with GNUplot. It's not nearly as good looking as matplotlib though. Also, I assume you have interactive mode turned off. A: I can't test if it helps since you didn't provide a runnable example, but you could see if modifying the Poly3DCollection returned by plot_surface is faster than creating a new collection every time. Also, you are using a non-interactive backend, right? (Call matplotlib.use('agg') before importing pyplot.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7503164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Encoding parameters values in a URL with Java I need to encode the parameters values in an URL. If I use following: URLEncoder.encode(url, "UTF-8"); for a URL like this: http://localhost:8080/... it will encode "://" etc. What I need is the encoding only for the values of the parameters starting from all the URL string. So in this case: http://localhost/?q=blah&d=blah I want encoded only the "blah" in the 2 parameters values (for n parameters of course). What's your best way? Thanks Randomize A: You're using URLEncoder in a wrong way. You're supposed to encode every parameter value separately and then assemble the url together. For example String url = "http://localhost/?q=" + URLEncoder.encode ("blah", "UTF-8") + "&d=" + URLEncoder.encode ("blah", "UTF-8"); A: For a URL like http://localhost/hello/sample?param=bla, you could use this (from Java's java.net.URI class): URI uri = new URI("http", "localhost", "/hello/sample", "param=bla", null); String url = uri.toASCIIString();
{ "language": "en", "url": "https://stackoverflow.com/questions/7503166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Multivariate Similarity Metrics Say I am tracking 2 objects moving in space & time, * *I know their x,y co-ords and score (score being a probabilistic measure of the tracked being the actual object), *and I get several such {x,y,score} samples over time for each object What metric would I use to measure "similarity" of say a ball moving across a room vs. man moving across the room vs. a child moving across the room. Assume the score is pretty accurate. A: Given your description, I'd recommend looking into a Hidden Markov Model or possibly an artificial neural network or some other machine learning approach. However, there are a number of other techniques that might be more appropriate for your situation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I tell Wolfram Alpha that I want it to compute the terms of an integer sequence? I want to compute a list of the terms of the sequence (14747-40*n)/(2621440*(41-n)), n from 1 to 40 I tried entering the above in Wolfram Alpha, and it plots me a graph of the function. This isn't what I want. I've tried variations on this command, as well as guessing at various keywords to stick before it, and I either get back the same thing, or something unhelpful. The help page on sequences suggests various things you might do with sequences, but doesn't say how to do something simple like this??? A: The following works: Table[(14747-40*n)/(2621440*(41-n)) n, {n, 1, 40}] Clicking on "approximate form" then on "copy plaintext" gives the following: {0.000140257, 0.000286924, 0.000440507, 0.000601567, 0.000770728, 0.000948683, 0.00113621, 0.00133417, 0.00154356, 0.00176547, 0.00200115, 0.00225204, 0.00251976, 0.00280618, 0.00311345, 0.00344409, 0.00380101, 0.00418764, 0.00460803, 0.00506701, 0.00557035, 0.00612508, 0.00673974, 0.00742493, 0.00819385, 0.00906326, 0.0100547, 0.0111963, 0.0125257, 0.0140939, 0.0159728, 0.0182658, 0.0211282, 0.0248041, 0.0297003, 0.0365488, 0.0468139, 0.0639122, 0.0980936, 0.200607}
{ "language": "en", "url": "https://stackoverflow.com/questions/7503174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: HTML (using CSS) Code for sending an email to given email-id How can i code a HTML (using CSS) file to send an email to me(i.e. to given email-id) by the visitor of that website? A: Without using a server-side language, the best you can really do is a mailto link. That will open the user's default email editor with the "To" field populated with the value of your mailto link. You can create one of those like so: <a href="mailto:you@somewhere.com">Email Me!</a> It is possible to provide extra information in a mailto link, to populate more fields. For example, if you want to provide a subject: <a href="mailto:you@somewhere.com?subject=Subject">Email Me!</a> You can also provide a value for the body, cc and bcc but I have no idea how well those default values are supported by various email clients. Also note that this has absolutely nothing whatsoever to do with CSS, which is used for styling documents. I've therefore removed the CSS tag from your question. A: You cannot. You can use a tag: <a href="mailto:youremailaddress">Email Me</a> And this will open a mail client in the client side. The client must have it configured for being able to send a email. If you want to create a form that, when the user presses a button "send" sends you a message, you must use a dynamic language such as PHP.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Maybe a nested div in an absolute div? I asked a similar question earlier and we came down to this CSS solution being the closest, but it's no cigar. So help out if you can! I need two divs, #post_content and #sidebar, to have matching heights. I'm trying to find a CSS workaround for this. Positioning it absolutely does the job but some content is cut-off when the post content is shorter than the sidebar's content. Is there a CSS solution (possibly adding another div inside #sidebar) which will allow me to absolutely position #sidebar while always showing all its content? Note: It is important #sidebar's background and border extend the same height as #post_content Note: #sidebar and #post_content are wrapped in #container Example of a page where the sidebar content is being cut-off (#post_content shorter than #sidebar): http://themeforward.com/demo2/2011/07/08/link/ THE CSS CONCERNED: #sidebar { float: right; width: 410px; overflow:hidden; position:absolute; clear:both; border-left:1px solid #000; background:#AAA; top:0; right:0; bottom:0 } #post_content { clear: both; display: block; float: left; position:relative; overflow: hidden; width: 660px } NOT NECESSARY... BUT COULD BE USED #container { width: 1126px; clear: both; overflow:hidden; position:relative; margin:35px auto } A: This is the CSS holy grail - here's the article: http://www.alistapart.com/articles/holygrail/
{ "language": "en", "url": "https://stackoverflow.com/questions/7503177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the easiest way to create an HTML mouseover tool tip? What is the easiest, cleanest way to create an HTML mouseover tool tip without using JavaScript? <img id=Pennstate src="/blah" style="cursor:pointer;"> mouse over that and have a a nice tooltip "We are Pennstate!" A: If you don't care much what the tooltip looks like you can always just use the "title" attribute A: The easiest way is to use the native HTML title attribute: <img src="https://stackoverflow.com/favicon.ico" style="cursor:pointer;" title="Stack Overflow"> But if you need more, try the tooltip widget provided by jQuery UI since version 1.9.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "87" }
Q: Javascript Runtime error why i am getting runtime error in javascript at var ClientID = document.getElementById("ClientIDTextBox").value; and my code is: <script type="text/javascript"> var ClientID = document.getElementById("ClientIDTextBox").value; if (ClientID == "") { alert("Please enter ClientID") } </script> please help me A: You are likely getting a runtime error because the call document.getElementById is returning null. The attempt to get the property value on null leads to an error. Try the following instead var element = document.getElementById('ClientIDTextBox'); if (element) { var ClientID = element.value; ... } The root cause though is likely that your javascript is running before the DOM is loaded and hence your element with id ClientIDTextBox is not available. Ensure your javascript runs after the DOM is loaded to prevent this problem. A: <script type="text/javascript"> var ClientID = document.getElementById("ClientIDTextBox"); if (ClientID == null || ClientID.value == "") { alert("Please enter ClientID") } </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7503185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Retrieving data bound object I created a ViewModel which has an observable property. I bind this array to an ul HTML element, like this: <ul id="sortable" data-bind="template: { name: 'parameterTemplate', foreach: parameters }, visible: parameters().length > 0" style="width: 100%"> </ul> My template is this: <script type="text/html" id="parameterTemplate"> <li class="ui-state-default parameterItem"> <input type="checkbox" data-bind="checked: isRequired" /> Name: <input data-bind="value: name " /> Type: <input data-bind="value: type " /> Size: <input data-bind="value: size " /> <a href="#" data-bind="click: remove">Delete</a> </li> </script> I'm using the draggable and sortable resources of jQuery to reorder the elements of the list. This means that when the users changes the order of the element, obviously ko databind is not altered, for jQuery does not know knockout exists. It so happens that I want my parameters to be saved in the same order the user configured. So my approach was to select al the li HTML elements via jQuery, getting an array ( var items = $(".parameterItem");) . How can I get , for each item in items, the databound knockout element, associated with the li HTML element? Is it possible? My View Model: function parameter(parameterName, parameterType, parameterSize, descriptive, defaultValue, isRequired, ownerViewModel) { this.name = ko.observable(parameterName); this.type = ko.observable(parameterType); this.size = ko.observable(parameterSize); this.label = ko.observable(parameterName); this.descriptive = ko.observable(descriptive); this.defaultValue = ko.observable(defaultValue); this.descriptive = ko.observable(descriptive); this.isRequired = ko.observable(isRequired); this.ownerViewModel = ownerViewModel; this.remove = function () { ownerViewModel.parameters.remove(this) }; } function excelLoaderViewModel() { this.parameters = ko.observableArray([]); this.newParameterName = ko.observable(); this.newParameterType = ko.observable(); this.newParameterSize = ko.observable(); this.newParameterDescriptive = ko.observable(); this.newParameterIsRequired = ko.observable(); this.newParameterDefaultValue = ko.observable(); this.systemName = ko.observable(); this.addParameter = function () { this.parameters.push( new parameter( this.newParameterName() , this.newParameterType() , this.newParameterSize() , this.newParameterDescriptive() , this.newParameterDefaultValue() , this.newParameterIsRequired() , this)); this.newParameterName(""); this.newParameterType(""); this.newParameterSize(""); this.newParameterIsRequired(false); this.newParameterDefaultValue(""); } var myVM = new excelLoaderViewModel(); ko.applyBindings(myVM); A: Your best bet is to use a custom binding to keep your observableArray in sync with your elements as they are dragged/dropped. Here is a post that I wrote about it a while ago. Here is a custom binding that works with jQuery Templates: //connect items with observableArrays ko.bindingHandlers.sortableList = { init: function(element, valueAccessor) { var list = valueAccessor(); $(element).sortable({ update: function(event, ui) { //retrieve our actual data item var item = ui.item.tmplItem().data; //figure out its new position var position = ko.utils.arrayIndexOf(ui.item.parent().children(), ui.item[0]); //remove the item and add it back in the right spot if (position >= 0) { list.remove(item); list.splice(position, 0, item); } } }); } }; Here is a sample of it in use: http://jsfiddle.net/rniemeyer/vgXNX/ If you are using it with Knockout 1.3 beta without jQuery Templates (or with), then you can replace the tmplItem line with the new ko.dataFor method available in 1.3: //connect items with observableArrays ko.bindingHandlers.sortableList = { init: function(element, valueAccessor) { var list = valueAccessor(); $(element).sortable({ update: function(event, ui) { //retrieve our actual data item var item = ko.dataFor(ui.item[0]); //figure out its new position var position = ko.utils.arrayIndexOf(ui.item.parent().children(), ui.item[0]); //remove the item and add it back in the right spot if (position >= 0) { list.remove(item); list.splice(position, 0, item); } } }); } };
{ "language": "en", "url": "https://stackoverflow.com/questions/7503186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there risk to having unsanitized user input display in a textarea? I save two versions of user input in the following sequence: * *Untrusted user enters raw markdown. *Raw markdown is stored in one table. *A copy of the raw markdown is converted into HTML. *HTML is sanitized and persisted, and is displayed upon request. *The raw markdown version is only displayed when users edit a entry; it's loaded into a textarea of a form. Is there any risk in loading raw markdown (which could potentially contain unsafe HTML) into a textarea? It would never be displayed outside of a textarea. I can't sanitize the markdown because it would result in inconsistencies between the markdown and HTML versions I'm saving. FYI: I always sanitize SQL, regardless of what I'm saving to the DB. A: You don't have to sanitize it there, just take care of correctly escaping HTML special characters such as < and >. For instance, Stackoverflow allows you to post HTML code in your posts, it does not remove anything. This is achieved by encoding, not sanitizing. A: It depends how you're "loading" it into the textarea. If you're doing it server-side through simple string concatenation, e.g. in php, $output = '<textarea>' + $markdown + '</textarea>'; ...then there is absolutely a risk, because that markdown could very easily close out the textarea and embed whatever else it wants. If you're using some sort of a component framework (e.g., ASP.NET), then you should be protected as long as you use a safe API method, such as MyTextArea.Value = markdown;. If you're doing it client-side, it also depends on how you're doing this. You would be safe if you used something like jQuery's .val() setter, but could still expose yourself to XSS vulnerabilities through other approaches. In short, the general answer is yes, depending on how you're actually creating and populating the textarea. A: Are you at least doing SQL sanitation? When you INSERT or UPDATE the data, are you using some type of DAO that escapes the SQL or, if using Java, using a Prepared Statement where you set the arguments? You must always sanitize things before they go into the DB. Otherwise people could add a stray '); --Malicious procedure here. ..into a request. There are some security risks to leaving unsanitized input in the text box; mainly if the user is infected with something that's injecting Javascript, it will show up for him or her each time. Why even save that? Then you're giving your user a totally inconsistent view from what they enter to what is displayed? They won't match up. It's best to clean the input so when they user views it again he or she can clearly see that the offending HTML was removed for security.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503191", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Bundler is not self-aware: claims to have version 0.0.1, but is really 1.0.18 EDIT: I'm an idiot -- I figured out the problem. In a gem I had written a while back, I had VERSION='0.0.1', and for some reason that overrode the version number of bundler. Won't do that again... Some background information: on an OS X Lion computer I'm using RVM with Macruby on a Rails 3.0.7 project. I set Macruby and my current gemset to be the default. When I try to run bundle install, I get the following message: Bundler could not find compatible versions for gem "bundler": In Gemfile: bundler (~> 1.0) Current Bundler version: bundler (0.0.1) Your version of Bundler is older than the one requested by the Gemfile. Perhaps you need to update Bundler by running `gem install bundler`. When I run gem list bundle, it shows exactly one installation at version 1.0.18. I suspect that somehow the RVM default setting is not applied all the way through the system. But the system ruby does not have any bundler installed, much less this elusive 0.0.1. Anybody know what might be going on here? A: Could it be possible that your bundle executable is still pointing to an old version of the gem?
{ "language": "en", "url": "https://stackoverflow.com/questions/7503192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Batch file to delete all folders in a directory except a specified list I'm looking for a batch file that will go into C:\Documents and Settings\ and delete all folders except a few that I want to keep. A: Here's a hack-around =D If you have a list of folder paths in say folders.txt listed as so: * *C:\Documents and Settings\Mechaflash *C:\Documents and Settings\Mom *C:\Documents and Settings\Dad etc. What you can do is temporarily change them to hidden folders, then RMDIR on all non-hidden folders. CD "C:\Documents and Settings\" FOR /F "tokens=*" %%A IN (folders.txt) DO ( ATTRIB +H "%%A" /S /D ) FOR /F "USEBACKQ tokens=*" %%F IN (`DIR /B /A:-HD "C:\Documents and Settings\"`) DO ( RMDIR /S /Q %%A ) FOR /F "tokens=*" %%A IN (folders.txt) DO ( ATTRIB -H "%%A" /S /D ) A: A solution using robocopy: cd /d "C:\Documents and Settings" md tmp robocopy . tmp /E /MOVE /XD folderToKeep1 folderToKeep2 ... rd /s /q tmp A: rem the last space character is deliberate set yourKeepList="abc def " for /f %%f in ('dir /b/ad "C:\Documents and Settings"') do ( (echo %yourKeepList% | findstr /v /i "%%f " 1>nul) && rd /q/s %%f )
{ "language": "en", "url": "https://stackoverflow.com/questions/7503194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Web Font not loading First and foremost, I have tried searching and can't really find anything that will help this specific problem. Basically I have my website http://www.jamesendres.com and I am trying to load a custom web font from http://justanotherfoundry.com/facit-web. When I was developing my website on my local machine it worked flawlessly, but when I uploaded all of my files to Dreamhost, the fonts aren't being loaded.. I opened Firebug and apparently the fonts are being downloaded last so I think this might have something to do with why they aren't being loaded. But I could be wrong. In my main.css file is where all of my font-related configurations are. For help purposes I have made the homepage default to whatever the browsers default is to show it's not working: @font-face{ font-family:'FacitWeb-Extralight'; src:url('http://webfonts.justanotherfoundry.com/Facit/FXL'); font-weight:bold } p, li{ font-size:14px; /*font-family:'FacitWeb-Extralight', Verdana, Trebuchet MS, Arial, sans-serif;*/ font-family: FacitWeb-Extralight; line-height:18px; } A: Instead of simply writing a direct @font-face, you should use one of the font-face generators out there. I pesonally recommend Font Squirrel. They keep the generator up to date. The benefits include * *Advanced font-face syntax for correct loading across browsers *Automatic IE-style font generation *Good fallback design when @font-face is not supported.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I use the field tag in a user defined tag with the Play! Framework? Right now I have a view like this that works. #{form @UserCreate.create()} #{field 'user.email'} #{text field /} #{/field} #{/form} With a corresponding text tag defined which then uses the field (it is more complicated than this, just boiling down to essentials) <input type="text" id="${_arg.id}" name="${_arg.name}" value="${_arg.value}"> Ideally I would rather have it so I did not have to declare the field in the view so it would look like this. #{form @UserCreate.create()} #{text 'user.email' /} #{/form} With a tag that looks like this. #{field 'user.email'} <input type="text" id="${field.id}" name="${field.name}" value="${field.value}"> #{/field} But the field.value always returns null because user is not in the tags' template binding. I am not really sure how to approach things at this point. Suggestions? A: Hey I have an interesting workaround: Just write the first line of the custom tag %{user = _user}% #{field 'user.email'} <input type="text" id="${field.id}" name="${field.name}" value="${field.value}"> #{/field} This works for me :) A: I don't believe you will be able to do what you want due to the way the #{field} tag works (see its code here). Probably the best approach is to create a series of fast tags based on Field tag's code, without the part that renders the body (as you won't need it), even if it may mean a bit of code duplication. Once done you can refactor to extract some common sections and reduce the duplication. A: I modified the field tag quite a bit myself. I still have to do this to use it :( :( #{xfield objectId:'groupDbo.name',label:'Group Name', help:'Some help message', length:'50'} #{text field/} #{/xfield} but I don't have to keep repeating this html at least...... <div class="entry"> <div class="spacer"></div> <span class="label ${_arg.errorClass}">${_arg.label}</span> <span class="input ${_arg.errorClass}"> <input type="text" class="inputtext" name="${_arg.name}" value="${_arg.value}" maxlength="${_arg.length}"> <a id="newinfo" class="help" title="${_arg.help}">${_arg.help}</a> <span class="error">${_arg.error}</span> </span> <div style="clear: both;"></div> </div> This also fixes a bug(in 1.2.x) they have in the field tag in which that don't get private fields which is very annoying....(and adds more fields that should be there and are not) public class TagHelp extends FastTags { private static final Logger log = LoggerFactory.getLogger(TagHelp.class); public static void _xfield(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) { Map<String,Object> field = new HashMap<String,Object>(); Object objId = args.get("objectId"); if(objId == null || !(objId instanceof String)) throw new IllegalArgumentException("'objectId' param must be supplied to tag xfield as a String"); Object label = args.get("label"); if(label == null || !(label instanceof String)) throw new IllegalArgumentException("'label' param must be supplied to tag xfield as a String"); Object length = args.get("length"); if(length == null || !(length instanceof String)) throw new IllegalArgumentException("'length' param must be supplied to tag xfield as a String"); Object help = args.get("help"); if("".equals(help)) help = null; String _arg = objId.toString(); Object id = _arg.replace('.','_'); Object flashObj = Flash.current().get(_arg); Object flashArray = new String[0]; if(flashObj != null && !StringUtils.isEmpty(flashObj.toString())) flashArray = field.get("flash").toString().split(","); Object error = Validation.error(_arg); Object errorClass = error != null ? "hasError" : ""; field.put("name", _arg); field.put("label", label); field.put("length", length); field.put("help", help); field.put("id", id); field.put("flash", flashObj); field.put("flashArray", flashArray); field.put("error", error); field.put("errorClass", errorClass); String[] pieces = _arg.split("\\."); Object obj = body.getProperty(pieces[0]); if(obj != null){ if(pieces.length > 1){ for(int i = 1; i < pieces.length; i++){ try{ Field f = getDeclaredField(obj.getClass(), obj, pieces[i]); f.setAccessible(true); if(i == (pieces.length-1)){ try{ Method getter = obj.getClass().getMethod("get"+JavaExtensions.capFirst(f.getName())); field.put("value", getter.invoke(obj, new Object[0])); }catch(NoSuchMethodException e){ field.put("value",f.get(obj).toString()); } }else{ obj = f.get(obj); } }catch(Exception e){ log.warn("Exception processing tag on object type="+obj.getClass().getName(), e); } } }else{ field.put("value", obj); } } body.setProperty("field", field); body.call(); } private static Field getDeclaredField(Class clazz, Object obj, String fieldName) throws NoSuchFieldException { if(clazz == Object.class) throw new NoSuchFieldException("There is no such field="+fieldName+" on the object="+obj+" (obj is of class="+obj.getClass()+")"); try { return clazz.getDeclaredField(fieldName); } catch(NoSuchFieldException e) { return getDeclaredField(clazz.getSuperclass(), obj, fieldName); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7503198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: A problem with regex (non wanted end) I have the following pattern: (name|id)\s*=\s*('|")([a-zA-Z\-\_])+('|") And I have to get all attributes name="a" or id="ab_c" which does not have the structure name="a-element" or id="a-element" (finishes with -element), I tried with: (name|id)\s*=\s*('|")([a-zA-Z\_][^-element])+('|") but it does not work, what is the mistake?? A: You want negative look-arounds, like this: (name|id)\s*=\s*('|")([a-zA-Z\-_](?!-element))+('|") (But keep in mind that you probably shouldn't be parsing XML manually.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7503199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I use DataGridView's CellEnter and CellLeave events? I need to handle some things during a cell enter and a cell leave. However, I'm finding that these are fired at times where the cell is not physically being entered (tabbed into or mouse-clicked). For instance, they seem to be getting fired when I change the data source. I've overridden the OnDataSourceChanged event in such a way: protected override void OnDataSourceChanged(EventArgs e) { _isBinding = true; base.OnDataSoruceChanged(e); _isBinding = false; } Then, I use the _isBinding flag in the CellEnter event to bypass my logic. However, then I saw that the OnBindingContextChanged event was also triggering these event. I could override this event also, but when does it end? There could be other events that call the CellEnter/CellLeave events that I haven't tested. Is there a better way?
{ "language": "en", "url": "https://stackoverflow.com/questions/7503201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Regex using PHP, any non-zero number containing the digits 0-9 I have this regex: /^[0-9]+$/i Used in this code: preg_match('/^[0-9]+$/i', $var); I want the following to be true: $var = 1; $var = 50; $var = 333; And the following to be false: $var = 0; $var = 01; $var = 'abc'; I think what I have works so far except for the "0" part..? I went through this guide (http://www.phpf1.com/tutorial/php-regular-expression.html) but was unable to come up with a complete answer. Any help would be appreciated, thanks! A: just check for a non zero digit first then any number of other digits preg_match('/^[1-9][0-9]*$/', $var); A: There are a couple of ways you can do this: /^[1-9][0-9]*$/ or /^(?!0)[0-9]+$/ Either one of these should be fine. The first one should be more or less self-explanatory, and the second one uses a zero-width negative lookahead assertion to make sure the first digit isn't 0. Note that regex isn't designed for numeric parsing. There are other ways of doing it that will be faster and more flexible in terms of numeric format. For example: if (is_numeric($val) && $val != 0) ...should pick up any nonzero number, including decimals and scientific notation. A: /^[1-9][0-9]*$/ Means: A non-zero digit followed by an arbitrary number of digits (including zero). A: You can solve this by forcing the first digit to be different from 0 with '/^[1-9][0-9]*$/' With your list of exemples: foreach (array('1', '50', '333', '0', '01', 'abc') as $var) { echo $var.': '.(preg_match('/^[1-9][0-9]*$/', $var) ? 'true' : 'false')."\n"; } This script gives the following results: $ php test.php 1: true 50: true 333: true 0: false 01: false abc: false
{ "language": "en", "url": "https://stackoverflow.com/questions/7503203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Google Maps Licensing and SocialEngine/Joomla/Drupal plugins The following plugin for SocialEngine uses Google Maps for proximity searches, maps, etc. http://www.socialengine.net/customize/mod-page?mod_id=211&mod=Google-Map--Locations-Plugin Additional Note: The website will also be using a directory plugin. Is it necessary to purchase a commercial Google Maps API key for this kind of activity? Somebody suggested that a Google Maps API key was going to cost a lot of money, and for a starter business this wouldn't be possible. Plugins do not tend to mention this, but I am led to believe that there may be an issue here. A: Google Maps API is free for all non-commercial and commercial use, and you can use it in your commercial site: * *if you keep the default Google branding *and if the map will be public to anyone You need to buy a special key if you are planning to use the map in private or sell map products that will be for private use only. A: You can find the information you need in the Google Maps/Google Earth APIs Terms of Service and via the FAQ. Specifically, search the FAQ page for the Q&A "Can I use the Google Maps API on a commercial website?" Essentially, as long as your site isn't getting super high traffic, you should be fine with the free level of service. A: There is news on the way Google executes its license ... We just have been contacted by Google and were told that selling a Maps API Implementation to a customer requires a OEM License. This is regardless wether you charge a one time fee or a recurrent fee. This is regardless if you operate the Maps API Implementation on your own server or on the customers server. This was new to me and I did not read that from the license texts. So, if I interpret this correctly and if you are planning to subcontract a plugin for your website from another company (aka a Maps API Implementation), the other company should have a Google Maps OEM License and will charge you for API Traffic using that plugin. This seems not to apply if you are using a public-domain plugin or a plugin developed in house.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to insert a picture/text label at specific coordinates in a word 2007 document using C#? I can do this to insert picture and text at a default location: private static object objTrue = true; private static object objFalse = false; private static object objMissing = Missing.Value; private static object objEndOfDoc = @"\endofdoc"; // \endofdoc is a predefined bookmark. ... this.WordApp = new Word.Application(); this.WordDoc = new Word.Document(); this.WordApp.Visible = true; this.WordDoc = this.WordApp.Documents.Add(ref objMissing, ref objMissing, ref objMissing, ref objMissing); this.WordDoc.Content.InlineShapes.AddPicture( FileName: @"C:\MyLogo.png", LinkToFile: ref objMissing, SaveWithDocument: ref objTrue, Range: objMissing); // Insert a paragraph at the beginning of the document. var paragraph1 = this.WordDoc.Content.Paragraphs.Add(ref objMissing); paragraph1.Range.Text = "Heading 1"; paragraph1.Range.Font.Bold = 1; paragraph1.Format.SpaceAfter = 24; //24 pt spacing after paragraph. paragraph1.Range.InsertParagraphAfter(); How can I move it to any location I want? When I am creating PowerPoint (manually), I can position stuff anywhere. When I manually insert a shape, I can position it anywhere. How can I achieve similar result when inserting pictures and text labels programmatically using c#? I have not had success figuring this out using Google searches. A: The Range class is used in word to determine where almost everything goes in a document. If you replaced the Range parameter in this.WordDoc.Content.InlineShapes.AddPicture with a valid Range object, it would insert the picture at that place in the word document, and the same goes for paragraphs. According to MSDN for the AddPicture method on InlineShapes: Range: Optional Object. The location where the picture will be placed in the text. If the range isn't collapsed, the picture replaces the range; otherwise, the picture is inserted. If this argument is omitted, the picture is placed automatically. Another way would be to use the Shapes member of the document instead of InlineShapes. The AddPicture method on the Shapes class allows you to specify the coordinates: this.WordDoc.Content.Shapes.AddPicture( [In] string FileName, [In, Optional] ref object LinkToFile, [In, Optional] ref object SaveWithDocument, [In, Optional] ref object Left, [In, Optional] ref object Top, [In, Optional] ref object Width, [In, Optional] ref object Height, [In, Optional] ref object Anchor ); InlineShapes.AddPicture Shapes.AddPicture
{ "language": "en", "url": "https://stackoverflow.com/questions/7503210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Oracle dynamic query I've a simple query, vanilla select statement to which I want to filter the values provided by the user. SELECT A,B,C,D,E FROM TAB WHERE .... Here the WHERE is not fixed i.e the user may input values for C, so only C should be filtered, or D or E so on. The problem is due to the user telling- filter callerID between 1 and 10 etc, but the database column has a different name. So to form a working query I have to map callerID to the columnName. As this would be in a procedure I've thought of passing the csv of userInputColumnNames, csv of dbColumns and filter begin and start. Then laboriously extract the values and match the correct db column name and form the query. This works, but however this is very cumbersome and not clean. Could there be a better way of doing this? A: Do the column names in the table change? Or are columns in the table added/removed? If not, you can generate a number to map to each column in the table like: SQL> SELECT column_name, ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY column_name) "COLUMN_NUMBER" 2 FROM dba_tab_columns 3 WHERE table_name='DBA_USERS' 4 baim> / COLUMN_NAME COLUMN_NUMBER ------------------------------ ------------- ACCOUNT_STATUS 1 CREATED 2 DEFAULT_TABLESPACE 3 EXPIRY_DATE 4 EXTERNAL_NAME 5 INITIAL_RSRC_CONSUMER_GROUP 6 LOCK_DATE 7 PASSWORD 8 PROFILE 9 TEMPORARY_TABLESPACE 10 USERNAME 11 USER_ID 12 12 rows selected. Then when the user selects column 9, you know it maps to the "PROFILE" column. If the column names can change, or if columns are added/dropped dynamically, then this won't work though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What does eclipse do when you inspect variables (while debugging) I have an instance of org.hibernate.envers.entities.mapper.relation.lazy.proxy.ListProxy that is causing some grief: whenever I programmatically try to access it I get a null pointer exception (ie calling list.size()) but when I first inspect the object using Eclipse's variable inspector I see Hibernate generate a SQL statement and the list changes dynamically. Then everything works. How can I do the same thing programmatically? I've tried list.toString() but that doesn't seem to help. Update 1 Don't know if this helps but when I first click on the list instance I see in the display: com.sun.jdi.InvocationException occurred invoking method. Then database query runs and when I click again I get the correct .toString() result. Update 2 Here is the original exception I get (when I don't inspect the element in debug mode). java.lang.NullPointerException at org.hibernate.envers.query.impl.EntitiesAtRevisionQuery.list(EntitiesAtRevisionQuery.java:72) at org.hibernate.envers.query.impl.AbstractAuditQuery.getSingleResult(AbstractAuditQuery.java:104) at org.hibernate.envers.entities.mapper.relation.OneToOneNotOwningMapper.mapToEntityFromMap(OneToOneNotOwningMapper.java:74) at org.hibernate.envers.entities.mapper.MultiPropertyMapper.mapToEntityFromMap(MultiPropertyMapper.java:118) at org.hibernate.envers.entities.EntityInstantiator.createInstanceFromVersionsEntity(EntityInstantiator.java:93) at org.hibernate.envers.entities.mapper.relation.component.MiddleRelatedComponentMapper.mapToObjectFromFullMap(MiddleRelatedComponentMapper.java:44) at org.hibernate.envers.entities.mapper.relation.lazy.initializor.ListCollectionInitializor.addToCollection(ListCollectionInitializor.java:67) at org.hibernate.envers.entities.mapper.relation.lazy.initializor.ListCollectionInitializor.addToCollection(ListCollectionInitializor.java:39) at org.hibernate.envers.entities.mapper.relation.lazy.initializor.AbstractCollectionInitializor.initialize(AbstractCollectionInitializor.java:67) at org.hibernate.envers.entities.mapper.relation.lazy.proxy.CollectionProxy.checkInit(CollectionProxy.java:50) at org.hibernate.envers.entities.mapper.relation.lazy.proxy.CollectionProxy.size(CollectionProxy.java:55) at <MY CODE HERE, which checks list.size()> Final Solution (Actually more of a temporary hack) boolean worked = false; while (!worked) { try { if(list.size() == 1) { // do stuff } worked = true; } catch (Exception e) { // TODO: exception must be accessed or the loop will be infinite e.getStackTrace(); } } A: Well what happends there is you're seing Hibernate's lazy loading in deep action :) Basically hibernate loads proxy classes for you lazily associated relations, such that instead of a List of classes C you get a List (actually a PersistenceBag implementation) of Hibernate autogenerated proxie for your C class. THis is hibernate's way of deferring load of that association's values until they are actually accessed. So that's why when you access it in the eclipse debugger (which basically accesses an instance's fields/methids via introspection) you see the sql hibernate triggers to fetch the needed data. The trick here is that depending on WHEN you access a lazy collection you might get different results. If you access it using the eclipse debugger you're more likely still in the Hibernate session that started loading that thing, so everything works as expected, an sql is (lazily) triggered when the thing is accessed and the data is loaded). Problem is that if you wanna access that same data in your code, but at a point where the session is already closed, you'll either get a LazyInitializationException or null (the latter if you're using some library for cleaning put hibenrate proxises such as Gilead)
{ "language": "en", "url": "https://stackoverflow.com/questions/7503217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery plugin tablesorter jSON: o is undefined I have a table where I store some data. This data is returned from code.php in a JSON structure' array. $("#errtable").tablesorter(); $.getJSON("./include/code.php", {key:$('#key').val()}, function(data) { // append the "ajax'd" data to the table body $.each(data, function(key) { $("#errtable > tbody").append("<tr><td>"+data[key].errorcode+"</td><td>"+data[key].errordescription+"</td></tr>"); }); // let the plugin know that we made a update $("#errtable").trigger("update"); // set sorting column and direction, this will sort on the first and third column var sorting = [[2,1],[0,0]]; // sort on the first column $("#errtable").trigger("sorton",[sorting]); }); The problem is that Firebug shows an error: o is undefined [Break On This Error] o.count = s[1]; referring to: function updateHeaderSortCount(table, sortList) { var c = table.config, l = sortList.length; for (var i = 0; i < l; i++) { var s = sortList[i], o = c.headerList[s[0]]; o.count = s[1]; o.count++; } } does anybody can help me to fix this ? Thank you. A: With the following code you insert two cells per row, if I am not mistaken: $("#errtable > tbody").append("<tr><td>"+data[key].errorcode+"</td><td>"+data[key].errordescription+"</td></tr>"); And try two sort the third column, which does not exist: // set sorting column and direction, this will sort on the first and third column var sorting = [[2,1],[0,0]]; Sorting the second and first - and not the third - should fix the error in my opinion
{ "language": "en", "url": "https://stackoverflow.com/questions/7503219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Join row with MAX row in another table? How do I join a row from one table to a row with the MAX value for a given column on another table? For example, I have a auctions table and an auction_bids table. I want to join the auctions table with the highest bid for that auction (i.e. highest value for column bid_amount AND where auction_id = x) in the auction_bids table. A: It's annoyingly complicated. You'd be better off with a "winner" flag in each winning auction_bid. SELECT * FROM auctions a INNER JOIN ( /* now get just the winning rows */ SELECT * FROM auction_bids x INNER JOIN ( /* how to tell the winners */ SELECT auction_id, MAX(bid_amount) as winner FROM auction_bids GROUP BY auction_id ) y ON x.auction_id = y.auction_id AND x.bid_amount = y.winner ) b ON a.auction_id = b.auction_id Note that auctions with zero bids will not be listed at all, and auctions with ties (can that happen?) will appear once for each tied bid. A: Try this: SELECT a.*, bid_amount FROM auction a INNER JOIN ( SELECT auction_id, MAX(bid_amount) AS bid_amount FROM auction_bids WHERE acution_id = x GROUP BY auction_id ) b ON a.auction_id = b.auction_id A: Try this: SELECT a.id, MAX(ab.bid_amount) FROM auctions AS a INNER JOIN action_bids AS ab ON a.id = ab.auction_id GROUP BY a.id; Add more columns to your SELECT and GROUP BY clauses as needed. A: Try this Select A.ID,max(AB.bit_amount) From auctions A Inner Join Auction_bids AB on A.ID = AB.auction_ID Where A.ID = x Group By A.ID A: Basically you have to use a sub query to do this in the actual join. Select bid as highest_bid from auctions left outer join auctions_bids on action_bids.ref_no = auctions.ref_no and (select max(bid) from auctions_bids as ab where auctions_bid.ref_no = a2.ref_no)
{ "language": "en", "url": "https://stackoverflow.com/questions/7503220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Problem with redirection to start secion I have a problem with ... header ("Location :".$_ SERVER ['HTTP_REFERER']); I get the following error: Error 310 (net:: ERR_TOO_MANY_REDIRECTS) I'm trying to start session and where it was redirected to the user. There are a safer alternative? A: You have done an infinite loop. You are redirecting your visitor to the page where he comes from. If you open the page, it creates an infinite loop, trying to redirect itself. Can you be more explicit in you question? With "secion" are you trying to say "session"? Update: your code is working properly. The question is incomplete since the HTTP redirect has no relation with sessions, or users. Maybe you can be interested in reading: PHP sessions - PHP redirects
{ "language": "en", "url": "https://stackoverflow.com/questions/7503221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: When does bounds get updated? I am loading a view as soon as the user rotates to landscape but when I use view.bounds in viewDidLoad it is still in portrait. Here the code where I load the view which is triggered from a notification - (void)orientationChanged:(NSNotification *)notification { UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation; if (UIDeviceOrientationIsLandscape(deviceOrientation) && !isShowingLandscapeView) { [self presentModalViewController:self.graphViewController animated:YES]; isShowingLandscapeView = YES; } else if (deviceOrientation == UIDeviceOrientationPortrait && isShowingLandscapeView) { [self dismissModalViewControllerAnimated:YES]; isShowingLandscapeView = NO; } } And in the graphViewController in viewDidLoad I use self.view.bounds to initialise a core-plot. This is how it looks like Any hint on how to fix that? Thanks a lot EDIT in viewDidLoad // Create graph from theme graph = [[CPTXYGraph alloc] initWithFrame:self.view.bounds]; CPTTheme *theme = [CPTTheme themeNamed:kCPTDarkGradientTheme]; [graph applyTheme:theme]; CPTGraphHostingView *hostingView = [[CPTGraphHostingView alloc] initWithFrame:self.view.bounds]; hostingView.collapsesLayers = NO; // Setting to YES reduces GPU memory usage, but can slow drawing/scrolling hostingView.hostedGraph = graph; [self.view addSubview:hostingView]; A: Assuming CPTGraphHostingView will adjust the orientation of how it renders, you need to set the autoresizingMask on it. This determines how views resize when their superviews resize, which is happening in this case. hostingView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); A: It's not the correct approach. You should be doing this stuff in layoutSubviews. It will be called first time in, and subsequently each time orientation changes. Do something like this: - (void)layoutSubviews { [super layoutSubviews]; CGRect frame = self.bounds; // Do your subviews layout here based upon frame }
{ "language": "en", "url": "https://stackoverflow.com/questions/7503222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: java XML find the sibling node I have the below XML. Here I want to get the previous sibling of node c which is b using java <root> <a> <b> <c> <d> </a> </root> Whenever I try to get the node using node.getPreviousSibling() method I get the node as #text but not the node b. Any help on this is very much appreciated. A: You need to do something like this: (the #text that you get is the actual text in the node) public static Element getPreviousSiblingElement(Node node) { Node prevSibling = node.getPreviousSibling(); while (prevSibling != null) { if (prevSibling.getNodeType() == Node.ELEMENT_NODE) { return (Element) prevSibling; } prevSibling = prevSibling.getPreviousSibling(); } return null; } A: You could use a loop... while (node!= null && !(node instanceOf Element)) { node = node.getPreviousSibling(); } You could also use an XPath expression, ./previous-sibling::*
{ "language": "en", "url": "https://stackoverflow.com/questions/7503227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: multiple oauth providers and implicit user account creation I'm learning oauth 2.0 and was wondering about the following scenario * *say I want a website to allow login with both twitter and facebook *when a new user logs in for the first time using twitter, the server checks if a user with this twitter id exists in the database and if not, creates a new user using values returned from twitter *the same user logs out and logs in again, this time using his facebook account Question: how can I match the returning user with the account that was created the first time and avoid creating a second user account for the same user ? Thanks A: If you request for their email address, you can detect matches and merge that way? A: If you are only interested in having the user log in, then you should be looking at openID, not OAuth. Unless you explicitly ask the user to link their various accounts together for your app, there really isn't a good way to know that JohnDoe on Twitter is JohnDoe on Facebook. You can ask the customer to link their accounts together and give them tools to merge two accounts (one created with Twitter account and one with Facebook account) together.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Determining the center of the viewed space in a UIScrollView I am displaying a CATiledLayer via a scrollview which displays a map. When the user presses a button, I want to determine the bounds of the catiledlayer that the user is currently viewing and place an image there. In other words, I need to determine the portion of the CATiledLayer that is being displayed, then determine the center point of that portion. Appreciate any thoughts. A: You can call scrollView.contentOffset (which returns a CGPoint) which will give you where all the content in your scroll view is in relation to the origin point of the scroll view. So if your CATiledLayer is up and to the left you'd get some thing like (-50, -100). Take those values, multiply by -1 and then add them to scrollView.center property (also returns a CGPoint). This will give you a CGPoint coordinate that if used as the center point of a new-subview within scrollView will center that view within the current frame. CGPoint currentOffset = CGPointMake(scrollView.contentOffset.x * -1, scrollView.contentOffset.y * -1); CGPoint center = CGRectMake(scrollView.center.x + currentOffset.x, scrollView.center.y + currentOffset.y); I haven't tested this code, but it should work or at least give you a general starting point!
{ "language": "en", "url": "https://stackoverflow.com/questions/7503232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to obtain a QuerySet of all rows, with specific fields for each one of them? I have a model Employees and I would like to have a QuerySet of all rows, but with some specific fields from each row, and not all fields. I know how to query all rows from the table/model: Employees.objects.all() I would like to know how to select fields for each of the Queryset element. How can I do that? A: Daniel answer is right on the spot. If you want to query more than one field do this: Employee.objects.values_list('eng_name','rank') This will return list of tuples. You cannot use named=Ture when querying more than one field. Moreover if you know that only one field exists with that info and you know the pk id then do this: Employee.objects.values_list('eng_name','rank').get(pk=1) A: In addition to values_list as Daniel mentions you can also use only (or defer for the opposite effect) to get a queryset of objects only having their id and specified fields: Employees.objects.only('eng_name') This will run a single query: SELECT id, eng_name FROM employees A: Oskar Persson's answer is the best way to handle it because makes it easier to pass the data to the context and treat it normally from the template as we get the object instances (easily iterable to get props) instead of a plain value list. After that you can just easily get the wanted prop: for employee in employees: print(employee.eng_name) Or in the template: {% for employee in employees %} <p>{{ employee.eng_name }}</p> {% endfor %} A: Employees.objects.values_list('eng_name', flat=True) That creates a flat list of all eng_names. If you want more than one field per row, you can't do a flat list: this will create a list of tuples: Employees.objects.values_list('eng_name', 'rank') A: We can select required fields over values. Employee.objects.all().values('eng_name','rank') A: You can use values_list alongside filter like so; active_emps_first_name = Employees.objects.filter(active=True).values_list('first_name',flat=True) More details here A: Employees.objects.filter().only('eng_name') This will give a QuerySet of all rows, but with only the specified fields. It does NOT give a list like the other answers above. It gives your the OBJECT INSTANCES. Watch out; it is objects.filter().only() NOT just objects.only() It is similar to SQL Query: SELECT eng_name FROM Employees; A: queryset = ModelName.objects.filter().only('field1', 'field2')
{ "language": "en", "url": "https://stackoverflow.com/questions/7503241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "155" }
Q: Cant figure how to implement following jQuery plugin into my webpage I've been looking for something that will authorize a textbox when user types something and I found this ideal plugin: http://james.padolsey.com/javascript/jquery-plugin-autoresize/ It seems prety straight forward, but for some reason I can't implement it on my website >.< do you guys have any ideas on how to do it? (read the post) Thank You ))) Here is what I tried, but it doesn't work HTML <head> <script type="text/javascript" src="js/jquery-1.6.js"></script> <script type="text/javascript" src="js/autoresize.jquery.js"></script> <script type="text/javascript"> $('textarea.mainStatusTxt').autoResize({ // On resize: onResize : function() { $(this).css({opacity:0.8}); }, // After resize: animateCallback : function() { $(this).css({opacity:1}); }, // Quite slow animation: animateDuration : 300, // More extra space: extraSpace : 40 }); </script> </head> <body> <textarea class="mainStatusTxt" placeholder="Comment" style="display:block;"></textarea> </body> A: Either wrap your script with: $(document).ready(function() { //YOUR CODE }); or move the entire <script> tag to the end of the document (or at least, after the <textarea>).
{ "language": "en", "url": "https://stackoverflow.com/questions/7503245", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Undefined external symbol in shared library I recently ran nm -m -p -g on the System.B.dylib library from the iOS SDK4.3 and was surprised to find a lot of symbols marked (undefined) (external). Why and when would an undefined symbol be marked external? I can understand a undefined external symbol marked lazy or weak but these aren't. Many of the pthread_xxx functions fall in this category. When I link with this library however, all symbols are resolved. The pthread_xxx symbols are defined in one of the libraries in the \usr\lib\system folder so I am assume they are satisfied from there. How does that work during linking? A: It's been a while since I was an nm and ld C-coding ninja, but I think this only means that there are other libraries this one links against. A: Usually this is how dynamic linking works. If you were to nm a static archive of System.B, you would not have observed this behavior. The System.B.dylib on it's own would not do much; unless you make it as part of an ensemble set of dynamic and static libraries whose functions it makes use of. If you now try to compile your final binary BUT omit the library path '/usr/lib/system' then you linker will cry foul and exit with an error telling you that it cannot find a reference to pthread_XXX() (using your above example). During the final assembling of the binary, it needs to make sure it knows the location of each and every function used. HTH
{ "language": "en", "url": "https://stackoverflow.com/questions/7503249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Call to undefined function time_nanosleep() I have installed php/apache (version 5.3.8) via MacPorts, and I am getting the error: Call to undefined function time_nanosleep() According to the manual: http://us.php.net/manual/en/function.time-nanosleep.php this function has been built into php since version 5, and for Windows 5.3. I'm on a Mac, but in either case I should be good. Is there some magic you have to do to enable this on MacPorts? Is there some extra package you have to install? I'm definitely confused on this one. Any help would be appreciated! A: This is a bug in PHP that was introduced between PHP 5.3.3 and 5.3.4. I have fixed it in MacPorts in php5 @5.3.8_1; run sudo port selfupdate and sudo port upgrade php5 to receive the fix.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: inmobi ads not opening I have incorporated inmobi ads in my android app.in my app i can see the ad from inmobi when i open the app. but when i click on the ad nothing happens. and i checked ddms which tells me this: ActivityNotFoundException. no activity found to handle the intent The following is my code snippet imAdView = new IMAdView(this, IMAdView.INMOBI_AD_UNIT_320X50,"xxxxxxx(my app id kept secret)"); RelativeLayout layout = (RelativeLayout)findViewById(R.id.adview); layout.addView(imAdView); imAdView.setIMAdRequest(adRequest); imAdView.loadNewAd(); do i need to import anything more?? A: I work for InMobi. That all looks ok, but it might be worth following our latest tutorial - http://developer.inmobi.com/wiki/index.php?title=Android
{ "language": "en", "url": "https://stackoverflow.com/questions/7503252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: US national debt clock I repair computers. I've never done any programming, but I've been asked by a customer to set up a computer in his store that does nothing but display the US national debt clock in real time. I found the clock in an SWF format. It says it will allow one to change the text at the top and bottom, which I'd like to do for for him by making the top a title bar and the bottom would hold his store name. The problem is, I don't have the first clue how to do this. Here's the address: http://www.oddhammer.com/tutorials/debt_clock/ I want to have as large as possible " National Debt in Real Time" in the top banner, and "Courtesy of DealMart" in the bottom. Can someone show me how to do this? A: WinKey+R "iexplore http://www.usdebtclock.org/" Enter A: As that page says, you can configure the variables in the FlashVars parameter: <noscript><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" width="340" height="155"> <param name="movie" value="US_debt_clock_dynamic.swf" /> <param name="quality" value="high" /> <PARAM NAME=FlashVars VALUE="topString=National Debt in Real Time&bottomString=Courtesy of DealMart" /> <embed src="US_debt_clock_dynamic.swf" quality="high" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="340" height="155" FlashVars="topString=Hello&bottomString=World"></embed> </object></noscript> You'd better ask the author whether you can display his work re-branded, without attribution, in a public, commercial environment.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: in wordpress, how do I add tags to the divs Class I want to add the post tags into its div class so I can add specific CSS for different types of tags. A: If you want to output the tag name(s) of the article being viewed into a div, do that : <div class=" <?php $posttags = get_the_tags(); if ($posttags) { foreach($posttags as $tag) { echo $tag->name . ' '; } } ?> "> ... </div> If you want to output the tag name that's being display (let's say the tag's page), do that : <div class="<? echo single_tag_title(); ?>"> ..... </div> A: Agreeing with mrtsherman, this question is vague, but if your wanting to name a class you would simply do something like <div class="the-name-you-want"> </div> A: Pass in argument on single_tag_title tag. single_tag_title("<div class="header">"); Its perfectly works on my site.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DoubleClick Event Handler for GWT Grid I am using a gwt grid and Im trying to get the cell that had the onDoubleClick event on it. So if I was doing onClickEvent I would use getCellForEvent(ClickEvent) and that returns a cell. But that method doesnt accept a DoublClickEvent. How do I get the cell that had the onDoubleClick...? A: Extend Grid and use the protected getEventTargetCell to obtain the cell from a NativeEvent instead of a GwtEvent. A: I didn't think of that NativeEvent thing. I hope it's portable across browsers. My DataGrid has an extension of ClickableTextCells. The DClickableTextCell ("D" for double-click) reacts to a double-click, which Microsoft defines as two-clicks within 500 milliseconds. public class DClickableTextCell extends ClickableTextCell { @Override public void onBrowserEvent(com.google.gwt.cell.client.Cell.Context context, Element parent, String value, NativeEvent event, ValueUpdater<String> valueUpdater) { String type = event.getType(); if ((valueUpdater != null) && type.equals("click")) { if (DoubleClickTimer.getInstance().isTimerRunning()) { event.preventDefault(); DoubleClickTimer.getInstance().stopTimer(); valueUpdater.update(value); } else { DoubleClickTimer.getInstance().startTimer(); } } } } If the DoubleClick timer is currently running, then this click must the second click of a double-click. If the DoubleClick timer is not currently running, then this is potentially the first click of a DoubleClick. Start the timer. Here's the code for DoubleClickTimer: public class DoubleClickTimer { private static DoubleClickTimer ref = null; private DoubleClickTimer() { } public static DoubleClickTimer getInstance() { if (ref == null) { ref = new DoubleClickTimer(); } return ref; } private boolean timerRunning = false; private Timer timer = new Timer() { @Override public void run() { timerRunning = false; } }; public void startTimer() { if (!timerRunning) { timer.schedule(500); timerRunning = true; } } public boolean isTimerRunning() { return timerRunning; } public void stopTimer() { timer.cancel(); timerRunning = false; } } It works, but now I'm going to look at extending DataGrid. The problem is that DataGrid refers to protected methods in AbstractCellTable that aren't accessible as soon as you put your DataGrid subclass in a different package. You can bring AbstractCellTable over as well, but then it makes similar references, and you end up copying more stuff. The call to event.preventDefault suppresses the normal behaviour of a double-click, and that is to highlight the widget being clicked on. Since the whole DataGrid is a single widget (cells and columns are not widgets), every bit of text in the DataGrid gets selected unless you prevent that default behaviour. I'm not an expert and I'd like to get advice from people on whether I could be doing this better. But it works, so I'm offering it as a possible answer. A: You'll need to extend the original cell. In the constructor change: super("click", "keyup", "keydown", "blur"); to super("dblclick", "keyup", "keydown", "blur"); and in the onBrowserEvent method change: if ("click".equals(type) || enterPressed) to if ("dblclick".equals(type) || enterPressed)
{ "language": "en", "url": "https://stackoverflow.com/questions/7503258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Sorting by SUM very slow I have the following query: SELECT SUM(s.count) as count, a.name, s.author_id as id FROM twitter_author_daily_stats s JOIN twitter_author a ON s.author_id = a.id WHERE s.`date` >= '2011-01-07' AND s.`date` <= '2011-09-21' AND s.profile_twitter_search_id IN (263) GROUP BY s.author_id LIMIT 30; It uses an index (author_id, profile_twitter_search_id, date); it's fast (~1s); and it returns ~2500 rows. However, when I add ORDER BY count, the query runs for minutes (I didn't bother waiting for it to finish). Shouldn't it just take the ~2500 rows from original query and sort by count column? Why does it take so long? Can someone who has better MySQL knowledge explain? A: Even better: get MySQL to explain it, with the aptly-named EXPLAIN keyword. Optimisations with indexes can only be performed in certain situations, and changing ordering/grouping/conditions is a good way to alter the landscape quite considerably.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to share a Symfony2 model with several projects We are creating a SaaS that monitors certain assets. This means it takes in data, saves it, and displays it in a webinterface. For this, we have a few components that we created with/are moving to Symfony2: * *a frontend web application, where users can view their data *a backend administrative web application, where we create new monitors, users, etc. *an API *an application that retrieves the received data from a queue and puts it in our database (this is now a seperate script, but I'm thinking of reworking this as a Symfony command that is called by cron) All these four applications share the same model: our main database that holds all the users, monitors, and data. My question is: how should I structure these projects in Symfony2? * *Do I create a seperate bundle which holds the entities for my database, and have the four projects include those entities and work with them? *Can I make a 'model' directory in my Symfony app folder, which is used by all the bundles in my /src directory? *Some other, cleaner way to do this? Option 1 seems a bit weird, since a bundle, to my understanding, needs routing, views, controllers, etc. Using it for just entities would be a bit weird. Option 2 seems alright, since the /app folder is considered 'communal' anyway for everything that is in the /src folder (since, for example, parameters reside there as well). However, there is no 'model' folder there, and I'm not sure that there should be? I understand that there are very few 'best practices' out already for Symfony 2, since it's brand new. But I wanted to see if there are any practices more preferable then others, in your opinion. Any feedback is more then welcome. Thanks in advance, Dieter A: What I am currently doing is the first option: create a separate bundle for your entities. That's where I store fixtures, entities, forms and entity-related tests. A bundle does NOT need to have routing, controllers, views etc. I've actually seen a blueprint bundle, and all it does is ship blueprint-css resources with it so they can be easily reused in projects. As for adding models to the app directory... I wouldn't like that. I see the app directory as a place where all the configuration should be. Even though you can override views under app/Resources, whenever I want to override something I create a new bundle. A: I haven't used this technique myself in a real world symfony2 app - but it's a pointer as you asked for any feedback. The service container seems to be the Smyfony2 method to make services available globally. So in your case the model access objects will be defined as services as discussed in the provided link, and then can be used from any bundle. Now in which bundle do the service objects go? We can put them into a separate bundle as they are shared among other bundles. However, I assume the model would not be perfectly symmetrical for all the bundles, so we can put the shared model into a separate bundle, and put bundle specific entities into the bundle itself. Then injection techniques discussed in the link above can be used to provide a full model specific to each bundle. This seems to provide maximum de-coupling. I'm interested in any feedback on this too as it's a common design scenario. Regards.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Having some situations with T4 Templates I am trying to create a T4 Template for a custom controller (with services). However, I am having some issues setting things up. I currently use tangible free T4 tool editor and TextTemplatingFileGenerator as a Custom Tool. I am running into a couple issues when experimenting: 1: I try using MvcTextTemplateHost mvcHost = (MvcTextTemplateHost)(Host); and it says "The type or namespace name MvcTextTemplateHost could not be found (are you missing a using directive or an assembly reference?). It says to clear the Custom tool, but I was wondering how I can view the generated T4 file if I do clear the tool? 2: Another approach was Steve Sanderson's CustomTemplate but I am having issues there with the DynamicTransform not being found and was wondering where I can get the file needed to use it. If i need to clear the tool for this, then how do I view a generated sample file? Thank you very much. Max Gilman Some sample code: <#@ Template Language="C#" HostSpecific="True" Inherits="DynamicTransform" #> <#@ Output Extension="cs" #> using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; namespace someNamespace { <# var modelType = (CodeType)Model.ModelType; var modelName = modelType.Name; var modelNamePlural = Model.ModelTypePluralized; var modelVariable = modelName.ToLower(); var relatedEntities = ((IEnumerable)Model.RelatedEntities).OfType<RelatedEntityInfo>(); var primaryKeyProperty = modelType.VisibleMembers().OfType<CodeProperty>().Single(x => x.Name == Model.PrimaryKey); var routingName = Regex.Replace(Model.ControllerName, "Controller$", "", RegexOptions.IgnoreCase); var isObjectContext = ((CodeType)Model.DbContextType).IsAssignableTo<System.Data.Objects.ObjectContext>(); #> public class foo { //This is a basic comment. } } A: In both cases it looks like you are trying to use a T4 template in your Visual Studio project and use the TextTemplatingFileGenerator as the custom tool to generate the code from the template. 1: The MvcTextTemplatingHost is a custom T4 host that is only available when you use the ASP.NET MVC Add View or Add Controller dialogs. It will not be available nor properly initialized when you use the TextTemplatingFileGenerator custom tool. 2: Steve Sanderson's MvcScaffolding/T4Scaffolding uses its own custom T4 host so you have a similar problem here. If you use the NuGet package manager console with your custom T4 scaffolding template then it should work but it will not work with the TextTemplatingFileGenerator custom tool. The DynamicTransform class itself does not exist. If you take a look at the T4Scaffolding source code on CodePlex, in the InvokeScaffoldTemplateCmdlet class, you will see that the Inherits="DynamicTransform" directive is actually removed and replaced with a reference to a dynamic model object. When you scaffold a controller various properties (e.g. such as Model.ModelType) are setup on the custom host and the dynamic model object before it is passed to the T4 template for processing. In both the above cases the use of the T4 templates with the TextTemplatingFileGenerator is not going to work since they use a custom templating host that needs to be initialized before it can be used by the T4 templates. I think your options are: * *Create a custom ASP.NET MVC T4 template and use the ASP.NET tooling to generate your custom controller using the Add Controller dialog. *Create a custom scaffolding T4 template and use the NuGet Package Manager console to generate your custom controller. *Create your own custom tool that initializes a custom host that can be used from your T4 template. Option 2) is probably your best bet since I believe MvcScaffolding can update existing controller code without removing the existing code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503274", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python import folder I'm using Python 2.6. I'm new at Python programming, so forgive my ignorance. I have multiple directories with multiple packages. My directory structure looks like this: /disconfig __init__.py /LLE __init__.py /DIS __init__.py /Data __init__.py /common __init__.py /LLE __init__.py I need to be able to import both of the LLE directories to make the program work. I can't add disconfig or common to PYTHONPATH because they both have an LLE directory. When I do import LLE, it only pulls in one of them. I've tried doing: import disconfig.LLE it errors saying: Traceback (most recent call last): File "./disconfig.py", line 9, in <module> import disconfig.LLE File "./disconfig.py", line 9, in <module> import disconfig.LLE ImportError: No module named LLE I've tried: import disconfig This works, but when I try to run code from within one of the modules: LLE.DIS.runDisFunc and it comes back saying name 'LLE' not defined If I try: disconfig.LLE.DIS.runDisFunc it says errors with: 'module' object has no attribute 'LLE' I've been working on this for so long and can't wrap my brain around it. Any suggestions? EDIT: Maybe there is one more thing to mention. The files that are in these directories are generated by slice2py from ZeroC. They place all of the generated .py files in the top-level directory (so under /disconfig). The LLE directory has the init.py that has the imports of all of the generated .py files as well as "import DIS" and "import Data". Then in DIS and Data, there are init.py files that include the imports specific to those modules. So, more completely it looks like: /disconfig __init__.py Attribute_ice.py DIS_ice.py DISControl_ice.py /LLE __init__.py /DIS __init__.py /Data __init__.py If I change the module from disconfig to MDIS (as suggested) and do import MDIS I get Traceback (most recent call last): File "./disconfig", line 9, in <module> import MDIS File "/oudvmt/python/MDIS/__init__.py", line 18, in <module> import LLE File "/oudvmt/python/MDIS/LLE/__init__.py", line 4, in <module> import Attribute_ice ImportError: No module named Attribute_ice If I try import MDIS.LLE I get Traceback (most recent call last): File "./disconfig", line 9, in <module> import MDIS.LLE File "/oudvmt/python/MDIS/__init__.py", line 18, in <module> import LLE File "/oudvmt/python/MDIS/LLE/__init__.py", line 4, in <module> import Attribute_ice ImportError: No module named Attribute_ice I've tried moving the generated .py files into the subdirectories, but that caused other problems because the files in /DIS depend on the files in /Data (DIS_ice.py imports Attribute_ice.py, which is part of LLE/Data). If I separate them, I get ImportErrors. More EDIT: I added all of the .py files to my init.py in the /MDIS directory and removed them from the init.py in the subdirectories. Now I have nore more import errors using just "import MDIS". However, now when I try my function disadmin = MDIS.LLE.DIS.DISAdminPrx.checkedCast() I get 'module' object has no attribute 'DISAdminPrx' In DISAdmin_ice.py, there is a class called DISAdminPrx and it does have a method of checkedCast. I tried disadmin = DISAdmin_ice.DISAdminPrx.checkedCast() and disadmin = MDIS.LLE.DIS.DISAdmin_ice.DISAdminPrx.checkedCast() and any other combination I could think of. EDIT AGAIN Looks like it's a problem with the python converter I'm using from ZeroC. They are helping me resolve it. Thanks for the help! A: It appears that your script is named disconfig.py so when you import disconfig you call the script. You should named your script differently from your module. EDIT before disadmin = MDIS.LLE.DIS.DISAdmin_ice.DISAdminPrx.checkedCast() you should do import MDIS.LLE.DIS.DISAdmin_ice or do from MDIS.LLE.DIS.DISAdmin_ice import DISAdminPrx DISAdminPrx.checkedCast() I really think that what I propose work but I can't explain why if someone could explain why in comprehensive words I'm sure the OP would be glad. It is explained in http://docs.python.org/tutorial/modules.html#packages but I'm not sure that is in simple words. A: You need an import LLE statement in disconfig/__init__.py, then import disconfig.LLE should work. A: This will work: import disconfig.LLE.DIS disconfig.LLE.DIS.runDisFunc() This is because Python does not automatically imports subpackages. A: write your own import file then import that this was made to import my scripts. repeat for every folder #scripts os.system("dir /b Scripts\\*.py > dirb.txt") file1=open("dirb.txt","r") file2=open("temp.py","w") for lines in file1.readlines(): lines=lines.strip() string="import Scripts."+str(lines[0:-3]) file2.write(string+"\n") file1.close() file2.close() from temp import * os.system("rem temp.txt")
{ "language": "en", "url": "https://stackoverflow.com/questions/7503275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Xml.Linq: Descendants() returns nothing I am trying to read from an ncx file (i.e. xml file) using XElement: XElement foundNode = ncx.Descendants("navPoint").Where(r => r.Attribute("class").Value == "chapter").FirstOrDefault(); As a result, foundNode is null because ncx.Descendants("navPoint") returns an empty enumeration. But the data is there: <?xml version='1.0' encoding='utf-8'?> <ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1" xml:lang="en"> <head> <meta content="8eab2efe-d584-478a-8c73-1304d2ae98fa" name="dtb:uid"/> <meta content="3" name="dtb:depth"/> <meta content="calibre (0.8.12)" name="dtb:generator"/> <meta content="0" name="dtb:totalPageCount"/> <meta content="0" name="dtb:maxPageNumber"/> </head> <docTitle> <text>Fine</text> </docTitle> <navMap> <navPoint class="chapter" id="27665f37-ecf5-4934-a044-4f77152e54d9" playOrder="1"> <navLabel> <text>I. BLIND</text> </navLabel> <content src="Fine_split_003.html"/> Could you please explain what is wrong here? Thanks. A: You can also strip out namespaces or refer to elements without using the namespace by using the XElement.Name.LocalName property: Examples here A: You need to take namespace in XML into account: XDocument ncx = XDocument.Load("file.xml"); XNamespace df = ncx.Root.Name.Namespace; XElement foundNode = ncx.Descendants(df + "navPoint").Where(r => r.Attribute("class").Value == "chapter").FirstOrDefault();
{ "language": "en", "url": "https://stackoverflow.com/questions/7503276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Best way of logging exceptions when tests fail (e.g. using a junit rule) When I'm running a complete test suite, it would be helpful if exceptions that caused a test to fail would appear in my (SLF4J-)log. What is the best method to achieve this? What I would like is a junit4 rule that handles exception logging for me. The code @Rule public TestRule logException = new TestWatcher() { @Override public void failed(Description d) { catch (Exception e) { logger.error("Test ({}) failed because of exception {}", d, e); throw e; } } } of course does not work, since I can only catch exceptions out of a try block. Is there a workaround to somehow achieve this in a similarly simple and general way? BTW, what I'm doing right now is logging the exception the moment it is created. But it would be nicer to log exceptions at the interface between caller and the library, so in my case in the test case. Not logging when the exceptions are created would also guarantee that they don't show up multiple times when the caller decides to log them. A: Look outside the box... What are you using to run the tests? Most environments for running tests (e.g., Ant, Jenkins, Maven, etc.) have means for using a testrunner that outputs an XML file, with support for aggregating the XML files from a suite into a comprehensive report. A: You need to extend TestRule, in particular the apply(). For an example, have a look at org.junit.rules.ExternalResource & org.junit.rules.TemporaryFolder. ExternalResource looks like this: public abstract class ExternalResource implements TestRule { public Statement apply(Statement base, Description description) { return statement(base); } private Statement statement(final Statement base) { return new Statement() { @Override public void evaluate() throws Throwable { before(); try { base.evaluate(); } finally { after(); } } }; } /** * Override to set up your specific external resource. * @throws if setup fails (which will disable {@code after} */ protected void before() throws Throwable { // do nothing } /** * Override to tear down your specific external resource. */ protected void after() { // do nothing } } TemporaryFolder then extends this and implements before() and after(). public class TemporaryFolder extends ExternalResource { private File folder; @Override protected void before() throws Throwable { // create the folder } @Override protected void after() { // delete the folder } So the before gets called before the testMethod, and the after is called in the finally, but you can catch and log any Exception, like: private Statement statement(final Statement base) { return new Statement() { @Override public void evaluate() throws Throwable { before(); try { base.evaluate(); } catch (Exception e) { log.error("caught Exception", e); } finally { after(); } } }; } EDIT: The following works: public class SoTest { public class ExceptionLoggingRule implements TestRule { public Statement apply(Statement base, Description description) { return statement(base); } private Statement statement(final Statement base) { return new Statement() { @Override public void evaluate() throws Throwable { try { base.evaluate(); } catch (Exception e) { System.out.println("caught an exception"); e.printStackTrace(System.out); throw e; } } }; } } @Rule public ExceptionLoggingRule exceptionLoggingRule = new ExceptionLoggingRule(); @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void testMe() throws Exception { expectedException.expect(IOException.class); throw new IOException("here we are"); } } The test passes and you get the following output: caught an exception java.io.IOException: here we are at uk.co.farwell.junit.SoTest.testMe(SoTest.java:40) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) ... The order that the rules are applied is ExpectedException which calls ExceptionLoggingRule which calls the testMe method. The ExceptionLoggingRule catches the Exception, logs it and rethrows it, and it is then processed by ExpectedException. If you want to log only unexpected exceptions, you just switch the declaration order of the rules: @Rule public ExpectedException expectedException = ExpectedException.none(); @Rule public ExceptionLoggingRule exceptionLoggingRule = new ExceptionLoggingRule(); That way, expectedException is applied first (i.e. nested in exceptionLoggingRule), and only rethrows exceptions that are not expected. Furthermore, if some exception was expected and none occured, expectedException will throw an AssertionError which will also get logged. This evaluation order isn't guaranteed, but it is quite unlikely to vary unless you're playing with very different JVMs, or inheriting between Test classes. If the evaluation order is important, then you can always pass one rule to the other for evaluation. EDIT: With the recently released Junit 4.10, you can use @RuleChain to chain rules correctly: public static class UseRuleChain { @Rule public TestRule chain= RuleChain .outerRule(new LoggingRule("outer rule") .around(new LoggingRule("middle rule") .around(new LoggingRule("inner rule"); @Test public void example() { assertTrue(true); } } writes the log starting outer rule starting middle rule starting inner rule finished inner rule finished middle rule finished outer rule A: This seems so easy that I think I am wrong and you are asking something different, but maybe I can help: JUnit 4.X @Test(expected=Exception.class) is going to pass the test if the exception is thrown in the test, or fail with a message captured by the Junit framework
{ "language": "en", "url": "https://stackoverflow.com/questions/7503277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Allow Some Special Characters using Regex The following regex matches any Unicode Letters + Unicode Numbers + Vowel Signs + Dot + Dash + Underscore + Space /^[\w\pN\pL\pM .-]+$/u Works successfully. I want to edit my regex so it accepts the following: ? ! ( ) % @ # , + - : newline - represents negative sign. My attempt doesn't work: /^[\w\pN\pL\pM .-**?!()%@#,+-:\r**]+$/u Here is my snippet with latest attempt: if(preg_match('/^[\w\pN\pL\pM .-?!()%@#,+-:\r]+$/u', $_POST['txtarea_msg'])) Any idea? A: - is a metacharacter in character classes, so you're saying: blahblahblah all characters from . to ? blahblahblah all characters from + to : blah blah It needs to be escaped with a \: blahblah .\-? blahblah +\-: blahblah A: /^[\w\pN\pL\pM \?!\(\)%@#,\+\-:\n\r]+$/u should do it. A: Some of these are regular expression characters, so you need to escape them: /^[\w\pN\pL\pM .?!()%@#,+\-:\r]+$/u Also note the difference between a newline (\n) and carriage return (\r).
{ "language": "en", "url": "https://stackoverflow.com/questions/7503278", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery UI modal problem I'm trying to bind a keypress ("enter") to trigger a function in a jQuery modal object. In the code below, I want $(this).dialog("login") to fire when the keypress event is detected. However it seems that I'm unable to call self.dialog("login"). Am I looking at this the wrong way? $("#login-dialog").dialog({ autoOpen: false, height: 250, width: 350, modal: true, open: function() { var self = $(this); $("#login-dialog").load("/accounts/login/", function() { $("#id_username").focus() .keypress(function(event) { if (event.which == 13) { event.preventDefault(); self.dialog("login"); } }); }); }, buttons: { close: function() { $(this).dialog("close"); }, login: function() { $.ajax({ type: "POST", url: "/accounts/login/", data: $("#login-form").serialize(), success: function(data) { var errors = $(data).find("#login-error").val(); if (errors) { $("#error-message").replaceWith("<p class='error'>" + "Your username and password didn't match" + "</p>"); } else { window.location = "/builder"; } } }); } } }); A: I would attach a handler to the onsubmit event of the login form. With this handler, call the login function with the appropriate field values (prevent default on the event so form doesn't actually submit). Now, a nice side effect of this is that pressing ENTER when on the form, that handler will get called. This approach also degrades a bit better and makes all your code more portable. Personally, I use a plugin that you just pass a form element into that will send it via ajax using all the form attributes and input elements. A: A quick work around for your problem, inside "keypress" function use the following code $("#login-dialog").dialog("option").buttons.login();
{ "language": "en", "url": "https://stackoverflow.com/questions/7503283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I debug a serialization error in a WebServiceHost? I've got a self-hosted WebServiceHost defined like so: var baseWebHttpBindingBase = "http://localhost:8085/MyService"); var wsEndPoint = new EndpointAddress(baseWebHttpBindingBase); var binding = new WebHttpBinding(); wsHost = new WebServiceHost(lsWsService, new Uri(baseWebHttpBindingBase)); wsHost.Faulted += new EventHandler(wsHost_Faulted); wsHost.UnknownMessageReceived += new EventHandler<UnknownMessageReceivedEventArgs>(wsHost_UnknownMessageReceived); ServiceDebugBehavior sdb = host.Description.Behaviors.Find<ServiceDebugBehavior>(); sdb.IncludeExceptionDetailInFaults = true; // Mex endpoint ServiceMetadataBehavior mexBehavior = new ServiceMetadataBehavior(); mexBehavior.HttpGetEnabled = true; wsHost.Description.Behaviors.Add(mexBehavior); wsHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), baseWebHttpBindingBase + "mex"); wsHost.Open(); I've got an OperationContract defined: [OperationContract] [WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, Method = "PUT", UriTemplate = "/handShake")] public ConfigSettings handShake(ClientInformationDto clientInfo) { var configSettings = new ConfigSettings(); // set configSettings values; return configSettings; } ConfigSettings has some misc. properties, mostly defined as strings and ints. There's one property though that is named complexClasses of type List<ComplexClass> - if complexClasses is null, then the client can consume the webservice just fine. However, if I populate complexClasses, the attempt to consume the webservice never completes - watching it in Fiddler just shows a generic ReadResponse() failed: The server did not return a response for this request. When I debug the code, I get to the return statement and when I do the final step out, Fiddler reports to above error. I know the problem is related to my ComplexClass in configSettings. The service continues to run just fine, and even after enabling Studio's "break on all exceptions" feature nothing ever breaks. Is there anyway to debug whatever happens after returning (most likely in the serialization stage) that is causing my service to fail to return anything? A: It is possible that ComplexClass is not serialized properly. ComplexClass needs to be exposed with Serialization attributes. [DataContract] public class ComplexClass { [DataMember] public string Field { get; set; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7503290", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to format cells in excel sheet programmatically? We have an asp.net c# program that reads a sheet from an Excel file and writes it out in a new sheet (also adding one column if data come from a Sql Server table). Issue: in the new sheet the data is not formatted as we want. For example we want date without time and left-aligned, but they're formatted with the time and right-aligned, etc. How can we format an Excel cell? This is our code: newSheet = (Worksheet)sheets.Add(sheets[1], Type.Missing, Type.Missing, Type.Missing); newSheet.Name = worksheetName; for (int i = 0; i < headerList.Count; i++) { newSheet.Cells[1, i + 1] = headerList[i]; Range headerRange = newSheet.Cells[1, headerList.Count]; ; headerRange.Font.Bold = true; } for (int i = 0; i < listDrugOrder.Count; i++) { DrugOrder drugorder = listDrugOrder[i]; newSheet.Cells[i + 2, 1] = drugorder.RES_ID; newSheet.Cells[i + 2, 2] = drugorder.STATION; newSheet.Cells[i + 2, 3] = drugorder.DATE; newSheet.Cells[i + 2, 4] = drugorder.DRUG; newSheet.Cells[i + 2, 5] = drugorder.NDC; newSheet.Cells[i + 2, 6] = drugorder.UNITS_PER_DOSE; newSheet.Cells[i + 2, 7] = drugorder.FORM; newSheet.Cells[i + 2, 8] = drugorder.ROUTE; newSheet.Cells[i + 2, 10] = drugorder.FREQUENCY; newSheet.Cells[i + 2, 11] = drugorder.Heading_LAKE_ORDERS; newSheet.Cells[i + 2, 12] = drugorder.HOA; newSheet.Cells[i + 2, 13] = drugorder.INSTRUCTIONS; newSheet.Cells[i + 2, 14] = drugorder.DIAGNOSIS; newSheet.Cells[i + 2, 15] = drugorder.DIAGNOSIS_CODES; newSheet.Cells[i + 2, 16] = drugorder.MAR; newSheet.Cells[i + 2, 17] = drugorder.TAR; newSheet.Cells[i + 2, 18] = drugorder.DRUG_ALERT; } workbook.Save(); workbook.Close(null, null, null); excelApp.Quit(); A: Just set the appropriate property on your cell (Range) objects. Set NumberFormat to control the cell number formatting, i.e.: newSheet.Cells[i, j].NumberFormat = "m/d/yyyy" Set HorizontalAlignment to control the alignment, i.e.: newSheet.Cells[i, j].HorizontalAlignment = ExcelAlignment.xlLeft; //or Excel.XlHAlign.xlHAlignLeft
{ "language": "en", "url": "https://stackoverflow.com/questions/7503298", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: List to IEnumerable problem in interface namespace WpfApplication3 { public class Hex { public String terr; } public class HexC : Hex { int Cfield; } public interface IHexGrid { IEnumerable<Hex> hexs { get; } } public class hexGrid : IHexGrid //error CS0738: 'WpfApplication3.hexGrid' does not { public List<Hex> hexs { get; set; } } public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); List<HexC> hexList1 = new List<HexC>(); genmethod(hexList1); //but this compiles fine } void genmethod(IEnumerable<Hex> hexList) { string str1; foreach (Hex hex in hexList) str1 = hex.terr; } } } The full error message is: 'WpfApplication3.hexGrid' does not implement interface member 'WpfApplication3.IHexGrid.hexs'. 'WpfApplication3.hexGrid.hexs' cannot implement 'WpfApplication3.IHexGrid.hexs' because it does not have the matching return type of 'System.Collections.Generic.IEnumerable'. Why doesn't List implicitly cast to IEnumerable above? Thanks in advance! A: That kind of casting (covariance?) doesn't apply to class/interface declarations. It can only be done on parameters and return types. The compiler is looking for the exact signature, isn't finding it, and rightly saying you didn't implement the member. The property/method signature must match exactly. This answer actually sums it up better than I could explain. A: Christopher has the right answer, but you could easily work around this by having a private property be the actual list and then the getter on the hexGrid just return the casted IEnumerable interface from the List. public class hexGrid : IHexGrid { private List<Hex> _hexs { get; set; } public IEnumerable<Hex> hexs { get { return _hexs as IEnumerable; } set { _hexs = new List<Hex>( value ); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7503300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to get base url in CodeIgniter 2.* In config.php $config['base_url'] = 'http://localhost/codeigniter/'; In View <link rel="stylesheet" href="<?php base_url(); ?>css/default.css" type="text/css" /> => Error: Call to undefined function base_url(); Help me A: To use base_url() (shorthand), you have to load the URL Helper first $this->load->helper('url'); Or you can autoload it by changing application/config/autoload.php Or just use $this->config->base_url(); Same applies to site_url(). Also I can see you are missing echo (though its not your current problem), use the code below to solve the problem <link rel="stylesheet" href="<?php echo base_url(); ?>css/default.css" type="text/css" /> A: I know this is very late, but is useful for newbies. We can atuload url helper and it will be available throughout the application. For this in application\config\autoload.php modify as follows - $autoload['helper'] = array('url'); A: You need to load the URL Helper in order to use base_url(). In your controller, do: $this->load->helper('url'); Then in your view you can do: echo base_url(); A: Just load helper class $this->load->helper('url'); thats it. A: You need to add url helper in config/autoload $autoload['helper'] = array('form', 'url', 'file', 'html'); <-- Like This Then you can use base_url or any kind of url.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "40" }
Q: jQuery DataTables: How to get row index (or nNode) by row id of tr? I have a dataTables <table id="myTable">. I would like to fnUpdate() and fnDestroy() my rows. every row has an id, eg: <tr id="16">. To fnUpdate()/fnDestroy() the appropriate <tr>, I need to get that row's index. For this I try to use fnGetPosition(), but the way I try it is not the way to do it: $("#myTable").fnGetPosition( $("#16") ) results in TypeError: nNode.nodeName is undefined [Break On This Error] var sNodeName = nNode.nodeName.toUpperCase(); Which makes sense, as fnGetPosition() expexts nNode (in my case a HTMLTableRowElement). How do I get the HTMLTableRowElement that has id="16" ? EDIT: A correct answer to my question is: document.getElementById("16"). Based on that, I would like to change my question to: Why does $("#myTable").fnGetPosition( document.getElementById("16") ) work, but $("#myTable").fnGetPosition( $("#16") ) fails? A: For anyone who still has this problem, try this: $("#myTable").fnGetPosition( $("#16")[0] ) To get the same result as document.getElementById you should access the first element in the jQuery object. A: document.getElementById() returns a DOM object, and everything on the DOM object will be inherently accessible. JQuery's $('#...') returns a wrapper around a single DOM object OR a set of DOM objects (depending on the selector) and as such, it does not return the actual DOM Object. It makes it easier to work with DOM objects. The reason you are getting that error in the second case would be that $(#...) is not actually a DOM object. A: You sould do: var oTable = $('#myTable').dataTable(); oTable.fnGetPosition( $("#myTable #16") );
{ "language": "en", "url": "https://stackoverflow.com/questions/7503306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How can I process a file uploaded through an HTML form in Spray/Scala/Java? I have an application written using Spray, and I have a page which has an <input type="file" name="foo"> form element that gets POSTed to /fileUpload. I have a Spray route set up to listen to the path /fileUpload using this code: path("fileUpload") { get { ctx => { val request: HttpRequest = ctx.request //Process the file, somehow with request? ctx.complete("File Uploaded") }} } I can't figure out how to get the POST body and get a handle on the file, and I can't find any examples online. It must be possible to receive a file and process it with Spray or even through simple Scala or Java, but I don't know how to do it. Can anybody help? Thanks! A: It's possible with Spray, although I haven't checked if streaming works properly. I fiddled a bit and got this working: post { content(as[MultipartFormData]) { def extractOriginalText(formData: MultipartFormData): String = { formData.parts.mapValues { (bodyPart) => bodyPart.content.map{ (content) => new String(content.buffer) } }.values.flatten.foldLeft("")(_ + _) } formData => _.complete( extractOriginalText(formData) ); } If you upload a plain text file to a service that has this code in it, it coughs the original text back up. I've got it running together with an ajax upload; it should also work with an old fashioned file upload form. It seems to me that there must be an easier way to do this, particularly the deep nesting of the content is rather clunky. Let me know if you find a simplification. UPDATE (thx akauppi): entity(as[MultipartFormData]) { formData => complete( formData.fields.map { _.entity.asString }.flatten.foldLeft("")(_ + _) ) } A: I ended up using the code below. Wasn't too hard, but there really should have been a Spray sample available somewhere about this. multipart/form-data forms must always be used (instead of the traditional application/x-www-form-urlencoded) if binary uploads are involved. More details here. My requirements were: * *need to upload binary files of reasonably large size *wanted to have metadata as fields (not embedded in URL or the upload's filename) Some questions: * *is the way I'm managing errors the "best" way? It's in the essence of REST API design to treat the client as a "human" (in debugging, we are), giving meaningful error messages in case something is wrong with the message. post { // Note: We cannot use a regular 'return' to provide a routing mid-way. The last item matters, but we can // have a 'var' which collects the correct success / error info into it. It's a write-once variable. // var ret: Option[Route] = None // Multipart form // // To exercise this: // $ curl -i -F "file=@filename.bin" -F "computer=MYPC" http://localhost:8080/your/route; echo // entity(as[MultipartFormData]) { formData => val file = formData.get("file") // e.g. Some( // BodyPart( HttpEntity( application/octet-stream, ...binary data..., // List(Content-Type: application/octet-stream, Content-Disposition: form-data; name=file; filename=<string>))) log.debug( s".file: $file") val computer = formData.get("computer") // e.g. Some( BodyPart( HttpEntity(text/plain; charset=UTF-8,MYPC), List(Content-Disposition: form-data; name=computer))) log.debug( s"computer: $computer" ) // Note: The types are mentioned below simply to make code comprehension easier. Scala could deduce them. // for( file_bodypart: BodyPart <- file; computer_bodypart: BodyPart <- computer ) { // BodyPart: http://spray.io/documentation/1.1-SNAPSHOT/api/index.html#spray.http.BodyPart val file_entity: HttpEntity = file_bodypart.entity // // HttpEntity: http://spray.io/documentation/1.1-SNAPSHOT/api/index.html#spray.http.HttpEntity // // HttpData: http://spray.io/documentation/1.1-SNAPSHOT/api/index.html#spray.http.HttpData log.debug( s"File entity length: ${file_entity.data.length}" ) val file_bin= file_entity.data.toByteArray log.debug( s"File bin length: ${file_bin.length}" ) val computer_name = computer_bodypart.entity.asString //note: could give encoding as parameter log.debug( s"Computer name: $computer_name" ) // We have the data here, pass it on to an actor and return OK // ...left out, application specific... ret = Some(complete("Got the file, thanks.")) // the string doesn't actually matter, we're just being polite } ret.getOrElse( complete( BadRequest, "Missing fields, expecting file=<binary>, computer=<string>" ) ) } } A: Ok, after trying to write a Spray Unmarshaller for multipart form data, I decided to just write a scala HttpServlet that would receive the form submission, and used Apache's FileUpload library to process the request: class FileUploadServlet extends HttpServlet { override def doPost(request: HttpServletRequest, response: HttpServletResponse) { val contentType = request.getContentType val boundary = contentType.substring(contentType.indexOf("boundary=")+9) val multipartStream = new MultipartStream(request.getInputStream, boundary) // Do work with the multipart stream } } A: To grab the posted (possibly binary) file, and stick it somewhere temporarily, I used this: post { entity(as[MultipartFormData]) { formData => { val ftmp = File.createTempFile("upload", ".tmp", new File("/tmp")) val output = new FileOutputStream(ftmp) formData.fields.foreach(f => output.write(f.entity.data.toByteArray ) ) output.close() complete("done, file in: " + ftmp.getName()) } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7503307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Get the nth string of text between 2 separator characters I have a long string of text delimited by a character (pipe character). I need to get the text between the 3rd and 4th pipes. Not sure how to go about this... Open to regex or non-regex, whichever is the most efficient. Especially open to extension method if none exist to be able to pass in: * *seperatorChar *index A: If string textBetween3rdAnd4thPipe = "zero|one|two|three|four".Split('|')[3]; doesn't do what you mean, you need to explain in more detail. A: This regex will store the text between the 3rd and 4th | you want in $1 /(?:([^|]*)|){4}/ Regex r = new Regex(@"(?:([^|]*)|){4}"); r.match(string); Match m = r.Match(text); trace(m.Groups[1].captures); A: Try This public String GetSubString(this String originalStirng, StringString delimiter,Int32 Index) { String output = originalStirng.Split(delimiter); try { return output[Index]; } catch(OutOfIndexException ex) { return String.Empty; } } A: You could do string text = str.Split('|')[3]; where str is your long string. A: Here's my solution, which I expect to be more efficient than the others because it's not creating a bunch of strings and an array that are not needed. /// <summary> /// Get the Nth field of a string, where fields are delimited by some substring. /// </summary> /// <param name="str">string to search in</param> /// <param name="index">0-based index of field to get</param> /// <param name="separator">separator substring</param> /// <returns>Nth field, or null if out of bounds</returns> public static string NthField(this string str, int index, string separator=" ") { int count = 0; int startPos = 0; while (startPos < str.Length) { int endPos = str.IndexOf(separator, startPos); if (endPos < 0) endPos = str.Length; if (count == index) return str.Substring(startPos, endPos-startPos); count++; startPos = endPos + separator.Length; } return null; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7503310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 404 Directory not found error in Dynamics CRM IFD login The problem is as follows: * *I can access the https:// url to see an ADFS login page *When I enter the proper credentials, the browser shows that the Dynamics CRM 2011 almost loads in and then displays "404 Directory not found" The amazing thing is - * *I am able to access the CRM site through my Outlook during this period (when it does not go through in the browser). *I am able to login successfully using the same credentials from a different user account on my laptop or any other computer. What on earth is the matter here? Yelp! A: I assume that the error goes away when you reload the page and "Almost loads" means that the navigation is loaded, but the content area shows a HTTP 404. There are some issues with this symptoms which are fixed in Rollup 1. Another issue with a similar symptom will be fixed in Rollup 6 (which is not yet released).
{ "language": "en", "url": "https://stackoverflow.com/questions/7503314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change class AND hide div on one click? I've recentley learnt how to change a class on a click, however i'm now trying something a little more tricky and getting stuck. I need to change the class on a button click, but also hide a div at the same time. Here's what I have so far: <script type="text/javascript"> $('button').click(function(e) { if ($(this).hasClass('grid')) { $('#primary ul').removeClass('stylelist').addClass('grid'); $('#single-style-text').hide(); } else if($(this).hasClass('list')) { $('#primary ul').removeClass('grid').addClass('stylelist'); $('#single-style-text').show(); } }); </script> The div #single-style-text is what i'm trying to hide whenever the grid class is active, and have it show when the stylelist class is active. Is there a better way to write this code? Thanks A: i'd try something like this: $('button').click(function(e) { var button = $(this); var hasGrid = button.hasClass('grid'); $('#primary ul') .toggleClass('stylelist', hasGrid) .toggleClass('stylegrid', !hasGrid); button .toggleClass('list', hasGrid) .toggleClass('grid', !hasGrid); $('#single-style-text').toggle(hasGrid); }); can give a more specific example if i see some more markup... but this is the basics by toggling classes... example on jsfiddle: http://jsfiddle.net/Xc7pH/2/ A: That looks pretty good to me. You could do things a little more efficiently by caching your selectors. E.g., // assuming these don't change, cache these outside of click handler // so that we only have to run these queries once, rather than on // every click var $primary = $('#primary ul'), $single = $('#single-style-text'); $('button').click(function(e) { var $this = $(this); if ($this.hasClass('grid')) { $primary.removeClass('stylelist').addClass('grid'); $single.hide(); } else if($this.hasClass('list')) { $primary.removeClass('grid').addClass('stylelist'); $single.show(); } }); A: Make a style that hides, apply it when you need it and take it away when you don't. <style ...> .noSeeum { display:none } </style> <script ... $('button').click(function(e) { if($(this).hasClass('grid')) { $('#primary ul').removeClass('stylelist').addClass('grid').addClass('noSeeum'); } else if($(this).hasClass('list')) { $('#primary ul').removeClass('grid').addClass('stylelist').removeClass('noSeeum'); } }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7503316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I create a list of structures automatically with R? Lets say that RES is a list with capacity for 1000 structs that function kmeans generates as output. How do I declare RES? After having RES declared I want to do something like this: for (i in 1:1000) { RES[i] = kmeans(iris,i) } Thank you. Rui A: If you use the R apply idiom, your code will be simpler and you don't have to declare your variable in advance: RES <- lapply(1:3, function(i)kmeans(dist(iris[, -5]),i)) The results: > str(RES) List of 3 $ :List of 7 ..$ cluster : Named int [1:150] 1 1 1 1 1 1 1 1 1 1 ... .. ..- attr(*, "names")= chr [1:150] "1" "2" "3" "4" ... ..$ centers : num [1, 1:150] 2.89 2.93 3.04 2.96 2.93 ... .. ..- attr(*, "dimnames")=List of 2 .. .. ..$ : chr "1" .. .. ..$ : chr [1:150] "1" "2" "3" "4" ... ..$ totss : num 55479 ..$ withinss : num 55479 ..$ tot.withinss: num 55479 ..$ betweenss : num 4.15e-10 ..$ size : int 150 ..- attr(*, "class")= chr "kmeans" $ :List of 7 ..$ cluster : Named int [1:150] 1 1 1 1 1 1 1 1 1 1 ... .. ..- attr(*, "names")= chr [1:150] "1" "2" "3" "4" ... ..$ centers : num [1:2, 1:150] 0.531 4.104 0.647 4.109 0.633 ... .. ..- attr(*, "dimnames")=List of 2 .. .. ..$ : chr [1:2] "1" "2" .. .. ..$ : chr [1:150] "1" "2" "3" "4" ... ..$ totss : num 55479 ..$ withinss : num [1:2] 863 9743 ..$ tot.withinss: num 10606 ..$ betweenss : num 44873 ..$ size : int [1:2] 51 99 ..- attr(*, "class")= chr "kmeans" $ :List of 7 ..$ cluster : Named int [1:150] 2 2 2 2 2 2 2 2 2 2 ... .. ..- attr(*, "names")= chr [1:150] "1" "2" "3" "4" ... ..$ centers : num [1:3, 1:150] 3.464 0.5 5.095 3.438 0.622 ... .. ..- attr(*, "dimnames")=List of 2 .. .. ..$ : chr [1:3] "1" "2" "3" .. .. ..$ : chr [1:150] "1" "2" "3" "4" ... ..$ totss : num 55479 ..$ withinss : num [1:3] 2593 495 1745 ..$ tot.withinss: num 4833 ..$ betweenss : num 50646 ..$ size : int [1:3] 62 50 38 ..- attr(*, "class")= chr "kmeans" A: I'll second that lapply is the right answer in this case. But there are many scenarios where a loop is necessary, and it's a good question. R lists don't need to be declared as empty ahead of time, so the easiest way to do this would to just 'declare' RES as an empty list: RES <- list() for (i in 1:1000) { RES[i] = kmeans(iris,i) } R will just extend the list for each iteration. Incidentally, this works even for non-sequential indexing: newList <- list() newList[5] <- 100 yields a list with slots 1 through 4 designed as NULL and the number 100 in the fifth slot. This is all just to say that lists are very different beasts in R than the atomic vectors. A: The way to create a list is unfortunately different from the usual way of creating a numeric vector. # The "usual" way to create a numeric vector myNumVec <- numeric(1000) # A numeric vector with 1000 zeroes... # ...But there is also this way myNumVec <- vector("numeric", 1000) # A numeric vector with 1000 zeroes... # ...and that's the only way to create lists: # Create a list with 1000 NULLs RES <- vector("list", 1000) So your example would become, RES <- vector("list", 1000) for (i in 1:1000) { RES[[i]] = kmeans(iris,i) } (Note that kmeans doesn't like to be called with the iris data set directly like that though...) But then again, lapply would do it too and in a more direct way as @Andrie showed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Back button skipping php pages I have a website that consists of entirely php pages. If you do the following: Google -> php page1 -> php page2 -> hit the browser back button and you go back to Google I want the user to get taken back to php page1 instead of Google when they hit the back button on php page2. I have a feeling this is to do with the automatic scripts, generated by php, that stop the browser caching pages. However, I don't want the pages to be cached as this would stop the content being updated. Thanks for any advice! A: function goToTag(tagid, tagloc){ location.replace("main.php?tagid="+tagid+"&result="+tagloc); } Switch it to location.href="main.php?tagid="+tagid+"&result="+tagloc; and you'll be just fine. location.replace does what it says on the tin - it replaces the current history item with the new page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add subscript/superscript to buttons label in flex? I need to add subscript or superscript and normal text to buttons label. But as far as I understand button's label property is simple label, if it was RichText it would be easy. I need subscript/superscript + normal text. Also I can't use 2 labels in skin class, I can only have 1 label or 1 RichText in skin class because as far as I understand labelDisplay works only for one label in skin class. Plus my button isn't constant. So guys any ideas on how to get that done for button? A: Here is the solution I found: * *Download & install GG Subscript & GG Superscript TrueType fonts. You will need to restart Flash software after installed fonts. *Create a text field with Arial font embeded. Set the HTML property to true. *Create a dynamic text field with GG Subscript font embeded. *Create a dynamic text field with GG Superscript font embeded. *Use htmltext to set text to subscript or superscript like below: my_txt.text = "Adobe<font face=\"GG Superscript\">TM</font>" This is old solution for text fields. mx:Label supports htmltext, it may work. I think.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it possible to add something above the Facebook Wall? I'm close to what I want at https://www.facebook.com/wheeleez?sk=app_107608005997641 I want to put these videos above my wall, but still retain all the functionality of the wall. The Share / "Write Something..." I'm using this Facebook app: https: //apps.facebook.com/wheeleez-videos/ for which the canvas is https: //www.wheeleez.com/facebook/video-wall/ But I'm losing the "Write something..." I'm using the plugin from http: //www.neosmart.de/social-media/fb-wall to put my wall on https: //www.wheeleez.com/facebook/video-wall/ Here's a jpg mockup of exactly what I'm trying to do http://wheeleez.com/images/FacebookAppScreenshot.jpg Is there any way to do this? Thanks, Scott A: I don't have a solution to make it work, but in my opinion this seems like something that should be in a different tab. You can make a FBML tab that the user will see when they visit your page for the first time and put those videos there. You may be able to have that be the default tab all the time, not sure. I hope that helps. That solution works well for a lot of pages.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Byte Array being returned in XML, Extract? I have a byte array being returned by a rest service. The issue is that it is being encoded into XML. Is there anyway to extract the byte array from the XML without losing its represented file structure? Or am I doomed to work with a string? If so is there any way to convert the string to the byte array so I can create the file it represents? Thanks!!!! A: To embed a byte array into an XML file, your best option is to encode the array into a string, via a hex encoder, or a base64 encoder. A hex encoder would accept an array like {0xEF, 0x12, 0x5A} into a string like "EF125A". The base64 encoder will do something similar, but will produce a smaller string. Then you would do the converse in order to read the xml file. Depending on your language and platform, there are different ways to do the encoding and decoding.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can you create templates in VIM with placeholders? Can you create a template in VIM with placeholders, and then it would cycle through the placeholders so you can fill in the content. If the placeholder was used elsewhere, that would automatically get filled in since you already provided a definition for that placeholder. example: public class $CLASSNAME$ { public $CLASSNAME$ { } } A: There are plenty of snippets plugins for vim. You could try snipmate or snippetsemu for example. A: The vim plugin snipmate already does precisely what you want to do. (Take a look at the screencast) Edit: Changed to active github repo of vim-snipmate (thanks Peter Rincker)
{ "language": "en", "url": "https://stackoverflow.com/questions/7503329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can you round up a number and display it as a percentage? I'm a bit rusty on my mathematics so I hope someone can help me. Using the code below I would like to do the following: Depending on the amount of memory installed, I would like to display the percentage of available memory and not how much is left in megabytes. private void timer1_Tick(object sender, EventArgs e) { string memory; int mem; memory = GetTotalMemoryInBytes().ToString(); mem = Convert.ToInt32(memory); mem = mem / 1048576; progressBar2.Maximum = mem; progressBar2.Value = mem - (int)(performanceCounter2.NextValue()); label2.Text = "Available Memory: " + (int)(performanceCounter2.NextValue()) + "Mb"; } //using Microsoft visual dll reference in c# static ulong GetTotalMemoryInBytes() { return new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory; } A: To get a percentage, you use: part/total * 100, eg: var Info = Microsoft.VisualBasic.Devices.ComputerInfo(); var PercentAvailable = Info.AvailablePhysicalMemory*1.0/Info.TotalPhysicalMemory * 100; var PercentLeft = 100 - PercentAvailable; // or alternatively: var PercentLeft = (1 - Info.AvailablePhysicalMemory*1.0/Info.TotalPhysicalMemory) * 100; A: (Available memory / Total memory) * 100 will be your percentage. double percent = ((performanceCounter2.NextValue() * 1.0) / mem) * 100; label2.Text = "Available Memory: " + percent; A: mem / memory would be the percentage of used memory. To get the available memory percentage, its 1 minus the result of that. But likely need a double for that. A: For most new machines, the total memory in bytes is at least 2GB. This does not fit into an Int32, so you won't work. Since you want to round up, you should use Math.Ceiling. ulong total = My.Computer.Info.TotalPhysicalMemory; ulong available = My.Computer.Info.AvailablePhysicalMemory; int pctAvailable = (int)Math.Ceiling((double)available * 100 / total); int pctUsed = (int)Math.Ceiling((double)(total - available) * 100 / total);
{ "language": "en", "url": "https://stackoverflow.com/questions/7503331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JavaScript Closure - Eval() and capturing variables in Eval()'s scope My question is regarding JavaScript Closures and the Eval() function. I have some code that looks like this, there is also some other jQuery plugin related code taht is not shown. I can update the question with more code if needed. var _CurrentDataRowIndex = 1; function LoadParsedRowTemplate(rowData, type) { var result; var asyncbinder = /&\{[\S\s]*?}&/g; while ((result = asyncbinder.exec(template)) != null) { replacement = eval("$.fn.ScreenSetup." + result[0].substring(2, result[0].length - 3) + ", rowData, " + _CurrentDataRowIndex + ")"); template = template.replace(result[0], "AsyncBind!!"); asyncbinder.lastIndex = 0; } } function AsynchronousBind(asyncFunc, args, rowData, rowIndex) { var watchTimer; asyncFunc.apply(this, Array.prototype.slice.call(args.FunctionArgs, 0)); watchTimer = setInterval(function () { if (args.finished) { clearTimeout(watchTimer); } else { try { console.log("watching the async function for a return on row: " + rowIndex); } catch (err) { } } }, 1000); } Eval is not capturing rowData and _CurrentDataRowIndex, both are undefined when the AsynchronousBind function is called. How does eval work with closures? I am wondering why the rowData and rowIndex arguments are undefined in AsynchronousBind. Edit: I am aware of the controversial nature of eval(), however this is for a behind the firewall app, and I'm adding to a plugin we've already written that uses eval to parse templates that contain HTML and JavaScript. Here is an example of the string being passed into eval(): "$.fn.ScreenSetup.AsyncBind( _CurrentDataRow.isPromotionAvailable, { 'FunctionArgs': {'doAsync' : true, 'finished' : false}, 'Property': 'isPromotionAvailable()', 'ControlType': 'TextBox', 'ControlIdPrefix': 'promoAvail'}, rowData, 3)" Edit (Fixed): Realized that when I added rowData and rowItem I I forgot to change the following in my plugin: var asyncMethods = { AsyncBind: function (func, args) { return AsynchronousBind(func, args) } } Should of been: var asyncMethods = { AsyncBind: function (func, args, rowData, rowIndex) { return AsynchronousBind(func, args, rowData, rowIndex) } } Updating this fixed the undefined reference in the AsyncBind function. A: Understanding eval scope is an interesting article. It shows that the scope is inconsistent among browsers. If you must use eval, you should be careful to only count on it being in global scope, and don't reuse global variable names in your local scope in case it is evaluated locally. Better yet, just don't use eval. You probably have other options.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Append div.html() to textarea.val() live function I'm working on project where DOM structure is something like this : <div id="wrapper"> <p> Some Text Goes Here </p> <ul id="sortable"> <li>list 1</li> <li>list 2</li> <li>list 3</li> <li>list 4</li> <li>list 5</li> </ul> </div> <textarea id="cloner" rows="50" column="50"></textarea> I'm appending #wrapper.html() to #cloner.val() using following simple function : $('#cloner').val($('#wrapper').html()); Now, #wrapper contains lot of dragable/sortable/editable events. So, what I want is to reflect those changes inside textarea Example : If I drag list 5 to list 2 position, this change within DOM should reflect inside textarea live. How can I achieve this ? A: You have to attach a stop event to the draggable method, in which you run: $('#cloner').val($('#wrapper').html()); The same for sortable, editable, etc. Or you can even copy that code into a function and just run that inside the stop event, so you would only have to update it in one place. A: Use the .sortable() stop event, like so: $( ".selector" ).sortable({ stop: function() { $('#cloner').val($('#wrapper').html()); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7503344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript if document.referrer redirect to another URL We are having issues getting the document.referrer url in our Javascript. We have a store and we want to prevent people from going from our shopping cart to a specific page. Meaning if they go from the shopping cart, hit the back button on the browser and the page before the shopping cart was a specific URL they need to skip that URL and we need to redirect to another page. We want to specify the URL for the product/page to skip if the referring URL is the shopping cart. I have tried doing this but seems not to work. Seems to fire on every single page no just the . I have it in the head of our Root.master page. Here is my code. $(document).ready(function () { var pathname = window.location.pathname; if (pathname = "http://www.mywebstore.com/Page-we-want-to-skip-over.aspx") { if (document.referrer = "http://www.mywebstore.com/ShoppingCart.aspx") { window.location = 'http://www.mywebstore.com/Page-we-want-to-go-to-instead.aspx' } } }); or we would like to skip back 2 pages. So we tried this too but it still fires on every single page, no just the page we want to prevent the back button action to. $(document).ready(function () { var pathname = window.location.pathname; if (pathname = "http://www.mywebstore.com/Page-we-want-to-skip-over.aspx") { if (document.referrer = "http://www.mywebstore.com/ShoppingCart.aspx") { window.history.back(-2); } } }); Again both of these solutions look correct but they are not working. Any help is greatly appreciated. Thanks in advance. A: You are using assignment instead of equality Change = to == in your tests. A: Using the back button doesn't change the referer in the way you want. e.g. a page sequence like: A -> B -> C (backbutton) -> B does not send 'C' as the referer when the user comes "back" to page B. The referer will be page A. Referers are set for 'forward' actions only, not 'back' actions. A: Also, window.location.pathname does not include the domain. So it should be: if (pathname == "/Page-we-want-to-skip-over.aspx") See the MDC documentation on window.location. You should also keep in mind that the referrer is unreliable. Some browsers or firewalls block it, and it can be forged.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Changing NSCursor for a specific view I'm trying to change the cursor when it passes over a view but I guess I am not coding it correctly as it is not working. I have an appcontroller class and in it's .m file I have this - (void) awakeFromNib { //set up the cursors NSCursor * handCursor = [NSCursor closedHandCursor]; //make a box Box* newBox = [[Box alloc] initWithFrame:NSMakeRect(10.0, 10.0, 100.0, 100.0)]; //set up the rect for the cursor change NSRect rectForCursor = [newBox frame]; [newBox addCursorRect:rectForCursor cursor:handCursor]; //add box to main win [[mainWin contentView] addSubview:newBox]; } A: Calling addCursorRect: from within awakeFromNib won't work. It must be called from within an override of resetCursorRects:, which is probably getting invoked at some point and clobbering the rect your set up. A: You've forgotten to call [handCursor setOnMouseEntered:YES]. Otherwise, NSCursor will ignore the mouseEntered: event it is sent.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Close colorbox modal window by clicking anchor link within modal window? I have made an anchor link - I am trying to make it so that when I click this anchor link (contained within the colorbox modal window) it will close the colorbox. $(document).ready(function(){ $('.newWindow a').click(function(){ alert('hello world'); // checking to be sure click function is being called $.fn.colorbox.close(); }); }); I would think this would work.. what could I be doing incorrectly? The content loaded in the colorbox is a hidden div on the page, not an iframe. EDIT: I don't know why it wasn't working. I have seen someone else's example and it was put together just as mine was. I noticed that when clicking on the transparent div to give the 'depth of field' with the colorbox the modal window will fade out/close. So I changed the code to: $(document).ready(function(){ $('.newWindow a').click(function(){ $('#DOMWindowOverlay').click(); // click overlay div and close colorbox }); }); Not really a fix - it's a workaround.. but it works! A: Kyle, that looks fine to me. Make sure you are also canceling the default action of the anchor, by returning false in your event handler or using the preventDefault method. Ex: $('.newWindow a').click(function(){ $.colorbox.close(); return false; }); It's ok to use .fn, (it is the standard way to access a jQuery plugin's methods), but it isn't required for any of colorbox's. A: What is that .fn for? Try $.colorbox.close() A: It doesn't work because the link doesn't exist when the docReady is run. In the future, you can do one of 2 things: A) put your click handler in a jquery live() function (still in docReady), or B) use colorbox's onComplete option to create the click handler (placed in the object literal you send when you create the colorbox). Also, as Thorsten pointed out, the .fn part is not necessary because the author of colorbox had the foresight to create a link to $.colorbox. A: Just put anchor onclick="$('#registerDialog').dialog('close');"> Where registerDialog is the modal dialog id like here data_dialog_id @Html.ActionLink("Register", "Register", "Account", null, new { @class = "openDialog", data_dialog_id = "**registerDialog**", data_dialog_title = "btewary.blogspot.in" })
{ "language": "en", "url": "https://stackoverflow.com/questions/7503351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to avoid methods calling each other in a chain? I have a C# class where I use a set of methods to filter out a List. I essentially do this by one method from inside the other and so on. So a( values) does some filtering, based on the output calls b(List values) or exits, b(List values) does some filtering and based on the output calls c(List values). I want to remove this method chaining code from and control everything from the method which calls a(List values). I can use if-else-if but that will lead to too many if-else-ifs which I dont think is so great. Are there any design patterns to solve this? Or some algo? Any help is appreciated. Thanks. Gaurav A: What you are discribinq sounds like typical scenario to use LINQ with Iterator pattern (it can be implemented in C# easily with iterator blocks). var results = someCollection .Where(c => c.SomeProperty < someValue * 2) .Where(c => c.OtherProperty == "hi") .OrderBy(c => c.AnotherProperty) .Select(c => new {c.SomeProperty, c.OtherProperty}); Or as query expression: var results = from c in SomeCollection where c.SomeProperty < someValue * 2 where c.OtherProperty == "Hi" orderby c.AnotherProperty select new {c.SomeProperty, c.OtherProperty}; You can chain as many operations as you wish. Of course much more advanced operations, shuch as joins and grouping, are also available. I recommend Jon Skeet's C# in Depth book if you really want to learn these techniques (and many others). A: I want to remove this method chaining code from and control everything from the method which calls a(List values) Well since you're filtering values you could use something like the LINQKit PredicateBuilder which would allow you to create a list of filters and apply them to the linq exprssion However if you're doing more than just filtering you could use create instances of the Action<T> Delegate to represent actions that could be done to a your list and then apply them. There's also the possibility of using Continuation Passing Style CPS but thinking about how that works makes my ears bleed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do you duplicate two matched lines in order with sed? If I have a file that looks like this: word foo bar word And I want to duplicate foo\nbar lines, so that it looks like this: word foo bar foo bar word I have tried using N to load the next line into the buffer, but I must be using it incorrectly, as it appears to skip over lines sometimes. sed -e '{ N s/\(foo\nbar\)/\1\1/ }' foobar.txt I think it is loading word\nfoo into the buffer, then bar\nword into the buffer, and misses the pattern entirely. How do you use N appropriately? Would this be easier with awk, perl, or some other tool? A: in awk: awk -v word1="foo" -v word2="bar" ' {print} prev==word1 && $1==word2 {print word1; print word2} {prev=$1} ' filename A: Since you specifically tagged the question with sed I thought I'd post a sed solution: /foo/,/bar/{ i\ foo i\ bar d } $ sed -f s.sed input word foo bar foo bar word
{ "language": "en", "url": "https://stackoverflow.com/questions/7503354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Jquery Get Textarea.val() with newlines I need to get the text entered into textarea and detect newlines (preferably <br>). I traced it until serverside and am sure that there are newlines because I'm printing the value with .val(). On serverside, I access to the same controls value and I see no newlines. I'm starting to think that '\n's don't appear on server side. I really don't want to replace all newlines with a character. Any ideas? Thanks A: This is what I did to get NewLines in the server side: string TextAreaText = txt.InnerHtml; string ReplacedText = TextAreaText.Replace(System.Environment.NewLine, "<br />"); Response.Write(ReplacedText); Sorry for the bad format. I am very new here and am not good at formatting code. Hopefully it helps. Hanlet A: I could guess that, if you try to render a textarea with nice format, you can see it with newline charater <textarea> </textarea> So you just use: <textarea></textarea>.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503367", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Gson de-serialize to Map generic type Attempting to de-serialize JSON to a Map<K, V> where K is a String and V one of several types (i.e String int or boolean). Using Gson, I tried the following code: public static void main(String[] args) { JsonObject json = new JsonObject(); json.addProperty("str", "str-value"); json.addProperty("int", 10); json.addProperty("bool", true); // "json" now contains {"str":"str-value","int":10,"bool":true} Type mapType = new TypeToken<Map<String, Object>>() {}.getType(); Gson gson = new Gson(); Map<String, Object> map = gson.fromJson(json, mapType); String str = (String) map.get("str"); // cannot cast Object to String str = String.valueOf(map.get("str")); // results in java.lang.Object@1632847 } A: Technical Answer If you attach the Gson source code and then debug the program you will find the source of the problem. The problem seems to rest in the Gson code. Since the value is of type Object your call to fromJson(), the class com.google.gson.ObjectNavigator will be used and comes into this section of code [~line 113] else if (objTypePair.type == Object.class && isPrimitiveOrString(objectToVisit)) { visitor.visitPrimitive(objectToVisit); //Target value is the proper value after this call visitor.getTarget(); //target value is now a blank Object. where visitor is of type JSonObjectDeserializationVisitor, objectToVisit is your value and objectTypePair is the type it is to become (Object). Now, The JsonObjectDeserializationVisitor has a flag called constructed which is set to false by default. so when the getTarget() method is called, it checks to see if the constructed flag is true, if not it creates a new instance of the object you are trying to create. since the constructed flag is never set the call to getTarget() returns a blank Object. The call to getTarget() seems unnecessary in the code and appears to be the source of the problem. visitPrimitive performs the proper action by placing the parsed value into the target variable which would be passed back. This appears to be a bug surrounding the Object type. This isn't something you could fix unless you are willing to do a custom build of Gson. I would recommend filing this as a report on the Gson forums. There is already one report filed for version 1.5 Work Around I see two ways you can fix this in the short term. 1) Make the Map of type <String, String>, though you lose the types you can still get the values back properly 2) Put the values into a bean class first and then Serialize that. public class myObj{ String myStr; int myInt; boolean myBool; //get and set methods } public static void main(String args[]){ MyObj o = new MyObj(); o.setMyStr("str-value"); Gson gson = new Gson(); String json = gson.toJson(o); o = gson.fromJson(json, MyObj.class); } Both defeat the purpose of what you are trying to do, but it is in googles court to fix this bug I believe.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I redirect a url that I am pointed to after clicking submit? There is a html form I have which submits to a Servlet once Submit button is clicked. After the submission the Servlet redirects to a fixed url which is http://siteforServlets.com/Servlet/Servlet That site then displays an xml report shown below: Sorry I cannot post Images not enough rep so I uploaded direct link here: http://img836.imageshack.us/img836/3343/sitea.png I dont want my users getting confused seeing an xml I prefer it going blank page or redirecting to a different url... How can I redirect the url to hide this xml report url? Mark, I tried what you said but it redirects before the form even loads. Here is a quick jsfiddle I made to demonstrate your suggestion: jsfiddle.net/ujsEG/12/ A: You could try making the form target a hidden iframe and then set the onload attribute of the iframe with a javascript call to window.location.href. <script type="text/javascript"> var okToRedirect = false; function redirect() { if (okToRedirect) { window.location.href = 'path/to/new/location'; } } </script> <form action="...some action..." target="MyIframe" onsubmit="okToRedirect = true;"> ... </form> <iframe name="MyIframe" style="display: none;" onload="parent.redirect()"></iframe> When the form posts, the results will display inside the hidden iframe. Once the iframe finishes loading, the onload attribute will fire the javascript to redirect the user. Update I updated my answer because of your comment. I added a javascript method which the iframe can call. There is now a global variable which is set to false initially. This will prevent the first load of the page from redirecting. When the form posts, the onsubmit event on the form will set the global variable okToRedirect to true, the iframe will reload and will call the redirect() method. This time around, the redirect will occur.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is there a way to add conditions into a COUNT()? What I want to do is add a COUNT into a query that is joined on several tables, but I only want to count the thing if it meets a specific condition. I want the count to only count the rows that have a ReceivedDate like so: COUNT(ReceivedDate = "0000-00-00 00:00:00", plpq.PurchaseOrderID) AS OrdersForPart Is there any way to achieve this without having to resort to a sub-query? A: Just use where. SELECT COUNT(plpq.PurchaseOrderID) AS OrdersForPart FROM ... WHERE ReceivedDate = '000-00-00 00:00:00' Should work just fine ;) A: Assuming you might want to perform some aggregation on the other rows and thus can't just exclude them entirely in the WHERE clause. COUNT(CASE WHEN ReceivedDate = "0000-00-00 00:00:00" THEN plpq.PurchaseOrderID END) AS OrdersForPart If this isn't the case the WHERE clause is of course the best option. A: SELECT COUNT(plpq.PurchaseOrderID) AS OrdersForPart FROM table WHERE ReceivedDate = "0000-00-00 00:00:00"
{ "language": "en", "url": "https://stackoverflow.com/questions/7503379", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: WordPress - Overriding a function in a plugin I've been wonder for some time what the best practice is for modifying a plugin created by a WordPress user? For example there are a couple lines of code I want to change within the Contact Form 7 plugin. The function is called function wpcf7_ajax_json_echo() and is located in: wp-content > plugins > contact-form-7 > includes > controller.php Of course I could just change the code right in that file and be done, but then I'm out of luck when I want to update that plugin as my modifications will probably get written over. I know I should be making this happen via my functions.php file, but I'm not sure how to go about achieving this. Also, that particular function is 100+ lines of code and I'm guessing I don't want to overwrite that whole function, because there is a good chance the author of the plugin may choose to update something in that function in the future. Does anyone know the cleanest way for me to modify a few lines within that function via my functions.php file? Thank you! A: I do not recommend changing the core. However, you are in a bit of a pickle. You can: * *Update the function code directly in the plugin *Copy the current function code from the plugin and override it in functions.php In the end, you still run into the same problem - future compatibility. Either: * *The update will overwrite your plugin changes. *Your function overwrites the plugin changes. So, as much as I don't want to say it, I'd update the plugin directly. At least then when you upgrade, you'll know pretty quick that your change is missing. Furthermore, it's possible the plugin updates will include your change. A: You could use SVN if you wanted to maintain forwards compatibility (and your host has SVN available), whilst being able to keep your own changes. Each plugin that's on the Plugin Directory has to have an SVN repo (that's how the Directory knows if there are updates). Here's the CF7 repo. Checkout the trunk to your /plugins/ directory inside a folder like /custom-contact-form-7/. Alter the wp-contact-form-7.php file to give it a unique name, and make the changes you want to make to customise it. To get new updates you can just svn up to get them, and they'll merge with your changes. Though, you may have to clean up merge conflicts sometimes. Version Control with Subversion is the place everyone starts to learn SVN, if you need it. There's also a Github repo now, if you'd like to fork that. A: I definitely think you should add your updates to functions.php or to a custom plugin. It's a hassle right now, but MUCH less hassle every time you upgrade the plugin. You'll always have to reference the changes made in updates no matter what. Even if you're able to extend the functionality without copying this file, you'll have to at least check and make sure your changes still work. And WinDiff/BBEdit's compare will make quick work of that. So my first suggestion is to override that function. Second suggestion: I noticed there's some extensions (a, b, c) to this plugin; perhaps you can find out how they made their extensions and use those details to make your own. Well, that's like suggesting you make a new house in order to fix the dripping faucet, but it's an idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Sequence of Events, alert is faster then removeAttr i got following problem, i need to build a two checkboxes; where only one can be selected at a time, but onchange there will be a live calculation. $('#calculator input, #calculator select').change(function() { $('#calc_keller_true').click(function() { $('#calc_keller_false').removeAttr('checked'); }); $('#calc_keller_false').click(function() { $('#calc_keller_true').removeAttr('checked'); }); liveCalculate(); }); This is how it looks like, which is working but it seems to slow cause in my function liveCalculate i do this. function liveCalculate() { // Getting the value of the checked checkbox var calc_keller = $('input[name=calc_keller]:checked').val(); alert(calc_keller); } So when i click on the false button the alert will trigger before my removeAttr and both Checkboxes will be 'checked' at the moment of the alert. Anyone got a plan why exactly the liveCalculate function triggers faster then the removeAttr ? Do i miss some basic knowledge in how the order works in javascript ? Best Regards, jay7 A: You only need to add click-handlers once. In your above example, you are adding them again and again, for every 'change' event you have on the select box. Furthermore, you are not actually removing the attr on the change event, that happens during the click events. However, you fire liveCalculate after the change event. Consider the following: $('#calc_keller_true').click(function() { $('#calc_keller_false').removeAttr('checked'); }); $('#calc_keller_false').click(function() { $('#calc_keller_true').removeAttr('checked'); }); $('#calculator input, #calculator select').change(function() { $('#calc_keller_false').removeAttr('checked'); $('#calc_keller_true').removeAttr('checked'); liveCalculate(); }); I'm not entirely sure if that accomplishes what you're expecting (simply because it isn't 100% clear to me what you do expect to happen).
{ "language": "en", "url": "https://stackoverflow.com/questions/7503387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Selecting an image from a page to add to another page - WP7 i've being searching the net and this forum for a couple of days, but still haven't find an answer to my problem. Here's the deal: i'm building an wp7 app and i created 2 pages; the first with a grid and some buttons on it; and the second will have a canvas and a ink color selector, where the user can drawn on a white space. I created a NavigationService for the user to click on the button and navigate to the second page. But now i want that, when the user clicks on this button, a specific image will be loaded on the navigated page, so the user can paint over it, in a canvas. A: So you want to have a image inside a Canvas? <Canvas> <Image Source="myimage.jpg" Width="100" Height="100" /> </Canvas>
{ "language": "en", "url": "https://stackoverflow.com/questions/7503388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: -webkit color stop acting weird My HTML document contains #victimDiv thats background image property is set to: -webkit-linear-gradient(-75deg, black 10px, #4AC0F2); After I load #victimDiv with ajax call and its height prolongs, gradient gets longer as its length is defined in percentage instead being fixed in pixels. A: maybe it's because you apply css length parameters on an element when the element is not already in the DOM. this is not possible... try to do it with the css embedded in the respective html tag. A: I misunderstood syntax meaning: pixels or percentage after color means that color starts from there not ends. Kind of a weird name color stop??? Anyway right syntax for what I wanted to achieve is: -webkit-linear-gradient(-75deg, black, #4AC0F2 10px); Good night, and good luck! :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7503396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: has_many through association, and multiple search criteria, how can i make this work? I'm trying to create a multi criteria search form. I want to submit all of the pieces of the search via GET and if they have a value assigned I would like them evaluated. The thing that I'm having trouble grasping is building a query that will allow me to layer more queries on top when you're doing it with a through association. Just to give you an idea of how my models are set up: class Client < ActiveRecord::Base has_many :campaigns has_many :pieces, :through => :campaigns end class Campaign < ActiveRecord::Base belongs_to :client has_many :pieces end class Piece < ActiveRecord::Base belongs_to :client end Now, with that model in mind, I'm using the collect method to grab the pieces that have an organization in common. if params.has_key?(:criteria) @selected_client = Client.where(:organization => "Org1") @pieces = @selected_client.collect{ |c| c.pieces }.flatten end Is there some way of formatting that query string so that I can narrow @pieces down, a couple more times? Let's say I wanted to use that through association again, to get pieces that have another of the same Client criteria... Thanks a ton! My brain is a pretzel at this point. A: I'm not sure if i undestand very well what you're trying to do. If you want to get all pieces matching your client criteria, in rails 3, you can do this : @pieces = Piece.joins(:campaign => :client).where(:clients => {:organization => criteria}) to get all pieces belonging to clients from organization "Org1". You can stack as many where statements as you want to add new conditions, as @Andrew said. See this for more information. A: Your first paragraph got cut off, just FYI. If @pieces is an array, you can use a find block to narrow your search further. Although this will put the load on your server CPU rather than the SQL database. You can stack where statements and Rails will automatically create a single query for you. Here is some sample code from the app store section of our website: @platform = params[:platform] @category = params[:category] @search = params[:app_q] # Get initial SQL, narrow the search, and finally paginate @apps = App.live @apps = @apps.where("platform = ?", AppPlatforms.value(@platform)) if AppPlatforms.value(@platform) @apps = @apps.where("(name LIKE ? OR description LIKE ?)", "%#{@search}%", "%#{@search}%") if @search @apps = @apps.where("id IN(?)", @cat.apps) if @category && @cat = Category.find_by_id(@category) @apps = @apps.paginate(:page => params[:page], :per_page => 10, :order => "name") Instead of using collect you should be able to use @selected_client.pieces.where(...) to narrow your search down via SQL. I hope this is a point in the right direction!
{ "language": "en", "url": "https://stackoverflow.com/questions/7503398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reading from stdin using read(..) and figuring out the size of the buffer I was wondering if anyone could tell me if there is a way to dynamically allocate a buffer when reading an input from stdin using read(...) For example: n = read(0, buffer, sizeof ?); How do I ensure that the number of bytes read from stdin (here 0) is the same as in buffer ? A: You can't. You do a read into a fixed-size buffer, e.g.: char buf[BUF_SIZE]; int num_read = read(0, buf, BUF_SIZE); and then figure out if there's any more data available (usually by checking whether num_read is equal to BUF_SIZE, but in some cases, maybe you need to interpret the data itself). If there is, then you do another read. And so on. It's up to you to deal with concatenating all the read data. A: You can't (unless you've got precognitive skills) figure out the size of what you will get. But the read method allow you to read part by part the content of stdin, if you put your read() call into a (while your_stop_condition) loop, you will be able to read all the stuff you need from stdin, by packets. char buffer_to_read[SIZE]; int bytes=0; while your_stop_condition { bytes = read(0, buffer_to_read, SIZE); // do what you want with your data read // if bytes < SIZE, you read an EOF }
{ "language": "en", "url": "https://stackoverflow.com/questions/7503399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Ckeditor force custom style attribute to specific elements I would like to force the inline style attributes for all p elements. How can I do this? I've tried to do this: CKEDITOR.config.format_p= { element : 'p', attributes : { style : 'padding:10px;' } } This line is executed and appears in the dom, but nothing really changed. A: config.format_p is the style that will be applied when "Paragraph" selected in the Styles combobox. If you want to change all p elements just add your own custom css file into the CKEditor body.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Android, get screen width and height? I am trying to get the width and height of the screen in Android, i have: DisplayMetrics displaymetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); stageWidth = displaymetrics.widthPixels; stageHeight = displaymetrics.heightPixels; The width is 1280 but its coming back with 752. Any ideas? A: Try this instead: Display display = getWindowManager().getDefaultDisplay(); stageWidth = display.getWidth(); stageHeight = display.getHeigth(); Is that the same width? Are you sure the width is 1280 and not 752? What device are you testing it on and what height are you getting? A: Use this method on the display object (from the docs): void getSize(Point outSize) - Returns the raw size of the display, in pixels. A: Rotate your screen and see.I think you will get your correct screen size. The above code worked with me and should work with you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: python not finding library under django that's found otherwise I've just successfully installed GeoDjango and all the required libraries. I've set the environment variables and registry keys (yea working under Windows here) and everything works find from the command line. d:\...\> python >>> from django.contrib.gis.geos import * >>> exit() d:\...\> python manage.py runserver 0.0.0.0 (...) Now when the server that's being run here encounters the very same line in code it's supposed to execute, it says WindowsError at /NT/BUAConvex/4DED02804:SQLEXPRESS:44_EU_2011Q2/20187417/ [Error 126] The specified module could not be found D:\...\views.py in <module> from django.contrib.gis.geos import * ... c:\python27\lib\site-packages\django\contrib\gis\geos\__init__.py in <module> from django.contrib.gis.geos.geometry import GEOSGeometry, wkt_regex, hex_regex ... c:\python27\lib\site-packages\django\contrib\gis\geos\geometry.py in <module> from django.contrib.gis.geos.coordseq import GEOSCoordSeq ... c:\python27\lib\site-packages\django\contrib\gis\geos\coordseq.py in <module> from django.contrib.gis.geos.libgeos import CS_PTR ... c:\python27\lib\site-packages\django\contrib\gis\geos\libgeos.py in <module> lgeos = CDLL(lib_path) ... c:\python27\lib\ctypes\__init__.py in __init__ self._handle = _dlopen(self._name, mode) ... A: Thanks to @ed. and @g.d.d.c I found the solution. Problem turned up in the Django shell as well. Turns out I had set GEOS_LIBRARY_PATH = 'c:\OSGeo4W' in my Django settings where it should've been 'c:\OSGeo4W\bin'. Calling plain Python ignored those settings and instead relied on the OS-own functionality to find the .dll (which succeeds).
{ "language": "en", "url": "https://stackoverflow.com/questions/7503416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: packaging android facebook sdk as apklib with maven I have used maven-android-plugin 3.0.0-alpha-7 to package the facebook android sdk as a apklib. It looks like this: $ unzip sdk-1.0-SNAPSHOT.apklib Archive: sdk-1.0-SNAPSHOT.apklib creating: META-INF/ inflating: META-INF/MANIFEST.MF inflating: AndroidManifest.xml creating: assets/ creating: res/ creating: res/drawable/ creating: res/drawable-hdpi/ creating: res/drawable-ldpi/ inflating: res/drawable/facebook_icon.png inflating: res/drawable-hdpi/facebook_icon.png inflating: res/drawable-ldpi/facebook_icon.png creating: src/ creating: src/com/ creating: src/com/facebook/ creating: src/com/facebook/android/ inflating: src/com/facebook/android/AsyncFacebookRunner.java inflating: src/com/facebook/android/DialogError.java inflating: src/com/facebook/android/Facebook.java inflating: src/com/facebook/android/FacebookError.java inflating: src/com/facebook/android/FbDialog.java inflating: src/com/facebook/android/Util.java I then install it into a local repo for my project and include it as a maven dep... and run the build I get this: $ mvn clean package android:deploy [INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building myproject 2.0-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- maven-clean-plugin:2.4.1:clean (default-clean) @ myproject-android --- [INFO] Deleting /Users/user/dev/projects/company/myproject-android/target [INFO] [INFO] --- maven-android-plugin:3.0.0-alpha-7:generate-sources (default-generate-sources) @ myproject-android --- [DEBUG] Expanding: /Users/user/.m2/repository/com/facebook/android/sdk/1.0-SNAPSHOT/sdk-1.0-SNAPSHOT.apklib into /Users/user/dev/projects/company/myproject-android/target/unpack/apklibs/com.facebook.android_sdk_apklib_1.0-SNAPSHOT [DEBUG] expand complete [INFO] ANDROID-904-002: Found aidl files: Count = 0 [INFO] ANDROID-904-002: Found aidl files: Count = 0 [INFO] ANDROID-904-002: Found aidl files: Count = 0 [INFO] /Users/user/dev/libs/android-sdk-mac_x86/platform-tools/aapt [package, -m, -J, /Users/user/dev/projects/company/myproject-android/target/generated-sources/r, -M, /Users/user/dev/projects/company/myproject-android/AndroidManifest.xml, -S, /Users/user/dev/projects/company/myproject-android/res, -S, /Users/user/dev/projects/company/myproject-android/target/unpack/apklibs/com.facebook.android_sdk_apklib_1.0-SNAPSHOT/res, --auto-add-overlay, -A, /Users/user/dev/projects/company/myproject-android/assets, -I, /Users/user/dev/libs/android-sdk-mac_x86/platforms/android-10/android.jar] [INFO] /Users/user/dev/libs/android-sdk-mac_x86/platform-tools/aapt [package, -m, -J, /Users/user/dev/projects/company/myproject-android/target/generated-sources/r, --custom-package, com.facebook, -M, /Users/user/dev/projects/company/myproject-android/AndroidManifest.xml, -S, /Users/user/dev/projects/company/myproject-android/res, -S, /Users/user/dev/projects/company/myproject-android/target/unpack/apklibs/com.facebook.android_sdk_apklib_1.0-SNAPSHOT/res, --auto-add-overlay, -A, /Users/user/dev/projects/company/myproject-android/assets, -A, /Users/user/dev/projects/company/myproject-android/target/unpack/apklibs/com.facebook.android_sdk_apklib_1.0-SNAPSHOT/assets, -I, /Users/user/dev/libs/android-sdk-mac_x86/platforms/android-10/android.jar] [INFO] [INFO] --- maven-resources-plugin:2.5:resources (default-resources) @ myproject-android --- [debug] execute contextualize [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] skip non existing resourceDirectory /Users/user/dev/projects/company/myproject-android/src/main/resources [INFO] skip non existing resourceDirectory /Users/user/dev/projects/company/myproject-android/target/generated-sources/extracted-dependencies/src/main/resources [INFO] Copying 0 resource [INFO] [INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ myproject-android --- [INFO] Compiling 141 source files to /Users/user/dev/projects/company/myproject-android/target/classes [INFO] ------------------------------------------------------------- [ERROR] COMPILATION ERROR : [INFO] ------------------------------------------------------------- [ERROR] /Users/user/dev/projects/company/myproject-android/target/unpack/apklibs/com.facebook.android_sdk_apklib_1.0-SNAPSHOT/src/com/facebook/android/FbDialog.java:[95,17] package R does not exist [INFO] 1 error [INFO] ------------------------------------------------------------- [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Skipping myproject [INFO] This project has been banned from the build due to previous failures. [INFO] ------------------------------------------------------------------------ [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 6.279s [INFO] Finished at: Wed Sep 21 09:32:40 PDT 2011 [INFO] Final Memory: 13M/81M [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile) on project myproject-android: Compilation failure [ERROR] /Users/user/dev/projects/company/myproject-android/target/unpack/apklibs/com.facebook.android_sdk_apklib_1.0-SNAPSHOT/src/com/facebook/android/FbDialog.java:[95,17] package R does not exist [ERROR] -> [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException I see the R files are getting generated and have the correct contents: $ find target/generated-sources/r/ target/generated-sources/r/ target/generated-sources/r//com target/generated-sources/r//com/facebook target/generated-sources/r//com/facebook/Manifest.java target/generated-sources/r//com/facebook/R.java target/generated-sources/r//com/company target/generated-sources/r//com/company/myproject target/generated-sources/r//com/company/myproject/droid target/generated-sources/r//com/company/myproject/droid/Manifest.java target/generated-sources/r//com/company/myproject/droid/R.java What am I missing to get the R files included in the compilation step? A: I already did that for you: https://github.com/casidiablo/android-facebook Download Latest version available is 1.5: * *Download JAR *Download Sources *Download Javadoc Maven You can use it from Maven by including this dependency and repository: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> ... <dependencies> ... <dependency> <groupId>com.codeslap</groupId> <artifactId>android-facebook</artifactId> <version>1.6</version> <scope>compile</scope> </dependency> </dependencies> <repositories> <repository> <id>codeslap</id> <url>http://casidiablo.github.com/codeslap-maven/repository/</url> </repository> </repositories> </project>
{ "language": "en", "url": "https://stackoverflow.com/questions/7503417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: VB.NET Function As String, Will Return False Be A Boolean? I have a HTTP class that gets content from URL's, POST's content to URL's etc and then returns the raw HTML content. In the function inside of the class it detects if there is a HTTP error and if so I would like to return false but will this work if I have declared the function to return a String? Code Sample of what I am trying to do (Note the Return Content & Return False if a HTTP error code is detected) Public Function Get_URL(ByVal URL As String) As String Dim Content As String = Nothing Try Dim request As Net.HttpWebRequest = Net.WebRequest.Create(URL) ' Request Settings request.Method = "GET" request.KeepAlive = True request.AllowAutoRedirect = True request.Timeout = MaxTimeout request.CookieContainer = cookies request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.60 Safari/534.24" request.Timeout = 60000 request.AllowAutoRedirect = True Dim response As Net.HttpWebResponse = request.GetResponse() If response.StatusCode = Net.HttpStatusCode.OK Then Dim responseStream As IO.StreamReader = New IO.StreamReader(response.GetResponseStream()) Content = responseStream.ReadToEnd() End If response.Close() Catch e As Exception HTTPError = e.Message Return False End Try Return Content End Function And usage example: Dim Content As String = Get_URL("http://www.google.com/") If Content = False Then MessageBox.Show("A HTTP Error Occured: " & MyBase.HTTPError) Exit Sub End If A: Usually in this type of scenario, you would throw a new exception with more detailed information, and let the exception bubble up to the processed by the main code (or just let the original exception bubble up without Catching it in the first place). Catch e As Exception ' wrap the exception with more info as a nested exception Throw New Exception("Error occurred while reading '" + URL + "': " + e.Message, e) End Try Inside the usage example: Dim content As String = "" Try content = Get_URL("http://www.google.com/") Catch e As Exception MessageBox.Show(e.Message) Exit Sub End Try
{ "language": "en", "url": "https://stackoverflow.com/questions/7503420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android USB Accessory Communication with Linux System I am trying to setup a Nexus One phone to communicate with an application running on a Linux tablet. On the phone side of things, the Nexus One is Android 2.3.4 so it has the USB accessory library on it. And I have created an application Android following the instructions on http://developer.android.com/guide/topics/usb/accessory.html. I have verified that the Android application works by plugging it into the Microchip Accessory Development Starter kit and connecting to it. On the Linux side of things, I have configured it to register the Nexus device with the usbserial module and create a ttyUSB0 device when the phone is plugged in. I have verified my application reads and writes to ttyUSB0 correctly. I did this by connecting it to a serial port on another computer and watching data come in through minicom. Unfortunately The Android developer website does not cover any configuration that host devices (in my case, my Linux tablet) need to perform. In other words, what protocol does the Linux heed to follow to communicate with the phone? A: This is not possible. After further research it is not possible to communicate with the Android device using serial USB communication. To communicate with Android applications through Linux use the libusb-1.x library.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Send SMS in USA with a PHP API Where I can find an enterprice API(PHP) to send SMS in USA? I am looking for an API that will be easy to use, also allows me view reports of sended SMS, that also has documentation and examples to how manage it. A: * *Twilio: http://www.twilio.com/docs/quickstart/sms/hello-monkey *Tropo: http://blog.tropo.com/2009/08/25/add-sms-and-im-to-any-existing-tropo-application-in-ruby-python-php-javascript-or-groovy-today/ A: http://www.twilio.com/ is a good service and they have a PHP library http://www.twilio.com/docs/libraries/ A: You can take a look to the open source projects on PHP script at http://www.aldeaglobal.net/callserver/ and another one is this: http://www.simong.net/finarea/ They work on more than 20 providers, and the APIs are quite similar. A comparision matrix for all prices can be found here: hXXp//progx.ch/home-voip-smsbetamax-3-1-1.html (replace hXXp by http: sorry I'm new and I need more reputation to post more than 2 links maybe you can vote me ;-) All of these Providers are compatible with the two PHP scripts above. Most of those providers also have an official API which is in most of the cases here: https://provider_name.com/myaccount/sendsms.php?username=XXXX&password=XXXX&from=00XXXX&to=00XXXX&text=XXXX Just replace the XXXX and open it with a fsockopen using the ssl:// or https://
{ "language": "en", "url": "https://stackoverflow.com/questions/7503433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Looking for pathing algorithms for maps without edges I have 2D world maps that are basically Mercator-Like projections, (If you walk west long enough you end up east of where you started) Question I have: Can you use A* for computing paths on these types of maps as well? I can't think of any reason why you couldn't (I'm thinking that you would simply represent the edge map nodes such that the North, South, East, Wed, "border" nodes simply connected to the opposite side). Thanks in advance, if anyone has seen something like this before or can give me a few hints I would appreciate it. A: Pathfinding algorithms don't really care about global topology of the map. The only tricky part is to get a good estimator for A* but using the 3D distance should be ok if your map is indeed a surface in a 3d space and step cost is step length. Your map can have all sort of strange "connections" (including for example knotted bridges) and this will not be a problem if you implement A* correctly. A: I can't imagine why a Mercator-Like projections would cause a problem for A*, as long as your heuristic function approximates distances correctly. I think something along the below function should work fine float heuristic(point from, point to, size mapsize) { float x = from.x - to.x; if (abs(x) > mapsize.x/2) x = mapsize.x - x; float y = from.y - to.y; if (abs(y) > mapsize.y/2) y = mapsize.y - y; return sqrt(x*x+y*y); } A: Edited: I realize know I was misled by the non-graph theoretical) use of the word edge (where the question title strongly suggested a graph algorithm question :)) Why do you suppose there are no edges? There are many logical discrete locations that you could model, and limited connections between (i.e. not where a wall is :)). There you go: you have your edges. What you probably mean is that you don't want to represent your edges in data (which you don't have to, but still there are the logical edges that connect locations/points.) That said: you ask whether someone has seen things like this before. I vaguely recall seeing something relevant to this in Knuths Dancing Links article (DLX) which is an implementation technique for A* algorithms. * *http://en.wikipedia.org/wiki/Dancing_Links *original publication [PDF] The article specifically treats states as 'cells' (in a grid) with east/west/north/south links. It's been a long time so I don't quite recall how you would map (no pun intended) your problem on that algorithm. The dance steps. One good way to implement algorithm X is to represent each 1 in the matrix A as a data object x with five fields L[x]; R[x]; U [x]; D[x]; C[x]. Rows of the matrix are doubly linked as circular lists via the L and R fields ("left" and "right"); columns are doubly linked as circular lists via the U and D fields ("up" and "down"). Each column list also includes a special data object called its list header.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to drop Enter, when I'm using Scanner? I want to write a program where you don't need to press Enter, when I'm using Scanner. Is there any way to avoid that? It supposed to be very simple program, but every time I am write something, I have to press enter. A: If you are using a scanner like Scanner userInputScanner = new Scanner(System.in); String scanInfo = userInputScanner.nextLine(); Then you need to press enter after because the docs say the method: Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line. Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present." Essentially, by pressing enter you are telling the computer your input is done If you need something that can scan information without pressing enter, you can scan a text file like this: String input = "1 fish 2 fish red fish blue fish"; Scanner s = new Scanner(input); Instead of input, you can use a txt file as well Note: in the string input example, you would likely want to use a delimiter (for instance separating the String input at instances of white space) Scanner s = new Scanner(input).useDelimiter(Character.isWhitespace); Personally, I like using txt files because with each line in the file I can use .hasNext() to get the data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Spring Tools Suite memory keeps increasing I have recently started using the Spring Tools Suite (STS 2.7.2), and it seems the memory consumed by the IDE keeps increasing as you continue to work. The usage of the IDE has been pretty limited as of now (no heavy server integration or so...) - just 4-5 Spring projects being worked upon, with a couple of plugins integrated : Maven and Perforce. As a stat, when the STS workbench was launched, the memory consumption was of the order of ~300MB, but gradually increases to ~800MB. And then the only option I have is to restart the IDE (after my system obviously goes low on memory). Is this a known issue? Any workarounds on how to avoid this, or check what may be causing this? A: There are no known memory issues with STS. By default, STS starts with 1024M of heap space. However, this is usually not completely necessary. Typically, STS/Eclipse will use a significant amount of memory on startup as things get initialized (such as Java search indexes, the package explorer, icons, etc.), but this memory usage will level off and decrease over time. Some operations like full builds and Java search will cause temporary spikes in memory usage, but again, memory should go down over time. You can try running with the Heap status widget active. Go to Preferences -> General -> Show heap status. This will allow you to force garbage collection and you should see your memory usage go down. If memory continues to increase and you eventually get out of memory errors, then something bad is definitely going on. How much physical memory does your system have? A: This is a genuine problem with Spring STS. It keeps increasing the memory it uses and then ultimately crashes without killing the javaw.exe process in the windows process tree.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How can I solve this strange VS 2010 form design view issue? The problem: In VS2010, I have a form with a broken design view. It's breaking on a couple of Atalasoft imageviewer controls. The weirdness: Took me some time to figure this out, but if I go into the forms designer.vb file, and comment out everything regarding these controls, save, uncomment, and save again, the form design view loads perfect. NOTE: I'm not changing anything. Just commenting/uncommenting portions of the designer and saving. The form design view continues to work fine until I do any of the following: * *close the form design view and the designer.vb file and try to view again. *close the solution and reopen. After doing either of these things, it's back to square one and I have to comment/uncomment/save to view the form designer again. I'm on Win7, 64 bit. I have worked on this app in the past with no issue. The app builds and runs just fine. It's just a VS form design view issue, and I'm flummoxed. I'd love to hear any thoughts on how I can solve this. If I can provide any more specific info, please let me know. A: I've seen this happen rarely, when something odd gets into the designer file for a form and the designer can't figure out how to display things anymore. A third-party control being part of it could be indicative of some bug with that control's designer-related code. One thing to try might be re-creating the form in question from scratch, and see if that fixes it. Perhaps something inadvertently got fubared. Also see if there is anything out there with others having designer problems with the same control(s) in question. Sorry can't offer more direct help; maybe someone else has experienced something more closely related.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can you set the Location header in a chunked http response trailer? HTTP 1.1 responses can be chunked (spec). At the end of the last chunk the server can send a "trailer", which contains additional headers. The question is: can you include a Location header in the trailer, and will the browser react by making a redirect? A: The problem is that Location header to work should be with specific response code 3xx so in a standard response you can't use it see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html A: Yes. To have the Location header, the server should be responding with the 201 or one of the 3XX status codes. It should also include content, perhaps a message in HTML explaining what happened and giving a handy hyperlink to the resource. The content would need to be chunked and the Transfer-Encoding header should be present and have the value "chunked". If all this were true, then the Trailer header could be added with a value of "Location", and the Location header could then trail the content. Here's the real issue: This seems silly and pointless. What use case might you have where you will redirect a client to a new location, yet you don't know that location until after the content is complete? I can't think of a reason. But maybe you have one? If there's not a good use case, then I don't think you should do this. Edit: I thought of a reason. Shiflett gives an example of chunked transfer encoding where the first chunk of HTML sent to the client says, "We are completing your transaction." Time passes while the transaction is completed. Then the second and final chunk of HTML is sent to the client that says, "Ok, your transaction is now complete." (HTTP Dev's Handbook p97) Combine this idea with a 201 where a new file is created. It might be that the location of the new file is unknown until the very end of the server's processing. Thus it would want to use chunked transfer encoding, and it would want to put the Location header in the trailers. Second Edit: Yes, you can add it because the spec specifically forbids only the following header fields: Transfer-Encoding, Content-Length, and Trailer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Cannot find or open the PDB file message, pdb exists I am using Visual Studio 2010, recently upgraded. The solution contains 25 projects, makes a dozen dll's and exe's. I am trying to debug a particular problem and I can't due to symbols not being loaded. I get the "Cannot find or open the PDB file", this is for a PDB file one of the DLL's the project generates, all the other PDB files load just fine. The PDB file exists in the same directory as the dll, I have also cleaned and rebuilt the solution. In addition I have ran process explorer filtering on the pdb name, this indicated that it was found, opened and read successfully. Oddly it also continued to look in other locations for the pdb as well. Anyone have any thoughts on this? A: In most cases Visual Studio has problems with the file handles. Visual Studio sees the PDB as being used by a process, but that process is Visual Studio (I know, kinda stupid). Try rebooting the machine and manually deleting the PDB file before build. That usually works for me. A: Are you getting multiple projects or builds outputting the same PDB file? I had a project that I could compile as a EXE or a DLL. Of course, by default, they over wrote each others PDB file. So VS would detect that the PDB doesnt match. When I moved to VS2010, I solved this issue by setting Target Name to "$(ProjectName)_$(Configuration)" for ALL projects and configurations. A: Turn on Microsoft Symbols Server in Debug -> Options and Settings -> Debugging -> Symbols
{ "language": "en", "url": "https://stackoverflow.com/questions/7503448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How do you turn a Mongoose document into a plain object? I have a document from a mongoose find that I want to extend before JSON encoding and sending out as a response. If I try adding properties to the doc it is ignored. The properties don't appear in Object.getOwnPropertyNames(doc) making a normal extend not possible. The strange thing is that JSON.parse(JSON.encode(doc)) works and returns an object with all of the correct properties. Is there a better way to do this? A: To get plain object from Mongoose document, I used _doc property as follows mongooseDoc._doc //returns plain json object I tried with toObject but it gave me functions,arguments and all other things which i don't need. A: The lean option tells Mongoose to skip hydrating the result documents. This makes queries faster and less memory intensive, but the result documents are plain old JavaScript objects (POJOs), not Mongoose documents. const leanDoc = await MyModel.findOne().lean(); not necessary to use JSON.parse() method A: You can also stringify the object and then again parse to make the normal object. For example like:- const obj = JSON.parse(JSON.stringify(mongoObj)) A: Mongoose Models inherit from Documents, which have a toObject() method. I believe what you're looking for should be the result of doc.toObject(). http://mongoosejs.com/docs/api.html#document_Document-toObject A: JohnnyHK suggestion: In some cases as @JohnnyHK suggested, you would want to get the Object as a Plain Javascript. as described in this Mongoose Documentation there is another alternative to query the data directly as object: const docs = await Model.find().lean(); Conditionally return Plain Object: In addition if someone might want to conditionally turn to an object,it is also possible as an option argument, see find() docs at the third parameter: const toObject = true; const docs = await Model.find({},null,{lean:toObject}); its available on the functions: find(), findOne(), findById(), findOneAndUpdate(), and findByIdAndUpdate(). NOTE: it is also worth mentioning that the _id attribute isn't a string object as if you would do JSON.parse(JSON.stringify(object)) but a ObjectId from mongoose types, so when comparing it to strings cast it to string before: String(object._id) === otherStringId A: the fast way if the property is not in the model : document.set( key,value, { strict: false }); A: Another way to do this is to tell Mongoose that all you need is a plain JavaScript version of the returned doc by using lean() in the query chain. That way Mongoose skips the step of creating the full model instance and you directly get a doc you can modify: MyModel.findOne().lean().exec(function(err, doc) { doc.addedProperty = 'foobar'; res.json(doc); }); A: A better way of tackling an issue like this is using doc.toObject() like this doc.toObject({ getters: true }) other options include: * *getters: apply all getters (path and virtual getters) *virtuals: apply virtual getters (can override getters option) *minimize: remove empty objects (defaults to true) *transform: a transform function to apply to the resulting document before returning *depopulate: depopulate any populated paths, replacing them with their original refs (defaults to false) *versionKey: whether to include the version key (defaults to true) so for example you can say Model.findOne().exec((err, doc) => { if (!err) { doc.toObject({ getters: true }) console.log('doc _id:', doc._id) } }) and now it will work. For reference, see: http://mongoosejs.com/docs/api.html#document_Document-toObject A: I have been using the toObject method on my document without success. I needed to add the flattenMap property to true to finally have a POJO. const data = document.data.toObject({ flattenMaps: true });
{ "language": "en", "url": "https://stackoverflow.com/questions/7503450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "272" }
Q: Converting a number (non-currency) value to a text entry Easy enough concept, but I have no idea where to start when it comes to creating a UDF, which is the only thing I can find any mention of. I have a column that populates on source sheets with either a 1 or 2. I want to do something so that all of the "1's" shows as one text entry("AA" for example) and all "2's" show as a different entry(say "BB"). Is this possible without a UDF; and if not then is there any advice on where to start? A: You can use custom formatting for this. Right-click the column in question and choose "Format Cells." In the dialog, choose "Custom" and in the box at the top enter: [=1]"AA";[=2]"BB";General This assumes that the "1" or "2" is the sole content of the cell. Any other number or text will display in the General format. A: This may help you as well. It is a conditional statement that will reference one cell the check if there is content, if not then it will put the word "None" in, otherwise it will put the contents of the cell. =IF((Sheet1!J1089)="","None",Sheet1!J1089) A: Just to update anyone else that may be interested. I have a solution that I am using. Had to go the vba route, but I've got it set up so that my macro for running reports runs the following: Sub Conversion() Dim X As Long, DBCodes() As String DBCodes = Split("AA,BB,CC", ",") For X = 1 To 3 Columns("H").Replace X, DBCodes(X - 1), xlWhole Next End Sub I can change the split values and the line after for as many more values as I need replacing, though it would take fiddling with to find the point where too many values would make it impractical. Also, it makes a world of difference where I put in the line to run this; found the best spot though and even the reports that are 600+ rows the conversion only adds a couple seconds.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: nhibernate to linq 3.2 generate error sql on || operator now i'm using nhibernate 3.2 as the orm,when i write code like this: PostReaderBll postReaderBll=new PostReaderBll(); var query = from p in postReaderBll.Query() where (p.Post.Flag == (int)PostType.Post && p.Post.MailState == (int)MailState.Normal) || (p.ReceiveUser == LoginUser.UserIdentity && p.Post.Flag == (int)PostType.Mail && p.Post.MailState == (int)APSP.Form.MailState.Normal) select p; i get this sql: SELECT TOP ( 10 /* @p0 */ ) ID1_70_, IsRead2_70_, ReceiveU3_70_, ReadDate4_70_, Flag5_70_, Label6_70_, PostID7_70_ FROM (select postreader0_.[ID] as ID1_70_, postreader0_.[IsRead] as IsRead2_70_, postreader0_.[ReceiveUser] as ReceiveU3_70_, postreader0_.[ReadDate] as ReadDate4_70_, postreader0_.[Flag] as Flag5_70_, postreader0_.[Label] as Label6_70_, postreader0_.[PostID] as PostID7_70_, ROW_NUMBER() OVER(ORDER BY CURRENT_TIMESTAMP) as __hibernate_sort_row from PostReader postreader0_ inner join Post post1_ on postreader0_.[PostID] = post1_.[ID] where post1_.[Flag] = 1 /* @p1 */ and post1_.[MailState] = 0 /* @p2 */ or postreader0_.[ReceiveUser] = 'admin' /* @p3 */ and post1_.[Flag] = 0 /* @p4 */ and post1_.[MailState] = 0 /* @p5 */) as query WHERE query.__hibernate_sort_row > 0 /* @p6 */ ORDER BY query.__hibernate_sort_row but i need the where like this: ( post1_.[Flag] = 1 /* @p1 */ and post1_.[MailState] = 0 /* @p2 */) or (postreader0_.[ReceiveUser] = 'admin' /* @p3 */ and post1_.[Flag] = 0 /* @p4 */ and post1_.[MailState] = 0 /* @p5 */) A: It is the same because, OR operators are always evaluated after AND operators. Reference documentation for OR operator: Combines two conditions. When more than one logical operator is used in a statement, OR operators are evaluated after AND operators. However, you can change the order of evaluation by using parentheses. http://msdn.microsoft.com/en-us/library/ms188361.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7503456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Facebook connect to external app inside iframed fan page content I have an app that implements facebook connect to login/register. I've also set up a fan page for that app. Suppose I render my connect button inside the iframe showing on the fan page. Will that work? The objective is to allow people to register for my application while viewing the fan page for it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to query current expanded item in accordion layout OK, so here is the way I can find current collapsed in accordion layout: Ext.getCmp("myaccordion").query("{collapsed}") How in the same manner I can find expanded one? I can't see expanded property. Moreover, this code: Ext.getCmp("myaccordion").query("not:{collapsed}") crushes my browser down. UPD: here is my decision, based on example in ExtJS docs: Ext.ComponentQuery.pseudos.expanded = function(items) { var res = []; for (var i = 0, l = items.length; i < l; i++) { if (!items[i].collapsed) { res.push(items[i]); } } return res; }; And then I just query this way Ext.getCmp("myaccordion").query(">*:expanded") But can we make it shorter, using :not somehow? A: You don't have to use a function for this component query. If you have other panels somewhere in your framework that are not collapsed query('[collapsed=false]') would also include those so that was probably the problem you were having. But you can limit the query to only direct children by calling child instead: Ext.getCmp("myaccordion").child("[collapsed=false]"); Or you can limit it to direct children in the selector string itself if you give the accordion an id config, as it looks like you did: (id: 'myaccordion'). You can use: Ext.ComponentQuery.query('#myaccordion > panel[collapsed=false]') If you have the accordion configured for only one expanded panel at a time (the default config) that will give you an array with one item - the expanded panel. If you have more than one expanded panel they will each be contained in the array. A: You could do: Ext.onReady(function(){ var p1 = Ext.create('Ext.panel.Panel', { renderTo: document.body, width: 100, height: 100, title: 'Foo', collapsed: true }); var p2 = Ext.create('Ext.panel.Panel', { renderTo: document.body, width: 100, height: 100, title: 'Foo', collapsed: false }); console.log(Ext.ComponentQuery.query('[collapsed=false]')); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7503460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I clear the view file location cache used by the ViewEngine in ASP.Net MVC 3 The ViewEngine in ASP.Net MVC 3 caches the physical paths of the views and partial views which is causing errors when I add or move view files in my production environment. Is there a way I can clear that cache at runtime? I found one article online that says that cache is stored in HttpContext.Cache, but I'm not sure which entry it is. A: Here's the key used by the Razor view engine: // System.Web.Mvc.VirtualPathProviderViewEngine private string CreateCacheKey(string prefix, string name, string controllerName, string areaName) { return string.Format(CultureInfo.InvariantCulture, ":ViewCacheEntry:{0}:{1}:{2}:{3}:{4}:", new object[] { base.GetType().AssemblyQualifiedName, prefix, name, controllerName, areaName }); } So for example if you wanted to clear the cache location of the Index view for Home controller you would remove the following key from the HttpContext.Cache: HttpContext.Cache.Remove(":ViewCacheEntry:System.Web.Mvc.RazorViewEngine, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35:View:Index:Home::"); and for the _LogOnPartial.cshtml partial: HttpContext.Cache.Remove(":ViewCacheEntry:System.Web.Mvc.RazorViewEngine, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35:Partial:_LogOnPartial:Home::"); You should obviously be aware that you are using a totally undocumented feature that could be changed without any notice and your code could stop working in a future version of ASP.NET MVC.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Inheritance problems in Java I have some problems with getting inheritance to work. In the parent class, the array Coefficients is private. I have some access methods but I still can't get it to work. import java.util.ArrayList; public class Poly { private float[] coefficients; public static void main (String[] args){ float[] fa = {3, 2, 4}; Poly test = new Poly(fa); } public Poly() { coefficients = new float[1]; coefficients[0] = 0; } public Poly(int degree) { coefficients = new float[degree+1]; for (int i = 0; i <= degree; i++) coefficients[i] = 0; } public Poly(float[] a) { coefficients = new float[a.length]; for (int i = 0; i < a.length; i++) coefficients[i] = a[i]; } public int getDegree() { return coefficients.length-1; } public float getCoefficient(int i) { return coefficients[i]; } public void setCoefficient(int i, float value) { coefficients[i] = value; } public Poly add(Poly p) { int n = getDegree(); int m = p.getDegree(); Poly result = new Poly(Poly.max(n, m)); int i; for (i = 0; i <= Poly.min(n, m); i++) result.setCoefficient(i, coefficients[i] + p.getCoefficient(i)); if (i <= n) { //we have to copy the remaining coefficients from this object for ( ; i <= n; i++) result.setCoefficient(i, coefficients[i]); } else { // we have to copy the remaining coefficients from p for ( ; i <= m; i++) result.setCoefficient(i, p.getCoefficient(i)); } return result; } public void displayPoly () { for (int i=0; i < coefficients.length; i++) System.out.print(" "+coefficients[i]); System.out.println(); } private static int max (int n, int m) { if (n > m) return n; return m; } private static int min (int n, int m) { if (n > m) return m; return n; } public Poly multiplyCon (double c){ int n = getDegree(); Poly results = new Poly(n); for (int i =0; i <= n; i++){ // can work when multiplying only 1 coefficient results.setCoefficient(i, (float)(coefficients[i] * c)); // errors ArrayIndexOutOfBounds for setCoefficient } return results; } public Poly multiplyPoly (Poly p){ int n = getDegree(); int m = p.getDegree(); Poly result = null; for (int i = 0; i <= n; i++){ Poly tmpResult = p.multiByConstantWithDegree(coefficients[i], i); //Calls new method if (result == null){ result = tmpResult; } else { result = result.add(tmpResult); } } return result; } public void leadingZero() { int degree = getDegree(); if ( degree == 0 ) return; if ( coefficients[degree] != 0 ) return; // find the last highest degree with non-zero cofficient int highestDegree = degree; for ( int i = degree; i <= 0; i--) { if ( coefficients[i] == 0 ) { highestDegree = i -1; } else { // if the value is non-zero break; } } float[] newCoefficients = new float[highestDegree + 1]; for ( int i=0; i<= highestDegree; i++ ) { newCoefficients[i] = coefficients[i]; } coefficients = newCoefficients; } public Poly differentiate(){ int n = getDegree(); Poly newResult = new Poly(n); if (n>0){ //checking if it has a degree for (int i = 1; i<= n; i++){ newResult.coefficients[i-1]= coefficients[i] * (i); // shift degree by 1 and multiplies } return newResult; } else { return new Poly(); //empty } } public Poly multiByConstantWithDegree(double c, int degree){ //used specifically for multiply poly int oldPolyDegree = this.getDegree(); int newPolyDegree = oldPolyDegree + degree; Poly newResult = new Poly(newPolyDegree); //set all coeff to zero for (int i = 0; i<= newPolyDegree; i++){ newResult.coefficients[i] = 0; } //shift by n degree for (int j = 0; j <= oldPolyDegree; j++){ newResult.coefficients[j+degree] = coefficients[j] * (float)c; } return newResult; } } Can anyone help me fix my Second class that inherits from the one above? I cant seem to get my multiply and add methods for the second class to work properly. public class QuadPoly extends Poly { private float [] quadcoefficients; public QuadPoly() { super(2); } public QuadPoly(int degree) { super(2); } public QuadPoly(float [] f) { super(f); if (getDegree() > 2){ throw new IllegalArgumentException ("Must be Quadratic"); } } public QuadPoly(Poly p){ super(p.coefficients); for (int i = 0; i < coefficients.length; i++){ if (coefficients[i] < 0){ throw new Exception("Expecting positive coefficients!"); } } } // public QuadPoly(Poly p){ // super(p.coefficients); //} public QuadPoly addQuad (QuadPoly p){ return new QuadPoly(super.add(p)); } public QuadPoly multiplyQuadPoly (QuadPoly f){ if (quadcoefficients.length > 2){ throw new IllegalArgumentException ("Must be Quadratic"); } return new QuadPoly(super.multiplyPoly(f)); } A: I would make the coefficients protected or use an accessor method. I wouldn't throw a plain checked Exception. An IllegalArgumentException would be a better choice. What is quadcoefficients? They don't appear to be set anywhere. A: You put coefficients private. I wouldn't change this but I would add a getter method into Poly class: public class Poly { //somecode here public float[] getCoefficients(){ return this.coefficients; } } Then I would use it by the getter method in other code; public QuadPoly(Poly p){ super(p.getCoefficients); //some more code here } Even if you make coefficient protected, you are trying to reach coefficients field of another Object, which is a parameter. So it is not related to inheritance and the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MVC 3 Displaying a dynamic image created in a controller I'm trying generate a images/chart in my controller and have that image displayed in an image tag in the view. In my view, I have <div id="graphcontainer"><a href="#">Close Graph</a><img id="chartImage" alt="" /></div> and in my controller (called EventReport) I have a method called "BuildChart". My idea was to capture the click event of a button designated as the build report button. In the click event handler I would want to assign the image's source to something like "/EventReport/BuildChart" to have the image control populated. Here's what's in the controller public ActionResult BuildChart() { var chart = new Chart { Height = Unit.Pixel(400), Width = Unit.Pixel(600), AntiAliasing = AntiAliasingStyles.Graphics, BackColor = Color.White }; // Populate chart here ... var ms = new MemoryStream(); chart.SaveImage(ms); return File(ms.ToArray(), "image/png"); } I'm just having problems wiring this up. Am I on the right track? Thanks! A: Set src of your image as link to your action on the click of your button, eg: using jquery: $('#build-chart').click(function() { $('#chartImage').attr('src', '/EventReport/BuildChart'); }); and action will be asked for content for image. Probably some 'loading' indicator will be needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to select all element leaving first element? I have jquery selector like $("li a") how can I modify it so it select all elements leaving first anchor tag ? A: .not is used to exclude elements and the pseudo-selector :first is used to get the first one. You can combine both to exclude first element like below: $("li a").not(":first"); Or you can use the :not pseudo-selector: $("li a:not(:first)"); Update I have profiled three different methods and it appears that using the .not method along with :first selector is faster (tested in Chrome 14). And another update, after reading @Jon's comment from the jQuery docs... using .slice is significantly faster than all jQuery methods! Here's a screenshot of the test results on Chrome 14: A: You can use the :gt selector: $("li a:gt(0)") Update: If you are interested in performance, the fastest by far is $("li a").slice(1) about which the docs say: Because :gt() is a jQuery extension and not part of the CSS specification, queries using :gt() cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use $("your-pure-css-selector").slice(index) instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7503471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }