text
stringlengths
8
267k
meta
dict
Q: Rails 3.1 Sprockets require directives - is there a way to exclude particular files? If I'm using //=require_tree . in application.css, is there a way to exclude particular files other than resorting to //=require_directory and tree organization? Perhaps something like //= require_tree ., {except: 'something'} A: This is possible with Sprocket's new stub directive which is available in Sprockets v2.2.0 and up. However, Rails 3.2 will only ever use Sprockets v2.1.3 which does not have this feature. As of now, the current Edge Rails has the stub directive and it will officially be in Rails 4.0 and above. Usage: //= require jquery //= require_tree . //= stub unwanted_js stub directives can not be overridden by subsequent require or include directives. If you want to use the stub directive in your Rails 3.2 project you will have to switch to Edge Rails, or branch your Rails gem with its Sprockets dependency modified to version 2.2.0. A: NB: This answer is now out of date, with an update to Sprockets having this feature. See the answer below. === This is not possible with current Sprockets directives, but it seems like a handy feature. The other way to to manually list each file you want. Perhaps you could file this as a feature request over on the Sprockets repo? :-) A: Since the release of rails 3.2.9, it has support to lock the sprockets to version 2.2.x so that we can use the //= stub directive that latest sprockets have. //= stub unwanted_js http://weblog.rubyonrails.org/2012/11/12/ann-rails-3-2-9-has-been-released/ So, to use it, just upgrade to Rails 3.2.9 A: The following monkey patch solves this for me: module Sprockets class DirectiveProcessor # support for: require_tree . exclude: "", "some_other" def process_require_tree_directive(path = ".", *args) if relative?(path) root = pathname.dirname.join(path).expand_path unless (stats = stat(root)) && stats.directory? raise ArgumentError, "require_tree argument must be a directory" end exclude = args.shift == 'exclude:' ? args.map {|arg| arg.sub(/,$/, '')} : [] context.depend_on(root) each_entry(root) do |pathname| if pathname.to_s == self.file or exclude.include?(pathname.basename(pathname.extname).to_s) next elsif stat(pathname).directory? context.depend_on(pathname) elsif context.asset_requirable?(pathname) context.require_asset(pathname) end end else # The path must be relative and start with a `./`. raise ArgumentError, "require_tree argument must be a relative path" end end end end A: Try better the https://github.com/QubitProducts/miniMerge It supports not only JS and is in basic mode sprockets compatible. You can exclude not only on file levels but block or even lines. Full depenedncies managment with multiple source bases. I used sprockets in past and this one is better, I use it also for CSS.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "43" }
Q: Should This Be In Its Own Stylesheet, and How? (PHP In Stylesheet?) Building a WordPress options panel. One of the things it does is allow users to pick custom colors. I use a default stylesheet, then call styles for custom inputs. However, I simply insert this in the header instead of having these custom values reside in their own stylesheet (since I need to call the user's choice via PHP). As an example, I have code in my header like this: <style type="text/css"> p a { <?php echo get_option('to_custom_css'); ?> } </style> And in my functions: array( "name" => "Custom CSS", "desc" => "Want to add any custom CSS code? Put in here, and the rest is taken care of. This overrides any other stylesheets. eg: a.button{color:green}", "id" => $shortname."_custom_css", "type" => "text", "std" => ""), How would I have this reside in its own stylesheet while still using <?php echo get_option('to_custom_css'); ?> to call the users input? A: You can create a stylesheet in PHP, but need to set the Content-type header to text/css. In your HTML: <head> <link rel="stylesheet" type="text/css" href="user-styles.php" /> <!-- ... --> The in user-styles.php: <?php header('Content-type: text/css'); ?> /* now put your css here : */ p a { <?php echo get_option('to_custom_css'); ?> } /* and so on... */ A: First, add this to your .htaccess file so that it will interpret php found in css files: AddType application/x-httpd-php .css Then, link to the external stylesheet. Make the link dynamically include the information needed to determine the user's css values (probably an id number), like this: <link rel="stylesheet" href="http://www.yourserver.com/customstyle.css?id=<?php echo $userid; ?>" type="text/css" /> Finally, put php code in the stylesheet that prints out the css dynamically, like this: <?php echo get_option('to_custom_css'); ?> Use $_GET['parametername'] to retrieve the parameters allowing you to calculate the css data. A: Ultimately you should be writing out the CSS to a file that can be included from the hosting page. That way it can be cached by the browser. <link rel="stylesheet" type="text/css" href="user1024/style.css" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7602396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Selecting Greatest N records in X groups So I've been running through all the questions under the greatest-n-per-group tag, and either I don't understand what I'm reading, or nothing has fit my needs so far. This link has also provided a lot of useful information, but still no answer. So I've got a table with the following fields: * *id (unique int) *user_id (int) *category (varchar) *score (int) *interest (int) I believe my problem strays from the common greatest-n-per-group question, in that I don't need the greatest N for every group. I need the greatest N records for X groups. So, I need to get X categories with the highest interest (simple, GROUP BY category ORDER BY interest, LIMIT X). And then I need to get N records with the highest score for each of those categories. How would my query look for something like this? Sorry if this is really a duplicate of every other greatest-n-per-group question, and I just don't understand how they work. Feel free to close this if so. Update: Per @tehshrike's prodding, here's a bit more information. Really what's happening is that my user's have interest in lots of different categories. I would like to generate a list of users with the highest score in the categories that the original user is interested in. So one possible thing that I'm looing for is: The 15 users with the highest score in the 4 categories that user 1 is most interested in. For a specific user_id find Top X categories (with highest interest for that specific user) and for those (X categories) find Top N users (with highest score for those categories). A: SELECT catX.category catX.interest t1.user_id t1.score FROM ( SELECT category , interest FROM tableX WHERE user_id = @user_id_we_are_interested_in --- specific user ORDER BY interest DESC LIMIT @X --- top @X categories per specific user ) AS catX JOIN tableX AS t1 ON t1.category = catX.category LEFT JOIN tableX AS t2 ON t2.category = t1.category AND t2.score > t1.score GROUP BY t1.category , t1.user_id HAVING COUNT(t2.score) < @N --- top @N users per category ORDER BY catX.interest DESC , t1.score DESC A: You probably want to write your groupwise-max query, and then limit it down by JOINing on something like this: JOIN ( SELECT category FROM your_table ORDER BY interest LIMIT 10 ) AS just_get_these_categories ON just_get_these_categories.category = your_table.category (This is assuming that category is a candidate key in your table) Edit: based on further questions, it looks like what you want is not possible. (See: chatlog)
{ "language": "en", "url": "https://stackoverflow.com/questions/7602398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: GWT Runtime vs Development mode We are using GWT to develop a complex application . In development mode all the RPC's and the application work perfectly with reasonable performance. But when we are in production mode some RPC calls are never been performed and the server side code never gets hit. We do a loadmask on some RPC calls and hid the loadmask on success. But since the server code never got executed the loadmask is for ever and the application is in dead state. Does anyone knows the reason behind the differences in dev and production mode? Also how do we track and debug on what's exactly happening in production mode apart from logging? I kind of know that the problem is with the GWT serialization but how can know what the exact problem is so that i can modify my code. Are there any tools that i could take advantage of? I currently run my application in IE-8 Thanks A: There are several ways on how to debug these kind of problems: * *For starters you could try to use FireBug or any other developer tool to check the RPC payload and if actually a server request is fired in development mode. *You can tell the compiler to not generate obfuscated output code (-pretty or -detailed) and then use Firebug with conditional breakpoints to check the code for errors. *Sometimes an exception is thrown only in production mode and not in development. You can also check that with the developer tools (firebug, java console).
{ "language": "en", "url": "https://stackoverflow.com/questions/7602400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: traversing DOM from code-behind I have a asp.net webpage with a series of hidden input fields that I use in order to communicate values from client-side to code-behing at submit time. <input type="hidden" id="zorro1" value="somevalue set at runtime from client-side" /> <input type="hidden" id="zorro2" value="somevalue set at runtime from client-side" /> .../... <input type="hidden" id="zorron" value="somevalue set at runtime from client-side" /> Now I need to extract these values from code-behind. I can write this ugly thingy: dim aValue as string = zorro1.value dim aValue as string = zorro2.value .../... dim aValue as string = zorron.value It works, but I would like to "findcontrol" each hidden input like this, with LINQ, in pseudo-code: dim inputControls = from c in page.controls where id.startswith("zorro") select s for each ic in inputControls aValue = ic.value aId = ic.ID next Can someone put me in the right direction? A: Found this answer somewhere on the web, and it works: Within the HTML page itself, you can add objects at your convenience, like: <input type="hidden" id="someMeaningfulID" runat="server" value="some Value" /> From Javascript its easy to change the value of such objects. In your code behind, add this sub: Private Sub AddControls(ByVal page As ControlCollection, ByVal controlList As ArrayList) For Each c As Control In page If c.ID IsNot Nothing Then controlList.Add(c) End If ' A pinch of recursivity never hurts :-) If c.HasControls() Then call AddControls(c.Controls, controlList) End If Next End Sub And when you need it: Dim controlList As New ArrayList() Call AddControls(Page.Controls, controlList) For Each c In controlList If c.id.startswith("something I'm looking for") Then ... If c.value <> "" Then.... If c.someProperty = someValue tThen... .../...
{ "language": "en", "url": "https://stackoverflow.com/questions/7602402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the best way to get the values of a radio button set with lxml? For example I have the following radio buttons: <input type="radio" name="hand" id='hand_left' checked value="L"> <label for='hand_left'>Left</label> <input type="radio" name="hand" id='hand_right' value="R"> <label for='hand_right'>Right</label> And have the following parsing code: import lxml.html as lh doc=lh.parse(response) # response is the response of # http post that returns the above html for el in doc.iter('input'): if el.name == 'hand': print el That prints out two InputElements, but lxml only returns a value for the checked one and returns None for the unchecked one (as per the lxml docs). I'd like to get each of the potential values regardless of which one is checked. <InputElement 8715f8c name='hand' type='radio'> <InputElement 8715f8f name='hand' type='radio'> A: You could use el.attrib['value'] instead of el.value
{ "language": "en", "url": "https://stackoverflow.com/questions/7602406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how do I find elements that contain a data-* attribute matching a prefix using jquery I'm want to create a selector to find elements which have attributes starting with a string. At this point, I'm assuming this selector does not exist. Do I need to extend the selector capabilities? Extending jQuery’s selector capabilities by James Padolsey I need to express something like the Attribute Contains Prefix Selector [name|="value"], but instead of matching "value", I need to match against the name of the attribute, and not the value of the attribute. <tag data-plugin-option1="val1" data-plugin-option2="val2" /> I'd like to end up with a syntax like this: $('tag(:attr|="data-plugin")') which should find the element tag because it has at least one element that starts with data-plugin A: Well, I guess I'm reading your question differently. The way I read it, you want to create a custom selector that selects elements that have a given attribute name (or the start of that name). If so, I think you'd need to iterate of the attributes collection for each element. DEMO: http://jsfiddle.net/GgmM7/ $.extend($.expr[':'],{ attrNameStart: function(el,i,props) { var hasAttribute = false; $.each( el.attributes, function(i,attr) { if( attr.name.indexOf( props[3] ) !== -1 ) { hasAttribute = true; return false; // to halt the iteration } }); return hasAttribute; } }); $('img:attrNameStart(data-plugin)')
{ "language": "en", "url": "https://stackoverflow.com/questions/7602410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Dynamic Increase / Decrease the number with C# I have two buttons to reduce or increase the number. Also, I have a label which is has value zero. How can I increase or decrease without giving zero value to the Label in C#? Code: int sayi = int.Parse(lbltext1.Text); sayi = sayi - 1; lbltext1.Text = sayi.ToString(); A: Store it as a member variable. Then increment/decrement it. Then set the Label's Text property to the string version of the value. A: Try something like this...(not tested) void IncreaseBtn_Click(Object sender, EventArgs e) { var value = this.myLabel.Text; var intValue = 0; Int32.TryParse(value, out intValue); this.myLabel.Text = (++intValue).ToString(); } void DecreaseBtn_Click(Object sender, EventArgs e) { var value = this.myLabel.Text; var intValue = 0; Int32.TryParse(value, out intValue); this.myLabel.Text = (--intValue).ToString(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7602419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Copy specific file types from one host to another I'm creating a bash script that automatically copies C source and header files from a particular directory in another host to the directory I'm in on the current host. It currently generates this command: ssh host2 "cd dir1/dir2 && find . -maxdepth 1 -regextype posix-extended -regex '.*.(c|h)' | tar -T - -c -f -" | tar xf - The problem is I get this error: "tar: This does not look like a tar archive" This error is output by the final tar (tar xf -) because for some reason the tar file that gets piped is corrupt. If I do it instead using a combination of ssh, tar and scp it works fine, but that requires me to enter my password (for host2) twice (once for the ssh and once for the scp). I could enter the password as an argument to the script, but I don't want it to appear in my bash history. Any ideas? A: Have you considered using rsync with appropriate --include and --exclude flags? rsync can copy over ssh, and you should be able to copy the entire tree (or an subset) with a single command. Also, if your only concern is having to type in your password you could also just try using authorized keys (and possibly ssh-agent) so you don't need to type in your password to access the other host. A: Why not use rsync to do this job instead? It supports --filter which fits your needs exactly. Here's a sample: http://ubuntuforums.org/showthread.php?t=1240150
{ "language": "en", "url": "https://stackoverflow.com/questions/7602421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AS3 Objects not being displayed I´m trying to display two movie clips on the scene. I made an action script file called main.as and the .fla file is calling the main class. The button class is a button movieclip. This is the code: package { import flash.display.MovieClip; import flash.events.MouseEvent; import flash.events; public class button extends SimpleButton { public function button() { // constructor code } } } public class main extends MovieClip { private var button1:button = new button; private var button2:button = new button; public function main() { // constructor code button1.x = 550/4*3; button1.y = 400/4*3; addChild(boton1); button2.x = 550/4*3; button2.y = 400/4*3; addChild(boton2); button1.addEventListener(MouseEvent.CLICK,pressButton); } private function pressButton(e:Event){ trace("Pressing button"); } } } I don´t know what went wrong, this error pops up in the console: S:\flash3\Clase2\main.as, Line 24 1046: Type was not found or was not a compile-time constant: Event. A: The error means you need to import flash.events.Event in your class. However you should use MouseEvent in your function instead, not Event. private function pressButton(event : MouseEvent) : void { // } A: 1: addChild(boton1); should be written with 2x 't' addChild(botton1); 2: pressButton(e:Event){ should be pressButton(e:MouseEvent){ and you should import flash.events.MouseEvents
{ "language": "en", "url": "https://stackoverflow.com/questions/7602423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In MVC Razor, how do you do a RenderSection defined below a sub-layout? I have a top-level _Layout.cshtml that looks something like this: <html> <head> @RenderSection("Header", required: false) </head> <body> @RenderSection("LeftPane", required: false) @RenderSection("RightPane", required: false) @RenderBody() </body> </html> Then I have two "sub-layouts." One defines just the LeftPane section, the other defines both a LeftPane and a RightPane. These sub-layouts are called _LeftPane.cshtml and _LeftPlusRightPane.cshtml, and they have Layout set to "_Layout.cshtml." Then in each View .cshtml file, I set the Layout to either _LeftPane.cshtml or _LeftPlusRightPane.cshtml, depending on what I want to show up on the page. That all works fine. The problem is with the new "Header" section I've added in the <head> portion of the document. This section is not defined in the sub-layouts, but rather in the actual Views. When I try to view something this way, I get the error: The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_LeftPlusRightPane.cshtml": "Header". I don't want to render the Header section in the sublayouts, I want to render it up in the _Layout.cshtml file. How do I "pass through" the defined Header section from the low level view, through the sub-layouts, up to the top _Layout? A: You can nest layouts. So _Layout2 has Layout = "_Layout.cshtml"; You can also use _ViewStart files in each of your View subfolders to specify a different default layout for that subfolder. To "pass through" the section, you just do something like this: @section Header {@RenderSection("Header", false)} That allows you to pass content up the chain.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: recaptcha words in other language Is there any way to set recaptcha to display challenge words in other language? I know there is a property "lang" but it localizes UI not words. I have website in other language and it doesn't make sense having recaptcha words in english because user may not have those characters in their keyboard. for example, if my website is in Russian language, i would like recaptcha words to show up in Russian language not in english. any help/suggestion? A: The problem is that reCaptcha is actually part of a project for digitising books. According to Wikipedia, they're currently digitising the New York Times archive and some Google Books. Until they start digitising Russian books, I think you're out of luck with reCaptcha.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Archiving, Scheme settings and Code Signing in Xcode 4.2 I am in the process of submitting an app to the App Store. I am using Xcode 4.2 (Build 4C151a). In the build settings I can choose iPhone Distribution for code signing under Release - Any iOS SDK. Then I go to menu Product > Edit Scheme and set the Archive Build configuration to release, Then Product > Archive. The first problem I have is that it builds and says build succeeded but no archive file shows in the Organizer. When I go to the Archive files location through Finder I see that that specific Archive file is Zero Bytes. If I repeat the same thing but change the Archive Build Configuration to Debug under Edit Scheme, the Archive file gets created and shows up in the Organizer. Now comes the second problem, when I choose that just created Archive and hit Share... button and choose iOS App Store Package (.ipa), for Identity, I cannot choose iPhone Distribution (It's gray and it says does not match any valid identity/profile pairs) even though in the Build Setting, it was fine and matched. However, iPhone Developer shows up active under Identity selections. Any help with either or both of these problems is highly appreciated. A: The problem persisted with downgrading to the last full-version of Xcode. Apparently, I missed some steps when I created the Distribution Provisioning Profile. After creating Distribution Provisioning Profile correctly, everything started to act as expected. A: You cannot submit apps to the appstore using beta/developer preview versions of Xcode. In this case, 4.1.1 is the latest public release, via the Mac App Store.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android USB Virtual COM port on an Archos? is there any option to have Virtual COM port Host on Android that would communicate with a connected device(via cable and physical USB unterface) in a virtual COM port way (fileopen/fileread/filewrite/fileclose)? I believe that kernel reconfiguring/recompiling is not possible A: There is no option for doing that. We gave up and change software on a device from classical RS232 to HID and now it works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Toggle divs open and close - ensure only one div visible at any time, not all I am using the below script to toggle open and close divs on click: (function ($) { $.fn.showHide = function (options) { //default vars for the plugin var defaults = { speed: 1000, easing: '', changeText: 0, showText: 'Show', hideText: 'Hide', }; var options = $.extend(defaults, options); $(this).click(function () { // this var stores which button you've clicked var toggleClick = $(this); // this reads the rel attribute of the button to determine which div id to toggle var toggleDiv = $(this).attr('rel'); // here we toggle show/hide the correct div at the right speed and using which easing effect $(toggleDiv).slideToggle(options.speed, options.easing, function() { // this only fires once the animation is completed if(options.changeText==1){ $(toggleDiv).is(":visible") ? toggleClick.text(options.hideText) : toggleClick.text(options.showText); } }); return false; }); }; })(jQuery); What would be the best method to automatically close any currently open divs before opening the next (to prevent all being open on page - only have the clicked link visible) HTML is below: <a href="#" class="show_hide" rel="#slidingDiv">View</a><br /> <div id="slidingDiv" style="display:none;"> Fill this space with really interesting content. </div> <a href="#" class="show_hide" rel="#slidingDiv_2">View</a><br /> <div id="slidingDiv_2" style="display:none;"> Fill this space with really interesting content. </div> Im guessing just a quick check before the open is fired - but Im unable to thus far get it to work. Many thanks in advance! A: Add a slidingDivs class to all of the sliding divs and simply call: $(".slidingDivs").hide(); I don't think its worth worrying about only hiding the visible ones, just hide them all. A: This may be useful $(toggleDiv).siblings(".slidingDivs").hide(); $(toggleDiv).toggle(); where toggle div is defined in your code as var toggleDiv = $(this).attr('rel'); and just add class "slidingDivs" to divs with id "slidingDiv" and "slidingDiv_2"
{ "language": "en", "url": "https://stackoverflow.com/questions/7602445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SelectedValue after updating dropdown with json/webmethod I have a dropdown list to which items are added via a json/webmethod call - an "add new item to the box" type of solution. Now - this problem is, that if I select the new value, the _comobox1.SelectedValue is empty. The controls are validated via a RequiredFieldValdiator so I am pretty sure that a value is indeed selected, and posted. If I look at _comobox1.Items i even see the new item, with the correct value - any thoughts? A: You must add this value to a hidden field and read it upon post. This is by design (and for security reasons) in asp.net web forms. I'm assuming you also turned off event validation just to enable this. See: http://social.msdn.microsoft.com/Forums/en/sharepointdevelopment/thread/05a3e4bc-b39e-4165-b04f-c3af9332b578
{ "language": "en", "url": "https://stackoverflow.com/questions/7602447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Calculating the sum of aggregate query set So I have a query set that returns a list of financial institutions and also the total amount of money in investments I have with each institution. views.py total_list = plan.investment_set.filter(maturity_date__gte= '%s-1-1' % current_year).values('financial_institution__abbr').annotate(Sum('maturity_amount')) What I would like to do now, is find a grand total for all that money. My question is, how do I go about calculating the sum to find the total of all my investments. A: I believe you're looking for .aggregate(): total_list = plan.investment_set.filter( maturity_date__gte= '%s-1-1' % current_year ).aggregate(Sum('maturity_amount')) which should give you: {'maturity_amount__sum': <total amount>} A: Sorry this is creating a hassle. Is the field that you're calculating maturity_amount named value? If so, you may try this which worked for your previous question (Using Django to summarize Report): grand_total = plan.investment_set.annotate(Sum('value'))
{ "language": "en", "url": "https://stackoverflow.com/questions/7602451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to suppress the browser top bar while using a BlackBerry BrowserSession I am trying to create an app that will redirect to a certain webpage when run. I would like this app to be full screen with no title bar or browse bar. I am able to call a BrowseSession to bring up the proper website in the browser but it doesn't give me the desired feel. Here is the code I am using for the BrowseSession: BrowserSession browser = Browser.getDefaultSession(); browser.displayPage("http://www.stackoverflow.com"); I have looked into using a BrowseField for this but I find that it does not act in the same fashion as a regular BrowseSession. The device Back Button closes the app and I receive errors in my simulator when JavaScript code is being run. My code for this follows: String baseURL = "http://www.stackoverflow.com"; BrowserFieldConfig config = new BrowserFieldConfig(); config.setProperty(BrowserFieldConfig.JAVASCRIPT_ENABLED, Boolean.TRUE); BrowserField browserField = new BrowserField(config); add(browserField); browserField.requestContent(baseURL); Any help will be greatly appreciated. A: There is no way to control the overall appearance of the browser programmatically, so you're stuck with the title bar and browse bar if you use BrowserSession. And JavaScript is broken for BrowserField on some of the simulators, although I think it may work on all the actual devices (although I wouldn't be surprised if it didn't work). The only thing I can suggest is handling and cancelling the ESC key (aka the back button) press, which should at least prevent the app from closing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: require_once path can't locate file? Here is my folder structure as example: source files/ controller/ ctrl_showData.php model/ Database.class.php Suppose it's now in controller directory, and in the ctrl_showData.php, I want to require the Database.class.php, so I try: require_once(dirname(__FILE__) .'/../model/Database.class.php'); But when I debug, the program stalls when it execute the statement above, which I guess it can't locate the file. I already read similar questions and tried their solutions, but none work. Any one could help? Thanks! Here is the echo result: /controller/../model/Database.class.php Apparently, it doesn't go the parent directory, which is the source files/, then go to the model/ , but don't know why? Thanks for the error message suggestions, the error message is: Warning: require_once(config/config.php): failed to open stream: No such file or directory in /model/Database.class.php Because I also require the the config.php in the database file, which the path is not correct. I didn't think about that, thank you for all your help! A: Try this: require_once(realpath(dirname(__FILE__) . '/..') . '/model/Database.class.php'); A: You could try using: include('./model/Database.class.php') A: You can use a relative path, so using this (below) should just be working: require_once('../model/Database.class.php'); A: Try wrapping that call in realpath() http://us.php.net/manual/en/function.realpath.php If your path isn't resolving correctly it will return null, and it cleans up the relative path mess you have in the middle. A: What is the error in your error log? Do you get something that says the file can't be found? Do you get an error at all? Use: error_reporting E_ALL ini_set('display_errors', 1); And then see what is the error. If your error is really about including a missing file, check that the path is right, also check that your include path is right. You could by error have removed the "." in the include_path directive or your CMS could have done so if it wants to restrict you to using their autoloader. Another idea is to EXIT('BLA') in your file and call your page again to see if the BLA appears, if it does, it means your file is included but there is bug in it and thats why you stall.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using XML and XSLT I'm just trying to create an example XML file with an XSL style sheet. The problem is, when i parse the two files, i get a strange output. here is the XML: <?xml version="1.0" encoding="utf-8"?> <?xml-stylesheet type="text/xsl" href="mySchema.xsl"?> <Artists> <Artist> <BandName>The Cure</BandName> <Albums> <Album> <AlbumTitle>Disintegration</AlbumTitle> <Tracks> <track> <Title>Plain Song</Title> <Order>1</Order> <Lenght> <min>5</min> <sec>12</sec> </Lenght> </track> <track> <Title>Pictures Of You</Title> <Order>2</Order> <Lenght> <min>7</min> <sec>24</sec> </Lenght> </track> </Tracks> </Album> <Album> <AlbumTitle>Wish</AlbumTitle> <Tracks> <track> <Title>A Letter To Elise</Title> <Order>4</Order> <Lenght> <min>5</min> <sec>14</sec> </Lenght> </track> <track> <Title>From the Edge of the Deep Green Sea</Title> <Order>2</Order> <Lenght> <min>7</min> <sec>45</sec> </Lenght> </track> </Tracks> </Album> </Albums> </Artist> <Artist> <BandName>The Pogues</BandName> <Albums> <Album> <AlbumTitle>If I Should Fall from Grace with God</AlbumTitle> <Tracks> <track> <Title>Fairytale of New York</Title> <Order>1</Order> <Lenght> <min>2</min> <sec>20</sec> </Lenght> </track> <track> <Title>Sit Down by the Fire</Title> <Order>13</Order> <Lenght> <min>4</min> <sec>10</sec> </Lenght> </track> </Tracks> </Album> <Album> <AlbumTitle>Peace And Love </AlbumTitle> <Tracks> <track> <Title>Young Ned Of The Hill</Title> <Order>3</Order> <Lenght> <min>2</min> <sec>45</sec> </Lenght> </track> <track> <Title>Boat Train</Title> <Order>11</Order> <Lenght> <min>2</min> <sec>40</sec> </Lenght> </track> </Tracks> </Album> </Albums> </Artist> </Artists> and here is the XSLT file: <?xml version="1.0" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="Artist"> <html> <body> <xsl:apply-templates select="BandName"/> <br></br> </body> </html> </xsl:template> <xsl:template match="BandName"> <b>Found a band!</b> </xsl:template> </xsl:stylesheet> When i render the two, using visual studio ide, i can see how the XML file transformed to XHTML. the output looks like this: <?xml version="1.0" encoding="utf-8"?> <html><body><b>Found a band!</b><br /></body></html> <html><body><b>Found a band!</b><br /></body></html> When i look at this in the browser, its fine, but i'm not happy how the < html >< body >< /body >< /html > is displayed more that once. What am i doing wrong? thanks jason A: I've edited your question to what I think the problem is, that the body and html tag are being included twice. That's because you're matching the template for Artist twice. Since the template includes both the body and html tags, they're being included twice in the output. You need to use a for-each to match multiple instances in a single template. Below is an excerpt from http://www.w3schools.com/ giving an example: <xsl:for-each select="catalog/cd"> <tr> <td><xsl:value-of select="title"/></td> <td><xsl:value-of select="artist"/></td> </tr> </xsl:for-each> Check out the w3school xsl section for more basics: http://www.w3schools.com/xsl/ A: Your match="Artist" template is getting applied twice because there are two Artist in your source document. This is what's resulting in two html elements in the result tree. Try using this slightly modified version of your stylesheet: <?xml version="1.0" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="Artists"> <html> <body> <xsl:apply-templates select="Artist"/> <br></br> </body> </html> </xsl:template> <xsl:template match="Artist"> <xsl:apply-templates select="BandName"/> </xsl:template> <xsl:template match="BandName"> <b>Found a band!</b> </xsl:template> </xsl:stylesheet> A: Your first template is matching multiple Artist elements. For each Artist element it matches, it is outputting your <html><body>...</> tree to the result document. You can try something like the following. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/Artists"> <html> <body> <xsl:apply-templates select="Artist/BandName"/> <br></br> </body> </html> </xsl:template> <xsl:template match="BandName"> <b>Found a band!</b> </xsl:template> </xsl:stylesheet> A: You have more than one Artist element and the match for "select" is grabbing both of them. A: Probably one of the shortest possible solutions (no template matching Artist): <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:template match="/*"> <html> <body> <xsl:apply-templates/> </body> </html> </xsl:template> <xsl:template match="Artist/BandName"> <b>Found a band!</b><br /><br /> </xsl:template> <xsl:template match="text()"/> </xsl:stylesheet>
{ "language": "en", "url": "https://stackoverflow.com/questions/7602461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a java library that supports smart parameter expansion, String.format, and more Here's what I'm looking for: * *Java *Log library that could replace commons logging or slf4j *Parameter expansion only when log level requires it (i.e. no if (log.isDebugEnabled()) blocks) *String formatting the same as java.lang.String.format *Detect java.lang.Throwable as final parameter and log stack trace The goal is to write code like this private static final Log log = new Log.getLog(MyClass.class); // ... String value = "test"; log.debug("The value is [%s]", value); // [1] // ... } catch (Exception e) { log.error("Caught Exception: %s", e.getMessage(), e); // [2] } [1] would print a log statement like The value is [test] If the log level were INFO, the string format operation would not happen. [2] would print Caught Exception: [value of e.getMessage()] java.lang.Exception at com.my.org.MyClass.myMethod(MyClass.[line number]) at [...] This seems like pretty sane behavior to me. I'm surprised I can't easily find a library that does this. EDIT: I should have specified, but slf4j does not meet all these requirements. A: Java SLF4J with Logback binding. Log library that could replace commons logging or slf4j The only well established alternatives are Log4J and java.util.logging... Parameter expansion only when log level requires it (i.e. no if (log.isDebugEnabled()) blocks) In SLF4J if you type: log.debug("Names are: {}", namesCollection); Then costly toString() will only be executed if isDebugEnabled() returns true (no need to provide it explicitly). String formatting the same as java.lang.String.format Do you really need fancy formatting (decimals, currencies, locales) in log files? Or is {} lazy expansion enough (see above)? Detect java.lang.Throwable as final parameter and log stack trace SLF4J works this way since 1.6. A: JBoss has a logging implementation that does printf- and MessageFormat-style formatting. Supposedly it can be used on it's own, but I can't find a project for it, other than its integration with Seam Solder. There are standalone artifacts though: https://repository.jboss.org/nexus/content/groups/public/org/jboss/logging/jboss-logging/
{ "language": "en", "url": "https://stackoverflow.com/questions/7602466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MVC How to return view in ActionFilterAttribute like ActionResult? Is it even possible to return a view from an ActionFilterAttribute? Right now i just have it throw an error and in the OnException in the base controller reroutes to an error page. Would liek to show my NoAccess view like i do when theres an permissions problem inside an action, but have it occur from an attribute on the action. public sealed class UserHasPermissionAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { if(HasPermission == false){ //What are my options here a view? } } } Seen several sites an blogs, but none have explained well, or what i am looking for. A: By the sounds of what you're using your action filter for, it sounds like perhaps you should be using the AuthorizeAttribute? Alternatively you could try just redirecting in the OnActionExecuting method itself, using something like: filterContext.HttpContext.Response.Redirect(errorUrl);
{ "language": "en", "url": "https://stackoverflow.com/questions/7602476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MYSQL query only in set I have a table that links entries with associated tags with the following data in it: entry_id | tag_id 1 | 1 2 | 1 3 | 1 1 | 2 2 | 2 I am trying to write a query that returns only entries tagged with 1 AND 2, in this example entries 1 and 2 would be returned, while 3 would not, because it does not have both tags. The current query I am using works but I know can't be right: SELECT entry_id, GROUP_CONCAT(DISTINCT tag_id ORDER BY tag_id) FROM tags GROUP BY entry_id HAVING GROUP_CONCAT(DISTINCT tag_id ORDER BY tag_id) LIKE "%1,2%"; A: If (entry_id, tag_id) is unique: SELECT entry_id FROM yourtable WHERE tag_id IN (1, 2) GROUP BY entry_id HAVING COUNT(*) = 2 An alternative approach that doesn't require uniqueness and can also be faster: SELECT T1.entry_id FROM yourtable T1 JOIN yourtable T2 ON T1.entry_id = T2.entry_id AND T1.tag_id = 1 WHERE T2.tag_id = 2 A: SELECT entry_id FROM tags t1 inner join tags t2 on (t1.entry_id = t2.entry_id and t1.tag_id = 1 and t2.tag_id = 2) A: This is a good case for a self-join... SELECT tagged1.entry_id FROM tags tagged1 JOIN tags tagged2 ON tagged1.entry_id = tagged2.entry_id AND tagged1.tag_id = 1 AND tagged2.tag_id = 2;
{ "language": "en", "url": "https://stackoverflow.com/questions/7602485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: QtRuby on Mac Os and ruby 1.9.2 i would really like to get down to some ruby programming with QT in Mac OS. I have tried lots of different things to install Qt on Mac os and develop there, but whatever i do does not seem to work. I've tried gems and even source, but i can't get it to work. Has anyone created the same programming environment in Mac OS successfully ? If so, can you give some insight on how to set it up, maybe a good up-to date resource or something ? I can't find something that works. P.S. I have a 64-bit core 2 duo processor. A: There is a fork of the QtBindings gem which is hacked to build on OS X https://github.com/deadprogrammer/qtbindings
{ "language": "en", "url": "https://stackoverflow.com/questions/7602487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: java.lang.SecurityException: Not allowed to start service Intent hey all when installing my app to the emulator I get this: ERROR/AndroidRuntime(465): java.lang.RuntimeException: Unable to start receiver com.myPackage.Widget.MYWidget: java.lang.SecurityException: Not allowed to start service Intent { cmp=com.myPackage/.Widget.MYWidget$MyWidgetService } without permission android.permission.BIND_REMOTEVIEWS here is the code from my manifest <!-- Broadcast Receiver that will process AppWidget updates --> <receiver android:name=".Widget.MYWidget" android:label="@string/app_name"> <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> <!--Broadcast Receiver that will also process our self created action --> <action android:name="com.temp.package.Widget.MYWidget.ACTION_WIDGET_LEFT_RECEIVER" /> <action android:name="com.temp.package.Widget.MYWidget.ACTION_WIDGET_PROGRESSBAR_RECEIVER" /> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/mywidget_widget_provider" /> </receiver> <service android:name=".Widget.MYWidget$MyWidgetService" android:permission="android.permission.BIND_REMOTEVIEWS" android:exported="true" /> <uses-permission android:name="android.permission.BIND_REMOTEVIEWS"></uses-permission> this is my code public class MyWidget extends AppWidgetProvider { @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { Intent svcIntent = new Intent(context, MyWidgetService.class); //svcIntent.setData(Uri.parse(svcIntent.toUri(Intent.URI_INTENT_SCHEME))); context.startService(svcIntent); } public static class MyWidgetService extends Service { @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); // Update the widget RemoteViews remoteView = buildRemoteView(this); // Push update to homescreen pushUpdate(remoteView); // No more updates so stop the service and free resources stopSelf(); } public RemoteViews buildRemoteView(Context context) { RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout); //do stuff return remoteViews; } @Override public void onConfigurationChanged(Configuration newConfig) { int oldOrientation = this.getResources().getConfiguration().orientation; if(newConfig.orientation != oldOrientation) { // Update the widget RemoteViews remoteView = buildRemoteView(this); // Push update to homescreen pushUpdate(remoteView); } } private void pushUpdate(RemoteViews remoteView) { ComponentName myWidget = new ComponentName(this, MyWidget.class); AppWidgetManager manager = AppWidgetManager.getInstance(this); manager.updateAppWidget(myWidget, remoteView); } @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } } A: Get rid of: android:permission="android.permission.BIND_REMOTEVIEWS" android:exported="true" from your <service> element, as neither are needed here. This should clear up your problem. A: it's almost working, I'm in vertical mode when I add the Widget. when on orientation change happens(To Horizontal) - I thought that onConfigurationChanged should be called but it is not- thus my widget is not working after For this you need to mention the android:configChanges parameter for which you want to handle your on. Please not if you working on ICS code you need to put 'screenSize' element also there with other parameters like 'keyboardHidden|screenSize' Hope this will help you. I mentioned this for activity only...I took your question wrongly. Thanks for update.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I disable these log messages in JasperReports? I am getting TONS of these messages when generating a PDF with Jasper now: INFO: Overriding bean definition for bean 'stackedAreaType': replacing [Generic bean: class [org.springframework.beans.factory.config.FieldRetrievingFactoryBean]; scope=singleton; abstract=false; lazyInit=false; autowireCandidate=true; autowireMode=0; dependencyCheck=0; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Generic bean: class [org.springframework.beans.factory.config.FieldRetrievingFactoryBean]; scope=singleton; abstract=false; lazyInit=false; autowireCandidate=true; autowireMode=0; dependencyCheck=0; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] Sep 26, 2011 10:42:57 AM org.springframework.beans.factory.support.DefaultListableBeanFactory registerBeanDefinition Obviously I need to set the log level somewhere, just not sure of the command. Any help is appreciated! I am not a Java expert, I use JR embedded in a Ruby app to give my customers nice PDFs. A: I don't know about Jasper specifically but this is the generic approach. You need to change the log4j root log level. Look for a file log4j.properties. Find a line that looks like: log4j.rootCategory=INFO Replace INFO for WARN. Restart your server process. A: I had the same problem, I run a java program from the commandline, that program outputs a pdf to stdout where PHP redirects it to browser, and some library(spring.jar) was outputting lots of INFO that crippled the pdf output, I tried running the java commandline with java -Dlog4j.rootCategory=WARN but for some reason it didn't work, so I finally solved it by setting the logging level programatically: import org.apache.log4j.Logger; import org.apache.log4j.Level; Logger logger = Logger.getRootLogger(); logger.setLevel(Level.WARN); Make sure you have log4j-1.2.16.jar in your CLASSPATH. A: I was able to do this using both of the answers listed here. I created a log4j.properties file and added this in it: log4j.rootCategory=WARN But I also had to add log4j in my classpath.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is there an easier way to fill a column in SQL Server 2008? I'm creating a temp table and I want to fill the column from 0-9999 using T-SQL. create table #tmp5 (userID int) Is there an easier way to fill a column up instead of using a loop? A: There are several approaches detaild here. Apart from looping (with and without IDENTITY), creative use of CTEs, ROW_NUMBER and more. A: Using GO N --N=number of iterations CREATE TABLE #tmp5 (userID int IDENTITY(0, 1)) Go INSERT INTO #tmp5 DEFAULT VALUES Go 10000 Or this: CREATE TABLE #tmp5 (userID int) GO INSERT INTO #tmp5 VALUES (0) GO DECLARE @N int SELECT @N=COUNT(*) FROM #tmp5 INSERT INTO #tmp5 SELECT userID+@N FROM #tmp5 WHERE userID+@N<10000 Go 14 A: use AdventureWorks --Or any database with a sizable amount of objects in it go insert into #tmp5 (userID) select top 9999 row_number() over (order by (select null)) as UserID from sys.objects a cross join sys.objects b This basically row_numbers over all the system objects, and the cross join ensures that you have a whole bunch of them to row number over. Depending on the size of the table you want to create and/or the size of your sys.objects table, you will need more or fewer cross joins.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Loading a data view from a UITableView list of items Okay, so i've been playing with Xcode and learning objective c for about a week now so i'm still pretty new to it all. So i've started creating an iPhone app. I wanted a screen where it would list some items and then when you clicked one of the items it would take the user to a different screen. I found and read a few tutorials on this which were great. However, when i implemented their code into my already created project, it didn't seem to work. I was able to click a button from the first view on my app and it wold successfully display the list of items, but when it came to clicking them, the view didn't change. So i downloaded the source from these tutorials and it worked great in their project but when i copied the code line-for-line into mine, it didn't work. I've been at this for a couple days now and im hours from tearing my hair out haha! I don't get any errors at all. It just simply won't change view when clicking on one of the table items. I feel bad for asking, but im really struggling with this and if anyone has a few minutes to take a look at my project that would be fantastic, just really want to know what's wrong with it and get it fixed. You can find my project here. Once again thanks a lot if you get chance to download and have a look at it, much appreciated. Cheers, Nathan Thanks for your help guys, but in the end it just seemed like it wasn't ever going to work so i just started a new project, navigation based. Which works fine now :) A: I recommend you check out the sample Apple apps in the documentation for UITableViewController. If you search for UITableViewController in the documentation, the top of the description provides you with a list of sample apps in which they have used that tag. UITableViewController Class Reference A: when you click into viewCtrl at the first time, the viewDidLoad will be called, then you go back and return, that function will not be called. So maybe you could reloadData again in the viewDidAppear, then the tableViewCtrl will display correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't provision iOS 5 Beta device with Xcode 4.1 I had to re-install iOS and decided to run the new beta 5 which is out. All went fine during the process except I have a project running in Xcode 4.1 and want to provision my iOS 5 device but it's not showing up when I plug it into my MBP. I setup it up in the developers portal side of things at it shows my device as provisioned. I figure it's my iOS 5 beta not being backwards compatible with the version of Xcode I'm using but I would like to be wrong about this. Any tips? advice? Also posted on the Apple Developers Forum if anyone wants to answer there A: As iOS 5.0 and Xcode 4.2 are both under NDA, I'd suggest you're best placed to raise this question on the Apple dev forums. A: The short answer to this question is you'll need Xcode 4.2. It's a good time to move to 4.2 as Preview 7 is fairly stable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multiple ListViews in ViewFlipper do not load I had 2 activities in a viewflipper with one activity and the other a listactivity. I loaded the list activity with setListAdapter and everything worked great. I added a third activity inside a viewflipper in my main layout. This third activity contains a listview just like my second activity. I switched the ListActivities to activities and load the listviews using setAdapter. The list are empty when I run the application and swipe to the other activity in the viewflipper. If I place the listview in the main xml the listview populates just fine. It appears the list is getting reset after the initial load. A: I figured it out as soon as i hit post! I had to remove the xml from the layout file. <TextView android:id="@android:id/empty" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="5dp" android:paddingRight="5dp" android:background="#000000" android:textColor="#FFFFFF" android:textSize="20sp" android:text="No contacts exists"/> Since I changed to an Activity from a ListActivity this was overriding the listview and would display.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Boost's ASIO, how can I wait on a Windows Event? My program needs to gracefully terminate when a Windows event becomes signaled. I am using Boost's ASIO library for it's sockets. I only have one io_service object. How can I 'register' this event handle with the io_service, so it calls a callback when the event signals? A: If you're looking for termination handling on Windows for Boost.Asio you can take a look at the examples here. In short, you need to handle the win events and call stop on your system. BOOL WINAPI console_ctrl_handler(DWORD ctrl_type) { switch (ctrl_type) { case CTRL_C_EVENT: case CTRL_BREAK_EVENT: case CTRL_CLOSE_EVENT: case CTRL_SHUTDOWN_EVENT: console_ctrl_function(); return TRUE; default: return FALSE; } } This uses a function object: boost::function0<void> console_ctrl_function; that you need to bind to your system's shutdown/stop routine. // Set console control handler to allow server to be stopped. console_ctrl_function = boost::bind(&your_system::shutdown, &s); SetConsoleCtrlHandler(console_ctrl_handler, TRUE); A: Beginning with Boost 1.49 it appears that it is possible to invoke a handle when an event becomes signaled, see http://www.boost.org/doc/libs/1_49_0/doc/html/boost_asio/overview/windows/object_handle.html.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Formatting Textbox in VBA 4 place decimal Is there anyway that you can format a textbox format to have four decimal places at all time? I know how to do it with C# and Visual Basic using a masked textbox, but vba is a bit more challeging due to the lack of function. Any help would be greatly appreciated. Thanks Public Sub UserForm_Initialize() TextBox6.Text = Format(Number, "###.####") End Sub A: You just have the format string incorrect. It should look like this: Public Sub UserForm_Initialize() TextBox6.Text = Format(Number, "0.0000") End Sub A: Try: Public Sub UserForm_Initialize() TextBox6.Text = Format(Number, "0.0000") End Sub Private Sub TextBox6_Exit(ByVal Cancel As MSForms.ReturnBoolean) If IsNumeric(TextBox6.Value) Then TextBox6.Text = Format(TextBox6, "0.0000") End If End Sub Private Sub TextBox6_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer) '// Disregard keys other than 0-9/period/minus sign. If Shift Then KeyCode = 0 Select Case KeyCode Case 8, 13, 46, 48 To 57, 96 To 105, 109, 110, 189, 190 Case Else KeyCode = 0 End Select End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/7602512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Database cross table or one table is better First, I have companies and their templates.templates in file table I related columns like this: FileTemplate ------------------- ID - CompanyID - Description - FileID Second design: FileTemplate ------------------- ID - Description CrossTable: ----------------------------------------- ID - CompanyID - FileID - FileTemplateID Which design is better for performance and maintenance? There will be a lot of data (1 million rows). It will be a very active table. A: As per my knowledge, the second approach is better as you have a huge amount of data. Normalizing is always the best approach. As you said, there should be company and field tables seperately along with the cross reference table. Hope this is of some help for you!!
{ "language": "en", "url": "https://stackoverflow.com/questions/7602513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CU3ER open source alternative Does anyone know either a javascript or flash based alternative for CU3ER? It was open source but has since changed: http://getcu3er.com/ A: Yes Piecemaker http://active.tutsplus.com/freebies/exclusive/exclusive-freebie-the-piecemaker-2/ A: CU3ER is Javascript ready and supports any browser in Javascript. It's 3D in Chrome, Firefox and Safari! http://getcu3er.com/javascript http://getcu3er.com/javascript-3d A: Yes. Here is a nice one : cute slider it's written in pure js and cross browser with smooth transitions
{ "language": "en", "url": "https://stackoverflow.com/questions/7602522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Facebook redirects to canvas url instead of the app on facebook I wrote a facebook app that works as a tab on a page. Here is my config.php file which contains the configuration and redirects to the authentication page if the user has not yet approved the app: <?php require_once("database.php"); require_once("functions.php"); require_once("facebook.php"); $config = array ( 'database' => array ( 'host' => 'localhost', 'name' => '***', 'username' => '***', 'password' => '***' ) ); $db = new Database($config['database']['host'], $config['database']['name'], $config['database']['username'], $config['database']['password']); $db->connect(); $facebook = new Facebook(array( 'appId' => '***', 'secret' => '***', 'cookie' => true )); $user = $facebook->getUser(); if ($user) { try { $me = $facebook->api('/me'); } catch (FacebookApiException $e) { error_log($e); $user = null; } } if ($user) $logoutUrl = $facebook->getLogoutUrl(); else { $loginUrl = $facebook->getLoginUrl(array( 'scope' => 'email,user_about_me,user_likes,user_status,read_stream,offline_access,publish_stream,publish_actions' )); } if (!$user) { echo "<script type=\"text/javascript\">top.location.href = '".$loginUrl."';</script>"; } ?> Here is my main file: <?php require_once("includes/config.php"); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="he" lang="he" dir="rtl"> <head> <meta http-equiv="content-type" content="text/html; charset=windows-1255" /> <title> שער 7 - הלב הצהוב | מכבי תל אביב </title> </head> <body> <?php $clLike = $facebook->api('/me/likes/204623816223540'); if (!empty($clLike['data'])) echo "I'm a fan!"; else echo "I'm not a fan :("; ?> </body> </html> As I mentioned before, this app works as a tab on a facebook page and not as a stand-along facebook app, therefore there is no canvas url. The page tab url is: http://www.gate7.co.il/fbapps/predictor/ . When a user enters the tab, he gets redirected to the authentication page (from the config.php), but when the authentication process is done, the user gets redirected to the page tab url (http://www.gate7.co.il/fbapps/predictor/) instead of the tab inside the page. I tried to add these lines to the index file: <script type="text/javascript"> if (top.location.href != "http://www.facebook.com/gate7yellowheart?sk=app_196175180456372") window.location = "http://www.facebook.com/gate7yellowheart?sk=app_196175180456372"; </script> It worked well on firefox, and the user got redirected from the page tab url to the actual tab in the page, but in chrome it just caused mess and showed facebook inside the tab. What's the solution for this? A: In your getLoginUrl() call, set the redirect_uri param to your tab page, like this: $loginUrl = $facebook->getLoginUrl(array( 'scope' => 'email,user_about_me,user_likes,user_status,read_stream,offline_access,publish_stream,publish_actions', 'redirect_uri' => 'http://www.facebook.com/gate7yellowheart?sk=app_196175180456372' ));
{ "language": "en", "url": "https://stackoverflow.com/questions/7602526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to insert a row into the Accounts table via the Sugar API This is code I have tried: $result = $sugar['soapclient']->call( 'set_entry', array( 'session'=>$sugar['session'], 'module_name'=>'Accounts', array( array("name" => 'id', "value" => $sugar_data['id']), array("name" => 'name', "value" => $sugar_data['name']), array("name" => 'description', "value" => $sugar_data['description']), array("name" => 'team_id', "value" => $sugar_data['team_id']), array("name" => 'team_set_id', "value" => $sugar_data['team_set_id']), array("name" => 'phone_fax', "value" => $sugar_data['phone_fax']), array("name" => 'billing_address_street', "value" => $sugar_data['address_street']), array("name" => 'billing_address_city', "value" => $sugar_data['address_city']), array("name" => 'billing_address_state', "value" => $sugar_data['address_state']), array("name" => 'billing_address_postalcode', "value" => $sugar_data['address_postalcode']), array("name" => 'billing_address_country', "value" => $sugar_data['address_country']), array("name" => 'shipping_address_street', "value" => $sugar_data['address_street']), array("name" => 'shipping_address_city', "value" => $sugar_data['address_city']), array("name" => 'shipping_address_state', "value" => $sugar_data['address_state']), array("name" => 'shipping_address_postalcode', "value" => $sugar_data['address_postalcode']), array("name" => 'shipping_address_country', "value" => $sugar_data['address_country']), array("name" => 'phone_office', "value" => $sugar_data['phone_work']) ) ) ); However, the row does not insert. I searched based on the ID and the account_name, and both returned 0 results. Thanks! I really appreciate the help, as this is due for completion by the end of the day today! Nick A: I think the problem is that you used "id" field in your data. In this case, SugarCRM try to update account record with this specific ID. If you want to create an account with you own id you should to add also this element in your array : array( 'name' => 'new_with_id', 'value' => 1, ), A: What is the response from the web service? Try to debug the web service call: * *Look in the web server log (Is the call getting through) *Enable the SugarCRM logging and set the level to debug *Either enable PHP error output or make PHP log errors to a log file *Use e.g. SoapUI to test SOAP call *See Where is SugarFullTest_Version2.php? (Sugar CRM and SOAP) for a more thorough SOAP example *Check the SugarCRM SOAP documentation I would also try with a simpler test and verify it works properly: $info = $soapClient->set_entry( $session, 'Accounts', array( array('name' => 'name', 'value' => 'Test account'), array('name' => 'description', 'value' => 'This is a test account'), ) ); } The id will be created automatically.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is my java made pacMan clone sometimes laggy? I'm working on a pacman clone in java using eclipse and sometimes it appears laggy more specifically the movement of pacman/ghosts is slow, sometimes its fine. Once it has happened while I was running it so it wasn't after I added code and it doesn't seem to be after any specific event in game. I can't find any trigger or produce the lag on purpose The resource manager shows the same cpu usage(only around 50%)/memory usage . Aswell the FPS seems to be around 200 consistently through lag and during the periods where it is working well. Does anyone know what this could be? Is there any information I left out that could be of use? edit - I am basing movement on a timer is that bad? I will post the movement relevant code below is there a good way of posting the whole code on here? Timer movement = new Timer(20, new ActionListener()//500 is time in milliseconds between //calls to actionPerformed as far as I know. { public void actionPerformed(ActionEvent arg0) { if(movingUp == true) { moveUp(); } else if(movingDown == true) { moveDown(); } else if(movingRight == true) { moveRight(); } else if(movingLeft == true) { moveLeft(); } } }); public void moveUp() { yPos -= 1; this.rect.y -= 1; } public void setDirUp() { movingUp = true; movingDown = false; movingRight = false; movingLeft = false; } in the main class in public void keyPressed: if(keyCode == KeyEvent.VK_W) { if(pacMan.isUpHittingWall == false) { pacMan.setDirUp(); pacMan.isDownHittingWall = false; pacMan.isRightHittingWall = false; pacMan.isLeftHittingWall = false; } } edit 2 -Thanks for the help guys. I have the movement using System time now and it seems to have fixed the issue because I implemented it only for pacman at first and the ghosts were still slow. Now there is an issue where moving right and down are much slower than moving left or up The only difference I see is that right and down are both adding and left and up are subtracting. What can I do about this? The updated code is below. //updated movement code public void moveUp(long timePassed) { yPos -= vy * timePassed; this.rect.y -= vy * timePassed; } public void moveDown(long timePassed) { yPos += vy * timePassed; this.rect.y += vy * timePassed; } public void moveRight(long timePassed) { xPos += vx * timePassed; this.rect.x += vx * timePassed; } public void moveLeft(long timePassed) { xPos -= vx * timePassed; this.rect.x -= vx * timePassed; } //I passed timePassed through a globalInputObject because my input is handled in public //void keyPressed(KeyEvent e) and I didnt know how else to get timePassed in to the //movement method //Here is the code in gameLoop() globalInputObject.isPacManMovingUp(timePassed); globalInputObject.isPacManMovingDown(timePassed); globalInputObject.isPacManMovingRight(timePassed); globalInputObject.isPacManMovingLeft(timePassed); //This is inside the GlobalInputObject public void isPacManMovingUp(long timePassed) { if(pacMan.movingUp == true) { pacMan.moveUp(timePassed); } } public void isPacManMovingDown(long timePassed) { if(pacMan.movingDown == true) { pacMan.moveDown(timePassed); } } public void isPacManMovingRight(long timePassed) { if(pacMan.movingRight == true) { pacMan.moveRight(timePassed); } } public void isPacManMovingLeft(long timePassed) { if(pacMan.movingLeft == true) { pacMan.moveLeft(timePassed); } } A: Rather than always moving the pacman by a constant distance (1 pixel, it appears) each time the timer runs, you should: * *Set the timer to run as fast as possible (e.g. once every millisecond or less). Edit: if you set it too fast, the game may end up actually running slower, you'll have to experiment. *Calculate how much time has passed between each frame using the system clock and move the pacman by an amount proportional to that. Doing the above will mean that if the system is "laggy," it will simply show fewer frames per second, rather than actually moving everything slower. A: As I feared, you're basing the distance moved on the time chunk from the Timer. You shouldn't do this as all timers can be variable and unreliable, especially with small time chunks. Better to base movement on difference in system time. So yes, use a Timer or something to run your "game loop", but know the sprite's position and velocity using doubles, and calculate the distance to move based on velocity vector (math vector not Java Vector) * difference in system time. That way if the timer is delayed by say garbage collection, making the time chunk larger, the distance moved will be correspondingly greater and will look smoother. A: You should look into creating a proper "main loop" or "game loop" as some call it. Take a look at the game structure part of this wikipedia article.. Basically those input events are happening\invoked from a separate thread than the main thread and they are directly modifying geometry of in game objects. Instead consider something like this for a main loop: loop: process collision detection process animation (alters geometry of game objects) process input (more on this later) any other game specific logic render screen your process input could be something like this if (globalInputObject.movingUp==true) { hero.y -= 10; } if (globalInputObject.movingDown==true) { hero.y += 10; } if (globalInputObject.movingLeft==true) { hero.x -= 10; } if (globalInputObject.movingRight==true) { hero.x += 10; } and your input handler would look something like this: public void actionPerformed(ActionEvent evt) { if (evt.button==UP_BUTTON) { globalInputObject.movingUp=true; } if (evt.button==DOWN_BUTTON) { globalInputObject.movingDown=true; } if (evt.button==LEFT_BUTTON) { globalInputObject.movingLeft=true; } if (evt.button==RIGHT_BUTTON) { globalInputObject.movingRight=true; } } Basically the processing that you're doing in your "extra" threads (input thread) is minimal and therefore doesn't interfere with your main thread. Also, this method has the benefied of easily supporting multiple directions simultaneously (ie: UP+RIGHT = diagonal). Only super high end games have more than a single thread (if they even need it at all). Dealing with synchronisation in a game is not good for performance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Combining Predicates In XPaths I have some XML like this: <MT N="tag1" V="text"/> <MT N="tag2" V="more text"/> <MT N="tag3" V="other text"/> <MT N="tag4" V="something cool"/> <MT N="target_tag" V="i want this"/> <MT N="target_tag" V="and this"/> I'm trying to target the MT where N=target_tag and by number (1 or 2). The following doesn't work, despite what I was hoping from this link: <xsl:variable name="display" select="MT[@N = 'target_tag' and 2]/@V" /> If I try this, I consistently get the first one: <xsl:variable name="display" select="MT[@N = 'target_tag']/@V" /> And if I try this, I consistently get the second MT tag (so "more text" in this example): <xsl:variable name="display" select="MT[2]/@V" /> I've tried this with no luck too: <xsl:variable name="display" select="MT[2][@N = 'target_tag']/@V" /> Based on my requirements, I need to combine them, so that when I'm looping through a recursive function I can show the first, then the second, then the third. Any ideas how these can be combined? A: select="MT[@N = 'target_tag'][2]" should work. A: Input XML: <root> <MT N="tag1" V="text"/> <MT N="tag2" V="more text"/> <MT N="tag3" V="other text"/> <MT N="tag4" V="something cool"/> <MT N="target_tag" V="i want this"/> <MT N="target_tag" V="and this"/> </root> XSLT: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="root"> <xsl:for-each select="MT"> <xsl:if test="@N = 'target_tag'"> <xsl:value-of select="@V"/> </xsl:if> </xsl:for-each> </xsl:template> </xsl:stylesheet> Output: i want thisand this
{ "language": "en", "url": "https://stackoverflow.com/questions/7602545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Capistrano: Can I set an environment variable for the whole cap session? I've got a staging server with both standard Ruby and Ruby Enterprise installed. As standard Ruby refuses to install a critical gem, I need to set $PATH so that ruby/gem/rake/etc. always refer to the REE versions. And since I use Capistrano to deploy to our machines, I need to do it in Capistrano. How can I set an environment variable once, and have it persist throughout the Capistrano session? 1) It's easy to do in bashrc files, but Capistrano doesn't read bashrc files. 2) I'd use Capistrano's default_environment['PATH'] = 'Whatever' but Capistrano uses these environment variables like env PATH=Whatever command arg ... and they're lost whenever another shell is spun up within the executable passed to env. Like when you use sudo. Which is kinda important: [holt@Michaela trunk]$ env VAR=hello ruby -e "puts ENV['VAR']" hello [holt@Michaela trunk]$ env VAR=hello sudo ruby -e "puts ENV['VAR']" nil 3) And I can't use the bash export command, as these are lost too - Capistrano seems to start up a new shell for each command (or something like that), and that's lost, too: cap> export MYVAR=12 [establishing connection(s) to xxx.xxx.xxx.xxx] cap> echo $MYVAR ** [out :: xxx.xxx.xxx.xxx] cap> 4) I've tried messing with Capistrano's :shell and :pty options as well (and in combination with the other approaches), but no luck there, either. So - what's the right way to do this? This seems like such a basic task that there should be a really simple way to accomplish it, but I'm out of ideas. Anyone? Thanks in advance! A: I have the exactly same problem, but I think this solution is better: set :default_environment, { 'env_var1' => 'value1', 'env_var2' => 'value2' } This works for me like a charm. A: I think you have in fact 2 problems: 1) You want to change the PATH on your remote host(s). Alter/set the path in your .bashrc on your remote host(s) and run cap> printenv, if your path is right, goto #2, else try to add export BASH_ENV=~/.bashrc to your /etc/profile (be careful, ~/.bashrc will then be run for all non-interactive shell for all users) 2) You want sudo to keep your PATH Run visudo on your remote host(s) and add: Defaults exempt_group = "<your_user>" A: I needed to set an environment variable for a specific task to work. The "run" command allows you to pass options which include :env: run "cmd", :env => { 'name' => 'value' } In my case, I wanted to add the environment variable to a task that I didn't write, so I used default_run_options which is used by all invocations of run. I added this to the top of my Capfile: default_run_options[:env] = { 'name' => 'value' } A: If you need to set a variable on the remote host other than PATH, you should know that sshd only allows certain /etc/profile or ~/.bashrc environment variables by default, for security reasons. As Lou said, you can either do cap shell and use the cap> printenv command, or you can do cap COMMAND=printenv invoke in one command. If you see the variable when you ssh into the remote shell normally, but you don't see it in the cap printenv command, here's one solution: * *Set PermitUserEnvironment yes in your remote server's /etc/ssh/sshd_config file, and restart sshd *Edit the ~/.ssh/environment file for the remote user you are ssh'ing in as, and put your variable(s) there as VARIABLE=value Now those should show up when you do cap COMMAND=printenv invoke A: I tried unsuccessfully to use @brian-deterling's technique, which is pretty commonly used by others who have discussed this... Maybe I'm doing something wrong, but meanwhile I found the dotenv-rails gem, and it worked very nicely for loading up values out of a .env file in my project root. The instructions on their Github repo are pretty straight-forward. I added the Dotenv.load to my config/application.rb
{ "language": "en", "url": "https://stackoverflow.com/questions/7602548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "37" }
Q: Mobile facebook login not logging in iPhone users? I've got to be doing something very obvious wrong here, because I just can't bring myself to believe that facebook's mobile login isn't working correctly for iPhone users. If you have a look at these urls, you'll see that they work (after you replace the 'YOUR_APP_ID' and 'YOUR_REDIRECT_URL', of course) in web browsers & Androids, but on iPhones (3s and 4s) they take you right into facebook and you never see the Extended Permissions page or get redirected: https://graph.facebook.com/oauth/authorize?type=user_agent&client_id=YOUR_APP_ID&redirect_uri=YOUR_REDIRECT_URL&display=wap&scope=email,user_location,read_friendlists,publish_stream,offline_access https://m.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_REDIRECT_URL&scope=email,user_location,read_friendlists,publish_stream,offline_access I mean, I'm sure they tested their mobile login stuff on an iPhone, right? Anyone know what I'm doing wrong?
{ "language": "en", "url": "https://stackoverflow.com/questions/7602550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Script-Run Silverlight Test Project I have a solution with several Silverlight Test Projects. I would like to have some kind of script or tool with the ability of running all these test projects and generating some kind of report (any simple output will work) I googled around for some time but I was unable to find any existent solution other than running the projects one by one from Visual Studio. Has someone came across this situation before? Any idea on how to implement such a tool? Regards A: If you need automated testing then Test Manager is a tool from Microsoft. http://www.microsoft.com/visualstudio/en-us/products/2010-editions/test-professional/overview http://msdn.microsoft.com/en-us/library/bb385901.aspx and use with silverlight http://jugalpanchal.blogspot.com/2011/09/configure-test-manager-for-silverlight.html A: Use StatLight! http://statlight.codeplex.com It's a Silverlight Test Project runner exe that you can invoke from the cmdline. Its great and can be integrated into TFS Workflows as well as Msbuild.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Web Site Thumbnail? I posted a link of my website on facebook, but it uses an image for a thumbnail that I don't want(it is an image inside my website). How can I govern which thumbnail is used for my web site on any web page(facebook etc) ? Thank You A: For facebook at least, use <link rel="image_src" href="your_image.jpg">
{ "language": "en", "url": "https://stackoverflow.com/questions/7602555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python cgi weird behaviour I have a simple CGI python script with an html output: print "Content-Type: text/html" print print hours,minutes,seconds,"," When I run it from my linux shell, it runs fine but when called from the browser, all I get is a blank page. I used to have this problem before when I used CRLF EOF instead of LF but I changed that and it worked fine until some recent modification. I don't know what to do when the script runs fine from shell but not when called from a browser. A: <!-- SHTML Wrapper - 500 Server Error --> means that something is going wrong on the server. The most common cause in CGI scripts for this error is that there is an uncaught error in the CGI script itself, causing it to prematurely terminate. Your best bet is to check your Apache error logs. These will normally be in /var/log/<name of Apache install>/error.log (This could be /var/log/apache2/error.log or /var/log/httpd/error.log, etc.) Since you've said that this works well in the shell, my guess is that this is an issue with sys.path (remember, Apache is a different user, it will have different settings), but I would need to see more to be certain. Other issues could be: * *Different Python version (3 vs. 2) *File has the wrong permissions (755 is the standard, I believe) *Syntax error somewhere in Python which is environmentally dependant
{ "language": "en", "url": "https://stackoverflow.com/questions/7602557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can i get an immediate response from a long running process in j2ee? I can't seem to find a solid answer anywhere. I THINK i found one with respect to JMS but it was confusing. A: It really depends what stack of j2EE are you using? Is it just web, ejb layer or both?. If we are talking about the web then you can use asynchronous servlet introduced in the newest Java EE specification, if you are using plain EJB's then the natural choice would be Messege driven beans (mentioned JMS). You can of course design a custom solution where for example you send some data to process and then the j2ee application itself calls your application (with http request for example) to notify that its done running the job. Possibilities are endless and if one is better than other always depends on the specific scenario. A: If I understand correctly what you are talking about is the ability to start a task (that will take some time) then respond to the user while that task is still doing it's stuff. Depending on your requirements it is really quite simple and you can use a plain old Java Thread to perform the operation. public class DoSillyCounting extends Thread { private volatile int counter; public int getCounter() { return counter; } public run() { while (counter < 10) { counter ++; try { Thread.sleep(1000); } catch (InterruptedException ie) { } } } } In your setup page you might do this: (session is an HttpSession) DoSillyCounting doSillyCounting = new DoSillyCounting(); doSillyCounting.start(); session.putValue("tenSecondsCounter", doSillyCounting); /* Here you can respond to the user while the Thread is executing */ And in your status page you might do this: DoSillyCounting doSillyCounting = (DoSillyCounting)session.getValue("tenSecondsCounter"); out.print(Integer.toString(doSillyCounting.getCounter()); if (doSillyCounting.isAlive()) { out.print("Still Working on it"); } else { out.print("Yippee, I finished"); } Of course, this is a rather useless example and this model is not a good idea when you may have a large number of requests to satisfy, it would then be worth looking at a ThreadPool implementation or using something like JMS.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Java Formatter class, is there an easy way to auto pad columns with spaces? Say you have some tabular data where the datas length can vary, is there a provision with the Formatter class to auto adjust the padding? So instead of this (note column A): columnA columnB 1 34.34 10 34.34 100 34.34 1000 34.34 You get this (note column B): columnA columnB 1 34.34 10 34.34 100 34.34 1000 34.34 Thus far, i've tried this which only simply includes the spaces between %5s %5s, but they are static and do not adjust to produce the results I want. I was under the impression that the 5 in %5s would auto pad 5 spaces Formatter formatter = new Formatter(); formatter.format("%5s %5s", columnAdata, columnBdata); A: It's definitely possible. The way I know off-hand is to configure a minimum width for data in your first column. To do this you want to make use of the width attribute in conjunction with left-justification (both documented in the Javadoc). Here's a start for you: System.out.printf("%-10d %d%n", 1, 100); System.out.printf("%-10d %d%n", 10, 100); System.out.printf("%-10d %d%n", 100, 100); This prints: 1 100 10 100 100 100 The format %-10d %d%n can be explained as follows: %-10d: first field %: start field -: left-justify 10: output a minimum of 10 characters d: format as a decimal integer %d: second field, using defaults for decimal integer %n: newline
{ "language": "en", "url": "https://stackoverflow.com/questions/7602562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using data attributes with jQuery I have this button: <button type="button" class="themeChanger" data-themeValue="grid" value="Grid"> <img src="templateImages/Icon_200.png" /> </button> And this jQuery: $(".themeChanger").click(function () { alert($(this).attr("data-themeValue")); alert($(this).data("themeValue")); }); For some reason the first alert shows "grid" like it should, but the second shows undefined. Is there something stupid I'm missing? A: The problem is the camel case. For clarity I'd stick to the data-theme-value format for your attributes. http://jsfiddle.net/NkHEx/2/ jquery automatically converts .data('some-value') to data('someValue') Note that both alert calls return grid A: I think it is the camel casing of hyphenated words in the data tag implementation that is the gotcha here Try this jsfiddle - http://jsfiddle.net/FloydPink/fb6Y6/ <button type="button" class="themeChanger" data-theme-value="grid" value="Grid"> data-theme-value </button> <button type="button" class="themeChanger" data-themeValue="grid" value="Grid"> data-themeValue </button> $(".themeChanger").click(function () { alert($(this).attr("data-themeValue")); alert($(this).data("themeValue")); }); A: I think data will look on lowercases: alert($(this).data("themevalue")) //grid or if you want to use themeValue you need to use: edit: I was wrong, it doesnt have anything to do with lowercases, you can use themeValue if you are having the attribute: data-theme-value then you call itwith $(element).data("themeValue") <button class="themeChanger" data-themeValue="Theme1" data-theme-value="Theme2"></button> $(".themeChanger").click(function() { var el = $(this); alert($(this).data("themeValue")); //Theme2 alert($(this).data("themevalue")); //Theme1 }); A: As noted in this Learning jQuery article, HTML5 data-* attributes are handled by the browser->JS conversion in the same way that CSS names are handled--that is: * *the leading data- is removed (a step not needed in the CSS name comparison I drew above) * *data-specialInfo becomes specialInfo *data-more-specialInfo becomes more-specialInfo *the remaining attr name is split on - * *specialInfo becomes [ specialInfo ] *more-specialInfo becomes [ more, specialInfo ] *the first of the resulting split parts is dropped to all lower case * *[ specialInfo ] becomes [ specialinfo ] *[ more, specialInfo ] becomes [ more, specialInfo ] (no change as first part was already lower) *the rest of the resulting split parts are dropped to lower case, but their first letter is made upper case * *[ specialinfo ] becomes [ specialinfo ] (no change because there were no other parts) *[ more, specialInfo ] becomes [ more, Specialinfo ] *The now case-modified parts are rejoined on empty string * *[ specialinfo ] becomes specialinfo *[ more, Specialinfo ] becomes moreSpecialinfo This being the case, your data-themeValue attribute is accessible via $(this).data("themevalue"). Whereas a data-theme-value attribute would be accessible via $(this).data("themeValue"). It's terribly confusing unless you recognize the mechanism in use.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: I cant create a framework that work in xcode 4 I have this library https://github.com/ararog/Unrar4iOS for unrar in IOS device and i build, like the creator of the project say, but one files is missing and dont work when i importing to my project but if i use the framework that cames with the example work fine. I need to compile but my self because the framework has a important leak of memory and i want to fix this issue. I am using xcode version 4.1 for snow leopard Regards Edit the error is: Ld /Users/pacoflaco/Library/Developer/Xcode/DerivedData/prueba-dvzvrihnyniqghgnyjzjdvqvnvne/Build/Products/Debug-iphonesimulator/prueba.app/prueba normal i386 setenv MACOSX_DEPLOYMENT_TARGET 10.6 setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin" /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/llvm-g++-4.2 -arch i386 -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk -L/Users/pacoflaco/Library/Developer/Xcode/DerivedData/prueba-dvzvrihnyniqghgnyjzjdvqvnvne/Build/Products/Debug-iphonesimulator -F/Users/pacoflaco/Library/Developer/Xcode/DerivedData/prueba-dvzvrihnyniqghgnyjzjdvqvnvne/Build/Products/Debug-iphonesimulator -F/Users/pacoflaco/Proyectos/prueba -filelist /Users/pacoflaco/Library/Developer/Xcode/DerivedData/prueba-dvzvrihnyniqghgnyjzjdvqvnvne/Build/Intermediates/prueba.build/Debug-iphonesimulator/prueba.build/Objects-normal/i386/prueba.LinkFileList -mmacosx-version-min=10.6 -Xlinker -objc_abi_version -Xlinker 2 -framework QuartzCore -framework UIKit -framework Foundation -framework CoreGraphics -framework CoreData -framework Unrar4iOS -o /Users/pacoflaco/Library/Developer/Xcode/DerivedData/prueba-dvzvrihnyniqghgnyjzjdvqvnvne/Build/Products/Debug-iphonesimulator/prueba.app/prueba ld: framework not found Unrar4iOS Command /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/llvm-g++-4.2 failed with exit code 1 The file missing is Unrar4iOS A: You need to include the folder that contains the Unrar4iOS framework among your Framework Search Paths, which is one of the build settings you can edit while editing the project object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove all HTML tags and do a carriage return on in C# I am creating a HTML to text parser. I need to remove all HTML elements and want to do a carriage return everytime there is a <BR> and then remove the <BR> as well after so there are no HTML tags left. I then want to parse the text for a certain string that is in the combobox. Thank you in advance for your help. private void navigateWeb_Click(object sender, EventArgs e) { openFD.Title = "Select your configuration file"; openFD.InitialDirectory = "C:"; openFD.FileName = ""; openFD.Filter = "Config File (*.cfg)|*.cfg|Text File (*.txt)|*.txt|All Files (*.*)|*.*"; openFD.ShowDialog(); MyURL = openFD.FileName; //Open and read file System.IO.StreamReader objReader; objReader = new System.IO.StreamReader(MyURL); richTextBox1.Text = objReader.ReadToEnd(); var lines = File.ReadAllLines(MyURL) .Select(l => l.Trim()) .Where(l => l.StartsWith(comboBox1.Text)); textBox1.Text = String.Join(Environment.NewLine, lines); } *********UPDATE***** Here is the solution that got the job done: public static string RemoveHTML(string text) { text = text.Replace("&nbsp;", " ").Replace("<br>", "\n"); var oRegEx = new System.Text.RegularExpressions.Regex("<[^>]+>"); return oRegEx.Replace(text, string.Empty); } private void navigateWeb_Click(object sender, EventArgs e) { openFD.Title = "Enter URL in the box below"; openFD.InitialDirectory = "C:"; openFD.FileName = "http://msnconf/configtc.aspx?IP=10.6.64.200&m=c"; openFD.Filter = "HTTP://|*.*|Config File (*.cfg)|*.cfg|Text File (*.txt)|*.txt|All Files (*.*)|*.*"; //openFD.ShowDialog(); if (openFD.ShowDialog() == DialogResult.Cancel) { //MessageBox.Show("cancel button clicked"); } else { MyURL = openFD.FileName; webBrowser1.Visible = true; richTextBox1.Visible = false; permitACL.Enabled = true; //webBrowser1.Navigate(new Uri(MyURL.SelectedItem.ToString())); webBrowser1.Navigate(MyURL); //Open and read file System.IO.StreamReader objReader; objReader = new System.IO.StreamReader(MyURL); richTextBox1.Text = objReader.ReadToEnd(); //Read all lines of file // String lines = objReader.ReadToEnd(); String[] crString = { "<BR>&nbsp;" }; String[] aLines = richTextBox1.Text.Split(crString, StringSplitOptions.RemoveEmptyEntries); // String[] lines = File.ReadAllLines(MyURL); String noHtml = String.Empty; for (int x = 0; x < aLines.Length; x++) { if(permitACL.Checked) { if (aLines[x].Contains("permit")) { noHtml += (RemoveHTML(aLines[x]) + "\r\n"); } } if (aLines[x].Contains(comboBox1.Text)) { noHtml += (RemoveHTML(aLines[x]) + "\r\n"); } } //Find lines that match our text in the combobox //lines.Select(l => l.Trim()); //.Where(l => l.StartsWith(comboBox1.Text)); //Print results to textbox textBox1.Text = String.Join(Environment.NewLine, noHtml); } } A: I suggest you use the HTML Agility Pack - it is an HTML parser that you can query with using XPath syntax. A: public static string RemoveHTML(string text) { text = text.Replace("&nbsp;", " ").Replace("<br>", "\n"); var oRegEx = new System.Text.RegularExpressions.Regex("<[^>]+>"); return oRegEx.Replace(text, string.Empty); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7602571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# - How to Rewrite a URL in MVC3 I have an URL like this: http://website.com/Profile/Member/34 I need this URL runs like this: http://website.com/Profile/John Given John as profile name for the user id=34. Can anyone give me directions to do that? A: In global.asx you need to add a new route. public static void RegisterRoutes(RouteCollection routes) { routes.MapRoute( "Member", // Route name "Profile/{member}", // URL with member new { controller = "YourController", action = "Profile"} ); } You will still need to implement the action that handles looking up the profile based on {member}. A: You have to add a custom route in the global.ascx.cs that will be used to redirect to the good controller. But I guess that "John" is not a unique value so you will have to keep the id in the Url, or if John is the username and is unique you can go with this url: routes.MapRoute("Member", "Profile/{member}", new { controller = "Member", action = "Profile"}); Then in your controller you will have : public ActionResult Profile(string username){ //fetch from the db } If "John" is not a unique value I suggest you use : routes.MapRoute("Member", "Profile/{id}/{member}", new { controller = "Member", action = "Profile"}); So your Url will look like http://website.com/Profile/John/34 and youre controller : public ActionResult Profile(int id){ //fetch from the db } Let me know if you need more help!
{ "language": "en", "url": "https://stackoverflow.com/questions/7602572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: My database query display sorts values into alphabetical order I have been trying to figure this problem out without asking for help, but I have reached the point where I honestly can not figure it out. Here is the function I use to query the database (I have had to change name for confidentiality): public Cursor getAllItems(){ Cursor cursor = db.query(true, DATABASE_TABLE, new String []{KEY_NAME, KEY_1,KEY_2, KEY_3, KEY_4, KEY_5, KEY6, KEY_7, KEY_8, KEY_9, KEY_10, KEY_11, KEY_12, KEY_13}, null, null, null, null, null, null); cursor.moveToFirst(); return cursor; } This is where I populate a tablelayout that has been created using xml. public void populate(){ db = new DBAdapter(this); TableLayout TL = (TableLayout)findViewById(R.id.table); db.open(); c = db.getAllItems(); while(!c.isAfterLast()){ if(Integer.toString(c.getPosition())!=null){ TableRow TR = new TableRow(this); TR.setId(c.getPosition()); TextView column1 = new TextView(this); TextView column2 = new TextView(this); TextView column3 = new TextView(this); TR.setLayoutParams(new TableRow.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); column1.setGravity(0x01); column1.setTextColor(0xff000000); column1.setTextSize(2,20); //column1.setText(c.getString(3)); column1.setText(Integer.toString(c.getPosition())); TR.addView(column1); column2.setGravity(0x01); column2.setTextColor(0xff000000); column2.setTextSize(2,20); column2.setText(c.getString(0)); TR.addView(column2); column3.setGravity(0x01); column3.setTextColor(0xff000000); column3.setTextSize(2,20); //column3.setText(c.getString(1)); column3.setText(Integer.toString(TR.getId())); TR.addView(column3); TR.setOnLongClickListener(this); TL.addView(TR); 1Total += c.getDouble(1); 2Total += c.getDouble(2); } c.moveToNext(); } db.close(); If I view the database using DDMS, everything is displayed in the correct order (the order in which I insert into the table). However, when I try to display the data in a tablelayout, for some reason it organizes the values based on the KEY_NAME value. So if I insert data into the table like "B - C - D - A - E" it will populate my table layout with "A - B - C - D - E" Something strange is that I have it setup so that a longclick on any given row with generate a dialogfragment displaying the rest of the information, and this information is correct. So if using the example above I long click on the displayed "C" row then I will actually get the data for "D" which is correct. Any idea? A: In the javadocs for the SQLiteDatabase class, for the query method, it says that "Passing null [for sort order] will use the default sort order, which may be unordered." That null is one of the many nulls you are passing, and so the order may be unordered, but apparently it may be ordered instead. Perhaps try using public Cursor rawQuery (String sql, String[] selectionArgs) instead of query? So I think for your case that would be something like public Cursor rawQuery (String "SELECT DISTINCT KEY_NAME, KEY_1,KEY_2, KEY_3, KEY_4, KEY_5, KEY6, KEY_7, KEY_8, KEY_9, KEY_10, KEY_11, KEY_12, KEY_13 FROM DATABASE TABLE", null); It's been my experience that Android SQLite returns rawQuery results in the insert order, although I'm not sure that it's required to. A more solid way to do it would be to add autoincrement key column -- giving each row a serial number, essentially -- and then ordering the results of queries on that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I format HTML into two columns similar to how MS Word does it? In Microsoft Word there is an option where you can separate the text in two columns as follows: The content has images and lists. All the content needs to continue normally as in the image. I've tried doing it with CSS3 but manually not dynamically (because I will have to load the content and then make operations to re-order the elements but I'm not sure if it will work): http://joseadrian.com/stackoverflow/columns.php Is there a way to do that with HTML (5) + JavaScript + CSS (3)? If so... creating a file with PHP giving it that structure will work? A: CSS isn't smart enough to make decisions like "when this column, which is 600px high is full, wrap the text into the next column". You'll need to do this using JavaScript. see: http://dancameron.org/code/splitting-content-into-two-columns-e-g-word-wrap-with-php-or-css-javascript
{ "language": "en", "url": "https://stackoverflow.com/questions/7602575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: OpenGraph Music music.listens returns error Following the spec here http://developers.facebook.com/docs/opengraph/music/ When I post: POST https://graph.facebook.com/me/music.listens?song=[song url] The response is invariably: { "error": { "type": "OAuthException", "message": "An unknown error has occurred." } } A: A bug report has been filed here: https://developers.facebook.com/bugs/124491790988961 According to a developer in the comments section, open graph music is not yet available to the developer public. A: A Facebook developer replied regarding this here: Opengraph and music.listen Seems like the best option is to create own "play music" actions, since Facebook doesn't seem to allow POST to music.listens in a foreseeable future... :/ A: To add on Kristofer and Garthex answers this Built-in Actions is not publicly available. However, you can submit a request if you think you have the rights on content broadcasting. Here is the doc for Built-in Actions: https://developers.facebook.com/docs/opengraph/actions/builtin/ Alternativly, you can use Custom Actions like "A user Play a Sound". A: Make sure you have prompted the user for publish_actions extended permission and that the user is a developer of the application (since the open graph actions are still in beta).
{ "language": "en", "url": "https://stackoverflow.com/questions/7602579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: load xelement into a datatable i have the following xml file, that contains a lot of Information about branches of a company .. (this is only an example).. what i really need, is to load only the data from Branch1 in a datatable(that has the same structure as my xml file, so no problem with the datatable at all) .. iam using c# and i would like to do this is linq, but i have no idea about linq... my question is: how would i read the entry from xml as a datatable row, so i can copy it to my datatable ? i now have: XElement main = XElement.Load("branches.xml"); IEnumerable<XElement> elList = from el in main.Descendants("branch").Where(ex=>ex.Attribute("name").Value=="Branch1") select el; //this will return me the element where name =Branch1 //now, how would i only load this entry into my datatable ?? //this won`t work branchesDataTable.ReadXml(XElement el in elList); any help is really appreciated .. <?xml version="1.0" encoding="utf-8"?> <branches> <branch name="Branch1"> <address>Street 1, 1234, NY</address> <tel>0123456789</tel> <director>James</director> </branch> <branch name="Branch2"> <address>Street 2, 4567, NY</address> <tel>9876543210</tel> <director>Will</director> </branch> </branches> A: try branchesDataTable.ReadXml(new StringReader(new XElement("branches", elList).ToString()));
{ "language": "en", "url": "https://stackoverflow.com/questions/7602581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Twitter Atom feed blank for one user but not another? I've been pulling the latest tweet via search.atom in Twitter. $feed = "http://search.twitter.com/search.atom?q=from%3A" . $username_for_feed . "&rpp=" . $limit; The problem is lately it just started showing no content. I went and looked at different URLs and it isn't showing, only for certain usernames?? http://search.twitter.com/search.atom?q=from:kevinbacon&rpp=1 That works for me. http://search.twitter.com/search.atom?q=from:zesty_one&rpp=1 Here, both accounts have tweets, and when I add most_recent, it makes no difference, so I can't see how date has anything to do with it. A: The search atom feed only goes back 7 days. So if that user with a blank feed hasn't tweeted for 7 days it won't show anything. A: There is an Atom feed at http://twitter.com/statuses/user_timeline/$username.atom?count=200
{ "language": "en", "url": "https://stackoverflow.com/questions/7602587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Embedding audio in IE(7+) with javascript capability to mute and unmute I've been looking around for a method to embed audio onto a website, have a capability to loop and autoplay and also be able to mute and unmute the audio with javascript. I know that this is possible and very easy in html5, but I've heard that IE doesn't support html5 yet (or the audio tags perhaps). I also need my embedded audio to work as far back as IE7. So i think that using the tags will work for all other browsers but IE, while I was hoping something like could work for IE; unfortunately, it doesn't support calls from javascript to mute and unmute - this is because I don't want any controls from the audio player to be visible; simply a custom sound button that the user can click to mute and unmute the audio. Any ideas? Seems that something like this is the most simple thing, but the hardest thing to code :/ A: Consider using a player that uses HTML 5 by default, but can fall back on Flash if it's not supported. JPlayer can do that, and has a mute function. A: HTML5 is your best bet. <audio> <source src="horse.ogg" type="audio/ogg" /> <source src="horse.mp3" type="audio/mp3" /> <!-- You can put a flash player here in case the users browser doesn't support HTML5 or any of the audio formats you have added. --> </audio> the attributes you might want to specify in the audio tag are controls='controls' to enable playback options like play pause and volume controls including mute; loop='loop' to enable auto-loop; autoplay='autoplay' obviously to autoplay; and preload='auto' to load the audio on page load (you can also specify "metadata" or "none") your player would probably look like: <audio preload='auto' autoplay='autoplay' controls='controls' loop='loop'> <source src="yoursound.ogg" type="audio/ogg" /> <source src="yoursound.mp3" type="audio/mp3" /> <!-- Flash player here to fall back on if the users browser doesn't support HTML5 --> </audio>
{ "language": "en", "url": "https://stackoverflow.com/questions/7602589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# Mono on mac - compile and run another project with code I am trying to build an automatic download, compile & run program for a project just to make it easier for other users on mac and myself so we do not have to do everything over and over as the project progresses. I cant find anything on how to compile and run a C# monodevelop project with code when i google. Does anyone here know how it could be done? thanks Edit: using xbuild as mentioned below compiles the project, but i cannot seem to find a command to run the build? the only output seems to be .exe and that launches vmware when i try to run, is there som command that i add somewhere? like execute tar -xf sources.tar.gz cd *project* xbuild project.sln A: To build applications you can use gmcs , to run then you can use mono. From a Terminal shell, you can try it out: $ gmcs hello.cs $ mono hello.exe Hello, World A: The full answer of course depends on the sources concerned and the build system it uses. For mono relates sources you can often do the following: tar -xf sources.tar.gz cd sources ./configure make sudo make install If you have a .sln file and csproj files, you need to use mdtool or xbuild. mdtool comes with monodevelop, xbuild comes with mono. Both understand visual studio solution and csproj files and will build them. xbuild a mono equivalent of msbuild.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: getActivity returning null from fragment For school I am making an android app. For this app I have a fragment, which shows a gridview with just strings, from a database. For this I need a fragment. When I call getActivity(), it returns null. The onAttach method, as suggested here doesn't get called before the app crashes. How should I solve this? weekFragmetn.xml: package nl.siebeh.schoolmate; import java.util.ArrayList; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.GridView; public class weekFragment extends Fragment { dbLayer db; Context mContext; @Override public void onAttach(Activity activity) { mContext = getActivity(); Log.i("Schoolmate","onAttach called"); super.onAttach(activity); } public weekFragment newInstance(String title) { Log.i("Schoolmate","newInstance called"); db = new dbLayer(mContext); weekFragment fragment = new weekFragment(); ArrayList<ArrayList<Object>> result = null; if(title == "leraren"){ result = db.getAllRowsAsArrays("weekTeacher", null); }else if(title == "locatie"){ result = db.getAllRowsAsArrays("weekLocation", null); }else if(title == "vakken"){ result = db.getAllRowsAsArrays("weekSubjects", null); } String[] array = new String[60]; for(int i = 0; i < 60; i++){ array[i] = ""; } array[1] = getResources().getStringArray(R.array.days)[0]; array[2] = getResources().getStringArray(R.array.days)[1]; array[3] = getResources().getStringArray(R.array.days)[2]; array[4] = getResources().getStringArray(R.array.days)[3]; array[5] = getResources().getStringArray(R.array.days)[4]; for(int i = 1; i < 10; i++){ array[i] = Integer.toString(i); } for(int position = 0; position < result.size(); position++){ ArrayList<Object> row = result.get(position); int hour = Integer.valueOf(row.get(1).toString()).intValue(); int day = Integer.valueOf(row.get(0).toString()).intValue(); int pos = 6 * hour + day; array[pos] = row.get(position).toString(); } fragment.mContent = array; return fragment; } private String[] mContent = {""}; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (container == null) { return null; } View v = inflater.inflate(R.layout.week_fragment, container, false); GridView gridview = (GridView) v.findViewById(R.id.gridview); gridview.setAdapter(new weekAdapter(mContext, mContent)); return gridview; } @Override public boolean onContextItemSelected(MenuItem item) { return super.onContextItemSelected(item); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); } } logcat: (since click on the item the item in a list that starts the activity, where the fragment is started/embedded) 09-29 19:10:56.611: INFO/ActivityManager(70): Starting: Intent { cmp=nl.siebeh.schoolmate/.overviewWeek } from pid 536 09-29 19:10:56.970: INFO/Schoolmate(536): newInstance called 09-29 19:11:06.631: WARN/ActivityManager(70): Launch timeout has expired, giving up wake lock! 09-29 19:11:06.671: WARN/ActivityManager(70): Activity idle timeout for HistoryRecord{40770188 nl.siebeh.schoolmate/.overviewWeek} 09-29 19:12:20.661: DEBUG/SntpClient(70): request time failed: java.net.SocketException: Address family not supported by protocol 09-29 19:14:11.811: DEBUG/dalvikvm(536): Debugger has detached; object registry had 413 entries 09-29 19:14:11.811: ERROR/SchoolMate(536): java.lang.NullPointerException 09-29 19:14:11.811: INFO/SchoolMate(536): Context is null 09-29 19:14:11.820: WARN/System.err(536): java.lang.NullPointerException 09-29 19:14:11.820: WARN/System.err(536): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:118) 09-29 19:14:11.820: WARN/System.err(536): at nl.siebeh.schoolmate.dbLayer.<init>(dbLayer.java:50) 09-29 19:14:11.820: WARN/System.err(536): at nl.siebeh.schoolmate.weekFragment.newInstance(weekFragment.java:31) 09-29 19:14:11.820: WARN/System.err(536): at nl.siebeh.schoolmate.fragmentAdapter.getItem(fragmentAdaptar.java:21) 09-29 19:14:11.820: WARN/System.err(536): at nl.siebeh.schoolmate.titleFragmentAdapter.getItem(titleFragmentAdapter.java:1) 09-29 19:14:11.820: WARN/System.err(536): at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:62) 09-29 19:14:11.820: WARN/System.err(536): at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:321) 09-29 19:14:11.820: WARN/System.err(536): at android.support.v4.view.ViewPager.populate(ViewPager.java:441) 09-29 19:14:11.820: WARN/System.err(536): at android.support.v4.view.ViewPager.onAttachedToWindow(ViewPager.java:563) 09-29 19:14:11.820: WARN/System.err(536): at android.view.View.dispatchAttachedToWindow(View.java:6156) 09-29 19:14:11.820: WARN/System.err(536): at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:1122) 09-29 19:14:11.820: WARN/System.err(536): at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:1127) 09-29 19:14:11.820: WARN/System.err(536): at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:1127) 09-29 19:14:11.820: WARN/System.err(536): at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:1127) 09-29 19:14:11.820: WARN/System.err(536): at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:1127) 09-29 19:14:11.820: WARN/System.err(536): at android.view.ViewRoot.performTraversals(ViewRoot.java:765) 09-29 19:14:11.830: WARN/System.err(536): at android.view.ViewRoot.handleMessage(ViewRoot.java:1859) 09-29 19:14:11.840: WARN/System.err(536): at android.os.Handler.dispatchMessage(Handler.java:99) 09-29 19:14:11.840: WARN/System.err(536): at android.os.Looper.loop(Looper.java:123) 09-29 19:14:11.840: WARN/System.err(536): at android.app.ActivityThread.main(ActivityThread.java:3683) 09-29 19:14:11.840: WARN/System.err(536): at java.lang.reflect.Method.invokeNative(Native Method) 09-29 19:14:11.840: WARN/System.err(536): at java.lang.reflect.Method.invoke(Method.java:507) 09-29 19:14:11.850: WARN/System.err(536): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 09-29 19:14:11.850: WARN/System.err(536): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 09-29 19:14:11.850: WARN/System.err(536): at dalvik.system.NativeStart.main(Native Method) 09-29 19:14:11.850: DEBUG/AndroidRuntime(536): Shutting down VM 09-29 19:14:11.850: WARN/dalvikvm(536): threadid=1: thread exiting with uncaught exception (group=0x40015560) 09-29 19:14:11.870: ERROR/AndroidRuntime(536): FATAL EXCEPTION: main 09-29 19:14:11.870: ERROR/AndroidRuntime(536): java.lang.NullPointerException 09-29 19:14:11.870: ERROR/AndroidRuntime(536): at nl.siebeh.schoolmate.weekFragment.newInstance(weekFragment.java:49) 09-29 19:14:11.870: ERROR/AndroidRuntime(536): at nl.siebeh.schoolmate.fragmentAdapter.getItem(fragmentAdaptar.java:21) 09-29 19:14:11.870: ERROR/AndroidRuntime(536): at nl.siebeh.schoolmate.titleFragmentAdapter.getItem(titleFragmentAdapter.java:1) 09-29 19:14:11.870: ERROR/AndroidRuntime(536): at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:62) 09-29 19:14:11.870: ERROR/AndroidRuntime(536): at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:321) 09-29 19:14:11.870: ERROR/AndroidRuntime(536): at android.support.v4.view.ViewPager.populate(ViewPager.java:441) 09-29 19:14:11.870: ERROR/AndroidRuntime(536): at android.support.v4.view.ViewPager.onAttachedToWindow(ViewPager.java:563) 09-29 19:14:11.870: ERROR/AndroidRuntime(536): at android.view.View.dispatchAttachedToWindow(View.java:6156) 09-29 19:14:11.870: ERROR/AndroidRuntime(536): at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:1122) 09-29 19:14:11.870: ERROR/AndroidRuntime(536): at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:1127) 09-29 19:14:11.870: ERROR/AndroidRuntime(536): at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:1127) 09-29 19:14:11.870: ERROR/AndroidRuntime(536): at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:1127) 09-29 19:14:11.870: ERROR/AndroidRuntime(536): at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:1127) 09-29 19:14:11.870: ERROR/AndroidRuntime(536): at android.view.ViewRoot.performTraversals(ViewRoot.java:765) 09-29 19:14:11.870: ERROR/AndroidRuntime(536): at android.view.ViewRoot.handleMessage(ViewRoot.java:1859) 09-29 19:14:11.870: ERROR/AndroidRuntime(536): at android.os.Handler.dispatchMessage(Handler.java:99) 09-29 19:14:11.870: ERROR/AndroidRuntime(536): at android.os.Looper.loop(Looper.java:123) 09-29 19:14:11.870: ERROR/AndroidRuntime(536): at android.app.ActivityThread.main(ActivityThread.java:3683) 09-29 19:14:11.870: ERROR/AndroidRuntime(536): at java.lang.reflect.Method.invokeNative(Native Method) 09-29 19:14:11.870: ERROR/AndroidRuntime(536): at java.lang.reflect.Method.invoke(Method.java:507) 09-29 19:14:11.870: ERROR/AndroidRuntime(536): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 09-29 19:14:11.870: ERROR/AndroidRuntime(536): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 09-29 19:14:11.870: ERROR/AndroidRuntime(536): at dalvik.system.NativeStart.main(Native Method) 09-29 19:14:11.890: WARN/ActivityManager(70): Force finishing activity nl.siebeh.schoolmate/.overviewWeek 09-29 19:14:12.413: WARN/ActivityManager(70): Activity pause timeout for HistoryRecord{40770188 nl.siebeh.schoolmate/.overviewWeek} 09-29 19:14:21.910: WARN/ActivityManager(70): Launch timeout has expired, giving up wake lock! 09-29 19:14:22.441: WARN/ActivityManager(70): Activity idle timeout for HistoryRecord{4070c7a0 nl.siebeh.schoolmate/.schoolmate} 09-29 19:14:32.451: WARN/ActivityManager(70): Activity destroy timeout for HistoryRecord{40770188 nl.siebeh.schoolmate/.overviewWeek} A: You do not have a getActivity() call, which makes it difficult to answer the question. You are getting a NullPointerException because mContext is null. My guess is that mContext is null because, in the code to fragmentAdapter, you are calling new weekFragment(), then calling newInstance() on it. You presumably thought you were following some patterns outlined in the Fragment JavaDocs, but in there, newInstance() is a static method, not an instance method as you have it here. Take just about all of the code out of newInstance() and move it to onActivityCreated() or some time when the fragment is attached to the activity so getActivity() works. Along the way, delete your onAttach() implementation and the mContext data member, neither of which are needed (and the mContext is populated in a very scary way).
{ "language": "en", "url": "https://stackoverflow.com/questions/7602591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: vb.net report viewer multiple reports Within vb.net is there a way I can dynamically create multiple reports using the same rdlc but with different SQL statements. So in essence I want to write a loop that will open the same report multiple times within the viewer which will end up having many pages.. A: Apparently not, I ended up creating a new report and using the list box tool.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to pass intent to ask user to chose any app to scan QR code? I am making a android app which requires QR code scanning and then parsing the text as a resul. I would like to pass intent to other apllications like google goggles or Barcode scanner which can do the job efficiently and take the scanned text back as result of the intent. I have read the other questions out there for the same and found that i can do it with Zxing library also, but i would like this functionality to be handled by other pre-installed app. So could someone help me with the way we will pass intent in this case. A: Try this one: http://code.google.com/p/zxing/wiki/ScanningViaIntent
{ "language": "en", "url": "https://stackoverflow.com/questions/7602598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Save Selections DialogInterface.OnMultiChoiceClickListener I'm trying to make an Android app, and I want to let users select Weekdays. now I've got the AlertDialog setup and users can select several options. But I can't figure out how to save the selections when the user clicks the "OK" button. Code: new AlertDialog.Builder(this) .setTitle("Weekdays") .setMultiChoiceItems(weekdayOptions, selections, new DialogInterface.OnMultiChoiceClickListener() { public void onClick(DialogInterface dialog, int whichButton, boolean isChecked) { if( selections[whichButton] == true) { //Only need the selected(True) values Log.d(TAG, "Choice: " + whichButton); } Log.d(TAG, "Weekdays Selected: " + whichButton + selections[whichButton]); selections[whichButton] = isChecked; } }) .setPositiveButton("OK", new DialogButtonClickHandler()) .create() .show(); } public class DialogButtonClickHandler implements DialogInterface.OnClickListener { public void onClick( DialogInterface dialog, int clicked ) { switch(clicked) { case DialogInterface.BUTTON_POSITIVE: //I want to check here what the user selected break; } } } So when the user hits the BUTTON_POSITIVE I want to save the whichButton and the selections[whichButton] in I think a two-dimension array.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can you simulate a conflict in CouchDB without using replication? I'd like to write a unit test for my app that simulates a conflict during replication. Is there a way to simulate a conflict using only a single CouchDB database and server? A: I assume you want to get a document containing a conflict in your database, rather than a 409 Conflict response? So, create a document in the database with a known _id: $ curl http://localhost:5984/scratch/foo -X PUT -H "Content-Type: application/json" -d '{}' {"ok":true,"id":"foo","rev":"1-967a00dff5e02add41819138abb3284d"} Then use the bulk docs API with the all_or_nothing: true option to update the same document with a deliberately bad or no _rev, adding some different document attributes for good measure: $ curl http://localhost:5984/scratch/_bulk_docs -X POST -H "Content-Type: application/json" -d '{"all_or_nothing": true, "docs": [{"_id": "foo", "abc": 123}]}' [{"id":"foo","rev":"1-15c813a2b4b312c6915821b01a1986c5"}] You should then have a conflict in the document: $ curl http://localhost:5984/scratch/foo?conflicts=true {"_id":"foo","_rev":"1-967a00dff5e02add41819138abb3284d","_conflicts":["1-15c813a2b4b312c6915821b01a1986c5"]} You can also perform a normal query with ?new_edits=false as described by CouchDB committer Randall Leeds. $ curl http://localhost:5984/scratch?new_edits=false -X POST -H "Content-Type: application/json" -d '{"_id": "foo", "abc": 123}' A: Googled further after asking the question, and it looks like the answer is to use the all-or-nothing mode of the bulk document API. http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API Look near the end of the page. A: Just post two documents with the same _id attribute. This creates a conflict since the 2nd doc will not contain the proper _rev attribute. Remember, you need to include the latest _rev attribute in each subsequent post so that CouchDB knows you are up to date. Also, you can create two databases on the same server and replicate between those.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Rails: How to handle model subclassing? There are ten ways to do anything but what is the best practice approach to organizing the Document and Section models described below in Rails? Documents can have n number of sections. Each Section can be a specialized type of section with its own attributes and associations differing from other sections. And each Document needs to track a section order state for all of the sections associated with it regardless of type. I could create model classes for each Section type and associate them on Document as has_many SectionTypeA, has_many SectionTypeA and write a sorting mechanism to put together a sorted collection of all types for the given document. I looked into Single Table Inheritance. But the STI approach seems questionable when the specialized attributes are more complicated than a few string or integer fields. Sections will have attributes that map to database text columns and their own section has_many, has_one associations. Here's a rough outline of the elements described: Document Sections -Section Type A Title, freeform text -Section Type B Title, collection of urls -Section Type C Title, collection of images with title and collection of image comments A: This seems like it could be solved with a reverse polymorphic association like: # Models class Document < ActiveRecord::Base has_many :document_sections has_many :freeform_sections, :through => :document_sections, :source => :section, :source_type => 'FreeformSection' def add_section(section) self.freeform_sections << section if section.is_a? FreeformSection end end class DocumentSection < ActiveRecord::Base belongs_to :document belongs_to :section, :polymorphic => true end class FreeformSection < ActiveRecord::Base has_one :document_section, :as => :section has_one :document, :through => :document_section end # Migrations class CreateDocuments < ActiveRecord::Migration def change create_table :documents do |t| t.string :name t.timestamps end end end class CreateDocumentSections < ActiveRecord::Migration def change create_table :document_sections do |t| t.integer :section_id t.string :section_type t.references :document t.timestamps end end end class CreateFreeformSections < ActiveRecord::Migration def change create_table :freeform_sections do |t| t.references :section t.timestamps end end end # Usage document = Document.create :name => 'My Doc' document.freeform_sections << FreeformSection.new document.add_section FreeformSection.new document.document_sections document.freeform_sections A: Take a look at polymorphic associations. Maybe you can create a 'sectionable' type for your different Section types and put those in one polymorphic association in Document.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Moving between lines in VIM Let's say I have a file with N lines. I'm at line X and I'd like to move to line Y, where both X and Y are visible on screen. I can do that by typing :Y<cr>, but if Y>99 that's a lot of typing. I can also do abs(Y-X)[kj] (move up or down by abs(Y-X)), but for big X,Y computing this difference mentally isn't so easy. Is there a way to exploit the fact, that both X,Y are visible on screen and move between X and Y fast? A: You can :set relativenumber which does that Y-X computing for you (only in Vim >= 7.3). A: You can use H, M or L to go the top, middle and bottom of the screen. A: Perhaps you can make use of H, M, or L. These keys jump the cursor to display lines: H "Home" top of screen M "Middle" middle of screen L "Last" last line of screen With a count, they offset: 4L would go to the third line above the last (1L is the same as just L). Personally, I make heavy use of the m command to mark a line for navigation. From where I am now, hit mq to mark the position with label q; then navigate to another line, and ma to mark it with label a; and from then on I can hit 'q to jump to position q and 'a to jump to position a. (q and a are arbitrary; I use those mostly due to their position on a QWERTY keyboard.) One you have the marks, you can use them for commands. To delete from the current position to the line marked with q, you just use: d'q There is a variant, where instead of single quote you use back quote. This takes you to the exact position on the line where you placed the mark; the single quote uses the start of the line. Those marks work even for ex (command line) commands. To limit search and replace to a specific set of lines, I mark the beginning and end lines respectively with labels b and e, and then do my search and replace like so: :'b,'es/foo/bar/g A: Dropping my dime in the pond: I find that traversing code is exceptionally easy with text objects. I rarely do use jk/JK for larger jumps any more. Instead I navigate for whitespace lines using { and } Since on any one screen there are usually only so-many whitespace delineations (and they are very easily visually recognized and counted), I find that e.g.    3}j lands me on the intended line a lot more often than, e.g., a guesstimated      27j To top it all, many 'brace-full' programming languages have opening braces at the start of functions. These can be reached with [[ resp. ]]. So sometimes it is just a matter of doing, e.g.    2[[} (meaning: go to start of previous function, after the first contiguous block of lines) A: My version of VIM lets you guestimate a number immediately before hitting J or K to go that many lines. 15K goes up 15 lines A: The tougher vimmer you are becoming, the bigger amount of lines you can count at first glance. Don't know, maybe there are some clever techniques, but I just type something like 17k/23j and so on. also, searching some word on the string you want to jump works. also, zz (center screen) is sometimes helpful in this cases.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Query to get one entry from multiple rows Query: select machinename, StatusCode, max(size) as size, statusID from machine where MachineID In( '33','22') and StatusCode = 166 group by machinename, StatusCode, statusID order by max(size) DESC Result: machinename StatusCode size statusID ----------- ---------- ---- -------- test1 166 50 1 test1 166 25 2 test2 166 75 3 test2 166 48 4 Requirement: I need to display only one entry for each machine. I have to do this by taking the max size value between the two entries as shown above. like for test1 i have two sizes 50 and 25 I have to show the row which has 50 and ignore row which has 25. Thanks Desired Result: machinename StatusCode size statusID ----------- ---------- ---- -------- test1 166 50 1 test2 166 75 3 A: SELECT machinename, StatusCode, size, statusID FROM ( SELECT machinename, StatusCode, size, statusID, ROW_NUMBER() OVER (PARTITION BY MachineID ORDER BY size DESC) AS rn FROM machine WHERE MachineID IN ('33','22') AND StatusCode = 166 ) T1 WHERE rn = 1 ORDER BY size DESC
{ "language": "en", "url": "https://stackoverflow.com/questions/7602620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Programmatically access to TFS 2010 from outside the domain I'm trying to access my TFS server programmatically from outside the domain where the server is installed. A basic test program would look like this : class Program { static void Main(string[] args) { Uri tfsUri = new Uri("<serverUri>"); TfsConfigurationServer _ConfigurationServer = TfsConfigurationServerFactory.GetConfigurationServer(tfsUri); CatalogNode projectCollectionCatalog = _ConfigurationServer.CatalogNode.QueryChildren(new[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None)[0]; // actual connection tries to happen here } } Another version, with credentials forced : class Program { static void Main(string[] args) { Uri tfsUri = new Uri("<serverURI>"); TfsConfigurationServer _ConfigurationServer = new TfsConfigurationServer(tfsUri, new NetworkCredential("<DifferentKindOfUsernames>", "<Password>")); CatalogNode projectCollectionCatalog = _ConfigurationServer.CatalogNode.QueryChildren(new[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None)[0]; } } Another version with a mix of both previous version : public class ConnectByImplementingCredentialsProvider : ICredentialsProvider { public ICredentials GetCredentials(Uri uri, ICredentials iCredentials) { return new NetworkCredential("<DifferentKindOfUsernames>", "<Password>", "<DomainOrNot>"); } public void NotifyCredentialsAuthenticated(Uri uri) { throw new ApplicationException("Unable to authenticate"); } } class Program { static void Main(string[] args) { string _myUri = @"<serverUri>"; ConnectByImplementingCredentialsProvider connect = new ConnectByImplementingCredentialsProvider(); ICredentials iCred = new NetworkCredential("<DifferentKindOfUsernames>", "<Password>", "<DomainOrNot>"); connect.GetCredentials(new Uri(_myUri), iCred); TfsConfigurationServer configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(new Uri(_myUri), connect); configurationServer.EnsureAuthenticated(); } } And a version with an active directory Impersonator : class Program { static void Main(string[] args) { using (new Impersonator("<DifferentKindOfUsernames>", "<DomainOrNot>", "<Password>")) { Uri tfsUri = new Uri("<serverUri>"); TfsConfigurationServer _ConfigurationServer = TfsConfigurationServerFactory.GetConfigurationServer(tfsUri); CatalogNode projectCollectionCatalog = _ConfigurationServer.CatalogNode.QueryChildren(new[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None)[0]; // actual connection tries to happen here } } } serverURI being in the form of http://<servername>:8080/tfs or http://<serverip>:8080/tfs (both tested, with hosts file up to date) which is what is set as Notification URL on the TFS Server. This program works inside the domain. DifferentKindOfUsernames being anything from 'DOMAIN\Username', 'LocallyDuplicatedUsername', 'LOCALMACHINE\Username' with the appropriate password, password being the same in the domain and on the machine. This simple access won't work outside of the domain , and I have this error : TF30063: You are not authorized to access <serverUri> translated in a web context (using the same process in an asp.net website), it is a 401 error : The remote server returned an error: (401) Unauthorized. even if (things tested so far) : * *I have a mapping between the local user/password who runs the program on the domain outsider machine and an active directory account who has admin access to TFS(even with impersonation rights on TFS activated) . *I add a BackConnectionNames registry key with the domain outsider machine name and ip like described here. *I disable the loopback check like described here. *I use an Active Directory Impersonator with different combination of user / domain or machine name. Active Directory Impersonator being described here. *I added the TFS Server IP to the local internet zone (tried trusted site as well) in the domain outsider server IE security options like described here. I have tested the access to the serverURI from a browser. The uri works and I have access to the TFS Collection if I give the credentials with DomainName\User + Password. I tested this before any of the modifications I described before. I wonder what could be the difference between the programmatic access and the browser access besides all the things I have tested so far. A: You're not passing credentials to build the connection. This means that you're using your currently logged in credentials from the host outside of the domain. I'm not an expert on Windows Authentication, but I think that this can, in certain circumstances, work transparently (if the username and password are identical) but it appears to depend on the NTLM version being used, the client and server operating systems, trust relationships and security zones, the IIS configuration and perhaps the phase of the moon. In other words, you probably want to pass the credentials to the connection: TfsConfigurationServer _ConfigurationServer = new TfsConfigurationServer(uri, new NetworkCredential("username", "password", "DOMAIN")); Note that it's strongly recommended to enable SSL/TLS if you're connecting to your server over an untrusted (public) network. (I corrected this to use the three-arg constructor for NetworkCredential -- my mistake. As you note, if you put DOMAIN\username in the username argument to NetworkCredential, it will treat it as \DOMAIN\username instead of DOMAIN\username. This, I suppose, it why nobody lets me write C# code.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7602627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Setting up Delphi XE to use Vim as Default Merge Viewer Is it possible to use vim as the default merge viewer for Delphi XE to resolve check-in conflicts? If so, what parameters do I need to use in the tools->options->Merge Viewer dialog? A: Yeah, it works. Put gvim in as the program, the working directory will automatically fill in. Then use the following parameters: -f -d -c "wincmd J" $(OutputFileName) $(MyFileName) $(BaseFileName) $(TheirFileName) source
{ "language": "en", "url": "https://stackoverflow.com/questions/7602632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: stat & S_IFREG in C++ void fun1(char *fl){ //flNamep : stores the path of our directory DIR *dip; struct dirent *dit; dip = opendir(fl); if (dip==NULL) {cerr<<"Error\n";exit(-1);} while ((dit=readdir(dip))) { string trun = (dit->d_name); struct stat buff; stat(dit->d_name, &buff); if (((buff.st_mode & S_IFREG)==S_IFREG)) {cout<<"File"<<endl;} else if (((buff.st_mode & S_IFDIR)==S_IFDIR)) {cout<<"Dir"<<endl;} } closedir(dip); } Code does not differentiate in dir and files. Am i missing something? I can not use Boost or any other STL. only C Posix Supported files. Need to know were i am wrong. Updated code as per answer DIR *dip; struct dirent *dit; dip = opendir(flNamep); if (dip==NULL) {cerr<<"Err\n";exit(-1);} while ((dit=readdir(dip))) { string trun = (dit->d_name); string fullpath = flNamep; fullpath+='/'; fullpath+=trun; if((trun==".") || (trun=="..")) {cout<<"";} else { struct stat buff; stat(dit->d_name, &buff); if (((buff.st_mode & S_IFDIR)==S_IFDIR)) {cout<<"Dir"<<endl;} else {cout<<"File"<<endl;} } A: I suspect that the stat actually fails with ENOENT (no such file) so buff doesn't contain anything useful. stat(dit->d_name, &buff); /* dirent.d_name is just the name, not the full path */ You probably want to concatenate fl, "/", d_name. But first of all, check the value returned by stat.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ruby sftp error password reset I am troubleshooting a ruby script that queries a database, creates a csv, and sftps it to another server. The server the script is on is a rhel box, running ruby 1.87 I believe. Here's the code that does the sftping: Net::SFTP.start(sftp_site, sftp_user, :password => sftp_pswd) do |sftp| sftp.upload!(local_filepath,sftp_dir+filename) end When executing the script, there is a curious message before it bombs out: Password Reset Your password has expired. You are required to change your password to proceed. This script works on another server, but not this one. A user can sftp from the prompt on this machine. SELinux has been turned off, as it may have had some interference. Anyway, point being, does anyone have any ideas? A: It appeared to be a gem issue (though someone in networking may have worked some magic I am unaware of). The production server had older versions of the net/ssh and net/sftp gems. It had version 1.1.1 and version 1.1.2, respectively, and upgrading those gems to a later version fixed the issue. Thanks for everyone who offered suggestions! A: I would compare the sshd daemon settings (sshd_config), as there's likely an issue in the server that's not working. Perhaps interactive-keyboard authentication is turned on or something like that?
{ "language": "en", "url": "https://stackoverflow.com/questions/7602637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Stop jquery functions inside dialog on close? I created a messaging system which opens up in a jquery dialog when the user clicks the link. It check ever 5 seconds for new messages. the thing is, after the user closes the dialog it continues to check for messages which is using up a lot of resources if the user does not refresh the page. so is there a way to kill functions after closing the dialog? Code which open the dialog. $('body a#link').each(function() { var $dialog = $('<div></div>'); var $link = $(this).one('click', function() { $dialog .load($link.attr('href')) .dialog({ title: $link.attr('title'), width: 500, height: 300 }); $link.click(function() { $dialog.dialog('open'); return false; }); return false; }); }); Messenger.php (which is loaded into the dialog) <script type="text/javascript"> $(function() { $("form").submit(function() { return false; }); }); $('#message').keypress(function(e) { if(e.which == 13) { $.ajax({ type: "POST", url: "includes/sendmessage.php", data: $("#messageform").serialize(), success: function(){ $("#message").val(""); } }); } }); setInterval(function() { var msngr = $.ajax({ type: "GET", url: "includes/checkmessages.php", success: function(msg){ $('div#messages').html(msg); $("div#messages").scrollTop($("div#messages")[0].scrollHeight); } }); }, 5000); </script> <div id="messages" style="width: 450px; height: 350px; overflow: auto;"><?php include("includes/dbcon.php"); $result = mysql_query("SELECT * FROM messages WHERE message!='' ORDER BY id LIMIT 50") or die(mysql_error()); while($row = mysql_fetch_array($result)) { $username = $row['username']; $message = $row['message']; echo stripslashes($username) . ": " . stripslashes($message) . "<br />"; } mysql_close($con); ?></div> <form id="messageform" method="post" action=""> <input type="text" id="message" width="450px" maxlength="500" name="message" /> </form> A: you'll want to assign your repeating code a variable var refreshTimer=null; refreshTimer = setInterval(function() { var msngr = $.ajax({ type: "GET", url: "includes/checkmessages.php", success: function(msg){ $('div#messages').html(msg); $("div#messages").scrollTop($("div#messages")[0].scrollHeight); } }); }, 5000); Then, when the dialog is closed you'll want to use clearInterval() to stop the timer from re-executing. if (refreshTimer) clearInterval(refreshTimer); UPDATE If you want to re-enable the timer, I would throw the whole thing in a function. This way you can call stopMessageRefreshTimer(); or startMessageRefreshTimer(); whenever you want. var refreshTimer=null; function stopMessageRefreshTimer(){ if (refreshTimer) clearInterval(refreshTimer); } function startMessageRefreshTimer(){ refreshTimer = setInterval(function() { var msngr = $.ajax({ type: "GET", url: "includes/checkmessages.php", success: function(msg){ $('div#messages').html(msg); $("div#messages").scrollTop($("div#messages")[0].scrollHeight); } }); }, 5000); } A: You need to stop the setInterval. This can be done like this: var intervalId = setInterval(function(){},5000); clearInterval(intervalId); A: use window.clearInterval to stop the timer on the dialog close event var timer = setInterval(function() { var msngr = $.ajax({ type: "GET", url: "includes/checkmessages.php", success: function(msg){ $('div#messages').html(msg); $("div#messages").scrollTop($("div#messages")[0].scrollHeight); } }); }, 5000); $dialog.dialog({ close: function(event, ui) { clearInterval(timer) } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7602638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PyPDF Merge and Write issue I am getting an unexpected error when using this. The first section is from a script that I found online, and I am trying to use it to pull a particular section identified in the PDF's outline. Everything works fine, except right at output.write(outputfile1) it says: PdfReadError: multiple definitions in dictionary. Anybody else run into this? Please forgive all the unnecessary prints at the end. :) import pyPdf import glob class Darrell(pyPdf.PdfFileReader): def getDestinationPageNumbers(self): def _setup_outline_page_ids(outline, _result=None): if _result is None: _result = {} for obj in outline: if isinstance(obj, pyPdf.pdf.Destination): _result[(id(obj), obj.title)] = obj.page.idnum elif isinstance(obj, list): _setup_outline_page_ids(obj, _result) return _result def _setup_page_id_to_num(pages=None, _result=None, _num_pages=None): if _result is None: _result = {} if pages is None: _num_pages = [] pages = self.trailer["/Root"].getObject()["/Pages"].getObject() t = pages["/Type"] if t == "/Pages": for page in pages["/Kids"]: _result[page.idnum] = len(_num_pages) _setup_page_id_to_num(page.getObject(), _result, _num_pages) elif t == "/Page": _num_pages.append(1) return _result outline_page_ids = _setup_outline_page_ids(self.getOutlines()) page_id_to_page_numbers = _setup_page_id_to_num() result = {} for (_, title), page_idnum in outline_page_ids.iteritems(): result[title] = page_id_to_page_numbers.get(page_idnum, '???') return result for fileName in glob.glob("*.pdf"): output = pyPdf.PdfFileWriter() print fileName pdf = Darrell(open(fileName, 'rb')) template = '%-5s %s' print template % ('page', 'title') for p,t in sorted([(v,k) for k,v in pdf.getDestinationPageNumbers().iteritems()]): print template % (p+1,t) for p,t in sorted([(v,k) for k,v in pdf.getDestinationPageNumbers().iteritems()]): if t == "CATEGORY 1": startpg = p+1 print p+1,'is the first page of Category 1.' if t == "CATEGORY 2": endpg = p+1 print p+1,'is the last page of Category 1.' print startpg, endpg pagenums = range(startpg,endpg) print pagenums for i in pagenums: output.addPage(pdf.getPage(i)) fileName2 = "%sCategory1_data.pdf" % (str(fileName[:-13])) print "%s has %s pages." % (fileName2,output.getNumPages()) outputfile1 = file(r"%s" % (fileName2), 'wb') output.write(outputfile1) outputfile1.close() A: I know it might be too late for you, but for anyone else who will stumble here to look for the answer: I had the same problem today, setting: export_reader = PdfFileReader(filename, strict=False) If you are just merging, then use: merger = PdfFileMerger(strict=False) This way, you will get only a warning, rather than an exception.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to display the similar information in every view? I would like to display the information about user's registration state. It should be displayed on every view, but i consider, that writting this code for about 20 times is a bad idea. By the way, this is the code, it works, i guarantee that: View/RegistrationInfo: <table width="95%" border="0" cols="2"> <tr> <td width="50%" height="124"><h2><strong>Simple Blog </strong></h2></td> <td width="50%" height="124"> @if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated) { using (Html.BeginForm("LogOff", "Account")) { <table width="95%" height="86" border="0"> <tr> <td width="50%" valign="middle">Hello, @System.Web.HttpContext.Current.User.Identity.Name</td> <td width="50%" valign="middle" align = "right"><input type="submit" value="Exit" /></td> </tr> </table> } } else { using (Html.BeginForm("LogIn", "Home")) { <table width="95%" height="86" border="0"> <tr> <td width="45%" valign="bottom">Login:</td> <td width="45%" valign="bottom">Password:</td> <td width="10%"></td> </tr> <tr> <td width="45%"> <p> <input type="text" name="login" /> </p> </td> <td width="45%"> <p> <input type="password" name="password" /> </p> </td> <td width="10%" align="left"> <input type="submit" value="Enter" /> </td> </tr> <tr> <td width="45%" valign="top"> @Html.ActionLink("Register", "Register", "Account") </td> </tr> </table> } } </td> </tr> </table> <hr align="left" width="100%" size="2" /> As you can see, this view doesn't require to be strongly typed... and i don't know, should I modify any controllers (because, all information is stored in HTML Context), and how. I tried to call @Html.RenderAction("RegistrationInfo", "Home"); or @Html.RenderPartial("RegistrationInfo", "Home"); and every time i receive compile error with message about invalid parametres A: While Darin's answer perfectly covers your question, I would point out that registration information seems like it's part of your layout more (master page for the .aspx-inclined) than an actual action. So what I would do (and indeed, do do) is put it either in the header part of your layout in the top right or under your side menu or something, and let the layout handle all the details of rendering it (with a conditional around it to hide it when you're not logged in, so you don't see it on the login screen). A: The following should work: @Html.Partial("~/Views/Home/RegistrationInfo.cshtml") Or if you are inside a view of the Home controller simply: @Html.Partial("RegistrationInfo") Or if you put this partial in ~/Views/Shared/RegistrationInfo.cshtml you will be able to reference with the shorthand syntax.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android static vs nonstatic issue I've been trying to call the following: public static void startfile() { Log.i("File Works", "working2 "); try { FileOutputStream fos = openFileOutput("sdcard/sdtext.txt", MODE_WORLD_WRITEABLE); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } I get an error that tells me that "Cannot make a static reference to the non-static method openFileOutput(String, int) from the type ContextWrapper" So I searched for that error and found this site. I implemented this: public static void startfile(Trackfile O) { Log.i("File Works", "working2 "); O.nonstatstartfile(); } public void nonstatstartfile(){ Log.i("File Works", "nonStat"); try { FileOutputStream fos = openFileOutput("sdcard/sdtext.txt", MODE_WORLD_WRITEABLE); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } When I call startfile from another class getting a Null pointer error. What argument do I need to send to avoid the null pointer error? A: You can pass context from activity like below public static void startfile(Context c) { Log.i("File Works", "working2 "); try { FileOutputStream fos = c.openFileOutput("sdcard/sdtext.txt", MODE_WORLD_WRITEABLE); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } A: public void startfile() { Log.i("File Works", "working2 "); try { FileOutputStream fos = openFileOutput("sdcard/sdtext.txt", MODE_WORLD_WRITEABLE); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } Add this method to your class, and use it without problems. If you need it in main class, use it over object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602648", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to respect Robots.txt using Nokogiri? I'm testing it and Nokogiri does not seem to respect Robots.txt file. Is there someway to make it respect? It seems like common question, but I could not find any answer online. A: Nokogiri parses the HTML or webpage that you give it. It does not know anything about the robots.txt file for the domain where the page you happen to have requested resides. I presume that you want to ignore in-site links that are in robots.txt? Since you've tagged this Rails, I'll assume you use Ruby. In that case you can use the Mechanize library which has the facility to use the robots.txt file. There is also the original Perl version and other language ports if you prefer those.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Inserting into multiple tables using more than one ID that just got created I had to add another table into my database and now I need to go back and update a page that allows inserts into more than one table. I didn't write this page, so I'm trying to clean everything up, but there are some parts that I don't really understand. Now I have broken the page and it only inserts into one table. The very first one that I insert into. ProductName: goes into the Product table Description: goes into the Picklist table as Data.....it also is supposed to generate an insert into the marketing table based on the PicklistID which is an identity column. The marketing table tells the Picklist table that it is looking for a description. Price: goes into Product table Category: goes into the CategoryLink table which also inserts the recently generated ProductID. Company: goes into the CompanyLink table which also inserts the recently generated ProductID. Target audience: goes into the TargetLink table which also inserts the recently generated ProductID. Status: goes into the Product table Protected Sub submitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitButton.Click Dim CategoryID As String = txtCategoryID.Value Dim CompanyIDs As New ArrayList 'Get selected companies----- Dim CompanyCount As Integer = CompanyCheckbox.Items.Count For i As Integer = 0 To CompanyCount - 1 If CompanyCheckbox.Items(i).Selected Then CompanyIDs.Add(CompanyCheckbox.Items(i).Value) End If Next 'Get selected targets--- Dim TargetIDs As New ArrayList Dim TargetCount As Integer = TargetCheckbox.Items.Count For i As Integer = 0 To TargetCount - 1 If TargetCheckbox.Items(i).Selected Then TargetIDs.Add(TargetCheckbox.Items(i).Value) End If Next 'Get Status--- Dim Status As String = Nothing If StatusCheckbox.Checked Then Status = "1" Else Status = "0" End If 'SQL Insert: Product Table Dim sqlInsertProduct As String = "IF NOT EXISTS (SELECT * FROM Product WHERE ProductName= @ProductName) BEGIN INSERT INTO Product (ProductName, Status, CreateDate, ModifyDate, CreateUser, ModifyUser, Price) VALUES (@ProductName, @Status ,getdate(),getdate(), @CreateUser, @ModifyUser, @Price) END; INSERT INTO Picklist (Title, Data) VALUES ('About this product', @Data);" 'Create SQL Connection Using cn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings ("LocalSqlServer").ConnectionString) Using cmd As New SqlCommand(sqlInsertProduct, cn) cmd.Parameters.Add(New SqlParameter("@ProductName", txtNewProductName.Text)) cmd.Parameters.Add(New SqlParameter("@Status", StatusCheckbox.Checked)) cmd.Parameters.Add(New SqlParameter("@Price", txtPrice.Text)) cmd.Parameters.Add(New SqlParameter("@Data", txtProductDesc.Text)) cmd.Parameters.Add(New SqlParameter("@CreateUser", System.Web.HttpContext.Current.User.Identity.Name)) cmd.Parameters.Add(New SqlParameter("@ModifyUser", System.Web.HttpContext.Current.User.Identity.Name)) cn.Open() cmd.ExecuteNonQuery() End Using 'Get the productID of the newly inserted product Dim sqlGetID As String = "SELECT @@IDENTITY" Dim ProductID As String = Nothing Dim cmdGetID As New SqlCommand(sqlGetID, cn) Dim myReader As SqlDataReader = cmdGetID.ExecuteReader() While myReader.Read If IsDBNull(myReader(0)) Then ProductID = "" Else ProductID = myReader(0) End If End While myReader.Close() cn.Close() 'SQL Insert: Marketing Table Dim sqlInsertMarketing As String = "INSERT INTO Marketing (ProductID, MarketingTypeID, MarketingTitle, MarketingData) VALUES ('" & ProductID & "', 2, 'Description', scope_identity())" 'SQL Insert: Category Table If CategoryID <> Nothing Then Dim sqlInsertCategory As String = "INSERT INTO CategoryLink (CategoryID, ProductID) VALUES (@CategoryID,'" & ProductID & "')" Using cmdInsertCategory As New SqlCommand(sqlInsertCategory, cn) cmdInsertCategory.Parameters.Add(New SqlParameter("@CategoryID", txtCategoryID.Value)) cn.Open() cmdInsertCategory.ExecuteNonQuery() End Using cn.Close() End If If CompanyIDs.Count > 0 Then For i = 0 To CompanyIDs.Count - 1 Dim sqlInsertCompany = "INSERT INTO CompanyLink (CompanyID, ProductID) VALUES ('" & CompanyIDs(i) & "','" & ProductID & "')" Using cmdInsertCompany As New SqlCommand(sqlInsertCompany, cn) cn.Open() cmdInsertCompany.ExecuteNonQuery() End Using cn.Close() Next End If If TargetIDs.Count > 0 Then For i = 0 To TargetIDs.Count - 1 Dim sqlInsertTarget = "INSERT INTO TargetLink (TargetID, ProductID) VALUES ('" & TargetIDs(i) & "','" & ProductID & "')" Using cmdInsertTarget As New SqlCommand(sqlInsertTarget, cn) cn.Open() cmdInsertTarget.ExecuteNonQuery() End Using cn.Close() Next End If End Using Response.Write("<script type='text/javascript'>{ alert('Product added successfully'); document.location.href = 'AddProduct.aspx'; }</script>") End Sub End Class Like I said before, only the insert that goes into the Product table works. Before I added the Picklist table and tried to reconnect everything, this entire page worked. The code was a lot sloppier and didn't have parameters, so that could also be where I messed up since I am still trying to learn how to use them. If I need to include additional information I can do that. I don't know how detailed to make this post. Thanks UPDATE: I have gotten everything to INSERT except for the INSERT to the Marketing table. I would really appreciate someone who can help me get that PicklistID to insert into the MarketingData column of the Marketing table A: If you only have one identity value to get use SCOPE_IDENTITY(), never use @@IDENTITY. The problem with @@IDENTITY is that it always returns the last identity value, even if it was from another "scope". For example, you insert into your table and an identity value is generated, a trigger then fires that inserts in to a log table with an identity. You then call @@IDENTITY, guess what you get the log table identity value, it was last. SCOPE_IDENTITY() gives you the last within your local scope. HOWEVER, if you need to capture multiple identity values because you insert multiple rows in one statement, you must use the OUTPUT clause. It works on INSERT, UPDATE and DELETE, but here is an example on an UPDATE: view the changed values after an update statement A: This is one of the drawbacks of surrogates i.e. harder to perform bulk-creation of entities. I avoid using surrogates myself but often come up against this problem. My general approach is to use a staging table to map system-generated surrogates to their natural keys. Assuming this somewhat simplified structure: CREATE TABLE Products ( ProductName VARCHAR(20) NOT NULL UNIQUE, -- natural key ProductID INTEGER IDENTITY(1, 1) NOT NULL UNIQUE -- surrogate ); CREATE TABLE PickLists ( PicklistDescription VARCHAR(30) NOT NULL UNIQUE, -- natural key PicklistID INTEGER IDENTITY(50, 50) NOT NULL UNIQUE -- surrogate ); CREATE TABLE Marketing ( ProductID INTEGER NOT NULL UNIQUE REFERENCES Products (ProductID), PicklistID INTEGER NOT NULL UNIQUE REFERENCES PickLists (PicklistID), MarketingComment VARCHAR(40) NOT NULL ); the following is a basic outline using vanilla Standard SQL-92 (IDENTITY keyword excepted!): (note: natural keys are those generated outside of the DBMS and surrogates are DBMS-generated values) CREATE TABLE StagingMarketing ( ProductName VARCHAR(20) NOT NULL UNIQUE, PicklistDescription VARCHAR(30) NOT NULL UNIQUE, MarketingComment VARCHAR(40) NOT NULL ); -- Bulk insert staging table using natural key values INSERT INTO StagingMarketing (ProductName, PicklistDescription, MarketingComment) VALUES ('Widget55', 'Stuff22', 'Prototype'); INSERT INTO StagingMarketing (ProductName, PicklistDescription, MarketingComment) VALUES ('Widget99', 'Stuff152', 'Research'); -- Update referenced tables INSERT INTO Products (ProductName) SELECT ProductName FROM StagingMarketing; INSERT INTO PickLists (PicklistDescription) SELECT PicklistDescription FROM StagingMarketing; -- Finally, update referencing table INSERT INTO Marketing (ProductID, PicklistID, MarketingComment) SELECT P.ProductID, L.PicklistID, S.MarketingComment FROM StagingMarketing S INNER JOIN Products P ON P.ProductName = S.ProductName INNER JOIN PickLists L ON L.PicklistDescription = S.PicklistDescription; -- Cleanup DELETE FROM StagingMarketing; SELECT * FROM Marketing; p.s. if the designer chose to use IDENTITY as an artificial key in absence of a natural key then you are up the creek.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: When I initialize a C++ container (such as a std::list) is the copy constructor called? When I initialize a STL container such as a list< vector<char> > using e.g. my_list.push_back(vector<char>(5000, 'T')) is this copied after construction? Or does the compiler invoke the constructor inside list< vector<char> > itself? A: In C++03 push_back is defined as void push_back(const T& x);. That means that you are constructing a vector and a const reference to such temporal is being passed to the list. Then the list internally invokes the copy constructor in order to store a copy of such element. In C++11 there is an extra definition for void push_back(T&& x); that takes an rvalue reference to your temporal vector, and would result in the move constructor being called internally to initialize the copy held by the list. A: Compilers are smart. Really smart. In this case, there is an optimization called "copy elision." The C++ standard allows the compiler to omit a copy when a temporary object is used to initialize an object of the same type and the copy constructor of said object has no side effects. This is in the same class of optimizations as the more popular "as if" rule. That rule allows the compiler to get away with nearly anything it wants, as long as the observable behavior of the resulting program is the same "as if" the standard had been followed exactly. Here is an example program. On gcc 4.4.5 with both -O0 and -O3 this code results in a "1" being printed. I think that GCC is wrong here... some compilers will output "2" indicating a copy took place. This is where things get tricky in trying to detect behavior that is supposed to be undetectable. In one of those compilers, the only way to tell will be to dive into the resulting assembly. #include <iostream> struct elision { explicit elision(int i) : v(i) { } elision(elision const &copy) : v(copy.v+1) { } int v; }; int main() { elision e(elision(1)); std::cout << e.v << std::endl; return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7602656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is there a way to add a permission to an application I'm testing? (my own app) My application needs that GPS is active at startup as for it to proceed. Iam testing the app, so I'm mocking the GPS by adding <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" /> to my AndroidManisfest.xml file. This works ok. But I want to keep things separate. Is it possible to add a permission at runtime when we are testing? EDIT: I know from the docs that: Android has no mechanism for granting permissions dynamically (at run-time) because it complicates the user experience to the detriment of security. But as a matter of testing the application, is there an alternative? Thanks A: There is no way to add Android permissions at run-time. They must be specified in your manifest. If you have a separate test application, I believe you only need to put this permission on your test application. EDIT A test application is really no different to Android than a regular one in terms of permissions. I would just put the permission in your test application's manifest and not worry about it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Graph Representation in C++ I am going through a book The Design and Analysis of Computer Algorithms Reading through the Graph chapter, I am trying to implement DFS. By Reading definition of this algorithm it says, Graph G=(V,E) partiions the edges in E into two sets T and B. An Edge (v,w) is place in set T if vertes w has not been previously visited when we are at vertex v considering edged (v,w) , otherwise edge `(v,w) is place in set B. Basically his algorithm of DFS will give me new Graph which will be G=(V,T). I want to know how one would implement this in C++. I tried using adjacency list, but I am confuse is there a need of storing edges of just a map of list should be fine. A: In VTK, edges are stored in a vector, and it always stores a pair (v,w). Near this vector there are 2 other vector of vectors to store in and out edges of graph nodes. When a new edge is added, it added to edge vector, its nodes (v,w) are added to in and out edges vector of vectors, too. A: I am not quite clear about what your exact question is. I assume that you are asking about how to maintain two sets T and B to distinguish edges that have been visited from edges that have been not during DFS. I think the easiest way to do so is to add a bool field "visited" to the node struct in your adjacency list. Initial value of this field for all nodes are "false". Suppose in the above case, when DFS come to v, and the edge (v,w) is not visited, then the node on the list of v that corresponds to w would have a value "false" for "visited" at that time. Otherwise it will have a value of "true". I think the author just try to give you the idea that edges will be categorized into two kinds: visited and not visited at the end of DFS. But I don't think keep two explicit sets maintaining those two kinds of edges are necessary. You can always print the visited edges after DFS according to their updated "visited" value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602664", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Store an array in HashMap i'm new to Java. How can i store an array of integers values in a HashMap, after that i write this HashMap in a txt file but this isn't important at the moment. I can store single fields but not an array. Any ideas ? public void salveazaObiectulCreat(String caleSpreFisier) { HashMap map = new HashMap(); map.put ("Autorul",numelePrenumeleAutorului); map.put ("Denumirea cartii",denumireaCartii); map.put ("Culoarea cartii",culoareaCartii); map.put ("Genul cartii",gen); map.put ("Limba",limba); map.put ("Numarul de copii",numarulDeCopii); map.put ("Numarul de pagini",numarulDePagini); map.put ("Pretul cartii",pretulCartii); try { File file = new File(caleSpreFisier); FileOutputStream f = new FileOutputStream(file); ObjectOutputStream s = new ObjectOutputStream(f); s.writeObject(map); s.close(); } catch(Exception e){ System.out.println("An exception has occured"); } } A: Yes, the Map interface will allow you to store Arrays as values. Here's a very simple example: int[] val = {1, 2, 3}; Map<String, int[]> map = new HashMap<String, int[]>(); map.put("KEY1", val); Also, depending on your use case you may want to look at the Multimap support offered by guava. A: HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>(); HashMap<String, int[]> map = new HashMap<String, int[]>(); pick one, for example HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>(); map.put("Something", new ArrayList<Integer>()); for (int i=0;i<numarulDeCopii; i++) { map.get("Something").add(coeficientUzura[i]); } or just HashMap<String, int[]> map = new HashMap<String, int[]>(); map.put("Something", coeficientUzura); A: Not sure of the exact question but is this what you are looking for? public class TestRun { public static void main(String [] args) { Map<String, Integer[]> prices = new HashMap<String, Integer[]>(); prices.put("milk", new Integer[] {1, 3, 2}); prices.put("eggs", new Integer[] {1, 1, 2}); } } A: If you want to store multiple values for a key (if I understand you correctly), you could try a MultiHashMap (available in various libraries, not only commons-collections). A: Your life will be much easier if you can save a List as the value instead of an array in that Map. A: You can store objects in a HashMap. HashMap<String, Object> map = new HashMap<String, Object>(); You'll just need to cast it back out correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "33" }
Q: How to invalidate token for C2DM with previous installs? Since there is apparently no reliable way to get the devices unique identifier, our app tracks the installation using this class... package com.themenetwork.app.misc; import java.io.*; import java.util.UUID; import android.content.Context; public class Installation { private static String sID = null; private static final String INSTALLATION = "INSTALLATION"; public synchronized static String id(Context context) { if (sID == null) { File installation = new File(context.getFilesDir(), INSTALLATION); try { if (!installation.exists()) writeInstallationFile(installation); sID = readInstallationFile(installation); } catch (Exception e) { throw new RuntimeException(e); } } return sID; } private static String readInstallationFile(File installation) throws IOException { RandomAccessFile f = new RandomAccessFile(installation, "r"); byte[] bytes = new byte[(int) f.length()]; f.readFully(bytes); f.close(); return new String(bytes); } private static void writeInstallationFile(File installation) throws IOException { FileOutputStream out = new FileOutputStream(installation); String id = UUID.randomUUID().toString(); out.write(id.getBytes()); out.close(); } } The resulting UUID is sent back to our server, with the C2DM token. We send C2DM notifications to the device based on this token. However, if the app is removed we have no way of knowing and any subsequent installs have no way of invalidating the token and Google doesn't appear to be doing it automatically. This is causing devices who have installed more than once to get duplicate notifications. Any ideas? A: Can you unregister the App from C2DM by: public static final String REQUEST_UNREGISTRATION_INTENT = "com.google.android.c2dm.intent.UNREGISTER"; public static final String GSF_PACKAGE = "com.google.android.gsf"; public static final String EXTRA_APPLICATION_PENDING_INTENT = "app"; public static void unregister(Context context) { Intent regIntent = new Intent(REQUEST_UNREGISTRATION_INTENT); regIntent.setPackage(GSF_PACKAGE); regIntent.putExtra(EXTRA_APPLICATION_PENDING_INTENT, PendingIntent.getBroadcast(context, 0, new Intent(), 0)); context.startService(regIntent); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7602678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Strings between quotation marks in C++ Possible Duplicate: What do single quotes do in C++ when used on multiple characters? The following code compiles in C++: unsigned int x; x = 'abc'; What does it mean? Is putting string between quotation marks legal? What does it do? A: Is not a string, but a multi character literal. See What do single quotes do in C++ when used on multiple characters?. (Vote to close as duplicated)
{ "language": "en", "url": "https://stackoverflow.com/questions/7602682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cannot modify header information - headers already sent In my (WordPress) functions when I try to change Code 1 to Code 2 I get this error: Warning: Cannot modify header information - headers already sent by (output started at /home/consumer/public_html/themeforward.com/demo2/wp-content/themes/Tutles/functions.php:1) in /home/consumer/public_html/themeforward.com/demo2/wp-admin/theme-editor.php on line 99 Code 1 array( "name" => "Custom CSS", "desc" => "Want to add any custom CSS code? Put in here, and the rest is taken care of. This overrides any other stylesheets. eg: a.button{color:green}", "id" => $shortname."_custom_css", "type" => "textarea", "std" => "" ), Code 2 array( "name" => "Link Color", "desc" => "Want to add any custom CSS code? Put in here, and the rest is taken care of. This overrides any other stylesheets. eg: a.button{color:green}", "id" => $shortname."_link_color", "type" => "textarea", "std" => "" ), Lines 89 - 102: // don't allow template files in subdirectories if (false !== strpos($basename, '/')) continue; $template_data = implode('', file( $template )); $name = ''; if (preg_match( '|Single Post Template:(.*)$|mi', $template_data, $name)) $name = _cleanup_header_comment($name[1]); if (!empty($name)) { if(basename($template) != basename(__FILE__)) $post_templates[trim($name)] = $basename; } I am completely confused as to how to fix this. A: You probably created a file (or edited a file). I assume functions.php? There probably is a whitespace in that file, being it on the beginning of the file, or at the end. To prevent whitespaces from happening on the end of the file, just remove the ?> tag. Also remove any whitespace at the beginning of every file A: Is your php file encoded in UTF8 without BOM ? If not, encode it this way and try again. maybe this is way you get the error A: You have blank space or BOM before your first <?php tag. Remove it A: When using certain encodings some editors add "dtž" at the beginning of the file (which is not shown in the editor.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602683", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Why does Spring 3.x ignore certain placeholderPrefixes for PropertyPlaceholderConfigurer? I have the bean definitions below. If I change the placeholderPrefix for the "exposeSystemProperties" bean to "${" and use that in the properties path of the second bean, it works. If I change it to anything but "%{" it doesn't work. I can't use any other string (e.g. "$sys{", "#[", etc.). I'm currently on 3.0.5.RELEASE. Any thoughts as to why this is? To compound it all, I have a 3rd PropertyPlaceHolderConfigure, so only having two prefixes does not work. <bean id="exposeSystemProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="ignoreUnresolvablePlaceholders" value="true" /> <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" /> <property name="placeholderPrefix"><value>$sys{</value></property> <property name="order" value="10" /> </bean> <bean id="localFileProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="ignoreUnresolvablePlaceholders" value="true" /> <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_NEVER" /> <property name="placeholderPrefix" value="%{" /> <property name="placeholderSuffix" value="}" /> <property name="order" value="20" /> <property name="locations"> <array> <bean class="java.lang.String"> <constructor-arg><value>classpath:properties/$sys{deploy.env}/client.properties</value></constructor-arg> </bean> </array> </property> </bean> A: Since what you need the prefix for is to control environment specific properties, this can be done by using system variables ( instead of a deploy.env property in your example ): <value>classpath:properties/${ENV_SYSTEM:dev}/client.properties</value> In this case it will always look under: <value>classpath:properties/dev/client.properties</value> by default, unless a ENV_SYSTEM system variable is set. If it is set to "qa", for example, it will automatically look under: <value>classpath:properties/qa/client.properties</value> Another approach, in case you are open to "look into the future" a bit, is to use Spring 3.1's PROFILE feature, where beans can be profile specific. For example: <beans profile="dev"> <jdbc:embedded-database id="dataSource"> <jdbc:script location="classpath:com/bank/config/sql/schema.sql"/> <jdbc:script location="classpath:com/bank/config/sql/test-data.sql"/> </jdbc:embedded-database> </beans> This dataSource will only be loaded in case a profile is set to dev: GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); ctx.getEnvironment().setActiveProfiles( "dev" ); ctx.load( "classpath:/org/boom/bang/config/xml/*-config.xml" ); ctx.refresh();
{ "language": "en", "url": "https://stackoverflow.com/questions/7602690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Webcal on Android I have a webcal feed with a calendar I would like to add to the user of my app's google calendar. I've tried searching around a lot to see if this is possible but haven't really gotten anywhere. I'm still relatively new to android development so bear with me if I'm missing something very easy! A: To subscribe to the calendar on your Android phone you need to subscribe to the appropriate calendar in the Google Calendar account that is associated with your phone. Once you have subscribed, the calendar should appear on the phone. I hope this is what you were looking for. A: What happens when you change the url from webcal:// to http://? You could build it and use CSS to display http or https when users are using Android. Does it perform an import or subscribe?
{ "language": "en", "url": "https://stackoverflow.com/questions/7602692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: iOS HTML Unicode to NSString? I'm in the process of porting an Android app to iOS and I've hit a small roadblock. I'm pulling HTML encoded data from a webpage but some of the data is presented in Unicode to display foreign characters... so characters in Russian (Лети за мной) will be parsed out as, "&#1051;&#1077;&#1090;..." In android I was able to get around this by calling HTML.fromHTML(). Is there anything similar in iOS? A: It's pretty easy to write your own HTML entity decoder. Just scan the string looking for &, read up to the following ;, then interpret the results. If it's "amp", "lt", "gt", or "quot", replace it with the relevant character. If it starts with #, it's a numeric entity. If the # is followed by an "x", treat the rest as hexadecimal, otherwise as decimal. Read the number, and then insert the character into your string (if you're writing to an NSMutableString you can use [str appendFormat:@"%C", thechar]. NSScanner can make the string scanning pretty easy, especially since it already knows how to read hex numbers. I just whipped up a function that should do this for you. Note, I haven't actually tested this, so you should run it through its paces: - (NSString *)stringByDecodingHTMLEntitiesInString:(NSString *)input { NSMutableString *results = [NSMutableString string]; NSScanner *scanner = [NSScanner scannerWithString:input]; [scanner setCharactersToBeSkipped:nil]; while (![scanner isAtEnd]) { NSString *temp; if ([scanner scanUpToString:@"&" intoString:&temp]) { [results appendString:temp]; } if ([scanner scanString:@"&" intoString:NULL]) { BOOL valid = YES; unsigned c = 0; NSUInteger savedLocation = [scanner scanLocation]; if ([scanner scanString:@"#" intoString:NULL]) { // it's a numeric entity if ([scanner scanString:@"x" intoString:NULL]) { // hexadecimal unsigned int value; if ([scanner scanHexInt:&value]) { c = value; } else { valid = NO; } } else { // decimal int value; if ([scanner scanInt:&value] && value >= 0) { c = value; } else { valid = NO; } } if (![scanner scanString:@";" intoString:NULL]) { // not ;-terminated, bail out and emit the whole entity valid = NO; } } else { if (![scanner scanUpToString:@";" intoString:&temp]) { // &; is not a valid entity valid = NO; } else if (![scanner scanString:@";" intoString:NULL]) { // there was no trailing ; valid = NO; } else if ([temp isEqualToString:@"amp"]) { c = '&'; } else if ([temp isEqualToString:@"quot"]) { c = '"'; } else if ([temp isEqualToString:@"lt"]) { c = '<'; } else if ([temp isEqualToString:@"gt"]) { c = '>'; } else { // unknown entity valid = NO; } } if (!valid) { // we errored, just emit the whole thing raw [results appendString:[input substringWithRange:NSMakeRange(savedLocation, [scanner scanLocation]-savedLocation)]]; } else { [results appendFormat:@"%C", c]; } } } return results; } A: The &#(number); construct in HTML (and XML) is known as a character reference. It's not Unicode-specific, other than in that all characters in HTML are defined in terms of Unicode, whether included verbatim or encoded as a character or entity reference. (Entity references are the named ones that look like &eacute; or &amp; and if you are scraping an HTML page you will certainly have to deal with those as well.) There isn't a function in the standard library for decoding character or entity references. See this question for approaches to decoding HTML text content. If you only have character references and the standard XML entities like &amp; you can get away with leveraging NSXMLParser to parse an <element>+yourstring+</element>, but this won't handle HTML-specific entities like &eacute;. In general, screen-scraping is best done using a proper HTML parser, rather than string-hacking. This will convert all text content into text nodes, converting the character and entity references as it goes. However, again, there is no HTML parser available in the standard library. If the target page is well-formed standalone XHTML you can again use NSXMLParser. Otherwise you might like to try libxml2, which offers an HTML parser as well as XML. See this question for some background. A: if you get data from a website you will have an NS(Mutable)Data-Object as your receiving-buffer. You just have to transform that NSData into an NSString via: NSString *myString = [[NSString alloc] initWithData:myRecvData usingEncoding:NSUnicodeStringEncoding] if your server is sending in Unicode. If your server is sending utf-8 or other then you have to adjust the stringencoding in your receiving-code as well. here a list of all supported string-encoding-types edit: take a look at this so-thread.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SQL - ordering results by parent child i have entries in my table of products and categories with columns id and parent. lets say i have the following 0 ----- 0 ------ home 1 ----- 4 ------ PD1 2 ----- 0 ------ CAT1 3 ----- 2 ------ PD2 4 ----- 2 ------ CAT2 the fist col being the id, second being parent and a title at the end. is there a way (using ORDER or some other method) of returning the results in the following order? 0 ----- 0 ------ home 2 ----- 0 ------ CAT1 3 ----- 2 ------ PD2 4 ----- 2 ------ CAT2 1 ----- 4 ------ PD1 A: Try this: SELECT id, parent, title FROM yourtable ORDER BY parent, id A: try this SELECT * FROM yourtablename ORDER BY parentfieldname A: could it be as simple as ORDER BY ParentID, ID A: Firstly, if you want to order in a custom way (not using PKs or alphabetic on a name field), you need to add a field to define the ordering weight of the various objects. I would add a field to the table called something like ordering_weight - you do not want to use the field name order or sequence b/c they are reserved SQL words. Secondly, you need an order by clause: ORDER BY top_level.ordering_weight, next_level.ordering_weight, ..., deepest_level.ordering_weight Notice that my order by clause orders first by the highest level of my tree, and last by the lowest or deepest level of the tree. Of course, disregard the above if all you are looking fo a dynamic level of recursion. Generally when I see a parent child relationship like this I see people wanting to do more than 1 level of recursion. The problem with your schema is that It doesn't support dynamic levels of recursion as it is. You can only fetch the top level parent's children, every additional level requires another join (there are some clever ways to get past this, but they still require additional SQL per level). I think what might be more useful to you is to look into the Nested Set Model, which allows querying of infinite levels of recursion. see: http://en.wikipedia.org/wiki/Nested_set_model For example the following tree of parent child relationships is extremely difficult using standard joins, but is very easy using a model like nested set. Category A - Category B - - Category D - Category E Category F - Category G - - Category H - - - Category I - - - - Category J
{ "language": "en", "url": "https://stackoverflow.com/questions/7602695", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Testing with MOQ and Session State Wrapper I'm using a Session wrapper as written below. The problem I have is when running tests the try doesn't work and it goes to the catch so session variables are never being set. I'm using Moq to create a mock Session state for my mock context. If I create a variable like: Session["variable"] = "something"; That works fine and persists to the end of the test. Everything created for in my wrapper does not. Since the Session is somehow persisting, my theory is just that I need to figure out where it is and then put it in my catch. I don't know how to go about that though. public class MySession { // private constructor private MySession() { id = new Random().Next(100000); } // Gets the current session. public static MySession Current { get { MySession session = new MySession(); try { session = (MySession)HttpContext.Current.Session["__MySession__"]; } catch { //Catch nothing } if (session == null) { session = new MySession(); HttpContext.Current.Session["__MySession__"] = session; } return session; } } // **** add your session properties here, e.g like this: public int id { get; set; } A: I feel you've got the wrong end of the stick in the way you've created your session wrapper. A session wrapper normally means you create a class which, in production code, passes all calls to the real session. In unit tests, it does not have a real session inside and could be a mock object. Your MySession class always needs a real session, so any test using will not be a true unit test. You might not need to roll your own, there is a HttpSessionStateWrapper in System.Web.Abstractions you could try.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Expected database model is inconsistent in real-time In this question, I was facing an issue where I was writing an update for a deployed application to bring the database up to date with the newer version we are deploying. Basic outline as follows: * *Began with currently deployed version of application *Added new functionality that used existing database *Added new database tables and relationships *Added new functionality that depended on the new databse structure *Testing complete, ready for deployment The issue here is that the currently deployed application has been in use for a few months and has a lot of data that would need to be preserved, so simply replacing the old with the new was not viable (at least not for the database, but of course it works for the code). So I used the following steps to write a script in SQL for the updated version of the application to run the first time it starts up to make the necessary changes to the database without touching existing data (aside from populating the new tables): * *Use VS2010's "Generate database from model" functionality to create a .sql (the model was originally created using the "Generate model from database" functionality) *Remove all parts of the .sql that act on the existing tables, except for those that add FKs between new and old tables *Use the resulting script to build the new database Sounds pretty clean and done, right? Wrong. The mapping from the model to the database was all wrong for the new tables. Long story short, the database that generated the model had tables named in the plural (and the mapping was correct and the application worked), and the database generated by the model created tables in the plural (identical names to what the tables where the DB generated the model, but the model did not map to them). The solution ended up being to change the script to name the tables in the singular, and then everything worked flawlessly. What happened here? The code remained untouched, no changes were made to the model, and the old tables continued to work fine the entire time, yet somewhere in the process of * *Generate script *Delete "new" tables and constraints (those that don't yet exist in the deployed version) *Run script to re-add the tables the mapping decided to be to singularly named tables (User instead of Users, Address instead of Addresses, etc). Can anyone explain to me how/why this would happen this way? A: You might want to look at some of the tools that redgate supply - good tools for comparing two DB structures and generating a script to update. http://www.red-gate.com/?utm_source=google&utm_medium=cpc&utm_content=brand_aware&utm_campaign=redgate&gclid=CIamkumgw6sCFcYPfAodnGVjsQ
{ "language": "en", "url": "https://stackoverflow.com/questions/7602700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the difference between "column1 and(column2 or column3)" or "(column1 andcolumn2) or (column1 and column3) in an sql query run in mysql " I m stuck in a situation where I needed (column1 and column2) or (column1 or column3) from a table. So i implemented it as select * from mytable where column1=x and (column2=y or column3=z) But it fetches me some unneccesory rows and by implementing as select * from mytable where (column1=x and column2=y) or (column1=x and column3=z) It gives the result but i couldn't understand the diff between the two...please suggest EDIT (added details) Below I have explained my situation, Please check this, Let me elaborate my situation ::: I have a table, say clientdetails(int id, var firstname, var mobileno, var landlineno) and I need to fetch those entries fetching values having unique (firstname and mobileno), or (firstname and landlineno). Either of the two mobileno or landlineno is mandatory. so i wrote a query... select id from clientdetails where firstname = 'pooja' and (mobileno = mn or landlineno= ln ) and mobileno REGEXP '^[0-9]+$' and landlineno REGEXP '^[0-9]+$'" Now ln or mn can be anything and say ''. Since there are many instances where the firstname is "pooja" without a landlineno. So it fetches that entries too which has no landlineno but different mobileno.. When I use the following query select id from clientdetails where (firstname = 'pooja' and mobileno = mn) or (firstname = 'pooja' and landlineno= '' ) and mobileno REGEXP '^[0-9]+$' and landlineno REGEXP '^[0-9]+$'" It fetches me the required rows. Please explain me the execution format of these queries A: So as Alnitak pointed out in comments, There shouldn't be any difference - given three boolean variables A, B, C, then A & (B | C) == (A & B) | (A & C) Well, I have tested both queries with simple example below both queries gives same result. create table emp_temp(id smallint(5),fname varchar(10),lname varchar(10)); insert into emp_temp values (1,'jon','kam'),(2,'ish','dalviv'),(3,'ctn','gado'), (4,'jin','jain'),(5,'niraj','yadav'); select * from emp_temp; mysql> select * from emp_temp; +------+-------+--------+ | id | fname | lname | +------+-------+--------+ | 1 | jon | kam | | 2 | ish | dalviv | | 3 | ctn | gado | | 4 | jin | jain | | 5 | niraj | yadav | +------+-------+--------+ 5 rows in set (0.00 sec) Now comparing your two queries. select * from mytable where column1=x and (column2=y or column3=z) select * from mytable where (column1=x and column2=y) or (column1=x and column3=z) Consider column1 is id column2 is fname column3 is lname mysql> select * from emp_temp -> where id=1 and (fname='jon' or lname='yadav'); +------+-------+-------+ | id | fname | lname | +------+-------+-------+ | 1 | jon | kam | +------+-------+-------+ 1 row in set (0.01 sec) mysql> select * from emp_temp -> where (id=1 and fname='jon') or ( id=1 and lname='yadav'); +------+-------+-------+ | id | fname | lname | +------+-------+-------+ | 1 | jon | kam | +------+-------+-------+ 1 row in set (0.01 sec) Both queries produces the same result. A: Are any of the columns NULL? true AND unknown => false true OR unknown => true etc. I did not see if all combinations of NULL would cause the two expressions to differ, but it seems a possible culprit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: EJB application shutdown hook How would i add a shutdown hook (just like the JVM Shutdown Hook) to listen (get notification) when an EJB application is deployed/undeployed (to stop the JMX MServerBean)? I could use a ServletContextListener, unfortunately this an EJB jar. A: Use @Singleton bean and implement @PreDestroy: @Startup @Singleton public class HookBean { @PreDestroy void wholeApplicationShuttingDown { } } UPDATE: Just noticed ejb-3.0 tag. @Singleton was added in 3.1. But still maybe you will find it useful. A: Use a Stateless Bean with a @PreDestroy method
{ "language": "en", "url": "https://stackoverflow.com/questions/7602706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: cellForRowAtIndexPath inserting in array I'm getting a weird issue. I have a custom UITableViewCell and each cell has a UIButton and UITextField. When the button is clicked, it changes the textfield value to some constant. Now in the cellForRowAtIndexPath method I have this: folderTitleTextView.tag=indexPath.row; [arrayOfTextFields insertObject:folderTitleTextView atIndex:indexPath.row]; NSLog(@"indexpath.row:%i", indexPath.row); NSLog(@"text fields count %i", [arrayOfTextFields count]); So if I have two cells, then every time I reload the table, it adds two more objects to the arrayofTextFields, even though it should replace the existing ones. So if I have two cells and I reload the table 3 times, then for some reason arrayOfTextFields count is 8. A: This folderTitleTextView.tag=indexPath.row; is not a good idea because everything starts with a tag of 0, so when accessing views with viewWithTag:0 or when setting up the row 0, you will get weird results. I would suggest also checking the number of items in arrayOfTextFields and use [arrayOfTextFields replaceObjectAtIndex:indexPath.row withObject:folderTitleTextView]; or [arrayOfTextFields insertObject:folderTitleTextView atIndex:indexPath.row]; depending on the current count for arrayOfTextFields Try this: folderTitleTextView.tag = (indexPath.row + 100); if ([arrayOfTextFields count] <= indexPath.row) { [arrayOfTextFields insertObject:folderTitleTextView atIndex:indexPath.row]; } else { [arrayOfTextFields replaceObjectAtIndex:indexPath.row withObject:folderTitleTextView]; } NSLog(@"indexpath.row:%i", indexPath.row); NSLog(@"text fields count %i", [arrayOfTextFields count]); A: The question is what are you trying to do? Right now you add the textView to an array each time a cell is displayed. If you have 1 cell you have 1 textView in the array because cellForRowAtIndexPath: was called 1 time. If you add another cell so you have 2 total cell cellForRowAtIndexPath will be called another 2 times and it will add 2 textViews to the array that already has one -> 3 If you add another cell cellForRowAtIndexPath adds 3 more textViews to the 3 that are already there -> 6 So much for the explanation of your results. My suggestion is to get rid of that array and get rid of the tag, most likely those are not needed at all. you can access the cell with something like this: - (IBAction)buttonPressed:(UIButton *)sender { UIView *contentView = [sender superview]; UITableViewCell *cell = (UITableViewCell *)[contentView superview]; // you should assign a tag to the textField of your cell. Use the same tag for each textView in all cells. UITextField *textField = (UITextField *)[cell viewWithTag:42]; textField.text = @"Foo"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7602709", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unity: register instance at runtime I can't seem to figure out this one. I have a component which depends on a service. The service has a URL which is only known at runtime. How can I get a Component instance using the container? public interface IService { Uri Url { get; set; } } public class Service : IService { public Uri Url { get; set; } } public class Component : IComponent { public Component(IService service) {... } } I can only think of using Unity as Service Locator to get the container on demand and register my runtime instance: var service = new Service { Url = new Uri("http://...") }; Container.Resolve<IUnityContainer>().RegisterInstance<IService>(service); var component = Container.Resolve<IComponent>(); But I really want to avoid SL. Is there another way?
{ "language": "en", "url": "https://stackoverflow.com/questions/7602710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I keep loosing my events, how can I keep them attached I have a small 'screen' that pops up over part of my page. This screen has two buttons on it. When either of these buttons get pressed the screen is removed. But the screen could need to be reused at a later time so instead of always rebuilding the screen i store it in data of an object on the page. While the stored screen reloads fine, all of the events seem to be missing as the second time the screen appears the buttons dont do n e thing. How can i fix this? function AddScreen() { var store= $('#store'), screen; if(objectStoringScreen.length > 0){ screen = objectStoringScreen.data('screen'); }else { store = CreateStore(); //Create Store $(this).parent().append(store); //Add Store screen = Screen(); // Create Screen } PushScreen(screen); //Load selected screen function Screen() { //build div // build two buttons and place them in the div // btn1.click(onOK); btn2.click(onCancel); } function onOK() { store.data('screen',screen); PopScreen(); } function onCancel() { PopScreen(); } } A: I would just create the screen beforehand and toggle it when needed. <div id="screen"> Screen Div <input type="button" value="OK" /> <input type="button" value="Cancel" /> </div> <div id="showScreen">click here to show the screen</div> $(document).ready(function () { // Screen already exists, just hide it. If you need to build it from data on the page, do it after it's hidden. $('#screen').hide(); // Some action that shows/hides your screen, I just used a click method as an example $('#showScreen').click(function () { if ($('#screen').css('display') == 'none') { // Or you can build here if you need it to be updated in real time for whatever reason // ex. $('#screen').append('<input type="button" id="someSpecialButton" value="Special Button" />'); $('#screen').show(); } else { $('#screen').hide(); } }); // Screen button events, will still exist after hiding the screen $('#screen input[type="button"]').click(function () { alert('You clicked ' + $(this).attr('value') + ' on the screen'); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7602711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: web.py not importing MySQLdb I'm working with web.py and for some reason I am getting the following error: [Thu Sep 29 13:47:20 2011] [error] [client 64.8.210.120] File "/usr/lib/python2.6/site-packages/web.py-0.36-py2.6.egg/web/db.py", line 975, in __init__ [Thu Sep 29 13:47:20 2011] [error] [client 64.8.210.120] import MySQLdb as db [Thu Sep 29 13:47:20 2011] [error] [client 64.8.210.120] ImportError: No module named MySQLdb Here is my sys.path, in case that's the culprit? I see the.egg, though, so I don't know. Thoughts? ['', '/usr/lib/python2.6/site-packages/Bravo-1.7.2-py2.6.egg', '/usr/lib/python2.6/site-packages/Twisted-11.0.0-py2.6-linux-i686.egg', '/usr/lib/python2.6/site-packages/construct-2.04-py2.6.egg', '/usr/lib/python2.6/site-packages/zope.interface-3.7.0-py2.6-linux-i686.egg', '/usr/lib/python2.6/site-packages/web.py-0.36-py2.6.egg', '/usr/lib/python2.6/site-packages/MySQL_python-1.2.3-py2.6-linux-i686.egg', '/usr/lib/python2.6/site-packages/setuptools-0.6c12dev_r88846-py2.6.egg', '/usr/lib/python26.zip', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/site-packages', '/usr/lib/python2.6/site-packages/PIL'] Here are the contents of the 2.6 site-packages directory: [root@xxxx ~]# locate *.egg /root/MySQL-python-1.2.3/dist/MySQL_python-1.2.3-py2.6-linux-i686.egg /usr/lib/python2.4/site-packages/errorhandler-1.1.1-py2.4.egg /usr/lib/python2.4/site-packages/setuptools-0.6c11-py2.4.egg /usr/lib/python2.4/site-packages/xlrd-0.7.1-py2.4.egg /usr/lib/python2.4/site-packages/xlutils-1.4.1-py2.4.egg /usr/lib/python2.4/site-packages/xlutils-1.4.1-py2.5.egg /usr/lib/python2.4/site-packages/xlwt-0.7.2-py2.4.egg /usr/lib/python2.6/site-packages/Bravo-1.7.2-py2.6.egg /usr/lib/python2.6/site-packages/MySQL_python-1.2.3-py2.6-linux-i686.egg /usr/lib/python2.6/site-packages/Twisted-11.0.0-py2.6-linux-i686.egg /usr/lib/python2.6/site-packages/construct-2.04-py2.6.egg /usr/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg /usr/lib/python2.6/site-packages/setuptools-0.6c12dev_r88846-py2.6.egg /usr/lib/python2.6/site-packages/web.py-0.36-py2.6.egg /usr/lib/python2.6/site-packages/zope.interface-3.7.0-py2.6-linux-i686.egg If I open python (either 2.4 or 2.6), I am able to import MySQLdb with no problem. Thanks, Tom A: At the bottom of your bashrc (usually in /etc/bashrc) file put this (or just update the PYTHONPATH env variable to include /usr/lib/python2.6/site-packages): if [ $PYTHONPATH ] then export PYTHONPATH=$PYTHONPATH:/usr/lib/python2.6/:/usr/lib/python2.6/site-packages/ else export PYTHONPATH=/usr/lib/python2.6/:/usr/lib/python2.6/site-packages/ fi Or, for the specific user that is running the script, put the above in /home/[USER_RUNNING_SCRIPT]/.bashrc. Then source the file: $ source ~/.bashrc # or # source /etc/bashrc A: You can download mysqldb at : http://sourceforge.net/projects/mysql-python/ A: Try writing a simple page to show the sys.path as it exists from within the web server execution environment. Not sure if that's what you're showing when you show your sys.path in your question or if you ran that interactively from your login. Chances are the userid that the http server is running under has a different environment set up from what you have as a regular user.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 3 checkboxes showing same div (display:none) I don't know much about coding and I need to build this form with 3 different areas/divs (A,B,C), where: A - always shown, controls B and C display B - Shown if checkboxes 1,2 and/or 3 on A are selected C - shown if checkbox 4 on A is selected So, what I've reached so far was: <head> <script type="text/javascript"> <!-- function showMe (it, box) { var vis = (box.checked) ? "block" : "none"; document.getElementById(it).style.display = vis; } //--> </script> </head> <body> <form> <input type="checkbox" value="value1" onclick="showMe('div1', this)" />value1 <input type="checkbox" value="value2" onclick="showMe('div1', this)" />value2 <input type="checkbox" value="value3" onclick="showMe('div1', this)" />value3 <input type="checkbox" value="value4" onclick="showMe('div2', this)" />value3 </form> <div id="div1" style="display:none;">Show Div 1</div> <div id="div2" style="display:none;">Show Div 2</div> </body> The thing is, if I check 1,2 and/or 3, Div B shows properly, but if I uncheck one of them, div B hides. I need div B to show whenever one of them is checked. Assigning a different div to each checkbox won't work since all the checkboxes "activate" the same form area (div). Any sugestions? A: Right now, your event handler only takes into consideration the checkbox that caused the event. What it really needs to do is to poll each of the three checkboxes to see if any of them are checked at the time of the event. So it makes sense for the logic to be maintained in your event handler: <head> <script type="text/javascript"> <!-- function updateVis () { var show1 = (document.theForm.input1.checked) || (document.theForm.input2.checked) || (document.theForm.input3.checked) ? "block" : "none"; document.getElementById("div1").style.display = show1; var show2 = (document.theForm.input4.checked) ? "block" : "none"; document.getElementById("div2").style.display = show2; } //--> </script> </head> <body> <form name="theForm"> <input name="input1" type="checkbox" value="value1" onclick="updateVis()" />value1 <input name="input2" type="checkbox" value="value2" onclick="updateVis()" />value2 <input name="input3" type="checkbox" value="value3" onclick="updateVis()" />value3 <input name="input4" type="checkbox" value="value4" onclick="updateVis()" />value3 </form> <div id="div1" style="display:none;">Show Div 1</div> <div id="div2" style="display:none;">Show Div 2</div> </body>
{ "language": "en", "url": "https://stackoverflow.com/questions/7602714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: InDesign Scripting how to quit application (not document) I'm trying to automate data merge process. Here's what I have: First of all have created a working datamerge script: function main(){ mySnippet (); myTeardown(); } //<setup> //<snippet> function mySnippet(){ // automate datamerge var myDocument = app.open(File("P:/RxCut/In Design Implementation/build/automate/automate.indd")); var myDataSource = File("P:/RxCut/In Design Implementation/build/automate/automate.txt"); myDocument.dataMergeProperties.selectDataSource(myDataSource); myDocument.dataMergeProperties.mergeRecords(); myDocument=myDocument.save("P:/RxCut/In Design Implementation/build/automate/AutomatedMerged.indd"); app.activeDocument.save(new File("P:/RxCut/In Design Implementation/build/automate/AutomatedMerged2.indd")); myDocument.close(); } //</snippet> //<teardown> function myTeardown(){ } This runs great as expected! Then had to write a vbscript to open InDesign and run that jsx script above: Set myInDesign = CreateObject("InDesign.Application.CS5") Msgbox("This message from Vbscript") myJavaScript = "C:\test2.jsx" myInDesign.DoScript myJavaScript, 1246973031 Now if CreateObject("InDesign.Application.CS5") opens InDesign how to close it? A: app.quit(); easy as that app.open to open app.quit to quit
{ "language": "en", "url": "https://stackoverflow.com/questions/7602718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WCF error: "The service cannot cache the negotiation state as the capacity '128' has been reached" I'm trying to find out why one of my WCF services sometimes randomly makes the lsass process take 100% of the CPU. I was looking through the WCF trace logs and found this error many times: <ExceptionString>System.ServiceModel.QuotaExceededException: The service cannot cache the negotiation state as the capacity '128' has been reached. Retry the request.</ExceptionString> The WCF service is hosted in IIS6. I've searched online but can't find what this actually means, or where I can set the capacity, or what might be causing the cache to get full. Any ideas?
{ "language": "en", "url": "https://stackoverflow.com/questions/7602720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C++ Bytes To Bits Conversion And Then Print Code Taken From: Bytes to Binary in C Credit: BSchlinker The following code I modified to take more than 1 Byte at a time. I modified it, and got it half working and then got really confused on my loops. :( Ive spent the last day and a half trying to figure it out... but my C++ skills are not really that good (still learning!) #include <iostream> using namespace std; char show_binary(unsigned char u, unsigned char *result,int len); int main() { unsigned char p40[3] = {0x40, 0x00, 0x0a}; unsigned char bits[8*(sizeof(p40))]; int c; c=sizeof(p40); show_binary(*p40, bits, 3); cout << "\n\n"; cout << "BIN = "; do{ for (int i = 0; i < 8; i++) printf("%d",bits[i+(8*c)]); c++; }while(c < 3); cout << "\n"; int a; cin >> a; return 0; } char show_binary(unsigned char u, unsigned char *result, int len) { unsigned char mask = 1; unsigned char bits[8*sizeof(result)]; int a,b,c; a=0; b=0; c=len; do{ for (int i = 0; i < 8; i++) bits[i+(8*a)] = (u[&a] & (mask << i)) != 0; a++; }while(a < len); //Need to reverse it? do{ for (int i = 8; i != -1; i--) result[i+(8*c)] = bits[i+(8*c)]; b++; c--; }while(b < len); return *result; } After I spit out: cout << "BIN = "; do{ for (int i = 0; i < 8; i++) printf("%d",bits[i+(8*c)]); c++; }while(c < 3); Id like to take bit[11] ~ bit[the end] and compute a BYTE every 8 bits. If that makes sense. But first the function should work. Any pro tips on how this should be done? And of course, rip my code apart. I like to learn. A: Man, there is a lot going on in this code, so it's hard to know where to start. Suffice to say, you're trying a bit too hard. It sounds like you are trying to 1) pass in a byte array; 2) turn those bytes into a string representation of the binary; and 3) turn that string representation back into a value? It just so happens I recently did something similar to this in C, which should still work using a C++ compiler. #include <stdio.h> #include <string.h> /* A macro to get a substring */ #define substr(dest, src, dest_size, startPos, strLen) snprintf(dest, dest_size, "%.*s", strLen, src+startPos) /* Pass in char* array of bytes, get binary representation as string in bitStr */ void str2bs(const char *bytes, size_t len, char *bitStr) { size_t i; char buffer[9] = ""; for(i = 0; i < len; i++) { sprintf(buffer, "%c%c%c%c%c%c%c%c", (bytes[i] & 0x80) ? '1':'0', (bytes[i] & 0x40) ? '1':'0', (bytes[i] & 0x20) ? '1':'0', (bytes[i] & 0x10) ? '1':'0', (bytes[i] & 0x08) ? '1':'0', (bytes[i] & 0x04) ? '1':'0', (bytes[i] & 0x02) ? '1':'0', (bytes[i] & 0x01) ? '1':'0'); strncat(bitStr, buffer, 8); buffer[0] = '\0'; } } To get the string of binary back into a value it can by done with bit shifting: unsigned char bs2uc(char *bitStr) { unsigned char val = 0; int toShift = 0; int i; for(i = strlen(bitStr)-1; i >= 0; i--) { if(bitStr[i] == '1') { val = (1 << toShift) | val; } toShift++; } return val; } Once you had a binary string you could then take substrings of any arbitrary 8 bits (or less, I guess) and turn them back into bytes. char *bitStr; /* Let's pretend this is populated with a valid string */ char byte[9] = ""; substr(byte, bitStr, 9, 4, 8); /* This would create a substring of length 8 starting from index 4 of bitStr */ unsigned char b = bs2uc(byte); I've actually created a whole suite of value -> binary string -> value functions if you'd like to take a look at them. GitHub - binstr
{ "language": "en", "url": "https://stackoverflow.com/questions/7602721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I simulate click event in Stars Rating Widget I am trying to integrate the Stars Rating Widget- http://orkans-tmp.22web.net/star_rating/ (I am using widget from demo 6, after 3) after the stars are get click, the event raised with ui object callback: function (ui, type, value) { var arr = ui.$stars.find("a"); ... //and the html form is: <form id="rat" action="" method="post"> <input type="radio" name="rate" value="1" title="Poor" /> <input type="radio" name="rate" value="2" title="Ahh" /> <input type="radio" name="rate" value="3" title="Good" /> <input type="radio" name="rate" value="4" title="Very Good" /> <input type="radio" name="rate" value="5" title="Superb"/> <input type="submit" value="Rate it!" /> </form> When the user click on the stars, it is working for me, What I am trying to do, is to 'fake' the click behavior, e.g inside my code, to click on the stars, As far as I understand it, I have two options 1)To fake click (I tried it, but it generate post to me, which I don't like) 2)To get the ui object, and call the same logic as the click event Can you help me solve my problem? (I need to simulate the click event, just because I want to improve the usability by selecting the rating by the keyboard..) Thanks. Edit: I tried combination of the following, non of them started the animation.. //$("#rat").stars("select", 5); //$("#rat").click(); //$("#rat:first").trigger("submit"); // document.forms[0].submit(); //jQuery('#rat').rating(); //$('#rat').rating('select', 1); //$('#rat').show(); Edit2: I am able to select the stars with the following code, but not to start the animation $("#rat").stars("select", 0); $("#rat").show(); Edit3 I did work around, but I still don't get the fancy animation function blinkStars(value) { $("#rat").stars("select", value); $("#rat").show(); setTimeout(function () { $("#rat").stars("select", 0); $("#rat").show(); }, 600); } Edit4 - I was asked to give more details about the ajax call, so it look like $(function () { $("#rat").children().not(":radio").hide(); // Create stars $("#rat").stars({ cancelShow: false, callback: function (ui, type, value) { var arr = ui.$stars.find("a"); arr.slowEach(100, function () { $(this).animate({ top: "28px" }, 300) }, function () { $.post("/Home/Vote", { rate: value}, function (data) { //do some work here.. }, "json"); $("#loader").fadeIn(function () { $("#loader").fadeOut(function () { arr.slowEach(100, function () { $(this).animate({ top: 0 }, 300) }); }); }); }); } }); I will be more than glade to make the animation working.. A: <form id="rat" action="" method="post"> <input type="radio" id="rate1" name="rate" value="1" title="Poor" /> <input type="radio" id="rate2" name="rate" value="2" title="Ahh" /> <input type="radio" id="rate3" name="rate" value="3" title="Good" /> <input type="radio" id="rate4" name="rate" value="4" title="Very Good" /> <input type="radio" id="rate5" name="rate" value="5" title="Superb"/> <input type="submit" value="Rate it!" /> </form> <script> $("#rate4").click(); //clicks the 'Very Good' star </script> A: a couple things on the site link u provided: "NOTE: With the newest jQuery (1.6) the rating control doesn't work properly, due to the changes to the attr() handling for the "disabled" attribute. The fix will be included in new release, as soon as jQuery UI team officialy include jQuery 1.6 to download. With that being said, you are now able to download a <> shared by Colin Guthrie, thanks! :) Optionally, you can download a <> right away. " so if you are using after 1.6 you need to make sure to have the patch and use this: $('input[name="rate"][value="3"]').prop("checked",true); $('#rat input[type="submit"]').click(); if you are using before 1.6 use $('input[name="rate"][value="3"]').attr("checked",true); $('#rat input[type="submit"]').click(); A: a few more options to trigger the event you would like: .change() ; .trigger() ; .trigger('click') ; .trigger('change') ; $('#rat').get(0).selectedIndex = 2 ; unfortunatelly i wont be able to test until monday. all yours :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7602722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: connect.facebook.net has been blocked I'm using JavaScript SDK to remove the scrollbars from my iframe application. My company blocks "connect.facebook.net" which hosts the JS SDK. Is there any way to host this javascript on heroku - the cloud platform that Facebook partenerd with? Or is there any way to resize the iframe without having to use the javascript sdk? A: No you won't be able to host this on a separate domain. It needs to be hosted on a Facebook domain/subdomain due to cross-domain restrictions. You should contact your administrators to unblock Facebook connect libraries.
{ "language": "en", "url": "https://stackoverflow.com/questions/7602738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create tooltip at cursor position in text area with jQuery I'm trying to create a tooltip above the input caret in a text area. This would be easy if I could get the x,y coordinates of the caret in the text area, however I've been searching for a little while and cannot figure out how to do that. Say a user is typing in a text area and then presses some key (@ symbol for instance). I'm trying to show a little tooltip above the text area caret. Any ideas? A: Hmmm I do not really see anything in jQuery events that will easily give you an x y coord for the caret. However there are quite a few ways for detecting the caret position in a text field: http://laboratorium.0xab.cd/jquery/fieldselection/0.1.0/test.html Is it possible to programmatically detect the caret position within a <input type=text> element? Caret position in textarea, in characters from the start Using this, you could try to estimate the pixel coordinates for the tool tip. If you want it to be more exact use a monospaced font inside of your text fields. //depending on size of font var charWidth = 10; //using any number of the above methods to get caret position var caretPosition = getCaretPos('#myTextField'); var textFieldOffsetX = $('#myTextField').offset.left; var toopTipPositionX = caretPosition * charWidth + textFieldOffsetX; It is not exact and it is not going to be perfect, but it might be close enough. A: Why does the tooltip have to be at the caret? Why not position it above (or somewhere around) the textarea? Here is a demo of what I mean. $('textarea').keyup(function(e) { switch (e.which) { // @ symbol case 50: makeTooltip(e, 'you typed in an at symbol'); break; } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7602750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }