text
stringlengths
8
267k
meta
dict
Q: How to instantiate a generic list without knowing the type I created a method to organize a generic list without know the type, it will sort if its int or decimal. However the code that retrieves the values from textboxes uses List I tried to convert it to List, but it doesnt work. I want this code to work if they type integers or decimals or strings in the textboxes. This was part of an interview question where they asked not to use the sort method, and that the input should receive for example INTS or DECIMALS private void btnSort_Click(object sender, EventArgs e) { List<int> list = new List<int>(); list.Add(int.Parse(i1.Text)); list.Add(int.Parse(i2.Text)); list.Add(int.Parse(i3.Text)); list.Add(int.Parse(i4.Text)); list.Add(int.Parse(i5.Text)); Sort(list); StringBuilder sb = new StringBuilder(); foreach (int t in list) { sb.Append(t.ToString()); sb.AppendLine(); } result.Text = sb.ToString(); } private void Sort<T>(List<T> list) { bool madeChanges; int itemCount = list.Count; do { madeChanges = false; itemCount--; for (int i = 0; i < itemCount; i++) { int result = Comparer<T>.Default.Compare(list[i], list[i + 1]); if (result > 0) { Swap(list, i, i + 1); madeChanges = true; } } } while (madeChanges); } public List<T> Swap<T>(List<T> list, int firstIndex, int secondIndex) { T temp = list[firstIndex]; list[firstIndex] = list[secondIndex]; list[secondIndex] = temp; return list; } I wanted that something like this: but gives error Error 1 The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?) c:\users\luis.simbios\documents\visual studio 2010\Projects\InterViewPreparation1\InterViewPreparation1\Generics\GenericsSorting1.cs 22 18 InterViewPreparation1 List list = new List(); list.Add(i1.Text); list.Add(i2.Text); Sort(list); A: because its an interview question in which they asked not to use the sort method. In this case you can add a generic constraint IComparable<T> and then use the CompareTo() method: private void Sort<T>(List<T> list) where T : IComparable<T> { //... } Edit: You would have to write custom code to determine whether the input is string, int or decimal, i.e. use TryParse(..) - this will be very fragile though. Once you do know the type (one way or another) you can use MakeGenericType() and Activator.CreateInstance() to create your List<T> object at run time and then use MakeGenericMethod() to call your generic method: Type type = typeof(string); IList list = (IList) Activator.CreateInstance(typeof(List<>).MakeGenericType(type)); //add items to list here var p = new Program(); MethodInfo method = typeof(Program).GetMethod("Sort"); MethodInfo genericMethod = method.MakeGenericMethod(new Type[] { type }); genericMethod.Invoke(p, new [] {list} ); I am pretty sure that is not what the interview question intended to ask for. A: First, as Jason points out, let the platform do the work for you - call .Sort. Second, it looks to me like you're going to have to select the 'T' of the List based on examining the contents of the textboxes so you can handle ints vs. strings, etc. And then assign items to the list based on that. But once you have decided, your sort won't care. A: You're not going about this the right way. Embrace generics correctly. What you want is this: public string Foo<T>(IEnumerable<string> strings) where T : struct, IComparable<T> { var list = strings.Select(s => (T)Convert.ChangeType(s, typeof(T))).ToList(); list.Sort((x, y) => (x.CompareTo(y))); return String.Join("\n", list); } Now you can say string response = Foo<int>(strings); or string response = Foo<decimal>(strings); depending on which you want. Note that * *We use List<T>.Sort to do the sorting. *We use String.Join to build the string to display back to the user. This should compile, but please excuse trivial errors if it doesn't. I can't fire up the ol' compiler right now. Edit: I see you edited in that you can't use List<T>.Sort. It's easy enough to replace my use of List<T>.Sort with your own implementation. A: Try something like: private static IList foobar(Type t) { var listType = typeof(List<>); var constructedListType = listType.MakeGenericType(t); var instance = Activator.CreateInstance(constructedListType); return (IList)instance; } Then use: IList list = foobar(TYPE); Where TYPE is the type that you want you list to be. Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7570992", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Any parameters passed with multiviews? Given /group/14/ with multiviews enabled on group, I get a redirect to /group.php, but is 14 passed to PHP in any form besides the $_SERVER variables? Ideally, I could get this in a query string of some kind. I read parts of the Content Negotiation article on it, but I can't seem to find any indication that this is the case. Edit: For whatever reason, that above wasn't clear. Let me try again. I have group.php which wants a group id like group.php?id=14. Normally, I'd use URL rewriting to have /group/14/ rewrite to /group.php?id=14. However, in this case I have multiviews enabled, and the URL rewrite does not trigger. So /group/14/ DOES get sent to /group.php but does not send 14 as a query string. Is there anyway besides parsing 14 from the $_SERVER['REQUESTED_URI'] that I can get it with multiviews enabled? A: This rule will match: RewriteRule ^group.php/(.*)$ ./group.php?id=$1 [L,NE] Having Multiviews enabled transform the group/14 to group.php/14 (where ${PATH_INFO} is '/14', which is smarter than other $_SERVER vars, but this is another problem). After this first apache internal rewrite (from multiviews) the rewriteRule are run again, and you can then capture the group.php/14.
{ "language": "en", "url": "https://stackoverflow.com/questions/7570998", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: asp.net - trigger updatepanel on pressing the return key I have a page with an updatepanel which contains a small login form - it runs fine when the user clicks on the submit button, but if the user presses the return key after entering their password, it does not run. Here's the code... <asp:UpdatePanel ID="UpdatePanel2" runat="server"> <Triggers> <asp:AsyncPostBackTrigger ControlID="loginButton" EventName="Click" /> </Triggers> <ContentTemplate> <asp:TextBox ID="username" MaxLength="11" runat="server" /> <asp:TextBox ID="password" MaxLength="64" runat="server" TextMode="Password" /> <asp:LinkButton ID="loginButton" OnClick="Submit_login" runat="server" Text="<img src='login.png' alt='Login' />" /> </ContentTemplate> </asp:UpdatePanel> A: If you add a panel in the Content template and assign the DefaultButton, it should submit the button when a user hits Enter. <ContentTemplate> <asp:panel id="p" runat="server" defaultbutton="loginButton"> //Form here with loginButton </asp:panel> </ContentTemplate> A: Put your the controls that are inside <ContentTemplate> inside an Panel and set it's default button to be loginButton. Like this: <asp:Panel id="defaultPanel" runat="server" DefaultButton="loginButton"> <asp:TextBox ID="username" MaxLength="11" runat="server" /> <asp:TextBox ID="password" MaxLength="64" runat="server" TextMode="Password" /> <asp:LinkButton ID="loginButton" OnClick="Submit_login" runat="server" Text="<img src='login.png' alt='Login' />" /> </asp:Panel>
{ "language": "en", "url": "https://stackoverflow.com/questions/7571002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Eclipse: Define multiple working sets all at once I have to define 10 working sets in Eclipse and repeat it over a couple of workspaces. * *Is there a way to define the 10 working sets all at once? Rather than trudging thro the select working set drop down ten times? *Is there a way to copy working set defs from one workspace to another? A: Regarding the 2nd problem, I found a duplication question here(Share / Export eclipse working sets) which use AnyEdit eclipse plugin. For the 1st, I dont think there's any better choice.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571003", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Compiler doesn't complain when I ended a line with two semicolons. Why? I thought bad thing would happen when I ended a line like this. But compiler didn't even complain. Does anybody have an idea, why this is legal in java. displayDataMap.put("dateInterval", getDateInterval());; Edit: The reason Eclipse wasn't complaining was because in preference->java->compiler->Errors/Warning I had the Empty statement: as ignore. A: The compiler uses semicolon to denote an 'end of statement'. Having two consecutively ends the statement prior to the first, and then creates a second empty statement. Really, you could even do this: displayDataMap.put("dateInterval", getDateInterval());;;;;;;;;;;;;;; A: Here's a practical example in C: #ifndef NDEBUG #define Dprintf printf #else #define Dprintf(X) #endif if(some_test) Dprintf("It's true!"); else Dprintf("It's false."); If NDEBUG is defined, the compiler will see: if(some_test) ; else ; This can be useful in some cases. Since Java is heavily inspired by C/C++, it's something they kept, even though it is not useful and there is no preprocessor. You can, if you want, run the C preprocessor cpp on your code to do this kind of behaviour. Some languages may say it's an error instead, it's up to them to choose. A: ; represents the empty statement or you can say, it's represent termination line of a any statement in Java, even if you put more than one it's valid in Java. Compiler will not gives you any error because this is valid. even the below statement is also valid: System.out.println("HI");;;;;;;; A: It's an empty statement and is valid. As pointed out by jwodder, to be more precise the empty statement is the lack of statement between the two semicolon and could be represented by two consecutive semicolons or by semicolons separated by white space (that is including new lines). IDE like Eclipse will warn you about this. If you check the picture below, I've inserted a double semicolon on line 236. The red lines were added by me to focus the attention, but Eclipse give many visual cues: * *a jagged yellow line under the semicolons. *a light bulb with a warning sign on the left margin of line 236, by hovering on that line, it will popup a small message saying "Unnecessary semicolon". *on the bar containing the directories and packages, the warning sign is shown again. It is shown for every package or source folder, which contains at least one warning. *on the package explorer and on the navigator file icon the same light bulb icon will be shown (not in this screenshot). A: ; means end of statement. for ;; , the second ; will imply that the statement consists of nothing. A: It's an empty statement, it's the same as if you did this: int x = 0; ; No problems there! A: Compiler wont complain even when you just create an empty file with .java extension. Its an empty compilation unit and its valid. Same way a semicolon is an empty statement which is valid.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Latest technologies in java I'm have an experience of 2+ in java development. I worked on corejava,toplink(db framework),sql. I have knowledge on servlets,jsp and struts. I would like to move to another company. What are the latest emerging technologies in java?? A: A master is a master not because of his knowledge of the additional elements in his field; but, because of his skill in handling the core fundamentals. All additional elements in a field stem from the fundamentals. A: I am getting into java as well. From what I have gleaned you should be well versed with the Spring Framework and Hibernate or other comparable tools (Google for alternatives). They aren't the "latest", but people will expect you to know them well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: When to use enums? I'm currently reading about enums in C. I understand how they work, but can't figure out situations where they could be useful. Can you give me some simple examples where the usage of enums is appropriate? A: They're often used to group related values together: enum errorcode { EC_OK = 0, EC_NOMEMORY, EC_DISKSPACE, EC_CONNECTIONBROKE, EC_KEYBOARD, EC_PBCK }; A: Enums are just a way to declare constant values with more maintainability. The benefits include: * *Compilers can automatically assign values when they are opaque. *They mitigate programmers doing bad things like int monday = SUNDAY + 1. *They make it easy to declare all of your related constants in a single spot. Use them when you have a finite list of distinct, related values, as in the suits of a deck of cards. Avoid them when you have an effectively unbounded list or a list that could often change, as in the set of all car manufacturers. A: Sometime you want to express something that is finite and discrete. An example from the GNU C Programming tutorial are compass directions. enum compass_direction { north, east, south, west }; Another example, where the ability of enums to correspond to integers comes in handy, could be status codes. Usually you start the OK code with 0, so it can be used in if constructs. A: The concept behind an enum is also sometimes called an "enumerated type". That is to say, it's a type all of whose possible values are named and listed as part of the definition of the type. C actually diverts from that a bit, since if a and b are values in an enum, then a|b is also a valid value of that type, regardless of whether it's listed and named or not. But you don't have to use that fact, you can use an enum just as an enumerated type. They're appropriate whenever you want a variable whose possible values each represent one of a fixed list of things. They're also sometimes appropriate when you want to define a bunch of related compile-time constants, especially since in C (unlike C++), a const int is not a compile-time constant. I think that their most useful properties are: 1) You can concisely define a set of distinct constants where you don't really care what the values are as long as they're different. typedef enum { red, green, blue } color; is better than: #define red 0 #define green 1 #define blue 2 2) A programmer, on seeing a parameter / return value / variable of type color, knows what values are legal and what they mean (or anyway knows how to look that up). Better than making it an int but documenting "this parameter must be one of the color values defined in some header or other". 3) Your debugger, on seeing a variable of type color, may be able to do a reverse lookup, and give red as the value. Better than you looking that up yourself in the source. 4) The compiler, on seeing a switch of an expression of type color, might warn you if there's no default and any of the enumerated values is missing from the list of cases. That helps avoid errors when you're doing something different for each value of the enum. A: Enums are primarily used because they are easier to read than integer numbers to programmers. For example, you can create an enum that represents dayy in a week. enum DAY {Monday, Tuesday....} Monday is equivalent to integer 0, Tuesday = Monday + 1 etc. So instead of integers thta represent each week day, you can use a new type DAY to represent this same concept. It is easier to read for the programmer, but it means the same to the compiler.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Maven project worked before "clean install". Why? I have two maven projects and both are working fine independently. I am able to create a jar file and run it from console as well as from eclipse. I copied over some classes from the second project into the first and made a few changes so that it runs as a single project with features from both. I have two pom files, so I combined them into a single pom file. The thing is that I am able to run it from eclipse fine and able to get the output I was hoping for. But I am not able to run it after executing the jar file created from "mvn package". I am using shade maven plugin. If I use maven build.. with clean install as goal, it again showing errors. My question is this, why this discrepancy? A: We would need more information to correctly diagnose the issue. One thing to look at is to ensure that any changes to dependencies which are projects in Eclipse have been installed as a command line build will only look in your repo, not at your Eclipse project. A: This may happen when you have a dependency which exists as an open project in your eclipse workspace. Try closing every project except the one where you're having this problem. Does it still compile in eclipse then?
{ "language": "en", "url": "https://stackoverflow.com/questions/7571020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google Chrome swf issue with allow button Please take a look at the image am attaching, as you can note its not readable nor it is clickable am only facing this issue in google chrome an idea why is that happening ?!! * *Google Chrome 14.0.835.186 (Official Build 101821) m *OS Windows *WebKit 535.1 (branches/chromium/835@94713) *JavaScript V8 3.4.14.21 *Flash 10,3,183,10 Thanks A: Will digging into this i found the solution of my question. The container of the flash object did have a style of "border-radius" removing this solved the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Broadcast Receiver for Sent SMS Is there a Broadcast Receiver in android to listen to the SMS sent event? In my application I want to count the number of SMS sent every predefined time interval. If its not possible to listen to sent sms, can anyone share code to count SMS and for specified time for example last 30 minutes. A: Check this link....i think its not complete solution but you have some idea how to implement... http://www.anddev.org/other-coding-problems-f5/sms-mms-contentobserver-and-service-t12938.html you can implement content://sms/sent observer se.. so if any changes in this then you can get event so u can count or get action sent sms or mms....... A: You can edit your own sms with SmsManager api from google and be notified by a PendingIntent: SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage (String destinationAddress, String scAddress, String text, PendingIntent sentIntent, PendingIntent deliveryIntent) You can be notified of the delivery with the parameter: PendingIntent sentIntent But SmsManager is now deprecated :(
{ "language": "en", "url": "https://stackoverflow.com/questions/7571026", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I count the days between two dates in javascript? Possible Duplicate: How to calculate the number of days between two dates using javascript I have those dates : 27/09/2011 29/10/2011 and I'd like to return the days between those dates (in the example, should be 33 days). How can I do it on javascript (or jquery?)? A: var daysBetween = (Date.parse(DATE1) - Date.parse(DATE2)) / (24 * 3600 * 1000); A: function days_between(date1, date2) { // The number of milliseconds in one day var ONE_DAY = 1000 * 60 * 60 * 24 // Convert both dates to milliseconds var date1_ms = date1.getTime() var date2_ms = date2.getTime() // Calculate the difference in milliseconds var difference_ms = Math.abs(date1_ms - date2_ms) // Convert back to days and return return Math.round(difference_ms/ONE_DAY) } http://www.mcfedries.com/JavaScript/DaysBetween.asp A: // split the date into days, months, years array var x = "27/09/2011".split('/') var y = "29/10/2011".split('/') // create date objects using year, month, day var a = new Date(x[2],x[1],x[0]) var b = new Date(y[2],y[1],y[0]) // calculate difference between dayes var c = ( b - a ) // convert from milliseconds to days // multiply milliseconds * seconds * minutes * hours var d = c / (1000 * 60 * 60 * 24) // show what you got alert( d ) Note: I find this method safer than Date.parse() as you explicitly specify the date format being input (by splitting into year, month, day in the beginning). This is important to avoid ambiguity when 03/04/2008 could be 3rd of April, 2008 or 4th of March, 2008 depending what country your dates are coming from.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to add a dynamic images in ViewFlipper ??? I am using this code. to access the particular folder in order to get a list of images and add it into a ViewFlipper. but i have problem with this, i can't add it into the ViewFlipper.So please if any one know how to resolve this problem, i will appreciate his help . Sorry for my bad english. public ImageView[] imageView; byte[] mByte = null; public BufferedInputStream mBufferedInputStream; Bitmap[] bMap; File dir=new File("/sdcard/image folder"); System.out.println("Dir is"+dir); String[] file_name = dir.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { // TODO Auto-generated method stub if(new File(dir,name).isDirectory()) return true; return name.toLowerCase().endsWith(".jpg"); } }); for(String singleFile : file_name){ System.out.println("---------->"+dir.toString()+"/"+singleFile); try { FileInputStream mFileInputStream = new FileInputStream(dir+"/"+singleFile); mBufferedInputStream = new BufferedInputStream(mFileInputStream); mByte = new byte[mBufferedInputStream.available()+(16*1024)]; mBufferedInputStream.read(mByte); bMap = new Bitmap[file_name.length]; bMap[position] = BitmapFactory.decodeByteArray(mByte, 0, mByte.length); imageView[file_name.length] = new ImageView(this); imageView[position].setImageBitmap(bMap[position]); mViewFlipper.addView(imageView[position]); bMap[position].recycle(); position++; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } mViewFlipper.startFlipping(); mViewFlipper.setOnTouchListener(this); In the LogCat : 09-27 19:27:17.490: WARN/System.err(9910): java.lang.NullPointerException 09-27 19:27:17.490: WARN/System.err(9910): at com.android.SD_Card_Img_Reader.SD_CardImageReaderActivity.onCreate(SD_CardImageReaderActivity.java:76) 09-27 19:27:17.501: WARN/System.err(9910): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 09-27 19:27:17.501: WARN/System.err(9910): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627) 09-27 19:27:17.501: WARN/System.err(9910): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679) 09-27 19:27:17.511: WARN/System.err(9910): at android.app.ActivityThread.access$2300(ActivityThread.java:125) 09-27 19:27:17.511: WARN/System.err(9910): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033) 09-27 19:27:17.541: WARN/System.err(9910): at android.os.Handler.dispatchMessage(Handler.java:99) 09-27 19:27:17.584: WARN/System.err(9910): at android.os.Looper.loop(Looper.java:123) 09-27 19:27:17.584: WARN/System.err(9910): at android.app.ActivityThread.main(ActivityThread.java:4627) 09-27 19:27:17.584: WARN/System.err(9910): at java.lang.reflect.Method.invokeNative(Native Method) 09-27 19:27:17.584: WARN/System.err(9910): at java.lang.reflect.Method.invoke(Method.java:521) 09-27 19:27:17.584: WARN/System.err(9910): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 09-27 19:27:17.584: WARN/System.err(9910): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 09-27 19:27:17.590: WARN/System.err(9910): at dalvik.system.NativeStart.main(Native Method) 09-27 19:27:17.590: INFO/System.out(9910): ---------->/sdcard/image folder/darkred.jpg 09-27 19:27:17.590: INFO/global(9910): Default buffer size used in BufferedInputStream constructor. It would be better to be explicit if an 8k buffer is required. 09-27 19:27:17.721: DEBUG/dalvikvm(9910): GC_EXTERNAL_ALLOC freed 406 objects / 125952 bytes in 125ms 09-27 19:27:18.571: WARN/System.err(9910): java.lang.NullPointerException 09-27 19:27:18.651: WARN/System.err(9910): at com.android.SD_Card_Img_Reader.SD_CardImageReaderActivity.onCreate(SD_CardImageReaderActivity.java:76) 09-27 19:27:18.651: WARN/System.err(9910): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 09-27 19:27:18.771: WARN/System.err(9910): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627) 09-27 19:27:18.771: WARN/System.err(9910): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679) 09-27 19:27:18.771: WARN/System.err(9910): at android.app.ActivityThread.access$2300(ActivityThread.java:125) 09-27 19:27:18.771: WARN/System.err(9910): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033) 09-27 19:27:18.771: WARN/System.err(9910): at android.os.Handler.dispatchMessage(Handler.java:99) 09-27 19:27:18.771: WARN/System.err(9910): at android.os.Looper.loop(Looper.java:123) 09-27 19:27:18.771: WARN/System.err(9910): at android.app.ActivityThread.main(ActivityThread.java:4627) 09-27 19:27:18.771: WARN/System.err(9910): at java.lang.reflect.Method.invokeNative(Native Method) 09-27 19:27:18.771: WARN/System.err(9910): at java.lang.reflect.Method.invoke(Method.java:521) 09-27 19:27:18.771: WARN/System.err(9910): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 09-27 19:27:18.771: WARN/System.err(9910): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 09-27 19:27:18.771: WARN/System.err(9910): at dalvik.system.NativeStart.main(Native Method) A: ViewFlipper only allows you to have one child per view. Inside that child you can add as many images as you want. You might want to add a LinearLayout and start adding images inside of that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mahout servlets per data model I am implementing the Mahout user-based recommendation engine where the recommendations will be served via RecommenderServlet running in Tomcat. So far looks like a basic setup, but it has some extra properties: * *Recommendations will be served from 100 different data models, depending on user's context. Each data model is ~2 Mb. *There could be 1000s of concurrent users querying recommendations at a given time. One option I considered is setting up one RecommenderServlet per data model. So there will be 100 of them distributed between multiple Tomcat instances. The main question for Mahout experts: Would you recommend to set up one RecommenderServlet per data model, or there are better alternatives? A: I don't think that choice really makes a difference to the issues of performance you mention. It's more about what makes more logical sense to you. A servlet typically provides one logical service and answers one "type" of request -- for a page, or method. In theory you could have one servlet serve everything on your site but it would be ugly, design-wise. My rule of thumb would be to use different servlets for different URL paths. It's not going to change the memory requirements or performance though. Either way you're serving those requests, from that data in memory. Now, you could in fact dedicate whole instances of Tomcat to serving only a subset of those 100 models. But then you're really running different web apps, on different servers. It's no longer a question of 1 or 100 servlets, but a bigger choice of splitting up your architecture.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to run a command on file system change in Visual Studio 2010? I use a tool for validating JavaScript syntax, called JavaScriptLint (javascriptlint.com). I'd like my Visual Studio to react to my save, CTRL-S and automatically trigger a command that runs javascript lint analyzing my current file. Currently I do this using an external keycommand mapped to a key combination. But just hitting save and seeing instant output would be huge! :) A: I think you can accomplish this task by using a Visual Studio Macro and configuring to a key combination/command. The following links should help: Can I have a macro run whenever I save a file in Visual Studio 2005? Visual Studio Macros Assigning a Keyboard Shortcut to Macro in VS Cheers! A: JSLint for Visual Studio 2010
{ "language": "en", "url": "https://stackoverflow.com/questions/7571042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What Actually this line of code `ptr=(char *)&a;` does? I have the code : #include<stdio.h> void main(){ int i; float a=5.2; char *ptr; ptr=(char *)&a; for(i=0;i<=3;i++) printf("%d ",*ptr++); } I got the output as 102 102 -90 64. I couldn't predict how it came, I get confused with this line ptr=(char *)&a;. Can anyone explain me what it does? And as like other variables the code *ptr++ increments? Or there is any other rule for pointers with this case. I'm a novice in C, so explain the answer in simple terms. Thanks in advance. A: This is called a cast. In C, a cast lets you convert or reinterpret a value from one type to another. When you take the address of the float, you get a float*; casting that to a char* gives you a pointer referring to the same location in memory, but pretending that what lives there is char data rather than float data. sizeof(float) is 4, so printing four bytes starting from that location gives you the bytes that make up the float, according to IEEE-754 single-precision format. Some of the bytes have their high bits set, so when interpreted as signed char and then converted to int for display, they appear as negative values on account of their two's-complement representation. The expression *ptr++ is equivalent to *(ptr++), which first increments ptr then dereferences its previous value; you can think of it as simultaneously dereferencing and advancing ptr. A: That line casts the address of a, denoted &a, to a char*, i.e. a pointer to characters/bytes. The printf loop then prints the values of the four constituent bytes of a in decimal. (Btw., it would have been neater if the loop had been for (i=0; i<sizeof(a); i++) printf("%d ", ptr[i]); ) A: The line ptr=(char *)&a; casts the address of the float variable to a pointer of type char. Thus you are now interpreting the 4 bytes of which the float consists of as single bytes, which values you print with your for loop. The statement *ptr++ post-increments the pointer after reading its value, which means, you read the value pointed to (the single bytes of the float) and then advance the pointer by the offset of one byte. A: &a gets the address of a, that is, it yields a pointer of type float *. This pointer of type float * is then cast to a pointer of type char *. Because sizeof(char) == 1, a can now be seen through ptr as a sequence of bytes. This is useful when you want to abstract away the type of a variable and treat it as a finite sequence of bytes, especially applicable in serialisation and hashing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Java - Properties: Add new keys to properties file in run time? Is it possible to create a new properties file and add keys and values in run time? I want to add new keys to properties file depending on user input while installing my application. I checked out Java Properties class but it seem it can set values to existing keys but can not add new keys to properties file. A: You can add new properties just by calling setProperty with a key which doesn't currently exist. That will only do it in memory though - you'll have to call store again to reflect the changes back to a file: Properties prop = new Properties(); prop.load(...); // FileInputStream or whatever prop.setProperty("newKey", "newValue"); prop.store(...); // FileOutputStream or whatever
{ "language": "en", "url": "https://stackoverflow.com/questions/7571045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Git - compare local and remote without fetching first? I've searched around and found no answer to this question. I have an app running on Heroku. From my local machine I typically implement and just: git add . git commit -m "whatever change, I know I can add and commit at the same time..." git push <the-heroku-repo> Then it goes up and the master branch in the Heroku app is updated. So far so good. Now. I want to have another machine that will automatically make a pull from the Heroku repo and update itself. So i do that with: git clone <the-heroku-repo> That gets me the app and I can see the git config with this: core.repositoryformatversion=0 core.filemode=true core.bare=false core.logallrefupdates=true remote.origin.fetch=+refs/heads/*:refs/remotes/origin/* remote.origin.url=git@heroku.com:theapp.git branch.master.remote=origin branch.master.merge=refs/heads/master To update this new repo I can do just a pull: git pull origin Or I could fetch and merge: git fetch origin git merge origin/master MY QUESTION Between the above fetch and merge I can check what are the changes by doing: git log -p master..origin/master Is there a way to find the differences between the local master branch and the latest version in the remote Heroku repo without fetching before? Just compare the local and remote and see the changes. I just can't find the proper way. Thanks. A: Although you can get some summary information about the branches in the origin repository using: git remote show origin ... you do need to fetch the branches from origin into your repository somehow in order to compare them. This is what git fetch does. When you run git fetch origin, it will by default only update the so-called "remote-tracking branches" such as origin/master. These just store where the corresponding branch was at in origin the last time you fetched. All your local branches that you've been working on are unaffected by the git fetch. So, it's safe to do: git fetch origin git log -p master..origin/master ... and then if you're happy with that, you can merge from or rebase onto origin/master. I would encourage you not to worry about the resources (either disk space or bandwidth) involved in the git fetch origin command. git efficiently sends just the objects that are necessary to complete the remote-tracking branches that are being updated, and unless you have unusually large files stored with your source code, this shouldn't make much of a difference. In addition, it's frequently useful to have the complete history of the branches from the other repository available even if you don't plan to use them, for example so you can examine that development history.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: asp.net assembly redirection windows server 2008 Can anyone tell me where the Asp.net Assembly Configuration is so I can set the assembly bindings for the GAC on Server 2008? A: You can put the assembly redirect in the machine.config or web.config to have it apply globally. see c:\Windows\Microsoft.NET\Framework\v4.0.30319\Config
{ "language": "en", "url": "https://stackoverflow.com/questions/7571049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trim node inside views I have a view (Drupal 7), filled with nodes. And I got a trimmer on 200 chars on the body. But as it happens, somethimes a word is cut in half. How do I get to trimm Drupal on words in stead of chars? A: Inside the Rewrite results field options and underneath the checkbox entitled Trim this field to a maximum length make sure the checkbox entitled Trim only on a word boundary is selected.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Realtime Socket.IO scaling problem - python I'm trying to do something like the stream on Facebook, with socket.io 0.6 and tornadio. Each user has is own comet channel/group in his wall. I'm sending a comet message to the wall of all my friends (even if they aren't online). The problem is about scaling: what if i have 1 million friends? It would take a long time to write in all walls. Is there any solution more efficient to do this using comet? A: This is a difficult problem in the social space. There is a trade-off between two approaches: * *push: When a user produces an event (e.g. a status update), you push that status update out to the stream of each of the user's friends. When a user loads his or her stream, you only have to read a record from a single place. *pull: When a user produces an event, you write that even to the user's data record. When a user loads his stream, you poll the data record of each of his friends, aggregating the results on the fly. The push method is good when loading a stream happens much more often than user updates and when the "fanout" of users (e.g. the maximum number of followers a user has) is low. The pull method is good when a user loading his stream is rare, or if the the number of users a user can follow is low. I co-authored a paper on how to do this efficiently. Basically, we used a hybrid method, determining when to push or pull based on user statistics. For simplicity, I would recommend you implement the pull model. Cache the results of the aggregation and only refresh a user's feed after the cache entry is stale for a certain period of time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SDL Moving my character I've a problem with my source code. basically, I tried to move a sprite character in 2D map here's my warrior class: class Warrior { private : int HP, SP; int xPos, yPos; int status; char *name; SDL_Surface *warrior; Map m; public : int atk, def, matk, mdef; Warrior(int, int, int, Map); int getHP(); bool isAlive(); int getSP(); int getX(); int getY(); void setX(int); void setY(int); void changeStatus(int); void drawChar(); void move(); void deleteChar(); }; //constructor buat warrior Warrior::Warrior(int pos, int x, int y, Map _m) { HP = 250; SP = 50; atk = 75; def = 20; matk = 15; mdef = 5; warrior = NULL; m = _m; status = pos; xPos = x; yPos = y; } bool Warrior::isAlive() { if (HP > 0) return true; return false; } //buat ngilangin character warrior-nya... //timpa ama sprite rumput di coord char-nya void Warrior::deleteChar() { char path = '0'; m.drawTile(xPos, yPos, path); m.drawTile(xPos, yPos+20, path); SDL_Flip (SDL_SCREEN); } //buat gambar character void Warrior::drawChar () { switch (status) { case WARRIOR_LEFT : warrior = IMG_Load ("Sprites/Warrior/WARRIOR_LEFT.png"); applySurface (xPos, yPos, warrior, SDL_SCREEN); break; case WARRIOR_RIGHT : warrior = IMG_Load ("Sprites/Warrior/WARRIOR_RIGHT.png"); applySurface (xPos, yPos, warrior, SDL_SCREEN); break; case WARRIOR_UP : warrior = IMG_Load ("Sprites/Warrior/WARRIOR_UP.png"); applySurface (xPos, yPos, warrior, SDL_SCREEN); break; case WARRIOR_DOWN : warrior = IMG_Load ("Sprites/Warrior/WARRIOR_DOWN.png"); applySurface (xPos, yPos, warrior, SDL_SCREEN); break; case WARRIOR_MOVE_LEFT : warrior = IMG_Load ("Sprites/Warrior/WARRIOR_MOVE_LEFT.png"); applySurface (xPos, yPos, warrior, SDL_SCREEN); SDL_Flip(SDL_SCREEN); SDL_Delay (100); deleteChar(); status = WARRIOR_LEFT; warrior = IMG_Load ("Sprites/Warrior/WARRIOR_LEFT.png"); applySurface (xPos, yPos, warrior, SDL_SCREEN); break; case WARRIOR_MOVE_RIGHT : warrior = IMG_Load ("Sprites/Warrior/WARRIOR_MOVE_RIGHT.png"); applySurface (xPos, yPos, warrior, SDL_SCREEN); SDL_Flip(SDL_SCREEN); SDL_Delay (100); deleteChar(); status = WARRIOR_RIGHT; warrior = IMG_Load ("Sprites/Warrior/WARRIOR_RIGHT.png"); applySurface (xPos, yPos, warrior, SDL_SCREEN); break; case WARRIOR_MOVE_UP : warrior = IMG_Load ("Sprites/Warrior/WARRIOR_MOVE_UP.png"); applySurface (xPos, yPos, warrior, SDL_SCREEN); SDL_Flip(SDL_SCREEN); SDL_Delay (100); deleteChar(); status = WARRIOR_UP; warrior = IMG_Load ("Sprites/Warrior/WARRIOR_UP.png"); applySurface (xPos, yPos, warrior, SDL_SCREEN); break; case WARRIOR_MOVE_DOWN : warrior = IMG_Load ("Sprites/Warrior/WARRIOR_MOVE_DOWN.png"); applySurface (xPos, yPos, warrior, SDL_SCREEN); SDL_Flip(SDL_SCREEN); SDL_Delay (100); deleteChar(); status = WARRIOR_DOWN; warrior = IMG_Load ("Sprites/Warrior/WARRIOR_DOWN.png"); applySurface (xPos, yPos, warrior, SDL_SCREEN); break; } SDL_Flip(SDL_SCREEN); } int Warrior::getX() { return xPos; } int Warrior::getY() { return yPos; } void Warrior::setX(int x) { xPos = x; } void Warrior::setY(int y) { yPos = y; } int Warrior::getHP() { return HP; } int Warrior::getSP() { return SP; } void Warrior::changeStatus(int _status) { status = _status; } //jalannya karakter void Warrior::move() { if (event.type == SDL_KEYDOWN) { //hilangkan char-nya dolo deleteChar(); switch (event.key.keysym.sym) { case SDLK_UP : // nge-cek collision dari coord peta-nya (Map m) if (m.map[m.getLevel()][(yPos/20)-1][xPos] == '0') { yPos -= 20; status = WARRIOR_MOVE_UP; } break; case SDLK_DOWN : if (m.map[m.getLevel()][(yPos/20)+1][xPos/20] == '0') { yPos += 20; status = WARRIOR_MOVE_DOWN; } case SDLK_LEFT : if (m.map[m.getLevel()][yPos/20][(xPos/20)-1] == '0') { xPos -= 20; status = WARRIOR_MOVE_LEFT; } case SDLK_RIGHT : if (m.map[m.getLevel()][yPos/20][(xPos/20)+1] == '0') { xPos += 20; status = WARRIOR_MOVE_RIGHT; } } //bru di-gambar drawChar(); SDL_Delay (100); } } The problem is I can't move it, and the program wasn't responding at all... I've checked all the sprite images and it works fine. A: * *Post your main loop. *Add prints in various places in your code, so you can see where it hangs. *Don't call IMG_Load every frame. Load your images at start-up. *SDL_Surfaces loaded with IMG_Load have to be freed with SDL_FreeSurface when no longer needed. Especially if you are loading a lot of them. *You don't have to call SDL_Flip every time you change something. Just make sure you call it at end of every frame. A: * *You can add your Sprite image to a map like textureMap(stringID, pTexture) before enter play state: SDL_Surface* pTempSurface = IMG_Load(fileName.c_str()); SDL_Texture* pTexture = SDL_CreateTextureFromSurface(pRenderer, pTempSurface); SDL_FreeSurface(pTempSurface); m_textureMap[id] = pTexture; *When draw the hero, you can use the stringID to get the texture: SDL_RenderCopyEx(pRenderer, m_textureMap[stringID], &srcRect, &destRect, 0, 0, flip); *For you do not post your main loop, you may should catch input in main loop like: SDL_Event event; if (SDL_PollEvent(&event)) { switch (event.type) {....} } Make sure you get the input event first and then check the draw position every frame.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to create Stencil buffer with texture (Image) in OpenGL-ES 2.0 Can I have Stencil prepared with a texture (Image) in OpenGL 2.0 So that some part of the Image will be transparent and as a result it will be transfered as is to Stencil buffer and then will use this use this stencil buffer for further drawing. EDIT by datenwolf to account for OPs question update in a answer: By @InfiniteLoop: @datenwolf thanks a lot for ur reply but no success :( here is my code - (void)render { [EAGLContext setCurrentContext:context]; glBindFramebuffer(GL_FRAMEBUFFER, defaultFramebuffer); glUseProgram(program); glClearColor(0, 104.0/255.0, 55.0/255.0, 1.0); glViewport(0, 0, backingWidth, backingHeight); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); // Set the stencil clear value glClearStencil ( 0x1 ); // Set the depth clear value glClearDepthf( 0.75f ); //////// //// GLfloat threshold = 0.5f;//half transparency /* the order in which orthogonal OpenGL state is set doesn't matter */ glEnable(GL_STENCIL_TEST); glEnable(GL_ALPHA_TEST); /* don't write to color or depth buffer */ glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); glDepthMask(GL_FALSE); glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); /* first set alpha test so that fragments greater than the threshold will pass thus will set nonzero bits masked by 1 in stencil */ glStencilFunc(GL_ALWAYS, 1, 1);//set one glAlphaFunc(GL_GREATER, threshold);//greater than half transparency glVertexAttribPointer(positionLoc, 3, GL_FLOAT, GL_FALSE, 0, fullVertices); glVertexAttribPointer(colorLoc, 4, GL_FLOAT, GL_FALSE, 0, colorVertices); glVertexAttribPointer(textureLoc, 2, GL_FLOAT, GL_FALSE, 0, textureVertices); [self drawTexture:texture2DMaskImage]; /* second pass of the fragments less or equal than the threshold will pass thus will set zero bits masked by 1 in stencil */ glStencilFunc(GL_ALWAYS, 0, 1);//set zero glAlphaFunc(GL_LEQUAL, threshold);//Less than Half transparency glVertexAttribPointer(positionLoc, 3, GL_FLOAT, GL_FALSE, 0, fullVertices); glVertexAttribPointer(colorLoc, 4, GL_FLOAT, GL_FALSE, 0, colorVertices); glVertexAttribPointer(textureLoc, 2, GL_FLOAT, GL_FALSE, 0, textureVertices); [self drawTexture:texture2DMaskImage]; // till here as suggested by u after this I have added to draw // the next Image which will use the created Stencil glDepthMask(GL_TRUE); glDisable(GL_ALPHA_TEST); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); // glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);//stop further write to stencil buffer glStencilFunc(GL_EQUAL, 0, 1);//pass if 0 glVertexAttribPointer(positionLoc, 3, GL_FLOAT, GL_FALSE, 0, fullVertices); glVertexAttribPointer(colorLoc, 4, GL_FLOAT, GL_FALSE, 0, colorVertices); glVertexAttribPointer(textureLoc, 2, GL_FLOAT, GL_FALSE, 0, textureVertices); [self drawTexture:texture2D]; //// /////// // Validate program before drawing. This is a good check, // but only really necessary in a debug build. // DEBUG macro must be defined in your debug configurations // if that's not already the case. #if defined(DEBUG) if (![self validateProgram:program]) { NSLog(@"Failed to validate program: %d", program); return; } #endif // draw [context presentRenderbuffer:GL_RENDERBUFFER];//Present } - (void) drawTexture:(Texture2D*)texture { // handle viewing matrices GLfloat proj[16], modelview[16], modelviewProj[16]; // setup projection matrix (orthographic) mat4f_LoadOrtho(-1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, proj); // glUniformMatrix4fv(uniforms[UNIFORM_PROJECTION], 1, 0, proj); // setup modelview matrix (rotate around z) mat4f_LoadIdentity(modelview); mat4f_LoadZRotation(0.0, modelview); mat4f_LoadTranslation3D(0.0, 0.0, 0.0, modelview); // projection matrix * modelview matrix mat4f_MultiplyMat4f(proj, modelview, modelviewProj); glUniformMatrix4fv(_modelViewUniform, 1, 0, modelviewProj); // update uniform values glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture.name); glUniform1i(_textureUniform, 0); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, cubeIndices); } please shed some light I am in desperate need :( thanks once again. A: Yes, you can use alpha testing (glEnable(GL_ALPHA_TEST); glAlphaFunc(COMPARISION, VALUE);) to discard fragments; discarded fragments will not be stencil tested, so you can use the passing fragments to build the stencil mask. EDIT code example /* the order in which orthogonal OpenGL state is set doesn't matter */ glEnable(GL_STENCIL_TEST); glEnable(GL_ALPHA_TEST); /* don't write to color or depth buffer */ glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); glDepthMask(GL_FALSE); glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); /* first set alpha test so that fragments greater than the threshold will pass thus will set nonzero bits masked by 1 in stencil */ glStencilFunc(GL_ALWAYS, 1, 1); glAlphaFunc(GL_GREATER, threshold); draw_textured_primitive(); /* second pass of the fragments less or equal than the threshold will pass thus will set zero bits masked by 1 in stencil */ glStencilFunc(GL_ALWAYS, 0, 1); glAlphaFunc(GL_LEQUAL, threshold); draw_textured_primitive(); Don't forget to revert OpenGL state for drawing afterwards. EDIT to account for updated question: Since you're actually using iOS, thus OpenGL-ES 2.0 things get a bit different. There's no alpha test in OpenGL-ES2. Instead you're expected to discard the fragment in the fragment shader, if it's below/above a chosen threshold, by using the discard keyword/statement. A: Finally I have managed to do it using conditional passing of colors using discard keyword in shader. I also used 2 textures in same shader and combined them accordingly. Thanks all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: What cms/ecommerce cart is store.barackobama.com run on? What shopping cart / ecommerce cms does http://store.barackobama.com use? I'm curious as to see what shopping cart his team uses. P.S. I'm not trying to advocate any affiliation or allegiance; as i feel political opinions are off topic. A: http://store.barackobama.com uses "Magento"
{ "language": "en", "url": "https://stackoverflow.com/questions/7571078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android: The AlertDialog is invisible when the Activity back to foreground This question is related to The AlertDialog is invisible when the Activity back to foreground post. I have the same problem. The previous post is old, and have no answer. Any suggestions how to solve that problem ? Thanks... A: For some reason, Dialogs' states must be handled by the developer. Simply keep a reference to the dialog showing For example Dialog showingDialog=null; Now in onResume() if(showingdialog!=null) //show the dialog and maybe resume some state A: Have you tried to re-display the AlertDialog when in the activities onResume(). Using Google developers example you would be able to create an instance of this dialog and just recall it. http://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog Hope that helps. A: Also we all create Dialogs on the fly whenever we need them, we should not. Android way is (by the book) to override an onCreateDialog(int) and showDialog(int) in our activities so that our dialogs can be managed by the activity lifecycle. Another way to do so is to use myDialog.setOwnerActivity(MyActivity.this) to tell the dialog it is managed by the activity.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: VisualStudio Multi Item Reports with multiple repeated subreports I am working on a C# project in VisualStudio 2010 and am trying to generate a more than simple report with multiple datasources (lists of business objects). I'm not using crystal reports. I have an inventory of items with data about sales for each item. What I would like to do is to have each item number displayed in a header of sorts for that specific item. Underneath each item I will have two separate subreports made of tables of information related to that specific item. I was able to do this for a single item, but I do not know how to get the format to repeat for each of my top level business objects (the items). I have not been able to find any tutorials or other information as to how to accomplish this. Any help would be greatly appreciated. Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CSS border radius will contain inner elements unless position is added I have noticed a problem with CSS3 rounded corners. They contain inner elements perfectly but when the container has a position:relative applied to it they no longer contain elements. I have set up 2 fiddles to explain. This has the container set to position:relative http://jsfiddle.net/abqHE/12/ This one isn't. http://jsfiddle.net/abqHE/11/ You can see that we have a rounded container only when position is not applied. The problem is that we need to use positioning. Any ideas how to fix this. Marvellous
{ "language": "en", "url": "https://stackoverflow.com/questions/7571087", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .htaccess issue, existing .php files and search.php I'm new to playing with .htaccess for nicely formatted urls and I'm just not sure I'm doing it right. My current .htaccess file looks like this: RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^search/(.*) search.php?query=$1 [L] RewriteRule !\.(gif|jpg|ico|css|js|txt|xml|png|swf)$ index.php What I want is for mysite.com/home/56/page-title to go to index.php where I filter out the number and load the correct index page, which works fine. Before that, I want to check if the url is pointing at search.php, and if so redirect to mysite.com/search/the-search-term, this also works fine. What isn't working is if I try to visit a specific .php file say mysite.com/control_panel.php - it just takes me to index.php, but I thought that the following line stopped that from happening? RewriteCond %{REQUEST_FILENAME} !-f If someone could explain it to me that would be great :) Thanks! A: 1. Order of rules matters 2. RewriteCond directives will only be applied to the ONE RewriteRule that follows it. If you need to apply the same conditions to multiple rules you have to write them multiple times or change the rewrite processing logic (multiple approaches available). Try this one: RewriteEngine On RewriteRule ^search/(.*) search.php?query=$1 [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule !\.(gif|jpg|ico|css|js|txt|xml|png|swf)$ index.php [L]
{ "language": "en", "url": "https://stackoverflow.com/questions/7571093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Div won't fill size of parent container I have a problem in which I am making a website which will have a main content section and a "Updates" bar on the right side. Here is the link. http://bebiafricanhairbraiding.com/ You should be able to get the code from the website itself but if you need the code I can post it here. Thanks. A: Is it really important that the div's are the same height, or that the background is the same length? I guess the latter. Instead of trying to get the div's to be the same height (which won't work), create two positioned div's and set the background on their parent. The rounded corners at the bottom should be done in a separate footer element. So like this: +-----+-----+ | a | b | | +-----+ | | +-----------+ | c | +-----------+ a is your content column, b is your sidebar. Both are (together) contained in a parent div, which has a background. c is the footer with rounded corners. See also http://www.alistapart.com/articles/fauxcolumns/. I would also really recommend to use a css framework like http://twitter.github.com/bootstrap/. This makes it a lot easier to make grids, nice typography, etc. A: #content has height:100% and #update has height:250px Set the updates height #updates {height:100%}
{ "language": "en", "url": "https://stackoverflow.com/questions/7571095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MySQL JOIN based on dynamic LIKE statement between multiple tables I have a table called faq. This table consists from fields faq_id,faq_subject. I have another table called article which consists of article_id,ticket_id,a_body and which stores articles in a specific ticket. Naturally there is also a table "ticket" with fields ticket_id,ticket_number. I want to retrieve a result table in format: ticket_number,faq_id,faq_subject. In order to do this I need to search for faq_id in the article.a_body field using %LIKE% statement. My question is, how can I do this dynamically such that I return with SQL one result table, which is in format ticket_number,faq_id,faq_subject. I tried multiple configurations of UNION ALL, LEFT JOIN, LEFT OUTER JOIN statements, but they all return either too many rows, or have different problems. Is this even possible with MySQL, and is it possible to write an SQL statement which includes @variables and can take care of this? A: First off, that kind of a design is problematic. You have certain data embedded within another column, which is going to cause logic as well as performance problems (since you can't index the a_body in such a way that it will help the JOIN). If this is a one-time thing then that's one issue, but otherwise you're going to have problems with this design. Second, consider this example: You're searching for faq_id #123. You have an article that includes faq_id 4123. You're going to end up with a false match there. You can embed the faq_id values in the text with some sort of mark-up (for example, [faq_id:123]), but at that point you might as well be saving them off in another table as well. The following query should work (I think that MySQL supports CAST, if not then you might need to adjust that). SELECT T.ticket_number, F.faq_id, F.faq_subject FROM Articles A INNER JOIN FAQs F ON A.a_body LIKE CONCAT('%', F.faq_id, '%') INNER JOIN Tickets T ON T.ticket_id = A.ticket_id EDIT: Corrected to use CONCAT A: SELECT DISTINCT t.ticket_number, f.faq_id, f.faq_subject FROM faq.f INNER JOIN article a ON (a.a_body RLIKE CONCAT('faq_id: ',faq_id)) INNER JOIN ticket t ON (t.ticket_id = a.ticket_id) WHERE somecriteria
{ "language": "en", "url": "https://stackoverflow.com/questions/7571098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IOS: random paging scrollview I have this code for a scrollView (with paging enabled) - (IBAction) random{ CGRect frame = scrollView.frame; frame.origin.x = frame.size.width * (arc4random() % (numberOfPage - 1)); frame.origin.y = 0; [scrollView scrollRectToVisible:frame animated:YES];} It make a random paging scroll and it's ok, but it is very slow. Can I have a fast scrolling as a slot machine? A: I'm not sure you could get it to look like slot machine (you'd probably need some motion blur to get that kind of effect), but you could try putting your scrollRectToVisible: in an animation block to change the duration of the animation: - (IBAction) random { CGRect frame = scrollView.frame; frame.origin.x = frame.size.width * (arc4random() % (numberOfPage - 1)); frame.origin.y = 0; [UIView animateWithDuration: <your duration> animations:^(void) { [scrollView scrollRectToVisible:frame animated: NO]; }]; } Don't forget the animated:NO, otherwise it'll override your duration
{ "language": "en", "url": "https://stackoverflow.com/questions/7571099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to combine flags using RewriteCond? I am using ISAPI-Rewrite on IIS7. How can we combine [NC] and [OR] in a RewriteCond ? [NC,OR] ? What is the simple way to match domains with and without "www." ? Here is a draft : RewriteCond %{HTTP_HOST} ^old-one.com$ [NC,OR] RewriteCond %{HTTP_HOST} ^www.old-one.com$ [NC,OR] RewriteCond %{HTTP_HOST} ^old-two.com$ [NC,OR] RewriteCond %{HTTP_HOST} ^www.old-two.com$ [NC] RewriteRule ^(.*)$ http://www.new-website.com/$1 [QSA,L,R=301] A: Yes, [NC,OR] is the way of combining those two flags. To combine multiple similar conditions into one, try this one: RewriteCond %{HTTP_HOST} ^(old-one\.com|www\.old-one\.com|old-two\.com|www\.old-two\.com)$ [NC] RewriteRule .* http://www.new-website.com%{REQUEST_URI} [L,R=301] P.S. Since you are on IIS 7, why not use their native rewriting engine (URL Rewrite module) -- yes, it has different syntax (not .Apache's .htaccess, but standard web.config XML file) but does work fine (no performance issues here on my servers).
{ "language": "en", "url": "https://stackoverflow.com/questions/7571104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Count messages in an msmq sub-queue Is there any way (C# or native) of counting the messages in a message queue (sub queue). Using a queue name of "DIRECT=OS:slc11555001\private$\file-queue;retry" I want to know how many messages are in the sub queue. At the moment I can see using the management console that there are in fact messages in that queue. If the OS can do it, so should I. MQMgmtGetInfo returns 0xc00e0020 (which is not a documented error code). I am therefore confused. I am using code from here: http://functionalflow.co.uk/blog/2008/08/27/counting-the-number-of-messages-in-a-message-queue-in/ A: The error is as follows (from http://support.microsoft.com/kb/304287): MQ_ERROR_UNSUPPORTED_FORMATNAME_OPERATION (0xC00E0020). MQMgmtGetInfo won't understand the subqueue format name. The retry subqueue only really exists as a logical division of private$\file-queue queue. You can call a count on the file-queue but not subqueues within it. Cheers John A: From the MSDN page on subqueues: Subqueues are created implicitly, so only the following APIs can be used with subqueues: MQOpenQueue, MQCloseQueue, MQCreateCursor, MQReceiveMessage, MQReceiveMessageByLookupId, MQHandleToFormatName, MQMoveMessage, and MQPathNameToFormatName. Calling any of the other Message Queuing APIs returns an error
{ "language": "en", "url": "https://stackoverflow.com/questions/7571106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how this code work ?? and what is the right code This is my current code that doesn't seem to work correctly. echo date("h:i", 1*60*60) ; /* 1*60*60 mean 1 hours right */ The result is 03:00 when it should be 01:00. Where is this going wrong? i want to do this 1- employee come in time admin select it 2- employee come - leave saved in mysql as timestamp Now I'm trying to make admin see how many hours user late mean user date time default late user1 11-09-2011 09:10 09:00 10 min user1 12-09-2011 08:00 09:00 -60 min A: If you output just date("Y-m-d H:i:s",0) you should see that it's not 1970-01-01 00:00:00 as it should be. It's because date is affected by your local timezone. For example I'm in GMT +3, and date("Y-m-d H:i:s") gives me 1970-01-01 03:00:00. So the answer is you are not in GMT timezone (probably in GMT+2), and date is affected by it. UPDATE The following code outputs 1970-01-01 00:00:00, so it's definitely time zones. date_default_timezone_set('UTC'); echo date("Y-m-d H:i:s", 0); Hovewer, I can't see any mention about it in PHP's date manual. A: The problem is due to your timezone (looks like GMT+2). Date calculations in PHP are based on the configured server timezone. For example mine shows $ php -r 'echo date("h:i", 3600), PHP_EOL;' 11:00 A: The second argument in date() function must be UNIX timestamp, seconds passed from Jan 1 1970. You need to make time according to that value. A: Err, if I'm right, date()'s second param is a unix timestamp, so the seconds since 1970. You have to get time() and add 60*60 to it. echo date("h:i", time()+60*60); // get current timestamp, add one hour A: You have probably not setup time zones, which should produce a PHP warning or notice if omitted. A: It occurs to me that what SamarLover think he wants is gmdate("h:i", 1 * 60 * 60);
{ "language": "en", "url": "https://stackoverflow.com/questions/7571113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Building Sphinx Autodoc on a Google App Engine project I have a Google App Engine project that I am trying to document with Sphinx. I am trying to use the autodoc feature for many of my modules/classes/functions. My Sphinx reST markup: .. automodule:: urls :members: Urls When I run make html, I get the error: WARNING: autodoc can't import/find module 'urls', it reported error: "No module >named appengine.api", please check your spelling and sys.path The file urls imports webapp2, which I believe will in turn try to import appengine.api. I don't think its possible to provide appengine.api to my sys.path. Is there some workaround? PS. I'm not married to Sphinx. I would be open to epydoc or alternatives. A: You can download the AppEngine SDK and then set your PYTHONPATH before calling make html. For example, I downloaded the SDK and can do this: $ ls /home/jterrace/Downloads/google_appengine/google/ appengine __init__.py net pyglib storage $ PYTHONPATH="/home/jterrace/Downloads/google_appengine/google" python Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import appengine >>> import appengine.api >>> So, you would do something like this: PYTHONPATH="/home/jterrace/Downloads/google_appengine/google" make html
{ "language": "en", "url": "https://stackoverflow.com/questions/7571116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery :contains(), but to match an exact string As said in the title, I'd like to find something like :contains() but to match an exact string. In other words, it shouldn't be a partial match. For example in this case: <div id="id"> <p>John</p> <p>Johny</p> </div> $("#id:contains('John')") will match both John and Johny, while I'd like to match only John. Thanks in advance. EDIT: ES2015 one-liner solution, in case anyone looked for it: const nodes = [...document.querySelectorAll('#id > *')].filter(node => node.textContent === 'John'); console.log(nodes); /* Output console formatting */ .as-console-wrapper { top: 0; } .as-console { height: 100%; } <div id="id"> <p>John</p> <p>Johny</p> </div> A: You can use filter for this: $('#id').find('*').filter(function() { return $(this).text() === 'John'; }); Edit: Just as a performance note, if you happen to know more about the nature of what you're searching (e.g., that the nodes are immediate children of #id), it would be more efficient to use something like .children() instead of .find('*'). Here's a jsfiddle of it, if you want to see it in action: http://jsfiddle.net/Akuyq/ A: jmar777's answer helped me through this issue, but in order to avoid searching everything I started with the :contains selector and filtered its results var $results = $('#id p:contains("John")').filter(function() { return $(this).text() === 'John'; }); Heres an updated fiddle http://jsfiddle.net/Akuyq/34/ A: You could try writing a Regular Expression and searching off of that: Regular expression field validation in jQuery A: Simple way is "select element by exact match" using pseudo function. Solution Select element by exact match of its content
{ "language": "en", "url": "https://stackoverflow.com/questions/7571117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "33" }
Q: Procedure execute inside SQL Developer, but not inside a script I had a procedure that was not working. If I tried to run: "BEGIN proc_name; END;" in SQL Developer or via script I had the same error. I've fixed the procedure and now when I run that same command in SQL Developer, it's fine, but the script returns an error. When I try: ... sql = """EXEC proc_name""" con = connection.cursor() con.execute( sql ) ... I get DatabaseError: ORA-00900: invalid SQL statement, but probably is because of that: Problem with execute procedure in PL/SQL Developer and I'm not really worried about it. What is really making me curious is when I try: ... sql = """BEGIN proc_name;END;""" con = connection.cursor() con.execute( sql ) ... I get the same error that I had before fix the procedure. Do you have any idea what is going on? PS: This is a python script using cx_Oracle and I'm using Oracle 10g. A: Try using the callproc() or callfunc() method on the cursor, instead of execute(). They are not exactly Py DB API compatible, but should do the job for cx_Oracle...
{ "language": "en", "url": "https://stackoverflow.com/questions/7571130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: linux linker/loader search order This question is related to the way libraries are looked up during compilation and dynamic linking. Consider this small project: * *project * *liba * *a.hpp *a.cpp *libb * *b.hpp *b.cpp *main.cpp a.hpp: int AAA(); a.cpp: #include <b.hpp> int AAA() { return BBB(); } b.hpp: int BBB(); b.cpp: int BBB() { return 3; } main.cpp: #include "liba/a.hpp" #include "libb/b.hpp" int main() { AAA(); BBB(); } libb is compiled with: cd libb; g++ -shared -o libb.so b.cpp liba is compiled with: cd liba; g++ -I../libb/ -L../libb/ -lb -shared -o liba.so -Wl,-rpath /full/path/to/project/libb/ a.cpp and main is compiled with: g++ -Lliba -la -Wl,-rpath /full/path/to/project/liba/ main.cpp The compilation finishes without error, but when executing a.out, libb.so can't be found. ldd outputs: ldd ./a.out linux-gate.so.1 => (0xffffe000) liba.so => /full/path/to/project/liba/liba.so (0xb780a000) libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb76ba000) libm.so.6 => /lib/libm.so.6 (0xb7692000) libgcc_s.so.1 => /lib/libgcc_s.so.1 (0xb7672000) libc.so.6 => /lib/libc.so.6 (0xb750f000) libb.so => not found libb.so => /full/path/to/project/libb/libb.so (0xb750c000) /lib/ld-linux.so.2 (0xb780e000) Note, that libb.so occurs twice. One time, the dynamic linker is not able to find the library and one time it is. I assume, that in the second case it uses the rpath embedded in liba.so. Of course, there are multiple ways to fix that problem (e.g. LD_LIBRARY_PATH, embed the correct rpath when compiling main.cpp...), but I'm more interested in why the compilation of main.cpp works, while the dynamic linking doesn't. So far I assumed that the same procedure was used for searching the needed libraries. Is there something I'm missing, or some hidden magic I don't know of? :) (Tested on a SLED11 box with gcc 4.3.4.) A: There's no hidden magic but you've basically promised the compiler that you're going to tell the loader, at run-time, where to find the functions but you haven't. The BBB called from AAA knows how to get there but the BBB called from main does not.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can you get a pointer to a {System.Array} that is inside a System::Object^? Ok so I have this program that accepts files the user drags and drops onto a label box. The program is currently able to accept files that are dropped. I then save the files into a System::Object^. Inside the System::Object^ is a {System.Array} that holds the path of the files dropped onto the label box. I need to be able to access the file paths in the {System.Array} inside of the System::Object^. I am converting another program that I wrote in Visual Basic to C++; so I'm trying to keep the code of both programs pretty close to each other. I have looked at OLE for drag and drop a little bit and I'm thinking that I should be able to perform drag and drop the way I started in this code. I feel OLE is too much for what I need, I just need the file paths for the files. Any ideas on how I can get the file paths? private: System::Void lblDragHere_DragEnter(System::Object^ sender, System::Windows::Forms::DragEventArgs^ e) { if (e->Data->GetDataPresent(System::Windows::Forms::DataFormats::FileDrop)) e->Effect = System::Windows::Forms::DragDropEffects::All; else e->Effect = System::Windows::Forms::DragDropEffects::None; lblError->Visible = false; blnSaveSuccessful = false; } private: System::Void lblDragHere_DragDrop(System::Object^ sender, System::Windows::Forms::DragEventArgs^ e) { bool blnContinue = false; // Checks if the user has not set a save location for the files. if (lblSaveLocation->Text == "Current Save Location") { lblError->ForeColor = Color::Red; lblError->Text = "Please select a save location first."; lblError->Visible = true; } else { lblError->Visible = false; // Checks to see if the user actually dropped anything onto lblDragHere if (e->Data->GetDataPresent(DataFormats::FileDrop)) { System::Object ^ MyFiles; // Assign the files to the array. MyFiles = e->Data->GetData(DataFormats::FileDrop); } } } A: You should be able to directly get the data as a cli array of file names with a cast: if(e->Data->GetDataPresent(DataFormats::FileDrop)) { // Assign the files to the array. array<String^>^ myFiles = (array<String^>^)e->Data->GetData(DataFormats::FileDrop); // Do something with the files for each(String^ file in myFiles) { ... } } (You should use void instead of System::Void, it's more readable)
{ "language": "en", "url": "https://stackoverflow.com/questions/7571142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ibatis / mybatis caching within a restful webservice I am using mybatis within a Jax-RS (Jersey) restful web app. So automatically, I dont have a session or state management. Question is how can I use the caching features of mybatis ? A: Caching in MyBatis is very straight forward. Per the documentation (pg 42 of the user manual http://mybatis.googlecode.com/svn/trunk/doc/en/MyBatis-3-User-Guide.pdf) By default, there is no caching enabled, except for local session caching, which improves performance and is required to resolve circular dependencies. To enable a second level of caching, you simply need to add one line to your SQL Mapping file: MyBatis 3 - User Guide 6 June 2011 43 <cache/> Literally that’s it. The common pitfalls I had while doing this: On the mapper you add the cache element to; if you have dependent entities, make sure to explicitly flush the cache when required. Even though flushing is already done for you on insert, update, delete for the elements in the mappings you have set the cache element, sometimes you have to flush a cache due to updates/deletes/etc defined in different xml mappings. Basically, when you're thinking about your caching, you should ask yourself, "When this entity is changed, do I want it to flush a cache for an entity in a different mapping?" If the answer is yes, use cache-ref element as opposed to just cache. Ex from page 45 of the doc: <cache-ref namespace=”com.someone.application.data.SomeMapper”/>
{ "language": "en", "url": "https://stackoverflow.com/questions/7571144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Contact Picker People.Name,People.Number Error? I want to get number from contacts in my project. I use this code http://www.androidsnippets.com/select-a-contact-from-the-from-address-book-using-people-provider-and-uri What is People.Number or People.Name? Android doesnt accept it? THX for advice. A: Now instead of People.Number or People.Name, Phone.Number or Phone.Name is used.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I evaluate performances of a lockless queue? I have implemented a lockless queue using the hazard pointer methodology explained in http://www.research.ibm.com/people/m/michael/ieeetpds-2004.pdf using GCC CAS instructions for the implementation and pthread local storage for thread local structures. I'm now trying to evaluate the performance of the code I have written, in particular I'm trying to do a comparison between this implementation and the one that uses locks (pthread mutexes) to protect the queue. I'm asking this question here because I tried comparing it with the "locked" queue and I found that this has better performances with respect to the lockless implementation. The only test I tried is creating 4 thread on a 4-core x86_64 machine doing 10.000.000 random operations on the queue and it it significantly faster than the lockless version. I want to know if you can suggest me an approach to follow, i.e. what kind of operation I have to test on the queue and what kind of tool I can use to see where my lockless code is wasting its time. I also want to understand if it is possible that the performance are worse for the lockless queue just because 4 threads are not enough to see a major improvement... Thanks A: First point: lock-free programming doesn't necessarily improve speed. Lock-free programming (when done correctly) guarantees forward progress. When you use locks, it's possible for one thread to crash (e.g., go into an infinite loop) while holding a mutex. When/if that happens, no other thread waiting on that mutex can make any more progress. If that mutex is central to normal operation, you may easily have to restart the entire process before any more work can be done at all. With lock-free programming, no such circumstance can arise. Other threads can make forward progress, regardless of what happens in any one thread1. That said, yes, one of the things you hope for is often better performance -- but to see it, you'll probably need more than four threads. Somewhere in the range of dozens to hundreds of threads would give your lock-free code a much better chance of showing improved performance over a lock-based queue. To really do a lot of good, however, you not only need more threads, but more cores as well -- at least based on what I've seen so far, with four cores and well-written code, there's unlikely to be enough contention over a lock for lock-free programming to show much (if any) performance benefit. Bottom line: More threads (at least a couple dozen) will improve the chances of the lock-free queue showing a performance benefit, but with only four cores, it won't be terribly surprising if the lock-based queue still keeps up. If you add enough threads and cores, it becomes almost inevitable that the lock-free version will win. The exact number of threads and cores necessary is hard to predict, but you should be thinking in terms of dozens at a minimum. 1 At least with respect to something like a mutex. Something like a fork-bomb that just ate all the system resources might be able to deprive the other threads of enough resources to get anything done -- but some care with things like quotas can usually prevent that as well. A: The question is really to what workloads you are optimizing for. If congestion is rare, lock structures on modern OS are probably not too bad. They mainly use CAS instructions under the hood as long as they are on the fast path. Since these are quite optimized out it will be difficult to beat them with your own code. Our own implementation can only win substantially for the congested part. Just random operations on the queue (you are not too precise in your question) will probably not do this if the average queue length is much longer than the number of threads that hack on it in parallel. So you must ensure that the queue is short, perhaps by introducing a bias about the random operation that is chosen if the queue is too long or too short. Then I would also charge the system with at least twice as much threads than there are cores. This would ensure that wait times (for memory) don't play in favor of the lock version. A: The best way in my opinion is to identify hotspots in your application with locks by profiling the code.Introduce the lockless mechanism and measure the same again. As mentioned already by other posters, there may not be a significant improvement at lower scale (number of threads, application scale, number of cores) but you might see throughput improvements as you scale up the system.This is because deadlock situations have been eliminated and threads are always making forward progress. Another way of looking at an advantage with lockless schemes are that to some extent one decouples system state from application performance because there is no kernel/scheduler involvement and much of the code is userland except for CAS which is a hw instruction. With locks that are heavily contended, threads block and are scheduled once locks are obtained which basically means they are placed at the end of the run queue (for a specific prio level).Inadvertently this links the application to system state and response time for the app now depends on the run queue length. Just my 2 cents.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Yet another routing error in Rails3.1 when I tried to nest the resource This is my error: No route matches {:controller=>"accounts", :format=>nil} and this is the url: users/1/accounts/new this is code in the routes.rb file: resources :users do resources :accounts end OK, now I'm still confused about associations in Rails. The code above always uses the pluralized model name, like :users, :accounts. Now, what if the relationship between user and account is one-to-one? Shouldn't the code change to something like this? resources :users do resources :account end
{ "language": "en", "url": "https://stackoverflow.com/questions/7571150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Convert 'a list to a Set? Is it really true that OCaml doesn't have a function which converts from a list to a set? If that is the case, is it possible to make a generic function list_to_set? I've tried to make a polymorphic set without luck. A: If you don't mind a very crude approach, you can use the polymorphic hash table interface. A hash table with an element type of unit is just a set. # let set_of_list l = let res = Hashtbl.create (List.length l) in let () = List.iter (fun x -> Hashtbl.add res x ()) l in res;; val set_of_list : 'a list -> ('a, unit) Hashtbl.t = <fun> # let a = set_of_list [3;5;7];; val a : (int, unit) Hashtbl.t = <abstr> # let b = set_of_list ["yes";"no"];; val b : (string, unit) Hashtbl.t = <abstr> # Hashtbl.mem a 5;; - : bool = true # Hashtbl.mem a 6;; - : bool = false # Hashtbl.mem b "no";; - : bool = true If you just need to test membership, this might be good enough. If you wanted other set operations (like union and intersection) this isn't a very nice solution. And it's definitely not very elegant from a typing standpoint. A: Just extend the original type, as shown in http://www.ffconsultancy.com/ocaml/benefits/modules.html for the List module: module StringSet = Set.Make (* define basic type *) (struct type t = string let compare = Pervasives.compare end) module StringSet = struct (* extend type with more operations *) include StringSet let of_list l = List.fold_left (fun s e -> StringSet.add e s) StringSet.empty l end;; A: Fundamental problem: Lists can contain elements of any types. Sets (assuming you mean the Set module of the standard library), in contrary, rely on a element comparison operation to remain balanced trees. You cannot hope to convert a t list to a set if you don't have a comparison operation on t. Practical problem: the Set module of the standard library is functorized: it takes as input a module representing your element type and its comparison operation, and produces as output a module representing the set. Making this work with the simple parametric polymoprhism of lists is a bit sport. To do this, the easiest way is to wrap your set_of_list function in a functor, so that it is itself parametrized by a comparison function. module SetOfList (E : Set.OrderedType) = struct module S = Set.Make(E) let set_of_list li = List.fold_left (fun set elem -> S.add elem set) S.empty li end You can then use for example with the String module, which provides a suitable compare function. module SoL = SetOfList(String);; SoL.S.cardinal (SoL.set_of_list ["foo"; "bar"; "baz"]);; (* returns 3 *) It is also possible to use different implementation of sets which are non-functorized, such as Batteries and Extlib 'PSet' implementation (documentation). The functorized design is advised because it has better typing guarantees -- you can't mix sets of the same element type using different comparison operations. NB: of course, if you already have a given set module, instantiated form the Set.Make functor, you don't need all this; but you conversion function won't be polymorphic. For example assume I have the StringSet module defined in my code: module StringSet = Set.Make(String) Then I can write stringset_of_list easily, using StringSet.add and StringSet.empty: let stringset_of_list li = List.fold_left (fun set elem -> StringSet.add elem set) StringSet.empty li In case you're not familiar with folds, here is a direct, non tail-recursive recursive version: let rec stringset_of_list = function | [] -> StringSet.empty | hd::tl -> StringSet.add hd (stringset_of_list tl) A: Ocaml 3.12 has extensions (7,13 Explicit naming of type variables and 7,14 First-class modules) that make it possible to instantiate and pass around modules for polymorphic values. In this example, the make_set function returns a Set module for a given comparison function and the build_demo function constructs a set given a module and a list of values: let make_set (type a) compare = let module Ord = struct type t = a let compare = compare end in (module Set.Make (Ord) : Set.S with type elt = a) let build_demo (type a) set_module xs = let module S = (val set_module : Set.S with type elt = a) in let set = List.fold_right S.add xs S.empty in Printf.printf "%b\n" (S.cardinal set = List.length xs) let demo (type a) xs = build_demo (make_set compare) xs let _ = begin demo ['a', 'b', 'c']; demo [1, 2, 3]; end This doesn't fully solve the problem, though, because the compiler doesn't allow the return value to have a type that depends on the module argument: let list_to_set (type a) set_module xs = let module S = (val set_module : Set.S with type elt = a) in List.fold_right S.add xs S.empty Error: This `let module' expression has type S.t In this type, the locally bound module name S escapes its scope A possible work-around is to return a collection of functions that operate on the hidden set value: let list_to_add_mem_set (type a) set_module xs = let module S = (val set_module : Set.S with type elt = a) in let set = ref (List.fold_right S.add xs S.empty) in let add x = set := S.add x !set in let mem x = S.mem x !set in (add, mem) A: Using the core library you could do something like: let list_to_set l = List.fold l ~init:(Set.empty ~comparator:Comparator.Poly.comparator) ~f:Set.add |> Set.to_list So for example: list_to_set [4;6;3;6;3;4;3;8;2] -> [2; 3; 4; 6; 8] Or: list_to_set ["d";"g";"d";"a"] -> ["a"; "d"; "g"]
{ "language": "en", "url": "https://stackoverflow.com/questions/7571157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Custom MBean in Tomcat - cannot find javaURLContextFactory when creating InitialContext I've written a custom MBean that deploys in Tomcat 6. One of its tasks is to query a database value. I'm doing this by loading up the database resource using JNDI - the resource is defined in Tomcat's server.xml. The problem is that when I create an instance of javax.naming.InitialContext it throws a ClassNotFoundException as it can't find org.apache.naming.java.javaURLContextFactory. This class is in catalina.jar and loaded by the common classloader. The jar containing my MBean code is loaded by a shared classloader. Any ideas as to how I can get around this? To note: my MBean is loaded by a ContextListener which I've defined in the tomcat/conf/web.xml. I've also defined it in a webapp web.xml which makes no difference. I can't really move my jar so as to be loaded by the common classloader as it relies on classes loaded by the shared classloader. Thanks in advance, Will A: It looks a weird classloading or security/permission issue. Below is a workaround. The main idea: Since the ServletContextListener could call the new InitialContext() without the ClassNotFoundException get it in the listener and pass it to the constructor of the MBean object before you register the MBean. I used a simple web application and I have not modified tomcat/conf/web.xml. Resource configuration in the tomcat/conf/context.xml: <Context> ... <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="root" password="..." driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/javatest?autoReconnect=true"/> ... <Context> The web.xml resource configuration: <resource-ref> <description>DB Connection</description> <res-ref-name>jdbc/TestDB</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> The ServletContextListener which registers the MBean: import java.lang.management.ManagementFactory; import javax.management.MBeanServer; import javax.management.ObjectName; import javax.naming.Context; import javax.naming.InitialContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; @WebListener public class ContextListener implements ServletContextListener { private ObjectName objectName; public void contextInitialized(final ServletContextEvent sce) { System.out.println("---> bean context listener started"); final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); try { final InitialContext initialContext = new InitialContext(); final Context envContext = (Context) initialContext.lookup("java:/comp/env"); objectName = new ObjectName("com.example:type=Hello"); final Hello helloMbean = new Hello(envContext); mbeanServer.registerMBean(helloMbean, objectName); System.out.println("---> registerMBean ok"); } catch (final Exception e) { e.printStackTrace(); } } public void contextDestroyed(final ServletContextEvent sce) { System.out.println("---> bean context listener destroyed"); final MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); try { mbeanServer.unregisterMBean(objectName); System.out.println("---> unregisterMBean ok"); } catch (final Exception e) { e.printStackTrace(); } } } MBean interface: public interface HelloMBean { void sayHello(); } MBean implementation: import java.sql.Connection; import javax.naming.Context; import javax.sql.DataSource; public class Hello implements HelloMBean { private final Context envContext; public Hello(final Context envContext) { this.envContext = envContext; System.out.println("new hello " + envContext); } @Override public void sayHello() { System.out.println("sayHello()"); try { final DataSource ds = (DataSource) envContext.lookup("jdbc/TestDB"); final Connection conn = ds.getConnection(); System.out.println(" conn: " + conn); // more JDBC code } catch (final Exception e) { e.printStackTrace(); } } } The MBean Descriptor How To says a mbeans-descriptor.xml is required but it's worked without it well. I could connect to the HelloMBean with jconsole. Calling sayHello() through jconsole printed the following: conn: jdbc:mysql://localhost:3306/javatest?autoReconnect=true, \ UserName=root@localhost, MySQL-AB JDBC Driver Sources: * *MBeans and Tomcat: A HOWTO Guide for Managing YOUR Application *JNDI Datasource HOW-TO
{ "language": "en", "url": "https://stackoverflow.com/questions/7571160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: OAuth with DotNetOpenAuth? Ok here is my question. I understand the process of the OAuth protocol, however I have some confusion around it. I'm trying to take advantage of DotNetOpenAuth.Here is where I don't get things. Suppose a user (a new user), attempts to login to my website using Twitter. The process goes like this (feel free to correct me if I'm wrong): * *A request token is issued (if my ConsumerKey and ConsumerSecret are ok). *Then an authorization token is issued and the user is redirected to Twitter. *The user authorizes my application. And an access token is issued. *I get the current user's details and store them in the database (along with the access token). So far, so good. Now here is the confusing part. The user logs out. Then comes back and tries to authenticate with Twitter again. How do I determine his access token, If I can't get his identity before I have the access token ? I have him in the database, however I can't determine who he is, before he goes through the same steps all over again. I'm sure I'm missing something, and I'll appreciate it if you point it out. I'm aware of the IConsumerTokenManager, I tried reverse engineering the InMemoryTokenManager and see how it works, but it's still not clear. A: Ah, the joys (ahem, lack thereof) of using an authorization protocol for authentication. I dislike OAuth for logging in. Grrr... With that out of the way, let me clarify the flow a bit: * *An "unauthorized" request token is issued (if your ConsumerKey and ConsumerSecret are ok). *The user authorizes your application, and is sent back to your application *Your request token is now "authorized" and DotNetOpenAuth exchanges it for an access token. *You use the access token to get the current user's details and store them in the database. When later, an anonymous user visits your site and wants to log in, you start the flow all over. Only this time, since Twitter recognizes the user (after they log in if need be) Twitter will likely immediately redirect the user back to your application rather than ask the user to confirm the login. The request token will be authorized, you'll exchange it for an access token, and you'll use that to get the user's data. Oh! Now you see that the data matches an entry already in your database, and you welcome your visitor back.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why do I need to set up the aspNetCompatibilityEnabled twice? Could anyone please explain why when creating a WCF webservice in which you want to use HttpContext.Current.Items you need to add some code in 2 places? One in the webservice itself ([AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]) and one in the web.config file (<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />)? A colleague of mine just had all his webservice calls failing. He had the web.config setup missing and asked me why. I tried to explain, but I'm not sure if I was able to :) I think it has to do with the separation of the webservice code and the place where the webservice gets hosted. The webservice itself says that it needs that compatibility mode. It is then also needed to setup the hosting environment to say that it should run in that compatibility mode. Isn't this basically the point? He still had a question: "but, if the service uses that attribute, should it not be automaticly ?" A: The first tells WCF that aspcompat must be enabled and the second enables it. You should be able to do without the first. This forces the person configuring the WCF service to use the right config. MS designed this with the idea that the person configuring the service might be someone else that the person that made it. To answer his last question. When you add attributes to your service you're not configuring the host, you're demanding how the host should be configured. The configuring happens on the host.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571162", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MS Access to ASP.NET MVC 3 via SharePoint: using Linq to SharePoint I am trying to see if you can use Microsoft Access Services, as available in Access 2010, to synchronise data between an MVC web app, and a Microsoft Access desktop solution. If you publish the Access app backend via Access Services to a sharepoint. This works fine, and you could use Web Databases to use that, but... sadly, there are limitations to Web Databases. So, if I can get the data into SharePoint lists, and these lists will synch with the Access tables, then all I need is to access the sharepoint lists from the MVC app, hey presto, you have an MVC app that synchs with an Access desktop app. So the questions are: Will the above idea work? And: How do you access sharepoint lists from an ASP.NET MVC 3 app? In an attempt to answer this myself, I came across the following: On MSDN, there is an article on Linq to SharePoint. As I understand it, this intended for use in SharePoint, but there seems no reason why this could not be used from an MVC app, EXCEPT that there is no available reference Microsoft.SharePoint.Linq from Visual Studio 2010 Professional. Presumably, this reflects the fact that the Microsoft.SharePoint.Linq namespace is only available to code running in a SharePoint site? Which would leave third party tooling, unless there is a native way for .NET to access SharePoint lists. In that respect: Is there a native way for .NET to access SharePoint lists? And: Do you know of any third party library or code samples for accessing sharepoint lists from an MVC 3 app? Presumably, someone has already tried to do this. So: Do you know of any links to read more on this subject? A: To get the Microsoft.SharePoint.Linq namespace just install SharePoint server Trial(on a virtual machine preferably) and then copy the DLL from the C:\Program Files\Common Files\Microsoft Shared\Web Server Extension\14\ASAPI\ directory to the BIN folder of your MVC3 Application and reference it within your project. To query the SharePoint list you might need other DLLs which are in that folder as well(by the way the \14\ directory is AKA "The 14th hive").
{ "language": "en", "url": "https://stackoverflow.com/questions/7571163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Format currency in a language, regardless of country I want to format an amount of money (in Euros) in the user's language in Java, regardless of the country the user is in: final NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(loc); currencyFormat.setCurrency(EUR); currencyFormat.format(new BigDecimal("1.99")); However, the output for different input locales (loc) is as follows: * *nl_NL: € 1,99 *nl_BE: 1,99 € *nl_DE: EUR 1,99 *nl (new Locale("nl")): EUR 1,99 So I have two problems * *The output does depend on country, not just language (as the first 2 show), but country shouldn't matter to me. My game can be played for example in Dutch while traveling in Africa. *When using a locale without a country or with a country that doesn't match the language (second 2), no symbol for the currency is printed. Note that I'm developing a payment interface for the game, so a locale of nl_DE means that the interface and currencies should be displayed in Dutch, but it shows only payment methods available in Germany. A: I am not exactly sure what you are up to, but it seems that you have let's say web application and you need separate pieces of information about language and country. OK, let me clarify that: * *To correctly format an amount to pay you actually need both the language and the country, meaning the locale as this is what identifies the appropriate format. *To offer correct payment system, you only need a country user is currently located. *To display appropriate translations you only need the language (at least that is what you think). Now, on how to do that. The easiest way would be to establish some kind of user profile and let user decide on what would be the best locales for formatting, what for translation and what payment system (s)he want to use. If you are developing some kind of web-based game, you can actually read Locales from HTTP Accept-Language headers (you actually need to set good defaults and this is the best place to find such information). To "separate" language from the country, all you need is to read language and country code from locale, which is as simple as: Locale locale = request.getLocale(); // the most acceptable Locale using Servlet API String language = locale.getLanguage(); // gets language code String country = locale.getCountry(); // gets country code Now, language is often not enough to read texts from Resource Bundles, as there are Locales (i.e. zh_CN, zh_TW) for which actual language is different depending on the country (in above example Chinese Simplified is used in mainland of China as well as in Singapore, whereas all other Chinese speaking world is using Traditional Chinese). Therefore you still need actual locale. Country code will give you the selected country, but not the one user currently is in. It might be good or bad, depending on the view. If you need to ensure that the payment happens in the country user is in, I am afraid that you would need to employ Geolocation, with all the consequences... Does this answer your question, or I misunderstood something...? A: I'm thinking I should just split the input locale for my payment screen into: * *Display locale, e.g. nl_NL, nl_BE, fr_FR. Used for, well, displaying stuff. This is a property of user accounts. *Country of residence, e.g. NL, FR, TR. User to determine the payment methods. This is determined via IP-address but can be manually overridden. A: I'm not clear on what you mean by language, regardless of country. The currency denomination itself is obviously independent of language and country, but the formatting conventions vary by culture, not language. Typically we tie these things to something besides local machine settings in our applications because there are always issues of the same language being used in different cultures - for instance Spain uses 9.999,99 and Mexico uses 9,999.99 but both (nominally) speak the Spanish language. And of course, just because someone lives in a particular country does not mean they don't work in a different cultural setting (for instance, telecommuters, or regional managers who cross cultural boundaries). It's not that simple a problem and can only really be solved by defining the scope of the expectations. A: Your payment methods shouldn't be tied to a locale, they should be tied to what you require for the payment processing system. Then you should display that value according to the customs of the selected locale.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: InvalidKeyException: Cannot decrypt OpenJDK/JRE-encrypted string with Sun JRE I encrypted and stored some data to a db using the OpenJDK JRE and also successfully decrypted with OpenJDK when retrieving back from db. Today I replaced the OpenJDK JRE with Sun's JRE and now I get the following exception when I try to decrypt the old (OpenJDK-encrypted) data: java.security.InvalidKeyException: Illegal key size or default parameters at javax.crypto.Cipher.a(DashoA13*..) at javax.crypto.Cipher.a(DashoA13*..) at javax.crypto.Cipher.a(DashoA13*..) at javax.crypto.Cipher.init(DashoA13*..) at javax.crypto.Cipher.init(DashoA13*..) The exception occurs here in line 14: // Decrypts the given ciphertext with the given password public String decrypt(String ciphertext, String password) throws FailedCryptOperationException { String plaintext = ""; byte[] ciphertext_bytes = decode(ciphertext); try { byte[] salt = decode(SALT_BASE64); SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); //$NON-NLS-1$ KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 1024, 256); SecretKey tmp = factory.generateSecret(spec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, secret); plaintext = new String(cipher.doFinal(ciphertext_bytes), TEXT_FORMAT); } catch (Exception e) { throw new FailedCryptOperationException(e); } return plaintext; } // Does Base64 decoding public byte[] decode(String text) throws FailedCryptOperationException { byte[] res; BASE64Decoder decoder = new BASE64Decoder(); try { res = decoder.decodeBuffer(text); } catch (IOException e) { throw new FailedCryptOperationException(e); } return res; } In this line: cipher.init(Cipher.DECRYPT_MODE, secret); Does the original Sun JRE do something differently here? If yes, how can I work around this? If no, what's the problem then? A: I think you need the Java Unlimited JCE extensions. Download and install the security policy files (replacing the the ones installed) and copy them in your JDK and JRE under /lib/security. The link is in the download site Java Downloads
{ "language": "en", "url": "https://stackoverflow.com/questions/7571171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Attaching popup to bottom of a div I am trying to have a clickable div so that when its clicked it appends to the bottom of the div that is clicked. I have it so when i click it appears where the mouse is but i want it to be right below the div that is clicked and is right up against the bottom border. I tried using $(div).position.left(); but it wasnt placing it in the right place and changed when you resized the screen. Any idea on how to do what I am looking for? Thanks, Craig Here is the code $('#clickDetails').click(function(e) { $('#dcHover') .css('position', 'absolute') .css('top', e.pageY + 10) .css('left', e.pageX - 8) .css('z-index','2') .toggle(); //$('#clickDetails').append('<div id="dchover">test</div>'); }); ANd this is the div tag <div id="clickDetails" style=" width: 10px; background-color:red; padding: 1px 5px 1px 5px; color: white; -moz-border-radius:5px; margin-top:-80px; margin-right:35px; z-index: -1;">!</div> A: Try using the .after() function in Jquery HTML: <div id="div1" class="d">Click Me</div> <div id="div3" class="d">Click Me</div> Javascript $(".d").click(function(){ $(this).after("<div id='div2'>Appended</div>"); }); Working Example: http://jsfiddle.net/PeepD/1/ A: You are applying CSS styles before the element has been appended, therefore they're not being added to dchover Try rearranging your code like this: $('#clickDetails').click(function(e) { $('#clickDetails').append('<div id="dchover">test</div>'); $('#dchover') .css('position', 'absolute') .css('top', e.pageY + 10) .css('left', e.pageX - 8) .css('z-index','2') }); A: It sounds like you actually want to append a new div after the current div. To do so, use the jQuery after method. $(function(){ // handle the click event of the div with id 'clickme' $("#clickme").click(function(){ // this is now the div that has been clicked $(this).after("<div class='added'>testing</div>"); }); }); Then use CSS to reduce or increase the margin between the divs as you require. Check it out here: http://jsfiddle.net/Ajbyt/3/
{ "language": "en", "url": "https://stackoverflow.com/questions/7571180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Should i go for the EF 4.2 update through nuget or a standalone installer? I would also like to know how the GAC works when i am using a standalone installer ? Will it override my existing assembly int the project ? if i have the express edition vs 2010 which does not have nuget ,how do i best make use of these packages without breaking my existing stuff? A: You're asking several different questions here. Generally, the GAC always overrides the bin folder for a given version of an assembly. However, if the bin assembly has a different version, and your config file points to that version, it will use that instead of the GAC. With VS Express that doesn't have the NuGet VSIX, using NuGet is definitely a bit harder. You need to get the NuGet command line tool, and run the install command to download packages, which you can then manually reference in your projects.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get label value from dynamically created menu items [tkinter] I have a cascade menu in a parent menu. The cascade items are created dynamically with add_checkbutton method. A user should be able to "check" menu items and select/confirm them. However, I don't know how to access text in the menu items, to decide which item is selected. Obvious solution is to generate tk.StringVar dynamically, but I would like to avoid that since it complicates the code significantly. How to get value of the menu label/text in tkinter? Is there other solution to the problem? A: You can use the entrycget method of a menu item to get any of its attributes, including the label and value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: problems using GridView with soft keyboard My program's main panel is a GridView .But when I touch an item of it and type in some words by soft keyboard,every item of the GridView changes its position.Then exit the program ,it amazes me that the items is just fine when I launch the program again , Any suggestions? Thanks. A: I'm learning Android and I had the same problem. I found the answer here: BaseAdapter causing ListView to go out of order when scrolled The problem was with the standard implementation of the image adapter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why does Eclipse opens http://localhost:8080/de.vogella.jersey.first/WEB-INF/web.xml I followed the following tutorial (although I installed Glassfish Open Source Edition, instead of Tomcat, and using Eclipse Indigo) : http://www.vogella.de/articles/REST/article.html. The webservice is ok, but when I "Run" the project from Eclipse, Eclipse opens a new pane showing the result of a Web browsing to http://localhost:8080/de.vogella.jersey.first/WEB-INF/web.xml. The point is that the browser yields the following result : HTTP Status 404 - -------------------------------------------------------------------------------- type Status report message descriptionThe requested resource () is not available. -------------------------------------------------------------------------------- GlassFish Server Open Source Edition 3.1.1 I don't understand what this is. What's the point in getting the web.xml at that point ? I this a normal behaviour ? How to remove this ? Thank you ! SCO A: i may not be correct but i assume you must have had the focus on web.xml when you clicked run. So eclipse just tried to run whatever you asked it to. Open your index.jspx or whatever jsp page you want to see first and then click run.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Website Product Specification Narrow Down URL List I am looking for a simpler or elegant solution in object oriented (C#) or functional (F#) programming language to solve the following problem. Given many thousands of products with specifications on an eCommerce website, consider the permutations of specification narrow down. Specifically, what is the smallest set of specifications that yield different sets of products that a customer may be interested. Users are given the opportunity to shop by any specification. For example take bolts. They have Drill Size, Finish (Plain, Zinc, etc.), Head Type, Head Height, Grade, Length, Package Quantity, etc. In an average product category, say there is 1000 products and 10 specifications. If each specification can be added to the URL, what are the possible pages. However, I am not just interested in all the permutations. Consider the following points: - by selecting one specification, many others are also selected because they are shared by the remaining set of products, and can be shown to the website user as also shared among the listed products - once there is only one product listed all remaining specifications are naturally selected - by placing the specification in a strict order (such as alphabetical) on the URL, this reduces unnecessary repetition First, the problem was tackled with recursive SQL, (CTE syntax) and this became unwieldy, yielding millions of combinations per category before being able to start clearing out duplications. Now, I am researching C# that takes on category at a time. 1) specifications types are ordered alphabetically 2) all products sets are compared with all others with the following code so as auto-select/auto-define additional specifications: public bool DefinesThisValue(CategoryValue value) { if (this.ProductIds.Count > value.ProductIds.Count) return false; var intersect = this.ProductIds.Intersect(value.ProductIds); return intersect.Count() == this.ProductIds.Count; } 2) next it attempts to traverse all selection sequences, respecting the above, after each selection the an addition path node is addition to a collection and path objects of copy/split if there are multiple additional selectable specifications My current solution is requiring much debugging and has become overly complex. Perhaps someone familiar with set theory and F# could propose something awesome. Thanks for your consideration. In repsonse to Daniel, here is a SQL layout of data. DATA STRUCTURES: TABLES: CREATE TABLE Category ( Id int identity not null, PRIMARY KEY CLUSTERED (Id) ) CREATE TABLE Spec ( Id int identity not null, CategoryId int not null REFERENCES Category(Id), Name varchar(100) not null, PRIMARY KEY CLUSTERED (Id) ) CREATE TABLE SpecValue ( Id int identity not null, SpecId int not null REFERENCES Spec(Id), Value varchar(200) not null, PRIMARY KEY CLUSTERED (Id) ) CREATE TABLE Product ( Id int identity not null, PRIMARY KEY CLUSTERED (Id) ) CREATE TABLE SpecValueProduct ( Id int identity not null, SpecValueId int not null REFERENCES SpecValue(Id), ProductId int not null REFERENCES Product(Id), PRIMARY KEY NONCLUSTERED (Id) ) A simple example might include the following example data: Product 1: Coffee Maker A, Color: Black, Cups: 2 Product 2: Coffee Maker B, Color: Black, Cups: 4 Product 3: Coffee Maker C, Color: Grey, Cups: 4 In this example, then if Color: Grey is selected, then Cups: 4 is also defined. But, if Color: Black is selected, then user has option to select Cup: 2 or Cups: 4. A url might look like: 'site.com\coffee-makers?Color=Black&Cups=4 A: Okay, let's start simple. The first thing you need to do, I presume, is show the list of available specs and their values. Easy enough... select s.Name, v.Id, v.Value from SpecValue v inner join Spec s on s.Id = v.SpecId where s.CategoryId = @CategoryId If you want, you can also join it to SpecValueProduct to limit the specs/values to those currently in use. Next, when spec values are selected, you'll need to run a similar query, but limiting it to relevant values, i.e., those applied to a product where the selected spec/values are present. Given the parameter: declare @SelectedSpecValue table (SpecValueId int) You might do something like select distinct s.Name, v.Id, v.Value, cast(case when n.SpecValueId is null then 0 else 1 end as bit) as IsSelected from SpecValue v inner join Spec s on s.Id = v.SpecId inner join SpecValueProduct p on p.SpecValueId = v.Id inner join ( select distinct y.ProductId from SpecValueProduct y inner join @SelectedSpecValue z on z.SpecValueId = y.SpecValueId ) x on x.ProductId = p.ProductId left join @SelectedSpecValue n on n.SpecValueId = v.Id where s.CategoryId = @CategoryId If I've written that correctly it should constrain the available spec values by those already selected. If not, it might do something entirely different. :-) Am I oversimplifying this? Does it answer your question?
{ "language": "en", "url": "https://stackoverflow.com/questions/7571195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using Expression Trees as an argument constraint Can I use an Expression Tree as an argument constraint in a FakeIteasy CallTo assertion? Given a method on an interface with the following signature: interface IRepository<TEntity> { TEntity Single(Expression<Func<TEntity, bool>> predicate); Being called in code like so: Flight flight = repository.Single(f => f.ID == id); I have in mind a unit test doing something like this: Expression<Func<Flight, bool>> myExpression = flight => flight.ID == 1; A.CallTo(() => repository.Single( A<Expression<Func<Flight, bool>>>.That.Matches(myExpression))) .Returns(new Flight()); However this produces a warning: Try specifying type arguments explicitly. I am currently having to use the Ignored property which is not ideal. A: The "Matches"-method takes a lambda but you're trying to pass it the expression. What are you trying to say with the "Matches"-call? Are you matching on equality? In that case you'd just write: A.CallTo(() => repository.Single(myExpression)).Returns(new Flight()); If you want to constrain the expression on something else you'd have to pass a predicate of the type: Func<Expression<Func<Flight, bool>>, bool> to the "Matches"-method. A: Thanks Patrik, Examining the expression was exactly what I needed to do, i.e. parse the expression (f => f.ID == id) and execute the Right side of the == to get its runtime value. In code this looks like this: A.CallTo(() => flightRepository.Single(A<Expression<Func<Flight, bool>>>.That .Matches(exp => Expression.Lambda<Func<int>>(((BinaryExpression)exp.Body).Right).Compile().Invoke() == 1))) .Returns(new Flight()); However I can't help thinking that there must be a more elegant way to achieve the same end. I'll leave that for another day though. Thanks again, Michael McDowell A: I had the same problem while attempting to assert an expression as an argument but I was using Moq. The solution should work for you though as well... I give most of the credit to this answer to a similar question: Moq Expect On IRepository Passing Expression It basically says you can do a ToString() on the expressions and compare them. It is kind of hacky but it only has one downside; the variables names in the lambda expression must match. Here is an example... [Test] public void TestWhichComparesExpressions() { // setup _mockRepository.Setup(x => x.GetByFilter(MatchQuery())).Returns(new List<Record>()); // execute var records = _service.GetRecordsByFilter(); // assert Assert.IsNotNull(records); Assert.AreEqual(0, records.Count()); } private static Expression<Func<DomainRecord, bool>> MatchQuery() { return MatchExpression(ServiceClass.QueryForTheRecords); // constant } // https://stackoverflow.com/questions/288413/moq-expect-on-irepository-passing-expression/1120836#1120836 private static Expression<Func<DomainRecord, bool>> MatchExpression(Expression<Func<DomainRecord, bool>> expression) { return It.Is<Expression<Func<DomainRecord, bool>>>(e => e.ToString() == expression.ToString()); } I decided to put the expression into a constant on the class which used it which guaranteed it would be the same in the test if someone changed the lambda expressions's variable names.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Using Model with none MVC application I'm trying to use a Model with my Asp.net page. But im not using MVC. I get an error when trying to inherit the model from a customcontrol. The error is ViewModel: interface name expected. public partial class CustomControl : UserControl, ViewModel A: You cant do multiple inheritance in C#. UserControl and ViewModel are both classes and you are only able to inherit from a single class. You can however implement as many interfaces as you like.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I access web.config from my Azure web role entry point? I have an Azure web role and I want to store some settings in web.config under <appSettings> tag. Yes, I'm aware of service configuration files, yet I have reasons to prefer web.config. When I execute (from here): System.Configuration.Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null); if (rootWebConfig1.AppSettings.Settings.Count > 0) { } settings count is always zero although I've added a key-value pair under <appSettings>. What am I doing wrong? Is it possible to read settings from web.config from inside web role entry point? A: The reason for this is that Microsoft has introduced Full IIS capability since Azure SDK 1.3. A side effect of this is that the RoleEntryPoint gets walled off from the rest of the web application. The following excerpt from Microsofts blog post describes what you're seeing. ...with full IIS, the RoleEntryPoint runs under WaIISHost.exe, while the web site runs under a normal IIS w3wp.exe process. ...so it expects its configuration to be in a file called WaIISHost.exe.config. Therefore, if you create a file with this name in the your web project and set the "Copy to Output Directory" property to "Copy Always" you'll find that the RoleEntryPoint can read this happily. Apart from the solution mentioned, an option might be to try to use Hosted Web Core (HWC) mode instead of full IIS mode. Update - changes introduced in Azure SDK 1.8 * *Azure SDK 1.3 -1.7 will look in WaIISHost.exe.config *Azure SDK 1.8+ will look in the WebRoleProjectName.dll.config. With the newest change to the SDK, you should be able to place an app.config in your project and your role entry point should then have access to it. A: Where is your web.config, and where is the code you're executing? If it's in the OnStart() method of a RoleEntryPoint subclass, you'll be seeing the entries in a web.config in the root of the same project - typically, this is the Web deploy project itself, not your Web site. This allows Azure to support multiple Web sites under one Web deployment role.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Memory SPIKE - Boost ASIO ASYNC read Wrote a Server which just reads data from a client: Using a boost::array buffer Started the server and system monitor shows 1MB of usage. 1.) Just do an async_read_some and do a handleRead in which I again call the asyncRead function. void asyncRead() { m_socket->async_read_some( boost::asio::buffer(m_readBuffer, READ_BLOCK_SIZE), m_strand->wrap(boost::bind(&ConnectionHandler::handleRead, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)) ); } and in handleRead I verify if there are any errors or not and if there aren't any I simply issue another asyncRead(). 2.) Kept sending frames ( data of size around 102 bytes ). At end of test for 10000 Frames. Total Sent size = 102*10000 Total Read Size = 102*10000 But, the memory usage in system monitor spikes up to 7.8 Mb . Couldn't figure out the cause of this increase. The different aspects tried out are: 1.) Number of connections being made - only 1. 2.) Verified closing of connection - yes. 3.) stopped even the ioServic but still no change. On a 2nd run of the client, I see the memory increasing. What could be the case? I am using a boost::array which is a stack variable and simply just reading. No other place there is a buffer being initialized. A: Raja, First of all, are you aware that async_read_some does not guarantee that you will read the entire READ_BLOCK_SIZE? If you need that guarantee, I would suggest you to use async_read instead. Now, back to the original question, your situation is quite typical. So, basically, you need a container (array) that will hold the data until is sent, and then you need to get rid of it. I strongly suggest you switching to boost shared_array. You can use it in the same way as boost array, but it has a built-in reference counter, so the object will be deleted when it is not needed anymore. This should solve your memory leak.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Can XML/XSLT substring-before take more than one match-string as a second argument? XML/XSLT Newb question. I apologise for this. I got handed a chunk of code and asked to 'have a look at this', and I'm not particularly familiar with XSLT :( I've got an .xsl file that transforms a chunk of story text, and plucks out the first sentence by using the line: <xsl:value-of select="substring-before(story,'.')" /> It works fine, mostly. The problem is this: if the first sentence ends in a question mark or an exclamation mark, I end up with two sentences. Is there any way of doing something along the lines of: <xsl:value-of select="substring-before(story,'.' or '!' or '?')" /> Or is there a way of using regex, e.g. /^(.*?)[.?!]\s/ ...to extract just the very first sentence? Or am I hugely off the mark and best waiting for the resident XSLT expert to get back? :) A: If your character set for punctuation is relative limited you could map it all to a single character (e.g. period) using the translate function and then use the substring-before. e.g. <xsl:value-of select="substring-before(translate(story,'?!','..'),'.')" /> Edit: I should say in answer to your actual question, no - you can't have a boolean expression as the second argument in substring-before.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Regexp matching except I'm trying to match some paths, but not others via regexp. I want to match anything that starts with "/profile/" that is NOT one of the following: * */profile/attributes */profile/essays */profile/edit Here is the regex I'm trying to use that doesn't seem to be working: ^/profile/(?!attributes|essays|edit)$ For example, none of these URLs are properly matching the above: * */profile/matt */profile/127 */profile/-591m!40v81,ma/asdf?foo=bar#page1 A: You need to say that there can be any characters until the end of the string: ^/profile/(?!attributes|essays|edit).*$ Removing the end-of-string anchor would also work: ^/profile/(?!attributes|essays|edit) And you may want to be more restrictive in your negative lookahead to avoid excluding /profile/editor: ^/profile/(?!(?:attributes|essays|edit)$) A: comments are hard to read code in, so here is my answer in nice format def mpath(path, ignore_str = 'attributes|essays|edit',anything = True): any = '' if anything: any = '.*?' m = re.compile("^/profile/(?!(?:%s)%s($|/)).*$" % (ignore_str,any) ) match = m.search(path) if match: return match.group(0) else: return ''
{ "language": "en", "url": "https://stackoverflow.com/questions/7571212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to create vertical cyclic image views in android...? I want a view, where 5 images scroll vertically and repeatedly (loop). How to achieve this in android..? I tried Gallery view but it will not support vertical view. I tried transition animation, it shows vertical but not in a loop. I tried dynamically adding views in a layout but its not appropriate. How to achieve this, please help..? Thanks in advance.. A: This is a demo created for one of my projects. It give you some idea. Here I scroll through the images in a loop. A: You can do this using a very simply ListView. In the ListView's Adapter.getView() method simply modulo the position by the total number of items in the list: public View getView(int position, View convertView, ViewGroup parent) { position = position % nObjects; // nObjects if the total number of objects to display // Code to get the new view is below this } One advantage of doing it this way is the OS will take care of recycling old views and clearing up memory. Where as if you create and destroy the views yourself you will have to do that manually.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS Divs Floated "Cards" in Wrap I have this basic scenario setup where I am trying to float divs inside of a wrap. It is working nicely, however the simple effect I am trying to achieve isn't cooperating when the divs have variable heights. I have researched this a bunch tried to apply a clearfix to the 3rd card without success. The only success I've had is actually injecting another div after the 3rd card with a style of clear both. However this is not an approach I want to take as I don't want to change any of the clean markup. Thoughts on the best way to get this done? I don't mind using a simple bit of JS/jQuery if necessary. Desired: Current: http://andrewherrick.com/spike/floatcards/ A: Perhaps I'm not understanding the question, but couldn't you simply add a "clear: both" to the 4th card? A: Solution 1: Add clear: both to the 3n+1 elements, using .card:nth-child(3n+1) { clear: both } or manually adding a class where needed. Solution 2: Instead of float: left on .card, use display: inline-block; vertical-align: top. You'll also need to reduce the margin-right to 16px. If you need to support IE7, then display: inline-block needs to be display:inline-block; *display:inline; zoom:1. A: You must define the "rows" somehow. You can set the same height of each div (thus setting row-height), or you can place a null height separator, or you can set clear:left for every 3rd div starting from the first one. A: Solution 1 If you're really averse to touching your mark-up, you could use some jQuery as such (Thanks to thirtydot for the tip): Jquery $('.card:nth-child(3n+1)').css('clear','left'); Solution 2 It might be cleaner (and more backwards-compatible) to just slightly alter your HTML. Perhaps wrap each row in its own wrapper, with a clearfix applied to that. jsfiddle: http://jsfiddle.net/leifparker/sh4fR/ You'll need to add the 'clearfix' CSS code. See the fiddle. HTML <div id="wrap"> <div class="cards clearfix"> <div class="card"> 1 text text text text text text text text text text text text text text text text text text text text text text text text text text </div> <div class="card"> 2 text text text text text text text text text text text text text text text text text text text text text text text text text text </div> <div class="card"> 3 text text text text text text text text text text text text text text text text </div> </div> <div class="cards clearfix"> <div class="card"> 4 text text text text text text text text text text text text text text text text text text text text text text text text text text </div> <div class="card"> 5 text text text text text text text text text text text text text text text text </div> <div class="card"> 6 text text text text text text text text text text text text text text text text </div> </div> A: clear:both set with an nth-child selector is what you are after. You can dynamically add a class, using the nth-child selector with jQuery for older browsers that don't support it natively: http://api.jquery.com/nth-child-selector/ A: Use the :nth-child selector in combination with clear:both. The following will clear every third card. This will work reliably since you're using a fixed width (910px). .card:nth-child(3n+1) { clear: both; } Simply add the rule to your existing CSS. Tested in Firefox, Chrome, and IE: jsfiddle
{ "language": "en", "url": "https://stackoverflow.com/questions/7571220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Images working/showing in my new Rails app Update: o.k. this is strange, in the brower, i can access the images at localhost:3000/assets/images/rails.png but when I put that path in the seeds.rb file and then load the page, it shows that it's trying to find the image in /assets/rails.png i.e. it's skipping over the images folder...any ideas? Is it possible that rails is configured somewhere to only look into two folders? I'm using a book called Agile web Development with Rails to learn how to use the framework but there seem to be some slight differences. It supplies code for rails 3.0 and 3.1 (I'm using the latter) but it's not always working as expected. Thus far we have created scaffolding for Products class and used seeds.rb to put some data in the sqlite3 database. There are images in the assets/images folder for each "product" but it's not showing. I experimented in the seeds.rb file with the path for the images but it didn't work. Images are in the folder app/assets/images I will show you the following files, all of which in some way deal with the images 1.app/views/products/_form.html.erb 2.app/views/products/index.html.erb 3. db/seeds.rb UPDATE: in the logfile, it says there is a routing error for the images. Started GET "/assets/wd4d.jpg" for 127.0.0.1 at Tue Sep 27 11:01:43 -0400 2011 Served asset /wd4d.jpg - 404 Not Found (3ms) ActionController::RoutingError (No route matches [GET] "/assets/wd4d.jpg"): Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.1.0/lib/action_dispatch/middleware/templates/rescues/routing_error.erb within rescues/layout (0.5ms) Started GET "/images/ruby.jpg" for 127.0.0.1 at Tue Sep 27 11:01:43 -0400 2011 ActionController::RoutingError (No route matches [GET] "/images/ruby.jpg"): app/views/products/_form.html.erb <%= form_for(@product) do |f| %> <% if @product.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@product.errors.count, "error") %> prohibited this product from being saved:</h2> <ul> <% @product.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= f.label :title %><br /> <%= f.text_field :title %> </div> <div class="field"> <%= f.label :description %><br /> <%= f.text_area :description, :rows => 6 %> </div> <div class="field"> <%= f.label :image_url %><br /> <%= f.text_field :image_url %> </div> <div class="field"> <%= f.label :price %><br /> <%= f.text_field :price %> </div> <div class="actions"> <%= f.submit %> </div> <% end %> 2.app/views/products/index.html.erb <h1>Listing products</h1> <table> <% @products.each do |product| %> <tr class="<%= cycle('list_line_odd', 'list_line_even') %>"> <td> <%= image_tag(product.image_url, :class => 'list_image') %> </td> <td class="list_description"> <dl> <dt><%= product.title %></dt> <dd><%= truncate(strip_tags(product.description), :truncate => 80) %></dd> </dl> </td> <td class="list_actions"> <%= link_to 'Show', product %><br/> <%= link_to 'Edit', edit_product_path(product) %><br/> <%= link_to 'Destroy', product, :confirm => 'Are you sure?', :method => :delete %> </td> </tr> <% end %> </table> <br /> <%= link_to 'New product', new_product_path %> * *3. db/seeds.rb (notice here that I experimented with image url) Product.delete_all Product.create(:title => 'Web Design for Developers', :description => %{ blah blah }, :image_url => 'wd4d.jpg', :price => 42.95) . . . Product.create(:title => 'Programming Ruby 1.9', :description => %{ blah blah. }, :image_url => '/images/ruby.jpg', :price => 49.50) . . . Product.create(:title => 'Rails Test Prescriptions', :description => %{ blah blah }, :image_url => '/images/rtp.jpg', :price => 43.75) A: Ok, So I've been working through this book to and you have to make changes in 2 places. In the seed file, just reference the name of the jpg. Since you're using rails 3.1, anything inside of assets/images/ can be referenced just by it's name. You'll have to make a change in the views as well. Download the source for the book here http://pragprog.com/titles/rails4/source_code and look at what they have for depot 2 in for the products#index view. They got really sloppy with this release. A: Have a look at the Rails 3.1 Guide to Asset Pipeline. In section 2.2 Coding Links to Assets, you will find the following: In regular views you can access images in the assets/images directory like this: <%= image_tag "rails.png" %> As I understand your code (I may be wrong here), you try to store the filename of an image in the database, and show that image later together with the other object data. So you should try to remove the path from it, use just the filename. And then denote it by using the method image_tag. A: I had the same problem and then realized that when I downloaded the test images for the Depot application, they got saved as XXX.jpeg instead of XXX.jpg. As a result, the URL's in seeds.rb didn't match the filenames in assets/images. A: The only thing that worked for me was: <%= image_tag('/assets/images/' + product.image_url, class: 'list_image') %>
{ "language": "en", "url": "https://stackoverflow.com/questions/7571222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Sunspot Solr in production I have need to deploy my app to production now that uses sunspot for search. I see some sources saying not to run the sunspot solr instance in production but to setup on tomcat, but others have said you can run sunspot in production ? Please can anyone tell me which is best to use in production and why? Obviously just running sunspot in production will be alot quicker to setup but i dont want problems caused by this. Also i have seen that you should turn off auto commits, is this best practice ? and if so how do you do commits? a cron or delayed job or something ? If anyone has a tutorial / article or example setup i can see for reference ? thanks a lot Rick A: Have you considered using http://websolr.com ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7571224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: FormsAuthentication working in every browser except for IE This certainly is a strange one... I have an ASP.net 4.0, C# website that has a login page using FormsAuthentication to handle user access. There's also code throughout the site that boots the user back to the login page whenever a session times out or something else that requires them to login again happens. This is all really basic stuff that I've done about a dozen times before. I know this whole process is working, because I've been able to login to the site running through VS2010 on EVERY browser I tried. It also works perfectly fine when it's sitting on the development server using Chrome, Firefox, Safari (Mac), and two Cellphone browsers. The only thing I've had a problem with is Internet Explorer. Now, this one is a bit hard to debug considering it works in IE locally but not on the server. The fact that it also works in other browsers on the server is also sort of ruling out a server configuration issue. What I did to try and figure out where it could be going wrong was add a query string to my FormsAuthentication.RedirectToLogin("WhateverPage=WhateverSectionOfCode"); line to try and solve this. The problem is that when I run the site in IE, it never appends that Query String, which leads me to believe that it never hits any of those "RedirectToLogin" lines. I know it authenticates, because the code that updates the Last Login timestamp in the database only fires if the user is authenticated. It looks as if the "RedirectFromLogin" line does go out and find the proper entry in the web.config...and it might actually be redirecting me, but even if it does, it always bounces me back to the login screen. I've been through all of the really basic ID-10T errors (heh) that could possibly be causing this: Heightened security settings, disabled cookies, etc., but I'm getting the same results on multiple machines. I'm really sort of stumped as to what to check for next. I've already had two other sets of eyes on the code, but they couldn't come up with any reason as to why this was happening. If anyone has any suggestions as to what could be happening, I'd love to hear them. Thanks! A: i think it is something about cookies.. did you set the domain attribute in the web.config? <authentication mode="Forms"> <forms loginUrl="~/login.aspx" name="cookiename" domain="domain.com" cookieless="UseCookies" slidingExpiration="true" timeout="60"/> </authentication> forms Element for authentication (ASP.NET Settings Schema) A: I know this ticket is a bit old, but apparently IE can't set forms authentication on a domain with an underscore in the name. So if the issue appeared on a development server that was, say Dev_XP, then IE won't be able to set an authentication cookie. That's what happened with me. Here's the link: http://orwin.ca/2012/02/09/formsauthentication-setauthcookie-not-working-in-ie-but-works-in-other-browsers/ This is the KB artical that outlines the issue http://support.microsoft.com/kb/316112 A: I'm having same issue, but with all other browsers except Chrome. The strange thing is that when all these browser are tried locally (in same computer where service is running), everything works well. When I'm connecting remotely - only Chrome works. Firefox and IE are redirecting me back to login page every time, though user is authenticated - same as yours, in database logon timestamp updated. But I have also developer server, located in the other network, connection to this network takes less time, and here are all three browsers works OK too. So I think that the problem is in IIS settings, which might be different on real vs developer server, or it might be a problem in Redirect and thread, which creates session. I found some interesting topic about this. It's about ASP WebForms though. See my question on stakoverflow. And please, let me know if you solve this problem!
{ "language": "en", "url": "https://stackoverflow.com/questions/7571227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Is there a way to create Eclipse plugins with Python? As far as I understand Eclipse doesn't provide user with python bindings by default. Nor any projects of such kind was I able to find with google. Are there any third-party plugins for that? Any tutorial? May be with Jython?.. A: As far as I know, you need to use Java. Eclipse is written in Java, and even the vanilla application is made up of several Java components glued together by the core plugin loader. Jython might work if: * *you can cross-compile Python to Java bytecode (indeed you can, thanks to sayth for pointing that out), and *you can access the Eclipse APIs inside Jython. So, here's more or less what your plugin's architecture might look like. If you can get at the Eclipse APIs, then you can write most of it in Jython, and then make a Java wrapper for it with the Embedding Jython instructions. If you can't get the Eclipse functionality into your Jython, then you can still write some of your code in python, and then have the Eclipse API access happening on your Java layer. This will be annoying in proportion to how evenly split your code is between python and Java. I've worked on a project before where we embedded python into C++ (or it might have been the other way around...), and it's a major headache if you don't plan it out right.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: ClickOnce connection string encryption I'm working on my first real WinForms application, and my boss has asked that I figure out a way to encrypt the connection string inside the app.config. I've read some of the suggestions in other questions about connection string encryption, and I recognize that it isn't a silver bullet answer to the security/privacy problem. We've considered writing web services to retrieve data from the database, but this is a very small project and unfortunately isn't a priority at this time. Edit: I left out the detail that I'm working for a state institution (community college) where, because we're identifying students using a state-mandated private system ID, we need to secure the application in some form or fashion. Students may enter their network IDs to identify themselves (which we need to protect anyway as some students have restraining orders and need much of their records kept private), but many students only know their system IDs (which are always kept private). Regardless, we'd like to get this process working in conjunction with ClickOnce deployment, but my encryption process crashes the application when I run the ClickOnce executable. Here's my encryption code (which is lifted from another question here on SO): public static void EncryptConfigSection(string sectionName) { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); ConfigurationSection section = config.GetSection(sectionName); if (section != null) { if (section.IsReadOnly() == false && section.SectionInformation.IsProtected == false) { section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider"); section.SectionInformation.ForceSave = true; config.Save(ConfigurationSaveMode.Full); } } ConfigurationManager.RefreshSection(sectionName); } I'm calling this function from the Main() function in Program.cs, but I'm not sure if this is the appropriate place for it. Additionally, while this function encrypts the app.config correctly, as soon as I exit the application, the app.config decrypts. I feel like I'm missing a piece to the puzzle (or perhaps large swaths of the puzzle). Can anyone offer me some insight into these problems? I'd like to reiterate that I recognize that web services are the end goal here, so if this is just not a solvable problem using CLickOnce, then I'm willing to suggest that we prioritize writing web services now. A: Have you looked at this topic? It talks about setting up the client using DPAPI so the string is encrypted. I would still look at the web services route rather than embed a connection string, encrypted or not, into a client application. This is ESPECIALLY true if you are talking about client apps outside of your domain (ie, non-employee use).
{ "language": "en", "url": "https://stackoverflow.com/questions/7571236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to use FormsAuthentication to connect to SharePoint Lists service to fetch all the Lists I have a sharepoint server which uses Forms Authentication. Now i want to connect to that server to fetch all the List via Lists Webservice. i am able to connect to the SharePoint server which uses Windows Authentication, but i am not able to do it with the FormsAuthentication. Can you please help me to figure that out. public static Lists CreateSharepointService(string sharepointHost) { Lists wssSrvc = new Lists(); if (sharepointHost.EndsWith("/")) wssSrvc.Url = sharepointHost + "_vti_bin/Lists.asmx"; else wssSrvc.Url = sharepointHost + "/_vti_bin/Lists.asmx"; return wssSrvc; } public static Lists CreateSharepointService(string sharepointHost, string sharepointUsername, string sharepointPassword, string sharepointDomain) { NetworkCredential credential = new NetworkCredential(sharepointUsername, sharepointPassword, sharepointDomain); Lists wssSrvc = CreateSharepointService(sharepointHost); wssSrvc.Credentials = credential; return wssSrvc; } A: You can either add a Service Reference or create a proxy class using wsdl.exe and use the code below to get all lists from a certain sharepoint site: XmlNode ndLists = listService.GetListCollection(); Let me know if you are having errors calling the GetListCollection() method. As long as you are able to pass the correct credentials this should work. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7571237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: "dynamic constructor" in c++ i am new to classes in C++ and i need to create a class "Plot" which has a method that reads in data from a file and creates a 3d grid. i understand that you can make "default" constructors with default values or you can create a special constructor with predefined values. in my "private" section, i have: int nx; // number of "x" values int ny; // number of "y" values int nz; // number of "z" values double* grid; // one dimensional array which stores nx*ny*nz values double tgrid(int ix, int iy, int iz); // function which searches grid and returns value now, i want to create my "plot" object and then AFTER that, dynamically create the "grid" array. is it possible to do this? or will i need to declare the size of the array "grid" when i first create "plot"? A: Use std::vector grid; as your member. Then you can use grid.resize(nx*ny*nz) to force the size you want or use grid.push_back(value); for each value you want to add to the array. A: It is possible: class Plot{ int nx; // number of "x" values int ny; // number of "y" values int nz; // number of "z" values double* grid; // one dimensional array which stores nx*ny*nz values double tgrid(int ix, int iy, int iz); // function which searches grid and returns value public: Plot() { grid = NULL; } ~Plot() { delete[] grid; } void init(int x, int y, int z) { delete[] grid; //make sure no memory leaks since grid might have already been allocated nx = x; ny = y; nz = z; grid = new double[nx*ny*nz]; } }; After the construction, just call the method init: Plot p(); p.init(2,3,4); EDIT: You should however consider Mark B's answer. I would also use something from std:: rather than a dynamically allocated array. Much easier to manage. EDIT2: As per Constantinius' answer, avoid init() methods when you can. If you specifically need the initalization AFTER construction, use it, otherwise keep all initialization logic in the constructor. A: It depends on how your Plot class should be used. If you consider it necessary to create objects of this class only with valid sizes you should not allow a default constructor. You do this by defining your own constructor like that: public: Plot(int _nx, int _ny, int _nz) : nx(_nx), ny(_ny), nz(_nz) { // initialize your array grid = new double[nx*ny*nz]; } also don't forget your destructor to clear the allocated memory: ~Plot() { delete[] grid; } A: class Plot { int nx; // number of "x" values int ny; // number of "y" values int nz; // number of "z" values double* grid; // one dimensional array which stores nx*ny*nz values double tgrid(int ix, int iy, int iz); // function which searches grid and returns value public: /* default constructor */ Plot() : nx(0), ny(0), nz(0), grid(NULL) { } /* rule of five copy constructor */ Plot(const Plot& b) : nx(b.nx), ny(b.ny), nz(b.nz) { int max = nx*ny*nz; if (max) { grid = new double(max); for(int i=0; i<max; ++i) grid[i] = b.grid[i]; } else grid = NULL; } /* rule of five move constructor */ Plot(Plot&& b) : nx(b.nx), ny(b.ny), nz(b.nz) grid(b.grid) { b.grid = NULL; } /* load constructor */ Plot(std::istream& b) : nx(0), ny(0), nz(0), grid(NULL) { Load(b); } /* rule of five destructor */ ~Plot() { delete[] grid; } /* rule of five assignment operator */ Plot& operator=(const Plot& b) { int max = b.nx*b.ny*b.nz; double* t = new double[max]; for(int i=0; i<max; ++i) t[i] = b.grid[i]; //all exceptions above this line, NOW we can alter members nx = b.nx; ny = b.ny; nz = b.nz; delete [] grid; grid = t; } /* rule of five move operator */ Plot& operator=(Plot&& b) { nx = b.nx; ny = b.ny; nz = b.nz; delete [] grid; grid = b.grid; b.grid = NULL; } /* always a good idea for rule of five objects */ void swap(const Plot& b) { std::swap(nx, b.nx); std::swap(ny, b.ny); std::swap(nz, b.nz); std::swap(grid, b.grid); } /* your load member */ void Load(std::istream& in) { //load data //all exceptions above this line, NOW we can alter members //alter members }; }; int main() { Plot x; //default constructor allocates no memory Plot y(x); //allocates no memory, because x has no memory Plot z(std::cin); //loads from stream, allocates memory x = z; //x.grid is _now_ given a value besides NULL. } This answers your questions I think. Still: use a std::vector.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571238", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Eclipse gdb expression: what is shown in "default"? Stepping through C code in gdb using Eclipse, I noticed that for a variable char* sval gdb prints (in Expressions tab): * *Expression: sval *Type: char* *Value: 0x7fffd9d79840 "BIDPRICE" However I know that the value should be something different (say, "BIDZSPD") because it was assigned a few lines above. Indeed, the value of sval[3] is 'Z', as expected. Then I noticed the following in the expressions view, same as in mouse-over on a variable: Name : sval Details:0x7fffd9d79840 "BIDZSPD" Default:0x7fffd9d79840 "BIDPRICE" Decimal:140736848173120 Hex:0x7fffd9d79840 Binary:11111111111111111011001110101111001100001000000 Octal:03777773165714100 Looks like different representations of char pointer, but why Details is different from Default? Should I interpret "Default" as previous value? Why Default is shown as expression value, and not current value? A: Full build fixed it. This is one of the things one needs to keep in mind when working with C++: if things look really screwy (like gdb reporting different values by the same address), you have to bite the bullet and do a full build.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Unique constraint violation during insert: why? (Oracle) I'm trying to create a new row in a table. There are two constraints on the table -- one is on the key field (DB_ID), the other constrains a value to be one of several the the field ENV. When I do an insert, I do not include the key field as one of the fields I'm trying to insert, yet I'm getting this error: unique constraint (N390.PK_DB_ID) violated Here's the SQL that causes the error: insert into cmdb_db (narrative_name, db_name, db_type, schema, node, env, server_id, state, path) values ('Test Database', 'DB', 'TYPE', 'SCH', '', 'SB01', 381, 'TEST', '') The only thing I've been able to turn up is the possibility that Oracle might be trying to assign an already in-use DB_ID if rows were inserted manually. The data in this database was somehow restored/moved from a production database, but I don't have the details as to how that was done. Any thoughts? A: Presumably, since you're not providing a value for the DB_ID column, that value is being populated by a row-level before insert trigger defined on the table. That trigger, presumably, is selecting the value from a sequence. Since the data was moved (presumably recently) from the production database, my wager would be that when the data was copied, the sequence was not modified as well. I would guess that the sequence is generating values that are much lower than the largest DB_ID that is currently in the table leading to the error. You could confirm this suspicion by looking at the trigger to determine which sequence is being used and doing a SELECT <<sequence name>>.nextval FROM dual and comparing that to SELECT MAX(db_id) FROM cmdb_db If, as I suspect, the sequence is generating values that already exist in the database, you could increment the sequence until it was generating unused values or you could alter it to set the INCREMENT to something very large, get the nextval once, and set the INCREMENT back to 1. A: It looks like you are not providing a value for the primary key field DB_ID. If that is a primary key, you must provide a unique value for that column. The only way not to provide it would be to create a database trigger that, on insert, would provide a value, most likely derived from a sequence. If this is a restoration from another database and there is a sequence on this new instance, it might be trying to reuse a value. If the old data had unique keys from 1 - 1000 and your current sequence is at 500, it would be generating values that already exist. If a sequence does exist for this table and it is trying to use it, you would need to reconcile the values in your table with the current value of the sequence. You can use SEQUENCE_NAME.CURRVAL to see the current value of the sequence (if it exists of course) A: Your error looks like you are duplicating an already existing Primary Key in your DB. You should modify your sql code to implement its own primary key by using something like the IDENTITY keyword. CREATE TABLE [DB] ( [DBId] bigint NOT NULL IDENTITY, ... CONSTRAINT [DB_PK] PRIMARY KEY ([DB] ASC), );
{ "language": "en", "url": "https://stackoverflow.com/questions/7571245", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Remote profilling java application I'd like to ask how I can profile REMOTELY a java application. For debugging I can say which port the JVM must listen etc since the machine I'm trying to access is behind an ssh gateway so I manually create an SSH tunnel but I've been googling about the same thing but when profiling and I couldn't seem to find. Basically I'm looking for the equivalent of this command: java -agentlib:jdwp=transport=dt_socket,server=y,address=8000 -jar /bla/bla but for profiling so that I can remotely attach a profiler. A: Disclaimer: My company develops JProfiler With JProfiler, the VM parameter is like this: -agentpath:/path/to/libjprofilerti.so=port=8849 "/path/to/libjprofilerti.so" is the path to the native agent library, on Linux x86, for a 32-bit JVM it would be [JProfiler installation directory]/bin/linux-x86/libjprofilerti.so. With the port parameter, you can tell the agent to listen on a specific port. You can set this to the port of your SSH tunnel. You can easily generate this VM parameter by invoking Session->Integration Wizards->New Remote Integration in JProfiler's main menu: On your local machine, you create a new session of type "Attach to profiled JVM" and choose the local port of your SSH tunnel (10022 in the screen shot):
{ "language": "en", "url": "https://stackoverflow.com/questions/7571247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Using awk/sed to parse out multiple strings from a MySQL error I have a bash script that needs to identify some important sub-strings within a MySQL error generated from a SHOW SLAVE STATUS\G command run from the terminal. In particular, the line starting with Last_Error: ... is of significant importance. As as example, if the line read (broken into multiple lines for ease of reading): Last_Error: Error 'Cannot add or update a child row: a foreign key constraint fails (`dms/active_sessions`, CONSTRAINT `active_sessions_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)' on query. Default database: 'dms'. Query: 'INSERT INTO active_sessions (session_id,user_id,lastused,ip) VALUES ('749d9d494c31ab8ee76bf6b6b1127fd2', '15389','2011-09-27 14:04:59','172.16.11.31')' Assuming the error string is stored in a variable $LAST_ERROR, I've used the following three variables to store user_id, the field in the table with the FK constraint, users, the table that is being referenced by the FK, and id which is the key in users that is being referenced: FIELD=`echo $LAST_ERROR | sed 's/.*FOREIGN KEY [\(\`]*\([0-9a-zA-Z_-]*\)[\`\)]*.*/\1/'` TABLE=`echo $LAST_ERROR | sed 's/.*REFERENCES \`\([0-9a-zA-Z_-]*\)\`.*/\1/'` COLUMN=`echo $LAST_ERROR | sed 's/.*REFERENCES \`['$TABLE']*\` [\(\`]*\([0-9a-zA-Z_-]*\)[\`\)]*.*/\1/'` Are these three variables and their sed commands an acceptable way of finding the values? With those variables defined, I need to parse through the SQL query in the error. The only variable that pertains to this specific case (the rest are being used elsewhere in the script) is $FIELD. In this case, I need to identify that if the fields specified in the SQL query are: (session_id,user_id,lastused,ip) That $FIELD is the 4th field listed in the SQL query, and it's corresponding value in: ('749d9d494c31ab8ee76bf6b6b1127fd2','15389','2011-09-27 14:04:59','172.16.11.31') is 15389. What sed/awk commands can reference the fields listed in the SQL query, and find the corresponding values in the latter part of the query? A: Superficially, this sed script would list the parts you request: sed 's/.* FOREIGN KEY (\([^)]*\)) REFERENCES \([^(]*\) (\([^)]*\)) .*/(\1) \2 (\3)/' on the not altogether implausible assumption that you do not use either open or close parentheses in your table and column names. The output is unambiguous and deals with a list of columns referencing another list of columns.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Final keyword in method signatures Possible Duplicate: Final arguments in interface methods - what’s the point? While trying to experiment a few things, I've ran into a problem that it's described in this page. interface B { public int something(final int a); } abstract class C { public int other(final int b); } class A extends C implements B { public int something(int a) { return a++; } public int other(int b) { return b++ } } Why is such feature possible? I don't know why it's possible to to make a final parameter into a non-final one by just overriding the method. Why is the final keyword ignored in a method signature? And how do I obligate sub-classes to use in their methods final variables? A: Java passes arguments to a method by value. Therefore, no changes to a parameter can propagate back to the caller. It follows that whether or not the parameter is declared final makes absolutely no difference to the caller. As such, it is part of the implementation of the method rather than part of its interface. What's your motivation for wanting to "obligate sub-classes to use in their methods final variables"? A: final for a parameter only means that the value must not be changed within the method body. This is not a part of the method signature, and is not relevant to subclasses. It should be invalid to have final parameters in interface or abstract methods, because it's meaningless. A: Final variables are the only ones that can be used in closures. So if you want to do something like this: void myMethod(int val) { MyClass cls = new MyClass() { @override void doAction() { callMethod(val); // use the val argument in the anonymous class - closure! } }; useClass(cls); } This won't compile, as the compiler requires val to be final. So changing the method signature to void myMethod(final int val) will solve the problem. Local final variable will do just as well: void myMethod(int val) { final int val0; // now use val0 in the anonymous class A: Java's final is not C++ const; there is no such thing as const-correctness in Java. In Java, one achieves const-ness using immutable classes. It turns out to be quite effective because unlike C++, one cannot simply mess with memory. (You can use Field.setAccessible(true), and then use Reflection. But even that corruption-vector can be prevented by running the JVM with an appropriately configured security manager.) A: The final keyword for arguments is not part of the method signature, and is only important for the body of the method, because Java passes all arguments by value (a copy of the value is always made for the method call). I only use the final keyword (for arguments) if the compiler forces me to make it final, because the argument is used inside an anonymous class defined in the method. A: In Java parameters are passed by value. Whether a parameter is final or not only affects that method, not the caller. I don't see why a class needs to obligate the subtypes. A: Note that final parameters have one main purpose: you can't assign new values to them. Also note that parameters are always passed by value, thus the caller won't see any assignments to the parameter inside the method. If you really want to force parameters to be final (in order to prevent bugs that might be introduced when reassigning a parameter accidentially), employ a code anaylzer such as checkstyle.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Create clickable URL in PHP Trying to create a clickable URL in PHP. If you visit www.wheels4rent.net/test00.html and input location and date clicking the 'quote' will take you to the list_car5.php page. At right of this page is a 'book now' button that does not work and the text hyperlink below this. problem is when clicking the text hyperlink instead of giving me the www.thrifty.co.uk URL it gives me www.wheels4rent.net/www.thrifty.co.uk URL which obviously does not display webpage. Please assist. Also i need to also create the text hyperlink within my 'book now' button instead. below is code $url = (string)$car->book; echo "<tr><td width=200px><' align='right' style='padding:1px; width:100px'><b>".$car->cartype."</b><br>".$car->carsipp."<br>".$car->transmission."</td><td><b>".$car->carexample."</b></td><td><b>&pound;".$car->price." </b><br>Unlimited Miles</b><br><a href='$url'><input type='submit' name='Book Now' value='Book Now'><br>book now<br></a></td></tr>"; } echo "</table>"; A: You need to add http:// to the beginning of the URL in the <a> tag. I can't even read the code you've posted, so that's the only answer I can give. A: Instead of wrapping your in an , use the onclick attribute of the tag. <input type='submit' name='Book Now' value='Book Now' onclick="javascript:window.location('http://www.thrifty.co.uk')" /> <a href="http://www.thrifty.co.uk">Book Now</a> A: single quotes doesn't read variables. So you could either write the whole html part in echo or you can simply close the php tag and enter the html code and then continue with your php code for ex: <?php echo "<input type='submit' value='submit' onclick='<script>window.location('http://www.google.com')</script>'"; ?> or simply: <?php -----//php code here ---- ---- ?> <input type="submit" value="submit" onclick="<script>window.location('http://www.google.com')</script>"/> <?php ------ ------ ------ ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7571252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to call a web service with a configurable URL I wrote a web-service. I wrote a website. I want the website BLL code to call the web-service. I have a config table with this service URL. I inject the web-service URL to the calling code. What web client or socket in C# should I use that can receive a dynamic web-service URL? I thought to use: WebClient webClient = new WebClient(); UTF8Encoding response = new UTF8Encoding(); string originalStr = response.GetString(webClient.DownloadData(BLLConfig.Current); But maybe there is more elegant way? I'm loading the configs at run time from a DB table. Here is how I tried to use a web-reference in Visual Studio: using (var client = new GetTemplateParamSoapClient("GetTemplateParamSoap")) { TemplateParamsKeyValue[] responsArray = client.GetTemplatesParamsPerId(CtId, tempalteIds.ToArray()); foreach (var pair in responsArray) { string value = FetchTemplateValue(pair.Key, pair.Value); TemplateComponentsData.Add(pair.Key, value); } } A: You can add the URL of the web service as a Web Reference in Visual Studio and then set the Service.URL property to the value from the config A: .NET has lots of built-in support for consuming web services... after adding the service reference to your project it generates the necessary code... whcih you can use as is - if you need to configure the URL the generated client class has a URL property which you can set accordingly... for an excellent walkthrough see http://johnwsaunders3.wordpress.com/2009/05/17/how-to-consume-a-web-service/ and see SOAP xml client - using Visual Studio 2010 c# - how?
{ "language": "en", "url": "https://stackoverflow.com/questions/7571253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get drupal webform module submitted value programmatically? I want to get the Webform submitted value using Webform module API. How can I do that? A: I've got these link regarding webform hooks Working with the Webform API (version 3.x only) that contain these links http://drupalcode.org/project/webform.git/blob/HEAD:/webform_hooks.php http://api.lullabot.com/file/contrib/webform/webform_hooks.php A: Custom coding: Adding advanced validation or submit code - Investigate $form_state structure via print_r or dsm (devel module) and find your submitted data in mywebform_extra_submit_44 function. A: Here is how I did it, the form was just an email address. function mymodule_webform_submission_insert($node, $submission) { $value = array_shift($submission->data); $value = array_shift($value['value']); //$value is now the first value entered (in the case of multi-entry fields) or only value entered } Both node and submission are stdClass objects. (Done in drupal 6)
{ "language": "en", "url": "https://stackoverflow.com/questions/7571256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Count number of operators in an expression - Cannot infer instance I'm working on a function that can count the number of operators used in an expression. My code is as follows: data Expr = Lit Int | Expr :+: Expr | Expr :-: Expr size :: Expr -> Int size (Lit n) = 0 size (e1 :+: e2) = 1 + (size e1) + (size e2) size (e1 :-: e2) = 1 + (size e1) + (size e2) But when I try to execute this code using Hugs98 i get the following error: Main> size 2+3 ERROR - Cannot infer instance *** Instance : Num Expr *** Expression : size 2 + 3 Can somebody tell me what I'm doing wrong? I'm really out of idea's myself. A: 2+3 is not a valid expression. With your types, primtive values are created using the Lit data constructor, and the valid operators are :+: and :-:. So what you really need is Lit 2 :+: Lit 3. So try size (Lit 2 :+: Lit 3) A: You can make it a Num instance: instance Num Expr where (+) = (:+:) (-) = (:-:) negate = (0 -) fromInteger = Lit . fromInteger (*) = error "not implemented" abs = error "not implemented" signum = error "not implemented" Once that is in place, size (2+3) will work (note the parenthesis).
{ "language": "en", "url": "https://stackoverflow.com/questions/7571259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Need to exclude a dependency from eclipse using a gradle build file I'm trying to exclude a dependency, mainly "slf4j-simple" from my gradle build. It works well, but is not reflected when I run "gradle eclipse". I have the following code in my gradle build file: apply plugin:'war' apply plugin:'eclipse' apply plugin:'jetty' ... dependencies { compile 'mysql:mysql-connector-java:5.1.16' compile 'net.sourceforge.stripes:stripes:1.5' compile 'javax.servlet:jstl:1.2' ... (Rest of the dependencies) } configurations { all*.exclude group:'org.slf4j',module:'slf4j-simple' } Now, when I run 'gradle build', the slf4j-simple is excluded from the war file created which is fine. When I run 'gradle eclipse', the slf4j-simple is not excluded from the eclipse classpath. A solution to the problem is mentioned in the gradle cookbook but I don't understand how to apply it: http://docs.codehaus.org/display/GRADLE/Cookbook#Cookbook-ExcludingdependenciesfromEclipseProjects A: Try adding this to your build.gradle: eclipseClasspath{ plusConfigurations.each{ it.allDependencies.each{ it.exclude group: 'org.slf4j', module: 'slf4j-simple' } } } A: With gradle 1.0-milestone-3 I had to do a modification from rodion's answer to make it work: eclipseClasspath{ doFirst{ plusConfigurations.each{ it.allDependencies.each{ it.exclude group: 'org.slf4j', module: 'slf4j-simple' } } } } A: Using eclipseClasspath didn't work for me, but this does the trick: configurations { compile { exclude group: 'commons-logging' exclude module: 'jcl-over-slf4j' } } That excludes commons-logging from being included transitively (from the project's dependency on Spring) and also jcl-over-slf4j from being included in the Eclipse project's build path (I have a Gradle runtime dependency on jcl-over-slf4j but don't want it included on the build (compile) path. A: This works in Gradle 4.10 eclipse { classpath { file { whenMerged { cp -> cp.entries.removeAll { (it instanceof Library) && it.moduleVersion?.group == 'org.slf4j' && it.moduleVersion?.name == 'slf4j-simple' } } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7571270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Javascript SHIFT and POP on Associative Array Using a regular array I am able to grab the image src from an array using shift() and pop(); I would like to do the same thing using an associative array to add a name and id. Single Array var products = ['product1.jpg']; $('#products').append('<img src="' + products.shift() + '">'); Associative Array var products = [{id:'1',name:'product 1',image:'product1.jpg'}]; $('#products').append('<img id="' + products.shift() + '" name="' + products.shift() + '" src="' + products.shift() + '">'); A: You're using a regular array full of objects, so shift and pop will work, but return you the object. var products = [{id:'1',name:'product 1',image:'product1.jpg'}]; var prod = products.shift(); $('#products').append('<img id="' + prod.id + '" name="' + prod.name + '" src="' + prod.image + '">'); A: This line: var products = [{id:'1',name:'product 1',image:'product1.jpg'}]; declares an array with a single value inside. The single value is an object with the properties id, name, and image. When you call shift on the array, the value returned will be this object. A: var products = [{id:'1',name:'product 1',image:'product1.jpg'}]; for(var i =0; i < products.length; i++){ var product = products[i]; $('#products').append('<img id="' + product.id + '" name="' + product.name + '" src="' + product.image + '">'); } A: shift() is going to pull the whole object out of the index, not piece by piece like in your example. You would need to access the object by name to get what you want. var products = [{id:'1',name:'product 1',image:'product1.jpg'}, {id:'2',name:'product 2',image:'product2.jpg'}]; var currentProduct = products.shift(); $('#products').append('<img id="' + currentProduct.id + '" name="' + currentProduct.name + '" src="' + currentProduct.image + '">'); to loop through it while(products.length>0){ var currentProduct = products.shift(); $('#products').append('<img id="' + currentProduct.id + '" name="' + currentProduct.name + '" src="' + currentProduct.image + '">'); } better performance loop would be one write to the DOM var strOut = ""; while(products.length>0){ var currentProduct = products.shift(); strOut += '<img id="' + currentProduct.id + '" name="' + currentProduct.name + '" src="' + currentProduct.image + '">'; } $('#products').append( strOut ); A: * *You can cache the shift, and use the object's properties: var products = [{id:'1',name:'product 1',image:'product1.jpg'}]; var product = products.shift(); $('#products').append('<img id="' + product.id + '" name="' + product.name + '" src="' + product.image + '">'); *You can store the values differently, as a multi-dimensional array: var products = [['1','product 1','product1.jpg']]; var product = products.shift(); $('#products').append('<img id="' + product.shift() + '" name="' + product.shift() + '" src="' + product.shift() + '">');
{ "language": "en", "url": "https://stackoverflow.com/questions/7571272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I define string constants in C++? Possible Duplicate: C++ static constant string (class member) static const C++ class member initialized gives a duplicate symbol error when linking My experience with C++ pre-dated the addition of the string class, so I'm starting over in some ways. I'm defining my header file for my class and want to create a static constant for a url. I'm attempting this by doing as follows: #include <string> class MainController{ private: static const std::string SOME_URL; } const std::string MainController::SOME_URL = "www.google.com"; But this give me a duplicate definition during link. How can I accomplish this? A: Define the class in the header file: //file.h class MainController{ private: static const std::string SOME_URL; } And then, in source file: //file.cpp #include "file.h" const std::string MainController::SOME_URL = "www.google.com"; A: You should put the const std::string MainController::SOME_URL = "www.google.com"; definition into a single source file, not in the header. A: Move the const std::string MainController::SOME_URL = "www.google.com"; to a cpp file. If you have it in a header, then every .cpp that includes it will have a copy and you will get the duplicate symbol error during the link. A: You need to put the line const std::string MainController::SOME_URL = "www.google.com"; in the cpp file, not the header, because of the one-definition rule. And the fact that you cannot directly initialize it in the class is because std::string is not an integral type (like int). Alternatively, depending on your use case, you might consider not making a static member but using an anonymous namespace instead. See this post for pro/cons.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571278", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: JMockit NullPointerException on Exceptions block? Having already spent a lot of time on this test and unable to reason my way out of it, i have no other choice than ask for your help :) Using JMockit to test some of my own JDBC "Wrapper" classes, i came to a dead end. This is the class im testing: public class JdbcConnectionProperties { private Properties properties = new Properties(); private String username; private String password; private String connectionString; public JdbcConnectionProperties(String propertiesFilePath) { loadProperties(propertiesFilePath); } public void setProperties() { username = properties.getProperty("user"); password = properties.getProperty("password"); String connectionType = properties.getProperty("connection_type"); String serverAddress = properties.getProperty("server_address"); String port = properties.getProperty("port"); String sid = properties.getProperty("sid"); //Create a connection string connectionString = "jdbc:oracle:" + connectionType + ":@" + serverAddress + ":" + port + ":" + sid; } private void loadProperties(String propertiesFilePath) { String filePath = Thread.currentThread().getContextClassLoader().getResource(propertiesFilePath).getFile(); //Load properties from classpath try { properties.load(new FileInputStream(filePath)); } catch (IOException e) { e.printStackTrace(); } } public String getUsername() { return username; } public String getPassword() { return password; } public String getConnectionString() { return connectionString; } public Properties getProperties() { return properties; } } This is the test: public class JdbcConnectionPropertiesTest { @Test public void testSetProperties( // @Mocked final Properties properties ) throws Exception { //Mock loadFilePath method so i dont end up mocking a ton of classes new MockUp<JdbcConnectionProperties>() { @Mock void loadProperties(String propertiesFilePath) { //Doing nothing, simple "stub" method } }; JdbcConnectionProperties jdbcConnectionProperties = new JdbcConnectionProperties("bla"); // Deencapsulation.setField(jdbcConnectionProperties, "properties", properties); // Mockit.stubOutClass(JdbcConnectionProperties.class, "loadProperties"); final String username = "username"; final String password = "password"; final String connectionType = "thin"; final String serverAddress = "localhost"; final String port = "1521"; final String sid = "orcl"; String connectionString = "jdbc:oracle:" + connectionType + ":@" + serverAddress + ":" + port + ":" + sid; new Expectations() { @Mocked Properties properties; { properties.get("user"); result = username; properties.get("password"); result = password; properties.get("connection_type"); result = connectionType; properties.get("server_address"); result = serverAddress; properties.get("port"); result = port; properties.get("sid"); result = sid; } }; jdbcConnectionProperties.setProperties(); Assert.assertEquals("Incorrect user", username, jdbcConnectionProperties.getUsername()); Assert.assertEquals("Incorrect password", password, jdbcConnectionProperties.getPassword()); Assert.assertEquals("Incorrect connection string", connectionString, jdbcConnectionProperties.getConnectionString()); } } A couple of notes. I tried forsing the mocked properties into the object with Deencapsulation(i left them commented in the code). I tried just mocking it with the @Mocked annotation. I tried stubing it with stubOutClass. This is not a first test i am writing, but im relativly new to JMockit. The tests i wrote before never caused me headaches like this one. I think i wrote about 20 - 30 tests with JMockit and never had problems like this. The error is(in all the mentioned scenarios) : java.lang.NullPointerException at java.util.Hashtable.get(Hashtable.java:335) at jdbc.JdbcConnectionPropertiesTest$2.<init>(JdbcConnectionPropertiesTest.java:49) at jdbc.JdbcConnectionPropertiesTest.testSetProperties(JdbcConnectionPropertiesTest.java:44) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:71) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:199) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:62) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120) The class is very simple. The test should be very simple. But somehow the test crashes on the Expectations block(on the first properties expectation). If I comment the first ones, then it continues to throw it on next one. Tried any, anyString for argument matching. The way I see it, i mock the JdbcConnectionProperties loadProperties so i can simplify my testing. Then i pass a mocked Properties object into the test. And then... ...it should work. BTW, I never saw an exception of this magnitude in a Exceptions block. Thank you. A: Hashtable#get is one of a few methods not mocked by default by JMockit, because it can interfere with the JDK or with JMockit itself when mocked. You can get this particular test to work by explicitly asking for it to be mocked, with @Mocked("get"). It might be simpler to just use an actual ".properties" file in the test, though, with no mocking. A: new Expectations() { @Mocked("getProperty") Properties properties; { properties.getProperty("user"); result = username; properties.getProperty("password"); result = password; properties.getProperty("connection_type"); result = connectionType; properties.getProperty("server_address"); result = serverAddress; properties.getProperty("port"); result = port; properties.getProperty("sid"); result = sid; } }; Thanks Rogerio. As he pointed out, the reason is the "internal" class mocking. A very small limitation to have in mind. The other classes that require some attention are(i hope i can write this):
{ "language": "en", "url": "https://stackoverflow.com/questions/7571284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Looking for tools on Sexp expressions in Ruby I am a recent fan of s-exp expressions in Ruby. I discovered Sexpistol parser for instance. Are you using other dedicated tools around them (schemas etc ) ? A: You might check out Lispy: https://github.com/ryan-allen/lispy It's no quite s-expressions, but similar in concept.. A: I've been rolling my own handlers for s-expressions in Ruby, but I'm loving the relative ease with which they can be manipulated. If you haven't seen Ruby's built-in Ripper library yet, it's worth checking out: > require 'ripper' > Ripper.sexp("1 + 1") => [:program, [[:binary, [:@int, "1", [1, 0]], :+, [:@int, "1", [1, 4]]]]] A: The fastest lib available is sfsexp (the small, fast s-expression library). It is written in C with Ruby bindings that you can see in action in the API Doc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Move value from local stack to heap? (C++) How can I take an object-as-value result from a method call and place it on the heap? For instance: The Qt QImage::scaledToWidth method returns a copy of the QImage object. Right now I'm doing: QImage *new_img_on_heap = new QImage(old_imgage_on_heap->scaledToWidth(2000)); Is this the only way? Seems like it's going through the trouble of making a 3rd whole new object when I already have a perfect good one on the stack. The reason I want to put it on the heap is because the real QImage is large, and I want it to outlive the lifetime of the current method. I was intending to stuff a pointer to it in a field of my class. I know that QImage has some sort of implicit data sharing, but I'm not exactly clear on how it works under the hood. Plus, I wanted to know a general solution should I ever need to use objects not as well designed as Qt's. A: Firstly, you should prefer the stack to the heap in most cases. Secondly, when you allocate objects on the heap you should wrap the raw pointer in some managed object which is on the stack. If for nothing else, do it for exception safety. Thirdly, Qt objects usually do exactly that i.e. there's no advantage in writing new QImage or new QMap<int> etc. Nevertheless the right way to move a non-heap object onto the heap is to say new ObjectType (old_instance) If you do this with a temporary object, such as new ObjectType (create_object ()) then it will probably elide the extra copy (link broken for me -- cached) A: An object is identified by its address. If you want it at another address, you have to construct a new one; you can't move objects. (Even with C++11, the new “move” semantics don't actually move an object; they provide an optimized way of moving its value, if you know that you won't need the value from where you're moving it.) A: Since the method QImage QImage::scaledToWidth ( int width, Qt::TransformationMode mode = Qt::FastTransformation ) const does not return a QImage address (i.e. QImage& ....) than I think you are out of luck. You are stuck with a copy. Unless you want to recompile the QT libraries to change that function signature so that it does not return a copy. What is so bad about having that object on the stack anyways? A: You can try following trick. Idea is to put your value to some structure and construct structure in heap. In this case copy elision works. No copies or moves are performed. Unfortunately it does not work on VS2017. But it works in G++ 8+ and probably in VS2019. #include <memory> struct C{ C() = default; C( C&& ) = delete; C( C const& ) = delete; C& operator=( C&& ) = delete; C& operator=( C const& ) = delete; }; C foo() { return C {}; } struct X { C c; X() : c (foo()) // here is how trick works { } }; int main() { auto x = std::make_unique<X>(); } A: The premise of this question/ask is incorrect in that it assumes that the image data for QImage has the same lifetime of the QImage object itself. The reason I want to put it on the heap is because the real QImage is large, and I want it to outlive the lifetime of the current method. I was intending to stuff a pointer to it in a field of my class. This statement is not correct as it would be a VERY BAD thing for something like QImage, and very quickly fail by popping "stack" limits. It would also make assignments very slow! Rather, QImage, like many C++ objects that deal with large and/or external data, is effectively a wrapper around internally managed memory of a different lifetime. This can be seen in the QImage source code; QImage contains QImageData, and QImageData malloc's the internal buffer independently of the original QImage's lifetime. As the bulk of the data is "outside" of QImage, there is little reason to prefer new QImage instead of using QImage and auto lifetimes for sake of the (incorrectly perceived) storage duration of the image data; QImage implements copy and move sanely*, so that all underlying image data (and underlying allocation of such) is shared. *In QImage's copy ctor the 'ref count' of the QImageData is briefly extended until the destruction of the previous object, while in the move the QImageData's lifetime could be directly transferred (in comment, missing from that source?). Regardless, neither case actually makes a copy of the underlying image data which would be expensive. So, to answer the question: new X(non_ptr_X), and let the properly written constructors/design do their thing, which is an implementation detail; and hopefully one of agreeable performance characteristics. YMMV.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: Binding to instance of ItemsSource I have a ListBox on a WPF User Control that is defined as <ListBox Grid.Row="1" ScrollViewer.CanContentScroll="False" Background="#00000000" BorderThickness="0" ItemsSource="{Binding BuyItNowOptions}" ItemTemplate="{DynamicResource BuyItNowDataTemplate}" IsSynchronizedWithCurrentItem="True" Style="{DynamicResource InheritEmptyListStyle}" SelectedItem="{Binding SelectedResearch}" ItemContainerStyle="{DynamicResource ListBoxItemStyle}"/> BuyItNowOptions is a public property on the ViewModel that is of type ObservableCollection In the BuyItNowDataTemplate I have a label that needs to have some logic performed before displaying a price. <Label Padding="1" HorizontalContentAlignment="Stretch" Grid.Column="2" Grid.Row="2" Margin="1"> <TextBlock Text="{Binding ExchangePrice, StringFormat=C}" Visibility="{Binding ReturnRequired, Converter={StaticResource BooleanToVisibilityConverter}}"/> </Label> The binding here indicates that it will use the ExchangePrice property of the instance of AutoResearchProxy that it is on like BuyItNowOptions[CurrentIndex].ExchangePrice. What I would like to know is it possible to create the binding in such a way that it references the whole instance of the AutoResearchProxy so that I can pass it to a converter and manipulate several properties of the AutoResearchProxy and return a calculated price? I would envision my converter looking like this. public class PriceConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value is AutoResearchProxy) { var research = value as AutoResearchProxy; //Some logic to figure out actual price } else return String.Empty; } Hopefully this makes sense. A: MyProperty="{Binding Converter={StaticResource ObjectToDerivedValueConverter} That should do it. A: You can pass the whole datacontext-object to a Binding by not specifying a Path or by setting it to ., that however will result in the binding not updating if any of the relevant properties of that object change. I would recommend you use a MultiBinding instead, that way you can target the necessary properties and the binding will update if any of those change. (For usage examples see the respective section on MSDN)
{ "language": "en", "url": "https://stackoverflow.com/questions/7571296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Set the DataContext of a ViewModel in MVVMLight I've got a question of the MVVM-Pattern. So I'm not sure, that I've had understand it completely. My scenario: * *ViewModelLocator : Provide the requested ViewModel to a specified view. *LoginViewModel: ViewModel for the LoginView *MainPageViewModel: ViewModel for the MainPageView My example app. is simple: The user can login and comes to the MainPageView. The MainPageView uses the MainPageViewModel. I use the messenger of the MVVMLight framework to navigate from the LoginView to the MainPageView. Messenger.Default.Register<LoginPerson>(this, Constants.NavigateLogin, person => this.Window.SetContentControl(new MainPage(person))); I pass the loggedin person to the View. The MainPage - View will set the the logged in person to its ViewModel (=> MainPageViewModel). Is this way correct? I don't think so :-) How can I communicate between the ViewModels? Thanks for your advices. Regards, pro A: When using MVVM, your application is your ViewModels, not your Views. You should not be handling any kind of business logic such as navigation or passing User objects around from your Views. The View is simply a pretty layer that allows the user's to interact with your ViewModels easily. Usually in this kind of situation I use a ShellViewModel which contains a CurrentPage property that is set to whatever ViewModel is the CurrentPage. I would store a CurrentUser property in the ShellViewModel as well. Your ShellViewModel is your startup object, and on startup the CurrentPage would be a LoginViewModel. When the user successfully logs in, the LoginViewModel broadcasts a LoginSuccessful message with a parameter of the CurrentUser, and the ShellViewModel would pickup that message and set the CurrentUser based on the message parameters, and would switch CurrentView to a new MainPageViewModel For an example, check out my post here
{ "language": "en", "url": "https://stackoverflow.com/questions/7571297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: This cobol Grammar doesn't handle --9 picture I'm using the grammar on this site in my javacc. It works fine apart from some picture statements. For example ----,---,---.99 or --9. http://mapage.noos.fr/~bpinon/cobol.jj It doesn't seem to like more than one dash. What do I need to change in this to support my picture examples. I'v messed about with void NumericConstant() : {} { (<PLUSCHAR>|<MINUSCHAR>)? IntegerConstant() [ <DOTCHAR> IntegerConstant() ] } but nothing seems to be working. Any help is much appreciated EDIT: <COBOL_WORD: ((["0"-"9"])+ (<MINUSCHAR>)*)* (["0"-"9"])* ["a"-"z"] ( ["a"-"z","0"-"9"] )* ( (<MINUSCHAR>)+ (["a"-"z","0"-"9"])+)* > Is this the regular expression for this whole line: 07 STRINGFIELD2 PIC AAAA. ?? If I want to accept 05 TEST3 REDEFINES TEST2 PIC X(10). would I change the regex to be: <COBOL_WORD: ((["0"-"9"])+ (<MINUSCHAR>)*)* (<REDEFINES> (["0"-"9"])* ["a"-"z"] ( ["a"-"z","0"-"9"] )*)? (["0"-"9"])* ["a"-"z"] ( ["a"-"z","0"-"9"] )* ( (<MINUSCHAR>)+ (["a"-"z","0"-"9"])+)* Thanks a lot for the help so far A: Why are you messing around with NumericConstant() when you are trying to parse a COBOL PICTURE string? According to the JavaCC source you have, a COBOL PICTURE should parse with: void DataPictureClause() : {} { ( <PICTURE> | <PIC> ) [ <IS> ] PictureString() } the --9 bit is a Picture String and should parse with the PictureString() function: void PictureString() : {} { [ PictureCurrency() ] ( ( PictureChars() )+ [ <LPARENCHAR> IntegerConstant() <RPARENCHAR> ] )+ [ PicturePunctuation() ( ( PictureChars() )+ [ <LPARENCHAR> IntegerConstant() <RPARENCHAR> ] )+ ] } PictureCurrency() comes up empty so move on to PictureChars(): void PictureChars() : {} { <INTEGER> | <COBOL_WORD> } But COBOL_WORD does not appear to support many "interesting" valid PICTURE clause definitions: <COBOL_WORD: ((["0"-"9"])+ (<MINUSCHAR>)*)* (["0"-"9"])* ["a"-"z"] ( ["a"-"z","0"-"9"] )* ( (<MINUSCHAR>)+ (["a"-"z","0"-"9"])+)* > Parsing COBOL is not easy, in fact it is probably one of the most difficult languages in existance to build a quality parser for. I can tell you right now that the JavaCC source you are working from is not going to cut it - except for some very simple and probably totally artificial COBOL program examples. Answer to comment COBOL Picture strings tend to mess up the best of parsers. The minus sign you are having trouble with is only the tip of the iceburg! Picture Strings are difficult to parse through because the period and comma may be part of a Picture string but serve as separators outside of the string. This means that parsers cannot unambiguously classify a period or comma in a context free manner. They need to be "aware" of the context in which it is encountered. This may sound trivial but it isn't. Technically, the separator period and comma must be followed by a space (or end of line). This little fact could make determining the period/comma role very simple because a Picture String cannot contain a space. However, many commercial COBOL compilers are "smart" enough correctly recognize separator periods/commas that are not followed by a space. Consequently there are a lot of COBOL programmers that code illegal separator period/commas, which means you will probably have to deal with them. The bottom line is that no matter what you do, those little Picture Strings are going to haunt you. They will take quite a bit of effort to to deal with. Just a hint of things to come, how would you parse the following: 01 DISP-NBR-1 PIC -99,999. 01 DISP-NBR-2 PIC -99,999.. 01 DISP-NBR-3 PIC -99,999, . 01 DISP-NBR-4 PIC -99,999,. The period following DISP-NBR-1 terminates the Picture string. It is a separator period. The period following DISP-NBR-2 is part of the string, the second period is the separator. The comma following DISP-NBR-3 is a separator - it is not part of the Picture string. However the comma following DISP-NBR-4 is part of the Picture string because it is not followed by a space. Welcome to COBOL! A: I found that I had to switch the lexer into another mode when I got PICTURE. A COBOL PICTURE string has completely different 'lexics' from the rest of the language, and you must discourage the lever from doing anything with periods, commas, etc, other than accumulate them into the picture string. See NealB's answer for some examples of knowing when to stop picture-scanning. I have no idea why you want to incorporate the REDEFINES phrase into the word. Just parse it normally in the parser.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to align a div bottom of a dynamic div I have a div called content which comes as an ajax content. so how to align a div called footer after the ajax content has loaded using jquery? A: Use absolute positioning. Set the bottom: property instead of top: A: Have you parent div be position: relative and the child div be position: absolute. From there, it's pretty simple. .parent { position: relative; } .child { position: absolute; bottom: 0px; left: 0px; right: 0px; height: 20px; /*or whatever you want the height to be*/ display: block; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7571305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Specifying system properties in Grails 2.0 interactive mode Is there a way how to specify system property in (already started) grails interactive mode ? For example I would specify environment in command line: grails -Dgrails.env=staging run-app but in interactive mode it is not possible this way (since JVM is already started): grails grails> -Dgrails.env=staging run-app A: This seems to work in Grails 1.3.7 interactive mode. Add a script to your Grails application at scripts/SetProperty.groovy: includeTargets << grailsScript('_GrailsArgParsing') target (default:'Set a system property') { depends('parseArguments') if (argsMap['params'][0] && argsMap['params'][1]) { System.setProperty(argsMap['params'][0], argsMap['params'][1]) } else { println 'You must define a property to set' } } Then in interactive mode set-property grails.env staging.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What's the fundamental difference between those two constructs? Possible Duplicate: Difference between method and function in Scala scala> val x1 : (Int) => Int = (x) => x + 1 x1: (Int) => Int = <function> scala> def x2 (x : Int) = x + 1 x2: (Int)Int scala> x1(1) res0: Int = 2 scala> x2(1) res1: Int = 2 What's the actual difference between x1 and x2 . Can you please give me examples when to use those two constructs ? A: In Scala, these are two construct that looks similar from user's perspective but totally different from JVM's perspective. x1 is a "function object" and x2 is a method. Code Example class Test { val x1 = (x: Int) => x + 3 def x2(x: Int) = { def x3(y: Int) = y + 10 x3(x) + 3 } } Method In Scala, def defines a method that directly compile to a JVM method, and it must belong to some Java class. In the above code snippet, both x2 and x3 are compiled to a JVM method, and belongs to the class Test, even x3 is defined inside a method (nested method). You could verify this by using javap -private Test after compile the code. And it will output the following mesage: brianhsu@USBGentoo ~/test $ javap -private Test Compiled from "test.scala" public class Test extends java.lang.Object implements scala.ScalaObject{ private final scala.Function1 x1; public scala.Function1 x1(); public int x2(int); private final int x3$1(int); public Test(); } You could see that x2 is just an ordinary Java method, and x3 being renamed to x3$1 (to avoid name conflict if there is another x3 in other method`), but it still an normal Java method from JVM's point of view. Function Object I use this term to avoid confuse, this is what you defined with something like val x1 = (x: Int) => x + 1. It may looks like method when you use it, but in fact it is totally different from the method you defined with defs. Then what does val x1 = (x: Int) => x + 2 means? Well, there is traits that called Function0, Function1, Function2, Function3...Function22 in Scala. It both looks like the following (I've simplified it): // T1 is the type of parameter 1, R is the type of return value triat Function1[T1, R] { def apply(t1: T1): R } And when you write val x1 = (x: Int) => x + 2, the Scala compiler will generate an object that implements the trait Function1, and it may looks like the following: val t = new Function1[Int, Int] { def apply(t1: Int) = t1 + 2 } And when you write x1(3), in fact the Scala is just convert it to t.apply(3). So, an function object is not a method, it is just an ordinary Java object that has a method called apply, And the Scala compiler give you a syntax sugar that don't have to explicit call apply when you use them. You could verify this by using javap again. brianhsu@USBGentoo ~/test $ javap Test\$\$anonfun\$1 Compiled from "test.scala" public final class Test$$anonfun$1 extends scala.runtime.AbstractFunction1$mcII$sp implements scala.Serializable{ public static final long serialVersionUID; public static {}; public final int apply(int); public int apply$mcII$sp(int); public final java.lang.Object apply(java.lang.Object); public Test$$anonfun$1(Test); } brianhsu@USBGentoo ~/test $ javap -private Test Compiled from "test.scala" public class Test extends java.lang.Object implements scala.ScalaObject{ private final scala.Function1 x1; public scala.Function1 x1(); public int x2(int); private final int x3$1(int); public Test(); } You will notice that there is an extra .class file called Test$$anonfun$1.class, that is the class of (x: Int) => x + 2, and you will notice there is an x1 private variable that is type of Function1 an a x1() method returns an scala.Function1. There is x1() method because Scala implements Uniform Access Principle. But the under hood is that x1() method just return an function object instance of Test$$anonfun$1 class. Conclusion Maybe method and function looks same, but they are different things. Scala compiler help us to use them together without a lot of effort. Most time you won't care about the difference between them, but indeed there are sometimes that something want an function object and you only have methods. In this situation, the compiler will told you that add an _ after a method name to lift it to an function object. Update Here is an interesting code example that show the differences between method and function object: You could define a method take 25 parameters, but could not define an function object that takes more than 22 parameters. class Test2 { def x ( x01: Int, x02: Int, x03: Int, x04: Int, x05: Int, x06: Int, x07: Int, x08: Int, x09: Int, x10: Int, x11: Int, x12: Int, x13: Int, x14: Int, x15: Int, x16: Int, x17: Int, x18: Int, x19: Int, x20: Int, x21: Int, x22: Int, x23: Int, x24: Int, x25: Int ) = 0 // Compile error: // implementation restricts functions to 22 parameters /* val y = ( x01: Int, x02: Int, x03: Int, x04: Int, x05: Int, x06: Int, x07: Int, x08: Int, x09: Int, x10: Int, x11: Int, x12: Int, x13: Int, x14: Int, x15: Int, x16: Int, x17: Int, x18: Int, x19: Int, x20: Int, x21: Int, x22: Int, x23: Int, x24: Int, x25: Int ) => 0 */ }
{ "language": "en", "url": "https://stackoverflow.com/questions/7571319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Using Cubeset To Create Top 10 Items List For a Specified Time Period I am using Excel 2010 to create a list of the top 10 vendors by sales during a specified time period. The catch is that I need to consider only customers that are a member of a particular set. I found this article which has helped me get the Top 10 vendors for sales from all customers, but I'm struggling with how to sum only over the members of a particular set. I tried the Sum/CrossJoin example that is further down the page in the comments, but I was unable to get it to work. It could be that I'm pretty new at this and just don't understand which pieces need to go where. Here is what I have so far (my connection name is in cell M1): All Customers (works perfectly): =CUBESET($M$1, "TopCount( [Product].[Brand].Children, 10, Sum( [Time].[Calendar].[Calendar Month].&[2011]&[8], [Measures].[Revenue] ) )", "Top 10 Brands" ) Subset of Customers (appears to return correct set): =CUBESET($M$1, "Intersect( Intersect( exists( [Customer].[Cust Num].Members, {[Customer].[Is Internal].&[False],[Customer].[Is Internal].[All].UNKNOWNMEMBER} ), exists( [Customer].[Cust Num].Members, [Customer].[Type].&[CAT] ), ALL ), exists( [Customer].[Cust Num].Members, [Market].[Market ID].[All].Children - [Market].[Market ID].&[3] - [Market].[Market ID].&[4] ), ALL )", "Cust Group" ) Any help and/or guidance would be greatly appreciated.....thanks in advance! A: You could try something like this =CUBESET($M$1, "TopCount( [Product].[Brand].Children, 10, Sum( ( [Time].[Calendar].[Calendar Month].&[2011]&[8], [Customer].[Is Internal].&[False], [Customer].[Type].&[CAT] ), [Measures].[Revenue] ) )", "Top 10 Brands" )
{ "language": "en", "url": "https://stackoverflow.com/questions/7571321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: mysql not in issue I have a select statement that I am trying to build a list of scripts as long as the users role is not in the scripts.sans_role_priority field. This works great if there is only one entry into the field but once I add more than one the whole function quits working. I am sure I am overlooking something simple, just need another set of eyes on it. Any help wold be appreciated. script: SELECT * FROM scripts WHERE active = 1 AND homePage='Y' AND (role_priority > 40 OR role_priority = 40) AND (40 not in (sans_role_priority) ) ORDER BY seq ASC data in scripts.sans_role_priority(varchar) = "30,40". Additional testing adds this: When I switch the values in the field to "40, 30" the select works. Continuing to debug... A: Maybe you are looking for FIND_IN_SET(). SELECT * FROM scripts WHERE active = 1 AND homePage='Y' AND (role_priority > 40 OR role_priority = 40) AND NOT FIND_IN_SET('40', sans_role_priority) ORDER BY seq ASC Note that having "X,Y,Z" as VARCHAR values in some fields reveals that your DB schema may be improved in order to have X, Y and Z stored as separate values in a related table. A: SELECT * FROM scripts WHERE active = 1 AND homePage='Y' AND role_priority >= 40 AND NOT FIND_IN_SET(40,sans_role_priority) ORDER BY seq ASC See: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set Note that CSV in databases is just about the worst antipattern you can find. It should be avoided at all costs because: * *You cannot use an index on a CSV field (at least not a mentally sane one); *Joins on CSV fields are a major PITA; *Selects on them are uber-slow; *They violate 1NF. *They waste storage. Instead of using a CSV field, consider putting sans_role_priority in another table with a link back to scripts. table script_sans_role_priority ------------------------------- script_id integer foreign key references script(id) srp integer primary key (script_id, srp) Then the renormalized select will be: SELECT s.* FROM scripts s LEFT JOIN script_sans_role_priority srp ON (s.id = srp.script_id AND srp.srp = 40) WHERE s.active = 1 AND s.homePage='Y' AND s.role_priority >= 40 AND srp.script_id IS NULL ORDER BY seq ASC A: SELECT * FROM scripts WHERE active = '1' AND homePage='Y' AND role_priority >= '40' AND sans_role_priority <> '40' ORDER BY seq ASC
{ "language": "en", "url": "https://stackoverflow.com/questions/7571322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Error using UTL_MAIL in a SQL procedure I am attempting to send an email using a sql procedure, and am getting some errors. Here is my relevant code: IF cur_email%FOUND THEN stu_email := schema.get_person_email_adr(v_id); IF send_email = 'Y' THEN UTL_MAIL.SEND (sender => v_email_from, -- line of error recipients => stu_email, subject => v_email_subject, mime_type => 'text/html', message => v_email_body ); END IF; END IF; I will be getting multiple "v_id", and am trying to send an email to each one that I get, so I was also wondering if I am doing that correctly? The error that I am getting is this: PLS-00201: identifier 'UTL_MAIL' must be declared I am not sure why I am encountering this, Before I made some of these changes, I never received this error, so I believe that the utl_mail set up is not the problem. Thanks! A: UTL_MAIL is not installed by default, because it requires some configuring on the part of the sysadmin team. Find out more. So, perhaps it has not been installed, or perhaps EXECUTE privilege on it has not been granted to your stored procedure owner.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why does dividing two int not yield the right value when assigned to double? How come that in the following snippet int a = 7; int b = 3; double c = 0; c = a / b; c ends up having the value 2, rather than 2.3333, as one would expect. If a and b are doubles, the answer does turn to 2.333. But surely because c already is a double it should have worked with integers? So how come int/int=double doesn't work? A: When you divide two integers, the result will be an integer, irrespective of the fact that you store it in a double. A: c is a double variable, but the value being assigned to it is an int value because it results from the division of two ints, which gives you "integer division" (dropping the remainder). So what happens in the line c=a/b is * *a/b is evaluated, creating a temporary of type int *the value of the temporary is assigned to c after conversion to type double. The value of a/b is determined without reference to its context (assignment to double). A: In C++ language the result of the subexpresison is never affected by the surrounding context (with some rare exceptions). This is one of the principles that the language carefully follows. The expression c = a / b contains of an independent subexpression a / b, which is interpreted independently from anything outside that subexpression. The language does not care that you later will assign the result to a double. a / b is an integer division. Anything else does not matter. You will see this principle followed in many corners of the language specification. That's juts how C++ (and C) works. One example of an exception I mentioned above is the function pointer assignment/initialization in situations with function overloading void foo(int); void foo(double); void (*p)(double) = &foo; // automatically selects `foo(fouble)` This is one context where the left-hand side of an assignment/initialization affects the behavior of the right-hand side. (Also, reference-to-array initialization prevents array type decay, which is another example of similar behavior.) In all other cases the right-hand side completely ignores the left-hand side. A: The / operator can be used for integer division or floating point division. You're giving it two integer operands, so it's doing integer division and then the result is being stored in a double. A: This is technically a language-dependent, but almost all languages treat this subject the same. When there is a type mismatch between two data types in an expression, most languages will try to cast the data on one side of the = to match the data on the other side according to a set of predefined rules. When dividing two numbers of the same type (integers, doubles, etc.) the result will always be of the same type (so 'int/int' will always result in int). In this case you have double var = integer result which casts the integer result to a double after the calculation in which case the fractional data is already lost. (most languages will do this casting to prevent type inaccuracies without raising an exception or error). If you'd like to keep the result as a double you're going to want to create a situation where you have double var = double result The easiest way to do that is to force the expression on the right side of an equation to cast to double: c = a/(double)b Division between an integer and a double will result in casting the integer to the double (note that when doing maths, the compiler will often "upcast" to the most specific data type this is to prevent data loss). After the upcast, a will wind up as a double and now you have division between two doubles. This will create the desired division and assignment. AGAIN, please note that this is language specific (and can even be compiler specific), however almost all languages (certainly all the ones I can think of off the top of my head) treat this example identically. A: For the same reasons above, you'll have to convert one of 'a' or 'b' to a double type. Another way of doing it is to use: double c = (a+0.0)/b; The numerator is (implicitly) converted to a double because we have added a double to it, namely 0.0. A: This is because you are using the integer division version of operator/, which takes 2 ints and returns an int. In order to use the double version, which returns a double, at least one of the ints must be explicitly casted to a double. c = a/(double)b; A: Here it is: a) Dividing two ints performs integer division always. So the result of a/b in your case can only be an int. If you want to keep a and b as ints, yet divide them fully, you must cast at least one of them to double: (double)a/b or a/(double)b or (double)a/(double)b. b) c is a double, so it can accept an int value on assignement: the int is automatically converted to double and assigned to c. c) Remember that on assignement, the expression to the right of = is computed first (according to rule (a) above, and without regard of the variable to the left of =) and then assigned to the variable to the left of = (according to (b) above). I believe this completes the picture. A: With very few exceptions (I can only think of one), C++ determines the entire meaning of an expression (or sub-expression) from the expression itself. What you do with the results of the expression doesn't matter. In your case, in the expression a / b, there's not a double in sight; everything is int. So the compiler uses integer division. Only once it has the result does it consider what to do with it, and convert it to double. A: The important thing is one of the elements of calculation be a float-double type. Then to get a double result you need to cast this element like shown below: c = static_cast<double>(a) / b; or c = a / static_cast(b); Or you can create it directly:: c = 7.0 / 3; Note that one of elements of calculation must have the '.0' to indicate a division of a float-double type by an integer. Otherwise, despite the c variable be a double, the result will be zero too (an integer).
{ "language": "en", "url": "https://stackoverflow.com/questions/7571326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "136" }
Q: How do you decouple a web service that requires an authheader on every call? I have a service reference to a .NET 2.0 web service. I have a reference to this service in my repository and I want to move to Ninject. I've been using DI for some time now, but haven't tried it with a web service like this. So, in my code, the repository constructor creates two objects: the client proxy for the service, and an AuthHeader object that is the first parameter of every method in the proxy. The AuthHeader is where I'm having friction. Because the concrete type is required as the first parameter on every call in the proxy, I believe I need to take a dependency on AuthHeader in my repository. Is this true? I extracted an interface for AuthHeader from my reference.cs. I wanted to move to the following for my repository constructor: [Inject] public PackageRepository(IWebService service, IAuthHeader authHeader) { _service = service; _authHeader = authHeader; } ...but then I can't make calls to my service proxy like _service.MakeSomeCall(_authheader, "some value"). ...because because MakeSomeCall is expecting an AuthHeader, not an IAuthHeader. Am I square-pegging a round hole here? Is this just an area where there isn't a natural fit (because of web service "awesomeness")? Am I missing an approach? A: It's difficult to understand exactly what the question is here, but some general advice might be relevant to this situation: * *Dependency injection does not mean that everything has to be an interface. I'm not sure why you would try to extract an interface from a web service proxy generated from WSDL; the types in the WSDL are contracts which you must follow. This is especially silly if the IAuthHeader doesn't have any behaviour (it doesn't seem to) and you'll never have alternate implementations. *The reason why this looks all wrong is because it is wrong; this web service is poorly-designed. Information that's common to all messages (like an authentication token) should never go in the body where it translates to a method parameter; instead it should go in the message header, wherethe ironically-named AuthHeader clearly isn't. Headers can be intercepted by the proxy and inspected prior to executing any operation, either on the client or service side. In WCF that's part of the behavior (generally ClientCredentials for authentication) and in legacy WSE it's done as an extension. Although it's theoretically possible to do this with information in the message body, it's far more difficult to pull off reliably. *In any event, what's really important here isn't so much what your repository depends on but where that dependency comes from. If your AuthHeader is injected by the kernel as a dependency then you're still getting all the benefits of DI - in particular the ability to have this all registered in one place or substitute a different implementation (i.e. a derived class). So design issues aside, I don't think you have a real problem in your DI implementation. If the class needs to take an AuthHeader then inject an AuthHeader. Don't worry about the exact syntax and type, as long as it takes that dependency as a constructor argument or property.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: getting out of memory error I am trying to load a 12mb txt file into memory as a HashMap to make it available for the application to use it but I am getting an OutOfMemoryError 09-27 15:42:17.560: ERROR/AndroidRuntime(19030): ... 11 more 09-27 15:42:17.560: ERROR/AndroidRuntime(19030): Caused by: java.lang.OutOfMemoryError 09-27 15:42:17.560: ERROR/AndroidRuntime(19030): at java.util.HashMap.makeTable(HashMap.java:559) 09-27 15:42:17.560: ERROR/AndroidRuntime(19030): at java.util.HashMap.doubleCapacity(HashMap.java:579) 09-27 15:42:17.560: ERROR/AndroidRuntime(19030): at java.util.HashMap.put(HashMap.java:409) 09-27 15:42:17.560: ERROR/AndroidRuntime(19030): at org.com.SentencesActivity.loadBigramFrequencies(SentencesActivity.java:151) 09-27 15:42:17.560: ERROR/AndroidRuntime(19030): at org.com.SentencesActivity.onClick(SentencesActivity.java:56) Is there any way to solve it or it is a limitation of dalvik vm? Code for loading the file into memory: public HashMap<String, Double> loadBigramFrequencies() throws IOException { AssetManager assetManager = getAssets(); HashMap<String, Double> bigramFrequencies = new HashMap<String, Double>(); String[] splittedLine; try { // open the file for reading InputStream instream = assetManager.open("bigramFrequencies.txt"); // if file the available for reading if (instream != null) { // prepare the file for reading InputStreamReader inputreader = new InputStreamReader(instream); BufferedReader buffreader = new BufferedReader(inputreader); String line; // read every line of the file into the line-variable, on line // at the time while ((line = buffreader.readLine()) != null) { // do something with the settings from the file splittedLine = line.split("\\#"); bigramFrequencies.put(splittedLine[0].trim(), Double.parseDouble(splittedLine[1].trim())); } Log.v(LOG_TAG, "bigram frequencies loaded"); } // close the file again instream.close(); } catch (java.io.FileNotFoundException e) { // do something if the myfilename.txt does not exits } return bigramFrequencies; } A: Reading a 12mb file in memory will slow down the device. 12mb might sound less for a normal pc, but most Android phones come with less then 512MB of RAM. You should be able to reformat the file or split it up so the application can read the necessary parts when it needs them. Also, using a SQLite Database might be better suited an speed up the whole thing. A: A HashMap in the application had an item added to it, and in doing so hit its limit for the current array backing. So, it attempted to resize and in doing so it ran out of memory. HashMaps use hashes to jump to a particular element in an array, then it looks for the item in the backing store. The entire algorithm depends heavily on the array being sparse enough to avoid excessive collision of the hash space (the hash divided modulus by the array size). If you add a lot to a hash oriented structure, it needs to allocate a bigger array to maintain enough empty array elements for the performance to not degrade horribly. After the allocation of the new array, each element from the old array is relocated into the new array. This effectively adds "empty slots" for other items to utilize. A: If device has adequate Memory then Try increasing the heap size available to app. Edit the build.prop file and increase the heap size dalvik.vm.heapsize=32m
{ "language": "en", "url": "https://stackoverflow.com/questions/7571331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to track down the actual code that causes this memory leak, in Xcode? I am having a dickens of a time trying to find the code that causes the memory leak you see in this image: In Xcode, how to you go from this information in Instruments to finding the actual code? When I run Analyze, I do not get any warnings about memory leaks, but clearly something is leaking. I cannot double click on this logged line in Instruments to get to the line of code, there just doesn't seem to be anyway to track it down. I hope someone can provide the obvious solution that I am missing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to compare two objects in generic implementation? I have a generic class which will be Long, Float, Integer and String types. In the cases of Number (Long, Float and Integer), I want to compare two of them to see which one is bigger or smaller. Is it possible? A: Its possible with a moderately complex Comparator implementation and liberal use of the 'instanceof' keyword. http://download.oracle.com/javase/6/docs/api/java/util/Comparator.html A: the easiest way would be to implement the Comparable interface in your subclasses. A: If you only need that for numbers, just compare them as "values" with the same data type (the proper methods for this are provided by the java.lang.Number class). So you can do: Double.compare( number1.doubleValue(), number2.doubleValue() ) where number1 and number2 are different types of numbers. The Comparable interface is implemented by all the numeric primitive wrappers but they can only compare numbers of the same type. For instance Integer implements Comparable<Integer>, so the compareTo method won't accept other numeric types.
{ "language": "en", "url": "https://stackoverflow.com/questions/7571337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Changing hostname in Shindig's container I'm using Shindig 2.0 with its default container. When the container renders the gadget, it calls the servlet: /gadgets/ifr?url=http://iltlvl094:8080/sample-gadget/spec.xml&libs=rpc&parent=http://iltlvl094&debug=1&#rpctoken=54612318 This servlet returns HTML code that imports JavaScript file from localhost: <script src="http://localhost:8080/gadgets/js/rpc.js?container=default&amp;nocache=0&amp;debug=1&amp;c=0&amp;v=249039fb66d20be125366df4d5ec26c2"></script> Why it's referring localhost and not the actual hostname - iltlvl094? Where I can change it? I'm using Shindig out of the box, thus I don't have any source code or configuration files to modify. Maybe I can do this via command line arguments? Thanks, Tomer A: I found out how I can do that. There are two ways: * *Add system property: -Dshindig.host=my_host -Dshindig.port=my_port *Add to the web.xml: shindig.host=my_host and shindig.port=my_port
{ "language": "en", "url": "https://stackoverflow.com/questions/7571338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }