text
stringlengths
8
267k
meta
dict
Q: Separate "hand-drawn" objects in Mathematica What is the simplest / most convenient way to separate hand-drawn objects in Mathematica from programmatically generated ones? The interactive drawing tools are convenient and useful. But if I draw something on top of the plot, it will get lost as soon as the plot is re-generated. Is there a convenient solution for this? I could make the drawing on top of an empty plot, them combine them with the actual plot. But this is again inconvenient as I need to manually set the plot range of the empty plot and I don't see the background on top of which I'm adding the annotations. A: One approach, using an annotation to flag the generated content: Plot[Annotation[Sin[x], "GeneratedPrimitives"], {x, 0, 10}] RecoverDrawing[g_Graphics] := g /. Annotation[_, "GeneratedPrimitives"] :> {} RecoverDrawing[<modified graphic>] A: Unfortunately, the best thing I can think of is writing a program using ClickPane or EventHandler which not only draws bu records the points being added to the image. A modification of code like: DynamicModule[{pts = {}}, ClickPane[Dynamic[Framed@Graphics[Line[pts], PlotRange -> 1]], AppendTo[pts, #] &]]
{ "language": "en", "url": "https://stackoverflow.com/questions/7635181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Sharepoint 2007 extensions for Visual studio 2005 I am using Visual Studio 2005 to work with Sharepoint 2007. I need sharepoint extension (VSSExtension for VS 2005).Tried in google but dint get any download link. Can anybody post the link here Thanks in advance A: I typed sharepoint extensions for visual studio 2005 into Google and the first result is: Windows SharePoint Services 3.0 Tools: Visual Studio 2005 Extensions, Version 1.1 Tools for developing custom SharePoint applications: Visual Studio project templates for Web Parts, site definitions, and list definitions; and a stand-alone utility program, the SharePoint Solution Generator.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript syntax to pass variables Still muddling my way through Javascript, I'm trying to pass the contents of variable playnoyes to the long line of code below to decide whether or not to autoplay the flash movie, but doing it as I have below, the resultant line of code has the variable in quotes and therefore the code doesn't execute it as expected. My question is, how can I pass the variable so that the resulting line of code doesn't have the quotes around the variable value. Many thanks, and sorry for the noobness of the question. var playnoyes='true'; var testtext = "<script type='text\/javascript'>AC_FL_RunContent ('codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0','width','320','height','220','id','HTIFLVPlayer','src','HTIFLVPlayer','flashvars','&MM_ComponentVersion=1&skinName=HTI_Skin&streamName=nigel&autoPlay=\""+playnoyes+"\"&autoRewind=true','quality','high','scale','noscale','name','HTIFLVPlayer','salign','lt','pluginspage','http://www.macromedia.com/go/getflashplayer','wmode','transparent','movie','HTIFLVPlayer');<\/script>"; alert (testtext); A: Thats because you are explicitly adding the quotes: change nigel&autoPlay=\""+playnoyes+"\"&autoRewind=true' to nigel&autoPlay=" + playnoyes + "&autoRewind=true' A: Try this: var playnoyes='true'; var testtext = "<script type='text\/javascript'>AC_FL_RunContent ('codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0','width','320','height','220','id','HTIFLVPlayer','src','HTIFLVPlayer','flashvars','&MM_ComponentVersion=1&skinName=HTI_Skin&streamName=nigel&autoPlay="+playnoyes+"&autoRewind=true','quality','high','scale','noscale','name','HTIFLVPlayer','salign','lt','pluginspage','http://www.macromedia.com/go/getflashplayer','wmode','transparent','movie','HTIFLVPlayer');<\/script>"; alert (testtext); A: Remove the two '\"' on each side of the variable, no?
{ "language": "en", "url": "https://stackoverflow.com/questions/7635189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Displaying hierarchical data in HTML.DropDownList Helper method in ASP.NET MVC I have a table in database that has a foreign key to itself. While adding product products I want the users to be able to select a category from DropDownList. Right now, I am able to show the result like following :: * *Electronics *MP3 Players But, it would be ideal if they are shown like this, since MP3 Player is a child of Electronics :- * *Electronics * *MP3 Players How can I achieve this in a DropDownList ? My current code for retrieving and displaying is following respectively :- public ActionResult Create() { ViewBag.ParentCategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName"); return View(); } CSHTML <div class="editor-field"> @Html.DropDownList("ParentCategoryID", String.Empty) @Html.ValidationMessageFor(model => model.ParentCategoryID) </div> A: It looks like you need optgroups. Unfortunately MVC has no native support for this. So as mentioned in the following post you can write one yourself: ASP.Net MVC 3: optgroup support in Html.DropDownListFor
{ "language": "en", "url": "https://stackoverflow.com/questions/7635191", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to generate unique ID field in module in sugarcrm Want to generate the unique ID field in the module which will automatically generate the unique IDs. Can anyone help help for this ? Thanks A: There is a function inside of SugarCRM called create_guid() which does this exact thing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: potential advantages/disadvantages of window.location over a tag with href? I inherited some code with <img src="../...gif" onclick="aURL">. I was wondering the reason behind this choice so I would like to know any potential advantages/disadvantages of window.location over a tag with href? I am considering changing to <a href="aURL"><img src="../...gif"></a>. Thanks, A: The main disadvantage with the <img onclick=""> approach I immediately see is that various forms of clicks will not work, e.g. Ctrl+click opening in a new tab, Shift+click opening in a new window, etc. Also, JavaScript being disabled is also an area the onclick="window.location=x;" fails. Definitely use an anchor here like you're thinking, that's its purpose. A: As for the reason, I can't speak to that. Typically, you're always better off setting the href on an anchor, even if you don't intend to use it. The href should be set as a fallback in case the user doesn't have JavaScript enabled, or if a bot is crawling your site and won't use the onclick event. If you have to open a popup, then put that in the onclick and return false so it doesn't hit the href. I would definitely recommend removing the onclick from the <img> and putting it in an <a> wrapping it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ListViewItem not Selecting on Button Click I have a ListView in which the ListView Items have button and textblock.... Senario : I am able to click the button with out selecting the ListView Item i.e is the selection the last Item and then if i try to click the button of the first item the first time is not selected (In DataGrid it does select). I Cannot use DataGrid as i am using CustomView in ListView. If you need my code for reference of the problem i'll post it.. Any help in this regard would be great My ListView : <ListView Name="lv" Grid.Row="1" DisplayMemberPath="Name" IsTextSearchEnabled="True" ItemsSource="{Binding}" KeyboardNavigation.DirectionalNavigation="Cycle" SelectionMode="Single" TextSearch.TextPath="{Binding Path=Person.Name}" View="{Binding Path=SelectedItem, ElementName=viewComboBox}" /> My DataTemplates for CustomViews : <Style x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type CustomView:PlainView}, ResourceId=ImageView}" BasedOn="{StaticResource {x:Type ListBox}}" TargetType="{x:Type ListView}"> <Setter Property="BorderBrush" Value="Black" /> <Setter Property="BorderThickness" Value=".5" /> <Setter Property="HorizontalContentAlignment" Value="Center" /> <Setter Property="ItemContainerStyle" Value="{Binding (ListView.View).ItemContainerStyle, RelativeSource={RelativeSource Self}}" /> <Setter Property="ItemTemplate" Value="{Binding (ListView.View).ItemTemplate, RelativeSource={RelativeSource Self}}" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate> <Border Name="bd" Margin="{TemplateBinding Margin}" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ScrollViewer Margin="{TemplateBinding Padding}"> <WrapPanel KeyboardNavigation.DirectionalNavigation="Cycle" Width="{Binding ActualWidth, RelativeSource={RelativeSource AncestorType=ScrollContentPresenter}}" MinWidth="{Binding (ListView.View).MinWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListView}}}" IsItemsHost="True" ItemWidth="{Binding (ListView.View).ItemWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListView}}}" Orientation="Vertical" Height="{Binding ActualHeight, RelativeSource={RelativeSource AncestorType=ScrollContentPresenter}}"/> </ScrollViewer> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> <Style x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type CustomView:PlainView}, ResourceId=ImageViewItem}" BasedOn="{StaticResource {x:Type ListBoxItem}}" TargetType="{x:Type ListViewItem}"> <Setter Property="Padding" Value="3" /> <Setter Property="Margin" Value="5" /> <Setter Property="BorderBrush" Value="Black" /> <Setter Property="BorderThickness" Value="2" /> <Setter Property="HorizontalContentAlignment" Value="Center" /> </Style> <DataTemplate x:Key="centralTile"> <StackPanel Width="80" Height="40" KeyboardNavigation.AcceptsReturn="True"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="30"></ColumnDefinition> <ColumnDefinition Width="*"></ColumnDefinition> </Grid.ColumnDefinitions> <Button x:Name="tempabc" Command="{Binding Path=Launch}" KeyboardNavigation.AcceptsReturn="True" > <TextBlock Text="{Binding Path=Name}" FocusManager.IsFocusScope="True"></TextBlock> </Button> <Image Grid.Column="1" Source="Water lilies.jpg"/> </Grid> <TextBlock HorizontalAlignment="Center" FontSize="13" Text="{Binding Path=Name}" /> </StackPanel> </DataTemplate> <CustomView:PlainView x:Key="plainView" ItemTemplate="{StaticResource ResourceKey=centralTile}" ItemWidth="100" /> <GridView x:Key="myGridView"> <GridViewColumn> <GridViewColumn.CellTemplate> <DataTemplate> <Button> <TextBlock Text="{Binding Path=Name}" /> </Button> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> </GridView> A: As with most things, there are a number of ways to do this. Here's one I just threw together in a minute... Given the following model: public sealed class ItemModel { public string Name { get; set; } } I wish to display a collection of them to the user and select one via a button. This means I need three things in my ViewModel: * *A collection of ItemModels *A "SelectedItem" property to hold the currently selected instance *An ICommand implementation to bind to the buttons in the View I create my ViewModel and add these items to it. Please note, I prefer making my ViewModels extend DependencyObject rather than mess with INPC. public sealed class ViewModel : DependencyObject { // 1. A collection of ItemModels public ObservableCollection<ItemModel> ItemModels { get; private set; } // 2. A "SelectedItem" property to hold the currently selected instance public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register( "SelectedItem", typeof(ItemModel), typeof(ViewModel), new UIPropertyMetadata(null)); public ItemModel SelectedItem { get { return (ItemModel)GetValue(SelectedItemProperty); } set { SetValue(SelectedItemProperty, value); } } // 3. An ICommand implementation to bind to the buttons in the View public Command SelectItem { get; private set; } public ViewModel() { ItemModels = new ObservableCollection<ItemModel>(); ItemModels.Add(new ItemModel { Name = "One" }); ItemModels.Add(new ItemModel { Name = "Two" }); ItemModels.Add(new ItemModel { Name = "Three" }); SelectItem = new Command { ExecuteAction = x => SelectedItem = x as ItemModel }; } } Lastly, I slap together my UI with a rudimentary ListView. <Window x:Class="q_7635202.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="WindowRoot"> <ListView SelectedItem="{Binding SelectedItem}" ItemsSource="{Binding ItemModels}"> <ListView.View> <GridView> <GridViewColumn DisplayMemberBinding="{Binding Name}" Header="Name" /> <GridViewColumn> <GridViewColumn.CellTemplate> <DataTemplate> <Button Content="Select" Command="{Binding DataContext.SelectItem, ElementName=WindowRoot}" CommandParameter="{Binding}"/> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> </GridView> </ListView.View> </ListView> </Window> Its all pretty straight forward. I'm leaving out the ICommand implementation as it is trivial.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Generate the MouseClick in MonkeyRunner I am new in android, Please tell me how we can generate the mouseclick event on the any application using monkeyrunner Jython script. Please give me some hint, how to write the code of mouseclick event. Thanks in advance...!!! A: There are no any such way to Generate the MouseClick in MonkeyRunner using the Jython Script. Because using this script we can generate only touch event and key press event. So try to generate mouseclick event is the waisting your time...!!! A: http://developer.android.com/guide/developing/tools/MonkeyDevice.html#touch has information about the touch method of MonkeyRunner.MonkeyDevice. You will probably also want to read more of that guide to get a feel of how monkeyrunner works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is the most efficient collection for accessing an object based on two key variants? I'm trying to implement a large cache of objects (up to 500000) and need to be able to access them in two different ways... The key for each item is made up of three different strings; ItemNumber, PubCode and SizeCode. In some circumstances I'll be calling for a match on all three of those values to return a single object. In other cirumstances I'll be calling for a match on only ItemNumber and PubCode with a view to returning a collection of objects. What is the best collection to use for this? I've considered just using a generic list of object (of which all three of the key values are properties of) and using LINQ to query it, however I don't believe this is going to be the most performant way of doing this especially when you consider the size of the collection. Any help will as always be appreciated! A: How many items are you likely to have for any ItemNumber / PubCode combination? If the answer is "reasonably few" then I would start off with a Lookup<ItemNumberPubCode, Value> (or a Dictionary<ItemNumberPubCode, List<Value>>) - so if you're asked to look up by just the two of them, you can get straight to all matches. If you're asked to look up by all three, you fetch all the matches of the first two really quickly, and then do an O(n) scan for any match by SizeCode. (Here ItemNumberPubCode is a type encapsulating the ItemNumber and PubCode; this could be an anonymous type, a Tuple<string, string>, or a real type.) If there can be lots of matches for a particular ItemNumber / PubCode combination, then you might want a Dictionary<ItemNumberPubCode, Dictionary<string, Value>> - that will let you efficiently search by all three, and from just two of them you can fetch the dictionaries and use the Values property to find all matching values for the pair. A: Here's a simple way to do it using a Dictionary of Dictionaries. Like Jon said, whether you need this depends on the data. class TwoKeyDictionary<T> : Dictionary<string, Dictionary<string, T>> { public new IEnumerable<T> this[string key1] { get { return base[key1].Values; } } public T this[string key1, string key2] { get { return base[key1][key2]; } } public void Add(string key1, string key2, T item) { if (!base.ContainsKey(key1)) base[key1] = new Dictionary<string, T>(); base[key1].Add(key2, item); } } A: Basically you can go and use a tree or hash structure for indexing (for example (Sorted)Dictionary) - in your case you would use three of them. You just have to identify exactly what you need. I don't know your scenario but I would guess that it would be sufficient to just cache based on one property and just use normal database-indizes (more or less the same as above) for the other cases. A: Since it is read-only I'd make a non-collection class that houses two collections. public class CacheOfManyObjects { private Dictionary<string, ObjectsToBeCached> ObjectsByItemPubSize{get;set;} //You might want to replace the IEnumerable<> with a List<> // but that depends on implementation private Dictionary<string, IEnumerable<ObjectsToBeCached>> ObjectsByItemPub{get;set;} public ObjectsToBeCached GetByItemPubSize(string tString); public IEnumerable<ObjectsToBeCached> GetByItemPub(string tString); } The objects would be added to each Dictionary. You will need additional logic to create the object cache, but there is no real reason to have just 1 collection, since the collections themselves are small.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: JNDI - Glassfish JDBC, error when referencing data source On a glassfish server I have a JDBC Connection pool set up for my postgresql database. I have also create a JDBC Resource on my Glassfish server for this Connection pool If I create a web app that I deploy and run on this Glassfish server I get the following message about the jdbc resource. (IDE is Eclipse) [#|2011-10-03T13:33:09.745+0200|WARNING|glassfish3.1.1|javax.enterprise.system.tools.deployment.org.glassfish.deployment.common|_ThreadID=132;_ThreadName=Thread-2;|This web app [GlassfishTest] has no expand »resource environment reference by the name of [jdbc/MEM_Reporting]|#] In my web.xml the resource is configured as follows: <resource-env-ref> <resource-env-ref-name>jdbc/MEM_Reporting</resource-env-ref-name> <jndi-name>reporting</jndi-name> </resource-env-ref> I have been searching for a while now but cant find any solution, hope any of you guyz can help out. A: Shouldn't you've be using resource-ref instead of resource-env-ref? UPDATE: How do you reference it? Did you try to reference it with "java:comp/env/jdbc/MEM_Reporting" also in web.xml resource-ref should look ike <resource-ref> <res-ref-name>jdbc/MEM_Reporting</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> in sun-web.xml <resource-ref> <res-ref-name>jdbc/MEM_Reporting</res-ref-name> <jndi-name>jdbc/MEM_Reporting</jndi-name> </resource-ref> Also, take a look at Sun documentation for Reference Elements A: I add <jndi-name> tag in glassfish-web.xml file, not in sun-web.xml and after that the warning dissapear.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does my json string have 28 unprintable characters in it? I am producing a JSON string from a database query in JSP but it always has unprintable characters in it and I don't understand why! The JSP to produce the JSON is below: String user = "username"; // set a username String password = "password"; // set a password Class.forName("org.firebirdsql.jdbc.FBDriver"); // JDBC for firebird a.k.a. Jaybird String DB = "jdbc:firebirdsql://123.123.123.123:3050/C:\\db.fdb"; JSONArray obj=new JSONArray(); //Creating the json object Connection connection = DriverManager.getConnection(DB, user, password); Statement statement = connection.createStatement(); int i=0; Class.forName("org.firebirdsql.jdbc.FBDriver"); // JDBC for firebird a.k.a. Jaybird String query = "SELECT ses.sessionid, ses.datetime, ses.guid, ses.staffid FROM session ses ORDER by ses.datetime"; ResultSet resultset = statement.executeQuery(query); while (resultset.next()) { JSONObject j = new JSONObject(); j.put("SessionID", resultset.getString("sessionid")); j.put("DateTime", resultset.getString("datetime")); j.put("GUID", resultset.getString("guid")); j.put("StaffID", resultset.getString("staffid")); obj.add(i, j); i++; // Counter for indexing the JSONArray } resultset.close(); statement.close(); connection.close(); And this is the code I am using in PHP to display: echo '*'.$json.'*<br>'; echo strlen($json).'<br>'; $json = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json); echo '*'.$json.'*<br>'; echo strlen($json).'<br>'; which shows: * [{"SessionID":"850","DateTime":"2011-10-03 14:21:37.0","GUID":"51e71c19-ca13-4053-bd95-2addb5ba69f6","StaffID":"804"}] * 146 *[{"SessionID":"850","DateTime":"2011-10-03 14:21:37.0","GUID":"51e71c19-ca13-4053-bd95-2addb5ba69f6","StaffID":"804"}]* 118 So a difference of 28 unprintable characters - mostly at the beginning. How are they getting there and how can I get rid of them in the JSP? Thanks A: Because JSP is as being a view technology part of the HTTP response. Everything outside <% %> is sent to the response as well, including whitespace and newlines (rightclick the HTML page produced by PHP, do View Source and you'll see those newlines yourself as well, it are those newlines which you account to "unprintable" characters). Remove any whitespace and newlines outside <% %> or, better, use a servlet instead. You can find some kickoff examples of a JSON-producing Servlet in the answer to How to use Servlets and Ajax?
{ "language": "en", "url": "https://stackoverflow.com/questions/7635213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JSON Objects vs Spring Model Objects I am using standard Spring MVC 3x framework and have my model entities all built up with all the good relational stuff (javax.persistence API)... integrated with my DB. As the application evolved, we needed to support JSON calls. Given that I have various relationships mapped out in my Model Entity layer, (classX->classY as well as classY->classX) I am wondering what the best practice is in translating some of these model classes to appropriate JSON objects without duplicate re-referencing? eg: Sample buggy response {"classX":{"id":"1", "classY":{"id":"2", "classX":{"id":"1", "classY":{"id":"2"... I am contemplating a couple of methodologies I wouldn't mind feedback on... * *Keep the existing model classes and set the cross relationships to NULL before putting it into my ModelMap so there won't be some form of re-referencing (me thinks its a HACK) {"classX":{"id":"1", "classY":{"id":"2", "classX":null}}} *Recreate JSON classes similar to the existing models without the re-referencing classes (but I think that means they will not be as reusable... since I will end up only having classX->classY and not backwards if I wished to drill the other way for a data response). {"jsonClassX": {"id":"1", "jsonClassY":{"id":"2"}}} *Just simply construct it as standard ModelMap mappings for every controller call. As such no concept of a reusable JSON class, and is dependent on the way the controller constructs and organises the return values. This seems like the easiest, but it means no-reusable code (besides cut and paste)... {"x":{"id":"1", "y":{"id":"2"}}} // for controller call 1 {"y":{"id":"2", "x":{"id":"1"}}} // for controller call 2 So those are the options I am juggling with at the moment, and I wouldn't mind getting some feedback and some pointers on how others have done it. A: You should use Jackson to manage your json marshalling. Then you can add annotations to your model object which tell Jackson how to handle this type of relationship. http://wiki.fasterxml.com/JacksonFeatureBiDirReferences is a good reference for how to set up these relationships.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Entity Framework - pessimistic locking What I am trying to do is basically what NHibernate does when you do something like: var instance = session.Get<Customer>(id, LockMode.Upgrade); I need to lock the entity row in the database. Why I need that? Imagine something like a workflow instance that can be updated by multiple actors(people or processes) at the same time. The constraints I have don't allow for optimistic locking solutions. A: EF doesn't have support for this. If you want to lock some record by query you must do something like: using (var scope = new TransactionScope(...)) { using (var context = new YourContext(...)) { var customer = context.ExecuteStoreQuery<Customer>("SELECT ... FROM Customers WITH (UPDLOCK) WHERE ..."); // rest of your logic while record is locked scope.Complete(); } } Or context.Database.SqlQuery in case of DbContext API. A: You could also move your SQL Code to EDMX storage model, if you don't want to have plain SQL in your C# Code (see here): <Function Name="LockTestTable" IsComposable="false"> <CommandText> SELECT NULL FROM TestTable WITH (UPDLOCK) WHERE TestTableID = @testTableID </CommandText> <Parameter Name="testTableID" Mode="In" Type="int" /> </Function> And call it like this using (var scope = new TransactionScope(...)) { using (var context = new YourContext(...)) { context.LockTestTable(1); // Record locked scope.Complete(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7635216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is it possible to collapse/expand a DIV within an email? What clients support this? I have an alerting system that sends out alerts by email. I would like to include diagnostic information but only make it visible if the end user clicks a [+] button. Is this possible to do in email? Can I do it without using Javascript and only CSS? If it helps, most of my clients use Outlook, iPhones, or Blackberries A: Most likely, not. JS has been disabled in a lot of clients, due to viruses and stuff. A workaround might be to include a URL to the full error-page with all details, and edit your mail to only summarize the diagnostic information. Also, you could try to see if you can use :hover CSS, to show the element with some nasty selectors... CSS3-style? http://www.campaignmonitor.com/css/ A: You can do this with a checkbox, but I don't know if it is cross email client compatible. I would thoroughly check it. Here's some more information: Reveal and hide a div on checkbox condition with css There are tonnes of other examples throughout the web. Here is a really good working example on Litmus which uses a Hamburger Menu: https://litmus.com/community/discussions/999-hamburger-in-email Here's the simplified version: <style> #hidden-checkbox:checked + div #menu{ ... css to display menu ... } </style> <input id="hidden-checkbox" type="checkbox"> <div> <label for="hidden-checkbox">Hamburger Button</label> <div id="menu">Menu Content...</div> </div> A: Based on https://stackoverflow.com/a/31743982/2075630 by Eoin, but using classes to avoid the use of IDs for this. Edit. For me it works for standalone HTML files, but not in Emails; In Thunderbird, the checkbox is not changeable, and in Gmail <style> tags are stripped before displaying the email and applied statically as inline style attributes. The latter probably means, that there is no way to make it work for Gmail recipients, for Thunderbird I am not sure. Minimal example <style> .foldingcheckbox:not(:checked) + * { display: none } </style> <input type="checkbox" class="foldingcheckbox" checked/> <div class=>Foldable contents</div> .foldingcheckbox:not(:checked) selects all unchecked checkboxes with class foldingcheckbox. .foldingcheckbox:not(:checked) + * selects any element directly after such a checkbox. .foldingcheckbox:not(:checked) + * { display: none } hides those elements. The attribute checked makes it so, that the default state of the checkbox is to be checked. When omitted, the default state is for the checkbox not to be checked. The state is preserved when reloading the page at least in this simple example. Larger, visually more appealing, example In order to demonstrate how it works for larger examples: <style> .foldingcheckbox { float: right; } .foldingcheckbox:not(:checked) + * { display: none } h1, h2 { border-bottom: solid black 1pt } div { border: 1px solid black; border-radius: 5px; padding: 5px } </style> <h1>1. Hello there</h1> <input class="foldingcheckbox" type="checkbox" checked/> <div> <p>Hello World.</p> <p>This is a test.</p> <h2>1.2. Nesting possible!</h2> <input class="foldingcheckbox" type="checkbox" checked/> <div> <p>Hello World.</p> <p>This is a test.</p> </div> </div> <h1>2. More things.</h1> <input class="foldingcheckbox" type="checkbox" checked/> <div> <p>This is another test.</p> <p>This is yet another test.</p> </div> A: I don't think you can, email clients won't allow you to run javascript code due to security issues. And you can't do what you want only using CSS. A: you can't respond to click events without js. you can try an approach using :hover on css, but i'm not sure how many email clients support it
{ "language": "en", "url": "https://stackoverflow.com/questions/7635219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: At some zoom levels, dropdown menu has transparent gaps in IE7 Please consider my stripped down code below that illustrates my issue. If I run it in Firefox 7 or IE8, it works fine. However, when pressing F12 and entering the wonderful world of IE7, I'm experiencing gaps in my orange list at some zoom levels (so please use "ctrl+mouse wheel" when menu is extended to reproduce the bug). The main annoyance there, excluding the aesthetic visual gap, is since my menu is defined as absolute, when the mouse stops on the gap my menu disappears. Any suggestion on what is causing the problem? Also what is the best way to handle it if an IE7 fix is required, in order that my menu remains exactly the same in other browsers? <!DOCTYPE html PUBliC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>IE 7 Menu Test</title> <style type="text/css"> body { line-height: 1; } ul li { background: #A0A0A0; } ul li ul li { background: #FF9900; display: block; white-space: normal; width: 200px; } ul ul { position: absolute; } div ul ul,div ul li:hover ul ul,div ul ul li:hover ul ul { display: none; } div ul li:hover ul,div ul ul li:hover ul,div ul ul ul li:hover ul { display: block; } </style> </head> <body> <div><ul><li>Menu <!-- drop down list --> <ul> <li>- One</li> <li>- Two</li> <li>- Three</li> <li>- Four</li> </ul><!-- end drop down list --> </li></ul></div> </body></html> A: You're experiencing this bug: http://www.brunildo.org/test/IEWlispace.php As you can see, different combinations cause the problem, so there are various way to fix it. Here's your original code: http://jsbin.com/itaxek One possible fix is to move width: 200px; from ul li ul li to ul ul: http://jsbin.com/itaxek/2
{ "language": "en", "url": "https://stackoverflow.com/questions/7635223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bitmap Cache (SoftReference, Hard) on Lazy List does not seem to work properly - Android I have read several topics on lazy list loading in stackoverflow and I am trying to understand how to work on the different cache levels in android. As mentioned here: Lazy load of images in ListView I used the Multithreading For Performance, a tutorial by Gilles Debunne. example. I modified it in order to just work with the correct way and also work with 1.6. Here is the code: /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class ImageDownloader { private static final String TAG = "ImageDownloader"; private static final int HARD_CACHE_CAPACITY = 40; private static final int DELAY_BEFORE_PURGE = 10 * 1000; // in milliseconds private final static ConcurrentHashMap<String, SoftReference<Bitmap>> sSoftBitmapCache = new ConcurrentHashMap<String, SoftReference<Bitmap>>(HARD_CACHE_CAPACITY / 2); /* Download the specified image from the Internet and binds it to the provided ImageView. The * binding is immediate if the image is found in the cache and will be done asynchronously * otherwise. A null bitmap will be associated to the ImageView if an error occurs. * * @param url The URL of the image to download. * @param imageView The ImageView to bind the downloaded image to. */ public void download(String url, ImageView imageView) { Log.d(TAG, "download(String url, ImageView imageView)"); resetPurgeTimer(); Bitmap bitmap = getBitmapFromCache(url); if (bitmap == null) { Log.d(TAG, "(bitmap == null)"); forceDownload(url, imageView); } else { Log.d(TAG, "(bitmap != null) "); cancelPotentialDownload(url, imageView); imageView.setImageBitmap(bitmap); } } /* * Same as download but the image is always downloaded and the cache is not used. * Kept private at the moment as its interest is not clear. private void forceDownload(String url, ImageView view) { forceDownload(url, view, null); } */ /** * Same as download but the image is always downloaded and the cache is not used. * Kept private at the moment as its interest is not clear. */ private void forceDownload(String url, ImageView imageView) { Log.d(TAG, "forceDownload(String url, ImageView imageView)"); // State sanity: url is guaranteed to never be null in DownloadedDrawable and cache keys. if (url == null) { Log.d(TAG, "(url == null)"); imageView.setImageDrawable(null); return; } Bitmap bitmap = null; BitmapDownloaderTask task = null; if (cancelPotentialDownload(url, imageView)) { Log.d(TAG, "(cancelPotentialDownload(url, imageView))"); task = new BitmapDownloaderTask(imageView); DownloadedDrawable downloadedDrawable = new DownloadedDrawable(task); imageView.setImageDrawable(downloadedDrawable); imageView.setMinimumHeight(156); task.execute(url); } } /** * Returns true if the current download has been canceled or if there was no download in * progress on this image view. * Returns false if the download in progress deals with the same url. The download is not * stopped in that case. */ private static boolean cancelPotentialDownload(String url, ImageView imageView) { Log.d(TAG, "---cancelPotentialDownload(String url, ImageView imageView)----)"); BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView); if (bitmapDownloaderTask != null) { Log.d(TAG, "(bitmapDownloaderTask != null)"); String bitmapUrl = bitmapDownloaderTask.url; if ((bitmapUrl == null) || (!bitmapUrl.equals(url))) { Log.d(TAG, "(((bitmapUrl == null) || (!bitmapUrl.equals(url)))"); bitmapDownloaderTask.cancel(true); } else { Log.d(TAG, "The same URL is already being downloaded."); // The same URL is already being downloaded. return false; } } return true; } /** * @param imageView Any imageView * @return Retrieve the currently active download task (if any) associated with this imageView. * null if there is no such task. */ private static BitmapDownloaderTask getBitmapDownloaderTask(ImageView imageView) { Log.d(TAG, "getBitmapDownloaderTask(ImageView imageView)"); if (imageView != null) { Log.d(TAG, "(imageView != null) )"); Drawable drawable = imageView.getDrawable(); if (drawable instanceof DownloadedDrawable) { Log.d(TAG, "(drawable instanceof DownloadedDrawable) "); DownloadedDrawable downloadedDrawable = (DownloadedDrawable)drawable; return downloadedDrawable.getBitmapDownloaderTask(); } } return null; } Bitmap downloadBitmap(String stringUrl) { Log.d(TAG, "(downloadBitmap(String stringUrl)"); URL url = null; HttpURLConnection connection = null; InputStream inputStream = null; try { url = new URL(stringUrl); connection = (HttpURLConnection) url.openConnection(); connection.setUseCaches(true); inputStream = connection.getInputStream(); return BitmapFactory.decodeStream(new FlushedInputStream(inputStream)); /* BitmapFactory.Options bfOptions=new BitmapFactory.Options(); bfOptions.inDither=false; //Disable Dithering mode bfOptions.inPurgeable=true; //Tell to gc that whether it needs free memory, the Bitmap can be cleared bfOptions.inInputShareable=true; //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future bfOptions.inTempStorage=new byte[32 * 1024]; Bitmap b=BitmapFactory.decodeStream(new FlushedInputStream(inputStream), null,bfOptions ); return b; */ } catch (IOException e) { //getRequest.abort(); Log.w(TAG, "I/O error while retrieving bitmap from " + url, e); } catch (IllegalStateException e) { // getRequest.abort(); Log.w(TAG, "Incorrect URL: " + url); } catch (Exception e) { //getRequest.abort(); Log.w(TAG, "Error while retrieving bitmap from " + url, e); } finally { if (connection != null) { connection.disconnect(); } } return null; } /* * An InputStream that skips the exact number of bytes provided, unless it reaches EOF. */ static class FlushedInputStream extends FilterInputStream { public FlushedInputStream(InputStream inputStream) { super(inputStream); } @Override public long skip(long n) throws IOException { long totalBytesSkipped = 0L; while (totalBytesSkipped < n) { long bytesSkipped = in.skip(n - totalBytesSkipped); if (bytesSkipped == 0L) { int b = read(); if (b < 0) { break; // we reached EOF } else { bytesSkipped = 1; // we read one byte } } totalBytesSkipped += bytesSkipped; } return totalBytesSkipped; } } /** * The actual AsyncTask that will asynchronously download the image. */ class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> { private String url; private final WeakReference<ImageView> imageViewReference; public BitmapDownloaderTask(ImageView imageView) { Log.w(TAG, "BitmapDownloaderTask(ImageView imageView)"); imageViewReference = new WeakReference<ImageView>(imageView); } /** * Actual download method. */ @Override protected Bitmap doInBackground(String... params) { Log.w(TAG, "doInBackground"); url = params[0]; return downloadBitmap(url); } /** * Once the image is downloaded, associates it to the imageView */ @Override protected void onPostExecute(Bitmap bitmap) { Log.w(TAG, "onPostExecute"); if (isCancelled()) { bitmap = null; } addBitmapToCache(url, bitmap); if (imageViewReference != null) { Log.w(TAG, "(imageViewReference != null)"); ImageView imageView = imageViewReference.get(); BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView); // Change bitmap only if this process is still associated with it // Or if we don't use any bitmap to task association (NO_DOWNLOADED_DRAWABLE mode) if ((this == bitmapDownloaderTask)) { Log.w(TAG, " if ((this == bitmapDownloaderTask)"); imageView.setImageBitmap(bitmap); } } } } /** * A fake Drawable that will be attached to the imageView while the download is in progress. * * <p>Contains a reference to the actual download task, so that a download task can be stopped * if a new binding is required, and makes sure that only the last started download process can * bind its result, independently of the download finish order.</p> */ static class DownloadedDrawable extends ColorDrawable { private final WeakReference<BitmapDownloaderTask> bitmapDownloaderTaskReference; public DownloadedDrawable(BitmapDownloaderTask bitmapDownloaderTask) { super(Color.BLACK); Log.w(TAG, "DownloadedDrawable(BitmapDownloaderTask bitmapDownloaderTask) "); bitmapDownloaderTaskReference = new WeakReference<BitmapDownloaderTask>(bitmapDownloaderTask); } public BitmapDownloaderTask getBitmapDownloaderTask() { Log.w(TAG, "BitmapDownloaderTask getBitmapDownloaderTask() "); return bitmapDownloaderTaskReference.get(); } } /* public void setMode(Mode mode) { this.mode = mode; clearCache(); } */ /* * Cache-related fields and methods. * * We use a hard and a soft cache. A soft reference cache is too aggressively cleared by the * Garbage Collector. */ // Hard cache, with a fixed maximum capacity and a life duration private final HashMap<String, Bitmap> sHardBitmapCache = new LinkedHashMap<String, Bitmap>(HARD_CACHE_CAPACITY / 2, 0.75f, true) // private final HashMap<String, Bitmap> sHardBitmapCache = new LinkedHashMap<String, Bitmap>() { // private static final long serialVersionUID = -695136752926135717L; @Override protected boolean removeEldestEntry(LinkedHashMap.Entry<String, Bitmap> eldest) { Log.w(TAG, "removeEldestEntry(LinkedHashMap.Entry<String, Bitmap> eldest) "); Log.w(TAG, "size() : " + size()); Log.w(TAG, "HARD_CACHE_CAPACITY : " + HARD_CACHE_CAPACITY); if (size() > HARD_CACHE_CAPACITY) { Log.w(TAG, "(size() > HARD_CACHE_CAPACITY) "); Log.e(TAG, "sSoftBitmapCache --> sSoftBitmapCache.put "); // Entries push-out of hard reference cache are transferred to soft reference cache sSoftBitmapCache.put(eldest.getKey(), new SoftReference<Bitmap>(eldest.getValue())); return true; } else return false; } }; //HARD_CACHE_CAPACITY / 2 // Soft cache for bitmaps kicked out of hard cache // private final static ConcurrentHashMap<String, SoftReference<Bitmap>> sSoftBitmapCache = new ConcurrentHashMap<String, SoftReference<Bitmap>>(); private final Handler purgeHandler = new Handler(); private final Runnable purger = new Runnable() { public void run() { Log.e(TAG, "purger run"); // clearCache(); } }; /** * Adds this bitmap to the cache. * @param bitmap The newly downloaded bitmap. */ private void addBitmapToCache(String url, Bitmap bitmap) { Log.w(TAG, "--------addBitmapToCache-----------"); if (bitmap != null) { Log.w(TAG, "(bitmap != null) "); synchronized (sHardBitmapCache) { //final Bitmap tryData = sHardBitmapCache.get(url); // if (tryData != null) { // sHardBitmapCache.remove(url); // } Log.w(TAG, " sHardBitmapCache.put(url, bitmap);"); sHardBitmapCache.put(url, bitmap); } } } /** * @param url The URL of the image that will be retrieved from the cache. * @return The cached bitmap or null if it was not found. */ private Bitmap getBitmapFromCache(String url) { Log.e(TAG, " --------getBitmapFromCache(String url)----------------"); // First try the hard reference cache synchronized (sHardBitmapCache) { final Bitmap bitmap = sHardBitmapCache.get(url); if (bitmap != null) { Log.e(TAG, " getBitmapFromCache ---> Bitmap found in Hard cache!!!!!"); // Bitmap found in hard cache // Move element to first position, so that it is removed last sHardBitmapCache.remove(url); sHardBitmapCache.put(url, bitmap); return bitmap; }else{ Log.e(TAG, " getBitmapFromCache ---> Bitmap not found in Hard cache"); } } // Then try the soft reference cache SoftReference<Bitmap> bitmapReference = sSoftBitmapCache.get(url); if (bitmapReference != null) { Log.e(TAG, " getBitmapFromCache ---> bitmapReference found in SoftReference cache!"); final Bitmap bitmap = bitmapReference.get(); if (bitmap != null) { Log.e(TAG, "Bitmap found in SoftReference cache!!!!!!!"); // Bitmap found in soft cache return bitmap; } else { Log.e(TAG, "oooooooooooooooooooo --> Soft reference has been Garbage Collected"); // Soft reference has been Garbage Collected sSoftBitmapCache.remove(url); } } return null; } /** * Clears the image cache used internally to improve performance. Note that for memory * efficiency reasons, the cache will automatically be cleared after a certain inactivity delay. */ public void clearCache() { Log.e(TAG, "----------------clearCache() ------------------"); synchronized (sHardBitmapCache) { //sHardBitmapCache.clear(); } //sSoftBitmapCache.clear(); sHardBitmapCache.clear(); sSoftBitmapCache.clear(); } /** * Allow a new delay before the automatic cache clear is done. */ private void resetPurgeTimer() { purgeHandler.removeCallbacks(purger); purgeHandler.postDelayed(purger, DELAY_BEFORE_PURGE); } } I completely understand the logic behind this example however I am confused why this does not work properly. We have two levels of cache :The Hard cache and the SoftReference cache. We save the bitmaps in the hard cache and then when is filled we save in the SoftReference and reorder hard cache.. Then I close the app, close the internet and restart it.In the constructor we call resetPurgeTimer() which clears the cache and therefore nothing is in the cache. To avoid this I commented that line in order not to clear the cache.. I restart my app and I can see 6-7 images which are present in SoftReference cache (according to LogCat).. I know that SoftReference cache maybe get empty when GC is called but it is almost empty even before closing the app or disabling wifi...There is a well known bug with SoftReferences which are garbage collected even without memory getting low.. Is something wrong with this widely used example? Thanks in advance, Andreas A: Yes, in Android 3.0 and above you can't use Weak or Soft References for Bitmaps. The JVM will aggressively collect them. Instead you should use an LRUCache (in the support library) to cache them. I'd also recommend setting the size of the max cache to some fraction of the size of the max heap (like 1/6 for example).
{ "language": "en", "url": "https://stackoverflow.com/questions/7635224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: NSMergeConflict with multiple threads A 1 <----> * B I'm using core data in an iOS application. A and B are entities that have a 1-to-many relationship between A and B. I have a background thread that updates and creates B. A is updated on the main thread, except when I add B to A on the background thread, because of the inverse relationship A gets updated. I have separate MOCs for the main and background thread. I've added a mergeChangesFromContextDidSaveNotification: on the main thread, but I get a NSMergeConflict on the background thread for A. Looking at the userInfo of the NSMergeConflict doesn't help, because all the attributes are the same, it's the to many relationships that I imagine are conflicting, and those arent returned by nsmergeconflict. I've tried adding a mergeChangesFromContextDidSaveNotification: to the background thread, but it now deadlocks when both threads try to save. I've looked over the answer for this NSMergeConflict question. I've tried adding the mergeChangesFromContextDidSaveNotification: notification, but I'm still seeing the NSMergeConflict. I don't think that any of the NSMergePolicy options are applicable, because I want to keep all of the persistent store's changes except for the relationship. I'm also not clear on how I can "manually resolve any conflicts". How would I be able to resolve or avoid these conflicts?
{ "language": "en", "url": "https://stackoverflow.com/questions/7635233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Delphi logging with multiple sinks and delayed classification? Imagine i want to parse a binary blob of data. If all comes okay, then all the logs are INFO, and user by default does not even see them. If there is an error, then user is presented with error and can view the log to see exact reason (i don't like programs that just say "file is invaid. for some reason. you do not want to know it" ) Probably most log libraries are aimed at quickly loading, classifying and keeping many many log lines per second. which by itself is questionable, as there is no comfort lazy evaluation and closures in Delphi. Envy Scala :-) However that need every line be pre-сlassified. Imagine this hypothetical flow: * * * *Got object FOO [ok] * *1.1. found property BAR [ok] * *1.1.1. parsed data for BAR [ok] *1.2 found property BAZ [ok] * *1.2.1 successfully parsed data for BAR [ok] *1.2.2 matching data: checked dependancy between BAR and BAZ [fail] ... So, what can be desired features? 1) Nested logging (indenting, subordination) is desired then. Something like highlighted in TraceTool - see TraceNode.Send Method at http://www.codeproject.com/KB/trace/tracetool.aspx#premain0 2) The 1, 1.1, 1.1.1, 1.2, 1.2.1 lines are sent as they happen in a info sink (TMemo, OutputDebugString, EventLog and so one), so user can see and report at least which steps are complete before error. 3) 1, 1.2, 1.2.2 are retroactively marked as error (or warning, or whatever) inheriting from most specific line. Obviously, warning superseeds info, error superseeds warning and info, etc/ 4) 1 + 1.2 + 1.2.2 can be easily combined like with LogMessage('1.2.2').FullText to be shown to user or converted to Exception, to carry the full story to human. 4.1) Optionally, with relevant setup, it would not only be converted to Exception, but the latter even would be auto-raised. This probably would require some kind of context with supplied exception class or supplied exception constructing callback. 5) Multisink: info can be just appended into collapsible panel with TMemo on main form or currently active form. The error state could open such panel additionally or prompt user to do it. At the same time some file or network server could for example receive warning and error grade messages and not receive info grade ones. 6) extra associated data might be nice too. Say, if to render it with TreeView rather than TMemo, then it could have "1.1.1. parsed data for BAR [ok]" item, with mouse tooltip like "Foo's dimensions are told to be 2x4x3.2 metres" * *Being free library is nice, especially free with sources. Sometimes track and fix the bug relying solely on DCUs is much harder. *Non-requiring extra executable. it could offer extra more advanced viewer, but should not be required for just any functionality. *Not being stalled/abandoned. *ability to work and show at least something before GUI is initialized would be nice too. Class constructors are cool, yet are executed as part of unit visualization, when VCL is not booted yet. If any assertion/exception is thrown from there, user would only see Runtime error 217, with all the detail lost. At least OutputDebugStreen can be used, if nothing more... Stack tracing is not required, if needed i can do it and add with Jedi CodeLib. But it is rarely needed. External configuration is not required. It might be good for big application to reconfigure on the fly, but to me simplicity is much more important and configuration in code, by calling constructors or such, is what really matters. Extra XML file, like for Log4J, would only make things more fragile and complex. I glanced few mentioned here libraries. * *TraceTool has a great presentation, link is above. Yet it has no info grade, only 3 predefined grades (Debug/Error/Warning) and nothing more, but maybe Debug would suit for Info replacement... Seems like black box, only saving data into its own file, and using external tool to view it, not giving stream of events back to me. But their messages nesting and call chaining seems cool. Cools is also attaching objects/collection to messages. *Log4D and Log4Delphi seems to be in a stasis, with last releases of 2007 and 2009, last targeted version Delphi 7. Lack documentation (probably okay for log4j guy, but not for me :- ) Log4Delphi even had test folder - but those test do not compile in Delphi XE2-Upd1. Pity: In another thread here Log4delphi been hailed for how simple is to create custom log appender (sink)... * *BTW, the very fact that the only LOG4J was forked into two independent Delphi ports leaves the question of which is better and that both lack something, if they had to remain in split. *mORMot part is hardly separated from the rest library. Demo application required UAC escalation for use its embedded SQLite3 engine and is frozen (no window opened, yet the process never exits normally) if refused Admin grants. Another demo just started infinite stream of AV exceptions, trying to unwind the stack. So is probably not ready yet for last Delphi. Though its list of message grades is excessive, maybe even a bit too many. Thank you. A: mORMot is stable, even with latest XE2 version of Delphi. What you tried starting were the regression tests. Among its 6,000,000 tests, it includes the HTTP/1.1 Client-Server part of the ORM. Without the Admin rights, the http.sys Server is not able to register the URI, so you got errors. Which makes perfectly sense. It's a Vista/Seven restriction, not a mORMot restriction. The logging part can be used completely separated from the ORM part. Logging is implemented in SynCommons.pas (and SynLZ.pas for the fast compression algorithm used for archival and .map embedding). I use the TSynLog class without any problem to log existing applications (even Delphi 5 and Delphi 6 applications), existing for years. The SQLite3 / ORM classes are implemented in other units. It supports the nesting of events, with auto-leave feature, just as you expect. That is you can write: procedure TMyClass.MyMethod(const Params: integer); begin TSynLog.Enter; // .... my method code end; And adding this TSynLog.Enter will be logged with indentation corresponding to the recursive level. IMHO this may meet your requirements. It will declare an ISynLog interface on the stack, which will be freed by Delphi at the "end;" code line, so it will implement an Auto-Leave feature. And the exact unit name, method name and source code line number will be written into the log (as MyUnit.TMyClass.MyMethod (123)), if you generated a .map file at compilation (which may be compressed and appended to the .exe so that your customers logs will contain the source line numbers). You have methods at the ISynLog interface level to add some custom logging, including parameters and custom state (you can log objects properties as JSON if you need to, or write your custom logging data). The exact timing of each methods are tracked, so you are able to profile your application from the data supplied by your customer. If you think the logs are too much verbose, you have several levels of logging, to be customized on the client side. See the blog articles and the corresponding part of the framework documentation (in the SynCommons part). You've for instance "Fail" events and some custom kind of events. And it is totally VCL-independent, so you can use it without GUI or before any GUI is started. You have at hand a log viewer, which allow client-side profiling and nested Enter/Leave view (if you click on the "Leave" line, you'll go back to the corresponding "Enter", e.g.): If this log viewer is not enough, you have its source code to make it fulfill your requirements, and all the needed classes to parse and process the .log file on your own, if you wish. Logs are textual by default, but can be compressed into binary on request, to save disk space (the log viewer is able to read those compressed binary files). Stack tracing and exception interception are both implemented, and can be activated on request. You could easily add a numeration like "1.2.1" to the logs, if you wish to. You've got the whole source code of the logging unit. Feel free to ask any question in our forum. A: Log4D supports nested diagnostic contexts in the TLogNDC class, they can be used to group together all steps which are related to one compound action (instead of a 'session' based grouping of log events). Multi-Sinks are called Appenders in log4d and log4delphi so you could write a TLogMemoAppender with around twentyfive lines of code, and use it at the same time as a ODSAppender, a RollingFileAppender, or a SocketAppender, configurable at run time (no external config file required).
{ "language": "en", "url": "https://stackoverflow.com/questions/7635235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: numpy: syntax/idiom to cast (n,) array to a (n, 1) array? I'd like to cast a numpy ndarray object of shape (n,) into one having shape (n, 1). The best I've come up with is to roll my own _to_col function: def _to_col(a): return a.reshape((a.size, 1)) But it is hard for me to believe that such a ubiquitous operation is not already built into numpy's syntax. I figure that I just have not been able to hit upon the right Google search to find it. A: np.expand_dims is my favorite when I want to add arbitrary axis. None or np.newaxis is good for code that doesn't need to have flexible axis. (aix's answer) >>> np.expand_dims(np.arange(5), 0).shape (1, 5) >>> np.expand_dims(np.arange(5), 1).shape (5, 1) example usage: demean an array by any given axis >>> x = np.random.randn(4,5) >>> x - x.mean(1) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: shape mismatch: objects cannot be broadcast to a single shape >>> ax = 1 >>> x - np.expand_dims(x.mean(ax), ax) array([[-0.04152658, 0.4229244 , -0.91990969, 0.91270622, -0.37419434], [ 0.60757566, 1.09020783, -0.87167478, -0.22299015, -0.60311856], [ 0.60015774, -0.12358954, 0.33523495, -1.1414706 , 0.32966745], [-1.91919832, 0.28125008, -0.30916116, 1.85416974, 0.09293965]]) >>> ax = 0 >>> x - np.expand_dims(x.mean(ax), ax) array([[ 0.15469413, 0.01319904, -0.47055919, 0.57007525, -0.22754506], [ 0.70385617, 0.58054228, -0.52226447, -0.66556131, -0.55640947], [ 1.05009459, -0.27959876, 1.03830159, -1.23038543, 0.73003287], [-1.90864489, -0.31414256, -0.04547794, 1.32587149, 0.05392166]]) A: I'd use the following: a[:,np.newaxis] An alternative (but perhaps slightly less clear) way to write the same thing is: a[:,None] All of the above (including your version) are constant-time operations.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Passing params through nested user controls in Silverlight 4 I have a three level of nested user controls in my Silverlght 4 application. the most low level control fires an event with some parameter, then second user control takes the parameter and also fires an event sending parameter to up. Third user controls makes same thing passing parameter to the MainPage. Anyway a have got my parameter but the way I did it very boring and confusing. Is there any acceptable and easy understanding way to do same thing shorter. Thanks a lot! A: That is the correct way, mainly because any level is replaceable and so should function the same way. Boring and simple looking are actually good things for code... makes it easier for others to follow. If you want excitement... I would suggest a career change :) A: It all depends on what the event is and what the parameter you are bubbling up contains. If this is purely user-interaction and the visual parent needs to react to your event, then, as HiTech Magic mentions, this is the best way to do it. Now, if what you are trying to do is actually related with the business logic of the application, then maybe your user control is not best place to handle this event and you may benefit from binding a view model to your user controls and using some kind of event aggregator to broadcast your events. It may be good for you to add more context to the event your are firing and the parameter which you are bubbling up to the container for you to get additional information which applies to your context.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635245", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MongoDB C# Driver FindAndModify I'm trying to run a FindAndModify operation in MongoDB, but I'm getting an unusual exception var query = Query.EQ("_id", wiki.ID); var sortBy = SortBy.Descending("Version"); var update = Update.Set("Content", wiki.Content) .Set("CreatedBy", wiki.CreatedBy) .Set("CreatedDate", wiki.CreatedDate) .Set("Name", wiki.Name) .Set("PreviousVersion", wiki.PreviousVersion.ToBsonDocument()) .Set("Title", wiki.Title) .Set("Version", wiki.Version); var result = collection.FindAndModify(query, sortBy, update, true); The exception I get is WriteStartArray can only be called when State is Value, not when State is Initial Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidOperationException: WriteStartArray can only be called when State is Value, not when State is Initial Source Error: Line 45: var query = Query.EQ("_id", wiki.ID); Line 46: var sortBy = SortBy.Descending("Version"); Line 47: var update = Update.Set("Content", wiki.Content) Line 48: .Set("CreatedBy", wiki.CreatedBy) Line 49: .Set("CreatedDate", wiki.CreatedDate) Thoughts? I've implemented this per the API on mongodb's site. EDIT-- Fixed per @jeffsaracco var update = Update.Set("Content", wiki.Content) .Set("CreatedBy", wiki.CreatedBy) .Set("CreatedDate", wiki.CreatedDate) .Set("Name", wiki.Name) .PushAllWrapped<WikiHistory>("PreviousVersion", wiki.PreviousVersion) .Set("Title", wiki.Title) .Set("Version", wiki.Version); A: Your solution with PushAllWrapped may or may not be want you want. It is different from Set because it appends the new values to the current array value. If you wanted to replace the existing array value with a new array value you could use this version of Set: var update = Update.Set("Content", wiki.Content) // other lines .Set("WikiHistory", new BsonArray(BsonDocumentWrapper.CreateMultiple(wiki.PreviousVersion); which says: set the value of the WikiHistory element to a new BsonArray constructed by serializing the wrapped values of the custom type of PreviousVersion. A: Are one of your columns an array type? If so, you might want to call Update.Push OR Update.PushAll for that column, and if PreviousVersion is already a BsonDocument you probably don't need to convert again A: Are you sure of your SortBy.Descending ? The api does not state that you could use somehting else than string[] as parameter (http://api.mongodb.org/csharp/current/html/96408b4e-c537-0772-5556-6f43805dd4d4.htm) A: In the end, since I'm just tracking the history of the object, I ended up using .AddToSetWrapped<WikiHistory>("PreviousVersion", CurrentVersion) which just appends the item to the set in the object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Having problems binding data using % wildcards Using sqlite and building queries, they all work fine until I try to bind certain data into a query such as - NSString *query = @"SELECT id, title FROM fields WHERE (staff LIKE '%?%'); sqlite3_prepare_v2(lessonPlansDatabase, [query UTF8String], -1, &stmt, nil); NSString *theValue = @"Fred"; sqlite3_bind_text(stmt, 1, [theValue UTF8String], -1, NULL); The problem appears to be with using the '%'. I've tried putting it into the string which I'm binding, but that doesn't work either. If I just make the query in full, like - NSString *query = @"SELECT id, title FROM fields WHERE (staff LIKE '%Fred%'); and don't bind anything, it works fine. But I don't want to do this in case there are characters in the string which upset the query, I'd prefer to let sqlite do the binding. The binding works fine where there are no '%' characters. Any help much appreciated! A: You want NSString *query = @"SELECT id, title FROM fields WHERE (staff LIKE ?)"; sqlite3_prepare_v2(lessonPlansDatabase, [query UTF8String], -1, &stmt, nil); NSString *theValue = @"%Fred%"; sqlite3_bind_text(stmt, 1, [theValue UTF8String], -1, NULL); A: Escape the (%)s with (%) and try to bind text. (staff LIKE '%%?%%')
{ "language": "en", "url": "https://stackoverflow.com/questions/7635259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is MouseEvent a class or an instance of a class or both? I'm having trouble getting the hang of as3 syntax (php is the only other coding language I know) mybutton.addEventListener(MouseEvent.CLICK, myListenerFunction); function myListenerFunction(e:MouseEvent):void { // function body } In this code it seems like MouseEvent is an instance of the class MouseEvent. MouseEvent.CLICK However in this code it seems like e is an instance of class MouseEvent e:MouseEvent A: MouseEvent.CLICK is a class's public constant which can be accessed everywhere with no need to create an instance. It's like public static variable in php class. e:MouseEvent is an instance of MouseEvent class. Check out MouseEvent class documentation http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/MouseEvent.html A: MouseEvent.CLICK This is reference to a static constant of the MouseEvent class. So to answer your question, MouseEvent here is a reference to a Class. The CLICK Constant might be defined within the MouseEvent Class something like this: package flash.events { public class MouseEvent extends Event { ... public static const CLICK:String = "click"; ... } } So writing: trace(MouseEvent.CLICK); Would output the String: click A: MouseEvent.CLICK is a static member of MouseEvent. It contains a string, which is the event name. You could also use addEventListener("click", myListenerFunction), though that is less safe. I guess they just needed somewhere to put that constant. The MouseEvent-class instance contains information on what happened to trigger the event etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635261", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Piping into objects/properties/methods in PowerShell In PowerShell, you can pipe into Cmdlets and into scripted functions. But is it possible to pipe into objects, properties, or member functions? For example, if I have a database connection object $dbCon, I want to be able to so something like this: $dbCon.GetSomeRecords() | <code-to-manipulate-those-records | $dbCon.WriteBackRecords() I know the same functionality can be achieved with Foreach-Object or with a Cmdlet that gets the object as an argument - the reason I want to pipe directly to the object or to it's members is to achieve elegance and to keep the OOP style(using an object's method instead of sending the object as an argument) Is it possible? EDIT: It looks like people don't understand my question, so I need to clarify it: PowerShell can pipe to normal functions. I can Write: function ScriptedFunction { $input|foreach{"Got "+$_} } 1,2,3|ScriptedFunction And get Got 1 Got 2 Got 3 As the result. But when I try to use that technique with a scripted method: $object=New-Object System.Object $object|Add-Member -MemberType ScriptMethod -Name ScriptedMethod -Value {$input|foreach{"Got "+$_}} 1,2,3|$object.ScriptedMethod I get an error message: Expressions are only allowed as the first element of a pipeline.(adding () does not help BTW). What I'm looking for is a way to make that command work the same way it works with global functions. A: This is not exactly what you are asking for but this has almost the same syntax: use a NoteProperty instead of a ScriptedMethod and call it using operators . or &: $object = New-Object System.Object $object | Add-Member -MemberType NoteProperty -Name Script -Value {$input|foreach{"Got "+$_}} 1,2,3 | & $object.Script Output Got 1 Got 2 Got 3 BUT: There is a caveat, perhaps a show stopper: this is not a script method at all, there will be no $this defined by the core for it (you can define $this = $object before invocation yourself but this is rather ugly, to send $object as a parameter would be better). A: If I'm following, you can attach new script methods to exiting objects with the Add-Member cmdlet (take a look at Example code #4 in help). You can also add them in a Type file (xml) and load the file with the Update-TypeData cmdlet so they become available automatically when you have certain type of objects in hand. UPDATE You cannot pipe to methods. Methods you add are avaiable on the objects: function ScriptedFunction { process { $object = $_ $object = $object | Add-Member -MemberType ScriptMethod -Name Increment -Value {$this+1} -PassThru -Force $object } } $newObjects = 1,2,3 | ScriptedFunction # increment the first object, its value is one, when the # Incereent method is invoked you get 2 $newObjects[0].Increment() 2
{ "language": "en", "url": "https://stackoverflow.com/questions/7635262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Haskell - declare/use data It's my first time to use data types in Haskell. Got a problem and I don't know how to improve the code. Here is the problem: Declear a data type called "Consonant" which include some letters(string), and an textstring which got the information about if all the letters in that word are consonant or not (string), then write a function "Cheak" which got indata (some letters to cheak) and outdata (the data type "Consonant"). Here is my code: module Consonant where import Char type Name = String type ConOrNot = String data Consonant = Cons Name ConOrNot deriving (Show,Eq) isVowel = "AEIOU" cheak :: String -> Consonant cheak [] = "" cheak (char:chars) = if elem (toUpper char) isVowel == false then cheak chars else cheak = Cons (char:chars) "Not Consonant" -- here I want to use "break", but I don't know how to use it in Haskell... cheak = Cons (char:chars) "Is Consonant" It doesn't work... How to change the code? Pls help! Thank you! Update: module Consonant where import Char type Word = String type ConOrNot = String data Consonant = Cons Word ConOrNot deriving (Show,Eq) isConsonant = "BCDFGHJKLMNPQRSTVWXYZ" cheak :: String -> Consonant cheak [] = Cons "" "" cheak (char:chars) |elem (toUpper char) isCosonant = cheak chars --if all the letters are cosonant, I want it return (Cons (char:chars) "is Consonant").. still working on it |otherwise = Cons (char:chars) "Not Consonant" It works now if the string got both vowels and consonant or only vowels, how to improve the code so it also works with only consonants? A: This is homework, isn't it? Issues with your code include: * *This line makes no sense: cheak [] = "" because cheak is supposed to return a Consonant, but here you return a String. *This line also makes no sense: cheak = Cons (seq:seqs) "Is Consonant" beacause cheak is supposed to take a String parameter and return a Consonant, but here you just return a Consonant without taking any parameter. *This line makes even less sense: else cheak = Cons (seq:seqs) "Not Consonant" Haskell is not Pascal or Visual Basic. You return a value from a function by letting the RHS of the equation evaluate to that value. *Indentation matters. *There is a function called break in Haskell, but it is unrelated to the break keyword you may be familiar with from Java or C. The Java/C concept of breaking out of a loop doesn't exist in Haskell. *You probably want to use a helper function. *"Cheak" isn't a word. *if-then-else is not a statement. The then-branch and the else-branch are not statements either. They're all expressions. It's like ?: from Java, C and some other languages. A: I'm not entirely sure what you are asking for. Is the Word in the returned Cons supposed to be the Word passed to cheak or the remainder of the Word starting from the first vowel? Does this do what you want? module Consonant where import Data.Char type Word = String type ConOrNot = String data Consonant = Cons Word ConOrNot deriving (Show,Eq) cheak :: Word -> Consonant cheak "" = Cons "" "" cheak s = Cons s $ if any isVowel s then "Not Consonant" else "is Consonant" where isVowel c = (toUpper c) `elem` "AEIOU" A: There are many ways to do what you want to do in Haskell. The obvious first choices are Maybe and Either. But in general, checkout the 8 ways to report errors in Haskell .
{ "language": "en", "url": "https://stackoverflow.com/questions/7635263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL Server - XML Validation: Invalid simple type value I'm trying to validate an XML input against an XML Schema in SQL Server 2005 and I get an error when validating the e-mail: Msg 6926, Level 16, State 1, Line 4 XML Validation: Invalid simple type value: 'john_doe@yahoo.com'. Location: /:xxx[1]/:yyy[1]/*:Email[1] The email field is defined in the schema as: <xsd:simpleType name="EMailType"> <xsd:restriction base="xsd:string"> <xsd:pattern value="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" /> </xsd:restriction> </xsd:simpleType> Every email address that matches the regexp is considered valid except for something with underscores in it (johnDoe@yahoo.com is OK, john.doe@yahoo.com is OK, but john_doe@yahoo.com is not). If I remove the underscore the XML is validated. I've tested my regexp (which is the one you can find on MSDN for validating emails) with various tools and they all say it's valid. But not SQL Server. Why does it not validate underscores? Is there something special I must do in SQL Server? A: Found a link about the issue with a workaround. http://www.agilior.pt/blogs/rodrigo.guerreiro/archive/2008/11/14/5965.aspx Apparently \w should include the underscore and does so except when it comes to handling XSD schemas. So this is not a specific SQL Server problem. I have the exact same behavior when validating an XML using XMLSpy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Can I load flex components asynchronously? I have a flex application that shows information gathered from different external services by using rest api. Some of them are resource intensive, take longer to response. Is there any way I can load the different components asyncronously? A: ActionScript (Flex) executes asynchronously by default. So, if you make concurrent calls to a service, ensure that your code handles the results appropriately (via Event handlers). By default, making a request to a web service operation that is already executing does not cancel the existing request. So, simply invoke your services, and register (result/failure) event handlers on them to capture their responses, and load the components accordingly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to access private key from eToken with jsp It's my first time to here, so please forgive me at first time if I make mistake. I am new to RSA(Cryptography), My requirement is, accessing private key from eToken for decryption and store decrypted data in a file. I want to ask here that where to find private key & how to access it via jsp page? I am using Spring 3 and RSA. Please share resource if any available. Thanks A: Is the "eToken" the product described here? If so, it's basically a smartcard, which means you can't extract the private key. The way you'd use it is to send the encrypted data to the token and have it decrypt for you. You said you're using JSP. Are you trying to utilize an eToken plugged into your server, or into the client's PC? A JSP page on your server can't talk to devices plugged into the client's PC; you'd need an application running on the client (maybe a browser plugin) to do it on your behalf. If it were possible for a website to extract the private key from a user's eToken, the eToken would be worthless as a security product.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Magento vs. I have seen in at least one layout xml file the use of the <layoutUpdate> xml node in place of the typical <layout version="0.1.0"> node. I have scoured the interwebs as well as any Magento Layout books and documents I have but I can't find an explanation about this. I initially thought there was a difference in the order in which it applies the updates, but that doesn't seem to be the case after further testing. Can someone explain what (if any) differences there are between the two? Thanks! Example Typical layout update XML file structure: <?xml version="1.0"?> <layout version="0.1.0"> <some_handle> <reference name"some-block"> ... </reference> </some_handle> </layout> A different version that still seems to work: <?xml version="1.0"?> <layoutUpdate> <some_handle> <reference name"some-block"> ... </reference> </some_handle> </layoutUpdate> Is there any functional difference between these 2? A: The tag is supposed to be <layout />. However, in current versions of Magento (and likely future versions), the name of this tag doesn't matter. Those files are all combined into a single XML tree. The code Magento uses to load those files into a single tree looks like this $fileStr = file_get_contents($filename); $fileStr = str_replace($this->_subst['from'], $this->_subst['to'], $fileStr); $fileXml = simplexml_load_string($fileStr, $elementClass); if (!$fileXml instanceof SimpleXMLElement) { continue; } $layoutStr .= $fileXml->innerXml(); The last line ($fileXml->innerXml();) is the one we're interested in, . The innerXml method works just like the browser DOM method of the same name. All the child nodes will be extracted into a string, but the root node will be ignored. You could name it <layout />, <layoutUpdate />, <i♥magento />. It currently doesn't matter. That said, you should name it <layout /> to avoid confusing people. A: Module layout update XML files contain the root node <layout />. Any top-level node contained by this root node is a layout update handle. Layout update handles are used to contain sets of layout update XML directives. The version number for the root node is not ever evaluated (to my knowledge). Layout update handles are essentially arbitrary, and may be any XML-safe string. Depending on how or if the controller action handling the request is using layout updates, certain layout update handles are called into scope. For more information on the related methods see the following: Mage_Core_Controller_Varien_Action's loadLayout() and renderLayout() methods, Mage_Core_Model_Layout, and Mage_Core_Model_Layout_Update.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to detect if a click() is a mouse click or triggered by some code? How to detect if a click() is a mouse click or triggered by some code? A: Wait for some time and use event.isTrusted - its supported by IE9, Opera 12, and Firefox Nightly. Webkit will support it too, most probably. Currently, there is no guaranteed way to know. A: Use the which property of the event object. It should be undefined for code-triggered events: $("#someElem").click(function(e) { if(e.which) { //Actually clicked } else { //Triggered by code } }); Here's a working example of the above. Update based on comments Pressing the Enter key when an input element has focus can trigger the click event. If you want to distinguish between code-triggered clicks and all other clicks (mouse or keyboard triggered) then the above method should work fine. A: You should check e.originalEvent: $("#someElem").click(function(e) { if(e.originalEvent === undefined) { //triggered } else { //clicked by user } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7635274", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Should or can an iphone app have a like button I have just implemented FB login and status updates in my app following the sample app in the IOS SDK. I know it is common practice to have a like button for a page but is it also true for an app? I mean is it possible to have a like button in my app that when tapped makes an entry on my FB page stating I like the app? I can't seem to track the like feature down in the docs :-( Thanks A: basically you can add UIWebView and put your html tags inside it check this and this sample they may help you
{ "language": "en", "url": "https://stackoverflow.com/questions/7635275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to properly scroll an overflowing div based on mouse position within its container I am working on a small jQuery plugin that autoscrolls through a set of overflowing elements within a container div based on the mouse position within that container div. See the Demo Here The idea is for this plugin to be an improvement of something I wrote a while ago. See the autoscrolling navigation in the lower left here The old problem with this was that it jumps around when you mouseenter from anywhere but the bottom(javascript perspective) of the container div. Now everything is working fine with my plugin but when you mouseenter from the top it screws up from time to time(move your mouse in and out fast and it will happen for sure), I think this is because I am getting different values from my mouseenter event and my mousemove event which are both used to calculate how to scroll the inner elements. Here is the function, the rest of the source is pretty small and decently commented. projList.mousemove(function(e){ //keep it from freaking out when we mouseenter from Top of div if(enterMouseY > divHeight){ enterMouseY = divHeight; } mouseY = e.pageY-projList.offset().top; //ok that didnt work... try to keep it from freaking out when we mouseenter from Top of div if (mouseY > divHeight){ mouseY = divHeight; } //distnace from top of container div to where our mouse Entered var distToTop = divHeight - enterMouseY; //here is the calculation, I parameterize the mouseY pos as a value between 0-1 //0 being where we entered and 1 being the top or bottom of the div //then multiply that by how much we have to scroll to get to the end of the list //are we moving up or down if(mouseY>enterMouseY){ //if up calculate based on Top var dist =totalScrollDistance * ((mouseY-enterMouseY-projList.offset().top)/(distToTop)); }else if(mouseY<enterMouseY){ //if up calculate based on Bottom var dist =totalScrollDistance * ((mouseY-enterMouseY-projList.offset().top)/(enterMouseY)); }else if(mouseY = enterMouseY){ var dist = 0; } //set the position of the list offsetting wherever we left it pos = dist+lastPos; //scroll to that position projList.scrollTop(pos); //are we trying to scroll past the scrollable amount if(pos<0){ pos = 0; } if(pos>totalScrollDistance){ pos = totalScrollDistance; } $('#div1').text("mouseY: "+ mouseY +" enterMouseY: "+ enterMouseY +" distance:"+ dist.toFixed(1) + " pos:"+ pos.toFixed(1)); }); A: I solved this problem, there was an error in my calculations, but works how I described above. You can see it in action here http://web.archive.org/web/20130529212243/http://www.robincwillis.com/AutoScroll/
{ "language": "en", "url": "https://stackoverflow.com/questions/7635276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get count of selected column out of DataGridView What do I have: * *Filled datagridview *Selected cells of this grid What do I want: * *Amount of unique columns of the selected cells *Names of these columns What I found: int selectedColumnsCount = dataGridView3.SelectedColumns.Count; Somehow this piece of code isn't working in my case. My question: How can I get the columns name and the amount of columns selected out of a DataGridView? This is what I created now: int selectedCellCount = dataGridView3.GetCellCount(DataGridViewElementStates.Selected); int selectedcolumncount = dataGridView3.SelectedColumns.Count; ArrayList arr = new ArrayList(); int j = 0; if (selectedCellCount > 0) { for (int i = 0; i < selectedCellCount; i++) { int Xcor2 = int.Parse(dataGridView3.SelectedCells[i].ColumnIndex.ToString()); test = test + dataGridView3.Columns[Xcor2].Name; arr.Add(dataGridView3.Columns[Xcor2].Name); } } ArrayList arr2 = new ArrayList(); foreach (string str in arr) { if (!arr2.Contains(str)) { arr2.Add(str); j++; } } This is what I made myself, not that nice but its working to get the count of columns if anyone has a better way of realizing this, feel free to add A: You can register for the SelectionChanged event and process the SelectedCells. For example public Form1() { InitializeComponent(); dataGridView1.SelectionChanged += new EventHandler(dataGridView1_SelectionChanged); } HashSet<int> column_indicies = new HashSet<int>(); HashSet<string> column_names = new HashSet<string>(); int number_of_columns = 0; void dataGridView1_SelectionChanged(object sender, EventArgs e) { column_indicies.Clear(); column_names.Clear(); foreach (DataGridViewCell cell in dataGridView1.SelectedCells) { // Set of column indicies column_indicies.Add(cell.ColumnIndex); // Set of column names column_names.Add(dataGridView1.Columns[cell.ColumnIndex].Name); } // Number of columns the selection ranges over number_of_columns = column_indicies.Count; } A: You cannot select columns. Only one columns can be selected at a time! Columns are the same as Rows. Or did you mean to get those columns, which cells are slected? A: Ok, this is one of the way of getting column names (you can even use HeaderText property instead of Name): List<DataGridViewColumn> listOfColumns = new List<DataGridViewColumn>(); foreach (DataGridViewCell cell in dataGridView1.SelectedCells) { DataGridViewColumn col = dataGridView1.Columns[cell.ColumnIndex] as DataGridViewColumn; if (!listOfColumns.Contains(col)) listOfColumns.Add(col); } StringBuilder sb =new StringBuilder(); foreach (DataGridViewColumn col in listOfColumns) sb.AppendLine(col.Name); MessageBox.Show("Column names of selected cells are:\n" + sb.ToString());
{ "language": "en", "url": "https://stackoverflow.com/questions/7635282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Calling C function from lua Can someone tell me is it possible to somehow call c function or simply wrap it into a lua function WITHOUT building a new module. A: If it works for you, try the FFI library. See also luaffi. A: Lua can't call arbitrary C functions - they have to be bound to something in the Lua namespace first. (This is intentional to prevent breaking out of sandboxes in embedded applications.) A: Or the Alien library.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to write an 8 bit grey scale tiff with Java? I am trying to write a grey scale image to an TIFF file using Sanselan. Obviously would like the save the data to be 8 bit grey scale file but somehow I always end up with a 24 bit colour file. I have searched for file formats in general and ExifTagConstants.EXIF_TAG_PIXEL_FORMAT in particular but was unable to find anything helpful. I also considered colour profiles but there seem to be none for grey scale images. But then they all have wacky names — I might just have overlooked the right one. Or do I have to use a different library? Here the code I use (without business logic and experimental stuff: Test_Only_Sanselan: try { final Map <String, Object> parameter = new HashMap <>(); parameter.put(org.apache.sanselan.SanselanConstants.PARAM_KEY_COMPRESSION, org.apache.sanselan.formats.tiff.constants.TiffConstants.TIFF_COMPRESSION_UNCOMPRESSED); final java.io.OutputStream output = new java.io.FileOutputStream("Test-1.tiff"); org.apache.sanselan.Sanselan.writeImage(image, output, org.apache.sanselan.ImageFormat.IMAGE_FORMAT_TIFF, parameter); output.close(); } catch (final IOException exception) { LdfImage.log.info("! Could not create tiff image.", exception); } catch (final org.apache.sanselan.ImageWriteException exception) { LdfImage.log.info("! Could not create tiff image.", exception); } I wonder if I need to add a special parameter. But I have not found a useful parameter yet. The following is a test of the Java 7 image writer which creates a correct grey scale image. But as PNG and not TIFF: Test_Only_Java_7: try { final java.util.Iterator imageWriters = javax.imageio.ImageIO.getImageWritersByMIMEType ("image/png"); final javax.imageio.ImageWriter imageWriter = (javax.imageio.ImageWriter) imageWriters.next(); final java.io.File file = new java.io.File("Test-2.png"); final javax.imageio.stream.ImageOutputStream output = javax.imageio.ImageIO.createImageOutputStream(file); imageWriter.setOutput(output); imageWriter.write(image); } catch (final IOException exception) { LdfImage.log.info("! Could not create tiff image.", exception); } Is there a TIFF pug-in for imageio? A: I'm not familiar with Sanselan but I see there is a ImageInfo.COLOR_TYPE_GRAYSCALE constant, I'm guessing it could be used in the params parameter map given to writeImage. I didn't find the javadoc for Sanselan, their link is broken, would you have one more up-to-date? If you want to use JAI you can get your inspiration here: void get8bitImage(byte[] data, int width, int height) { BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); byte[] rasterData = ((DataBufferByte)image.getRaster().getDataBuffer()).getData(); System.arraycopy(pixels, 0, rasterData, 0, pixels.length); // A LOT faster than 'setData()' } void main(String[] argv) { TIFFEncodeParam ep = new TIFFEncodeParam(); FileOutputStream out = new FileOutputStream("c:\\test.tiff"); BufferedImage img = get8bitImage(myData); ImageEncoder encoder = ImageCodec.createImageEncoder("tiff", out, ep); encoder.encode(img); } Be sure that the BufferedImage has BufferedImage.TYPE_BYTE_GRAY as imageType.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I let a user navigate and play a playlist using the HTML5 tag? I want to link a playlist with the <audio> element in HTML5, so that: * *When one song in the list ends, the next song starts automatically *The user can switch to the next or previous song in the playlist How can this be achieved through HTML5, JavaScript etc.? I'm using ASP.NET at the backend. Also, can I give user the liberty to play any song from his/her playlist alongside the audio player? My friend told me that it can be achieved by tweaking its DOM (Document Object Model). Please help how can it be achieved? A: How about jQuery HTML5 Audio Player? http://www.jplayer.org/latest/demo-02/
{ "language": "en", "url": "https://stackoverflow.com/questions/7635295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Jquery replace text live doesn't works this is my js. $('.wysiwyg').live('keyup',function(){ wysiwyg_val = $(this).val(); wysiwyg_val = wysiwyg_val .replace(/\n/g, "<br />") .replace(/\n\n+/g, '<br /><br />') .replace("{code}","<pre><code>") .replace("{/code}","</code></pre>") .replace("{img}",'<img src="http://localhost/CI_DEVBASE/img/logo.png" width="150" height="50"') .replace("{/img}",'/>'); $('.wysiwyg-preview').html(wysiwyg_val); }); the html is. <textarea class="wysiwyg"></textarea> <div class="wysiwyg-preview"></div> this code works if i put just 1 {code}{/code} inside the textarea, but if i put 2 {code}{/code} {code}{/code} it replaces only the first one, how can i apply this function to all the text inside wysiwyg_val ? A: g should be used for global replacement. Also I have used \ to escape special characters like {,/ etc. Here's the corrected code for you: wysiwyg_val = wysiwyg_val .replace(/\n/g, "<br />") .replace(/\n\n+/g, '<br /><br />') .replace(/\{code\}/g,"<pre><code>") .replace(/\{\/code\}/g,"</code></pre>") .replace(/\{img\}/g,'<img src="http://localhost/CI_DEVBASE/img/logo.png" width="150" height="50"') .replace(/\{\/img\}/g,'/>'); A: Hej Ispuk you already have the solution in your code .replace(/\n/g, "<br />") the g tels it to do it globally. Use the same technique with the code blocks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Perl passing data to stdin and reading from stdout and stderr There might be many questions available here regarding the same, but none works for me as of now. I've a C program as follows: #include <stdio.h> #include <sys/stat.h> long size(FILE *st_in) { struct stat st; if (fstat(fileno(st_in), &st) == 0) return st.st_size; return -1; } int main (){ FILE *file = stdin; long s1, s2; s1 = size(file); printf("Size is %ld\n", s1); fprintf(stderr, "%d", 1); return 0; } I compile it as an output a.out. I've an xml file 'sample.xml' <sample> <tag>Hello</tag> <tag>Cool</tag> </sample> Then I've this perl code #!/usr/bin/perl use warnings; use IPC::Open2; open FILE, "sample.xml" or die $!; my @xmlfile = <FILE>; my $pid = open2(*Reader, *Writer, "./a.out"); print Writer "@xmlfile"; waitpid($pid, 0); my @got = <Reader>; close Writer; close Reader; close $pid; print "Output got is\n"; print @got; If I run the C program passing simple.xml via stdin, I get the following: [bharath@xml 18:22:34]$ ./a.out < sample.xml Size is 60 When I run the perl code, I expect the size as 60. But I get as 0. [bharath@xml 18:22:42]$ ./firmware.pl Output got is Size is 0 So how do I solve this? I need to pass the sample.xml from an @array in perl. And the stderr integer from the C program should get stored in a separate variable and the stdout from the C program should get stored in another separate variable in perl. I think this might require using open3 but I don't know how to use. Any working example would be highly appreciated. A: UPDATE: as for your comments Ilmari Karonen already explained you that a pipe doesn't have a filesize because it's a stream of data, the program doesn't know how big this stream could be. You've two problems: your C program is not working and also your Perl program is not working because it goes in a deadlock. You can't test the two things together. Separate the two problems. For instance first try your program with the pipe from the shell. cat sample.xml | ./a.out Size is 60 Originally it wasn't working. To make it work I've used this modified C program: the size could be calculated from the stream by counting all received chars until EOF. #include <stdio.h> int main (){ long size = 0; int ch; FILE *file = stdin; if (!file) { return 2; } while ((ch = getc(file)) != EOF) { ++size; } printf("Size is %ld\n", size); fprintf(stderr, "%d", 1); return 0; } As for your Perl program you had a deadlock because both programs were in wait state, to solve it I've changed slightly the order of the instructions: #!/usr/bin/perl -w use strict; use IPC::Open2; open FILE, "sample.xml" or die $!; my @xmlfile = <FILE>; my $pid = open2(*Reader, *Writer, './a.out 2> /dev/null'); print Writer @xmlfile; close(Writer); my @got = <Reader>; close(Reader); waitpid($pid, 0); print "Output got is: "; print @got; As you can see I close the writer, before I start to read because my C program is designed to get all the input and then do the output. And now the whole interprocess communication will work: ./program.pl Output got is: Size is 60 As a side note you don't need to close $pid, since is just a number representing the process id of the child. In other cases you might want to explore non blocking reads, but will make the logic more complicated. ORIGINAL ANSWER: didn't solve the poster problem because he wanted to use IPC. Can you just add the filename as sample.xml to the $cmd? You could just use the backtick operator to capture the output, chomp removes the newline and the output will be in $out. #!/usr/bin/perl $cmd = './a.out < sample.xml 2> /dev/null'; $out = `$cmd`; chomp $out; print "out='$out'\n"; I guess that your example is to find a way to communicate between C and Perl, because of course, if it's just for the file size it's much easier in Perl: #!/usr/bin/perl print -s 'sample.xml'; print "\n"; A: I'm pretty sure the problem is not in your Perl code, but in the C program. Try running cat sample.xml | ./a.out in shell, and you should get the same output as from your Perl program. The problem is that, in both cases, stdin will be a pipe instead of a file, and fstat() obviously can't return any meaningful size for a pipe. In any case, calling fstat() on stdin seems like bad practice to me — you shouldn't be relying on what is essentially an optimization made by the shell. The only real guarantee you get about stdin is that you can (try to) read data from it; other than that, it might be anything: a file, a pipe, a tty, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635298", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Access: Min function error on report page header I am trying to get the min() and max() date of the current query to display on the Page Header section. My textbox is as follows ="Range date: " & Min([myDate]) & " to " & Max([myDate]) I am getting the #Error message on Access 2010 (MS Access 2003 file format, .mdb). A: In the page header, you will need DMin and DMax, as far as I recall. -- http://msdn.microsoft.com/en-us/library/aa159048(v=office.10).aspx A: * *AFAIK, you can't use those in the page header, but you can use them in a group header/footer and in report header/footer. And you can force new page in a group headre/footer. *Otherwise, you will need a report level variable that you increment in the Detail_Format section, and that you reset in the PageHeaderSection_Format. *You could also have a control in the page header that refers to the one in the group header. That might be the easiest solution. A: If I needed this, I'd tend to put it in the report's Recordsource, and then the values would be available anywhere in the report.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Adding FileUpload control via code-behind Because of the environment I work in I need to add controls to a page via code-behind. I have done it dozens of times. For some reason the FileUpload control is giving me grief. here is my code: FileUpload fileUpload = new FileUpload(); fileUpload.ID = "FileUploadControl"; this.Controls.Add(fileUpload); The page looks as though it is timing out and display this error, "Internet Explorer cannot display the webpage". When I remove the last line (the Add), then the page renders just fine. Any ideas? Thanks!! A: You didn't mentioned which event handler you have used. Please try this, FileUpload file; protected void Page_Load(object sender, EventArgs e) { file= new FileUpload(); PlaceHolder1.Controls.Add(file); } protected void Button1_Click(object sender, EventArgs e) { if(file.HasFile) { file.SaveAs(MapPath("~/" + file.FileName)); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7635303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ASP.NET MySQL WebApp Architecture I'd like to know the best architecture. We have a web application running different domains. Each domain has its own MySQL database but the db structure is the same for all of them. * *We have a web application for the visible part of the application. *We have a dataLogic project *We have a dataEntities project *We have a dataAccess that contains only the methods to connect to the data base. Before we called stored procedures on a database. But we had to change it because the performance was bad. Also, the problem was that every change we made we had in a stored procedure we had to copy to every database. We are thinking in using a WebService to retrieve the data. Every domain can call the web service with a connection string and connect its database to retrieve data. This way when we change a SQL query we only have to compile the webService and change it, we don't have to change versions on multiples domains. Also, what do you think about the SQL queries? Since we don't want to keep using stored procedures, what is the best way to do it? Directly from code? Thanks T A: If you have multiple Database servers you will have to make Structural changes from one DB to another one way or another. There are many tools to change Database structures. These tools will look for differences between Schema, and will either generate the SQL code for you, or do the changes by itself (it depends a lot in the tool, there are powerful ones and not so powerful ones). Please do take a look at Toad for MySql. Now, for the Data changes, you may want to replicate the data from one Database to another. This is done through Replication. We are thinking in using a WebService to retrieve the data. Every domain can call the web service with a connection string and connect its database to retrieve data. This sounds like a good idea and since you already have "dataAccess" and "dataLogic" projects, it should not be too hard to make the services. Also, what do you think about the SQL queries? Since we don't want to keep using stored procedures, what is the best way to do it? Directly from code? I don't think it is a good practice to have the SQL queries directly into your code, but it depends in a lot of things, so I would suggest Stored Procedure vs Hard-Coding the queries, or LinQ (Entity Framework 4.1). Good luck with your project and I will take a look at this thread frequently to see what you end up doing. Have fun! Hanlet
{ "language": "en", "url": "https://stackoverflow.com/questions/7635306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: changing property from another viewmodel Im trying to "connect" two viewModels, clicking a button in one, to trigger/change observable in another viewmodel. knockout v 1.3 something like this: http://jsfiddle.net/ffBDr/9/ thanks A: I think that you could choose to explicitly indicate which model to communicate with like: http://jsfiddle.net/CG5LW/ function BoxA() { this.Imlistening=ko.observable(''); this.tellThem = function(){ if (this.whoToTell) { this.whoToTell.Imlistening("message from A"); } }; } function BoxB() { this.Imlistening=ko.observable(''); this.tellThem = function(){ if (this.whoToTell) { this.whoToTell.Imlistening("message from B"); } }; } function appViewModel() { this.BoxA = new BoxA(); this.BoxB = new BoxB(); this.BoxA.whoToTell = this.BoxB; this.BoxB.whoToTell = this.BoxA; }; or you could use subscriptions like: http://jsfiddle.net/CG5LW/1/ function BoxA() { this.Imlistening=ko.observable(''); this.message = ko.observable(''); this.tellThem = function(){ this.message("message from A"); }; } function BoxB() { this.Imlistening=ko.observable(''); this.message = ko.observable(''); this.tellThem = function(){ this.message("message from B"); }; } function appViewModel() { this.BoxA = new BoxA(); this.BoxB = new BoxB(); function receiveMessage(newValue) { this.Imlistening(newValue); } this.BoxA.message.subscribe(receiveMessage, this.BoxB); this.BoxB.message.subscribe(receiveMessage, this.BoxA); };
{ "language": "en", "url": "https://stackoverflow.com/questions/7635307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: No expected output for my performance testing I want to do a performance test for my rails 3 app and I did a try according to the rails online guide rake test:profile and it gave some output as: Specify ruby-prof as application's dependency in Gemfile to run benchmarks. Loaded suite /usr/local/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/rake_test_loader Started . Finished in 0.326233 seconds. 1 tests, 0 assertions, 0 failures, 0 errors, 0 skips But according to the guide, there should be something like: BrowsingTest#test_homepage (31 ms warmup) wall_time: 6 ms memory: 437.27 KB objects: 5,514 gc_runs: 0 gc_time: 19 ms and also some log files produced in app's tmp/performance dir, which doesn't exist in my case. The performance test is the generated sample test, browsing_test.rb, in my app's test\performance dir: require 'test_helper' require 'rails/performance_test_help' # Profiling results for each test method are written to tmp/performance. class BrowsingTest < ActionDispatch::PerformanceTest def test_homepage get '/' end end And my rails version is 3.0.10. Can anyone give me some tips or hints? A: Had the exact same issue, and solved it by running rvm install 1.9.2-p290 --patch gcdata # Make sure you have the same patch version (note: not sure how much that step helped since I had an error, but since it's part of what I did...) Adding to my gemfile gem 'ruby-prof', :git => 'git://github.com/wycats/ruby-prof.git' gem 'test-unit' And of course running bundle install Some reading that helped me * *http://rubylearning.com/blog/2011/08/14/performance-testing-rails-applications-how-to/ *https://rails.lighthouseapp.com/projects/8994/tickets/4171-fresh-rails-3-app-cannot-run-performance-tests *http://guides.rubyonrails.org/performance_testing.html#installing-gc-patched-mri
{ "language": "en", "url": "https://stackoverflow.com/questions/7635308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Outlook Synchronization - Outlook 2010 and SP 2010 I'm using SharePoint 2010 and I want outlook to reflect whatever tasks I create/update/delete in my SharePoint site. How can I synchronize tasks from SharePoint to Outlook? A: Go to the tasks list and click on the "Connect to Outlook" button in the list ribbon. This will open your outlook and connect the task list. Every update you make in Sharepoint will be reflected in Outlook and viceversa. You can work with Outlook in offline mode and synchronize tasks when you go back online.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java Class Dynamically with Constructor parameter I have to create a class dynamically but I want to use class constructor passing parameter. Currently my code looks like Class<HsaInterface> _tempClass = (Class<HsaInterface>) Class.forName(hsaClass); _tempClass.getDeclaredConstructor(String.class); HsaInterface hsaAdapter = _tempClass.newInstance(); hsaAdapter.executeRequestTxn(txnData); How can I call the constructor with the parameter ? A: Class<HsaInterface> _tempClass = (Class<HsaInterface>) Class.forName(hsaClass); // Gets the constructor instance and turns on the accessible flag Constructor ctor = _tempClass.getDeclaredConstructor(String.class); ctor.setAccessible(true); // Appends constructor parameters HsaInterface hsaAdapter = ctor.newInstance("parameter"); hsaAdapter.executeRequestTxn(txnData); A: You got close, getDeclaredConstructor() returns a Constructor object you're supposed to be using. Also, you need to pass a String object to the newInstance() method of that Constructor. Class<HsaInterface> _tempClass = (Class<HsaInterface>) Class.forName(hsaClass); Constructor<HsaInterface> ctor = _tempClass.getDeclaredConstructor(String.class); HsaInterface hsaAdapter = ctor.newInstance(aString); hsaAdapter.executeRequestTxn(txnData); A: Constructor constructor = _tempClass.getDeclaredConstructor(String.class); Object obj = constructor.newInstance("some string");
{ "language": "en", "url": "https://stackoverflow.com/questions/7635313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to get RSS date using Universal Feed Parser I have a RSS feed which have the data in the following format: <item> <title><![CDATA[à¨ç·à«çµàµÍÃì-JETSETER-»Å×éÁ-½Ñ¹à»ç¹¨ÃÔ§-¤Í¹àÊÔÃìµãË­è¤ÃÑé§áá㹪ÕÇÔµ-REDioactive-Presents-Jetseter-Music-Inspiration-Concert ]]></title> <link>http://www.thaiticketmajor.com/»ÃЪÒÊÑÁ¾Ñ¹¸ìÅÙ¡¤éÒ/à¨ç·à«çµàµÍÃì-JETSETER-»Å×éÁ-½Ñ¹à»ç¹¨ÃÔ§-¤Í¹àÊÔÃìµãË­è¤ÃÑé§áá㹪ÕÇÔµ-REDioactive-Presents-Jetseter-Music-Inspiration-Concert-1012.html</link> <guid isPermaLink="false">http://www.thaiticketmajor.com/»ÃЪÒÊÑÁ¾Ñ¹¸ìÅÙ¡¤éÒ/à¨ç·à«çµàµÍÃì-JETSETER-»Å×éÁ-½Ñ¹à»ç¹¨ÃÔ§-¤Í¹àÊÔÃìµãË­è¤ÃÑé§áá㹪ÕÇÔµ-REDioactive-Presents-Jetseter-Music-Inspiration-Concert-1012.html</guid> <pubDate>Fri, 30 Sep 2011 12:06:38 +0700</pubDate> <description><![CDATA[<img src="http://www.majorcineplex.com/cropImage.php?imgName=http://www.thaiticketmajor.com/bus/imgUpload/newsThumb1012_jet-sm.jpg&w=70&h=33;c:width=50,height=50;file:rssimg.jpg"/> ¾º¡Ñº¤Í¹àÊÔÃìµãË­èàµçÁÃٻẺ¤ÃÑé§áá¢Í§ ǧà¨ç·à«çµàµÍÃì (JETSET'ER) ! ! ! ǧ´¹µÃÕ·Õè¼ÊÁ¼ÊÒ¹¤ÇÒÁʹء¡Ñºà¾Å§à¾ÃÒпѧʺÒÂàÍÒäÇé´éÇ¡ѹÍÂèҧŧµÑÇ ]]></description> </item> Now I want the date value that is present in pubDate, and I tried that by using : for entry in RSS_FEED.entries: FEED_TITLE = entry.title FEED_DESCRIPTION = entry.description FEED_DATE = entry.pubDate which result in error : raise AttributeError, "object has no attribute '%s'" % key then I tried Universal Feed Parser document and try using: FEED_DATE = str(entry.updated_parsed) Though I am not getting any error this time , but I am not getting the actual date tim ein pubDate field instead I am getting the values as below: Datetime.struct_time(tm_year=2011, tm_mon=9, tm_mday=30, tm_hour=11, tm_min=19, tm_sec=4, tm_wday=4, tm_yday=273, A: It's in the format of a time.struct_time class. You can convert it to a datetime object, or just access the properties, however you desire.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery Radio button I was wondering why this isn't working properly on IE, when you choose a radio button? <html> <head> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript"> $(document).ready(function() { $("input[name='crkbrd']").change(function(){ if ($("input[name='crkbrd']:checked").val() == 'Upload') { alert("Upload Your Own Ad"); } else if ($("input[name='crkbrd']:checked").val() == 'Edit') { alert("Edit Your Ad Here"); } else { alert("You haven't chosen anything"); } }); }); </script> </head> <body> <input type="radio" id="rb1" name="crkbrd" value="Upload" /> Upload Your Own Ad<br /> <input type="radio" id="rb2" name="crkbrd" value="Edit" /> Edit Your Ad Here </body> </html> A: IE has a bug with radio buttons in that it doesn't fire the change event until the radio button is blurred. Use the click event instead. Bug details: http://webbugtrack.blogspot.com/2007/11/bug-193-onchange-does-not-fire-properly.html Note this bug was fixed in IE9 (as long as you are running in standards mode) A: I have this working on IE 8, Firefox and chrome browsers Try assigning a class attribute to the radio buttons as: <input type="radio" id="rb1" name="crkbrd" value="Upload" class="myRadio" /> Upload Your Own Ad<br /> <input type="radio" id="rb2" name="crkbrd" value="Edit" class="myRadio" /> Edit Your Ad Here and then use the following: $( ".myRadio" ).change( function(){ if ($(this).val() == 'Upload') { alert("Upload Your Own Ad"); } else if ($(this).val() == 'Edit') { alert("Edit Your Ad Here"); } else { alert("You haven't chosen anything"); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7635320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby's variable swap: x,y = y,x -- seems to be slower with array references? I was just testing out some array operations and doing the ol'reverse-an-array problem (at high level) to see what the performance difference between Ruby's x,y = y,x swap and the typical use-a-temp-variable-to-swap method: # using Ruby's swap z = arr.length-1 for x in 0..(z/2) arr[x], arr[z - x] = arr[z - x], arr[x] end # using standard temp var z = arr.length-1 for x in 0..(z/2) temp = arr[x] arr[x] = arr[z - x] arr[z - x] = temp end Ruby's shortcut swap is about 40 percent slower. I'm guessing there's some kind of extra array reference that's done? But I don't see where that extra operation would be done...I just assumed Ruby did a temp-var-swap behind the scenes. edit: This is the benchmark I'm using: def speed_test(n) t = Time.now n.times do yield end Time.now - t end tn = speed_test(TIMES) do # code... end And the array is just: arr = 10000.times.map A: I'd guess that the problem is with your benchmark. Probably the first loop brings everything into the cache. Then the second loop runs identical code but it happens to be faster because the cache is fresh. As a quick check of this, try reversing the order of the two loops!
{ "language": "en", "url": "https://stackoverflow.com/questions/7635324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Odd date behaviour Using the following code, up until this week, the object was returning a drop-down with the "correct" weeks, i.e. week 36 as 5th september, 37 as 12th september, etc. Since the month has changed to October, the weeks are now being returned incorrectly. Code from LEAP.Schedule object: /* --- LEAP Namespace --- */ var LEAP = {}; /* --- LEAP.Schedule Object --- */ LEAP.Schedule = function(){//init this.weeks = []; this.calculateWeeks(); }; LEAP.Schedule.prototype.calculateWeeks = function(){ this.date = new Date ( 2011, 8, 5 ); // First week of new school year this.num = 36; // Calendar number of this week this.weeks.push(new LEAP.Schedule.week(this.date, this.num)); for (var i = 1; i < 51; i++) { var week = i * 7; var updated_date = new Date (); updated_date.setDate(this.date.getDate() + week); if (this.num > 51) { this.num = 0; } this.num++; this.weeks.push(new LEAP.Schedule.week(updated_date, this.num)); } }; LEAP.Schedule.prototype.getWeeks = function(){ return this.weeks; }; /* --- LEAP.Schedule.week Object --- */ LEAP.Schedule.week = function(n_date, n_week){ this.week = n_week; this.date = n_date; this.year = this.date.getFullYear(); this.month = this.date.getMonth(); this.month += 1; this.day = this.date.getDate(); var mydate = new Date(this.date); this.end_date = mydate.setDate(mydate.getDate() + 6); }; LEAP.Schedule.week.prototype.getJSDate = function(){ return this.date; }; LEAP.Schedule.week.prototype.getStartDate = function(){ return this.year + "-" + pad(this.month) + "-" + pad(this.day); }; LEAP.Schedule.week.prototype.getEndDate = function(){ end_of_week = new Date(this.end_date); var year = end_of_week.getFullYear(); var month = pad(end_of_week.getMonth() + 1); var day = pad(end_of_week.getDate()); return year + "-" + month + "-" + day; }; LEAP.Schedule.week.prototype.getLabel = function(){ return "Week " + this.week + ": " + this.day + (this.day==1||this.day==21||this.day==31?"st":this.day==2||this.day==22?"nd":this.day==3||this.day==23?"rd":"th") + " " + ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][this.month-1] + " " + this.year; }; pad = function (n) { return n>9 ? n : "0"+n; }; Code initialising/displaying this Object: WeeklyUpdate.init = function() { var Scheduleobject = new LEAP.Schedule(); var weeks = Scheduleobject.getWeeks(); var dispHTML = '<p>weeks.length: ' + weeks.length + '</p>'; for (var i = 0; i < weeks.length; i++) { if (i % 2 > 0) { dispHTML += '<div style="background:#ccc;">'; } else { dispHTML += '<div style="background:#fff;">'; } dispHTML += '<p>i: ' + i + '</p>'; dispHTML += '<p>getJSDate: ' + weeks[i].getJSDate() + '</p>'; dispHTML += '<p>getStartDate: ' + weeks[i].getStartDate() + '</p>'; dispHTML += '<p>getEndDate: ' + weeks[i].getEndDate() + '</p>'; dispHTML += '<p>getLabel: ' + weeks[i].getLabel() + '</p>'; dispHTML += '</div>'; } $('div#wrapper').html(dispHTML); //WeeklyUpdate.displayWeekFilter(weeks); } Output (trimmed after three weeks): weeks.length: 51 i: 0 getJSDate: Mon Sep 05 2011 00:00:00 GMT+0100 (GMT Daylight Time) getStartDate: 2011-09-05 getEndDate: 2011-09-11 getLabel: Week 36: 5th Sep 2011 i: 1 getJSDate: Wed Oct 12 2011 13:58:02 GMT+0100 (GMT Daylight Time) getStartDate: 2011-10-12 getEndDate: 2011-10-18 getLabel: Week 37: 12th Oct 2011 i: 2 getJSDate: Wed Oct 19 2011 13:58:02 GMT+0100 (GMT Daylight Time) getStartDate: 2011-10-19 getEndDate: 2011-10-25 getLabel: Week 38: 19th Oct 2011 I've looked through this a few times but I'm getting rather confused! Any ideas? I'm sure it's something pretty obvious. Cheers A: When you initialize a new Date() it defaults to the current date. getDate only refers to the day, not the month or year. Your code worked in September because that was the same as the start month, but since it is now October, you are offsetting from the wrong month. var updated_date = new Date (); should be var updated_date = new Date (2011, 8, 5); That way you are offsetting from the start of the school year, not today. Demo: http://jsfiddle.net/aXgk6/ A: Use this code, and change the base date to the this.week variable. I've also applied a change to the part of the code which determines a new week. Otherwise, you would be back near the end of this calender year, asking why your code is broken ;) LEAP.Schedule.prototype.calculateWeeks = function(){ this.date = new Date ( 2011, 8, 5 ); // First week of new school year this.num = 36; // Calendar number of this week this.weeks.push(new LEAP.Schedule.week(this.date, this.num)); var not_new = true; for (var i = 1; i < 51; i++) { var week = i * 7; var updated_date = new Date(this.date); updated_date.setDate(this.date.getDate() + week); if (not_new && updated_date.getYear() > this.date.getYear() ) { not_new = this.num = 0; } this.num++; this.weeks.push(new LEAP.Schedule.week(updated_date, this.num)); } };
{ "language": "en", "url": "https://stackoverflow.com/questions/7635325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Django query not working Here's the thing. I have a model called User and an attribute counter that counts the number of page access. So, if a user already exists, I have to query up the db and for that user only to increase in counter. Otherwise, create a new user. I have an annoying error in the get method. How can I surpass it? if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): u = form.save() try: obj = User.objects.get(user=u.user) obj.counter += 1 obj.ipaddress = request.META['REMOTE_ADDR'] obj.save() except Statistic.DoesNotExist: ip = request.META['REMOTE_ADDR'] obj = User(user=u.user, counter=1, ipaddress=ip) obj.save() return {'status': 'OK'} else: return {'errors': form.errors} return {'status': 'NOT OK. GET method'} Here's the errorget() returned more than one User -- it returned 2! Lookup parameters were A: Django has amazing documentation on their QuerySet API. https://docs.djangoproject.com/en/dev/ref/models/querysets/ get only returns exactly 1 queryset. If no queryset is found, or more then 1 queryset is returned, an error is raised. To catch this particular error you have to specify except User.MultipleObjectsReturned, A: This means there are multiple users matching the query in your database. get should be used to fetch only one. It seems you are already coding for this but I think you are catching the wrong exception type. Try changing except Statistic.DoesNotExist: To from django.core.exceptions import DoesNotExist except DoesNotExist:
{ "language": "en", "url": "https://stackoverflow.com/questions/7635339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change DatePicker DisplayDate? How can i change DatePicker DisplayDate from mm/dd/yyyy to yyyy-mm-dd ? A: Change the SelectedDateFormat to 'yyyy-MM-dd' If you want to set the culture correctly for your entire app, look at this question: StringFormat Localization issues in wpf. You need this code somewhere that runs on startup. FrameworkElement.LanguageProperty.OverrideMetadata( typeof(FrameworkElement), new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
{ "language": "en", "url": "https://stackoverflow.com/questions/7635346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: what's the most efficient way to implement a returned calculated value in C++? With the advent of rvalue references on top of Return Value Optimization, what would be the most efficient way to implement a core function like this? How can I improve this implementation or should I leave it alone? template <typename T> string to_string(const T& t) { stringstream ss; ss << t; return ss.str(); } Obviously, I want to avoid copying or allocating memory if I can. TIA. Edit: Thx to D. Rodriguez for that detailed answer. Now, I have a second part to my question. Is there a way to improve on this? #define to_cstr( T ) (to_string( T ).c_str()) Of course I would like to avoid MACROs if I can, but if I copy and paste the template code above to return ss.str().c_str() and const char*, the temporary doesn't live long enough; although the code seems to run, valgrind complains (red light). I haven't been able to come up with a cleaner solution than the MACRO above for to_cstr(). Any ideas how to improve, or should I also leave alone? * *Ken A: Just leave it alone, it is efficient as it is. Even with C++03 compilers, the compiler will optimize the copies away. Basically the compiler will make sure that the object in the calling code to to_string, the return statement of to_string, and the return statement of ss.str() all take exactly the same memory location. Which in turn means that there will be no copies. Outside of what the standard mandates, the calling conventions for the return statement of a function that returns by value an object that does not fit in the registers in all 32/64 compilers I know (including VS, gcc, intel, suncc) will pass a pointer to the location in memory where the function is to construct the returned object, so that code will be translated internally to something in the lines of: // Not valid C++! Just for illustration purposes template <typename T> to_string( uninitialized<string>* res, const T& t ) { stringstream ss; ss << t; stringstream::str( res, &ss ); // first argument is return location // second argument is `this` } A: Now, I have a second part to my question. Is there a way to improve on this? #define to_cstr( T ) (to_string( T ).c_str()) Of course I would like to avoid MACROs if I can, but if I copy and paste the template code above to return ss.str().c_str() and const char*, the temporary doesn't live long enough; although the code seems to run, valgrind complains (red light). You can make the compiler create a temporary value in the caller scope for you, so that the temporary lifetime corresponds to that of the expression where the temporary is created. Here is how: struct TmpStr { mutable std::string s; }; template<typename T> char const* to_cstr(T value, TmpStr const& tmp = TmpStr()) { tmp.s = to_string(value); // your original function return tmp.s.c_str(); // tmp lives in the scope of the caller } int main() { printf("%s\n", to_cstr(1)); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7635348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Android Database access from .NET application Hi we have an Android app that currently stores its data in xml files and are looking to move it to SQL Lite based database. The app is a consumer of data and data is added through a windows application after the phone is connected to the PC (Currently both are done through xml files on the SD card) If the data is stored on a SQLite database, is it possible to locate and connect to the database from a .NET application which can both enter and delete records from it. Please advise. Thanks, A: Yes. You will be able to connect and then manipulate a SQLite database from a .NET application. Use a data provider like System.Data.SQLite. The downloads are here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can I mock a protected superclass method call in Java? I have stumbled upon a testing problem of mocking a call of protected method from a super class. e.g. : public class A extends B { @Override protected int calculate(int x, int y) { int result = super.calculate(x, y); result += 10; return result; } } So is it possible by any means to mock super.calcluate(x,y)? I have tried it with spy but spy could not invoke super method cause it's out of scope I think. A: I would imagine a mocking framework would allow for you to mock protected members, but if your mocking framework doesn't, have you considered creating a stub of the class? public class AStub extends A { @Override protected int calculate(int x, int y) { // do stub calculation return calculation; } } A: When you mock an object, you don't care about its implementation. You only add expectations about which method is called. If you mock A, then your expectations will say something "I expect method calculate on A to be called with parameters 2 and 3, and the result will be 15". You don't care what the calculate method does in practice, that's the whole point of mocking. A: You shouldn't be mocking a call to super. A unit test is intended to test the functionality of a class, and the functionality of ancestor classes is a part of that functionality. The only time you should need to mock a super class is when the ancestor class behaves badly - such as initializing outside classes as part of its own initialization (without the projection of dependency injection) or accessing external resources (without the projection of dependency injection). If you have access to the ancestor class, refactor it to remove these problems. A: Unfortunately, I don't think there's an easy way to mock super.calculate. I can see that you want to write a "clean" unit test for A that does not rely on B, which is a reasonable aim. But if A is calling a protected method on its superclass, Java makes it hard to decouple the two classes. This is one of many examples where using inheritance couples classes more closely than you'd like. Ideally A would wrap B rather than extending it (i.e. using composition rather than inheritance), and would then call myB.calculate rather than super.calculate. Both classes could implement the same interface (e.g. Calculable) to allow them to be treated polymorphically by clients. This approach would requre B.calculate to be public, or at least package-public. Your unit test could set up an A that wraps a mock B, thereby solving your problem. I think you have to choose between increasing the visibility of calculate(), as described above, and writing a clean unit test - I don't think you can have both.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use ASP.NET Membership with Active Directory for a company I am new to the world of ASP.NET Web Forms and I was a Java developer for 3 years and I have a good knowledge of C# but I just used it for developing simple console applications. Now, I am having a project in ASP.NET and the first thing I am thinking to do is the administrative tasks like adding users and managing users roles. For this part, I am having two options either to use the forms authentication or to use the active directory. I am gonna use the active directory with the ASP.NET Membership but now I am facing some problems. I tried to follow the procedures written on the following link. But I failed to get them right from the first step which is creating a new website because as you see, the author specified the web location as HTTP and then he specified the located folder as https://localhost/. when I did this it gave me an error message about the inability to connect to the IIS, I don't know what the reason so I made the location to my file system. Then for the security, I chose the local Area Network for security because the project that I am developing is for a company so I need to use the windows credentials. But at the end, I failed on configuring the membership for the rest of users in the company and I do know what the reason behind that. Any help? A: Do you have a look to these two links : How To: Use Forms Authentication with Active Directory in ASP.NET 2.0 Active Directory Authentication from ASP .NET
{ "language": "en", "url": "https://stackoverflow.com/questions/7635357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: RackSpace Relative path to css/stylesheet images I m going to use Rack space cloud as CDN for Delivering Images and CSS/Stylesheets. The CSS files contains images as a relative path to the image location. My image folder contains sub folders like 1./images/home/banner.jpg 2./images/home/fb/like.png I dont want to change the relative path of the images in css files. How can i upload my images to CDN (Rack Space Cloud) So that i don't need to change anything in the css files? Help me folks... A: Either make the image paths relative to the css file or put your images folder where the CSS file is.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CodeIgniter routing with app ID's and entry ID's I'm new to CodeIgniter and going to be using it for building a sort of reusable application with multiple instances of an application. For example, each instance of the application will have an id "12345", and inside that instance, there will be entry IDs of 1,2,3,4,5,6,7,8, etc. to do this, I think I will want to be able to using Routing to set up something like: http://example.com/12345/Entry/Details/1 Where this URI will go to the Details page of the Entry of ID=1, inside application ID 12345. This would be a different group of entries from a url of, say, /12346/Entry/Details/1. Is this a routing rule that needs to be set up, and if so, can someone please provide an example of how this could be configured, and then how I would be able to use 12345, and 1, inside of the function. Thanks so much for your help, in advance. A: My suggestion would be that you route your urls like this: $route['(:any)/{controller_name}/(:any)/(:any)'] = '{controller_name}/$2/$3/$1'; so that the last parameter for the function is always the id of the app (12345/12346). Doing this means that your Entry controller functions will look like this: class Entry extends CI_Controller { function Details(var1, var2, ..., varn, app_id){} function Someother_Function (var 1, app_id){} } you will also need to add a route for functions that don't have anything but the app_id: $route['(:any)/{controller_name}/(:any)'] = '{controller_name}/$2/$1'; //This may work for everything. I hope this is what you we're asking... Edit: If you are only going to be using numbers you could use (:num) instead of (:any) A: You can achieve a routing like that by adding this rule to the application/config/routes.php file: $route['default_controller'] = "yourdefaultcontroller"; $route['404_ovverride'] = ""; // custom route down here: $route['(:num)/entry/details/(:num)'] = "entry/details/$1/$2", of course assuming your URI to be like the example. In your controller "Entry" you'll have a method "details" which takes 2 parameters, $contestID and $photoID, where $contestID is the unique instance you're assigning, while $photoID is the other (assumed) variable of your url (last segment). class Entry extends CI_Controller( { function details {$contestID, $photoID) { //do your codeZ here } } See URI routing for more info on that. You might also want to consider the __remap() overriding function, in case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Incorrectly display in Internet Explorer I have added to the site jquery content slider, but in IE it displays a wry, also displayed a wry header. This screenshot shows all Code my webpage: <%@ Page Language="C#" AutoEventWireup="true" Inherits="Bitrix.UI.BXPublicPage, Main" Title="Социальный образовательный портал" %> <script runat="server" id="@__bx_pagekeywords"> public override void SetPageKeywords(System.Collections.Generic.IDictionary<string, string> keywords) { keywords[@"keywords"]=@""; keywords[@"description"]=@""; keywords[@"ShowLeftColumn"]=@""; } </script> <asp:Content ID="Content1" ContentPlaceHolderID="bxcontent" runat="server" > <html> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <head> <link rel="stylesheet" type="text/css" href="style.css" /> <script type="text/javascript" src="jquery.js"></script> <meta http-equiv="X-UA-Compatible" content="IE=EmulateFirefox" /> <title>Документ без названия</title> <script type="text/javascript"> $(function(){ $("#about-button").css({ opacity: 0.3 }); $("#contact-button").css({ opacity: 0.3 }); $("#page-wrap div.button").click(function(){ $clicked = $(this); if ($clicked.css("opacity") != "1" && $clicked.is(":not(animated)")) { $clicked.animate({ opacity: 1, borderWidth: 5 }, 600 ); var idToLoad = $clicked.attr("id").split('-'); $("#content").find("div:visible").fadeOut("fast", function(){ $(this).parent().find("#"+idToLoad[0]).fadeIn(); }) } $clicked.siblings(".button").animate({ opacity: 0.5, borderWidth: 1 }, 600 ); }); }); </script> </head> <body> <div id="page-wrap"> <div style="width:565px !important;"> <div id="home-button" class="button" style="margin:0;"><img style="margin:0 !important;" class="button" alt="Социальный образовательный портал" src="button-1.png" /> </div> <img style="FLOAT: left; margin:0 !important;" src="devide.png" width="2" height="24" /> <div id="about-button" class="button" style="margin:0 !important;"><img style="margin:0 !important;" class="button" alt="Комплектация" src="button-2.png" /> </div> <img style="FLOAT: left; margin:0 !important;" src="devide.png" width="2" height="24" /> <div id="contact-button" class="button" style="margin:0 !important;"><img style="margin:0 !important;" class="button" alt="План развития системы" src="button-3.png" /> </div> </div> <div class="clear"></div> <div id="content"> <div id="home"> <p></p> <h1>Социальный образовательный портал</h1> <table class="st2"> <tbody> <tr><td style="BORDER-BOTTOM-COLOR: ; BORDER-TOP-COLOR: ; BORDER-RIGHT-COLOR: ; BORDER-LEFT-COLOR: ; -moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; -moz-border-image: none" class="left"> <p>Социальный образовательный портал &ndash; это веб-сервис для обучения через общение всех участников учебного процесса. Как и в любой системе обучения в данном сервисе есть возможность изучения курсов и прохождения тестов. Но главный принцип работы пользователей в сервисе – общение, интерактивное взаимодействие в решении задач и создание личного виртуального пространства.</p> </td><td style="BORDER-BOTTOM-COLOR: ; BORDER-TOP-COLOR: ; BORDER-RIGHT-COLOR: ; BORDER-LEFT-COLOR: ; -moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; -moz-border-image: none" class="right"> <p>Участвуя в жизни портала, каждый пользователь сервиса становится частью информационного пространства учебного заведения или организации. Если в привычном понимании портал - это обширная и систематизированная база учебных материалов и документов, то социальный образовательный портал - это актуальные знания каждого из его участников в динамике.</p> </td></tr> </tbody> </table> <center> <table class="st2"> <tbody> <tr><td style="BORDER-BOTTOM-COLOR: ; BORDER-TOP-COLOR: ; BORDER-RIGHT-COLOR: ; BORDER-LEFT-COLOR: ; -moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; -moz-border-image: none" class="left"> <p><img alt="Социальный образовательный портал" src="/project/src001.jpg" width="370" height="236" /></p> </td><td style="BORDER-BOTTOM-COLOR: ; BORDER-TOP-COLOR: ; BORDER-RIGHT-COLOR: ; BORDER-LEFT-COLOR: ; -moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; -moz-border-image: none" class="right"> <p><img alt="Социальный образовательный портал" src="/project/src002.jpg" width="370" height="236" /></p> </td></tr> </tbody> </table> </center> <table class="st3"> <tbody> <tr><td style="BORDER-BOTTOM-COLOR: ; BORDER-TOP-COLOR: ; BORDER-RIGHT-COLOR: ; BORDER-LEFT-COLOR: ; -moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; -moz-border-image: none" class="left"> <p>В отличие от традиционных систем дистанционного обучения (СДО), данный сервис усиливает направляющую роль преподавателя. Активность обучаемых видна преподавателям, что способствует их профессиональной ориентации, раскрытию творческого потенциала и вовлечению в общественную жизнь. </p> </td><td style="BORDER-BOTTOM-COLOR: ; BORDER-TOP-COLOR: ; BORDER-RIGHT-COLOR: ; BORDER-LEFT-COLOR: ; -moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; -moz-border-image: none" class="middle"> <p>Обучаемые также могут наблюдать активность друг друга, что делает процесс обучения прозрачным, мотивирует к соперничеству и достижению лучших результатов в учебной и не учебной деятельности.</p> </td><td style="BORDER-BOTTOM-COLOR: ; BORDER-TOP-COLOR: ; BORDER-RIGHT-COLOR: ; BORDER-LEFT-COLOR: ; -moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; -moz-border-image: none" class="right"> <p>В СДО под самостоятельной работой обучаемых фактически подразумевается его изоляция от друзей и от более качественных и актуальных учебных материалов, а Социальный образовательный портал предлагает коллективную работу по выработке и накоплению знаний, где самостоятельность означает лидерство. </p> </td></tr> </tbody> </table> <p style="TEXT-ALIGN: center"><img style="MARGIN-TOP: 20px; MARGIN-BOTTOM: 20px" alt="Социальный образовательный портал" src="/project/diag001.jpg" width="810" height="251" /></p> <table class="st2"> <tbody> <tr><td style="BORDER-BOTTOM-COLOR: ; BORDER-TOP-COLOR: ; BORDER-RIGHT-COLOR: ; BORDER-LEFT-COLOR: ; -moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; -moz-border-image: none" class="left"> <p>В Социальном образовательном портале используются средства неформального общения, знакомые пользователям по популярным социальным сервисам. Это помогает пользователям более активно взаимодействовать друг с другом: делиться полезной информацией, интенсивно использовать навыки общения, коллективно решать задачи, и выполнять групповые учебные и творческие проекты.</p> <p>Используя социальный образовательный портал, Вы получаете управление интеллектуальным капиталом Вашей организации и творческим потенциалом Ваших студентов и работников. В процессе взаимодействия пользователей генерируются уникальные новые решения и информационные ресурсы. Вы можете применять их для последующего цикла обучения и в целях совершенствования бизнес-процессов Вашей организации.</p> </td><td style="BORDER-BOTTOM-COLOR: ; BORDER-TOP-COLOR: ; BORDER-RIGHT-COLOR: ; BORDER-LEFT-COLOR: ; -moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; -moz-border-image: none" class="right"> <p><strong>Социальный образовательный портал включает в себя взаимодополняющий функционал продуктов трёх типов:</strong></p> <ul> <li>система управления сайтом (администрирование, управление правами пользователей, учебные группы, настройка интерфейса, обновление учебного контента, добавление общих компонент: новости, объявления, галереи); </li> <li>система дистанционного обучения (курсы и тесты в формате SCORM, статистика обучения, вебинары, календари событий, управление проектным обучением); </li> <li>социальная сеть (блоги, группы друзей, фотоальбомы, комментарии, хранение документов, события, закладки и обмен ими). <br /> Все пользователи сервиса имеют одинаковый набор инструментов, отличающийся только возможностями, зависящими от роли (студент, преподаватель, куратор и др.) </li> </ul> </td></tr> </tbody> </table> <p></p> </div> <div id="about"> <h1>Комплектация</h1> <p style="MARGIN-TOP: 20px">На текущий момент <strong><em>социальный образовательный портал (СОП)</em></strong> поставляется в двух комплектациях: </p> <ol> <li><strong>e-Learning standart</strong> </li> <li><strong>e-Learning interactive</strong> </li> </ol> <p>В комплектацию e-Learning interactive помимо базовых функциональных модулей, входящих в конфигурацию e-Learning standart, входит модуль &laquo;Видеочат&raquo;, который поставляеться как в составе модуля e-Learning interactive, так и самостоятельно.</p> <p>Используя комплектацию e-Learning standart, Вы получаете простой способ организации замкнутого цикла дистанционного обучения с возможностью получения итоговой статистики.</p> <br /> <center><img alt="Социальный образовательный портал" src="/project/screen_1.jpg" width="628" height="354" /></center> <br /> <p>Функциональные возможности комплектации e-Learning standart:</p> <ul> <li>система авторизации и разграничения доступа на базе гибкого управления ролями; </li> <li>конфигурирование функциональных возможностей с помощью модульного подхода; </li> <li>импорт пользователей в в систему на базе популярных форматов; </li> <li>загрузка и проигрывание учебных материалов в международном стандарте SCORM; </li> <li>управление курсами и учебными группами с использованием календарного плана и расписания; </li> <li>личный кабинет пользователя; </li> <li>управление видом и содержанием портала с помощью конструктора; </li> <li>возможность получения групповой и индивидуальной статистики по результатам обучения; </li> <li>возможность публикации новостей на станицах портала с использованием функционального модуля «Новости» и встроенного редактора новостей; </li> <li>возможность публикации фотографий на станицах портала с использованием функционального модуля «Фотогалерея» и универсального загрузчика; </li> <li>Ваши дискуссии на страницах портала при помощи функционального модуля «Форум». </li> </ul> <br /> <p>Мы постарались сделать Ваше on-line общение при обучении максимально комфортным. Для организации вебинаров в социальном образовательном портале (СОП) мы используем богатые возможности приложения FlashChat, которое хорошо зарекомендовало себя при использовании в таких популярных CMS-системах, как Joomla&#33;, Drupal, WordPress и т.д. FlashChat в рамках социального образовательного портала это: </p> <br /> <ul> <li>ваши виртуальные комнаты с использованием web-камер; </li> <li>общение в чате с использованием привычных инструментов оформления текста и возможностью рисования; </li> <li>вставка в чат видео и ссылок на видео с сайта YouTube; </li> <li>приватный чат; </li> <li>белая доска; </li> <li>передача файлов и изображений (опционально); </li> <li>возможность пригласить в чат Ваших друзей, отправив им ссылку; </li> <li>большое количество разнообразных настроек (настройка расположения видеоокна, смена аватара и т.д.); </li> <li>набор предустановленных скинов; </li> <li>широкий выбор анимированных смайликов; </li> <li>обширные возможности администрирования (опционально): управление пользователями, виртуальными комнатами и многое другое. </li> </ul> <br /> <center><img alt="Социальный образовательный портал" src="/project/screen_2.jpg" width="628" height="359" /></center> <br /> <p>Сделать FlashChat неотъемлемой часть СОП нам помогли широкие возможности интеграции, которые мы использовали для того чтобы сделать виртуальное общение неразрывной частью Вашего обучения. Наш вклад в Вашу комфортную работу это:</p> <br /> <ul> <li>настройка доступа к видеочату, как отдельному функциональному блоку портала; </li> <li>единая система авторизации в рамках СОП; </li> <li>данные личного кабинета при общении в чате; </li> <li>планирование вебинаров как отдельных мероприятий в календаре; </li> <li>управление виртуальными комнатами в рамках прав администратора портала. </li> </ul> <br /> <p>По мере выхода новых версий СОП этот вклад будет расширяться. Используйте широкие возможности видеочата при обучении, и оно станет более интерактивным и интересным, а мы поможем Вам в этом, расширяя возможности on-line общения, интегрируя новые функции FlashChat в социальный образовательный портал.</p> </div> <div id="contact"> <h1>План развития системы</h1> <p style="MARGIN-TOP: 20px">Объявив льготную подписку на социальный образовательный портал (СОП), мы взяли на себя определенные обязательства перед нашими пользователями по выпуску новых версий до конца 2011 года. Этот план мы намерены неукоснительно соблюдать.</p> <p> <br /> </p> <p>Обнародовать свои планы разработки принято далеко не всегда, но мы сознательно идем на этот шаг, чтобы на деле демонстрировать наши принципы по отношению к пользователям. И прежде всего это - быть максимально честными и открытыми по отношению к клиенту&#33; Так что же ждет наших подписчиков до конца 2011 года:</p> <br /> <center><img alt="план развития" src="/project/type.gif" width="618" height="570" /></center> <br /> <p>Мы указали здесь только основные планы нашего развития. За время реализации данной функциональности будет происходить много интересного. Вы можете стать полноправным участником разработки и воочию каждый день убеждаться в приближении к той конфигурации, которую Вы приобрели по льготной подписке. Версии СОП планируются к выходу каждый месяц. Уже сегодня Вы можете посмотреть, как будет выглядеть тот или иной функциональный модуль планируемый к разработке. Так, например, будет выглядеть Ваш календарь событий...</p> <br /> <center><img alt="Социальный образовательный портал" src="/project/screen_3.jpg" width="628" height="397" /></center> <br /> <p>Ваши обновления могут быть документально зафиксированы при оформлении подписки на текущую версию социального образовательного портала (СОП). Спешите оформить подписку сегодня и получить обширные возможности электронного обучения уже в конце текущего года&#33;</p> </div> </div> </div> </body> </html> </asp:Content> Address site: edusf.ru/project All other browsers correctly display page. What can I do to IE? A: The doctype must be the first thing in your page. You have got the <html> element before it; this needs to be moved to after the doctype. That will solve the problem for you.
{ "language": "ru", "url": "https://stackoverflow.com/questions/7635373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: xml base and relative query combination in qml I have the following xml : <response> <id>...</id> <category_id>...</category_id> <name>...</name> <detail> <resource> <label>...</label> <value>...</value> </resource> <resource> <label>...</label> <value>...</value> </resource> </detail> <price>...</price> <currency>...</currency> </response> I need to get the id, name as well as label and value from one XmlListModel I have the following code: XmlListModel { id: model query:"/response" source:"xml source" XmlRole { name: "name"; query: "name/string()" } XmlRole { name: "id"; query:"id/number()" } XmlRole { name: "label"; query: "detail/resource/label/string()" } XmlRole { name: "value"; query:"detail/resource/value/string()" } } What is wrong with this code? Thanks. A: The problem is, that the xpath query detail/resource/label/string() does not select exactly one node, because there are multiple resource nodes. If you don't need all resource nodes, you can select only the first one with detail/resource[1]/label/string(). If you need all resource nodes, you can use an additional XmlModel: import QtQuick 1.0 Item { property string xmlData: "<response> <id>1234</id> <category_id>...</category_id> <name>The Name</name> <detail> <resource> <label>Res1</label> <value>1</value> </resource> <resource> <label>Res2</label> <value>2</value> </resource> </detail> <price>...</price> <currency>...</currency> </response>" // model for general data XmlListModel { id: model xml: xmlData query:"/response" XmlRole { name: "name"; query: "name/string()" } XmlRole { name: "id"; query: "id/number()" } } // model for resource data XmlListModel { id: resModel xml: xmlData query: "/response/detail/resource" XmlRole { name: "label"; query: "label/string()" } XmlRole { name: "value"; query: "value/string()" } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7635377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Apache, SSL Client certificate, LDAP authorizations I posted this question on serverfault.com, but I had no answer, so I'm trying here... Is it possible to mix mod_ssl and mod_auth_ldap so that the authentication is done with the client certificate and authorizations with mod_auth_ldap (Require ldap-group)? If so, can you give me some pointer? Thanks in advance A: OK, for those interested, apache requires the presence of an AuthType directive and the validation of the username by some module. So I have written a very short module that accepts AuthType Any and accepts any username. The configuration looks like that: <Location /slaptest> Allow from all SSLVerifyClient require SSLVerifyDepth 1 SSLUserName SSL_CLIENT_S_DN_CN AuthType Any AuthAnyAuthoritative on AuthLDAPURL "ldaps://vldap-rectech/ou=XXX,ou=YYY,o=ZZZ?cn" AuthzLDAPAuthoritative on AuthLDAPBindDN "cn=UUU,ou=Users,ou=XXX,ou=YYY,o=ZZZ" AuthLDAPBindPassword "******" AuthLDAPGroupAttributeIsDN on AuthLDAPGroupAttribute member AuthLDAPRemoteUserIsDN off Require valid-user Require ldap-group cn=ADMIN,ou=Groups,ou=XXX,ou=YYY,o=ZZZ </Location> UPDATE: The code of the module is listed below. It defines the following directives: AuthAnyAuthoritative on/off AuthAnyCheckBasic on/off If AuthAnyCheckBasic is on, the module will check that the username obtained from the certificate matches the on in the Authorization header. #include "apr_strings.h" #include "apr_md5.h" /* for apr_password_validate */ #include "apr_lib.h" /* for apr_isspace */ #include "apr_base64.h" /* for apr_base64_decode et al */ #define APR_WANT_STRFUNC /* for strcasecmp */ #include "apr_want.h" #include "ap_config.h" #include "httpd.h" #include "http_config.h" #include "http_core.h" #include "http_log.h" #include "http_protocol.h" #include "http_request.h" #include "ap_provider.h" #include "mod_auth.h" typedef struct { int authoritative; int checkBasic; } auth_any_config_rec; static void *create_auth_any_dir_config(apr_pool_t *p, char *d) { auth_any_config_rec *conf = apr_pcalloc(p, sizeof(*conf)); /* Any failures are fatal. */ conf->authoritative = 1; conf->checkBasic = 0; return conf; } static const command_rec auth_any_cmds[] = { AP_INIT_FLAG("AuthAnyAuthoritative", ap_set_flag_slot, (void *)APR_OFFSETOF(auth_any_config_rec, authoritative), OR_AUTHCFG, "Set to 'Off' to allow access control to be passed along to " "lower modules if the UserID is not known to this module"), AP_INIT_FLAG("AuthAnyCheckBasic", ap_set_flag_slot, (void *)APR_OFFSETOF(auth_any_config_rec, checkBasic), OR_AUTHCFG, "Set to 'On' to compare the username with the one in the " "Authorization header"), {NULL} }; module AP_MODULE_DECLARE_DATA auth_any_module; static void note_basic_auth_failure(request_rec *r) { apr_table_setn(r->err_headers_out, (PROXYREQ_PROXY == r->proxyreq) ? "Proxy-Authenticate" : "WWW-Authenticate", apr_pstrcat(r->pool, "Basic realm=\"", ap_auth_name(r), "\"", NULL)); } /* Determine user ID, and check if it really is that user, for HTTP * basic authentication... */ static int authenticate_any_user(request_rec *r) { auth_any_config_rec *conf = ap_get_module_config(r->per_dir_config, &auth_any_module); /* Are we configured to be Basic auth? */ const char *current_auth = ap_auth_type(r); if (!current_auth || strcasecmp(current_auth, "Any")) { return DECLINED; } if (!r->user) { return conf->authoritative ? HTTP_UNAUTHORIZED : DECLINED; } if (conf->checkBasic) { /* Get the appropriate header */ const char *auth_line = apr_table_get(r->headers_in, (PROXYREQ_PROXY == r->proxyreq) ? "Proxy-Authorization" : "Authorization"); if (!auth_line) { note_basic_auth_failure(r); return HTTP_UNAUTHORIZED; } if (strcasecmp(ap_getword(r->pool, &auth_line, ' '), "Basic")) { /* Client tried to authenticate using wrong auth scheme */ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "client used wrong authentication scheme: %s", r->uri); note_basic_auth_failure(r); return HTTP_UNAUTHORIZED; } /* Skip leading spaces. */ while (apr_isspace(*auth_line)) { auth_line++; } char *decoded_line = apr_palloc(r->pool, apr_base64_decode_len(auth_line) + 1); int length = apr_base64_decode(decoded_line, auth_line); /* Null-terminate the string. */ decoded_line[length] = '\0'; const char *user = ap_getword_nulls(r->pool, (const char**)&decoded_line, ':'); if (strcasecmp(user, r->user)) { return HTTP_UNAUTHORIZED; } } r->ap_auth_type = "Any"; ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server, "Accepting user: %s", r->user); return OK; } static void register_hooks(apr_pool_t *p) { ap_hook_check_user_id(authenticate_any_user,NULL,NULL,APR_HOOK_MIDDLE); } module AP_MODULE_DECLARE_DATA auth_any_module = { STANDARD20_MODULE_STUFF, create_auth_any_dir_config, /* dir config creater */ NULL, /* dir merger --- default is to override */ NULL, /* server config */ NULL, /* merge server config */ auth_any_cmds, /* command apr_table_t */ register_hooks /* register hooks */ };
{ "language": "en", "url": "https://stackoverflow.com/questions/7635380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Real location of jquery in rails One day I've got jquery.js file corrupted (maybe because of my IDE, i don't really know), it has arbitrary number in the beginning. I can see this in the browser: 3/*! * jQuery JavaScript Library v1.6.2 * http://jquery.com/ * * I'm under Rails 3.1, using Pipeline by default. So I've checked the places which Pipeline can retrieve jquery. The first was vendor/assets/javascripts project's directory, it was empty. Then I went to location where gem jquery-rails is located /home/megas/.rvm/gems/ruby-1.9.2-p290@rails31/gems/jquery-rails-1.0.14/vendor/assets/javascripts/ but all files there are OK. Where I can find real jquery file? A: Have you checked /usr/share/javascript ? A: I didn't find what was the problem, so I had to recreate project and this bug went way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Prevent word wrap in error message I have weird situation that extjs 4 always puts last word of custom error message in new row, and effectively hides it. I tried shortening message, but always last word goes to new line. This happens in Firefox 7.0.1 (firebug turned off), not in Chrome, Opera, Safari. Default message text is displayed correctly. My error message has no strange letters or symbols. I tried escaping white characters, putting nobr tags etc... but nothing works. How to prevent this behavior? I have no any css or any other styling applied. Here is code from view: this.items = [{ waitMsgTarget: 'dailyReport', xtype: 'form', url: 'php/dailyReport.php', items: [{ margin: 10, xtype: 'datefield', name: 'reportDate', fieldLabel: 'Report for', format: 'd.m.Y.', altFormats: 'd.m.Y|d,m,Y|m/d/Y', value: getCorrectDate(), disabledDays: [0] }, { margin: 10, xtype: 'checkboxgroup', fieldLabel: 'Report by', columns: 2, vertical: true, allowBlank: false, blankText: 'Choose at least one.', items: [{ boxLabel: 'pos', name: 'rb', inputValue: '1', checked: true }, { boxLabel: 'seller', name: 'rb', inputValue: '2', checked: true }] }] }]; A: 'Ctrl' + '+' was reason. My view in Firefox was zoomed in, but I didn't notice it until today. After I returned it to normal zoom level 'Ctrl' + '0' everything works and shows up fine. Silly me, it took me 2 weeks to realize this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CKEditor text area is blank in rails 3.1 app I'm trying to embedd a ckeditor into a form and it just comes up blank. The text area is just an empty space where I expect to find an html editor window. I have a model where I want the "description" field to be html text. I thought it would be convenient to use ckeditor to edit it. I can't work out why the text field editor is not showing. I've got a rails 3.1 app, and I'm using the ckeditor gem (version 3.6.2). I've downloaded ckeditor and put it in my assets/javascripts folder. In my application.html.erb file I have this line: <%= javascript_include_tag "ckeditor/ckeditor.js" %> In my view I have some code like this: <%= form_for(@k) do |f| %> <%= f.cktext_area :description, :toolbar => 'Full', :width => 800, :height => 400 %> This generates html like this: <textarea id="k_description" rows="20" name="k[description]" cols="40" style="visibility: hidden;"></textarea> <script type="text/javascript"> //<![CDATA[ if (CKEDITOR.instances['k_description']) {CKEDITOR.remove(CKEDITOR.instances['k_description']);}CKEDITOR.replace('k_description', { height: 400,language: 'en',toolbar: 'Full',width: 800 }); //]]> </script> It all looks like it should work, but it doesn't. What am I missing? A: Because of the way CKeditor links its dependancies you'll have to move it to the public folder. There is a helper option coming in Rails 3.1.1 which I believe will fix this problem. (:digest => false).
{ "language": "en", "url": "https://stackoverflow.com/questions/7635388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Yield to other threads/tasks in OpenMP I want to use OpenMP with CUDA to achieve overlapping kernel executions. Ther kernel calls are all asynchronous, but I have very little code between launches so the individual OpenMP threads tend to block as they try to launch another kernel, or do a mem copy (I don't always have mem copys right after the call so async mem copys aren't necessarily the solution). I would like a way to signal to the OpenMP schedular to switch to another OpenMP thread. Is this possible in OpenMP? Example: int main() { #pragma omp parallel for for(int i=0;i<10;i++) { for(int j=0;j<10;j++) { //call kernel here // ----> Would like to signal to continue with other // threads as next call will block //copy data from kernel } } } A: If a thread blocks, the operating system's scheduler should automatically switch to another runnable thread (if one is available), so you shouldn't need to do anything. However, if all your OpenMP program is doing is calling CUDA kernels, it's likely that the GPU is the bottleneck, so you won't get much benefit from using threads on the CPU anyway. It may not be worth using OpenMP at all. If you do continue using OpenMP, though, you should probably add a collapse(2) to that omp parallel for.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Position div using Jquery on doc load without seeing it move How do you position a div using Jquery without seeing it noticeably move from its original position? As I understand it, the Jquery selectors only work in the ready function, which means there is a slight delay between the DOM showing and the jquery function being called to move the div. I want the div to be moved instantly without any noticable transition AND no delay in it being shown. A: You can make the div invisible by giving display:none with css, and at the time when DOM is loaded relocate it and show it. This will also prevent the page reflow. A: jQuery selectors do work outside of domready as well as demonstrated in this fiddle). So, You could to this: <div id="mydiv">Content</div> <script type="text/javascript">$('#mydiv').css({'position' : 'absolute', 'left' : '55px'});</script> I don't quite get though, why you wouldn't position the div by pure CSS in the first place. Edit: Under no circumstances should you render the div invisible via CSS and display it via JS only. Rather use .hide() on the element early in the page load. A: To my knowledge, the only way to reliably achieve this is to render the <div> element initially hidden, and show it only after it was moved. For instance: <div id="yourDiv" style="display: none;"> <!-- ... --> </div> $(document).ready(function() { $("#yourDiv").appendTo("#targetContainer").show(); }); However, doing that breaks graceful degradation / progressive enhancement: if Javascript is disabled on the client, the <div> element will remain hidden in the page. A: If you execute your code when the document is ready and not when it's loaded, the delay between rendering the dom and executing your code is minimal, because (as answered in other questions : What is the difference between $(window).load and $(document).ready?), the ready event fires after the dom is constructed. My point is that you can rely on $(document).ready and reposition your elements, because in most cases it won't be noticeable. Here's a live demo showing that you can dynamically position an element "any noticable transition AND no delay in it being shown". If you're still not convinced that this is the right thing for you, you should probably hide your elements and show them only after you've repositioned them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# Using Generic Class without Specifying Type I have a generic class I have created as so: public abstract class MyClass<T> { public T Model { get; protected set; } } And at some point in my code I want to do something with anything of MyClass type. Something like: private void MyMethod(object param) { myClassVar = param as MyClass; param.Model....etc } Is this possible? Or do I need to make MyClass be a subclass of something (MyClassBase) or implement an interface (IMyClass)? A: No. You need to inherit a non-generic base class or implement a non-generic interface. Note that you won't be able to use the Model property, since it cannot have a type (unless you constrain it to a base type and implement an untyped property explicitly). A: Yes, you need. If type of generic class is undefined you need to create generic interface or using base-class... A: I believe what you are need is to make MyMethod method generic and add constraint on its type parameter: interface IMyInterface { void Foobar(); } class MyClass<T> { public T Model { get; protected set; } } private void MyMethod<T>(MyClass<T> param) where T : IMyInterface { param.Model.Foobar(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7635396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Using Google OAuthUtil in a desktop application I am building a Desktop application that interacts with Google Contacts. I have been trying to authenticate the application using google supplied OAuthUtil, but cant get it to work... it seems it is only suitable for webapplication because of the callback url you have to provide, I think that because the function OAuthUtil.GetUnauthorizedRequestToken returns void... A: I'm not that familiar with C# or I'd try and write some example code. However, looking at their docs you have to open a web browser and detect whatever callback you sent. When you detect the callback you then redirect to the client program. http://code.google.com/apis/accounts/docs/OAuthForInstalledApps.html It seems they're working on being able to make a REST request to their servers so that you don't have to have a web browser. http://sites.google.com/site/oauthgoog/UXFedLogin/nobrowser/input-capable-devices Even for things, without a web browser they're current suggestion is to provide a pin, which you then have the user register on a device with a web browser. http://sites.google.com/site/oauthgoog/UXFedLogin/nobrowser
{ "language": "en", "url": "https://stackoverflow.com/questions/7635397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iOS Action, based on region in MapKit Basically what I'm trying to accomplish is a GPS tour guide app, where when you enter a certain region and a sound file is played. Let's say i've got 10 sound files and 10 regions. Is there a way to basically define a line on the map, and if the user crosses the line - the app changes the sound file being played? Thanks A: MKMapViewDelegate has a function mapView:regionDidChangeAnimated: which occurs when user scrolls the map. In this function you can switch music or whatever you need based on current map position (for example by checking which region is closer to the map center etc.): - (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated { /* do what you need with mapView.region */ } A: Maybe - (void)startMonitoringForRegion:(CLRegion *)region desiredAccuracy:(CLLocationAccuracy)accuracy on CLLocationManager is what you are looking for. You can define multiple regions -- as soon as the user enters one of the defined regions you will start to receive notifications. More info here
{ "language": "en", "url": "https://stackoverflow.com/questions/7635402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery each function IE7 I have some links in a page that i'd like to change from <span id="lireArticle"> <a href="/Lists/ListeActualitesCarrousel/4_.000/DispForm.aspx?ID=4" class="action">Lire l'article</a> </span> <span id="lireArticle"> <a href="/Lists/ListeActualitesCarrousel/2_.000/DispForm.aspx?ID=4" class="action">Lire l'article</a> </span> <span id="lireArticle"> <a href="/Lists/ListeActualitesCarrousel/3_.000/DispForm.aspx?ID=4" class="action">Lire l'article</a> </span> to <span id="lireArticle"> <a href="/Lists/ListeActualitesCarrousel/DispForm.aspx?ID=4" class="action">Lire l'article</a> </span> <span id="lireArticle"> <a href="/Lists/ListeActualitesCarrousel/DispForm.aspx?ID=4" class="action">Lire l'article</a> </span> <span id="lireArticle"> <a href="/Lists/ListeActualitesCarrousel/DispForm.aspx?ID=4" class="action">Lire l'article</a> </span> This works in Firefox, IE9, IE8 but not IE7! it just changes the first link in IE7 jQuery("#lireArticle a").each(function(){ jQuery(this).attr('href',jQuery(this).attr('href').replace(/\/(\d)_.(\d{3})\//,'/')); }) How can i get it to work in IE7? A: You cannot have multiple elements with the same ID. Use class="" instead. A: The issue is you're using the same ID multiple times on the page. The ID of the element should be unique. Your code is finding the first instance of an element with the ID of "lireArticle" and changing all its a's. I suggest using class="" instead. Markup: <span class="lireArticle"> <a href="/Lists/ListeActualitesCarrousel/4_.000/DispForm.aspx?ID=4" class="action">Lire l'article</a> </span> <span class="lireArticle"> <a href="/Lists/ListeActualitesCarrousel/2_.000/DispForm.aspx?ID=4" class="action">Lire l'article</a> </span> <span class="lireArticle"> <a href="/Lists/ListeActualitesCarrousel/3_.000/DispForm.aspx?ID=4" class="action">Lire l'article</a> </span> JavaScript: jQuery(".lireArticle a").each(function(){ jQuery(this).attr('href',jQuery(this).attr('href').replace(/\/(\d)_.(\d{3})\//,'/')); }) A: Oops made syntax error on previous post, updated. If you don't want to change the links by adding a class just use a different selector. $('a[href^="/Lists/ListeActualitesCarrousel"]').each(function(){ var newURL = $(this).attr('href').replace(/\/(\d)_.(\d{3})\//,'/'); $(this).href(newURL); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7635405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to force JAXB marshaller to use xlink references? I use JAXB marshaller to store some java objects as XML files. Some of these objects reference each other, so I unsurprisingly obtain this error: [com.sun.istack.internal.SAXException2: A cycle is detected in the object graph. This will cause infinitely deep XML The solution which consists in removing the cycles and use only tree structure is not feasible - I need both navigability directions. To solve this issue, I would rather use xlink to reference the xml objects instead of copying them in cascade. Is this solution pertinent? Is it possible to do that with JAXB marshaller? How? A: You can implement an XLink approach in JAXB using an XmlAdapter. Below are links to various similar answers. * *Serialize a JAXB object via its ID? *Using JAXB to cross reference XmlIDs from two XML files *Can JAXB marshal by containment at first then marshal by @XmlIDREF for subsequent references? I lead the EclipseLink JAXB (MOXy) implementation, and we have the @XmlInverseReference extension for mapping bidirectional relationship that you may be interested in: * *http://blog.bdoughan.com/2010/07/jpa-entities-to-xml-bidirectional.html A: Dude, you can note in one of the entity the annotation @XmlTransient, so when unmarch, it will not complain about the cycle problem. But with thius workaround after unmarch the xml you will have to populate the atribute with the @XmlTransient. I was reading some paper and find this. You can set @XmlTransient and use the callback method to do something after the unmarch. So you can set the parent to you child. public void afterUnmarshal(Unmarshaller u, Object parent) { this.pessoa = (Pessoa) parent; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7635411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SpeechToText on Shake of phone not working properly In my application,i want to use TextToSpeech when users shakes the phone. I have handled shaking of phone successfully using- Android: I want to shake it But problem came when i intigrated TextToSpeech with this code. Tried this- http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/TextToSpeechActivity.html It gave me no error but can't hear speech when tried in real device. Also tried using this code: http://www.javacodegeeks.com/2010/09/android-text-to-speech-application.html But it gives me force close in real device so i can't get idea about error. I can't test shaking on immulator so can't find out even there. Any help is appriciated. Thanks. A: I solved it... I didn't install TTS engine.It is working fine now.Silly me!
{ "language": "en", "url": "https://stackoverflow.com/questions/7635414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: is it possible to share session variables between servlets/jsp and javascript functions? I have a scenario where a form has to be filled in as easily as possible. The values to be filled in in the form, are asked from the user initially and stored in database. Afterwards, when user clicks on a button, a javascript function is invoked that auto-fills all the fields in the form with values obtained by jsp/servlet. I want to retrieve the values (that are to be filled in into the form) from database with the help of servlet/jsp...Now there should be some way for the javascript function to fill in this value (that was obtained by the servlet/jsp) into the form... Is it possible to do such sharing of data/variables between jsp/servlets and javascript functions? The javascript functions will be part of the jsp (that retrieves the value that should be filled in in the form). A: The Javascript client in the browser has no direct access to the environment on the server (and shoudln't - imagine how it would be bad if all pages broke the day you decided to use a diferent server solution). You basically have two choices: * *Include all the data you will ever need on the page you serve to the client (perhaps the form html is dinamically generated to suit your needs, etc etc) *Manually request extra information dinamically via XMLHttpRequest (aka AJAX). This is the only way if you can only determine what data you will need dinamically, after the page loads. A: If the request is sent synchronously (e.g. a form submit button), then you don't necessarily need JS for this job. Just let JSP/EL print them immediately as input values based on data which is prepopulated by a servlet. For example, assuming that ${user} is a typical Javabean which is prepared by the servlet: <input type="text" name="name" value="${fn:escapeXml(user.name)}" /> <input type="text" name="city" value="${fn:escapeXml(user.city)}" /> <input type="text" name="country" value="${fn:escapeXml(user.country)}" /> (the fn:escapeXml() is just to prevent XSS attacks) If the request is sent asynchronously (e.g. using ajax), then you just need to let the servlet return the data in a format which is easily parseable by JS, for example JSON. { "username": "Bauke Scholtz", "city": "Willemstad", "country": "Curaçao" } which you can then use as follows in the ajax response callback function (where user is the obtained JSON object): document.getElementById("name").value = user.name; document.getElementById("city").value = user.city; document.getElementById("country").value = user.country; jQuery makes things like this much easier. See also How to use Servlets and Ajax? A: You could access your database dynamiclly using xmlhttprequest. For further information + relevant examples read : http://www.w3schools.com/ajax/ajax_aspphp.asp
{ "language": "en", "url": "https://stackoverflow.com/questions/7635415", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: returning back to the android app, from the browser, without restarting the app I am using Phonegap to create an android application. The application has a feature that enables the user to visit a micro site by opening the android web browser. The micro site has a return button that will return the user back to the app. I created my own scheme so I can launch the app from the android browser. <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="microsite" /> </intent-filter> My problem is that when the app is launch from the browser, the app is restarted. How will I be able to return to the app without restarting the app? How to return to where I left off?
{ "language": "en", "url": "https://stackoverflow.com/questions/7635421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Passing XML to Popup window I'm using classic asp, and I would like to pass an xml to the popup window, change something on it and send it back to the parent. Is this possible? Also, is it possible from the popup to edit the xml on the parent window directly? Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP: Why is date made into an array? Why is this string being made into an array and how do I stop it please? Snippet: (to get date) public function setDate(){ $this->date = date("Y-m-d"); return $date; } public function getDate(){ return $this->date; } $date = getDate(); Snippet: (part of query) ->where_equal_to( array( 'sales_date' => $date ) ) When you dump the query its doing this... Output: array(1) { ["sales_date"]=> array(11) { ["seconds"]=> int(42) ["minutes"]=> int(10) ["hours"]=> int(14) ["mday"]=> int(3) ["wday"]=> int(1) ["mon"]=> int(10) ["year"]=> int(2011) ["yday"]=> int(275) ["weekday"]=> string(6) "Monday" ["month"]=> string(7) "October" [0]=> int(1317647442) } } instead of something like this... Output: array(1) { ["sales_date"]=> "2011-10-03 00:00:00" } A: You're calling the PHP function getdate() rather than $obj->getDate(), so it's returning an array based off of the return value from the built-in function. http://us2.php.net/getdate A: The array you're seeeing is the output of PHP's getdate() function. Somewhere in your code, you're calling getdate() instead of your custom getDate() function (I presume the latter is in a class, otherwise it would throw a compiler error trying to redeclare an existing function). That's where your problem lies. You haven't shown the relevant bit of code, but it's probably inside your class. You may need to call it as $myvar = $this->getDate(); or $myvar = $someobject->getDate(); instead of just $myvar = getDate();. For what it's worth, in case you can't change the class itself, the [0] element of the returned array is a timestamp, which is easy enough to convert back into a date of any format using the date() function. A: You can't redeclare getDate()[docs] because it already exists. Also, you forgot to * *declare instance for your class *you're calling getDate (function) instead of getDate (method) http://sandbox.phpcode.eu/g/9fb88/3
{ "language": "en", "url": "https://stackoverflow.com/questions/7635427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: css container div not aligning to top of page I have a two-column layout. I have a #mainContainer div that contains all of the following (except the #footer): * *Across the top: a header div (#intro)(contains a small gradient image), and a #hero div (contains images) *To contain the two columns: a #content div *Within the #content div on the left: a #mainContent div *Within the #content div on the right: a #sideBar div *Across the bottom (outside the #mainContainer div): a #footer div on the bottom (including a gradient image like the header div) Simple, right? But I'm having trouble getting the #mainContainer div to be at the top of the browser (no spaces or that 6-8px default margin/padding all browsers have at the top) and getting the #footer div to span across the entire bottom of the browser window (not inside any of the Div's ). (disregard inline styles in footer). Could someone help me out? UPDATED: ADDED HTML body { font-family:Arial, Helvetica, sans-serif; margin:0; padding:0; background:#bbb; text-align:center; } #mainContainer { width:980px; margin: 0 auto; background: #fff url(../i/content-box-header-gray.jpg) repeat-x; text-align:left; /*height: 700px;*/ } #intro { /*top:0;*/ margin: 0; text-align:left; } #hero { width:960px; padding-left:10px; padding-right:10px } #content { width:960px; padding-left:10px; padding-right:10px; } #mainContent_left { float:left; width:640px; margin:0; padding-right: 20px; background:#ccc; } #sideBar { float:left; width:300px; margin:0; /*padding-right: 20px;*/ background:#ffd; } #footer { width:960px; clear:both; background:#cc9; } HTML: <title>Descriptions </title> <link rel="stylesheet" href="css/mainstyles.css" type="text/css" /> </head> <body> <div id="mainContainer"> <div id="intro"><h2>introducing</h2></div> <div id="Hero"> <ul> <li class="name"></li> <li class="textJoin">is a member of </li> <li class="name"></li> </ul> </div> <div id="content"> <div id="mainContent"> <h3>First Topic title</h3> <p>floated left image and text</p> <p>Some content</p> <p>Some content</p> <h3>Second Topic title</h3> <p>Some content</p> <p>Image here</p> <h3>Third Topic title</h3> <p>(floated left image here) Some text</p> <h3>Fourth Topic title</h3> <p>(floated left image here) Some text</p>> <h3>Fifth Topic title</h3> <p>(floated left image here) Some text</p> <p>Image here</p> <p>(link to FAQ page)</p> </div> <div id="sideBar">sidebar content <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> </div> <div id="footer_warranty">footer content <div id="wf_logos" style="float:left; padding:0 10px 0 0;"><p>contact info</p> </div> <div id="wf_footerCopy" style="float:left; padding:0 10px 0 0;"> <p>some text</p></div> <p style="clear:both;" /> </div> </div> <p style="clear:both;" /> </div> </body> </html> A: Try importing Meyer's reset stylesheet: http://meyerweb.com/eric/tools/css/reset/ A: I am unable to reproduce your problem. However, I have created a fiddle for you, where I have also added some CSS reset rules which should take care of a problem such as this, cross any and all browsers. You should always use a reset CSS when you start a new site. That way, it's all on your terms and you don't have to "code away" specific browser behaviour. I have also created some placeholder code since you did not provide any. I hope the reset fixes your problem. http://jsfiddle.net/dekket/eERsK/ Edit: Check this new fiddle. Out to work. http://jsfiddle.net/dekket/6bTkZ/ A: try adding float:left and overflow:hidden to your #mainContainer A: you need to set the html and body css margin and padding properties to 0. use the following in your css file html, body { margin: 0; padding: 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7635430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Images from a video show subtle differences when processed on different computers I have a small video clip that I've run through my video to image software and noticed that the images come out different. Both set of images are identical in which they are cut at 1 second segments. Where they vary is one of the images seem to be brighter then the other set. I'm trying to think what can cause this subtle difference, but I'm at a loss. I thought that maybe because the hardware is different that would cause this, but I'm not doing anything on the GPU. I also thought that it could be the codec being used, but if the video is encoded the same way using the same codec and information then would decoding really effect it in this way? Below is a list of what the program is: * *Takes a video and saves it out as 1 second images *Uses DirectX in C# to load in a video and saves out the texture. *Video is encoded using MPEG-4 similar compression I understand that this may not be much information to go off of, but I am at a loss of where I can look. Any advice is greatly appreciated. A: I'd say that images are not actually different. It is unlikely that MPEG-4 decoding uses any GPU resources. Well, it's possible to hardware decode MPEG-4 Part 10, but it's subject to certain conditions too. Far more likely, the effect is due to on of the reasons below (or both): * *if you show the picture up within video streaming context, or as you mentioned textures in use - the images might be appearing from YUV surfaces which video hardware is managing differently from regular stuff like desktop, and video hardware might be having a different set of brightness/contrast/gamma controls for those, which result in different presentation *you have different codecs/decoders installed and they decode video with certain differences, such as with post-processing; with all the same encoded video, decoded presentation might be a bit different
{ "language": "en", "url": "https://stackoverflow.com/questions/7635434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Lion, RVM, Postgresql, and the PG Gem I'm attempting to upgrade me Rails 3.0.x application to 3.1 but I'm running into some problems: Heroku (which my app is hosted on) requires that I use their Cedar stack & include the "PG" gem in my gemfile. I've seen that people have quite a lot of problems when installing this gem because it doesn't seem to know where to find the Postgresql install at. I know that my options for installing Postgresql are probably MacPorts, One Click Installer (from their website), Homebrew, and possibly some that I'm not aware of. So I guess my question is, which of these methods should I use to install Postgresql (on Lion)? Then, how would I get the PG gem to install w/ RVM without it complaining that it cannot find my postgresql install? A: I've simply installed PosgreSQL using homebrew and then did a bundle install for my project which used the pg gem. Works like a charm. And yes, I run RVM. A: In my experience, the "one-click" installer works best, though I'd imagine Homebrew's is probably fine as well. The "one-click" version on Lion is the version I use when doing development and testing on the pg library. You'll want to avoid installing it via Macports unless you ensure that it is linked against the same version of OpenSSL that your Ruby's OpenSSL extension is. If they're linked against different versions, you risk segfaulting . The 'pg_config' binary is the critical piece of getting the 'pg' gem to install. If it can't find that (and you don't point it at one using the --with-pg-config option), it will try to guess where stuff is installed, but that doesn't always work. Also, as with any extension that links against a shared library, you need to ensure that you compile the extension with the same architecture/s as your Ruby. Setting 'ARCHFLAGS' to '-arch x86_64' usually works on Lion. See the MacOS X README for more details. If you still are having trouble, feel free to mail me, as I'd like to make 'pg' easier to install for everyone. I'm working on better diagnostics for when things go wrong, but it's hard to anticipate every way the build could go wrong.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ERROR on accept: Resource temporarily unavailable I am trying to create single threaded server in linux (red-hut) in C that will listen to multiple sockets. I need to use non-blocking sockets, when I set the flags to non-blocking like this: int flagss = fcntl(socketfds[j],F_GETFL,0); flagss |= O_NONBLOCK; fcntl(socketfds[j],F_SETFL,flagss); I get: ERROR on accept: Resource temporarily unavailable Otherwise everything works perfectly. A: Resource temporarily unavailable is EAGAIN and that's not really an error. It means "I don't have answer for you right now and you have told me not to wait, so here I am returning without answer." If you set a listening socket to non-blocking as you seem to do, accept is supposed to set errno to that value when there are no clients trying to connect. You can wait for incoming connection using the select (traditional) or poll (semantically equivalent, newer interface, preferred unless you need to run on some old unix without it) or epoll (optimized for thousands of descriptors, Linux-specific) system calls. Of course you will be using poll (or any of the alternatives) to wait for data on the listening socket or any of the data sockets. A: maybe, set up fnctl flags after accept() could work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Can I pre-compile a single modified page to an already preCompiled .Net Web Site? I have many usercontrols that i reuse in different projects. They are all in the web site project. Upon making extension for a new customer, I am precompiling the complete web site and deploy it (with around 600 items UserControls & Pages in it). If I have to make a small modification on any page and want to deploy it I have to pre-compile whole project which takes around 15-20 minutes on my machine. Is there a way to precompile and deploy only modified or selected items of a web site? Thank you! A: I recommend you put your UserControls into their own projects(Web Deployment Projects) within the same solution, however many needed, which will compile them into .dlls: ie: Namespace.Module1.UI.dll Namespace.Module2.UI.dll Namespace.Module3.UI.dll A: After long searches the answer is NO! A: If you publish using "allow this precompiled site to be updatable", you can precompile certain things and only publish those. For example, if you only changed code in .cs files since the last publish, you can sometimes get away with only publishing the new App_Code.dll, but there are some tricky situations… For example, if you changed code in .cs files that the code in one of your pages depends on, you might need to publish a new precompiled version of that page as well. (I asked about why this is here, but no one has given a good answer so far.) You can even publish precompiled pages and user controls in some cases, but nasty situations may arise here as well. For example, if your page uses a Master Page and User Controls, you might need new precompiled versions of those as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Javascript not updating DOM immediately My question is very similar to the one described in this post: Javascript progress bar not updating 'on the fly', but all-at-once once process finished? I have a script that calls a few services, and processes some actions. I'm trying to create a progressbar that indicates the current status of script execution to the end user. I calculate the process (#currentaction / #totalactions) to indicate the progress and update the DOM each time an action is processed with this new value. However, the DOM is only updated when all actions are finished. I have placed a setTimeout in my function, and for some reason the DOM is still not updating step by step, it's only updating when the entire jscript is executed. here's an example of my JScript var pos = RetrievePos(); _TOTALCOUNT = (pos.length); for(var i = 0; i < pos.length; i++) { var cpos = pos[i]; CreateObject(cpos, id); } function CreateObject(cpos, id) { setTimeout(function() { //do work here, set SUCCESS OR ERROR BASED ON OUTCOME ... //update gui here var scale = parseFloat(_SUCCESS + _ERRORS) / parseFloat(_TOTALCOUNT); var totWidth = $("#loaderbar").width(); $("#progress").width(parseInt(Math.floor(totWidth * scale))); }, 500); } I've tried setting the setTimeout function around the entire CreateObject call, around the DOM calls only, but nothing seems to do the trick. I'm probably missing something very obvious here, but I really don't see it. Any ideas? Thanks, A: The reason your code isn't working properly is that the CreateObject function will be called several times over in quick succession, each time immediately cueing up something to do 500ms later. setTimeout() doesn't pause execution, it merely queues a function to be called at some future point. So, essentially, nothing will happen for 500ms, and then all of your updates will happen at once (technically sequentially, of course). Try this instead to queue up each function call 500ms apart. for (var i = 0; i < pos.length; i++) { setTimeout((function(i) { return function() { var cpos = pos[i]; CreateObject(cpos, id); } })(i), i * 500); } and remove the setTimeout call from CreateObject. Note the use of an automatically invoked function to ensure that the variable i within the setTimeout call is correctly bound to the current value of i and not its final value. A: I presume you are doing more than just the setTimeout within CreateObject ? If you are not, best just to call the setTimeout from the loop. I suspect you are using JQuery. If so, try using animate $('#progress').animate({width: parseInt(Math.floor(totWidth * scale)) }, 'slow'); Since that will invoke it's own updating code, it might solve the issue. Without your full code, I couldn't say exactly what the problem here is. I'm also a PrototypeAPI head and not a JQuery head. A: @gazhay: you probably have a point that using the .animate function of jQuery this problem could have been bypassed. However, I found a solution for this problem. I modified the JScript to no longer use a for loop, but use recursive functions instead. Appearantly the DOM does not get updated untill the FOR loop is completely terminated... Can anyone confirm this? I've tested this out with the following script: This doesn't work: for(var i = 0; i < 1000; i ++) { setTimeout(function() {document.getElementById('test').innerHTML = "" + i;}, 20); } While this does work: function dostuff(i) { document.getElementById("test").innerHTML = i; if(i<1000) setTimeout(function(){ dostuff(++i);}, 20); } var i = 0; dostuff(i);
{ "language": "en", "url": "https://stackoverflow.com/questions/7635453", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to track an objects state in time? In my script I read messages from socket and change the state of some objects in memory depending on the content in message. Everything works fine. But I want to implement deletion of non-active objects: for example, if there's no message for specified object during some time, it should be deleted. What is the best way to do it ? A: This one might not work for you, but: if you're okay with not removing objects after a specified time, but only keeping a specified number of objects, Python 3.2 has functools.lru_cache for exactly that. A: Store a timestamp in each object - update the timestamp to the current time whenever you modify it. Then have something that runs every so often, looks at all of the objects, and removes any with a timestamp earlier than a certain amount before the current time. A: If you're stuck with Python 2, or if you need this to be timestamp-based and Amber's answer isn't fast enough, you can do a variation on what Python 3's lru_cache does, but take the object's modification time into account: (I didn't test this; hopefully the bugs are minor and the idea is clear.) Store the objects in an OrderedDict (there's a package for Pythons older than 2.7). import collections objects = collections.OrderedDict() I assume you have some key for each object so you can identify them in the stream. Do a variation of a regular lookup that removes and re-inserts an already existing object from the dict. This will keep the OrderedDict sorted by last access. try: obj = objects.pop(the_key) except KeyError: obj = create_new_object(the_key) objects[the_key] = obj obj.timestamp = current_time() Then, every once in a while (or every time), remove the old objects. The LRU variant (limiting the number of objects) is easy enough: while len(objects) > some_threshold: objects.popitem(last=False) The timestamp-based variant is a bit trickier, but not much. The oldest entries are in the front, so we only have to look at the first one, and pop it if it's too ancient. while objects: obj = objects.itervalues().next() # Python 2 only :( if obj.timestamp < some_threshold(): objects.popitem(last=False) else: break An eyeball analysis says that this gives you amortized O(1) access, and O(number of discarded objects) upkeep in both variants.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Basic Mono installation wont work Am using a CentOS 5.3 box as prod server and am trying to get mono running there. after much sifting i managed to install version 2.10.2 via yum. i installed also xsp and mod_mono the same way and created a simple hello world web page. thing is its not running. iam guessing something is up with my config files which are responsible for this. Being a newbie on both linux and apache configuration, i dont know whats wrong. I have tried to follow some relative responses on the site but i cant get it work. So here is what ive done: installed mono, xsp and mod_mono via yum; added to httpd.conf (mine is in /usr/local/apache/conf) Include "/usr/local/apache/conf.d/*.conf" then i created the following /usr/local/apache/conf.d/mod_mono.conf file : MonoAutoApplication enabled LoadModule mono_module /usr/lib/httpd/modules/mod_mono.so AddType application/x-asp-net .aspx AddType application/x-asp-net .asmx AddType application/x-asp-net .ashx AddType application/x-asp-net .asax AddType application/x-asp-net .ascx AddType application/x-asp-net .soap AddType application/x-asp-net .rem AddType application/x-asp-net .axd AddType application/x-asp-net .cs AddType application/x-asp-net .config AddType application/x-asp-net .Config AddType application/x-asp-net .dll DirectoryIndex index.aspx DirectoryIndex Default.aspx DirectoryIndex default.aspx Alias /gpsmapper /usr/local/apache/htdocs/gpsmapper MonoApplications "/gpsmapper:/usr/local/apache/htdocs/gpsmapper" MonoServerPath "/opt/novell/mono/lib/mono/4.0/mod-mono-server4.exe" SetHandler mono i created an index.aspx under htdocs/gpsmapper but am getting a 503 Service temporarily unavailable. Is any setting i made wrong? A: You mix "MonoAutoApplication" and "MonoApplications" in the same file. I don't think it works. The AutoConfiguration feature allows precisely to avoid having to declare the application. Here is my own mod_mono.conf (used on Mac OS X 10.7.2 and Linux Ubuntu 11.04) : <IfModule !mono_module> LoadModule mono_module "libexec/apache2/mod_mono.so" </IfModule> <IfModule mono_module> AddType application/x-asp-net .config .cs .csproj .dll .resources .resx .sln .vb .vbproj AddType application/x-asp-net .asax .ascx .ashx .asmx .aspx .axd .browser .licx .master .rem .sitemap .skin .soap .webinfo MonoAutoApplication enabled MonoDebug true MonoServerPath "/usr/bin/mod-mono-server4" MonoSetEnv LANG=fr_FR.UTF-8 MonoUnixSocket "/tmp/.mod_mono" <IfModule dir_module> DirectoryIndex Default.aspx </IfModule> <DirectoryMatch "/(bin|App_Code|App_Data|App_GlobalResources|App_LocalResources)/"> Order deny,allow Deny from all </DirectoryMatch> <Location "/Mono"> Order deny,allow Deny from all Allow from 127.0.0.1 ::1 SetHandler mono-ctrl </Location> </IfModule> As you can see, I never define any Alias or MonoApplications directive.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Magento preserve form/grid input values on error/exception at server side While submitting forms and grids in Magento, if some error/exception comes then how all user inputs can be preserved and reproduce same form so that user can easily correct the error and resubmit the form A: The Grid has a method for such: setSaveParametersInSession() http://docs.magentocommerce.com/Mage_Adminhtml/Mage_Adminhtml_Block_Widget_Grid.html#setSaveParametersInSession As for forms take a look at: app/code/core/Mage/Adminhtml/controllers/CustomerController.php restoreData() I believe is what your looking for. http://docs.magentocommerce.com/Mage_Customer/Mage_Customer_Model_Form.html#restoreData in the CustomerController.php: $formData = $customerForm->extractData($request, 'account'); $customerForm->restoreData($formData); A: var edit_form = varienform(form_id, validationUrl) Whenever you create a varien form you can pass validation Url and Magento will send Ajax request to this Url before submitting the form and If you get any error, it wont submit the page else will proceed with the submission. For grid also it uses apply function in grid.js to submit the grid , there you also you can use Ajax to submit grid, check values at server side, throw error/exception- catch at client side-values will be preserved if there is an error, else submit the grid.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: label inside **NoRecordsTemplate** in **telerik radgrid** i have a label inside NoRecordsTemplate in telerik radgrid how can I find label id in .cs file in telerik radgrid control in NoRecordsTemplate?? <NoRecordsTemplate> <div><asp:Label ID="lblerror" runat="server"></asp:Label></div> </NoRecordsTemplate> Currently I am using following code to get label id but it is not working. protected void rgUsers_ItemDataBound(object source, Telerik.Web.UI.GridItemEventArgs e) { if (e.Item is GridNoRecordsItem) { Label lblerror = ((Label)e.Item.FindControl("lblerror")); SetValidation(lblerror, Messages.NO_RECORD_FOUND); } } A: Untested, but if you have a recent Telerik version, could you try just setting the text instead of using a control: rgUsers.MasterTableView.NoMasterRecordsText = "Your Error Text" More suggestions here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: combinations for forest in disjoint datastructure The average-case analysis is quite hard to do for disjoint data structure. The least of the problems is that the answer depends on how to define average (with respect to the union operation). For instance, in the forest given below. For description purpose each tree is represented by set. {0}, {1}, {2}, {3}, {4, 5, 6,8 } we could say that since there are five trees, there are 5 * 4 = 20 equally likely results of the next union (as any two different trees can be unioned). Of course, the implication of this model is that there is only a 2/5 chance that the next union will involve the large tree. Another model might say that all unions between any two elements in different trees are equally likely, so a larger tree is more likely to be involved in the next union than a smaller tree. In the example above, there is an 8/11 chance that the large tree is involved in the next union, since (ignoring symmetries) there are 6 ways in which to merge two elements in {1, 2, 3, 4}, and 16 ways to merge an element in {5, 6, 7, 8} with an element in {1, 2, 3, 4}. There are still more models and no general agreement on which is the best. The average running time depends on the model; O(m), O(m log n), and O(mn) bounds have actually been shown for three different models, although the latter bound is thought to be more realistic. Above text is from Algorithms and data analysis by Wessis. I am quite poor in combinational maths, so i am not understanding above problem, i need help here in answering following questions. * *How do we got 2/5 in above description? *How do we got 8/11 in above description? *Author has described only two models but at end of paragraph it is mentioned for different models, what is third model? Thanks for your help A: Here is the answer for the first two questions: * *Given five trees A, B, C, D, E what is the probability that E is included in a pair of randomly chosen trees? Since there are 10 pairs possible (AB, AC, AD, AE, BC, BD, BE, CD, CE, DE) and four of them (AB, AC, AD, AE) contain A the probability is 4/10 = 2/5. *Given five trees A={a}, B={b}, C={c}, D={d}, E={e,f,g,h} what is the probability that an element of E is included in a pair of randomly chosen items (where no two items are chosen from one tree)? There are 22 pairs of items (ab, ac, ad, ae, af, ag, ah, bc, bd, be, bf, bg, bh, cd, ce, cf, cg, ch, de, df, dg, dh) and 16 of them include one of (e,f,g,h) the probability is 16/22 = 8/11.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WCF REST is not returning a Vary response header when media type is negotiated I have a simple WCF REST service: [ServiceContract] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)] [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] public class Service1 { [WebGet(UriTemplate = "{id}")] public SampleItem Get(string id) { return new SampleItem() { Id = Int32.Parse(id), StringValue = "Hello" }; } } There is not constrain about the media that the service should return. When I send a request specifying json format, it returns JSON: GET http://localhost/RestService/4 HTTP/1.1 User-Agent: Fiddler Accept: application/json Host: localhost HTTP/1.1 200 OK Cache-Control: private Content-Length: 30 Content-Type: application/json; charset=utf-8 Server: Microsoft-IIS/7.5 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Date: Sun, 02 Oct 2011 18:06:47 GMT {"Id":4,"StringValue":"Hello"} When I specify xml, it returns XML: GET http://localhost/RestService/4 HTTP/1.1 User-Agent: Fiddler Accept: application/xml Host: localhost HTTP/1.1 200 OK Cache-Control: private Content-Length: 194 Content-Type: application/xml; charset=utf-8 Server: Microsoft-IIS/7.5 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Date: Sun, 02 Oct 2011 18:06:35 GMT <SampleItem xmlns="http://schemas.datacontract.org/2004/07/RestPrototype.Service" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><Id>4</Id><StringValue>Hello</StringValue></SampleItem> So far so good, the problem is that the service doesn't return a Vary HTTP header to say that the content has been negotiated and that the Accept http header has been a determinant factor. Should not it be like this?: GET http://localhost/RestService/4 HTTP/1.1 User-Agent: Fiddler Accept: application/json Host: localhost HTTP/1.1 200 OK Cache-Control: private Content-Length: 30 Content-Type: application/json; charset=utf-8 Server: Microsoft-IIS/7.5 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Vary:Accept Date: Sun, 02 Oct 2011 18:06:47 GMT {"Id":4,"StringValue":"Hello"} As far as I know, in terms of caching, the "Vary" header will tell intermediate caches that the response is generated based on the URI and the Accept HTTP header. Otherwise, a proxy could cache a json response, and use it for somebody that is asking xml. There is any way to make WCF REST put this header automatically? Thanks. A: You can use a custom message inspector to add the Vary header to the responses. Based on the automatic formatting rules for WCF WebHTTP, the order is 1) Accept header; 2) Content-Type of request message; 3) default setting in the operation and 4) default setting in the behavior itself. Only the first two are dependent on the request (thus influencing the Vary header), and for your scenario (caching), only GET are interesting, so we can discard the incoming Content-Type as well. So writing such an inspector is fairly simple: if the AutomaticFormatSelectionEnabled property is set, then we add the Vary: Accept header for the responses of all GET requests - the code below does that. If you want to include the content-type (for non-GET requests as well), you can modify the inspector to look at the incoming request as well. public class Post_0acbfef2_16a3_440a_88d6_e0d7fcf90a8e { [DataContract(Name = "Person", Namespace = "")] public class Person { [DataMember] public string Name { get; set; } [DataMember] public int Age { get; set; } } [ServiceContract] public class MyContentNegoService { [WebGet(ResponseFormat = WebMessageFormat.Xml)] public Person ResponseFormatXml() { return new Person { Name = "John Doe", Age = 33 }; } [WebGet(ResponseFormat = WebMessageFormat.Json)] public Person ResponseFormatJson() { return new Person { Name = "John Doe", Age = 33 }; } [WebGet] public Person ContentNegotiated() { return new Person { Name = "John Doe", Age = 33 }; } [WebInvoke] public Person ContentNegotiatedPost(Person person) { return person; } } class MyVaryAddingInspector : IEndpointBehavior, IDispatchMessageInspector { public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { } public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) { } public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) { WebHttpBehavior webBehavior = endpoint.Behaviors.Find<WebHttpBehavior>(); if (webBehavior != null && webBehavior.AutomaticFormatSelectionEnabled) { endpointDispatcher.DispatchRuntime.MessageInspectors.Add(this); } } public void Validate(ServiceEndpoint endpoint) { } public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { HttpRequestMessageProperty prop; prop = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name]; if (prop.Method == "GET") { // we shouldn't cache non-GET requests, so only returning this for such requests return "Accept"; } return null; } public void BeforeSendReply(ref Message reply, object correlationState) { string varyHeader = correlationState as string; if (varyHeader != null) { HttpResponseMessageProperty prop; prop = reply.Properties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty; if (prop != null) { prop.Headers[HttpResponseHeader.Vary] = varyHeader; } } } } public static void SendGetRequest(string uri, string acceptHeader) { SendRequest(uri, "GET", null, null, acceptHeader); } public static void SendRequest(string uri, string method, string contentType, string body, string acceptHeader) { Console.Write("{0} request to {1}", method, uri.Substring(uri.LastIndexOf('/'))); if (contentType != null) { Console.Write(" with Content-Type:{0}", contentType); } if (acceptHeader == null) { Console.WriteLine(" (no Accept header)"); } else { Console.WriteLine(" (with Accept: {0})", acceptHeader); } HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri); req.Method = method; if (contentType != null) { req.ContentType = contentType; Stream reqStream = req.GetRequestStream(); byte[] bodyBytes = Encoding.UTF8.GetBytes(body); reqStream.Write(bodyBytes, 0, bodyBytes.Length); reqStream.Close(); } if (acceptHeader != null) { req.Accept = acceptHeader; } HttpWebResponse resp; try { resp = (HttpWebResponse)req.GetResponse(); } catch (WebException e) { resp = (HttpWebResponse)e.Response; } Console.WriteLine("HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription); foreach (string headerName in resp.Headers.AllKeys) { Console.WriteLine("{0}: {1}", headerName, resp.Headers[headerName]); } Console.WriteLine(); Stream respStream = resp.GetResponseStream(); Console.WriteLine(new StreamReader(respStream).ReadToEnd()); Console.WriteLine(); Console.WriteLine(" *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* "); Console.WriteLine(); } public static void Test() { string baseAddress = "http://" + Environment.MachineName + ":8000/Service"; ServiceHost host = new ServiceHost(typeof(MyContentNegoService), new Uri(baseAddress)); ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(MyContentNegoService), new WebHttpBinding(), ""); endpoint.Behaviors.Add(new WebHttpBehavior { AutomaticFormatSelectionEnabled = true }); endpoint.Behaviors.Add(new MyVaryAddingInspector()); host.Open(); Console.WriteLine("Host opened"); foreach (string operation in new string[] { "ResponseFormatJson", "ResponseFormatXml", "ContentNegotiated" }) { foreach (string acceptHeader in new string[] { null, "application/json", "text/xml", "text/json" }) { SendGetRequest(baseAddress + "/" + operation, acceptHeader); } } Console.WriteLine("Sending some POST requests with content-nego (but no Vary in response)"); string jsonBody = "{\"Name\":\"John Doe\",\"Age\":33}"; SendRequest(baseAddress + "/ContentNegotiatedPost", "POST", "text/json", jsonBody, "text/xml"); SendRequest(baseAddress + "/ContentNegotiatedPost", "POST", "text/json", jsonBody, "text/json"); Console.Write("Press ENTER to close the host"); Console.ReadLine(); host.Close(); } } A: In WCF Web API, we are planning to add automatically setting the Vary header during conneg. For now if you are using Web API, you can do this by either using a custom operation handler or message handler. For WCF HTTP then using a message inspector as Carlos recommended is the way to go. A: It seems the webHttpBinding was designed to fit the model described in this post which allows soap to "co-exists" with non-soap endpoints. The implication in the endpoint URLs of the code in that link is each endpoint provides a resource as a single content-type. The endpoints in that link are configured to support soap, json and plain XML through the endpointBehaviors attribute. Your sample shows that webHttpBinding can support content negotiation but it is only partially implemented since the Vary header isn't being generated by WCF. If you want to use a framework that embraces the REST architecture style more closely, look at the reasons you might want to use OpenRasta. A: That behavior IMHO violates the SHOULD in https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-p6-cache-16#section-3.5 . I cannot see any grounds not to send the Vary in case of a negotiated response. I'll send it to the WCF HTTP list for clarification/fixing and get back with the answer here. Jan
{ "language": "en", "url": "https://stackoverflow.com/questions/7635466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Way to copy the values from column1(containing numbers) declared as varchar to another column2 declared as number in Mysql I am using a table say employee, which has two columns-mobileno and landlineno (both declared as varchar) contains the contact number of that employee. So now we are moving a step ahead by adding two additional columnms mn and fn both declared as bigint. So I wrote an update query which updated the values. Since the table has grown large, so it contains many junk values like 052-12525, which was inserted from from frontend, the value copied in mn is 052 ignoring the digits after "-". And 1 more instance is the mobileno is 5.836 which was incorrectly entered from front end was copied as 6. So please suggest me if there is a way in which the characters can be ignored and only the digits should be copied to the new column A: use FORMAT and REPLACE SELECT REPLACE('052-12525', '-', ''), FORMAT(12332.1,0) will return 05212525 and 12332
{ "language": "en", "url": "https://stackoverflow.com/questions/7635467", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to dissmiss keybord when editing UITextField Possible Duplicate: How do you dismiss the keyboard when editing a UITextField I know that I need to tell my UITextField to resign first responder when I want to dismis the keyboard, but I'm not sure how to know when the user has pressed the "Done" key on the keyboard. Is there a notification I can watch for? A: You should implement this method to know if the user has just pressed the return key (that key is called "return key"), and don't forget to return YES from this method. - (BOOL)textFieldShouldReturn:(UITextField*)textField { A: set the delegate of the UITextFieldDelegate ViewController(.h file) class and impliment following method in viewController (.m file) class. - (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return NO; } It will work.. A: You can set a delegate on your UITextField : UITextFieldDelegate Then this method is there for you : - (BOOL)textFieldShouldReturn:(UITextField *)textField A: You should implement next methods in your UITextFieldDelegate class: Tells the delegate that editing stopped for the specified text field. - (void)textFieldDidEndEditing:(UITextField *)textField; Asks the delegate if the text field should process the pressing of the return button. - (BOOL)textFieldShouldReturn:(UITextField *)textField;
{ "language": "en", "url": "https://stackoverflow.com/questions/7635468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bitmap Size is wrong Hy! The size of the Bitmap in the imageview doesn't look like 10x10 My Code: iv = (ImageView) findViewById(R.id.imageViewPizza); iv.setMaxHeight(10); iv.setMaxWidth(10); Screenshot: The Image is lager than 10x10 Layout: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <TextView android:text="Name" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView> <MultiAutoCompleteTextView android:id="@+id/multiAutoCompleteTextView1" android:layout_height="wrap_content" android:text="" android:layout_width="fill_parent"></MultiAutoCompleteTextView> <TextView android:text="Bewertung" android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView> <RatingBar android:id="@+id/ratingBar1" android:layout_width="wrap_content" android:layout_height="wrap_content"></RatingBar> <TextView android:text="Foto hinzufügen" android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView> <ImageView android:layout_height="wrap_content" android:src="@drawable/icon" android:layout_width="wrap_content" android:id="@+id/imageViewPizza" ></ImageView> <RelativeLayout android:id="@+id/relativeLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:text="hinzufügen" android:layout_height="wrap_content" android:id="@+id/bt_addform" android:layout_alignParentBottom="true" android:layout_width="fill_parent"></Button> </RelativeLayout> </LinearLayout> Please help A: Set your desired width then add a scaleType mode. I would try fitXY. http://developer.android.com/reference/android/widget/ImageView.ScaleType.html A: Try setting theLayoutParams of ImageView like this. iv = (ImageView) findViewById(R.id.imageViewPizza); iv.setLayoutParams(new LayoutParams(10,10)); It will set the width & height related to view. A: You have both layout_width and layout_height set to wrap_content, in addition to setting explicit values for width and height. Instead, you should just set layout_width and layout_height to some number value. See this link: http://developer.android.com/guide/practices/screens_support.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7635474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Flurry Analytics with iPhone and Website I have an iPhone application that is based on social networking. I have integrated flurry analytics into it. Now, there is a limitation to the information that my client can send to flurry and I want some other information also to be tracked and only my server can provide thatinformation. Can I integrate them both into one for my application. In other words, can I make some JSON calls from my server so that it also adds information to the unique id allocated for my mobile application so that I can see all the information I want in one place on the flurry page of my application. A: I don't know about any official ways to do this. You may ask this question to Flurry support - actually it is a better way to find out. I think it would be a hack if you sniff the format of the Flurry requests (which are not open, because we do them thru the provided FlurrySDK in iOS apps) and then try to perform the same type of requests on your server side. I don't even know whether Flurry sends the info plaintext or encrypted - I suppose it is encrypted, so you are gonna have a hard time rev.engineering it. A: AFAIK their public server API is read-only (link). I'd say the only way to get what you want is to export the data from Flurry to your own server and then correlate the data there. But of course that means not having Flurry's nice GUI to view the data with, so it might not be what you want. A: If you find a feature missing in Flurry or Flurry forces you to upgrade to their paid plan, you can also consider using the google analytics for ios. http://code.google.com/mobile/analytics/docs/iphone/ It's free and has event tracking as well, which you can use custom variables with it. After you set up google analytics, you can use the google gdata library to read any kind of data you need from google using their API. I wouldn't create my own tracking system.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635482", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: nhibernate. Bag is null after creation in same session I have the object, which contain the list of objects. public class Product: IProduct { public virtual long Id { get; set; } public virtual string Name { get; set; } public virtual IList<IFunction> Functions { get; set; } } public class Function : IFunction { public virtual long Id { get; set; } public virtual string Name { get; set; } public virtual IProduct Product { get; set; } } Mapped list of objects ( IList < IFunction > ): <bag name="Functions" cascade="all" table="T_WEBFUNCTIONS" lazy="false"> <key column="PRODUCT_ID" /> <one-to-many class="Function" /> </bag> Code : I try create a new object of Product public IProduct SetProduct(string productName) { // Product repository, which have nhibernate opened session ( ISession ) IDBRepository<IProduct> rep = Repository.Get<IProduct>(); // Create new object of product rep.Create(new Product() { Name = productName }); // get created object by name prod = rep.Query().Where(x => x.Name == productName).SingleOrDefault(); // I HAVE ISSUE HERE // prod.Functions == NULL. It must be a new List<Function>() // Nhibernate don't create empty list for me and this property always null return prod; } BUT. When nhibernate session close and open again, the list will be created and have 0 items. If I create an object(Product) in the same session and get it after creation, bag will be null. Function of data repository public class DBRepository<T> : IDBRepository<T> { protected ISession CurrentSession; public DBRepository(ISession session) { CurrentSession = session; } public void Create(T obj) { var tmp = CurrentSession.BeginTransaction(); CurrentSession.Save(obj); tmp.Commit(); } } A: When you are calling new Product(), your code is instantiating an object and the List<> property begins life as null. NHibernate can't help you there - it's what you've decided to do (by not overriding the default c'tor). NHibernate's 1st level cache (short explanation here) saves your object when you commit the transaction, so when in the same open session you ask for the object by its ID NHibernate skips getting the entity from the database and serves you that same instantiated object. You can test that with Object.ReferenceEquals(prodYouCreated, prodRetrievedFromRepository). When you close the session the 1st level cache is cleared and next time you query NHibernate fetches the data and builds the object itself - it chooses to give you back a zero-length list instead of null. That is the default behaviour. Hope this helps, Jonno
{ "language": "en", "url": "https://stackoverflow.com/questions/7635484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can I pass a value to a CSS function? I have a speedometer. I would like to show the speed depending on what value was entered in the textbox. Here is the demo. Here is the code, if you would like to browse. The main code where I need to update the value is. @-webkit-keyframes rotate { from {-webkit-transform:rotate(0deg);} to {-webkit-transform:rotate(180deg);} <-- I need to update 180deg on the fly } In ideal situation, I need to pull this value from a database. But just wondering is there a way to update this field anyhow on the go? May be JavaScirpt? Note:The demo works only in Safari and Chrome, not in firefox and IE A: You can define the syle hardcoded in the HTML file. And change it with a JS declaration in PHP. Not very strict, but it does the trick :) A: You may wish to try here for some solutions. Seems as though you will have to write out a whole new CSS rule onto the page in Javascript. Or create numerous classes and change the class with Javascript, but this would not prove practical for you as you would need potentially 360 classes. A: You should try to use a css preprocessor like LESS.js or SASS: http://lesscss.org/ http://sass-lang.com/ A: My answer: No you can not. But you can create the whole CSS using PHP. The best bet is to use PHP to generate the entire CSS esp the one you need to modify according to the user settting.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Runtime exception not terminating the programm As per my little-bit java knowledge Program supposed to be terminated after it throws runtime exception. But in my application after throwing runtime exception it is not terminating ,and as i am executing it on linux i have to use ctrl+c to terminate it, Otherwise it just do not terminate. I am creating jar on windows sytem and copy paste it in linux. Also i have logging enabled in my application. Update: I am not catching any exception No multithreading is used. A: A RuntimeException (or any Exception or Throwable) does not necessarily terminate your application. It only terminates your applications if it's thrown on the only non-daemon thread and is not handled. That means that if either another non-daemon thread is running or you catch the exception, the application will not be terminated. This recent answer from me gives a summary of what happens (it's specifically about an OutOfMemoryError, but the idea is the same).
{ "language": "en", "url": "https://stackoverflow.com/questions/7635501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dynamic extension in PHP I am new on SO, so I hope I make myself clear in the following question. I have been struggling myself recently trying to write a framework for a project. The problem is that I am new to PHP OOP and I am not sure how to extend an object that can be changed in the future and still keep the properties available in the extended class. More precisely: class main { function __construct() { $this->a='some a text'; $this->b='some b text'; } } class submain extends main() { function __construct() { parent::__construct(); $this->c='some c text'; } } $main=new main(); $submain=new submain(); So now the $submain variable contains 3 properties a,b and c. What if now I do $main->d='some d text'; How do I make so that the d property appears in the $submain variable which extended the main class? I suppose I should be using cloning?! A: Starting with the Edited Answer I now understand the question to be: How can you set a property on one object and have it set in all classes that derive from it (at runtime). Sorry, I think my best answer can only be a philosophical one. Certain languages favour certain approaches to solving problems. (Actually in javascript this would be really easy). Writing a class in PHP defines the object that gets created when the class is instantiated. Once an object is created methods of the class and inherited methods can be called to perform actions that the object is designed to do. Many objects can be created which each encapsulate a part of your system. Making each object do a specific job and keeping its coupling to other parts of the system low enables large systems to be built in specific testable parts. Each object created through a class is specific (possibly sharing static members - although static may be considered bad design). You would have to force PHP to dynamically share settings between objects of the same class. Now that I have hopefully dissuaded you from doing so - here is how you could do it. Notice that it looks ugly and will cause you infinite problems in the future if your program gets to any size. Please don't use what I am posting here. I didn't test this code or its syntax, I never write static stuff so there are probably mistakes, but I think this idea would work (and be horrible). class main { // Yes its defined statically but with an array you can do anything. public static $settings; public function __construct() {} public defineVar($varName, $varValue) { self::$settings[$varName] = $varValue; } public static function get($varName) { return self::$settings[$varName] = $varValue; } } // Submain as before. $t = new submain(); main::defineVar('d', 'some d text'); $t->get('d'); This will create a dynamically definable value that you can store in your main and all derived classes. Their values will be the same throughout all objects. If you want a value that can be different for the same variable through the classes you would basically be setting up a registry system (I think there might be a design pattern for that). Original Answer Below I would write this with the access types of public, protected and private which are important in OOP. All objects you create of class main will contain the properties as set by their constructor. Same goes for submain so you would add $d just as an a, b or c entry. I'll add it to the main, the submain constructor already calls its parent constructor so will construct objects with properties a, b, c and d defined. class main { public $a; protected $b; public $d; public function __construct() { $this->a='some a text'; $this->b='some b text'; $this->d='some d text'; } } class submain extends main() { public $c; public function __construct() { parent::__construct(); $this->c='some c text'; } public function getB() { return $this->b; } } $main=new main(); echo $main->a; // Publicly accessible. // Can't do $main->b() it is protected. echo $main->d; $submain=new submain(); echo $submain->a; // Still publicly accessible. echo $submain->getB(); // protected variable exposed by public function. echo $submain->d; A: You can just set the $d property in the main class: class main { public $d = 'some d text'; # <- set the property as public here. function __construct() { $this->a='some a text'; $this->b='some b text'; } } class submain extends main() { function __construct() { parent::__construct(); $this->c='some c text'; } } $main=new main(); $submain=new submain(); echo $submain->d; # some d text But I'm a bit unsure what you're looking for exactly. Just ask.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Check all fields in a dijit form Is there any way I can loop through all the dijit fields in a dijit form and print out whether they are valid. I only ask because my 'onValidStateChange' function disables my submit button and I don't know why it wont re-enable it. A: You get use the dijit.form.Form's getChildren() to get all of the child widgets in a form, and then use isValid() to check whether the field is valid; var form, iterFunction; form = dijit.byId('form'); iterFunction = function(widget){ console.log(widget.isValid()); }; dojo.forEach(form.getChildren(), iterFunction); A: By default, form.validate() will validate all the child widgets too. If any form widgets are added/removed dynamically to/from the form respectively, then connect all the child widgets and then validate form = dijit.byId('form_id'); form.connectChildren(); form.validate(); if the form has multiple tabs (TabContainer), the "connectChildren" function will actually attach all the fields at all descendant levels to the parent form object. We need not run a loop manually, until unless the particular fields need to be known for any more manipulations. For special case: If form contains many tabs and need to validate per form at a time and navigate for eg: cp1 and cp2 are the 2 tabs var mytab1 = dijit.byId("cp1"); var canNavigate = true; var highlight = function(widget){ var v = widget.validate; if(!v) return true; widget._hasBeenBlurred = true; if(!widget.validate()) { canNavigate = false; } }; dojo.forEach(mytab1.getChildren(), highlight); if(canNavigate) { dijit.byId("tc").selectChild("cp2"); } Complete example :- http://jsfiddle.net/ZtzTE/29/
{ "language": "en", "url": "https://stackoverflow.com/questions/7635508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to set CAP_SYS_NICE capability to a Linux user? My program is using the Linux system call setpriority() to change the priorities of the threads it creates. It needs to set negative priorities (-10) but, as mentioned on the documentation, this fails when run as a normal user. The user needs the CAP_SYS_NICE capability to be able to set the priorities as he wants, but I have no idea how to give such capability to the user. So my question: how to set CAP_SYS_NICE capability to a Linux user? A: Jan Hudec is right that a process can't just give itself a capability, and a setuid wrapper is the obvious way get the capability. Also, keep in mind that you'll need to prctl(PR_SET_KEEPCAPS, ...) when you drop root. (See the prctl man page for details.) Otherwise, you'll drop the capability when you transition to your non-root real user id. If you really just want to launch user sessions with a different allowed nice level, you might see the pam_limits and limits.conf man pages, as the pam_limits module allows you to change the hard nice limit. It could be a line like: yourspecialusername hard nice -10 A: There is a nice handy utility for setting capabilities on a binary: setcap. This needs to be run as root on your application binary, but once set, can be run as a normal user. Example: $ sudo setcap 'cap_sys_nice=eip' <application> You can confirm what capabilities are on an application using getcap: $ getcap <application> <application> = cap_sys_nice+eip I'd suggest integrating the capabilities into your makefile in the install line, which is typically run as root anyhow. Note that capabilities cannot be stored in a TAR file or any derivative package formats. If you do package your application later on, you will need a script (postinst for Debian packages) to apply the capability on deploy. A: AFAIK It's not possible to get a capability. Root processes have all capabilities and can give them up, but once given up, they can't be regained. So you'll need a suid-root wrapper that will give up all other capabilities and run the process. A: Regarding sudo, I added the user like this: niceuser ALL=NOPASSWD:/usr/bin/nice And then it worked fine: niceuser@localhost $ nice 0 niceuser@localhost $ sudo nice -n -10 nice -10
{ "language": "en", "url": "https://stackoverflow.com/questions/7635515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: iPad - Recognizing specified telephone number after globally disabling I'm have webpage optimizes for iPad, and I've noticed that sometimes it recognizes my random numbers as telephone numbers. I've dealt with that with this meta: <meta name = "format-detection" content = "telephone=no" /> and it works perfectly. But now I have kind of a problem. On one webpage, I have contact information (including telephone number), and I want that telephone number to get recognized. How can I tell iPad to recognize only that number, while ignoring all others ? A: You need to explicitly inform Safari what is a telephone link. Take a look on the IOS Developer Library.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: g++ undefined reference in very simple example Please help with the following noob question about C++ and g++ compilation and linking. Essentially I have 2 classes in 2 different files, and can compile them but when I attempt to link, one class can't see the methods of the other, even though I am linking both. Order of object files does not help in this case. The problem seems related to a non-default constructor that takes a parameter. I have distilled and reproduced the problem in the following simple code: File: a.cpp: #include <iostream> class A { public: int my_int; A(int i) { my_int = i; std::cout << "A"; } }; File: a.hpp: #ifndef __A_H_ #define __A_H_ class A { public: A(int i); }; #endif File b.cpp: #include <iostream> using namespace std; #include <a.hpp> class B { public: int my_int; B(int i) { my_int = i; A a(i); cout << "B\n"; } }; int main(int argc, char* argv[]) { B b(5); cout << "hello world: "; cout.flush(); return 0; } Commands I use to build: g++ -c -I. a.cpp g++ -c -I. b.cpp g++ -o c_test a.o b.o Alternately, I've tried each of these: g++ -o c_test b.o a.o g++ -I. -o c_test a.cpp b.cpp g++ -I. -o c_test b.cpp a.cpp Error I get in any of above link scenarios: b.o: In function `B::B(int)': b.cpp:(.text._ZN1BC1Ei[B::B(int)]+0x1c): undefined reference to `A::A(int)' collect2: ld returned 1 exit status Thanks in advance for any insight. (sorry if this is a re-post -- I thought I posted it and don't see it...) A: It doesn't work that way. What you've come across is technically an ODR violation, which roughly means that A in both a.cpp and b.cpp must be the same thing. It isn't. Moreover, the constructor is implicitly inline in a.cpp and therefore its code needn't be emitted. Changing a.cpp to #include <iostream> #include "a.hpp" A::A(int i) { my_int = i; std::cout << "A"; } will fix the error. A: You a.cpp is violating the one definition rule and redefining A entirely. You just want to define the function in your source file: A::A(int i) { my_int = i; std::cout << "A"; } Also you may want to mark the function explicit to avoid ints being treated as A's in a variety of unwanted contexts. A: In a.cpp, you should #include "a.hpp" and then define the constructor simply as A::A(int i) { ... }. By writing a whole definition of class A with the constructor code within the class body, you're implicitly defining the constructor as an inline function, which is why there's no definition for it in the object file. A: You have two different classes (one containing myint, one not) both called class A. You can't do that. Change a.cpp to: #include <iostream> #include "a.hpp" A::A(int i) { my_int = i; std::cout << "A"; } And change a.hpp to: #ifndef __A_H_ #define __A_H_ class A { public: int my_int; A(int i); }; #endif Thank about it, the way you have it, what would the compiler do if someone did this: #include "a.hpp" // ... A foo(3); cout << sizeof(foo) << endl; How could it know that class A has a member other than the constructor? How could it know the size? A: You are breaking the One Definition Rule, as you have two distinct separate A classes in your program. The simple common implementation of your A.cpp file should look like: #include "a.h" // where the definition of the type is A::A( int x ) : myint(i) {} With "a.h" containing the proper definition of the type: #ifndef A_H_ // identifiers containing double underscores (__) are reserved, don't use them #define A_H_ class A { int myint; // This must be present in the definition of the class! public: A(int i); }; #endif; And then in the implementation of B, you probably meant: #include "a.h" #include <iostream> using namespace std; // I don't like `using`, but if you use it, do it after all includes! class B { public: // int my_int; // do you really want to hide A::my_int?? B(int i) : A(i) { // use the initializer list cout << "B\n"; } }; A: The right thing to do is: a.hpp #ifndef __A_H_ #define __A_H_ class A { public: int my_int; A(int i); }; #endif a.cpp #include <iostream> #include "a.hpp" A::A(int i) { my_int = i; std::cout << "A"; } b.cpp - remains the same
{ "language": "en", "url": "https://stackoverflow.com/questions/7635517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: XmlSerializer saves null-file I have a problem with serializing my objects. I implemented IXmlSerializable interface and initialize object of XmlSerializer(for example, serializer). But sometimes after calling serializer.Serialize(writer, data) my output file looks like this: why do I have such behavior? public class MyClass : IData { private static readonly XmlSerializer _formatter = new XmlSerializer(typeof(MyData)); public void Save(string filePath) { using (StreamWriter writer = new StreamWriter(filePath)) { Save(writer); writer.Close(); } } public void Save(TextWriter Writer) { MyData data = GetMyDataObject(); _formatter.Serialize(Writer, data); } private MyData GetMyDataObject() { MyData data = new MyData (); foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(typeof(IData))) pd.SetValue(data, pd.GetValue(this)); return data; } } public class MyData : IData, IXmlSerializable { public void WriteXml(System.Xml.XmlWriter writer) { writer.WriteAttributeString("Number", Number); if (HardwareInformation != null) { writer.WriteStartElement("HWInfoList"); foreach (KeyValuePair<string, string> kw in HardwareInformation) { writer.WriteStartElement("HWInfo"); writer.WriteAttributeString("Key", kw.Key); writer.WriteAttributeString("Value", kw.Value); writer.WriteEndElement(); } writer.WriteEndElement(); } } } public interface IData { Dictionary<string, string> HardwareInformation { get; set; } string Number { get; set; } } A: How are you serializing? Here is an example of a Serialize Function private XDocument Serialize<T>(object obj) { XDocument ReturnValue = new XDocument(); XmlSerializer Serializer = new XmlSerializer(typeof(T)); System.IO.StringWriter sw = new System.IO.StringWriter(); System.IO.StringReader sr; Serializer.Serialize(sw, obj); sr = new System.IO.StringReader(sw.ToString()); ReturnValue = XDocument.Load(sr); return ReturnValue; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7635519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }