text
stringlengths
8
267k
meta
dict
Q: jQuery autocomplete item click and event bubbling How can I get the link click to trigger a select? EDIT: Im refering to why doesnt the line $("a:contains('item2')").click(); trigger a autocomplete menu select? <!doctype html> <head> <title>Test</title> <script src="jquery-1.6.4.js"></script> <script src="jquery-ui-1.8.16.js"></script> </head> <script> $(function() { var menu = $('<div></div>') .attr('id', 'menu') .appendTo('body') .autocomplete({ minLength: 0, source: ['item1','item2'], select: function(event, ui){ alert('selected ' + ui.item.label); } }) ; $('<button></button>') .attr('id', 'open') .button({ label: 'display menu' }) .click(function() { menu.focus(); menu.autocomplete("search", ""); }) .appendTo('body') .height(30) ; $('<button></button>') .click(function() { $("#open").click(); $("a:contains('item2')").click(); }) .appendTo('body') ; }); </script> <body> </body> </html> A: This is caused by an "unfortunate" choice in the autocomplete widget -- it doesn't know what item you're selecting unless you've previously "hovered" it to make it the active menu choice. $('<button></button>') .click(function() { $("#open").click(); $("a:contains('item2')").trigger('mouseover').trigger('click'); }) .appendTo('body');
{ "language": "en", "url": "https://stackoverflow.com/questions/7572043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Validator id is not registered i am getting this warning in eclipse: Validator id is not registered on the line: <f:validator validatorId="confirmPasswordValidator" /> i am using JSF 2, and tomcat 6 and my el-impl library is org.glassfish.web any ideas why ? and how to solve it ? A: Ignore and run it. Eclipse is relying on it being present as <validator> declaration in faces-config.xml the JSF 1.x way. It does by default not recognize @FacesValidator and likes yet and therefore don't see it already being registered by new JSF 2.x annotations. The upcoming newer Eclipse versions will. You could consider to turn off JSF validation in Eclipse preferences, it will only lead to more confusion and annoyances. The upcoming JBoss Tools plugin 3.3 (currently still in beta) will support JSF annotations like @FacesValidator, @ManagedBean, etc. Note that this is in no way related to EL. You aren't using #{} anywhere.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Segmentation fault with arrays and pointers I have a segmentation fault...i'm not sure what's causing it. Also, when passing the member pname into the function get_names, am I doing this correctly, or is there a better way of doing this? #include <stdio.h> #define MAX_NAME 20 #define MAX_PLAYRS 16 typedef struct { char pname[MAX_NAME]; int runs; char how_out; } Team_t; Team_t player[MAX_PLAYRS]; Team_t *player_ptr[MAX_PLAYRS]; void get_names (int count, char *str); int main (void) { int i; for (i = 0; i < MAX_PLAYRS; i++) { get_names(i, &(*player[i].pname)); printf("Player: %s\n", player[i].pname); } } void get_names (int count, char *str) { FILE *inp; char status; inp = fopen("teamnames.rtf", "r"); status = fscanf(inp, "%s", str); if (status == EOF) { count = MAX_PLAYRS; } } A: With your code unchanged, I get a segmentation fault if the file can't be opened properly (i.e. it's unreadable due to permissions, or it simply does not exist). Here's a modified version of you function get_names(): void get_names(int count, char *str) { FILE *inp; inp = fopen("teamnames.rtf", "r"); if (inp == NULL) { perror("Failed"); return; } fgets(str, MAX_NAME, inp); fclose(inp); } This would still read the first name 16 times, but it would tell you why it didn't manage to open the file. To read the next name from the file (rather than repeatedly the first name), open (and close) the file in the main() function instead. Also, you might as well call get_names() like so: get_names(i, player[i].pname); No need to do that &(*...) thing you're doing. And, finally, I hope that the teamnames.rtf file is not actually an RTF file, but a simple text file with a name on each line. A: Get a debugger to tell you what is wrong. Compile the code with debugging enabled (see you man page for your compiler) and run something like this: gdb a.out core Then you should be able to see which line made the code core dump. You could use idb as well, if you have the intle compiler installed. This is, of course, on *nix. If you are talking windows, use the VS debugger. In addition do NOT use fscanf as it is unsafe. Use fgets instead. A: The problem comes from this line: get_names(i, &(*player[i].pname)); Understanding pointers and dereferencing is one of the biggest adjustments to learning C if you are switching from another language. You're doing it wrong, and I think you should seek out a tutorial on the subject. Try http://www.cplusplus.com/doc/tutorial/pointers/ as a starting point. A: There are many strange things. First thing is, it seems like the names are in a file, but what you are doing is in every iteration of your for loop, you call get_names which opens the file again, that is goes to the beginning of the file and you read the same name over and over again. That is if you closed the file. Since you haven't closed the file, the file is already open and you keep reopening it (which could be the cause of your problem) Another thing is, how can if (status == EOF) { count = MAX_PLAYRS; } Give you the current count? Regardless of the count of the players in the file, you are just setting it to MAX_PLAYERS. Another thing is that count is an input to the function that is not a pointer, so setting it does not change the value outside the function (which is what I assumed you wanted). Here is how I would do it with minimum change to your code: #include <stdio.h> #define MAX_NAME 20 #define MAX_PLAYRS 16 typedef struct { char pname[MAX_NAME]; int runs; char how_out; } Team_t; Team_t player[MAX_PLAYRS]; Team_t *player_ptr[MAX_PLAYRS]; void get_names (int count, char *str, FILE *inp); int main (void) { FILE *inp; int i; int count; inp = fopen("teamnames.rtf", "r"); for (i = 0; i < MAX_PLAYRS; i++) { get_names(&count, player[i].pname, inp); printf("Player: %s\n", player[i].pname); } } void get_names (int *count, char *str) { char status; status = fscanf(inp, "%s", str); if (status == EOF) { *count = MAX_PLAYRS; } } Here is how I would do it more concisely: #include <stdio.h> #define MAX_NAME 20 #define MAX_PLAYRS 16 typedef struct { char pname[MAX_NAME]; int runs; char how_out; } Team_t; Team_t player[MAX_PLAYRS]; Team_t *player_ptr[MAX_PLAYRS]; int get_names (Team_t *team); int main (void) { get_names(player); } int get_names (Team_t *team) { int i = 0; FILE *inp; inp = fopen("teamnames.rtf", "r"); while (i < MAX_PLAYRS && !feof(inp) { fscanf(inp, "%s", team[i].pname); printf("Player: %s\n", player[i].pname); } } Note that the problems with fscanf, checking array boundaries etc are not the concern of this solution, but this rather gives you the idea of what to do not a code for you to copy-paste.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572050", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: nspredicate problem with AND operation I am stuck up with below line and i am not have much knowledge on coredata , `NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(bookPath == %@) AND (accessed==%u)) AND (isCurrentSession==%u)", myString,[NSNumber numberWithBool:NO],[NSNumber numberWithBool:_accessed]];` upto now i sent two values to my predicate, in the above predicate i am using three values, My Question: can we apply two AND operations in a single predicate, can any one provide some idea about this.Thanks in Advance. A: Yes, you should be able to combine predicates with 'AND' and 'OR' to an arbitrary level of complexity. The formal parser grammar for the predicate syntax can be found here. For best performance you should order your predicate terms so that simple tests (e.g numeric comparisons) appear first in the format string and more complex tests (e.g. REGEX pattern matching) appear last.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Transfer piece of xaml to resource I have 8 columns and every of them has the same datacontext. <!-- COLUMN: PREVIEW MESSAGE --> <data:DataGridTemplateColumn x:Name="PreviewColumn" CanUserSort="True" SortMemberPath="Preview" Width="*"> <data:DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding Preview}" FontWeight="{Binding IsBold, Converter={StaticResource cnvFontWeight}}" Foreground="{Binding IsOverdueMessage, Converter={StaticResource cnvOverdue}}" VerticalAlignment="Center" Margin="5,0,5,0"> <telerik:RadContextMenu.ContextMenu> <telerik:RadContextMenu Opened="inboxContextMenu_Opened" ItemClick="inboxContextMenu_ItemClick"> <telerik:RadMenuItem Header="Forward message" Loaded="ForwardMessageMenuItem_Loaded"/> </telerik:RadContextMenu> </telerik:RadContextMenu.ContextMenu> </TextBlock> </DataTemplate> </data:DataGridTemplateColumn.CellTemplate> </data:DataGridTemplateColumn> What is the most practical way to make this contextmenu reusable? It is in every column identical. I haven't much experience in silverlight. I'm using silverlight 4. A: First I thought, you could create a specific style for the TextBlock, and then put the ContextMenu inside the style. However, because TextBlock is not inherited from ContentControl, you can't simply do it. What you then can do is, use a Label instead of the TextBlock. After including the sdk namespace, you would have something like this, xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" <sdk:Label Content="{Binding Preview}" FontWeight="{Binding IsBold, Converter={StaticResource cnvFontWeight}}" Foreground="{Binding IsOverdueMessage, Converter={StaticResource cnvOverdue}}" VerticalAlignment="Center" Margin="5,0,5,0" Style="{StaticResource LabelWithContextMenuStyle}"/> You can see I have specified a style for this Label control. This style basically is the Label's default style with an additional ContextMenu sitting inside its ContentControl. <Style x:Key="LabelWithContextMenuStyle" TargetType="sdk:Label"> <Setter Property="IsTabStop" Value="False"/> <Setter Property="HorizontalContentAlignment" Value="Left"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="sdk:Label"> <Grid> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal"/> <VisualState x:Name="Disabled"/> </VisualStateGroup> <VisualStateGroup x:Name="ValidationStates"> <VisualState x:Name="Valid"/> <VisualState x:Name="Invalid"> <Storyboard> <ObjectAnimationUsingKeyFrames Duration="0:0:1.5" Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentControl"> <DiscreteObjectKeyFrame KeyTime="0"> <DiscreteObjectKeyFrame.Value> <SolidColorBrush Color="Red"/> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> <VisualStateGroup x:Name="RequiredStates"> <VisualState x:Name="NotRequired"/> <VisualState x:Name="Required"> <Storyboard> <ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetProperty="FontWeight" Storyboard.TargetName="ContentControl"> <DiscreteObjectKeyFrame KeyTime="0" Value="SemiBold"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" CornerRadius="2" Padding="{TemplateBinding Padding}"> <ContentControl x:Name="ContentControl" Cursor="{TemplateBinding Cursor}" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" Foreground="{TemplateBinding Foreground}" FontWeight="{TemplateBinding FontWeight}" FontStretch="{TemplateBinding FontStretch}" FontSize="{TemplateBinding FontSize}" FontFamily="{TemplateBinding FontFamily}" HorizontalAlignment="{TemplateBinding HorizontalAlignment}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" IsTabStop="False" VerticalAlignment="{TemplateBinding VerticalAlignment}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}" Margin="131,106,0,0"> <telerik:RadContextMenu.ContextMenu> <telerik:RadContextMenu Opened="RadContextMenu_Opened" ItemClick="RadContextMenu_ItemClick"> <telerik:RadMenuItem Loaded="RadMenuItem_Loaded"/> </telerik:RadContextMenu> </telerik:RadContextMenu.ContextMenu> </ContentControl> </Border> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> This is it. I hope this helps. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7572053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can a property return a default value (similar to some built-in .NET properties)? Is there a way to have a class that can return a default type without specifying the property? If I had a class that had a few properties and one property returned a string value and others returned additional types, could I do the following? Dim StudentGrade as new StudentGradeClass Call and get default property, Dim CurrentGrade as string=StudentGrade instead of this Dim CurrentGrade as string=StudentGrade.Current The reason I am asking this is when I have classes that have other classes as properties and would like to just get a default return value. A: An implicit conversion operator (Widening conversion operator in VB) will get you basically what you want, but this is really a hindrance to readability. I would advise you not to do it unless you have a really, really, really good reason. References: * *How to: Define a Conversion Operator (Visual Basic) *Is there a way to define an implicit conversion operator in VB.NET? A: The .NET framework has no support for what you refer to as a "default property." You could potentially fake it through the use of implicit operators, but I would suggest that it is probably a bad idea to do so.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Twitter PHP - URL not encoded in tweet I'm trying to post to Twitter using the Twitter PHP SDK twitter-async my tweets include a URL in them that doesn't seem to be getting encoded. How can I make the URLs show properly when tweeted? I call this function in the SDK function postTweet($tweet) { $this->twitterObj->post('/statuses/update.json', array('status' => $tweet)); } There's not much to it really. A: In the end it was simply an issue with Twitter not recognizing my local URL as an url, when I tested changing to my production site it worked fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is subclassing NSNotification the right route if I want to add typed properties? I am trying to subclass NSNotification. Apple's docs for NSNotificationstate the following: NSNotification is a class cluster with no instance variables. As such, you must subclass NSNotification and override the primitive methods name, object, and userInfo. You can choose any designated initializer you like, but be sure that your initializer does not call NSNotification’s implementation of init (via [super init]). NSNotification is not meant to be instantiated directly, and its init method raises an exception. But this isn't clear to me. Should I create an initializer like this? -(id)initWithObject:(id)object { return self; } A: It seems this does work. For example: #import "TestNotification.h" NSString *const TEST_NOTIFICATION_NAME = @"TestNotification"; @implementation TestNotification -(id)initWithObject:(id)object { object_ = object; return self; } -(NSString *)name { return TEST_NOTIFICATION_NAME; } -(id)object { return object_; } - (NSDictionary *)userInfo { return nil; } @end also beware a massive Gotcha related to NSNotifications. The type of NSNotifications greated using NSNotification notificationWithName:object: is NSConcreteNotification, not NSNotification. And to make it a little more awkward, if you are checking for class, NSConcreteNotification is private so you have nothing to compare to. A: Subclassing NSNotification is an atypical operation. I think I've only seen it done once or twice in the past few years. If you're looking to pass things along with the notification, that's what the userInfo property is for. If you don't like accessing things through the userInfo directly, you could use a category to simplify access: @interface NSNotification (EasyAccess) @property (nonatomic, readonly) NSString *foo; @property (nonatomic, readonly) NSNumber *bar; @end @implementation NSNotification (EasyAccess) - (NSString *)foo { return [[self userInfo] objectForKey:@"foo"]; } - (NSNumber *)bar { return [[self userInfo] objectForKey:@"bar"]; } @end You can also use this approach to simplify NSNotification creation. For example, your category could also include: + (id)myNotificationWithFoo:(NSString *)foo bar:(NSString *)bar object:(id)object { NSDictionary *d = [NSDictionary dictionaryWithObjectsForKeys:foo, @"foo", bar, @"bar", nil]; return [self notificationWithName:@"MyNotification" object:object userInfo:d]; } If, for some strange reason, you'd need the properties to be mutable, then you'd need to use associative references to accomplish that: #import <objc/runtime.h> static const char FooKey; static const char BarKey; ... - (NSString *)foo { return (NSString *)objc_getAssociatedObject(self, &FooKey); } - (void)setFoo:(NSString *)foo { objc_setAssociatedObject(self, &FooKey, foo, OBJC_ASSOCIATION_RETAIN); } - (NSNumber *)bar { return (NSNumber *)objc_getAssociatedObject(self, &BarKey); } - (void)setBar:(NSNumber *)bar { objc_setAssociatedObject(self, &BarKey, bar, OBJC_ASSOCIATION_RETAIN); } ... A: You don’t set it, exactly—you just override the implementation of the name method so it returns what you want. In other words: - (NSString *)name { return @"Something"; } Your initializer looks fine—I haven’t seen an example of an init that doesn’t call its superclass’s implementation before, but if that’s what the doc’s saying you should do, it’s probably worth a try. A: You can pass a userInfo argument when delivering a notification. Why not create a payload and send that. // New file: @interface NotificationPayload : NSObject @property (copy, nonatomic) NSString *thing; @end @implementation NotificationPayload @end // Somewhere posting: NotificationPayload *obj = [NotificationPayload new]; obj.thing = @"LOL"; [[NSNotificationCenter defaultCenter] postNotificationName:@"Hi" object:whatever userInfo:@{ @"payload": obj }]; // In some observer: - (void)somethingHappened:(NSNotification *)notification { NotificationPayload *obj = notification.userInfo[@"payload"]; NSLog(@"%@", obj.thing); } Done. As a side note: I've found over the years that making a conscious effort to avoid subclassing has made my code more clean, maintainable, changeable, testable and extensible. If you can solve the problem using protocols or categories then you wont lock yourself into the first shoddy design you come up with. With Swift 2.0 protocol extensions in the mix we're really laughing too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Load Returned mySQL Values Into Form I wonder whether someone may be able to help me please. I've put together a form and php code (below) that allows an administrator to search for member records from a mysql database using the email address as the search criteria. HTML Form <form name="memberpasswordresetform" id="memberpasswordresetform" method="post" action="search.php"> <div class="container"> <p align="justify">Member Details </p> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="26%" height="25"><strong>Email Address </strong></td> <td width="4%">&nbsp;</td> <td width="70%"><input name="email" type="email" id="email" size="50" /></td> </tr> <tr> <td height="25"><strong>Confirm Email Address </strong></td> <td>&nbsp;</td> <td><input name="conf_email" type="email" id="conf_email" size="50" /></td> </tr> <tr> <td height="25"><label> <input type="submit" name="Submit" value="search" /> </label></td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td height="25">&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td height="25"><strong>First Name </strong></td> <td>&nbsp;</td> <td><input name="fname" type="text" id="fname" size="30" /></td> </tr> <tr> <td height="25"><strong>Last Name </strong></td> <td>&nbsp;</td> <td><input name="lname" type="text" id="lname" size="30" /></td> </tr> <tr> <td height="25">&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td height="25"><strong>New Password</strong></td> <td>&nbsp;</td> <td><input name="newpass" type="password" id="newpass" size="30" /></td> </tr> <tr> <td height="25"><strong>Confirm New Password </strong></td> <td>&nbsp;</td> <td><input name="conf_newpass" type="password" id="conf_newpass" size="30" /></td> </tr> <tr> <td height="25"><input type="submit" name="save" value="save" /></td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </table> </div> </form> PHP Script <?php include("admin/link.php"); include("admin/opendb.php"); mysql_select_db ("userdetails"); $term = $_POST['email']; $sql = mysql_query("select forename, surname, email address from userdetails where emailaddress like '%$email%'"); while ($row = mysql_fetch_array($sql)){ echo '<br/> First Name: '.$row['forename']; echo '<br/> Last Name: '.$row['surname']; echo '<br/><br/>'; } ?> The search functionality works fine, but I can't work out how to populate the forename and surname fields on my form from the records retrieved from my database. I've been looking for, and found examples on how to do this, if I want to simply show the data as a table, but I can't find any that explain how to populate the fields in a form. I just wondered whether it would be at all possible that someone could provide some guidance please on how I can do this. Many thanks A: just set the value of your input element <tr> <td height="25"><strong>First Name </strong></td> <td>&nbsp;</td> <td><input name="fname" type="text" id="fname" size="30" value="<?= $row['surname'] ?>" /></td> </tr> A: The previous answer will work fine if short tags are enabled on the server. You should stick to the long syntax as below in case you change hosting providers at a later date. <input name="fname" type="text" id="fname" size="30" value="<?php echo $row['surname']; ?>" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7572062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Question about anchor point So I have been playing around with animations lately and I've come across the anchor point. I understand that the anchor point is (0.5, 0.5) by default, which is the middle of the view, and you can change it so that the anchor point is on one of the borders. My question is, how do I go on about this if I want my view to rotate around a specific point in the view's superview? Any help is greatly appreciated A: Checkout this question how to rotate CALayer at one point Also - although I guess you've probably already done this - have a read of Core Animation Programming Guide, Layer Geometry and Transforms. Your question differs in that you want to specify a rotation point that is in your view's superview. To do that, you want to convert that superview point to the subview. You can do that as follows: * *Take your superview bounds, e.g. (0, 0, 500, 500) *Take your subview frame, e.g. (50, 50, 100, 100) *Take your superview rotation point, e.g. (75, 75) *Convert that to a point relative to the subview as follows: CGFloat subviewX = 75.0f - subview.frame.x; CGFloat subviewX = 75.0f - subview.frame.y; *That gives the result expected (25.0f, 25.0f) To rotate a CALayer with a CABasicAnimation, have a look at the selected answer for this question: CALayer with rotation animation. A: I figured it out myself: I wanted the anchor point to be on the left screen border, so I did the following: CGFloat subviewX = ((1/view.frame.size.width)*view.frame.origin.x) * (-1); CGFloat subviewY = 0.5;
{ "language": "en", "url": "https://stackoverflow.com/questions/7572063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: asp.net get html controls in code behind If I alter the html on a page using JavaScript, how can I access those changes in my ASP.NET code behind? I found some dhtml "drag and drop" code online (http://www.dhtmlgoodies.com/scripts/drag-drop-nodes/drag-drop-nodes-demo2.html), but after moving list items from one control to another, I don't know how to "access" each control in the code behind so I can save the list items in each control. I tried using the HTML Agility pack, but it seems like I'm only able to access the unaltered html - meaning all the controls are empty. Any help/suggestions are appreciated. Or any suggestions as to a better way of accomplishing this are welcome (jQuery? Ajax Toolkit?). EDIT: Here's some code. I'm able to populate an ASP Label control (_saveContent), from the JavaScript function saveDragDropNodes, with the "ul" ID and the corresponding "li" controls that I've dragged and dropped. When clicking the save button however, my Label control no longer contains any Text... function saveDragDropNodes() { var saveString = ""; var uls = dragDropTopContainer.getElementsByTagName('UL'); for (var no = 1; no < uls.length; no++) { // LOoping through all <ul> var lis = uls[no].getElementsByTagName('LI'); for (var no2 = 0; no2 < lis.length; no2++) { if (saveString.length > 0) saveString = saveString + ";"; saveString = saveString + uls[no].id + '|' + lis[no2].id; } } document.getElementById("<%=_saveContent.ClientID %>").innerHTML = saveString.replace(/;/g, ';<br>'); } <div id="dhtmlgoodies_dragDropContainer"> <div id="dhtmlgoodies_listOfItems"> <div> <p> Available Items</p> <ul id="allItems" runat="server"> </ul> </div> </div> <div id="dhtmlgoodies_mainContainer"> <div> <p> Group 1</p> <ul id="_ul1"> </ul> </div> <div> <p> Group 2</p> <ul id="_ul2"> </ul> </div> </div> <asp:Label ID="_lSave" runat="server" ForeColor="Red" EnableViewState="false" /> </div> <div id="footer"> <span onmouseover="saveDragDropNodes()"> <asp:Button ID="_btnSave" runat="server" Text="Save Groups" OnClick="_btnSave_OnClick" /></span> </div> <ul id="dragContent"> </ul> <div id="dragDropIndicator"></div> <asp:Label ID="_saveContent" runat="server" /> Code Behind: Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load If Not Page.IsPostBack Then GetItems() End If End Sub Private Sub GetItems() Dim dt As DataTable = DbHelper.GetDataTableForSP("GetListOptions") Dim index As Integer = 1 For Each _row As DataRow In dt.Rows Dim _li As New HtmlGenericControl("li") _li.ID = _row("ClassId") _li.Attributes.Add("runat", "server") _li.InnerHtml = String.Format("{0}) {1} {2}", index, _row("ClassId"), _row("ClassDescription1")) allItems.Controls.Add(_li) index += 1 Next End Sub Private Sub SaveGroups() Dim str As String = _saveContent.Text /*No text here */ _lSave.Text = "Groups Saved!" GetItems() End Sub A: The only content posted back to the server are values from form fields. See: Form submission. You have two options: * *Make use of ajax to pass the HTML from the client to the server. *Use a hidden input field to store the HTML just before the page posts back. Here is an example of the latter: Markup <div id="content"></div> <asp:HiddenField ID="hiddenContentField" runat="server" /> <asp:Button ID="button1" runat="server" Text="Post back" OnClick="button1_Click" OnClientClick="storeContent();" /> Script function storeContent() { $('#<%= hiddenContentField.ClientID %>').val($('#content').html()); } Any changes made in the content element will then be stored in the hidden input element and sent up to the server on postback. Then in the code behind you can access the HTML passed up like so: protected void button1_Click(object sender, EventArgs e) { string html = hiddenContentField.Value; } Hope this helps. A: First of all, HTML code changes will not posted to Server by default. To achieve the drag-n-drop element, please follow the steps below * *Uniquely name(id) the Container panels and child elements in it. *Using jQuery/JavaScript track the child element movements from on container panel to another and store the id of element's old parent panel and new parent in json/dictionary object. *While clicking on save button post the tracked dictionary object to server. *On server-side, get the posted json object using Page.Request. *Using the id's stored in json object, Save the list items. Hope this will helps. A: Specify runat="server" on the controls you need to access from code-behind. Also, remember to use ClientID to reference server controls in JavaSript: var el = document.getElementById("<%=MyElement.ClientID%>"); A: First, add the jQuery lib to your page header. Add it from the Google CDN, as most of your users should have it cached. <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> Then, after the JS has modified the HTML, call sendToServer and it will post the html you select to the servlet you enter. function sendToServer(){ var myhtml = document.getElementById('theIdOfTheContainer').innerHTML; $.post("http://yoururlhere.com",myhtml,function(responseFromServer){ //some code to handle the response from the server on the client. }); } $('#buttonid').click(sendToServer); I am having you use jQuery for this, as it is a very powerful AJAX library. jQuery does three things extremely well, and one of them is AJAX. Inside the post method, the third parameter is an anonymous function. That is the function that gets called once the data has successfully been sent to the server. So, yeah. Try it out, let me know.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Two postgresql server with same configuration, different performance I got two identical servers, in both is installed postgresql server version 9.0.4 with the same configuration. If I launch a .sql file that performs about 5k inserts, on the first one it takes a couple of seconds, on the second one it takes 1 minute and 30 seconds. If I set synchronous_commit, speed dramatically reduces (as expected), and the performances of the two servers are comparable. But if I set synchronous_commit to on, on one server the insert script execution time increases of less than one second, on the other one it increases too much, as I said in the first period. Any idea about this difference in performances? Am I missing some configuration? Update: tried a simple disk test: time sh -c "dd if=/dev/zero of=ddfile bs=8k count=200000 && sync" fast server output: 1638400000 bytes (1.6 GB) copied, 1.73537 seconds, 944 MB/s real 0m32.009s user 0m0.018s sys 0m2.298s slow server output: 1638400000 bytes (1.6 GB) copied, 4.85727 s, 337 MB/s real 0m35.045s user 0m0.019s sys 0m2.221s Common features (both servers): SATA, RAID1, controller: Intel Corporation 82801JI (ICH10 Family) SATA AHCI Controller, distribution: linux centOS. mount -v output: /dev/md2 on / type ext3 (rw) proc on /proc type proc (rw) none on /dev/pts type devpts (rw,gid=5,mode=620) /dev/md1 on /boot type ext3 (rw) fast server: kernel 2.6.18-238.9.1.el5 #1 SMP Disk /dev/sda: 750.1 GB, 750156374016 bytes 255 heads, 63 sectors/track, 91201 cylinders, total 1465149168 sectors Units = sectors of 1 * 512 = 512 bytes Device Boot Start End Blocks Id System /dev/sda1 3906 4209029 2102562 fd Linux raid autodetect /dev/sda2 4209030 4739174 265072+ fd Linux raid autodetect /dev/sda3 4739175 1465144064 730202445 fd Linux raid autodetect slow server: kernel 2.6.32-71.29.1.el6.x86_64 #1 SMP Disk /dev/sda: 750.2 GB, 750156374016 bytes 64 heads, 32 sectors/track, 715404 cylinders, total 1465149168 sectors Units = sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disk identifier: 0x0006ffc4 Device Boot Start End Blocks Id System /dev/sda1 2048 4194303 2096128 fd Linux raid autodetect /dev/sda2 4194304 5242879 524288 fd Linux raid autodetect /dev/sda3 5242880 1465147391 729952256 fd Linux raid autodetect Could it be useful to address the performance issue? A: To me this sounds like in the "fast" server there is a write cache enbled for the harddisk(s), whereas in the slow server the harddisk(s) are really writing the data when PG writes it (by calling fsync) A: I suppose your slow server with newer kernel has working barriers. This is good, as otherwise you can loose data in case of a power failure. But it is of course slower than running with write cache enabled and without barriers, aka running with scissors. You can check if barriers are enabled using mount -v — search for barrier=1 in output. You can disable barriers for your filesystem (mount -o remount,barrier=0 /) to speed up, but then you risk data corruption. Try to do your 5k inserts in one transaction — Postgres won't have to write to disk on every row inserted. The theoretical limit for number of transactions per second wound be comparable to disk rotational speed (7200rpm disk ≈ 7200/60 tps = 120 tps) as a disk can only write to a sector once per rotation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I run curl as shell command line in PHP If I try to run this inside a script: <?php exec("curl http://ww.google.com") ?> I get: -bash-3.2$ php test.php sh: /curl: No such file or directory using shell_exec: PHP Warning: shell_exec(): Cannot execute using backquotes in Safe Mode... How can I run curl as shell command line? Those errors are happening on Linux, on my mac works. A: The issue is that PHP safe mode is on and it is better to use the full path to run cURL (thanks ghostJago and amosrivera). Running the script with the following command fixed the issue: php -dsafe_mode=Off test.php I do not want to change the php.ini but it could be a solution too. shell_exec tells the safe mode problem, but exec just tell you an wrong message, hopefully I tried both exec and shell_exec. A: Disable safe mode in your php.ini file. Also check if you do have curl installed. safe_mode = Off A: To convert from an bash command (like you can copy from chrome-dev-tools) to php take a look at this: https://incarnate.github.io/curl-to-php/ A: at the commandline, do this: which curl This will give you the absolute path to the curl program. Then double check that safe_mode = Off is in your php.ini. When you've done this, change your code to: <?php exec("path/you/got/from/which/curl http://www.google.com") ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7572078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Decrees size of Font : decrees size of Font in Java which I am printing it in PDF file I am printing data on PDF using Java code when data populate data gose to out of field in PDF here the code I am using PSD address for printing data form DB String FULL_NAME= rs.getString("FULL_NAME"); af.setField("topmostSubform[0].Page1[0].USAO_OFFENDER[0]",FULL_NAME);
{ "language": "en", "url": "https://stackoverflow.com/questions/7572085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Alternatively presentation of the archive I'm searching for an alternativ view of the archiv output page. So if you click on a archiv link you get a view e.g. of the Month. And exactly this Page where i get the filtered output i want to apply some changes. So i mean not: wp_get_archives() Best regards Illu A: If you just want to make a few small changes, then just filter it with the wordpress function is_archive(), e.g. <?php if (is_archive()) { ?> Say hello to the archeologist users <?php } ?> ...otherwise, if you want to have a completly different template for that page, then just create a file called archive.php in your theme directory. Hope I understood your question right :) Some more resources for the is_archive() function is to be found here - well explained examples. And some more information about template files are here
{ "language": "en", "url": "https://stackoverflow.com/questions/7572086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error while trying to connect to SQLite3 database from CakePHP Recently I migrate an application from one server to another and now when I try to access to the app I get this error: "Fatal error: Call to a member function query() on a non-object in /var/www/reynierpm/magno-reynierpm/models/datasources/dbo/dbo_sqlite3.php on line 144" can any tell me why or where it fails? A: I'm not sure where you got your dbo_sqlite3.php from. As far as I can tell the "official" one never called a query() method on line 144 and has proper exception handling to prevent this kind of error surfacing when a database connection cannot be established. * *The new PDO() call always returns a PDO object. *Unless the connection fails, then it throws a PDOException. *The latest datasource catches that exception. *PDO objects have a query() method (which solves your problem). I would advise updating that file to the latest version.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Transparent image not appearing in menu My page is here. My drop down navigation css is here. I'm trying to add a transparent png image, image here, to the drop down portion of the menu. However, it's not appearing. I thought adding a "suboptions" class to the dropdown ul would do the trick, along with setting CSS for that dropdown, but it doesn't seem to be working. HTML in question: <ul class="suboptions"> <li><a href="/faqs" title="CET Color Frequently Asked Questions">F.A.Q.'s</a></li> <li><a href="/install" title="CET Color Installation &amp; Site Prep">Installation</a></li> </ul> CSS in question: #menu li ul.suboptions { background-image: url(/images/bkg_nav.png) !important; background-color: transparent !important; } Any suggestions? Thanks! A: you have float for the <li> You have to clear the float, after <li> or apply bg image for li. EX:1 add this to your css #menu li ul.suboptions:after { content: "."; display: block; clear: both; visibility: hidden; line-height: 0; height: 0; } #menu li ul.suboptions { display: inline-block; } html[xmlns] #menu li ul.suboptions { display: block; } * html #menu li ul.suboptions { height: 1%; } EX2: add this to #menu li ul.suboptions li class #menu li ul.suboptions li { background-image: url(/images/bkg_nav.png) !important; background-color: transparent !important; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7572093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java. Creating a date according to user timezone in web-application I have a Java web-application. In some places there is showing of dates. I want to display the date according to user timezone. How do I create a date for the show if I know the timezone the user? I use the class Date. Any help would be greatly appreciated. A: There is no standard way to do this. On client side, you may capture time using Java script and send that information to the server. On server side, you can covert the time to Coordinated Universal Time. A: Use GregorianCalendar rather than Date when you have any requirements besides basic display. You can create one for the current time by time-zone using new GregorianCalendar(TimeZone).
{ "language": "en", "url": "https://stackoverflow.com/questions/7572097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: C#: Get exact substring from HTML code using IndexOf and LastIndexOf I have a HTML page retrieved using the GetResponseStream() in C#. I need an exact value (int) that comes from that page, which is different every time I run the program. Nevertheless, the structure of the HTML code is the same, in particular: (...) <td colspan="2" class="txtnormal"><div align="right">&nbsp;TAX:</div></td> <td class="txtnormal"><div align="right"><strong>0.00</strong></div></td> <td colspan="2">&nbsp;</td> (...) and (...) <td colspan="2"><div align="right" class="txtnormal">Total:</div></td> <td class="txtnormal"><div align="right"><strong>10.00</strong></div></td> <td colspan="2">&nbsp;</td> (...) Notice that the code is repeated in the same page (i.e: <td class="txtnormal"><div align="right"><strong>VALUE</strong></div></td>), but the title of the values (TAX and Total) are the only different thing (the actual value could be the same). I would like to store in a variable the Total value, this is: 10.0 in this case. I tried this: int first = responseFromServer.IndexOf("<td class= \"txtnormal\"><div align=\"right\"><strong>") + "<td class=\"txtnormal\"><div align=\"right\"><strong>".Length; int last = responseFromServer.LastIndexOf("</strong></div></td>"); string value = responseFromServer.Substring(first, last - first); But i get bad results, the value stored in value of ALL the HTML page until the value (is for the difference I´m doing). Do you know how could I get the exact value, this is: the sub-string between the text I pasted? Thank you very much. A: To scrape from a page, you have a couple of options. The "best" is to use the DOM to find the node(s) in question and pull it's value. If you can't use the DOM for some reason, you can move to regex and pull the value that way. Your method is "okay" in many instances, as long as you can be sure the site owner will never set up another instance of "</strong></div></td>" anywhere downstream. This is a risky assumption. What value are you getting for the int string? that will tell you whether or not your particular pattern is working correctly. And I would consider the HTML DOM still, as it is a more accurate way to traverse the nodes. A: I think Regex is your friend here: using System; using System.Text.RegularExpressions; namespace SimpleApp { class Program { static void Main(string[] args) { Regex theRegex = new Regex(@">Total:<.+?<strong>(.+?)</strong>"); string str = @"<td colspan=""2""><div align=""right"" class=""txtnormal"">Total:</div></td>" + @"<td class=""txtnormal""><div align=""right""><strong>10.00</strong></div></td>" + @"<td colspan=""2"">&nbsp;</td>"; if (theRegex.Match(str).Success) { Console.WriteLine("Found Total of " + theRegex.Match(str).Result("$1")); } else { Console.WriteLine("Not found"); } Console.ReadLine(); } } } Obviously your HTML page might have other things that could trip this simple regular expression up but you get the idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does the Facebook OG Object Debugger Somehow Skip PHP? I have a dynamic PHP page that basically displays a video. When a Facebook user clicks on the video, a timeline event is posted to their Facebook profile, but my OG meta tags don't seem to want to cooperate with the PHP variables the video information is stored in. If I type the correct strings directly into the meta tags, everything works great, but the page by design picks a video from my Database. These are the current tags with PHP Variables included: <head prefix='og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# visiovert: http://ogp.me/ns/fb/visiovert#'> <meta property='fb:app_id' content='261459743887413'> <meta property='og:type' content='visiovert:advertisement'> <meta property='og:url' content='http://visiovert.net/ad.php'> <meta property='og:site_name' content='VisioVert'> <?php echo("<meta property=\"og:title\" content=\"".$Video->title."\" />\n"); echo("<meta property=\"og:description\" content=\"".$Video->description."\" />\n"); echo("<meta property=\"og:image\" content=\"".$Video->location.".jpg\" />\n"); echo("<meta property=\"og:video\" content=\"".$Video->location.".mp4\" />\n"); ?> <meta property='og:video:height' content='432' > <meta property='og:video:width' content='768'> </head> If you view the page source, this is what you can see in the header: <head prefix='og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# visiovert: http://ogp.me/ns/fb/visiovert#'> <meta property='fb:app_id' content='261459743887413'> <meta property='og:type' content='visiovert:advertisement'> <meta property='og:url' content='http://visiovert.net/ad.php'> <meta property='og:site_name' content='VisioVert'> <meta property="og:title" content="Echo" /> <meta property="og:description" content="An example video ad for VisioVert." /> <meta property="og:image" content="http://visiovert.net/Videos/echo.jpg" /> <meta property="og:video" content="http://visiovert.net/Videos/echo.mp4" /> <meta property='og:video:height' content='432' > <meta property='og:video:width' content='768'> </head> That matches exactly what I would like it to, but when testing using the Facebook Object Debugger, it is not getting anything out of PHP variables. I could be missing something right in front of me...but I've looked around and haven't found an answer. A: Veliisx try adding fb namespace to your html tag. <html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml" xmlns:og="http://ogp.me/ns#" xmlns:shawnsspace="http://www.shawnsspace.com/ns#"> p.s. in your source only half of the tags are closed. Not sure if this would be ignored but will cause errors in some browsers. A: I often have issues with escaping too, have you tried something like below to avoid the heavy escaping? The below is basicly how dynamically add my meta, i know its a bit more code to echo each but it avoids a lot of confusion with escaping. <head prefix='og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# visiovert: http://ogp.me/ns/fb/visiovert#'> <meta property='fb:app_id' content='261459743887413'> <meta property='og:type' content='visiovert:advertisement'> <meta property='og:url' content='http://visiovert.net/ad.php'> <meta property='og:site_name' content='VisioVert'> <meta property="og:title" content="<?php echo $Video->title; ?>" /> <meta property="og:description" content="<?php echo $Video->description; ?>" /> <meta property="og:image" content="<?php echo $Video->location; ?>.jpg" /> <meta property="og:video" content="<?php echo $Video->location; ?>.mp4" /> <meta property='og:video:height' content='432' > <meta property='og:video:width' content='768'> </head>
{ "language": "en", "url": "https://stackoverflow.com/questions/7572102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I *think* I have a memory leak. What now? I created a C++ DLL function that uses several arrays to process what is eventually image data. I'm attempting to pass these arrays by reference, do the computation, and pass the output back by reference in a pre-allocated array. Within the function I use the Intel Performance Primitives including ippsMalloc and ippsFree: Process.dll int __stdcall ProcessImage(const float *Ref, const float *Source, float *Dest, const float *x, const float *xi, const int row, const int col, const int DFTlen, const int IMGlen) { int k, l; IppStatus status; IppsDFTSpec_R_32f *spec; Ipp32f *y = ippsMalloc_32f(row), *yi = ippsMalloc_32f(DFTlen), *X = ippsMalloc_32f(DFTlen), *R = ippsMalloc_32f(DFTlen); for (int i = 0; i < col; i++) { for (int j = 0; j < row; j++) y[j] = Source[j + (row * i)]; status = ippsSub_32f_I(Ref, y, row); // Some interpolation calculations calculations here status = ippsDFTInitAlloc_R_32f(&spec, DFTlen, IPP_FFT_DIV_INV_BY_N, ippAlgHintNone); status = ippsDFTFwd_RToCCS_32f(yi, X, spec, NULL); status = ippsMagnitude_32fc( (Ipp32fc*)X, R, DFTlen); for (int m = 0; m < IMGlen; m++) Dest[m + (IMGlen * i)] = 10 * log10(R[m]); } _CrtDumpMemoryLeaks(); ippsDFTFree_R_32f(spec); ippsFree(y); ippsFree(yi); ippsFree(X); ippsFree(R); return(status); } The function call looks like this: for (int i = 0; i < Frames; i++) ProcessFrame(&ref[i * FrameSize], &source[i * FrameSize], &dest[i * FrameSize], mX, mXi, NumPixels, Alines, DFTLength, IMGLength); The function does not fail and produces the desired output for up to 6 images, more than that and it dies with: First-chance exception at 0x022930e0 in DLL_test.exe: 0xC0000005: Access violation reading location 0x1cdda000. I've attempted to debug the program, unfortunately VS reports that the call stack location is in an IPP DLL with "No Source Available". It consistently fails when calling ippMagnitude32fc( (Ipp32fc*)X, R, DFTlen) Which leads me to my questions: Is this a memory leak? If so, can anybody see where the leak is located? If not, can somebody suggest how to go about debugging this problem? A: To answer your first question, no that's not a memory leak, that's a memory corruption. A memory leak is when you don't free the memory used, and so , the memory usage is growing up. That doesn't make the program to not work, but only end up using too much memory, which results in the computer being really slow (swaping) and ultimately any program crashing with a 'Not enough memory error'. What you have is basic pointer error, as it happend all the time in C++. Explain how to debug is hard, I suggest you add a breakpoint just before in crash, and try to see what's wrong.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iOS Facebook connect not working when user has FB's app installed? Has anyone else had this problem? I'm getting this error when trying to authorize a user via FB, I think I've isolated it only when a user has installed the Facebook app: fb_our_appID://authorize#error=unknown%5Ferror If you delete the FB app from the user's phone, our app will then try to authenticate via Safari, and everything works fine. Thanks so much. A: I got the same issue. I Removed the facebook app from the phone and it started to work again. I then installed the facebook app and my app kept working. So looks like it only works fine if the app is installed before the facebook app and leads me to think it is a facebook app problem. A: I didn't tried with Safari, but I had the same error message from facebook app. My problem was from my application bundle, which must be exactly the same as in your facebook app configuration (first field of facebook iOS app configuration). A: Yup, we were getting this as well. It occurs when your bundle identifier does not match the one configured as part of your facebook application. Copy your bundle-id from your plist, and update the iOS Bundle ID value on facebook https://developers.facebook.com/apps/_YOUR_APP_ID_/summary PS: Check out facebook.stackoverflow.com for good facebook help. A: Make sure your application bundle id is set correctly on your app's Facebook page. check out this answer Authentication Fails with Facebook App Installed (iOS) for reference.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572107", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Grails filter multiple actions Within one filter, how can I match more than one action of the same controller? def filters = { organisationDelete(controller: "organisation", action: "confirmDelete, delete") { //... } } In this mapping I have "confirmDelete" as a GET and "delete" as POST A: in the old ACEGI plugin I could write the actions separated by comma. Though, now with Spring Security Core I have to use a pipe. So, the following solves the problem action: "confirmDelete|delete"
{ "language": "en", "url": "https://stackoverflow.com/questions/7572108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: regular expression : find all digit in a string I would like to get all digits of a string like this : "0" => Groups = "0" "1 2-3" => Groups = "1", "2", "3" "45i6" => Groups = "4", "5", "6" I'm using this code : var pattern = @"(\d)"; var m = System.Text.RegularExpressions.Regex.Match(value, pattern); if(m.Success) { foreach (var gp in m.Groups) { Console.WriteLine(gp); } } Can you help me to get the good pattern please ? Many thanks OK, the good code is : Thanks Daniel I'm using this code : var pattern = @"(\d)"; var ms = System.Text.RegularExpressions.Regex.Matches(value, pattern); if(ms.Count > 0) { foreach (var m in ms) { Console.WriteLine(m); } } A: You want to do Matches. You will only have one group with that pattern. A: If you aren't stuck on regular expressions, a more straightforward method would be: var digits = someString.Where(c => char.IsDigit(c)).ToArray();
{ "language": "en", "url": "https://stackoverflow.com/questions/7572109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MVC3 - Binding DropdownList to int - Value always required I would like to bind a dropdownlist to an integer as follows: @Html.DropDownListFor(m => m.ProductID, Model.AllProducts, "") Obviously in the above case I am allowing for a default (blank) value so that no value is chosen by default. My viewmodel is very simple, and doesn't have any annotations for these properties public SelectList AllProducts {get;set;} public int ProductID {get;set;} It appears that because I am binding to an int data validation is forced resulting in data-val* attributes generated in my html and causing my client side validation to fail if i do not choose an option. The alternative seems to be binding to a string rather than an int and then parsing the string on the serverside - however, this seems kind of hackish and i'm wondering if there is an alternative that would allow me to bind to an int, with a default (empty) value but not make this field mandatory Thank you JP A: You should use a nullable integer in in your view model to bind to if the drop down ilst could have a default value: public SelectList AllProducts { get; set; } public int? ProductID { get; set; } And if you want to enforce validation that the user actually selects a value decorate with the Required attribute: public SelectList AllProducts { get; set; } [Required] public int? ProductID { get; set; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7572113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: jQuery simulating a click after default event was prevented I'm having some smashing time with jQuery again, this time it doesn't quite work on calling .click(). The idea is to have a singleton class that looks for any elements tagged with ui-hint-confirm and show a confirm dialog. If user clicks OK the original element is clicked, else dialog simply closed. But since code can say more than thousand words: ConfirmDialogManager = function () { var _dialogShown = false; var ensureDialog = function (target, text) { var targetEl = $(target); if (!text) { text = targetEl.attr('title'); text = text == null || text == '' ? 'Are you sure?' : text += '?'; } var el = $('div#dlgConfirm'); if (el.length == 0) el = $('<div id="dlgConfirm"></div>'); el.dialog({ autoOpen: false, modal: true, width: 300, height: 150, minWidth: 200, minHeight: 130, title: 'Please confirm', maxHeight: 500, position: 'center', open: function () { $(this).css({ 'max-height': 500, 'overflow-y': 'auto' }); }, buttons: { 'OK': function (ev) { onConfirm.call(target, ev); }, 'Cancel': function (ev) { onCancel.call(target, ev); } } }); el.html(text); $('div#dlgConfirm').dialog('open'); }; var closeDialog = function () { $('div#dlgConfirm').dialog('close'); }; var onConfirm = function (ev) { closeDialog(); _dialogShown = true; $(this).click(); _dialogShown = false; }; var onCancel = function (ev) { _dialogShown = false; closeDialog(); }; var onClick = function (ev) { if (_dialogShown) return true; ensureDialog(this, ev.data.text); return false; }; return { init: function () { $('.ui-hint-confirm').click(onClick); }, setConfirm: function (target, text) { $(target).click(text, onClick); } }; } (); $(document).ready(ConfirmDialogManager.init); Next to looking for ui-hint-confirm elements on load it can also be manually invoked with setConfirm function. The issue with above code is that nothing happens inside $(this).click() I have verified that it reaches that line through debugger (Chrome) and through alerting. I also tried $(this).unbind('click', onClick) and $(this).unbind('click') with no difference. There are no errors being logged to console. Any ideas? Thanks. UPDATE: As requested, adding a html element samples this would work on: Has to work on a regular link: <a href="http://stackoverflow.com" class="ui-hint-confirm">Stack Overflow</a> Has to work on a js only link: <a href="#" class="ui-hint-confirm">JS Only</a> Has to work on a submit button: <input type="submit" value="Submit button" class="ui-hint-confirm" /> Has to work on a say link with some script already attached: <a href="http://stackoverflow.com" id="theLink" class="ui-hint-confirm">Stack Overflow</a> $('#theLink').click(function () { alert('Now going to Stack Overflow'); } ); In this last example the dialog should be shown before the alert message. I has a similar thing working without an issue in ExtJS (now calles Sencha) I just can't get it to work in jQuery. Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7572117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to detect an empty div using jQuery? I can't use: $('div:empty') because the div might have empty spaces in it. I want to remove it if it has nothing or nothing but empty spaces. A: Based on @Xeon06's answer, you can extend jQuery's selectors to find all elements with no content: $.expr[':'].nocontent = function(obj, index, meta, stack){ // obj - is a current DOM element // index - the current loop index in stack // meta - meta data about your selector // stack - stack of all elements to loop // Return true to include current element // Return false to explude current element return !($.trim($(obj).text()).length) && !($(obj).children().length) }; usage for you would then be: $('div:nocontent').remove(); Live example: http://jsfiddle.net/JNZtt/ A: You could use this condition: if (!$.trim($("div").text()).length && !$("div").children().length) The additional children length check is to make sure that you don't consider a div with no text but other elements (for example, images) as empty. A: This will return all div elements with no text apart from blank spaces (or other characters removed by .trim such as new line characters): var emptyDivs = $("div").filter(function() { return $.trim($(this).text()) === ""; }); Update - based on comments If any of the div elements in question have child elements which do not contain text (for example, img elements) then the above method will include them in the set of "empty" elements. To exclude them, you can use the following: var emptyDivs = $("div").filter(function() { return $.trim($(this).text()) === "" && $(this).children().length === 0; }); A: if ($.trim($('div').html()) == '') { $("div").remove(); } A: You can do something like this: $('div:empty').each(function(){ if($.trim($(this).html()).length == 0){ //do what you want here... } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7572123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to filter a table by column using native jQuery I would like to make use the core jQuery libraries to do as per title. Is it possible to do this with the native jQuery UI library? I prefer not to use plugins as these are not hosted on any CDN (as far as I' am aware). How can i filter the table by matching the typed input text against the 2nd table column? <input type="text" id="filter" /> <table> <tr><td>1</td><td>UK</td></tr> <tr><td>2</td><td>USA</td></tr> <tr><td>3</td><td>France</td></tr> </table> A: $('tr td:nth-child(2)') will give you all the 2nd TDs in that table. It is 1-based and will include in its count any non-TD children of the TR. $('tr td:eq(1)') will also give you all the 2nd TDs in that table. It is 0-based and will only include in its count the TD children of the TR. Once you wish to do something with the row containing a TD, you can use the TD's parent. A: Briefly, you'll put an id on your table element. Then, when you leave the input element (or, in the onclick() handler of a button) you'll do the following: * *Grab the table element. *Find each child in turn, which will be a row, preserving a reference to the element *Find the second child of the row and test it against the value of the input to see if it matches (exact match, contains, or whatever kind of test you want to apply). *If it matches, set a style indicating it matched onto the row. If not, set a style indicating "not matched" onto the row. You'll also need a style sheet that makes matched items visible and not-matched items invisible (or uses dark and light text, or whatever visual indicator you want to use for matched & unmatched). You can make this somewhat more robust if, instead of relying on the second cell on each row to hold the country name you use a class indicator on the cells that hold the country name. Then, instead of "Find the second child" you would "Find the child of class country. Doing this means that your application won't break when you add, remove, or rearrange columns.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: extract array from multidimensional array i have an array which is like this Array ( [0] => Array ( [name] => Amanda Coleman [id] => 98764676778 ) [1] => Array ( [name] => Hashimi Sultana [id] => 876304848 ) [2] => Array ( [name] => Maren Shawesh [id] => 988363747 ) [3] => Array ( [name] => Ajo Khan [id] => 039494857587 ) [4] => Array ( [name] => Negar Jan [id] => 948437484748 ) [5] => Array ( [name] => Mehran Khan [id] => 3948474947 ) [6] => Array ( [name] => Sal Man [id] => 039383734647 ) this is upto 566 mean this is my facebook friends name and ids what i am trying to do is i want to make autocomlete of facebook friends which work fine for me its showing what i want to do but i need the ids also against name here is my code if(isset($_REQUEST['queryString'])) { lets $var = fa $var = ucfirst ($_REQUEST['queryString']); //making first character uppercase for matching with fb name $friends_inner=$_SESSION['friends']; echo "<pre>"; print_r($friends_inner); echo "</pre>"; the output is above array for($i=0; $i<sizeof($friends_inner); $i++) { $selected_friend=$friends_inner[$i]; $selected_friend_id=$selected_friend['id']; //array of ids $selected_friend_name=$selected_friend['name']; // array of names $name[$i]=$selected_friend_name; } $result=preg_grep('/^'.$var.'.*/', $name);//returns array matching with requested alphabet from textbox which work fine dispalaying names echo "<pre>"; print_r($result); echo "</pre>"; here is the output Array ( [17] => Fazal Muhammad [18] => Fawad Ahmad [39] => Fayaz Zafar [42] => Farhan Bogra [66] => Farzana KArim Elora [81] => Fahim Khan [92] => Fahad Shams [119] => Fazal Yazdan [166] => Fakhar Alam [173] => Faheem Ur Rahman [183] => Fawaid Khan [187] => Faizan Sabir [258] => Fayaz Ali [269] => Faizan Khattak [308] => Faridullah Khan [411] => Fawad Qamar [446] => Fahad Khan [458] => Fahad Khan [507] => Faisl Qureshi [529] => Faisal Khan [538] => Faiza Baloch [555] => Fawad Khan ) as it its index is not sequentially so i am diong so to make it start from zero $final_result=array(); $maxindex = max(array_keys($result)); for($i=0;$i<=$maxindex;$i++){ //returns array that start with zero if(isset($result[$i])){ array_push($final_result,$result[$i]); } } echo "<pre>"; print_r($final_result); echo "</pre>"; the result is Array ( [0] => Fazal Muhammad [1] => Fawad Ahmad [2] => Fayaz Zafar [3] => Farhan Bogra [4] => Farzana KArim Elora [5] => Fahim Khan [6] => Fahad Shams [7] => Fazal Yazdan [8] => Fakhar Alam [9] => Faheem Ur Rahman [10] => Fawaid Khan [11] => Faizan Sabir [12] => Fayaz Ali [13] => Faizan Khattak [14] => Faridullah Khan [15] => Fawad Qamar [16] => Fahad Khan [17] => Fahad Khan [18] => Faisl Qureshi [19] => Faisal Khan [20] => Faiza Baloch [21] => Fawad Khan ) $ids_of_result=array(); now here is the big problem i want to extract all user ids from $friends_inner array which name equal to my $final_result array.i am doing so but the problem is that it goes upto last index i-e 22 and than through error that index 22 and ahead is not valid offset.how can i extract the ids from this $friends_inner which is my main array for($j=0; $j<sizeof($friends_inner); $j++){ $selected_friend=$friends_inner[$j]; if($final_result[$j] == $selected_friend['name']){ echo $selected_friend['name']; echo $selected_friend['id']; array_push($ids_of_result,$selected_friend['id']); //returns array of ids against result } } echo "<pre>"; print_r($ids_of_result); echo "</pre>"; it result in Array ( ) $counter=0; foreach($final_result as $key=>$value){ echo '<li onClick="fill(\''.$ids_of_result[$counter].'\');">'.$value.'</li>'; $counter++; } } please help me my code work fine in sense of autocomplete but i want the ids too.Graph api does not provide the id from name.if so i would not write much code.any help me thanx in advance ?> A: function sort_arrays($final_result,$friends_inner) { $ids_of_result = array(); foreach($final_result as $fnl_rslt){ foreach($friends_inner as $frnd_in){ if($fnl_rslt == $frnd_in['name']){ //echo 'Name : '.$frnd_in['name'].'<br>'; //echo 'Id : '.$frnd_in['id'].'<br>'; array_push($ids_of_result,$frnd_in['id']); } } } return $ids_of_result; } $ids_of_result = sort_arrays($final_result,$friends_inner);
{ "language": "en", "url": "https://stackoverflow.com/questions/7572130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Grails basics:dates, strings, and object properties I'm just starting out with Grails, transitioning from Javascript In a controller, I'm trying to do this below, but I get an error def list = { def projects = Project.list() projects.each { it.dateCreated = it.dateCreated.format('mm/dd') println it.dateCreated } return [projectInstanceList: projects, projectInstanceTotal: projects.size()] } In my view I then display the dateCreated for a project, I just want to format the date so it's cleaner/more concise. This is my error: 'java.lang.String' to class 'java.util.Date' I also tried assigning this to it.dateCreated new Date(2011, 09, 31, 10, 57, 00) But that gave a similar error also. A: First, you should never change a domain instance property like that just for "display" purposes. The reason for that is the domain instance is actually going to be persisted with your changes when the hibernate session flushes. Second, let the view display the property in the correct format. That's the responsibility of the view, not the domain instance, or the controller. A: Date.format(...) returns a String (see the documentation). You can't assign a java.lang.String to java.util.Date Either println it.dateCreated.format('mm/dd') or use Grails' formatDate tag to render this in your view. A: it.dateCreated is a java.util.Date. When you do: it.dateCreated.format('mm/dd') you are formatting the date but returning a java.lang.String. Then you try to assign that String to your it.dateCreated, but it can't take it, because it is a date. Try just: println it.dateCreated.format('mm/dd')
{ "language": "en", "url": "https://stackoverflow.com/questions/7572142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multiple folders to reports in TestNG Eclipse plugin I'm running Test Cases with TestNG Eclipse plugin. How can I specify a distinct folder as output to the HTML reports by configurating testng.xml? I've seen Cedric's answer to this very similar question (http://stackoverflow.com/questions/5401746/generating-testng-reports/), but I couldn't obtain the same on TestNG Eclipse plugin. I've tried , and another bunch of similar things I've seen in the doc and nothing worked. Extending the question a bit, we want to be able to run tests repeatedly and pick at any time the last n (say 20) reports, is it possible? It happens sometimes we use TestNG to do a lot of exploratory test. As some fails are rare and hard to repeat (and in the first approach they may not be predicted as such), sometimes the "explorer" just re-run the test and lose that inconstant fail. Thanks in advance to any answer to the primary or a bit extended question, Regards, Henrique A: try by passing argument -doutputdir in arguments tab
{ "language": "en", "url": "https://stackoverflow.com/questions/7572144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ClearCase: Are views created in Unix not visible from Windows and vice versa? We have a ClearCase UCM project implementation that we access from Windows and Solaris stations. I have created several views on the same stream of the project from the CC project explorer in both Windows and Solaris. But when I go into the properties of the stream and look for views from CC project explorer in Windows, I don't see the views I created from Solaris and vice versa. But from CC project explorer in Windows, I can see views created from other Windows stations. Whats happening here? A: What is happening is the notion of regions: you would usually define one region per Os, precisely to not see (and list with a cleartool lsview) all the views. * *The windows ones will have a global path with a windows-like schema: \\server\share\path\to\view_storage. *The Unix ones will have a global path with a Unix mount: /mount/server/path/to/view_storage Both paths wouldn't be usable by the opposite Os, so there is no point seeing all the views: you need only the ones for your Os. See "registry regions" and cleartool lsreg for more on those regions. They apply also for Vobs (not just views):
{ "language": "en", "url": "https://stackoverflow.com/questions/7572145", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Process Class Not Found in System.Diagnostics? (System.dll???) I am using .NET Framework 3.5, I have referenced all the assemblies, I have double checked everything, but still this irritating error CS0234: The type or namespace name 'Process' does not exist in the namespace 'System.Diagnostics' (are you missing an assembly reference?) (CS0234) (Proj1) According to MSDN and various other sources, the Process class is definitely located in System.dll in the System.Diagnostics namespace. Then What In The World Is The Problem? A: Ensure you are referencing the correct System.Dll. The version should be roughly v2.0.50727 A: I was also facing the same problem. I was using CodeDom to execute code that required Process Class. So the solution for me was to refrence System.dll in options. Here is the solution, if any one needs it. CSharpCodeProvider cs = new CSharpCodeProvider(); cs.CompilerOptions = "/optimize /reference:System.dll";
{ "language": "en", "url": "https://stackoverflow.com/questions/7572150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Silverlight treeview: save expanded/collapsed state I'm using a hierarchical tree view in Silverlight 4. This tree can be cleared and rebuilded quite often, depending on the user's actions. When this happends, the tree is collapsed by default, which can be annoying from a user perspective. So, I want to somehow save which nodes are expanded so I can restore the visual state of my tree after it is clear and reloaded. My treeview is implemented like this: xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls" xmlns:controls2="clr-namespace:System.Windows;assembly=System.Windows.Controls" <controls:TreeView x:Name="Tree" ItemsSource="{Binding Source={StaticResource ViewModel}, Path=TreeStructure, Mode=OneWay}" ItemTemplate="{StaticResource hierarchicalTemplate}" /> <controls2:HierarchicalDataTemplate x:Key="hierarchicalTemplate" ItemsSource="{Binding Children}"> <TextBlock Text="{Binding Value.DisplayName}"> </controls2:HierarchicalDataTemplate> ItemsSource of my treeview is bound on an ObservableCollection TreeStructure; Node is a wrapper class that looks like that: public class Node { public object Value { get; private set; } public ObservableCollection<Node> Children { get; private set; } public Node(object value) { Value = value; Children = new ObservableCollection<Node>(); } } Pretty standard stuff. I saw some solutions for WPF, but I can find anything for the Silverlight tree view... Any suggestions? Thanks! A: Given the way you are implementing your data as a tree, why not bind the 'TreeViewItem.IsExpanded` dependency property to a bool property on your own Node? It will need to be an INotifyPropertyChanged property at a minimum so Node will need to implement INotifyPropertyChanged. In Silverlight 5 you can just set a style like this to bind to the IsExpanded property: <Style TargetType="sdk:TreeViewItem" x:Key="itemStyle"> <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" /> </Style> And use with ItemContainerStyle="{Binding Source={StaticResource itemStyle}}" In Silverlight 4 there are a number of workarounds. A: Here's what I did to bind on the TreeViewItem.IsExpanded property. First, I added an IsExpanded property in my Node class. public class Node : INotifyPropertyChanged { public object Value { get; private set; } public ObservableCollection<Node> Children { get; private set; } private bool isExpanded; public bool IsExpanded { get { return this.isExpanded; } set { if (this.isExpanded != value) { this.isExpanded = value; NotifyPropertyChanged("IsExpanded"); } } } public Node(object value) { Value = value; Children = new ObservableCollection<Node>(); } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } After that, I subclassed the TreeView and TreeViewItem controls (I lose the custom theme on my treeview, but whatever...) public class BindableTreeView : TreeView { protected override DependencyObject GetContainerForItemOverride() { var itm = new BindableTreeViewItem(); itm.SetBinding(TreeViewItem.IsExpandedProperty, new Binding("IsExpanded") { Mode = BindingMode.TwoWay }); return itm; } } public class BindableTreeViewItem : TreeViewItem { protected override DependencyObject GetContainerForItemOverride() { var itm = new BindableTreeViewItem(); itm.SetBinding(TreeViewItem.IsExpandedProperty, new Binding("IsExpanded") { Mode = BindingMode.TwoWay }); return itm; } } In my XAML, I just have to use BindableTreeView instead of TreeView, and it works. A: The trick is to use SetterValueBindingHelper from here. Then your XAML will look like the following. Make sure you carefully copy what I have below. <sdk:TreeView.ItemContainerStyle> <Style TargetType="sdk:TreeViewItem"> <Setter Property="local:SetterValueBindingHelper.PropertyBinding"> <Setter.Value> <local:SetterValueBindingHelper> <local:SetterValueBindingHelper Property="IsSelected" Binding="{Binding Mode=TwoWay, Path=IsSelected}"/> <local:SetterValueBindingHelper Property="IsExpanded" Binding="{Binding Mode=TwoWay, Path=IsExpanded}"/> </local:SetterValueBindingHelper> </Setter.Value> </Setter> </Style> </sdk:TreeView.ItemContainerStyle> The syntax isn't exactly like what you would use in WPF, but it works and it works well!
{ "language": "en", "url": "https://stackoverflow.com/questions/7572151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: XML search or DB search / javascript (client side) or php (server side) calculation Let's say your site has 200,000 unique users a day. So, your server is heavily loaded/pounded; and you do NOT have resources to buy a bigger/better server. So, you are stuck with what you have. Now, whenever a user comes to your site, you need to do some calculation (calculate distance between user city as detected via GeoIP and some whitelist of cities, figure out the nearest city within 140 mile radius). Would you do this calculation via PHP or via JavaScript? First, would you precalculate all nearby cities within 140 mile radius of whitelisted cities? For eg: Whitelist city 1 can have 20 nearby cities. Or would you do on-the-fly calculation everytime? For eg: Whitelist = Detroit, MI and nearby city = Kalamazoo, MI (140 miles) Second, if pre-computed: would you store this in XML file or some MySQL table? Now, we just have to search through a table (mysql or xml no more than 1 mb in size). I am guessing this would be inefficient because client browser (JavaScript) would have to download 1mb xml and search through it. This would make page load time even slower. Using DB might be faster but then DB load increases (if 200,000 unique users are trying to load the page over the course of a day). Maybe the best way to do would be to do precompute, store precomputed results in XML, and then use PHP to search through XML and find nearest whitelisted city to user? A: If you, the site, are actually relying on the city information, then you must do the calculation on the server. Database queries are almost always going to be faster than XML searches for sufficiently large XML files. You can optimize the query, MySQL will cache things, etc. Pre-calculating all city-city distances would be a way to go, for sure. GeoIP doesn't only provide city names, it does give actual latitude/longitude locations as well. I'm sure that the possible list of cities changes rather constantly, too. I would look into using the geospacial capabilities of MySQL. General over view of searching by coordinates here: Fastest Way to Find Distance Between Two Lat/Long Points In short what you will do is setup a database of the cities you care about, with their lat/long, and query that table based on the GeoIP provided lat/long.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting "error: type mismatch; found : Unit required: () => Unit" on callback I am just starting out going through a tutorial on scala and have hit a block. I have merged together a couple of examples and am getting an error, but don't know why. import java.text.DateFormat._ import java.util.{Date, Locale} object FrenchDate { def main(args: Array[String]) { timer(println(frenchDate)) } def frenchDate():String = { val now = new Date val df = getDateInstance(LONG, Locale.FRANCE) df format now } def timer(callback: () => Unit) { while(true) {callback(); Thread sleep 1000} } } Brings the error error: type mismatch; found : Unit required: () => Unit println(frenchDate) while the below works import java.text.DateFormat._ import java.util.{Date, Locale} object FrenchDate { def main(args: Array[String]) { timer(frenchDate) } def frenchDate() { val now = new Date val df = getDateInstance(LONG, Locale.FRANCE) println(df format now) } def timer(callback: () => Unit) { while(true) {callback(); Thread sleep 1000} } } The only difference is that the date is printed out in frenchDate() in the second once whereas it is returned and printed in the callback on the first. A: The difference is that this line: timer(println(frenchDate)) is trying to call println(frenchDate) and use the return value (which is Unit) as the callback to pass to timer. You probably want: timer(() => println(frenchDate)) or possibly timer(() => { println(frenchDate) }) (I'm not a Scala dev, so I'm not sure of the right syntax, but I'm pretty confident about what's wrong in your current code :) EDIT: According to comments, this should work too and may be more idiomatic: timer { () => println(frenchDate) }
{ "language": "en", "url": "https://stackoverflow.com/questions/7572166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: resize image by area I am trying to write a javascript function to resize an image based on a given area (or in my case (somewhat inaccurate) 'average dimension' since that's easier to think in terms of. Rather than feeding in maximum height and width, I want to feed in maximum area so that long or narrow images will appear visually to be roughly the same size. I'm getting really caught on the math aspect of it, though... just how to logic it, as I haven't done much math of late. Basically, given an aspect ratio I want to determine the maximum size within an area. Something like this: function resizeImgByArea(img, avgDimension){ var w = $(img).width(); var h = $(img).height(); var ratio = w/h; var area = avgDimension * avgDimension; var targetHeight //something involving ratio and area var targetWidth //something involving ratio and area $(img).width(targetWidth); $(img).height(targetHeight); } Not sure if this is on topic here, but I'm not able to brain it. A: Sounds like you want to constrain the thumbnail's pixels to be as close as possible to the average area as all the other thumbnails, right? So basically, given the h/w of the original image, and a target area A: h * w = original image's pixel size (let's got with 640x480 = 307,200 pixels) A = maximum number of pixels allowed (let's go for 100x100 = 10,000 pixels) 307,200 / 10,000 = 30x reduction original aspect ratio = 640 / 480 = 1.3333 : 1 To calculate the new thumbnail's x/y size: newX * newY = 10000 newX = newY * 1.333 (newY * 1.333) * newY = 10000 newY^2 * 1.333 = 10000 newY^2 = 10000 / 1.333 newY^2 = 7502 newY = 86.6 -> 87 newX = 87 * 1.333 = 115.97 -> 116 116 x 87 = 10,092 pixels if we'd rounded down on the thumbnail sizes, we'd get 86x114 = 9,804 pixels so... to convert your 640x480 image to a standard 10,000-ish pixel size, you need a new image size of 86-87 height and 114-116 width. A: Are you looking for something like: function resizeImgByArea(img, avgDimension) { var w = $(img).width(); var h = $(img).height(); var maxWidth = avgDimension; var maxHeight = avgDimension; var divisor; var targetWidth = w; var targetHeight = h; if (w > maxWidth || h > maxHeight) { // Set the divisor to whatever will make the new image fit the dimensions given if((w - maxWidth) > (h - maxHeight)) { divisor = w / maxWidth; } else { divisor = h / maxHeight; } targetWidth = w / divisor; targetHeight = h / divisor; } $(img).width(targetWidth); $(img).height(targetHeight); } A: It isn't that hard. maxPix = average^2 maxPix = x * h + x * w average^2 = x*h + x*w //: x average^2/x = h+w inverse and multiply with average^2 x = average^2 / (h+w) then multiply h and w with x to get the new dimensions A: Here is the function I came up with that's simpler than some mentioned and does what I need. It constrains to a set maxWidth, but not height because of the particular requirements I was using.. it would probly be appropriate to throw on a maxHeight as well as well as some cleanup, but it gets 'er done. function resizeImgByArea(imgId, avgDimension){ var node, w, h, oldArea, oldAvgDimension, multiplicator, targetHeight, targetWidth, defAvgDimension; node = $('#' + imgId); node.css('width', '').css('height', ''); var maxW = $('#' + imgId).css('maxWidth'); if (maxW){ defAvgDimension = maxW; } else { defAvgDimension = 200; } avgDimension = (typeof avgDimension == "undefined")?'defAvgDimension':avgDimension; w = node.width(); h = node.height(); oldArea = w*h; oldAvgDimension = Math.sqrt(oldArea); if (oldAvgDimension > avgDimension){ multiplicator = avgDimension / oldAvgDimension; targetHeight = h * multiplicator; targetWidth = w * multiplicator; node.width(targetWidth); node.height(targetHeight); } } A: function fitImageInArea(img, area) { var r; if (img.width/img.height >= area.width/area.height) { r = area.width / img.width; img.width = area.width; img.height = img.height*r; } else { r = area.height / img.height; img.height = area.height; img.width = img.width*r; } return img; } Give an image or anything with width and height properties as an argument. area argument assume width and height properties too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572170", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MYSQL/PHP/AJAX Search using SELECT, CONCAT, OR and LIKE on multiple columns I'm makeing a search filed for a table that has 25+ columns in it. Two of them are a First Name and a Last name. I can get the CONCAT to search them fine alone but when I add the other OR selections I get errors. Can anyone point me in the right direction? Any help would be great. More details: I'm tring to figure this out here.. I have two different SELECT statments that are working fine #1 is $query = "SELECT `CustomerID`, `CompanyName`, `ContactFirstName`, `ContactLastName`, `BillingAddress`, `BillingAddress2`, `City`, `PostalCode`, `PhoneNumber`, `FaxNumber`, `EMail` FROM `Customers` WHERE `CustomerID` LIKE '%".mysql_real_escape_string($search_text)."%' OR `CompanyName` LIKE '%".mysql_real_escape_string($search_text)."%' OR `ContactFirstName` LIKE '%".mysql_real_escape_string($search_text)."%' OR `ContactLastName` LIKE '%".mysql_real_escape_string($search_text)."%' OR `BillingAddress` LIKE '%".mysql_real_escape_string($search_text)."%' OR `BillingAddress2` LIKE '%".mysql_real_escape_string($search_text)."%' OR `PhoneNumber` LIKE '%".mysql_real_escape_string($search_text)."%' OR `EMail` LIKE '%".mysql_real_escape_string($search_text)."%'"; And #2 is SELECT *, CONCAT_WS(' ',ContactFirstName,ContactLastName) AS FullName FROM `Customers` HAVING FullName LIKE '%".mysql_real_escape_string($search_text)."%'"; I've been unable to figure out how to add the second select into the first one. ---EDIT--- After a1ex07's post I redid the query and it's working they way I was looking for... $query = "SELECT `CustomerID`, `CompanyName`, `ContactFirstName`, `ContactLastName`, BillingAddress`, `BillingAddress2`, `City`, `PostalCode`, `PhoneNumber`, `FaxNumber`, `EMail` FROM `Customers` WHERE `CustomerID` LIKE '%".mysql_real_escape_string($search_text)."%' OR `CompanyName` LIKE '%".mysql_real_escape_string($search_text)."%' OR `BillingAddress` LIKE '%".mysql_real_escape_string($search_text)."%' OR `BillingAddress2` LIKE '%".mysql_real_escape_string($search_text)."%' OR `City` LIKE '%".mysql_real_escape_string($search_text)."%' OR `PostalCode` LIKE '%".mysql_real_escape_string($search_text)."%' OR `PhoneNumber` LIKE '%".mysql_real_escape_string($search_text)."%' OR `FaxNumber` LIKE '%".mysql_real_escape_string($search_text)."%' OR `EMail` LIKE '%".mysql_real_escape_string($search_text)."%' OR CONCAT_WS(' ',ContactFirstName,ContactLastName) LIKE '%".mysql_real_escape_string($search_text)."%'"; $query_run = mysql_query($query); while ($query_row = mysql_fetch_assoc($query_run)) { $CustomerID = $query_row['CustomerID']; $CompanyName = $query_row['CompanyName']; $ContactFirstName = $query_row['ContactFirstName']; $ContactLastName = $query_row['ContactLastName']; $BillingAddress = $query_row['BillingAddress']; $BillingAddress2 = $query_row['BillingAddress2']; $City = $query_row['City']; $PostalCode = $query_row['PostalCode']; $PhoneNumber = $query_row['PhoneNumber']; $FaxNumber = $query_row['FaxNumber']; $EMail = $query_row['EMail']; echo $CustomerID.' '.$CompanyName.' '.$ContactFirstName.' '.$ContactLastName.' '.$BillingAddress.' '.$BillingAddress2.' '.$City.' '.$PostalCode.' '.$PhoneNumber.' '.$FaxNumber.' '.$EMail.'<br>'; It seems to be doing what I want, unless there would be a way to get the FullName variable back in? A: If I understood you well, you are trying to add WHERE ... OR FullName LIKE ... to the first query. It fails because you cannot use field aliases in WHERE. You need to do WHERE ... OR CONCAT_WS(' ',ContactFirstName,ContactLastName) LIKE .... Updated: It seems to be doing what I want, unless there would be a way to get the FullName variable back in? Just add it to SELECT : SELECT ..., CONCAT_WS(' ',ContactFirstName,ContactLastName) AS FullName. Once again, the problem is that aliases cannot be used in WHERE. There are some ways to deal with it: * *Use expression in WHERE : SELECT ..., CONCAT_WS(' ',ContactFirstName,ContactLastName) AS FullName WHERE ... OR CONCAT_WS(' ',ContactFirstName,ContactLastName) *Use alias in HAVING : SELECT ..., CONCAT_WS(' ',ContactFirstName,ContactLastName) AS FullName WHERE ... HAVING FullName ... *Use derived tables : SELECT * FROM ( SELECT ..., CONCAT_WS(' ',ContactFirstName,ContactLastName) AS FullName ...)a WHERE ... OR FullName .... Your final query should look like: $query = "SELECT `CustomerID`, `CompanyName`, `ContactFirstName`, `ContactLastName`, BillingAddress`, `BillingAddress2`, `City`, `PostalCode`, `PhoneNumber`, `FaxNumber`, `EMail`, CONCAT_WS(' ',ContactFirstName,ContactLastName) AS FullName FROM `Customers` WHERE `CustomerID` LIKE '%".mysql_real_escape_string($search_text)."%' OR `CompanyName` LIKE '%".mysql_real_escape_string($search_text)."%' OR `BillingAddress` LIKE '%".mysql_real_escape_string($search_text)."%' OR `BillingAddress2` LIKE '%".mysql_real_escape_string($search_text)."%' OR `City` LIKE '%".mysql_real_escape_string($search_text)."%' OR `PostalCode` LIKE '%".mysql_real_escape_string($search_text)."%' OR `PhoneNumber` LIKE '%".mysql_real_escape_string($search_text)."%' OR `FaxNumber` LIKE '%".mysql_real_escape_string($search_text)."%' OR `EMail` LIKE '%".mysql_real_escape_string($search_text)."%' OR CONCAT_WS(' ',ContactFirstName,ContactLastName) LIKE '%".mysql_real_escape_string($search_text)."%'"; A: On #1 What if you put a space after the single quote? ' "; In other words so your sql doesn't run together, proper spacing. Also, echo your SQL and try look at it to see.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572173", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a NANT task to start/stop COM+ components? I am automating our deploymnet using CC.net and a NANT build script. I have to stop and start our COM+ components during deployment. Is there a NANT task that does this? A: Assuming that the COM+ components are your components (ServicedComponent instances), then you can use the <regsvcs> task to achieve this. You would have to indicate the assembly that your COM+ components are in, remove the application (using an action with an ActionType of uninstall) and then install it again (you might need two task instances for this). If your assembly is not the source of the COM+ components/application, then you will need to write your own custom task accessing the COM+ Administration API through COM interop. A: I've been struggling with the same problem. Couldn't find any other detailed way than vbs scripts. The solution I came up with is as follows: I created a C# .Net solution which references NAnt.Core. I created two classes (tasks) which inherit from the Nant Task class. You need three things: 1) Place TaskName attribute on the class [TaskName("startupComApplicationTask")] 2) Place a Task attribute on any properties that you want to pass in from Nant [TaskAttribute("machineName", Required = true)] 3) Implement the ExecuteTask() Method The Final outcome was something like this: [TaskName("startupComApplicationTask")] public class StartupComApplicationTask: Task { private string _applicationName; private string _machineName; [TaskAttribute("applicationName", Required = true)] public string ApplicationName { get { return _applicationName; } set { _applicationName = value; } } [TaskAttribute("machineName", Required = true)] public string MachineName { get { return _machineName; } set { _machineName = value; } } protected override void ExecuteTask() { COMAdminCatalog objAdmin = new COMAdminCatalog(); objAdmin.Connect(MachineName); var objCollection = (COMAdminCatalogCollection)objAdmin.GetCollection("Applications"); objCollection.Populate(); foreach (COMAdminCatalogObject objAppNames in objCollection) { if (objAppNames.Name.Equals(ApplicationName)) { ICatalogCollection objComponents = (ICatalogCollection)objCollection.GetCollection("Components", objAppNames.Key); objComponents.Populate(); } } objAdmin.StartApplication(ApplicationName); } } Obviously in order to get this going you need to include a reference to the ComAdmin interop assembly. Which you can find under "COM+ 1.0 Type Library" in your Com references. Build the project which will create two dlls for you. The interop one and yours. Drop these into your nant folder (in the bin directory). You can call these from within Nant the following way: <startupComApplicationTask machineName="193.132.119.249" applicationName="NantTest" /> Repeat for shutingdown, just call ShutdownApplication instead of StartApplication. Hope this helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7572176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JavaScript sound synthesis As part of a third level project I am going to attempt to build a web based sound synthesiser using HTML5 and JavaScript. Does anyone know of any APIs that would allow me to deploy it on all or most browsers? I have so far seen an API that works with Firefox only and another on GitHub that works with Chrome only. It would be great to be able to use this in Safari, as with the iPad it could become a stand alone instrument. Is this feasible? A: If you go to http://caniuse.com they will tell you if a technology is supported by Safari or not. Go check it out. Then, any API that you use will tell you what support you will get for it. A: I think your best bet might be to do it server side. I would have your app use AJAX to call a server-side script to generate the sound file if it doesn't already exist, then return it's URL so you can use it in JS. Eventually, all the different sound files should be created by the server and named properly allowing you to look them up quickly. A: http://mohayonao.github.com/timbre.js/ seems pretty powerful. Pity some of the documentation appears to be in Japanese only! A: WebPd is a partial Puredata port to JS - https://github.com/sebpiq/WebPd - it works well with Chrome and Firefox. "It is also a standalone DSP library. Every object as you know it in Pure Data exposes a complete API, allowing developers to control everything with JavaScript."
{ "language": "en", "url": "https://stackoverflow.com/questions/7572177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: RuntimeWarning: in python 2.6 while importing python-pycrypto-2.3-1.el3.pp I have installed "python-pycrypto-2.3-1.el3.pp" and "python-paramiko-1.7.6-1.el3.rf" in red hat linux and using python2.6 version. And when I import paramiko, I get below RuntimeWarning mismatch: /usr/local/lib/python2.6/site-packages/Crypto/Random/Fortuna/SHAd256.py:38: RuntimeWarning: Python C API version mismatch for module Crypto.Hash.SHA256: This Python has API version 1013, module Crypto.Hash.SHA256 has version 1011. please help how to resolve this problem. A: The EL3 packages are for EL3 Python. Since you've installed Python from source yourself, perform a source installation of those modules.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android + Which layout would you suggest? I'm laying out a row for use in a ListView and I need a little help. The row will look like this: Below is what I have so far, the highlight bg is not showing up and the text won't align center (sticks to the top). <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/rl0" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="0dp" android:layout_margin="0dp" android:background="@color/grey"> <!-- shine --> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageView android:id="@+id/imgShine" android:background="@color/shine" android:layout_height="0dp" android:layout_width="fill_parent" android:layout_weight="1" /> <View android:layout_height="0dp" android:layout_width="fill_parent" android:layout_weight="1" /> </LinearLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" android:id="@+id/ll" android:layout_gravity="center_vertical"> <!-- cal graphic --> <RelativeLayout android:id="@+id/rl1" android:layout_width="wrap_content" android:layout_height="match_parent" android:padding="10dp"> <!-- cal bg --> <ImageView android:id="@+id/imageView1" android:src="@drawable/cal" android:layout_width="60dp" android:layout_height="wrap_content" android:adjustViewBounds="true" android:scaleType="fitCenter" android:layout_centerVertical="true" android:layout_alignParentLeft="true" /> <!-- month --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tvMonth" android:textSize="11sp" android:layout_marginLeft="11dp" android:layout_marginTop="10dp" android:textColor="@drawable/list_cal_selector" /> <!-- day --> <TextView android:id="@+id/tvDay" android:textSize="23sp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/tvMonth" android:layout_marginTop="2dp" android:layout_centerHorizontal="true" android:textColor="@drawable/list_cal_selector" /> </RelativeLayout> <!-- text and button graphic --> <RelativeLayout android:id="@+id/rl2" android:layout_width="wrap_content" android:layout_height="fill_parent" android:gravity="center_vertical" android:layout_gravity="center_vertical"> <!-- team name --> <TextView android:id="@+id/tvTeam" android:textSize="23dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingBottom="0dp" android:textColor="@drawable/list_text_selector" /> <TextView android:id="@+id/tvTime" android:textSize="12sp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/tvTeam" android:textColor="@drawable/list_text_selector" /> <TextView android:id="@+id/tvStation" android:textSize="12sp" android:paddingLeft="12dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/tvTeam" android:layout_toRightOf="@+id/tvTime" android:textColor="@drawable/list_text_selector" /> <!-- add button --> <ImageView android:id="@+id/imgAddBtn" android:src="@drawable/btn" android:layout_height="wrap_content" android:layout_width="60dp" android:scaleType="fitCenter" android:layout_centerVertical="true" android:adjustViewBounds="true" android:layout_alignParentRight="true" android:padding="10dp" /> <!-- divider --> <ImageView android:id="@+id/imgDivider" android:src="@drawable/divider" android:layout_height="fill_parent" android:layout_width="2dp" android:layout_toLeftOf="@id/imgAddBtn" android:cropToPadding="false" /> </RelativeLayout> </LinearLayout> </FrameLayout> A: I would use just one RelativeLayout. It will avoid the use of various Layouts and its easier to place componentes on screen. edit: This solution works, but I don't know if it's the best: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentBottom="true" android:orientation="vertical" > <View android:layout_width="1dp" android:layout_height="0dp" android:layout_weight="0.25"/> <ImageView android:layout_weight="0.5" android:layout_height="0dp" android:layout_width="50dp" android:background="#dedede"/> <View android:layout_width="1dp" android:layout_height="0dp" android:layout_weight="0.25"/> </LinearLayout> <!-- ... --> </RelativeLayout> A: Look at this tutorials you can choose which layout is best. Every layout has own merits and demerits. Only one that layout is not best in android but in most cases Relative layout easy to use because it has move to easy any where of UI. just like your matches problems, tutorials http://android-developers.blogspot.com/2009/02/android-layout-tricks-1.html you can see more layout of in developer.android.con. which has to learn more simply way. here some Best links you can see various layouts. http://developer.android.com/resources/tutorials/views/hello-relativelayout.html http://developer.android.com/guide/topics/ui/layout-objects.html http://mobile.tutsplus.com/tutorials/android/android-user-interface-design-relative-layouts/ http://www.learn-android.com/2010/01/05/android-layout-tutorial/ A: Check this out ![<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="35dp" android:orientation="horizontal" > <ImageView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="2" android:scaleType="centerInside" android:src="@drawable/ic_launcher" /> <LinearLayout android:layout_width="0dp" android:layout_height="40dp" android:layout_weight="4" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Row 1" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:layout_width="wrap_content" android:layout_height="fill_parent" android:text="Row 2" /> <TextView android:layout_marginLeft="10dp" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="Row 3" /> </LinearLayout> </LinearLayout> <View android:layout_height="match_parent" android:layout_width="2dp" android:background="#fff"/> <ImageView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="2" android:scaleType="centerInside" android:src="@drawable/ic_launcher" /> </LinearLayout>
{ "language": "en", "url": "https://stackoverflow.com/questions/7572180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Hibernate 4, EnversIntegrator could not be instantiated I'm trying to set up Hibernate, and since 4.0.0 just came out I naturally decided to go with that. It seems that no matter what way I try to create a SessionFactory, it always leads to the same error: Initial SessionFactory creation failed.java.util.ServiceConfigurationError: org.hibernate.integrator.spi.Integrator: Provider org.hibernate.envers.event.EnversIntegrator could not be instantiated: java.lang.ClassCastException: Cannot cast org.hibernate.envers.event.EnversIntegrator to org.hibernate.integrator.spi.Integrator It seems like there is something wrong with my Hibernate configuration but I can't figure out what. Here's my 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> <!-- Database connection settings --> <property name="connection.driver_class">org.postgresql.Driver</property> <property name="connection.url">jdbc:postgresql://192.168.0.17:5432/mydb</property> <property name="connection.username">myusrname</property> <property name="connection.password">mypasswd</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- c3p0 configuration --> <property name="hibernate.c3p0.min_size">5</property> <property name="hibernate.c3p0.max_size">20</property> <property name="hibernate.c3p0.timeout">300</property> <property name="hibernate.c3p0.max_statements">50</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">false</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">create</property> </session-factory> </hibernate-configuration> Does anyone spot anything out of the ordinary, or do you have other ideas? A: I found no way to get Hibernate 4.0.0 CR4 working. Switching to 3.6.7 resolved the problem and works just fine. I conclude that there must be some bug in the release, and will file a bug report.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Button background before a thread Why the background of the button doesn't change before the thread starts? It changes after the thread sleep ends. I mention that the background changes if there is no thread. answer1Top.setBackgroundDrawable(correct); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } //I want to stop this playerScTop--; playerScoreTop.setText(String.valueOf(playerScTop)); A: Create a new class extending AsyncTask, pass it the View of which to change the background as well as the two background Drawable instances, then: * *in onPreExecute() (runs on UI thread), set the first background drawable on your view *in doInBackground() (runs on background thread), sleep 2 seconds *in onPostExecute() (runs on UI thread), set the other drawable on your view Untested sample code: public class BackgroundChangeTask extends AsyncTask<Void, Void, Void> { private View view; private Drawable background1; private Drawable background2; public BackgroundChangeTask(View view, Drawable background1, Drawable background2) { this.view = view; this.background1 = background1; this.background2 = background2; } @Override protected void onPreExecute() { view.setBackgroundDrawable(background1); } @Override protected Void doInBackground(Void... params) { try { Thread.sleep(2000); } catch (InterruptedException e) { // too bad } return null; } @Override protected void onPostExecute(Void result) { view.setBackgroundDrawable(background2); // add anything else you want to run "after 2 seconds" here, e.g. playerScTop--; playerScoreTop.setText(String.valueOf(playerScTop)); } } Invoke from your Activity/Fragment/etc like this (no need to keep the created task around in a field): new BackgroundChangeTask(BackgroundChangeTask, correct, theOtherDrawable).execute(); A: answer1Top.setBackgroundDrawable(correct); new Handler().postDelayed(new Runnable() { @Override public void run() { playerScTop--; playerScoreTop.setText(String.valueOf(playerScTop)); } }, 2000);
{ "language": "en", "url": "https://stackoverflow.com/questions/7572184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Boolean variable has to be shared in diff spring bean I have two beans <bean id="eventService" class="xxx.xxxx.xxxxx.EventServiceImpl"> </bean> <bean id="UpdateService" class="xxx.xxxx.xxxxx.UpdateServiceImpl"> </bean> A Boolean variable has to be shared... means updating Boolean in a bean should be available for other bean to know the status appreciate your idea guys A: The fact that you have multiple objects interested in a the same flag sounds very much like an event. Have a look at Spring's support from broadcasting and listening to events (including custom events). http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#context-functionality-events What you could do is have one managed object be the "owner" of that flag, and broadcast state changes to anyone else that's interested via an event. A: I'm afraid you will need some value holder bean, something like this: public class ValueHolder{ private boolean flag; public boolean isFlag(){return flag;} public void setFlag(boolean flag){this.flag=flag;} } Wire this as a Spring Bean and inject it into your service beans. Just for completeness: or you could use a static field, but that's even uglier.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: The action value does not match a navigation case outcome I am getting the following error in Eclipse: The action value does not match a navigation case outcome on the following line: <h:commandLink value="Add person" action="add?faces-redirect=true" /> I am using JSF 2, Tomcat 6, Glassfish el. Any ideas, why I am getting this, and how to solve it? A: Ignore and run it. Eclipse is relying on it being present as <navigation-case> declaration in faces-config.xml the JSF 1.x way. It does by default not recognize new JSF 2.x implicit navigation and likes yet and therefore gives false warnings. It's likely fixed in a newer Eclipse release. In the meanwhile, you could consider to turn off JSF validation in Eclipse preferences, it will only lead to more confusion and annoyances. Note that this is in no way related to EL. You aren't using #{} anywhere.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572187", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is it possible to have Camera Preview and TextView on the same screen? I was wondering if there is some way to have a camera preview fill a part of the screen, and at the bottom have a textview box into which I can add text later. I don't have any code yet because my team is still evaluating if this is possible at all before proceeding with the code. Edit 2: Now I am finally able to see the text on the screen after playing around with android:gravity. But the TextView always shows up on the top of the screen, is there some way to move it to the bottom? Edit 3: Changing android:layout_height to fill_parent instead of wrap_content fixed the positioning issue <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <SurfaceView android:id="@+id/preview_view" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_centerInParent="true"/> <com.google.zxing.client.android.ViewfinderView android:id="@+id/viewfinder_view" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@color/transparent"/> ........ ........ <TextView android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="bottom" android:text="Header text"/> </FrameLayout> A: Yes, this is possible. You should use FrameLayout for this. Here is an example: <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <SurfaceView android:id="@+id/preview_view" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_centerInParent="true"/> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="top|center_horizontal" android:text="Header text"/> </FrameLayout> A: yes it is possible like this: <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <android.view.SurfaceView android:id="@+id/surface" android:layout_width="fill_parent" android:layout_height="fill_parent" /> <TextView android:id = "@+id/txtview" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "TextView" android:padding = "7dp" android:gravity = "bottom" /> </FrameLayout> A: Thanks to the posts on this thread, here's a variation using simple LinearLayout that restricts the dimension of the camera display. This reduces the size of the "scanning square" <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal" android:background="@color/sea_blue_green_dark" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:padding="10dp" android:textColor="@color/white" android:textSize="28sp" android:text="Scan Code Now"/> <me.dm7.barcodescanner.zxing.ZXingScannerView android:id="@+id/scanner" android:layout_width="match_parent" android:layout_height="200dp" android:background="@color/white"/> <!-- Add this view to prevent camera from taking up remaining vertical space Although seems to be better UX when user can still see camera outside of "Scanner Box Target". Leaving here for reference --> <View android:layout_width="match_parent" android:layout_height="match_parent" android:background="#8BC34A"/> </LinearLayout> ======= This will generate the following layout, where white block becomes the camera area:
{ "language": "en", "url": "https://stackoverflow.com/questions/7572189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: NotSerializableException when sending an serializable object over socket? Im trying to send a custom-made object over a socket connection. The class implements serializable but the constructor still throws a NotSerializableException when im trying to write the object to the socket. I'll post relevent code below: public class serilizableArrayHolder implements Serializable { private ArrayList<Client> array= null; public serilizableArrayHolder(ArrayList<Client> array) { this.array=array; } public ArrayList<Client> getArray() { return array; } } This is my custom-made class. For now im trying to send an arraylist from the server to the client but i'll add additional info in a later stage. The send method is posted below in my server class is posted below: public void sendData(Socket clientSocket){ ObjectOutputStream out; try { serilizableArrayHolder temp = new serilizableArrayHolder(clientCollection); out = new ObjectOutputStream(clientSocket.getOutputStream()); out.writeObject(temp); <---This line generates the error. out.flush(); } catch (IOException e) { e.printStackTrace(); } } This is my send-method from the server. clientCollection is the arrayList that im trying to send. The whole Client class: public class Client implements Runnable, Serializable{ public Thread thread = new Thread(this); private Socket s; private DataInputStream in; private DataOutputStream out; private ObjectOutputStream objOut; private ServerMain server=null; private String host=null; private Client c; private String userName; public Client(Socket s, String host, ServerMain server) throws IOException{ c=this; this.host=host; this.s=s; this.server=server; this.userName=userName; in= new DataInputStream(s.getInputStream()); out=new DataOutputStream(s.getOutputStream()); objOut=new ObjectOutputStream(s.getOutputStream()); thread.start(); } public String getClientInfo(){ return host; } public String getUserName(){ return userName; } public void send(String s){ try { out.writeUTF(s); } catch (IOException e){ } } public void run() { while(true){ try { String temp = in.readUTF(); if(temp.equals("sendOnline")){ sendOnline(); } String tempHost=s.getInetAddress().getHostAddress(); server.appendString(tempHost+" Skickade: "+temp+"\n"); } catch (IOException e) { String str = s.getInetAddress().getHostName(); server.clientDisconnect(str); break; } } try { s.close(); } catch (IOException e) { } } public void sendOnline(){ serilizableArrayHolder temp = new serilizableArrayHolder(server.getClients()); try { objOut.writeObject(temp); objOut.flush(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Metoden anropas"); } } The new stacktrace: java.io.NotSerializableException: java.io.DataInputStream Metoden anropas at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1180) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1528) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346) at java.util.ArrayList.writeObject(ArrayList.java:710) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:962) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1480) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1528) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346) at Gesäll.Client.sendOnline(Client.java:83) at Gesäll.Client.run(Client.java:58) at java.lang.Thread.run(Thread.java:722) A: The exception tells you the problem. Your Client class is not serializable. To serialize an object, all the objects it references (and so on, transitively) need to also be serializable. You can mark a reference transient if you don't want it to be serialized. A: All classes which are reachable through serilizableArrayHolder have to be Serializable including your Client class. Your Client class contains Socket, Thread, DataInputStream, DataOutputStream and ObjectOutputStream members. None of them are Serializable. That's why you cannot serialize the Client class. Here is another answer with the same topic. I think you should rethink your design and share why are you want to serialize these objects.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572191", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Best way to animate programatically created bitmaps in android I have a board game app that creates a lot (hundreds) of bitmaps, and constantly changes them as the game progresses. These bitmaps are created, not loaded from a resource... so they have no R.id to refer to. I would like to animate some of them, e.g. a bitmap moving from one loction to another when a player taps to move it. What is the best way to do this? Note, this is 2.1 and the bitmaps are drawn on a canvas via a matrix translate. A: Make this function to get image from drawable folder private Bitmap getImageBitmap(){ int resID = getResources().getIdentifier(uri, "drawable", "a.b.c"); Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), resID); return mBitmap; } For set the image , where do you you want> ImageView imageview01.setImageBitmap(getImageBitmap("name of bitmap"); if you want more about bitmap. then you may try this links. http://developer.android.com/reference/android/widget/ImageView.html drawable getResources().getIdentifier problem setImageURI / setimagebitmap to fetch image from net and display in image view
{ "language": "en", "url": "https://stackoverflow.com/questions/7572195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I put a lightbox or image map within a lightbox? I've had a look around but haven't managed to find what I'm looking for. Basically, I've got an image on a page that uses a jquery lightbox to make it larger and easier to view. In addition to this, with the original lightbox active, I now need 'hot spots' on that image that either generate a tooltip when hovered on, or a seperate relatively positioned lightbox when clicked on. The type of look I'm after can be seen on the Create Bikes website if you click on a bike and go to a product page. Been playing around but can't for the life of me work it out - does anyone know if this is even possible or able to point me in the direction of any sites that already have something like this implemented? Edit: Ok, as suggested, I've put some existing code in here which I hope helps. This block of code is typical of where the lightbox is used with the class lightbox-image calling the script. The lightbox used is Colorbox. <p> <a href="images/search-wheel-big.png" title="This is where the title goes"class="lightboxElement lightbox-image" rel="lightbox-image"> <img class="c-right" alt="alt tag here" src="testimonials_files/SearchWheel.png"> </a> Some text here </p> When the lightbox is loaded, <div> tags that then appear include the below, with the <img> tag generated by the Colorbox script (it disappears again when the lightbox is closed): <div id="lightboxContent" style="float: left; width: 500px; height: 554px;"> <div id="lightboxLoadedContent" style="display: block; width: 500px; overflow: auto; height: 507px;"> <img class="lightboxPhoto" src="images/search-wheel-big.png" style="float: none;"> </div> <div id="lightboxLoadingOverlay" class="" style="height: 554px; display: none;"></div> <div id="lightboxLoadingGraphic" class="" style="height: 554px; display: none;"></div> <div id="lightboxTitle" class="" style="display: block;">This is where the title goes</div> <div id="lightboxCurrent" class="" style="display: none;"></div> <div id="lightboxNext" class="" style="display: none;"></div> <div id="lightboxPrevious" class="" style="display: none;"></div> <div id="lightboxSlideshow" class="" style="display: none;"></div> <div id="lightboxClose" class="" style="">close</div> </div> I then thought I'd be able to just put a jquery command saying something like: $(".lightboxPhoto").each(function(){ $(this).append("<div class='hotspot'></div>"); }); I was hoping this I could do this multiple times (for the different 'hotspots' on the image that can in turn be clicked / hovered on for additional info) and insert a relatively positioned background image in each <div> tag. However, nothing happens in the code, could this be something to do with the fact the the <div> tags themselves are generated by the .js file and not in my original html? Would I need to edit the .js file myself?? Edit 2 - the solution! Hi All! So I just thought I'd add in here what I did in the end in case someone else is looking to create the same effect. As suggested by Chris, I used the inline command that works with the colorbox lightbox. Instead of using a tooltip though, I took an idea from the create bikes website (see one of their product pages) and entered the following html code: <div style="display:none"> <div class="example1"> <div class="example2">This is where the title goes</div> <div class="example3"> <span class="example4"></span> <div class="example5"> <h5 class="example6">Header text here</h5> <p class="example7">Some more text here</p> </div> </div> </div> </div> The <span> tag and <div> tag with class of example5 both had a background image. With this <div> tag having a default state of display:none I wanted it to change to display:block when the <span> tag image was hovered on. I did this using the follow line of css: span.example4:hover + div.example5 { display: block; } Works like a dream! Just bear in mind this css won't work in IE6 or less A: Absolutely possible. Here's how I would do it: * *Use a lightbox plugin like this one here: http://www.no-margin-for-errors.com/projects/prettyphoto-jquery-lightbox-clone/#!prettyPhoto. This is clever as it allows you to have not just an image loaded into a lightbox, but a div or other content. This isn't the only one it's just one I've used in the past. *Inside the div which is loaded into the lightbox (when you click a bike) I would have two parts: an image and a collection of tags which make up the buttons. Position the image absolutely in the background, and the buttons also absolutely positioned but in the place you want (ie. top: 200px; left: 183px). *Then, on the buttons use this plugin http://www.vertigo-project.com/files/vTip/example.html which will give you a hover tooltip, all contained within the lightbox. I'm afraid I do not have any code as it's quite a bit of work but the theory is all sound (listen to me getting all big headed) so you should be able to make something work. Maybe try similar plugins in case those two in particular clash but I see no reason why they should. Good luck! Edit: Not quite. The method I've described does not use the basic image load. Instead, it loads up a div on your page into your lightbox. Inside this div you can have the image (in the background) and then your buttons positioned on top. See the Inline HTML link (second from bottom) on this page: http://colorpowered.com/colorbox/core/example1/index.html. A div is placed elsewhere on the page and hidden. The plugin then loads the contents of the div into the lightbox when the link is pressed. As it is a traditional div, you can have whatever content inside that you want: more divs, images, links etc. So inside this div load in an image (position: absolute; top: 0; left: 0; z-index: 10) and then some buttons on top (position: absolute; top: 50px; left: 50px; z-index: 20). The table on this page http://colorpowered.com/colorbox/ has a row with inline that explains how to do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: IFrame and Parent Frame Session Handling I have an application that contains no session time out, we don't want our users to have to log in every time they come to the site or even if they've remained idle. We recently partnered with an external vendor to provide some research data which we are rendering in an i-frame. The vendor has a 30 minute session after that session expires in the iframe the users are asked to re-login to the vendor site. As I stated previously we don't want to have the end user log in multiple times. The solution I came up with was when the end users session expired in the iframe there would be a javascript call to: /if called from an iframe, refresh the containing window if (self != top) { window.parent.location.href = window.parent.location.href; } I tested this locally and it works, ie both the parent and the iframe were running on the same application server, however when this is deployed on 2 different domains (Parent window and i-frame are running on different app servers) it is still sending the users to the login screen of the vendor, and if I just press refresh I'm successfully re-logged in without having to provide credentials. A couple of questions: * *Is there a different way anyone can think of to handle this issue? *Any idea why this would work locally but not across domains? A: i think you need to change parent window's URL from IFRAME content Parent window's content: <b>iframe starts here</b><br><br> <iframe src='iframe1.html'></iframe> <br><br> <b>iframe ends here</b> <script type="text/javascript"> function change_parent_url(url) { document.location=url; } </script> Iframe's content: IFRAME content<br><br> <a href="javascript:parent.change_parent_url('http://yahoo.com');"> Click here to change parent URL </a>
{ "language": "en", "url": "https://stackoverflow.com/questions/7572198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery: Onload Scroll to Object I've got a bit of a problem with scrolling at the moment. I'm developing a forum app for Facebook and I'm trying to get the page to scroll to the latest post on a page if the user wishes. I can do this no problem when I load the topic via AJAX in the same page, but I run into a problem if the user wants to open the topic in a new page first. My problem is that I can't get the code to wait until the document finishes loading before it executes (so the page isn't fully loaded and the function fails). I know EXACTLY what you're thinking at this point, and neither $(document).ready() nor $(window).ready() are working. The problem is in the fact that this is a Facebook application and I don't have access to the parent frame (as all apps are loaded through an iframe). Luckily I can run the function after an AJAX call and it works fine (seeing as I can wait until the content is fully loaded); however, I've definitely got a problem with opening topics in new tabs. Regardless, there must be a way to tell when my frame has completely loaded so that I can then initiate the function to scroll to an object. Can anyone give me a few ideas to try out? A: I figured out the problem. I generally load the Facebook JS SDK asynchronously and that was causing a delay in being able to use the functions. I'd call them but they weren't loaded yet. I made it load synchronously and the problem is resolved. A: The cross-domain stuff makes this awkward. A hackish solution would to include a script block at the very bottom of your iframe content that fires the scrolling: <script type="text/javascript"> scrollToPost(); </script> As this script is the last thing to load and execute, you'll not have the issue you had above. You might also try playing with the iframe.onload handler for a cleaner solution, but I think you'll come up against cross-domain issues again.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Link, clone, fork or download Twitter Bootstrap? What should be the best thing to do with Twitter's bootstrap css/javascript library? link (online), clone, fork or download it? I would like to always have the latest updates on my website but I would like to customize small things like width size of a the tabbed navigation feature, some colors, etc. A: Fork it. You will be able later to easily update to the new version, and merge in case you changed something. I suppose you are using github, so also push watch button, so you will always be aware of issues, updates, fixes of this project on your dashboard. Also you will be able to contribute to that awesome project. Don't link directly, because one day they will change something, and this could break your app. Also I suggest to look at LESS, and not compiled CSS version of library, in my opinion it's easier to customize everything there. Update: Probably easily update was too strong expression, and was referred only to bug fixes and minor updates. In a case of major version updates with breaking backwards compatibility there couldn't be easy and perfect solution. In this case, only if you really think you need this update, you can create new branch, update twitter bootstrap there, and than start a painful process of fixing your code. With branches you will be able work on your main app with old and working bootstrap, while part of your team will refactor code to become compatible with the new version of the bootstap(even if you only one person on the project, it's also good idea to test new solutions in the test branches, to not mess up working code).
{ "language": "en", "url": "https://stackoverflow.com/questions/7572210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Assembly built by a newer runtime error after converting to Web App I've recently been converting a website project over to a web application project. The old website had a C# file in the App_Code folder which worked fine even though the rest of the project is in VB. Since I've converted the project to a web app, the .cs file will no longer compile, so I moved the .cs file to its own project to compile as a .dll and included it in the solution so it will compile seperately. The problem is that now when I run the site, I get a runtime error refering to that dll: This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded. I can't downgrade the .net framework of the .cs file because it uses System.Web.Linq, which only dates back to 3.5. When I try to change the framework of the web app it already shows up as 4.0 (which makes no sense to me). The version info for the server is: Version Information: Microsoft .NET Framework Version:2.0.50727.3623; ASP.NET Version:2.0.50727.3618 Is there anyway to restore the old functionality without changing the .net framework on the server? Am I simply missing a configuration file or something? A: Before upgrading the server, I would try upgrading the C# 3.5 project to 4.0. Could be that the error is occurring when the C# file tries to talk back to the web app. EDIT: A better idea might be to downgrade your web app to 3.5. That way both parts of the app are on the same version and 3.5 should be able to run on a 2.0 server. A: If you keep the framework at 2.0, try referencing "System.Core" and make sure "Copy Local"=true or you move that file manually to the server. You will need .NET 2.0 SP1 as well to make this work. A: You probably need to change the version of the .NET framework that the application pool running the website is using. Make sure that the newer version of the framework is installed on the server, then follow the instructions at the bottom of this page, under "To associate an IIS application with the .NET Framework 4 in IIS 7.0": http://msdn.microsoft.com/en-us/library/dd483478.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7572212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best way to implement a keyword search from a MySQL CLOB or VARCHAR column I have to implement a keyword search from a CLOB column in my MySQL / JPA project. I know that I can use a JPA query something like SELECT something FROM something WHERE..., but are there any other 'Enterprise' way of doing this? (I am asking this question keeping Hibernate search in mind, but there seems to be no equivalent for Hibernate search in JPA) A: What do you mean under "enterprise"-way? Hibernate is pretty enterprisish as most of Fortune-500 companies actually use that in one or another way. Though latest Hibernate Search version is still in beta, that's probably not what most of the enterprises will accept. But there is a stable release you can probably use. And you can still use Apache Lucene to index your CLOBs and search in the index instead of DB. That's what basically Hibernate Search is also doing under the hood. And that's the aproach used by many companies. UPDATE: I never used Hibernate Search as a separate product and what they say in their documentation is that Hibernate Core is a requirement. But you can still try plain Lucene instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Check if string appears within node value in XSLT I have the following XML: <nodes> <node> <articles>125,1,9027</articles> </node> <node> <articles>999,48,123</articles> </node> <node> <articles>123,1234,4345,567</articles> </node> </nodes> I need to write some XSLT which will return only nodes which have a paricular article id, so in the example above, only those nodes which contain article 123. My XSLT isn't great, so I'm struggling with this. I'd like to do something like this, but I know of course there isn't an 'instring' extension method in XSLT: <xsl:variable name="currentNodeId" select="1234"/> <xsl:for-each select="$allNodes [instring(articles,$currentNodeId)]"> <!-- Output stuff --> </xsl:for-each> I know this is hacky but not sure of the best approach to tackle this. The node-set is likely to be huge, and the number of article ids inside the nodes is likely to be huge too, so I'm pretty sure turning that splitting the value of the node and turning it into a node-set isn't going to be very efficient, but I could be wrong! Any help as to the best way to do this would be much appreciated, thanks. A: XSLT 2.0 : This will match articles which have exactly 123 somewhere as text. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:variable name="id" select="123"/> <xsl:template match="/"> <xsl:for-each select="//node[matches(articles, concat('(^|\D)', $id, '($|\D)'))]"> <xsl:value-of select="current()"/> </xsl:for-each> </xsl:template> </xsl:stylesheet> Sample input : <?xml version="1.0" encoding="utf-8"?> <nodes> <node> <articles>1234,1000,9027</articles> </node> <node> <articles>999,48,01234</articles> </node> <node> <articles>123,1234,4345,567</articles> </node> <node> <articles> 123 , 456 </articles> </node> </nodes> Output : 123,1234,4345,567 123 , 456 I don't know how to do this efficiently with XSLT 1.0 but as the OP said he is using XSLT 2.0 so this should be a sufficient answer. A: In XSLT 1.0 you can use this simple solution, it uses normalize-space, translate, contains, substring, string-length functions. Sample input XML: <nodes> <node> <articles>125,1,9027</articles> </node> <node> <articles>999,48,123</articles> </node> <node> <articles>123,1234,4345,567</articles> </node> <node> <articles> 123 , 456 </articles> </node> <node> <articles>789, 456</articles> </node> <node> <articles> 123 </articles> </node> <node> <articles>456, 123 ,789</articles> </node> </nodes> XSLT: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:variable name="id" select="123"/> <xsl:template match="node"> <xsl:variable name="s" select="translate(normalize-space(articles/.), ' ', '')"/> <xsl:if test="$s = $id or contains($s, concat($id, ',')) or substring($s, string-length($s) - string-length($id) + 1, string-length($id)) = $id"> <xsl:copy-of select="."/> </xsl:if> </xsl:template> <xsl:template match="/nodes"> <xsl:copy> <xsl:apply-templates select="node"/> </xsl:copy> </xsl:template> </xsl:stylesheet> Output: <nodes> <node> <articles>999,48,123</articles> </node> <node> <articles>123,1234,4345,567</articles> </node> <node> <articles> 123 , 456 </articles> </node> <node> <articles> 123 </articles> </node> <node> <articles>456, 123 ,789</articles> </node> </nodes>
{ "language": "en", "url": "https://stackoverflow.com/questions/7572215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Login via curl to webmail I wanna login to my university webmail page by curllib. I program following code to do that: $url = 'http://eetd.kntu.ac.ir/mda2.asp'; $reffer = 'http://sabamail.kntu.ac.ir:3000/WorldClient.dll?View=Main'; $agent = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax)"; $cookie_file_path = "/var/www/cookie.txt"; $post_fields = 'dom=ee.kntu.ac.ir&usr=hoseini&password=*****'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields); curl_setopt($ch,CURLOPT_REFERER,$reffer); curl_setopt($ch, CURLOPT_USERAGENT, $agent); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path); curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path); $result = curl_exec($ch); curl_close($ch); echo $result; but it will redirect to 1 again with out showing your password is wrong! where is problem? A: If you actually examine the source code of the login page, you will find the password element is named pd and not password. Therefore you need to change this: $post_fields = 'dom=ee.kntu.ac.ir&usr=hoseini&password=*****'; ...to this: $post_fields = 'dom=ee.kntu.ac.ir&usr=hoseini&pd=*****'; This may not be the only issue, but it is certainly an issue. A: site says: <input type="password" name="pd" size="18"> you set: $post_fields = 'dom=ee.kntu.ac.ir&usr=hoseini&password=*****'; change password to pd
{ "language": "en", "url": "https://stackoverflow.com/questions/7572216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: A table value places a checkmark in a checkbox on a form How do you have MS Access place a checkmark in a checkbox control based off a value in a table? A: The usual way is to bind the form to a query or table and bind the control to the relevant field (column).
{ "language": "en", "url": "https://stackoverflow.com/questions/7572217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to do a function for a sprite or menu in cocos2d? I created two CCLayers, one is gamelayer, another is howlayer. The code of gamelayer.m is -(id)init{ if (self = [super init]) { CCSprite *gamebg = [CCSprite spriteWithFile:@"bg.png"]; gamebg.anchorPoint = CGPointZero; [self addChild:gamebg z:0 tag:1]; HowLayer *howLayer = [HowLayer node]; [self addChild:howLayer]; [self schedule:@selector(showthegamecontent:) interval:0.4]; } return self; } the code of howlayer is -(id)init{ if (self=[super init]) { CCSprite *howbg = [CCSprite spriteWithFile:@"translucentbg.png"]; howbg.anchorPoint = CGPointZero; [self addChild:howbg z:5 tag:1]; CCMenuItem *howmenu = [CCMenuItemImage itemFromNormalImage:@"how.png" selectedImage:@"how.png" target:self selector:@selector(startgame:)]; CCMenu *ccMenuhowmenu = [CCMenu menuWithItems:howmenu, nil]; ccMenuhowmenu.position=ccp(517,384); [self addChild:ccMenuhowmenu z:5 tag:2]; } return self; } -(void)startgame:(id)sender{ [self removeAllChildrenWithCleanup:YES]; } I want to do function like this: When I click the menu on howlayer, the Howlayer will be removed (I have done), and then the game starts, calls the selector 'showthegamecontent', so how should I do? A: Simple hack in your howlayer: -(void)startgame:(id)sender{ gameLayer* parent = (gameLayer*) self.parent; [parent showthegamecontent]; } but it may leave you with a warning.. But it works.. The implementation without warning is that you have to store a reference to the parent with you init. Which i feel its unnecessary as you only need to reference it once.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Could you recommend an IDE to develop HTML5 canvas applications We're starting to develop a Web application that will have some complex functionality written in HTML5 canvas. Please, could you recommend any good IDE (open or commercial), or a toolset to develop/debug this kind of applications? Thanks in advance. A: I prefer Aptana Studio for web applications development as this offers very good support for javascript, HTML and even new libraries like coffee script. Aptana Studio's latest release in beta also has support for HTML5. A: This might not quite be what you're looking for... but you can take a look at jsFiddle - http://jsfiddle.net/ If you can't use it for major parts of your web app, you can at least put it to use as a debug tool.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: CSS gradient on a pseudo element in IE9 Knows someone a solution for setting a CSS gradient on a pseudo element in IE9? This is my approach: http://jsbin.com/iquhut/edit#html,live It seems like filter does not apply on pseudo elements or I missed something out? A: Use images. IE9 does not support css gradients (-ms- prefix works for IE10 only), and dx filters (which you used in exapmle code) are very bad for performance (and buggy). Alternatively, you can use canvas to render gradient, and then set that gradient as data-url background for your element. Alternatively, you might use SVG gradient backgrounds, but then you will need to hide them from other browsers (good thing, we still have conditional comments in ie9). Keep in mind they are buggy too. But not as buggy as filters. A: The almost same effect is possible with a simple box-shadow by setting a negative spread-radius. inset? && [ <offset-x> <offset-y> <blur-radius>? <spread-radius>? <color>? ] Example: ( http://jsbin.com/ekehoz/edit#html,live ) box-shadow: 0px -15px 30px -10px #888;
{ "language": "en", "url": "https://stackoverflow.com/questions/7572231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Django QuerySets - with a class method Below is a stripped down model and associated method. I am looking for a simple way upon executing a query to get all of the needed information in a single answer without having to re-query everything. The challenge here is the value is dependent upon the signedness of value_id. class Property(models.Model): property_definition = models.ForeignKey(PropertyDefinition) owner = models.IntegerField() value_id = models.IntegerField() def get_value(self): if self.value_id < 0: return PropertyLong.objects.get(id=-self.value_id) else: return PropertyShort.objects.get(id=self.value_id) Right now to get the "value" I need to do this: object = Property.objects.get(property_definition__name="foo") print object.get_value() Can someone provide a cleaner way to solve this or is it "good" enough? Ideally I would like to simply just do this. object = Property.objects.get(property_definition__name="foo") object.value Thanks A: this is a bad design. as Daniel Roseman said, take a look at generic foreign keys if you must reference two different models from the same field. https://docs.djangoproject.com/en/1.3/ref/contrib/contenttypes/#generic-relations A: Given this is a bad design. You can use the builtin property decorator for your method to make it act as a property. class Property(models.Model): property_definition = models.ForeignKey(PropertyDefinition) owner = models.IntegerField() value_id = models.IntegerField() @property def value(self): if self.value_id < 0: return PropertyLong.objects.get(id=-self.value_id) else: return PropertyShort.objects.get(id=self.value_id) This would enable you to do what you'd ideally like to do: Property.objects.get(pk=1).value But I would go as far as to call this "cleaner". ;-) You could go further and write your own custom model field by extending django.models.Field to hide the nastiness in your schema behind an API. This would at least give you the API you want now, so you can migrate the nastiness out later. That or the Generic Keys mentioned by others. Choose your poison... A: Model inheritance could be used since value is not a Field instance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Custom CMDIChildWndEx template class linking errors Ok, I have defined the template class, which compiles as expected, when I implement this class in a function of the CMainFrame of the application and compile it, I receive unresolved linking errors. void CMainFrame::OnFunc() { CTestList<CMyClass> list; } The linking errors: 1>mainfrm.obj : error LNK2019: unresolved external symbol "public: virtual __thiscall CTestList<class CMyClass>::~CTestList<class CMyClass>(void)" (??1?$CTestList@VCWnd@@@@UAE@XZ) referenced in function "protected: void __thiscall CMainFrame::OnFunc(void)" (?OnFunc@CMainFrame@@IAEXXZ) 1>mainfrm.obj : error LNK2019: unresolved external symbol "public: __thiscall CTestList<class CMyClass>::CTestList<class CMyClass>(void)" (??0?$CTestList@VCWnd@@@@QAE@XZ) referenced in function "protected: void __thiscall CMainFrame::OnFunc(void)" (?OnFunc@CMainFrame@@IAEXXZ) I've checked all the obvious missing headers, undefined functions, etc, but still it throws these errors at me, the files are all part of the main application and are not in static/shared libs, as this is the error I would expect if i'd done so.. Here is the basic definition of the template class cut right down, I've followed what I believe to be the correct path in constructing the class, and all my research seems to suggest its correct. Really need to get this nailed ASAP, so if you guys & girls could help I would be very grateful. Cheers, DIGGIDY ///////////////////////////////////////////////////////////////////////////// // CTestList class template <class T> class CTestList : public CMDIChildWndEx { //DECLARE_DYNAMIC(CTestList<T>) public: CTestList(); virtual ~CTestList(); protected: // Generated message map functions afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// // CTestList //IMPLEMENT_DYNCREATE(CTestList<SDCM_OBJECT_TYPE>, CMDIChildWndEx) template <class T> CTestList<T>::CTestList() { } template <class T> CTestList<T>::~CTestList() { } BEGIN_TEMPLATE_MESSAGE_MAP(CTestList, T, CMDIChildWndEx) ON_WM_CREATE() END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CTestList message handlers template <class T> int CTestList<T>::OnCreate(LPCREATESTRUCT lpCreateStruct) { if ( CMDIChildWndEx::OnCreate(lpCreateStruct) == -1 ) return -1; // this removes the crappy un-drawn client edge on screen ModifyStyleEx(WS_EX_OVERLAPPEDWINDOW, WS_EX_WINDOWEDGE); return 0; } A: Your template code is not inlined in the header file. When the template class cpp file is being compiled the compiler doesn't know what instances of T will be required. When your main file is being compiled and you need to instantiate a CTestList the compiler only has the template header file. You need to add a force explicite template instantiation to your template .cpp file - so at the moment this is compiled it will generation the correct CMyClass instantiation of the template.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Learning wxPython, basic thing I want to display a button that when I click adds to the main panel a static text that automatic adds to the BoxSizer of the panel. I have this code but dosen't work good. Anyone can help me? I am desperate. Thanks import wx class MyApp(wx.App): def OnInit(self): self.frame = MainFrame(None,title='') self.SetTopWindow(self.frame) self.frame.Show() return True class MainFrame(wx.Frame): def __init__(self, *args, **kwargs): super(MainFrame, self).__init__(*args, **kwargs) #Atributos self.panel = MainPanel(self) self.CreateStatusBar() #Layout self.sizer = wx.BoxSizer(wx.HORIZONTAL) self.sizer.Add(self.panel,1,wx.EXPAND) self.SetSizer(self.sizer) class MainPanel(wx.Panel): def __init__(self, parent): super(MainPanel, self).__init__(parent) #Atributos bmp = wx.Bitmap('./img.png',wx.BITMAP_TYPE_PNG) self.boton = wx.BitmapButton(self,bitmap=bmp) # Layout self.sizer = wx.BoxSizer(wx.HORIZONTAL) self.sizer.Add(self.boton) self.SetSizer(self.sizer) self.Bind(wx.EVT_BUTTON,self.add,self.boton) def add(self,event): self.sizer.Add(wx.StaticText(self,label='Testing')) if __name__ == "__main__": app = MyApp(False) app.MainLoop() A: If your problem is that your text initially shows up behind the button when it is clicked, you can force the sizer to update by adding a call to your Panel's Layout method. class MainPanel(wx.Panel): def __init__(self, parent): super(MainPanel, self).__init__(parent) #Atributos bmp = wx.Bitmap('./img.png',wx.BITMAP_TYPE_PNG) self.boton = wx.BitmapButton(self,bitmap=bmp) # Layout self.sizer = wx.BoxSizer(wx.HORIZONTAL) self.sizer.Add(self.boton) self.SetSizer(self.sizer) self.Bind(wx.EVT_BUTTON,self.add,self.boton) def add(self,event): self.sizer.Add(wx.StaticText(self,label='Testing')) self.Layout()
{ "language": "en", "url": "https://stackoverflow.com/questions/7572243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to catch keyboard keys if jqueryUI datepicker is active jqgrid column contains jqueryUI DataPicker used in inline edit mode. If DataPicker input element has focus and Ctrl+S or some other key is is pressed, body_onkeydown is not executed: IE9 invokes ctrl+s default behaviour (save dialog). In FireFox body_onkeydown is also not executed. How to fix this code so keys can catched if DatePicker has focus ? DatePicker is defined as: $(elem).datepicker({ dateFormat: 'dd.mm.yy', autoSize: true, showOn: 'button', changeYear: true, changeMonth: true, showButtonPanel: true, showWeek: true }); Code used to catch ctrl+s keypress is: $(function () { $("html").keydown(body_onkeydown); }); function body_onkeydown(evt) { // Why this function is not executed if datepicker has focus? if (evt.ctrlKey) { switch (evt.keyCode) { case 83: $("#grid_savebutton").click(); break; } cancel(evt); return false; } function cancel(evt) { evt.returnValue = false; evt.keyCode = 0; evt.cancelBubble = true; evt.preventDefault(); evt.stopPropagation(); } A: It's a good question! In the code of jqGrid you can fine sometime return false or stopPropagation inside of event handles which I personally find unneeded. In your case the problem make the line 8237 of the jquery.jqGrid.src.js (in version 4.1.2) or the line 87 of the grid.inlinedit.js (see here): e.stopPropagation(); If you comment the like the inline editing will not more stop propagation of the keydown event and how you could see on the demo you will be able to catch Ctrl+S during inline editing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: replace all but - ,+, and . I'm working on a donation webapp, and I need to format a string the will leave minuses (-), pluses (+), and decimals (.). I want people to be able to format their dollar amounts how they want, but leave the numbers and decimals as is. I currently have the following code: var raised = $('#raised').val().replace(/\D/g,''); Any help? Thanks! UPDATE Let me explain a little more about why this is an easy/quick way to validate the input. This is going to be something that administration is going to use one time only, with only one person in charge. It's not going to be something where multiple users input to submit actual money. I agree that this could be much better planned, but this is more of a rush job. In fact, showing you what I have done is going to be the quickest way to show you: http://www.cirkut.net/sub/batterydonate-pureCSS/ This is going to be projected during an event/auction so people kind of have an idea of how much money has been donated. The person in charge of typing in donations is competent enough to type valid inputs, so I was putting together what I could as quickly as possible (the entire thing needs to be done by noon tomorrow). But anyways I found what I needed. Thanks a lot everyone! A: To do exactly what you're asking, you could use this regex: var raised = $('#raised').val().replace(/[^-+.\d]/g,''); But be advised, you'll still need to verify that the returned string is a valid number, because strings like '---' and '+++' will pass. This, perhaps, is not even something you want to do on the client-side. A: Try the following regex: .replace(/[^\d\-+\.]/g, '') Since this doesn't guarantee you have a valid number and not something like +-12.34.56--1, You can then validate that you have a valid number with something like: /^[-+]?\d+(\.\d+)?$/ A: A regular expression character class can be negated by adding a ^ symbol to the beginning. In your case, this makes it fairly simple: you could add all the characters you want to keep in a character class and negate it. var raised = $('#raised').val().replace(/[^\d\.\+\-]/g,''); Hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: what is the best way to upload a csv file into a MS SQL table? Several approaches: * *Use SQL Bulk Import Stored Proc and call the stored proc with the file path *Use SqlBulkCopy in System.Data.SqlClient dll *Read the file line by line and then insert into a table row by row *Any other ways? Which one is best? I just want the user to select a file from asp.net webpage. And then click on Upload button to store the file in DB. Secondly, do I need to move the file in server's memory before the file is copied into db table? A: * *The DB won't know of the file because everything should be decoupled and layered. Saving the file to some shared location adds overhead and tidy ups etc *Yes *Surely you want this to be an atomic operation. 10k rows would be 10 round trips with a client side transaction running. If not atomic, then you'd need staging tables and tidy ups *Parse in c#, send to the DB with a table valued parameter. Otherwise, probably nothing same and/or realistic...
{ "language": "en", "url": "https://stackoverflow.com/questions/7572253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Login activity problem Im currently developing an application for android, the first screen of the application is the LoginActivity, it is authenticating with facebook and a facebook login dialog is shown on users request. The whole login process is working great, when you have logged in user are brought to a new activity. I've created a logout function in that activity which logging the user out of facebook in the whole application, but. If you press the "back-button" on an android device when the user is at the activity where you are when you have logged in the loginactivity is shown for the user. I want to make it impossible for the user to show the loginactivity but i don't know how. When the user successfully logging in from the beggining the following lines are runned: Intent intent = new Intent().setClass(LoginActivity.this, LocationActivity.class); startActivity(intent); And when the user successfully logged out from the MainActivity the following lines are runed: ApplicationController appController = (ApplicationController)getApplicationContext(); appController.setfullnametoNull(); appController.setuseridtoNull(); finish(); Any suggestions on how to make it impossible for the user to get to the loginactivity when the user is currently logged in? A: finish() the activity and if the user navigates to other app without log out then you should check in the login activity when comes back to app and redirect the user to appropriate activity. You need to save the login credentials for this. You can use SharedPreferences for this. A: Use an broadcast intent which you send from the activity you start after the login activity. Then use the login activity as the receiver of the broadcast intent. Then you can use this broadcast to call finish() for the login activity. This way the login activity should get out of the android activity stack. A: Not sure if I understood your question correctly... you are saying after you logged in and another Activity is started the user hits the back button and the activity is shown again? If yes: you can prevent this with starting the activity using startActivityForResult(intent, REQUEST_CODE) instead of using startActivity(intent). Then you have to add this method: @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE) { finish(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7572254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Creating function arguments from a named list (with an application to stats4::mle) I should start by saying what I'm trying to do: I want to use the mle function without having to re-write my log likelihood function each time I want to try a different model specification. Because mle is expecting a named list of starting values, you apparently cannot just write the log-likelihood function as taking a vector of parameters. A simple example: Suppose I want to fit a linear regression model via maximum likelihood and at first, I'm ignoring one of my predictors: n <- 100 df <- data.frame(x1 = runif(n), x2 = runif(n), y = runif(n)) Y <- df$y X <- model.matrix(lm(y ~ x1, data = df)) # define log-likelihood function ll <- function(beta0, beta1, sigma){ beta = matrix(NA, nrow=2, ncol=1) beta[,1] = c(beta0, beta1) -sum(log(dnorm(Y - X %*% beta, 0, sigma))) } library(stats4) mle(ll, start = list(beta0=.1, beta1=.2, sigma=1) Now, if I want to fit a different model, say: m <- lm(y ~ x1 + x2, data = df) I cannot re-use my log-likelihood function--I'd have to re-write it to have the beta3 parameter. What I'd like to do is something like: ll.flex <- function(theta){ # theta is a vector that I can use directly ... } if I could then somehow adjust the start argument in mle to account for my now vector-input log-likelihood function, or barring that, have a function that constructs the log-likelihood function at run-time, say by constructing the named list of arguments and then using it to define the function e.g., something like this: X <- model.matrix(lm(y ~ x1 + x2, data = df)) arguments <- rep(NA, dim(X)[2]) names(arguments) <- colnames(X) ll.magic <- function(bring.this.to.life.as.function.arguments(arguments)){...} Update: I ended up writing a helper function that can add an arbitrary number of named arguments x1, x2, x3... to a passed function f. add.arguments <- function(f,n){ # adds n arguments to a function f; returns that new function t = paste("arg <- alist(", paste(sapply(1:n, function(i) paste("x",i, "=",sep="")), collapse=","), ")", sep="") formals(f) <- eval(parse(text=t)) f } It's ugly, but it got the job done, letting me re-factor my log-likelihood function on the fly. A: You can use the mle2 function from the package bbmle which allows you to pass vectors as parameters. Here is some sample code. # REDEFINE LOG LIKELIHOOD ll2 = function(params){ beta = matrix(NA, nrow = length(params) - 1, ncol = 1) beta[,1] = params[-length(params)] sigma = params[[length(params)]] minusll = -sum(log(dnorm(Y - X %*% beta, 0, sigma))) return(minusll) } # REGRESS Y ON X1 X <- model.matrix(lm(y ~ x1, data = df)) mle2(ll2, start = c(beta0 = 0.1, beta1 = 0.2, sigma = 1), vecpar = TRUE, parnames = c('beta0', 'beta1', 'sigma')) # REGRESS Y ON X1 + X2 X <- model.matrix(lm(y ~ x1 + x2, data = df)) mle2(ll2, start = c(beta0 = 0.1, beta1 = 0.2, beta2 = 0.1, sigma = 1), vecpar = TRUE, parnames = c('beta0', 'beta1', 'beta2', 'sigma')) This gives you Call: mle2(minuslogl = ll2, start = c(beta0 = 0.1, beta1 = 0.2, beta2 = 0.1, sigma = 1), vecpar = TRUE, parnames = c("beta0", "beta1", "beta2", "sigma")) Coefficients: beta0 beta1 beta2 sigma 0.5526946 -0.2374106 0.1277266 0.2861055 A: It might be easier to use optim directly; that's what mle is using anyway. ll2 <- function(par, X, Y){ beta <- matrix(c(par[-1]), ncol=1) -sum(log(dnorm(Y - X %*% beta, 0, par[1]))) } getp <- function(X, sigma=1, beta=0.1) { p <- c(sigma, rep(beta, ncol(X))) names(p) <- c("sigma", paste("beta", 0:(ncol(X)-1), sep="")) p } set.seed(5) n <- 100 df <- data.frame(x1 = runif(n), x2 = runif(n), y = runif(n)) Y <- df$y X1 <- model.matrix(y ~ x1, data = df) X2 <- model.matrix(y ~ x1 + x2, data = df) optim(getp(X1), ll2, X=X1, Y=Y)$par optim(getp(X2), ll2, X=X2, Y=Y)$par With the output of > optim(getp(X1), ll2, X=X1, Y=Y)$par sigma beta0 beta1 0.30506139 0.47607747 -0.04478441 > optim(getp(X2), ll2, X=X2, Y=Y)$par sigma beta0 beta1 beta2 0.30114079 0.39452726 -0.06418481 0.17950760 A: It might not be what you're looking for, but I would do this as follows: mle2(y ~ dnorm(mu, sigma),parameters=list(mu~x1 + x2), data = df, start = list(mu = 1,sigma = 1)) mle2(y ~ dnorm(mu,sigma), parameters = list(mu ~ x1), data = df, start = list(mu=1,sigma=1)) You might be able to adapt this formulation for a multinomial, although dmultinom might not work -- you might need to write a Dmultinom() that took a matrix of multinomial samples and returned a (log)probability. A: The R code that Ramnath provided can also be applied to the optim function because it takes vectors as parameters also.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: In ruby how to use class level local variable? (a ruby newbie's question) So suppose I have this (not working): class User description = "I am User class variable" def print puts description end end So, how should I use the var description, how to pass this into a method as a default parameter, or used in the method directly? Thanks.. A: In your case, the description is only local variable. You can change this scope using special characters @, @@, $: a = 5 defined? a => "local-variable" @a = 5 defined? @a => "instance-variable" @@a = 5 defined? @@a => "class variable" $a = 5 defined? $a => "global-variable" For your purpose, I think it might be using by this way class User def initialize(description) @description = description end def print puts @description end end obj = User.new("I am User") obj.print # => I am User A: You can access the class-scope using define_method. class User description = "I am User class variable" define_method :print do puts description end end > User.new.print I am User class variable => nil I don't think it's good idea, though :) A: To define a class variable, use an @@: class User @@description = "I am a User class variable" def print puts @@description end end A: Instance variables must be prefixed with an @ and are not accessible from outside. Class variables must be prefixed with an @@. The first time you use this variable anywhere in code, it will be initialized. If you want to access the value from outside: attr_reader :description http://rubylearning.com/satishtalim/tutorial.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7572265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: using $.each to addClass to elements I'm trying to style a sub-set of anchors using an array HTML & CSS: <div> <a href="#1">one</a> <a href="#2">two</a> <a href="#3">three</a> <a href="#4">four</a> <a href="#5">five</a> <a href="#6">six</a> <a href="#7">seven</a> </div> .hilight { background: #f00; } e.g. how would I add the class 'hilight' to anchors 2, 5, & 6... Having tested this: $("a[href='#5']").addClass('hilite'); I tried the the following with $.each(), which doesn't work. I guess I'm iterating over each anchor 3 times, but I didn't expect NO output! var arr = ["#2", "#5", "#6"]; $.each(arr, function(index, value) { $("a[href=value]").addClass('hilite');' }); Can someone point me in the right direction please :) A: Your code doesn't work because $("a[href=value]") doesn't exist. You wan to use $("a[href='"+value+"']") instead, where value will be "replace" by the value of the variable value. Here a fix: var arr = ["#2", "#5", "#6"]; $.each(arr, function(index, value) { $("a[href='"+value+"']").addClass('hilite'); }); A: You dont need each at all, you can just use all selectors separated by commas. $("a[href='#2'], a[href='#5'], a[href='#6']").addClass('hilite'); A: If you don't have a TON of them, it might be simpler to just do... $("a[href='#2'], a[href='#5'], a[href='#6']").addClass('hilite'); To do the same thing, but more dynamically (for John)... var arr = ["#2", "#5", "#6"]; $("a[href='"+arr.join("'], a[href='")+"']").addClass('hilite'); This assumes that arr always has at least one element. A: The jQuery addClass() method has the ability to create a function to determine what class to add. You can use this to determine if the element is a one that needs the class added. This would be more efficient than running the selector $("a[href='"+value+"']") for each value in the array as it would only traverse the DOM once instead of n(size of the array) times. var arr = ["#2", "#5", "#6"]; $("a").addClass(function () { if (arr.indexOf($(this).attr("href")) != -1) { return "hilight"; } }); Here is a demonstration http://jsfiddle.net/VqLnt/3/ I also want to note that your CSS class is named hilight but the class you are trying to add in JavaScript is hilite. This is probably a typo but just want you to be aware.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to encode a hyperlink in CSV formatted file? When I try to encode a HTML anchor link in CSV file cell it becomes corrupted and not readable by Excel. Is there some sort of non-HTML solution or format to encode a hyperlink in CSV file cell? A: For when automagicalism doesn't work, and you're definitely using Excel, use this as the field content. =HYPERLINK("http://stackoverflow.com") A: This worked for me: * *Use the =HYPERLINK function, the first parameter is the web link, the second is the cell value. *Put " quotes around the entire function. *Escape the internal quotes within the function with two sets of quotes, i.e., "" Here's a four-column comma-delimited example.csv: 5,6,"=HYPERLINK(""http://www.yahoo.com"";""See Yahoo"")",8 When a spreadsheet program (LibreOffice, etc.) opens this .csv, it creates an active link for you. A: What worked for me in Excel 2003 - output to your CSV the statement: CELLVALUE="=HYPERLINK("+QM+URLCONTENTS+QM+";"+QM+"URLDISPLAYNAME"+QM+")" * *note the semicolon ; use in the hyperlink. I've found the comma not to work for me in Excel 2003. *Depending on the script or language you use quotemarks could be handled differently. The cellvalue you put into the CSV before you import it into Excel should look exactly like this: "=HYPERLINK("URLCONTENTS";"URLDISPLAYNAME")" where: * *CELLVALUE is the output written to the CSV *QM is the ASCII value of ["] -> (ASCII 34) *URLCONTENTS is the full URL to the page you want to link to. -URLDISPLAYNAME is the text you see in the Excel cell. You can also use relative paths and set a base location in Excel. File/Properties > Tab Summary > Field Hyperlink Base. Use as fieldvalue something like http://www.SITENAME.com/SUB_LOCATION/../SUB_LOCATION that sets your starting point so you can click it in Excel. Of course, you don't have to use SUB_LOCATIONs if the sitename itself already will resolve successfully for your relative path. What I couldn't find is how to make the links automatically underlined in Excel. From other tips found in this article: Format manually all linkcells as underlined and darkblue (for example) and then the standard functionality appears with already visited links turning into another color. A: A CSV file is simply text - it's up to the loading program how it chooses to interpret the text. If Excel is complaining when you feed it "<a href=\"blah\">Link</a>", "another cell" then try just having the raw URL and you might find Excel will automagically turn it into a link. But in general Excel doesn't process HTML, so expecting it render HTML from a CSV file is asking too much.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "53" }
Q: Conditional Formatting in Excel using Alphanumerics I have a conditional format in Excel that is displaying the up/down arrows based on certain values. This works just fine. However, in my spreadsheet (which is largely controlled by VBA) the user has the ability to review data in a 'grade' display (L=1,M=3,H=5) rather than the 1/3/5 score. I have a custom function that can convert the L/M/H to a number, but I can't figure out how to incorporate this into the conditional format. I can do it in a normal conditional format, but I want the up/down arrows icon set. I'd remove the conditional formatting and apply an icon to the cell with VBA but I don't think that's possible. Any help? A: You could either: Mimic Conditional Formatting Forget conditional formatting and use excel 2003 type methods with arrows and Wingdings font. Looks very similar, Andy Pope has a good example:Mimic 2007 Conditional Formatting Icon Use an invisible helper column The hidden helper column will display the numeric values 1,3,5 based on the actual cells L,M,H. Then in the cell with the L,M,H, you add the conditional and set it to the value of the helper column. A: What I ended up doing was adding an additional cell to the right that used a UDF to convert the cell values to numbers. I then applied the conditional formatting to this new cell and set it to to display the icon only. By locking the icon cell and protecting the worksheet (was going to protect anyways) the field is never user editable which is exactly what I wanted.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change ProgressBar style in ListFragment under compatibility library? The progress bar is large one by default in ListFragment ProgressBar progress = new ProgressBar(context, null, android.R.attr.progressBarStyleLarge); Is the only way to change it using reflection? A: I believe you should be able to subclass it and override the onCreate() with your custom layout. I haven't done it with the ProgressBar, but that's how I customized the ProgressDialog.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Dev express ASPXGridview close row after insert. e.cancel has gone? How do you close a row on an ASPXGridView after running the RowUpdated event serverside. In the 9.3 version, you just needed to call to close the row after an insert, but grid.CancelEdit() e.cancel = true I now have v11 and the e.cancel option has been removed from DevExpress.Web.Data.ASPxDataUpdatedEventArgs, however, its still showing on the v11 API http://documentation.devexpress.com/#AspNet/DevExpressWebASPxGridViewASPxGridView_RowUpdatingtopic A: It seems you are talking about two different events: * *ASPxGridView.RowUpdating *ASPxGridView.RowUpdated The ASPxGridView.RowUpdating event offer the eventArgs' e.Cancel property for canceling this event. The ASPxGridView.RowUpdated event does not offer it, because the DataRow is already updated and the changes are posted to the underlying data source.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Stuck in glDrawElements I have a very strange problem. My game engine performs loading of model asynchronously. After that it is added to the rendering loop. The problem is that sometimes (and it's absolutely random) after model was loaded the execution freezes at glDrawElements. I don't get any EXC_BAD_ACCESS or smth like that. It seems that all execution is performed inside glDrawElements in some infinite loop. Here is the snapshot that I made in profiler: Maybe someone knows how glDrawElements works internally and can point me to the possible reason of the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is the purpose of the tilde in this situation? What could be the purpose of the tilde in this code block? public override int GetHashCode() { return ~this.DimensionId.Id ^ this.ElementId.Id; } ^ Operator (C# Reference) Visual Studio 2010 Binary ^ operators are predefined for the integral types and bool. For integral types, ^ computes the bitwise exclusive-OR of its operands. For bool operands, ^ computes the logical exclusive-or of its operands; that is, the result is true if and only if exactly one of its operands is true. ~ Operator (C# Reference) Visual Studio 2010 The ~ operator performs a bitwise complement operation on its operand, which has the effect of reversing each bit. Bitwise complement operators are predefined for int, uint, long, and ulong. The ~ (tilde) operator performs a bitwise complement on its single integer operand. (The ~ operator is therefore a unary operator, like ! and the unary -, &, and * operators.) Complementing a number means to change all the 0 bits to 1 and all the 1s to 0s What would be a reason why it would be used in this context (as opposed to simply excluding it)? A: It's simply one way of generating a hash code. I'm not a huge fan of XORs in hash codes unless you want something that's order-independent, but it's a reasonable way of flipping bits in a reasonably arbitrary but repeatable way. Basically you've got two 32-bit values here, which you need to combine in some form to create another 32-bit value. The code could have just XORed the values together without any bitwise complement: return DimensionId.Id ^ ElementId.Id; ... but that would always give zero for cases where ElementId.Id == DimensionId.Id, which probably isn't ideal. On the other hand, we now always end up with -1 if the two IDs are the same, as noted in comments (doh!). On the other hand, it makes the pair {6, 4} have a different hash code to {4, 6} whereas a simple XOR doesn't... it makes the ordering important, in other words. Again, that could be important if your real identifiers are likely to be taken from a relatively small pool. The XOR itself makes sure that a change to any bit in either ID makes a difference to the final hashcode. Personally I normally follow Josh Bloch's pattern from effective Java, e.g. unchecked { int hash = 17; hash = hash * 31 + DimensionId.Id; hash = hash * 31 + ElementId.Id; return hash; } ... but that's just because of some of the properties of hashing that way1, and it doesn't make the implementation you've shown "wrong" in any sense. 1 It seems to work pretty well at producing distinct values in a number of common scenarios. Obviously it can't prevent hash collisions, but if your IDs are actually generated from a sequence of 1, 2, 3... then this will do better at real-life collisions that an XOR. I did see a web page analyzing this approach and which numbers work well etc, but I can't remember where.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: how to change block view pagination style I previously posted this question on drupal stackoverflow, but I didn't get any answers. I'm trying to make 2 different pagination styles. One for page views, and the other for block views. The block view should display image arrows for previous and next. I tried the following, but it changes both styles function theme_pager_first($variables) { $text = $variables['text']; $text = "test123"; $element = $variables['element']; $parameters = $variables['parameters']; global $pager_page_array; $output = ''; // If we are anywhere but the first page if ($pager_page_array[$element] > 0) { $output = theme('pager_link', array('text' => $text, 'page_new' => pager_load_array(0, $element, $pager_page_array), 'element' => $element, 'parameters' => $parameters)); } return $output; } A: You could fudge something together with a bunch of theme override functions but really there's no need: you can just use good 'ol CSS. Just create rules like this: .block .pager-first a{display:inline-block;text-indent:-999em;background:url(/path/to/arrow.jpg) left top no-repeat;} .block .pager-last a{display:inline-block;text-indent:-999em;background:url(/path/to/arrow.jpg) right top no-repeat;} That will target just pagers that are inside a block, removing the next and previous text and adding your image in their place :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7572280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how can be possible to programmatically upload and retrieve photos from PicasaWeb in C# Is it possible to use PicasaWeb to host photos for my website? My requirement to upload and access within my ASP.NET Website. A: Yes, technically. You can use the Picasa Web Albums Data API to access the metadata about your images and then display them from Picasa. For an album, this is not a horrible idea, but I would not use this method for your site graphics. A: public string UploadImage(byte[] imageBytes_, string imageName_) { string url = string.Empty; try { PicasaEntry newPhoto = null; MemoryStream ms = new MemoryStream(); ms.Write(imageBytes_, 0, imageBytes_.Length); if (_albumFeed != null) { PicasaEntry photoEntry = new PhotoEntry(); photoEntry.MediaSource = new Google.GData.Client.MediaFileSource(ms, imageName_, "image/jpeg"); newPhoto = this._service.Insert<PicasaEntry>(new Uri(this._albumFeed.Post), photoEntry); } url = newPhoto.FeedUri; } catch (Exception ex) { throw new DneException("Error while uploading photo", ex ); } return url ; } I am uploading a zipped images and extracting using SharpZipLib library. I am getting each file in chunk of bytes and which I am converting into MemoryStream later to pass the MediaSource object. I am getting 400 Bad Request error each time. When I am passing FileStream, it works fine but doesn't work with MemoryStream
{ "language": "en", "url": "https://stackoverflow.com/questions/7572281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I check for a nil="true" value on XML that is passed back from webservice call? I am receiving xml from a webservice call that contains a nil="true": <cacheEntry> <systemFK nil="true"/> </cacheEntry> I used the Flex DataService (webservice) wizard to create the service objects for the cacheEntry component. This object will be serialized later on a different webservice call and stored in a database. I set a breakpoint on the set SystemFK method in the service object. It appears that the value passed in was an empty string! Allowing this value to be an empty string will cause problems in the webservice implementation in Java on the other side. Since the database value was null it is expecting a null in return, If I avoid setting this value, the serviceObject should send back a null which will make the database happy. My question is: How can I detect that a nil = true is present in the XML in order to avoid setting this value? A: For some reason the ActionScript XML parsers don't know about Booleans. Without seeing the code that got generated for you, my guess is that somehow you're getting the string "true", instead of true, and that's what's causing your problem. Make changes to the accessors to act as if @nil comes from the XML as a string, and then convert to Boolean manually.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572290", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to check if a row in a table has muti-byte characters in it in a MySQL database? I have a table which has column of descr which stores string values. Some of the values in descr has multi-byte characters in it and I want to know all those rows so I can remove those characters. How can I query the tables using MySQL functions to determine which rows have multi-byte characters. I am using MySQL version 5.1 A: SELECT ... FROM yourtable WHERE CHAR_LENGTH(descr) <> LENGTH(descr) char_length is multi-byte aware and returns the actual character count. Length() is a pure byte-count, so a 3-byte char returns 3. A: have you tried the collation and CHARSET functions on your descr column? You can find the description of this functions here: http://dev.mysql.com/doc/refman/5.1/en/information-functions.html I think for your need it fits better the COERCIBILITY function. You can do something like: select COERCIBILITY(descr, COLLATE utf8) from myTable; and if this function returns 0 then you must edit the line.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to "insert into table (col1, col2) values (select max(id) from table2, select id from table3); "? I am trying to create a many-many relationship between the max(id) in table1 with all the ids in table2, using a lookup table called table1_table2. Ultimately so that the rows in table1_table2 will be: table1_id, table2_id 30, 1 30, 2 30, 3 ... 30, 10000 How can I do this? I have tried insert into insert into table1_table2 (table1_id, table2_id) values (select max(id) from table2, select id from table3); and insert into insert into table1_table2 (table1_id, table2_id) select max(table1_id), table2_id from table1 join table1_table2 on table1_table2.table1_id = table1.id outer join table1_table2 on table1_table2.table2_id = table2.id; But neither seem to work A: You have 3 tables, I see. I guess you mean this: insert into table1_table2 (table1_id, table2_id) SELECT (select max(id) from table2) --- or perhaps: from table1 ? , id FROM table3 --- or perhaps: FROM table2 ? A: It sounds like this is what you want: INSERT INTO table1_table2 (table1_id, table2_id) SELECT MAX(table1.id), table2.id FROM table1, table2 GROUP BY table2.id;
{ "language": "en", "url": "https://stackoverflow.com/questions/7572295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to bind a List (one or more times)? I follow the Presentation Model pattern for coding some screens. * *I store some Beans in an ArrayList *I will display the content of this List in a JTable, thanks to an AbstractTableModel *I also want to display some records from this list in a Combo Box (in a form) and some others in a JList, at the same time *These three screens (and their model) are independent from each other How to manage add {one or more}/remove {one or more} on my List and view changes in "real-time" everywhere? I'm about to write my own ObservableList or implement that around an EventDispatcher... What do you think? PS: * *I know that in C# the BindingList helps for that purpose, what about Java? *I'm already able to display updates of each bean, thanks to PropertyChangeSupport. A: Let your AbstractTableModel implement ListModel, which is usable with both JComboBox andJList. You can forward methods to the default model implementations as required. Addendum: SharedModelDemo, mentioned in How to Use Tables, is an example that may get you started. It extends DefaultListModel implements TableModel, while you should do extends AbstractTableModel implements ListModel Addendum: For reference, here's an outline of the minimal implementation and three test instantiations. I've used the default combo and list implementations, but you can use the corresponding abstract implementations if necessary. public class SharedModel extends AbstractTableModel implements ComboBoxModel, ListModel { private ComboBoxModel comboModel = new DefaultComboBoxModel(); private ListModel listModel = new DefaultListModel(); //ComboBoxModel @Override public void setSelectedItem(Object anItem) { comboModel.setSelectedItem(anItem); } @Override public Object getSelectedItem() { return comboModel.getSelectedItem(); } // ListModel @Override public int getSize() { return listModel.getSize(); } @Override public Object getElementAt(int index) { return listModel.getElementAt(index); } @Override public void addListDataListener(ListDataListener l) { listModel.addListDataListener(l); } @Override public void removeListDataListener(ListDataListener l) { listModel.removeListDataListener(l); } // TableModel @Override public int getRowCount() { return 0; } @Override public int getColumnCount() { return 0; } @Override public Object getValueAt(int rowIndex, int columnIndex) { return null; } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { SharedModel sm = new SharedModel(); JTable table = new JTable(sm); JList list = new JList(sm); JComboBox check = new JComboBox(sm); } }); } } A: For the JComboBox and the JList you could simply reference sections of the ArrayList using the subList() method. This will work if you can easily identify the starting and ending locations within the ArrayList and the elements you need are sequential. If the situation is more dynamic than that you could implement custom List classes that took the ArrayList in the constructor and then apply whatever logic you need to return the appropriate records.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: HTTP could not register URL ... because TCP port ... is being used by another application First, I am not good in WCF. I have a WCF service hosted in WindowsService. Since sometime the service stoped to run because of the exception: HTTP could not register URL http://+:8092/MyService/ because TCP port 8092 is being used by another application. * *Nothing uses this port, it says the same about any port I tried. *SSL certificate is configured. There are many machines that can start this service, but the most required (customer's) machine cannot. I saw many posts in this site or anywhere else, but cannot find a solution. I never see the post like "It helped me". I am stuck several days already, help please. Below the data from config file: <system.serviceModel> <services> <service name="MyCompany.MyApp.MyAppService" behaviorConfiguration="MetadataSupport"> <host> <baseAddresses> <add baseAddress="http://localhost:8092/MyAppService" /> <add baseAddress="net.tcp://localhost:8093/MyAppService" /> <add baseAddress="net.pipe://localhost/" /> </baseAddresses> </host> <endpoint binding="wsDualHttpBinding" contract="MyCompany.MyApp.IMyAppService" /> <endpoint binding="netTcpBinding" contract="MyCompany.MyApp.IMyAppService" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> <endpoint address="tcpmex" binding="mexTcpBinding" contract="IMetadataExchange" /> </service> </services> <behaviors> <serviceBehaviors> <behavior name="MetadataSupport"> <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> <serviceMetadata httpGetEnabled="True" httpGetUrl="" /> <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> <serviceDebug httpHelpPageEnabled="True" includeExceptionDetailInFaults="True" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> A: You are using WCF duplex communication with wsDualHttpBinding. In this case, WCF creates a HTTP socket on port 8092 to service client callbacks. Clearly the client was conflicting with IIS 5.X. (I guess you have XP and IIS 5.x) To resolve this problem you have to provide a clientBaseAddress in the binding configuration on the client and specify a different port. Sample client configuration: I hope that this is really the problem in your machine, please notify me about the results of this solution. Good luck :-) A: Try running the windows service as someone with admin privileges. Certain versions of Windows (2008/Vista and up) are picky about who can open ports. If that helps, then you certainly don't want to actually run the service as an admin, but it at least points you in the permissions direction. Also, you mention an SSL cert, but it is an 'http' url, not 'https'. That seems unusual. A: I suggest to do the following diagnostics steps: Try hosting the WCF Service in a Self-Host manner (Console Application): * *use the class HttpServiceHost *use this binding: var binding = new HttpBinding(HttpBindingSecurityMode.Transport); *AddServiceEndpoint(typeof(YourServiceClass),binding,"https://url..."); If it works for you it seems that you have problems in configuring the WCF service to work under Managed-Windows Service. Lets me know your results :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7572305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Any neat way to limit significant figures with BigDecimal I want to round a Java BigDecimal to a certain number of significant digits (NOT decimal places), e.g. to 4 digits: 12.3456 => 12.35 123.456 => 123.5 123456 => 123500 etc. The basic problem is how to find the order of magnitude of the BigDecimal, so I can then decide how many place to use after the decimal point. All I can think of is some horrible loop, dividing by 10 until the result is <1, I am hoping there is a better way. BTW, the number might be very big (or very small) so I can't convert it to double to use Log on it. A: You can use the following lines: int digitsRemain = 4; BigDecimal bd = new BigDecimal("12.3456"); int power = bd.precision() - digitsRemain; BigDecimal unit = bd.ulp().scaleByPowerOfTen(power); BigDecimal result = bd.divideToIntegralValue(unit).multiply(unit); Note: this solution always rounds down to the last digit. A: Someone will probably come up with a better solution, but the first thing that comes to mind is chuck it in to a StringBuilder, check whether it contains a '.' and return an appropriate length substring. E.g.: int n = 5; StringBuilder sb = new StringBuilder(); sb.append("" + number); if (sb.indexOf(".") > 0) { n++; } BigDecimal result = new BigDecimal(sb.substring(0, n)); A: Why not just use round(MathContext)? BigDecimal value = BigDecimal.valueOf(123456); BigDecimal wantedValue = value.round(new MathContext(4, RoundingMode.HALF_UP)); A: The easierst solution is: int newScale = 4-bd.precision()+bd.scale(); BigDecimal bd2 = bd1.setScale(newScale, RoundingMode.HALF_UP); No String conversion is necessary, it is based purely on BigDecimal arithmetic and therefore as efficient as possible, you can choose the RoundingMode and it is small. If the output should be a String, simply append .toPlainString(). A: To me this seems as simple as: Given N = 5, D = 123.456789 * *get the string representation of the number, "123.456789" *retrieve the first N-1 digits of the number, "123.4" *evaluate D[N] and D[N+1], in this case "5" and "6" *6 meets the criteria for rounding up (6 > 4), therefore carry 1 and make D[N] = 5+1 = 6 *D post rounding is now 123.46 Order can be calculated using Math.floor(Math.log(D)). hope this helps. A: Since BigDecimal is basically a string, perhaps this: import java.math.BigDecimal; public class Silly { public static void main( String[] args ) { BigDecimal value = new BigDecimal("1.23238756843723E+5"); String valueString = value.toPlainString(); int decimalIndex = valueString.indexOf( '.' ); System.out.println( value + " has " + (decimalIndex < 0 ? valueString.length() : decimalIndex) + " digits to the left of the decimal" ); } } Which produces this: 123238.756843723 has 6 digits to the left of the decimal A: A.H.'s answer is technically correct, but here is a more general (and easier to understand) solution: import static org.bitbucket.cowwoc.requirements.core.Requirements.assertThat; /** * @param value a BigDecimal * @param desiredPrecision the desired precision of {@code value} * @param roundingMode the rounding mode to use * @return a BigDecimal with the desired precision * @throws NullPointerException if any of the arguments are null */ public BigDecimal setPrecision(BigDecimal value, int desiredPrecision, RoundingMode roundingMode) { assertThat("value", value).isNotNull(); assertThat("roundingMode", roundingMode).isNotNull(); int decreaseScaleBy = value.precision() - desiredPrecision; return value.setScale(value.scale() - decreaseScaleBy, roundingMode); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7572309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Actionscript code not executed without user interaction The following code works as expected: when a user clicks the button, the installer automatically launches. <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" creationComplete="applicationInit(event)"> <fx:Script> <![CDATA[ import flash.utils.setTimeout; import mx.events.FlexEvent; private var airSWF:Object; private var airSWFLoader:Loader = new Loader(); private var loaderContext:LoaderContext = new LoaderContext(); private function applicationInit(event:FlexEvent):void { this.loaderContext.applicationDomain = ApplicationDomain.currentDomain; this.airSWFLoader.contentLoaderInfo.addEventListener(Event.INIT, onAirInit); this.airSWFLoader.load(new URLRequest("http://airdownload.adobe.com/air/browserapi/air.swf"), loaderContext); } private function onAirInit(event:Event):void { this.airSWF = event.target.content; this.button.addEventListener(MouseEvent.CLICK, installApp); } private function installApp(event:MouseEvent):void { var url:String = "URL HERE"; var runtimeVersion:String = "2.7"; var arguments:Array = ["launchFromBrowser"]; this.airSWF.installApplication(url, runtimeVersion, arguments); } ]]> </fx:Script> <s:Button id="button" label="Download" horizontalCenter="0" verticalCenter="0"/> </s:Application> Yet, suprisingly enough, the following code does not work as expected: it does not launch the installer upon creation. <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" creationComplete="applicationInit(event)"> <fx:Script> <![CDATA[ import flash.utils.setTimeout; import mx.events.FlexEvent; private var airSWF:Object; private var airSWFLoader:Loader = new Loader(); private var loaderContext:LoaderContext = new LoaderContext(); private function applicationInit(event:FlexEvent):void { this.loaderContext.applicationDomain = ApplicationDomain.currentDomain; this.airSWFLoader.contentLoaderInfo.addEventListener(Event.INIT, onAirInit); this.airSWFLoader.load(new URLRequest("http://airdownload.adobe.com/air/browserapi/air.swf"), loaderContext); } private function onAirInit(event:Event):void { this.airSWF = event.target.content; installApp(); } private function installApp():void { var url:String = "URL HERE"; var runtimeVersion:String = "2.7"; var arguments:Array = ["launchFromBrowser"]; this.airSWF.installApplication(url, runtimeVersion, arguments); } ]]> </fx:Script> <s:Button id="button" label="Download" horizontalCenter="0" verticalCenter="0"/> </s:Application> I verified that the installApp function is executed. Why doesn't the second piece of code work? Is user interaction required? If so what's a way around this? A: Yes, user interaction (user event) is needed for the AIR installer to work. Unfortunately, I can't seem to find official informations on this, but I've encountered this issue in the past. It's build that way for security reasons so that no app can install unwanted apps in the background. EDIT :Found it : http://livedocs.adobe.com/flex/3/html/help.html?content=distributing_apps_3.html Installing an AIR application from the browser A SWF file can install an AIR application by calling the installApplication() method in the air.swf file loaded from http://airdownload.adobe.com/air/browserapi/air.swf. For details, see Loading the air.swf file. [...] The installApplication() method can only operate when called in the event handler for a user event, such as a mouse click. The installApplication() method throws an error if the required version of Flash Player (version 9 upgrade 3) is not installed in the browser.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WP7 - How to embed my xap in a webpage I have made a Windows Phone 7 app and I would like to embed it in a webpage. I found two examples to help explain what I want to do: http://www.lifewaresolutions.com/deluxe_moon_demo_wp7.html http://help.arcgis.com/en/arcgismobile/10.0/apis/WindowsPhone/samples/start.htm I have looked at the page sources for both of these websites and have tried to mimic what they have down, but the farthest I have gotten is a webpage with a silverlight app in the middle, but my app doesn't start. I am not that familiar with web development, but if someone could help me create a simple html page with my wp7 app embedded in it, that would be great. A: The Silverlight desktop computer plugin can't execute Windows Phone Silverlight apps. The two example websites embed a "classic" Silverlight app within a fake Windows Phone chrome. So basically what you can do to have something similar is: * *Create a new Silverlight 4 "classic" project *Implement your app (you can share code between the new project and your existing WP7 code) *Retemplate the controls to make them look like the Windows Phone ones *Embed the app within a WP7 chrome on a website
{ "language": "en", "url": "https://stackoverflow.com/questions/7572327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Chaining calls to temporaries in C++ I have a class that does a transformation on a string, like so class transer{ transer * parent; protected: virtual string inner(const string & s) = 0; public: string trans(const string & s) { if (parent) return parent->trans(inner(s)); else return inner(s); } transer(transer * p) : parent(p) {} template <class T> T create() { return T(this); } template <class T, class A1> // no variadic templates for me T create(A1 && a1) { return T(this, std::forward(a1)); } }; So I can create a subclass class add_count : public transer{ int count; add_count& operator=(const add_count &); protected: virtual string inner(const string & s) { return std::to_string((long long)count++) + s; } public: add_count(transer * p = 0) : transer(p), count(0) {} }; And then I can use the transformations: void use_transformation(transer & t){ t.trans("string1"); t.trans("string2"); } void use_transformation(transer && t){ use_trasnformation(t); } use_transformation(add_count().create<add_count>()); Is there a better design for this? I'd like to avoid using dynamic allocation/shared_ptr if I can, but I'm not sure if the temporaries will stay alive throughout the call. I also want to be able to have each transer be able to talk to its parent during destruction, so the temporaries also need to be destroyed in the right order. It's also difficult to create a chained transformation and save it for later, since sometrans t = add_count().create<trans1>().create<trans2>().create<trans3>(); would save pointers to temporaries that no longer exist. Doing something like trans1 t1; trans2 t2(&t1); trans3 t3(&t2); would be safe, but annoying. Is there a better way to do these kinds of chained operations? A: Temporaries will be destructed at the end of the full expression, in the reverse order they were constructed. Be careful about the latter, however, since there are no guarantees with regards to the order of evaluation. (Except, of course, that of direct dependencies: if you need one temporary in order to create the next—and if I've understood correctly, that's your case—then you're safe.) A: If you don't want dynamic allocation you either pass the data which is operated on to the function that initiates the chain, or you need a root type which holds it for you ( unless you want excessive copying ). Example ( might not compile ): struct fooRef; struct foo { fooRef create() { return fooRef( m_Val ); } foo& operator=( const fooRef& a_Other ); std::string m_Val; } struct fooRef { fooRef( std::string& a_Val ) : m_Val( a_Val ) {} fooRef create() { return fooRef( m_Val ); } std::string& m_Val; } foo& foo::operator=( const fooRef& a_Other ) { m_Val = a_Other.m_Val; } foo startChain() { return foo(); } foo expr = startChain().create().create(); // etc First the string lies on the temporary foo created from startChain(), all the chained operations operates on that source data. The assignment then at last copies the value over to the named var. You can probably almost guarantee RVO on startChain().
{ "language": "en", "url": "https://stackoverflow.com/questions/7572328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: second highest salary in table in sql second highest salary in table in sql select * from emp e where 2 =(select count(distinct sal) from emp where e.sal<=sal) I am unable to understand this query...can anyone help me. A: Let's analyze the inner query: you are selecting all the distinct salaries there are more or equal than a predefined salary, which is the salary of the outer query. So, for EVERY row, you are searching and counting all the other rows with a salary greater or equal that one, and you finally select the one which have a value of 2, which is exactly the second highest salary (because the second highest salary has just 2 salary greater or equal itself: the greater salary at all, and itself). Tremendous inefficent, because for every row you re-scan the entire table, but funny :) A: This is a very inefficient way of doing it. It uses a correlated sub query. Conceptually for each row in the outer query it does a self join back into the emp table and counts the number of distinct salary values less than or equal to the current salary. If this is 2 then this salary is the 2nd highest salary in the table. This is known as a "triangular join" and as the number of rows increase the work required grows exponentially. A: We can get nth highest salary from table, see below sql: SELECT DISTINCT salary, name, id FROM emp_salary GROUP BY salary ORDER BY salary DESC LIMIT N-1,1; For example : Find second highest salary SELECT DISTINCT salary, name, id FROM emp_salary GROUP BY salary ORDER BY salary DESC LIMIT 1,1; We can get nth lowest salary from table, see below sql: SELECT DISTINCT salary, name, id FROM emp_salary GROUP BY salary ORDER BY salary ASC LIMIT N-1,1; For example : Find second lowest salary SELECT DISTINCT salary, name, id FROM emp_salary GROUP BY salary ORDER BY salary ASC LIMIT 1,1;
{ "language": "en", "url": "https://stackoverflow.com/questions/7572331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Easiest way to edit a huge geoJSON? I'm sitting here with a huge geoJSON that I got from an Open Street Map shape-file. However, most of the polygons are unnecessary. These could, in theory, easily be singled out based on certain properties. But how do I query the geoJSON file to remove certain elements (features)? Or would it be easier to save the shape-file in another format (working in QGIS)? Link to sample of json-file: http://dl.dropbox.com/u/15955488/hki_test_sample.json (240 kB) A: When you say "query the geoJSON," are you talking about having the source where you get the geoJSON give you a subset of data? There is no widely-implemented standard for "querying" JSON like this, but each site you retrieve from may have its own parameters to reduce the size of data you get. If you're talking about paring down the data in client-side code, simply looping through the structure and removing properties (with delete) and array items is what you'd have to do. A: Shapefile beats GeoJSON for large (not mega) data. It supports random access to features. To get at the GeoJSON features in a collection you have to read and deserialize the entire file. A: Depending on how you want to edit it and what software is available you have a few options. If you have access to Safe FME this is by far the best geographic feature manipuluation software and will give you tons of options (it can read / write (and convert between) just about any geographic format). If you're just looking for a text editor that can handle the volume of data I would look at Notepad++ - it can hold a lot of text and you can do find / replace using regular expressions. Safe FME can be a little pricy, but you might be able to get a trial A: As Jacob says, just iterate and remove the elements you don't want. I like http://documentcloud.github.com/underscore/#reject for convenience. A: If you are going to permanently remove fields just convert it to a shapefile, remove the fields you don't want, and re-export it as GeoJSON. A: I realize this question is old, but if anyone comes across this now, I'd recommend TopoJSON. Convert it to TopoJSON. By default TopoJSON removes all attributes, but you can flag those you'd like to keep like this: topojson -o output.topojson -p fieldToKeep,anotherFieldToKeep input.geojson More info in the TopoJSON command line reference
{ "language": "en", "url": "https://stackoverflow.com/questions/7572333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to inject in @FacesValidator with @EJB, @PersistenceContext, @Inject, @Autowired How can I inject a dependency like @EJB, @PersistenceContext, @Inject, @AutoWired, etc in a @FacesValidator? In my specific case I need to inject a Spring managed bean via @AutoWired: @FacesValidator("emailExistValidator") public class EmailExistValidator implements Validator { @Autowired private UserDao userDao; // ... } However, it didn't get injected and it remains null, resulting in java.lang.NullPointerException. It seems that @EJB, @PersistenceContext and @Inject also doesn't work. How do I inject a service dependency in my validator so that I can access the DB? A: JSF 2.3+ If you're already on JSF 2.3 or newer, and want to inject CDI-supported artifacts via e.g. @EJB, @PersistenceContext or @Inject, then simply add managed=true to the @FacesValidator annotation to make it CDI-managed. @FacesValidator(value="emailExistValidator", managed=true) JSF 2.2- If you're not on JSF 2.3 or newer yet, then you basically need to make it a managed bean. Use Spring's @Component, CDI's @Named or JSF's @ManagedBean instead of @FacesValidator in order to make it a managed bean and thus eligible for dependency injection. E.g., assuming that you want to use CDI's @Named: @Named @ApplicationScoped public class EmailExistValidator implements Validator { // ... } You also need to reference it as a managed bean by #{name} in EL instead of as a validator ID in hardcoded string. Thus, so <h:inputText ... validator="#{emailExistValidator.validate}" /> instead of <h:inputText ... validator="emailExistValidator" /> or <f:validator binding="#{emailExistValidator}" /> instead of <f:validator validatorId="emailExistValidator" /> For EJBs there's a workaround by manually grabbing it from JNDI, see also Getting an @EJB in @FacesConverter and @FacesValidator. If you happen to use JSF utility library OmniFaces, since version 1.6 it adds transparent support for using @Inject and @EJB in a @FacesValidator class without any additional configuration or annotations. See also the CDI @FacesValidator showcase example. See also: * *CDI Injection into a FacesConverter *What's new in JSF 2.2 - Injection A: You can now inject into JSF validators if you're using Java EE 8 and/or JSF 2.3. Tested using Mojarra 2.3.9.payara-p2 on Payara Server 5.192 #badassfish. <?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html"> <h:body> Hello from Facelets <h:form> <h:messages/> <h:inputText value="#{someBean.txtField}" validator="someValidator"/> </h:form> </h:body> </html> import javax.inject.Named; import javax.enterprise.context.Dependent; @Named(value = "someBean") @Dependent public class SomeBean { private String txtField; public String getTxtField() { return txtField; } public void setTxtField(String txtField) { this.txtField = txtField; } } import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.validator.FacesValidator; import javax.faces.validator.Validator; import javax.faces.validator.ValidatorException; import javax.inject.Inject; @FacesValidator(value = "someValidator", managed = true) public class CustomValidator implements Validator<String> { @Inject NewClass newClass; @Override public void validate(FacesContext context, UIComponent component, String value) throws ValidatorException { System.out.println("validator running"); System.out.println("injected bean: " + newClass); if (value != null && value.equals("badvalue")) { throw new ValidatorException(new FacesMessage(newClass.getMessage())); } } } public class NewClass { public String getMessage() { return "secret message"; } } import javax.faces.annotation.FacesConfig; // WITHOUT THIS INJECTION WILL NOT WORK! @FacesConfig(version = FacesConfig.Version.JSF_2_3) public class ConfigurationBean { } Should render something like: I banged my head on the wall for about an hour before realizing the need for ConfigurationBean. From the documentation: FacesConfig.Version.JSF_2_3 This value indicates CDI should be used for EL resolution as well as enabling JSF CDI injection, as specified in Section 5.6.3 "CDI for EL Resolution" and Section 5.9 "CDI Integration" And from this GitHub issue, https://github.com/eclipse-ee4j/glassfish/issues/22094: By default, JSF 2.3 runs in a compatibility mode with previous releases of JSF, unless a CDI managed bean is included in the application with the annotation @javax.faces.annotation.FacesConfig. To switch into a JSF 2.3 mode you will need a configuration bean like below: (shows ConfigurationBean) ... The fact that JSF needs to be switched into the "current version" was highly controversial. Pretty much the entire EG voted against that, but eventually we could not get around the backwards compatibility requirements that the JCP sets for Java EE and the spec lead enforces.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "34" }
Q: Make linked directories I have a class that pulls in an id, name and (if needed) parent-id, it converts these into objects and then links them. If you look right at the end you will see what Im trying to fix at the moment, The folder objects know if they have a child and/or parent but if I were to run mkDirs() here it would only work for two levels (root, child-folder) but if there were multipul levels (root/folder1/folder1) it would not work. Any Idea how I can solve this? package stable; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import java.util.Map; public class Loop { public static void main(String[] args) { int PID = 0; int RepoID = 1; Connection con = null; String url = "jdbc:mysql://localhost/document_manager"; String user = "root"; String password = "Pa55w0rd"; try { con = DriverManager.getConnection(url, user, password); } catch (SQLException e) { e.printStackTrace(); } Map<Integer,Folder> data = new HashMap<Integer,Folder>(); while( PID < 50 ) { try { Statement st = con.createStatement(); ResultSet result = st.executeQuery("SELECT name, category_id, parent_id FROM categories WHERE parent_id = '"+PID+"' AND repository_id = '"+RepoID+"'"); while (result.next ()) { String FolderName = result.getString ("name"); String FolderId = result.getString ("category_id"); String ParentId = result.getString ("parent_id"); int intFolderId = Integer.parseInt(FolderId); int intParentId = Integer.parseInt(ParentId); System.out.println( FolderId+" "+FolderName+" "+ParentId ); Folder newFolder = new Folder(FolderName, intFolderId, intParentId); data.put(newFolder.getId(), newFolder); } } catch (SQLException ex) { System.out.println(ex.getMessage()); } PID++; } for(Folder folder : data.values()) { int parentId = folder.getParentFolderId(); Folder parentFolder = data.get(parentId); if(parentFolder != null) parentFolder.addChildFolder(folder); //Added System.out.print("\n"+folder.getName()); if(parentFolder != null) System.out.print(" IS INSIDE "+parentFolder.getName()); else System.out.print(" HAS NO PARENT!"); } } } A: Looks like you could/should break out the directory creation logic into its own function and then make it recursive. That should get you the ability to make 'infinite' depth directory hierarchies. Side note: Its horribly inefficient to make repeated DB calls in a loop. Try a single Select and then loop thru results. If needbe, you can use SQL's 'IN' operator to filter results: http://www.w3schools.com/sql/sql_in.asp
{ "language": "en", "url": "https://stackoverflow.com/questions/7572336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TestNG: Use ApplicationContext in multiple Test-Classes I've written some test-cases inside a single TestNG Test which extends AbstractTestNGSpringContextTests. The ApplicationContext is correctly setup and I can use it inside my test-cases. The problem is that the setting up of the applicationContext can take some time and I don't want to do this for every test-class I have, as this would take some time which is unnecessary from my point of view. So my question is: Is it possible to run more than one TestNG test-class using the same Spring ApplicationContext which is setup only once? Thanks and best regards, Robert A: How about using a @BeforeSuite? A: Spring may cache and re-use ApplicationContext when you use similar locations in @ContextConfiguration annotations. See related article from Tomasz Nurkiewicz (@tomasz-nurkiewicz) at http://nurkiewicz.blogspot.com/2010/12/speeding-up-spring-integration-tests.html A: Once the TestContext framework loads an ApplicationContext (or WebApplicationContext) for a test, that context will be cached and reused for all subsequent tests that declare the same unique context configuration within the same test suite. The Spring TestContext framework stores application contexts in a static cache. This means that the context is literally stored in a static variable. In other words, if tests execute in separate processes the static cache will be cleared between each test execution, and this will effectively disable the caching mechanism. To benefit from the caching mechanism, all tests must run within the same process or test suite. This can be achieved by executing all tests as a group within an IDE. Similarly, when executing tests with a build framework such as Ant, Maven, or Gradle it is important to make sure that the build framework does not fork between tests. For example, if the forkMode for the Maven Surefire plug-in is set to always or pertest, the TestContext framework will not be able to cache application contexts between test classes and the build process will run significantly slower as a result.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add two arrays together AND run methods on them to order, limit, or paginate Im trying to make a news feed for a site and Im adding two arrays of different classes together to create a @feed_items array. But clearly I need to be able to order the new array by created_by right now I have: def home @comments = Comment.all @images = Image.all @feed_items = @comments+@images end So right now when I loop the @feed_items in my view, the loop displays all the comments (ordered by created_at), and then it display the images(ordered by created_at). But I need to order the entire array so everything is mixed up and ordered correctly. I tried to do this: def home @comments = Comment.all @images = Image.all @feed_items = (@comments+@images).order('created_by DESC') end But I get an undefined method error for the @feed_items array. Same thing with tying to use limit or paginate. A: If you can't do it in SQL, which is the case when you're dealing with two different tables in a single query, you can do it with Ruby: def home @comments = Comment.all @images = Image.all @feed_items = (@comments + @images).sort_by(&:created_at) end Remember that using the all method can be dangerous because you may have, potentially, tens of thousands of records. It's always a good idea to use a pagination system like will_paginate if nothing else. A: You need to call sort and take def home @comments = Comment.all @images = Image.all @feed_items = (@comments+@images).sort{|x,y| y.created_by <=> x.created_by} end home.take(10)
{ "language": "en", "url": "https://stackoverflow.com/questions/7572343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iOS: HTML5 video, continuous playback while remaining in fullscreen I am currently developing an iPad app that aggregates various video feeds on the internet. Then using a UIWebView, some Javascript, a <video> tag, and the mp4 URL I can playback the video and the native iOS video controls appear. This all works great. Additionally by subscribing to the video 'end' event, I can queue up another video to play after the one you were watching finishes. This also works great, EXCEPT if you were in fullscreen when the next video starts to play, you are taken out of it and back to the app! Does anyone know a way that I can persist fullscreen HTML5 video in iOS when a new video is loaded? A: The following worked for me on mobile safari on an iPod touch. Listen for the end event and change the source of the current video tag to the new video. <html> <body> <video id="myVideo" src="http://shapeshed.com/examples/HTML5-video-element/video/320x240.m4v" autoplay> </video> <script> document.getElementById('myVideo').addEventListener('ended',myHandler,false); function myHandler(e) { if(!e) { e = window.event; } // What you want to do after the event document.getElementById('myVideo').src='http://movies.apple.com/media/us/html5/showcase/2010/demos/apple-html5-demo-tron_legacy-us-20100601_r848-2cie.mov'; } </script> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7572346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Speed up Excel Autofilter I have a workbook that I made which generates a density map of I/O signals in an industrial plant. The whole workbook is driven by the lead sheet which the user inputs the signal type and where it is located. On the worksheet that generates the density map I give the user the ability to click a cell of interest in the density map. when the user clicks the cell a on_selectionChange macro will run computing the location in the plant. The location is than fed into the lead sheets auto filter to show the user what signals are actually at that spot in the plant. My problem is that the location information is computed instantly, but when I go to apply the filter criteria to the autofilter it takes 12 seconds for the filter to apply and the code to change from the density map sheet to the lead database sheet. So does anyone know how I can speed up my code with autofilters. I do turn off screen updating and application calculations when running the macro. This has never been this slow until I started adding other sheets to the workbook. Below you can see my code on how I compute the location. Can someone help me out with this Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range) ' Filter the I/O data to those associated with the clicked cell ' Turn off screen updating, this speeds up Calc Application.ScreenUpdating = False ' Turn off automatic calculations Application.Calculation = xlCalculationManual ' Setup benchmarking Dim Time1 As Date Time1 = Timer Dim Time2 As Date Dim rngOLD As Boolean Dim rngNEW As Boolean Const Building_rng = "C4:K6" Const Lvl_rng = "C4:E30" Const RL_rng = "C4:C6" Const FB_rng = "C4:E4" Dim NEW_Offset As Integer Dim Extra_Off As Integer Dim rowOff As Integer Dim colOff As Integer ' Define Filter Criteria Variables Dim Criteria_Building As String ' Building Dim Criteria_lvl As String ' Building Level Dim Criteria_FB As String ' Front/Back on Level Dim Criteria_RL As String ' Left/Right on Level rngOLD = InRange(Target, Worksheets("Density Map").Range("C4:K27")) rngNEW = InRange(Target, Worksheets("Density Map").Range("N4:V30,W4:Y12")) If (rngOLD Or rngNEW) And Not RangeIsBlank(Target) Then If rngNEW Then NEW_Offset = 11 Criteria_Building = FindBuildingionNEW(Target, Union(Range(Building_rng).Offset(0, NEW_Offset), Range("W4:Y6"))) ' Account for the Extra module in NEW Building If Criteria_Building = "Extra" Or Criteria_Building = "5" Or Criteria_Building = "6" Or Criteria_Building = "7" _ Or Criteria_Building = "8" Or Criteria_Building = "9" Or Criteria_Building = "10" Then Extra_Off = 3 End If Else Criteria_Building = FindBuildingionOLD(Target, Range(Building_rng)) End If Criteria_lvl = FindLvl(Target, Range(Lvl_rng).Offset(0, NEW_Offset), Criteria_Building) ' Get the offsets, Default will return zero if not found rowOff = getBuildingionOffset(Criteria_Building) + Extra_Off colOff = getLevelOffset(Criteria_lvl) Criteria_RL = FindRLFB(Target, Range(RL_rng).Offset(0, NEW_Offset), 1, rowOff, colOff) Criteria_FB = FindRLFB(Target, Range(FB_rng).Offset(0, NEW_Offset), 2, rowOff, colOff) ' Benchmark Debug.Print "1st Half Time: " & Format(Timer - Time1, "00:00") Time2 = Timer ' End Benchmark ' Filter sheet based on click position If rngVA Then ' Filter OLD location data With Worksheets("IO Data") .AutoFilterMode = False With .Range("A3:Z3") .AutoFilter .AutoFilter Field:=10, Criteria1:=Criteria_Building .AutoFilter Field:=12, Criteria1:=Criteria_lvl, Operator:=xlOr, Criteria2:="" .AutoFilter Field:=13, Criteria1:=Criteria_FB, Operator:=xlOr, Criteria2:="" .AutoFilter Field:=14, Criteria1:=Criteria_RL, Operator:=xlOr, Criteria2:="" End With End With Else ' Filter NEW location data With Worksheets("IO Data") .AutoFilterMode = False With .Range("A3:Z3") .AutoFilter .AutoFilter Field:=17, Criteria1:=Criteria_Building .AutoFilter Field:=19, Criteria1:=Criteria_lvl, Operator:=xlOr, Criteria2:="" .AutoFilter Field:=20, Criteria1:=Criteria_FB, Operator:=xlOr, Criteria2:="" .AutoFilter Field:=21, Criteria1:=Criteria_RL, Operator:=xlOr, Criteria2:="" End With End With End If ' Turn on automatic calculations Application.Calculation = xlCalculationAutomatic ' Turn on screen updating Application.ScreenUpdating = True Worksheets("IO Data").Activate ' Benchmark Debug.Print "Autofilter Time: " & Format(Timer - Time2, "00:00") ' End Benchmark End If End Sub A: Inspired by barrowc 's answer, you could try this: Rather than autofiltering in place, add a report sheet using a 'Get External Data' reference (from the same workbook, in spite of the name!) that returns the required filterd result set. To set up, add a connectionselect: From Data, Get External Data, Other Sources, Microsoft Query, Excel Files, and select your current workbook. (based on excel 2010, other excel version menus are a little different) Set up the query on your 'IO data' sheet, and include a WHERE clause (any criteria will do, you will edit this with code later) Update your _SelectionChange code to modify the connections query Here's a sample of code to access the connection (this assumes only 1 connection in the workbook, which queries a set of sample data I created to test the performance): Sub testConnection() Dim wb As Workbook Dim c As WorkbookConnection Dim sql As String Dim Time2 As Date Time2 = Timer Set wb = ActiveWorkbook Set c = wb.Connections.Item(1) sql = c.ODBCConnection.CommandText sql = Replace(sql, "WHERE (`'IO Data$'`.k=10)", _ "WHERE (`'IO Data$'`.k=9) AND (`'IO Data$'`.l=11) AND (`'IO Data$'`.m=12) AND (`'IO Data$'`.n=13) ") c.ODBCConnection.CommandText = sql c.Refresh Debug.Print "Connection Time: " & Format(Timer - Time2, "00:00") End Sub I performed a simple test on a data set of 26 columns, 50,000 rows, all cells containing a simple formula referencing another cell. Running on Win7 with Office2010, Autofilter took 21seconds to execute, and this method < 1 second Adapting this to your requirements will be basically building the WHERE clause part of the sql query string, accessed in c.ODBCConnection.CommandText A: You might need to look at using ADO to filter the sheet. That should be substantially faster but there's a bit of a learning curve. Start with this overview. You'll need to add a reference to "Microsoft ActiveX Data Objects 2.8 Library" before you can use ADO
{ "language": "en", "url": "https://stackoverflow.com/questions/7572348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CakePHP business logic layer CakePHP doesn't seem to ever mention separating the business logic and data access layers of an app. This is my first MVC app and my "fat models" are turning out to be very fat because they contain all kinds of business logic whose only real thing in common is requiring access to the same database. When you hear the suggestion to move your business logic from controllers into the model, is it really acceptable to wind up in such a state? Does CakePHP provide any structure for a separate business logic layer as part of their framework? Thanks, Brian A: No. It sounds to me that what you are running into is the classic downside of the Active Record pattern. Also, it doesn't help that CakePHP is all based around result associative arrays instead of object instances. I suggest that you take a look at packages like Doctrine 2. It implements a DataMapper pattern instead of an ActiveRecord pattern. It keeps your business logic completely separate from your data access layer. There are CakePHP extensions to integrate Doctrine into CakePHP.
{ "language": "en", "url": "https://stackoverflow.com/questions/7572353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Storing and retrieving Shared objects in Red5 I want a "simple" method so i can store shared objects in the disk, and then i can retrieve these so's from the disk even the red5 server restarts. PS: i wasted many hours on finding good doc that explains the procedure but i found none. A: Just notice that every field in your object should be serializable, then you can refer to this code sample: import java.io.Serializable; @SuppressWarnings("serial") public class Person implements Serializable{ private String name; private int age; public Person(){ } public Person(String str, int n){ System.out.println("Inside Person's Constructor"); name = str; age = n; } String getName(){ return name; } int getAge(){ return age; }} ** import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class SerializeToFlatFile { public static void main(String[] args) { SerializeToFlatFile ser = new SerializeToFlatFile(); ser.savePerson(); ser.restorePerson(); } public void savePerson(){ Person myPerson = new Person("Jay",24); try { FileOutputStream fos = new FileOutputStream("E:\\workspace\\2010_03\\src\\myPerson.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); System.out.println("Person--Jay,24---Written"); System.out.println("Name is: "+myPerson.getName()); System.out.println("Age is: "+myPerson.getAge()); oos.writeObject(myPerson); oos.flush(); oos.close(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } public void restorePerson() { try { FileInputStream fis = new FileInputStream("E:\\workspace\\2010_03\\src\\myPerson.txt"); ObjectInputStream ois = new ObjectInputStream(fis); Person myPerson = (Person)ois.readObject(); System.out.println("\n--------------------\n"); System.out.println("Person--Jay,24---Restored"); System.out.println("Name is: "+myPerson.getName()); System.out.println("Age is: "+myPerson.getAge()); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } }}
{ "language": "en", "url": "https://stackoverflow.com/questions/7572364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Could not load file or assembly '' or one of its dependencies. An API call exited abnormally I have a .NET App that I've recently Checked In to Team Foundation Server. Ever since I Checked it in, I get Access Denied to the App folder. I then give security permissions to the impersonated user and receive the error: Could not load file or assembly 'PMD Image Upload' or one of its dependencies. An API call exited abnormally. (Exception from HRESULT: 0x800300FA (STG_E_ABNORMALAPIEXIT)) A: The impersonate user should be given privileges to the solution files as well as the temp asp.net files for the solution, usually located in the following directory: C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files Where "Framework" could be "Framework64" and "v4.0.30319" may be another .Net version number. A: Impersonate on the web.config was enabled for a user with no privileges on the debug machine. Commented out the impersonate and was able to debug the .NET app. A: I know this is pretty old, but if you need to impersonate on the webserver you also need to award the impersonated user the rights to create/modify the folder "Temporary ASP.NET Files" in Windows\Microsoft.NET\"TheUsedFrameworkVersion". A: Bruno is correct. Disabling impersonation worked for me as well. If you don't have impersonate in your webconfig, and you're still having trouble. If you're running IIS 7.5 check your Application Pool. Sometimes it can be set to impersonate. Look under [Advanced Settings > Process Model > Identity] You'll want to set it to [ApplicationPoolIdentity]. A: <div id="divWindowMain"> <asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server"> <Services></Services> </asp:ScriptManagerProxy> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7572365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: How to use HTML5 ondrag event to change the element's position? For example : https://github.com/lbj96347/easypost/blob/master/test.html (p.s: you should have jquery and the css file of the page.:-)) Like this page,you can use the jquery extension to change the element's postion. But html5 and ie offers us the drags api.Like ondrag ondragend and so on. When I use the new events I can't get the mouse's position on the page,so that I can't achieve the effect like the jquery extension. ok,how can i use the drags api to achieve that effect? Thank you. A: Highly recommend reading 'The HTML5 drag and drop disaster'. <!DOCTYPE html> <html> <head> <style> html { height: 100%; } body { margin: 0; padding: 0; height: 100%; } section { height: 100%; } div { width: 40px; height: 40px; position: absolute; background-color: #000; } </style> </head> <body> <section ondragenter="return drag_enter( event )" ondrop="return drag_drop( event )" ondragover="return drag_over( event )"> <div id="item" draggable="true" ondragstart="return drag_start( event )"></div> </section> <script> function drag_enter( action ) { action.preventDefault( ); return true; } function drag_over( action ) { action.preventDefault( ); } function drag_start( action ) { action.dataTransfer.effectAllowed = 'move'; action.dataTransfer.setData( 'id', action.target.getAttribute( 'id' ) ); return true; } function drag_drop( action ) { var id = action.dataTransfer.getData( 'id' ); var element = document.getElementById( id ); element.style.top = action.clientY + 'px'; element.style.left = action.clientX + 'px'; if ( action.stopPropagation ) { action.stopPropagation( ); } return false; } </script> </body> </html> Further Reading HTML Drag and Drop API Native HTML5 Drag and Drop Native Drag and Drop
{ "language": "en", "url": "https://stackoverflow.com/questions/7572366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }