text
stringlengths
8
267k
meta
dict
Q: time_t conversion format question I am trying to make an easily accessible TimeDate variable, but am having problems with conversion. In time.h, how would I convert time_t (seconds since 1/1/1970), into the current local timezone (compensating for daylight savings time if applicable), so that: time_t Seconds; Becomes: struct TimeDate { short YYYY; unsigned char MM; unsigned char DD; unsigned char HH; //Non-DST, non-timezone, IE UTC (user has to add DST and TZO to get what they need) unsigned char MM; unsigned char S; char TZ[4]; //This can be optionally a larger array, null terminated preferably char TZO; //Timezone Offset from UTC char DST; //Positive is DST (and amount of DST to apply), 0 is none, negative is unknown/error }; Without using any string literals (bar for the timezone name) in the process (to keep it efficient)? This is also taking into account leap years. Bonus if TimeDate can be converted back into time_t. A: The C standard library (accessible in C++ by using ctime) provides localtime for exactly that purpose (or gmtime for UTC). You could shoe-horn the resultant struct tm into your own structure after that if there's some reason why the standard one is not sufficient to your needs. The one thing it doesn't provide is the timezone itself but you can get that (and the offset in ISO 8601 format) by using strftime with the %Z and %z format strings By way of example, here's a program that demonstrates this in action: #include <iostream> #include <cstdlib> #include <ctime> int main(void) { time_t t; struct tm *tim; char tz[32]; char ofs[32]; std::system ("date"); std::cout << std::endl; t = std::time (0); tim = std::localtime (&t); std::strftime (tz, sizeof (tz), "%Z", tim); std::strftime (ofs, sizeof (ofs), "%z", tim); std::cout << "Year: " << (tim->tm_year + 1900) << std::endl; std::cout << "Month: " << (tim->tm_mon + 1) << std::endl; std::cout << "Day: " << tim->tm_mday << std::endl; std::cout << "Hour: " << tim->tm_hour << std::endl; std::cout << "Minute: " << tim->tm_min << std::endl; std::cout << "Second: " << tim->tm_sec << std::endl; std::cout << "Day of week: " << tim->tm_wday << std::endl; std::cout << "Day of year: " << tim->tm_yday << std::endl; std::cout << "DST?: " << tim->tm_isdst << std::endl; std::cout << "Timezone: " << tz << std::endl; std::cout << "Offset: " << ofs << std::endl; return 0; } When I run this on my box, I see: Wed Sep 28 20:45:39 WST 2011 Year: 2011 Month: 9 Day: 28 Hour: 20 Minute: 45 Second: 39 Day of week: 3 Day of year: 270 DST?: 0 Timezone: WST Offset: +0800
{ "language": "en", "url": "https://stackoverflow.com/questions/7582263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using hyphen or underscore as word separator for files under Linux I get always confused when I have to give a new name for a new data or executable file under linux, to use underscore or the dash to separate words in the name. My question: Are there any standard or guide to follow to know when to use this or that? A: $ ls /usr/bin/*_* | wc -l 120 $ ls /usr/bin/*-* | wc -l 717 Some files are actually duplicated in both lists: x86_64-linux-gnu-cpp, but you probably get the idea that there are more dashes that underscores. Additionally there are files where there is no separation whatsoever as in atktopbm, bdftruncate... not really standard it seems.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to convert String to double in JSP I'm extracting some results in the table in JPS like this : <tr> <td>${item[0]}</td> <td>${item[5]}</td> <td>${item[1]}</td> <td>${item[2]}</td> <td>${item[5]}</td> <td>${item[6]}</td> </tr> Now I'd like to add one more column which will be percentage ${item[2]} divided by ${item[1]} . But these are strings how do convert the result to double? EDIT: In both answers so far I get compile error resulting in : org.apache.jasper.JasperException: Unable to compile class for JSP: An error occurred at line: 30 in the jsp file: /WEB-INF/views/home.jsp Syntax error, insert ")" to complete MethodInvocation 27: <td>${item[5]}</td> 28: <td>${item[1]}</td> 29: <td>${item[2]}</td> 30: <td><%= Double.parseDouble(${item[2]})/Double.parseDouble(${item[1]}) %> </td> 31: <td>${item[5]}</td> 32: <td>${item[6]}</td> 33: </tr> More code : <table width="100%"> <c:forEach var="item" items="${myList}"> <tr> <td>${item[0]}</td> <td>${item[5]}</td> <td>${item[1]}</td> <td>${item[2]}</td> <td><%= Double.valueOf(item[2]) / Double.valueOf(item[1]) %></td> <td>${item[5]}</td> <td>${item[6]}</td> </tr> </c:forEach> </table> A: Don't worry about type conversion If an expressions ${item[2]} or ${item[1]} contains numeric value (digits). Simply use, ${item[2]/item[1]} or <c:catch> ${items[0]/items[1]} </c:catch> From EL Specification: Every expression is evaluated in the context of an expected type. The result of the expression evaluation may not match the expected type exactly, then the conversion will be take place as per coercion rules. Edit: For better design try to change datasource but do not add scriptlets. You can use entity (bean) list. ${item.produtid} ${item.qty*item.rate} A: <td><%= Double.valueOf(item[2]) / Double.valueOf(item[1]) %></td> A: I'd setup the values at the top of the JSP in a <% %> or in the controller (servlet) itself: String[] item = new String[1]; /* Assume a standard array */ String sOne = null, sTwo = null; double dOne = 0.0d, dTwo = 0.0d, dPercent; try { sOne = item[1]; sTwo = item[2]; dOne = Double.parseDouble(item[1]); dTwo = Double.parseDouble(item[2]); /* Making an assumption on the *100 here.... */ dPercent = (dTwo/dOne)*100; } catch(NumberFormatException nfe) { /* Handle the NFE here...*/ } catch (NullPointerException npe) { /* Handle the NPE here...*/ } catch (Exception e) { /* Handle any other exception here...*/ } Preprocessing the data at the top of the JSP or in the controller keeps the JSP cleaner: <tr> <td><%=item[0]%></td> <td><%=item[5]%></td> <td><%=item[1]%></td> <td><%=item[2]%></td> <td><%=item[5]%></td> <td><%=item[6]%></td> <td><%=dPercent%></td> </tr> Note that the difference between Double.parseDouble() and Double.valueOf() is the return type. .valueOf() returns a Double object while .parseDouble() returns a double type. Some java programmers use 'double' and Double interchangeably, but I come from the camp of 'avoid the Objects, use the primitive types!'. Not only does Double use more memory than a double does, but not knowing the difference between the two can cause some (major) confusion. See this link for an int vs Integer example: http://illegalargumentexception.blogspot.com/2008/08/java-int-versus-integer.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7582265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Returning a Json file with Nancy for use in Jquery I have a file that contains some JSON with an extension of .json. I am using Nancy to serve the file as follows: Get["/schema/{file}"] = parameters => { return Response.AsFile(Directory.GetCurrentDirectory() + @"\sitefiles\schema\" + parameters.file as String); } When I make a jQuery ajax request for the file like this: $.ajax({ url: "/schema/auditResponseSchema.json", type: 'GET', contentType: "application/json; charset=utf-8", dataType: "json", cache: false, success: function (responseSchema) { console.log("get response data - Success"); console.log(responseSchema); }, timeout: 5000, error: function (xmlObj, textStatus, errorThrown) { console.log("get response data - failed. status:" + textStatus + " error:" + errorThrown); } }); I get the file back but it is not recognised as JSON, I'm sure this is because of the Content-Type being returned is application/octet-stream. How do i change the to Content-Type to be application/json? I've tried: // this returns "application/json in the content. return Response.AsFile(Directory.GetCurrentDirectory() + @"\sitefiles\schema\" + parameters.file as String).Headers["Content-Type"] = "application/json"; // this returns the location of the file return Response.AsJson(Directory.GetCurrentDirectory() + @"\sitefiles\schema\" + parameters.file as String); Do i have to read the contents of the file into a string and then use Response.AsJson or is there a way to change the headers the Response.AsFile returns? A: Currently you can't override the content type using the extension method, you should be able to, and I'll log an issue and get it fixed for 0.8, but you currently can't. You can, however, just return a GenericFileResponse directly (which is all the extension method does behind the scenes): return new GenericFileResponse(Directory.GetCurrentDirectory() + @"\sitefiles\schema\" + parameters.file as String, "application/json"); I'd recommend against using Directory.GetCurrentDirectory though, you should be able to just specify it as a relative path. Edit: logged the issue here if you're interested https://github.com/NancyFx/Nancy/issues/315 Edit: and it's fixed .. the fix will be in 0.8 coming at the end of the week :-) A: And here is the fix https://github.com/NancyFx/Nancy/commit/3d3e45017c0710f4732cf971274f9116611ec478 in master now :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7582270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Prevent Jenkins from Installing Artifact to Local Maven Repository Jenkins is installing the most-recently built artifact to the local Maven repository, even when the job is executed with a goal of only clean package. This caused an issue when someone accidentally committed an updated version of a shared library without incrementing the version number in the library's POM. Jenkins built the jar, installed it to the local Maven repository, and then (as configured) deployed the artifact to our shared Nexus repository. Nexus quite rightly refuses to accept the new artifact, as it already has a release with the given version number. Some time later Jenkins builds a project that depends on that library, and uses the copy of the library from its local Maven repository rather than Nexus. Thus the project got built with the wrong version of the code. It seems there are two possible solutions: * *Stop Jenkins from erroneously installing the .jar to the local repository *Prevent the local repository from being used when building projects that depend on the library A: It's the install goal that publishes to the local repository... So I've no answer for the first problem. The second problem can be solved by isolating each build. Configure them to use their own local repositories so that mistakes in one don't affect others: mvn -s settings.xml compile package In the settings file declare unique path for the build job's local repository <settings> <localRepository>/data/job1/repository</localRepository> .. And it's probabily a good idea to periodically purge the local repositories, forcing clean builds. A: There is a setting in the Jenkins job configuration to use a private repository. This way you can avoid artefacts from your Jenkins build finding their way into your main repository. You need to open the extended options for the Maven build to see the option. A: I wonder if there is an option to actually use the (shared) local repository but turn off writing to it (i.e. deploy the artifacts only to the remote repository). This is to reduce the number of concurrent updates (but still keep sane disk usage:) A: You can prevent duplicate artifacts from being deployed in Nexus. Each artifact should have a build number appended to avoid confusion. Avoid SNAPSHOT versions as they cause headaches.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android Preferences: Incorrect default values DESPITE "setDefaultValues" I have a similar problem like this, so I proceeded according to the proposed solution and added this line of code to onCreate: PreferenceManager.setDefaultValues(this, R.xml.settings, false); Unfortunately the problem still occurs, if the user hasn't altered the settings, still the default-value (true) from mPreferences.getBoolean(String.valueOf(day_of_week), true) is used instead of the default value from the XML. One proposed to change the default-value parameter of getBoolean() to null, but this code crashes the app: mPreferences.getBoolean(String.valueOf(day_of_week), (Boolean) null) Any advice? Thanks in advance! A: Finally it works! I really put much time and effort into searching for the error and as soon as I post here, I find it out alone ~~ thanks guys for helping me with this one. If ever anyoneelse has this problem, the solution goes like this: Change the default Value of getBoolean() from true to false like so: mPreferences.getBoolean(String.valueOf(day_of_week), true) -> doesn't work, it is always true no matter what happened in the XML mPreferences.getBoolean(String.valueOf(day_of_week), false) -> it works! It's the correct default Value from the XML I really don't understand the logic into doing this, but now it works perfectly. Seems a bit like a bug to me. A: Set the third argument of setDefaultValues to true. So, PreferenceManager.setDefaultValues(this, R.xml.settings, true); From the documentation: public static void setDefaultValues (Context context, int resId, boolean readAgain) If readAgain is false, this will only set the default values if this method has never been called in the past (or the KEY_HAS_SET_DEFAULT_VALUES in the default value shared preferences file is false). To attempt to set the default values again bypassing this check, set readAgain to true. Note: this will NOT reset preferences back to their default values. So, my understanding is: * *If readAgain is false, it will read default values only once after the first run of app. If you add new property with default value to preferences, it will not initialized until you uninstall and install the app again. *If readAgain is true, it will read default values again and again on every function call. BUT, it will not reset values to default, if they already had been set or changed by the app.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Creating pdf report from a excel document using iTextSharp I need to create a PDF Report using iTextSharp. I have an excel sample,which i need to create an exact replica of it in PDF format and use it in that report.The page layout shouldn't be altered. How am i going to achieve it using c#??? Thanks in advance... A: In general you should probably stick to the Office methods mentioned in your question comments. Using iTextSharp to convert is a huge amount of work because you have to translate sizes, page areas, headers, lines, etc. from the Excel doc and somehow get them into the PDF based objects that iTextSharp expects. I created a tool to do such a thing for work (because it required special functionality outside of normal "printing"), it took a very long time and it doesn't even come close to being fully featured.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Apply TreeView bindings to non-expanded notes I want to use a hierarchical TreeView which I will populate programmatically. My XAML file is as follows: <Window.Resources> <HierarchicalDataTemplate DataType="{x:Type local:MyTreeViewItem}" ItemsSource="{Binding Path=Children}"> <TextBlock Text="{Binding Path=Header}"/> </HierarchicalDataTemplate> </Window.Resources> <Grid> <TreeView Margin="12,12,422,33" Name="treeView1" SelectedItemChanged="treeView1_SelectedItemChanged" MouseDoubleClick="treeView1_MouseDoubleClick"> <TreeView.ItemContainerStyle> <Style TargetType="{x:Type TreeViewItem}"> <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/> <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}"/> </Style> </TreeView.ItemContainerStyle> </TreeView> </Grid> The problem I'm having is that it seems that the bindings are applied only once the item is visible. Suppose I populate the TreeView as follows: private ObservableCollection<MyTreeViewItem> m_items; private MyTreeViewItem m_item1; private MyTreeViewItem m_item2; public MainWindow() { InitializeComponent(); m_items = new ObservableCollection<MyTreeViewItem>(); m_item1 = new MyTreeViewItem(null) {Header = "Item1"}; m_item2 = new MyTreeViewItem(null) {Header = "Item2"}; m_item1.Children.Add(m_item2); m_items.Add(m_item1); treeView1.ItemsSource = m_items; } I also have a button that selects m_item2: private void button2_Click(object sender, RoutedEventArgs e) { m_item2.IsSelected = true; m_item2.IsExpanded = true; } Now, if I launch the program and the TreeView only shows Item1 (Item2 is hidden because Item1 is not expanded), then clicking the button won't select m_item2. If I expand Item1 (thus making Item2 visible), the button will select m_item2. Examining the PropertyChanged event on m_item2, I see that it is set to null initially, and a delegate is registered only once it is visible. This is a problem for me because I want to be able to programmatically select an item, even if its parent has not yet been expanded (e.g. I want to be able to find a node in the tree). I suppose I can programmatically expand and collapse all nodes, but it seems there should be a better way. Can someone suggest a solution? A: Two suggestions: 1) Expand m_item1 before selecting m_item2 2) Hold your Selections in a ViewModel (using MVVM-Pattern)
{ "language": "en", "url": "https://stackoverflow.com/questions/7582284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Determine the shape of multiple selected cells within a data grid I'm using the Infragistics UltraWinGrid to present some data. I need some Excel copy/paste functionality. That's the easy bit. * *What I want to do is determine the shape of the selection, and ensure it's a rectangle of adjacent cells. If it's not, an error is to be shown (as pasting said data will just lead to errors). *I then need to detect all the boundary edge cells so I can put a "you've copied this" border around the cells, ala Excel. I'm hoping to achieve this by comparing a list of Point structures or something along those lines. To illustrate the problem better, here are some pictures: 1. This is fine, see the edge cells (duh) ] 2. This won't work, I've tried to copy too much, show an error 3. The user hasn't learnt by now that this just won't work. You can even see where I've copied the "wrong" cell out of sheer lazyness. I've got a Dictionary of Points and Cells, ready to work with. Any ideas? C#/VB is fine. UPDATE: This might help? Taking the second diagram: 0,0 1,0 2,0 0,1 1,1 2,1 0,2 1,2 2,2 0,3 1,3 2,3 1,4 <<< wrong Thanks, Tom A: Ok I've had a good think about this and GertArnold has pointed me in the right direction, simply by saying "range of cells with a hole in it allowed?" This is what happens when you spend 6 months not coding or problem solving, due to massive paperwork and auditing requirements, you forget how to even begin a simple algorithm. It's so easy it hurts. Firstly I get the cells from the datasheet and reformat them so they're based at zero (as opposed to their actual position on the grid). I do this by simply negating the value of the cell at {0,0} and applying this to all the cells. To calculate the gaps, do this: Private Function HasGapsInCells(points As List(Of CellPoint)) As Boolean Dim colCount As Integer = points.GroupBy(Function(x) x.Column).Count() Dim rowCount As Integer = points.GroupBy(Function(x) x.Row).Count() For row As Integer = 0 To rowCount - 1 Dim rowL As Integer = row For col As Integer = 0 To colCount - 1 Dim colL As Integer = col If Not points.Exists(Function(x) x.Row = rowL And x.Column = colL) Then Return True '-- There are gaps' End If Next Next Return False End Function So easy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can text be resizable using jquery-ui? Can html text in p tag is resizable using jquery-ui or without p tag in a div tag is resizable? I have done resizing the image using jquery ui from following example but text is not getting resized http://jqueryui.com/demos/resizable/. A: You may use resize event handler. The trick is how to calculate new font size. Check this solution as a variant: Html: <div id="resizable" class="ui-widget-content"> <h3 class="ui-widget-header">Resizable</h3> <div id="content">Quis non magna sagittis, et cras tortor nunc? Enim, lectus et quis penatibus enim augue eros, dis sit sit urna cras placerat sociis porta</div> </div> Javascript: var initDiagonal; var initFontSize; $(function() { $("#resizable").resizable({ alsoResize: '#content', create: function(event, ui) { initDiagonal = getContentDiagonal(); initFontSize = parseInt($("#content").css("font-size")); }, resize: function(e, ui) { var newDiagonal = getContentDiagonal(); var ratio = newDiagonal / initDiagonal; $("#content").css("font-size", initFontSize + ratio * 3); } }); }); function getContentDiagonal() { var contentWidth = $("#content").width(); var contentHeight = $("#content").height(); return contentWidth * contentWidth + contentHeight * contentHeight; } You may look this solution at jsFiddle: jsFiddle link A: Text sizing has nothing to do with jQuery specifically. You can tie a CSS property to a slider, however. $('#slideBar').slider({ startValue: 12, minValue: 0, maxValue: 100, stop: function(e, ui) { $("#text").css({fontSize: ui.value + 8}); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7582289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Nested Set Model: Query node childs only 1 level below AND all parents above I am using Nested Set Model with MySQL to create hierarchical tree model. I have successfully managed to get Node and all its Childs 1 level below (I need to get only 1 sub-level) However, I would like to have not only all Childs 1 level below, but all Parents above that Node too. Is it possible to modify current query to get what I want? This is my code (actually it's taken from this, non-working, site: http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/ but mine is exactly the same): SELECT node.name, (COUNT(parent.name) - (sub_tree.depth + 1)) AS depth FROM nested_category AS node, nested_category AS parent, nested_category AS sub_parent, ( SELECT node.name, (COUNT(parent.name) - 1) AS depth FROM nested_category AS node, nested_category AS parent WHERE node.lft BETWEEN parent.lft AND parent.rgt AND node.name = 'PORTABLE ELECTRONICS' GROUP BY node.name ORDER BY node.lft )AS sub_tree WHERE node.lft BETWEEN parent.lft AND parent.rgt AND node.lft BETWEEN sub_parent.lft AND sub_parent.rgt AND sub_parent.name = sub_tree.name GROUP BY node.name HAVING depth <= 1 ORDER BY node.lft; Tree structure looks like this: Electronics --Televisions ----LCD --Portable Electronics ----MP3 Players ------Flash ----CD Players Using my current code above, I get this: --Portable Electronics ----MP3 Players But I need to get something like this: Electronics --Portable Electronics ----MP3 Players I will be using this query later in PHP, so I can use PHP-based solution (or part of it) too. Thank you A: I think you want to split this up in multiple queries. First the 'PORTABLE ELECTRONICS' item with all its childs, like you're doing now. After that, fetch the parents is easy, just fetch all elements WHERE left < [PE-left] AND right > [PE-right]. A: I managed to solve the problem by using multiple queries. First query retrieves all parents above node (as Rijk suggested) and second query retrieves everything below the node (code, posted in original post). Then using UNION ALL I combined everything into one result set. However I could not use depth column to make indentation anymore, so to make page formating for childs, i used php-based function to indent nodes ( http://www.sitepoint.com/hierarchical-data-database-2/ ) Note: I had to add if/else statement at the end of this code to indent only parent nodes and not everything. A: I had the same issue. This seemed to work. SELECT parent.name FROM nested_category AS node,nested_category AS parent,nested_category AS midpoint WHERE (node.lft BETWEEN parent.lft AND parent.rgt) AND (node.lft BETWEEN midpoint.lft AND midpoint.rgt) AND midpoint.name='PORTABLE ELECTRONICS' GROUP BY parent.name ORDER BY node.lft;
{ "language": "en", "url": "https://stackoverflow.com/questions/7582292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: MongoDB C# map an Item i´m using map/reduce to find the max Revision of an Document. var map = "function() {emit(this.DocName, this.Revision);}"; var reduce = "function (key,values) {return Math.max.apply(Math, values);}"; QueryDocument Query = new QueryDocument("DocName", stFName); var mr = docs.MapReduce(Query, map, reduce).Response; mr contains {[{ "_id" : "WINWORD8.DOC", "value" : 2.0 }]} How can use 'value' as an variable? Regards Thomas A: Map reduce can be considered as overkill for such a simple request. You can use the InlineResults property : docs.MapReduce(Query, map, reduce).InlineResults which is an enumerable of BsonDocument (in this case 1 doc only) and get the first result. I would however suggest a better way to find the maximum revision, avoiding map reduce usage : IMongoSortBy sort = SortBy.Descending("Revision"); IMongoQuery = Query.EQ("DocName", stFName); BsonValue maxRev = docs.FindAs<BsonDocument>(q).SetFields(new string[] {"Revision"}).SetSortOrder(sort).SetLimit(1).GetFirstOrDefault() if (maxRev !=null) int revMax = maxRev.AsBsonDocument.GetValue("Revision").AsInt32; // <- this is the maximum revision If you want, in the end, to get the maximum revision for all your documents then mapreduce is a good call.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ANTLR for Writing JAPE Grammar I am using GATE to process texts written in natural language. I have to extract height, weight, bp etc from the text and store it in structured form. Now, these things(i.e height, weight etc) can be written in many forms which is unknown to me. Writing JAPE grammar for all the different ways I can come up with, is merely hard-coding it. Do I have any other option to process the docs in a more flexible way? Also, I am confused as to whether I can use ANTLR to generate jape grammar by presenting different ways of writing height, weight etc? The text will contain the following: Vitals: Height: 72 inches, Weight is 170 pounds, T is 89.9 degree Fahrenheit. OR Vitals: He is 184 cm tall, his weight was 67.8 Kg, RR 16 (its respiration rate). OR Vitals: height is 6ft 3 in, he weighs 70 kg, pulse is 67, Temperature 99.8 degrees. Now I use JAPE grammar and ANNIE to tokenize the text to extract these vitals and store in structured form. Will using ANTLR be flexible to tokenize this such text? Flexible in the sense that I should not hard-code it for each way of representation, as you see height, weight etc can be represented in many forms. Will that be a good idea to search for or develop any grammar generator that would generate jape grammars? If you require any detail to better understand the problem pls let me know. Thanks a lot!! A: You can try JAPE lightway alternative Gexp
{ "language": "en", "url": "https://stackoverflow.com/questions/7582297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Jsoncpp stop making it write based on elements alphabetical order I am using Jsoncpp to write a Json::value to a string using the Json::FastWriter. string s; s.append("me?json="); val["firstname"] = firstname; val["lastname"] = lastname; val["x"] = me->myPos.X; val["y"] = me->myPos.Y; val["z"] = me->myPos.Z; val["lookx"] = me->myOri.X; val["looky"] = me->myOri.Y; val["lookz"] = me->myOri.Z; url.append(writer.write(val)); The problem is they don't appear in the string as in the order that I added them to the Json::value val, they seem to be alphabetically sorted depending on the first letter in each element("firstname, lastname, lookx, looky, lookz,x",etc). How do you prevent this? I want it to be added in the order that I add it to the Json::value and NOT be sorted. If this is not possible, how would one alter the source code to achieve it? Thanks A: Most likely Jsoncpp uses a std::map to store the key/value pairs, and it will return you an alphabetically-ordered key/value pairs. I've not looked into the code of Jsoncpp, but you have two alternatives: * *Change the code to use internally a std::list or some other ordered container (vector, etc.). That may result in performance penalty. *Store the order of the keys you want to output and produce the output yourself. However, as you may know, the order of keys in JSON is not specified, so if you're relying on that fact, you should reconsider your application design.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Virtual Memory size on Linux I'm trying to understand in depth the virtual memory management on OS Linux. I don't really understand how the OS determine the size of the VM for a process. I know that an 32-bits x86 OS can give up to 3 GB of vm adress space... Is it always true ? In my case, i have about 110 MB physical memory with and 32-bits Linux, and my main process have a vm adress space about 660 MB. However, only 50 MB are in physical memory (the RSS of my process), so my physical RAM isn't full. The rest is free and almost the whole is used by page cache. That's seems to be a normal behaviour. If i check /proc/my_process_PID/smap, there are several 8 MB anonymous VMA. My actual problem is that i need to make a additionnal 10 MB malloc in the code, but unfortunately OOM-Killer kills my process (out-of-memory) ... I think there are no more free available pages in the vm for the Heap, isn't it ? Is there an huge memory leak somewhere ? Why the OS doesn't extend my process vm size so ? For information the vm size is unlimited : ulimit -v : unlimited A: You can have 3GB of virtual memory per process (approximately, on many 32-bit Linux), and keep on creating new processes taking up gigabytes upon gigabytes of virtual memory. There's a small overhead in the kernel, but virtual memory is very cheap. The amount of address space you're using is probably not important, and it probably won't trigger the OOM killer. However, your system only has so much RAM. As you start using pages in your address space (writing to them), the kernel is forced to find physical RAM to map them to. If there's no physical RAM, the kernel can evict other pages from RAM -- either swap them out or discard them. But if it can't evict any pages, then it triggers the OOM killer. Running out of address space will cause malloc to return NULL on my system, instead of triggering the OOM killer. It sounds like your process is simply using too much RAM. RSS isn't the amount of memory your process uses, it's just the amount that's in physical RAM right now. If your process has a memory leak and keeps growing, RSS will eventually stop growing -- because for every new page you use, the kernel will evict one page from your process. Try using a memory profiler, like Valgrind. This will help you sort out what memory you should be worried about (mallocs) and what memory you can ignore (shared libraries and other memory mapped files). The kernel (and /proc) won't give you enough detail. A: The total amount of virtual memory space available on a linux system is (roughly) RAM + swap space - kernel overhead. The RAM is the hardware you have installed and the kernel overhead is roughly a constant (varies between kernel versions though), so the only easy way to control the total VM space available is by adding or removing swap space. In addition to the total limit, there's also a per-process VM limit. This is configurable and (on 32bit linux at least) is at most 3GB, but may be quite a bit less. ulimit -v will tell you this limit or can be used to change it. When a process requests more VM space (generally via malloc), the kernel will look at all of these limits, and if any of them would be exceeded, will return 0. The OOM killer, on the other hand, only kicks in when you're getting close to the total VM limit. However, when the OOM killer kills you, you just die -- there's no out-of-memory error or any opportunity to catch it. So if you really are running into the total VM limit, and want to avoid that, you can either allocate more swap space, or get rid of (kill or not start in the first place) other processes that are using a lot of VM space so as to free up some for your program.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: String is not empty but not appearing when using var_dump Currently I am trying to return a publicly available XML resource, though when I use var_dump($resource) it returns string(4390) " ". I am using CURL to retrieve the resource, and it successfully returns other resources. There's clearly something there (as you can see there is 4390 characters!) but it is not returning successfully. I have tried wrapping it in utf8_encode though this has made no difference. I have also tried returning it using print_r and <pre> tags though this too returned nothing. Any help here would be great! A: To display non-displayable characters from strings, don't use var_dump but print out a hex-dump of the string, for example echo bin2hex($resource); using bin2hexDocs, but the link above has more alternatives to offer. Take what suits your debug needs best. Edit: In case you're actually outputting HTML or XML elements, use htmlspecialcharsDocs: echo htmlspecialchars($result); A: What type of text is in the xml? If there are just html tags try to view the source code of the internet page. Maybe they wont be displayed because your browser interpret the html and dont show the tags A: Or you can use Kint instead of var_dump to display the debug output. It will show the most information about the dumped variables in the most readable way. Needless to say it displays html effortlessly too. Screenshot: (source: github.io)
{ "language": "en", "url": "https://stackoverflow.com/questions/7582302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What is the best way to code this correlated query? (Select Prices that may contain NULL following a Priority) Lets imagine you have a portfolio to value containing 4 assets that needs to be priced. The SourceID dictates the priority that the PriceSource should be given and the lowest SourceID should be retrieved. Where no price is available from the EODPrice table, then the AverageBookCost should be retrieved (which resides in a different Table). I am using SQL Server 2005. As an example, lets imagine that EODPrice table has the following data ('TEST004' is missing): SourceID Date Ticker Price 0 2011-08-02 00:00:00 TEST001 104.50 1 2011-08-01 00:00:00 TEST001 100.00 1 2011-08-02 00:00:00 TEST001 105.00 1 2011-08-04 00:00:00 TEST001 115.00 2 2011-08-03 00:00:00 TEST001 109.38 2 2011-08-04 00:00:00 TEST001 114.24 1 2011-08-01 00:00:00 TEST002 9.99 1 2011-08-02 00:00:00 TEST002 9.89 1 2011-08-03 00:00:00 TEST002 9.79 1 2011-08-04 00:00:00 TEST002 9.69 0 2011-08-03 00:00:00 TEST003 0.42 2 2011-08-01 00:00:00 TEST003 0.33 2 2011-08-02 00:00:00 TEST003 0.38 2 2011-08-03 00:00:00 TEST003 0.28 2 2011-08-04 00:00:00 TEST003 0.45 Lets imagine that we would like to build a Select statement where we retrieve the EODPrice for the following assets ('TEST001','TEST002', 'TEST003', 'TEST004'). Note that 'TEST004' is a new asset that has just hit the Market and no price is available yet in the EODPrice table or the Market. Further, lets imagine that ALL Tickers for any Date has a non-NULL AverageBookCost field from a RunningTotal Table. (i.e. SELECT AverageBookCost FROM RunningTotal WHERE Ticker = 'TEST004' AND Date = '2011-08-03' would return the value 0.15 say). How do I build the most efficient 'Correlated' or 'COALESCE / ISNULL' Query: SELECT Ticker, SourceID, Price ??? WHERE [Date] = '2011-08-03' AND [Ticker] IN ('TEST001','TEST002', 'TEST003' and 'TEST004') That would return the following Table: (Note as 'TEST004' Price is the AverageBookCost and not in the EODPrice table, then the SourceID is set to NULL to indicate that the Price is from the RunningTotal table: Ticker SourceID Price TEST1 2 109.38 TEST2 1 9.79 TEST3 0 0.42 TEST4 NULL 0.15 Many thanks, Bertie. A: I most likely overcomplicated things but this might get you started. In a nutshell, the reasoning goes like this * *In a subselect, SELECT all tickers for given date with their lowest SourceID. *JOIN the results of this subselect back with the original table. This step allows the price to be retrieved for each ticker with given date and lowest SourceID. *FULL OUTER JOIN the previous result with the average book cost. This step adds to each row the average price for that ticker and adds rows for tickers that don't have a record returned from Pricetable. *SELECT from these results the Price if available, otherwise select from the appended columns the average book cost. SQL Statement SELECT [Ticker] = ISNULL(pt.Ticker, pt_avg.Ticker) , [SourceID] = pt.SourceID , [Price] = ISNULL(pt.Price, pt_avg.AverageBookCost) FROM EODPriceTable pt INNER JOIN ( SELECT SourceID = MIN(SourceID), Ticker, Date FROM EODPriceTable WHERE Date = '2011-08-03 00:00:00' GROUP BY Ticker, Date ) pt_min ON pt_min.SourceID = pt.SourceID AND pt_min.Ticker = pt.Ticker AND pt_min.Date = pt.Date FULL OUTER JOIN ( SELECT Ticker, AverageBookCost FROM RunningTable ) pt_avg ON pt_avg.Ticker = pt.Ticker WHERE ISNULL(pt.Ticker, pt_avg.Ticker) IN ('TEST001', 'TEST002', 'TEST003', 'TEST004') Test script ;WITH EODPriceTable (SourceID, Date, Ticker, Price) AS ( SELECT 0, '2011-08-02 00:00:00', 'TEST001', 104.50 UNION ALL SELECT 1, '2011-08-01 00:00:00', 'TEST001', 100.00 UNION ALL SELECT 1, '2011-08-02 00:00:00', 'TEST001', 105.00 UNION ALL SELECT 1, '2011-08-04 00:00:00', 'TEST001', 115.00 UNION ALL SELECT 2, '2011-08-03 00:00:00', 'TEST001', 109.38 UNION ALL SELECT 2, '2011-08-04 00:00:00', 'TEST001', 114.24 UNION ALL SELECT 1, '2011-08-01 00:00:00', 'TEST002', 9.99 UNION ALL SELECT 1, '2011-08-02 00:00:00', 'TEST002', 9.89 UNION ALL SELECT 1, '2011-08-03 00:00:00', 'TEST002', 9.79 UNION ALL SELECT 1, '2011-08-04 00:00:00', 'TEST002', 9.69 UNION ALL SELECT 0, '2011-08-03 00:00:00', 'TEST003', 0.42 UNION ALL SELECT 2, '2011-08-01 00:00:00', 'TEST003', 0.33 UNION ALL SELECT 2, '2011-08-02 00:00:00', 'TEST003', 0.38 UNION ALL SELECT 2, '2011-08-03 00:00:00', 'TEST003', 0.28 UNION ALL SELECT 2, '2011-08-04 00:00:00', 'TEST003', 0.45 ) , RunningTable (Ticker, AverageBookCost) AS ( SELECT 'TEST004', 0.15 UNION ALL SELECT 'TEST003', 0.09 ) SELECT [Ticker] = ISNULL(pt.Ticker, pt_avg.Ticker) , [SourceID] = pt.SourceID , [Price] = ISNULL(pt.Price, pt_avg.AverageBookCost) FROM EODPriceTable pt INNER JOIN ( SELECT SourceID = MIN(SourceID), Ticker, Date FROM EODPriceTable WHERE Date = '2011-08-03 00:00:00' GROUP BY Ticker, Date ) pt_min ON pt_min.SourceID = pt.SourceID AND pt_min.Ticker = pt.Ticker AND pt_min.Date = pt.Date FULL OUTER JOIN ( SELECT Ticker, AverageBookCost FROM RunningTable ) pt_avg ON pt_avg.Ticker = pt.Ticker WHERE ISNULL(pt.Ticker, pt_avg.Ticker) IN ('TEST001', 'TEST002', 'TEST003', 'TEST004')
{ "language": "en", "url": "https://stackoverflow.com/questions/7582303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: HTML form, character sets, and the accept-charset attribute Is there a default character set used by HTML forms? Or is there a default accept-charset attribute that is used? We're experiencing some problems with characters and character sets in our online forms. The HTML pages are set to use the character set ISO-8859-1 (using a content meta tag), but there is no specific accept-charset attribute set in the forms. The databases in the back end use UTF-8 encoding. I'm not sure why there are two different character sets used here - that decision was a bit before my time, and can't be easily changed. Most of the time, everything runs quite happily. The problem comes when someone enters a character that's not contained in the ISO-8859 character set - it displays correctly in the browser, but comes through to the back end as an unknown entity. Really bizarrely, it then transfers back to the browser correctly. I've assumed so far that even if a user enters a character into the form that's not in the ISO-8859 charset, the page will use the character set from the meta tag when sending the data to the server; causing the odd entity to be displayed in the database. Does this sound like a feasible explanation, and - if so - would changing the content type of the HTML pages be a reasonable solution to the problem? Cheers. A: Browsers will send the text from inputs in the same charset as the page is served. accept-charset can cause problems, if you use it, make sure it has the same charset as your page. The reason it's an unknown entity is because your database is treating it as UTF-8. But when it comes back to the page, it's just bytes, this time treated as ISO-8859. However, it may cause problems if you are using any of your database's string functions on the text if it is treating it as UTF-8.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: asking about android:installLocation on manifest so i learned the syntax for the installLocation for the android manifest, in the i typed the android:installLocation as an attribute and it has an error, but when i remove the android: part and just leave the installLocation everything works out, my minsdk is 7 targeted is 8, i use emulator 2.1 update 1. i just want to make sure that there is nothing wrong with this, if this is just normal? cause all the syntax sample includes the android: part of the code? i have screenshots, but new members are not allowed to upload photos apparently. A: yes, the thing is that installLocation supports on Android Ver2.2(froyo) and above
{ "language": "en", "url": "https://stackoverflow.com/questions/7582311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Very strange PDO->bindparam behaviour php The query below is running well and runs quite fast for what it does. However it is displaying some very strange behaviour as outlined below. However in PHP it seems to decide by itself which ids it will work for. I am certain that the code is correct. I am using PDO in PHP and binding the variables as required. So for instance if I pass it the author_id 600 it will work, but if I pass it the author_id 2 it won't work and brings back no records. But if I echo the query and paste it into MySQL and run it, it works for both the ids. It would seem that the PDO is failing to bind the variable on some ids. I have echoed the id variable and it does indeed contain the proper id. Has anyone else experienced this behaviour? I find it very very unusual. SELECT GROUP_CONCAT(a.author_id) AS author_ids FROM references_final AS rf INNER JOIN (reference_authors AS ra INNER JOIN authors_final AS a ON (ra.author_id = a.author_id)) ON (rf.reference_id = ra.reference_id) GROUP BY rf.reference_id HAVING :author_id IN (author_ids) A: Hey I am having the same problem With BindParam and ID value in my PDO Statement $retrieveUsersToken = $dataBase->prepare('SELECT TheUsersTable.token AS token, TheUsersTable.myID AS myID, FROM TheUsersTable INNER JOIN TheCategoryListTable ON TheUsersTable.myID = TheCategoryListTable.userID WHERE TheUsersTable.myID != :userID AND TheCategoryListTable.category = :category'); $retrieveUsersToken->bindParam( ':category', $_POST['category'], PDO::PARAM_STR); $retrieveUsersToken->bindParam( ':userID', $_POST['creatorID'], PDO::PARAM_INT); myID != userID never works neighter does TheCategoryListTable.category = :category when :category contain space Looks like the Inner Join is creating troube in both our situations. It's not really an answer but maybe binValue works better.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: LinQ Query Where Condition I am trying to import data into a new database, but some of the columns in the old database are null. In one of my methods, I am using the query below to get the records, like I said already there is a column in the rows which has a null value for some records. Guid nameGuid= new guid('CCECE54B-EE14-4463-8A0B-02C72679334A') MySubQuery = from a in MainQuery where a.Table1.Id.Equals(nameGuid) Select a; I want to check for a.Table1.Id value, if it is equal to null, then I still want the row but ignore the where condition. Any suggestion for using the ternary operator in Linq query or any other approaches for my task. A: Sounds like you want: MySubQuery = from a in MainQuery where a.TableId.Id Is Nothing OrElse a.Table1.Id.Equals(nameGuid) That's assuming my VB is correct... in C# I'd just write: var query = from a in mainQuery where a.TableId.Id == null || a.TableId.Id == nameGuid select a; or using the extension method directly: var query = mainQuery.Where(a => a.TableId.Id == null || a.TableId.Id == nameGuid); A: How about: MySubQuery = from a in MainQuery where a.Table1.Id == null || a.Table1.Id.Equals(nameGuid) select a; Or am I missing something? EDIT: The thing I am missing is what Mr Skeet spotted. It's VB. Well, I'll let this stick around as a C# sample. A: var datarows = (from row in dt.AsEnumerable() where row.Field<Guid>("Id") == new Guid(ddlCode.SelectedValue.ToString()) select row); After that DataTable newDt=datarows.CopyToDataTable(); var sampleName=newDt.Rows[0]["SampleName"].ToString();
{ "language": "en", "url": "https://stackoverflow.com/questions/7582316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: DHCP server for Windows with NTP option Does anybody know about a DHCP server app for Windows 7 Professional 32-bit, with the posibility to configure the NTP server address? I found these apps: http://tftpd32.jounin.net/tftpd32.html http://www.dhcpserver.de/dhcpsrv.htm Great apps but I can't find any option to add the NTP server address. Grtz A: This one http://alax.info/blog/dhcp-server can be set up to send NTP servers (DCHP Option 4).
{ "language": "en", "url": "https://stackoverflow.com/questions/7582317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery Post does not work in asp.net mvc 3? I just copied some code from an asp.net mvc 2 app which works. Now i am trying it in asp.net mvc 3 and it does not call the save method on the controller? controller: [HttpPost] public JsonResult save(string inputdata) { return Json(new { Result = string.Format("From the controller - you have clicked the GO-button ! ") }, JsonRequestBehavior.AllowGet); } view: <button id="but">go</button> <div id=result></div> <script type="text/javascript"> $(document).ready( $("#but").click( function () { $.ajax({ url: "/Home/save", dataType: "json", type: 'POST', data: "test", success: function (result) { $("#result").html(result.Result); } }); } ) ); </script> A: You are not passing the data correctly. The action argument is called inputdata. So you should use this same name in the data hash of the AJAX request: $.ajax({ url: '/Home/save', dataType: 'json', type: 'POST', data: { inputdata: 'test' }, success: function (result) { $('#result').html(result.Result); } }); Also never hardcode urls in your javascript, always use url helpers or your application will simply stop working when you deploy due to the possibility of having a virtual directory name: $.ajax({ url: '@Url.Action("save", "home")', dataType: 'json', type: 'POST', data: { inputdata: 'test' }, success: function (result) { $('#result').html(result.Result); } }); Another issue that you have with your code is that you are not canceling the default action of the button meaning that if this is an action link or a submit button the AJAX request might never have the time to execute before the browser redirects. Also you don't need to specify the dataType to JSON as jQuery is intelligent enough to deduce this from the Content-Type response header sent from the server. So the final version should look something along the lines of: <script type="text/javascript"> $(function() { $('#but').click(function () { $.ajax({ url: '@Url.Action("save", "home")', type: 'POST', data: { inputdata: 'test' }, success: function (result) { $('#result').html(result.Result); } }); return false; }); }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7582319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WCF custom binding I am using custom binding in the sevrice side in C#. I want binary Encoding in HTTP. <bindings> <customBinding> <binding name="myOwnBinding"> <binaryMessageEncoding></binaryMessageEncoding> <httpTransport/> </binding> </customBinding> </bindings> <extensions> <bindingExtensions> <add name="myOwnBinding" type="CustomBinding.UserBinding,CustomBinding"/> </bindingExtensions> </extensions> <service name="CustomBinding.Service1" behaviorConfiguration="CustomBinding.Service1Behavior"> This service is not going to expose the metadata.So,i will not be able to create a service Reference in client to consume the servvice. Now,I want to know how to use this binding in the client channel factory to consume this service.Below is my client side code. EndpointAddress address = new EndpointAddress("http://localhost:2418/Service1.svc"); ChannelFactory<IService1> c = new ChannelFactory<IService1>(Binding, address); IService1 reqChannel = c.CreateChannel(); String str = reqChannel.GetData(1); How to manually fill the binding object that the Channel factory is expecting when service is developed with custom binding.? Thanks Arun A: I have sorted it out when i used the app.config to load the custom binding object. System.ServiceModel.Channels.CustomBinding cus = new System.ServiceModel.Channels.CustomBinding("CustomBinding_IService1"); EndpointAddress address = new EndpointAddress("http://localhost:2418/Service1.svc"); ChannelFactory<IService1> c = new ChannelFactory<IService1>(cus); IService1 serviceInstance = c.CreateChannel(address); String str = serviceInstance.GetData(1); Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7582320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I identify the edited row in GridView? My client wanted the GridView to display fields inside TextBoxes, and DropDownListBoxes only. He wanted the flexibility to update the Record just by clicking on the Update button after altering the values in the cell. He wanted the current editing GridViewRow in some different color so that he can click on "Update" button for that particular row. How can I identify the current editing row in the GridView? Since there is no edit button to click on!! A: Probably you are looking for GridView.EditIndex Also here is tutorial which looks like fit your problem: http://csharpdotnetfreak.blogspot.com/2009/05/gridview-sqldatasource-insert-edit.html A: Based on Gridview rows EditItemIndex you can find whether a row is in Edit mode or not. Refer to this to know more. A: you can select the Row by using this code,And show the Row with different color. u can highlight, protected override void Render(System.Web.UI.HtmlTextWriter writer) { AddRowSelectToGridView(gridView); base.Render(writer); } private void AddRowSelectToGridView(GridView gv) { try { foreach (GridViewRow row in gv.Rows) { row.Attributes["onmouseover"] = "this.style.cursor='hand'; this.style.textDecoration='underline';"; row.Attributes["onmouseout"] = "this.style.textDecoration='none';"; row.Attributes.Add("onclick",Page.ClientScript.GetPostBackEventReference(gv,"Select$"+row.RowIndex.ToString(), true)); } } catch (Exception ex) { } } A: Are you talking a multi-line edit? Or a scenario where all rows show their editable UI? The best way, if this is the case, is to use TemplateFields for all fields, and render the textboxes/other controls in the template. Out of the box, multi-row editing is not supported. Or you can create a custom control like what was done here: http://blogs.msdn.com/b/mattdotson/archive/2005/11/09/real-world-gridview-bulk-editing.aspx If you are talking simply editing, selecting the AutoGenerateUpdateButton="true" will add an update button, or manually add a commandfield and set its CommandName to update. HTH.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Replication with SQL Server 2008 Web edition I need to use replication between my databases. But me hosting provides only Web Edition of SQL Server. In web edition replication is not supported. May be anyone have some suggestions? Thanks A: If you are savvy with programming then you can accomplish a very slim form of replication through code. If not, you might be out of luck. You can have DML triggers on your tables that you would normally have as articles for replication, and when the data changes log it to a table with the necessary information. Then have a scheduled task that runs an application to push those changes to the logical subscriber(s). Just an idea, but it looks like you may have to get creative.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to create a 4x4 flexbox grid? I'm attempting to create a 4x4 flexbox grid. Each of the four boxes should have the same vertical height, but stack two per row from left to right. Is this possible? (Resize your browser between 960 and 640 to see my attempt: http://www.joshuasortino.com/index-new or view how I would like it to work: http://www.joshuasortino.com/index) Edit: This effect is possible by creating two containers (one for each row) but I would prefer to only use one wrapper/container. A: There's nothing wrong with your boxes. You are just running into trouble because your svg images are rendering with a lot of extra vertical space. Just add height/width styles like you were on the old version. Change this: <object data="public/images/charts/routine.svg" type="image/svg+xml" class="chart"> To this: <object data="public/images/charts/routine.svg" type="image/svg+xml" class="chart" style="width: 482px; height: 265px;"> And change this: <object data="public/images/charts/skills.svg" type="image/svg+xml" class="chart"> To this: <object data="public/images/charts/skills.svg" type="image/svg+xml" class="chart" style="width: 482px; height: 265px;"> Ideally, you'd use styles and css to set these attributes, I just in-lined them for demo purposes A: It appears there is an element which can solve the issue. Unforuntately it is not widely supported at this time. -webkit-box-lines: multiple; Supossedly allows flexbox DIVs to span multiple rows.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Jenkins: settings for Gerrit Trigger problems I've installed the plugin Gerrit Trigger on Jenkins cos I need to start automatically the building when a developer in the team pushes something on the repository (relative to a specific project). I followed the settings here: https://wiki.jenkins-ci.org/display/JENKINS/Gerrit+Trigger The test connection is ok. Anyway when something is pushed the building doesn't "trigger". The only thing I can see is: Under "Manage Jenkins" -> The connection to Gerrit is down! Check your settings and the Gerrit server. any idea? thanks randomize BTW I got this: BTW I got this: Command "git fetch -t git@github.com:somewhere/MyProject.git $GERRIT_REFSPEC" returned status code 128: fatal: Couldn't find remote ref $GERRIT_REFSPEC fatal: The remote end hung up unexpectedly ERROR: Could not fetch from any repository FATAL: Could not fetch from any repository hudson.plugins.git.GitException: Could not fetch from any repository at hudson.plugins.git.GitSCM$2.invoke(GitSCM.java:1008) at hudson.plugins.git.GitSCM$2.invoke(GitSCM.java:968) at hudson.FilePath.act(FilePath.java:758) at hudson.FilePath.act(FilePath.java:740) at hudson.plugins.git.GitSCM.checkout(GitSCM.java:968) at hudson.model.AbstractProject.checkout(AbstractProject.java:1184) at hudson.model.AbstractBuild$AbstractRunner.checkout(AbstractBuild.java:537) at hudson.model.AbstractBuild$AbstractRunner.run(AbstractBuild.java:425) at hudson.model.Run.run(Run.java:1376) A: There is trick described on the Gerrit plugin page: Normally when you have configured a job to be triggered by Gerrit you can't use the "Build Now" link anymore since your builds are dependent on information from Gerrit, especially if you are using the Git plugin to checkout your code in the workspace. You can get around this limitation if you for example want to use the same job to build the master branch at some point. If you are using the Git plugin do the following Add a String parameter called GERRIT_REFSPEC with the default value refs/heads/master Using this trick will enable you to build, but no results will be sent to Gerrit since tit is not triggered by it. A: That doesn't work with the Gerrit trigger, because then the variable $GERRIT_REFSPEC isn't set. If you want to manually trigger a changeset from Gerrit, you have to use the "Query and Trigger Gerrit Patches". There you can search for open changes in Gerrit and build them. You should also notice, that a build is only triggered, if you have pushed the changes to the review branches in Gerrit, e.g. a refs/for/ reference. If you pushed directly to the branches (e. g. refs/heads/master), because you don't want to do code review, the Gerrit trigger doesn't work. You would have to use one of the Gerrit hooks, that calls a URL which starts a build or let the build job poll your Git repository. A: in our case, we had to restart the jenkins service. this looks to be a bug with the gerrit trigger plugin (we're on 2.27.5) A: You Need to start the gerrit server from the jenkin>> gerrit trigger> click on status icon.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Python: get datetime of last hour I want to get the date time object for last hour. Lets say the sys time is "2011-9-28 06:11:30" I want to get the output as "2011-9-28 05" #{06 - 1 hour} I used: lastHourDateTime = date.today() - timedelta(hours = 1) print lastHourDateTime.strftime('%Y-%m-%d %H:%M:%S') However, my output is not showing the time part at all. where am I going wrong? A: This works for me: import datetime lastHourDateTime = datetime.datetime.now() - datetime.timedelta(hours = 1) print(lastHourDateTime.strftime('%Y-%m-%d %H')) # prints "2011-09-28 12" which is the time one hour ago in Central Europe A: You can achieve the same goal using pandas: import pandas as pd pd.Timestamp.now() - pd.Timedelta('1 hours') A: Date doesn't have the hour - use datetime: from datetime import datetime, timedelta last_hour_date_time = datetime.now() - timedelta(hours = 1) print(last_hour_date_time.strftime('%Y-%m-%d %H:%M:%S'))
{ "language": "en", "url": "https://stackoverflow.com/questions/7582333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "61" }
Q: How to disable back button of windows phone after one click I have a problem in my app is that when the user hit back button multiple times the app become crashed.Is there any way to handle this problem ?Is any way to disable back button after the first click from a page.so further click can be avoided.The exception i am getting while hitting back button multiple time is 0x8000ffff.Is there any solution for this in windows phone 7.1? A: You should fix the issue which is causing your app to crash. If you disable the back button behaviour you risk failing marketplace certification due to requirement 5.2.4[.1] http://msdn.microsoft.com/en-us/library/hh184840(v=VS.92).aspx A: You can control that, here is a sample code: private void YourPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e) { //App.NaviService.BackKeyPress(sender, e); if (NavigationService.CanGoBack) { NavigationService.GoBack(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7582334", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Force youtube embed to start in 720p There are a few methods suggested for doing this online, but none of them seem to work. For example: http://blog.makezine.com/archive/2008/11/youtube-in-720p-hd-viewin.html That article is about making it start in 720p, but it doesn't even work on their own video. Does anyone here know how to do it? A: Youtube doesn't support playback quality anymore A: This is an embed example of video played in HD 1080. <iframe width="560" height="315" src="http://youtube.com/v/IplDUxTQxsE&vq=hd1080" frameborder="0" allowfullscreen="1"></iframe> Let's break apart the code:http://youtube.com/v/ video_id &vq=hd1080 Video id for that video: IplDUxTQxsE you will see this type of random code in the link of every YouTube video. So far so good, this trick works for playing full HD videos directly on webpages! You can change the quality to 720 too. &vq=hd720 A: I've managed to get this working by the following fix: //www.youtube.com/embed/_YOUR_VIDEO_CODE_/?vq=hd720 You video should have the hd720 resolution to do so. I was using the embedding via iframe, BTW. Hope someone will find this helpful. A: The first example below does not work for me, but the second one does (in Chrome). <iframe width="720" height="405" src="//www.youtube.com/embed/GX_c566xYcQ?rel=0&vq=hd1080" frameborder="0" allowfullscreen="1"></iframe> <iframe width="720" height="405" src="//youtube.com/v/IplDUxTQxsE?rel=0&vq=hd1080" frameborder="0" allowfullscreen="1"></iframe> I believe the first one uses the new HTML5 youtube player whereas the bottom one (which works) uses the older flash player. However, the second one doesn't seem to load correctly in Safari/Firefox etc so probably not usable. A: 2021 here is my answer that works. https://youtube.com/embed/ZkTzXrczk5M?vq=hd720p;feature=oembed&amp;controls=0&amp;hd=1&amp;modestbranding=1&amp;autohide=1&amp;showinfo=0 The secret is in placing a "p" e.g. ?vq=hd720p not ?vq=hd720, after your desired resolution on the of the src. A: None of the above solutions seem to work if the width/height is less than the line resolution of quality you select. For example, the following doesn't work for me in Chrome: <iframe width="720" height="480" src="//youtube.com/embed/hUezoHa1ZF4?autoplay=true&rel=0&vq=hd720" frameborder="0" allowfullscreen></iframe> I want to show the high quality video, but not use up 1280 x 720 pixels on the webpage. When I go to youtube itself, playing 720p video in a 720x480 window looks better than 480p at the same size. I want to play 720p in a 720x480 window (downsampled better quality). There is no good solution yet afaik. A: You can do this by adding a parameter &hd=1 to the video URL. That forces the video to start in the highest resolution available for the video. However you cannot specifically set it to 720p, because not every video has that hd ish. http://www.youtube.com/watch?v=VIDEO_ID&hd=1 http://code.google.com/apis/youtube/player_parameters.html UPDATE: as of 2014, hd is deprecated https://developers.google.com/youtube/player_parameters?csw=1#Deprecated_Parameters A: In case you're still wondering how to do it, then add: &feature=youtu.be&hd=1 Actually now I checked, this works only when you're sending the URL to someone else, not on embed. A: (This answer was updated, as the previous method using vq isn't recognized anymore.) Specifying the height of the video will change the quality accordingly. example for html 5; <iframe style='width:100%; height:800px;' src='https://www.youtube.com/embed/xxxxxxxx'></iframe> If you don't want to hardcode the width and height you can add a class to the iframe for css media queries. Tested on a working server + passes the w3.org nuhtml validator. A: Use this, it works 100% _your_videocode?rel=0&vq=hd1080"
{ "language": "en", "url": "https://stackoverflow.com/questions/7582336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "51" }
Q: Rails 3.1, memory leak for missing local partial variables (Ruby 1.9.2-p290) If I render a partial like so: = render :partial => "event_news_item", :object => event, :variable => true And then reference variable in the partial a memory leak is triggered. It seems rails goes into a recursion. I have to then quickly restart my server before memory usage spirals out of control. Anyone knows why the memory leak is triggered here? Can anyone confirm this on their machine? If I do = render :partial => "event_news_item", :object => event An error is raised correctly when trying to reference variable in the partial. (The correct way of doing this by the way is = render :partial => "event_news_item", :object => event, :locals => { :variable => true }) A: I have seen a really bad memory leak in similar environment. I've tracked it to the innocently looking association fetch (comment.author, to be precise), then tried to debug it for some time, and finally gave up and ran on 1.9.3-rc1. Surprisingly, that fixed this particular memory leak, and, moreover, reduced the unicorns' startup size by 15M (from 85M to 70M; i386).
{ "language": "en", "url": "https://stackoverflow.com/questions/7582338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: reorder cells dynamically through code(without dragging cell) with the animation I have sorted data coming from server and I am displaying it on tableview, however, there is a another functionality on cell, that If I do that functionality, cells should be rearranged accordingly. I want to have animation like reordering cell using reordercontrol of table view cell. Does anyone know, how to animate like reordering cells? A: Check this post at Matt Gallagher's blog Cocoa With Love. It has a great project that shows how to animate rows and a lot of cool stuff about customizing UITableviews.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get a JPA-persisted String[] column by ResultSet#getString() in JDBC? I want to store multiple checkbox values in a single DB column. I don't want to store in a seperate table with @OneToMany. This is the JPA entity: @Entity @Table(name="COOK") ... @Column(name="ARRAY_FOOD" ) private String[] arrayFood; ...getter and setters... Here are the checkbox values (JSF): <h:selectManyCheckbox value="#{foodBean.selectedModel.arrayFood}" layout="lineDirection"> <f:selectItem itemLabel="FISH" itemValue="FISH" /> <f:selectItem itemLabel="SOUP" itemValue="SOUP" /> <f:selectItem itemLabel="CAKE" itemValue="CAKE" /> <f:selectItem itemLabel="1/2 WATER" itemValue="1/2 WATER" /> <f:selectItem itemLabel="BANANA 1KG" itemValue="BANANA 1KG" /> </h:selectManyCheckbox> JPA stores the submitted checked values as follows: Column Name Data Type Sample Data ---------------------------------------- ARRAY_FOOD RAW (255) ACED0005757200135B4C6A6176612E6C616E672E537472696E673BADD256E7E91D7B4702000078700000000174000141 How can I get the original array by ResultSet in aother program? String array = rs.getString("ARRAY_FOOD"); // ??????????? Or how can I format it in a understandable format like so in other program I can split it by char like ";" : FISH;SOUP;BANANA 1KG A: By default serializable types that are not supported database types are serialized. You would need to use Java serialization to get these types back outside of JPA. You could instead use a @Converter to convert the array as you wish if using EclipseLink. You could also use get/set method to convert the value, see, http://en.wikibooks.org/wiki/Java_Persistence/Basic_Attributes#Conversion
{ "language": "en", "url": "https://stackoverflow.com/questions/7582353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# Default Value at Method - compile error : compile-time constant private static Vector2 DefaultMulFactors = new Vector2(0.5f, 0.5f); private static Point DefaultShifts = new Point(0,0); public static Vector2 Function(Vector2? mulFactors = MyClass.DefaultMulFactors , Point? shifts = MyClass.DefaultShifts ) { ... return result; } Why does my code not accept my static values? How can I assign default parameters to my function parameters? Indeed Vector2? mulFactors = new Vector(0.2,0.3) or Vector2? mulFactors = Vector2.Zero does not work. A: You can't, basically. The value must be supported by the compiler to allow that type of usage (it is essentially a constant). I would just use null here: , Point? shifts = null) then: if(shifts == null) shifts = MyClass.DefaultShifts; A: From MSDN: Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used. A default value must be one of the following types of expressions: a constant expression; an expression of the form new ValType(), where ValType is a value type, such as an enum or a struct; an expression of the form default(ValType), where ValType is a value type. No one of mentioned cases is yours, that's why it doesn't work for you! :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7582362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: "Edit profile" form is not populated using FOSUserBundle I have User entity with properties like name, address, and I want these fields to be editable on "edit profile" page. Sounds easy, but I couldn't make it work following official documentation. My form is not populated with the User data, though I have configured services (form type, form handler). I suppose that it might be because $this->form->getData() should get CheckPassword object, but I pass User entity to it (function process() in ProfileFormHandler.php). Or not ? How to populate form with User data? All related files are here - http://www.pastie.org/2604806
{ "language": "en", "url": "https://stackoverflow.com/questions/7582368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create and validate check box programmatically using Java in Android I need to create a number of check boxes programmatically using Java, check if one of them is checked and when I click Next Button the control will move to next page. If none of them is checked a toast message has to be displayed. Please suggest as I am new to Android. Here is my code: public class TestValidCheckboxActivity extends Activity implements OnCheckedChangeListener{ private RelativeLayout layoutMiddle = null; private TableLayout layout1; private CheckBox chk; private String[] resarr = {"silu", "pinky", "meera"}; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); layoutMiddle = (RelativeLayout)findViewById(R.id.layoutMiddleUp); layout1 = (TableLayout)findViewById(R.id.tableId1); final Button btnNext = (Button)findViewById(R.id.btnNext); int i = 0; for(String res: resarr){ TableRow tr=new TableRow(this); chk=new CheckBox(this); chk.setId(i); chk.setText(res); chk.setTextColor(Color.BLACK); tr.addView(chk); i++; RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT); lay.addRule(RelativeLayout.BELOW, layoutMiddle.getId()); layout1.addView(tr, lay); } chk.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton arg0, boolean arg1) { // TODO Auto-generated method stub if (arg1) { btnNext.setOnClickListener(new View.OnClickListener() { public void onClick(final View view) { Log.e("1111111111","111111111"); if(chk.isChecked()){ Intent intent = new Intent(view.getContext(),NextPage.class); startActivityForResult(intent, 0); }else{ Toast msg = Toast.makeText(view.getContext(), "please choose at least one option", Toast.LENGTH_LONG); msg.show(); } } }); }else{ Toast msg = Toast.makeText(TestValidCheckboxActivity.this, "please choose at least one option", Toast.LENGTH_LONG); } } }); } @Override public void onCheckedChanged(CompoundButton arg0, boolean arg1) { // TODO Auto-generated method stub } } A: this can be easily done take a boolean flag and set true it on checkbox.isChecked();(inbuilt) then check if flag is set then navigate to next else TOAST A: Can you show us some of your layout code, meaning, are the checkboxes defined in an xml file and do they have IDs? If they do, you can access each of them with findViewByID and check their status one by one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Encrypting video sent from Android device to server We have developed an Android application that streams H264 & MJPEG video from the android device to a server through internet connection, using HTTP protocol both for authentication and video. Right now, the authentication part is encrypted using RSA. Now we are looking for a solution that will allow us to send the video encrypted with the minimum additional computational cost. Symmetric key encryption such as AES over the whole video is unacceptable. Looking for any advice on how to do it, either on H264, MJPEG or both. A: "Symmetric key encryption such as AES over the whole video is unacceptable." Why? Use a stream cipher and encrypt the chunks you send as you send them. The simplest way to send the video encrypted is of course to use HTTPS (TLS) instead of plain HTTP to send the video to the server.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ASPX post back problems with combobox I've created a simple ASPX page that lists records in a GridView. The records are a list of incidents and one of the columns is the ID of the person who reported the incident. The initial page shows all records but I would like to provide a filter for the ReportedBy column. I've gotten this working by allowing the user to type in the ReportedByID in a textbox and then clicking on the submit button. This refreshes the page as expected with the filtered view. The code for this page is as follows: public MyPage() { this.Load += new EventHandler(Page_Load); } protected void Page_Load(object sender, EventArgs e) { if (IsPostBack == false) { DataAccessObj daObj = new DataAccessObj(); IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(0); IncidentGrid.DataBind(); } } protected void btnSubmit_Click(object sender, EventArgs e) { int reportedById = 0; if (int.TryParse(txtReportedById.Text, out reportedById) == false) { reportedById = 0; } DataAccessObj daObj = new DataAccessObj(); IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(reportedById); IncidentGrid.DataBind(); } To make it more user friendly, I decided to add a dropdown box populated with the ReportedBy names for the user to select which would then be used to filter on upon clicking the submit button. The dropdown box has names as the display items but the values should still be set to the IDs. The problem I have is that the ID number I get from the dropdown box always comes up as the first element of the list rather than the one the user selected at the time they clicked on the submit button. The code for this page with this implementation is as follows: public MyPage() { this.Load += new EventHandler(Page_Load); } protected void Page_Load(object sender, EventArgs e) { DataAccessObj daObj = new DataAccessObj(); foreach (ReportedByItem repByItem in daObj.GetAllReportedBy()) { ListItem listItem = new ListItem(repByItem.Name, repByItem.Id.ToString()); combobox.Items.Add(listItem); } if (IsPostBack == false) { IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(0); IncidentGrid.DataBind(); } } protected void btnSubmit_Click(object sender, EventArgs e) { int reportedById = 0; if (combobox.SelectedItem != null) { if (int.TryParse(combobox.SelectedItem.Value, out reportedById) == false) { reportedById = 0; } } DataAccessObj daObj = new DataAccessObj(); IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(reportedById); IncidentGrid.DataBind(); } Any help would be gratefully appreciated. TIA A: Keep in mind that with WebForms the Page_Load code is executed before the event handler code for the control which created the postback. You have to populate the list in the section where postbacks flags are checked, just like you do with the grid. if (IsPostBack == false){ //bind the combobox } Otherwise, on a postback, the list will re-populate and the selection will be gone. A: protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { DataAccessObj daObj = new DataAccessObj(); foreach (ReportedByItem repByItem in daObj.GetAllReportedBy()) { ListItem listItem = new ListItem(repByItem.Name, repByItem.Id.ToString()); combobox.Items.Add(listItem); } IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(0); IncidentGrid.DataBind(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7582376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Disabled cell's button click event fire I have a table in which there is a button in one cell. Now when I am disabling that cell, the cell gets disabled but on clicking upon that cell, button click event is happening. So instead of disabling the cell, I disabled the button. Now everything working fine, but I wanted to know that why on disabling the cell, button click event was getting fired? my code snippet is like below: To disable cell-(previous approach) --- grid.rows[i].cells[1].disabled=true; To disable button:(new approach)-- grid.rows[i].cells[1].firstChild.disabled=true; A: From the html4 spec: The following elements support the disabled attribute: BUTTON, INPUT, OPTGROUP, OPTION, SELECT, and TEXTAREA. Looking at the html4 spec for td, there is nothing saying disabled is valid. So that means setting disabled on the table's cell does nothing. You need to set individually on the form elements inside of the cell. What you are doing now is randomly setting some property on the cell that means nothing to it. It is the same thing as setting grid.rows[i].cells[1].foobar=true;. It means nothing, but the cell has it attached to it. A: I think it maybe happening because when u disable the cell then the button element does not get disabled. It still remains enabled, unlike the cell.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to set the default HTML5-Video volume? HTML5 videos always start at 100% volume. How can I make them start at 50% volume? A: Assuming you're good with mixing JS into your HTML, you can leverage one of the events, such as loadstart: <video onloadstart="this.volume=0.5" ...> A: You can affect the volume property of the <video> element as follows: document.getElementsByTagName('video')[0].volume = 0.5; If using jQuery then you can use their prop method to alter the volume in a jQuery collection object like so: $("video").prop("volume", 0.5); This will alter all DOM elements in the collection. A: var video = document.getElementById('player'); video.volume = 0.5; P.S. Use this script for compatibility. A: If you don't want to mess with javascript, you can do it like this: <video muted=""> <source src="yourvideo.mp4" type="video/mp4"> </video> A: <div> <video id="sampleMovie" src="mp4/Premier delivery.mp4" width="777" height="582.75" controls autoplay ></video> <script> var video = document.currentScript.parentElement; video.volume = 0.1; </script> </div> Works perfectly! A: With jQuery need to use a little trick: $('#your_video_id').get(0).volume = 0; A: Setting the default volume, using jquery: $(function() { $("video").each(function(){ this.volume = 0.5; }); }); A: The React way using useCallback import { useCallback } from "react" const vid = useCallback((x) => x.volume = 0.5) return ( <video ref={vid} /> )
{ "language": "en", "url": "https://stackoverflow.com/questions/7582385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "48" }
Q: Highlighting entire table row if validation fails I am working on JSF2.0 and Richfaces. I am having an requirement where I need to change the style of the form field(entire row) if the validation fails. I am using the following code to display field label and text box. <h:panelGrid columns="2"> <h:outputLabel value="#{uit.firstname}:"> <span class="required"><strong>*</strong> </span> </h:outputLabel> <h:inputText value="#{editUserProfileBean.firstName}" type="text" id="firstname" styleClass="basicFormTextBox" size="30" required="true" requiredMessage="#{uitkem.valueRequired}" validatorMessage="#{prod.firstNameValidator}"> <f:validateLength maximum="#{prodConf.MaxLengthForFirstName}" minimum="#{prodConf.MinLengthForFirstName}" /> <f:validator validatorId="trimSpaces" /> </h:inputText> </h:panelGrid> Suppose if the validation fails, I need to hightlight the row(both label and textbox). I can use the following code to hightlight the textbox if the validation fails. But I want to hightlight the entire row, that is not possible using the following code. <h:inputText value="#{editUserProfileBean.firstName}" required="true" styleClass="#{not component.valid ? 'newStyleClass' : ''}" /> Can anyone help me on this? Thanks in advance. A: You could just write a tiny JS script with jQuery, or use <rich:jQuery> for that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Looking for OCaml IDE I like F# but sometimes I need something light and cross-platform and without .NET for sure. I tried to use OCamL many times but seems like I just can't start it. * *Installed IDEA, added OCamL plugin -> Doesn't work *Installed eclipse ODT plugin -> Can't launch even config OCamL compiler - too complicated *Even had tried NetBeans plugin a long time ago but even can't deal with it. So, for now, I'm using ocamlc -o "main.exe" "main.ml" from the command shell and different light editors. I don't use Vim or Emacs, I'm using nano and I have a habit of usage full-featured IDEs. I found various documentation (this is looking like the best to start http://caml.inria.fr/pub/docs/oreilly-book/html/index.html for me) but still being confusing when looking for something a bit specific alike sqlite access. found this: http://neugierig.org/software/ocaml/sqlite/ with strange api annotation and no examples. And all the documentation about IDE usage I found are outdated or doesn't work. Addition subquestion: some people told me "don't use OCamL, it's a dead language for students with low libraries support and seems like dying, use python or ruby instead". But I like the beauty of OCamL. I want to give it a try. Tell me if that is normal to use OCamL for production code today? thank you. A: There are a few options: * *Tuareg for emacs was already mentioned: http://tuareg.forge.ocamlcore.org/ *vim has a few options for OCaml integration, with one good example available here: http://www.ocaml.info/software.html#vim *OcaIDE seems to be the best option for Eclipse: http://www.algo-prog.info/ocaide/ *Geany, Komodo Edit and a number of other editors have syntax highlighting support for OCaml and some extra IDE-like features which are independent of the programming language being used. Most of these have limited OCaml-specific support. OCaml is not dead. Some of the more vocal industry users of OCaml are XenSource/Citrix and Jane St. Capital. The language does not receive the same public and community evangelism that some other languages receive. A: It's been years, but I really liked emacs' tuareg mode http://tuareg.forge.ocamlcore.org/ But if you're afraid of emacs, then it's not the right tool. I specially like the shell integration and the possibility to "throw" a function you're developping in the shell and then test it. EDIT For the subquestion, OCaml seems dead, and it's a pitty. However you cannot compare it with ruby/python. I'd say it's main competitor is Haskell which seems to be growing in popularity. A: There is TypeRex, a new development environment for OCaml. Here is a summary of TypeRex features: * *Improved syntax coloring *Auto-completion of identifiers (experimental) *Browsing of identifiers: show type and comment, go to definition, cycle between alternate definitions, and semantic grep; *Strictly semantic-preserving, local and whole-program refactoring: * *renaming identifiers and compilation units *open elimination and reference simplification *Robust w.r.t. not-recompiled, possibly unsaved buffers *Scalable (used regularly on a few hundreds of source files) There are some screenshots available on the website. The first release candidate is out since yesterday. EDIT: The first release (v1.0) is out now :-) A: Googling "ocaml ide" shows now http://camelia.sourceforge.net/ as the first result. Haven't tested it though, so I can't really say if it is recommendable or not.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Help with creating a Parcelable class I am trying to create a Parcelable class. The class extends TableRow: import android.content.Context; import android.os.Parcel; import android.os.Parcelable; import android.widget.TableRow; public class AcmTableRow extends TableRow implements Parcelable{ private int index; public boolean isSection; private String volumeLink; private String rowId; private String cfr; private static Context context; public AcmTableRow(Context context) { super(context); } public AcmTableRow(Context context, Parcel in) { super(context); AcmTableRow.context = context; readFromParcel(in); } private void readFromParcel(Parcel in) { //strValue = in.readString(); //intValue = in.readInt(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { //dest.writeString(strValue); //dest.writeInt(intValue); } public void setIndex(int index) { this.index = index; } public int getIndex() { return index; } public void setRowId(String rowId) { this.rowId = rowId; } public String getRowId() { return rowId; } public void setCfr(String cfr) { this.cfr = cfr; } public String getCfr() { return cfr; } public void setVolumeLink(String volumeLink) { this.volumeLink = volumeLink; } public String getVolumeLink() { return volumeLink; } public static final Parcelable.Creator<AcmTableRow> CREATOR = new Parcelable.Creator<AcmTableRow>() { public AcmTableRow createFromParcel(Parcel in) { return new AcmTableRow(context, in); } public AcmTableRow[] newArray(int size) { return new AcmTableRow[size]; } }; } I am confused as what I need to put in: readFromParcel(Parcel in) And writeToParcel(Parcel dest, int flags) Any explanation or help is greatly appreciated. Thank you Phil A: The writeToParcel method simply flattens the object into a parcel. You'll use this when you need to pass your object between activities. In your case, it should look like this: public void writeToParcel (Parcel dest, int flags) { dest.writeInt(index); dest.writeBoolean(isSection); dest.writeString(volumeLink); dest.writeString(rowId); dest.writeString(cfr); } I've never had to use readFromParcel and I'm not sure you need to here either. Your object will be created from the Parcel when you call the appropriate method in your next activity. Just a quick note, you probably don't want to pass the context in your parcelable class. I'm not even sure you can. You'll need to assign the context when you inflate the parcelable again later on. A: This is a simple working Parcelable example: public class ParcelableExample implements Parcelable { private int intMember; private String stringMember; /* * Getters and setters * .... */ /* * Constructors * .... */ /* * Custom parcelable implementation */ private ParcelableExample(Parcel in) { // notice that we are reading in the same order as we have written intMember = in.readInt(); stringMember = in.readString(); } @Override public int describeContents() { return hashCode(); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(intMember); dest.writeString(stringMember); } @SuppressWarnings("rawtypes") public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public ParcelableExample createFromParcel(Parcel in) { return new ParcelableExample(in); } public ParcelableExample[] newArray(int size) { return new ParcelableExample[size]; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7582391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: strdup or _strdup? When I use strdup in Microsoft Visual C++, it warns me: warning C4996: 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup. See online help for details. Thus it seems _strdup is correct. But when I use _strdup in GCC (Fedora Linux OS), the compiler shows an error: error: ‘_strdup’ was not declared in this scope With GCC and Linux, compiler does not show any error for strdup. Which is correct - strdup or _strdup? Note: I include <string.h> in my code. A: strdup is POSIX: http://pubs.opengroup.org/onlinepubs/9699919799/functions/strdup.html _strdup is Windows specific: http://msdn.microsoft.com/en-us/library/y471khhc(v=vs.80).aspx On Unix, use strdup. On Windows, use _strdup. It's that simple. If you need to write portable code between Unix and Windows: * *use system dependent macros (for example _WIN32 vs. _POSIX_VERSION) to select the proper function (but notice that the macros may depend on specific pre existing include files): http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/unistd.h.html http://msdn.microsoft.com/en-us/library/b0084kay(v=vs.80).aspx * *use standard functions to reimplement strdup: strlen, malloc and memmove. *use a cross platform utility library, like glib: http://developer.gnome.org/glib/2.28/glib-String-Utility-Functions.html#g-strdup Note that Visual C++ message suggests that _strdup belongs to the C++ standard, but this is false, as it can be verified on the C++ standard. It merely uses the underscore prefix as a "namespace" for the function. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3376.pdf A: Don't know about C++. The C Standard does not describe any function with the strdup name (though the name is reserved). To be portable, in C, you're better off replacing that with malloc, strcpy, and free. A: Which is correct? strdup is a perfectly correct POSIX function. Nevertheless, it doesn't belong to the standard, and the ANSI C standard reserves some (broad) classes of function names for further use. Among these, there are * *Function names that begin with str and a lowercase letter therefore, the MS guys decided to replace strdup with _strdup. I'd just continue using strdup. It's unlikely the C committee will define strdup to something else than POSIX. Either #define strdup _strdup or silence the warning. BTW I hope you see this applies to your functions with names like string_list etc., too. A: strdup is not a standard C++ function. but it is apparently a Posix function, and anyway it's a well known function which has been there since K&R C. so if you absolutely must use it, do not fret about any possible name collision, and just write strdup for maximum portability. A: You can #define _CRT_NONSTDC_NO_DEPRECATE to disable this warning. A: If you just want to avoid the Warning message: Project-> property -> C/C++ -> Preprocessor -> Preprocessor Definitions Edit this, and add _CRT_NONSTDC_NO_DEPRECATE A: it's not a warning but an error reported in higher version of vs. use macro #ifdef WIN32 to switch
{ "language": "en", "url": "https://stackoverflow.com/questions/7582394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "69" }
Q: Can I use Mercurial to allow different users access to different parts of a project? We're using SVN, but it seems to be getting a little out of date and heavy for our liking. We have a big project that we need different team members to get access to different parts of. Can we set up Mercurial is a way that certain people can checkout / update the entire project, where as some other people only check out / access certain parts of the project? A: There's the ACL extension which is shipped as part of Mercurial that may be suitable for your needs. A: My initial thought is that it could be done using subrepos. If you can split your project into defined parts, these could be set up as sub-repositories. You would have a parent repository which contains all of the sub-repositories. The sub-repositories themselves could be set up to be accessible only by certain people.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rotate a vector about another vector I am writing a 3d vector class for OpenGL. How do I rotate a vector v1 about another vector v2 by an angle A? A: You may find quaternions to be a more elegant and efficient solution. After seeing this answer bumped recently, I though I'd provide a more robust answer. One that can be used without necessarily understanding the full mathematical implications of quaternions. I'm going to assume (given the C++ tag) that you have something like a Vector3 class with 'obvious' functions like inner, cross, and *= scalar operators, etc... #include <cfloat> #include <cmath> ... void make_quat (float quat[4], const Vector3 & v2, float angle) { // BTW: there's no reason you can't use 'doubles' for angle, etc. // there's not much point in applying a rotation outside of [-PI, +PI]; // as that covers the practical 2.PI range. // any time graphics / floating point overlap, we have to think hard // about degenerate cases that can arise quite naturally (think of // pathological cancellation errors that are *possible* in seemingly // benign operations like inner products - and other running sums). Vector3 axis (v2); float rl = sqrt(inner(axis, axis)); if (rl < FLT_EPSILON) // we'll handle this as no rotation: { quat[0] = 0.0, quat[1] = 0.0, quat[2] = 0.0, quat[3] = 1.0; return; // the 'identity' unit quaternion. } float ca = cos(angle); // we know a maths library is never going to yield a value outside // of [-1.0, +1.0] right? Well, maybe we're using something else - // like an approximating polynomial, or a faster hack that's a little // rough 'around the edge' cases? let's *ensure* a clamped range: ca = (ca < -1.0f) ? -1.0f : ((ca > +1.0f) ? +1.0f : ca); // now we find cos / sin of a half-angle. we can use a faster identity // for this, secure in the knowledge that 'sqrt' will be valid.... float cq = sqrt((1.0f + ca) / 2.0f); // cos(acos(ca) / 2.0); float sq = sqrt((1.0f - ca) / 2.0f); // sin(acos(ca) / 2.0); axis *= sq / rl; // i.e., scaling each element, and finally: quat[0] = axis[0], quat[1] = axis[1], quat[2] = axis[2], quat[3] = cq; } Thus float quat[4] holds a unit quaternion that represents the axis and angle of rotation, given the original arguments (, v2, A). Here's a routine for quaternion multiplication. SSE/SIMD can probably speed this up, but complicated transform & lighting are typically GPU-driven in most scenarios. If you remember complex number multiplication as a little weird, quaternion multiplication is more so. Complex number multiplication is a commutative operation: a*b = b*a. Quaternions don't even preserve this property, i.e., q*p != p*q : static inline void qmul (float r[4], const float q[4], const float p[4]) { // quaternion multiplication: r = q * p float w0 = q[3], w1 = p[3]; float x0 = q[0], x1 = p[0]; float y0 = q[1], y1 = p[1]; float z0 = q[2], z1 = p[2]; r[3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1; r[0] = w0 * x1 + x0 * w1 + y0 * z1 - z0 * y1; r[1] = w0 * y1 + y0 * w1 + z0 * x1 - x0 * z1; r[2] = w0 * z1 + z0 * w1 + x0 * y1 - y0 * x1; } Finally, rotating a 3D 'vector' v (or if you prefer, the 'point' v that the question has named v1, represented as a vector), using the quaternion: float q[4] has a somewhat strange formula: v' = q * v * conjugate(q). Quaternions have conjugates, similar to complex numbers. Here's the routine: static inline void qrot (float v[3], const float q[4]) { // 3D vector rotation: v = q * v * conj(q) float r[4], p[4]; r[0] = + v[0], r[1] = + v[1], r[2] = + v[2], r[3] = +0.0; glView__qmul(r, q, r); p[0] = - q[0], p[1] = - q[1], p[2] = - q[2], p[3] = q[3]; glView__qmul(r, r, p); v[0] = r[0], v[1] = r[1], v[2] = r[2]; } Putting it all together. Obviously you can make use of the static keyword where appropriate. Modern optimising compilers may ignore the inline hint depending on their own code generation heuristics. But let's just concentrate on correctness for now: How do I rotate a vector v1 about another vector v2 by an angle A? Assuming some sort of Vector3 class, and (A) in radians, we want the quaternion representing the rotation by the angle (A) about the axis v2, and we want to apply that quaternion rotation to v1 for the result: float q[4]; // we want to find the unit quaternion for `v2` and `A`... make_quat(q, v2, A); // what about `v1`? can we access elements with `operator [] (int)` (?) // if so, let's assume the memory: `v1[0] .. v1[2]` is contiguous. // you can figure out how you want to store and manage your Vector3 class. qrot(& v1[0], q); // `v1` has been rotated by `(A)` radians about the direction vector `v2` ... Is this the sort of thing that folks would like to see expanded upon in the Beta Documentation site? I'm not altogether clear on its requirements, expected rigour, etc. A: This may prove useful: double c = cos(A); double s = sin(A); double C = 1.0 - c; double Q[3][3]; Q[0][0] = v2[0] * v2[0] * C + c; Q[0][1] = v2[1] * v2[0] * C + v2[2] * s; Q[0][2] = v2[2] * v2[0] * C - v2[1] * s; Q[1][0] = v2[1] * v2[0] * C - v2[2] * s; Q[1][1] = v2[1] * v2[1] * C + c; Q[1][2] = v2[2] * v2[1] * C + v2[0] * s; Q[2][0] = v2[0] * v2[2] * C + v2[1] * s; Q[2][1] = v2[2] * v2[1] * C - v2[0] * s; Q[2][2] = v2[2] * v2[2] * C + c; v1[0] = v1[0] * Q[0][0] + v1[0] * Q[0][1] + v1[0] * Q[0][2]; v1[1] = v1[1] * Q[1][0] + v1[1] * Q[1][1] + v1[1] * Q[1][2]; v1[2] = v1[2] * Q[2][0] + v1[2] * Q[2][1] + v1[2] * Q[2][2]; A: Use a 3D rotation matrix. A: The easiest-to-understand way would be rotating the coordinate axis so that vector v2 aligns with the Z axis, then rotate by A around the Z axis, and rotate back so that the Z axis aligns with v2. When you have written down the rotation matrices for the three operations, you'll probably notice that you apply three matrices after each other. To reach the same effect, you can multiply the three matrices. A: I found this here: http://steve.hollasch.net/cgindex/math/rotvec.html let [v] = [vx, vy, vz] the vector to be rotated. [l] = [lx, ly, lz] the vector about rotation | 1 0 0| [i] = | 0 1 0| the identity matrix | 0 0 1| | 0 lz -ly | [L] = | -lz 0 lx | | ly -lx 0 | d = sqrt(lx*lx + ly*ly + lz*lz) a the angle of rotation then matrix operations gives: [v] = [v]x{[i] + sin(a)/d*[L] + ((1 - cos(a))/(d*d)*([L]x[L]))} I wrote my own Matrix3 class and Vector3Library that implemented this vector rotation. It works absolutely perfectly. I use it to avoid drawing models outside the field of view of the camera. I suppose this is the "use a 3d rotation matrix" approach. I took a quick look at quaternions, but have never used them, so stuck to something I could wrap my head around.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: CSS @font-face not working in IE8 I have tried reading multiple articles on how to deal with custom fonts in IE, but they never seemed to work for me. I tried converting the fonts to EOT, but that didn't seem to work either. I am not sure what I am doing wrong, so I will post my code @font-face { font-family: "Klavika Regular"; src: url('../fonts/klavika.eot'); src: local('☺'), url('../fonts/klavika.woff') format('woff'), url('../fonts/klavika.ttf') format('truetype'), url('../fonts/klavika.svg') format('svg'); font-weight: normal; font-style: normal; } A: this works in ie8/9 http://dev.bowdenweb.com/a/fonts/serif/alegreya/demo.html @font-face { font-family: 'AftaserifRegular'; src: url('AftaSerifThin-Regular-webfont.eot'); src: url('AftaSerifThin-Regular-webfont.eot?#iefix') format('embedded-opentype'), url('AftaSerifThin-Regular-webfont.woff') format('woff'), url('AftaSerifThin-Regular-webfont.ttf') format('truetype'), url('AftaSerifThin-Regular-webfont.svg#AftaserifRegular') format('svg'); font-weight: normal; font-style: normal; } A: if IE8 thinks it supports any other format other than eot of the ones listed below, then it will probably try to use that one. Maybe you could use a IE8 hack, like src: local('☺'), url('../fonts/klavika.woff') format('woff'), url('../fonts/klavika.ttf') format('truetype'), url('../fonts/klavika.svg') format('svg'); src /*\**/: url('../fonts/klavika.eot')\9 so only IE8 will read the last src line and thus load the .eot. A: Try three kinds of CSS Formats for @font-face on FontSquirrel Generator (in "EXPERT..." mode > in section "CSS Formats:" > "more information") A: It's worth checking to see if your .htaccess file allows the file type.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: Conflict between Mootools and a pure JS script I am stuck with a pure JS script that should be included in Joomla (1.7, Mootools 1.3.2) and raises a conflict with this library while working perfectly outside it. Examples : * *no Mootools http://jsfiddle.net/2W87v/ *with Mootools http://jsfiddle.net/2W87v/1/ Firebug error around line 133 : document.getElementById("pu_" + champs[i]) is null I tried all kinds of solutions, renaming certain variables, using $ instead of document.getElementById, wrapping each function around an anonymous function. To no avail. If someone could point in the right direction, I'd be very grateful. A: mootools is prototypical. var champs = ['surfaceMaison','surfaceGarage','terrasseCouverte','terrasseNonCouverte','cloture']; var prix = ['pack','valeur','valeur','valeur']; var options = ['toitureMultipentes','doucheItalienne','wcSuspendu','enduitTaloche','voletsRoulants','climGainable']; // and.. for (var i in champs) for (var i in options) is a no go as is, it will go up the prototype chain and get the stuff mootools adds to the Array prototype. in general, for var in object as a construct has always been intended for OBJECTS and not arrays. it works anyway, because in javascript you don't have a proper Array type, it's just an Object type with Array-like properties (eg, length). loop the arrays via options.each(function(el, i) {} or a normal for loop instead. also, you can check for hasOwnProperty: for (var i in champs) if (champs.hasOwnProperty(i)) { // do the stuff }
{ "language": "en", "url": "https://stackoverflow.com/questions/7582407", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: replace text with image, Data from .net web service android Possible Duplicate: replace images in data from webservice android can any one tell me how to display a image instead of a text. Text coming from web service. Eg: I send "hi android". I need to replace text "android" with "icon.png" image. How can i achieve this. Please help me in solving this issue. Thanks. A: Put an ImageView in your layout, set it's visibility as gone by default. When ever you are ready with your image, make the textView visibility gone and put the ImageView visibility to visible . Don't forget to set the ImageView resource before making it visible. HTH.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: StatLight hangs when run from TeamCity as single command I'm running TeamCity 6.5 on a Windows Server, with a couple of build agents on the same server (all running as the system user as services). I had been building SilverLight projects and running the StatLight (v 1.4.4147) tests previously under Jenkins with no problems. On Jenkins, I called the StatLight test in a custom script as follows: StatLight.exe -x="Tests.xap" StatLight.exe -x="MoreTests.xap" StatLight.exe -x="EvenMoreTests.xap" ... etc., but when I migrated my build jobs to TeamCity, I also changed these into a single command line step as follows: StatLight.exe --teamcity -x="Tests.xap" -x="MoreTests.xap" -x="EvenMoreTests.xap" This works about 50% of the time, but when it fails, there's no output in the build log to tell me why - I just get: [11:41:18]: [MyProject\bin\Release\MoreTests.xap] Tests.ExtensionsTests.WatchObservableCollection [11:41:18]: [MyProject\bin\Release\MoreTests.xap] Tests.SubscribingModelBaseTests.DisposeIsCalled [11:41:18]: [MyProject\bin\Release\MoreTests.xap] --- Completed Test Run at: 28/09/2011 11:41:18. Total Run Time: 00:00:11.8125000 [11:41:19]: [MyProject\bin\Release\MoreTests.xap] Test run results: Total 6, Successful 6, Failed 0, [11:41:19]: [Step 5/6] MyProject\bin\Release\EvenMoreTests.xap (9m:42s) ... and then nothing more. The time reported in that last line just goes up and up until I kill the the build job. Adding the --debug switch to StatLight doesn't improve the above output either. Right now, I've switched the TeamCity build step to call each test individually as I was in Jenkins, but this is more of a workaround than a proper solution. And of course, I may still run into the above problem - I've yet to find out. What I'd like to know is what steps I can take to debug this issue properly, or whether there are known issues that can cause the above behaviour? A: There was one issue fixed in the 1.5 version relating to teamcity. http://statlight.codeplex.com/workitem/13654 I'm not sure it will fix your issue, but would you mind upgrading, trying and reporting back?
{ "language": "en", "url": "https://stackoverflow.com/questions/7582414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using ViewModel as WPF DataContext Disposing problems Just starting out using WPF / MVVM and have a question regarding using a viewmodel as the datacontext for a wpf window. I'm using a view first approach and my view looks like this; <Window x:Class="TestContext.TestForm" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="TestForm" Height="300" Width="300" DataContext="{StaticResource testViewModel}"> <Grid> <TextBox Text="{Binding Path=Address}" Height="23" HorizontalAlignment="Left" Margin="34,44,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" /> </Grid> </Window> and I create my viewmodel in code like this ; public class ViewModelFactory { public TestViewModel CreateTestViewModel() { return new TestViewModel(); } } I'm using the following approach in the app.xaml to create an instance of the viewmodel whenever I instantiate the view ; <ObjectDataProvider x:Key="testViewModel" ObjectInstance="{StaticResource viewModelFactory}" MethodName="CreateTestViewModel"> This all works fine. The problem is that I only ever see the viewmodel being created once. So new instances of the view use the same instance of the viewmodel. I'd like to start out with a new instance of the viewmodel. If I create the view model manually in the forms constructer ; public TestForm() { InitializeComponent(); this.DataContext = new TestViewModel(); } then it works as expected. I'm trying to get my head around what's happening here... Thanks.... A: Honestly using ObjectDataProvider isnt a good idea to get view models as that instance is single per App. But if you insist to recreate the viewmodels you will have to refresh the testViewModel. The way you do that is testViewModel.Refresh(); A: Yes, Agree with @AngelWPF You should use set DataContext as View.DataContext = ViewModel; A: You could instantiate you view model in the resources section of your view. Once you create new view - you'll get new view model. Moreover, you'll get static bindings which are a bit performant and convenient to use because you'll get intellsense. <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:WpfApplication1="clr-namespace:WpfApplication1" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <WpfApplication1:MyViewModel x:Key="ViewModel"/> </Window.Resources> <Grid DataContext="{StaticResource ViewModel}"> <ItemsControl ItemsSource="{Binding Data}"/> </Grid> </Window> A: In Code * *Create your view *Create Single Property on View (called VM) *Create your viewmodel *Assign the new viewmodel to VM *Set DataContext to ViewModel *Setup your bindings in XAML to point to the correct properties on your view model As a rule * *I never use ObjectDataProviders or instantiate anything in XAML (too buggy) *Always use the MVVM pattern *Be careful of static resources - they are only set once per app instance where dynamic resources can be updated
{ "language": "en", "url": "https://stackoverflow.com/questions/7582417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to recognize objects or patterns in one image? suppose I have two images one contains circle and other contains square,I just want to give input as this images. program should recognize which one is circle and which one is square. how i can implement this using c# language? A: There are a few image recognition libraries out there. Try aforge: http://code.google.com/p/aforge/. Another one is EmguCV for .Net. A: using Emgu.CV: exactly what you want: http://www.emgu.com/wiki/index.php/Shape_(Triangle,_Rectangle,_Circle,_Line)_Detection_in_CSharp
{ "language": "en", "url": "https://stackoverflow.com/questions/7582434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Upgrading Plone 4017 to 4018 I really need some help with Plone. I am experiencing some issue upgrading from 4017 to 4018. All the Plone websites say "The site configuration is outdated and needs to be upgraded." When I press Upgrade I get the following error: "Starting the migration from version: 4017 End of upgrade path, migration has finished The upgrade path did NOT reach current version Migration has failed" I was really hoping someone could help me sort out this issue and also help me get to the latest stable build of Plone 4.1. Thanks. A: This happens when there is a discrepancy between the current Plone setup profile version number and the upgrade steps final version number. Because there is no step from 4017 to 4018 you get this error message. This is not necessarily a problem. Your upgrade to version 4017 worked without a hitch. What exact Plone version are you upgrading to, 4.0.9? It may be worth reporting this as a (low priority) bug, but I doubt there is anything there to prevent you from using your site. To illustrate, I see this all the time when using the latest development version of the Products.CMFPlone package, because that'll be one version 'tick' further than the latest release of the plone.app.upgrade package can upgrade me to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Get physical path corresponding to a network share on local computer I want to be able to get the physical path (C:\somepath...) corresponding to an UNC path to a network share on the local computer (\\mycomputer\somepath...). I've tried doing this using ManagementObjectSearcher as described here. This works fine when running as an Adminstrator, but fails when running from a non-privileged account. No exception is thrown, the SelectQuery simply returns a ManagementObject whose path property is null. I would like to be able to get this information from a non-privileged account, without adding the account to privileged groups such as Administrators or Power Users. Can anyone indicate how to do this - what are the minimum privileges needed to execute this query successfully? I've tried giving permission to the account as described here using Computer Management / WMI Control / Security but this makes no difference - even if I give all permissions to the Root node with Apply onto "this namespace and subnamespaces". A: You would need to give users the ability to execute remote WMI queries, there's an overview at http://msdn.microsoft.com/en-us/library/aa393266.aspx of the DCOM configuration needed. In order to change WMI security from the Windows GUI: * *Open a 'Manage Computer' for the target computer *Open the 'Services and Applications' section *Right-click on 'WMI Control' and choose 'Properties' *Select the security tab, click the Security button, and make the changes - add the 'Remote Enable' privilege to your target group or user.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP Count function with Associative Array Could someone please explain to me how the count function works with arrays like the one below? My thought would be the following code to output 4, cause there are 4 elements there: $a = array ( "1" => "A", 1=> "B", "C", 2 =>"D" ); echo count($a); A: You can use this example to understand how count works with recursive arrays <?php $food = array('fruits' => array('orange', 'banana', 'apple'), 'veggie' => array('carrot', 'collard', 'pea')); // recursive count echo count($food, COUNT_RECURSIVE); // output 8 // normal count echo count($food); // output 2 ?> Source A: count works exactly as you would expect, e.g. it counts all the elements in an array (or object). But your assumption about the array containing four elements is wrong: * *"1" is equal to 1, so 1 => "B" will overwrite "1" => "A". *because you defined 1, the next numeric index will be 2, e.g. "C" is 2 => "C" *when you assigned 2 => "D" you overwrote "C". So your array will only contain 1 => "B" and 2 => "D" and that's why count gives 2. You can verify this is true by doing print_r($a). This will give Array ( [1] => B [2] => D ) Please go through http://www.php.net/manual/en/language.types.array.php again. A: The array you have created only has two elements in it hence the count returning 2. You are overwriting elements, to see whats in your array use : print_r($a);
{ "language": "en", "url": "https://stackoverflow.com/questions/7582443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Calling property changed on a bound element My view model implements INotifyPropertyChanged for properties that it makes available to my view. It makes available a collection of objects that do not implement INotifyPropertyChanged. My collection is bound to an ItemControl in my view, with an ItemTemplate used to display each item invidually. The item template is bound to the Name attribute of my collection members. How can i tell my view to update when properties of my collection members change? A: You must implement INotifyPropertyChanged for collection members. Or you can reset your collection in ViewModel: public void Reset() { List<TestData> temp = YourCollection; YourCollection = null; YourCollection = temp; } A: You need to either implement INotifyPropertyChanged for the objects in your collection (recommend approach), or you can manually refresh the binding by something like myItemsControl.GetBindingExpression( ItemsControl.ItemsSourceProperty).UpdateTarget(); If you're in the ViewModel, you might be able to raise a PropertyChanged event on your Collection class such the following, although I am not sure if that will update the individual items or not // My PropertyChanged method is usually called RaisePropertyChanged RaisePropertyChanged("MyCollection"); You can also do what Mirimon suggeted and set the value to null then back again, although personally I would recommend a different approach if possible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do i increment a global variable while reading my specific tag using xslt2.0? This is my xml Document. <w:document xmlns:w="w"> <w:body> <w:p> <w:r> <w:t> Para1 </w:t> </w:r> </w:p> <w:p> <w:r> <w:t> Para2 </w:t> </w:r> </w:p> <w:p> <w:r> <w:t> Para3 </w:t> </w:r> </w:p> <w:p> <w:r> <w:t> Para4 </w:t> </w:r> </w:p> <w:p> <w:r> <w:t> Para5 </w:t> </w:r> </w:p> <w:tbl> <w:tr> <w:tc> <w:p> <w:r> <w:t> Para6 </w:t> </w:r> </w:p> </w:tc> <w:tc> <w:p> <w:r> <w:t> Para7 </w:t> </w:r> </w:p> </w:tc> </w:tr> </w:tbl> <w:p> <w:r> <w:t> Para8 </w:t> </w:r> </w:p> <w:tbl> <w:tr> <w:tc> <w:p> <w:r> <w:t> Para9 </w:t> </w:r> </w:p> </w:tc> <w:tc> <w:p> <w:r> <w:t> Para10 </w:t> </w:r> </w:p> </w:tc> </w:tr> </w:tbl> <w:p> <w:r> <w:t> Para11 </w:t> </w:r> </w:p> </w:body> </w:document> Now, I want to increment my global variable whenever <w:tbl><w:tr> encounters.for my above xml file,it has two <w:tr> nodes inside <w:tbl>. So, for example : 1. if my current node is Para8 then it's count will be 1. 2. if my current node is para11 then it's count will be 2. How i do it? A: XSLT is a functional language and in any functional language the value of a variable, one set, cannot be updated. One needs a "paradigm shift" -- to start thinking in a functional way -- in order to understand that the "capability" to update variables isn't necessary at all. For any imperative algorithm (that uses variable update) there is a corresponding functional algorithm (that doesn't require update of any variable). There are a number of advantages using a functional programming style over an imperative one -- the main being that a functional program is much better to read, understand, maintain and even prove correct. Due to variables being immutable, the optimizer of a compiler can perform much more aggressive optimizations and this results in more efficient, highly optimized compiled programs. In this particular case, it isn't necessary to update a variable in order to get the required count: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:w="w"> <xsl:output method="text"/> <xsl:strip-space elements="*"/> <xsl:template match="node()|@*"> <xsl:for-each select= "//w:t [contains(., 'Para8') or contains(., 'Para11') ] "> <xsl:number level="any" count="w:tbl/w:tr"/> <xsl:text>&#xA;</xsl:text> </xsl:for-each> </xsl:template> </xsl:stylesheet> When this transformation is applied on the provided XML document: <w:document xmlns:w="w"> <w:body> <w:p> <w:r> <w:t> Para1 </w:t> </w:r> </w:p> <w:p> <w:r> <w:t> Para2 </w:t> </w:r> </w:p> <w:p> <w:r> <w:t> Para3 </w:t> </w:r> </w:p> <w:p> <w:r> <w:t> Para4 </w:t> </w:r> </w:p> <w:p> <w:r> <w:t> Para5 </w:t> </w:r> </w:p> <w:tbl> <w:tr> <w:tc> <w:p> <w:r> <w:t> Para6 </w:t> </w:r> </w:p> </w:tc> <w:tc> <w:p> <w:r> <w:t> Para7 </w:t> </w:r> </w:p> </w:tc> </w:tr> </w:tbl> <w:p> <w:r> <w:t> Para8 </w:t> </w:r> </w:p> <w:tbl> <w:tr> <w:tc> <w:p> <w:r> <w:t> Para9 </w:t> </w:r> </w:p> </w:tc> <w:tc> <w:p> <w:r> <w:t> Para10 </w:t> </w:r> </w:p> </w:tc> </w:tr> </w:tbl> <w:p> <w:r> <w:t> Para11 </w:t> </w:r> </w:p> </w:body> </w:document> the wanted, correct result is produced: 1 2 In case this value should be contained in a variable -- to be used later somewhere in its scope, one will simply define the variable as: <xsl:variable name="vMyCount"> <xsl:number level="any" count="w:tbl/w:tr"/> </xsl:variable> And you can use this variable as in the transformation below: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:w="w"> <xsl:output method="text"/> <xsl:strip-space elements="*"/> <xsl:template match="node()|@*"> <xsl:for-each select= "//w:t [contains(., 'Para5') or contains(., 'Para8') or contains(., 'Para11') ] "> <xsl:variable name="vMyCount"> <xsl:number level="any" count="w:tbl/w:tr"/> </xsl:variable> <xsl:value-of select= "concat($vMyCount, substring('0', 1 + boolean(string($vMyCount))) )"/> <xsl:text>&#xA;</xsl:text> </xsl:for-each> </xsl:template> </xsl:stylesheet> producing the same correct result: 0 1 2
{ "language": "en", "url": "https://stackoverflow.com/questions/7582446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Weird JSpinner behaviour I encountered the weirdest behaviour of swings JSpinner. The spinner looks like this (the component in the middle is the spinner): As you notice, it has no text and no buttons and it behaves like a disabled JTextField. I tried setEnable(true), but nothing happend. The JSpinner is on a transparent JPanel, wich is added to a JFrame with a background image. I suspect that this has something to do with this problem. Note that the same behavior occurs with a JComboBox, but every other Component (like a JTextField or a JSlider) works perfectly fine. Any ideas? Thanks A: You have to use synchronized(this.getTreeLock()) { this.validateTree() }.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jquery Autocomplete plugin working with older versions of the browsers but not new ones? i am using jquery Autocomplete plugin it is working fine in older versions of the browsers but in new version of the browsers it is not showing all the suggestions. i am using JSON to parse the data.is there any compatibility problems with json or with jquery plugin? A: Without seeing your JSON, I am guessing the JSON is not valid. I will assume your JSON is missing double quotes around the keys. [ { id: "Ficedula hypoleuca", label : "Eurasian Pied Flycatcher", value : "Eurasian Pied Flycatcher" }, ... ] To be valid JSON, it needs the double quotes around the keys [ { "id": "Ficedula hypoleuca", "label": "Eurasian Pied Flycatcher", "value": "Eurasian Pied Flycatcher" }, ... ] Older browser do not support native JSON.parse(). jQuery uses the native JSON parse method when available. The native parse is very strict when it comes to JSON syntax.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multi-column Select box Im looking for a multi-column select box that is searchable. I have found Flexbox (http://www.fairwaytech.com/flexbox) which does almost everything I need except it limits searching only to the {name} column. I'm needing something that will search over all columns shown. Im looking for something as powerful as the MS Access dropdown boxes if possible. Thanks in advance. A: not sure if this is what you're looking for... Presenting SooperFish: jQuery plugin for Multi-Column Dropdown Menus A: I ended up creating a (rather crude) custom combo box using div's and a bit of javascript. While it isn't the most elegant it works for my purposes. Hopefully someone is working on something similar to this but for now this is the only solution I was able to find.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Strange hibernate error in weblogic(10.3.4) console I have followgin configuration files, and I got following exception while getting Hibernate session. Is there a problem or missing property in hibernate.cfg.xml? persistence.xml <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="test" transaction-type="JTA"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <jta-data-source>test-ds</jta-data-source> <properties> <property name="hibernate.jndi.url" value="t3://127.0.0.1:7001" /> <property name="hibernate.connection.datasource" value="test-ds" /> <property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.WeblogicTransactionManagerLookup" /> <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" /> <property name="hibernate.hbm2ddl.auto" value="update" /> <property name="hibernate.current_session_context_class" value="jta" /> </properties> <!-- For WebLogic AppSer. --> <class>test.model.BaseEntity</class> <class>test.model.InvoiceDetail</class> <class>test.model.InvoiceMovement</class> <class>test.model.InvoicePaymentItem</class> <class>test.model.Job</class> <class>test.model.Member</class> </persistence-unit> hibernate.cfg.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration> <session-factory> <property name="hibernate.jndi.url">t3://127.0.0.1:7001</property> <property name="hibernate.connection.datasource">test-ds</property> <property name="hibernate.transaction.manager_lookup_class">org.hibernate.transaction.WeblogicTransactionManagerLookup</property> <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property> <property name="hibernate.hbm2ddl.auto">update</property> <property name="hibernate.current_session_context_class">jta</property> <mapping class="test.model.BaseEntity" /> <mapping class="test.model.InvoiceDetail" /> <mapping class="test.model.InvoiceMovement" /> <mapping class="test.model.InvoicePaymentItem" /> <mapping class="test.model.Job" /> <mapping class="test.model.Member" /> </session-factory> I've also added the classpath jpa2.0 jars in weblogic configuration file and created a datasource named test-ds and jndi name named test-ds via weblogic admin console. I assembled the all model operations methods into the class ModelOperations. The header of the class is the following: @Stateless @TransactionManagement(TransactionManagementType.CONTAINER) public class ModelOperations implements ModelOperationsLocal { @PersistenceContext(unitName = "beyazfatura") private EntityManager em; ... In this class I have a method stated below: @Override @SuppressWarnings("unchecked") public List<Member> getMembers(int first, int pageSize, String sortField, String sortOrder, Map<String, String> filters, Date beginDate, Date endDate) { Session session = null; List<Member> memberList = null; try { session = HibernateUtil.getSessionFactory().openSession(); Criteria crit = session.createCriteria(Member.class); Criterion betweenDate = null; if (beginDate != null) { if (endDate == null) { endDate = new Date();// now } betweenDate = Restrictions.between("createTime", beginDate, endDate); } if (betweenDate != null) { crit.add(betweenDate); } // sorting if (sortField != null && !sortField.isEmpty()) { if (!sortOrder.equalsIgnoreCase("UNSORTED")) { if (sortOrder.equalsIgnoreCase("ASCENDING")) { crit = crit.addOrder(Order.asc(sortField)); } else { crit = crit.addOrder(Order.desc(sortField)); } } } // filtering if (filters != null && !filters.isEmpty()) { Iterator<Entry<String, String>> iterator = filters.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, String> entry = iterator.next(); Class<?> type = Member.class.getDeclaredField( entry.getKey()).getType(); try { if (type.isEnum() || Number.class.isAssignableFrom(type)) { crit = crit.add(Restrictions.eq( entry.getKey(), type.getDeclaredMethod("valueOf", String.class).invoke(null, entry.getValue()))); } else { crit = crit.add(Restrictions.like(entry.getKey(), entry.getValue(), MatchMode.START)); } } catch (Exception ex) { // Aim: return the list anyway. LOG.warn(ex, ex); } } } if (first != -1) { crit = crit.setFirstResult(first); } if (pageSize != -1) { crit = crit.setMaxResults(pageSize); } memberList = crit.list(); } catch (Exception e) { LOG.error(e, e); } finally { session.close(); } return memberList; } @Override public Long getMemberCount(Date beginDate, Date endDate) { Session session = null; Long returnValue = 0L; try { session = HibernateUtil.getSessionFactory().openSession(); Criteria crit = session.createCriteria(Member.class); Criterion betweenDate = null; if (beginDate != null) { if (endDate == null) { endDate = new Date();// now } betweenDate = Restrictions.between("createTime", beginDate, endDate); } if (betweenDate != null) { crit.add(betweenDate); } crit.setProjection(Projections.rowCount()); if(crit.list() != null){ returnValue = (Long) crit.list().get(0); } else { returnValue = 0L; } } catch (Exception e) { LOG.error(e, e); } finally { session.close(); } return returnValue; } and this is the HibernateUtil class: public class HibernateUtil { private static final Logger LOG = Logger.getLogger(HibernateUtil.class); private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return new Configuration().configure().buildSessionFactory(); } catch (Throwable e) { LOG.error(e, e); throw new ExceptionInInitializerError(e); } } public static SessionFactory getSessionFactory() { return sessionFactory; } } I call getMember and getMemberCount method from a backing bean(of a datatable). I annotated the modeloperations class in the backing-bean. In order to use @EJB annotation, I deploy the jsf2.war as a libray in weblogic. The header of the managed bean and the LazyDataModel are below: Backing-bean header: @ManagedBean(name = "memberManagement") @SessionScoped public class MemberManagement { @EJB private ModelOperationsLocal modelOperations; private static final Logger LOG = Logger.getLogger(MemberManagement.class); private MemberLazyDataModel memberModel; @PostConstruct public void initModel() { memberModel = new MemberLazyDataModel(pageSize, beginDate, endDate, modelOperations); } LazyDataModel public class MemberLazyDataModel extends LazyDataModel<Member> { private ModelOperationsLocal modelOperations; private static final Logger LOG = Logger.getLogger(MemberLazyDataModel.class); private int pageSize; private Date beginDate; private Date endDate; public MemberLazyDataModel() { } public MemberLazyDataModel(int pageSize, Date beginDate, Date endDate, ModelOperationsLocal modelOperations) { this.pageSize = pageSize; this.beginDate = beginDate; this.endDate = endDate; this.modelOperations = modelOperations; super.setPageSize(pageSize); super.setRowCount(modelOperations.getMemberCount(beginDate, endDate).intValue()); } @Override public List<Member> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) { super.setRowCount(modelOperations.getMemberCount(beginDate, endDate).intValue()); return modelOperations.getMembers(first, pageSize, sortField, sortOrder.name(), filters, beginDate, endDate); } @Override public String getRowKey(Member member) { return member.getId() + ""; } @Override public Member getRowData(String rowKey) { List<Member> members = (List<Member>) getWrappedData(); for (Member member : members) { if ((member.getId() + "").equals(rowKey)) { return member; } } return null; } } When I click the page which includes the member datatable I get the following exception(as if it gets the hibernate.cfg.xml first time???): INFO Configuration - configuring from resource: /hibernate.cfg.xml INFO Configuration - Configuration resource: /hibernate.cfg.xml INFO Configuration - Configured SessionFactory: null some table binding logs then the below logs and the exception: INFO TransactionFactoryFactory - Using default transaction strategy (direct JDBC transactions) INFO ransactionManagerLookupFactory - instantiating TransactionManagerLookup: org.hibernate.transaction.WeblogicTransactionManagerLookup INFO ransactionManagerLookupFactory - instantiated TransactionManagerLookup INFO SettingsFactory - Automatic flush during beforeCompletion(): disabled INFO SettingsFactory - Automatic session close at end of transaction: disabled INFO SettingsFactory - JDBC batch size: 15 INFO SettingsFactory - JDBC batch updates for versioned data: disabled INFO SettingsFactory - Scrollable result sets: enabled INFO SettingsFactory - JDBC3 getGeneratedKeys(): enabled INFO SettingsFactory - Connection release mode: auto INFO SettingsFactory - Default batch fetch size: 1 INFO SettingsFactory - Generate SQL with comments: disabled INFO SettingsFactory - Order SQL updates by primary key: disabled INFO SettingsFactory - Order SQL inserts for batching: disabled INFO SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory INFO ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory INFO SettingsFactory - Query language substitutions: {} INFO SettingsFactory - JPA-QL strict compliance: disabled INFO SettingsFactory - Second-level cache: enabled INFO SettingsFactory - Query cache: disabled INFO SettingsFactory - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory INFO SettingsFactory - Optimize cache for minimal puts: disabled INFO SettingsFactory - Structured second-level cache entries: disabled INFO SettingsFactory - Statistics: disabled INFO SettingsFactory - Deleted entity synthetic identifier rollback: disabled INFO SettingsFactory - Default entity-mode: pojo INFO SettingsFactory - Named query checking : enabled INFO SettingsFactory - Check Nullability in Core (should be disabled when Bean Validation is on): disabled INFO SessionFactoryImpl - building session factory INFO BasicTypeRegistry - Type registration [materialized_blob] overrides previous : org.hibernate.type.MaterializedBlobType@1a11d34 INFO SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured INFO SchemaUpdate - Running hbm2ddl schema update INFO SchemaUpdate - fetching database metadata ERROR SchemaUpdate - could not get database metadata java.sql.SQLException: Cannot set auto commit to "true" when in distributed transaction. at weblogic.jdbc.wrapper.JTSConnection.setAutoCommit(JTSConnection.java:625) at org.hibernate.tool.hbm2ddl.SuppliedConnectionProviderConnectionHelper.prepare(SuppliedConnectionProviderConnectionHelper.java:60) at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:168) at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:375) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1872) What is your idea about this exception? Thanks. A: I think the clue is in INFO SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured From the hibernate docs: 3.8.2. JNDI-bound SessionFactory A JNDI-bound Hibernate SessionFactory can simplify the lookup function of the factory and create new Sessions. This is not, however, related to a JNDI bound Datasource; both simply use the same registry. If you wish to have the SessionFactory bound to a JNDI namespace, specify a name (e.g. java:hibernate/SessionFactory) using the property hibernate.session_factory_name. If this property is omitted, the SessionFactory will not be bound to JNDI. This is especially useful in environments with a read-only JNDI default implementation (in Tomcat, for example). So you'll need to provide a hibernate.session_factory_name in your hibernate config.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: is there a good open source project to learn generics and to avoid dataset? in my company we are using datasets continuously for data related operations but i want to learn how can we use the generics in c sharp so i want to know is there any open source project which have used generics beautifully and customizable so i can understand well and can implement in our new project and also please give some performance measurements of dataset vs generics so i can convince my team lead to use the generics .. thanks A: You could have a look at this white paper - http://msdn.microsoft.com/en-us/data/ff707264.aspx It looks at implementing the Nerd Dinner sample site using a number of different .Net data architectures. Scott Hanselman also wrote a blog post that summarised the contents of the white paper.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Backbone Sync with a mashup of models in Rails I have a rails controller which sends a mash-up of models as a global json object. Something like this { dogs : { species: {}, ...}, cats : { food: {}, ...}, foxes : { }, ..., ... } On my client side, I have all these entities neatly segregated out into different backbone models and backbone collections. On some onchange event, I need to send a mashup of some model attributes back to the server as a HTTP POST request and the server sends a response which again spans values across a few models. How do I setup Backbone.sync to deal with such an ajax scenario? I do not want to change the rails backend because its quite a steady implementation. Or do I make vanilla $.ajax requests through jQuery in one of my backbone views and handle it in a callback on ajax success/failure? A: I think there are a couple of ways to do this via backbone. I think I'd start out with a model to represent the mashup: var MashupModel = Backbone.Model.extend({ }); Then you can pass in any models like you would normally (or a collection for that matter): var my_mash = new MashupModel({ dog: dogModel.toJSON(), cat: catModel.toJSON(), foxes: foxCollection.toJSON() }); // do stuff if you need... Then do what you want when the response comes back like normal: my_mash.save({}, { success: function(model, response) { // do stuff here to put new data into the proper models / collections }, error: function() { alert("I FAIL!"); } }); That's all well and good... however, I think it would be better to push the above down into the MashupModel object instead of at the request level. Again, several ways: var MashupModel = Backbone.Model.extend({ initialize: function(attrs) { // can't remember the actual code, but something along the lines of: _.each( attrs.keys, function(key) { this.set(key, attrs.key.toJSON(); }); }, save: function(attrs, opts) { var callback = opts.success; opts.success = function(model, response) { // do your conversion from json data to models / collections callback(model, response); }; // now call 'super' // (ala: http://documentcloud.github.com/backbone/#Model-extend) Backbone.Model.prototype.set.call(this, attrs, opts); } }); Or you could override toJSON (since backbone calls that to get the attrs ready for ajax): // class definition like above, no initilize... ... toJSON: function() { // again, this is pseudocode-y var attrs = {}; _.each( this.attributes.keys, function() { attrs.key = this.attributes.key.toJSON(); }); return attrs; } ... // save: would be the same as above, cept you'd be updating the models // directly through this.get('dogs').whatever... Now, you can just do: var my_mash = new MashupModel({ dog: dogModel, cat: catModel, foxes: foxCollection }); // do some stuff... my_mash.save({}, { success: function(model, response) { // now only do stuff specific to this save action, like update some views... }, error: function() { alert("I FAIL!"); } A: it would be possible, but may be difficult to modify backbone.sync to work with this structure. i'd recommend going with plain old jquery $.ajax requests. then on success, pull the info apart and populate your collections. $.get("/whatever", function(data){ catCollection.reset(data.cats); dogCollection.reset(data.dogs); // etc }); data = {}; data.cats = catCollection.toJSON(); data.dogs = dogCollection.toJSON(); // etc $.post("/whatever", data);
{ "language": "en", "url": "https://stackoverflow.com/questions/7582465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: trinidad 2 and myfaces 2.13 I have started a brand new web application, using myfaces 2.1.3, tomahawk 20-1.1.11 and trinidad 2.0.0. I followed the developers guide and got facelets, jsf and the tomahawk stuff to work. But the trinidad tags keep throwing this: java.lang.ClassNotFoundException:org.apache.myfaces.trinidadinternal.facelets.TrinidadFaceletViewHandler I checked in the api and impl and there really is no TrinidadFaceletViewHandler. Is this an oversight, or am I missing something? A: Do you have this in you web.xml <context-param> <param-name>org.apache.myfaces.trinidad.ALTERNATE_VIEW_HANDLER</param-name> <param-value>org.apache.myfaces.trinidadinternal.facelets.TrinidadFaceletViewHandler</param-value> </context-param> Remove it! A: This indicates that you've somewhere a Facelets 1.x JAR file around in your /WEB-INF/lib. Remove it. It's already bundled in JSF 2.x libraries. Ensure that you're reading the installation instructions for JSF 2.x and Trinidad 2.x, not JSF 1.x and Trinidad 1.x. A: Unfortunately, I can't find any installation guide for JSF 2.x and Trinidad 2.x. The documentation for Trinidad is really poor.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582467", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: why is my element not targeted when reload through AJAX I'm using object literals on my project. I'm targeting selecting with jquery. It works fine the first time but when the part I'm targeting is reloaded with AJAX I can't target those element anymore. But I look into firebug they're there... I'm even doing console.log() to test if my code works and it works but it just doesn't want to pick those. So in order for it to work, I have to refresh the entire browser. Do you know what's the deal with AJAX dom reload and selectors. I think it's something to do with the DOM reloading and redrawing itself or something along those lines... Here is my code: Module.editWishlistTitle = { wishListContent: $('.mod-wish-list-content'), title: $('.title').find('h2'), titleTextField: $('#wishlist-title-field'), titleInnerContainer: $('.title-inner'), editTitleForm: $('.edit-title-form'), submitCancelContainer: $('.submit-cancel'), notIE9: $.browser.msie && $.browser.version < 9, edit: function () { var fieldTxt = this.titleTextField.val(), editForm = this.editTitleForm, titleParent = this.titleInnerContainer, fieldCurrentTitle = this.title.text(); this.titleTextField.val(fieldCurrentTitle); this.submitCancelContainer.removeClass('hidden'); if (!this.notIE9) { editForm.css('opacity', 0).animate({ opacity: 1 }).removeClass('hidden'); titleParent.addClass('hidden').animate({ opacity: 0 }); console.log(editForm); } else { editForm.removeClass('hidden'); titleParent.addClass('hidden'); } } init: function () { var self = this; console.log(this.editTitleForm); //edit this.wishListContent.delegate('.edit-title a', 'click', function (e) { self.edit(); e.preventDefault(); }); }; A: If you are replacing an element on the page, you are destroying the original reference to the element. You need to redo the reference to point to the new element. Create a new method in your code that (re)initializes the references you need. Instead of adding them in the odject, set them in the method. Basic idea: Module.editWishlistTitle = { wishListContent: $('.mod-wish-list-content'), title: $('.title').find('h2'), //titleTextField: $('#wishlist-title-field'), ... ... initReferences : function(){ this.titleTextField = $('#wishlist-title-field'); }, ... ... init: function () { this.initReferences(); ... ... And when your Ajax call comes back you just need to call initReferences again. A: After DOM ready, if you inject any data / class / id will not be available in DOM, so better you use live or delegate to get your new data access. http://api.jquery.com/delegate/ Best to use delegate, that will take care your new data loaded after dom ready, that way you can avoid to refresh /reload your page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Any feedback or advice on multiplayer platform for Android games? I'd like to add multiplayer mode for an Android game (a turn by turn game). So I'm looking for a multiplayer platform. The most important feature I'm waiting for such a platform is to let users do some matches against random users on the Internet. Casmul looks good, but it looks a little bit heavy (maybe too many features for what I want?). Do you have some feedback with that kind of platform. Any advice ? Regards,
{ "language": "en", "url": "https://stackoverflow.com/questions/7582473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Detect Location using Bluetooth Accesspoints I would like to detect location of bluetooth enabled devices automatically using bluetooth accesspoints. Is it possible? If so, how can I do it? A: Bluetooth devices have unique MAC addresses so I think this would be possible but has a number of constraints: * *You would want the devices to be either discoverable, or to have already paired with them *Bluetooth devices don't tend to be screwed to the ceiling like enterprise access points, or tethered to a phoneline like their domestic counterparts. *The range of bluetooth is typically less than WiFi, which will potentially increase the difficulty in accurate localisation. *No such database already exists to my knowledge. You can get the signal strength information you'd need to do this from BlueZ on Linux, so I assume similar is possible on other platforms. It's then a question of building a database of measured signal strengths at known location to "map" an area. With this database an unknown set of signal strengths can be matched to a large radius, by just using the set of all known positions of all of the devices seen. With that knowledge you could either: * *Triangulate properly if you actually know locations of individual devices or: *See which location in your database, within the trivially calculated radius best matches the strengths you are measuring on the device currently.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom HTML attributes and jQuery I am often needing to store little pieces of reference in a page element, most of the time a <div>. I couldn't find too much documentation on how valid it would be to create my own attributes. What do you suggest is the most valid way of doing this or can I even do this? If so, can I just use jQuery's attr() call to get the reference? example : <div class="sample" dataref="Sample Data Reference"></div> A: Use HTML5 data attributes See: http://api.jquery.com/data/ E.g. <div class="sample" data-ref="some string" /> Then: $('.sample').data('ref'); A: Use jQuery data functionality. The data will not show in DOM, but you will able to set and access it fast. Documentation: http://api.jquery.com/jQuery.data/ Example: // set value $.data(element, key, value); // get value var value = $.data(element, key); A: I feel you can use any word other than "id" and "class" attributes to keep your data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: jQuery Mobile - IE casching problem Im using jQuery mobile to make a small project. You can say its a signup system for a weekly event, and then the event is reset each week (through some scripts running on a server). I have had problems with IE before, since it has the most wack cashing properties ever, and therefore won't update page content when ajax requests are using GET. I then turned all my ajax into POST and it worked. Now, how do i do this in jQuery Mobile? Everythings works great in firefox, but IE just won't update my content since the page are loaded through the ajax GET command. I tried to pass this into my custom js file to get it away, but it still dosen't work :( $(document).ready(function(){ $(document).bind("mobileinit", function(){ $.extend( $.mobile , { ajaxLinksEnabled : false }); }); }); Anyone with an idea on what to do :)? A: Try with: $.ajaxSetup ({ // Disable caching of AJAX responses cache: false }); called on page initialization (befor doing the real request).
{ "language": "en", "url": "https://stackoverflow.com/questions/7582483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Kill MySQL query on user abort When running a long query from PHP, [how] can I kill the query if the user presses stop in their browser? Take into consideration that I cannot call any other PHP functions because PHP is blocked while waiting for MySQL. Also I cannot make any more requests to the server (via Ajax) because of session locking. So one solution could be: * *ignore user abort *run the long query in the back ground and have PHP check every 100ms if it has finished *get the pid from the query *if the user aborts, kill the pid *else return the result when finished The 2 thing that I dont know how to do in that is: * *run a non blocking (background) query *get the pid of a query A: Once PHP notices the user has stopped the request (this usually will not happen until the script tries to output something to the user), your script will terminate. Before shutting down, PHP calls any shutdown functions you've activated. You can implement a shutdown function that kills your query, and register it with register_shutdown_function() An other way you might be able to do this, is by running your script with ignore_user_abort() turned on, and checking if the user has aborted by calling connection_aborted() periodically. If the user has aborted, kill the query and gracefully exit your script. More information on connection handling here. A: If the time taken by query is because of the large dataset returned, then you can use mysql_unbuffered_query. And then in shutdown_function you can free the result and disconnect form mysql. And if you are using PHP 5.3.x and have mysqlnd you can probably use MYSQLI_ASYNC in mysqli_query and then use mysqli_poll to get the result. The first option will only help in case of time taken in retrieval of dataset. But if the mysql is actually taking a long time in parsing and creating the execution plan and loading tables to memory it wont help. In that case you need MYSQLI_ASYNC which is only available on PHP 5.3.x WITH mysqlnd. Also if your main problem is session locking have a look at this post on PHP's documentation http://php.net/manual/en/ref.session.php#64525 You might find some helpful advice there. A: For those who are interested, here is what I used: <?php // Connection to query on $query_con = mysqli_connect($host, $user, $password, $name, $port); // Connection to kill on $kill_con = mysqli_connect($host, $user, $password, $name, $port); // Start the query $query_con->query($slow_query, MYSQLI_ASYNC); // Get the PID $thread_id = $query_con->thread_id; // Ignore user abort so we can kill the query ignore_user_abort(true); do { // Poll MySQL $links = $errors = $reject = array($mysqli->mysqli); $poll = mysqli_poll($links, $errors, $reject, 0, 500000); // Check if the connection is aborted and the query was killed if (connection_aborted() && mysqli_kill($kill_con, $thread_id)) { die(); } } while (!$poll); // Not aborted, so do stuff with the result $result = $link->reap_async_query(); if (is_object($result)) { // Select while ($row = $result->fetch_object()) { var_dump($row); } } else { // Insert/update/delete var_dump($result); } A: i think you can give a try to mysql KILL http://dev.mysql.com/doc/refman/5.0/en/kill.html if you are able to call something over user abort then you can use KILL to kill you mysql connection or query by fetching it's process id. And as you said in your comment that PHP is blocked until mysql returns so you can take help from javascript in this way: 1.detect the user abort using JS 2.call a function on user abort 3.in that function you can kill you previous query but here you need the process id of the previous query so you can get that by a trick that you can select the process id when you run you first long query and pass it to JS function and use it in killing you query. Hope it will help you. A: PHP, in most cases, won't know that a connection was closed (since the user aborted) until it tries to send something over the network and then receives a SIGPIPE. The only thing you can do is try working with timeouts aborting to long queries or killing them from another process. A: This is an example of doing it with PDO. $id = $connection->executeQuery("SELECT CONNECTION_ID()")->fetchColumn(); ignore_user_abort(true); while($row = $result->fetch()) { /* Processing ... */ if (connection_aborted()) { $this->connection->executeQuery("KILL CONNECTION $id"); break; } } Note: Keep an eye out for multiple connections, you may kill the wrong one. A: You can unset session variable using: <?php session_unset(); ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7582485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Conceptual question related to Model–view–controller on iOS The question deals with an application which uses many views in a UINavigation controller Style. In the background there is a process which load and cache data, the process is rather extensive, which can take quite some time, that said it is designed to run on separate thread(s) doing it's loading task in the background - while the other views are present and active to the user. Question: Assuming I would like to show the progress running in the background to the user, for example a progress view or alike. I shouldn't think that each view should have a progressView which is populating and controlled by some Notification / Listener mechanism. Logic tells me that there should be a way to have only a single progress view which is present in all views and somehow being called only once, allocated only once and so on. If my logic is right, how should one approach this , where should this element be placed? any ideas, philosophy or clues would be highly appricated. A: Every UIView, that is added to the view hierarchy, has a property window. A UIWindow is also a UIView, so you just can add a view to it and it will be overlaying any other view. edit I wrote an example: https://github.com/vikingosegundo/my-programming-examples/tree/master/OverlayTest A: Add it as a subview to the UIWindow, above the UINavigationController's view. This is how I do overlays for achievements etc, which can happen at any time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Concatenate strings using preprocessor in C How to concatenate two strings (one of them is stored in a variable) in C using preprocessors? For example how to do this? #define CONCAT(x,y) x y //ecmd->argv[0] is equal to "sometext" myfunc(CONCAT("/", ecmd->argv[0]), ecmd->argv[0]); //error: expected ')' before 'ecmd' A: You can't concatenate them using a macro like that. using the preprocessor, only raw strings (either string literals or names) can be concatenated. You have to use strcat or some other technique to combine the strings. For example: char * buf = malloc(strlen(ecmd->argv[0]) + 2); buf[0] = '/'; buf[1] = '\0'; strcat(buf, ecmd->argv[0]);
{ "language": "en", "url": "https://stackoverflow.com/questions/7582500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: some problems with IntegerType in cassandra Why I am getting such symbols "N���" from the column with IntegerType? in cassandra-cli.bat it is showing normally, as integer. I'm using phpcassa...maybe I need to convert this value, like I'm doing with UUID UUID::import($uuid)->string but with other certain function? A: Thanks to all!I found a solution. just needs to unpack('N', $value); or to modify a bit phpcassa's ColumnFamily class, it uses this(unpack) function, but this function is private
{ "language": "en", "url": "https://stackoverflow.com/questions/7582501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Removing duplicate rows from a table id lat long speed date address 1 22.92138131 72.44103313 3.96 km/h 2011-09-26 National, Gujarat, India 2 22.92138145 72.44103413 13.96 km/h 2011-09-26 National, Gujarat, India 3 22.92138134 72.44103423 15.96 km/h 2011-09-26 National, Gujarat, India 4 22.92138454 72.44103233 13.96 km/h 2011-09-26 10t ring Rd, Nehru Nagar 5 22.92138354 72.44102533 13.96 km/h 2011-09-26 Anandnagar Rd, Ahmedabad 6 22.92138484 72.44103293 19.96 km/h 2011-09-26 Anandnagar Rd, Ahmedabad I want to write a query such that my result looks like this: id lat long speed date address 1 22.92138131 72.44103313 3.96 km/h 2011-09-26 National, Gujarat, India 4 22.92138454 72.44103233 13.96 km/h 2011-09-26 10t ring Rd, Nehru Nagar 5 22.92138354 72.44102533 13.96 km/h 2011-09-26 Anandnagar Rd, Ahmedabad I want to remove duplicate rows according to the address. A: To check what you are going to delete: SELECT distinct t1.* FROM yourtable as t1 join yourtable as t2 WHERE t1.address = t2.address and t1.id < t2.id If you are happy with that: DELETE t1 FROM yourtable as t1 join yourtable as t2 WHERE t1.address = t2.address and t1.id < t2.id This way you keep the record with the max value on id column A: If you don't care which of the rows you keep ALTER IGNORE TABLE table ADD UNIQUE KEY 'address' (`address`); The 'IGNORE' is important, that means to silently ignore duplicate data. (ie ignores it when inserting into the 'new version' of the table.) May want to remove the index afterwoods ALTER TABLE table DROP KEY 'address'; A: Assuming that you wish to return the rows with the smallest ID values: SELECT * FROM TABLENAME T INNER JOIN ( SELECT MIN(ID) AS ID FROM TableName GROUP BY Address ) SUB ON T.ID = SUB.ID A: Need to create duplicate/temporary table with same field what your current table have. Then execute below SQL First clear temporary table : DELETE FROM `#TMP_TABLE#`; Insert record in temporary table as per your expectation. INSERT INTO `#TMP_TABLE#` SELECT T . * FROM #TABLE# T INNER JOIN ( SELECT MIN( ID ) AS ID FROM #TABLE# GROUP BY address ) SUB ON T.id = SUB.id Truncate main table DELETE FROM `#TABLE#`; Copy Data from temporary table INSERT INTO #TABLE# SELECT * FROM `#TMP_TABLE#` A: delete from table_name tb where id not in (select min(id) from table_name tb1 group by address) I assumed that you want to remove rows having address duplicacy and want to keep minimum id's row in your table A: You Can Do this Easily by Doing these 3 easy steps and therefore 3 SQL statements: Step 1: Move the non duplicates (unique tuples) into a temporary table CREATE TABLE new_table as SELECT * FROM old_table WHERE 1 GROUP BY [column to remove duplicates by]; Step 2: delete delete the old table We no longer need the table with all the duplicate entries, so drop it! DROP TABLE old_table; Step 3: rename the new_table to the name of the old_table RENAME TABLE new_table TO old_table; For Another Way You Can go to the Bellow Link... Its is Also a good Way... Difficult but with less statements http://dev.mysql.com/doc/refman/5.0/en/insert.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7582508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Using autotools to generate application specific *.conf files I'm new to using autotools so forgive me if this sounds a little bit basic but googling didn't show up much. How would I go about generating a custom conf file with autotools. Seeing as configure based on m4 contains the necessary macros and generates the required files. Some hunting and reading seems to suggest I could do something like add: AC_CONFIG_FILES([appname.conf]) To my configure.am. Then create an appname.conf.in file. What I'm not clear on is how I populate custom macros i.e. LOG_DIR=@log_dir@ CACHE_DIR=@cache_dir@ to So when configure gets run it produces LOG_DIR=/var/log CACHE_DIR=/mycachedir etc... A: The information you seem to be missing is AC_SUBST, which sets up the substitutions. E.g. in configure.ac: TEST_SUB="hello world" AC_SUBST(TEST_SUB) AC_CONFIG_FILES(test.conf) In test.conf.in: TEST_VAR=@TEST_SUB@ Gives test.conf: TEST_VAR=hello world (If you're curious have a look in the Makefile.in files that automake generates to see how it uses this mechanism. The AM_CONDITIONALs get turned into two things, one for each case, one of which gets made into a comment by a substitution)
{ "language": "en", "url": "https://stackoverflow.com/questions/7582520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How could I run this python script on my webserver? TorBulkExitList.py I have a web server that can run python scripts, but I have no experience at all with python. I uploaded the file (TorBulkExitList.py) to my server inside the cgi-bin folder and I tried calling it in the browser but it's giving me a 500 Internal Server Error. Here's the python script: https://svn.torproject.org/svn/check/trunk/cgi-bin/TorBulkExitList.py Is there anything I need to do before I could run this script? I didn't change anything from the script at all. Any other alternative, I just need to get a list of the TOR exit IPs. I'm on a Linux/PHP/Apache server btw. A: I see that file is a wsgi application (because it implements a application method.) You need to configure apache to send requests to it using mod_wsgi (or some other wsgi server.) Try adding this to the site's .htaccess (with the correct file path): WSGIScriptAlias /TorBulkExitList /usr/local/www/cgi-bin/TorBulkExitList.py and then visit http://example.com/TorBulkExitList Click here to read more about mod_wsgi configuration.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python UDP server on ubuntu not working I am trying to run this script on a ubuntu 11.04 box: http://taoofmac.com/space/projects/ReGrowl Its a small script bound to UDP port 9887 designed to relay Growl packets. I can send the script Growl packets from the local machine and it works exactly as expected. However, when trying to send packets from another machine on my network they seem to be dropped or not make it to the script. I have configured ubuntu to allow the port and the output of netstat looks like this: root@UbuntuVM:~# netstat -a | grep "udp" udp 0 0 localhost:9887 *:* udp 768 0 *:mdns *:* udp 0 0 *:mdns *:* udp 0 0 *:45030 *:* udp6 0 0 [::]:44730 [::]:* udp6 0 0 [::]:mdns [::]:* My script is the first entry on the list. I have used wireshark and confirmed that the ubuntu machine is receiving the packets. Do I need todo anything to ubuntu to allow python to bind to UDP ports? Anyone know whats going on here? Thanks in advance! UPDATE: The output of the script should look like this: 127.0.0.1 - - [28/Sep/2011 12:30:27] REGISTER Network Responder 56 ['192.168.0.24', '192.168.0.140', '192.168.0.11', '192.168.0.25', '192.168.0.18', '192.168.0.28', '192.168.0.10', '192.168.0.30'] 127.0.0.1 - - [28/Sep/2011 12:30:27] NOTIFY ('Network Status', 'Connection Status', 'Test', 'Network Responder') 80 ['192.168.0.24', '192.168.0.140', '192.168.0.11', '192.168.0.25', '192.168.0.18', '192.168.0.28', '192.168.0.10', '192.168.0.30'] The first IP is the source of the packet, and the array of IPs at the end are the destinations for the packet to be relayed to. As you can this packet originated from the local machine, if I send a packet form another machine its IP should apear first. Here is the portion of the script that implements the UDP server: class GrowlRelay(UDPServer): """Growl Notification Relay""" allow_reuse_address = True def __init__(self, inpassword = None, outpassword = None): """Initializes the relay and launches the resolver thread""" self.inpassword = inpassword self.outpassword = outpassword self.resolver = RendezvousWatcher() self.resolver.start() UDPServer.__init__(self,('localhost', GROWL_UDP_PORT), _RequestHandler) def server_close(self): self.resolver.shutdown() The full script and dependant classes are available and the link above. A: Your code binds the server to localhost, i.e. it only listens to local connections. Replace UDPServer.__init__(self,('localhost', GROWL_UDP_PORT), _RequestHandler) with UDPServer.__init__(self,('', GROWL_UDP_PORT), _RequestHandler) to accept connections from anywhere.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582525", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Does gdb temporarily give pages write permission? I was debugging a seg fault in a Linux app that was caused by a program trying to change a static constant array structure (so the data was in the read-only section of the ELF and subsequently loaded in a page that was then given read-only permission). While in GDB I put a breakpoint on the line of assembler that did the bad store, and when it stopped there I manually performed the equivalent write action using GDB. GDB did this without any complaints, and reading the value back proved it had indeed been written. I looked in /proc/thepid/maps and that particular page was still marked as "not writeable". So my question is: does GDB temporarily set write permissions on a read-only page, perform the write, then reset the permissions? Thanks. A: does GDB temporarily set write permissions No. On Linux/*86, ptrace() (which is what GDB uses to read and write the inferior (being debugged) process memory) allows reads and writes to pages that are not readable/writable by the inferior, leading exactly to the confusion you've described. This could be considered a bug in the kernel. It should be noted that the kernel has to allow ptrace to write to normally non-writable .text section for the debugger to be able to plant breakpoints (which is done by overwriting original instruction with the breakpoint/trap instruction -- int3 via PTRACE_POKETEXT request). The kernel doesn't have to do the same for POKE_DATA, but man ptrace says: PTRACE_POKETEXT, PTRACE_POKEDATA Copies the word data to location addr in the child's memory. As above, the two requests are currently equivalent. I believe it's that equivalentness that causes the current behavior.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: getting value from JSON in iPhone through JAVASCRIPT I am building an application to find the route between two places.Also, i have to give the details of checkpoint between the route.In this case, I'm struggling. Through JSON i got the different checkpoint like this "<b>NH 75</b>\U3092\U9032\U3080<div class=\"google_note\">\n<b landmarkid=\"0x39847e91e9351f85:0x9e82c70b4b91c047\" class=\"dir-landmark\">\U30da\U30c8\U30ed\U30fc\U30eb\U30fb\U30d1\U30f3\U30d7</b>\U3092\U901a\U904e\U3059\U308b<div class=\"dirseg-sub\">\Uff0831.0&nbsp;km \U5148\U3001\U5de6\U624b\Uff09</div>\n</div>" "\U5de6\U6298\U3057\U3066<b>SH 11</b>\U306b\U5165\U308b" "1 \U3064\U76ee\U306e\U89d2\U3092\U53f3\U306b\U66f2\U304c\U3063\U3066\U3001\U305d\U306e\U307e\U307e<b>SH 11</b>\U3092\U9032\U3080<div class=\"google_note\">\n<b landmarkid=\"0x39847f74faa9a325:0xd74f16593a886b60\" class=\"dir-landmark\">Prem Nursing Home</b><div class=\"dirseg-sub\">\Uff08\U53f3\U5074\Uff09</div>\U3092\U901a\U904e\U3059\U308b</div>" for this, i have to print value like this.... 1. Continue onto NH 75 Pass by Petrol Pump (on the left in 31.0 km) 2. Turn left onto SH 11 3. Take the 1st right to stay on SH 11 Pass by Prem Nursing Home (on the right) I'm getting place name.But, in fetching details m struggling. How can it be done. Any help would be appreciated. Thanx in advance. A: A UIWebView has the method - stringByEvaluatingJavaScriptFromString: - this should help with your issue. Example: NSString *result = [myWebView stringByEvaluatingJavaScriptFromString:@"someJavascriptFunction(42);"];
{ "language": "en", "url": "https://stackoverflow.com/questions/7582536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Table's td with specified height doesn't work the same way on different browsers I have a table and I need that every cell have the same fixed height and width. So I have: th, td { min-width: 110px; width: 110px; max-width: 110px; min-height: 60px; height: 60px; max-height: 60px; } a td is just: <td><span>*number*</span></td> I was testing my code on Firefox 7 and I saw they OK but in Chrome/IE9 the cells are taller. So: With or without min-max height, the heights are: FF7: 56px/60px (without borders / with borders) Chrome: 62px/66px IE9: 61px/65px The problem is that I made a background for the TD on Photoshop and it's look weird if the size is not the right one and I don't know how to resolve it. Outside this problem, chrome is acting weird. I Apply via Javascript some a to some td's once the page is loaded and they don't work on chrome... until you refresh sometimes. EDIT: The table have fixed height and some border-spacing too. EDIT 2: I made a jsFiddle: http://jsfiddle.net/cFTpp/1/ The difference is less (58vs60) but is still different. A: Use a fixed table layout: table { table-layout: fixed; } A: Please check the following codes. <table border="0" align="center" cellpadding="0" cellspacing="0" style="width:800px;"> <colgroup> <col style="width:200px; background:#CCC"/> <col style="width:100px; background: #666"/> <col style="width:500px; background: #000"/> </colgroup> <thead> <tr> <th style="height:100px">head</th> <th style="height:100px">&nbsp;</th> <th style="height:100px">&nbsp;</th> </tr> </thead> <tfoot> <tr> <td>foot</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </tfoot> <tbody> <tr> <td>body</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </tbody> You can adjust width of the any Column by changing the width of the <col style="width:200px;. I just write the inline styles. A: I ended changing the table for divs, more easy to archieve some results.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java and Type Safety The MDN JavaScript guide states the following when doing a comparison between Java and JavaScript: Type safety means, for instance, that you can't cast a Java integer into an object reference or access private memory by corrupting Java bytecodes. Sure, regarding the first part of the above statement, when talking about typing the general concept of type safety revolves around a languages ability to provide some kind of checking that eliminates possible erroneous conditions regarding operations performed with incompatible types (even though the above example is naive considering that in Java you can box primitive int to the reference type Integer). But, what exactly do they mean by the second part of the statement? Here there is talk about the JVM's verifier ensuring a level of memory protection - where "arbitary bit patterns cannot be used as an address." How does the second part of the statement from MDN relate to type safety? A: I suspect they mean that you can't cast an arbitrary memory address into a different type, like you can in C. struct bar_s { char foo_s[100]; } void stuff() { int foo = 5; bar_s *bar = &foo; } Forgive me if the syntax is wrong, my C is rusty. This takes the memory address of foo, assigns it to a pointer to a bar_s struct, which you can then dereference with lots of associated pain. You are treating an area of memory which was originally an int as a bar_s. In C, there are a number of attack vectors which allow you to overwrite memory with arbitrary information, and have them executed subsequently. See Buffer Overflow In java, once an Integer, always an Integer[*]. There is also bounds checking on all arrays which help prevent buffer overflows. [*] Until garbage collection that is. A: It means that in Java, there is (in principle) no way to get around how types are identified. In javascript, a type can be inferred based on how the byte sequence that represents a piece of data. In Java, the VM prevents that sort of thing, to ensure that a sequence of bytes that is intended to be a Foo object, can not be seen as a Bar object. About accessing private members, that means that you can't make a sequence of bytes mean something different than intended by the programmer, to obtain access to something unintended. At runtime, you can't change object foo of type Foo with private member foobar into an object of type Bar, with the same members, but with foobar made public. The type of each object is encoded in the byte code, which is controlled by the VM at runtime.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Set the size of a UIViewControllers view How does one set the size of a UIViewController view so that the view behind it is visible? Or will setting a UIViewControllers view to clear, allow for the view below it in the display stack to be visible? A: * *Size of view is set using its frame property. *You can play with alpha property of that view to change its transparency. A: This previous question and the one it links to suggests what you want may not be possible, if you are thinking that the parent view is just occluded by the current view and not removed? A: Changing the alpha of the UIViewController will affect everything that you place on the controller -- and that may not be what you want. What you can do is to make the view's background clear, then add another view with a suitable background color (black, white or whatever), and change the alpha of that view to make it translucent. You can then place controls on top of the translucent view and they will be opaque. The results look like this:
{ "language": "en", "url": "https://stackoverflow.com/questions/7582542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Submitting a form results in 404; when this is refreshed, original form redisplays Sorry for a vague title but it's hard to be more specific. Platform used: Eclipse Helios, Tomcat 6, Maven 2.2.1 Background/ Problem: I am doing a pilot for a conversion from JSF 1.2 to JSF2. The server starts fine and loads the converted login page and when doing so it connects to the bean. However when the login form is submitted it never reaches the bean and goes 404 instead and leaves no strack trace behind. The page it's supposed to navigate to is itself so it's not a question about not reaching another page, you can basically press F5 and it comes back asking for username and password. I cant figure out why it goes 404. web.xml: <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-app_2_5.xsd" id="YourWebappID" version="2.5"> <context-param> <param-name>javax.faces.CONFIG_FILES</param-name> <param-value> /WEB-INF/faces-config-logic.xml, /WEB-INF/ap-faces-config.xml, /WEB-INF/bup-faces-config.xml, /WEB-INF/bup-faces-config-logic.xml, /WEB-INF/qt-faces-config.xml, /WEB-INF/bs-faces-config.xml, /WEB-INF/bs-faces-config-logic.xml, /WEB-INF/fp/fp-faces-config-controller.xml, /WEB-INF/fp/fp-faces-config-service.xml, /WEB-INF/fp/fp-faces-config-dao.xml, /WEB-INF/fp/fp-navigation-rules.xml, /WEB-INF/pm/pm-faces-config-controller.xml, /WEB-INF/pm/pm-faces-config-service.xml, /WEB-INF/pm/pm-faces-config-dao.xml, /WEB-INF/pm/pm-navigation-rules.xml, /WEB-INF/rp/rp-faces-config-controller.xml, /WEB-INF/rp/rp-faces-config-service.xml, /WEB-INF/rp/rp-faces-config-dao.xml, /WEB-INF/rp/rp-navigation-rules.xml, /WEB-INF/ap/ap-faces-config-controller.xml, /WEB-INF/ap/ap-faces-config-service.xml, /WEB-INF/ap/ap-faces-config-dao.xml, /WEB-INF/ap/ap-navigation-rules.xml </param-value> <description> JSF config files beside faces-config.xml </description> </context-param> <context-param> <param-name>javax.faces.STATE_SAVING_METHOD</param-name> <param-value>client</param-value> <description> State saving method: "client" or "server" (= default) See JSF Specification 2.5.2 </description> </context-param> <context-param> <param-name>org.apache.shale.view.VIEW_CONTROLLER_MAPPER</param-name> <param-value>com.wmdata.raindance.ap.ui.RDViewControllerMapper</param-value> </context-param> <!-- Rest --> <context-param> <param-name>resteasy.scan</param-name> <param-value>true</param-value> </context-param> <!-- Rest --> <context-param> <param-name>resteasy.servlet.mapping.prefix</param-name> <param-value>/resteasy</param-value> </context-param> <!-- Rest --> <context-param> <param-name>resteasy.resource.method-interceptors</param-name> <param-value> org.jboss.resteasy.core.ResourceMethodSecurityInterceptor </param-value> </context-param> <!-- Resource location directory of Birt resources used to locate images --> <context-param> <param-name>BIRT_RESOURCE_PATH</param-name> <param-value>image/default</param-value> </context-param> <!--filter> <filter-name>SessionFilter</filter-name> <filter-class>com.wmdata.raindance.portal.auth.SessionFilter</filter-class> </filter --> <listener> <listener-class>com.wmdata.raindance.portal.config.InitApplication</listener-class> </listener> <listener> <listener-class>com.wmdata.raindance.portal.menu.PGMenuFactory</listener-class> </listener> <listener> <listener-class>com.wmdata.raindance.portal.config.InitAP</listener-class> </listener> <!-- Rest --> <listener> <listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class> </listener> <!-- Faces Servlet --> <servlet> <servlet-name>Streamdoc</servlet-name> <servlet-class>com.wmdata.raindance.servlets.Streamdoc</servlet-class> </servlet> <servlet> <servlet-name>StreamAppendix</servlet-name> <servlet-class>com.wmdata.raindance.servlets.StreamAppendix</servlet-class> </servlet> <servlet> <servlet-name>Movedoc</servlet-name> <servlet-class>com.wmdata.raindance.servlets.Movedoc</servlet-class> </servlet> <servlet> <servlet-name>GetTicket</servlet-name> <servlet-class>com.wmdata.raindance.portal.auth.GetTicket</servlet-class> </servlet> <servlet> <servlet-name>ExtRepositoryReportRequest</servlet-name> <servlet-class>com.wmdata.raindance.bup.servlets.ExtRepositoryReportRequest</servlet-class> </servlet> <servlet> <servlet-name>PurchaseCommission</servlet-name> <servlet-class>com.wmdata.raindance.servlets.PurchaseCommission</servlet-class> </servlet> <servlet> <servlet-name>BirtResourceServlet</servlet-name> <servlet-class>com.wmdata.raindance.bup.birt.BirtResourceServlet</servlet-class> </servlet> <!-- Rest --> <servlet> <servlet-name>Resteasy</servlet-name> <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class> </servlet> <!-- Use extensions mapping for Faces servlet --> <context-param> <param-name>javax.faces.DEFAULT_SUFFIX</param-name> <param-value>.xhtml</param-value> </context-param> <context-param> <param-name>facelets.DEVELOPMENT</param-name> <param-value>true</param-value> </context-param> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.jsf</url-pattern> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <!-- Application servlets --> <servlet-mapping> <servlet-name>Streamdoc</servlet-name> <url-pattern>/rdservlets/Streamdoc</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>StreamAppendix</servlet-name> <url-pattern>/rdservlets/StreamAppendix</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>Movedoc</servlet-name> <url-pattern>/rdservlets/Movedoc</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>GetTicket</servlet-name> <url-pattern>/rdservlets/GetTicket</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ExtRepositoryReportRequest</servlet-name> <url-pattern>/rdservlets/ExtRepositoryReportRequest</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>PurchaseCommission</servlet-name> <url-pattern>/rdservlets/PurchaseCommission</url-pattern> </servlet-mapping> <!-- Rest --> <servlet-mapping> <servlet-name>Resteasy</servlet-name> <url-pattern>/resteasy/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>BirtResourceServlet</servlet-name> <url-pattern>/rdservlets/BirtResourceServlet</url-pattern> </servlet-mapping> <session-config> <!-- 30 minutes --> <session-timeout>30</session-timeout> </session-config> <!-- Specifies which files the web app shall look for as default --> <!-- when no file has been specified in the URL --> <welcome-file-list id="default"> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> </welcome-file-list> <!-- <error-page> Handle all exceptions in the portal application <exception-type>java.lang.Throwable</exception-type> <location>/portal/noauth/showError.jsp</location> </error-page> --> <!-- JSP Component Tag library from Bording --> <taglib> <taglib-uri>http://java.agetor.com/jspc</taglib-uri> <taglib-location>/WEB-INF/jspc.tld</taglib-location> </taglib> <!-- Agetor Tag library, may only be used in Anskaffningsportalen --> <taglib> <taglib-uri>http://java.agetor.com/agetor</taglib-uri> <taglib-location>/WEB-INF/inside.tld</taglib-location> </taglib> <!-- Another mapping used by Agetor Control Center --> <taglib> <taglib-uri>/inside.tld</taglib-uri> <taglib-location>/WEB-INF/inside.tld</taglib-location> </taglib> <context-param> <param-name>facelets.LIBRARIES</param-name> <param-value> /META-INF/elfunctions.taglib.xml </param-value> </context-param> </web-app> A: This was resolved by removing the shale-view component from the Apache shale framework
{ "language": "en", "url": "https://stackoverflow.com/questions/7582543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using generic std::function objects with member functions in one class For one class I want to store some function pointers to member functions of the same class in one map storing std::function objects. But I fail right at the beginning with this code: #include <functional> class Foo { public: void doSomething() {} void bindFunction() { // ERROR std::function<void(void)> f = &Foo::doSomething; } }; I receive error C2064: term does not evaluate to a function taking 0 arguments in xxcallobj combined with some weird template instantiation errors. Currently I am working on Windows 8 with Visual Studio 2010/2011 and on Win 7 with VS10 it fails too. The error must be based on some weird C++ rules i do not follow A: You can avoid std::bind doing this: std::function<void(void)> f = [this]-> {Foo::doSomething();} A: A non-static member function must be called with an object. That is, it always implicitly passes "this" pointer as its argument. Because your std::function signature specifies that your function doesn't take any arguments (<void(void)>), you must bind the first (and the only) argument. std::function<void(void)> f = std::bind(&Foo::doSomething, this); If you want to bind a function with parameters, you need to specify placeholders: using namespace std::placeholders; std::function<void(int,int)> f = std::bind(&Foo::doSomethingArgs, this, std::placeholders::_1, std::placeholders::_2); Or, if your compiler supports C++11 lambdas: std::function<void(int,int)> f = [=](int a, int b) { this->doSomethingArgs(a, b); } (I don't have a C++11 capable compiler at hand right now, so I can't check this one.) A: If you need to store a member function without the class instance, you can do something like this: class MyClass { public: void MemberFunc(int value) { //do something } }; // Store member function binding auto callable = std::mem_fn(&MyClass::MemberFunc); // Call with late supplied 'this' MyClass myInst; callable(&myInst, 123); What would the storage type look like without auto? Something like this: std::_Mem_fn_wrap<void,void (__cdecl TestA::*)(int),TestA,int> callable You can also pass this function storage to a standard function binding std::function<void(int)> binding = std::bind(callable, &testA, std::placeholders::_1); binding(123); // Call Past and future notes: An older interface std::mem_func existed, but has since been deprecated. A proposal exists, post C++17, to make pointer to member functions callable. This would be most welcome. A: Unfortunately, C++ does not allow you to directly get a callable object referring to an object and one of its member functions. &Foo::doSomething gives you a "pointer to member function" which refers to the member function but not the associated object. There are two ways around this, one is to use std::bind to bind the "pointer to member function" to the this pointer. The other is to use a lambda that captures the this pointer and calls the member function. std::function<void(void)> f = std::bind(&Foo::doSomething, this); std::function<void(void)> g = [this](){doSomething();}; I would prefer the latter. With g++ at least binding a member function to this will result in an object three-pointers in size, assigning this to an std::function will result in dynamic memory allocation. On the other hand, a lambda that captures this is only one pointer in size, assigning it to an std::function will not result in dynamic memory allocation with g++. While I have not verified this with other compilers, I suspect similar results will be found there. A: Either you need std::function<void(Foo*)> f = &Foo::doSomething; so that you can call it on any instance, or you need to bind a specific instance, for example this std::function<void(void)> f = std::bind(&Foo::doSomething, this); A: You can use functors if you want a less generic and more precise control under the hood. Example with my win32 api to forward api message from a class to another class. IListener.h #include <windows.h> class IListener { public: virtual ~IListener() {} virtual LRESULT operator()(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) = 0; }; Listener.h #include "IListener.h" template <typename D> class Listener : public IListener { public: typedef LRESULT (D::*WMFuncPtr)(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); private: D* _instance; WMFuncPtr _wmFuncPtr; public: virtual ~Listener() {} virtual LRESULT operator()(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) override { return (_instance->*_wmFuncPtr)(hWnd, uMsg, wParam, lParam); } Listener(D* instance, WMFuncPtr wmFuncPtr) { _instance = instance; _wmFuncPtr = wmFuncPtr; } }; Dispatcher.h #include <map> #include "Listener.h" class Dispatcher { private: //Storage map for message/pointers std::map<UINT /*WM_MESSAGE*/, IListener*> _listeners; public: virtual ~Dispatcher() { //clear the map } //Return a previously registered callable funtion pointer for uMsg. IListener* get(UINT uMsg) { typename std::map<UINT, IListener*>::iterator itEvt; if((itEvt = _listeners.find(uMsg)) == _listeners.end()) { return NULL; } return itEvt->second; } //Set a member function to receive message. //Example Button->add<MyClass>(WM_COMMAND, this, &MyClass::myfunc); template <typename D> void add(UINT uMsg, D* instance, typename Listener<D>::WMFuncPtr wmFuncPtr) { _listeners[uMsg] = new Listener<D>(instance, wmFuncPtr); } }; Usage principles class Button { public: Dispatcher _dispatcher; //button window forward all received message to a listener LRESULT onMessage(HWND hWnd, UINT uMsg, WPARAM w, LPARAM l) { //to return a precise message like WM_CREATE, you have just //search it in the map. return _dispatcher[uMsg](hWnd, uMsg, w, l); } }; class Myclass { Button _button; //the listener for Button messages LRESULT button_listener(HWND hWnd, UINT uMsg, WPARAM w, LPARAM l) { return 0; } //Register the listener for Button messages void initialize() { //now all message received from button are forwarded to button_listener function _button._dispatcher.add(WM_CREATE, this, &Myclass::button_listener); } }; Good luck and thank to all for sharing knowledge.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "238" }
Q: Understanding C++ member function template specialization I have the following class: #pragma once #include <string> #include <iostream> class testclass { public: template <class T> T item(const std::string& key) { std::cout << "non-specialized\n"; return T(); } }; For the item method I would like to provide a specialization for strings. I try to do this the following way (in testclass.cpp): #include "testclass.h" #include <iostream> template<> std::string testclass::item(const std::string& key) { std::cout << "specialized\n"; return std::reverse(key.begin(), key.end()); } And then I try to call the function like this: #include <iostream> #include "testclass.h" int main() { testclass t; std::string key = "foo"; t.item<int>(key); std::string s = t.item<std::string>(key); std::cout << s << std::endl; } However, the output is $ ./a.out non-specialized non-specialized (empty line) What I excepted was $ ./a.out non-specialized specialized oof How can I do this properly? I am using g++ 4.5.2 to compile the program. Edit: The solution is the move the whole definition of the specialization of item to testclass.h (but not into the class). I had other mistakes in the program, such as not including <algorithm> (for reverse), and incorrectly thinking that it would return the reversed string. To achieve the excepted behaviour, the .cpp file is left empty, and the header contents are the following: #pragma once #include <string> #include <iostream> #include <algorithm> class testclass { public: template <class T> T item(const std::string& key) { std::cout << "non-specialized\n"; return T(); } }; template<> std::string testclass::item(const std::string& key) { std::cout << "specialized\n"; std::string s = key; std::reverse(s.begin(), s.end()); return s; } A: Sadly, this is not the whole story. The explicit specialization of the member template function 'item' must be unique throughout the program. If you were to create another translation unit that implemented another function that did the same thing as 'main' and linked that into your program, you would get multiple definitions. You have a couple of alternatives: (1) declare the specialization to be an inline function in the header (not a general solution); (2) declare the specialization in the header and define it in the '.cpp' file (general answer). This is a great example of the importance of understanding at a fundamental level how compilers and linkers implement the "physical linking" of various C++ constructs. A: The problem boils down to the common problem of not having the templates in the header file. The compiler, when processing main does not see the specialization and it generates its own instantiation of the generic template for std::string. This is a violation of the ODR, as there are now 2 different specializations for std::string in the same program, but the compiler is not required to diagnose it. The simple solution is to declare/define the specialization in the header so that the compiler can either use it, or at least will know not to generate the specialization from the generic version when processing main
{ "language": "en", "url": "https://stackoverflow.com/questions/7582548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Dynamic ContextMenu In CodeBehind I just want to add ContextMenu for several objects that I create dynamically, but The only way I found is to create ContextMenu in runtime like this: ContextMenu pMenu = new ContextMenu(); MenuItem item1 = new MenuItem(); MenuItem item2 = new MenuItem(); //I have about 10 items //... item1.Header = "item1"; item1.Click += new RoutedEventHandler(item1_Click); pMenu.Items.Add(item1); item2.Header = "item2"; item2.Click += new RoutedEventHandler(item2_Click); pMenu.Items.Add(item2); //and so on It works, however, in WinForms I was able to drop ContextMenuStrip component to my form and define items and events very quickly w/o writing any code. Is it possible in WPF? A: You can define your ContextMenu in resources and bind it to any control you needed. Check this out: <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Window.Resources> <ContextMenu x:Key="MyContextMenu"> <MenuItem Header="Send" /> </ContextMenu> </Window.Resources> <Grid> <Button Name="a_button" ContextMenu="{StaticResource MyContextMenu}" > </Button> </Grid> </Window> A: The following code works for me, InsertQuery/DeleteQuery are two ICommand methods defined in ViewModel. <DataGrid.ContextMenu> <ContextMenu> <MenuItem Header="Insert" Command="{Binding DataContext.InsertQuery, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"/> <MenuItem Header="Delete" Command="{Binding DataContext.DeleteQuery, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"/> </ContextMenu> </DataGrid.ContextMenu> A: Additionaly you can put commands on the menuItem... Like this: <MenuItem Header="MyContextMenuItem Command="{Binding Path=MyCommand}" CommandTarget="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}"> CommandTarget can be very important, if you use your contextMenu on different controls. I often use the FindAncestor here, to identify the caller.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Java EE WebApplication on Tomcat6 Crashes I have a web application (J2EE+Tomcat6+MySQL+Struts2+Hibernate) running on a Linux Cent-OS. Sometimes(usually After about 3-4 days) it becomes inaccessible and I see a blank white page! Both "/etc/init.d/httpd status" AND "/etc/init.d/tomcat status" say they are running fine. I think my web-application crashes, because the Web-app can be up again when I restart the tomcat(restarting httpd solves nothing). The project's logs shows nothing suspicious. Please help me how can I trace the problem or find more about this crisis! Is this a tomcat problem or what? reinstalling tomcat can help my case? A: Narrowing down your problem is something no one can do for you, you need to shape up your general purpose debugging skills. If your logs show nothing wrong, that only means your logging is wrong. Probably also means you have a drowned exception somewhere. I wouldn't reinstall anything, when bugs happen in 99.99% cases they are in your own code. (when opposed to high-profile open-source systems) Your best chance is also to pinpoint which servlet is returning you that blank page. Is that page really blank? Check html source in your browser. 3-4 days bug period suggests a memory leak so I suggest using some java profiling tool on your app. http://download.oracle.com/javase/6/docs/technotes/guides/visualvm/ http://www.skill-guru.com/blog/2010/11/11/troubleshooting-application-performance-with-visualvm/
{ "language": "en", "url": "https://stackoverflow.com/questions/7582554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: XSL tansform result of DOMXpath->evaluate in php I have: $XML = new DOMDocument(); $XML->load('demo.xml'); $xpath = new DOMXpath($XML); $elements = $xpath->evaluate($_GET["xpath"]); $XSL = new DOMDocument(); $XSL->load('xml2json.xsl', LIBXML_NOCDATA); $xslt = new XSLTProcessor(); $xslt->importStylesheet($XSL); echo $xslt->transformToXML($elements); I get the following error: ( ! ) Warning: XSLTProcessor::transformToXml() [xsltprocessor.transformtoxml]: Invalid Document in C:\wamp\www\content.php on line 18 How do I convert a DOMNodeList to a DOMDocument to make this work? Here is how I got it to work! function getContent(&$NodeContent="",$nod) { $NodList=$nod->childNodes; for( $j=0 ; $j < $NodList->length; $j++ ) { $nod2=$NodList->item($j);//Node j $nodemane=$nod2->nodeName; $nodevalue=$nod2->nodeValue; if($nod2->nodeType == XML_TEXT_NODE) $NodeContent .= $nodevalue; else { $NodeContent .= "<$nodemane"; $attAre=$nod2->attributes; foreach ($attAre as $value) $NodeContent .=" {$value->nodeName}='{$value->nodeValue}'" ; $NodeContent .=">"; getContent($NodeContent,$nod2); $NodeContent .= "</$nodemane>"; } } } $XML = new DOMDocument(); $XML->load('demo.xml'); $xpath = new DOMXpath($XML); $elements = $xpath->query($_GET["xpath"]); $XSL = new DOMDocument(); $XSL->load('xml2json.xsl', LIBXML_NOCDATA); $xslt = new XSLTProcessor(); $xslt->importStylesheet($XSL); $newdoc = new DOMDocument; $newdoc -> preserveWhiteSpace = false; $newdoc -> formatOutput = true; $elm = $elements->item(0); getContent($docstring,$elm); $docstring = '<root>'.$docstring.'</root>'; $docstring = str_replace(array("\r\n", "\r", "\n", "\t"), '', $docstring); $newdoc -> LoadXML($docstring); echo $xslt->transformToXML($newdoc); A: You are doing $elements = $xpath->evaluate($_GET["xpath"]); … echo $xslt->transformToXML($elements); The return values for DOMXPath::evaluate() are Returns a typed result if possible or a DOMNodeList containing all nodes matching the given XPath expression. If the expression is malformed or the contextnode is invalid, DOMXPath::evaluate() returns FALSE. The method signature for transformToXML() states string XSLTProcessor::transformToXML ( DOMDocument $doc ) In other words, you are not passing a DOMDocument and get an "Invalid Document" error.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How do I route a request to a specific action in a specific controller in MVC2? In my MVC2 application I have an AccountController class inherited from Controller. I want to achieve the following: when a user tries to open Account/Payments/NewPayment AccountController.ExecuteNewPayment() method should be invoked. I added the following route: routes.MapRoute( @"CreateNewRuntime", @"{langId}/Account/Payments/NewPayment/{whatever}", new { langId = @"default", controller = @"Account", action = @"ExecuteNewPayment"}); but when I try to request the path above I get HTTP 404 error message with "Requested URL" /Account/Payments/NewPayment and when I do that under debugger there's an exception A first chance exception of type 'System.Web.HttpException' occurred in System.Web.Mvc.dll Additional information: The controller for path '/Account/Payments/NewPayment' was not found or does not implement IController. What am I doing wrong? How do I perform the mapping? A: I believe you should use these routes, routes.MapRoute( @"CreateNewRuntime1", @"Account/Payments/NewPayment/{whatever}", new { langId="en-US",controller = @"Account", action = @"ExecuteNewPayment" }); routes.MapRoute( @"CreateNewRuntime2", @"{langId}/Account/Payments/NewPayment/{whatever}", new { controller = @"Account", action = @"ExecuteNewPayment" }, new { langId = "[a-z]{2}-[a-z]{2}" }); Note that here in first route, I am not using langId and setting langId default value to "en-US". In second route langId is necessary but a regex is there so that other routes of your page are not disturbed. Without this regex, langid can be anything else. A: You need to include the langid as part of your route or MVC will not map your URI to it even if you have a default specified. Take these two routes: routes.MapRoute( @"CreateNewRuntime", @"{langId}/Account/Payments/NewPayment/{whatever}", new { langId = @"default", controller = @"Account", action = @"ExecuteNewPayment"}); routes.MapRoute( @"CreateNewRuntime1", @"{langId}/{subLangId}/Account/Payments/NewPayment/{whatever}", new { langId = @"default", subLangId= @"test", controller = @"Account", action = @"ExecuteNewPayment1"}); If I specify the URI of /Account/Payments/NewPayment, which one of the routes should it pick? If MVC did use the default for langId then the first route would always get used since it was declared before the other one. If you swapped the two then the second one would always get invoked. When you have varying data in the beginning of your URI's you need to specify them and you cannot use the default value when specifying the route. In order for these two routes to be hit you would need a URI of /eng/Account/Payments/NewPayment and /eng/e/Account/Payments/NewPayment A: {language} has no counterpart default value, is langid supposed to be language = @"default"? A: What you need is a custom route handler Have a look at this regards.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: lock free containers and visibility I've seen some lock free implementations of stack... My question is regarding the visibility, not atomicity. For example do elements(not pointers) of lock free stack must be at most 64bit? I think so, because you cant guarante visibility. Real example: can this struct be safely inserted and removed from lock free container struct person { string name; uint32_t age; } EDIT: some people are confused by the question. To explain a bit: if writer pushes person on stack, reader gets it, is it guaranteed that reader sees(memory visibility) correct content of the person. A: I may be wrong, but I think the question is incorrect. Atomic instructions deal typically with single pointer length data; at most, with two pointer lengths worth of data. A typical structure cannot be atomically manipulated because it is too large. So the lock-free stack will and only will be manipulating pointers to elements (which AFAIK need to be aligned on pointer length boundaries - I know of no platform where this is not the case). A: I must admit to being slightly confused by the question myself... Lock-free data-structures exist by manipulating pointers (of machine size & alignment) to nodes. Those nodes then contain the real "content" of your lock-free data-structure. That content can have any arbitrary size you want it to, so your struct could be put there. The usual node for lock-free data-structures looks something like: struct Node { ATOMIC_PTR next; content; } where content can be whatever you want it to be, a pointer to memory containing something or directly memory that contains something. Visibility is a non-issue here, since when modifying your lock-free data-structure, you'd first allocate a new node, then populate it with the desired content, and finally use atomic operations to set the various involved pointers right. Since that is the last thing you do, and those operations usually involve memory barriers themselves to guarantee visiblity and ordering, you're fine. A: According to other QnA's on SO, * *Does Interlocked.CompareExchange use a memory barrier? *question about lock free queues every x86 interlocked instruction (including CAS) imply a full memory barrier. So, at least on x86, we don't need to care about visibility of elements of lock-free containers (assuming that they use CAS.) A: Yes the structure could be used. Because all you need for a lock-free data structure is some way of atomically updating a single value that represents the innards of the structure. The size of the element or payload would not have any impact on its lock-free nature. As I understand it, a lock-free data structure would work like so: * *Copy the data *Modify the data *Atomically check that the original object has been unmodified and update it *Otherwise repeat from the beginning So as long as the third step can be performed atomically all is well. Making the elements themselves atomically updatable wouldn't give you any benefit since the container has to manage them collectively as a group. A: Note: Please mark this answer as correct only if you actually test this approach. About your question whether the below struct be safely inserted and removed from lock free container: struct person { string name; uint32_t age; } Multi-byte sequences of any length can be safely inserted/removed from lock free container if you use a redundant encoding. Let us assume that we already have atomic instructions for manipulating 4 bytes at a time (32 bits). In that case, we can encode the uint32_t age field like so: struct age_t { uint32_t age_low; uint32_t age_high; } The field age_low stores the low bits (for example, the low 16 bits) of the 32-bit uint32_t age. The field age_high stores the remaining high bits. Conceptually: struct age_t { uint16_t age_low; uint16_t id_low; uint16_t age_high; uint16_t id_high; } The fields id_low and id_high should contain an ID identifying the writer. A read is implemented as two atomic 32-bit reads, and succeeds if all the id_ parts are equivalent to each other. If it fails, the read operation needs to be restarted. A write is implemented as two atomic 32-bit writes, and is followed by a read of the whole age_t value. The write succeeds if: the read mentioned in the previous sentence succeeds and the IDs which were read are equivalent to the written IDs. About the string value: the principle is the same. You just need to figure out how to split its binary value similarly to how age value was split. Same in respect to reading/writing the whole person structure. A: Thread safe containers (lockfree or with locks for that matter) solve the thread safety of the list/container not the thread safety of the items you put into the container. Thus the lock-free stack will make sure the push and pop are threadsafe and lock-free but if you have two different threads that holds pointers to the same struct instance (e.g. the thread that pushed into the stack still holds the ponter and another thread pops the stack) you'd have to use some other thread-safety measure to ensure the structs consistency A: One could implement a thread-safe implementation of a dequeue for arbitrary-sized data elements if the elements did not have to be stored within the stack or queue in any particular order, and if one used a thread-safe queue to hold the indices of unallocated items, as well as a thread-safe dequeue to hold the indices of the data slots which hold the enqueued/stacked items. Writing an item to the dequeue would entail pulling a number from the "unallocated slots" queue, writing the desired data to that slot, and then enqueueing the index of that number in the "main" dequeue. Fetching an item would require pulling its number from the "main" dequeue, copying it elsewhere, and then enqueueing that number in the "unallocated slots" queue. One caveat with this approach is that it while it may be "lock-free" insofar as a thread which stalls cannot arbitrarily delay the progress of other threads, a thread which gets waylaid between the time it acquires a slot index from one queue and the time it stores it in another queue may render an array slot unusable for an arbitrary length of time. By contrast, some wait-free stack or queue implementations used with smaller data types don't have that limitation. A thread could vanish from existence during a read or write, and the system would either be in a valid state representing that the read or write completed, or else in a valid state indicating it was never begun.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582561", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Build executable jar from multiple maven modules I have problem with building the single executable jar from multiple maven modules. So here is the situation: I have three maven modules: app -> persistence -> domain. I have parent pom.xml too. I added to this parent pom maven assembly plugin: <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <configuration> <archive> <manifest> <mainClass>com.toys.app.Service</mainClass> </manifest> </archive> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> </plugin> So when I type from command line in parent pom directory (which contain parent.pom and app, persistence and domain maven modules) command: mvn assembly:assembly it gave my next error: [INFO] ------------------------------------------------------------------------ [INFO] Building persistence 1.0-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- maven-assembly-plugin:2.2-beta-5:single (default-cli) @ persistence --- [INFO] ------------------------------------------------------------------------ [INFO] Reactor Summary: [INFO] [INFO] parent ..................................... SUCCESS [3.147s] [INFO] domain ............................................ SUCCESS [4.765s] [INFO] persistence ....................................... FAILURE [0.570s] [INFO] app ............................................... SKIPPED [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 9.287s [INFO] Finished at: Wed Sep 28 12:30:26 CEST 2011 [INFO] Final Memory: 6M/81M [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal org.apache.maven.plugins:maven-assembly-plugin:2.2-beta-5:single (default-cli) on project persistence: Failed to create assembly: Failed to resolve dependencies for project: com.toys:persistence:jar:1.0-SNAPSHOT: Missing: [ERROR] ---------- [ERROR] 1) com.toys:domain:jar:1.0-SNAPSHOT [ERROR] [ERROR] Try downloading the file manually from the project website. [ERROR] [ERROR] Then, install it using the command: [ERROR] mvn install:install-file -DgroupId=com.toys -DartifactId=domain -Dversion=1.0-SNAPSHOT -Dpackaging=jar -Dfile=/path/to/file [ERROR] [ERROR] Alternatively, if you host your own repository you can deploy the file there: [ERROR] mvn deploy:deploy-file -DgroupId=com.toys -DartifactId=domain -Dversion=1.0-SNAPSHOT -Dpackaging=jar -Dfile=/path/to/file -Durl=[url] -DrepositoryId=[id] [ERROR] [ERROR] Path to dependency: [ERROR] 1) com.toys:persistence:jar:1.0-SNAPSHOT [ERROR] 2) com.toys:domain:jar:1.0-SNAPSHOT [ERROR] [ERROR] ---------- [ERROR] 1 required artifact is missing. [ERROR] [ERROR] for artifact: [ERROR] com.toys:persistence:jar:1.0-SNAPSHOT [ERROR] [ERROR] from the specified remote repositories: [ERROR] central (http://repo1.maven.org/maven2, releases=true, snapshots=false) [ERROR] -> [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException [ERROR] [ERROR] After correcting the problems, you can resume the build with the command [ERROR] mvn <goals> -rf :persistence Every other maven life-cycles works fine! Can Anyone help me? A: Try to add execution phase: <plugin> <artifactId>maven-assembly-plugin</artifactId> <configuration> <archive> <manifest> <mainClass>com.toys.app.Service</mainClass> </manifest> </archive> <descriptorRef>jar-with-dependencies</descriptorRef> </configuration> <executions> <execution> <id>make-jar-with-dependencies</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin> </plugins> A: I suggest you add project 'distribution' on the same level as your app, persistence, domain projects. <project> <artifactId>distribution</artifactId> <packaging>pom</packaging> <parent> ... </parent> <dependencies> <dependency> <groupId>${project.groupId}</groupId> <artifactId>app</artifactId> <version>${project.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>${project.groupId}</groupId> <artifactId>persistence</artifactId> <version>${project.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>${project.groupId}</groupId> <artifactId>domain</artifactId> <version>${project.version}</version> <scope>runtime</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <configuration> <archive> <manifest> <mainClass>com.toys.app.Service</mainClass> </manifest> </archive> <descriptorRef>jar-with-dependencies</descriptorRef> </configuration> <executions> <execution> <id>make-jar-with-dependencies</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> <plugin> </plugins> </build> </project> I had similar problems when trying to create distribution in the reactor POM, after moving to its own project - no headaches. Also, don't forget to add 'distribution' module to the reactor project.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS + Opacity change on Hover + Flickering I am trying to achieve a very simple thing: change opacity of a table row on hover. Unfortunately, it doesn't work very good, because if I hover in and out very fast, sometimes the opacity change is too slow and it seems like the colors are flickering. This flickering doesn't happen when I hover in and out kinda slow. I made an example so you know what I mean: http://jsfiddle.net/yfhTW/2/ Is this behavior a browser bug or is something wrong with my code? And can it be fixed somehow? I have tried to use a Jquery script instead of doing the opacity change via CSS, but the results are the same :/ A: Try to add the border: 1px solid transparent; to the element (not to :hover pseudoclass). It worked for me. A: For people coming here who have an image with an opacity that isn't 1, and have a similar flicker, make sure you set background-color:white; on the image! I know this doesn't resolve the question at hand but it is a similar problem. .post img { opacity:.8; background-color:white; } .post:hover img { opacity:1; } A: Ha, it's almost the same problem the webkit sometimes have. So, I've tried to emulate the fix for webkit (the one with -webkit-transform: translateZ(0)), but using the 2D transform, and it worked! So, it seems like just adding -moz-transform: rotate(0); to the elements that are affected by flickering solves the problem: http://jsfiddle.net/kizu/yfhTW/4/ A: This did not work for me and so I thought I would mention what did. I had to add overflow:hidden to all of the surrounding elements. A: In case the affected element is already translated (and thus, the fix by kizu is not applicable) make sure to set -webkit-backface-visiblity: -webkit-transform-style: preserve-3d; -webkit-backface-visibility: hidden; A: After trying the above suggestons, adding a z-index to the item the hover effect was being applied to solved the problem for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to protect directories I have uploaded different Microsoft Word documents to the directory http://www.mywebsite.com/documents/ Now the problem is that when I browse to this url you can see all my documents in a list but they need to be hidden and only aproachable by a given link (for example http://www.mywebsite.com/documents/document1.doc) Any idea how I can do this? Is it OK to place a index.html in every documents directory so they get a blank page, or does Google not like this? A: If you are using IIS, make sure you have unchecked the "Allow Directory Browsing" in the directory properties. If you are using Apache, read this Apache configuration A: you can disable directory browsing using .htaccess file if you use apche. just add the below line into your .htaccess file Options -Indexes This will disable the directory browsing in your website.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Php $_POST method to get textarea value I am using php to get textarea value using post method but getting a weird result with that let me show you my code <form method="post" action="index.php"> <textarea id="contact_list" name="contact_list"></textarea> <input type="submit" name="submit" value="Send" id="submit"/> </form> I am entering some names and their email address in the textarea, and everytime i echo the value or textarea it skips the email address and only showing the name let me show the way i am entering value in textarea "name1" <name@email.com>, "name2" <name2@email.com> and once I will echo using php it will only echo the name and will skip the email address. A: Make sure your escaping the HTML characters E.g. // Always check an input variable is set before you use it if (isset($_POST['contact_list'])) { // Escape any html characters echo htmlentities($_POST['contact_list']); } This would occur because of the angle brackets and the browser thinking they are tags. See: http://php.net/manual/en/function.htmlentities.php A: Always (always, always, I'm not kidding) use htmlspecialchars(): echo htmlspecialchars($_POST['contact_list']); A: Use htmlspecialchars(): echo htmlspecialchars($_POST['contact_list']); You can even improve your form processing by stripping all tags with strip_tags() and remove all white spaces with trim(): function processText($text) { $text = strip_tags($text); $text = trim($text); $text = htmlspecialchars($text); return $text; } echo processText($_POST['contact_list']); A: Remove some of your textarea class like <textarea name="Address" rows="3" class="input-text full-width" placeholder="Your Address" ></textarea> To <textarea name="Address" rows="3" class="full-width" placeholder="Your Address" ></textarea> It's dependent on your template (Purchased Template). The developer has included some JavaScript to get the value from correct object on UI, but class like input-text just finds only $('input[type=text]'), that's why. A: Try to use different id and name parameters, currently you have same here. Please visit the link below for the same, this might be help you : Issue using $_POST with a textarea A: //My Form <form id="someform"> <div class="input-group"> <textarea placeholder="Post your Comment Here ..." name="post" class="form-control custom-control" rows="3" style="resize:none"></textarea> <span class="input-group-addon"> <button type="submit" name="post_comment" class="btn btn-primary"> Post </button> </span> </div> </form> //your text area get value to URL <?php if(isset($_POST['post_comment'])) { echo htmlspecialchars($_POST['post']); } ?> //print the value using get echo $_GET['post']; //url must be like this http://localhost/blog/home.php?post=asdasdsad&post_comment= //post value has asdasdsad so it will print to your page A: it is very simply. Just write your php value code between textarea tag. <textarea id="contact_list"> <?php echo isset($_POST['contact_list']) ? $_POST['contact_list'] : '' ; ?> </textarea> A: Try this: <?php /* the php */ ?> <?php if ($_POST['submit']) { // must work echo $_POST['contact_list']; }; ?> <?php /* and the html */ ?> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>teszt</title> </head> <body> <form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>"> <textarea id="contact_list" name="contact_list"></textarea> <input type="submit" name="submit" value="Send" id="submit"/> </form> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7582577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: How can we Create a lightbox gallery with sql images I am using asp.net 4.0 and all my images are stored in database using admin CMT. I want to create a image gallery to display all thumbnail images in a list and lightbox effect for big images. lightbox works fine if we have a physical location of the image, but in this case it is binary data (image datatype) in database. Can you help me how can i assign the (binary) image to lightbox. A: You need a script that ouputs a single image under a specified URL. Then you can take these URLs and provide them to the lightbox. A: Using lightbox for displaying images from database directly Create a HTTP handler and called the handler in the in every img scr <img src="ShowImg.ashx?ID=imageid" alt="imgetitle" /> handler will load the image from the imageid passed as a querystring to it. on handler we will right the code to read the image from database and display on the page. A: Image control will read value returned by HTTPHandler but problem with lightbox is that you must provide img src to HyperLink navigateUrl or and those are not able to read Image value returned by HTTPHandler, you must have lightbox plug-in that is able to read image files...
{ "language": "en", "url": "https://stackoverflow.com/questions/7582588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JPA2 and hibernate - why does merge store child entities whilst persist does not? I have the usual parent - child OneToMany relationship: @OneToMany(mappedBy = "mapType", cascade = CascadeType.ALL, orphanRemoval = true) public List<Child> getChildren() { return children; } I have fairly standard use cases: * *Must delete children on persist- this works fine. *Add new children by adding to collection. This works fine for already persisted parents, but does not work for new parents. EntityManager.merge however does persist the new parent with the new children. Why would adding new children not work for new Parent objects? They're definitely there before persist is called. I'm on Hibernate 3.6.6 by the way. A: Try to add this attribute in @OneToMany annotation fetch = FetchType.EAGER. Default value is LAZY. It'll be helpful because hibernate will be manage collection permanently then you make changes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to PLINQ an existing LINQ query with Joins? I'm using LINQ to compare two DataSets with each other to create new rows and update existing. I've noticed that the complete comparison lasts ~1,5 hours and only one of the two cores is busy(Task-Manager is 50-52% CPU Usage). I must admit that I'm completely new to parallel LINQ, but I assume that it could increase performance significantly. So my question is, how and what should I parallelize? These are the original queries(reduced to the essentials): 'check for new data Dim srcUnique = From row In src.Email_Total Select Ticket_ID = row.ticket_id, Interaction = row.interaction, ModifiedAt = row.modified_time Dim destUnique = From row In dest.ContactDetail Where row.ContactRow.fiContactType = emailContactType.idContactType Select row.ContactRow.Ticket_ID, row.Interaction, row.ModifiedAt 'get all emails(contactdetails) that are in source but not in destination Dim diffRows = srcUnique.Except(destUnique).ToList 'get all new emails(according to ticket_id) for calculating contact columns Dim newRowsTickets = (From row In src.Email_Total Join d In diffRows On row.ticket_id Equals d.Ticket_ID _ And row.interaction Equals d.Interaction _ And row.modified_time Equals d.ModifiedAt Group row By Ticket_ID = row.ticket_id Into NewTicketRows = Group).ToList For Each ticket In newRowsTickets Dim contact = dest.Contact.FindByTicket_IDfiContactType(ticket.Ticket_ID, emailContactType.idContactType) If contact Is Nothing Then ' Create new Contact with many sub-queries on this ticket(omitted) ****' Dim newContact = Me.dest.Contact.NewContactRow dest.Contact.AddContactRow(newContact) contact = newContact Else ' Update Contact with many sub-queries on this ticket(omitted) ' End If daContact.Update(dest.Contact) ' Add new ContactDetail-Rows from this Ticket(this is the counterpart of the src.Email_Total-Rows, details omitted) ' For Each newRow In ticket.NewTicketRows Dim newContactDetail = dest.ContactDetail.NewContactDetailRow newContactDetail.ContactRow = contact dest.ContactDetail.AddContactDetailRow(newContactDetail) Next daContactDetails.Update(dest.ContactDetail) Next Note: daContact and daContactDetails are SqlDataAdapters, source and dest are DataSets and Contact and ContactDetail are DataTables, where every ContactDetail belongs to a Contact. Even if not both cores would use 100% CPU, I assume that it would increase performance significantly if I would parallelize the queries, because the second core is nearly idle. The for each might also be a good place to optimize since the tickets are not related to each other. So I assume that I could loop with multiple threads and create/update records parallel. But how to do it with PLINQ? Side Note: As I've mentioned in the comments, performance is not a key factor for me so far, since the server's only purpose is to synchronize the MySQL Database(on another server) with a MS SQL-Server(on the same server as this Windows-Service). It acts as a source for reports that are generated by another service. But these reports are only generated once a day. But apart from that I was interested in learning PLINQ because I thought that this could be an excellent exercise. It takes the mentioned 1,5h only if destination DB is empty and all records must be created. If both databases are nearly in sync, this method takes only ~1 minute yet. In future performance will become more important since email is only one of several contact-types(chat+calls will exceed 1mil.records). I think that I'll anyway need some kind of (LINQ) Data-Paging then. If something is unclear I'll update my answer accordingly. Thanks in advance. Edit: Here is the result of my investigations and attempts: Question: How to "PLINQ" an existing LINQ query with joins? Answer: Note that some LINQ operators are binary—they take two IEnumerables as input. Join is a perfect example of such an operator. In these cases, the type of the left-most data source determines whether LINQ or PLINQ is used. Thus you need only call AsParallel on the first data source for your query to run in parallel: IEnumerable<T> leftData = ..., rightData = ...; var q = from x in leftData.AsParallel() join y in rightData on x.a == y.b select f(x, y); But if I change my query in the following way(note the AsParallel): Dim newRowsTickets = (From row In src.Email_Total.AsParallel() Join d In diffRows On row.ticket_id Equals d.Ticket_ID _ And row.interaction Equals d.Interaction _ And row.modified_time Equals d.ModifiedAt Group row By Ticket_ID = row.ticket_id Into NewTicketRows = Group).ToList The compiler will complain that I need to add AsParallel to the right datasource as well. So this seem to be a VB.NET issue or a lack of documentation(article is from 2007). I assume the latter because the(apart from that recommendable) article also says that you need to add System.Concurrency.dll manually but actually it is part of .NET 4.0 Framework and in Namespace Sytem.Threading.Tasks. I realized that I won't profit from a parallelized Except since the query is fast enough in sequential mode(even with nearly the same number of rows in both collection which results in the maximum number of comparisons, I got the result in less than 30 seconds). But I will add it for the sake of completeness later. So I decided to parallelize the for-each what is as easy as with LINQ-Queries, you simply need to add AsParallel() at the end. But I realized that I need to force the parallelism with WithExecutionMode(ParallelExecutionMode.ForceParallelism), otherwise .NET decides to use only one core for this loop. I also wanted to tell .NET that I wish to use as many Threads as possible but not more than 8: WithDegreeOfParallelism(8). Now both cores are working at the same time, but the CPU usage stays on 54%. So this is the PLINQ version so far: Dim diffRows = srcUnique.AsParallel.Except(destUnique.AsParallel).ToList Dim newRowsTickets = (From row In src.Email_Total.AsParallel() Join d In diffRows.AsParallel() On row.ticket_id Equals d.Ticket_ID _ And row.interaction Equals d.Interaction _ And row.modified_time Equals d.ModifiedAt Group row By Ticket_ID = row.ticket_id Into NewTicketRows = Group).ToList For Each ticket In newRowsTickets. AsParallel(). WithDegreeOfParallelism(8). WithExecutionMode(ParallelExecutionMode.ForceParallelism) ' blah,blah ... ' 'add new ContactDetails for this Ticket(only new rows) For Each newRow In ticket.NewTicketRows. AsParallel(). WithExecutionMode(ParallelExecutionMode.Default) ' blah,blah ... ' Next daContactDetails.Update(dest.ContactDetail) Next Unfortunately I don't see any performance benefits from using AsParallel in comparison with sequential mode: The for each with AsParallel(hh:mm:ss.mm): 09/29/2011 18:54:36: Contacts/ContactDetails created or modified. Duration: 01:21:34.40 And without: 09/29/2011 16:02:55: Contacts/ContactDetails created or modified. Duration: 01:21:24.50 Can somebody explain me this result? Is the database' write access in the for each responsible for the similar time? Following are recommendable readings: * *http://msdn.microsoft.com/en-us/magazine/cc163329.aspx (not up-to-date) * *List of changes since above article *Overview of videos/articles according this topic *PDF: When To Use ParallelForEach Or PLINQ *When PLINQ will speedup performance A: There are 3 points worth investigating further, * *Do not use .toList(). I might be wrong but I think using .ToList this way would not allow the compiler to optimize the query, if further optimization was possible. *Use your own filtering operation to compare data from both destionations. It might give you better performance. *See if you could use LinqDataview to provide better performance. I dont think you will gain an advantage of PLinq while doing insertion. Look at this answer for more details. Hope that helps. Please do ask if you need clarification on any of the above points.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How does this forces singleton? In some code, I saw singleton template template<typename T> class Singleton { public: Singleton(T& instance) { assert(!sfpInstance || (sfpInstance==&instance)); sfpInstance = &instance; } static T& getInstance() { assert(sfpInstance); return *sfpInstance; } private: static T* sfpInstance; }; And classes used like this: class MyClass : public Singleton<MyClass> { protected: MyClass() : Singleton<MyClass>(*this) {} } I don't know how can this be used as singleton? If it can be used, what is the proper way to use it. EDIT: MyClass constructor is protected. A: This code won't work at all since there is no publicly available constructor of MyClass and Singleton is no friend of MyClass. Now, if the MyClass constructor /were/ public, each call of the MyClass constructor would check whether the global sfpInstance pointer already points somewhere object, and triggers the assertion if it does. Thereby, only a single instance of MyClass can be constructed during the program run. Note that this method is not really elegant since it does not track the destruction of the MyClass singleton instance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ASP.NET MySQL using stored procedures Someone told me using stored procedures could be bad for database performance, that is better to have the query inside the code and call database. For me is better to have a stored procedure since if I have to make a change in the database I don't have to recompile the whole web app to change a SELECT statement.... What do you think? A: Did the person who told you this have a reason to back up their statement? If they can't explain it, then chances are they don't actually know what they're talking about, they're probably just repeating something they heard or mis-heard somewhere. Stored procedures in general are considered to perform better, but not for the reason you suggest. Database engines internally parse the queries sent to them to develop an execution plan. (Think of it like compiling the query code.) With a stored procedure, the database saves this execution plan so it doesn't have to compile it later. So that step is skipped when using a stored procedure. This same thing can apply to parameterized queries, etc. though. Modern database engines are pretty good at optimizing things. That's why I say "in general" above. There are a lot of details about the optimization of code-database interactions. But for the most part the statement holds true. As for re-compiling your app, that's another story entirely. If you change the shape of the data being returned by the stored procedure, then wouldn't you have to update the app anyway? Changing the shape of a table shouldn't affect the app if the app doesn't need to know about it. (Unless you're using SELECT *, which isn't good practice for primarily this reason.) If, on the other hand, you're talking about using stored procedures as a kind of database API for apps to use which conceals the actual table schema, then that can certainly work. As long as the app isn't bound to a specific schema implementation, I'd consider that a good design decision. In this case I guess the stored procedures would be acting as part of the data access layer itself. A: This debate has been running for a long, long time now. In general, the performance difference between stored procs and embedded SQL is almost never an issue anymore - as David says, database engines are really good at optimizing queries. However, within stored procs, inexperienced developers have been known to write poorly performing code - classic anti-pattern is procedural, rather than set-based thinking - looping through a table record by record and updating that record, rather than an update statement with a where clause. On the other hand, "manageability" continues to be a really big deal. And then it all depends on the people and processes you already have. If your developers are not familiar with stored procs, I'd avoid them - you can end up with unmaintainable procedures which nobody wants to touch. If your client code is tightly coupled with the database code (which is nearly always the case), you need to have a release process for keeping them in sync - and source code control for schema objects (inc. stored procs) is not always straightforward. There's a risk that you end up with lots of stored procs which don't add value - simple CRUD operations. You could be creating a lot of code (which needs to be versioned, deployed and maintained) without adding any extra value. Philosophically, most current software architectures are based on object orientation in some way - stored procs inject procedural code into that paradigm (though you can deal with this by creating a database API, as David suggests - data as a service). So, unless your application is focussed mostly on the database, in general, I recommend against stored procedures - they don't pay their way in terms of maintainability. Exceptions are batch routines - archiving, data cleansing etc. - which are often easier to manage as stored procs, but have almost no external dependencies.
{ "language": "en", "url": "https://stackoverflow.com/questions/7582600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }