text
stringlengths
8
267k
meta
dict
Q: asp.net mvc action result and count question I am working on a plugin based architecture. Its kind of social networking site. For a user, I can have pictures, blogs, videos. but they all come from modules. So, when you visit a user profile, you see tabs, saying pictures, videos and other things. I have an interface public interface IUserContent { UserContent GetContent(long id); } public class UserContent { public int Count {get;set;} public string URL {get;set; public string Text {get;set; } So, if a photos module implements IUserContent it will look like this public class UserPhotos : IUserContent { public UserContent GetContent(long id) { return new UserContent { Count = SomeRepository.GetPhotosCountByUser(id), URL = string.format("/photos/byuser/{0}",id) , Text ="Photos" }; } } This URL is an action method in Photos Controller. On my profile page i get all the implementations of IUserContent var list = GetAllOf(IUserContent); and render them using foreach loop as tabs on user profile page. Now, my question is, is there any better way to do it. I dont want to use URL as string. Or any better practise to achieve it. Regards Parminder A: Yes. Replace URL = string.format("/photos/byuser/{0}",id) with: URL = Url.Action("ByUser", "Photo", new { id }) If you wish to generate a url whereby your action is called ByUser and accepts an id as argument and your controller is called PhotoController; or use: URL = Url.RouteUrl("PhotosByUser", new { id }) If you wish to generate your url derived from a route called PhotosByUser. See: - * *http://msdn.microsoft.com/en-us/library/dd460348.aspx and; *http://msdn.microsoft.com/en-us/library/dd505215.aspx For further information :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7562905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make sure a thread gets the most recent variables modified by another thread? Ok, so I am making a 2D game, and all the map is represented in a 2D Array. I have this huge methods that modifies the map based on what is already in the map. So after a while implementing features, the FPS is lowering, so I decided to try to use multiple threads to make it faster ( Good thing, no? ). I made 3 Threads to do the work, one that paints and handles Events, one that updates the base part of the map and the other updates another set of variables. The problem is, it paints but it does not update when I start all 3 Threads. It does update when I call the methods from the painting thread. I tested the first updating thread by adding "System.exit(0);" at the run, and it did not started when it otherwise would start. I also tried to manually change a tile of the map directly in the run method of the Updating thread, but it did nothing. So I concluded the run is executed, and the variables are modified. So I thought that maybe the variables used by the painter aren't the updated ones. All the variables are in a seperated class and are static ( Was that right? ) and were accessed by an object, but then I changed it to 'Direct' Access ( IDE Suggestion ) with the code "nameOfTheClass.variableName" Almost forgot to mention, the Events ( In the class with the paint() method ) modifies the Map, and this part does work. I don't know what to do, anyone got an idea? A: You need to mark the offending variable as volatile, which will prevent the compiler from caching a copy in a local variable, instead reading/writing the actual value each time. A: I believe the problem is a race condition instead. The variable modification may be 'delayed' (by a few hundred nanoseconds?) as other accesses go through, but it will still happen, eventually. In this case, I don't think volatile or anything like that will make a difference, since the ordering of thread syncs should not be important. If it is, you have bigger things to worry about. Also, I think your terminology might be a bit messed up --I can't really understand the threading issue in relation to your code. If you need hard synchronisation, you can establish resource 'fences' (synchronization blocks) and keep your resource accesses within these fences, so that race conditions cannot occur. You establish transactions by nature of the fact that nothing can get into the fence while you are operating on these variables.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562907", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In SQL Server Reporting Services, how do I limit Previous function's scope to a group? I am working on a report that gets, for example purpose, 5 columns from database. Lets say ProductionCountry, Industry, ProductGroup, ProductId, Price. I am grouping them on ProductionCountry, Industry and ProductGroup. Visually its like this. I have applied this expression to hide repetition of a group's column data =Previous(Fields!IndustryName.Value) = Fields!IndustryName.Value But the problem with that is, this expression considers previous value from previous group. If you can see the 2 red boxes in the image for Taiwan, I would like to show Hardware and LCD Panels in Industry and ProductGroup columns respectively. But the expression would hide it. Any one knows how to fix it? A: You need to check more than one criteria as you go down the hierarchy of values so you'll need three Visibility-Hidden expressions: For ProductionCountry: =Previous(Fields!ProductionCountry.Value) = Fields!ProductionCountry.Value For Industry: =Previous(Fields!ProductionCountry.Value) = Fields!ProductionCountry.Value AND Previous(Fields!IndustryName.Value) = Fields!IndustryName.Value For ProductGroup: =Previous(Fields!ProductionCountry.Value) = Fields!ProductionCountry.Value AND Previous(Fields!IndustryName.Value) = Fields!IndustryName.Value AND Previous(Fields!ProductGroup.Value) = Fields!ProductGroup.Value
{ "language": "en", "url": "https://stackoverflow.com/questions/7562908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: replace all occurences of "\x0d" in a Java String Possible Duplicate: How do I replace a character in a string in Java? how can i replace all occurences of '\x0d' in a Java String?? * *I have tried myString.replaceAll("\x0d", "")... does not works and all the answers below does not work have tried that already OMG :) Apologies for the crap guys. A: Escape the backslash: myString = myString.replace("\\x0d", "whateverYouWantToReplaceWith") See it working on ideone. A: I believe you want this: String test = "\r".replace("\r", "princess"); System.out.println(test); // princess ASCII 13 is Carriage Return A: You may consider trying String.replace. A: Just a guess -- String.replace? There's a character version and a "character sequence" version. A: myString.replaceAll("\\x0d","whateverYouWantToReplaceWith");
{ "language": "en", "url": "https://stackoverflow.com/questions/7562909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Session variable is lost on RedirectToAction in IE My .NET MVC3 website is being loaded through an iframe on the parent website. They GET a controller's action on my website with certain parameters in the query string. My action validates these parameters, stores them in session and does RedirectToAction() to a different controller's action. In the second action, the first line of code gets these parameters from session. We did not have any problems in DEV, moreover we did not have any problems in QA. In Production, after the redirect, the session variable gets cleared. This only happens in IE 8 and 7. The Production server does have a load balancer, but at the moment the second server is turned off and the problem is still there. Here is the code, I stripped out validation and some other stuff. //Here is where they come in [HttpGet] public ActionResult Index(string locationGUID, string OtherParam) { //?locationGUID=ABCDEFGHIJKLMNOP,XXXXXXXXX&ContractInstance=2111,##### //some validation here var passedData = new PassedData { Guids = locationGUID.Split(',').ToList(), OtherParam = OtherParam }; PassedData = passedData; //more validation and init DB logging here return RedirectToAction("Index", "OtherController"); } //PassedData is a property of Base Controller, from which all other controllers inherit public PassedData PassedData { get { return (PassedData)Session["PassedData"]; } set { Session["PassedData"] = value; } } //Here is Index of "OtherController", when we get here in Prod in IE, first line throws null reference exception, because PassedData is now NULL.... [HttpGet] public ActionResult Index() { ViewBag.CustInfoList = PassedData.Guids.Select(guid => GetCustomerInfo(guid).Data).ToList(); //the rest of the code is not relevant to this question, since PassedData is already NULL :( } Thank you very much in advance! UPDATE: I implemented session state mode "StateServer". Nothing changed. UPDATE: I'm looking at Fiddler. IE: The parent site sets session cookie. My site doesn't. FF: Both sites set session cookie. A: This is due to IE not trusting cookies created by IFrames See Cookie blocked/not saved in IFRAME in Internet Explorer for a detailed explanation and a fix. HTH A: Another possible cause/solution is that IE doesn't save cookies if the domain name has an underscore (because strictly speaking domain names can't have underscores, so you'll probably only encounter this in development), e.g. http://my_dev_server/DoesntWork. Chrome or Firefox should work in this scenario, and if you change the domain name you're using to not have an underscore problem solved. Ref: * *http://blog.smartbear.com/software-quality/internet-explorer-eats-cookies-with-underscores-in-the-hostname/ *http://social.msdn.microsoft.com/Forums/ie/en-US/8e876e9e-b223-4f84-a5d1-1eda2c2bbdf4/ie7-cookie-issue-when-domain-name-has-underscore-character-in-it?forum=iewebdevelopment A: Load up fiddler. Watch for the Set-Cookie respond and note the cookie domain. Ensure it matches your site. Then on the next request (from redirect to action) ensure the cookie is sent over, and again, it matches the domain in the request.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Better Way to Pass Data from child to parent in UINavigationController, and modal presentations: reference to parent or delegates? So lately I have been trying ways to pass data from a child to a parent view controller. I have settled with two. The delegates approach: http://timneill.net/2010/11/modal-view-controller-example-part-2/ and the simple approach of just passing reference of the parent view controller to the child view controller before the child controller is pushed (UINavigationController) or presented (via modal presentation) - (IBAction)myAction:(id)sender{ MyViewController *myView = [[MyViewController alloc] init]; myView.isLinking = YES; myView.parent = self; // present child pushing or presentation logic here [sender resignFirstResponder]; } but I'm wondering why should I go with delegates if I can do the latter when I only just want to be able to pass data from child to parent view controllers? Also, there's only about a few answers on SO where doing the latter is recommended. In fact, I can't remember if there are. So I was wondering, why is doing the latter not recommended and why are there more people suggesting delegates or even retrieving the controller from the application delegate? A: Because the second approach ties both the parent to the child and vice versa, making a circular dependency. This is bad OOP. Using delegates means the child view can be used from any manner of calling code, now or in the future.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Scope_Identity() returning incorrect value fixed? I've been searching hi and low for an answer to this and figured I would turn to the stackoverflow community. I have been avoiding using type identity id fields fields within sql server and nhibernate due to this bug: http://connect.microsoft.com/SQLServer/feedback/details/328811/scope-identity-sometimes-returns-incorrect-value However, I just noticed that it was marked as fixed. Does, anybody know if this applies to the recent SQL server service pack that was released? I can't find a yes or no to this. A: My suggestion would be to try the query and test your results. There are a number of work arounds on this such as Output clause and run query not in parralel. See Microsoft KB on this http://support.microsoft.com/kb/2019779 Also a post on this that indicated not sure if fixed in 2008 SP1 but may be fixed in 2008 R2 http://blog.sqlauthority.com/2009/03/24/sql-server-2008-scope_identity-bug-with-multi-processor-parallel-plan-and-solution/
{ "language": "en", "url": "https://stackoverflow.com/questions/7562917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Re-enable radio inputs with a clear function I've tried a number of different things, including typical form reset and jQuery examples I've found across the web with no luck. Screenshot: The Goal: I have a rankable list where a user is expected to rank items from 1-6 according to importance to them. If they select "2" for a certain row, we don't want to let them select "2" for another row. Here is the jQuery that's accomplishing this: // Disable sibling radio buttons in form once an item is selected $("input:radio").click(function() { var val = $(this).val(); $(this).siblings("input:radio").attr("disabled","disabled"); $("input:radio[value='" + val + "']").not(this).attr("disabled","disabled"); }); The Issue: This code seems to be working, with a couple of quirks. * *The code correctly disables sibling rows, but if the user wants to change, they're stuck. They can click "2" on a row, then click "3" on the same row, but that leaves all other "2" and "3" options disabled completely. *The user needs a way to completely clear the form via a "start over" or "reset" button that apparently needs some special jQuery magic that I haven't been able to figure out yet. *I took code referenced in another post from this url, but it seems to only half work on my site. I notice on that fiddle link that if you click "1", it also disables "2" and "3" on the same row, which doesn't happen on my local development attempt. It does, however, permanently disable "2" in other rows if you were to click "2"...so I'm unsure why it works in the example but not my code (above). There's got to be some easier way around this that I'm just not seeing here. I appreciate any help or code examples that might work along these lines. A: Instead of outright disabling radio options that are not valid, you can instead take one of two approaches: * *When the user clicks an option, validate the option on the fly, i.e., that "3" is not already selected when you click another "3". If not valid, then display a popup to user and clear it out. *When the user clicks an option, say a "3", then clear out all other "3" options so that only one is rated at that amount at a time. Here is a sample code that will use method #2, clearing out all same value options whenever an option is clicked: http://jsfiddle.net/xy9wC/ A: From a users perspective, disabling these kinds of radio buttons may be very annoying to deal with as it forces the user to use two clicks instead of one while selecting something else. A better alternative would be to "suggest" errors to the user, then enforce them on submit. For example, you could make the row with the invalid option red, then allow the user to discover the error and fix it themselves. An even better way than that, use jQuery to create a sortable list. http://jqueryui.com/demos/sortable/ -Sunjay03
{ "language": "en", "url": "https://stackoverflow.com/questions/7562921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to dynamically change the Spinner's items I have two spinners. Country and City. I want to dynamically change the City's values upon Country selection. I know how to create and initialize the values of Country but don't know how to set and change the City's values. Any guidance is appreciated. UPDATES1 The problem is, I don't have idea on how to update the content of City Spinner. I know listener and other basics on how to create a fixed spinner. A: For the second spinner, use an Adapter over a List<String> (or whatever your City representation is). After changing the contents of the list, call notifyDataSetChanged on the adapter, and that will do. A: You need to get a programmatic reference to the spinner, something like this: Spinner spinner = (Spinner) findViewById(R.id.spinner); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.planets_array, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); Then to update your city's values, use an OnItemSelectedListener, like this: public class MyOnItemSelectedListener implements OnItemSelectedListener { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { //update content of your city spinner using the value at index, // id, or the view of the selected country. } } public void onNothingSelected(AdapterView parent) { // Do nothing. } } Finally, you need to bind the listener to the country spinner like this: spinner.setOnItemSelectedListener(new MyOnItemSelectedListener()); see here for reference: http://developer.android.com/resources/tutorials/views/hello-spinner.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7562922", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Memory-optimizing recursive calls in C I have a recursive function which can be written like: void func(TypeName *dataStructure, LL_Node **accumulator) { func(datastructure->left, accumulator); func(datastructure->right, accumulator); { char buffer[1000]; // do some stuff } return; } I know that in reality the buffer is being allocated at the beginning of the function and putting the statement in a nested scope block doesn't actually use a new stack frame. But I don't want the compiler to allocate an exponential number of 1000-byte buffers at once, when they can be allocated and thrown away one at a time as each level returns. Should I use outside global variables? A call to a helper function to force the buffer to be allocated after the recursive call? What I'm really fishing for here is advice on the cleanest, most C-idiomatic way of forcing this behavior. Edit: One add-on question. If the exact same accumulator will be passed to every call of func, is it unheard of to leave the accumulator pointer in a global variable rather than pushing it onto the stack with every call? A: Since it's only used by one call at a time, you can just preallocate it and pass it into all the calls via an operand: void func(TypeName *dataStructure, LL_Node **accumulator, char *buffer) { func(datastructure->left, accumulator, buffer); func(datastructure->right, accumulator, buffer); { // do some stuff } return; } A: One option is to break the function into a non-recursive "public" function that sets up the buffer and calls a private recursive function that requires a buffer be passed in: struct func_buffer { char buffer[1000]; }; static void func_private(TypeName *dataStructure, LL_Node **accumulator, struct func_buffer* buf) { func_private(datastructure->left, accumulator, buf); func_private(datastructure->right, accumulator, buf); // do some stuff with *buf return; } void func(TypeName *dataStructure, LL_Node **accumulator) { struct func_buffer buffer; func_private( dataStructure, accumulator, &buffer); return; } That way the users of the function don't need to be concerned with the details of how the memory used by the recursive part of the function is managed. So you could pretty easily change it to use a global or a dynamically allocated buffer if it became evident that such a change was necessary or would make sense. A: You can either pass the reference to the buffer or use global variable. When you use the reference as in void func(TypeName *dataStructure, LL_Node **accumulator, char buffer[]) { func(datastructure->left, accumulator, buffer); func(datastructure->right, accumulator, buffer); { char buffer[1000]; // do some stuff } return; } void main() { char buffer[1000]; func (structure, accum, buffer); } you are passing the reference, just the pointer to the beginning of the the array, so you have to remember its length. If you choose to use a global variable, you are actually not using stack, but allocating program memory, a shared space where code and data coexists (code is data). Therefore, you are never using a single byte of extra ram in your calls if you do it like this: char buffer[1000]; void func(TypeName *dataStructure, LL_Node **accumulator) { func(datastructure->left, accumulator); func(datastructure->right, accumulator); { // do some stuff } return; } void main() { func (structure, accum); } It is up to you to choose one. The second one pushes less parameters onto the stack on each recursive call, but enlarges the program size. The first one is more elegant to some, but is a bit slower, maybe not even noticeable. A: I would personally allocate the buffer on the heap in this scenario somewhat like this: void func(TypeName *dataStructure, LL_Node **accumulator, char *buffer ) { bool alloced = false; if( buffer == 0 ){ buffer = (char*) malloc( 1000 ); alloced = true; } func(datastructure->left, accumulator, buffer); func(datastructure->right, accumulator, buffer); { // do some stuff } if( alloced ) free( buffer ); return; } If you don't mind C++ syntax, you could have buffer default to equal zero, or you could mangle the function name and add #define func(a,b) __mangledfunc__(a,b,0) That seems like it would be the easiest for your application. A: I believe your average compiler can optimize what are known as "tail recursive functions", where basically the last instruction in your function is a recursive call to that function. In that special case, the function will simply reuse the stack frame with every recursion (so all of your stack allocated variables don't get un/re-allocated!) If you can push all of your instructions before the recursive calls, and you have a decent compiler, it should work-- otherwise, I'd just pass it around as a reference variable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: how should I go about making many reports in the same ruby application I am making an app that contains a lot of information the few users will want to have reports against. I might write 10 different reports against the 3 tables involved. Should I create multiple methods on a report_controller to access each report? for example I could have a report that is all_to_date or year_over_year_comparison. I don't know if it would be better to write the reports as separate methods like /reports/report1 and reports/report2 etc or should I create a non database model for the reports an have many different pieces in there? Is there a better method? A: Take a look at the statistics gem, it should do what you need. A: Consider also using Presenters * *http://www.subelsky.com/2008/01/presenter-classes-help-with-rails.html and *https://gist.github.com/1001089 Presenters allow you to extract the logic needed for complex views (especially views that require the use of more than one model) into a separate, easily testable class. This helps you write clean code and skinny controllers, among other benefits.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ParVector map is not running in parallel I have a bit of code like: val data = List(obj1, obj2, obj3, obj4, ...).par.map { ... } and the ParVector is roughly 12 elements large. I noticed that all of my work is being done in the main thread so I traced down the stacktrace and found that in the following line (in the link below), ifParallel is false (from CanBuildFrom). Any hints as to why it's false, and what I can do to help it? https://github.com/paulp/scala-full/blob/2.9.0.1/src/library/scala/collection/parallel/ParIterableLike.scala#L504 A: I can't reproduce this: case class Obj(i: Int) val list = List(1 to 12 map Obj: _*) def f(o: Obj) = { println("f " + o); Obj(o.i + 1) } val data = list.par.map(f) Prints: f Obj(1) f Obj(2) f Obj(3) f Obj(4) f Obj(5) f Obj(6) f Obj(7) f Obj(8) f Obj(10) f Obj(11) f Obj(12) f Obj(9) // data: ParVector(Obj(2), Obj(3), Obj(4), Obj(5), Obj(6), Obj(7), Obj(8), Obj(9), // Obj(10), Obj(11), Obj(12), Obj(13)) See scala: parallel collections not working? for a similar symptoms and where adding some artificial delay showed things could happen in parallel. How do you find out ifParallel is taking the otherwise route? I do this: scala> collection.parallel.ParSeq.canBuildFrom[Int].isParallel res0: Boolean = true Also, what is the value of Runtime.getRuntime.availableProcessors? A: There was an error in the version of scala I was using. It has since been fixed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CSS is not working for links I can not figure out why the below css will not do what it appears to do, if anyone can explain why or help show what I am doing wrong, would greatly appreciate. <style> .button-blue a:link{ text-decoration: underline overline; color: red!; background: #55a4f2!; padding: 12px 24px!; -webkit-border-radius: 6px!; -moz-border-radius: 6px!; border-radius: 6px!; color: white!; font-size: 16px!; font-family: 'Lucida Grande', Helvetica, Arial, Sans-Serif!; text-decoration: none!; vertical-align: middle!; font-weight:bold!; } .button-blue a:hover { background: #1071d1; color: #fff; } .button-blue a:active { background: #3e779d; } </style> <div class="button-blue"> <a href="dd" class="button-blue">Post Comment</a> </div> <span class="button-blue"> <a href="dd" class="button-blue">Post Comment</a> </span> http://jsbin.com/etijiz A: It doesn't do what you expect it to do because you have syntax errors. You appear to have used ! instead of !important. If you remove the exclamation marks it will look a little more like you expected it to. Generally it is a bad idea to use !important and if you find yourself using it you probably need to refactor something. It would be a good idea to learn more about how CSS selector specificity works. A: Basically it's because you're applying the style to the span/div and not the anchor and a span/div doesn't have an a.hover etc etc. A quick test by removing the .blue-button from each of the a: style definitions shows it working more correctly. Here's the fiddle I set up based on your sample. http://jsfiddle.net/tS9vt/ Added a comment with a new link showing better behaviour without the exclamation marks. Edit: here's that link http://jsfiddle.net/LuaAv/
{ "language": "en", "url": "https://stackoverflow.com/questions/7562942", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: is there an "onAnything" javascript event? have dumb question. Here I've got three events calling the same function, connected to the same <div>: <html> <head> <script type='text/javascript'> function universal_action_handler( event ) { var eType = event.type; var eTarget = event.target || event.srcElement; console.log( "Captured Event, type=", eType, ", target=", eTarget ); if( 'mouseover' == eType ) { console.info( "onMouseOver: set background color to red." ); eTarget.style.backgroundColor = 'red'; eTarget.style.fontSize = ''; } if( 'mouseout' == eType ) { console.info( "onMouseOut: set background color to transparent." ); eTarget.style.backgroundColor = 'transparent'; eTarget.style.fontSize = ''; } if( 'click' == eType ) { console.info( "click!" ); eTarget.style.fontSize = 'larger'; } } </script> </head> <body> <div style='border: 1px dashed red; display: inline-block;' onClick="universal_action_handler(event);" onMouseOver="universal_action_handler(event);" onMouseOut="universal_action_handler(event);">Click me!</div> </body> </html> I have onClick='', onMouseOver='', and onMouseOut='', all connected to the same <div>, and all calling the same function. If I want to add an event, I have to add an onEventThingy='' and call the same universal action handler function above. Inside the function, it decides what kind of event (event.type) and takes action. Is there an onAnything='' event that I can use to call the universal function for any event which may happen to that <div>? A: Instead of all those onevent attributes (which should be avoided anyway), you could set the onevent properties on the DOM element like so: div.onclick = div.onmouseover = div.onmouseout = universal_action_handler; where div is a reference to your DIV element. Btw this is how I would implement the handler: function universal_action_handler ( e ) { var target, style; e = e || window.event; target = e.target || e.srcElement; style = target.style; if ( e.type === 'click' ) { style.fontSize = 'larger'; } else { style.backgroundColor = e.type === 'mouseover' ? 'red' : 'transparent'; style.fontSize = ''; } } Live demo: http://jsfiddle.net/rPVUW/ A: No, there's no way to attach the same handler to all possible events. Is that really what you want? This could lead to your handler containing a huge if..else block or big switch statement. If you want to attach common functionality (logging in your example) to all event handlers, consider this JavaScript: function logAndHandle(event, innerHandler) { var eType = event.type; var eTarget = event.target || event.srcElement; console.log( "Captured Event, type=", eType, ", target=", eTarget ); return innerHandler(event); } Which you'd use like this: <div onclick="logAndHandle(event, yourClickHandler);" onmouseover="logAndHandle(event, yourMouseOverHandler);" onmouseout="logAndHandle(event, yourMouseOutHandler)">Click me!</div> A: No, there is no universal event. You can try what Šime Vidas suggested, or some libraries (e.g., jQuery) allow you to bind multiple events to the same handler with a single line of code, but either way you do need to explicitly list out the events to be bound. A: Given that you seem to want some functionality to run for all events, and other functionality to be specific to particular events, I'd combine Jacob's answer with Šime Vidas's: var log = function(innerHandler) { return function(event){ var eType = event.type; var eTarget = event.target || event.srcElement; console.log( "Captured Event, type=", eType, ", target=", eTarget ); return innerHandler(event); }; }; And use it thus: div.onclick = log(yourClickHandler); div.onmouseover = log(yourMouseOverHandler); div.onmouseout = log(yourMouseOutHandler); Currying the log function makes it very easy to compose future "all event" functionality: var count = function(innerHandler){ var totalCount = 0; return function(event){ totalCount += 1; alert("I've been called " + totalCount + " times."); return innerHandler(event); }; }; div.onclick = count(log(yourClickHandler)); Anyway, if you want to do functional-style programming in Javascript, you'd also want to look at Function.apply and Function.call. A: Using just javascript, no, there is no 'onAnything' attribute. If you have the ability to add jQuery, you can 'bind' multiple events to the same div and then run the same function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Modulo doesn't work I know this will seem like a really stupid question, but I just don't get why this isn't working. This: System.out.println(5 % .10); And it's returning: 0.09999999999999973 I really have NO IDEA. I'm just learning Java, and I'm pretty good with C#, so I tried with C# to. C# seemed to return the same thing also. A: This is due to floating-point precision. 0.10 cannot be represented exactly in binary. Therefore the result is not exactly 0.10 and is hence not modded down to 0. This will work with 0.25 because 0.25 can be represented exactly in binary. EDIT: In general, any number that can be expressed as a fraction with a power-of-two in the denominator can be expressed exactly in IEEE floating-point. (provided it doesn't over/underflow) A: As others explained, this is due to inaccuracies caused by floating point precision. You should use BigDecimal, in this case the remainder method for precise arithmetic involving decimals. BigDecimal number = new BigDecimal(5); BigDecimal divisor = new BigDecimal("0.1"); BigDecimal result = number.remainder(divisor); System.out.println(result); // 0 A: You're doing floating point arithmetic. 0.1 has no exact representation as a float. A: Java (like most programming languages except COBOL) is making computations in the binary systems. I think 0.10 has such a unlucky binary representation that the result of your computation looks like this. I think it is best to avoid computing modulus of double or float and stick to integer or long to get better results. A: The binary representation for 0.1 is System.out.println(new BigDecimal(0.1)); prints 0.1000000000000000055511151231257827021181583404541015625 When you print 0.1, you get a small amount of rounding which hides this error. When you perform a calculation you have to use BigDecimal or round the result or transform the calculation to minimise error. 5 % 0.1 (5 / 0.1 % 1) * 0.1 50 % 1 / 10 In terms of double you can do double d = 5; double mod0_1 = d * 10 % 1 / 10; double rounded = Math.round(mod0_1 * 1e12)/1e12; // round to 12 places. Note: the result can still have a slight error, but it will be small enough that when you print it, you won't see it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Uneven axis in R plot Is it possible to draw an uneven axis in R? I know that I can specify labels at specific spots, but I mean, I want a particular section of my graph to be spread out. For instance, imagine an X axis such as: -10 -5 0 1 2 3 4 5 10 where there is equal spacing between each of the above values. A: You would need to make a factor of your levels, say "fac", and then plot. Later using axis() with labels=as.character(fac). dat <- data.frame(x=factor(c(-10 ,-5, 0, 1, 2, 3, 4, 5, 10)), y=1:9) with(dat, plot(x, y)) # a step-like plot with(dat, plot(as.numeric(x), y, type="p", xaxt="n")) # points instead of steps axis(1, at=1:9, labels=as.character(dat$x)) # the "irregular" axis Thinking further about @Ben Bolker's question, it should also be possible to define a an auxiliary x-value to determine the plotting "x=" and the axis "at=" coordinate on the horizontal and then using unique(as.character(.)) applied to the "real x" as the "labels=" argument to axis as shown above but not needing a factor construction. An even more complex scheme is possible with this approach where continuous values across specific ranges of the auxiliary variable could be used for plotting but truncated values constructed for the labels at the boundaries of those ranges. I think further design justification and specification would be needed before building an implemented example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Converting large numbers to String format for comparison I am trying to compare numbers that are so large that even BigIntegers cannot deal with them. My solution is to convert the numbers to Strings and use String comparison on them. Will this work? I am not really sure how to implement something like this. I am just attempting to unit test an algorithm to produce the factorial of 1000 for a project Euler program that I am sucked into. A: Your assumption is wrong. BigInteger provides arbitrary precision, so it can definitely deal with numbers this big. Try the following: public class Main { public static void main(String[] args) { BigInteger thousand = BigInteger.valueOf(1000L); for (int i = 999; i > 0; i--) { thousand = thousand.multiply(BigInteger.valueOf(i)); } System.out.println(thousand.toString()); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7562958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What does this statement mean in C? I am trying to understand the piece of code written in C and not sure I understand it fully. Here is the function written in C: int gsl_multimin_diff (const gsl_multimin_function * f, const gsl_vector * x, gsl_vector * g) { size_t i, n = f->n; double h = GSL_SQRT_DBL_EPSILON; gsl_vector * x1 = gsl_vector_alloc (n); /* FIXME: pass as argument */ gsl_vector_memcpy (x1, x); for (i = 0; i < n; i++) { double fl, fh; double xi = gsl_vector_get (x, i); double dx = fabs(xi) * h; if (dx == 0.0) dx = h; (x1, i, xi + dx); fh = GSL_MULTIMIN_FN_EVAL(f, x1); gsl_vector_set (x1, i, xi - dx); fl = GSL_MULTIMIN_FN_EVAL(f, x1); gsl_vector_set (x1, i, xi); gsl_vector_set (g, i, (fh - fl) / (2.0 * dx)); } gsl_vector_free (x1); return GSL_SUCCESS; } There is a line 14 in this code, which has this: (x1, i, xi + dx) What does it do? For referenc: x1 is the pointer to the function that allocates memory for a newly created vector. i - loop iterator xi - returning an element from the vector at position i dx is just a value. Thanks for your help! A: It looks like there's something missing there. It should be function arguments. Otherwise it's a no-op - (x1, i, xi + dx) is a valid expression in C, but one that doesn't do anything. It just mentions x1, then mentions i, then mentions the sum of xi and dx.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android - how to create music note sound? Folks, In my android app, I need to display a musical instrument such that the user (mostly children) could press a key and I play the music note through the speaker. I am trying to understand what it takes to generate a music note under Android. The examples on sound that I saw mostly use MediaPlayer or SoundPlayer to play media files. I am looking for sending a specific tone with duration to the speaker. I would appreciate your help in pointing me in the right direction. Thank you in advance for your help. Regards, Peter A: Check out this question for 1 possible implementation of Tone Generating. Playing an arbitrary tone with Android
{ "language": "en", "url": "https://stackoverflow.com/questions/7562960", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Using ClientSideValidations gem inside ajax rendered partial I am currently using the ClientSideValidations gem and stuck while rendering a partial using ajax and trying to validate addresses inside that rendered partial with the gem mentioned above. Nothing happens when entering a wrong combination specified in the model. If browsing to the address-form directly and trying out validations, everything works fine, just like specified. Any hints or thoughts on how to make the validations gonna work inside the partial? Thanks! EDIT: No errors in JS console, just nothing happens when for example entering a too short zipcode (specified in the model with 5 digits). Btw I use haml for the views. So the code in my view: = link_to "Shipping", addresses_path, :remote => true corresponding controller addresses_controller.rb respond_to do |format| ... format.js {render :layout => false} ... end corresponding index.js.erb $("#ajax_content").html("<%= escape_javascript(render :partial => "partialXY") %>"); and corresponding partial = form_for @address, :validate => true, :id => "address_form", :remote => true do |f| - if @address.errors.any? #error_explanation %h2 = pluralize(@address.errors.count, "error") prohibited this user from being saved: %ul - @address.errors.full_messages.each do |msg| %li =msg %ul %li = f.label :type = f.select :address_type, [['Billing Address', 'billing'],['Shipping Address', 'shipping']], :class => "address_selection" %li = f.label :gender = f.select :gender, [['Male', 'male'],['Female', 'female']], :class => "text_field" %li = f.label :last_name = f.text_field :last_name, :id => "last_name", :class => "text_field" %li = f.label :first_name = f.text_field :first_name, :class => "text_field" %li = f.label :company_name = f.text_field :company_name, :class => "text_field" %li = f.label :street = f.text_field :street, :class => "text_field" %li = f.label :number = f.text_field :number, :class => "text_field" %li = f.label :zipcode = f.text_field :zipcode, :class => "text_field" %li = f.label :place = f.text_field :place, :class => "text_field" %li = f.label :phone_no = f.text_field :phone_no, :class => "text_field" %li = f.label :country = f.text_field :country, :class => "text_field" %li = f.label :email = f.text_field :email, :class => "text_field" %li = f.submit so like I said nothing happens when validating the rendered partial inputs like zipcode, etc. The funny thing is, that if you look at the following, automatically by rails generated view for editing addresses, the validation works just fine. rails generated view to edit address =render 'partialXY' I have been working on this issue for a long time and have absolutely no clue on how to fix this. I'm sure it has something to do with ajax since using validation when rendering the rails generated partial works just fine. Thanks a lot! Phil A: Ok I fixed it. Turned out despite giving the form an ID, the ID was a different one in the final html code. So I just added a $('form.form_real_id').validate(); to my .js.erb file!
{ "language": "en", "url": "https://stackoverflow.com/questions/7562963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: converting existing web project using maven I have been trying to convert a web project that produces a war file to maven. my existing project structure is as follows - MyWebProject | -- WEB-INF/src - contains a bunch of packages like com.myweb.client, com.myweb.server etc -- WEB-INF/test - contains 1 package com.myweb.tests -- web-scripts - contains bunch of scripts (just a folder; not on classpath) -- misc-files1 - contains misc files sets 1 -- misc-files2 - similar to above presently a war file is being created using ant script with the resulting war file structure as follows myweb.war - Meta-INF (only contains MANIFEST.MF) - WEB-INF - classes - com.myweb.client - com.myweb.server etc. - web-scripts - misc-files1 - misc-files2 i created a basic maven project using simple-artifact and added my packages. i am using maven assembly plugin to generate the war file and using filesets to filter. but my resultant war file is no where close to what i get with ant. here is a shortened version of my assembly.xml file <assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd"> <id>assembler</id> <formats> <format>war</format> </formats> <includeBaseDirectory>false</includeBaseDirectory> <dependencySets> <dependencySet/> </dependencySets> <fileSets> <fileSet> <directory>src/main/java</directory> <outputDirectory>WEB-INF</outputDirectory> <includes> <include>**</include> </includes> </fileSet> <fileSet> <directory>es</directory> <outputDirectory>resources1</outputDirectory> <includes> <include>**</include> </includes> </fileSet> <fileSet> <directory>resources2</directory> <outputDirectory>resources2</outputDirectory> <includes> <include>**/*</include> </includes> </fileSet> <fileSet> <fileSet> <directory>test</directory> <outputDirectory>WEB-INF</outputDirectory> <includes> <include>**</include> </includes> </fileSet> </fileSets> </assembly> To create a custom war, is assembly plugin the right approach. I can always include my ant script in pom using maven-antrun-plugin, but i want to avoid using ant if possible. any suggestions. A: You should be using maven-war-plugin for this. A: You're going entirely the wrong direction. Try some basic Maven webapp tutorials first to get a feel for the tool. Then you should see some clear parallels between your Ant build and the Maven lifecycle and default plugin bindings. When you're more comfortable, first let Maven handle all the stuff that it does out of the box, like compiling, testing, and creating the WAR. Try to move the dependency management to Maven, too. If you still need a classpath set up in Ant, use the Maven Ant tasks to let Maven build the classpath for your Ant script. Leave any custom stuff in Ant build files and invoke it using the antrun plugin from Maven until and unless you convert to using a Maven plugin for it. Edit: Your problem seems to be that you have multiple directories containing source files that need to be bundled into the war. Is that right? The simplest solution would be to get them all into one place--src/main/webapp is the Maven convention. Even an Ant build should have at least this much organization to it. If there's a really good reason to have your war resources scattered all over (I'd like to hear it), then you can use some other plugin like the resources plugin, GMaven, or the antrun plugin to copy the multiple directories into the directory where the war plugin builds the war directory structure. That's known as the "webappDirectory" in the war plugin. The possibility of using the antrun plugin goes back to my original answer of invoking pieces of your existing Ant script from Maven. If this multi-directory thing has to stay and is already taken care of by Ant, refactor that into a target/task that can also be used from Maven. As much as possible, let the custom parts of your existing build be reused as you adopt Maven.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562966", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: sending cross-domain messages via PHP and JSON Ok, so I am building a CMS one of the features I wanted to add is ability for me to send messages to my friends which are also using the CMS currently in development mode. This point of the idea is to allow more fluent communication between me and them, since e-mail can be delayed sometimes and here i want to send a simple message to them. With something like following format Name: Avatar: Subject: Date: Message: I am pretty sure this can be easily rigged together with PHP and JSON just assuring the access to the JSON file is secure in which I implemented something like access key which checks if the site requesting the file matches site host, and matches the key. In any case sorry for my babling, this is my way. But folks I would like to know what would you suggest in making cross-domain messaging system build in into a PHP + jQuery based CMS? In terms of being robust, fast, secure and easy to work with. A: Exchange data in the jsonp format, http://en.wikipedia.org/wiki/JSONP. Server: How to convert php to jsonp with json_encode. http://1080d.com/lang/en-us/2009/10/converting-php-to-jsonp-with-json_encode/ Client: Ajax example of jsonp data call. This particular example concerns the timeout feature but is an excellent example of how to set it up. jQuery ajax (jsonp) ignores a timeout and doesn't fire the error event
{ "language": "en", "url": "https://stackoverflow.com/questions/7562967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Varbinary text representation to byte[] In C#, how can I take the textual output that SQL Server Management Studio shows as the contents of a varbinary column, and turn that text into the byte[] that is stored in the column? A: SqlConnection conn = new SqlConnection(yourConnectionString); SqlCommand cmd = new SqlCommand("select col from yourtable", conn); SqlDataReader reader = cmd.ExecuteReader(); if (reader.HasRows) { byte[] bytes = (byte[])reader[0]; } reader.Close(); conn.Close(); A: OK, so you want to copy and paste the value displayed in SSMS for a varbinary column (e.g. "0x6100730064006600"), and get the byte[] from it in C#? That's quite easy - the part after 0x is just hex values (2 characters each). So, you take each pair, convert it to a number specifying a base of 16 (hex), and add it to a list, like so: string stringFromSQL = "0x6100730064006600"; List<byte> byteList = new List<byte>(); string hexPart = stringFromSQL.Substring(2); for (int i = 0; i < hexPart.Length / 2; i++) { string hexNumber = hexPart.Substring(i * 2, 2); byteList.Add((byte)Convert.ToInt32(hexNumber, 16)); } byte [] original = byteList.ToArray(); Disclaimer - fairly dodgy and unoptimal code, I just hacked it together for demonstration purposes (it should work though).
{ "language": "en", "url": "https://stackoverflow.com/questions/7562968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: How to keep a JButton pressed after its JPanel loses focus I have found how to keep a JButton in its pressed state using this code: JButton[] buttons; . . . public void actionPerformed(ActionEvent e) { for(int i = 0; i < buttons.length; i++) { if(e.getSource() == buttons[i]) { buttons[i].getModel().setPressed(true); } else { buttons[i].getModel().setPressed(false); } } } This code captures the clicked button, keeps it pressed, and makes all other buttons on the panel unpressed. And this code works great... until the window loses focus (or more specifically, its parent JPanel loses focus). After that, all the buttons return to a non-pressed state. Right now the tutorial on how to write WindowFocusListeners is down. Is there a way to make a JButton's pressed state persist through a loss of focus? A: Why not simply use a series of JToggleButtons and add them to the same ButtonGroup object? All the hard work is done for you since the toggle button is built to stay in pressed state if pressed. Think of it as a JRadioButton that looks like a JButton (since in actuality, JRadioButton descends from JToggleButton). For example: import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class BunchOfButtons extends JPanel { private static final String[] TEXTS = {"One", "Two", "Three", "Four", "Five"}; private ButtonGroup btnGroup = new ButtonGroup(); private JTextField textField = new JTextField(20); public BunchOfButtons() { JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 0)); BtnListener btnListener = new BtnListener(); for (String text : TEXTS) { JToggleButton toggleBtn = new JToggleButton(text); toggleBtn.addActionListener(btnListener); toggleBtn.setActionCommand(text); btnPanel.add(toggleBtn); btnGroup.add(toggleBtn); } JPanel otherPanel = new JPanel(); otherPanel.add(textField ); // just to take focus elsewhere setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); setLayout(new GridLayout(0, 1, 0, 15)); add(btnPanel); add(otherPanel); } private class BtnListener implements ActionListener { public void actionPerformed(ActionEvent aEvt) { textField.setText(aEvt.getActionCommand()); } } private static void createAndShowGui() { BunchOfButtons mainPanel = new BunchOfButtons(); JFrame frame = new JFrame("BunchOfButtons"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(mainPanel); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGui(); } }); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7562972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: ListBox items as AutoCompleteCustomSource for a textbox I have populated some items into a listbox using the datasource property. Now I need to set the AutoCompleteCustomSource for a textBox from the items listed in the listbox. Precisely, the DataSource for the ListBox and the AutoCompleteCustomSource for the textBox are same. How can I set the AutoCompleteCustomSource without using the for-loops? .Net 2.0 only. No support for LINQ A: The AutoCompleteStringCollection takes only string[], so it should be like this: var cc = new AutoCompleteStringCollection(); cc.AddRange(listBox1.Items.Cast<string>().ToArray()); A: If your ListBox is a list of strings, you should be able to do this: (untested) textBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend; textBox.AutoCompleteSource = AutoCompleteSource.CustomSource; textBox.AutoCompleteCustomSource.AddRange((List<String>)listBox.DataSource); A: Here is a similar question and answer seems to be appropriate. autocomplete textbox on listbox Another similar question C# AutoComplete
{ "language": "en", "url": "https://stackoverflow.com/questions/7562989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to access this json data with JavaScript / Ajax? {"4255":"Alpine 50W x 4 Apple® iPod®-Ready In-Dash CD Deck","4254":"Alpine 50W x 4 In-Dash CD Deck with Detachable Faceplate","4251":"Alpine 50W x 4 Apple® iPod®-/Satellite Radio-/HD Radio-Ready Marine CD Deck","4256":"Alpine 50W x 4 Apple® iPod®-Ready In-Dash CD Deck","9839":"Boss Marine 10\" Marine Single-Voice-Coil 4-Ohm Subwoofer","12433":"Alpine Type R 10\" Dual-Voice-Coil 8-Ohm Subwoofer","12428":"Alpine 12\" Single-Voice-Coil 4-Ohm Subwoofer"} Do I need to get my json data into another format, or is this suitable for accessing via ajax? A: Most actual browsers support this method : var json = JSON.parse('{"4255":"Alpine 50W x 4 Apple® iPod®-Ready In-Dash CD Deck","4254":"Alpine 50W x 4 In-Dash CD Deck with Detachable Faceplate","4251":"Alpine 50W x 4 Apple® iPod®-/Satellite Radio-/HD Radio-Ready Marine CD Deck","4256":"Alpine 50W x 4 Apple® iPod®-Ready In-Dash CD Deck","9839":"Boss Marine 10\" Marine Single-Voice-Coil 4-Ohm Subwoofer","12433":"Alpine Type R 10\" Dual-Voice-Coil 8-Ohm Subwoofer","12428":"Alpine 12\" Single-Voice-Coil 4-Ohm Subwoofer"}');
{ "language": "en", "url": "https://stackoverflow.com/questions/7562991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Upgrade Current Target to IPhone Not IPad I currently have an ipad app and would now like to turn it into a universal app for both iPad and iPhone. The problem is I cant seem to find the feature to upgrade my iPad app to universal. There is an option to go from iPhone to iPad but not the other way around. Any ideas? Thanks A: You can just add a new target and chose what kind of devices you want to deploy on: iPhone, iPad or Universal See the screenshot below:
{ "language": "en", "url": "https://stackoverflow.com/questions/7562992", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Are the MIT Introduction to C++ lecture notes any good? I've been wondering if these lecture notes from an Introduction to C++ course are good material for me to learn the language. Does this material contain any gross factual errors in it? Will I learn some concepts in a wrong way with them? Will I get any bad practices from it? A: The original MIT Open Courseware C++ course was unfortunately of very low quality, full of factual errors. The next one, from the mid-term course a year later, was much improved. And judging from a cursory review of the first PDF you link to, the current stuff is good. However, as @Muggen remarked, you should better get one of the well known C++ books such as one of the books in the Stack Overflow C++ book list, e.g. Accelerated C++. A book is much more complete and dependable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calculating shipping & handling - JavaScript I'm trying to accomplish the following problem: Many companies normally charge a shipping and handling charge for purchases. Create a Web page that allows a user to enter a purchase price into a text box and includes a JavaScript function that calculates shipping and handling. Add functionality to the script that adds a minimum shipping and handling charge of $1.50 for any purchase that is less than or equal to $25.00. For any orders over $25.00, add 10% to the total purchase price for shipping and handling, but do not include the $1.50 minimum shipping and handling charge. The formula for calculating a percentage is price * percent / 100. For example, the formula for calculating 10% of a $50.00 purchase price is 50 * 10 / 100, which results in a shipping and handling charge of $5.00. After you determine the total cost of the order (purchase plus shipping and handling), display it in an alert dialog box. Here's my code so far: <script type="text/javascript"> /*<![CDATA [*/ //Shipping & handling fee var price = 0; var shipping = 0; var total = price + shipping; function calculateShipping(price){ //Add $1.50 with any purchase that is less than or equal to $25.00 if (price <= 25){ return 1.5; } //Add 10% with any purchase that is greater than $25.00 but do not inlcude the $1.50 fee else{ return price * 10 / 100 } } /* ]]> */ .. and my HTML <form> <table> <p> <tr> <td>Enter purchase price</td> <td><input type="text" name="inputPrice" size="6" onchange="" /></td> </tr> <tr> <td>Shipping &amp; handling</td> </tr> <tr> <td/> <td><input type="button" name="calcShipping" value="Calculate" onchange="" /></td> </p> </table> </form> I wanna go the extra mile and I'd like to show the shipping & handling fee prior to clicking the Calculate button, in other words, as soon as I type the purchase price, the S&H price appears and then, when clicking the button, the alert dialog box show my total price. P.S. I still have problems with how to call functions :S A: Try adding an onkeyup event handler to the input where you've got your price, i.e. onkeyup="calculateFee()" This will call the calculateFee() function every time the user releases a key while in that field. Alternatively, you can use onchange instead of onkeyup, which will wait until the focus exits the field.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563003", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WAS server - attach policy set to a single JAX-WS client I have a java project (*.jar) that has code for 10 JAX-WS clients. One of the clients uses WS-Security and needs policy set/bindings to be attached to it. Remaining nine clients use plain HTTP without any security to invoke respective services. I used instructions from http://www.redbooks.ibm.com/redbooks/pdfs/sg247758.pdf section 6.5 and configured local/developer RAD workspace, such that the policy set/bindings are associated only to the secure service client, and am able to invoke all services successfully. However, in our QA environment, from WAS Admin Console am unable to associate the policy set/binding to the specific service. It is either all or none. That is, either I can attach the policy set to all 10 clients, and the secure client works OR I can detach the policy set and remaining 9 HTTP clients will work. Can you help me understand why i am not able to attach the policy set to the secure service alone? Thanks for your help in advance. A: IBM confirmed that it was a defect in WebSphere Application server v 7.0.0.13. The regular expression matcher that attached the policy set/bindings to a JAX-WS call was not working. Hence we could not attach it to an individual service, but it worked when we attached it to the entire EAR. IBM provided us with a fix
{ "language": "en", "url": "https://stackoverflow.com/questions/7563005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I simulate ctrl-F5 with jQuery? So the refresh should discard the cache, how to do it with jQuery? A: The ability to modify the browser cache is outside the scope of what jQuery can do. A: This won't be possible. Just increment the version number to your javascript reference like this every time you wish to force a fresh download: <script language="javascript" src="scripts/script.js?ver=2"></script> Just to clarify, the appended ver parameter has no intrinsic value on the script src attribute as Slomojo pointed out. It was merely a way to address the problem of a forced file reload and also keep a neat versioning system. A: No jQuery required, pure JavaScript: location.reload(true); documentation See this article for a more in depth explanation. A: You can detect ctrl+F5 using following code $(document).keydown(function(e) { if (e.keyCode == 116 && e.ctrlKey) { alert('ctrl + F5'); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7563010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: JPA/hibernate order by subclass attribute Is it possible to query for entities of a base class, but order by an attribute of a subclass? For example, (JPA annotations omitted) class Base { int base; } class SubA extends Base { int subA; } class SubB extends Base { int subB; } and assume that the database contains instances of all 3 classes. I want to retrieve all Base instances, polymorphically, sorted on a attribute of the subclass. If the attribute doesn't exist, assume it's null. (Imagine all of these instances are shown in a table, with all attributes, and the user is allowed to sort on any attribute.) I was hoping for something like: select b from Base b order by b.subA but obviously the subA attribute isn't recognised. Is there some way to attempt a cast so the subA attribute can be used? A: Sorry, that isn't possible. But you can use something like this: TypedQuery<Base> baseQ = em.createQuery("SELECT b FROM Base b", Base.class); List<Base> resultList = baseQ.getResultList(); Collections.sort(resultList, new Comparator<Base>() { @Override public int compare(Base b1, Base b2) { ... } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7563012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ascii character not showing in browser I have an MVC Razor view @{ ViewBag.Title = "Index"; var c = (char)146; var c2 = (short)'’'; } <h2>@c --- @c2 --’-- ‘Why Oh Why’ & &#146;</h2> @String.Format("hi {0} there", (char)146) characters stored in my database in varchar fields are not rendering to the browser. This example demonstrates how character 146 doesn't show up How do I make them render? [EDIT] When I do this the character 146 get converted to UNICODE 8217 but if 146 is attempted to be rendered directly on the browser it fails public ActionResult Index() { using (var context = new DataContext()) { var uuuuuggghhh = (from r in context.Projects where r.bizId == "D11C6FD5-D084-43F0-A1EB-76FEED24A28F" select r).FirstOrDefault(); if (uuuuuggghhh != null) { var ca = uuuuuggghhh.projectSummaryTxt.ToCharArray(); ViewData.Model = ca[72]; // this is the character in question return View(); } } return View(); } A: @Html.Raw(((char)146).ToString()) or @Html.Raw(String.Format("hi {0} there", (char)146)) both appear to work. I was testing this in Chrome and kept getting blank data, after viewing with FF I can confirm the representation was printing (however 146 doesn't appear to be a readable character). This is confirmed with a readable character '¶' below: @Html.Raw(((char)182).ToString()) Not sure why you would want this though. But best of luck! A: You do not want to use character 146. Character 146 is U+0092 PRIVATE USE TWO, an obscure and useless control character that typically renders as invisible, or a missing-glyph box/question mark. If you want the character ’: that is U+2019 SINGLE RIGHT QUOTATION MARK, which may be written directly or using &#x2019; or &#8217;. 146 is the byte number of the encoding of U+2019 into the Windows Western code page (cp1252), but it is not the Unicode character number. The bottom 256 Unicode characters are ordered the same as the bytes in the ISO-8859-1 encoding; ISO-8859-1 is similar to cp1252 but not the same. Bytes 128–159 in cp1252 encode various typographical niceties like smart quotes, whereas bytes 128–159 in ISO-8859-1 (and hence characters 128–159 in Unicode) are seldom-used control characters. For web applications, you usually want to filter out the control characters (0–31 and 128–159 amongst a few others) as they come in, so they never get as far as the database. If you are getting character 146 out of your database where you expect to have a smart quote, then you have corrupt data and you need to fix it up before continuing, or possibly you are reading the database using the wrong encoding (quite how this works depends what database you're talking to). Now here's the trap. If you write: &#146; as a character reference, the browser actually displays the smart quote U+2019 ’, and, confusingly, not the useless control character that actually owns that code point! This is an old browser quirk: character references in the range &#128; to &#159; are converted to the character that maps to that number in cp1252, instead of the real character with that number. This was arguably a bug, but the earliest browsers did it back before they grokked Unicode properly, and everyone else was forced to follow suit to avoid breaking pages. HTML5 now documents and sanctions this. (Though not in the XHTML serialisation; browsers in XHTML parsing mode won't do this because it's against the basic rules of XML.) A: We finally agreed that the data was corrupt we have asked users who can't see this character rendered to fix the source data
{ "language": "en", "url": "https://stackoverflow.com/questions/7563014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# Linq to XML, get parents when a child satisfy condition I need some help. I have this xml document: <?xml version="1.0" encoding="utf-8"?> <MyItems> <Parent upc="A00000000000000000000001" sku="" archivo="pantalon1.jpg"> <Child upc="101" sku="" archivo="image##.jpg"> <GrandChild archivo="image##.jpg" /> </Child> <Child upc="102" sku="" archivo="image##.jpg"> <GrandChild archivo="image##.jpg" /> </Child> </Parent> <Parent upc="A00000000000000000000002" sku="" archivo="image##.jpg"> <Child upc="101" sku="" archivo="image##.jpg"> <GrandChild archivo="image##.jpg" /> </Child> <Child upc="102" sku="" archivo="image##.jpg"> <GrandChild archivo="image##.jpg" /> </Child> </Parent> <Parent upc="200" sku="" archivo="image##.jpg"> <Child upc="201" sku="" archivo="image##.jpg"> <GrandChild archivo="image##.jpg" /> </Child> <Child upc="202" sku="" archivo="image##.jpg"> <GrandChild archivo="image##.jpg" /> </Child> </Parent> </MyItems> Then, I'm trying to select all the 'Parents' where a 'Child' fulfils a condition. Example, all the parents which contains a child where, child attribute upc is equal to 101 I was studying this article: Select nodes based on properties of descendant nodes But I just can't get what I want. A: XDocument doc = ...; var targetUpc = 101; var query = doc.Descendants("Parent") .Where(p => p.Elements("Child") .Any(c => (int)c.Attribute("upc") == targetUpc) ); So what the query does is select all descendant elements named Parent where any of its child elements named Child have an attribute named upc that is equal to the target upc value, targetUpc. Hopefully you should be able to follow that. A: Use a Where with a nested Any. var xml = XElement.Parse(yourString); var result = xml.Elements("Parent").Where(parent => parent.Elements("Child").Any(child => child.Attribute("upc").Value == "101")); A: try this: string xml = @"<?xml version=""1.0"" encoding=""utf-8""?> <MyItems> <Parent upc=""A00000000000000000000001"" sku="""" archivo=""pantalon1.jpg""> <Child upc=""101"" sku="""" archivo=""image##.jpg""> <GrandChild archivo=""image##.jpg"" /> </Child> <Child upc=""102"" sku="""" archivo=""image##.jpg""> <GrandChild archivo=""image##.jpg"" /> </Child> </Parent> <Parent upc=""A00000000000000000000002"" sku="""" archivo=""image##.jpg""> <Child upc=""101"" sku="""" archivo=""image##.jpg""> <GrandChild archivo=""image##.jpg"" /> </Child> <Child upc=""102"" sku="""" archivo=""image##.jpg""> <GrandChild archivo=""image##.jpg"" /> </Child> </Parent> <Parent upc=""200"" sku="""" archivo=""image##.jpg""> <Child upc=""201"" sku="""" archivo=""image##.jpg""> <GrandChild archivo=""image##.jpg"" /> </Child> <Child upc=""202"" sku="""" archivo=""image##.jpg""> <GrandChild archivo=""image##.jpg"" /> </Child> </Parent> </MyItems>"; XElement MyItems = XElement.Parse(xml); var parents = MyItems.Elements("Parent").Where(parent => parent.Elements("Child").Any(child => child.Attribute("upc").Value == "101")); foreach (var parent in parents) Console.WriteLine(parent.Attribute("upc").Value); A: This works nicely for me: var query = from p in XDocument.Parse(xml).Root.Elements("Parent") where ( from c in p.Elements("Child") where c.Attribute("upc").Value == "101" select c ).Any() select p;
{ "language": "es", "url": "https://stackoverflow.com/questions/7563020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: NullPointerException in Android onClick ERROR/AndroidRuntime(545): at no.jarle.f02.myActivity.onClick(myActivity.java:38) public void onClick( View v ) { tvTextView.setText(editText1.getText()); <--- line 38 } <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".myActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> The TextView should display the text user typed in the EditText when the button is clicked. Instead it obviously crashes and i can't seem to find the problem. Any help is greatly appreciated :) A: Use this: if (editText1.getText().toString().trim() > 0) tvTextView.setText(editText1.getText().toString()); A: My guess is you are having empty editText1 when you click on the button. So before you do setting text, just make sure you have something in the editText1. For example if (editText1.getText().length>0) tvTextView.setText(editText1.getText()); A: Maybe your TextView and/or EditText are only instanced on onCreate Method and they don't have "life" on your onClick method. Is your class something like this? Class YourClass { private EditText editText1; private TextView tvTextView; public void `onCreate`(Bundle arg) { super.onCreate(savedInstanceState); setContentView(R.layout.main) editText1 = (EditText) findViewById(R.id.editText1); tvTextView = (TextView) findViewById(R.id.tvTextView); } public void onClick(View v) { tvTextView.setText(editText1.getText()); } ? if your TextView and EditText are not attribute, you cant manipulate them on onClick. or you can get the instance of them on onClick method using findViewById before try to setText.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript to remove text I am trying to remove the text, "Hi Mom" from an html page using javascript after it loads. I can not use any framework like jQuery. I can use the DOM, but will not know where it is, other than it's wrapped in a tag somewhere. Can this be done in plain old Javascript? A: Here's a pretty simple DOM walk you can do. There could be improvements if you thought there may be more than once occurrence in the same text node, but it doesn't sound like that's the case. DEMO: http://jsfiddle.net/UrNWb/ var text_to_remove = "Hi Mom"; function dom_walk( el ) { if( el.nodeType === 1 && el.childNodes.length ) { if( el.nodeName.toLowerCase() !== 'script' ) { for( var i = 0; i < el.childNodes.length; i++ ) { dom_walk( el.childNodes[ i ] ); } } } else if( el.nodeType === 3 ) { if( el.data.indexOf( text_to_remove ) !== -1 ) { el.data = el.data.replace( text_to_remove, '' ); } } } dom_walk( document.body ); A: Easiest solution: function removeText(s) { var el, els = document.getElementsByTagName('*'); var node, nodes; for (var i=0, iLen=els.length; i<iLen; i++) { el = els[i]; if (el.tagName.toLowerCase() != 'script') { nodes = el.childNodes; } else { nodes = []; } for (var j=0, jLen=nodes.length; j<jLen; j++) { node = nodes[j]; if (node.nodeType == 3) { node.data = node.data.replace(s, ''); } } } } window.onload = function() { removeText('hi mom'); } You could also do a recursive version, but the above is just simpler. A: document.body.innerHTML = document.body.innerHTML.replace("Hi Mom", "") should be a decent start.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WindowsImagingComponent or System.Windows.Media.Imaging I need to work with some bitmaps in managed code and save them as PNG files. Should I use Microsoft.WindowsAPICodePack.DirectX.WindowsImagingComponent, or System.Windows.Media.Imaging? They both seem very similar, and I'm not sure why I would choose one over the other. Can anybody compare and contrast them? A: They both use WIC, that's why they are so similar. The Windows API Code pack is retired content, you'll want to use the WPF namespace since it is available on .NET 3 and up and doesn't require a separate install. A: Microsoft.WindowsAPICodePack.DirectX.WindowsImagingComponent is in the Windows API Code Pack, which is a source code library that you would need to build into your application. On the other hand, System.Windows.Media.Imaging is included in the .NET Framework. If you have no other use for the Windows API Code Pack, I would recommend using System.Windows.Media.Imaging. I believe the inclusion of a WIC API in the Windows API Code Pack is primarily for interoperability with the DirectX APIs in the Code Pack, which have no equivalents in the .NET Framework.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: oodle.com API - Use it with PHP? I am working on a web-application using PHP/Ajax , It include an RSS aggregator of blog posts , I want to add a new functionality that gives us the ability to post into oodle or vast. I tried to integrate the oodle.com API with PHP but I didn't find enough support . http://www.oodle.com/info/feed Did any one try to work with this API ? , I am looking for help. A: As far as I understand, you may use the form http://www.oodle.com/submitfeed to register a feed. oodles reads items from this feed automatically.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Putting $variable string into "string" I have question because i think i doing unnecessary job. e.g. $phone = "222-333-444" echo "Phone number is " . $phone; $phone['2'] = "222-333-444" echo "Phone number is " . $phone['2']; Please explain is there ANY ANY ANY reason to do it the way above rather than" $phone = "222-333-444" echo "Phone number is $phone"; $phone['2'] = "222-333-444" echo "Phone number is $phone['2']"; A: Both are right ways to print a variable. There's no right or wrong, just different approaches. A: No, actually both are equivalent. I personally always write this, because for me it is far more explicit: echo "Phone number is " . $phone['2']; A: The only reason would be consistency and clarity. Concatenation is faster than interpolation, but the difference is so negligible it should not define your choice. I prefer the second personally. A: No, there is not difference. second example should be like this: $phone = "222-333-444" echo "Phone number is {$phone}"; $phone['2'] = "222-333-444" echo "Phone number is {$phone['2']}"; A: No, there is no reason at all, unless your variable is an array and you need to access a specific index.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: I have to make public URLs for private actions? Lets say I have a website where I allow users to perform actions (communicate, post photos, etc) on their friends on my site (they are friends on Facebook). This is private information between User A and User B. Before the new Open Graph [beta] I would encode as much information as needed in the original POST request. But now Facebook has moved to a more "callback" scheme where I do a simple POST and provide a URL which FB then hits via GET and I provide series of og: tags to describe the core content - all of this is the information that I would have PREVIOUSLY provided in the first and only POST request. Here in lies the problem though: I have to provide a completely un-authenticated URL for FB to hit (the GET) and it has to be the same URL the app will use in the Timeline, so I cannot make a special, secure by obscurity URL as the callback, but provide a "friendly" URL (which would require authentication) to be used as the click through URL in the timeline. Am I understanding this correctly? EDIT: this would also be a different issue if FB when doing the callback GET would provide some kind of authentication data in the URL or HTTP headers, but after examining the complete HTTP details in the GET request FB is giving us nothing other than a special User-Agent that we can use to differentiate the request. UPDATE: I believe this question is driving at the same issue. IF we can provide a different og:url on our gibberish "callback" page then it would make things a lot easier. Can You Have Your OpenGraph Object Link to a Different URL? A: Are you sure open graph is the best solution for your application? By definition the actions go into a user's timeline so if you simply want to share a generic action "i.e. Ted answered Cody's question" but not link to that answer as it is private, why not build a static page with the generic information in og: tags and place your link back to that. This way you can share the activity without exposing the details. In our application many postings occur in in-accessible pages so we've altered public pages to dynamically expose the right og: data when Facebook goes looking. It's not perfect as users can see it but this way we can show nothing for a private entry and everything on a public one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Can I add a newline and an HTML link in UITextView? Messing about with interface builder for the first time, exploring my options. Text seems to be in one long batch--found another thread where someone was importing an SQL db, but I just want to type something with a CR. Or should I just make a new TextView item for that? I've also found threads complaining about autodetected links, but I'm not getting those—links are simply treated as plain text. Not that surprising, but is there a way to turn autodetect on somehow? A: In Interface Builder, there is an "Detection" panel where you can check a checkbox to detect links. But it isn't detecting HTML, just text that is in the form of a URL. As for carriage returns, though, a UITextView should be able to handle those just fine. If you want to deal with HTML, though, you should look at a UIWebView.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to recover bluetooth packet loss?? Android I'm currently creating an Android App where it collects data through bluetooth and draw a real time graph but it seems like after short while there is packet loss and graph comes out weird. I've been searching for a while how to recover the loss but seems like there is no way.... only TCP/IP or UDP has.... Since I need all the data, I can't ignore the packets that doesn't have starting bit or end bit. Is there anyway to prevent the loss or recover the loss completely? Thanks A: Use of RFComm on Android already has built in packet order and reliability like TCP. You should try running tests to see if the Android device is too far away, receiving accurate information, has a bad Bluetooth module, or if the sensor is at fault.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using OUTPUT with joined tables Why doesn't the following work? INSERT INTO dbo.Pending_Break (Pending_Pod_ID, Break_Date_Time, Break_Length, Booked_Length) OUTPUT INSERTED.Pending_BH_ID -- This is the inserted identity , INSERTED.Pending_Pod_ID , INSERTED.Break_Name , INSERTED.Break_Date_Time , pb.PENDING_BH_ID -- complains on this one INTO #InsertedPendingBreaks SELECT ippod.Pending_Pod_ID, pb.Break_Date_Time pb.break_length, 0 FROM PendingBreak pb JOIN InsertedPod ippod ON ... Can I not use anything other than Inserted or Deleted in the OUTPUT clause? A: Can I not use anything other than Inserted or Deleted in the OUTPUT clause? No you can't. At least not with an insert. In SQL Server 2008 you can convert your insert to a merge statement instead and there you can use values from the source table in the output clause. Have a look at this question how to do that in SQL Server 2008. Using merge..output to get mapping between source.id and target.id A: The inserted and deleted tables are available only in DML triggers. I'm not sure if you just pulled a code snippet out of a trigger, but if that is a standalone batch then it won't work. Also, there is no updated table. An update is a delete and then an insert for this. deleted contains the old data and inserted contains the new data on an UPDATE.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Javascript - Input field On Change Set Cookie of Value Thanks to anyone in advance that can help me in my issue. I'm simply trying to save the value of a form input type="text" to a cookie when the input value has changed. Think I almost had it, but I cannot get it to work. Here is what I have so far -This is the javascript Set_cookie Function. function Set_Cookie( name, value, expires, path, domain, secure ) { var today = new Date(); today.setTime( today.getTime() ); if ( expires ) { expires = expires * 1000 * 60 * 60 * 24; } var expires_date = new Date( today.getTime() + (expires) ); document.cookie = name + "=" +escape( value ) + ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + ( ( path ) ? ";path=" + path : "" ) + ( ( domain ) ? ";domain=" + domain : "" ) + ( ( secure ) ? ";secure" : "" ); } -This is the Function that is suppose to save the input on change. $(document).ready(function () { $('#inputText1').change(function () { Set_Cookie( 'inputText1', .val($(this)), '', '/', '', '' ); }); }); -Input Field input type="text" name="inputText1" id="inputText1" Thanks again to anyone who can help. A: Give this project a try http://plugins.jquery.com/project/Cookie And this tutorial will help you http://www.komodomedia.com/blog/2008/07/using-jquery-to-save-form-details/
{ "language": "en", "url": "https://stackoverflow.com/questions/7563061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: cakephp - Unable to retrieve session in controller I am having problems with cakephp session. I created a session in my controller (users/home) then I attempted to retrieve it in another controller, but I wasn't able to get it. Also, I created another session in another controller and was unable to retrieve it in the users controller. I would like to know how to stop this behaviour. Thanks Note: I use the session component. A: Make sure you have $components = array('Session'); (and any other app wide components) in your AppController. http://book.cakephp.org/view/1311/Methods
{ "language": "en", "url": "https://stackoverflow.com/questions/7563062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how do i create all possible letter combinations with php I looked around stack overflow and couldn't find a sample on what I needed. how would I create something like this? so lets say i want all possible combinations of up to 5 characters. the output would look like this: aaaaa aaaab aaaac aaaad ..etc A: Ok, because I believe that you don't have any clue what to do, I will give you a short code example. It is not perfect and its written down in a couple of minutes but it should bring you on the right way: $values = 'abcd'; run(strlen($values), 0 ); function run($length, $pos, $out = '' ) { global $values; for ($i = 0; $i < $length; ++$i) { if ($pos < $length ) { run($length, $pos + 1, $out . $values[$i]); } } echo $out.PHP_EOL; } Next time try first and post your question with the code you have written even if it is nearly nothing and looks stupid for you. But in the end it will show that you make own work and don't hope to get your work done for free without thinking by yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to calculate the number of "Tuesdays" between two dates in TSQL? I'm trying to figure out how to calculate the number of "Tuesdays" between two dates in TSQL? "Tuesday"could be any value. A: @t-clausen.dk & Andriy M as response to t-clausen.dks response and comments The query uses the fact that 1900-01-01 was a monday. And 1900-01-01 is the date 0. select dateadd(day,0,0) The second parameter into the datediff-function is the startdate. So you are comparing '1899-12-26' with your @to-date and '1899-12-26' is a tuesday select datename(dw,dateadd(day, 0, -6)), datename(dw, '1899-12-26') Same thing about the second date that uses the same fact. As a matter of fact you can compare with any known tuesday and corresponding wednesday (that isnt in the date interval you are investigating). declare @from datetime= '2011-09-19' declare @to datetime = '2011-10-15' select datediff(day, '2011-09-13', @to)/7-datediff(day, '2011-09-14', @from)/7 as [works] ,datediff(day, '2011-10-18', @to)/7-datediff(day, '2011-10-19', @from)/7 as [works too] ,datediff(day, '2011-09-27', @to)/7-datediff(day, '2011-09-28', @from)/7 as [dont work] Basically the algorithm is "All Tuesdays minus all Wednesdays". A: Thank you t-clausen.dk, Saved me few days. To get no of instances of each day: declare @from datetime= '3/1/2013' declare @to datetime = '3/31/2013' select datediff(day, -7, @to)/7-datediff(day, -6, @from)/7 AS MON, datediff(day, -6, @to)/7-datediff(day, -5, @from)/7 AS TUE, datediff(day, -5, @to)/7-datediff(day, -4, @from)/7 AS WED, datediff(day, -4, @to)/7-datediff(day, -3, @from)/7 AS THU, datediff(day, -3, @to)/7-datediff(day, -2, @from)/7 AS FRI, datediff(day, -2, @to)/7-datediff(day, -1, @from)/7 AS SAT, datediff(day, -1, @to)/7-datediff(day, 0, @from)/7 AS SUN A: declare @from datetime= '9/20/2011' declare @to datetime = '9/28/2011' select datediff(day, -6, @to)/7-datediff(day, -5, @from)/7 * *find the week of the first monday before the tuesday in @from. *find the week of the first monday after @to *subtract the weeks A: Check out this question: Count work days between two dates There are a few ways you can leverage the answer to that question for yours as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Inserting in MySQL Table Error I wonder is anyone can help me with this annoying problem. Trying to insert some data into a table. In the mean time, I want to leave out some fields and not insert something there. For some reason I'm getting Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING error. Is there something I'm doing wrong below? Your help will be appreciated. <?php function sqlEscape($string){ return "'".mysql_real_escape_string($string)."'"; } if( $_GET['location'] == '' || $_GET['name'] == '' || $_GET['school'] == '' || $_GET['reason'] == '' || $_GET['address'] == '' || $_GET['postcode'] == '' || $_GET['email'] == '' || $_GET['telephone'] == '') { exit('You missed a value'); } include('theConfig.php'); $con = mysql_connect($host, $username, $password) or die(mysql_error()) ; if (!$con){ die('Could not connect: ' . mysql_error()); } mysql_select_db($db, $con); //$description = mysql_real_escape_string($_GET[description]); $sql = sprintf('INSERT INTO applications (location, name, school, reason, address, postcode, email, telephone, town, county, state, country) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s,'','')', sqlEscape($_GET['location']), sqlEscape($_GET['name']), sqlEscape($_GET['school']), sqlEscape($_GET['reason']), sqlEscape($_GET['address']), sqlEscape($_GET['postcode']), sqlEscape($_GET['email']), sqlEscape($_GET['telephone'])); if (!mysql_query($sql,$con)){ die('Error: ' . mysql_error()); } header('Location: thankyou.php'); mysql_close($con) ?> A: You should have values set for town and county - or set with default value (empty string like the others): $sql = sprintf("INSERT INTO applications (location, name, school, reason, address, postcode, email, telephone, town, county, state, country) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, '','','','')", ... ) Edit: Also - use double quotes to surround the first sprintf parameter as single quotes are used within... A: You use single quotes for the string in your sprintf() call, but you also use single quotes inside the string as well. A: $sql = sprintf('INSERT INTO applications (location, name, school, reason, address, postcode, email, telephone, town, county, state, country) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s,'','')', You have '', '')' which is incorrect, b/c the first quote in this sequence closes the string, so it's actually three strings togather: 'INSERT ... ', then ', ', and then ')'. You must escape quotes in the string with backslash or use double quotes to enclose whole string: (escaping) $sql = sprintf('INSERT INTO applications (location, name, school, reason, address, postcode, email, telephone, town, county, state, country) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s,\'\',\'\')', (using double quotes) $sql = sprintf("INSERT INTO applications (location, name, school, reason, address, postcode, email, telephone, town, county, state, country) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s,'','')", A: Try changing function sqlEscape($string){ return "'".mysql_real_escape_string($string)."'"; } to function sqlEscape($string){ return mysql_real_escape_string($string); } or better yet just throw it in your sprintf $sql = sprintf('INSERT INTO applications (location, name, school, reason, address, postcode, email, telephone, town, county, state, country) VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s','','')', mysql_real_escape_string($_GET['location']), etc... note I changed %s to '%s'
{ "language": "en", "url": "https://stackoverflow.com/questions/7563070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using a class/struct/union over multiple cpp files C++ I am trying to create a class in C++ and be able to access elements of that class in more than one C++ file. I have tried over 7 possible senarios to resolve the error but have been unsuccessful. I have looked into class forward declaration which doesen't seem to be the answer (I could be wrong). //resources.h class Jam{ public: int age; }jam; //functions.cpp #include "resources.h" void printme(){ std::cout << jam.age; } //main.cpp #include "resources.h" int main(){ printme(); std::cout << jam.age; } Error 1 error LNK2005: "class Jam jam" (?jam@@3VJam@@A) already defined in stdafx.obj Error 2 error LNK1169: one or more multiply defined symbols found I understand the error is a multiple definiton because I am including resources.h in both CPP files. How can I fix this? I have tried declaring the class Jam in a CPP file and then declaring extern class Jam jam; for each CPP file that needed to access the class. I have also tried declaring pointers to the class, but I have been unsuccessful. Thank you! A: You're declaring the structure Jam and creating a variable called jam of this type. The linker is complaining that you've got two (or more) things called jam, because your header causes each .cpp file to declare one of its own. To fix this, change your header declaration to: class Jam{ public: int age; }; extern Jam jam; And then place the following line in one of your .cpp sources: Jam jam; A: You need to separate your definition from your declaration. Use: //resources.h class Jam{ public: int age; }; // Declare but don't define jam extern Jam jam; //resources.cpp // Define jam here; linker will link references to this definition: Jam jam; A: The variable jam is defined in the H file, and included in multiple CPP classes, which is a problem. Variables shouldn't be declared in H files, in order to avoid precisely that. Leave the class definition in the H file, but define the variable in one of the CPP files (and if you need to access it globally - define it as extern in all the rest). For example: //resources.h class Jam{ public: int age; }; extern Jam jam; // all the files that include this header will know about it //functions.cpp #include "resources.h" Jam jam; // the linker will link all the references to jam to this one void printme(){ std::cout << jam.age; } //main.cpp #include "resources.h" int main(){ printme(); std::cout << jam.age; } A: As a first step you should separate the definition of the class and declaration of an instance. Then use extern in resources.h and declare the instance in a CPP. Like this: //resources.h class Jam{ public: int age; }; extern Jam jam; //functions.cpp #include "resources.h" void printme(){ std::cout << jam.age; } //main.cpp #include "resources.h" Jam jam; int main(){ printme(); std::cout << jam.age; } A: Use the pragma once directive, or some defines to make sure a header doesn't get included more than once in your code. Example using pragma directive (example.h): #pragma once // Everything below the pragma once directive will only be parsed once class Jam { ... } jam; Example using defines (example.h): #ifndef _EXAMPLE_H #define _EXAMPLE_H // This define makes sure this code only gets parsed once class Jam { ... } jam; #endif
{ "language": "en", "url": "https://stackoverflow.com/questions/7563074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Using hashmaps, breaking loops and user input in java I'm fairly new to programming in general and need some help. I am using the Java.util.TimeZone to retrieve the IDs (city names) and their time zones. I am using a hashmap to implement this. I have put the city names and the time zones in the map and I am now trying to ask the user to enter a city they wish to get the time zone of. However, in my loop I have a validation check to make sure the city name is in the hashmap. Not only is it not working but the loop also does not break. It correctly puts out the time it is currently but not the correct timezone for the city (I have typed various city names and all have about the same timezone). After printing out the local time it is in the city the user can choose to end the program by "saying yes". If the user enters yes then the loop should break and the the program should end. If they enter anything else it should continue. Could someone please help me fix this! Here is my code. import java.util.*; import java.util.TimeZone; import java.util.Date; import java.text.DateFormat; import java.util.HashMap; class Maps { public static void main(String[] args) { String[] Zone = TimeZone.getAvailableIDs(); int i = 0; for (i = 0; i < Zone.length; i++) { String zone1 = Zone[i].replaceAll("_", " "); if (zone1.indexOf('/') != -1) { zone1 = zone1.substring(zone1.indexOf('/') + 1); } TimeZone tz = TimeZone.getTimeZone(zone1); HashMap hm = new HashMap(); HashMap<String, Integer> map = new HashMap<String, Integer>(); hm.put(zone1, tz); // System.out.println(hm); while (hm != null) { java.util.Scanner input = new java.util.Scanner(System.in); System.out.println("City?"); String city = input.nextLine(); boolean CityExist = hm.containsKey(city); if (CityExist == true) { System.out .println("I can not find a match to the city, sorry. "); break; } TimeZone tz2 = TimeZone.getTimeZone(city); DateFormat timeFormatter = DateFormat.getTimeInstance(); Date now = new Date(); System.out.println("Here: " + timeFormatter.format(now)); System.out.print("Local Time: "); timeFormatter.setTimeZone(tz2); System.out.println(timeFormatter.format(now)); System.out .println("If you would like to quit please enter yes: "); String user = input.nextLine(); if (user.equals("yes") || user.equals("Yes")) { break; } } } } } A: Looks like you have the logic inverted: if CityExist then there was no match? A: Please format your code next time. Doing this, you will see that your first for loop is not closed and you are doing while loop still inside your for loop. Solution, put the close bracket } before while loop.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I make instructions appear at the user's request? I need to provide information for various clients when they log in to build a profile. I will be using HTML and Javascript for this purpose. What I would like is a concise set of instructions followed by an option to show more detailed instructions. If the client chooses to see the more detailed instructions, the field (ideally) expands to show more content. Other ideas that achieve a similar result are also welcome, as are comments that simply point me in the right direction. Preliminary research hasn't turned up much for me; I imagine this is largely due to being a novice and not knowing what to look for. Is this a conditional visibility issue, or is that something else entirely? Many thanks for any help. A: Place the hidden content in a separate container element with its display initially set to none. Then, add an onclick handler to a link that shows the content. That handler should set the display value to block or inline. Here is one way to do it (there are many). Set up your HTML something like this: <p> [Instruction text here] <a href="#" onclick="expandContent(this)">more ...</a><span class="more"> [Additional content here]</span> </p> Some CSS to initially hide the additional content: .more { display: none; } Create your expandContent() function: function expandContent(link) { link.nextSibling.style.display = "inline"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7563080", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Key-up event in Emacs, or poll keyboard state? In emacs is there is a way to check for a key-up event, or, alternatively, is it possible to poll the keyboard and check if a key is currently pressed? A: Emacs elisp API don't allow you get info how long key pressed and if it still currently pressed. Emacs work not only in GUI mode but also in terminals, where this info is not available (as hardware don't support it). So GNU Emacs written in way that it can not pull such info to you. If you want more complete answer ask on emacs-devel@gnu.org but be careful do not be offtopic. help-gnu-emacs@gnu.org is primary list for Emacs questions. Also check: EmacsMailingLists EmacsNewsgroups StackOverflow is not good site for question about Emacs internals...
{ "language": "en", "url": "https://stackoverflow.com/questions/7563086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Converting ^M Character to Whitespace without Line Break using PHP I'm trying to convert ^M character to a white space character, but having hard time doing this. In PHP, I used "wb" option so, it wouldn't write DOS character into the file. fopen("file.csv", "wb") It was successful, but still has line breaks instead of ^M $fp = fopen("file.csv", "wb"); $description =nl2br( $product->getShortDescription()); $line .= $description . $other_variables . "\n"; fputs($fp, $line); but I still see line break within the description, is there any way to remove ^M and replace it with possibly a whitespace. Also used dos2unix, when it was in regular file "w" mode. It removes all ^M characters, but the file still has line breaks where there was ^M. I really need it to be all on one line for my CSV file to work. Thank you. A: I think you're asking how to remove all the newline/line feed/carriage return characters from the description. If so: $description =str_replace(array("\r", "\n"), '', nl2br($product->getShortDescription());
{ "language": "en", "url": "https://stackoverflow.com/questions/7563088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Data constructor in template haskell I'm trying to create the ring Z/n (like normal arithmetic, but modulo some integer). An example instance is Z4: instance Additive.C Z4 where zero = Z4 0 (Z4 x) + (Z4 y) = Z4 $ (x + y) `mod` 4 And so on for the ring. I'd like to be able to quickly generate these things, and I think the way to do it is with template haskell. Ideally I'd like to just go $(makeZ 4) and have it spit out the code for Z4 like I defined above. I'm having a lot of trouble with this though. When I do genData n = [d| data $n = $n Integer] I get "parse error in data/newtype declaration". It does work if I don't use variables though: [d| data Z5 = Z5 Integer |], which must mean that I'm doing something weird with the variables. I'm not sure what though; I tried constructing them via newName and that didn't seem to work either. Can anyone help me with what's going on here? A: The Template Haskell documentation lists the things you are allowed to splice. A splice can occur in place of * *an expression; the spliced expression must have type Q Exp *an type; the spliced expression must have type Q Typ *a list of top-level declarations; the spliced expression must have type Q [Dec] In both occurrences of $n, however, you're trying to splice a name. This means you can't do this using quotations and splices. You'll have to build declaration using the various combinators available in the Language.Haskell.TH module. I think this should be equivalent to what you're trying to do. genData :: Name -> Q [Dec] genData n = fmap (:[]) $ dataD (cxt []) n [] [normalC n [strictType notStrict [t| Integer |]]] [] Yep, it's a bit ugly, but there you go. To use this, call it with a fresh name, e.g. $(genData (mkName "Z5"))
{ "language": "en", "url": "https://stackoverflow.com/questions/7563092", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: ExtendedFormAuthenticator in JBoss 7 I'm porting a legacy application from JBoss 4.2.3 to JBoss 7 (the web profile version). They used a custom login module and used a valve to capture the login failure reason into j_exception. They did this by putting context.xml into the web-inf directory of the war, with the following contents: <!-- Add the ExtendedFormAuthenticator to get access to the username/password/exception -> <Context cookies="true" crossContext="true"> <Valve className="org.jboss.web.tomcat.security.ExtendedFormAuthenticator" includePassword="true" ></Valve> </Context> The login is working for me, but not that valve. When there's a login exception, the j_exception is still empty and the logic that depends on analyzing why the login was rejected fails. According to this link: http://community.jboss.org/wiki/ExtendedFormAuthenticator, everything looks right. However that link is very old, and it's possible things have changed since then. What's the new way? A: It seems that security valves are now defined directly in jboss-web.xml, like this: <jboss-web> <security-domain>mydomain</security-domain> <valve> <class-name>org.jboss.web.tomcat.security.ExtendedFormAuthenticator</class-name> <param> <param-name>includePassword</param-name> <param-value>true</param-value> </param> </valve> </jboss-web> However, the ExtendedFormAuthenticator class wasn't ported to JBoss 7.0.1. A ticket has been opened for me, so it should be present in JBoss 7.1.0: https://issues.jboss.org/browse/AS7-1963
{ "language": "en", "url": "https://stackoverflow.com/questions/7563095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL Server: FAILING extra records I have a tableA (ID int, Match varchar, code char, status = char) ID Match code Status 101 123 A 102 123 B 103 123 C 104 234 A 105 234 B 106 234 C 107 234 B 108 456 A 109 456 B 110 456 C I want to populate status with 'FAIL' when: For same match, there exists code different than (A,B or C) or the code exists multiple times. In other words, code can be only (A,B,C) and it should exists only one for same match, else fail. So, expected result would be: ID Match code Status 101 123 A NULL 102 123 B NULL 103 123 C NULL 104 234 A NULL 105 234 B NULL 106 234 C NULL 107 234 B FAIL 108 456 A NULL 109 456 B NULL 110 456 C NULL Thanks A: No guarantees on efficiency here... update tableA set status = 'FAIL' where ID not in ( select min(ID) from tableA group by Match, code)
{ "language": "en", "url": "https://stackoverflow.com/questions/7563096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can I restore the files that I have deleted in Eclipse? I'm working on eclipse and sometimes I have to delete some lines of code that indeed I prefer to backup on a notepad file (because I never know if that lines of code could be useful in another moment), so I have to select all the code I have to delete, ctrl+x, open a text editor, ctrl+v, and save it somewhere. I was searching for a "code recycle bin plugin", so that I can select the code to trash, right click and "send to code recycle bin"; and in the future the deleted code is still there if I need it. A: You can achieve a similar effect by configuring your workspace Local History settings: A: What I'm gathering from your question is that you often modify code in such a way that you're not sure if it will work after you modify it. What you need is a software versioning system. Often, because a coder may introduce new code that is faulty or introduces unnecessary defects, we need to revert back to the last working version. There is an easier way than "Ctrl+X"ing the code and placing it in a "recycle bin" for future use. Try using a software versioning system such as Git for better results. The source code is available online, and you can get an account for free. In short, version control system will stop you from having to juggle files unnecessarily. A: There is something similar which will resolve your issue, the Eclipse Remus project. You can download the plugin via the Eclipse Marketplace. After installation you can open the Remus Navigation view in your Java perspective, select the code and drop the code into the Navigation-Structure of the Remus Navigation view. The dropped source-code will be saved.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Send reminder: 2 months, 1 month and one week before expiration date I was wondering how I can send reminder to my users (via email) two months, a month and one week before their account expiration date (eg. $accountExp which is a unix timestamp)? A: You'll need to set up a cron job to work out if an email needs to be sent and send it, and use the date_diff sql function to calculate what needs to be sent in the script A: set up a cron job to run a php script that will fetch entries in this way e.g. /* send those 2 months before exp date*/ $sql='select * FROM users WHERE exp_date_unix>='.(time()+86400*60); or if you use the datetime/timestamp field the condition would be smth like DATE_DIFF(exp_date_unix, CURRENT_TIMESTAMP) >=60;
{ "language": "en", "url": "https://stackoverflow.com/questions/7563110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I add a boolean column to an SQL result set based on comparison with a second table Essentially I have the first part of the question answered and here is the SQL statement I have so far... SELECT DbaRolePrivs.GRANTEE, DbaRolePrivs.GRANTED_ROLE, ApplicationRoleDefinition.ROLE, ApplicationRoledefinition.description_tx, CASE WHEN GRANTED_ROLE = ROLE AND GRANTEE = USERNAME THEN 'T' ELSE 'F' END AS checkMark FROM DBA_ROLE_PRIVS DbaRolePrivs, APPLICATION_ROLE_DEFINITION ApplicationRoleDefinition Here is the logic I am trying to perform in plain english. "Given a list of all roles and their descriptions, mark each role as TRUE or FALSE based on if the current selected USERNAME has been granted that role based on their own GrantedRoles list." Right now it is of course returning a double list since the "case when" section compares each of the granted roles with the total list of roles. (I say duplicate because the test user only has two roles, in the current SQL query it will return a row per granted role for every possible role. I've barely worked with SQL so I'm more used to C++, Objective-C, etc. Really all I need in the "case when" section is to check if the current ROLE exists at all in the GRANTED_ROLE column. I've seen the EXISTS function but that seems to be meant solely for result sets such as "WHERE EXISTS." Thanks in advance, I know it's probably simple for anyone whose worked with databases often, I've only just started. A: You need to outer join and then test whether the join was successful or not. If the outer join fails a row is still returned but all the DbaRolePrivs columns will be null SELECT DbaRolePrivs.GRANTEE, DbaRolePrivs.GRANTED_ROLE, ApplicationRoleDefinition.ROLE, ApplicationRoledefinition.description_tx, NVL2( DbaRolePrivs.GRANTED_ROLE, 'T', 'F' ) AS checkMark FROM DBA_ROLE_PRIVS DbaRolePrivs , APPLICATION_ROLE_DEFINITION ApplicationRoleDefinition WHERE ApplicationRoleDefinition.ROLE = DbaRolePrivs.GRANTED_ROLE (+) AND USERNAME = DbaRolePrivs.GRANTEE (+)
{ "language": "en", "url": "https://stackoverflow.com/questions/7563112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java SQL output format table result I got everything working and it prints the right result with header (column name) and value. However I wanted to change a plain and unorganized result into a really nice output table format just like MySql table result with dash lines from query. How do I do that? Statement statement = conn.createStatement(); ResultSet rs = statement.executeQuery("SELECT * FROM quarter"); ResultSetMetaData rsMetaData = rs.getMetaData(); int numberOfColumns = rsMetaData.getColumnCount(); for(int i = 1; i <= numberOfColumns; i++) { System.out.print(rsMetaData.getColumnLabel(i) + " "); } System.out.println(); while (rs.next()) { for(int e = 1; e <= rsMetaData.getColumnCount(); e++) { System.out.print(rs.getString(e) + " "); } System.out.println(); } A: You can use String.format() method with appropriate format string. For instance, StringBuilder sb=new StringBuilder(); for(int i = 1; i <= numberOfColumns; i++) { sb.append(String.format("| %-10s",rsMetaData.getColumnLabel(i))); } A: You can have function for that. Change the parameter as need while calling. public static void printHeader(ResultSet rs, char symbol, int width) throws Exception { ResultSetMetaData rsmd = rs.getMetaData(); int nCols = rsmd.getColumnCount(); for(int i = 1; i <= nCols; ++i) System.out.printf("%-10s ", rsmd.getColumnLabel(i)); System.out.printf("\n"); for(int i = 0; i < width; ++i) System.out.printf("%c", symbol); } //call <br> printHeader(rs,'-',70);
{ "language": "en", "url": "https://stackoverflow.com/questions/7563116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Saving an image of a UIElement rendered larger than it appears on screen I have a chart that I'm displaying to the user and I want to be able to export the chart as an image to disk so they can use it outside of the application (for a presentation or something). I've managed to get the basic idea working using PngBitmapEncoder and RenderTargetBitmap but the image I get out of it is way to small to really be usable and I want to get a much larger image. I tried to simply increase the Height and Width of the control I was wanting to render, but the parent seems to have direct control on the render size. From this I tried to duplicate the UIElement in memory but then the render size was (0,0) and when I tried to use methods to get it to render, such as Measure() Arrange() and UpdateLayout() they throw exceptions about needing to decouple the parent to call these, but as it's in memory and not rendered there shouldn't be a parent? This is all done with Visiblox charting API Here is what I've got currently, except it doesn't work :( var width = 1600; var height = 1200; var newChart = new Chart { Width = width, Height = height, Title = chart.Title, XAxis = chart.XAxis, YAxis = chart.YAxis, Series = chart.Series}; Debug.WriteLine(newChart.RenderSize); var size = new Size(width, height); newChart.Measure(size); newChart.Arrange(new Rect(size)); newChart.UpdateLayout(); Debug.WriteLine(newChart.RenderSize); var rtb = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32); rtb.Render(newChart); var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(rtb)); using (var stream = fileDialog.OpenFile()) encoder.Save(stream); I've gotten a bit closer, it now render the graph background the axis' etc. but just not the actual lines that are being graphed. Below is an updated source public static void RenderChartToImage(Chart elementToRender, string filename) { if (elementToRender == null) return; Debug.Write(elementToRender.RenderSize); var clone = new Chart(); clone.Width = clone.Height = double.NaN; clone.HorizontalAlignment = HorizontalAlignment.Stretch; clone.VerticalAlignment = VerticalAlignment.Stretch; clone.Margin = new Thickness(); clone.Title = elementToRender.Title; clone.XAxis = new DateTimeAxis(); clone.YAxis = new LinearAxis() { Range = Range<double>)elementToRender.YAxis.Range}; foreach (var series in elementToRender.Series) { var lineSeries = new LineSeries { LineStroke = (series as LineSeries).LineStroke, DataSeries = series.DataSeries }; clone.Series.Add(lineSeries); } var size = new Size(1600, 1200); clone.Measure(size); clone.Arrange(new Rect(size)); clone.UpdateLayout(); Debug.Write(clone.RenderSize); var height = (int)clone.ActualHeight; var width = (int)clone.ActualWidth; var renderer = new RenderTargetBitmap(width, height, 96d, 96d, PixelFormats.Pbgra32); renderer.Render(clone); var pngEncoder = new PngBitmapEncoder(); pngEncoder.Frames.Add(BitmapFrame.Create(renderer)); using (var file = File.Create(filename)) { pngEncoder.Save(file); } } So I get out something like this: Which while big, isn't useful as it has nothing charted. A: http://www.visiblox.com/blog/2011/05/printing-visiblox-charts The main point I was missing was InvalidationHandler.ForceImmediateInvalidate = true; Setting this before I rendered the chart in memory and then reverting it once I had finished. From there it was smooth sailing :D A: RenderTargetBitmap DrawToImage<T>(T source, double scale) where T:FrameworkElement { var clone = Clone(source); clone.Width = clone.Height = Double.NaN; clone.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch; clone.VerticalAlignment = System.Windows.VerticalAlignment.Stretch; clone.Margin = new Thickness(); var size = new Size(source.ActualWidth * scale, source.ActualHeight * scale); clone.Measure(size); clone.Arrange(new Rect(size)); var renderBitmap = new RenderTargetBitmap((int)clone.ActualWidth, (int)clone.ActualHeight, 96, 96, PixelFormats.Pbgra32); renderBitmap.Render(clone); return renderBitmap; } static T Clone<T>(T source) where T:UIElement { if (source == null) return null; string xaml = XamlWriter.Save(source); var reader = new StringReader(xaml); var xmlReader = XmlTextReader.Create(reader, new XmlReaderSettings()); return (T)XamlReader.Load(xmlReader); } A: I think these might help : Exporting Visifire Silverlight Chart as Image with a downloadable silverlight solution. Exporting Chart as Image in WPF
{ "language": "en", "url": "https://stackoverflow.com/questions/7563118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Windows Phone 7 Mango saving the state of a CookieContainer update1: After more research I'm not sure this is possible, I created a UserVoice entry on fixing it. I'm trying to save CookieContainer on app exit or when Tombstoning happens but I've run into some problems. I've tried to save CookieContainer in the AppSettings but when loaded, the cookies are gone. Researching this internally, DataContractSerializer cannot serialize cookies. This seems to be a behavior that Windows Phone inherited from Silverlight's DataContractSerializer. After doing more research it seemed like the work around was to grab the cookies from the container and save them another way. That worked fine until I hit another snag. I'm unable to GetCookies with a Uri of .mydomain.com. I belive it's because of this bug. I can see the cookie, .mydomain.com in the domaintable but GetCookies doesn't work on that particular cookie. The bug is posted again here. There is also a problem with getting cookies out of a container too when the domain begins with a .: CookieContainer container = new CookieContainer(); container.Add(new Cookie("x", "1", "/", ".blah.com")); CookieCollection cv = container.GetCookies(new Uri("http://blah.com")); cv = container.GetCookies(new Uri("http://w.blah.com")); I found a work around for that using reflection to iterate the domaintable and remove the '.' prefix. private void BugFix_CookieDomain(CookieContainer cookieContainer) { System.Type _ContainerType = typeof(CookieContainer); var = _ContainerType.InvokeMember("m_domainTable", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.Instance, null, cookieContainer, new object[] { }); ArrayList keys = new ArrayList(table.Keys); foreach (string keyObj in keys) { string key = (keyObj as string); if (key[0] == '.') { string newKey = key.Remove(0, 1); table[newKey] = table[keyObj]; } } } Only, when InvokeMember is called a MethodAccessException is thrown in SL. This doesn't really solve my problem as one of the cookies I need to preserve is HttpOnly, which is one of the reasons for the CookieContainer. If the server sends HTTPOnly cookies, you should create a System.Net.CookieContainer on the request to hold the cookies, although you will not see or be able to access the cookies that are stored in the container. So, any ideas? Am I missing something simple? Is there another way to save the state of the CookieContainer or do I need to save off the users info including password and re-authentic them every time the app starts and when coming back from tombstoning? A: I have written a CookieSerializer that specifically address this issue. The serializer is pasted below. For a working project and scenario, please visit the project's CodePlex site. public static class CookieSerializer { /// <summary> /// Serializes the cookie collection to the stream. /// </summary> /// <param name="cookies">You can obtain the collection through your <see cref="CookieAwareWebClient">WebClient</see>'s <code>CookieContainer.GetCookies(Uri)</code>-method.</param> /// <param name="address">The <see cref="Uri">Uri</see> that produced the cookies</param> /// <param name="stream">The stream to which to serialize</param> public static void Serialize(CookieCollection cookies, Uri address, Stream stream) { using (var writer = new StreamWriter(stream)) { for (var enumerator = cookies.GetEnumerator(); enumerator.MoveNext();) { var cookie = enumerator.Current as Cookie; if (cookie == null) continue; writer.WriteLine(address.AbsoluteUri); writer.WriteLine(cookie.Comment); writer.WriteLine(cookie.CommentUri == null ? null : cookie.CommentUri.AbsoluteUri); writer.WriteLine(cookie.Discard); writer.WriteLine(cookie.Domain); writer.WriteLine(cookie.Expired); writer.WriteLine(cookie.Expires); writer.WriteLine(cookie.HttpOnly); writer.WriteLine(cookie.Name); writer.WriteLine(cookie.Path); writer.WriteLine(cookie.Port); writer.WriteLine(cookie.Secure); writer.WriteLine(cookie.Value); writer.WriteLine(cookie.Version); } } } /// <summary> /// Deserializes <see cref="Cookie">Cookie</see>s from the <see cref="Stream">Stream</see>, /// filling the <see cref="CookieContainer">CookieContainer</see>. /// </summary> /// <param name="stream">Stream to read</param> /// <param name="container">Container to fill</param> public static void Deserialize(Stream stream, CookieContainer container) { using (var reader = new StreamReader(stream)) { while (!reader.EndOfStream) { var uri = Read(reader, absoluteUri => new Uri(absoluteUri, UriKind.Absolute)); var cookie = new Cookie(); cookie.Comment = Read(reader, comment => comment); cookie.CommentUri = Read(reader, absoluteUri => new Uri(absoluteUri, UriKind.Absolute)); cookie.Discard = Read(reader, bool.Parse); cookie.Domain = Read(reader, domain => domain); cookie.Expired = Read(reader, bool.Parse); cookie.Expires = Read(reader, DateTime.Parse); cookie.HttpOnly = Read(reader, bool.Parse); cookie.Name = Read(reader, name => name); cookie.Path = Read(reader, path => path); cookie.Port = Read(reader, port => port); cookie.Secure = Read(reader, bool.Parse); cookie.Value = Read(reader, value => value); cookie.Version = Read(reader, int.Parse); container.Add(uri, cookie); } } } /// <summary> /// Reads a value (line) from the serialized file, translating the string value into a specific type /// </summary> /// <typeparam name="T">Target type</typeparam> /// <param name="reader">Input stream</param> /// <param name="translator">Translation function - translate the read value into /// <typeparamref name="T"/> if the read value is not <code>null</code>. /// <remarks>If the target type is <see cref="Uri">Uri</see> , the value is considered <code>null</code> if it's an empty string.</remarks> </param> /// <param name="defaultValue">The default value to return if the read value is <code>null</code>. /// <remarks>The translation function will not be called for null values.</remarks></param> /// <returns></returns> private static T Read<T>(TextReader reader, Func<string, T> translator, T defaultValue = default(T)) { var value = reader.ReadLine(); if (value == null) return defaultValue; if (typeof(T) == typeof(Uri) && String.IsNullOrEmpty(value)) return defaultValue; return translator(value); } } A: You cannot access private members outside of your assembly in WP7, even with Reflection. It's a security measure put in place to ensure you cannot call internal system APIs. It looks like you may be out of luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Data-structure to store "last 10" data sets? I'm currently working with an object Literal to store temporary information to send to clients, it's like a history container for the last 10 sets of data. So the issue that I', having is figuring out the most efficient way to splice on object as well as push an object in at the start, so basically i have an object, this object has 0 data inside of it. I then insert values, but what I need to do is when the object reaches 10 keys, I need to pop the last element of the end of object literal, push all keys up and then insert one value at the start. Take this example object var initializeData = { a : {}, b : {}, c : {}, d : {}, e : {}, f : {}, g : {}, h : {}, i : {}, j : {} } When I insert an element I need j to be removed, i to become the last element, and a to become b. So that the new element becomes a. Can anyone help me solve this issue, I am using node.js but native JavaScript is fine obviously. Working with arrays after advice from replies, this is basically what I am thinking your telling me would be the best solution: function HangoutStack(n) { this._array = new Array(n); this.max = n; } HangoutStack.prototype.push = function(hangout) { if(this._array.unshift(hangout) > this.max) { this._array.pop(); } } HangoutStack.prototype.getAllItems = function() { return this._array; } A: Sounds like it would be a lot easier to use an array. Then you could use unshift to insert from the beginning and pop to remove from the end. Edit: Example: var items = [] function addItem(item) { items.unshift(item) if (items.length > 10) { items.pop() } } Alternatively, you could use push/shift instead of unshift/pop. Depends on which end of the array you prefer the new items to sit at. A: What you need is called a Circular Buffer. Have a look at this implementation in javascript A: Yeah, use an Array. var arr = []; // adding an item if (arr.unshift(item) > 10) { arr.pop(); } If you need the 'name' of the item, like "a" or "b" in your object example, just wrap each item in another object that contains the name and the object. Objects in js are like dictionaries -- they have no inherent order to the items. It's just a collection of things. You can try to make up an order (like a through z in your example), but then you have to manage that order yourself when things change. It's just much easier to use an array.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: binary tree swapping method I'm having trouble with swapping nodes between two binary trees. I'm trying to swap the current node with the passed node in the tree, but I can't figure out how; I can only seem to swap the parents of the nodes, but not the nodes themselves. Can anyone give me some direction? public void swap(Node node) { if(this.equals(this.parent.leftChild)){ Node tempNodeR = node.parent.rightChild; System.out.println("Is a left child"); node.parent.rightChild = this.parent.leftChild; this.parent.leftChild = tempNodeR; } else{ Node tempNodeL = node.parent.leftChild; System.out.println("Is a right child"); node.parent.leftChild = this.parent.rightChild; this.parent.rightChild = tempNodeL; } } Calling node2.swap(node4): Given Tree: 1 3 / \ 2 4 Resulting Tree (unchanged): 1 3 / \ 2 4 Expected Tree: 1 3 / \ 4 2 A: For each node, the node has a reference to its parent and the parent has a reference to that child. So if you're going to swap two nodes, you need to update four references. Tree 1 3 / \ 2 4 So here... * *1 has a reference that points to 2 that you want to point to 4. *2 has a reference to 1 that should point to 3. *4 has a reference to 3 that should point to 1. *3 has a reference to 4 that should point to 2. Hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Single Signon Implementation in ASP.NET ( Different Domains with two different applications ) we have a production site like www.Domain1.com, and developing a new web application www.domain2.com, and would like to implement single sign on. I am looking for solution pretty much like how google works like login to gmail, in gmail navigate to other google apps or we can open new window and we can use picasa or other google apps with out login. I have found an interesting solution, where we will be developing a dedicated Authentication site like www.sso.com. http://www.codeproject.com/KB/aspnet/CrossDomainSSOExample.aspx we use webfarm environment, site 1 and site 2 will be deployed in webfarm environment, but when we deploy www.sso.com in webfarm , this solution will not work. I am sure google might have implemented www.sso.com service in webfarm environment. i am trying to understand and implement the same. Experts i kindly request your help in this direction , any information which helps me. A: AFAIK, after Google authenticates user with main auth site/service, it issues a set of redirects to auth. end-points to all main domains with one-time secret key in URL, so each end-point on each domain sets auth. cookies for given user. E.g. user signs in at http://sso.com/login, then he is redirected to http://domain1.com/auth?secret=12345 http://domain2.com/auth?secret=12345 ... http://domainX.com/auth?secret=12345 And each domain sets an auth cookie to the browser. Correct me if I'm wrong.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Buffer overflow to jump to a part of code My teacher gave me some code and I have to run it and make it jump to the admin section using a buffer overflow. I cannot modify the source code. Could someone explain how I could jump to the admin method using a buffer overflow? I'm running it on ubuntu 8.10 and it was compiled with an older version of gcc so the overflow will work. A: Without being able to see the code, on a general level you need to design inputs to the function that will overwrite the return address (or another address to which control will be transferred by the function) on the stack. At a guess, the code has a fixed length character buffer and copies values from a function parameter into that buffer without validating that the length does not exceed the length of the buffer. You need to make a note of what the stack layout looks like for your application (running it under a debugger may well be the quickest way to do this) to work out where the address you need to override is, then put together a string to overwrite this with the address of the admin function you need to call. A: You can always get the asm output of it (I forgot how right now... brainfart) and see where the buffer you want to overflow is being used/read and check it's length. Next you want to calculate how far you need to overflow it so that you either replace the next instruction with a JMP (address of admin code) or change a JMP address to that of the admin section. 0xE8 is the jump opcode for x86 if you need it since you want to overwrite the binary data of the instruction with your own.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Linq to Entities: Where clause containing ToString fails I can do the following: var result = DB.Products.ToList() // .AsEnumerable() too .Where( p => p.ID.ToString() == ViewModel.ID); But it pulls all the products instead of only what I want, then filters locally. Without the ToList(), it fails to find/use the .ToString method in the projection. The ViewModel.ID is string from the client. This question here talks about the same issue, minus the where clause, but the answer doesn't fix pulling every product locally. My ViewModel.ID is string because knockout.js converts it from numeric to string if the user changes the value. I figured I would pursue this first as it's probably easier to rule it out. A: I think you are approaching the problem from the wrong direction. Convert ViewModel.ID back to integer (int.Parse), then you can offload the filtering back to the database. This is going to be far better than a workaround to cast p.ID to a string at the database, a move that would likely defeat any indexing on the value at the DB.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: what is the difference between eq("+index+") and eq(index) in jQuery In an example where eq() function is used, it was used as eq("+index+") I haven't seen syntax like this before. What does "+" sign on both sides mean? How is it different from eq(index)? Thank you! A: In jQuery, eq refers to two slightly different things: .eq, the function, and :eq, the selector. The function version is chained onto a jQuery object, so you'd see examples like: $(".whatever").eq(index) Whereas the other form is used as part of the selector string, so you'll see people concatenate the index with the rest of the string: $(".whatever:eq(" + index + ")") For performance reasons (and better readability in many cases), the jQuery documentation recommends the first form, the .eq function. A: if you are using eq as a function you should use it like $("div").eq(3).html("test"); if as a selector: var index = 3; $("div:eq(" + index + ")").html("test"); 2 ways, same result.... A: Probably you were looking at an example similar to this: $("foo:eq(" + index + ")") You are probably comparing that to something like this: $("foo").eq(index) The difference is that the former is a (faux) CSS selector syntax and the latter is just a method call. Compare http://api.jquery.com/eq-selector/ to http://api.jquery.com/eq/.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Lowercase true/false keywords in Aptana PHP editor Is it possible to make TRUE/FALSE autocompletion lowercase in Aptana? A: Well, seems like there is no such option. So I've created feature request at Aptana's bug tracker: http://jira.appcelerator.org/browse/APSTUD-3585
{ "language": "en", "url": "https://stackoverflow.com/questions/7563131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem submitting existing app to iTunes Connect I have an app that is already in the App Store. For this current build I made a new project (I rebuilt everything from scratch) and signed it with my previous application key. When I try to submit it to the App Store through XCode Organizer I get the error: No Suitable Application Records Were Found: Please make sure that you have set up a record for this application on iTunes Connect What do I need to change in order for this new project to be recognized as the existing app I have in the App Store? A: Are you using the exact same identifier as before in your Info.plist file? You will probably also need to bump up the version number and make sure that iTunes Connect knows you want to create an update.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FireBird: How do you nest a select in an if? I'm very new to FireBird, but I want to know how I can use a select statement as part of my conditional criteria. I feel like I've been to the internet in back trying to find a way to do this, but haven't come up with much. Below is my attempt at getting this to work. Thanks in advance for any help. SET TERM ^ ; ALTER PROCEDURE sp_test ( IPADD Varchar(32), HN Varchar(32), NOTE Varchar(200) ) RETURNS ( update_count integer ) AS BEGIN IF((SELECT COUNT(*) FROM ADDRESSES a WHERE a.ADDRESS_TYPE = 'Reserved' AND a.ALIVE = 'N' AND (a.HOST_NAME = '' OR a.HOST_NAME is NULL) AND (a.DNS_NAME = '' OR a.DNS_NAME is NULL) AND (a.SYSTEM_NAME = '' OR a.SYSTEM_NAME is NULL)) > 0) THEN UPDATE ADDRESSES a SET a.HOST_NAME = :HN, a.ADDRESS_TYPE = 'Assigned', a.NOTES = :NOTE WHERE a.SHORT_IP_ADDRESS = :IPADD; update_count = 1; SUSPEND; ELSE update_count = 0; SUSPEND; END^ SET TERM ; ^ GRANT EXECUTE ON PROCEDURE sp_test TO SYSDBA; A: Using COUNT to check is there records to update is not the best way, use EXISTS instead, ie your IF would be IF(EXISTS(SELECT 1 FROM ADDRESSES a WHERE a.ADDRESS_TYPE = 'Reserved' AND a.ALIVE = 'N' AND (a.HOST_NAME = '' OR a.HOST_NAME is NULL) AND (a.DNS_NAME = '' OR a.DNS_NAME is NULL) AND (a.SYSTEM_NAME = '' OR a.SYSTEM_NAME is NULL))) THEN But there seems to be a problem with your return value, update_count - you return 1 if you execute the UPDATE, but the actual number of rows affected by the statement might be something else. I suggest you use ROW_COUNT context variable instead. So your procedure would be ALTER PROCEDURE sp_test ( IPADD Varchar(32), HN Varchar(32), NOTE Varchar(200) ) RETURNS ( update_count integer ) AS BEGIN IF(EXISTS(SELECT 1 FROM ADDRESSES a WHERE (a.ADDRESS_TYPE = 'Reserved') AND (a.ALIVE = 'N') AND (a.HOST_NAME = '' OR a.HOST_NAME is NULL) AND (a.DNS_NAME = '' OR a.DNS_NAME is NULL) AND (a.SYSTEM_NAME = '' OR a.SYSTEM_NAME is NULL))) THEN BEGIN UPDATE ADDRESSES a SET a.HOST_NAME = :HN, a.ADDRESS_TYPE = 'Assigned', a.NOTES = :NOTE WHERE a.SHORT_IP_ADDRESS = :IPADD; update_count = ROW_COUNT; END ELSE update_count = 0; SUSPEND; END^
{ "language": "en", "url": "https://stackoverflow.com/questions/7563134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Customize a document_view and add a div? This feels like a newbie question but: I am trying to create a new page from the drop-down display menu so that I can supply a background color to the page (so end user doesn't have to go into the html and add a div). I tried adding a new (empty) div to the template but it's not working. Is this even possible? Here is my code (my div is called "s_holder"): <metal:field use-macro="python:here.widget('text', mode='view')"> Body text </metal:field> <div metal:use-macro="here/document_relateditems/macros/relatedItems"> show related items if they exist </div> <div tal:replace="structure provider:plone.belowcontentbody" /> </tal:main-macro> </metal:main> <div id="s_holder"></div><!--end s holder--> </body> </html> A: Sure you can do it. I'm not convinced it's a good idea :-), but you need the <div> to be inside the main_macro (your example HTML is invalid - you have a </tal:main-macro> and no start tag, but I'm assuming you just cut and pasted the last part of the template here, because that template would never display, if it was written that way. That said, how exactly are you adding it to "the drop-down display menu"? A: For the part of creating the new display view: as @Auspex said, you should put the div inside the macro. To add your display view to the drop down menu you need to edit every content type. There are two ways of doing this: 1- manually add a "types" folder in the genericsetup profile of your product and put inside one xml file per content type. Ex: File.xml <?xml version="1.0"?> <object name="File" meta_type="Factory-based Type Information with dynamic views" i18n:domain="plone" xmlns:i18n="http://xml.zope.org/namespaces/i18n"> <property name="view_methods"> <element value="file_view"/> <element value="myniewfantastic_view"/> </property> </object> 2- in the ZMI -> portal_types edit every content type to add your display view and then in the portal_setup tool export the step for types. Extract the xml definitions from the downloaded archive to your genericsetup profile (in the "types" folder) and then edit them to remove unuseful parts as above.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python: preventing caching from slowing me down I'm working on a web app with very aggressive caching. Virtually every component of the web app: views, partial views, controller output, disk loads, REST-API calls, Database queries. Everything that can be cached, at any level, is cached, all using decorators. Naturally, this is blazing fast, since the vast majority of the HTML-generation comprises pure functions, with very few loads from disk/REST APIs. Furthermore, what few disk loads/database queries/REST API queries i perform are also cached until invalidated, so unless something just changed, they are really fast too. So everything is blazing fast, but there is a hitch: all this stuff is being cached in memory, in one huge global dictionary in my WSGI process, and hence can be stored directly without serialization. Once i start putting stuff in memcached, the time taken for cache hits doesn't change too much, but putting stuff in cache starts taking much longer. In general that's ok, but the initial "fill cache" generation of each page goes from ~900ms (which is already pretty fast considering how many flat files it reads from disk) to about ~9000ms. For reference, generating an arbitrary page takes something like 10ms once the cache is warmed up. Profiling the code, the vast majority of the time is going to cPickle. So the question is, how can I make this faster? Are there any in-memory caches which I can directly pass my objects to without serialization? Or some way to make caching my huge pile of objects faster? I could just go without a persistent memcached, but then my performance (or lack thereof) will be at the whim of the Apache/WSGI process manager. A: If you are serializing Python objects and not simple datatypes, and have to use pickle, try cPickle.HIGHEST_PROTOCOL: my_serialized_object = cPickle.dumps(my_object, cPickle.HIGHEST_PROTOCOL) The default protocol is compatible with older versions of Python, but you likely don't care about that. I just did a simple benchmark with a 1000 key dict and it was almost an order-of-magnitude faster. UPDATE: Since you appear to already be using the highest protocol, you are going to have to do some extra work to get more performance. Here is what I would do at this point: * *Identify which classes are the slowest to pickle *Create a pair of methods in the class to implement a faster serialization method, say _to_string() and _from_string(s). The actual serialization can be tailored to what the object encompasses and how it's going to be used. For example, some objects may really only contain a simple string, such as a rendered template, and some may actually be sent to a browser as JSON, in which case you can simply serialize to JSON and serve it directly. Use the timeit module to ensure that your method is actually faster *In your decorator, check hasattr(object, '_to_string') and use that instead, if it exists This method lets you tackle the worst classes first, and introduces minimal disruption to the code base.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Using xs:alternative in Visual Studio I am trying to use xs:alternative in an XSD, however Visual Studio 2010 does not recognise xs:alternative as a valid child for xs:element. I am using xmlns:xs="http://www.w3.org/2001/XMLSchema" as my namespace. I have tried some of the examples I have found online and VS2010 does not like those either. When I run the document through W3C validator, it also does not recognise it. Am I missing something or is xs:alternative not available yet? A: <xs:alternative /> is part of the XSD 1.1 specification. No Microsoft product yet supports XSD 1.1.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563145", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: passing xpath to xquery I usually hardwire the xpath in the xqueries like so: let $xml := <books> <book price="1"> <name>abc</abc> </book> </books> return $xml/book/name I am trying to figure out if there is a way to path xpath as a string variable and use it in the xquery something like so: declare variable $xpath as xs:string external; let $xml := <books> <book price="1"> <name>abc</abc> </book> </books> return $xml/$xpath Say the value passed to $xpath is book/name. Thanks. A: short answer: no. However, if your processor has an "eval()" method you can construct your query as a string and evaluate it. You might be able to create the query in some external process and embed a dynamic path that way. If you have a small number of cases, you could pass in a variable indicating which one of them to use. But there is no facility in the xquery language for evaluating dynamic paths.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to access the html of a site with a 204 response code via java.net? I am trying to read a website using the java.net package classes. The site has content, and i see it manually in html source utilities in the browser. When I get its response code and try to view the site using java, it connects successfully but interprets the site as one without content(204 code). What is going on and is it possible to get around this to view the html automatically. thanks for your responses: Do you need the URL? here is the code: URL hef=new URL(the website); BufferedReader kj=null; int kjkj=((HttpURLConnection)hef.openConnection()).getResponseCode(); System.out.println(kjkj); String j=((HttpURLConnection)hef.openConnection()).getResponseMessage(); System.out.println(j); URLConnection g=hef.openConnection(); g.connect(); try{ kj=new BufferedReader(new InputStreamReader(g.getInputStream())); while(kj.readLine()!=null) { String y=kj.readLine(); System.out.println(y); } } finally { if(kj!=null) { kj.close(); } } } A: Suggestions: * *Assert than when manually accessing the site (with a web browser client) you are effectively getting a 200 return code *Make sure that the HTTP request issued from the automated (java-based) logic is similar/identical to that of what is sent by an interactive web browser client. In particular, make sure the User-Agent is identical (some sites purposely alter their responses depending on the agent). *You can use a packet sniffer, maybe something like Fiddler2 to see exactly what is being sent and received to/from the server *I'm not sure that the java.net package is robot-aware, but that could be a factor as well (can you check if the underlying site has robot.txt files). Edit: assuming you are using the java.net package's HttpURLConnection class, the "robot" hypothesis doesn't apply. On the other hand you'll probably want to use the connection's setRequestProperty() method to prepare the desired HTTP header for the request (so they match these from the web browser client) Maybe you can post the relevant portions of your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how marge each value from the same array onto each key I have this array and I can't figure out how to dissect it and get it to built onto itself. I have compiled my array to what I think might be the easiest to keep track of: Array ( [domain.com] => Array ( [dev] => Array ( [path] => /var/www/config/ [ini] => Array ( [0] => db [1] => common ) ) [theme] => Array ( [path] => /var/ww/themes/ [ini] => theme ) ) ) My whole thing is that I want to make a helper class to parse ini files. So I have through a couple of methods been able to build my array like above. My end goal is have something like this parse_ini_file($ini[$domain][$nick][path] . $ini[$domain][$nick][ini] . ".ini", true) where $nick is either 'dev' or 'theme' its just a way for me to distinguish paths and ini that belong together. I have tried to do a foreach loop through each key value pair but I'm stuck on the fact that one of my values holds an array. foreach (self::$ini[$domain] as $k => $v) { //if (self::$ini[$domina][$nick]['path'][$k] === self::$ini[$domain][$nick]['ini'][$k]) foreach (self::$ini[$domain][$k] as $i => $l) { foreach ($l as $m => $n) //if (!is_array($i)) { // (strlen($i) - 1 === '/' ? $i : $i . '/'); echo $n; //self::$built = parse_ini_file($i . $j, true); //} } } It may seem like a mess, but i didn't bother with making meaningful variable names until I am able to make a solid code block. But In my attempt I have done a foreach loop through the $domain array to extract each $nick from there I thought doing another foreach to then break it down to get the path and ini key => values to then built the parse ini file function. But like I said, one of my ini key's holds an array so I'm not sure how to loop through that while still being able to parse an ini file and not overwriting the holder variable $built Any help would really be appreciated! A: You must first go and read about recursion. Just type the word into Google or even Wikipedia, you'll get the idea. Or just look for array_merge and array_merge_recursive at http://php.net, that's what you need. But first read about recursion anyway, you should know such basic things if you are going to write code further.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bug in Div height IE Hihi, I´m slicing down the main layout for a webpage. For some reason the div id="main" won´t align to the header url: http://nicejob.is/clients/pizzahollin/www/forsida.htm As you can see the div id="main" (in green) match perfectly with the header in Chrome and Firefox, but in IE the "main" goes almost overlap the header I´ve done this many times before without this bug so I don´t know what ghost is hunting me now Any suggestions? :) A: try adding display:block; on the <header>
{ "language": "en", "url": "https://stackoverflow.com/questions/7563151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: ODBC via ssh tunnel to a 3rd machine At work we have a SqlServer database that cannot be connected to from outside our internal network. If we want to work remotely we can ssh into several other servers on our network and then work via X Forwarding so the development applications have access to the database. This is annoying for a bunch of obvious reasons such as latency in the IDE and I'm wondering how I could tunnel the database connnections back to my machine. It seems like this should be possible but I'm not sure how to do it since there's has to be an intermediate step in between. This question is similar to what I want to do but only works for going directly to the db server if I understand it correctly. I'm asking specifically about ODBC because that's the driver the application already uses. If there is a more general solution I would of course be open to that. What I want to do is Local machine (Linux) -> Server (Linux) -> Database connection to DB (Sql Server) A: Well, as you say, if you wanted to directly use a encrypted connection to SQL Server you could just use Linux driver that give you that, and most I think do. You could use a bridge as already suggested. But It might be possible using socat. What driver are you using on the local machine? I will have a quick play and see how it works. A: The OpenLink Software - Multi-tier ODBC Driver for SQL Server might help you out here... It has a client server architecture as which can easily be configured in a three-tier (client/proxy/server) architecture as follows -- * *Linux Client - * *ODBC Application *OpenLink Generic ODBC Driver (Multi-tier client component) *Linux Proxy - * *OpenLink Request Broker (Multi-tier server component) *OpenLink Database Agent for SQL Server (Multi-tier server component) *Windows Server - * *SQL Server DBMS
{ "language": "en", "url": "https://stackoverflow.com/questions/7563156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to remove ETX character from the end of a string? (Regex or PHP) How can I remove the ETX character (0x03) from the end of a string? I'd either like a function, otherwise I can write a regular expression, all I want to know is how to match the ETX character in a regular expression? trim() doesn't work. A: To complete Charles' answer, I had a case where the ETX character was not at the end of the line so I had to use the following code: $string = preg_replace('/\x03/', '', $string); Just remove the $ sign. A: Have you tried rtrim function http://php.net/manual/en/function.rtrim.php A: The ETX is a control character, which means we have to go through some extra effort to bring it into existence. From the PHP interactive prompt: php > $borked = "Hello, have an ETX:" . chr(3); php > print_r($borked); Hello, have an ETX: php > var_export($borked); 'Hello, have an ETX:' php > echo urlencode($borked); Hello%2C+have+an+ETX%3A%03 php > var_dump( preg_match('/' . chr(3) . '/', $borked) ); int(1) php > var_dump( preg_match('/' . chr(3) . '$/', $borked) ); int(1) php > echo urlencode( preg_replace('/' . chr(3) . '$/', '', $borked) ); Hello%2C+have+an+ETX%3A In other words, you can basically just inject the character into the regex string. Now, this might backfire. This technique may backfire based on character sets and other horrible things. In addition to chr(3), you could also try urldecode('%03') to produce the character. You can also use a special escape syntax, as listed on the PCRE syntax pages: /\x03$/ Here's a function for you, using that last method: function strip_etx_at_end_of_string($string) { return preg_replace('/\x03$/', '', $string); } A: At a guess rtrim($var,"\c"); or preg_replace("/\c+\$/",'',$var);
{ "language": "en", "url": "https://stackoverflow.com/questions/7563163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: execv and testing correct absolute paths I'm trying to test absolute paths on a linux machine to find where a program is located so I can run it with my specific arguments. The problem is, when I find it, I keep adding more strings to the correct path as well as memory leak by freeing the dynamically allocated memory. Only fix for the stack dump is to not free(ret). I believe based on gdb that when I run an example with "ls" it finds the program and runs it, but gives strange results. for(j = 0; j < i; j++, path = NULL) { token = strtok_r(path, delim, &saver); if(token == NULL) break; else { strncat(ret, token, 80); strncat(ret, "/", 1); strncat(ret, command, 80); args[0] = ret; printf("%s\n", ret); m = execv(ret, args); printf("%d\n", m); if(m < 0) { free(ret); ret = malloc(120*sizeof(char)); } else break; } } Where the delimiter character is a colon (:) and I believe the strncat is done correctly. I'm not sure though so thanks for the help. A: Each time you malloc(), you get new uninitialised memory. strncat() will then raise a segmentation fault as it will try to find a NUL character in ret, which could be way outside of your 120 bytes for ret. Either replace malloc with calloc, or use memset(ret, 0, 120*sizeof(char)); after you call malloc. Or somehow fill ret with zeros before the first strncat. The reason it's not breaking if you don't free could be due to ret being declared on the stack - then do not free/malloc it. Or it could so happen that the initial value of ret is all zeros - but subsequent malloc calls yield uninitialised memory. PS: Are you sure you want to use execv? That replaces the current process. But I assume you fork.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MVC 3 Route problem ActionLink result "http://localhost:5089/Article/GetArticlesByCategory?category=ASP.NET&categoryId=2". i want to show that link type "http://localhost:5089/Blog/ASP.NET". what is wrong route named "Article". Routes: routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "index", id = UrlParameter.Optional } // Parameter defaults ); routes.MapRoute( "Article", "Blog/{category}", // new { controller = "Article", action = "GetArticlesByCategory", category = UrlParameter.Optional, categoryId = UrlParameter.Optional } Link: @Html.ActionLink(k.Name, "GetArticlesByCategory", "Article", new { category = k.Name, categoryId = k.CategoryId }, null) SOLVED GetArticlesByCategory parameter int categoryId changed to >> string category and replaced action codes as to new parameter (string category) Routes replaced with: routes.MapRoute( "Category", "Blog/{category}", new { controller = "Article", action = "GetArticlesByCategory", category = UrlParameter.Optional } ); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "index", id = UrlParameter.Optional } // Parameter defaults ); ActionLink replaced with: @Html.ActionLink(k.Name, "GetArticlesByCategory", "Article", new { category = k.Name }, null) A: There are a few issues. First, and most important, your routes are specified in the wrong order. The default route should be defined last. Second, never define a route with two optional parameters. It just causes too many problems. Try the following for your routes: routes.MapRoute( "CategoryAndId", "Blog/{category}/{categoryId}", new { controller = "Article", action = "GetArticlesByCategory" } ); routes.MapRoute( "CategoryOnly", "Blog/{category}", new { controller = "Article", action = "GetArticlesByCategory", category = UrlParameter.Optional } ); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "index", id = UrlParameter.Optional } // Parameter defaults ); A: You are not specifying the action in the route routes.MapRoute( "Article", "Blog/{action}/{category}/{categoryId}", // new { controller = "Article", action = "GetArticlesByCategory", category = UrlParameter.Optional, categoryId = UrlParameter.Optional } I suggest you use Phil Haack's routes debug, http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx. A great way for debugging your MVC routes A: If you want the link to show as http://localhost:5089/Blog/ASP.NET, you'll need to change the actionlink as such: @Html.ActionLink(k.Name, "GetArticlesByCategory", "Article", new { category = k.Name }, new { @title = "Kategorisindeki Makaleler", @class = "selected" }) Since you don't want the CategoryID in the link, there is no need to put it in. the route isn't being matched by the actionlink because it expects a CategoryID parameter as well EDIT If you want the CategoryID to be read from the route, it needs to be added to the route. otherwise it will just be appended as a parameter (like in your original example). If you change your route to: "Blog/{categoryId}/{category}" or "Blog/{category}/{categoryId}" The link will now look like Blog/2/ASP.NET or Blog/ASP.NET/2 but if you want the categoryId to be read from the URL, then I don't think you have much choice
{ "language": "en", "url": "https://stackoverflow.com/questions/7563167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Detect which word has been clicked on within a text I am building a JS script which at some point is able to, on a given page, allow the user to click on any word and store this word in a variable. I have one solution which is pretty ugly and involves class-parsing using jQuery: I first parse the entire html, split everything on each space " ", and re-append everything wrapped in a <span class="word">word</span>, and then I add an event with jQ to detect clicks on such a class, and using $(this).innerHTML I get the clicked word. This is slow and ugly in so many ways and I was hoping that someone knows of another way to achieve this. PS: I might consider running it as a browser extension, so if it doesn't sound possible with mere JS, and if you know a browser API that would allow that, feel free to mention it ! A possible owrkaround would be to get the user to highlight the word instead of clicking it, but I would really love to be able to achieve the same thing with only a click ! A: And another take on @stevendaniel's answer: $('.clickable').click(function(){ var sel=window.getSelection(); var str=sel.anchorNode.nodeValue,len=str.length, a=b=sel.anchorOffset; while(str[a]!=' '&&a--){}; if (str[a]==' ') a++; // start of word while(str[b]!=' '&&b++<len){}; // end of word+1 console.log(str.substring(a,b)); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p class="clickable">The objective can also be achieved by simply analysing the string you get from <code>sel=window.getSelection()</code>. Two simple searches for the next blank before and after the word, pointed to by the current position (<code>sel.anchorOffset</code>) and the work is done:</p> <p>This second paragraph is <em>not</em> clickable. I tested this on Chrome and Internet explorer (IE11)</p> A: The only cross-browser (IE < 8) way that I know of is wrapping in span elements. It's ugly but not really that slow. This example is straight from the jQuery .css() function documentation, but with a huge block of text to pre-process: http://jsfiddle.net/kMvYy/ Here's another way of doing it (given here: jquery capture the word value ) on the same block of text that doesn't require wrapping in span. http://jsfiddle.net/Vap7C/1 A: Here's a solution that will work without adding tons of spans to the document (works on Webkit and Mozilla and IE9+): https://jsfiddle.net/Vap7C/15/ $(".clickable").click(function(e){ s = window.getSelection(); var range = s.getRangeAt(0); var node = s.anchorNode; // Find starting point while(range.toString().indexOf(' ') != 0) { range.setStart(node,(range.startOffset -1)); } range.setStart(node, range.startOffset +1); // Find ending point do{ range.setEnd(node,range.endOffset + 1); }while(range.toString().indexOf(' ') == -1 && range.toString().trim() != ''); // Alert result var str = range.toString().trim(); alert(str); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p class="clickable"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris rutrum ante nunc. Proin sit amet sem purus. Aliquam malesuada egestas metus, vel ornare purus sollicitudin at. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer porta turpis ut mi pharetra rhoncus. Ut accumsan, leo quis hendrerit luctus, purus nunc suscipit libero, sit amet lacinia turpis neque gravida sapien. Nulla facilisis neque sit amet lacus ornare consectetur non ac massa. In purus quam, imperdiet eget tempor eu, consectetur eget turpis. Curabitur mauris neque, venenatis a sollicitudin consectetur, hendrerit in arcu. </p> in IE8, it has problems because of getSelection. This link ( Is there a cross-browser solution for getSelection()? ) may help with those issues. I haven't tested on Opera. I used https://jsfiddle.net/Vap7C/1/ from a similar question as a starting point. It used the Selection.modify function: s.modify('extend','forward','word'); s.modify('extend','backward','word'); Unfortunately they don't always get the whole word. As a workaround, I got the Range for the selection and added two loops to find the word boundaries. The first one keeps adding characters to the word until it reaches a space. the second loop goes to the end of the word until it reaches a space. This will also grab any punctuation at the end of the word, so make sure you trim that out if you need to. A: -EDIT- What about this? it uses getSelection() binded to mouseup <script type="text/javascript" src="jquery-1.6.3.min.js"></script> <script> $(document).ready(function(){ words = []; $("#myId").bind("mouseup",function(){ word = window.getSelection().toString(); if(word != ''){ if( confirm("Add *"+word+"* to array?") ){words.push(word);} } }); //just to see what we've got $('button').click(function(){alert(words);}); }); </script> <div id='myId'> Some random text in here with many words huh </div> <button>See content</button> I can't think of a way beside splitting, this is what I'd do, a small plugin that will split into spans and when clicked it will add its content to an array for further use: <script type="text/javascript" src="jquery-1.6.3.min.js"></script> <script> //plugin, take it to another file (function( $ ){ $.fn.splitWords = function(ary) { this.html('<span>'+this.html().split(' ').join('</span> <span>')+'</span>'); this.children('span').click(function(){ $(this).css("background-color","#C0DEED"); ary.push($(this).html()); }); }; })( jQuery ); //plugin, take it to another file $(document).ready(function(){ var clicked_words = []; $('#myId').splitWords(clicked_words); //just to see what we've stored $('button').click(function(){alert(clicked_words);}); }); </script> <div id='myId'> Some random text in here with many words huh </div> <button>See content</button> A: Here is a completely different method. I am not sure about the practicality of it, but it may give you some different ideas. Here is what I am thinking if you have a container tag with position relative with just text in it. Then you could put a span around each word record its offset Height, Width, Left, and Top, then remove the span. Save those to an array then when there is a click in the area do a search to find out what word was closest to the click. This obviously would be intensive at the beginning. So this would work best in a situation where the person will be spending some time perusing the article. The benefit is you do not need to worry about possibly 100s of extra elements, but that benefit may be marginal at best. Note I think you could remove the container element from the DOM to speed up the process and still get the offset distances, but I am not positive. A: This is a followup on my comment to stevendaniels' answer (above): In the first code section above, range.setStart(node, (range.startOffset - 1)); crashes when run on the first word in a "node," because it attempts to set range to a negative value. I tried adding logic to prevent that, but then the subsequent range.setStart(node, range.startOffset + 1); returns all but the first letter of the first word. Also, when words are separated by a newline, the last word on the previous line is returned in addition to the clicked-on word. So, this needs some work. Here is my code to make the range expansion code in that answer work reliably: while (range.startOffset !== 0) { // start of node range.setStart(node, range.startOffset - 1) // back up 1 char if (range.toString().search(/\s/) === 0) { // space character range.setStart(node, range.startOffset + 1);// move forward 1 char break; } } while (range.endOffset < node.length) { // end of node range.setEnd(node, range.endOffset + 1) // forward 1 char if (range.toString().search(/\s/) !== -1) { // space character range.setEnd(node, range.endOffset - 1);// back 1 char break; } } A: For the sake of completeness to the rest of the answers, I am going to add an explanation to the main methods used: * *window.getSelection(): This is the main method. It is used to get information about a selection you made in text (by pressing the mouse button, dragging and then releasing, not by doing a simple click). It returns a Selection object whose main properties are anchorOffset and focusOffset, which are the position of the first and last characters selected, respectively. In case it doesn't make total sense, this is the description of anchor and focus the MDN website I linked previously offers: The anchor is where the user began the selection and the focus is where the user ends the selection * *toString(): This method returns the selected text. *anchorOffset: Starting index of selection in the text of the Node you made the selection. If you have this html: <div>aaaa<span>bbbb cccc dddd</span>eeee/div> and you select 'cccc', then anchorOffset == 5 because inside the node the selection begins at the 5th character of the html element. *focusOffset: Final index of selection in the text of the Node you made the selection. Following the previous example, focusOffset == 9. *getRangeAt(): Returns a Range object. It receives an index as parameter because (I suspect, I actually need confirmation of this) in some browsers such as Firefox you can select multiple independent texts at once. * *startOffset: This Range's property is analogous to anchorOffset. *endOffset: As expected, this one is analogous to focusOffset. *toString: Analogous to the toString() method of the Selection object. Aside from the other solutions, there is also another method nobody seems to have noticed: Document.caretRangeFromPoint() The caretRangeFromPoint() method of the Document interface returns a Range object for the document fragment under the specified coordinates. If you follow this link you will see how, in fact, the documentation provides an example that closely resembles what the OP was asking for. This example does not get the particular word the user clicked on, but instead adds a <br> right after the character the user clicked. function insertBreakAtPoint(e) { let range; let textNode; let offset; if (document.caretPositionFromPoint) { range = document.caretPositionFromPoint(e.clientX, e.clientY); textNode = range.offsetNode; offset = range.offset; } else if (document.caretRangeFromPoint) { range = document.caretRangeFromPoint(e.clientX, e.clientY); textNode = range.startContainer; offset = range.startOffset; } // Only split TEXT_NODEs if (textNode && textNode.nodeType == 3) { let replacement = textNode.splitText(offset); let br = document.createElement('br'); textNode.parentNode.insertBefore(br, replacement); } } let paragraphs = document.getElementsByTagName("p"); for (let i = 0; i < paragraphs.length; i++) { paragraphs[i].addEventListener('click', insertBreakAtPoint, false); } <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p> It's just a matter to get the word by getting all the text after the previous and before the next blank characters. A: As far as I know, adding a span for each word is the only way to do this. You might consider using Lettering.js, which handles the splitting for you. Though this won't really impact performance, unless your "splitting code" is inefficient. Then, instead of binding .click() to every span, it would be more efficient to bind a single .click() to the container of the spans, and check event.target to see which span has been clicked. A: Here are improvements for the accepted answer: $(".clickable").click(function (e) { var selection = window.getSelection(); if (!selection || selection.rangeCount < 1) return true; var range = selection.getRangeAt(0); var node = selection.anchorNode; var word_regexp = /^\w*$/; // Extend the range backward until it matches word beginning while ((range.startOffset > 0) && range.toString().match(word_regexp)) { range.setStart(node, (range.startOffset - 1)); } // Restore the valid word match after overshooting if (!range.toString().match(word_regexp)) { range.setStart(node, range.startOffset + 1); } // Extend the range forward until it matches word ending while ((range.endOffset < node.length) && range.toString().match(word_regexp)) { range.setEnd(node, range.endOffset + 1); } // Restore the valid word match after overshooting if (!range.toString().match(word_regexp)) { range.setEnd(node, range.endOffset - 1); } var word = range.toString(); });​ A: like this Get user selected text with jquery and its uses? A: The selected solution sometimes does not work on Russian texts (shows error). I would suggest the following solution for Russian and English texts: function returnClickedWord(){ let selection = window.getSelection(), text = selection.anchorNode.data, index = selection.anchorOffset, symbol = "a"; while(/[a-zA-z0-9а-яА-Я]/.test(symbol)&&symbol!==undefined){ symbol = text[index--]; } index += 2; let word = ""; symbol = "a"; while(/[a-zA-z0-9а-яА-Я]/.test(symbol) && index<text.length){ symbol = text[index++]; word += symbol; } alert(word); } document.addEventListener("click", returnClickedWord); A: As with the accepted answer, this solution uses window.getSelection to infer the cursor position within the text. It uses a regex to reliably find the word boundary, and does not restrict the starting node and ending node to be the same node. This code has the following improvements over the accepted answer: * *Works at the beginning of text. *Allows selection across multiple nodes. *Does not modify selection range. *Allows the user to override the range with a custom selection. *Detects words even when surrounded by non-spaces (e.g. "\t\n") *Uses vanilla JavaScript, only. *No alerts! getBoundaryPoints = (range) => ({ start: range.startOffset, end: range.endOffset }) function expandTextRange(range) { // expand to include a whole word matchesStart = (r) => r.toString().match(/^\s/) // Alternative: /^\W/ matchesEnd = (r) => r.toString().match(/\s$/) // Alternative: /\W$/ // Find start of word while (!matchesStart(range) && range.startOffset > 0) { range.setStart(range.startContainer, range.startOffset - 1) } if (matchesStart(range)) range.setStart(range.startContainer, range.startOffset + 1) // Find end of word var length = range.endContainer.length || range.endContainer.childNodes.length while (!matchesEnd(range) && range.endOffset < length) { range.setEnd(range.endContainer, range.endOffset + 1) } if (matchesEnd(range) && range.endOffset > 0) range.setEnd(range.endContainer, range.endOffset - 1) //console.log(JSON.stringify(getBoundaryPoints(range))) //console.log('"' + range.toString() + '"') var str = range.toString() } function getTextSelectedOrUnderCursor() { var sel = window.getSelection() var range = sel.getRangeAt(0).cloneRange() if (range.startOffset == range.endOffset) expandTextRange(range) return range.toString() } function onClick() { console.info('"' + getTextSelectedOrUnderCursor() + '"') } var content = document.body content.addEventListener("click", onClick) <div id="text"> <p>Vel consequatur incidunt voluptatem. Sapiente quod qui rem libero ut sunt ratione. Id qui id sit id alias rerum officia non. A rerum sunt repudiandae. Aliquam ut enim libero praesentium quia eum.</p> <p>Occaecati aut consequuntur voluptatem quae reiciendis et esse. Quis ut sunt quod consequatur quis recusandae voluptas. Quas ut in provident. Provident aut vel ea qui ipsum et nesciunt eum.</p> </div> Because it uses arrow functions, this code doesn't work in IE; but that is easy to adjust. Furthermore, because it allows the user selection to span across nodes, it may return text that is usually not visible to the user, such as the contents of a script tag that exists within the user's selection. (Triple-click the last paragraph to demonstrate this flaw.) You should decide which kinds of nodes the user should see, and filter out the unneeded ones, which I felt was beyond the scope of the question. A: Here's an alternative to the accepted answer that works with Cyrillic. I don't understand why checking the word boundaries is necessary, but by default the selection is collapsed for some reason for me. let selection = window.getSelection(); if (!selection || selection.rangeCount < 1) return let node = selection.anchorNode let range = selection.getRangeAt(0) let text = selection.anchorNode.textContent let startIndex, endIndex startIndex = endIndex = selection.anchorOffset const expected = /[A-ZА-Я]*/i function testSlice() { let slice = text.slice(startIndex, endIndex) return slice == slice.match(expected)[0] } while(startIndex > 0 && testSlice()) { startIndex -= 1 } startIndex += 1 while(endIndex < text.length && testSlice()){ endIndex += 1 } endIndex -= 1 range.setStart(node, startIndex) range.setEnd(node, endIndex) let word = range.toString() return word A: What looks like a slightly simpler solution. document.addEventListener('selectionchange', () => { const selection = window.getSelection(); const matchingRE = new RegExp(`^.{0,${selection.focusOffset}}\\s+(\\w+)`); const clickedWord = (matchingRE.exec(selection.focusNode.textContent) || ['']).pop(); }); I'm testing A: an anonymous user suggested this edit: An improved solution that always gets the proper word, is simpler, and works in IE 4+ http://jsfiddle.net/Vap7C/80/ document.body.addEventListener('click',(function() { // Gets clicked on word (or selected text if text is selected) var t = ''; if (window.getSelection && (sel = window.getSelection()).modify) { // Webkit, Gecko var s = window.getSelection(); if (s.isCollapsed) { s.modify('move', 'forward', 'character'); s.modify('move', 'backward', 'word'); s.modify('extend', 'forward', 'word'); t = s.toString(); s.modify('move', 'forward', 'character'); //clear selection } else { t = s.toString(); } } else if ((sel = document.selection) && sel.type != "Control") { // IE 4+ var textRange = sel.createRange(); if (!textRange.text) { textRange.expand("word"); } // Remove trailing spaces while (/\s$/.test(textRange.text)) { textRange.moveEnd("character", -1); } t = textRange.text; } alert(t); }); A: Here's an alternative that doesn't not imply to visually modify the range selection. /** * Find a string from a selection */ export function findStrFromSelection(s: Selection) { const range = s.getRangeAt(0); const node = s.anchorNode; const content = node.textContent; let startOffset = range.startOffset; let endOffset = range.endOffset; // Find starting point // We move the cursor back until we find a space a line break or the start of the node do { startOffset--; } while (startOffset > 0 && content[startOffset - 1] != " " && content[startOffset - 1] != '\n'); // Find ending point // We move the cursor forward until we find a space a line break or the end of the node do { endOffset++; } while (content[endOffset] != " " && content[endOffset] != '\n' && endOffset < content.length); return content.substring(startOffset, endOffset); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7563169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "51" }
Q: Prevent Main UI to collapse from child thread I have this code: class FinalUI1 extends javax.swing.JFrame { //do something Thread t; try { t = new Thread(new PcapTool(null)); t.start(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // do something } class PcapTool extends ApplicationFrame implements Runnable { //do something public void run() { Display Graph based on above classes input } } There is a Main UI window and new graphs are generated in separate window whenever user clicks a button. I want to display graphs, when user clicks button in FinalUI1 class, but when I close any of generated graphs, the whole UI collapses, everything is gone. I want to retain the main UI and shut down the particular graph which user chose to close. It came to my mind that, since UI is on main thread and I can spawn new graphs in new thread, if I do this and close one of child threads, the main UI should still be running. Additional code: public class PcapTool extends ApplicationFrame { public static String domainChoice, domainConcatenate="";; public static XYSeries series1; public static XYSeriesCollection dataset=null; public static XYSeries series2; public static PacketInfo resPacketObject; public static Hashtable<String, Object> DomainNameTable=new Hashtable<String, Object>(); public static String[] hasArray=new String[100]; public static JFreeChart chart; public static String customTitle = " "; public ArrayList<Double> dataNumberList=new ArrayList<Double>(); public static String[]dataUsage; public static String[]timeArrival,txRxTag; private static final long serialVersionUID = 1L; public PcapTool(final String title) throws InterruptedException { super(title); IntervalXYDataset dataset = createDataset(); JFreeChart chart = createChart(dataset); final ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new java.awt.Dimension(2000,1000));//(width,height) of display setContentPane(chartPanel); } public IntervalXYDataset createDataset() throws InterruptedException { // add Series 1 and Series 2 } dataset= new XYSeriesCollection(series1); dataset.addSeries(series2); dataset.setIntervalWidth(0.05);//set width here return dataset; } private JFreeChart createChart(IntervalXYDataset dataset) { final JFreeChart chart = ChartFactory.createXYBarChart( "Pcap Analysis Tool\n Domain: "+domainConcatenate, "Time (Seconds)", false, "Data Usage (bytes)", dataset, PlotOrientation.VERTICAL, true, true, false ); return chart; } public static void main(final String[] args) throws InterruptedException { final PcapTool demo = new PcapTool("PCAP Analysis"); demo.pack(); RefineryUtilities.centerFrameOnScreen(demo); demo.setVisible(true); System.out.println("domain: "+dropBoxUserValue); } } A: I'm guessing that this behavior is due to your using JFrames or something similar to display your child windows, and that the JFrame's setDefaultCloseOperation properties have been set to JFrame.EXIT_ON_CLOSE which will cause the JVM to exit when any of the windows close. I think that you should show them in dialog windows such as a JDialog, not in a JFrame or ApplicationFrame. Also, I have to worry about your use of threading. All Swing code needs to be called on one single thread, the EDT, not separate threads as you may be doing above. Sure, do long-running calculations in a background thread, but the actual display of the chart and any other Swing calls must be on the EDT (unless you know for certain that the calls are thread-safe). The other option is to set the JFrame setDefaultCloseOperation to JFrame.DISPOSE_ON_CLOSE, but still these guys are behaving as dialogs and in my mind, should be shown as dialogs, JDialogs. If this doesn't help, consider posting a minimal compilable and runnable example that is very small, has no extraneous code unrelated to the problem at hand, and that demonstrates your problem, an SSCCE.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: href from json in android xml I have and app and on my main menu page I want to load a clickable ad (href) from json. example : 'nationalad': "<"img src=\"http:\/\/www.mywebsite.com\/images\/national\/fullrz_2_4e657ae4df4ee_mywebsite.JPG\">" This is the value I am getting back from json : "<"img src="http://www.mywebsite.com/images/national/fullrz_2_4e657ae4df4ee_kickintheapp.JPG"> How do I set this in my xml page? Do I use a view or webview or an image /image button? Completely lost. A: Use a WebView, and show the data by using loadDataWithBaseURL(null, yourData, "text/html", "utf-8", null); A: Hmm this works great for the first run what when I re-run the app the webview is not showing. The only thing that changes is that the image coming in is different on each load. webView2.loadDataWithBaseURL(null, valArray.getString(1), "text/html", "utf-8", null);
{ "language": "en", "url": "https://stackoverflow.com/questions/7563174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jqGrid is empty, even though pager shows results I'm upgrading from jqGrid 3.6.3 -> 4.1.2. After upgrading the grid always displays empty, even though the pager shows the correct number of results (6 in this case). I can see that the JSON is being retrieved and is valid. No error is displayed, and nothing is written to the javascript console. If I hook into the loadComplete event, it fires -- and grid.getDataIDs() returns an empty array - as if there were no data. Here is the JSON being transmitted (formatted with JSONLint). It is properly formatted JSON & passes JSONLint validation: { "pageCount": "1", "pageSize": "15", "pageNumber": "1", "itemCount": "6", "items": [ { "Id": "1", "Name": "Administrator" }, { "Id": "3", "Name": "asfasfassf" }, { "Id": "6", "Name": "askjdhajksdk sh" }, { "Id": "2", "Name": "fg" }, { "Id": "5", "Name": "test" }, { "Id": "4", "Name": "sa afasf saf" } ] } Here is the relevant portion of the jqGrid options that I am passing into jqGrid: { datatype: 'json', jsonReader: { root: 'items', id: '0', repeatitems: false, page: 'pageNumber', total: 'pageCount', records: 'itemCount' }, mtype: 'POST', ... }; I have scoured the interwebs for an answer, but no luck. Does anyone have a suggestion?! See below a screenshot of the options object that I am passing into jqGrid(options): Thanks in advance!!! A: Add cell: '' to your jsonReader: jsonReader: { root: 'items', id: '0', repeatitems: false, page: 'pageNumber', total: 'pageCount', records: 'itemCount', cell: '' } http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data#json_data By default, the jsonReader's cell option is set to "cell", which would mean your data would need to be formatted like this: { "pageCount": "1", "pageSize": "15", "pageNumber": "1", "itemCount": "6", "items": [ { "Id": "1", "cell": ["Administrator"] }, { "Id": "3", "cell": ["asfasfassf"] } ] } Also, take a look at the upgrade guide for v3.6.4 to v3.6.5: http://www.trirand.com/jqgridwiki/doku.php?id=wiki:upgrade_from_3.6.4_to_3.6.5 A: I solved the problem & the issue was completely unrelated to JSON. After upgrading to jqGrid 4.1.2 I found that my grid table needed to have an id attribute. Unfortunately, I had set an invalid ID on the table (it, by accident, had spaces in it). Once I fixed the table's id attribute, the grid started rendering correctly. Thanks for your answers!
{ "language": "en", "url": "https://stackoverflow.com/questions/7563176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Iphone google plus stream page How does stream page of google plus works on iphone, where you can slide the view left to right or vice versa (Nearby - Circles - Incoming). Is there any native control or sample codes? A: This doesn't exactly answer your question, but you can use the Google API Objective-C Client to call the Google+ APIs. Client Library: http://code.google.com/p/google-api-objectivec-client/ Sample Code: http://code.google.com/p/google-api-objectivec-client/source/browse/#svn%2Ftrunk%2FExamples%2FPlusSample
{ "language": "en", "url": "https://stackoverflow.com/questions/7563182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Making an array available outside of a function I have the following code: class Transaction : public transactor<> { public: Transaction(arg1, arg2) // can put any number of args :transactor<>(arg1) { //some initialization } void operator()(argument_type &T) { //create an array //cannot modify outside program from here } void on_commit() { //must make array created in operator()() available to outside program here //cannot return anything } Both operator()() and on_commit() are called by 3rd party code. In the operator()() method, I create an array after querying a database. In case the transaction fails, the outside program cannot be changed at this point. This must all be done in the on_commit() method. The question is: How can I make this array available to the outside program? I am quite new to C++ and I understand this is likely a rather simple question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: best practice for handling PHP to mysql queries? I find myself writing very similar queries many times in an application I am making. I am looking for ideas on how I could organize and handle many different SELECT queries? I am not asking about how to optimize or secure the queries, I'm asking how I could organize multiple ones on a single page. A: The simplest way is to see if you can make very similar queries into functions that take parameters. The next simplest way is to make classes that represent logical components or "services" in your system and make methods that query things relevant to those services. One such service might be a "UserService" that has to do with user accounts. It might have a method like "getLatestRegisteredUsers($limit)". These service classes might have a small base class with some commonly used helper methods. More complex solutions like ORMs and query builders exist, but they may well be overkill in your case. Whatever you do, try to make small, well-defined and well-named functions and classes. A huge "functions.php" or "DatabaseClass.php" with everything randomly lumped together hardly helps anything in the long run. A: I'd reccomend you look into creating a master PHP Class for your common database connections and queries.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Anything wrong with short-lived event handlers? For example, is there anything wrong with something like this? private void button1_Click(object sender, EventArgs e) { Packet packet = new Packet(); packet.DataNotSent += packet_DataNotSent; packet.Send(); } private void packet_DataNotSent(object sender, EventArgs e) { Console.WriteLine("Packet wasn't sent."); } class Packet { public event EventHandler DataNotSent; public void Send() { if (DataNotSent != null) { DataNotSent(null, EventArgs.Empty); } } } If it were just a simple integer variable declaration it would be fine because once it went out of scope and would later be collected by the garbage collector but events are a bit .. longer-living? Do I have to manually unsubscribe or take any sort of measures to make sure this works properly? It just feels.. weird. Not sure if it is correct or not. Usually when I add to an event handler it lasts for the entirety of the application so I'm not sure about what happens when constantly adding and removing event handlers. A: Technically, there is nothing wrong with this code. Since there won't be any references to packet after the method finishes, the subscription is going to be (eventually) collected too. As a matter of style, doing this is very unusual, I think. Better solution would probably be to return some kind of result from Send() and base your next action on that. Sequential code is easier to understand. A: That's really the beauty of event-based programming -- you don't really care who / what / if anyone is listening, you just say something happened and let whoever subscribed react accordingly. You don't have to manually unsubscribe but you should unsubscribe as the object goes out scope. The link will keep the subscribers alive (from @pst). A: When the object that publishes the event becomes eligible for garbage collection, all the objects subscribed to that event become eligible for garbage collection as well (provided there are no other references to them). So, in your example: * *When packet goes out of scope, it becomes eligible for GC. *So the object containing packet_DataNotSent become eligible for GC as well (unless referenced by something else). *If the object containing packet_DataNotSent is referenced by something else, it will of course not be GC-ed, but it will still automatically "unsibscribe" when packet is GC-ed. A: I understand that you can get a memory leak if the event source i.e. Packet class and the event sink i.e. the handler of the event have a lifetime mismatch. In this case the delegate that you create is scoped to this function because the event sink is only scoped to this function. You can make a call to packet.DataNotSent -= packet_DataNotSent; after the send method executes to ensure that the delegate is garbage collected. Please read this A: I guess you've simplified the example for brevity, but in your snippet, there is no need to use an event. Packet.Send() could just return a result that is checked. You only really need a more complicated approach if there is going to be some asynchronicity (e.g. an asynchronous operation, scheduling for future execution, etc.), and Packet.Send() does not return immediately. In terms of object life-cycle management, your event subscription does not pose a problem, since an event subscription will keep the handler alive but not vice versa. That is, the class that button1_Click belongs to will not be garbage collected while there is a live reference to a packet that it has subscribed to. Since the packets have a short lifespan, this won't be a problem. If in your real-world usage, Packet.Send() cannot return the result, then I would be tempted to pass a delegate to the packet rather than subscribe to an event on it, assuming only one object needs to be notified of the failure. A: Events should be used for scenarios where one doesn't know who might be interested in being notified when something happens or some action becomes necessary. In your example, if anyone's interested in knowing when the packet is discovered to be undeliverable, the code calling the constructor is apt to know who that would be. It would thus be better to have the packet's constructor accept an Action<Packet, PacketResult> delegate than publish an event for that purpose.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: std::vector, element pointer and input interator I don't have my copy of Meyer's Effective C++ with me, so please forgive the question. template <class InputIterator> void insert ( iterator position, InputIterator first, InputIterator last ); For vector's insert, is a byte* to a raw memory block a valid InputIterator? typedef unsigned char byte; vector<byte> my_vector; byte my_data[NNN]; const byte* first = my_data; const byte* last = my_data + COUNTOF(my_data); my_vector.insert(my_vector.end(), first, last); A: Yes, a pointer is an input iterator.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563197", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Can a Grails plugin use the datasource from the app that uses it? I want to use a plugin to share a bunch of domain classes and controllers between multiple applications. Each application will use its own database. I'd like the domain classes in the plugin to store their data in the same database as the application. How do I do that please? A: The plugin basically gets merged into the application that contains it, so it uses the settings from the application. This includes the DataSource. There's actually no way to specify in a domain class what database it uses. Technically this isn't true in 2.0 since it can choose which of multiple datasources to use, but the choice comes from the application's defined datasources. A: Your plugin can change the DataSource.groovy file, so you might try reading the application name from the configuration and setting the data source accordingly. Perhaps it would look like this: production { dataSource { jndiName = "java:comp/env/jdbc/${grailsApplication.metadata.'app.name'}" } } A: In Grails 3 if you want to share domain classes between multiple applications you can put the domain classes in a plugin. You can then add that plugin as a dependency to your multiple applications. Your application will then have access to those domain classes. The datasource is set at the toplevel application that uses the plugins. So if you only have 1 datasource setup in the top level app the plugins domain classes will be created in the outputed sql when you do a grails schema-export command.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: from domain model to transaction script The new place I started at is just starting to develop a completely new product from scratch. They are going transaction script in application services, completely dumb entities, and a hand rolled DAL with stored procedures (the argument is that nhibernate doesn't optimize sql well, loads too much stuff, doesn't scale well to huge projects etc etc etc). the app is supposed to be HUGE project just in it's infancy. I'm coming from a position where I was doing domain model with all business logic encapsulated in that and the app services only handling infrastructure + loading up the model with nhibernate and scripting it. I really believe going with the 2nd approach is much better. I was planning on doing a presentation on why. I have plenty of books/articles/personal opinions that I can back this up with...but being more of a "junior" there it might not mean much (I was also the single dev at my last place). What I'm looking for is some experience/tips/examples of failed projects from more senior people why going transaction script/hand rolled DAL is not the right idea. A: Well there is always two sides of a coin. They may have some points regarding Nhibernate and performance issues. But there is always solutions to that, like load strategies where you tell exactly how Nhibernate should tackle specific critial queries. With load strategies, caching and sql index tuning you can get far regarding performance, really far. But true benefit with ORM is that it reduces code base and make it more DRY. Makes your system more maintainable. It also reduces a "layer" since you do not need stored procedures. I've been in several projects like you, and trust me, they face mainaince problem with * probably redundant code in application services since you do not have a domain core that can put logic at one place instead of appearing in several application services methods. * *A huge DAL layer that includes several Stored procedures. *Logic easily slips out to GUI I can make the list longer... but my point is that people tend to choose Transaction script sometimes just because it easy to understand, to start with and, well can be good at performance. BUT usually the problems occur when consultants, employees leave project and maintanence team takes over. There is often not cristal clear where changes should be done and most TS application I've seen has been architectural abused. They were good apps from the begining but since the invite you to put logic in SP's, services, GUI (because of the lack of restricted API, interfaces etc). You follow me? /Magnus p.s You can get great performance and DDD with CQRS approach... A: In addition to what Paul T Davies and Magnus Backeus have said. I think that at the end of the day it would be a people and cultural issue. If people are open minded and willing to learn it will be relatively easy to convince them. If they consider you a 'junior' (which is a bad sign because the only thing that matters is what you say not how old/experienced you are) you can appeal to a 'higher authority': * *Patterns of Enterprise Application Architecture *Domain-Driven Design *Growing Object Oriented Software *Dependency Injection in .NET Stored procedures are dead and you are not the only one who thinks so: It is startling to us that we continue to find new systems in 2011 that implement significant business logic in stored procedures. Programming languages commonly used to implement stored procedures lack expressiveness, are difficult to test, and discourage clean modular design. You should only consider stored procedures executing within the database engine in exceptional circumstances, where there is a proven performance issue. There is no point in convincing people that are not willing to improve and learn. Even if you manage to win one argument and squeeze in NHibernate, for example, they may end up writing the same tightly coupled, untestable, data-or-linq-oriented code as they did before. DDD is hard and it will require changing a lot of assumptions, hurt egos etc. Depending on the size of the company it may be a constant battle that is not worth starting. Driving Technical Change is the book that might help you to deal with these issues. It includes several behavior stereotypes that you may encounter: * *The Uninformed *The Herd *The Cynic *The Burned *The Time Crunched *The Boss *The Irrational Good luck! A: I would say taking material to back it up is the way to go, that way they can't use your inexperience as an argument (although it sounds to me that you are not particularly inexperienced or junior!). My main reccomendation would be this book: http://www.amazon.co.uk/Microsoft-NET-Architecting-Applications-PRO-Developer/dp/073562609X/ref=sr_1_1?ie=UTF8&qid=1317121019&sr=8-1 On page 146, it states: 'TS is suited for simple scenarios where the business logic is straightforward and, better yet, not likely to change and evolve.' This does not describe the system you are working on. It then goes on to describe Domain Model, and why it is suited to bigger systems. I would question whether thay understand that it is Transaction Script they are opting for? In my experience, TS can often be the default choice for inexperienced organisations who don't even understand that there is even an option. They just think 'that's how it's done'. How successful and maintainable is their current code? If they are choosing TS for huge projects, my guess would be 'not very'! Do they blame the client for changing specifications when things go wrong? If so, this is an indication that their choice of architecture is wrong. In my experience, the overhead in implementing Domain Model is minimal. And it is a lot less painful than trying to scale and maintain a badly architected system. Also, in this day and age, database servers should be able to handle systems based around NHibernate with no problems. If it can't, then that is a problem with the database server. And how do they intend to unit test these stored procedures? I usually find SP are the single biggest point of developer error. Like Magnus said, I could just go on and on about this. I don't know the details of the system, but as soon as you used the word HUGE, Domain Model becomes the most obvious choice.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to get MVC remote validation working I have an Invoice Model which has an areaId property: public class Invoice : IEntity, IValidatableObject { ... [Required(ErrorMessage = "Region is a required field.")] [Display(Name = "Region:")] [Remote("Check","Invoice")] public virtual int? AreaId { get; set; } ... So, I'm trying to get the remote validation working on AreaId. In my invoice controller I set up: public void Check(int id) { } which I expected would get hit when I did an insert for an Invoice as it would try to validate. Nothing happened when I validated. I checked fiddler and it had an HTTP 500 error trying to get to /Invoice/Check/Invoice.AreaId=1 It never got to my check method. I did however manually type in the URL Invoice/Check/1 and it got there alright. Anyone know what I'm doing wrong? It's like it's constructing the Url all wrong. A: The Url you are looking to create should actually be /Invoice/Check?AreaId=1 since you are passing the AreaID. I'm not sure if they are the cause but having both a virtual property and a function that returns void could be messing with the remote validation so change the function to return JsonResult and make the property non-virtual. Change the parameter in the Check function to AreaId rather than id. Also, if you have created custom routes they could be stuffing it up. Try following this: http://msdn.microsoft.com/en-us/library/gg508808%28v=vs.98%29.aspx. Especially the section entitled Adding Custom Remote Validation. A: Well, the 500 code is because your ajax url would be /Invoice/Check?AreaID=1 whereas you are accepting id in method signature, which also happens to be non nullable. This is why exception is thrown and you get 500 code on client side. Second thing, void method would not server your purpose here because it would not send back a value to client side. However, i can't imagine that it could be the source of exception in my wildest dreams. Furthermore, you can set return type to JsonResult, String or ContentResult to send an appropriate value to the client so it can check against it for validity. public string Check(int AreaID) { return "true"; } public JsonResult Check(int AreaID) { return Json(true); } public ContentResult Check(int AreaID) { return Content("True"); } one more thing, when you manually type Invoice/Check/1, 1 is assigned to id route value if you have not removed (and i bet you haven't) default route that comes with mvc app. This way non nullable parameter id gets value and no exception is thrown. A: Ended up using [Bind(Prefix = "EditInvoiceViewModel.ActivityId")] from How to use Bind Prefix?
{ "language": "en", "url": "https://stackoverflow.com/questions/7563201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Filenames and paths trouble The following example "walks" through a directory, prints the names of all the files, and calls itself recursively on all the directories. import os def walk(dir): for name in os.listdir(dir): path = os.path.join(dir,name) if os.path.isfile(path): print path else: walk1(path) os.path.join` takes a directory and a file name and joins them into a complete path. My exercise: Modify walk so that instead of printing the names of the files, it returns a list of names. Can someone explain what this function is doing per line? I have a good idea but when it gets to the line: else: walk(path), that throws me off since there is no explanation what that is doing. For this exercise, the only way I could think to change this to a list is by: def walk1(dir): res = [] for name in os.listdir(dir): path = os.path.join(dir,name) if os.path.isfile(path): res.append(path) else: walk1(path) return res My output went from so many output lines to just a mere few. Did I do this correctly? A: You need to add the result of your recursion to what you already have. A: Here's an annotated version with a small fix to the recursion. def walk1(dir): res = [] # for all entries in the folder, for name in os.listdir(dir): # compute the path relative to `dir` path = os.path.join(dir,name) # include entries recursively. if os.path.isfile(path): # the path points to a file, save it. res.append(path) else: # the path points to a directory, so we need # to fetch the list of entries in there too. res.extend(walk1(path)) # produce all entries at once. return res A: A small module I wrote, pathfinder, makes it easier (in my opinion anyway) to find paths. from pathfinder import pathfind paths = pathfind(a_dir, just_files=True) It's just a layer on top of os.walk, but removes some of the confusion surrounding it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can I Use A Javascript Array Object As An Argument In A Function? How? So I'm trying to create a function that takes in an array (I guess it's more of a JSON object, or so we were told) object and returns a value based on that array, but I keep getting an error, so I'm pretty certain I'm doing this wrong. I'm fairly new at JavaScript so go easy on me. Also, I found this thread which is similar to the question I'm asking, but I don't quite understand THAT question (and therefore it's answers). Here's a sample of the object we're given: var returned_json = { "nike_runs": [ { "start_time": "2011-03-11T19:14:44Z", "calories": 12.0, "distance_miles": "0.10", "total_seconds": 288.0, "average_pace":"50.47" }, { "start_time": "2011-03-11T19:41:25Z", "calories": 7.0, "distance_miles": "0.06", "total_seconds": 559.0, "average_pace": "165.19" }, { "start_time": "2011-03-11T20:27:45Z", "calories": 197.0, "distance_miles": "1.63", "total_seconds": 8434.0, "average_pace": "86.22" }, ... ] } Here's my code: function getExp (returned_json) { var exp; for (var i = 0; i <= returned_json.nike_runs.length; i++) { exp += returned_json.nike_runs[i].calories; } return exp; } It returns an error: TypeError: returned_json.nike_runs[i] is undefined I figured this has to do with the fact I'm not defining the type of object I want to pass into the function, but my research tells me that doesn't matter. Help? :( Thanks. A: Use i < returned_json.nike_runs.length, not i <= returned_json.nike_runs.length. Edit: While you’re at it, you better define a starting value for exp too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using app.yml to set root web address in Symfony 1.4 Alright, so this is a question more or less questioning how intelligent this design decision was in a symfony project, rather than a question to get something functioning. A coworker of mine recently decided forms should post certain data on a site using this action: <form action="http://<?php echo sfConfig::get( 'app_webroot' ) ?>" method="post" name="userCity" id="userCity"> That simply posts a user selected city to the index controller of the site to update the city in the session. In index.php within the web directory, we have this line: $configuration = ProjectConfiguration::getApplicationConfiguration('frontend', 'webrootrule', false); webrootrule being the rule set in app.yml. The purpose is to ensure the forms post to the correct domain, so in my dev environment I have the webroot option in index.php set to my environment, he has his set to his environment, and prod is set to the website's production domain name. Here's what the different webroot paths look like: echopony.website.internalsite.com coworker.website.internalsite.com website.com I've never needed to do anything like this. Before I divert too much time to getting this working without futzing with index.php and testing all of the forms, I just wanted to bounce this off of some of you and see if this is indeed a waste of our efforts. Even worse is that index.php is now versioned by him. I do not agree with versioning that file, but rather than outwardly denounce his methods I want to be absolutely sure he's actually doing things wrong. It just seems absurd to have to edit index.php before releasing updates to the site. You know, to avoid index.php setting the webroot as echopony.website.internalsite.com He has years and years of experience on me, so when I don't agree with his methods... I have to really ensure I'm in the right before taking action. Thanks for any input! A: You should work with absolute URLS here. Just use the url_for helper of Symfony. This helper is working environment dependend and can generate absolute URLs if you want. <form action="http://<?php echo url_for('/', true) ;?>" method="post" name="userCity" id="userCity"> the second parameter of the helper is responsible for creating absolute URLs (true) or not (false) Take a look at the official documentation for more info
{ "language": "en", "url": "https://stackoverflow.com/questions/7563210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: IIS 7.5 and MVC 3 using Windows Authentication - Getting 401 for static content, but never get prompted for credentials I have a MVC 3 site running on Server 2008 R2 with IIS 7.5. I am wondering why, (using fiddler), I keep getting 401 responses on static content followed immediately by either a 302 or a 200? Is this something I need to be concerned about? I can directly navigate in my browser to the content giving a 401, and the browser displays it without prompting for credentials. If I do a trace on failed requests, I get this as output: ModuleName UrlAuthorization Notification 4 HttpStatus 401 HttpReason Unauthorized HttpSubStatus 0 ErrorCode 0 ConfigExceptionInfo Notification AUTHORIZE_REQUEST ErrorCode The operation completed successfully. (0x0) I have checked all the directories, and files and they have the application pool user, (domain user), as owner with full permissions. As I said, my site is not broken, but I am wondering if I have an issue with my set up. Thanks in advance. EDIT: Here is a sample from Fiddler: A: Alright ... I resolved this in an odd way. In IIS 7.5 you can set the credentials to use when accessing the physical path for the file system. It appears by default it uses a "pass through" option ... somehow this appears to not work even when IUSR has access on the file system. I made a basic user account, granted them read on the file system, and then under IIS -> my website [Right Click] -> "Manage Website" -> "Advanced Settings" and updated the Physical Path Credentials. Oddly, Orchard, sharepoint, tfs, and SSRS websites on the same server didn't have this issue ... just my MVC3 app running from wwwroot. A: Deployed a simple MVC3 app to the default web path in IIS 7.5 / Windows 2008R2 that works correctly within Vis2k10's web server. Accessing the site unauthenticated, even though I am using the [authorize] on specific modules, retained the default code in global.asax.cs, and really haven't modified much. Any suggestions would be appreciated. Tried enabling only Anonymous as well as Anonymous plus Forms authentication without luck. Added to web.config without success: <location path="Content"> <system.web> <authorization> <allow users="*" /> </authorization> </system.web> </location> Tried updating modules without success: <modules> <remove name="UrlRoutingModule-4.0" /> <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" /> </modules> Verified IIS permissions with access to the file system. Once logged in, system works like a champ. A: Do you have a web.config in your content folder by any chance or any auth rules setup for the content folder in your root web.config or in any application above it that could cause web config inheritance to be an issue?
{ "language": "en", "url": "https://stackoverflow.com/questions/7563211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Scala Enums - How to assign initial values? object WeekDay extends Enumeration { type WeekDay = Value val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value } How would you set an initial value so WeekDay.Mon == 1 and WeekDay.Tue == 2 and so on would be true? There's a constructor in Enumeration, Enumeration(initial: Int, names: String*), is there a way I could use that to create the WeekDay object? A: Try object WeekDay extends Enumeration(1) i.e. call Enumeration's constructor. The second parameter names: String* means it accepts any number of string arguments - including none at all, hence just one argument.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Linking multiple times a single cross platform object file? If I compile a cross-platform piece of code into an object file, will it be possible to use the linker to create separate platform-dependent executables (.exe,.bin) from that single binary file? EDIT: It seems the answerers don't really understand my question. I'm asking if you can use a cross-platform object and generate platform-dependent executables from that. A: That pretty much depends entirely on the linker and other development tools that you have. Certainly cross compilation is possible in an advanced environment like gcc, where you can generate object code for different architectures. But packaging all those different-architecture objects into a single executable is not something I've ever seen done in gcc. I've seen fat binaries on the Apple platforms (where an executable would run on the old 68K Macs or the newer PowerPC ones) but I've never really been a big fan of them and Apple was in total control of the environment there. In addition, the loader code (part of the OS usually) has to be able to detect which architecture it should extract and run from such a fat binary (this is where Apple's control came in handy - they could modify their various operating systems to detect and load the correct version). Personally, I think you'd either be better off using a portable language (Java, Perl, Python et al) or packaging your application into different binaries - you could always use one of the excellent cross-platform installation toolkits to install the correct version. Based on your edit clarifying the question: yes. If the object files are truly cross-platform, they will work on all those platforms. So, by definition, you can construct a platform-specific executable based on that. Note that this is not the same as compiling some cross-platform source code since the compilation process itself will most likely lock it to a specific platform. And, again, it depends on the tool chain being used (compiler, linker, loader, etc). A: Fat binaries are supposed to be supported on linux as well, never tried however. The FatELF page says they support static and dynamic libraries, their faq seems extensive.
{ "language": "en", "url": "https://stackoverflow.com/questions/7563218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }