text
stringlengths
8
267k
meta
dict
Q: Calling an object after an ajax call returns I built the following object: var cls = { offset : 0, onSuccess : function(data) { alert(this.offset); } }; $(document).ready(function(){ $("form").submit(function() { $.post( "/ajax", {}, cls.onSuccess ); }); }); When the ajax returns and onSuccess of cls is called then I get an alert of undefined. If I just call cls.onSuccess() then the alert returns 0 ex expected. Any reason for this behavior? A: don't use "this". it will not refer to what you expect to refer. use window.alert(cls.offset); it's quite long to explain, but this should help you. A: this is not your object, cls, anymore. You are passing a function reference, onSuccess to the post call. A: You need to give the AJAX function a context for the callback. I would use .ajax() instead of .post() and pass cls as the context: $.ajax({ url: "/ajax", context: cls, type: "POST", success: cls.onSuccess }); A: You are passing just the function, independent of the object. If you wrap it in a function it should work: $(document).ready(function(){ $("form").submit(function() { $.post( "/ajax", {}, function(data){ cls.onSuccess(data); } ); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7534221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What causes the "user agent stylesheet" to use "border-box" instead of "content-box" for box-sizing? I'm under the impression that the user agent stylesheet in browsers such as Safari, Chrome and Firefox is something that is internal to the browser and can't be directly modified (rather a style property needs to be overridden). I'm also under the impression due to various websites including Mozilla's that the default value of the box-sizing property for Webkit and Mozilla is "content-box." I tested this on a rather simple dummy page viewed in various browsers. My problem is that on two pages in our production application the default property is different, and we can't figure out why this is. One one page we see a box-sizing property of "border-box" in the Web Inspector or console. It's assigned to the CSS selector input:not([type="image"]), textarea. On the other page there is no mention of the box-sizing property in the Web Inspector or console. Does anyone know if there's some way to directly affect the box-sizing definition in the user agent stylesheet for a particular page? Maybe there's a library that does this? We're using prototype.js and swfobject.js in the application... UPDATE: In case I wasn't clear on almost every page in my web application and in every "dummy" page I've tested on the box-sizing property has the default "content-box" value. For some reason one particular page in my web application shows in the web inspector that the user agent stylesheet (the one used by the browser for its defaults) has set that property to "border-box." I can't for the life of me figure out why this is. I'm looking for anything that might cause Firefox to change what its default value for that property is. A: I had the same issue on chrome which by default added the following user agent style rule: input:not([type="image"]), textarea { box-sizing: border-box; } After adding the doctype property <!DOCTYPE html> the rule no longer appeared. A: Just had this same issue. What was happening in my case was that someone had put a snippet of Javascript code above the <!doctype html>. As a result, when I inspected DOM through firebug, it appeared that the document didn't have a doctype. When I removed the snippet of JS code such that the doctype declaration was at the very top of the file, the doctype reappeared and fixed the box-sizing problems I was seeing (the same one you had). See: Hope this helps. A: No, you can't touch the browser default stylesheet, and yes, browsers do have different rules for box-sizing specifically in respect to form fields. This is for compatibility with old browsers that used to implement form fields entirely with native OS widgets that CSS couldn't style (and so which didn't have ‘border’ or ‘padding’ as such). Why not just put your box-sizing/-moz-box-sizing/-webkit-box-sizing rule in the site stylesheet? Works for me, I often use this to make inputs with set widths line up across modern browsers. (IE 6–7 don't support it, though, so need some extra help.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7534222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: Converting from sign-magnitude to two's complement For this assignment I can only use basic bitwise operators and no control structures, so I've come up with this code so far to convert sign-magnitude to two's complement. int sm2tc(int x) { // Invert and add 1 // Problem: sm has 2 zeros.. 1000...000 & 0000...000 int tmin = 1 << 31; int mask = x >> 31; // Determine sign of x int mask2 = ~tmin; // Negate tmin to get 0111111... int first = (x ^ mask) + (~mask + 1) ; int second = first & mask2; // Turns of MSB return second; } Where have I gone wrong? A: So, what you really want to compute is result = (x & sign_bit) ? -(x & ~sign_bit) : x; But of course you're not allowed control structures. The first step is to rewrite -(x & ~sign_bit) using just the + and ^ operators: (-1 ^ (x & ~sign_bit)) - -1. Now note that if (x & sign_bit) is zero then (0 ^ (x & ~sign_bit)) - 0 is equal to x. We now have result = (x & sign_bit) ? (-1 ^ (x & ~sign_bit)) - -1 : (0 ^ (x & ~sign_bit)) - 0 You then just need to replace the -1 and 0 with functions of x that generate those values depending on the sign bit, and lo and behold both sides of the condition become the same expression and the condition becomes unnecessary.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Converting some Excel formula to C# I'm trying to convert some Excel formulas into C# code, and I'm kind of lost... I have the following: SUMPRODUCT(1*(RIGHT(A1)={"a","e","i","n","y"})) What exactly does that mean? Here is what I know: * *RIGHT(A1) returns the last character of the text in A1. *SUMPRODUCT({1,2,3}, {4,5,6}) returns 1*4 + 2*5 + 3*6 (something like a scalar product, right?) but here is what I don't understand: If the text is Claude, for example... RIGHT(A1)={"e","a","b","c","d"} returns TRUE and RIGHT(A1)={"a","b","e","c","d"} returns FALSE I only changed the index position of the e character. What is happening there? What I'm not understanding? A: Basically the formula is checking if the last character in cell A1 is any of the following characters: a, e, i, n, or y. The SUMPRODUCT part is important because it is a hack to check the entire array at once against the last character. When you strip that part out and just use RIGHT(A1)={"a","b","e","c","d"}, Excel actually only looks at the first entry in the array, checks to see if it's a match, and returns immediately. So when 'e' is in the first position, you get True. SUMPRODUCT allows the checking to be applied across the entire array. Another way to see this would be to manually type it out into separate cells in a grid fashion like this A | B | C | D 1 | Claude | =RIGHT(A1,1) | 'a' | =1*(B1=C1) 2 | | =RIGHT(A1,1) | 'e' | =1*(B2=C2) 3 | | =RIGHT(A1,1) | 'i' | =1*(B3=C3) 4 | | =RIGHT(A1,1) | 'n' | =1*(B4=C4) 5 | | =RIGHT(A1,1) | 'y' | =1*(B5=C5) 6 | | | | =SUM(D1:D5) The bottom right cell would contain a 1 if any of the characters a,e,i,n,y are at the end of the value in A1, or a 0 if not. I am manually performing the same logic as SUMPRODUCT to get to the same result. So, how this would be accomplished in C#.Net: var checkValue = "Claude"; var letters = {"a", "e", "i", "n", "y"}; var found = 0; foreach (var theLetter in letters) if (checkValue.EndsWith(theLetter)) found = 1; return found; // returns same value as Excel function A: If you want one line based on @CoryLarson's suggestion that will work for any set of letters: Func<string, string[], int> LetterCount = (x, y) => y.Contains(x.Substring(x.Length-1, 1)) ? 1 : 0;
{ "language": "en", "url": "https://stackoverflow.com/questions/7534235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: tag is not displayed if Empty The tag of the following PHP echo statement is not displayed by the browser if it is empty. Found this on IE9. echo ' <div id="'.$url['ID'].'" class="link"> ' .'<img class="link_handle" src="http://www.google.com/s2/favicons?domain='.$urlico.'" align="middle" />' .'&nbsp;' .'<a href="'.$url->URL.'" target="_blank" onmouseOver="preview_link(\'show\', this, \''.$node['ID'].'\');" onmouseOut="preview_link(\'hide\', this, \''.$node['ID'].'\');" >'.$url->TITLE.'</a> ' .'<a href="#" title="Edit" class="link_button_edit" onClick=""> </a>' .'<a href="#" title="Delete" class="link_button_delete" onClick="delete_link(\''.$url['ID'].'\');"> </a> ' .'</div>'; the last two tags are for images. They are ignored unless I have text in <a> </a>. Why does this happen. The images are defined in these CSS styles. .link .link_button_edit { background: url("/icodeact/Edit16.png") no-repeat; background-size: 50%; cursor: pointer; vertical-align: bottom; } .link .link_button_delete { background: url("/icodeact/Delete16.png") no-repeat; background-size: 50%; cursor: pointer; vertical-align: bottom; } Why does this happen? A: The <a> tag has a "display" value of "inline" by default, so if it has no content, it should not show anything. If you want it to show the image for the background, you should make it a block and give it dimensions (width and height). That should solve your problem... A: The easiest way to accomplish setting an empty <a> tag is to wrap it in a container of the width and height of the link you want it to be and give it a position:relative; then you can set the <a> tag properties to width:100%; height : 100%; display:block; and it should end up as the same size as it's parent.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Why is F# generic type inference different on constructors? This case (simplified to the point that it doesn't make much sense) is handled correctly by the F#'s type system: type HumanBeing() = class end type Animal() = class end type CreatureController() = member this.Register creature = creature type CreatureFactory() = let anAnimal = new Animal() let aHuman = new HumanBeing() member this.GiveMeAnAnimal = (new CreatureController()).Register anAnimal member this.GiveMeAHuman = (new CreatureController()).Register aHuman The type of CreatureController.Register is correctly inferred: 'a -> 'a, thus it can be called with the two different arguments. Now the following version has a slight difference: instead of passing creature as argument to CreatureController.Register, it is passed to its constructor. type HumanBeing() = class end type Animal() = class end type CreatureController(creature) = member this.Register = creature type CreatureFactory() = let anAnimal = new Animal() let aHuman = new HumanBeing() member this.GiveMeAnAnimal = (new CreatureController(anAnimal)).Register member this.GiveMeAHuman = (new CreatureController(aHuman)).Register This second example does not compile because Register is inferred as Animal, so you cannot call new CreatureController(aHuman). (Note: in this simplified case the Factory is obviously flawed because it always return the same animal/humanBeing, but this behavior does not change if you replace anAnimal/aHuman with functions.) Why isn't CreatureControlled created as generic in the second case? Is this a compiler limitation? Am I missing something very basic (still learning...)? A: In the first case, as you stated, Register is inferred to be generic, so it works. In the second case, you're passing two different types to the constructor of a non-generic class. A concrete type must be inferred in this case. If you add type args to creature controller, it works: type HumanBeing() = class end type Animal() = class end type CreatureController<'T>(creature:'T) = member this.Register = creature type CreatureFactory() = let anAnimal = new Animal() let aHuman = new HumanBeing() member this.GiveMeAnAnimal = (new CreatureController<_>(anAnimal)).Register member this.GiveMeAHuman = (new CreatureController<_>(aHuman)).Register The difference is type parameters must be explicit on types, but not on functions. Also, constructors may only deal with type parameters declared by the type itself. A: In the constructor case, it is likely (or at least ambiguous) that you meant for the type itself to be generic, e.g. type CreatureController<'T>(creature:'T) = ... and in F#, generic arguments on type definitions must always be explicitly specified.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why do I get an undefined index for signed_request in my facebook app? I am attempting a test app to learn on facebook. I am using this code from the facebook developer page: <?php $app_id = "YOUR_APP_ID"; $canvas_page = "YOUR_CANVAS_PAGE_URL"; $auth_url = "http://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" . urlencode($canvas_page); $signed_request = $_REQUEST["signed_request"]; list($encoded_sig, $payload) = explode('.', $signed_request, 2); $data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true); if (empty($data["user_id"])) { echo("<script> top.location.href='" . $auth_url . "'</script>"); } else { echo ("Welcome User: " . $data["user_id"]); } ?> When I run this I get: Message: Undefined index: signed_request I am using this in Codeigniter. I have no idea if that matters.. When I run this it uses the $auth_url and return: http://mydomain.com/responsepage?code=biglongstring so I know I am getting to facebook and getting something... In that string url returned is a variable named "code." I tried to change the $_REQUEST object to look for "code" but it gives the same error. It does redirect me back to my response page after it briefly displays the error because the "user_id" element is empty. It is empty because signed_request is not present in the url sent back. What am I doing wrong? It should go to facebook, ask for me to allow the app, display the user_id. For some reason the signed_request just isn't there. Thank you. EDIT: I'm looking at this again. Where does it ever actually go out and use that URL? EDIT: If I use the $auth_url manually, pasting it in the address of the browser it redirects back to my response page with no problem. Of course, I did not see a variable named signed_request, just "code" so I don't know what's going on. A: Okay it seems that you are using your Canvas URL in the $canvas_page variable which is wrong. You need to use the Canvas Page which is something like: http://apps.facebook.com/appnamespace This way, your app will open inside the iframe and Facebook will be able to send you the signed_request A: Make sure that you have "signed_request for Canvas" enabled in settings->advanced->migrations Then you should get the signed_request via $_POST.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Validation Ignored with PostBackUrl or Response.Redirect Using C# I have a form with some custom validation. There is a button on the form that should take the user to a 'confirm page' to show all the details of an order. On-Page Validation <asp:TextBox ID="txtBillingLastName" Name="txtBillingLastName" runat="server" CssClass="txtbxln required"></asp:TextBox> <asp:CustomValidator ID="CustomValidatorBillLN" runat="server" ControlToValidate="txtBillingLastName" OnServerValidate="CustomValidatorBillLN_ServerValidate" ValidateEmptyText="True"> </asp:CustomValidator> Validator code behind protected void CustomValidatorBillLN_ServerValidate(object sender, ServerValidateEventArgs args) { args.IsValid = isValid(txtBillingLastName); } However, if I add PostBackUrl or Response.Redirect to the button onclick method, all the validation controls are ignored. I could call all the validation methods with the onclick method, but that seems a less than an elegant solution. I've tried setting CausesValidation=False with no luck. Any suggestions? A: Of course that validation IS ignored if you redirect unconditionally. You should call this.IsValid before you redirect like protected btRedirect_Click( object sender, EventArgs e ) { if ( this.IsValid ) Response.Redirect( ... ); } A: Check this code void ValidateBtn_OnClick(object sender, EventArgs e) { // Display whether the page passed validation. if (Page.IsValid) { Message.Text = "Page is valid."; } else { Message.Text = "Page is not valid!"; } } void ServerValidation(object source, ServerValidateEventArgs args) { try { // Test whether the value entered into the text box is even. int i = int.Parse(args.Value); args.IsValid = ((i%2) == 0); } catch(Exception ex) { args.IsValid = false; } } And Html side code <form id="Form1" runat="server"> <h3>CustomValidator ServerValidate Example</h3> <asp:Label id="Message" Text="Enter an even number:" Font-Name="Verdana" Font-Size="10pt" runat="server"/> <p> <asp:TextBox id="Text1" runat="server" /> &nbsp;&nbsp; <asp:CustomValidator id="CustomValidator1" ControlToValidate="Text1" ClientValidationFunction="ClientValidate" OnServerValidate="ServerValidation" Display="Static" ErrorMessage="Not an even number!" ForeColor="green" Font-Name="verdana" Font-Size="10pt" runat="server"/> <p> <asp:Button id="Button1" Text="Validate" OnClick="ValidateBtn_OnClick" runat="server"/> For further information check Custom validator Hope my answer help you to solve your problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is a pythonic webserver equivalent to IIS and ASP? For very simple, internal web-apps using ASP I was able to just switch IIS 'on' and then write some ASP scripts in the www directory that would start working immediately. Is there an equivalent webserver app for Python scripts that I can run that will automatically start serving dynamic pages (python scripts) in a certain folder (with virtually no configuration)? Solutions I've already found are either too limited (e.g. SimpleHTTPRequestHandler doesn't serve dynamic content) or require configuring the script that does the serving. A: There's always CGI. Add a script mapping of .py to "C:\Python27\python.exe" -u "%s" then drop .py files in a folder and IIS will execute them. I'd not generally recommend it for real work—in the longer term you would definitely want to write apps to WSGI, and then deploy them through any number of interfaces including CGI—but it can be handy for quick prototyping. A: For development or just to play around, here's an example using the standard Python library that I have used to help friend who wanted to get a basic CGI server up and running. It will serve python scripts from cgi-bin and files from the root folder. I'm not near a Windows computer at the moment to make sure that this still works. This also assumes Python2.x. Python 3.x has this, it's just not named the same. * *Make a directory on your harddrive with a cgi-bin folder in it (Ex. "C:\server\cgi-bin") *In a command window, navigate to "C:\server" directory *Type the following assuming you've installed python 2.7 in C:\Python27: "c:\python27\python.exe -m CGIHTTPServer" You should get a message like "Serving HTTP on 0.0.0.0 port 8000" Linux is the same - "python -m CGIHTTPServer" in a directory with a cgi-bin/ in it. A: WSGI setups are fairly easy to get started, but in no anyway turn key. django MVC has a simple built in development server if you plan on using a more comprehensive framework. A: My limited experience with Python web frameworks has taught me that most go to one extreme or the other: Django on one end is a full-stack MVC framework, that will do pretty much everything for you. On the other end, there are Flask, web.py, CherryPy, etc., which do much less, but stay out of your way. CherryPy, for example, not only comes with no ORM, and doesn't require MVC, but it doesn't even have a templating engine. So unless you use it with something like Cheetah, you can't write what would look like .asp at all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Match an item to a list of items Let's say I want to group States into Regions. For instance, the Southwest Region might be: Texas, Oklahoma, Colorado, New Mexico, Utah, Arizona, Nevada. Somehow I need to create the list of states and define the region groupings. I also need to be able to lookup a region given the name of a state, something like region_for('Texas') which would return 'Southwest'. What is the best, cleanest, "Ruby Way" to do something like this? I'd like to do it using plain 'ol ruby, no database or frameworks. A: The 'pure' ruby way is just to use hashes, and then have keys to do your lookups. There's a gem that kind of does something like this: ruport. It might be worth it to look at the source-code. For the use case you've illustrated, I'd have something like: class RegionMapper #potentially put this in a config file REGIONS = Hash[[['California', 'Southwest'], ...]] def initialize @region_map = REGIONS.inject({}) {|r, e| r[e.second] ||= []; r[e.second] << e.first; r} end def region_for_state(state) REGIONS[state] end def states_for_region(region) @region_map(region) end end The point is, to be efficient, you want to have a hash to do the lookups on each key you want to search by. But you dont' want to expose the data-duplication, so you put it all in a class. If you have multiple values / keys, then you really have a table. If you want to keep constant time lookups, then you build a hash for each column (like the @region_map) A: You can almost type this data structure directly into Ruby... result = { 'Southwest' => %W{Texas Oklahoma Colorado New\ Mexico Utah Arizona Nevada}, 'West' => %W{California Oregon Washington}, }.inject({}) do |m, (k, v)| m[k] = v v.each { |s| m[s] = k } m end This produces a single Hash that has both states and regions as keys identifying each other. The data structure looks something like: {"Colorado" => "Southwest", "New Mexico" => "Southwest", "Oklahoma" => "Southwest", "California" => "West", "Oregon" => "West", "Texas" => "Southwest", "Washington" => "West", "Utah" => "Southwest", "Nevada" => "Southwest", "Arizona" => "Southwest" "Southwest" => ["Texas", "Oklahoma", "Colorado", "New Mexico", "Utah", "Arizona", "Nevada"], "West" => ["California", "Oregon", "Washington"], } Another approach would create a separate hash for states. Then you could get a list of regions or states by using Hash#keys, but you could do that here as well by using Enumerable#select or Enumerable#reject based on the type of the value. A: Try: class State attr_accessor :name, :region def initialize(name, region=nil) @name = name @region = region end end class Region attr_accessor :name, :states def initialize(name, states) @name = name @states = states end def set_state_regions self.states.each {|state| state.region = self.name} end end mo = State.new("missouri") il = State.new("illionois") oh = State.new("ohio") midwest = Region.new("midwest", [mo, il, oh]) midwest.states.each {|state| puts state.name} midwest.set_state_regions I may come back and reflect on this later, I think it violates some OO principles. A: I builded a very similar answer like Caley. Main difference: I stored my data in a yaml-structure. require 'yaml' class Region @@all = {} def self.[](key) @@all[key] end def initialize(name) @name = name @states = [] @@all[@name] = self end def <<(state) @states << state state.region = state end def each_state @states.each{|state| yield state } if block_given? @states end attr_reader :name end class State @@all = {} def self.[](key) @@all[key] end def initialize(name, region = nil) @name = name @region = region @@all[@name] = self end attr_accessor :name attr_accessor :region end YAML.load(DATA).each{|region,states| r = Region.new(region) states.each{|state| r << State.new(state) } } p Region['Southwest Region'] p Region['Southwest Region'].each_state Region['Southwest Region'].each_state{|state| p state.name } __END__ Southwest Region: - Texas - Oklahoma - Colorado - New Mexico - Utah - Arizona - Nevada. Pacific: - California - Oregon - Washington A: A Hash is fine, you don't need anything fancier for this. region = { "Maine" => "New England", "New Hampshire" => "New England", etc } Which you then use like region["Maine"] Or if you want to set it up more compactly, like this: regions = { "Southwest" => ["Texas", "Oklahoma", "Colorado", "New Mexico", "Utah", "Arizona", "Nevada"], "New England" => ["Maine", "New Hampshire", "Vermont", "Massachusetts","Rhode Island", "Connecticut"], etc } region = {} regions.each do |r,states| states.each do |state| region[state] = r end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7534246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding a Stored Proc to complex type not showing up in .edmx (thus not mapped)? 1 (mvc3) I have added a stored proc to my model as mapped to a ComplextType. Two Issues: 1) ComplextType.cs exists in class under Model1.tt BUT doesn't show up in .edmx? 2) When I try to create a controller with strongly typed views with that ComplexType.cs it errors stating that it can't be created because ComplextType.cs is not part of the DbContextEntities class? How can I get this complex type added to the .edmx and mapped to my dbcontext (I have done this with tables but not sure what I'm missing for the stored procedures? Thanks! A: For those who just came here from googling,, :)I will give the what is basically has to be done to map a stored procedure into a ADO.Net entity. When mapping the Database to the EDMX file(Entity Model).. the Entity Model automatically map the tables and complex types and ect.. But the stored procedures that are created in the database is not mapped with return complex types. We have to map it in the Function imports by creating our own complex type. This complex type can be accessed in the code. This is done as below: * *Right click on the function Import and add new Function import. *Give your name to the function and specify the stored procedure and then select complex type(If stored procedure returns complex type) or you can select scalar. IF you are selecting the complex type and you can view the columns that are returning and you can create a complex there by create new complex type. *So the return data from the stored procedure will be a set of those complex type. One thing that should be one should access the design or the model view to update the Entity Model. You can not update the Entity Model by just right clicking on the Entity Model. The option of updating the model is provided only on the Model Browser and the Database design diagram. This model browser can be taken from the Other windows of Views in VS2010/VS2012. These information will seems boring. But trust me if you are new to this these seems big at the beginning. Most probably you are going to create this Entity Model from mapping an existing database. Keep in mind that even you map the Entity model form the database you can customize the Entity model by deleting the unnecessary entities(tables) and creating complex types
{ "language": "en", "url": "https://stackoverflow.com/questions/7534248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Translating strings postgres I'm trying to translate 2 types of data using only postgres SQL I've got a column "type" that may contains the kind of data. type is a string column and may have "ACTUAL" or "OLD" values +-type-+ +ACTUAL+ +OLD + +------+ when I show the list with a lot of other joins I would like to show only "A" or "O" values I couldnt find other way to do this than: SELECT replace(replace(mytable.type, 'ACTUAL', 'A'),'OLD', 'O'); With that I can replace the text the way I need, but I was looking for some more function using an array as parameter. something like a cross-reference simple function: translate(['ACTUAL','OLD'], ['A','O']) Does anyone know a way to do this that doesn't use SQL views and neither needs another table like joining the results of this value with other table? Thanks in advance, Andre A: I would use something like CASE... SELECT (CASE type WHEN 'ACTUAL' THEN 'A' WHEN 'OTHER' THEN 'O' ELSE '?' END) FROM Using this method, you can return whatever you want based on whatever criteria you want, not just sub-stringing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Register to the DeviceManager of Linux I read some questions here but couldn't really find the specific problem I'am faced with here... I need to implement a "DeviceCache" in a particular project which caches all device-names found in /proc/net/dev . The Language is C/++ So I thought about a seperate thread looking every X seconds in the directory mentioned above but was encouraged to find a more direct way. How can I register a method of my process to the device manager of linux? Is there a similar way like events/signals? I looked in other sites but couldn't find any helpful code... Im relatively new to Linux-programming but willing to learn new things :) A: Based on your comments, what you really want is to track which network interfaces are operational at any given time. The only true way to determine if a network interface is up is to test it - after all, the router on the other end may be down. You could send pings out periodically, for example. However, if you just want to know if the media goes down (ie, the network cable is unplugged), take a look at these SO questions: * *Linux carrier detection notification *Get notified about network interface change on Linux If you just want to be notified of the actual hardware-level registration of interfaces (eg, when a USB NIC is plugged in), you can use udev events if your platform has udev; otherwise, I believe there's another netlink category for hardware addition/removal events.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Lost connection to MySQL server at 'reading initial communication packet', system error: 110 When i'm trying to connecting to mysql. getting this error. Lost connection to MySQL server at 'reading initial communication packet', system error: 110 A: Error 110 is "connection timed out". If you're trying to connect via TCP sockets, make sure that the MySQL port (3306 by default) is not firewalled off.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Magento Collection Filtering functions What is the difference between addAttributeToFilter() and addFieldToFilter() when dealing with Magento collections? Does it have anything to do with whether or not the value is an eav_attribute? EDIT: According to http://www.magentocommerce.com/wiki/5_-_modules_and_development/catalog/using_collections_in_magento: addFieldToFilter($attribute, $condition=null) -- alias for addAttributeToFilter() Can anybody confirm this? A: Apologies, there's no short answer that doesn't mislead or confuse things here. Important Point #1: The Magento core team is loath to remove or rename methods from the source tree. Startup culture meant they eschewed tests plus being a public project it meant they couldn't control what people did with their product. Rather than remove methods and risk breaking things, they'll leave methods in place that call the new method. This way, even if there's old code out there that calls the method, they're covered. Important Point #2: The collection inheritance chain is screwy, and has been inconsistently applied in certain parts of the codebase. This is being cleaned up, but it can still easily throw you for a loop. Important Point #3: I'm speculating on how a lot of this is meant to be used and happened. I am not the final authority here, I'm just someone trying to make sense of it. The specifics below refer to 1.6, but the concepts apply to all versions All collections inherit from the class Varien_Data_Collection_Db. This is the class that models the basic concept of "collecting a series of objects loaded from the database". This class has a single method addFieldToFilter. public function addFieldToFilter($field, $condition=null) { $field = $this->_getMappedField($field); $this->_select->where($this->_getConditionSql($field, $condition), null, Varien_Db_Select::TYPE_CONDITION); return $this; } which is a simple implementation that adds a where clause to the theoretical query. Next up, there are two abstract classes that have Varien_Data_Collection_Db as an ancestor. Mage_Core_Model_Resource_Db_Collection_Abstract and Mage_Eav_Model_Entity_Collection_Abstract. Mage_Core_Model_Resource_Db_Collection_Abstract is the collection class for "regular, non EAV models". It has neither a addFieldToFilter method or an addAttributeToFilter method. It relies on the implementation in on the base Varien_Data_Collection_Db class. Mage_Eav_Model_Entity_Collection_Abstract is the collection class for EAV models. It has an addAttributeToFilter method, which is more complex. public function addAttributeToFilter($attribute, $condition = null, $joinType = 'inner') { if ($attribute === null) { $this->getSelect(); return $this; } if (is_numeric($attribute)) { $attribute = $this->getEntity()->getAttribute($attribute)->getAttributeCode(); } else if ($attribute instanceof Mage_Eav_Model_Entity_Attribute_Interface) { $attribute = $attribute->getAttributeCode(); } if (is_array($attribute)) { $sqlArr = array(); foreach ($attribute as $condition) { $sqlArr[] = $this->_getAttributeConditionSql($condition['attribute'], $condition, $joinType); } $conditionSql = '('.implode(') OR (', $sqlArr).')'; } else if (is_string($attribute)) { if ($condition === null) { $condition = ''; } $conditionSql = $this->_getAttributeConditionSql($attribute, $condition, $joinType); } if (!empty($conditionSql)) { $this->getSelect()->where($conditionSql, null, Varien_Db_Select::TYPE_CONDITION); } else { Mage::throwException('Invalid attribute identifier for filter ('.get_class($attribute).')'); } return $this; } That's because an attribute query is not a straight "where" query. Also, this method was designed to take either an attribute name, or an attribute database ID, or an instantiated attribute object. You are not adding a field to the filter, you're adding an attribute to the filter. So, depending on the implementation of EAV and which table the attribute is stored in, you need to add a different bit of SQL code (a straight where query on the main table, a where added with one of the join tables, etc.) This creates a problem. Because this EAV collection object inherits from the base collection object, the addFieldToFilter still exists, and would still add a basic where condition to the EAV query, which might confuse an end user by not doing what they thought. Therefore, the EAV collection class also has this public function addFieldToFilter($attribute, $condition = null) { return $this->addAttributeToFilter($attribute, $condition); } which wraps any call to addFieldToFilter to addAttributeToFilter (again, on an EAV model). So, if you have an EAV model, you can use addFieldToFilter or addAttributeToFilter. If you're working with a regular model, you may only call addFieldToFilter, addAttributeToFilter doesn't exist. Ideally, the method names would have been unified from the start, but once the split happened, the Magento team chose to continue supporting the split in favor of backwards compatibility. Wait, There's More There's two collections left in the codebase that inherit directly from Varien_Data_Collection_Db. These are Mage_Sales_Model_Resource_Sale_Collection and Mage_Review_Model_Resource_Review_Summary_Collection. This number is higher in versions of Magento CE prior to 1.6. While this doesn't impact the question of filtering, it does confuse the inheritance chain, so you should watch out for it. Many non-EAV collections will implement their own addFieldToFilter to do sanity checks on variables, or jigger the query paramaters a little if they're doing something a little non standard. The EAV collections get in on this act as well by redefining addAttributeToFilter. Again, this is done to add custom logic that doesn't fit in with the basic Magento collection loading.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: SQL basic full-text search I have not worked much with TSQL or the full-text search feature of SQL Server so bear with me. I have a table nvarchar column (Col) like this: Col ... more columns Row 1: '1' Row 2: '1|2' Row 3: '2|40' I want to do a search to match similar users. So if I have a user that has a Col value of '1' I would expect the search to return the first two rows. If I had a user with a Col value of '1|2' I would expect to get Row 2 returned first and then Row 1. If I try to match users with a Col value of '4' I wouldn't get any results. I thought of doing a 'contains' by splitting the value I am using to query but it wouldn't work since '2|40' contains 4... I looked up the documentation on using the 'FREETEXT' keyword but I don't think that would work for me since I essentially need to break up the Col values into words using the '|' as a break. Thanks, John A: You should not store values like '1|2' in a field to store 2 values. If you have a maximum of 2 values, you should use 2 fields to store them. If you can have 0-many values, you should store them in a new table with a foreign key pointing to the primary key of your table.. If you only have max 2 values in your table. You can find your data like this: DECLARE @s VARCHAR(3) = '1' SELECT * FROM <table> WHERE @s IN( PARSENAME(REPLACE(col, '|', '.'), 1), PARSENAME(REPLACE(col, '|', '.'), 2) --,PARSENAME(REPLACE(col, '|', '.'), 3) -- if col can contain 3 --,PARSENAME(REPLACE(col, '|', '.'), 4) -- or 4 values this can be used ) Parsename can handle max 4 values. If 'col' can contain more than 4 values use this DECLARE @s VARCHAR(3) = '1' SELECT * FROM <table> WHERE '|' + col + '|' like '%|' + @s + '|%' A: Need to mix this in with a case for when there is no | but this returns the left and right hand sides select left('2|10', CHARINDEX('|', '2|10') - 1) select right('2|10', CHARINDEX('|', '2|10'))
{ "language": "en", "url": "https://stackoverflow.com/questions/7534266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: python: method depends on whether param is int or string Is there a more pythonic way to write __getitem__ than the following? The issue is checking type and doing different things depending on the type of the parameter in the call. class This(): def __init__(self, name, value): self.name, self.value = name, value class That(): def __init__(self): self.this_list = [] def add_this(self, this): self.this_list.append(this) def __getitem__(self, x): if isinstance(x, int): return self.this_list[x] # could wrap in try/except for error checking elif isinstance(x, str): for this in self.this_list: if this.name == x: return this return None a = This('a', 1) b = This('b', 2) c = That() c.add_this(a) c.add_this(b) print c[1].name print c['a'].name A: There are quite a few options, but I think there is not one best choice. It depends on your use case and preferences. Just to give you a few hints: Do you really have to store the data in a list? In your example you could use a dictionary and insert the object twice: Once using the integer as key and once using the string as a key. That would make your __getitem__ quite simple. ;-) Another option would be to make your interface more explicit and use byInt/byString methods. You should choose better names of course. If you give more details about what you really want to do, I could propose more alternatives. A: You are almost always better off testing the behavior of the kind of item you want rather than explicitly testing for type. In your case, I'd simply try to get the desired item by index first and catch TypeError to check by name. def __getitem__(self, key): try: return self.this_list[key] except TypeError: try: return next(item for item in self.this_list if item.name == key) except StopIteration: raise KeyError("key `%s` not found" % key) Note that this will automatically work with slices too, since in this case the key will be a slice object and that will work fine with the [...] notation. You should probably be using a dict rather than a list inside your class, though, rather than searching a list for an object attribute. Exceptions would be if you really need slicing or if the names can be changed by code outside your class. Another (perhaps slightly unconventional) possibility is to implement the special method __eq__() on your This class, allowing it to be compared to a string, so that if the class's name attribute is (say) "Jerry", then This("Jerry", 0) == "Jerry". Then you don't actually need the container class and can just use a regular list: class This(object): def __init__(self, name, value): self.name, self.value = name, value def __eq__(self, other): return self.name == other thislist = [This("Jerry", 42), This("Amy", 36)] "Jerry" in thislist # True thislist.index("Amy") # 1 The syntax for accessing an item by name is still a little hairy: thislist[thislist.index("Amy")] But you can simply subclass list and combine this with my previous suggestion, which becomes simpler and more generic, since it works with any object that knows how to compare itself to whatever kind of key you're using: class That(list): def __getitem__(self, key): try: return list.__getitem__(self, key) except TypeError: return list.__getitem__(self, self.index(key)) thislist = That([This("Jerry", 42), This("Amy", 36)]) thislist["Amy"].value # 36 A: You can define two private methods __getitem_int() and __getitem_str(). Then you can use getattr() to get handle to proper method depending of type(x).__name__ and call type-specific method. See how KantGenerator.parse() is implemented in dive into python parsing xml example. A: Is there a more pythonic way to write getitem in the following? Only slightly. __getitem__ is used by both sequences, where int's and slice's are used, and by mappings, where pretty much anything can be used. It looks like you are implementing both sequence-type and mapping-type interfaces, so you're stuck with checking type. Missing two things: * *support for slices (but only put it in if you want your That to support it) *raising an exception for failure (returning None in this case is not pythonic) Here's an updated __getitem__: def __getitem__(self, x): if isinstance(x, int): return self.this_list[x] elif isinstance(x, slice): return self.this_list[slice] elif isinstance(x, str): for this in self.this_list: if this.name == x: return this return None raise KeyError("invalid key: %r" % x) At this point you have two possible exceptions being raised * *IndexError (if x is outside the range of this_list) *KeyError (if the name is not found, or something besides str or int was passed in) This may be fine for you, or you might want to create a custom Exception that gets returned in all cases: class LookupError(Exception): "x is neither int nor str, or no matching This instance found" Here's the updated code (Python 2.x): class LookupError(IndexError, KeyError): "x is neither int nor str, or no matching This instance found" class This(): def __init__(self, name, value): self.name, self.value = name, value class That(object): def __init__(self): self.this_list = [] def add_this(self, this): self.this_list.append(this) def __getitem__(self, x): try: if isinstance(x, int): return self.this_list[x] elif isinstance(x, slice): return self.this_list[slice] elif isinstance(x, str): for this in self.this_list: if this.name == x: return this raise KeyError("invalid key: %r" % x) except (IndexError, KeyError), err: raise LookupError(err.message) a = This('a', 1) b = This('b', 2) c = That() c.add_this(a) c.add_this(b) print c[1].name print c['a'].name try: print c[2.0] except LookupError, e: print e try: print c['c'] except LookupError, e: print e
{ "language": "en", "url": "https://stackoverflow.com/questions/7534271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: $(document).scroll is not firing in IE8 only I have a site running some javascript. In IE8 only, the $(document).scroll is not firing when you scroll with or without the mousewheel. Code snippet below: $(document).scroll(function () { //do something on scroll }); Is there a specific reason this function won't fire in IE8? I have searched online with no success. Thanks for all advice and tips in advance!!!!! A: For a lot of areas, IE ties the event to window rather than document as other browsers will. $(window).scroll(function(e) {}); is what you're after here. Should generally also work in most other browsers too, but if not, use a check on the navigator to find IE and use window or document based on that Boolean. A: Try using window: $(window).scroll(function () { //do something on scroll });
{ "language": "en", "url": "https://stackoverflow.com/questions/7534277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: Tkinter and Tix demo or showcase application? Is there a showcase (demo) application with all Tkinter and Tix features and widgets? For example, wxPython download includes a "wxPython Demo" application which not only demonstrates the widgets, but also provides the source code and some comments on it, which I liked a lot. But now I have to stick to Tkinter and Tix only, and as of those - there is some real good documentation, even with patterns explained, but there is no a showcase I could find, so I basically have to copy-paste lots of code from docs to my sample app to understand what it looks like in real. P.S. Tix is really wanted, not only Tkinter... A: check this message: http://groups.google.com/group/comp.lang.python/msg/0b42abf092120140 A: The Python wiki page on TkInter is a good starting point - listing many resources. The TutorialsPoint site seems to be one of the few that gives a reasonable visual overview of the TkInter widgets. Also there is an overview of the basic tk widgets on the tcl.tk site.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: NSMutableDictionary not Setting Keys All, I'm sure I'm overlooking something, but I've been staring at this code for too long trying to figure out what's going on. -(IBAction)continue:(id)sender { //setters for the limits NSLog(@"Log ageUnder18: %@", ageUnder18.text); //returns Y NSMutableDictionary *cardLimits; [cardLimits setObject:ageUnder18.text forKey:@"ageUnder18"]; NSLog(@"Just set %@", [cardLimits objectForKey:@"ageUnder18"]); //returns NULL //more code here } Why is that returning NULL? Thanks in advance, James A: You're not initializing your variable. In fact, you're rather lucky that you aren't crashing outright on the -setObject:forKey: line. Your cardLimits variable currently holds garbage memory, i.e. whatever was on the stack at the address that the variable occupies. You need to use NSMutableDictionary *cardLimits = [NSMutableDictionary dictionary]; Note that the Static Analyzer should be able to catch this for you. A: You are not allocating cardLimits at any time. You need: NSMutableDictionary *cardLimits = [[NSMutableDictionary alloc] init]; A: You aren't initializing a NSMutableDictionary.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASIHTTPRequest crashing in performInvocation I'm getting a crash in ASIHTTPRequest on the performInvocation: method. The stack is: ASIHTTPRequest performInvocation:onTarget:releasingObject: 1877 ASIHTTPRequest performSelector:onTarget:withObject:amount:callerToRetain: 1870 ASIHTTPRequest updateProgressIndicator:withProgress:ofTotal: 1903 ASINetworkQueue request:didReceiveBytes: 240 ASIHTTPRequest performInvocation:onTarget:releasingObject: 1877 This is the method where the crash happens: + (void)performInvocation:(NSInvocation *)invocation onTarget:(id *)target releasingObject:(id)objectToRelease { if (*target && [*target respondsToSelector:[invocation selector]]) { [invocation invokeWithTarget:*target]; } CFRelease(invocation); if (objectToRelease) { CFRelease(objectToRelease); } } I believe it to be happening on the invokeWithTarget call. This happens rarely, but in a large-scale deployment it's happening a lot. Searching around, I found a vague reference to adding: [cbInvocation retainArguments]; back in performSelector:... right before the [cbInvocation performSelectorOnMainThread:...] call. But it hardly seemed authoritative, and I'm not certain I understan what's going on there enough to make and/or trust that sort of change. I cannot reproduce the problem locally, but I get a large number of crash reports with this stack trace from the field. This on iOS code, by the way. Anyone have an idea what this might be? A: Your downloadProgressDelegate has been freed, without removing it from ASIHTTPRequest's downloadProgressDelegate first. In the dealloc implementation for your download progress delegate, call: [request setDownloadProgressDelegate:nil];
{ "language": "en", "url": "https://stackoverflow.com/questions/7534294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Objective-C Guid with Hyphens All I am looking to format a guid stored in an NSString with hyphens? I would like to avoid substrings and use a formatter if possible so D21AB2C8-E61F-11E0-ADEE-20D04824019B instead of D21AB2C8E61F11E0ADEE20D04824019B The value is already in an NSString and I just need to add the hyphens, but I would rather not have to deal with parsing the String and inserting hyphens with substrings. Any thoughts? Thanks! A: Not sure why you are against parsing, but if you are so dead set against it then use an NSMutableString and insert your hyphens at the appropriate index. NSMutableString * guid = [NSMutableString stringWithString: @"D21AB2C8E61F11E0ADEE20D04824019B"]; [guid insertString: @"-" atIndex: 8]; [guid insertString: @"-" atIndex: 13]; [guid insertString: @"-" atIndex: 18]; [guid insertString: @"-" atIndex: 23]; NSLog(@"GUID: %@", guid); For the record, I think its better to use NSString's stringWithFormat and substrings, but to each his own. A: Use an NSCharacterSet NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"-"]; NSString *newUUID = [myString stringByTrimmingCharactersInSet:set];
{ "language": "en", "url": "https://stackoverflow.com/questions/7534298", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add a array variable parameter in mysql query?(PHP) I need to do a query like: UPDATE screening SET maileddate = NOW(), reference = '{$reference[$user_id]}' WHERE user_id IN(....) And I want to do the judgement, when reference[$user_id] is empty, reference[$user_id] = NULL. My code is : if(empty($reference[$user_id]) || $reference[$user_id] == ''){ $reference[$user_id] = NULL; } But when I execute the query, if $reference[$user_id] is empty, the value of reference in database is empty but not null. What should I do to make it null? thanks A: You may need to pass NULL as a string to MySQL if the variable is empty. Use a different variable to hold the possibly NULL contents and quote the non-null contents. Don't forget to escape it otherwise: $refid = empty($reference['user_id']) ? "NULL" : "'" . mysql_real_escape_string($reference['user_id']) . "'"; UPDATE screening SET maileddate = NOW(), reference = '{$refid}' WHERE user_id IN(....) A: Just make it a string saying null. If it's null $reference[$user_id] = 'null'; Oh, also with the query you should be using reference IS null {$reference[$user_id]} instead of the equals sign A: Without seeing the rest of your code, my guess is it has something to do with reference = '{$reference[$user_id]}' having {$reference[$user_id]} in single quotes. MySQL is going to see whatever is in there as what should be in the database. So if $reference[$user_id] prints out as nothing (because it's NULL), that bit of your query will be reference = '' rather than reference = NULL. You need to use the keyword NULL rather than the actual value NULL for the variable you use in the query. As an example: $query = "UPDATE screening " . "SET maileddate = NOW(), " . "reference = " . ($reference[$user_id] === NULL ? 'NULL ' : "'{$reference[$user_id]}' ") . "WHERE user_id IN(....)"; A: $reference = 'reference = '; $reference .= ' empty($reference[$user_id]) ? 'NULL' : "'". mysql_real_escape_string($reference[$user_id]) . "'"; $query = "UPDATE screening SET maileddate = NOW(), $reference WHERE user_id IN(....)"; A: Try this: $user_id = empty($reference[$user_id]) ? 'NULL' : $reference[$user_id]; $sql = "UPDATE screening SET maileddate = NOW(), reference = " . $user_id . " WHERE user_id IN(....)";
{ "language": "en", "url": "https://stackoverflow.com/questions/7534299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Add/remove class working but clicking on new class doesn't Sorry for the bad title wording! I have the JS: $(".add").click(function(event) { cid=event.target.id; alert("add class changed"); $("#"+cid).addClass("del"); $("#"+cid).removeClass("add"); }); $(".del").click(function(event) { cid=event.target.id; alert("del class changed"); $("#"+cid).addClass("del"); $("#"+cid).removeClass("add"); }); And some html like this: <a class="add" id="1" href="#">test a</a> <a class="add" id="2" href="#">test b</a> <a class="add" id="3" href="#">test c</a> When I click on one of the "tests" I get the "add class changed" alert and the HTML shows it's class has been changed to "del". However when I click on one of the changed "tests" the function for something with a del class doesn't run, just the add one again. So the class is changing and displaying accordingly, but the click function for the corresponding class isn't happening. Can anyone see where I'm going wrong? EDIT: Needed a "LIVE" event. The following code works: $(".add").live({ click: function(event) { cid=event.target.id; alert("add class changed"); $("#"+cid).addClass("del"); $("#"+cid).removeClass("add"); } }); A: The $(".add") just selects elements that at that moment have the add class. It doesn't mean the click event will magically be assigned to other elements when their classes change. This can be achieved, though, by using the JQuery live method to bind the events.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a rate and comment system for android app? I want to create a rate system for an android application using java. Ive searched around and havent found much on the web concerning this. What do i need to do to build or get started building a rate system for a android application. Such as the android market. The user is allowed to leave comments and rate a app. I want to implement the same concept except with the ability just to rate or vote up a object in my application. Has anyone implemented this before? Some guidance on this would be very helpful. Thanks A: This is a pretty broad question, but I would use an approach like this: Android Client <--> (RESTful) Web Service (e.g. PHP) <--> Database (e.g. MySQL) The last two items, of course, reside server side in this architecture. The flow would essentially consist of the user makes a rating or comment, an HTTP request is made to your web service, the web service executes a SQL statement that adds the rating or comment to the database, which leads to a result and an HTTP response from which you can update your Android client. I would first suggest looking into RESTful web services and web services in general if you're unfamiliar with them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: UIColor colorWithPatternImage The documentation for the method colorWithPatternImage of the UIColor class states: During drawing, the image in the pattern color is tiled as necessary to cover the given area. This means that if the object's frame is larger than the size of my image used with the method colorWithPatternImage, then the image is tiled to fit. However, I would like for it to be stretched instead. Is this possible? How would one accomplish this? A: Using UIColor with colorWithPatternImage will not let your UIImage stretched If you want to use stretchableImageWithLeftCapWidth:topCapHeight: try UIViewImage
{ "language": "en", "url": "https://stackoverflow.com/questions/7534303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change class of element based on javascript variable value? I have the following script: <script> window.now = some_int_value; </script> and the following html: <span class="dot"></span>&nbsp; <span class="dot active"></span>&nbsp; <span class="dot"></span>&nbsp; <span class="dot"></span>&nbsp; How should I change the style of the dot in accordance with window.now value? So, if it is equal to 1, then first dot should be 'dot active', if equal to 2, then second and so on. A: document.getElementsByClassName("dot")[window.now-1].className += " active"; You can do that (for IE9+ and all other major browsers). Or you can use document.querySelectorAll(".dot")[window.now-1].className += " active"; for IE8+, FF3+, and all other major browsers. or you can combine them if(document.getElementsByClassName); document.getElementsByClassName("dot")[window.now-1].className += " active"; else if(document.querySelectorAll) document.querySelectorAll(".dot")[window.now-1].className += " active"; Compatibility Documentation A: You should consider looking into jQuery, which simplifies working with the DOM a lot. This is all you'd need for your indicator in jQuery: $('span.dot').eq(window.now - 1).addClass('active'); No more * *"Maybe I should assign an ID to each dot" *"getElementByTagName() is not implemented in some more or less obscure browser". *"This won't work in IE8" *… A: This should do it: var dots = document.querySelectorAll( '.dot' ); [].slice.call( dots ).forEach( function ( dot, i ) { dot.className = 'dot' + ( window.now === i + 1 ? ' active' : '' ); }); (This doesn't work in IE8.) Live demo: http://jsfiddle.net/dKDLx/ (The demo shows that even though the 2. dot had the class "active" set, window.now = 3; will cause that class to be "moved" to the 3. dot.) A: This isn't, by any chance, supposed to be a 4-dot progress bar/throbber? If so, I'd say just use a gif - there's a site that can generate them for you: http://preloaders.net/
{ "language": "en", "url": "https://stackoverflow.com/questions/7534310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: User script directory in Google Chrome When I follow a link to a user script in Google Chrome (for example, https://gist.github.com/raw/1107277/cacd006f78ae9e02bb10a173e30092b0b56fb5e9/answers-6825715.user.js), where does the script get stored? If I make changes and save, will the script be updated when I refresh? A: By default the script gets stored in the Extensions folder at: Windows XP: C:\Documents and Settings\***{username}***\Local Settings\Application Data\Google\Chrome\User Data\Default Windows Vista: C:\Users\***{username}***\AppData\Local\Google\Chrome\User Data\Default Windows 7: C:\Users\***{username}***\AppData\Local\Google\Chrome\User Data\Default You can change the folder by running Chrome with the --user-data-dir= option. If you make changes to the script, they won't apply until the script is reloaded by Chrome. To reload a script, either restart Chrome, or navigate to chrome://extensions/ and do hit the Reload link, if it is available. If the Reload link is not available, hit Disable, then Enable for the changes to go into effect. Note that changing the script's @include, @exclude, or @match directives will do nothing on already installed scripts. The manifest.json file must be edited for that. See "Manually adding a Userscript to Google Chrome" for more information.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why do you have to create a new set of RelativeLayout.LayoutParams for each element you put in your view? I have to do this programmatically. So, bear with me. I have text and two buttons that I set to align below each other. So I created a new RelativeLayout.LayoutParams instance for each and added a rule to set it below one another. That works and I'm happy with it. My question is: why do I have to create a new instance in order for the layout to display them this way? Is there any way to reduce the following code so that it's not so repetitive (besides writing my own private method to dry it up. I'm wondering whether there's a way to accomplish the same thing in fewer lines of code utilizing something I've possibly overlooked in the Android SDK)? Do I have to keep creating a new RelativeLayout.LayoutParams instance for each element? layout = new RelativeLayout(this); layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); text = new TextView(this); text.setId(1); text.setText("This is text"); layout.addView(text); myButton1 = new Button(this); myButton1.setId(2) myButton1.setOnClickListener(this); RelativeLayout.LayoutParams buttonParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); buttonParams.addRule(RelativeLayout.BELOW, text.getId()); layout.addView(myButton1, buttonParams); myButton2 = new Button(this); myButton2.setId(3) myButton2.setOnClickListener(this); buttonParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); buttonParams.addRule(RelativeLayout.BELOW, myButton1.getId()); layout.addView(myButton2, buttonParams); A: Unfortunately, there is no removeRule() method for RelativeLayout.LayoutParams (at least according to the API) so you have to create a new LayoutParams object each time. I would tend to agree with @jeffamaphone that you should prefer xml layouts over programmatically setting the layout. Even if you don't put the entire layout in an xml, you should use the resource id (see doc for details) to set the id's for the items. This will guarantee a unique id. A: you can set whatever rule you added to false using 0. buttonParams.addRule(RelativeLayout.BELOW, 0);
{ "language": "en", "url": "https://stackoverflow.com/questions/7534317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Page Flickering Asp.Net Using Master Page Asp.Net I have masterpage and i am using update panels for all my partial page renderings and panels. When i run this on my local machine the postbacks dont casue flickering but when i run from the host server the whole page flikers on postback. any ideas? A: I found this link and it prevents masterpage flickering. the re-load time will remain the same but is much easier on the user's eyes. <meta http-equiv="Page-Enter" content="blendTrans(Duration=0)"> <meta http-equiv="Page-Exit" content="blendTrans(Duration=0)"> Source : Prevent Master_Page Flickering
{ "language": "en", "url": "https://stackoverflow.com/questions/7534319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: If a page takes 1 ms to render, does that mean 1000 pages per second? If a webpage takes 1 ms to render, does that mean my application can do 1000 pages per second? I understand it also depends on other things like db connections and locks, but in general is that a good measurement or is it actually probably more because of multi-threading capabilities of web servers and the # of cores etc? BTW, as a side question, what kind of millisecond #'s do you guys see for your page views on rails apps? A: the response time of 1 request isn't certainly enough data to estimate the performance and scalability of a rails app. this first and easiest way to get a quick hint at how your app is performing, is using ab (apache bench). ab -n 100 -c 4 http://yourdomain.com/ where 100 is the number of requests, and 4 is the number of concurrent requests. don't forget the / at the end! (or specify some route / controller-action you want to test) A: You definitely can't rely on linear scale, especially using low data points (or in your case, 1 data point). This is the point of load testing - so that you can more reliably determine how your site/application will perform. By testing at predefined load intervals, you can better determine the curve at which performance declines.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Change from long to wide format with indicators All- I am needing to change from a long format to a wide format in R, but I need the column values to be 1 or zero depending on if the particular variable is present for the subject. The input data looks like: Subject Product 1 ProdA 1 ProdB 1 ProdC 2 ProdB 2 ProdC 2 ProdD 3 ProdA 3 ProdB and I want it to be Subject ProdA ProdB ProdC ProdD 1 1 1 1 0 2 0 1 1 1 3 1 1 0 0 Is there any way in R to accomplish this? EDIT: One way I think is to first table the data: tbl<-data.frame(table(data)) Then apply final <- cast(tbl, Subject~Product, max) I wonder if there is a more efficient way? A: xtabs(data=dat) Product Subject ProdA ProdB ProdC ProdD 1 1 1 1 0 2 0 1 1 1 3 1 1 0 0 A slightly more readable version would make the fiormula explicit: xtabs( ~Subject+Product, data=dat) If you want to go with stats::reshape, then try this: reshape(dat, idvar="Subject", timevar=2, v.names="Product", direction="wide") Subject Product.ProdA Product.ProdB Product.ProdC Product.ProdD 1 1 ProdA ProdB ProdC <NA> 4 2 <NA> ProdB ProdC ProdD 7 3 ProdA ProdB <NA> <NA> (But it does not return numbers.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7534328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mvc 2 - 404 error page not found I am getting a 404 error when I start up my mvc 2 project. I followed the guide here: http://net.tutsplus.com/tutorials/asp-net/asp-net-from-scratch-mvc/ I haven't set up a start page (Which I figured out to be a normal newbie mistake) and I've edited my global.asax class to look like below so it contains the right route. I just can't figure out why it gives me a 404. public class MvcApplication : System.Web.HttpApplication { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "CreateUserController", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); } } Here's my CreateUserController: public class CreateUserController : Controller { // // GET: /CreateUser/ public ActionResult Index() { return View(); } public ActionResult AddLinks() { return View(); } } My Project looks like this: * *Controllers * *CreateUserController.cs *Models ((This is empty for now)) *Views * *CreateUser * *Index.aspx *Shared * *Site.Master *global.asax *Web.Config I am totally new at mvc 2, I've worked with normal web forms for about 2 months now. Let me know if you need the aspx files, but I just need it to find my controller, at this point I just want another error. A: routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "CreateUser", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); controller should be "CreateUser" not "CreateUserController" you can see this hint in your file // GET: /CreateUser/
{ "language": "en", "url": "https://stackoverflow.com/questions/7534330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to show image with out symbol hi guys i am trying submit form and get a result as jpeg on same page. how ever when click to submit button i get the some weird code instead of image hcan you guys help me here is my code function xgetbarcode() { $.get('ajax_barcode.php', { barcode: $('form[name=getbarcodeform] input[name=barcode]').val(), getarticlenumber: $('form[name=getbarcodeform] input[name=getarticlenumber]').val(), }, function(output) { $('#getbarcodee').html(output).show(); }); } <form>.... <input type="button" value="barcode" onclick="xgetbarcode();"> </form> <div id="getbarcodee">here i get some weird symbol</div> thanks a lot A: Add a header to your php file header('Content-Type: image/png'); and add image into div with the source to your php file A: Most likely, you are returning an image from ajax_getbarcode.php, and inserting the image (binary data) into the HTML. You need to use an <img> tag for displaying an image in HTML. I suggest the following code. <script type="text/javascript"> function xgetbarcode() { var image = '<img src="ajax_getbarcode.php?barcode=' + $('form[name=getbarcodeform] input[name=barcode]').val() + '&amp;getarticlenumber=' + $('form[name=getbarcodeform] input[name=getarticlenumber]').val() + '"/>'; $(#getbarcodee).html(image).show(); } </script> <form name="getbarcodeform"> .... <input type="button" value="barcode" onclick="xgetbarcode();"> </form> <div id="getbarcodee"></div> A: What are you returning from your ajax_barcode.php? Image name like xyz.jpeg you supposed to return html tag like <img src="xyz.jpg" width="" height="" /> Because .html() replace the entire text element of it's parent.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Specify CIFS vs NFS for UNC in Windows? On Windows 2008 Server R2 (acting as a client) I have the Client from Windows Services for NFS installed and a server mounted as Y: with NFS. That server also supports CIFS. When I open a UNC path to the server with start/run it connects using CIFS but when an application on the same client is passed the same UNC path it connects using NFS. The full UNC path (not the Y: drive letter) is used in both cases. How does Windows determine whether to use NFS or CIFS when passed a UNC path?
{ "language": "en", "url": "https://stackoverflow.com/questions/7534334", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Accessing GridView Cells Value I am trying to access the integer value of the first cell but I'm getting this error: Unable to cast object of type 'System.Web.UI.WebControls.DataControlFieldCell' to type 'System.IConvertible'. And the value i have stored in that cell is an ID like 810 My Code int myID = Convert.ToInt32(GridView1.Rows[rowIndex].Cells[0]); A: Cells[0] returns a DataControlFieldCell object, not the cell's value. Use the cell's Text property. A: GridView1.Rows[rowIndex].Cells[0].Text --or-- GridView1.Rows[rowIndex].Cells[0].Value Makes programmer's life harder with these stupid ambiguities introduced by Microsoft over time. A: Try this both of this codes are valued int SB = Convert.ToInt32(gdTest.SelectedRow.Cells[1].Text); ---------OR------- int AS = Convert.ToInt32(gdTest.Rows[1].Cells[1].Text); A: The recommended approach to retrieve the value of a cell in GridView/FormView is to use ExtractValuesFromCell() method. See an example below: foreach(var row in GridView.Rows) { // retrieve all cell values in a row as a ordered dictionary. IOrderedDictionary cellValues = new OrderedDictionary(); foreach(DataControlFieldCell cell in row.Cells) { cell.ContainingField.ExtractValuesFromCell(cellValues, cell, row.RowState, true); } // now do something with the cellValues for e.g read the columns value // like - cellValues["EmployeeName"] } The returned values are strings and can be converted with the help of System.Convert class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Add to Timeline vs Login I've got or site working with timeline using the new javascript SDK sample code but we'd like to move this into the natural flow of the script for authenticated users [so they don't have to actively post items each time they do an action]. I suspect I'm over thinking this but will adding publish_actions to the existing login-button calls be enough to grant timeline permission or do we have to have to run the separate add-to-time feature shown in the new Open Graph tutorial [https://developers.facebook.com/docs/beta/authentication/]? A: Adding the publish_actions permission to the login-button call will suffice to publish Open Graph actions into Timeline. A: You will have to request and the user will have to approve the "publish_stream" permission. This appears on a 2nd dialog advising the user that additional permissions are being requested. Your app should be able to handle the user not providing this approval.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Rails 3 test fixtures with carrierwave? I'm working on upgrading from attachment_fu to carrierwave, since attachment_fu is broken in rails 3. None of the tests are able to run, because we have invalid fixtures that were using the syntax from attachment_fu for attachment files. For example, we have a Post model that has one PostAttachment. Here's what the data in the PostAttachment fixture looks like: a_image: post_id: 1 attachment_file: <%= Rails.root>/test/files/test.png And this is the error I'm getting: ActiveRecord::StatementInvalid: PGError: ERROR: column "attachment_file" of relation "post_attachments" does not exist LINE 1: INSERT INTO "post_attachments" ("post_id", "attachment_file"... attachment_file would have been picked up by attachment_fu, and it would have taken care of all the processing to create the attachment_fu attachment for the model. Is there a way to have image attachments in the fixtures, but with using CarrierWave instead? A: Try passing a file instead of a String. a_image: post_id: 1 attachment_file: File.open(Rails.root.join("test/files/test.png")) This works for me using FactoryGirl Note: Edit thanks to @dkobozev A: The only way I've managed to get this to work is to use a storage provider specifically for testing that doesn't actually save/read files. In your config/initializers/carrier_wave.rb Add a NullStorage class that implements the minimum interface for a storage provider. # NullStorage provider for CarrierWave for use in tests. Doesn't actually # upload or store files but allows test to pass as if files were stored and # the use of fixtures. class NullStorage attr_reader :uploader def initialize(uploader) @uploader = uploader end def identifier uploader.filename end def store!(_file) true end def retrieve!(_identifier) true end end Then when initializing CarrierWave add a clause for the test environment, e.g., if Rails.env.test? config.storage NullStorage end Here is a gist of my complete carrier_wave.rb for reference. It also includes how to setup S3 for uploads in staging/production and local storage for development so you can see how to configure CarrierWave in context. Once CarrierWave is configured you can simply put any string in the fixtures column to simulate an uploaded file. A: config/initializers/carrier_wave.rb In Rails 4 # class NullStorage is defined here before the following block if Rails.env.test? CarrierWave.configure do |config| config.storage NullStorage end end & in fixtures: a_image: post_id: 1 attachment_file: <%= File.open(Rails.root.join("test/files/test.png")) %> A: To be able to use fixtures that have uploaded files as well as doing uploads in the tests, I've played around with CarrierWave for a bit lately. I've written an article about how I'd do it. A: I know it is old but, for some that uses Rails 5 + RSpec + CarrierWave + Fixtures: Edit test configs: # config/initializers/carrierwave.rb if Rails.env.test? class NullStorage < CarrierWave::Storage::Abstract def store!(_file) _file end def retrieve!(identifier) file = Rails.root.join('spec', 'fixtures', 'files', identifier) tmp = Rails.root.join('tmp', 'blank_tmp.jpg') FileUtils.cp(file, tmp) CarrierWave::SanitizedFile.new(tmp) end end CarrierWave.configure do |config| config.storage = NullStorage config.enable_processing = false end end Create a folder and a file, for example spec/fixtures/files/some-user-photo.jpg and, create some fixtures, for example: first_user: avatar: "some-user-photo.jpg" name: "First User Name" about: "First User About Long Text..." lat: 0.001 lng: 0.001 created_at: <%= Time.current - 3.days %> updated_at: <%= Time.current - 3.days %> That is enough to make the test understand that this user has an avatar A: We have just removed the fixtures all together, the system seeds this files for each test. Ask yourself... do you need al these fixtures here for this test? No probably not. And Fixtures dont BANG! so we just use Model.create!( ... ) with specific data for the test
{ "language": "en", "url": "https://stackoverflow.com/questions/7534341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: Java: Morphia how easy is it to update a Collection with new field values I'm new to this, Let's say I have Collection "UserData" and there are 1000 Documents in the UserData. Now I need to add one more field called "position". Can I do this, how?, or how does it work? Looking on the wiki Morphia but cannot find anything A: if the UserData is look like, @Entity UserData{ @Id private ObjectId id; private String name; private int age; } and you have added 1000 documents in this Collection. Now, you want one more field called position, Just do this, @Entity UserData{ @Id private ObjectId id; private String name; private int age; private String position;//Add the field like this. } In the old 1000 documents, the value of position will be null. Its the power of mongo, you can expand your data structure when ever you want. A: Essentially, yeah, you can. There are implications, but significantly less than using a traditional ORM. With Morphia, if your persisted object has an instance variable that isn't set, its not included in the record in mongo. So adding another instance variable is pretty straightforward for mongo to retroactively map older records - they just get null for that variable (in my experience). Now if your application now absolutely depends on Position you'll have to update those 1000 records, but in general in my experience you can add the instance variable and it'll just work, easy as that. A: Maybe this page can help you with your problem. http://code.google.com/p/morphia/wiki/Updating
{ "language": "en", "url": "https://stackoverflow.com/questions/7534342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Spring Hibernate access joined database field my database tables: cities(id serial, name varchar(40); weather(id serial, city_id int, temp int, date date) cities.id = weather.city_id In Spring I have same POJO as the fields in database. for example City.java: @Entity @Table(name="CITIES") public class City { @Id @Column(name="ID") @GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "CITIES_ID_SEQ") @SequenceGenerator(name = "CITIES_ID_SEQ", sequenceName="cities_id_seq", allocationSize=1) private Integer id; @Column(name="NAME") private String name; //here come getters and setters DAO - so this will be returned to controller, which sends it to JSP: public Weather getWeatherById(Integer id) { return (Weather) sessionFactory.getCurrentSession().get(Weather.class, id); } Controller: model.addAttribute("weather", weatherService.getWeatherById(id)); Question is that, how can I access the cities.name from JSP? Or that is not possible, without special query? A: These two objects should have biderectional one-to-one releationship. public class City{ @One-To-One private Weather weather; } and the second class: public class Weather { @One-to-One private City city; } then you can fetch city and get its weather using getWeather() or you can fetch weather and get its city. Alternatively, you can use HQL join statement to fetch city: from City c join c.weather wheather where wheather.id = :id . A: Actualy, this does not seem like a one-to-one relationship to me but rather a many-to-one. Try using the following for the children: public class Weather { @Many-to-One private City city; } and for the parent: public class City{ @One-To-Many private Weather weather; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7534347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Finding strrpos of \ in a String Here's a puzzler. I have a variable that contains computer file paths. I need to separate the filename from the path. Example: From this: $filepath = C:\\User\Me\Myfiles\file.jpg I need this: $path = C:\\User\Me\Myfiles\ $file = file.jpg I know how to get the substrings of $filepath using substr. The problem is using "\" as a "needle" to get the position of the filename. This causes an error: $pos = strrpos("\",$filepath); This doesn't cause an error, but doesn't give me a value for $pos: $pos = strrpos("\\",$filepath); As always, any help with be rewared with my eternal gratitude. A: $pos = strrpos("\\",$filepath); This is trying to find the position of $filepath in the string "\\". Unless the $filepath is a single backslash, no position will be returned. You want to swap the two arguments around. $pos = strrpos($filepath, "\\"); Also, basename($filepath) or pathinfo($filepath, PATHINFO_BASENAME) can be used to get the file name. A: Look at the output of pathinfo($filepath), or for an oo approach, at the available methods of SplFileInfo. A: preg_match('#^(.+)\\\\(.+)$#', $filepath, $matches); $path = $matches[1]; $file = $matches[2]; This works because the + regex quantifier is greedy, so it will match all the characters it can. The \ is double-escaped, once for the PHP string, and once for the regex.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: After a db insert with AJAX, how can I make a div on same page update with inserted info? I am in the middle of learning jQuery and improving my AJAX, and I am a bit stumped. I have this page here: http://www.problemio.com You can use the left hand div to add something to the database. And it does that. What I am not sure how to do is how to show that new information in the right hand div right after the form on the left side is executed. Is it possible? Thanks! Here is the code that submits the AJAX request: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script> <script type="text/javascript" > $(function() { $("input[type=submit]").click(function() //$("input[type=button]").click(function() { var name = $("#problem_name").val(); var problem_blurb = $("#problem_blurb").val(); var dataString = 'problem_name='+ name + '&problem_blurb=' + problem_blurb; if(name=='' || problem_blurb == '') { $('.success').fadeOut(200).hide(); $('.error').fadeOut(200).show(); } else { $.ajax({ type: "POST", url: "/problems/add_problem.php", data: dataString, success: function() { $('.success').fadeIn(200).show(); $('.error').fadeOut(200).hide(); } }); } //alert ("before false"); return false; }); }); </script> A: Without much code I can't give you much specifics on this - but can rough out the idea. $.post('db-processing.php', {vars: 'whatever'}, function(data) { // data is whatever db-processing.php writes to the page. // if you want something to show up as a result - // have the db-processing.php echo - "Success / fail or whatever" $('#sidebar').html(data); }); Update Now having seen your code: $(function() { $("input[type=submit]").click(function() { var name = $("#problem_name").val(); var problem_blurb = $("#problem_blurb").val(); var dataString = 'problem_name='+ name + '&problem_blurb=' + problem_blurb; if(name=='' || problem_blurb == '') { $('.success').fadeOut(200).hide(); $('.error').fadeOut(200).show(); } else { $.ajax({ type: "POST", url: "/problems/add_problem.php", data: dataString, success: function(data) { $('#results_div').html(data); $('.success').fadeIn(200).show(); $('.error').fadeOut(200).hide(); } }); } //alert ("before false"); return false; }); }); Still the function(data) - and putting that data somewhere are the important parts. A: It works like this: * *Your ajax function sends data off to the server. *The server executes a function in response to the data and optionally returns data to the web page that sent the request. *That data is received as an argument to the success function in your ajax call. *That success function unpacks the data and updates the DOM of the web page with the new information. So your server-side function must package and return some data that will be used in your success function to update the web page. This could be actual HTML that the success function could insert into an existing (for example) <div> on your web page, or it could be JSON or XML that parsed by code you write in the success function and use, in pieces, to update the web page. A: You should show us your code that submits the ajax request. I entered a value in your page. The response contained Problem name: aaaaProblem blurb: wwaa First, you should return json that looks something like {name: "aaaa", blurb: "wwaa"} In the success callback for the request that does the insert, you need to process the response, and then grab a div and stuff the response in there. So if you have a div with id=#container or something like that, you could do var newDom = "<div>" + response.name + "</div>"; $('#container').html(newDom); The $('#container') code tells jquery to get the div with the id of container (ids must be unique) and the html(...) part is a way to put new dom inside an element. A: what are you getting from the server upon successful form submission? is it json? xml? html? say for example you have the following ajax call $("input.button").click(function(e){ e.preventDefault(); //prevent the default submission of the form //var name=$("#problem_name").val();// get the name input value //var desc=$("#problem_blurb").val(); // get the description $.ajax({ data:{problem_name:name,problem_blurb:desc}, //other parameters, success:function(data){ //give some id to your right div $("#RightDIV").append("<p>Name:"+name+"<p>"); $("#RightDIV").append("<p>Desc:"+desc+"<p>"); } }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7534353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET Add cell to Gridview row with string from code behind I have a gridview display results from a LINQ query. I want to add a column at the end that has a link. The issue is the link is dynamically generated in my code behind. I am not sure how to get this to the main page. Thanks! A: Check out the OnRowDataBound event, you can use this event to create your link and insert it into the last cell. It will be fired each time a row is created and bound to a data item. A: You can add a column to the GridView during PageLoad or some other event that fires once. You can then set the content of that column using it's RowDataBound function by using some thing a long these lines, where 0 is the index of the column: protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { e.Row.Cells[0].Text = "*** results from your LINQ Query ****" }
{ "language": "en", "url": "https://stackoverflow.com/questions/7534355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: android gallery no scroll on click By default it seems, when a gallery item is clicked, the gallery automatically scrolls to center the item that was clicked. How can I override this behavior? I do not want the gallery to scroll to center when clicked, I want it to stay where it is. A: I think this is a correct solution: @Override public boolean onSingleTapUp(final MotionEvent e) { boolean handled = super.onSingleTapUp(e); onDown(e); return handled; } A: I think this is what you are looking for. First create a class that extends from Gallery and then override the onSingleTapUp method: @Override public boolean onSingleTapUp(final MotionEvent e) { final OnItemClickListener listener = getOnItemClickListener(); final View selectedView = getSelectedView(); final float tapX = e.getRawX(); final float tapY = e.getRawY(); if ((selectedView != null) && (listener != null) && (tapX >= selectedView.getLeft()) && (tapX <= selectedView.getRight()) && (tapY >= selectedView.getTop()) && (tapY <= selectedView.getBottom())) { final int selectedPosition = getSelectedItemPosition(); listener.onItemClick(this, selectedView, selectedPosition, selectedPosition); } return true; } A: I never used a gallery before (actually i had to watch a youtube view to see it's visual effect first ;-) So i digged in the source code of gallery and it seems to me that they have tied the selection quite heavy to the positioning, so you would have to override the class and do some heavy code hacking, maybe even reflection, to reach your goal. I can't even tell whether you would succeed. This is not a solution, but a hint what you should expect if you want to realize that ;-) A: Gallery has a method to override this. gallery.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView parent, View v, int position, long id) { Toast.makeText(HelloGallery.this, "" + position, Toast.LENGTH_SHORT).show(); } }); } A: I haven't tried this... but you can try the following: In the onItemClickListener.onItemClick(), determine the currently selected position using Gallery.getSelectedItemPosition() and then set the position using Gallery.setSelection(int position). I don't know if this will work or not but you can give it a shot. There is also the OnItemSelectedListener which you could try leveraging. A: Unfortunately I don't seem to have the ability to comment on others' posts yet, but for any who found this question but was having issues, note that if you are creating a custom gallery that overrides the onSingleTap method (as suggested by Ohgema), you need to override the constructor that takes a Context and an AttributeSet.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Doctrine objects are HUGE I'm a .NET convert to PHP and am so far having a good time with the transition. I'm using doctrine 1.2 as my ORM and have my models working and everything is connected fine. However, the problem i'm looking at now is the output objects are enormous. I have a fairly simple table called USERS -- it has probably 8 columns and FKs to 4 or 5 other tables. I'm using the code below to hydrate my USERS object: $q = Doctrine_Query::create() ->select('u.*') ->from('USERS u') ->where('u.VANITY_URL = ?',$Url_Frag); $users = $q->execute(); print_r($users); I see the object hydrated w/ my data so that's good. However, it also comes along with what looks like a bunch of meta data that I obviously don't need. Overall, the object is over 5000+ lines long! I'm sure there's an obvious switch somewhere that basically says "only emit such-and-such data" but I can't find it in the doctrine manual. Thoughts? A: In Doctrine2, there is a dump() method available at: \Doctrine\Common\Util\Debug::dump($var, $maxDepth) It does a job similar to print_r and var_dump, but hides all the Doctrine-related data. Maybe there is something similar for Doctrine 1.x? A: Doctrine 1.2 entities object and collections has a method named "toArray". So you can do: print_r($users->toArray()); A: You have several options. One is to switch to doctrine2: it has sleek models, without any magic of doctrine1. The second ones are to change your hydration mode. You cannot really tweak the doctrine model or fatness of an object without changing the doctrine_record logic. So this might work: $q = Doctrine_Query::create() ->select('u.*') ->from('USERS u') ->where('u.VANITY_URL = ?',$Url_Frag) ->setHydrationMode(Doctrine::HYDRATE_ARRAY); $users = $q->execute(); Print_r'ing these objects will be hughe, since there are many nested objects in the doctrine class network (some objects have a bit of the "god complex" in them). More documentation can be found here: http://www.doctrine-project.org/documentation/manual/1_2/pl/data-hydrators:core-hydration-methods A: if I'm not mistaking, there are some circle references in the Doctrine1.2 entities, so print_r or var_dump on them is not a good idea. Actually, if you don't have something like Xdebug that limits the recursion depth, you'll never get the output to the browser. If you are really concerned of memory consumption, use memory_get_usage function to examine the memory footprint before and after hydration.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Authorization/Authentication with Google account in GWT I'm trying to enable my GWT application authenticate users with their Google accounts. What I basically need is just to have an unique value for every user and be sure that these values will always describe correct users. The main requirement is, the number of lines of code I have to write is as small as possible :-) I'm trying to use gwt-oauth2 library, but it looks like the whole idea of OAuth is to provide a token that allows access to different private resources like mail, contacts, etc., but it doesn't define the user itself. Question #1 - is that right that token Google gives me only defines "session with rights to access user's private data" and it doesn't define "the unique user"? Question #2 - should I use OpenID instead, since I'm 100% sure I'll never need to access any private data and the only thing I need is to have user's unique descriptor? For those who consider it a duplicate of Easiest way to enable Google authentication for GWT application? (non-GAE-hosted). This question is not about libraries to use to solve the problem ASAP, this question is about understanding of "whether authentication is a subset of authorization". The question is OAuth vs. OpenID for my case. A: 1) The point of OAuth is to allow a site owner to access certain info the user allows. You don't get a "unique user", however you could request their e-mail address and/or name and store that, then retrieve it when they log back in via OAuth. 2) Yeah, OpenID probably a better option for your use case. If you're not saving the user's info, don't bother asking them to give you access to it. OpenID does offer unique IDs for users. A: If you're searchig to go further by controlling what is visible/enabled to the user (authorizations), and how it is displayed. I just created a solution for that. I hope you'll enjoy: Use the project UiBinderAutho to catch widget creation and adapt them to your needs (connected profile ui, rights, widget handlers). Some explanations here http://ziedhamdi.github.io/UiBinderAutho/ here are the github projects https://github.com/ziedHamdi
{ "language": "en", "url": "https://stackoverflow.com/questions/7534374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Lync SDK - Making a plugin for Lync - Conversation Window Extension I was reading the MSDN documentation about Conversation Window Extensions and all of the examples that I found require working with IIS. Is there some way to create a CWE without using IIS? Can I create a CWE for Lync 2010 without working on HTML? A: A Conversation Window Extension must either be Silverlight or HTML - Silverlight is preferred as this gives you access to the Lync SDK. There is no reason why they have to be hosted in IIS - you could have the Silverlight Xap file and the host HTML file on your local drive, and point Lync to this via the registry settings. To try this out, install the Lync SDK and create a new Lync Silverlight Application. When you get prompted, uncheck the box to create a new website. Go into the Page.Xaml - there will be a PresenceIndicator control on the page - change the URI property to the URI of one of your contacts. Then build the app, and go to the output directory (bin/debug) - among other files, there should be a .Xap file and a TestPage.html. Create your registry settings according to this article, using the location of the TestPage.html file as the InternalURL and ExternalURL properties, e.g. file://S:\Testing\LyncSilverlightApplication2\LyncSilverlightApplication2\Bin\Debug\testpage.html Restart Lync, start a new conversation with anybody, and then select your app from the "More Options" menu (>>). The Silverlight app should be displayed as a CWE.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CTFramesetterSuggestFrameSizeWithConstraints: what attributes can be set? The documentation for CTFramesetterSuggestFrameSizeWithConstraints describes the frameAttributes parameter as so: Additional attributes that control the frame filling process, or NULL if there are no such attributes. I've only ever set this parameter to NULL and can't seem to find any documentation on what I can set these attributes to. The CTFramesetterCreateFrame also takes a frameAttributes parameter, but there's no documentation there, either. Does anyone know where the documentation for these parameters is? A: That parameter is named frameAttributes, which implies that they're the same attributes that would be valid when creating a frame and that you might retrieve by asking the frame for them. The documentation doesn't directly say what attributes a frame can have. However, it does have, in the CTFrame reference, constants named kCTFrameProgressionAttributeName, kCTFramePathFillRuleAttributeName, and kCTFramePathWidthAttributeName, along with constants for the values for the two that require constant values. So, educated guess: Those attributes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to compile and run xv6 on windows? We are being taught xv6 in our course. Currently we use to login to linux server of our school using putty in windows. There we make changes in source of xv6 (using vim), then compile and run it in qemu simply make clean make make qemu-nox It is not always possible to connect to their servers therefore I want to be able to compile and run xv6 withing windows (in some emulator obviously). What emulator I can use for above kind work? (edit code, compile and run) and how? A: Well, there are reasonable instructions on how to construct environment for building and using XV6 under Windows in the site http://www.cs.mta.ac.il/~carmi/Teaching/OS.xv6/index.html. The emulator they are using for actually running it is Bochs. A: If you wanna use WSL (Windows sub-system for Linux) on Windows 10, this might help. Follow Instructions regarding Windows here or Step 1: enable and setup WSL following this. Step 2: run WSL bash and install required stuffs on WSL. * *open CMD *type cd <xv6-source-path> *type bash and this will switch CMD into WSL bash *then sudo apt-get update && sudo apt-get install git nasm build-essential qemu gdb Step 3: disable video device for qemu in Makefile. * *open Makefile in xv6 source directory with any text editor. *find the line starting with QEMUOPTS = * *append -display none to this line and save the file. Step 4: type linux like commands in that terminal i.e * *first make *then make qemu Now if everything is okay, you should be in the xv6 terminal A: You can run Linux inside VirtualBox, that would give you the same environment on your machine that you use on the school's server. Then you could continue to run xv6 within qemu. You'll need a reasonably capable machine for this, though -- a dual-core CPU with 4G of memory is the minimum I'd attempt this with. A: I'd go for some sort VM solution (as suggested by TMN) as well, but it might be worth a try building it on Cygwin if you don't have the hardware to run a sufficiently specced VM. A: I had tried the above but make qemu-nox gave me this error: Cannot set up guest memory 'pc.ram': Cannot allocate memory I opened up the Virtual Box GUI, right clicked on the VM, when it was turned off (on halt), I right-clicked on the VM, then clicked the "system" tab, and then changed the motherboard memory to over 2000MB. After that I ran: make make qemu-nox This worked for me even though nothing else worked. A: I have succeeded to build and run xv6 with Command Prompt (cmd.exe) on Windows 10. That's what I've done. Not on Linux, nor Windows10 + WSL environment, nor Windwos10 + Cygwin or MSYS environment, I built it on Windows10 using Command Prompt. You need the following for Windows: MinGW, BusyBox, and QEMU. The xv6 source code modified by me can be download the following URL. https://github.com/mirokuuno/xv6-windows The details are documented in "How to build and run Unix-xv6 with Command Prompt on Windows" .
{ "language": "en", "url": "https://stackoverflow.com/questions/7534388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: MSBuild Property Scope Once again I'm battling MSBuild. I want to have a property value defined with a root path. As part of the build, the path will get updated with version information. However, MSBuild seems to have its own scoping rules that seem completely backwards. Take this first example: <?xml version="1.0" encoding="utf-8"?> <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5"> <PropertyGroup> <MyPath>\\server\folder</MyPath> </PropertyGroup> <Target Name="Main"> <Message Text="In Main Before - MyPath = $(MyPath)"/> <CallTarget Targets="Task1" /> <CallTarget Targets="Task2" /> <CallTarget Targets="Task3" /> <Message Text="In Main After - MyPath = $(MyPath)"/> </Target> <Target Name="Task1"> <PropertyGroup> <MyPath>$(MyPath)\version5</MyPath> </PropertyGroup> <Message Text="In Task1 - MyPath = $(MyPath)"/> </Target> <Target Name="Task2"> <Message Text="In Task2 - MyPath = $(MyPath)"/> </Target> <Target Name="Task3"> <Message Text="In Task3 - MyPath = $(MyPath)"/> </Target> </Project> Here's the output with this command line: msbuild PropertyScopeTest1.proj /target:Main Project "C:\Temp\PropertyScopeTest1.proj" on node 1 (Main target(s)). Main: In Main Before - MyPath = \\server\folder Task1: In Task1 - MyPath = \\server\folder\version5 Task2: In Task2 - MyPath = \\server\folder\version5 Task3: In Task3 - MyPath = \\server\folder\version5 Main: In Main After - MyPath = \\server\folder Done Building Project "C:\Temp\PropertyScopeTest1.proj" (Main target(s)). Now, here's a slightly different version setting the MyPath variable in the Main target: <?xml version="1.0" encoding="utf-8"?> <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5"> <PropertyGroup> <MyPath>\\server\path</MyPath> </PropertyGroup> <Target Name="Main"> <Message Text="In Main Before - MyPath = $(MyPath)"/> <PropertyGroup> <MyPath>$(MyPath)\version5</MyPath> </PropertyGroup> <Message Text="In Main After PropertyGroup - MyPath = $(MyPath)"/> <CallTarget Targets="Task1" /> <CallTarget Targets="Task2" /> <CallTarget Targets="Task3" /> <Message Text="In Main After - MyPath = $(MyPath)"/> </Target> <Target Name="Task1"> <Message Text="In Task1 - MyPath = $(MyPath)"/> </Target> <Target Name="Task2"> <Message Text="In Task2 - MyPath = $(MyPath)"/> </Target> <Target Name="Task3"> <Message Text="In Task3 - MyPath = $(MyPath)"/> </Target> </Project> Here's the output with this command line: msbuild PropertyScopeTest2.proj /target:Main Project "C:\Temp\PropertyScopeTest2.proj" on node 1 (Main target(s)). Main: In Main Before - MyPath = \\server\path In Main After PropertyGroup - MyPath = \\server\path\version5 Task1: In Task1 - MyPath = \\server\path Task2: In Task2 - MyPath = \\server\path Task3: In Task3 - MyPath = \\server\path Main: In Main After - MyPath = \\server\path\version5 Done Building Project "C:\Temp\PropertyScopeTest2.proj" (Main target(s)). I've looked at other links on this site that are similar, but all seem to be calling the MSBuild task from within the MSBuild project file. All I want to do is update the path and have it available everywhere in the project. Any ideas? A: Building on sll's answer, making the target that sets the new path a dependency instead of using CallTarget will yield the expected behaviour: <?xml version="1.0" encoding="utf-8"?> <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5"> <PropertyGroup> <MyPath>\\server\folder</MyPath> </PropertyGroup> <Target Name="Main" DependsOnTargets="SetMyPathProperty"> <Message Text="In Main Before - MyPath = $(MyPath)"/> <CallTarget Targets="Task1" /> <Message Text="In Main After - MyPath = $(MyPath)"/> </Target> <Target Name="SetMyPathProperty"> <PropertyGroup> <MyPath>$(MyPath)\version5</MyPath> </PropertyGroup> </Target> <Target Name="Task1"> <Message Text="In Task1 - MyPath = $(MyPath)"/> </Target> </Project> Build Output: Main: In Main Before - MyPath = \\server\folder\version5 Task1: In Task1 - MyPath = \\server\folder\version5 Main: In Main After - MyPath = \\server\folder\version5 Making SetMyPathProperty a dependency of Task1 instead of Main will result in identical behaviour to your PropertyScopeTest1.proj. A: This is a very interesting question which is investigated deeply with examples in following article: Scope of properties and item in an MSBuild script Basically there are tricks with a local and global context switches across a target executions: * *One instance of the Project class is created for the script and contains all the values of the properties and items in a global context. *When a target is executed, the global context is copied in a local context which will be used by the target. *A the target execution end, the local context updates are merged back to the global context. *Until a target execution is finished the local updates are not accessible to targets called using CallTarget or MSBuild tasks
{ "language": "en", "url": "https://stackoverflow.com/questions/7534390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: Rows to columns SQL Server query I am writing a query that will be used in a .NET application, therefore I would like the SQL Server 2008 o do much of the processing for me instead of the client PC that the application will run on. I am trying to get data from a single table with an index value, based off of that index value I would like that item to placed in a specific column. Here is an example: table MAS: MA SN Mindex B275 7A1515 1 B276 7A1515 2 E530 7A1515 3 B291 7A1519 1 B292 7A1519 2 E535 7A1519 3 B301 7A2515 1 B302 7A2515 2 B331 7A2519 1 B332 7A2519 2 Here is the output I would like: SN mi1 mi2 mi3 7A1515 B275 B276 E530 7A1519 B291 B292 E535 7A2515 B301 B302 null 7A2519 B331 B332 null I tried doing the following query, it works with items with 3 indexes but if there are only two, it fills it with random data. select mas1.SN, mas1.MA as mi1,mas2.MA as mi2, mas3.MA as mi3 from MAS ma1, MAS ma2, MAS ma3 where mas1.SN = '7A1515' and mas1.Mindex = '1' and mas2.Mindex = '2' and mas3.Mindex = '3' I was wondering if anyone would be able to point me in the right direction as I am still fairly new at writing these advanced queries. A: As you are on SQL Server 2008 you can also use PIVOT but the old style way of doing it is often easier IMO. SELECT SN, MAX(CASE WHEN Mindex=1 THEN MA END) AS mi1, MAX(CASE WHEN Mindex=2 THEN MA END) AS mi2, MAX(CASE WHEN Mindex=3 THEN MA END) AS mi3 FROM MAS GROUP BY SN
{ "language": "en", "url": "https://stackoverflow.com/questions/7534403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to write event log using vbscript I want to write event log when this vbscript run. How to i can? Thanks for any help. A: Like so: Set shell = CreateObject("WScript.Shell") shell.LogEvent 4, "Your Message Here" The 4 is a severity level. You can learn more about the LogEvent method on MSDN. A: This is old but I'm sure still valid. http://msdn.microsoft.com/en-us/library/b4ce6by3 You also need permissions to be able to write to the event log so depending on the user running the script you may or my not have access. A: You might want to simply write to your own log file. Check out my link with more information and details http://www.yeshaib.com/2010/08/vbscript-in-the-logging/ '---------------------------------------------------------------------- ' ' Please Enter Updates with date and name including line of Change '---------------------------------------------------------------------- '---------------------------------------------------------------------- set objShell = CreateObject("Wscript.Shell") set objFSO = CreateObject("Scripting.FileSystemObject") '--- Main Begins --------------------------------------- WriteToLog("Generic Log.vbs - Write This") '--- Main Ends ----------------------------------------- '--- Write to log -------------------------------------- Sub WriteToLog(strLogMessage) Const ForAppending = 8 Const vbsName = "Generic Log" strLogFileName = "C:\GenericLog.log" strLogEntryTime = NOW 'test whether file exists To either write/append to file if objFSO.FileExists(strLogFileName) Then Set objLogFileTransaction = objFSO.OpenTextFile(strLogFileName, ForAppending) Else Set objLogFileTransaction = objFSO.CreateTextFile(strLogFileName) End if objLogFileTransaction.WriteLine strLogEntryTime &amp; chr(9) &amp; chr(58) &amp; chr(9) &amp; vbsName &amp; chr(9) &amp; chr(58) &amp; chr(9) &amp; strLogMessage objLogFileTransaction.Close WScript.StdOut.WriteLine strLogMessage WScript.StdOut.WriteLine "" End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/7534407", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Python Object Inspector GUI What I would like is a handy GUI to inspect objects. The dir() function just isn't enough sometimes! What would happen would I would type view_object(module) and it would give me a GUI window that has Features: - Tree-view representation, similar to a file-viewer. This would let me see all the classes, and I could expand/contract these views. - selecting on any object lets me see any doc attributes. Ideally it would also let me cntrl+click on an object (or some other command) and open up the tree-view on THAT object, within IT'S module! This shouldn't be THAT hard to make, so I assume someone has made it, I'm just having a hell of a time finding it! A: Eclipse PyDev is really great. Especially debugger. I't heavy and it starts slowly, but it's a powerful tool. Not only you can see a tree-view of any variable in a runtime but you can even modify it on the fly. See Variables view: A: You can take a look at objbrowser (disclaimer I wrote it).
{ "language": "en", "url": "https://stackoverflow.com/questions/7534409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: multiple inside I am just wondering whether the below code is valid? <c:choose> <c:when test="${empty example1}"> </c:when> <c:when test="${empty example2}"> </c:when> <c:otherwise> </c:otherwise> </c:choose> A: <c:choose> <c:when test="${empty example1}"> </c:when> <c:when test="${empty example2}"> </c:when> <c:otherwise> </c:otherwise> </c:choose> This code is nothing but switch(int i){ case 1: ... break; case 2: ... break; default: ... break; } A: In a c:choose, the first when for which the test is true is the winner. In the c:choose below, if "first test" and "second test" are both true, then the "Kpow" h2 will be added to the html page and the "Blammy" will not. <c:choose> <c:when test="first test"> <h2>Kpow</h2> </c:when> <c:when test="second test"> <h2>Blammy</h2> </c:when> </c:choose> A: Yes its valid. Why not just try it though? Look up JSTL for more info.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Using TSimpleDataset for multiple purposes Delphi 2010 I am trying to use TSimpleDataset for multiple purposes. var q: tsimpledataset; row: String; n: Integer; begin q:=tsimpledataset.create(nil); q.connection:= SQLConnection1 ; q.dataset.commandtype:=ctQuery ; q.dataset.commandtext:='select lastid from last_id where tablename=:ARow'; q.Params.Assign(q.Dataset.Params); ShowMessage(q.dataset.commandtext); row:='accounts'; q.params[0].asstring:= row; q.open; if q.isempty then raise exception.create('No matching row found in LAST_ID table.'); n:=q.fieldbyname('lastid').asinteger +1; q.close; q.dataset.commandtype:=ctQuery ; q.dataset.commandtext:='update last_id set lastid=22'; q.execute; //exception Here! end; I get the following error on the q.Execute line: Missing Data provider or Data packet Seems to be a problem with the closing of the TSimpleDataset and the reuse of it. It would work if i freed it and recreated it and reassined the properties and new properties to use it for an execute. However, i would like to not have to do that. I would like to be able to close it, and then assign a new CommandText and reuse it. I have researched and read alot of comments on the internet reagrding not using the buggy TSimpleDataset, to use the three other components instead (ClientDataSet, DataSetProvider and SQLDataSet). You would think that by 2010 Embarcadero would have worked out any issues with the TSimpleDataset. Is there any workaround other than having to swictch to something other than a TSimpleDataset? Thanks! A: Shouldn't the second commandtype be. q.DataSet.CommandType := ctUpdate;
{ "language": "en", "url": "https://stackoverflow.com/questions/7534412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: IronJS CommonObject, are dynamic properties possible? In IronJS, we have a custom object derived from CommonObject. We're wanting to intercept calls to undefined properties on the object, and provide dynamic responses. (This is required, as it is not possible in our situation to preregister all the properties.) We can capture function calls on this object by overriding the BoxedValue Get(string name) function, and provide functions "on the fly" without preregistering them on the object. We're hoping we can do the same with properties, but none of the overrides seem to be able to handle this. I'm hoping that someone has enough experience with IronJS to suggest how we can better approach this. Hopefully this clarifies what we're trying to achieve: IronJS.Hosting.CSharp.Context ctx = new IronJS.Hosting.CSharp.Context(); ctx.SetGlobal("data", new MyCustomObject()); string script = @"var x = data.mydynamicproperty;"; ctx.Execute(script); When the script executes, we are wanting to be able to override and return a custom value. For example (on the MyCustomObject class declaration): public override BoxedValue Get(string name) { if (name == "mydynamicproperty") { return BoxedValue.Box("test"); } } The above override is called for functions (e.g. var x = data.mydynamicfunction();) but not for properties. Any help or suggestions would be greatly appreciated. A: It does not seem like this is currently possible (as of 1/14/12) due to the way function invoking and property access are compiled. Function invoking seems to ask the CommonObject implementation for the object with the property name, but normal property access seems to only hit the runtime's internal property cache and not the object's overrides. I'm trying to get the code modified to handle this, you can follow progress on the mailing list. Once the answer is figured out can post it here. If I knew F# better could probably make better progress, so if someone else does, please contribute :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7534413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: GAS: Explanation of .cfi_def_cfa_offset I would like an explanation for the values used with the .cfi_def_cfa_offset directives in assembly generated by GCC. I know vaguely that the .cfi directives are involved in call frames and stack unwinding, but I would like a more detailed explanation of why, for example, the values 16 and 8 are used in the assembly outputted by GCC in compiling the following C program on my 64-bit Ubuntu machine. The C program: #include <stdio.h> int main(int argc, char** argv) { printf("%d", 0); return 0; } I invoked GCC on the source file test.c as follows: gcc -S -O3 test.c. I know that -O3 enables nonstandard optimization, but I wanted to limit the size of the generated assembly for the sake of brevity. The generated assembly: .file "test.c" .section .rodata.str1.1,"aMS",@progbits,1 .LC0: .string "%d" .text .p2align 4,,15 .globl main .type main, @function main: .LFB22: .cfi_startproc subq $8, %rsp .cfi_def_cfa_offset 16 xorl %edx, %edx movl $.LC0, %esi movl $1, %edi xorl %eax, %eax call __printf_chk xorl %eax, %eax addq $8, %rsp .cfi_def_cfa_offset 8 ret .cfi_endproc .LFE22: .size main, .-main .ident "GCC: (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2" .section .note.GNU-stack,"",@progbits Why are the values 16 and 8 used for the .cfi_def_cfa_offset directives in the generated assembly? Also, why is the number 22 used for the local function begin and function end labels? A: I would like an explanation for the values used with the .cfi_def_cfa_offset directives in assembly generated by GCC. Matthew provided a good explanation. Here's the definition from Section 7.10 CFI Directives in the GAS manual: .cfi_def_cfa_offset modifies a rule for computing CFA. Register remains the same, but offset is new. Note that it is the absolute offset that will be added to a defined register to compute CFA address. And .cfi_adjust_cfa_offset: Same as .cfi_def_cfa_offset but offset is a relative value that is added/substracted from the previous offset. A: As the DWARF spec says in section 6.4: [...] The call frame is identified by an address on the stack. We refer to this address as the Canonical Frame Address or CFA. Typically, the CFA is defined to be the value of the stack pointer at the call site in the previous frame (which may be different from its value on entry to the current frame). main() is called from somewhere else (in the libc C runtime support code), and, at the time the call instruction is executed, %rsp will point to the top of the stack (which is the lowest address - the stack grows downwards), whatever that may be (exactly what it is doesn't matter here): : : ^ | whatever | <--- %rsp | increasing addresses +----------------+ | The value of %rsp at this point is the "value of the stack pointer at the call site", i.e. the CFA as defined by the spec. As the call instruction is executed, it will push a 64-bit (8 byte) return address onto the stack: : : | whatever | <--- CFA +----------------+ | return address | <--- %rsp == CFA - 8 +----------------+ Now we are running the code at main, which executes subq $8, %rsp to reserve another 8 bytes of stack for itself: : : | whatever | <--- CFA +----------------+ | return address | +----------------+ | reserved space | <--- %rsp == CFA - 16 +----------------+ The change of stack pointer is declared in the debugging information using the .cfi_def_cfa_offset directive, and you can see that the CFA is now at an offset of 16 bytes from the current stack pointer. At the end of the function, the addq $8, %rsp instruction changes the stack pointer again, so another .cfi_def_cfa_offset directive is inserted to indicate that the CFA is now at an offset of only 8 bytes from the stack pointer. (The number "22" in the labels is just an arbitrary value. The compiler will generate unique label names based on some implementation detail, such as its internal numbering of basic blocks.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7534420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "72" }
Q: Passing variadic arguments in one function to another function in D I have a variadic D-style function foo(format, ...), which is a wrapper around writefln. I'd like to do something like this: foo(format, <...>) { //... writefln(format, ...); } Essentially, passing on the ellipsis parameter(s) to writefln. I understand that this isn't easy/possible in C/C++, but is there a way to accomplish this in D? A: This will do it for you: import std.stdio; void customWrite(Args...)(string format, Args args) { writefln(format, args); } A: I had forgotten that those type of variadics even existed in D. I don't think that TDPL even mentions them. I believe that that makes a grand total of 4 different types of variadics in D. * *C variadics extern(C) void func(string format, ...) {...} *D variadics with TypeInfo void func(string format, ...) {...} *Homogeneous variadics using arrays void func(string format, string[] args...) {...} *Heterogeneous variadics using template variadics void func(T...)(string format, args) {...} I believe that TDPL really only talks about #3 and #4, and those are all that I normally use, so I'd have to go digging to figure out how to pass arguments using #2. I expect that it's similar to how you do it in C with #1, but I don't know. However, it's easy with #3 and #4. In both cases, you just pass args to whatever function you want to pass it to. And both allow for indexing and slicing (e.g. args[1] and args[1 .. $]) as well as having a length property. So, they're easy to use, and for the most part, they're the better way to go. The only exceptions that I can think of are if you're calling an existing C function (in which case, you use #1) or if you need heterogeneous templates and can't afford the increase in binary size that templates create (in which case you use #2), which should really only be an issue in embedded environments. In general, #3 and #4 and just plain better solutions. A: If you want templates, you can do it like this: auto bar(T...)(T args) { ... } auto foo(T...)(T args) { return bar!T(args); } but if you want run-time variadic arguments, then you have to do what C does: pass _argptr to the "v-version" of your function, e.g. vprintf.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to access Library, File, and Field descriptions in DB2? I would like to write a query that uses the IBM DB2 system tables (ex. SYSIBM) to pull a query that exports the following: LIBRARY_NAME, LIBRARY_DESC, FILE_NAME, FILE_DESC, FIELD_NAME, FIELD_DESC I can access the descriptions via the UI, but wanted to generate a dynamic query. Thanks. A: Along with SYSTABLES and SYSCOLUMNS, there is also a SYSSCHEMAS which appears to contain the data you need. Please note that accessing this information through QSYS2 will restrict rows returned to those objects with which you have some access - the SYSIBM schema appears to disregard this (check the reference - for V6R1 it's about page 1267). You also shouldn't need to retrieve this with a dynamic query - static with host variables (if necessary) will work just fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Named process internal mutexes with C/C++? Are there ways to implement named process internal mutexes using C/C++ (in Unix/Linux)? The trick is that the mutexes lifetime would need to be process persistent. Unlike for example the named posix semaphores and shared memory. You could have for example pthread mutexes, in a dynamic map and access them with some id. But then you need to protect the mutexes somehow. If you use memory mapped files or shared memory, you get the filesystem persistence... Any ideas? A: You can always revert back to the older (albeit depreciated) System V semaphores which work off a common key-value rather than a POSIX named semaphore which has file-system persistence. That being said, a POSIX named semaphore will not have file-system persistence if you close and then unlink the semaphore in every process using it. Once the last process that was using the semaphore has exited, the semaphore reference will be removed from the file-system. If you're worried about the visibility of the semaphore at the file-system level, you can always precede the name of the semaphore with a "." in order to make the file invisible, and/or adjust the permissions on the file so that only the current user or some privileged user/group can access the semaphore. A: What do you mean by "process-persistent"? If you want them to persist after the process ends, just use named semaphores or named shared memory, and prefix the name with something unique to your program. If you want them to go out of existence when the process terminates, just use any kind of hash map protected by an rwlock (locked in read mode to lookup existing names, write mode to add/remove names). A: It's quite simple. Have a mapping of strings to mutexes, and a mutex to protect this mapping: std::map<std::string, pthread_mutex_t *> mutexMap; pthread_mutex_t mutexMap_lock = PTHREAD_MUTEX_INITIALIZER; When you need to find a mutex, take the mutexMap_lock lock first. Once you have the mutex, drop the lock, and cache the mutex pointer so you don't have to keep referring to this mutexMap point of contention.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to define url which accept everykind of strings in django In django, I defined url like that (r'^checkstring/(?P<string>\w+)/$',views.check_str,name='check str') But, When i enter string inputs like ibrahim.yilmaz, ibrahi!m or ibrahim@ibrahim.com, it returns http 404. So how can i write the url which accept everykind of string? any help will be appreciated. İbrahim A: Django uses regular expressions to match incoming requests. In python a dot (.) matches any character except a newline. See docs for more information and try: (r'^checkstring/(?P<string>.+)/$',views.check_str,name='check str') Also keep in mind that this will accept any character (including the forward slash) which may not be desirable for you. Be sure to test to make sure everything works as you would expect. A: In Django >= 2.0, you can implement in the following way. from django.urls import path urlpatterns = [ ... path('polls/<string>/$','polls.views.detail') ... ] A: For Django 2.0 import re_path in urls.py file like this:from django.urls import re_path then in the urlpatterns write the following code: urlpatterns = [ re_path('prefixs/.*', your_ViewClass_name.as_view()), ]
{ "language": "en", "url": "https://stackoverflow.com/questions/7534436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Upgrading to SQL Server 2008: Upgrading a VS2005 .NET program that uses BCP I have VS2005 .NET C# program. My understanding is that VS2005 targeted only the 2.0 version of the .NET FW. The program uses the Bulk copy object. I believe the source dll of this object is the System.Data.dll file in the Version 2 Framework system folder. My guess is that the System.Data.dll must be calling the SQL Server 2005 version iof the BCP.exe when using the BulkCopy object. At the current time, our database server has both the 2005 and 2008 versions of the BCP.exe on it. Soon, the 2005 version will be removed and I need to ensure that my .NET program will continue to run. My thought is to use VS2008 to upgrade the app to the 3.5 version of the Framework, which I verified is on the DB server. In fact, I see that all version of the FW are there, including 1,1,2.0,3.5 and 4.0. I'm thinking that if I upgrade to the 3.5 FW that the 2008 version of the BCP.exe will be used. How do I know which version of the the bulkcopy (BCP.exe) I am using in order to ensure that the program continues to work when only the 2008 BCP.exe remains on our db server? A: If you are talking about SqlBulkCopy class, then it does not use bcp.exe at all. So your app will run as expected after upgrade. P.S. There is no connection between Framework version and SQL Server version. A: From the MSDN docs for SqlBulkCopy: Microsoft SQL Server includes a popular command-prompt utility named bcp for moving data from one table to another, whether on a single server or between servers. The SqlBulkCopy class lets you write managed code solutions that provide similar functionality. In other words, bcp.exe is unrelated to your issue. The System.Data.SqlClient namespace included in newer versions of the .NET Framework generally works against older SQL Server versions; I have yet to see any place in the MSDN docs where they failed to call out SQL Server backward-compatibility issues. Your safest bet is to just rebuild for .NET 3.5 or 4.0, as you said, so that it picks up the latest System.Data.SqlClient code (which handles compatibility for you). If you're curious about what it's doing, you can run Sql Server Profiler while running your application, and see what SQL is actually being generated by SqlBulkCopy. You should see relatively simple SQL that is verifiably 2008-compatible. A: * *If your app runs on a different server/PC that doesn't have any SQL Server compoents installed it will still work (assuming you have .net framework) *SqlBulkCopy class does not call bcp.exe. It is absolutely unrelated *It doesn't matter what version of bcp.exe may or may not be installed *Your application's use of SQLBulkCopy is not affected by SQL Server version
{ "language": "en", "url": "https://stackoverflow.com/questions/7534439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Determine current year or previous year based upon month selection I have inherited an archive program written in C#. The previous developer was only interested in archiving data from the previous month. However, some months were missed and my task had been to add functionality to see what other months were missed. The part I am stuck on is: When determining the missed month, I need to determine if the month is part of the current year or is it from the previous year. The current month is the key. If the current month is Sept, then months from Jan to Sept are considered current year. If the current month is Sept, then Oct to Dec are considered the previous year. Of course, this would be a sliding range as each month progressed. Looking for some guidance. A: Unless I'm missing something, you just need to compare your missing month date against DateTime.Today.Month DateTime archiveDate; if(someMonth > DateTime.Today.Month) archiveDate = new DateTime(DateTime.Today.Year - 1, someMonth, 1); else archiveDate = new DateTime(DateTime.Today.Year, someMonth, 1); A: Use DateTime.Now.Month it gives you the actual Month and you can compare to that the other dates you have as you described if it is smaller or equal then it is current year if it is greater then previous year. And then you can set the archive date on a previous year archive with DateTime.Now.AddYears(-1) A: You can get the current month number (via DateTime.Month) and subtract it from the comparison month and check if it's greater than zero. Sample: int month1 = 5; //may int month2 = 4; //apr bool isCurrentYear = (month1 - month2 >= 0); //current year int month1 = 8; //aug int month2 = 11; //nov bool isCurrentYear = (month1 - month2 >= 0); //last year
{ "language": "en", "url": "https://stackoverflow.com/questions/7534443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can I do this without reflection? For a presentation involving six components of a Person object's PersonName, I added an extension and a 'mini view model' (PersonNamePropertyTextBox) to cut down on duplicated code and facilitate data binding. So in the constructor of the parent view model, I create these mini view models like: public PimDetailVm(Person person, ..) { LastName = new PersonNamePropertyTextBox( () => Model.GetPersonName().LastName, v => this.UpdatePersonNameProperty(pn => pn.LastName, v)) { Label = PeopleResources.LastName_Label }; FirstName = new PersonNamePropertyTextBox( () => Model.GetPersonName().FirstName, v => this.UpdatePersonNameProperty(pn => pn.FirstName, v)) { Label = PeopleResources.FirstName_Label }; ... etc. } public PersonNamePropertyTextBox LastName { get; private set; } public PersonNamePropertyTextBox FirstName { get; private set; } What I would really like now is to be able to do is just pass in the current property, ie "LastName" and the label value, and let the mini view model set the appropriate Getter/Setter delegates, something like: LastName = new PersonNamePropertyTextBox(vm=>LastName, PeopleResources.LastName_Label); I am struggling as to how to do this though. Any ideas? Extension (handle updating the PersonName in the Model) public static void UpdatePersonNameProperty(this PimDetailVm vm, Expression<Func<PersonName, object>> propertyExpression, string value) { var pn = vm.Model.GetPersonName(); var pnProps = pn.GetType().GetProperties(); var subj = ExprHelper.GetPropertyName(propertyExpression); var subjProp = pnProps.Single(pi => pi.Name.Equals(subj)); var currentVal = subjProp.GetValue(pn, null); // split if there is nothing to update if(currentVal==null && value==null) return; if (currentVal != null && currentVal.Equals(value)) return; // update the property var capitalized = value == null ? null : value.Capitalize(); subjProp.SetValue(pn, capitalized, null); // update the model vm.Model.SetName(pn); // broadcast the update vm.NotifyOfPropertyChange(subj, value); } Mini View Model for some property of a PersonName public class PersonNamePropertyTextBox : TextBoxActionData { public PersonNamePropertyTextBox(Func<string> getterFunc, Action<string> setterAction) { if (getterFunc == null) throw new ArgumentNullException("getterFunc"); if (setterAction == null) throw new ArgumentNullException("setterAction"); GetterFunc = getterFunc; SetterAction = setterAction; } } A: Try implementing a binder class to manage the binding. In this case I have used PropertyBinding. public class PropertyBinding { public static PropertyBinding To(ViewModel vm, Name name, string label) { return new PropertyBinding { ViewModel = vm, Getter = new Func<string>(delegate() { return name.Value; }), Setter = new Action<string>(delegate(string value) { name.Value = value; }), Label = label }; } public string Label { get; set; } public ViewModel ViewModel { get; set; } public Func<string> Getter { get; set; } public Action<string> Setter { get; set; } public string Value { get { return this.Get(); } set { this.Set(value); } } internal string Get() { // Implement UpdatePersonNamePropert here. // Maybe convert culture before returning. return this.Getter(); } internal void Set(string value) { // Maybe convert culture before storing. this.Setter(value); } } It would be called like: LastName = new PersonNamePropertyTextBox(PropertyBinding.To(Model, Model.GetPersonName().LastName, PeopleResources.LastName_Label)); Please note that Model.GetPersonName().LastName must return a pointer type not a value type otherwise the LastName can not be updated when the Setter is called. For example: public sealed class Name { public string Value { get; set; } } In this example PersonName is implemented as below however your implmentation may be different. public class PersonName { public Name LastName { get; set; } public Name FirstName { get; set; } } Without all your class information and the strong types associated with some of the variables you used it was hard to validate but I think this should get you out of trouble. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: parse html data from iframe in anoter domain Hi i have an application in http://abc.def.aspx and I want to parse the contents (basically a report) existing in http://uvw.xyz.html . I have created an iframe in def.aspx page but it gives me permission error. I just want to parse the html content to allow new sorting features to the page. Can anyone point me to the right direction please A: You cannot access the iframe for security reasons (if its a different domain) The only solution I can suggest is if you have server side logic, you can go get the html of the different domain and parse the content on the server first.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: UITableViewController crash on loading second time I have a project where I want to open a UITableViewController after a UITableViewController via a UINavigationController. The thing is, it works the first time when it gets called by this function: - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { SDMetadataEntity *entity = [self.optionItems objectAtIndex:indexPath.row]; SudzcDetailViewController *detailViewController = [[SudzcDetailViewController alloc] init]; detailViewController.refName = entity.Name; [self.navigationController pushViewController:detailViewController animated:YES]; [detailViewController release]; [entity release]; } But when I press the back button on the navigation bar, and press the same item again, it crashes! It doesn't crash when I press a different item in the first UITableViewController. I would really like to learn from what I am doing wrong! A: You shouldn't be releasing entity. You got that object from an array, you don't own it, so when you release it you may be causing it to be deallocated prematurely. A: You should not [entity release]; because when you do [self.optionItems objectAtIndex:indexPath.row]; you just fetching a pointer to it, not init/copy/retaining it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: matplotlib does not show my plot although I call pyplot.show() Help required on matplotlib. Yes, I did not forget calling the pyplot.show(). $ ipython --pylab import matplotlib.pyplot as p p.plot(range(20), range(20)) It returns matplotlib.lines.Line2D at 0xade2b2c as the output. p.show() There is nothing to happen. No error message. No new window. Nothing. I install matplotlib by using pip and I didn't take any error messages. Details: I use, * *Ubuntu *IPython v0.11 *Python v2.6.6 *matplotlib v1.0.1 A: What solved my problem was just using the below two lines in ipython notebook at the top %matplotib inline %pylab inline And it worked. I'm using Ubuntu16.04 and ipython-5.1 A: I ran into the exact same problem on Ubuntu 12.04, because I installed matplotlib (within a virtualenv) using pip install matplotlib To make long story short, my advice is: don't try to install matplotlib using pip or by hand; let a real package manager (e.g. apt-get / synaptic) install it and all its dependencies for you. Unfortunately, matplotlib's backends (alternative methods for actually rendering your plots) have all sorts of dependencies that pip will not deal with. Even worse, it fails silently; that is, pip install matplotlib appears to install matplotlib successfully. But when you try to use it (e.g. pyplot.show()), no plot window will appear. I tried all the different backends that people on the web suggest (Qt4Agg, GTK, etc.), and they all failed (i.e. when I tried to import matplotlib.pyplot, I get ImportError because it's trying to import some dependency that's missing). I then researched how to install those dependencies, but it just made me want to give up using pip (within virtualenv) as a viable installation solution for any package that has non-Python package dependencies. The whole experience sent me crawling back to apt-get / synaptic (i.e. the Ubuntu package manager) to install software like matplotlib. That worked perfectly. Of course, that means you can only install into your system directories, no virtualenv goodness, and you are stuck with the versions that Ubuntu distributes, which may be way behind the current version... A: %matplotlib inline For me working with notebook, adding the above line before the plot works. A: Adding the following two lines before importing pylab seems to work for me import matplotlib matplotlib.use("gtk") import sys import pylab import numpy as np A: I had to install matplotlib from source to get this to work. The key instructions (from http://www.pyimagesearch.com/2015/08/24/resolved-matplotlib-figures-not-showing-up-or-displaying/) are: $ workon plotting $ pip uninstall matplotlib $ git clone https://github.com/matplotlib/matplotlib.git $ cd matplotlib $ python setup.py install By changing the backend, as @unutbu says, I just ran into loads more problems with all the different backends not working either. A: Similar to @Rikki, I solved this problem by upgrading matplotlib with pip install matplotlib --upgrade. If you can't upgrade uninstalling and reinstalling may work. pip uninstall matplotlib pip install matplotlib A: If I set my backend to template in ~/.matplotlib/matplotlibrc, then I can reproduce your symptoms: ~/.matplotlib/matplotlibrc: # backend : GtkAgg backend : template Note that the file matplotlibrc may not be in directory ~/.matplotlib/. In this case, the following code shows where it is: >>> import matplotlib >>> matplotlib.matplotlib_fname() In [1]: import matplotlib.pyplot as p In [2]: p.plot(range(20),range(20)) Out[2]: [<matplotlib.lines.Line2D object at 0xa64932c>] In [3]: p.show() If you edit ~/.matplotlib/matplotlibrc and change the backend to something like GtkAgg, you should see a plot. You can list all the backends available on your machine with import matplotlib.rcsetup as rcsetup print(rcsetup.all_backends) It should return a list like: ['GTK', 'GTKAgg', 'GTKCairo', 'FltkAgg', 'MacOSX', 'QtAgg', 'Qt4Agg', 'TkAgg', 'WX', 'WXAgg', 'CocoaAgg', 'agg', 'cairo', 'emf', 'gdk', 'pdf', 'ps', 'svg', 'template'] Reference: * *Customizing matplotlib A: Just type: plt.ion() See https://www.youtube.com/watch?v=1zmV8lZsHF4 at 23:30 ! plt is used because of my import: import matplotlib.pyplot as plt I'm using python2.7 on a mac with iTerm2. A: For future reference, I have encountered the same problem -- pylab was not showing under ipython. The problem was fixed by changing ipython's config file {ipython_config.py}. In the config file c.InteractiveShellApp.pylab = 'auto' I changed 'auto' to 'qt' and now I see graphs A: Be sure to have this startup script enabled : ( Preferences > Console > Advanced Options ) /usr/lib/python2.7/dist-packages/spyderlib/scientific_startup.py If the standard PYTHONSTARTUP is enabled you won't have an interactive plot A: For me the problem happens if I simply create an empty matplotlibrc file under ~/.matplotlib on macOS. Adding "backend: macosx" in it fixes the problem. I think it is a bug: if backend is not specified in my matplotlibrc it should take the default value. A: After running your code include: import pylab as p p.show() A: if you are a nube from ruby, don't forget the parenthesis - show() A: If you are working with yolov5 the fixes described here might not work as in my case. YOLOv5 developers have turned off the preview of the images using plt.show(), so most likely this will happen to you. To resolve make sure that your environment is correctly configured using requirements.txt file that comes with yolov5 and then use the workaround: import torch import matplotlib model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # Load model first matplotlib.use('TkAgg') # Change backend after loading model as described here: https://github.com/ultralytics/yolov5/issues/2779 you can also try another backend from the ones mentioned above like 'Qt4Agg' or smth else. A: For Ubuntu 12.04: sudo apt-get install python-qt4 virtualenv .env --no-site-packages source .env/bin/activate easy_install -U distribute ln -s /usr/lib/python2.7/dist-packages/PyQt4 . ln -s /usr/lib/python2.7/dist-packages/sip.so . pip install matplotlib A: I found that I needed window = Tk() and then window.mainloop() A: It also shows the error when you don't call plt.plot() on anything. I got that error haha. I though I was calling it in a loop but right before the loop I overwrote my array to a blank array so it never entered the loop
{ "language": "en", "url": "https://stackoverflow.com/questions/7534453", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "198" }
Q: Dependent Observable syntax woes My simple 'dependent observable' does not update and when I give it the syntax of a function as the turorials say is required I get a javascript error. I'm just trying to sum the three observable values. If I use <td>${G1 + G2 + G3}</td> I get a static display: the does not update when the other input fields change. If I use the viewModel.Series I get no display of values at all. If change viewModel.Series to: this.G1() + this.G2() I get a javascript error saying G1 is NOT a function. var initialData = {"DateId":32,"Scores":[{"Alias":"Cap Stocks","G1":129,"G2":123,"G3":222, var theScores = initialData.Scores; var viewModel = {scores : ko.observableArray(theScores) }; viewModel.Series = ko.dependentObservable(function() { return this.G1 + this.G2 + this.G3; }, viewModel); $(function () { ko.applyBindings(viewModel); } Here is my template binding that at least displays something <td> ${Alias}</td> <td><input data-bind="value: G1"/></td> <td><input data-bind="value: G2"/></td> <td><input data-bind="value: G3"/></td> <td>${G1 + G2 + G3}</td> A: In this case you would need to make the G1, G2, and G3 properties observable. An observableArray notifies when there are changes to the array itself, but not individual properties on its items. You could use something like the mapping plugin or map it yourself using a constructor function that either takes in a score object or each property. function Score(alias, g1, g2, g3) { this.Alias = alias; this.G1 = ko.observable(g1); this.G2 = ko.observable(g2); this.G3 = ko.observable(g3); this.Series = ko.dependentObservable(function() { return parseInt(this.G1(), 10) + parseInt(this.G2(), 10) + parseInt(this.G3(), 10); }, this); } Then, map your existing array: var theScores = ko.utils.arrayMap(initialData.Scores, function(score) { return new Score(score.Alias, score.G1, score.G2, score.G3); }); Sample here: http://jsfiddle.net/rniemeyer/SbFDR/
{ "language": "en", "url": "https://stackoverflow.com/questions/7534458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Use a variable in file path in .vbs Is it possible to usa variable in a path in .vbs. My basic situation is I have a vbs script that will often be run on a computer with one person logged in and run by an admin with a completely different user name (assume the file will be right clicked and "Run As"). The script edits an ini file that is located in the user directory for the person logged in. I know in batch I could simply insert the variable "C:\Users\%Logger%\AppData\Local\stat.ini" and the variable would be replaced. But I can't do this in .vbs. My script thus far. Or look at the bulk of it in an answer here. Dim blnRes: blnRes = 0 Dim strOld, strNew, logger strOld = "frogg" strNew = "frog" logger = Inputbox("What is your Domain ID exactly as entered when you log into this machine?","Domain ID") On Error Resume Next Call update("C:\Users\logger\AppData\Local\stat.ini", strOld, strNew) blnRes = blnRes Or (Err.Number = 0): Err.Clear Is there some way I can flag logger as a variable, or is there an easier way to do this? A: I guess you meant a script variable. Try this: logger = Inputbox("What is ID?","Domain ID") Call update("C:\Users\"& logger &"\AppData\Local\stat.ini", strOld, strNew) A: You can use command line arguments with vbs. See the following technet site: http://technet.microsoft.com/en-us/library/ee156618.aspx using the example vbs at the bottom, you can have Ping.vbs reply based on the computer name entered after the script name when its called (C:\scripts\Ping.vbs Hostname) Here's more info on WScript.Aurguments https://www.google.com/search?q=WScript.Arguments&sourceid=ie7&rls=com.microsoft:en-us:IE-Address&ie=&oe= 'Ping.vbs: Dim arArguments, strArgument Set arArguments = WScript.Arguments WScript.Echo WScript.Arguments.Count For Each strArgument in arArguments If Ping(strArgument) Then WScript.Echo strArgument & " is available." Else WScript.Echo strArgument & " is not available." End If Next Function Ping( myHostName ) Dim colPingResults, objPingResult, strQuery strQuery = "SELECT * FROM Win32_PingStatus WHERE Address = '" & myHostName & "'" Set colPingResults = GetObject("winmgmts://./root/cimv2").ExecQuery( strQuery ) For Each objPingResult In colPingResults If Not IsObject( objPingResult ) Then Ping = False ElseIf objPingResult.StatusCode = 0 Then Ping = True Else Ping = False End If Next Set colPingResults = Nothing End Function A: If I understand what you're after correctly, you're either going to need to do a string concatenation where you build a string like "string part 1" & logger & "string part 2" or use the replace function to replace %Logger% (e.g. Replace(templateString, "%Logger%", logger)) with your logger variable. There's not a direct equivalent to the %1 sort of format used in batch files. A: This worked for me: Dim fs, ws, Path Set ws = CreateObject( "WScript.Shell" ) Path = ws.ExpandEnvironmentStrings( "%UserProfile%\testfile.txt" ) ws = Nothing Set fs = CreateObject("Scripting.FileSystemObject") Set f = fs.CreateTextFile (Path, True) f.WriteLine("This is a test") f.Close() f = Nothing Don't assume "C:\Users" will be valid on every system. There are times when you may want to use a different location for user profiles. I also looked at the %AppData% environment variable, but in my case that pointed to AppData\Roaming, and you want AppData\Local.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I display all possible values in a SuggestBox I would like to display all possible values in a SuggestBox. Naturally, I have the following code (settingName is a SuggestBox) settingName.getTextBox().addFocusHandler(new FocusHandler() { @Override public void onFocus(FocusEvent event) { settingName.showSuggestionList(); } }); Unfortunately, the suggestbox displays anything. Of course, the settingName is associated to an oracle with several values inside it. Am I crazy ? According to the documentation : public void showSuggestionList() Show the current list of suggestions. A: You need to set the defaults to show by suggestOracle.setDefaultSuggestionsFromText(..) A: When showing the list, the SuggestBox will ask the oracle for values to show. If the text box is empty, then requestDefaultSuggestions will be called (which by default calls requestSuggestions).
{ "language": "en", "url": "https://stackoverflow.com/questions/7534463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Is the Facebook canvas tutorial missing something? Possible Duplicate: Why do I get an undefined index for signed_request in my facebook app? I posted a question on the regular SO that is very similar but then found the facebook SO. If I copy and paste this code from the facebook canvas tutorial page: <?php $app_id = "YOUR_APP_ID"; $canvas_page = "YOUR_CANVAS_PAGE_URL"; $auth_url = "http://www.facebook.com/dialog/oauth?client_id=" . $app_id . "&redirect_uri=" . urlencode($canvas_page); $signed_request = $_REQUEST["signed_request"]; list($encoded_sig, $payload) = explode('.', $signed_request, 2); $data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true); if (empty($data["user_id"])) { echo("<script> top.location.href='" . $auth_url . "'</script>"); } else { echo ("Welcome User: " . $data["user_id"]); } ?> How can I ever get the signed_request if the $auth_url is never called? Or maybe I don't understand PHP. It creates the $auth_url but never goes and gets it, so $signed_request is never populated. What am I doing wrong? EDIT: It is because I am stupid and was not accessing it via apps.facebook.com and instead going to http://mydomain.com... A: The key bit is here: if (empty($data["user_id"])) { echo("<script> top.location.href='" . $auth_url . "'</script>"); That creates a script element that that directs the browser to load the auth_url if the user session is empty. A: Are you sure you're browser isn't blocking that "top.location.href" javascript call? Try just echo/writeln the $auth_url for further inspection. If you could show us the "$auth_url" that it's retunring, that would/might help :) A: The '$auth_url' is only used to redirect the user in case he/she hasn't given permissions to your application. The '$signed_request' is an encrypted data sent by facebook, the variable '$data' contains all this data decrypted as an associative array. You don't need to care about '$signed_request' what you really need is in the '$data' variable which contains the user info that you probably will need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Filtering a data frame I have read in a csv file in matrix form (having m rows and n columns). I want to filter the matrix by conducting a filter in verbal form: Select all values from column x where the values of an another column in this row is equal to "blabla". It is like a select statement in database where I say I am interested in a subset of the matrix where these constraints need to be satisfied. How can I do it in r? I have the data as dataframe and can access it by the headers. data["column_values" = "15"] does not give me back the rows where the column named column_values have values 15 only. Thanks A: First, note that a matrix and a data.frame are different things in R. I imagine you have a data.frame (as that is what is returned by read.csv()). data.frame's have named columns (if you don't give them ones, generic ones are created for you). You can subset a data.frame by indicating both what rows you want and/or what columns you want. The easiest way to specify which rows is with a logical vector, often built out of comparisons using specific columns of the data.frame. For example data[["column values"]] == "15" would make a logical vector which is TRUE if the corresponding entry in the column column values is the string "15" (since it is in quotes, it is a string, not a number). You can make as complicated a selection criteria as you like (combining logical vectors with & and |) to specify the rows you want. This vector becomes the first argument in the indexing. A list of column names or numbers can be the second argument. If either argument is missing, all rows (or columns) are assumed. Putting this all together, you get examples like data[data[["column values"]] == "15", ] or using an actual data set (mtcars) mtcars[mtcars$am == 1, ] mtcars[mtcars$am == 1 & mtcars$hp > 100, "mpg"] mtcars[mtcars$am == 1 & mtcars$hp > 100, "mpg", drop=FALSE] mtcars[mtcars$hp > 100, c("mpg", "carb")] Take a look at what each of the conditionals (first arguments, e.g. mtcars$am == 1 & mtcars$hp > 100) return to get a better sense of how indexing works. A: You said you just wanted the column x values where column_values was 15, right? subset(dat, column_values==15, select=x) I think this may come as a dataframe so it's possble you may need to unlist() it and maybe even "unfactor" it. > dat Subject Product 1 1 ProdA 2 1 ProdB 3 1 ProdC 4 2 ProdB 5 2 ProdC 6 2 ProdD 7 3 ProdA 8 3 ProdB > subset(dat, Subject==2, Product) Product 4 ProdB 5 ProdC 6 ProdD > unlist( subset(dat, Subject==2, Product) ) Product1 Product2 Product3 ProdB ProdC ProdD Levels: ProdA ProdB ProdC ProdD > as.character( unlist( subset(dat, Subject==2, Product) ) ) [1] "ProdB" "ProdC" "ProdD" If you want all of the columns you can drop the third argument (the select= argument): subset(dat, Subject==2 ) Subject Product 4 2 ProdB 5 2 ProdC 6 2 ProdD A: Assuming that dat is the data frame in question, col is the name of the column and "value" is the value that you want, you can do dat[dat$col=="value",] That fetches all of the rows of dat for which dat$col=="value", and all of the columns.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Dropdown list filled from repository I have an MVC3 drop down list that come from this code on the controller. private SelectList progCodesList = new SelectList(new[] { "Description", "Requirements", "Development", "Testing", "Documentation" }); How can I fill the fields from a repository, to build the drop down dynamically? Thanks. A: Assuming you have the progCodes in a database table, with progCode having the text, and progCodeId with a unique id, then you can read the table into a list of SelectListItem as follows: private DbContext _db = new DbContext(); var progCodesList = _db.progCodes.Select(x => new SelectListIem() { Text = x.progCode, value = x.progCodeId }).ToList(); You can then pass this List<SelectListItem> to your view either in a strongly-typed model, or using the ViewBag. A: You need to pass the progCodesList to the ViewBag in your controller method using something like: ViewBag.ProgCodeId = progCodesList; Then in your view, you need to fill the drop down like this: <div class="editor-label"> @Html.LabelFor(model => model.ProgCodeId, "ProgCode") </div> <div class="editor-field"> @Html.DropDownList("ProgCodeId", String.Empty) @Html.ValidationMessageFor(model => model.ProgCodeId) </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7534470", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL table view (Visual Studio or...) Is there any way to read .SQL document in table view in VisualStudio or any other program? A: .sql quite simply contains a set of executable SQL instructions. ( described here ) The instructions are in plain-text and are can be viewed with any text editor (i.e. notepad). Based on the way your question is phrased, I assume you have instructions to create a table in SQL which you would like to view in a more user-friendly way. The best way I can think of to do this (although I am not extensively familiar with Visual Studio), is to set up a test sql environment (on localhost/a testing server - XAMPP comes to mind). Then open up phpmyadmin (or another database manager, although phpmyadmin is packaged with xampp) and run your code... and, if teh code is not your own, obviously look for sql injections ;) .
{ "language": "en", "url": "https://stackoverflow.com/questions/7534471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to clone A: I need to see "alfa_1" when I click in the cloned Text, but nothing happens. Doing DOM or innerHTML manipulations on <script> elements is inconsistent in browsers and doesn't really make any sense in terms of the JavaScript execution cycle. Avoid it in all cases. If you want to copy DOM elements together with their jQuery event handlers, use clone(true): <div id="alfa">Text</div> <script type="text/javascript"> $('#alfa').click(function() { alert(this.id); }); var clone= $('#alfa').clone(true); clone[0].id+= '_1'; // sorry, I couldn't bring myself to do this the jQuery way $('#alfa').after(clone); </script> A: The alert for the original div is triggered twice because the script is defined inside the div. Move the script out of the div and it should work as expected: <div id="alfa">Text</div> <script> $("#alfa").click(function() { alert($(this).attr("id")); }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7534476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Copy LIne in qt shortcut I have been searching a lot on this but of no use. Is there any shortcut to copy an entire line with a keyboard shortcut in QT creator? I have seen shortcut for cutting a line but that's not what i want.. A: Set cursor to the line you want copy and press Command+Alt+Down or Command+Alt+Up That's it! You can also move a line: Mark the line you want to move and press Command+Shift+Down or Command+Shift+Up Cheers! ps: clearly they are shortcuts for mac! pps: see also https://wiki.qt.io/Qt_Creator_Keyboard_Shortcuts A: The shortcut list is user configurable in Tools menu -> Options -> Environment -> Keyboard. And the default shortcut to copy a line is Ctrl + Ins.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534477", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: How to use Google Analytics API with 2-legged OAuth (Google Apps for business)? I want to develop an application for the business I work. We are using Google Apps and want to get data from Google Analytics and show it in one of our web apps. I do not want the client to see any request to authorize the app. I want to use 2-legged OAuth like such http://www.google.com/support/a/bin/answer.py?hl=en&answer=162105 but Google Analytics is not in the list. Will I still be able to use it ? Is it supported in the .NET Google Data API library or the Google API .NET Client ? EDIT 1 : Using the Google API .NET Client, I came up with something that should work to my sense : var auth = new Google.Apis.Authentication.OAuth2LeggedAuthenticator(DOMAIN_CONSUMER_KEY, DOMAIN_CONSUMER_SECRET, USER_TO_IMPERSONATE, DOMAIN); var service = new Google.Apis.Analytics.v3.AnalyticsService(auth); service.Key = DEV_KEY_FROM_API_CONSOLE; var _request = service.Management.Accounts.List(); foreach (var item in _request.Fetch().Items) { Console.WriteLine(item.Name); } ... but I get this error : Google.Apis.Requests.RequestError InvalidCredentials [401] Errors [ Message[Invalid Credentials] Location[Authorization - header] Reason[authError] Domain[global] ] Thanks A: This blog post explains step by step how to implement a 2 legged authentication with the Google API .Net client. http://bittwiddlers.org/?p=212#awp::?p=212 However, the author ends his post by this comment: The above information specific to the google-api-dotnet-client project is relevant, but that library leaks memory like a sieve and will kill your performance if you try to do any asynchronous work or use 2LO (on behalf of multiple users). Good luck and let me know if you figured out a better solution, I'm a bit sick of the issue... A: I have answered a similar question here. That answers how to fix a couple of problems that will cause 401 Invalid Credentials and may help you get the v3 version of the .Net APIs working. I'm just adding this here as your solution uses the deprecated v2 API to circumvent the problem you were having with authentication. A: I found a method using .NET library for the Google Data API. I found this link thanks to this guy. Here is a working code that lists all Analytics accounts, considering that GOOGLE_APPS_DOMAIN_SECRET is the key generate using this method, the DOMAIN is the domain of the Google Apps, and username is the prefix (ex. : "firstname.lastname") of the email from the Google Apps user we want to impersonate (the admin for example, to have access to everything) : var requestFactory = new GOAuthRequestFactory("an", "Any app name"); requestFactory.ConsumerKey = DOMAIN; requestFactory.ConsumerSecret = GOOGLE_APPS_DOMAIN_SECRET; var service = new AnalyticsService("Any app name"); service.RequestFactory = requestFactory; var query = new AccountQuery(); query.OAuthRequestorId = username + "@" + DOMAIN; var serviceQuery = service.Query(query); foreach (AccountEntry Entry in serviceQuery.Entries) { WriteLine(Entry.Title.Text); } The only problem, is that I have to impersonate a user, and cannot simply have access to everything. EDIT: Method deprecated
{ "language": "en", "url": "https://stackoverflow.com/questions/7534480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to avoid stack overflow in Haskell? Haskell does not support cycling for computation, instead it offers to use recursion algorithms. But this approach leads to growing of stack, and even stack overflow. I believe there should be approach to solve this problem in general. Here is the sample. I wanted to know, how many times getClockTime may be called per 5 seconds: import System.Time nSeconds = 5 main = do initTime <- totalPicoSeconds `fmap` getClockTime doWork initTime 1 where doWork initTime n = do currTime <- totalPicoSeconds `fmap` getClockTime if (currTime - initTime) `div` 10 ^ 12 >= nSeconds then print n else doWork initTime (n+1) totalPicoSeconds :: ClockTime -> Integer totalPicoSeconds (TOD a b) = a * 10 ^ 12 + b The program goes 5 seconds, but eventually I'm getting: Stack space overflow: current size 8388608 bytes. Use `+RTS -Ksize -RTS' to increase it. Manual management of stack size may help in particular case, but if I would wish to run this algo for 10 seconds, it may overflow again. So this is not a solution. How can I get this code working? A: The problem here is not the recursion, but the laziness of your n argument. Stack overflows in Haskell come from trying to evaluate deeply-nested thunks; in your case, each call to doWork initTime (n+1) is making a slightly-deeperly-nested thunk in the second argument. Simply make it strict, and things should be happy again: doWork initTime $! n+1.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Actionscript 3 - Calling onLoadProgress function from inside another function I have an AS3 function that loads and audio file and then plays it. I have the pre-loader for the first audio file working - now I need to run the pre-load function before the 2nd audio file starts. myMusic.addEventListener(ProgressEvent.PROGRESS, onLoadProgress2, false,0, true); myMusic.addEventListener(Event.COMPLETE, playMusicNow, false, 0,true); myMusic.load(soundFile, myContext); //This code works Here is the play code: //This code doesn't work function receiveText1(value:String):void { channel.stop(); channel2.stop(); songPosition = 0; soundFile2 = new URLRequest(jsVariableValue1); myMusic2= new Sound(); //Intstantation myMusic2.load(soundFile2, myContext); //need to run preloader here soundFile2exist = null; } Here is my event listener and preloader: myMusic2.addEventListener(ProgressEvent.PROGRESS, onLoadProgress, false,0, true); myMusic2.addEventListener(Event.COMPLETE, playMusicNow, false, 0,true); function onLoadProgress(evt:ProgressEvent):void { progBar.alpha = .70; prcLoaded.alpha = .70; var pcent:Number=evt.bytesLoaded/evt.bytesTotal*100; prcLoaded.text =int(pcent)+"%"; progBar.width = 90 * (evt.bytesLoaded / evt.bytesTotal); } I thought I could call onLoadProgress(evt:ProgressEvent); from within the function, but I'm getting an error 1084: Syntax error: expecting rightparen before colon. A: why you want to call manually the "onLoadProgress" ? It should be executed automatically (if your file is not cached, and you are adding the listener correctly I see your addEventListener in your question, but you are not showing where/when you are adding this listener. Anyway, if you want to execute your onLoadProgress you should do something like this: var bytesLoaded:uint = 50; var bytesTotal:uint = 100; var evt:ProgressEvent = new ProgressEvent( ProgressEvent.PROGRESS, false, false, bytesLoaded, bytesTotal); onLoadProgress(evt); You must note that you need to create a "fake" Progress event, and assign fakes bytesLoaded and bytesTotal values. And even knowing that the onLoadProgress will be executed just once. And I'm sure that is not what you want. Please explain better what are you trying to do. A: I added the event listeners inside the function and all is right now.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to serialize HashTable to XML using JAXB? I am trying to use JAXB to serialize a HashTable<String, String> to XML. I am very new to Java (came from C#), so I am kinda perplexed by this task. I have seen the following code: public static <T> String ObjectToXml(T object, Class<T> classType) throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(classType); StringWriter writerTo = new StringWriter(); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(object, writerTo); //create xml string from the input object return writerTo.toString(); } Which is invoked like so: ObjectToXml(o, ClassOfO.class), but HashTable<String, String>.class is wrong (that I already know). Can Java gurus out there show me how to invoke this code? Proposing a simpler implementation (along with an invocation example, of course) is most welcome as well. Thanks. A: You will need to create a wrapper class to hold onto the Hashtable: package forum7534500; import java.util.Hashtable; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Wrapper { private Hashtable<String, String> hashtable; public Hashtable<String, String> getHashtable() { return hashtable; } public void setHashtable(Hashtable<String, String> hashtable) { this.hashtable = hashtable; } } Then you can do the following: package forum7534500; import java.io.StringWriter; import java.util.Hashtable; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Wrapper.class); Wrapper wrapper = new Wrapper(); Hashtable<String, String> hashtable = new Hashtable<String,String>(); hashtable.put("foo", "A"); hashtable.put("bar", "B"); wrapper.setHashtable(hashtable); System.out.println(objectToXml(jc, wrapper)); } public static String objectToXml(JAXBContext jaxbContext, Object object) throws JAXBException { StringWriter writerTo = new StringWriter(); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(object, writerTo); //create xml string from the input object return writerTo.toString(); } } This will produce the following output: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <wrapper> <hashtable> <entry> <key>bar</key> <value>B</value> </entry> <entry> <key>foo</key> <value>A</value> </entry> </hashtable> </wrapper> Things to Note * *JAXBContext is a thread-safe object and should be created once and reused. *Hashtable is synchronized, if you do not need this then using HashMap is the common replacement. *The convention is to start Java method names with a lower case letter. Customizing the Mapping You can use an XmlAdapter in JAXB to customize the mapping of any class. Below is an link to a post on my blog where I demonstrate how to do just that: * *http://blog.bdoughan.com/2010/07/xmladapter-jaxbs-secret-weapon.html A: Unfortunately, JAXB is not able to directly serialize a Map or HashMap instance directly. Instead, you'll have to do some sort of translation from a Map into a list of entries that have a key and a value. Try looking into this Stack Overflow question and see if it can help you. This problem shows up a lot in Google, and the sad answer is that JAXB doesn't know how to serialize a Map. A: Bah! If you had only googled on jaxb and hashmap you would have directly found this: http://download.oracle.com/javase/6/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html But, yes, I kind of agree that 'perplexion' is a good description of the feeling of the non-obviousness of the task. A: While you might be familiar with C# reified generics, Java's generics are for compile time only, they go away at runtime. That's why, at runtime, even if you have an instance with established generics (Such as String for HashTable) at runtime those generics go away, so all you can do is obtain the class of the thing (HashTable here) and not the actual generic types (String here). In short: compile time Hashtable<String,String> becomes HashTable at runtime (or, to be totally pedantic HashTable<?,?>) A: I think your best bet is to create an xml schema that reflects what you want and then run xjc on it. This way you have some control over what the xml will look like w/o getting into the guts of JaxB. http://download.oracle.com/docs/cd/E17802_01/webservices/webservices/docs/1.6/jaxb/xjc.html You can then translate your HashTable to the generated object and pass it to this variation of your static method. public static <T> String ObjectToXml(T object) throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass()); StringWriter writerTo = new StringWriter(); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(object, writerTo); return writerTo.toString(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7534500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Is STL Vector calling a destructor of a not-allocated object? The folowing code shows an output not expected: class test { public: test() { std::cout << "Created" << (long)this << std::endl; } ~test() { std::cout << "Destroyed" << (long)this << std::endl; } }; int main(int argc, char** argv) { std::vector<test> v; test t; v.push_back(t); return EXIT_SUCCESS; } When executed it shows: Created-1077942161 Destroyed-1077942161 Destroyed674242816 I think the second "Destroyed" output should not be there. When I don't use the vector the result is one Created and one Destroyed line as expected. Is this behavior normal? (This is compiled with GCC on a FreeBSD system) A: Everything is as it should be: there's the local variable t, which gets created and then destroyed at the end of main(), and there's v[0], which gets created and destroyed at the end of main(). You don't see the creation of v[0] because that happens by copy or move constructor, which your test class doesn't provide. (So the compiler provides one for you, but without output.) For testing purposes it's handy to write for yourself once and for all a test class that contains all the possible constructors, destructors, assignment and swap operators and prints a diagnostic line in each, so you can witness how objects behave when used in containers and algorithms. A: #include <cstdlib> #include <vector> #include <iostream> class test { public: test() { std::cout << "Created " << (long)this << std::endl; } test( const test& ) { std::cout << "Copied " << (long)this << std::endl; } ~test() { std::cout << "Destroyed " << (long)this << std::endl; } }; int main(int argc, char** argv) { std::vector<test> v; test t; v.push_back(t); return EXIT_SUCCESS; } Output: Created -1076546929 Copied 147865608 Destroyed -1076546929 Destroyed 147865608 std::vector::push_back copies the t object, you can see the copy constructor being invoked by the above code. A: The vector is holding a copy of t, therefore after the call to push_back, you have two versions of t ... one on the stack, and one in the vector. Since the vector version was created by a copy-construtor, you don't see a "Created ..." prompt for that object ... but it still must be destroyed when the vector container goes out of scope, therefore you get two "Destroyed ..." messages.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Disabling optimizations in an executable and maintaining them in a static library I've come across an odd situation and my (supposed) knowledge of code linkage is failing me... I have come across a bug that only occurs in a 64-bit build with optimizations turned on (/O2, /O3, or /Ox). The bug occurs in an executable that is not performance critical and we have to give a demo of a prototype very soon (i.e., Monday). Due to the extreme pressure to get this working for the demo, I had an idea; build the static library (which is performance critical) with optimizations on and turn them off in the executable. This should hide the bug until I fix it while not slowing down the system, or so I thought. I have now tried this with Link Time Code Generation off, as well as on, and no whole program optimization, but each time, with the VS2005 C++ compiler as well as when using Intel's compiler, the performance critical library is not being linked in with optimizations enabled and things slow down dramatically. Does anyone know how to accomplish what I am after here? This is an odd situation and I have never had to deal with it, but I did some reading and I couldn't find any documentation saying that what I am trying to accomplish isn't feasible, but apparently it is not or I am missing something. Thanks in advance for any help you guys can offer, I know this is an odd request for a dirty short term "fix", but it is rather important. A: Your problem is almost assuredly that critical inlining of functions in your library or the standard library is being disabled in the final application by turning off optimizations. A: I would guess that your non-optimized EXE is not actually being linked with the optimized static lib. If you know what function the optimization is borking, something you can do is use pragmas around that function to turn off optimizations just for it. #pragma optimize( "", off ) int f(int x ) { return x - 1; } #pragma optimize( "", on ) A: The statement "is not being linked in with optimizations enabled" is a bit confusing, as this should be impossible; the linker will link whatever the compiler generated. If you set the compiler flags properly when compiling the modules in the static library, then they should all be optimized. The problem might be that your static library is calling functions from the C++ library that are not optimized. There is nothing you can do about this, since the application and the library must both use the same C++ library or you will have much worse problems than you started with.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to make an array linkable that's using implode? My array displays properly but I would like for the link inside to display the current value of the array. Here is my code: foreach( $persons as $pid => $p) { echo '<a href="?tag=">' . implode( '</a>, <a href="?tag=">', $tags[ $p['id'] ]) . '</a>'; echo '<br /><br />'; } This is what I want to display: <a href="?tag=tag1">tag1</a>, <a href="?tag=tag2">tag2</a> UPDATE I got the answer elsewhere. Turns out it was pretty simple. Going to accept answer that's helped me improve on my code. $tags_arr = $tags[$p['id']]; foreach($tags_arr as $v){ $out[] = "<a href='?tag=$v'>$v</a>"; } A: use http_build_query — Generate URL-encoded query string SYNTAX : string http_build_query ( mixed $query_data [, string $numeric_prefix [, string $arg_separator [, int $enc_type = PHP_QUERY_RFC1738 ]]] ) Returns a URL-encoded string. <?php $data = array('foo'=>'bar', 'baz'=>'boom', 'cow'=>'milk', 'php'=>'hypertext processor'); echo http_build_query($data) . "\n"; echo http_build_query($data, '', '&amp;'); ?> The above example will output: foo=bar&baz=boom&cow=milk&php=hypertext+processor foo=bar&baz=boom&cow=milk&php=hypertext+processor A: I'm assuming $tags is an array itself, and you are attempting to write out each tag for each $p['id']. If I have it correct, don't use implode() for this. Instead use two foreach loops. foreach ($persons as $pid => $p) { foreach ($tags as $t) { echo "<a href='?tag={$t[$p['id']]}'>{$t[$p['id']]}</a>\n"; } } UPDATE I see some problems here: $persons[$row['id']]['title'] = $row['title']; $persons[$row['id']]['height'] = $row['height']; $persons[ $row['id'] ] = array( 'id' => $row['id'], 'tag' => $row['tag']); Above, you set the title and height array keys to $persons[$row['id']]. Following that though, you overwrite the whole $persons[$row['id']] with a new array(). Instead since you're keeping the same array keys you can simply use: $persons[$row['id']] = $row; Now where I believe the most serious problem is: $tags[ $row['id'] ][] = $row['tag']; By using the [] notation, you are appending $row['tag'] onto the $tags[ $row['id'] as an array element rather than setting its value to the tag. That's the reason you're getting Array(1) in place of the tag value. Instead use: $tags[$row['id']] = $row['tag'];
{ "language": "en", "url": "https://stackoverflow.com/questions/7534507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Set request attribute and then redirect to another app in a Spring Controller How can I set a request attribute and then redirect that to another app in a Spring Controller. Thanks! A: Please look at this answer, I think this is what are you looking for How to pass model attributes from one Spring MVC controller to another controller?
{ "language": "en", "url": "https://stackoverflow.com/questions/7534510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Gallery of TextViews, using styles etc I want to use Gallery as a horizontal menu so I've taken the code for the Gallery tutorial to use TextViews instead of ImageViews by using a String[] and changing the adapter's getView((...) method as follows... public View getView(int position, View convertView, ViewGroup parent) { TextView tv = new TextView(mContext); tv.setText(mMenuItems[position]); tv.setLayoutParams(new Gallery.LayoutParams(150, 100)); return tv; } The problem I have now is as shown in the image... As you can see, what should be the 'selected' TextView is 'greyed' (although I can select it) and the other items are 'highlighted and I'd like the reverse. So the question is what is Gallery doing to cause this and how do I override it? UI stuff is a weak point of mine (I'm learning gradually honest) but I think I need to define styles as explained here...Definining styles and I understand what's being explained but how do I get the Gallery to automatically apply the styles I define? Do I have to apply the styles the TextViews I return from the adapter's getView(...) method or can I apply them 'globally' to the Gallery somehow? A: You can leverage getSelectedItemPosition() to update the view accordingly but you'll need a reference to the Gallery view (mGallery below): public View getView(int position, View convertView, ViewGroup parent) { TextView tv = new TextView(mContext); tv.setText(mMenuItems[position]); tv.setLayoutParams(new Gallery.LayoutParams(150, 100)); if (position == mGallery.getSelectedItemPosition()) { // set tv properties to make it look selected } else { // set tv properties to make it look unselected } return tv; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7534512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using SQL Server Users and Roles as an authorization database for an intranet web application? I have a question that really feels like I should have an easy answer to, but for one reason or another I haven't been able to totally reason around it. I'm embarking on development of an ASP.NET MVC3 intranet application, and I'm currently working on designing authentication & authorization. We're forced to use basic authentication in our environment, and we use Active Directory, so the authorization part is generally taken care of. Unfortunately our role/user hierarchy in active directory doesn't mirror what I need for the roles in the application, so I'm going to have to define my own. I'm using SQL Server, so I was originally thinking of using stored procedures for all DML, and then creating roles and adding users in roles in SQL Server, and then controlling access to the stored procedures via those roles. I was also thinking I could query for those SQL Server database-level users & roles in order to use that as the source of authorization info in the application itself. That originally seemed like a great idea, but it doesn't seem like a popular one (for one, it seems the queries for that are a little long and messy for what they produce). Alternatively, would it be better to have the web app impersonate a user for all queries to the server, and then implement a user/role database with my own schema, and only authorize on the application side? It originally seemed that authorizing on both the application and database side would be a good thing for security, and using the SQL Server user/role objects means that the user and role data wouldn't need to be stored in two places. I did see some potentially relevant discussion at Best practice on users/roles on SQL Server for a web application, but I think this is a different question overall. Thanks! A: I recommend creating a sql login that the web application will use to connect to sql server. This way you are not impersonating any specific AD account which may get deleted, disabled in the future and can control the user strickly in SQL Server. I would then recommend implementing roles based authentication in your application. This will enable you to create users and roles that are custom to your application and then assign users to them. This way if a user tries to access a resource that their role is not allowed it will not do any work. Here is a demo app based on this principle http://www.codeproject.com/KB/web-security/rolesbasedauthentication.aspx.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Name-value pair list with duplicate names to JavaScript object For submitting the form data to the server from the AJAX call to bind Telerik MVC grid, we can set e.data in OnDataBinding event to a anonymous JavaScript object <script type="text/javascript"> function Grid_onDataBinding(e) { var categoryValue = "Beverages"; var priceValue = 3.14; // pass additional values by setting the "data" field of the event argument e.data = { // the key ("category") specifies the variable name of the action method which will contain the specified value category: categoryValue, price: priceValue }; } </script> To facilitate the model binding for Boolean, ASP.NET MVC generates checkboxes along with a hidden text field with the same name <input name="myCheckBox" class="check-box" id="myCheckBox" type="checkbox" CHECKED="checked" value="true"/> <input name="myCheckBox" type="hidden" value="false"/> and when these are submitted the data submitted is myCheckBox=true&MyCheckBox=false - when the checkbox is checked myCheckBox=false - when the checkbox is not checked For pages where there is no checkbox, the post data can be easily obtained by e.data = form.serializeObject() where serializeObject creates that object by looping thru all the form fields. How to construct that object in case of forms when there are checkboxes as described above? Basically how can a name-value pair list be represented in the object form when the names are allowed to be duplicate? e.data = { textBox1: "some value1", myCheckBox: true //, //myCheckBox: false // ??? }; The implementation of serializeObject creates an array for such form elements and those are submitted as myCheckBox[]=true&myCheckBox[]=false which breaks the model binding on the server side. A: You can select specific form subelements to serialize, rather than just serializing the entire form. This allows you to filter out the ones you don't want: $('form input:not([type=hidden])').serializeObject(); Edit: Per @amit_g's comment, you want the checkbox when it's checked or the hidden element when it's not. This requires a more complex filter than the :not selector: $('form input') .filter(function() { if ($(this).attr('type') == 'hidden') { // filter out those with checked checkboxes var name = $(this).attr('name'); return !$('form input[type=checkbox][name=' + name +']') .prop('checked'); } else { // include all other input return true; } }) .serializeObject(); See the working jsFiddle here: http://jsfiddle.net/nrabinowitz/nzmg7/4/ A: serializeObject uses serializeArray internally and serializeArray serializes only those elements that would be submitted actually. So using the following code, I have disabled the hidden fields corresponding to checkbox and added a change event to toggle the disbaled state on each hidden input. Since the inputs are disabled, they don't get serialized. The .serializeArray() method uses the standard W3C rules for successful controls to determine which elements it should include; in particular the element cannot be disabled and must contain a name attribute. No submit button value is serialized since the form was not submitted using a button. Data from file select elements is not serialized. $('form.form-class :checkbox').change(function () { enableDisableCorrespondingHiddenField($(this)); }); $('form.form-class :checkbox').each(function () { enableDisableCorrespondingHiddenField($(this)); }); enableDisableCorrespondingHiddenField(checkbox) { $(":hidden[name='" + checkbox.attr("name") + "']", checkbox.parent()).attr("disabled", checkbox.attr("checked")); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7534516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to view SQL Server Compact Edition 4 blob data in VS 2010 I have a SQL Server CE 4.0 table that has a text blob field (ntext). When I browse the data in VS 2010 SP1 the ntext field does not show any data. Is there any way to view the blob data in VS 2010? A: Ntext data is displayed as text using Show Table Data in VS 2010 SP1, but image data is displayed as "Binary Data". The SQL Server Compact Toolbox can display images with the "Edit Table Data" feature.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In SQL Server 2005, when does a Select query block Inserts or Updates to the same or other table(s)? In the past I always thought that select query would not blocks other insert sql. However, recently I wrote a query that takes a long time (more than 2 min) to select data from a table. During the select, a number of insert sql statements were timing out. If select blocks insert, what would be the solution way to prevent the timeout without causing dirty read? I have investigate option of using isolation snapshot, but currently I have no access to change the client's database to enable the “ALLOW_SNAPSHOT_ISOLATION”. Thanks A: When does a Select query block Inserts or Updates to the same or other table(s)? When it holds a lock on a resource that is mutually exclusive with one that the insert or update statement needs. Under readcommitted isolation level with no additional locking hints then the S locks taken out are typically released as soon as the data is read. For repeatable read or serializable however they will be held until the end of the transaction (statement for a single select not running in an explicit transaction). serializable will often take out range locks which will cause additional blocking over and above that caused by the holding of locks on the rows and pages actually read. A: READPAST might be what you're looking for - check out this article.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: UNIX shell script while loop I am trying to write a script to track the progress of file change. I have the following till now: #!/bin/sh old=‘ls -l /tmp/file‘ new=‘ls -l /tmp/file‘ while [ "$old" = "$new" ] do new=‘ls -l /tmp/file‘ done echo "The file has been changed" The above program when run gives the message: new: command not found Can someone please help. Thanks A: You probably have space around =. In shell, when you assign the values you cannot put space around =: MY_VAR = "my value" # this is wrong! Shell will think: "call MY_VAR with arguments: ('=', 'my value') ", but wait! I don't know the command "MY_VAR"! You need to do it this way: MY_VAR="my value" # this is OK! BTW, consider using inotifywatch command. Here's example: inotifywatch -v -e access -e modify -t 60 -r /file/to/watch
{ "language": "en", "url": "https://stackoverflow.com/questions/7534527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Spring MVC annotated controller in groovy I have this in src/main/groovy/... package com.mycompany.web; // imports.... @Controller class GroovyController { @RequestMapping("/status_groovy") public @ResponseBody String getStatus() { return "Hello World from groovy!"; } } Using maven 3 and spring 3.1 (Milestone). Spring MVC works perfectly well for java controllers and everything is set up fine. The groovy class compiles fine and can be found in the classes directory along with the java controller classes. I have similar controller written in java (JavaController) in same package but under src/main/java and its getting picked up properly by spring and mapped and I can see the response on screen when I hit the url. package com.mycompany.web; // imports.... @Controller class JavaController { @RequestMapping("/status") public @ResponseBody String getStatus() { return "Hello World!"; } } Jetty starts normally with no error in log but in I dont see groovy url getting mapped whereas i can see the java one. 2011-09-23 16:05:50,412 [main] INFO org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/status],methods=[],params=[],headers=[],consumes=[],produces=[]}" onto public java.lang.String com.mycompany.web.JavaController.getStatus() All the setting are fine as other parts of app are working just fine with annotations (component-scan etc.), Just that I can not get the url mapped in GroovyController Can anyone explain what needs to be done in order to get Controllers written in groovy working? PS: I am avoiding GroovyServlet to run the scripts because it has major downside when it comes to bean injection and url path mappings. A: With all due respect to Ben (whom I work with), the problem here isn't that Spring is creating a cglib proxy. Rather, it's creating a dynamic JDK (or interface-based) proxy. This method of creating proxies can only implement methods declared in the target's implemented interfaces. You actually want Spring to create a cglib proxy, which creates a proxy that is a subclass of the target object and can therefore recreate all of its public methods. Unless you specify otherwise, Spring will create a cglib proxy if the target object doesn't implement any interfaces, and an interface-based proxy otherwise. Since all Groovy objects implement GroovyObject, you're getting an interface-based proxy, even though you didn't explicitly implement any interfaces in your Groovy controller. Ben's solution is correct in that if you create an interface with all your controller methods, you'll get the expected behavior. An alternative is to create a BeanFactoryPostProcessor which instructs Spring to create cglib proxies for classes that implement GroovyObject and only GroovyObject. Here's the code: /** * Finds all objects in the bean factory that implement GroovyObject and only GroovyObject, and sets the * AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE value to true. This will, in the case when a proxy * is necessary, force the creation of a CGLIB subclass proxy, rather than a dynamic JDK proxy, which * would create a useless proxy that only implements the methods of GroovyObject. * * @author caleb */ public class GroovyObjectTargetClassPreservingBeanFactoryPostProcessor implements BeanFactoryPostProcessor { private static final Logger logger = LoggerFactory.getLogger(GroovyObjectTargetClassPreservingBeanFactoryPostProcessor.class); @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { for (String beanDefName : beanFactory.getBeanDefinitionNames()) { BeanDefinition bd = beanFactory.getBeanDefinition(beanDefName); //ignore abstract definitions (parent beans) if (bd.isAbstract()) continue; String className = bd.getBeanClassName(); //ignore definitions with null class names if (className == null) continue; Class<?> beanClass; try { beanClass = ClassUtils.forName(className, beanFactory.getBeanClassLoader()); } catch (ClassNotFoundException e) { throw new CannotLoadBeanClassException(bd.getResourceDescription(), beanDefName, bd.getBeanClassName(), e); } catch (LinkageError e) { throw new CannotLoadBeanClassException(bd.getResourceDescription(), beanDefName, bd.getBeanClassName(), e); } Class<?>[] interfaces = beanClass.getInterfaces(); if (interfaces.length == 1 && interfaces[0] == GroovyObject.class) { logger.debug("Setting attribute {} to true for bean {}", AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, beanDefName); bd.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, true); } } } } Just include a bean of this type in your context, and voila! You can have Groovy controllers without needing to define interfaces. A: I beg to differ. There is no need to implement an interface. The problem here is that the default AnnotationMethodHandlerAdapter does not read annotations from proxies. Hence we would have to create this proxy aware AnnotationMethodHandlerAdapter which extends the default AnnotationMethodHandlerAdapter of spring. We also need to instantiate a bean for this ProxyAwareAnnotationMethodHandlerAdapter in the Spring Configuration xml file. Note: This feature is not available in Spring 3.x but since spring 4.0 would support groovy beans, this feature should be covered. //ProxyAwareAnnotationMethodHandlerAdapter.java package name.assafberg.spring; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.aop.TargetSource; import org.springframework.aop.framework.Advised; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter; /** * Add proxy awareness to <code>AnnotationMethodHandlerAdapter</code>. * * @author assaf */ public class ProxyAwareAnnotationMethodHandlerAdapter extends AnnotationMethodHandlerAdapter { /** * @param request * @param response * @param handler * @return * @throws Exception * @see org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#handle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object) */ @Override public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { handler = unwrapHandler(handler); return super.handle(request, response, handler); } /** * @param handler * @return * @see org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#supports(java.lang.Object) */ @Override public boolean supports(Object handler) { handler = unwrapHandler(handler); return super.supports(handler); } /** * Attempt to unwrap the given handler in case it is an AOP proxy * * @param handler * @return Object */ private Object unwrapHandler(Object handler) { if (handler instanceof Advised) { try { TargetSource targetSource = ((Advised) handler).getTargetSource(); return targetSource.getTarget(); } catch (Exception x) { throw new RuntimeException(x); } } else { return handler; } } } The spring configuration XML file must have the following. Instead of creating a bean of AnnotationMethodHandlerAdapter we must create a ProxyAwareAnnotationMethodHandlerAdapter bean. <beans ......... ... ... <bean class="full.qualified.name.of.ProxyAwareAnnotationMethodHandlerAdapter" /> ... ... <lang:groovy script-source="classpath:com/example/mysample.groovy refresh-check-delay="1000" /> </beans> Also Spring parses the configuration XML file using a SAX parser (based on event occurence). So, in order for spring to understand the annotations within the groovy scripts, the groovy beans (using tag) must be created after the ProxyAwareAnnotationMethodHandlerAdapter. Hope than helps Reference: http://forum.springsource.org/showthread.php?47271-Groovy-Controller A: Unfortunately, if you want to get this running in Groovy you'll have to create an interface for your Controller class and annotate the method definitions as well. Spring creates a proxy for your class using Cglib. However, without creating a custom interface for your controller Spring is proxying on groovy.lang.GroovyObject because all Groovy objects implement that interface by default. interface GroovyControllerInterface { @RequestMapping("/status_groovy") @ResponseBody String getStatus() } @Controller class GroovyController implements GroovyControllerInterface { @RequestMapping("/status_groovy") public @ResponseBody String getStatus() { return "Hello World from groovy!"; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7534529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Amazon Mechanical Turk task retrieval API I'm writing an app wherein the premise is that people who can't directly fund a charity out of their pocket could automatically work on Amazon AWS HITs in order to bring clean water to the 3rd world - I'd known there was an Amazon AWS API but is very unclear on how to retrieve a HIT to be worked on, rather than just consume some data about some tasks I'm trying to complete. Is there any way to retrieve a HIT to be worked on through the AWS API or otherwise? Thanks ahead of time. A: As far as I know, the only way to work on a HIT is through the mTurk website. i.e. - not via API. There is a site that is trying to do something very similar to what you have described. http://www.sparked.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/7534532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating a Wizard using MVC 2 Does anyone have any go example I could follow to create wizard in MVC 2? When using old ASP.Net you had server controls where you could other controls, and based upon how a user went through the steps you could add other steps dynamically or show other controls dynamically. Basically, all I am trying to do is to create a wizard where based upon what answers are gain, add some other questions (controls) dynamically, and at the end of the wizard to show a table of results. Are there any good examples out there? A: If you have ASP.NET MVC2 book by Steven Sanderson great guide starts from page 477 otherwise: nice tutorial with loads of text to read about is here (just formating is in mvc2) but from there you get the picture http://afana.me/post/create-wizard-in-aspnet-mvc-3.aspx Also nice part from Steven is partial vatidation, as you will need it for validation: http://blog.stevensanderson.com/2010/02/19/partial-validation-in-aspnet-mvc-2/ here is another sample of the guide: http://thedotnetninja.com/index.php/2011/05/multi-step-wizard-with-asp-net-mvc-the-wizardcontroller/
{ "language": "en", "url": "https://stackoverflow.com/questions/7534533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: using mipmaps with ETC1 textures Ive modified my code to use ETC1 textures to help lower memory usage and while the texture loads, its not automatically generating mipmaps anymore. Is this not supported for ETC1 images? Heres my code: //Generate three texture pointers... gl.glGenTextures(3, textures, 0); //...and bind it to our array gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]); //Create Nearest Filtered Texture gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); // gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR_MIPMAP_NEAREST); //problem child gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); //gl.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_GENERATE_MIPMAP, GL11.GL_TRUE); problem child. gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); //Get the texture from the Android resource directory Log.e("Sys", "ETC1 texture support: " + ETC1Util.isETC1Supported()); InputStream input = context.getResources().openRawResource(R.drawable.testtile); try { ETC1Util.loadTexture(GLES10.GL_TEXTURE_2D, 0, 0, GLES10.GL_RGB, GLES10.GL_UNSIGNED_SHORT_5_6_5, input); Log.w("sys", "loaded!"); } catch (IOException e) { Log.w("sys", "Could not load texture: " + e); } finally { try { input.close(); } catch (IOException e) { // ignore exception thrown from close. } } A: An easy way to solve this is to generate the mipmap levels with the tool you use to create your ETC1 texture (all the levels will end up in the file (eg .pvr)) and to upload each level individually. A: Use this tool : http://www.malideveloper.com/developer-resources/tools/texture-compression-tool.php The one from the Android SDK ( etc1tool ) will not generate mipmaps automatically. The mali tool can even batch convert textures to etc1/etc2 .
{ "language": "en", "url": "https://stackoverflow.com/questions/7534535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I get only one row from a list of items in SQL Server? I've got a non-normalized sales database like this: Invoice Item Price Total_Sale ------- ---- ----- ---------- 565 Nails 1.25 6.25 565 Hammer 5.00 6.25 566 Paint 7.95 7.95 ... As you can see, the "total_sale" is repeated for each line item in the invoice. Invoice #565 has two items, for a total of $6.25. Invoice #566 only has one item, the total is $7.95. The sum(total_sale) for both invoices should be $14.20. Q: Is there any easy way to get all the columns* for just one row for each different invoice? Regardless if the invoice has one, two or one hundred line items? A: Q: Is there any easy way to get all the columns* for just one row for each different invoice? WITH T AS ( SELECT Invoice, Item, Price, Total_Sale, ROW_NUMBER() OVER (PARTITION BY Invoice ORDER BY (SELECT 0)) AS RN FROM YourTable ) SELECT Invoice, Item, Price, Total_Sale FROM T WHERE RN=1; A: A simple query would be: Select SUM(Price), Invoice, Total_Sale From InvoicesTable Group By Invoice, Total_Sale Order By Invoice The item column cannot be included as the group by would yield multiple rows.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I fix this javascript conflict mess (jquery + prototype + google visualization + PRADO php)? I have a webapp relatively old running on Prado 2.1RC1 and I am trying to enhance it by adding some nice google visualizations charts. The problem arose at the moment of integrating google jsapi (that depends on jquery) and the old libraries used by prado2.1. Prado use some built-in libraries (some of them are base.js, dom.js, ajax.js, etc) + prototype 1.4. In a first moment when I tried to integrate the tutorial example I got two errors logged in the chrome javascript console. Uncaught RangeError: Invalid array length on base.js:524 Uncaught TypeError: undefined is not a function Looking at base.js I found out that those errores where caused by a prototype bug in shift function (I think) because shift is implemented like this: shift function() { var result = this[0]; for (var i = 0; i < this.length - 1; i++) this[i] = this[i + 1]; this.length--; return result; } But when this.length==0, this.length-- explodes. So after fixing this bug I had the hope that google nice charts will show up... But no. No error was thrown in javascript console but I got this text rendered with red background in the div where google chart should be appended: number is not a function I have no clue on this error. I suspect that there is some mess with the great quantity of javascript libraries required by the webapp. I know that the situation is not really good considering I am using a old, deprecated, non-supported version of Prado and Prototype. But I am very n00b with php and with this framework. I don't really know how much time would take to me to migrate to a new Prado version of to update the javascript libraries and I even know if I am able to do this. Maybe some of you with more experience could tell me what are the best things to do in this situation or how should I proceed... Thanks!! And let me know if you need more details in the problem. A: I'm not sure if this is exactly your problem, but from what I understand, it seems that you noticed issues when you tried to integrate jquery/google jsapi into your project. You shouldn't need jquery to this, and can load the jsapi (and necessary visualization packages) directly. These should be namespaced (like google.x.y) and not interfering with your other code - though I may be mistaken about how this may mess things up. Here's how you can load the jsapi without jquery: <script type="text/javascript" src="http://www.google.com/jsapi"></script> <script type="text/javascript"> google.load('visualization', '1', {packages: ['table']}); </script> Is that the issue? A: Since Prado is using Prototype and the "$" is used by both Prototype and jQuery make sure you explicitly write (jQuery)(#selector) instead of $(#selector). It might be the root cause of your problem. A: I had a template powered by jQuery and I used it as Layout ( Master page ) for my project. I avoided conflicts between prototype and jQuery when I replaced all $("selector") with jQuery("selector"). A: I beleive that it maybe better to not use the jquery wrapper of the google api. This is because there is a conflict between jQuery and prototype both using $. If you still must use jQuery you need to call jQuery.noConflict() to tell jQuery to not assign $ as the global pointer to jquery After the prototype.js is included u need to include jquery and call noConflict(). <script src="jquery.js"></script> <script> jQuery.noConflict(); </script> It should be put after com:TForm. because TForm adds the prototype.js link to the page. Then include the google jquery wrapper. now "$" points to prototype and "jQuery" points to jQuery Explained on the JQuery site here
{ "language": "en", "url": "https://stackoverflow.com/questions/7534540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: String.replace with / and \ in Nodejs different than in Chrome? I'm trying to make a router in Nodejs. A big part of that is URI -> action, so I'll need an easy configurable list of URI's and regexping them to regexps to match against the request URI. Simple! I've done this in PHP a million times. Give or take. So this is what I do (to test): > uri = '/users/#/status/*' > uri.replace(/\//g, '\\/').replace(/#/g, '(\d+)').replace(/\*/g, '([^/]+)') What I'm doing is 1) escaping / and 2) replacing # with a \d+ and 3) replacing * with a [^/]+ In Chrome this works as expected: < \/users\/(d+)\/status\/([^/]+) Escaped / and replaced # and * correctly. This is V8. In Nodejs: < \\/users\\/(d+)\\/status\\/([^/]+) Que!? Every / is doubly escaped? I either get a doubly escaped / or a not escaped /. The regex is right, right? I'm using Chrome 15 dev (V8 javascript) and Node 0.5.8 dev (V8 javascript). What's going on here? Potentially interesting If I test /^\/users\/(\d+)\/status\/([^/]+)/.test('/users/1/status/x') it returns true in both Chrome and Node. A: This is due to a difference in the way the Node REPL differs from the Chrome console. When you run the command in Node, you're getting a peek at the escaped string (including the "invisible" escape characters), but when you see it in Chrome, it's the actual string evaluated, with the escape characters removed. They're the same strings, but Chrome is trying to "prettify" it for you. In fact, if you copy and paste the string you got from Node into the Chrome (or even a FF Firebug) console, you'll get a string with the single escapes. If you copy and paste it in again, it'll remove the next level of escapes characters. Chrome console: > "\\/users\\/(d+)\\/status\\/([^/]+)" "\/users\/(d+)\/status\/([^/]+)" > "\/users\/(d+)\/status\/([^/]+)" "/users/(d+)/status/([^/]+)"
{ "language": "en", "url": "https://stackoverflow.com/questions/7534541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: serialport communication .net 4.0 from a webpage Looking for serial port communication using ASP.NET 4.0. I have a cardwriter/reader from IDTECH which talks through a comport. Is there any way to accomplish with .net through the web. I read things but most of the topics on speaking about .net 2.0 and I was not sure if they created something to handle this in .net 4.0 Thanks A: Anything written for .net 2 should work in .net 4 with some changes that occur between revisions. However, using the serial port from asp.net will not work on most servers as the user that the asp.net process is using won't have permission to access the hardware. The only way around this would be to build the portion of the process that talks with the card reader/writer as a Windows service and add some method of communicating to the service from your asp.net application (TCP connection or something similar). A: The only way this is possible is via a browser plugin. This has nothing to do with .NET (unless that's what you use to write your browser plugin). Everything you see about issues with the .NET serial port control are referring to desktop applications. As a side note, most of the issues have been resolved in .NET 4.0, but not all. I've given up and now use CommStudio, which is available as an ActiveX control, so you may be able to access its methods from a web page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trying to get a string concatenated in Linq2Entities query I am trying to create a Dictionary<string, string> from the combined results of two string fields in an entity. I am using this dictionary to populate a drop down list. For this particular case, both the key and value are the same. Here is the query I have so far: var qry = ( from x in db.Treatment_Type select new { TreatmentCode = x.Project_Classification + ":" + x.Improvement_Type }) .AsEnumerable() .ToDictionary<string, string>(x => x); I am trying to concatenate the Project_Classification and Improvement_Type values into one value. It is coming back as an anonymous type, instead of a string, so I get errors about how the dictionary can't infer the types from the anonymous type and advising me to explicitly state the type. When I do that, I get errors that anonymous types can't be converted to string. How can I accomplish this? A: Why don't you just get rid of it being an anonymous type? That's not helping you: var qry = (from x in db.Treatment_Type select x.Project_Classification + ":" + x.Improvement_Type) .AsEnumerable() .ToDictionary<string, string>(x => x); Only use anonymous types when you actually get some benefit from it :) The same applies to query expressions - in this case I'd use: var qry = db.Treatment_Type .Select(x => x.Project_Classification + ":" + x.Improvement_Type) .AsEnumerable() .ToDictionary<string, string>(x => x); A: var qry = (from x in db.Treatment_Type select new { TreatmentCode = x.Project_Classification + ":" + x.Improvement_Type }).AsEnumerable().ToDictionary<string, string>(x => x); It's coming back as an anonymous type because you are using anonymous type annotation. which is. new {//some stuff} A: Try var qry = (from x in db.Treatment_Type select x.Project_Classification + ":" + x.Improvement_Type ).ToDictionary<string, string>(x => x); A: Try to change this ToDictionary<string, string>(x => x); into this ToDictionary(x => x, x => x); And i'm guessing that this two "Project_Classification" and "Improvement_Type" values are string Types.
{ "language": "en", "url": "https://stackoverflow.com/questions/7534543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: getting value first offset name after click? How can get value 2011 in input:name with jquery? <input type="text" name="hi[2011][]"> Example: <button>Click me</button> <input type="text" name="hi[2011][]"> $('button').click(function() { var f_offset = $('input').prop('name'); alert(f_offset); } A: Using match: $('button').click(function() { var f_offset = $('input').prop('name'); alert(f_offset.match(/\d+/)[0]); }) Example
{ "language": "en", "url": "https://stackoverflow.com/questions/7534544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }