text
stringlengths
8
267k
meta
dict
Q: android Difference between handler.postAtTime and handler.postDelayed Please tell me the difference between handler.postAtTime and handler.postDelayed in android.And also please guide me when to use handler.postAtTime and when to use handler.postDelayed. A: From documentation: For postAtTime: public final boolean postAtTime (Runnable r, long uptimeMillis) ... uptimeMillis The absolute time at which the callback should run, using the uptimeMillis() time-base. ... And for postDelayed: public final boolean postDelayed (Runnable r, long delayMillis) ... delayMillis The delay (in milliseconds) until the Runnable will be executed. ... If this is still not clear, postDelayed() run something after X millisecond from current time. While postAtTime() runs something at specified time XX:YY:ZZ.mmm.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: backbone.js nested model's object not unique to instance I have a parent Model that has by default and nested Model. The nested Model itself has propertyA, which is an object with defaultValue and userValue. The idea is that every instance of parent Model comes with a nested Model that has a userValue of null, and a static default value. The problem is, when I update the userValue for one instance, it ends up changing for all instances going forward. Instead of updating the userValue for a particular instance, I'm doing something wrong and updating the nested Model "prototype". Below code available at http://jsfiddle.net/GVkQp/4/. Thanks for help. var ParentModel = Backbone.Model.extend({ initialize: function(){ var defaultObjs = { nestedModel : new NestedModel() }; $().extend(this.attributes, defaultObjs); } }); var NestedModel = Backbone.Model.extend({ defaults: { "propertyA" : { "defaultValue" : "ABC", "userValue": null } } }); var ParentView = Backbone.View.extend({ initialize: function(){ var self = this; var defaultValue = self.model.get("nestedModel").get("propertyA")["defaultValue"]; var userValue = self.model.get("nestedModel").get("propertyA")["userValue"]; var div = $("<div class='box'>defaultValue = <span id='defaultValue'>" + defaultValue+ "</span>, userValue = <span id='userValue'>" + userValue + "</span></div>"); var divButton = $('<input type="button" value="Change my userValue to DEF">') .click(function(){ temp = self.model.get("nestedModel").get("propertyA"); temp.userValue = "DEF"; //wherewas my intention is just to set the userValue for a particular instance, //generating another instance of ParentView (by clicking button) reveals that //the userValue is set even for new instances. //How can I change it such that I only change the userValue of the particular //instance? //set value self.model.get("nestedModel").set({"propertyA": temp}); //update userValue in View userValue = self.model.get("nestedModel").get("propertyA")["userValue"]; $(this).parent().find("span#userValue").text(userValue); }); //append divButtont to div div.append(divButton) //append div to body $('body').append(div) }, }); $("#add").click(function(){ var newBoxView = new ParentView({ model: new ParentModel() }); }); A: Thanks for the jsFiddle. It illustrates your problem perfectly. You see, when you set your "propertyA" in your defaults, the object you create is the default value being copied along with every other nested class you create. For this reason, when you define your defaults, you have the option to define it as a function in order to create the default value new every time. If you do this, you solve your problem: var ParentModel = Backbone.Model.extend({ defaults: function() { return {nestedModel: new NestedModel()}; } }); var NestedModel = Backbone.Model.extend({ defaults: function() { return { "propertyA" : { "defaultValue" : "ABC", "userValue": null } }; } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7593209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create function dynamically in a database HI i need to create a function dynamically in a database..My procedure accepts Database name as a parameter, then i need to create this function dynamically in that DATABASE. But i am unable to execute this..please help me.Regards in advance Create procedure [dbo].[Sp_Insertfun] ( @OrgName nvarchar(100) ) AS BEGIN Declare @orgdataInsertString nvarchar(max); set @orgdataInsertString='Use '+@OrgName+'' ; set @orgdataInsertString=@orgdataInsertString+char(13)+char(10)+'GO'+' Create function dbo.[fn_GroupDisplay](@GroupID int) RETURNS @Group TABLE ( GrpPath nvarchar(max) ) as begin declare @ParentId1 int declare @ParentId2 varchar(50) declare @ParentId3 varchar(50) declare @parentId4 varchar(50) declare @Text nvarchar(max) set @ParentId3='''' begin set @ParentId1=(select ParentID from GroupDetails where GroupID=@GroupID) set @ParentId4=(select GroupName from GroupDetails where GroupID=@GroupID) while(@ParentId1>0) begin set @parentId2=(select GroupName from GroupDetails where GroupID=@ParentId1 ) set @ParentId3 = @ParentId2+ ''\'' + coalesce(@ParentId3,''') set @ParentId1=(select ParentID from GroupDetails where GroupID=@ParentId1 ) end set @Text=@ParentId3+@ParentId4 INSERT INTO @Group VALUES (@Text) end RETURN end' execute sp_executesql @query=@orgdataInsertString print @orgdataInsertString end
{ "language": "en", "url": "https://stackoverflow.com/questions/7593215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django:How to let 3rd party sites access images on your server.(limited access i.e. only to that folder) I am working in Django.I am trying to connect my website to Facebook. What i want to do is 1)Send post_data post_data = [('access_token',access_token), ('message', message), ('link', some_link),('picture',internal_server_path_of_image) 2)urllib2.urlopen(graph_url, urllib.urlencode(post_data)) What this should do is post that data on the facebook profile of a user. But i am unable to access "internal_server_path_of_image". Is there anyway in which i can make a particular folder on my server available to the site ? i.e. the images on that folder should be accessible from outside. for e.g. I have folder site_name/project/images/photos.png on the server some_server.dreamhost.com/site_name/project/images/photos.png. Now i want to access this image somehow. Is the question clear ? or do I need to add a few things ? Any help will be highly appreciated. A: I have come with a solution. As people had pointed out that the imagefield gives us the url of the image. That was true, what i am doing now is passing that url. At that url i have written a controller method. This method simply renders the image and returns it. This gives access to the facebook api to get the required image from my server. def test(request,name): name = str(name)+".jpg" url = "Users/admin/workspace/bolt/templates/media/images/photos/" full = url+name image_data = open(full, "rb").read() return HttpResponse(image_data, mimetype="image/png") Hope this helps others
{ "language": "en", "url": "https://stackoverflow.com/questions/7593220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Serial Port Communication Project I'm doing a final year project on car park display system. What it does basically is to detect any cars in the parking lot, update the number of lots available and show whether it's full or not. I'm having trouble writing a programme in C# using Microsoft Visual Studio 2008. I'm getting data from the serial port that my other project mate is sending through. All I need to do is to receive the data, then read the data. This is just to simulate the car lots being occupied and emptied. I need to edit my program so that i can receive and update data regarding the lots whether it is occupied or not and calling other functions. The data receiving will be in ascii. each lot will be assigned to a specific ascii. Like for example 0x5A is for lot1, 0x59 is for lot 2 etc.. Here is a sample of my project. int intNumberLots = 6; SerialPort serialPort = new SerialPort("COM1"); serialPort.BaudRate = 115200; serialPort.Parity = Parity.None; serialPort.StopBits = StopBits.One; serialPort.DataBits = 8; serialPort.Handshake = Handshake.None; serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); serialPort.Open(); private void startButton_Click(object sender, EventArgs e) { while(){ if (serialPort.ReadLine == "0x57" && intNumberLots >= 0) // if data received is "1", do tasks below { inputTextBox.Clear(); // clear input textbox pictureBox1.Visible = true; // show a picture of a vehicle intNumberLots--; // decrease the number of available parking lots shown label9.Text = intNumberLots.ToString(); } else if (serialPort.ReadLine == "0x58" && intNumberLots >= 0) { inputTextBox.Clear(); pictureBox2.Visible = true; intNumberLots--; label9.Text = intNumberLots.ToString(); } else if (serialPort.ReadLine == "0x59" && intNumberLots >= 0) { inputTextBox.Clear(); pictureBox3.Visible = true; intNumberLots--; label9.Text = intNumberLots.ToString(); } else if (serialPort.ReadLine == "0x5A" && intNumberLots >= 0) { inputTextBox.Clear(); pictureBox4.Visible = true; intNumberLots--; label9.Text = intNumberLots.ToString(); } } Then for the code that updates if there is no car in the lot; else if (string.str != "0x57" && intNumberLots >= 3) { inputTextBox.Clear(); pictureBox1.Visible = false; intNumberLots++; label9.Text = intNumberLots.ToString(); } else if (string.str != "0x58" && intNumberLots >= 3) { inputTextBox.Clear(); pictureBox2.Visible = false; intNumberLots++; label9.Text = intNumberLots.ToString(); } else if (string.str != "0x59" && intNumberLots >= 3) { inputTextBox.Clear(); pictureBox3.Visible = false; intNumberLots++; label9.Text = intNumberLots.ToString(); } else if (string.str != "0x5A" && intNumberLots >= 3) { inputTextBox.Clear(); pictureBox4.Visible = false; intNumberLots++; label9.Text = intNumberLots.ToString(); } A: Each call to serialPort.ReadLine is going to block until the next line comes in. You need to serialPort.ReadLine once at the top of the loop into a variable and test that. While(){ message = serialPort.ReadLine(); if (message == "0x57" && intNumberLots >= 0) // if data received is "1", do tasks below { ...etc. Also, is the data really a string comprising the characters "0x5A" etc. or is each a character '0x5A' ? I notice that your example isn't real code - (While instead of while, serialPort.ReadLine instead of serialPort.ReadLine(), string.str, for example). Please try to post proper example code that we can help you fix - there are too many issues with this to identify your true problem (especially since you've not said what the problem is!) A: I see you have hooked up the datareceived event handler for the serial port. If so, why are you not using it? The event will fire up whenever data comes thru the serial port, which is better then aimlessly polling the serial port for data which is only a waste of resources. public void DataReceived(object sender, SerialDataReceivedEventArgs e) { var datareceived = serialport.ReadLine() // Do data processing here // Invoke delegate using dispatcher to update UI }
{ "language": "en", "url": "https://stackoverflow.com/questions/7593221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ebean and playframework In play 2.0 Ebean should become the default persistence layer. And after a few days of hibernate frustration I started a look on Ebean. I found the yabe example really impressive. However I had a bunch of questions: * *Does anybody use the play-module in a commercial project? *Does the module works with play 1.2? *What databases-platforms are supported? I found a special-class for Hsql. *Is there any update-support for database-tables or is it always drop and create? Would be great if any one can give some information about. A: On your questions: * *I'm not aware of any famous application using it, but for what I saw it has a very active community that uses it. It's been around for 4 years (maybe more), so I expect some reliability :) *There seems to be a module, code here, that should be compatible. Never tried it though *Supported DB include: Oracle, MySql, Postgres, H2, SQL Server, SQLite. Maybe mroe, but these should be enough *EBeans can generate DDL for the database Schema. And it would surprise me if it doesn't have a "update" procedure (it would limit the usefulness a lot!) A: * *Does anybody use the play-module in a commercial project? Not yet. * *Does the module works with play 1.2? I've tried, it does not. * *What databases-platforms are supported? I found a special-class for Hsql. All that ebean supports. * *Is there any update-support for database-tables or is it always drop and create? Use the liquibase module for this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I ensure that two divs always have the same height? I am using jquery-mobile framework. I have two divs side by side (as columns), I am trying to keep their height same irrespective of how much data they contain. This the html: <ul class="datablock" id="Manufacturing_and_Qualification_Information" style="display: none;"> <div data-role="controlgroup" data-theme="d" class="ui-grid-m ui-corner-all ui-controlgroup ui-controlgroup-vertical"> <div data-theme="d" id="paramBlk" class="ui-block-m"><li>Blah Blah Blah Blah Blah</li></div> <div data-theme="d" id="valueBlk" class="ui-block-n"><li>Blah</li></div> </div> <div data-role="controlgroup" data-theme="d" class="ui-grid-m ui-corner-all ui-controlgroup ui-controlgroup-vertical"> <div class="ui-block-m" id="leftBtmRnd"><li>Blah Blah Blah Blah Blah</li></div> <div class="ui-block-n" id="rightBtmRnd"><li>Blah</li></div> </div> </ul> This is the jQuery code, which I tried so for, but it's not working as expected: var $blockM = $(".datablock").find('.ui-block-m'); var $blockN = $(".datablock").find('.ui-block-n'); if($blockM.height() < $blockN.height()){ $blockM.css('height',$blockN.height()); }else if($blockM.height() > $blockN.height()){ $blockN.css('height',$blockM.height()); } How can I achieve this? A: We use a jquery plugin (I guess) called 'equalheights' For this. There seem to be several out there, but they all seem to do the same job. (I'v not picked this one in our project, so I don't know exactly which it is we use, but they seem somewhat equal) Take a look at this plugin or this plugin, I think they do what you want. A: Working link : http://jsfiddle.net/bMMpz/1/ Here is the code: var biggestHeight = 0; var $blockM; var $blockN; $(function() { $blockM = $(".datablock").find('.ui-block-m'); $blockN = $(".datablock").find('.ui-block-n'); getBiggestHeight(); $blockN.height(biggestHeight); $blockM.height(biggestHeight); }); function getBiggestHeight() { $blockM.each(function(i, e) { if ($(e).height() > biggestHeight) biggestHeight = $(e).height() }); $blockN.each(function(i, e) { if ($(e).height() > biggestHeight) biggestHeight = $(e).height() }); } I look for the biggest div and then select both selector and set height. A: function equalHeight(group) { tallest = 0; group.each(function() { thisHeight = $(this).height(); if(thisHeight > tallest) { tallest = thisHeight; } }); group.height(tallest); } $(document).ready(function() { equalHeight($(".ui-grid-m")); }); Or use css3 .datablock { display:table; } .ui-grid-m { display:table-cell; } A: if($blockM.height() < $blockN.height()) { $blockM.height($blockN.height()); }else if($blockM.height() > $blockN.height()) { $blockN.height($blockM.height()); } try this A: Two column grids <div class="ui-grid-a"> <div class="ui-block-a"><strong>I'm Block A</strong> and text inside will wrap</div> <div class="ui-block-b"><strong>I'm Block B</strong> and text inside will wrap</div> </div> Just look in jQuery Mobile A: $(document).ready(function({ var x = $('#primary').height(); $('#sidebar').css('height', x); }); Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: LinQ query with multiple tables and extracting data I'm doing a query to inner join 4 tables and I have to extract data and convert into string and place it in an array for it. var query = from a in context.as join b in context.bs on a.prikey equals b.forkey join c in context.cs on b.prikey equals c.forkey join d in context.ds on c.prikey equals d.forkey where b.gender == gender where c.age == age select new { a.Name, a.Age, b.Gender, }; string[] results = new string[] {} return results; Normally, if a single table is involved a as = plural of table a as t = query.First() string[] results = new string[] {t.Name, t.Age, t.Gender} return results; I'm missing a step to extract the data. A: It depends what exactly you want to do with the data. Your code won't actually compile at the moment as it's trying to create an anonymous type with multiple properties all called "arg" but I'm assuming you've really got a more sensible query. Ultimately, the fact that you're using multiple tables is irrelevant here - you're only getting a single result element at a time: the fact that each result element contains data from multiple tables is neither here nor there in terms of how you access it. Now I've just noticed that you say you want to "extract data and convert into string". If possible, you should express that in your query. You may be able to do that at the database, or you may need to force the final part of the execution to execute locally, like this: // Not executed yet! var dbQuery = from a in context.a join b in context.bs on a.prikey equals b.forkey join c in context.cs on b.prikey equals c.forkey join d in context.ds on c.prikey equals d.forkey where ... select { a.Age, b.Name, c.Salary, d.Location }; // This still won't talk to the database! var finalQuery = dbQuery.AsEnumerable() .Select(x => string.format("Age: {0}; Name: {1}; " + "Salary: {2}; Location: {3}", x.Age, x.Name, x.Salary, x.Location)); // This will finally execute the query string[] results = finalQuery.ToArray(); Now you don't have to do it like this - but it's probably the best approach, at least with the amount of information you've given us. If you can tell us more about how you're trying to combine the data from the multiple tables, we may be able to help you more. EDIT: Okay, now you've given us a bit more information, I suspect you want: var query = from a in context.a join b in context.bs on a.prikey equals b.forkey join c in context.cs on b.prikey equals c.forkey join d in context.ds on c.prikey equals d.forkey where ... select new string[] { a.arg, b.arg, c.arg, d.arg }; string[] results = query.First(); I haven't tried creating arrays in LINQ to SQL... that may work, or you may need to go via an anonymous type and AsEnumerable as per the earlier part of my answer. You should also think about what you want to happen if there are no results, or multiple results. EDIT: Having seen the edited question, you really can treat multiple tables the same way as a single table. You'd use exactly the same code for handling the result, once it's been projected into an anonymous type: var query = from a in context.as join b in context.bs on a.prikey equals b.forkey join c in context.cs on b.prikey equals c.forkey join d in context.ds on c.prikey equals d.forkey where ... select new { a.Name, a.Age, b.Gender }; var result = query.First(); // Call ToString appropriately on each property, of course string[] array = new string[] { result.Name, result.Age, result.Gender }; A: var query = from a in context.a join b in context.bs on a.prikey equals b.forkey join c in context.cs on b.prikey equals c.forkey join d in context.ds on c.prikey equals d.forkey where a.arg == arg where b.arg == arg where c.arg == arg select new { allStrings = a.arg + a.arg + b.arg + c.arg + d.arg }; string[] results = query.ToArray();
{ "language": "en", "url": "https://stackoverflow.com/questions/7593227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Maven : wrong local POM and versioning issue I have 4 Modules (4 POM XML files ) and one parent XML file I have this directory structure , please refer to the screen shot http://postimage.org/image/1gjk3mdg/ Currently this error is occuring when i ran the Parent POM.xml file (which internally runs all the Module's POM xml files) The project com.bayer:tata-mw:1.0 (C:\tata\middleware\pom.xml) has 1 error [ERROR] Non-resolvable parent POM: Could not find artifact com.bayer:tata:pom:1.0-SNAPSHOT and 'parent.relativePath' points at wrong local POM @ line 9, column 12 -> [Help 2] To resolve the Parent POM error i am refering like this on to my child POM.xml file <parent> <groupId>com.bayer</groupId> <artifactId>tata</artifactId> <version>1.0-SNAPSHOT</version> <relativePath>c:/tata/pom.xml</relativePath> </parent> Please guide me whether this is correct approach or not , becuase when i did that the error still persists . Thank you . A: In parent section, relativePath xml tag should point to a path in ... relative ! Like : <parent> <groupId>com.bayer</groupId> <artifactId>tata</artifactId> <version>1.0-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> A: Update maven with force update of Snapshot/Release right click on project-->maven-->update project-->check force update of snapshot A: follow below steps - 1- Create a Parent Maven project Go to your .m2 folder( C:\Users.m2 ) and delete all repository. 2- Go your Maven project Update your Maven Project A: Simply add an empty <relativePath/> to so that it can resolve the parent pom - <parent> <groupId>com.proj</groupId> <artifactId>com.proj.api</artifactId> <version>0.1.1</version> <relativePath></relativePath> </parent> Another preffered way to create modular maven projects is to follow below steps - 1- Create a Parent Maven project new-->project-->Maven Project-->Check Create a simple project checkbox-->provide all Maven Ids 2- Create Maven Module and add the module to previously created parent project new-->other..-->Maven Module-->Check Create simple project checkbox-->name your module -->Browse Parent projst-->select previously created project
{ "language": "en", "url": "https://stackoverflow.com/questions/7593229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Updating large number of rows I have a large number of rows in a SQL Server table. I need to select all those rows and run an update query for each of those rows. I need to know what's the best option do it from the following * *run a select query and get a DataTable and use the following code in the application foreach(DataRow item in DataTable.Rows) { //perform update } *in the database level use a stored procedure, select the set of data and use SQL Server cursor to perform the update A: Option 1 vs option 2 means you work with disconnected dataset vs connected data readers. As discussed other times here in SO in fact this means more memory needs at once on the client vs a connection kept open longer and smaller chunk of data transmitted more often while looping on results. Since your main focus is on the update of data i think both options are probably similar and if you have many records i would probably go for the second one, using datareader, to do not have to load all those records at once in a dataset. As others already pointed out the best performances would be achieved having a set based update stored procedure to which you would pass certain parameters and all records are atomically updated at once. Or also have a look at SqlBulk updates. A: i have also one suggestion foreach(DataRow item in DataTable.Rows) { //perform update } here you can use LINQ .so it can give fast response A: Like Marc already commented, go for option 3, and do a set based update if at all possible (and usually it is). If you think it isn't, maybe you could ask a separate question on how to do that. The more specifics you will give, the better the proposed solutions will fit your situation
{ "language": "en", "url": "https://stackoverflow.com/questions/7593230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to select default button in wpf dialog? I am creating a WPF dialog. It is like our normal messagebox with ok and cancel button. How to create such a dialog so that the Ok button is selected when the dialog is opened? A: To set a Window's Default button Set your default button's IsDefault property to true. Note that you can also set a Window's Cancel button by setting a button's IsCancel property to true. To set the Selected (focused) button in a Window If you want to select a particular button then use the Focus method like this: yourButton.Focus(); You might do this when a Window loads (in the Window_Loaded event). To select a particular button when your Window opens make sure its IsTabStop property is set to true and ensure its TabIndex property is lower than any other control on the Window. A: just create a new button template and change the look and feel for the IsDefault=Tue state. I just created a style and modified the state. <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:System="clr-namespace:System;assembly=mscorlib" xmlns:Microsoft_Windows_Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero" x:Class="WpfApplication7.Window3" x:Name="Window" Title="Window3" Width="640" Height="480" FocusManager.FocusedElement="{Binding ElementName=test}"> <Window.Resources> <Style x:Key="ButtonFocusVisual"> <Setter Property="Control.Template"> <Setter.Value> <ControlTemplate> <Rectangle Margin="2" Stroke="red" StrokeThickness="1" SnapsToDevicePixels="true" StrokeDashArray="1 2"/> </ControlTemplate> </Setter.Value> </Setter> </Style> <Style x:Key="ButtonStyle1" TargetType="{x:Type Button}"> <Setter Property="FocusVisualStyle" Value="{StaticResource ButtonFocusVisual}"/> <Setter Property="HorizontalContentAlignment" Value="Center"/> <Setter Property="VerticalContentAlignment" Value="Center"/> <Setter Property="Padding" Value="1"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type Button}"> <Border x:Name="border" BorderThickness="1" BorderBrush="#FF040000" CornerRadius="5"> <Border.Background> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FF7A7A7A" Offset="0"/> <GradientStop Color="#FFE7E7E7" Offset="1"/> </LinearGradientBrush> </Border.Background> <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/> </Border> <ControlTemplate.Triggers> <Trigger Property="IsDefault" Value="True"> <Setter Property="Background" TargetName="border"> <Setter.Value> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FFA76F6F" Offset="0"/> <GradientStop Color="#FFE7E7E7" Offset="1"/> </LinearGradientBrush> </Setter.Value> </Setter> </Trigger> <MultiTrigger> <MultiTrigger.Conditions> <Condition Property="IsFocused" Value="True"/> <Condition Property="IsDefault" Value="True"/> </MultiTrigger.Conditions> <Setter Property="Background" TargetName="border"> <Setter.Value> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FFC2BE5B" Offset="0.007"/> <GradientStop Color="#FFE7E7E7" Offset="1"/> </LinearGradientBrush> </Setter.Value> </Setter> </MultiTrigger> <Trigger Property="IsPressed" Value="True"> <Setter Property="BorderBrush" TargetName="border" Value="#FF01641D"/> <Setter Property="BorderThickness" TargetName="border" Value="2"/> <Setter Property="Background" TargetName="border"> <Setter.Value> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FF528159" Offset="0"/> <GradientStop Color="#FFE7E7E7" Offset="1"/> </LinearGradientBrush> </Setter.Value> </Setter> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </Window.Resources> <Grid x:Name="LayoutRoot"> <Button x:Name="test" Content="Button" HorizontalAlignment="Left" Height="26" Margin="130,157,0,0" VerticalAlignment="Top" Width="164" Style="{DynamicResource ButtonStyle1}" IsDefault="True"/> <Button Content="Button" Height="26" Margin="298,157,162,0" VerticalAlignment="Top" Style="{DynamicResource ButtonStyle1}"/> <Button Content="Button" HorizontalAlignment="Right" Height="26" Margin="0,157,-6,0" VerticalAlignment="Top" Width="164" Style="{DynamicResource ButtonStyle1}"/> </Grid> A: How about IsDefault? <Button Command="{Binding MyButtonCommand}" Content="My Button Text" IsDefault="True"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/7593231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "43" }
Q: ASP alternative to codepad.org Is there any alternative to http://codepad.org/ for use with ASP language? I would like to quickly check syntax online. Thanks A: How about http://ideone.com/ it supports C# & VB.NET, no mention of ASP specifically though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Fast way to sum Fourier series? I have generated the coefficients using FFTW, now I want to reconstruct the original data, but using only the first numCoefs coefficients rather than all of them. At the moment I'm using the below code, which is very slow: for ( unsigned int i = 0; i < length; ++i ) { double sum = 0; for ( unsigned int j = 0; j < numCoefs; ++j ) { sum += ( coefs[j][0] * cos( j * omega * i ) ) + ( coefs[j][1] * sin( j * omega * i ) ); } data[i] = sum; } Is there a faster way? A: A much simpler solution would be to zero the unwanted coefficients and then do an IFFT with FFTW. This will be a lot more efficient than doing an IDFT as above. Note that you may get some artefacts in the time domain when you do this kind of thing - you're effectively multiplying by a step function in the frequency domain, which is equivalent to convolution with a sinc function in the time domain. To reduce the resulting "ringing" in the time domain you should use a window function to smooth out the transition between non-zero and zero coeffs. A: If your numCoefs is anywhere near or greater than log(length), then an IFFT, which is O(n*log(n)) in computational complexity, will most likely be faster, as well as pre-optimized for you. Just zero all the bins except for the coefficients you want to keep, and make sure to also keep their negative frequency complex conjugates as well if you want a real result. If your numCoefs is small relative to log(length), then other optimizations you could try include using sinf() and cosf() if you don't really need more than 6 digits of precision, and pre-calculating omega*i outside the inner loop (although your compiler should do be doing that for you unless you have the optimization setting low or off).
{ "language": "en", "url": "https://stackoverflow.com/questions/7593245", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CakePhp form validation when having two models on two different database I've a not common problem to do a form validation. First let me explain a part of the problem: I'm doing a cakePhp website, this website will be used to sell product to customer. To do this, we have two database: one database(database A) relative to products, customer references, bills(provided by the ERP), and one database (database B)relative to information that the website has to store only for the website(passwords of users, cart content, comments on a products, ...). To register ONE user on our website, I've to: Create one "address" in the database A Create one "customer" in the database A Create one "user" in the database B. This has to be only one action. I'm on the user controller, so no problem to validate every fields of the "user", but how to make this form validate all constraints I have in my customer and address models? The problem is that because user and customer are not in the same database, I can't(in fact I'm not sure of that, but it seems to be logic, because of automatic Left join) declare the $belongsTo and $hasOne relationship between user and customer. So how could I make the check of those constraints? Thank you very much A: You can validate fields manually. $this->Customer->set( $this->data ); $this->Address->set( $this->data ); if( $this->User->validates() && $this->Customer->validates() && $this->Address->validates() ) { // save data }
{ "language": "en", "url": "https://stackoverflow.com/questions/7593248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: iPhone : How to fetch data from web service where web service uses "POST" method for JSON? I want to fetch data from web service using JSON in my app. Web service is developed in C# and it uses POST method to pass data. I found one example but its useful only for GET method? So How can I fetch JSON data where web service uses POST method? And I also want to send data to web service. How can I do that ? A: I'm sending POST request in following way (sending xml with some parameters). NSString *message = [[NSString alloc] initWithFormat:@"<?xml version=\"1.0\" ?>\n<parameters></parameters>"]; NSURL *url = [NSURL URLWithString:@"https://www.site.com"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; NSString *msgLength = [NSString stringWithFormat:@"%d",[message length]]; [request addValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; [request addValue:msgLength forHTTPHeaderField:@"Content-Length"]; [request setHTTPMethod:@"POST"]; [request setHTTPBody:[message dataUsingEncoding:NSUTF8StringEncoding]]; [message release]; self.connection = [NSURLConnection connectionWithRequest:request delegate:self]; To collect data you should implement method: - (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data where you should save received data. In method: - (void)connectionDidFinishLoading:(NSURLConnection *)conn you can parse that data with some JSON-parser. Hope, that will help you. If you'll have questions about this code ask them in comments.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java config equivalent of echcache.xml Is there a sample Java Config for a standard ehcache XML config file (ehcache.xml) . I am using Spring 3.1. A: Take a look at the provided documentation, there are some good code snippets, too: http://www.ehcache.org/documentation/user-guide/configuration A: Specifically: "Adding and Removing Caches Programmatically": http://www.ehcache.org/documentation/2.5/code-samples#adding-and-removing-caches-programmatically
{ "language": "en", "url": "https://stackoverflow.com/questions/7593259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a way to format code in TextWrangler? I'm using TextWrangler on Mac OS X to do some web development. Is there a way to auto format code? A: Yes, there is a possibility but not a simple one. Using Text Filters, if you can find a filter your choice you put it into Library/Application Support/TextWrangler/Text Filters and reach it from Text/Apply Text Filter menu. This is how you do it for XML: http://magp.ie/2010/02/15/format-xml-with-textwrangler/ and for PHP: http://wizguild.com/textwrangler_phptidy_filter/ A: Create a new file -> Tidy XML.sh Copy and Paste this lines below: #!/bin/sh XMLLINT_INDENT=$'\t' xmllint --format --encode utf-8 - Save on Desktop Open Finder and GO to folder -> ~/Library/Application Support/TextWrangler/Text Filters Move your Tidy XML.sh from desktop to Text Filters. Open TextWrangler and beautifier your xml file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Spring ROO GWT Select by reference I created a GWT Spring ROO project with the following entities: Facture and ItemFacture. ItemFacture contains a reference to a Facture. @RooJavaBean @RooToString public class ItemFacture { @ManyToOne private Facture facture; ... This is the code for Facture : @RooJavaBean @RooToString @RooEntity public class Facture { private String nom; private String type; } and everything went fine until I wanted to create a custom finder that selects all the ItemFactures that contains a specific Facture : @SuppressWarnings("unchecked") public static List<ItemFacture> findByFacture(Facture facture) { Query q = entityManager().createQuery("SELECT o FROM ItemFacture AS o WHERE o.facture = :facture"); q.setParameter("facture", facture); return q.getResultList(); } When I try to execute this finder, it gives me this error: Server Error: Field "facture" does not exist in com.test.ItemFacture or is not persistent; nested exception is javax.persistence.PersistenceException: Field "facture" does not exist in com.test.ItemFacture or is not persistent I created a few custom finders and every one of them worked just fine except this one. I tried adding @Persistent to the field and @PersistenceCapable(identityType = IdentityType.APPLICATION) to Facture but it still doesn't work. Anyone know what is the problem? A: i guess the reason why this doesn't work is that the ItemFacture class is not an @Entity so JPA has no idea this field exists. with annotating the ItemFacture class with @RooEntity roo generates a ItemFactures_Roo_Entity.aj (STS hides these files in the package explorer by default) which wires the @Entity annotation on your ItemFacture-class together with some other stuff making it an ActiveRecord (http://martinfowler.com/eaaCatalog/activeRecord.html) A: In AppEngine, references are made with the ID of the referenced object. So event if ItemFacture contain and attribute facture, it's actually stored as factureId. So the method to write is this one: @SuppressWarnings("unchecked") public static List<ItemFacture> findByFacture(Facture facture) { Query q = entityManager().createQuery("SELECT o FROM ItemFacture AS o WHERE o.factureId = :facture"); q.setParameter("facture", facture.getId()); return q.getResultList(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7593267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: RabbitMQ: Verify version of rabbitmq How can I verify which version of rabbitmq is running on a server? Is there a command to verify that rabbitmq is running? A: You can simply execute from the command line: sudo rabbitmqctl status | grep rabbit A: On debian systems, you can just run: dpkg-query --showformat='${Version}' --show rabbitmq-server A: If rabbitimq can not start I found the only way to determine version is via installer system. Eample Debian/Ubuntu: dpkg -s rabbitmq-server | grep Version A: sudo rabbitmqctl status and look for line that looks like that: {rabbit,"RabbitMQ","2.6.1"}, A: To get RabbitMQ version using the .NET/C# RabbitMQ Client Library: using (var connection = connectionFactory.CreateConnection()) { if (connection.ServerProperties.ContainsKey("version")) Console.WriteLine("Version={0}", Encoding.UTF8.GetString((byte[])connection.ServerProperties["version"])); } Output: Version=3.6.3 A: If you have no access to rabbitmqctl or rabbitmq-server is not running, on linux do : ls /usr/lib/rabbitmq/lib/ I got : rabbitmq_server-3.5.6 A: As Marek said on a local server, or, on a remote server (using amqplib): from amqplib import client_0_8 as amqp import sys conn = amqp.Connection(host=sys.argv[1], userid="guest", password="guest", virtual_host="/", insist=False) for k, v in conn.server_properties.items(): print k, v Save as checkVersion.py and run with python checkVersion.py dev.rabbitmq.com: % python checkVersion.py dev.rabbitmq.com information Licensed under the MPL. See http://www.rabbitmq.com/ product RabbitMQ copyright Copyright (C) 2007-2011 VMware, Inc. capabilities {} platform Erlang/OTP version 2.6.0 A: Since I was looking to do this in C# on a Windows machine and all the current answers are for *nix, I'll post the code that I ended up using: public string GetRabbitMqVersion() { string prefix = "rabbitmq_server-"; var dirs = System.IO.Directory.EnumerateDirectories(@"C:\Program Files (x86)\RabbitMQ Server", string.Format("{0}*",prefix)); foreach (var dir in dirs) { //Just grab the text after 'rabbitmq_server-' and return the first item found var i = dir.LastIndexOf(prefix); return dir.Substring(i+16); } return "Unknown"; } A: In the likely event you're using the "management" (web) plug-in, the RabbitMQ version appears in the upper-right corner of every web page, along with the version of the Erlang run-time. A: I use following command to trim output down to version, rabbitmqctl status | grep "{rabbit,\"RabbitMQ\"" Output: {rabbit,"RabbitMQ","3.7.3"}, A: On Centos you can use yum list rabbitmq-server. A: Login to management ui and in top right you can find the version. Also use the following command to find the version # sudo bash # rabbitmqctl status | grep rabbit
{ "language": "en", "url": "https://stackoverflow.com/questions/7593269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "171" }
Q: Can't break a long string/text, it exceeds the width of html div <div id="id_div_comments"><p>body4qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq</p></div><br/><br/> </div> The css file: div#id_div_comments { width: 400px; } But the string/texts exceeds the division width. What can i do to break the texts when it reaches the width of the division ? A: Try this code: #id_div_comments p{ white-space:normal; } A: wirte this in your css word-wrap:break-word; css: #id_div_comments p{ word-wrap:break-word; } A: The accepted answer doesn't work for me After seaching around, the following css actually works #id_div_comments p{ overflow: hidden; } Just trust me A: Old question but no correct answer, for long text this should work #id_div_comments p{ word-break: break-all; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7593275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Linking problem when derived class calls a template function in base class I have a class Base in base.h, which has a template function class Base { template <typename T> void test(T a); } this template is supposed to read in int or double type, and I have class Derived, which is derived from class Base I tried to call function test in class Derived, but I have the linker error. In the end, I realised that if in base.cpp, I add void test(int a); void test(double a); there will be no compiler error. This solution seems awkward, is there a better solution? Thank you A: C++ templates must be defined (given a complete function body) in the same translation unit (.CPP file plus all included header files) where they are used. In your header file, all you have done is declared (given the name and signature of) the function. The result is that when you include base.h, all the compiler sees is: class Base { template <typename T> void test(T a); } This declares but does not define the function. To define it, you must include a function body: class Base { template <typename T> void test(T a) { // do something cool with a here } } The reason why this is required is that the C++ compiler generates code for templates on an "as-needed" basis. For example, if you call: Base obj; obj.test< int >( 1 ); obj.test< char >( 'c' ); The compiler will generate two sets of machine code based on the Base::test template, one for an int and one for a char. The limitation here is that the definition of the Base::test template must be in the same translation unit (.CPP file), or else the compiler will not know how to build the machine code for each version of the Base::test function. The compiler only operates on one translation unit at a time, so it has no idea whether or not you've defined Base::test< T > in some other CPP file. It can only work with what it has at hand. This is quite different from the way generics work in C#, Java, and similar languages. Personally I like to think of templates as a text macro that gets expanded by the compiler as needed. That forces me to keep in mind that the complete body of the template function needs to be included in any CPP file where it is used. A: You must fully define the template function test before it can be used. The easiest way to do that is just to write your function body in the header in base.h: class Base { template <typename T> void test(T a) { ... function body here } } A: if you declare template function in base class which means it take the template argument at compile time but if u try to access through derived class which is runtime implementation so template request at compile time which ur providing at runtime is not possible ,and main thing c++ does not support this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can synchronization be treated as an aspect in AOP I understand that in AOP any cross cutting concerns such as Logging, transaction etc can be treated as an aspect and most of the AOP frameworks very well support these kind of cross-cutting concerns. My question is, * *Can Synchronization be treated as a crosscutting concern ? *If yes, are there any existing libraries (including AspectJ and Spring AOP) which support this functionality out of box ? I searched but could not find many examples. I came across some restricted research papers (1,2) though. A: Just a theoretical "answer". :) As I understand AOP, you add independent behaviours/"advices" to some "pointcuts"/"joint points". But synchronization is intended to be used tightly related with a code it manages. I guess the way to use synchronization is if it will be attached as advice and will provide itself as a "joint point" for which other "aspects" will define some "advices". Or you might get some kind of synchronization inside your "advices" while trying to call some "joint points". A: In theory it's possible to have an AOP framework which adds synchronization to a set of methods/classes. It's not even hard to implement. But it is usually not what you want. Too much synchronization is just as bad as too few synchronization, because you either run into deadlocks or you sequentialize your threading so much, that you are not able to use multiple cores effectively. I am afraid there is no no brainer shortcut to multithreaded programming. A: Yes, synchronisation can be treated as an aspect. Isn't the idea behind AOP to handle cross cutting concerns? Then, regarding synchronisation as a cross cutting concern can be handled via AOP without defining and using external libraries. Consider the following example about read-write locking. Whenever an object is subject to be read/write, then you can capture the method and provide sufficient functionality for concurrency control. public abstract aspect ReadWriteLockSynchronizationAspect perthis(readOperations() || writeOperations()) { public abstract pointcut readOperations(); public abstract pointcut writeOperations(); private ReadWriteLock _lock = new SomeReadWriteLock(); before() : readOperations() { _lock.readLock().acquire(); } after() : readOperations() { _lock.readLock().release(); } before() : writeOperations() { _lock.writeLock().acquire(); } after() : writeOperations() { _lock.writeLock().release(); } } perthis creates a new aspect for each read/write operation. Otherwise, only one aspect will be created and it works like a singleton object. For further information check AspectJ in Action.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Objective C: Accessing properties of an IBOutlet If I have a UIImageView in an .xib file called MainViewController (which, of course, is linked with the respective MainViewController interface (.h) and implementation (.m) files), how can I change the image of the UIImageView from an entirely separate class? I want to process all of the image initialisation from a separate class (there are a lot of images), but can't seem to figure out how to do it outside of MainViewController.m. Any tips? Thanks. A: Declare these ImageView as @property and access them in other classes. @property (nonatomic, retain) IBOutlet UIImageView *image1; In the implementation class @synthesize image1; Now you can use setter and getter from other classes to access these objects to play around.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: A simple MySQL query help Been stuck with this fairly simple MySQL query for a day now! Can't believe how quickly I've forgotten the basics. I have 3 tables - user, post and favourite_post. The post table has a user_id that is a FK to user table. The favourite_post table has user_id REFERENCES user(id) post_id REFERENCES post(id) timestamp When a user favourites a post, his user_id, the post_id and timestamp are inserted into the favourite_post table. I use the following query to retrieve the 15 more recent posts SELECT post.id, post.text, post.timestamp, post.user_id, user.username FROM post INNER JOIN user ON post.user_id = user.id ORDER BY post.id DESC LIMIT 15; What I need to do along with that is check if each post has been favourited by the current user(say user_id = 1) by joining with the favourite_post table. A: SELECT p.id, p.text, p.timestamp, p.user_id, u.username, IF(ISNULL(fp.post_id), 'No', 'Yes') has_favourite FROM post p INNER JOIN user u ON p.user_id = u.id LEFT JOIN favourite_post fp ON p.id = fp.post_id AND u.id = fp.user_id ORDER BY p.id DESC LIMIT 15; A: Try this: SELECT p.id, p.text, fp.timestamp, p.user_id, u.username FROM post p INNER JOIN user u ON p.user_id = u.id LEFT JOIN favourite_post fp ON fp.user_id = p.user_id AND fp.post_id = p.id WHERE p.user_id = your_user_id ORDER BY p.id DESC LIMIT 15;
{ "language": "en", "url": "https://stackoverflow.com/questions/7593284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to bind hash table to gridview hi i have a hash table with following set of values int ID 1 string Name ram list date 2/3/2011 5/3/2011 Code: <asp:TemplateField HeaderText="ID"> <ItemStyle Width="200px"> </ItemStyle> <ItemTemplate> <asp:Label ID="lblID" runat="server" Text='<%# Bind("ID") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> its throws error in bind statement A: You need to add a Repeator or GridView or Datalist control to bind the list (dates) inside the ItemTemplate of GridView. A: Hash tables have keys and values so you can't bind your grid using the key names (as you are doing) because the key names are not properties of the hash table. If anything, you could have columns bound to Key and Value; however, your data has a List of things (dates) and the Gridview won't know how to bind this list to one column. As AVD suggested, you need to have an item template and inside it, have another gridview if you want to bind a data structure like this to a grid view.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hibernate criteria with projection doesn't return the entity on which criteria is implemented I'm using spring-hibernate and using HibernateDAOSupport class. I have two tables mapped to each other in one-to-many fashion. I'm implementing the below criteria DetachedCriteria criteria = getCriteria( "a" ) .setProjection( Projections.projectionList() .add( Projections.groupProperty("a.id" ) ) .add( Projections.count( "a.id" ), "count" ) ) .createCriteria( "huApps", "hu") .addOrder( Order.desc( "count" ) ) ; this works well and create the below query select this_.id as y0_, count(this_.id) as y1_ from apps this_ inner join huapps huapp1_ on this_.id=huapp1_.appid group by this_.id order by y1_ desc In result, it returns a list of object[]. But I want that it should return List<App>(App is the class on which I implemented/created the criteria). I want that it would create the query select this_ from apps this_ inner join huapps huapp1_ on this_.id=huapp1_.appid group by this_.id order by y1_ desc Please help me in writing the correct criteria. I also tried with sqlProjection() but even that didn't work. Is there any way I can achieve this? A: You try to add orger for new critheria that is result of function detachedCriteria.createCriteria("huApps", "hu"). This function return the new criteria for class of huApp property. Try to replace you criteria like this: DetachedCriteria detachedCriteria = DetachedCriteria.forClass(A.class); detachedCriteria.setProjection(Projections.projectionList() .add(Projections.groupProperty("id")) .add(Projections.count("id"), "count") ); detachedCriteria.createCriteria("huApps", "hu"); detachedCriteria.addOrder(Order.desc("count")); List<A> list = detachedCriteria.getExecutableCriteria(getSession()).list(); It works well for me. A: Try calling DetachedCriteria criteria = getCriteria( "a" ) .setProjection( Projections.projectionList() .add( Projections.groupProperty("a.id" ), "id" ) .add( Projections.count( "a.id" ), "count" ) ) .createCriteria( "huApps", "hu") .addOrder( Order.desc( "count" ) ) .setResultTransformer(Transformers.aliasToBean(App.class)) This should map the properties alias to the fields of the bean that you specify. App will need setters and getters on the appropriate fields
{ "language": "en", "url": "https://stackoverflow.com/questions/7593302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Seeking a more elegant method to populate a WPF DataGrid with dynamic columns (one column for each object's property) I am trying to setup a WPF datagrid. The standard datagrid is setup to accept a list of objects which are displayed on different rows, with a column for each property. I actually need to do the inverse; a row for each property, and a column for each object in the list. Therefore I started with the solution proposed by blindmeis here in order to handle a dynamic number of columns and it works well so far. I have a class DataGridVM to which I can pass a list of objects. Each of the objects has its own View Model which derives from a class ParentalBaseVM. Each property of that object has its own View Model which derives from a class ElementVM. Each ParentalBaseVM can return list of ElementVM for each of its object’s properties through overriding the virtual method PropertyLists E.g. within an example of a class dervived from ParentalBaseVM I have: public override Dictionary<string, List<ElementVM>> PropertyLists { get { Dictionary<string, List<ElementVM>> iPropertyLists = new Dictionary<string, List<ElementVM>>(); List<ElementVM> BasicProperties = new List<ElementVM>(); BasicProperties.Add(iNBViewModel); BasicProperties.Add(iIDViewModel); iPropertyLists.Add("Basic", BasicProperties); List<ElementVM> AdvancedProperties = new List<ElementVM>(); AdvancedProperties.Add(iNBViewModel); AdvancedProperties.Add(iIDViewModel); AdvancedProperties.Add(iXSAreaViewModel); iPropertyLists.Add("Advanced", AdvancedProperties); return iPropertyLists; } set { } } As you can see, I can return a different set of properties by passing either “Basic” or “Advanced” as a string. The DataGridVM code is below. I pass to this the list of objects (columnList) and the string which represents the (“Basic” or “Advanced” in the example above) class DataGridVM { private List<List<ElementVM>> iDataList; public DataGridVM(List<ParentalBaseVM> columnList, string rowListKey) { iDataList = new List<List<ElementVM>>(); for (int i = 0; i < columnList[0].PropertyLists[rowListKey].Count; i++) { List<ElementVM> newRowList = new List<ElementVM>(); for (int j = 0; j < columnList.Count; j++) { newRowList.Add(columnList[j].PropertyLists[rowListKey][i]); } iDataList.Add(newRowList); } } public List<List<ElementVM>> DataList { get { return iDataList; } set { } } } Finally, the datagrid is populated using: testControlDataGrid.testDataGrid.ItemsSource = testDataGridVM.DataList; And then the columns are generated dynamically (the code within CreateDataTemplate sets up the bindings) for (int i = 0; i < testDataGridVM.DataList[0].Count; i++) { testControlDataGrid.testDataGrid.Columns.Add(new DataGridTemplateColumn() { Header = "Col" + i, CellTemplate = CreateDataTemplate(TheTextBlock.GetType(),i) }); } This all works fine, but it feels very messy. Passing string values like “Basic” and accessing dictionaries feels wrong. Perhaps there is an elegant solution where I have classes deriving from DataGridVM such as DataGridVMBasicProperties which accesses the “Basic” properties of the object, but I’m not sure if this would result in repeating lots and lots of code. Also, I’m not sure cluttering up the ParentalBaseVM class with a method which returns the list of properties is great either. I was thinking of perhaps moving this to a new base class PropertiesListGenerator which can simply have a ParentalBaseVM passed to it, and returns a list of ElementVM. A derivation could be BasicPropertiesListGenerator, and a further derivation of this could be AdvancedPropertiesListGenerator. However, if not all ParentalBaseVM contain an "advanced" list and only the "basic" list then this may cause problems. My main aim here is to avoid repeating lots of code. I have never used Delegates or Interfaces enough to truly understand them, so my coding skills aren’t really firing on all cylinders. Maybe they can help provide an elegant solution? Any help is appreciated. I’m new to this and programming isn’t my full time job (evidently). If you see room for improvement in layout, readability, convention following, please feel free to suggest, I certainly will not be offended.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Multiple markers at this line - Line breakpoint:HelloListView [line: 34] - onItemClick(AdapterView>, View, int, long) for the following code can any one help me how to resolve this. Multiple markers at this line - Line breakpoint:HelloListView [line: 34] - onItemClick(AdapterView, View, int, long) for the following code. this is the error for the following code. Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
{ "language": "en", "url": "https://stackoverflow.com/questions/7593307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android weird lib.c crash I'm writing an Android app. I totally have no idea why it happenes often. Could someone tell me what reason might cause it happened? Thanks! 09-29 13:58:00.540: INFO/DEBUG(4658): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** 09-29 13:58:00.540: INFO/DEBUG(4658): Build fingerprint: 'MOTO/wifi_hubble/wifi_hubble:3.1/H.6.4-20/1310119769:user/ota-rel-keys,release-keys' 09-29 13:58:00.540: INFO/DEBUG(4658): pid: 23390, tid: 23390 >>> com.aaa.bbb <<< 09-29 13:58:00.540: INFO/DEBUG(4658): signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr deadbaad 09-29 13:58:00.540: INFO/DEBUG(4658): r0 deadbaad r1 00000001 r2 a0000000 r3 00000000 09-29 13:58:00.540: INFO/DEBUG(4658): r4 00000000 r5 00000027 r6 00000028 r7 00000005 09-29 13:58:00.540: INFO/DEBUG(4658): r8 00000002 r9 001aa540 10 00000005 fp 0000005e 09-29 13:58:00.540: INFO/DEBUG(4658): ip ffffffff sp bed42ee8 lr afe164ad pc afe12c1c cpsr 68000030 09-29 13:58:00.540: INFO/DEBUG(4658): d0 000000a043208000 d1 0000000043208000 09-29 13:58:00.540: INFO/DEBUG(4658): d2 0000000000000000 d3 3ff0000000000000 09-29 13:58:00.540: INFO/DEBUG(4658): d4 0000000000000000 d5 4082780000000000 09-29 13:58:00.540: INFO/DEBUG(4658): d6 c413c000c30c0000 d7 0000000000000000 09-29 13:58:00.540: INFO/DEBUG(4658): d8 0000000043fa8000 d9 3f80000000000000 09-29 13:58:00.540: INFO/DEBUG(4658): d10 4004cccd430e0000 d11 0000000040951f28 09-29 13:58:00.540: INFO/DEBUG(4658): d12 00000000bfd55580 d13 0000000000000000 09-29 13:58:00.540: INFO/DEBUG(4658): d14 0000000000000000 d15 0000000000000000 09-29 13:58:00.540: INFO/DEBUG(4658): scr 8000001b 09-29 13:58:00.640: INFO/DEBUG(4658): #00 pc 00015c1c /system/lib/libc.so 09-29 13:58:00.640: INFO/DEBUG(4658): #01 pc 00013efe /system/lib/libc.so (dlfree) 09-29 13:58:00.640: INFO/DEBUG(4658): #02 pc 0001445c /system/lib/libc.so (free) 09-29 13:58:00.640: INFO/DEBUG(4658): #03 pc 0002239e /system/lib/libsqlite.so 09-29 13:58:00.640: INFO/DEBUG(4658): #04 pc 0000483c /system/lib/libsqlite.so (sqlite3_free) 09-29 13:58:00.640: INFO/DEBUG(4658): #05 pc 00005b28 /system/lib/libsqlite.so 09-29 13:58:00.640: INFO/DEBUG(4658): #06 pc 00005b60 /system/lib/libsqlite.so 09-29 13:58:00.640: INFO/DEBUG(4658): #07 pc 00005d20 /system/lib/libsqlite.so 09-29 13:58:00.640: INFO/DEBUG(4658): #08 pc 00005e76 /system/lib/libsqlite.so 09-29 13:58:00.640: INFO/DEBUG(4658): #09 pc 0000a7c2 /system/lib/libsqlite.so 09-29 13:58:00.640: INFO/DEBUG(4658): #10 pc 0000a7e0 /system/lib/libsqlite.so 09-29 13:58:00.640: INFO/DEBUG(4658): #11 pc 0001cd96 /system/lib/libsqlite.so 09-29 13:58:00.640: INFO/DEBUG(4658): #12 pc 0001d8fa /system/lib/libsqlite.so 09-29 13:58:00.640: INFO/DEBUG(4658): #13 pc 0001da3c /system/lib/libsqlite.so 09-29 13:58:00.640: INFO/DEBUG(4658): #14 pc 0001e31c /system/lib/libsqlite.so 09-29 13:58:00.640: INFO/DEBUG(4658): #15 pc 0003b68e /system/lib/libsqlite.so 09-29 13:58:00.640: INFO/DEBUG(4658): libc base address: afdfd000 09-29 13:58:00.640: INFO/DEBUG(4658): code around pc: 09-29 13:58:00.640: INFO/DEBUG(4658): afe12bfc 4623b15c 2c006824 e026d1fb b12368db 09-29 13:58:00.640: INFO/DEBUG(4658): afe12c0c 21014a17 6011447a 48124798 24002527 09-29 13:58:00.640: INFO/DEBUG(4658): afe12c1c f7f57005 2106eb8a ec18f7f6 460aa901 09-29 13:58:00.640: INFO/DEBUG(4658): afe12c2c f04f2006 94015380 94029303 efe2f7f5 09-29 13:58:00.640: INFO/DEBUG(4658): afe12c3c 4622a905 f7f52002 f7f5efec 2106eb76 09-29 13:58:00.640: INFO/DEBUG(4658): code around lr: 09-29 13:58:00.640: INFO/DEBUG(4658): afe1648c 41f0e92d 46804c0c 447c2600 68a56824 09-29 13:58:00.640: INFO/DEBUG(4658): afe1649c e0076867 300cf9b5 dd022b00 47c04628 09-29 13:58:00.640: INFO/DEBUG(4658): afe164ac 35544306 37fff117 6824d5f4 d1ee2c00 09-29 13:58:00.640: INFO/DEBUG(4658): afe164bc e8bd4630 bf0081f0 0002802e 41f0e92d 09-29 13:58:00.640: INFO/DEBUG(4658): afe164cc fb01b086 9004f602 461f4815 4615460c 09-29 13:58:00.640: INFO/DEBUG(4658): stack: 09-29 13:58:00.640: INFO/DEBUG(4658): bed42ea8 00af9de0 09-29 13:58:00.640: INFO/DEBUG(4658): bed42eac 008aa8f8 09-29 13:58:00.640: INFO/DEBUG(4658): bed42eb0 00000000 09-29 13:58:00.640: INFO/DEBUG(4658): bed42eb4 00000007 09-29 13:58:00.640: INFO/DEBUG(4658): bed42eb8 afe3e700 09-29 13:58:00.640: INFO/DEBUG(4658): bed42ebc afe3e690 09-29 13:58:00.640: INFO/DEBUG(4658): bed42ec0 00000000 09-29 13:58:00.640: INFO/DEBUG(4658): bed42ec4 afe164ad /system/lib/libc.so 09-29 13:58:00.640: INFO/DEBUG(4658): bed42ec8 00000000 09-29 13:58:00.640: INFO/DEBUG(4658): bed42ecc bed42efc 09-29 13:58:00.640: INFO/DEBUG(4658): bed42ed0 00000028 09-29 13:58:00.640: INFO/DEBUG(4658): bed42ed4 00000005 09-29 13:58:00.640: INFO/DEBUG(4658): bed42ed8 00000002 09-29 13:58:00.640: INFO/DEBUG(4658): bed42edc afe15619 /system/lib/libc.so 09-29 13:58:00.640: INFO/DEBUG(4658): bed42ee0 df002777 09-29 13:58:00.640: INFO/DEBUG(4658): bed42ee4 e3a070ad 09-29 13:58:00.640: INFO/DEBUG(4658): #00 bed42ee8 00000002 09-29 13:58:00.640: INFO/DEBUG(4658): bed42eec 00000001 09-29 13:58:00.640: INFO/DEBUG(4658): bed42ef0 00afe158 09-29 13:58:00.640: INFO/DEBUG(4658): bed42ef4 00afe5cc 09-29 13:58:00.640: INFO/DEBUG(4658): bed42ef8 00afe150 09-29 13:58:00.640: INFO/DEBUG(4658): bed42efc fffffbdf 09-29 13:58:00.640: INFO/DEBUG(4658): bed42f00 00000002 09-29 13:58:00.640: INFO/DEBUG(4658): bed42f04 afe434a0 09-29 13:58:00.640: INFO/DEBUG(4658): bed42f08 00000888 09-29 13:58:00.640: INFO/DEBUG(4658): bed42f0c afe10f03 /system/lib/libc.so 09-29 13:58:00.640: INFO/DEBUG(4658): #01 bed42f10 00afe158 09-29 13:58:00.640: INFO/DEBUG(4658): bed42f14 00afe5cc 09-29 13:58:00.640: INFO/DEBUG(4658): bed42f18 00000002 09-29 13:58:00.640: INFO/DEBUG(4658): bed42f1c 005e6c90 09-29 13:58:00.640: INFO/DEBUG(4658): bed42f20 00000002 09-29 13:58:00.640: INFO/DEBUG(4658): bed42f24 afe1145f /system/lib/libc.so 09-29 13:58:04.160: INFO/DEBUG(4658): debuggerd committing suicide to free the zombie! 09-29 13:58:04.170: INFO/BootReceiver(148): Copying /data/tombstones/tombstone_05 to DropBox (SYSTEM_TOMBSTONE) 09-29 13:58:04.180: INFO/DEBUG(25207): debuggerd: Jul 8 2011 03:35:12 EDIT: Add another log. 10-04 10:21:31.210: INFO/DEBUG(2375): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** 10-04 10:21:31.210: INFO/DEBUG(2375): Build fingerprint: 'asus/TW_epad/TF101:3.2.1/HTK75/TW_epad-8.6.5.13-20110925:user/release-keys' 10-04 10:21:31.210: INFO/DEBUG(2375): pid: 4044, tid: 4045 >>> com.aaa.bbb <<< 10-04 10:21:31.210: INFO/DEBUG(2375): signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr deadbaad 10-04 10:21:31.210: INFO/DEBUG(2375): r0 deadbaad r1 00000001 r2 a0000000 r3 00000000 10-04 10:21:31.210: INFO/DEBUG(2375): r4 00000000 r5 00000027 r6 002f3540 r7 0000b000 10-04 10:21:31.210: INFO/DEBUG(2375): r8 100ffad0 r9 4002bfa0 10 4002bf8c fp fffffe90 10-04 10:21:31.210: INFO/DEBUG(2375): ip ffffffff sp 100ffa78 lr aff194ad pc aff15c1c cpsr 60000030 10-04 10:21:31.210: INFO/DEBUG(2375): d0 42c8000042a982a6 d1 0000005f01997918 10-04 10:21:31.210: INFO/DEBUG(2375): d2 4e19740842be9580 d3 42c8000000670ff0 10-04 10:21:31.210: INFO/DEBUG(2375): d4 000001fd006235c8 d5 3fe999999999999a 10-04 10:21:31.210: INFO/DEBUG(2375): d6 01e31fe000000000 d7 000000544f1ff34d 10-04 10:21:31.210: INFO/DEBUG(2375): d8 0000000000000000 d9 0000000000000000 10-04 10:21:31.210: INFO/DEBUG(2375): d10 0000000000000000 d11 0000000000000000 10-04 10:21:31.210: INFO/DEBUG(2375): d12 0000000000000000 d13 0000000000000000 10-04 10:21:31.210: INFO/DEBUG(2375): d14 0000000000000000 d15 0000000000000000 10-04 10:21:31.210: INFO/DEBUG(2375): scr 80000012 10-04 10:21:31.330: INFO/DEBUG(2375): #00 pc 00015c1c /system/lib/libc.so 10-04 10:21:31.330: INFO/DEBUG(2375): #01 pc 00013efe /system/lib/libc.so (dlfree) 10-04 10:21:31.330: INFO/DEBUG(2375): #02 pc 0001445c /system/lib/libc.so (free) 10-04 10:21:31.330: INFO/DEBUG(2375): #03 pc 000009bc /system/lib/libstdc++.so (_ZdaPvRKSt9nothrow_t) 10-04 10:21:31.330: INFO/DEBUG(2375): #04 pc 0005cccc /system/lib/libandroid_runtime.so 10-04 10:21:31.330: INFO/DEBUG(2375): libc base address: aff00000 10-04 10:21:31.330: INFO/DEBUG(2375): code around pc: 10-04 10:21:31.330: INFO/DEBUG(2375): aff15bfc 4623b15c 2c006824 e026d1fb b12368db 10-04 10:21:31.330: INFO/DEBUG(2375): aff15c0c 21014a17 6011447a 48124798 24002527 10-04 10:21:31.330: INFO/DEBUG(2375): aff15c1c f7f57005 2106eb8a ec18f7f6 460aa901 10-04 10:21:31.330: INFO/DEBUG(2375): aff15c2c f04f2006 94015380 94029303 efe2f7f5 10-04 10:21:31.330: INFO/DEBUG(2375): aff15c3c 4622a905 f7f52002 f7f5efec 2106eb76 10-04 10:21:31.330: INFO/DEBUG(2375): code around lr: 10-04 10:21:31.330: INFO/DEBUG(2375): aff1948c 41f0e92d 46804c0c 447c2600 68a56824 10-04 10:21:31.330: INFO/DEBUG(2375): aff1949c e0076867 300cf9b5 dd022b00 47c04628 10-04 10:21:31.330: INFO/DEBUG(2375): aff194ac 35544306 37fff117 6824d5f4 d1ee2c00 10-04 10:21:31.330: INFO/DEBUG(2375): aff194bc e8bd4630 bf0081f0 0002802e 41f0e92d 10-04 10:21:31.330: INFO/DEBUG(2375): aff194cc fb01b086 9004f602 461f4815 4615460c 10-04 10:21:31.330: INFO/DEBUG(2375): stack: 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffa38 0023aa60 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffa3c 0000b000 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffa40 100ffad0 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffa44 4002bf80 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffa48 aff41700 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffa4c aff41690 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffa50 00000000 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffa54 aff194ad /system/lib/libc.so 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffa58 00000000 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffa5c 100ffa8c 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffa60 002f3540 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffa64 0000b000 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffa68 100ffad0 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffa6c aff18619 /system/lib/libc.so 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffa70 df002777 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffa74 e3a070ad 10-04 10:21:31.330: INFO/DEBUG(2375): #00 100ffa78 8bfffbfc 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffa7c 00000001 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffa80 002f3578 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffa84 00000000 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffa88 002f3578 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffa8c fffffbdf 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffa90 100ffad0 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffa94 00000006 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffa98 00000080 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffa9c aff13f03 /system/lib/libc.so 10-04 10:21:31.330: INFO/DEBUG(2375): #01 100ffaa0 002f3578 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffaa4 00000000 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffaa8 100ffb78 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffaac 4002bfa8 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffab0 100ffad0 10-04 10:21:31.330: INFO/DEBUG(2375): 100ffab4 aff1445f /system/lib/libc.so 10-04 10:21:34.920: INFO/BootReceiver(140): Copying /data/tombstones/tombstone_08 to DropBox (SYSTEM_TOMBSTONE) 10-04 10:21:34.930: INFO/DEBUG(2375): debuggerd committing suicide to free the zombie! A: The system is crashing trying to dereference the address 'deadbaad'. That looks like a debugging hint (someone is initializing a pointer to deadbaad to make crashes a bit easier to identify). Looks like you're not the first to hit this: http://groups.google.com/group/android-ndk/browse_thread/thread/8d083a0ccebe0faa Looks like 'deadbaad' means the Dalvik heap got corrupted. So some JNI code or C library is messing with the heap. Do you have any Native code in your app? Blame it. Update #1 No native code to blame.... Are there any interesting log lines before the crash happens? From looking at the android source the 0xdeadbaad crash is used to implement 'abort()'. And both backtraces are in the C 'free' routine (some simple sanity checks on the memory range are done there). Note 'free' is just detecting the memory corruption and isn't likely the source of the corruption. Does your app do a lot of native memory allocations indirectly? E.g., through OpenGL textures or loading of audio? Are you doing any SQL directly? Can you add some details to the question about what's going on in your app when this happens? (How long is the app running? Anything happening on the UI or the network? etc)
{ "language": "en", "url": "https://stackoverflow.com/questions/7593308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: VCF Vcard import c# iam trying to write a class which imports *.vcf files (Vcard), because i didn´t found a adequate .net class to solve that job. So i decided to treat the *.vcf file like a *.txt file. I just import the whole file, line by line, with a StreamReader. Finally i save the line into a List object. The Code: private List<string> vcardList = new List<String>(); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { using (StreamReader reader = new StreamReader(@"H:\VS.vcf")) { string line; while ((line = reader.ReadLine()) != null) { vcardList.Add(line); } } } After importing the text i needed to edit the lines, because i need to remove all the unnecessary symbols. I tried to use the RedEx claa: private void button1_Click(object sender, EventArgs e) { vcardList[0] = Regex.Replace(vcardList[0], "BEGIN:", string.Empty); } that works very well, for the first line! but the *.vcf file is very complex and allways different. So my question is: Is there a better way to solve that problem? This is the *.vcf file: BEGIN:VCARD VERSION:2.1 N;LANGUAGE=de;CHARSET=Windows-1252:Test;Mustermann;;;(geschäftlich) FN;CHARSET=Windows-1252:Test Mustermann (geschäftlich) ORG:Mustermann CompanyTITLE;CHARSET=Windows-1252:CEO TEL;WORK;VOICE:0049 1111 22 769 23 - 1 TEL;CELL;VOICE:0049 2222 33 71 55 90 ADR;WORK;PREF;CHARSET=Windows-1252:;;Frobuehl 22;Gothtown;;101092;England LABEL;WORK;PREF;CHARSET=Windows-1252;ENCODING=QUOTED-PRINTABLE:Leihb=FChl 21=0D=0A= 101092 Frobuehl X-MS-OL-DEFAULT-POSTAL-ADDRESS:2 URL;HOME:www.Test-Mustermann.de EMAIL;PREF;INTERNET:Test@Test-Mustermann.de X-MS-OL-DESIGN;CHARSET=utf-8:<card END:VCARD I only need the name and address. Thanks in advance A: Pretty old, but it still works: https://github.com/drlongnecker/Thought.vCards A: You can try to use this sample. A: Helle, sry for the long delay. I solved my problem now with the follwing code: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Outlook = Microsoft.Office.Interop.Outlook; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { Outlook.ContactItem contact; Outlook.Application app = new Outlook.Application(); contact = (Outlook.ContactItem)app.Session.OpenSharedItem(@"C:\vv.vfc"); MessageBox.Show(contact.FirstName); } } } This is just an example of how to easily import a VCF file with C# . i hope this helps. Of course i wouldnt implement it in that way, i rather would create a method with a parameter "incomingFile" or smth else. Berry A: the solution with the outlook application is not effictive. Outlook.Application app = new Outlook.Application(); this will open the outlook first. and actually you need only to open the vcard and parse it to extract the information you want from it. A: C# purely does not has specific method or class for work with vcfs. But these solutions can be way.last one is the best: * *Work with Microsot.office.interop.outlook. Ohhh nooo.it will open outlook first and then after steps you can do your work.surely its not best solution. *Use Thought vcard.its not too bad but image that you have multiple vcfs and you merge them in one vcf.with this package its too hard(or almost impossible) to work with it. *Use VCardlib .it doesnt has previous problem but its not update for work with vcf version4 until now. *I use MixERP.NET.VCard and its more simple and effective.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Application crashes while displaying many images Please review following code -(void)addScrollView{ [self selectData]; scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(5, 00, 320, 480)]; int counter=5; float y=40.0f; int fullLength=[photoArray count]; int horizontal=320; int vertical=(fullLength/4)*80; int c1=1; for(int c=0;c<[photoArray count];c++){ PhotoData *d=[photoArray objectAtIndex:c]; if(c1==5){ counter=5; y=y+80.0f; c1=1; } UIImage *img1=[[UIImage alloc]initWithContentsOfFile:d.photoPath]; UIButton* button = [[UIButton alloc] init]; button.tag=c; [button setBackgroundImage:img1 forState:UIControlStateNormal]; [button setFrame:CGRectMake(counter, y, 70.0, 70.0)]; [button addTarget:self action:@selector(showDetail:) forControlEvents:UIControlEventTouchUpInside]; [scrollView addSubview:button]; counter=counter+78.0f; c1++; [button release]; [img1 release]; [d release]; } [scrollView setContentSize:CGSizeMake(horizontal, vertical+200)]; [self.view addSubview:scrollView]; [scrollView release]; } -(void)selectData{ //This method is defined to retrieve data from Database NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsPath = [paths objectAtIndex:0]; //Obtained the path of Documennt directory which is editable NSString *filePath = [documentsPath stringByAppendingPathComponent:@"memory.sql"]; //memory.sql is sqlite file which is used as local database photoArray=[[NSMutableArray alloc]init]; NSString *dbPath=filePath; sqlite3 *database; if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) { // Setup the SQL Statement and compile it for faster access const char *sqlStatement = "select * from photo where mid=?"; sqlite3_stmt *compiledStatement; if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) { sqlite3_bind_int(compiledStatement, 1,memoryId); while(sqlite3_step(compiledStatement) == SQLITE_ROW) { PhotoData *data=[[PhotoData alloc]init]; int pId=sqlite3_column_int(compiledStatement, 1); NSString *filePath=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)]; [data setPhotoId:pId]; [data setPhotoPath:filePath]; [photoArray addObject:data]; [filePath release]; } // end of the while } sqlite3_finalize(compiledStatement); } sqlite3_close(database); tableArray=[[NSArray alloc]initWithArray:photoArray]; paths=nil; documentsPath=nil; filePath=nil; dbPath=nil; } Some times application crashes by giving data formatter error A: You should not release object that was returned by objectAtIndex: if you have not retained it. SO try to remove line: [d release]; You should release that object after adding it to photoArray. Do it after line : [photoArray addObject:data]; [data release]; You should do that because your data object is not autoreleased (PhotoData *data=[[PhotoData alloc]init];) and after adding it to photoArray it is automatically retained.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Transparent Panel on Form that has a backgroundimage I have a Form, that has a BackgroundImage, and the BackColor of form is set to red. Then, I try to add a panel on that form, set panel's Background to Transparent, but it inherits Form's BackColor and thus panel's background becomes red. How do I "tell" the panel not to inherit Form's BackColor, but Form's BackgroundImage? Update: It's working fine on Windows 7, but not on Windows XP (SP3). Fixed: The problem was caused by overriding Form's CreateParams and turning on WS_EX_COMPOSITED A: That is because Windows Forms ask for the backcolor of the parent control when current control's backcolor is set to transparent. Transparent Panel A: change the panel property BackColor to Transparent [web tab]
{ "language": "en", "url": "https://stackoverflow.com/questions/7593313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Fetching data in small units instead of fetching at a time I'm currently working on a Struts 2 application with Spring as backend with MySQL database. Right now fetching 1000+ rows on page load. I'm using tablesorter jquery plugin for displaying the results,sorting on click and pagination purpose. But the page is taking lot of time to load and also it hangs in IE !! Is there any easier way to do this like fetching required data from database as and when the user makes the selection like fetch first 10 rows,sorting data,etc. Any ideas to make the application work faster are welcome !! A: I couldn't tell from the docs if the plugin supported server-side paging or not, but that'd be one thing to consider. It was unclear if its paging plugin had any options for this. Does the plugin's example with a thousand students crash under the same circumstance?
{ "language": "en", "url": "https://stackoverflow.com/questions/7593317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: error in java basic test program $cat JarTest.java package edu.testjava.simple; public class JarTest { public static void main(String args[]) { System.out.println("Hello World\n"); } } $javac JarTest.java $java JarTest I get error: Exception in thread "main" java.lang.NoClassDefFoundError: JarTest (wrong name: edu/testjava/simple/JarTest) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632) at java.lang.ClassLoader.defineClass(ClassLoader.java:616) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141) at java.net.URLClassLoader.defineClass(URLClassLoader.java:283) at java.net.URLClassLoader.access$000(URLClassLoader.java:58) at java.net.URLClassLoader$1.run(URLClassLoader.java:197) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:248) Could not find the main class: JarTest. Program will exit. Why so? Anything wrong with package etc? Thanks! A: You need to do: $ java -cp . edu.testjava.simple.JarTest You need to specify the name of the class with the full package name (in this case edu.testjava.simple). You don't need .class or .java on the end. You can also see the answers to How to execute a java .class from the command line. A: Yes, it's because of the package. Java enforces the project structure to be the same as the package structure. That means, that the class in the edu.testjava.simple package must be located in the edu/testjava/simple/ directory. You may either: * *Remove package declaration (this, however, is only acceptable in such "hello world" cases) *Compile the file using javac -d . JarTest.java (this will put the .class file in the appropriate directory) and launch it via java edu.testjava.simple.JarTest
{ "language": "en", "url": "https://stackoverflow.com/questions/7593320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Confused about how fetchResultController works with MagicalRecord I have a NSOperation subclass,this is the main method: (void)main { NSAutoreleasePool *Pool = [[NSAutoreleasePool alloc] init]; managedObjectContext = [NSManagedObjectContext contextThatNotifiesDefaultContextOnMainThread]; Message *message = (Message *) [managedObjectContext objectWithID:self.messageID]; message.status = [NSNumber numberWithInt:SKMessageSendStateStart]; [message save]; [self send]; [self finish]; [Pool drain]; } I define the fetchResultController and defaultContext like this: (BOOL)application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [MagicalRecordHelpers setupCoreDataStackWithStoreNamed:@"Shark"]; self.context = [NSManagedObjectContext context]; [NSManagedObjectContext setDefaultContext:self.context]; self.fetchController = [Message fetchRequestAllGroupedBy:nil withPredicate:nil sortedBy:@"text" ascending:YES]; [self.fetchController setDelegate:self]; [self.fetchController performFetch:nil]; } Everytime i call [message save],the console logout: -NSManagedObjectContext(MagicalRecord) mergeChangesFromNotification: Merging changes to * DEFAULT context on Main Thread * But the NSFetchedResultsControllerDelegate never get called! Does this mean that I set the FetchedResultsController wrong or what? I am totally confused. Thanks in advance. A: The reason this isn't working is because MagicalRecord will automatically call performFetch: for you, thus not allowing you to set the delegate ahead of time. Also, in your applicationDidFinishLaunching: method, you want to delete these lines: self.context = [NSManagedObjectContext context]; [NSManagedObjectContext setDefaultContext:self.context]; You want to NOT change the default context in this case. MagicalRecord is handling stuff for you when you call setupCoreDataStackWithStoreNamed:...that is, a MOC is already available for use when that method completes, there is no need to toss the one it created for you and set the default context to a new instance in this particular case. It's also not necessary to hold on to the context if all you're doing is going to use it to pass to one of the fetch methods provided by MagicalRecord. MagicalRecord will create a single context for its use (the 'default' context) and just use that... A: I misunderstood what the [NSManagedObjectContext context] means. It create a new context in the main thread. Since the context that the fetchResultController monitor is not the same context that the change merged to, the NSFetchedResultsControllerDelegate will not get called. Change [NSManagedObjectContext context] to [NSManagedObjectContext defaultContext] solved the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Java Wicket AJAX refresh paginated DataView I have a page that has a list of Hibernate entities that is loaded dynamically on display of the page. The list is used to create a DataView, which is used to display a paginated list of the entries in the list in a container. Each entry in the list has a delete icon on it. When the delete icon is pressed, I lazy delete the entry, reload the list with entities (which will no longer contain the lazy deleted entry), and reload the container, but the entry is still there in the container until I reload the whole page. Why? public class LogPage extends ProjectPage{ @SpringBean private LogDao logDao; @SpringBean private LogEntryDao logEntryDao; private List<LogEntry> logEntryList; private DataView<LogEntry> dataView; private WebMarkupContainer logEntryListContainer; public LogPage(PageParameters pp) { super(pp); Project activeProject = SciProSession.get().getActiveProject(); Log log = null; if (activeProject.getLog()==null){ log = new Log(activeProject); log = logDao.save(log); }else{ log = activeProject.getLog(); } logEntryList = logEntryDao.findAll(); Collections.sort(logEntryList); logEntryListContainer = new WebMarkupContainer("logEntryListContainer"); logEntryListContainer.setOutputMarkupId(true); dataView = (DataView<LogEntry>) new DataView<LogEntry>("logEntryDataView", new ListDataProvider(logEntryList)) { private static final long serialVersionUID = 1L; @Override protected void populateItem(final Item<LogEntry> item) { final LogEntry logEntry = item.getModelObject(); item.add(new Label("contents", logEntry.getContents())); item.add(new Label("creator", logEntry.getCreator().toString())); AjaxActionIcon deleteIcon = new AjaxActionIcon("deleteIcon", ImageIcon.ICON_DELETE){ private static final long serialVersionUID = 1L; @Override protected void onClick(AjaxRequestTarget target) { LogEntry toBeRemoved = logEntryDao.reLoad(logEntry); toBeRemoved.setDeleted(true); logEntryDao.save(toBeRemoved); logEntryList = logEntryDao.findAll(); target.addComponent(logEntryListContainer); } }; item.add(deleteIcon); } }; dataView.setItemsPerPage(10); logEntryListContainer.add(dataView); logEntryListContainer.add(new PagingNavigator("navigator", dataView)); add(logEntryListContainer); } } A: You are changing what the variable logEntryList points to, but that does not impact what the new ListDataProvider(logEntryList) sees. Upon reload, what you could do is * *logEntryList.clear().addAll(logEntryDao.findAll()) so that the variable to which the data provider points is updated *provide your own DataProvider implementation A: You pass in the list of logEntries upon creation of the DataView. Any changes to the list afterwards will not be reflected. Try wrapping the list in a PropertyModel and provide a getter for it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NotificationWindow in browser silverlight is there a way to have NotificationWindow in browser? I need NotificationWindow in browser not in "out of browser". A: Like AnthonyWJones said, in Silverlight 4 the NotificationWindow is restricted to Out Of Browser use. However with Silverlight 5, apps will be able to run in the browser with elevated permission (under certain conditions). That means that the NotificationWindow will work in the browser. More info on Silverlight 5 in-browser trusted apps here A: Silverlight exclusively limits NotificationWindow to OOB use. You will need to find something else outside of Silverlight to acheive the requirement. A: As guys said, there is no NotificationWindow in browser for Silverlight 4. For solving this issue you can choose different ways: first is just to wait for release of SL 5 or on the other hand - implement your own MessageBox with desired functionality. Regarding second one I can help with some code samples.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Block/prevent Loaded SWF from accessing Loader's Stage I have two SWFs: a Loader SWF, and a Loaded SWF. I need to add the Loaded SWF to the display hierarchy, but I don't want to give it free access to the stage. It may, for instance, attempt to change the scaleMode, and I don't want that to happen. What are some good methods for restricting loaded content's access to the stage? I may, for instance, want to allow it to access the stageWidth and stageHeight, but not the scaleMode or align. Suggestions? EDIT: Additional Constraints I can't change anything about the Loaded SWF. Both SWFs are in the local-with-file-system sandbox. These SWFs are both Flash Player 10, ActionScript 3, made in Flash Professional. Not AIR, not Flex. I'd love to be able to implement a proxy class or a getter to somehow intercept calls to the stage, but I don't believe there is any way to. I don't believe, for example, that you can subclass the Stage class and use that subclass in place of the normal Stage object referenced by the stage property in all MovieClips. The stage property is read-only, so it can't be cross-scripted by the Loader to point to something different. A: By default, Flash will not allow a child SWF to access its parent's properties and methods, so you don't need to do anything. Should you ever want to allow access you need to explicitly allow it using Security.allowDomain() If you want the child SWF to access some properties but not others, you can use a sandbox bridge (complicated). Or you can have the child SWF "declare" what it wants to do. For example, add a property such as "requiredStageWidth" to the child. Then have the parent check for the existence of this property - if it's there, set the stage width, otherwise do nothing. A: One solution could be to override the stage getter in your main swf and in that way prevent the loaded swf from accessing it. You would though have to return a valid object that simulates the stage to prevent errors in the loaded swf if it tries to access the stage. public override function get stage():Stage{ trace("trying to access stage") return new Object() as Stage }
{ "language": "en", "url": "https://stackoverflow.com/questions/7593330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get all windows user account name? Possible Duplicate: Getting a list of user profiles on a computer in C++ Win32 I should get all windows user accounts including "SYSTEM" and logged-in user's name. But I don't know how to access it. I'm using C++. So I want to know the Windows API to get the information. Please help me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to call C++ from Java? I wanted to call a C++ method from Java. I read about JNI, but I am not getting how to get all the library files and where I should keep it in order to run the program from command line. Is there any way to call a C++ method from Eclipse itself, because I am using it to run Java classes. A: While I've used JNI-C++ bridging in the past (only a little though) - it can be a bit ugly. You might want to consider using SWIG to help you generate all the messy boiler plate code. A: If JNI is too complicated you can take a look at JNA. In first case you have to create native wrapper code (in C or C++) to join Java and native (C++/C/...) code. In second case it is done at runtime (so you only need Java code + config). A: I use JNR/FFI https://github.com/jnr/jnr-ffi which I have found to be faster than JNA and easier than SWIG. It's as close to JNI for speed I have found but less error prone. A: I have used JNA before for simple interfaces and it was simple and elegant enough. It is advised though, that if there is a complex interface then it's better to use SWIG. There are some good answers that compare SWIG with JNI and JNA. It's a while since the question was asked though. SWIG vs JNI and JNA A: JavaCPP - https://github.com/bytedeco/javacpp It provides efficient access to native C++ inside Java. Under the hood, it uses JNI, so it works with all implementations of Java SE. Much easier than JNA/JNI A: Call c++ code from java program. Follow the below Step * *write java code * *that contian declaration of native methods *load shared library contain native code *call native method public class Sample1 { public native int intMethod(int n); public static void main(String[] args) { System.loadLibrary("Sample1"); Sample1 sample = new Sample1(); int square = sample.intMethod(5); System.out.println("intMethod: " + square); } } *Compile java code javac Sample2.java *create c++ header file javac Sample2.java *Write c++ code #include "Sample1.h" #include <string.h> JNIEXPORT jint JNICALL Java_Sample1_intMethod (JNIEnv *env, jobject obj, jint num) { return num * num; } void main(){} *compile c++ code cc -G Sample1.c -o Sample1.so *Run java program java Sample1 A: JNA can be used instead of JNI . All you need is to download JNA jar( https://github.com/java-native-access/jna#download ) Which should be included in your java project. You need to give the location of your c++ library in your project properties. * *Right click project *Run *In VM options include this -Djava.library.path="C:Your dll location". Visit this site for an example which also has a source code for Java and c++ project to know how this works. ( http://blog.mwrobel.eu/how-to-call-dll-methods-from-java/#a_downloads ) A: How to call a C/C++ function from Java then you can use Java Native Interface (JNI), part of the Java platform, is an interface that enables communication between Java applications running on a Java Virtual Machine (JVM) and native applications or libraries written in other programming languages (e.g. C, C++). You can use some below URLs for as examples. http://malinsky.eu/blog/how-to-call-a-c-function-from-java/ https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7593334", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "41" }
Q: how to parse html file in iphone i dont know how to work on it guide me on this i have to fetch html file which is im my resource folder example.html in application i don’t know how to parsh this all file in iphone some one help me how can i parse this static html file in iphone please explane some one to me <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><META http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Ryanair.com</title><link rel="stylesheet" type="text/css" href="css/Ryanair/Standard.css" xmlns:ms="urn:schemas-microsoft-com:xslt" xmlns:usr="urn:the-xml-files:xslt"><link rel="stylesheet" type="text/css" href="css/Ryanair/datePicker.css" xmlns:ms="urn:schemas-microsoft-com:xslt" xmlns:usr="urn:the-xml-files:xslt"><script type="text/javascript" src="/data/js/skysales_3F5DBD0632207A3932CD626AEDC1A849.js"></script><script type="text/javascript" src="/data/js/skysales_B5A6631CD62DEC33073F138AE4A7C8D2.js"></script><script src="http://www.google.com/jsapi"></script><script type="text/javascript" charset="utf-8"> google.load('ads.search', '2'); </script><script type="text/javascript" language="javascript" xmlns:ms="urn:schemas-microsoft-com:xslt" xmlns:usr="urn:the-xml-files:xslt"> Date.dayNames=['Sunday','Monday','Tuesday','Wednesday','Thusday','Friday','Saturday']; Date.monthNames=['January','February','March','April','May','June','July','August','September','October','November','December']; if (typeof jQuery != 'undefined') { $.dpText={ TEXT_PREV_YEAR:'Previous year', TEXT_PREV_MONTH:'Previous month', TEXT_NEXT_YEAR:'Next year', TEXT_NEXT_MONTH:'Next month', TEXT_CLOSE:'Close', TEXT_CHOOSE_DATE:' ' }; } var datePickerFormat='yyyy-mm-dd'; var datePickerDelimiter='-'; Date.format=datePickerFormat; var pln="en"; var pcu="IE"; </script></head><body><noscript xmlns:ms="urn:schemas-microsoft-com:xslt" xmlns:usr="urn:the-xml-files:xslt"><p class="error noprint"> ERROR: This service makes use of Javascript, which appears to be turned off. Click <a href="activateJavascript.htm">here</a> to learn how to activate it. </p></noscript><form novalidate="true"method="post" action="FRSelect.aspx" id="SkySales" ><div><input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value=""><input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value=""><input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUBMGRkg4UKvNNb1NbM14/2n9zUxhNQ++A="></div><div id="header" style="width: 100%;"><div id="blu"><a href="http://www.ryanair.com"><img src="Images/Ryanair/logoyelbg.gif" width="228" height="42" alt="Ryanair.com Homepage" title="Ryanair.com Homepage"></a></div><div id="yel" onclick="this.firstChild.innerHTML='WWW156 2011-09-29 06:31:09 reglixj3c555jw1v|413894465 ';"><span title="DNS: www156 62.73.129.156 10.37.2.156 "> </span>Search » <b>Select</b> » Services » Payment » Itinerary</div><input type="hidden" id="sysdate" value="2011-09-29"><input type="hidden" id="systime" value="06:31:09"></div><div><div id="body"><div id="wrapper"><div id="error"><input type="hidden" name="errorlist" value=""><script language="Javascript" type="text/javascript"> $(document).ready(function(){ var msg = ""; if (msg.length > 0) { msg = msg.replace(/([\.|:])\s*([^\.]+)/g,"$1``$2") var msg_array = msg.split("``"); var newMsg = ""; for (var idx = 1; idx < msg_array.length + 1; idx++){ if (newMsg.indexOf(msg_array[msg_array.length - idx]) == -1) { newMsg = msg_array[msg_array.length - idx] + "\n" + newMsg ; } } alert(newMsg); } }); </script></div><div id="main"><p><b>Here are the flights and fares available on the requested date(s).</b></p><ol><li>Select the flight of your choice.</li><li>Click on the fare name to see the fare rules.</li></ol><script language="javascript" type="text/javascript"> $(document).ready(function() { var minDepArr = ('2011 09 29 12 31').split(' '); var minDep = new Date(minDepArr[0],minDepArr[1]-1,minDepArr[2],minDepArr[3],minDepArr[4]); $(".avlLst").each(function(){ if($(this).find("input[type='radio']").size() == 0){ $("input[id$='_ButtonSubmit']").attr('disabled', 'disabled').css('background-color','#C0C0C0'); } }); $("input[type=radio]").each(function() { var re = new RegExp("[0-9]{2}\/[0-9]{2}\/[0-9]{4}\\s[0-9]{2}\:[0-9]{2}"); var m = re.exec($(this).val()); if(m != null){ var regexp = /([0-9]{2})(\/)([0-9]{2})(\/)([0-9]{4})(\s)([0-9]{2}):([0-9]{2})/gi; var depArr = m[0].replace(regexp,'$5 $1 $3 $7 $8').split(' '); var dep = new Date(depArr[0],depArr[1]-1,depArr[2],depArr[3],depArr[4]); if(dep <= minDep){ $(this).attr('disabled', 'disabled').attr('checked',''); } } }); }); function setTabIndex(marketIndex, index){ var fld=['', '']; var i=marketIndex==1?0:1; document.getElementById(fld[i]).value = index; postBack(); } function postBack(){ ; } var pleaseWaitMessage = 'Please Wait...'; var marketHeaders = ['','Going Out','Coming Back']; function feesTaxes(fltKeys,names){ var mkts=[]; for(var k in names){ var market=names[k].charAt(names[k].length-1); mkts.push(market); $("div#taxAndFeeInclusiveDivBody"+market).css('background-color','#A3AECC').find(".hdr").html('<span>'+pleaseWaitMessage+'</span>').css('background-color','#FFFF99') .ajaxError(function(evt,req,sett){ $(this).html('<span>Unavailable... try again!</span>').css('background-color','#FFBBBB'); }); } $.get("FRTaxAndFeeInclusiveDisplay-resource.aspx", {'flightKeys':fltKeys.join('+++'), 'numberOfMarkets':fltKeys.length, 'keyDelimeter':'+++'}, function(data,stat){ $htm=$(data); for(var i=0,ml=mkts.length;i<ml;i++){ if($($htm[i]).html().match(/RefreshWindow/) ) { window.location.reload(true); } $("div#taxAndFeeInclusiveDivBody"+mkts[i]).css('background-color','white').html('<p class="hdr">'+marketHeaders[mkts[i]]+'</p>'+$($htm[i]).html()); } $('big#totalPrice').text($($htm[$htm.size()-1]).text()); } ); } function selFlight(o){ if(!o) return false; $(o).parents('table:first').find("div[class^='planeImg']").css('background-position','top left'); $(o).parents('table:first').find("tr").removeAttr('class'); var tro=$(o).parents('tr:first').attr('class','on'); var pval=[],pname=[],doJson=true; var A=parseIDDate(tro.attr("id")); var outDTarr=new Date(A[1],A[2],A[3],A[4]+1,A[5],A[6]); $(".avlLst table").each(function(){ var $chkbs=$(this).find("input[type='radio'][name*='market']"); if(A[0]==1 && $chkbs.is("input[name*='market2']")) { $chkbs.each(function(){ var troB=$(this).parents('tr:first'); var B=parseIDDate(troB.attr("id")); var inDTdep=new Date(B[1],B[2],B[3],B[4],B[5],B[6]); if(outDTarr>=inDTdep) { $(this).attr('disabled', 'disabled').attr('checked',''); $("div[class^='planeImg']", troB).css('background-position','top left').attr('disabled', 'disabled'); }else { $(this).attr('disabled', ''); $("div[class^='planeImg']", troB).attr('disabled', ''); } }); } var $chkb=$chkbs.filter(':checked'); if($chkb.size()!=0) { pval.push($chkb.val());pname.push($chkb.attr('name')); $chkb.parent().prev().children('div').css('background-position','top right'); } else if($chkbs.is(':enabled')) { doJson=false; if(A[0]==1) { $chkbs.filter(':enabled:first').attr('checked','true').trigger('click'); } } else $("div[id*='taxAndFeeInclusiveDivBody']", this.parent).find("*:not(.hdr)").remove(); }); if(doJson) { feesTaxes(pval,pname); } } function parseIDDate(s){ var a=s.split('_'); for(var k in a) a[k]=parseInt(a[k].replace(/^0([0-9]+)/,'$1')); return a; } var nbrMarkets=2; var dateRanges=[[],[new Date(2011,9,2), new Date(2011,9,2)],[new Date(2011,9,5), new Date(2011,9,5)]]; var localization={ inPast:'You cannot search earlier than the current date.', datesOverlap:'Your outbound date range cannot overlap your return date range', timesOverlap:'Please recheck the flights you selected\nYour second flight(s) must DEPART at least 1 hour(s) after your first flight(s) ARRIVES!', bookToday:'Unfortunatley due to security restrictions, If you wish to book a flight departing today.\nYou must either make the booking through your local RYANAIR CALL CENTER or at the AIRPORT.' }; function checkDate(market,days){ var flexi=Math.abs(days)==7?true:false; var idx=days>0?1:0; var today=new Date(), tomorrow=new Date(); tomorrow.addDays(1); if(idx==0 && dateRanges[market][idx] <= today){ alert(localization['inPast']); return false; } if(nbrMarkets > 1){ var overlap=false; if(market==2 && idx==0 && dateRanges[market][idx] <= dateRanges[market-1][idx]) overlap=true; else if(market==1 && idx==1 && dateRanges[market][idx] >= dateRanges[market+1][idx]) overlap=true; if(overlap){ alert(localization['datesOverlap']); return false; } } return true; } function checkTimes(){ if(nbrMarkets < 2) return true; var DA=[0,0]; $(".avlLst table input[type='radio']:checked").each(function(){ var A=parseIDDate($(this).parents("tr:first").attr("id")); DA[A[0]-1]=new Date(A[1],A[2],A[3],A[4],A[5],A[6]); }); $("input[id*='oTime']").each(function(){ var A=parseIDDate($(this).val()); DA[A[0]-1]=new Date(A[1],A[2],A[3],A[4],A[5],A[6]); }); if((DA[1]-DA[0]) <= (60*60*1000)){ alert(localization['timesOverlap']); return false; } return true; } $(document).ready(function(){ // This could probably be cleaned up $("a[id*='LinkButtonNextDay1']").click(function(){return checkDate(1,1);}); $("a[id*='LinkButtonNextWeek1']").click(function(){return checkDate(1,7);}); $("a[id*='LinkButtonPreviousDay1']").click(function(){return checkDate(1,-1);}); $("a[id*='LinkButtonPreviousWeek1']").click(function(){return checkDate(1,-7);}); $("a[id*='LinkButtonNextDay2']").click(function(){return checkDate(2,1);}); $("a[id*='LinkButtonNextWeek2']").click(function(){return checkDate(2,7);}); $("a[id*='LinkButtonPreviousDay2']").click(function(){return checkDate(2,-1);}); $("a[id*='LinkButtonPreviousWeek2']").click(function(){return checkDate(2,-7);}); $("a[id*='tab_']").click(function(){ var A=this.id.split("_"); var tabDate=new Date(A[2],A[3]-1,A[4]); var dtime=new Date(), today=new Date(dtime.getFullYear(),dtime.getMonth(),dtime.getDate()); return true; }); $("table[id*=ttable] th").click(function(){ eval($(this).find("a").attr("href")); }).hover(function(){ $(this).find("a").css("text-decoration", "underline"); },function(){ $(this).find("a").css("text-decoration", "none"); }); $(".avlLst table").find("div[class^='planeImg'],input[type='radio']").click(function(){selFlight(this);}); var firstRadio=null; $(".avlLst table").each(function(){ var $chkbs= $("input[type='radio'][name*='market'][lwst='true']:enabled:first", this); if($chkbs.size() == 0){ $chkbs = $("input[type='radio'][name*='market']:enabled:first", this); } $chkbs.each(function(){ $(this).attr('checked','checked').parents('tr:first').attr('class','on'); if(firstRadio==null) firstRadio=this; }); var filter=function(){ var flnum=this.value.replace(/.*FR~\s*(\d+)~.*/, 'FR$1'); var a=preselectflights.split(','); for(var i=0;i<a.length;i++) if(a[i].replace(/\s/g, '')==flnum) return true; return false; }; if(preselectflights!=''){ $("input[type='radio'][name*='market']:enabled", this).filter(filter).eq(0).each(function(){ $(this).attr('checked','checked'); firstRadio=this; }); } }); $(firstRadio).trigger('click'); displayPopUpFareRule = getFareRule; displayPopUpFareRule('K','K2LOW|K|FR|BND2||en-IE','ADT'); }); var preselectflights=''; function getFareRule(classOfService, fareRuleKeys, paxTypes){ var url='FareRules.aspx?fareRuleKeys=' + fareRuleKeys +'&class=' + classOfService + '&paxTypes=' + paxTypes; $('div#fareRules').load(url + ' #main h2,#main div', function() { $('#main div.avlLst > table td:nth-child(3)').each(function(index, cell) { $(cell).wrapInner('<a href="#" onclick="return false;"></a>'); }); $('#fareRules').jqm({overlay: 30, modal: false, onShow: showFareRules}).jqmAddTrigger('#main div.avlLst > table td:nth-child(3) *').jqmAddClose('#fareRules h2 span'); }); } function showFareRules(hs) { var pos = $(hs.t).offset(); var width = $(hs.t).width(); $('#fareRules').css( { 'left': (pos.left + width) + 'px', 'top': pos.top + 'px' }); hs.w.show(); } </script><div class="avlBlk"><h2>Going Out <span>From Aarhus - Malaga</span></h2><table><tr><td align="left" class="chgOff"><a id="AvailabilityInputFRSelectView_LinkButtonPreviousDay1" href="javascript:__doPostBack('AvailabilityInputFRSelectView$LinkButtonPreviousDay1','')">« Previous Day</a></td><td align="right" class="chgOn"><a id="AvailabilityInputFRSelectView_LinkButtonNextDay1" href="javascript:__doPostBack('AvailabilityInputFRSelectView$LinkButtonNextDay1','')">Next Day »</a></td></tr></table><div class="avlLst avlLst1"><p id="taxAndFeeInclusiveDivHeader1"><b>Select A Flight</b></p><div id="taxAndFeeInclusiveDivBody1" class="drilldown"><p class="hdr">Select a Flight</p></div><table><tr id="1_2011_9_2_23_05_00"><td><div class="planeImg1" title="Click to select this fare on this flight"></div></td><td><input id="AvailabilityInputFRSelectView_RadioButtonMkt1Fare1" type="radio" name="AvailabilityInputFRSelectView$market1" value="K~K2LOW~BND2~~RoundFrom|FR~2523~ ~~AAR~10/02/2011 19:30~AGP~10/02/2011 23:05" onclick="return raise('SelectFare', new SelectFareEventArgs(1, 1, 'K'))" required="true" requiredError="Please select a flight and fare in every market." checked lwst="true"></td><td>Regular Fare</td><td>Adult<br></td><td align="right" style="font-size:110%;">449.00 DKK<br></td><td></td><td><b>Sun</b>2 Oct 11<br><b>Flight</b>FR 2523</td><td>19:30 Depart<br>23:05 Arrive</td></tr></table><div style="clear:both; width: 100%; text-align: center;"><a href="javascript:infoWin('trvfee',0,0,'EN')">Fares do not include optional fees/charges. For a full list of Ryanair fees, please click here</a></div><div class="clr"></div></div></div><div class="avlBlk"><h2>Coming Back <span>From Malaga - Aarhus</span></h2><table><tr><td align="left" class="chgOff"><a id="AvailabilityInputFRSelectView_LinkButtonPreviousDay2" href="javascript:__doPostBack('AvailabilityInputFRSelectView$LinkButtonPreviousDay2','')">« Previous Day</a></td><td align="right" class="chgOn"><a id="AvailabilityInputFRSelectView_LinkButtonNextDay2" href="javascript:__doPostBack('AvailabilityInputFRSelectView$LinkButtonNextDay2','')">Next Day »</a></td></tr></table><div class="avlLst avlLst1"><p id="taxAndFeeInclusiveDivHeader2"><b>Select A Flight</b></p><div id="taxAndFeeInclusiveDivBody2" class="drilldown"><p class="hdr">Select a Flight</p></div><table><tr id="2_2011_9_5_15_50_00"><td><div class="planeImg2" title="Click to select this fare on this flight"></div></td><td><input id="AvailabilityInputFRSelectView_RadioButtonMkt2Fare1" type="radio" name="AvailabilityInputFRSelectView$market2" value="C~C2LOW~BND2~~RoundFrom|FR~2522~ ~~AGP~10/05/2011 15:50~AAR~10/05/2011 19:30" onclick="return raise('SelectFare', new SelectFareEventArgs(2, 1, 'C'))" required="true" requiredError="Please select a flight and fare in every market." checked lwst="true"></td><td>No Taxes</td><td>Adult<br></td><td align="right" style="font-size:110%;">379.00 DKK<br></td><td></td><td><b>Wed</b>5 Oct 11<br><b>Flight</b>FR 2522</td><td>15:50 Depart<br>19:30 Arrive</td></tr></table><div style="clear:both; width: 100%; text-align: center;"><a href="javascript:infoWin('trvfee',0,0,'EN')">Fares do not include optional fees/charges. For a full list of Ryanair fees, please click here</a></div><div class="clr"></div></div></div><div class="section right" style="width:38%;padding:4px;"><div class="bld" style="font-size:16px;margin-bottom: 4px;"><p style="float:left;"><big>Total</big></p><p class="rght"><big id="totalPrice">Please Wait...</big></p></div><p><small>Optional charges such as administration and checked baggage fees are not included.<br><a href="javascript:infoWin('trvfee',0,0,'EN');">Click here for details</a></small></p></div><div style="display: none; border: 1px solid black; position: absolute; background-color: white; width: 33%; padding: 0 5px 5px 5px;" id="fareRules"></div><div class="btnRight"><input class="buttonRight" onClick="return validate(this) &amp;&amp; checkTimes() &amp;&amp; preventDoubleClick();" type="submit" name="AvailabilityInputFRSelectView$ButtonSubmit" value="Select and Continue" id="AvailabilityInputFRSelectView_ButtonSubmit"><button id="NewSrch" class="button" onclick="&#xA; window.location='FRSearch.aspx';&#xA; &#xA; return false;&#xA; ">New Search</button><style type="text/css"> .ad_header {color:#191970;font-weight:bold;font-size:11px} .ad_line1 {color:#0000FF;font-size:13px; text-decoration:underline} .ad_url {color:#008000;margin-bottom:12px; text-decoration:none} .ad_text {color:#191970;text-decoration:none} .wide_ads {padding:5px;} div.ads ul {margin: 0px; list-style: none;} .narrow_ads {padding:2px;position: absolute; top: 100px; left: 780px; width:200px;} </style><div id="wide_ad_unit" class="ads wide_ads"></div><div id="narrow_ad_unit" class="ads narrow_ads"></div><script type="text/javascript" charset="utf-8"> var channels = {'DE':'1901616133','ES':'1730142402','FR':'4307283847','GB':'3975277388','IE':'0091594208','IT':'9330300293','NL':'6066899700','PL':'0911139945','SE':'1735271438','Other':'1974134150'}; var channelid= channels['IE']; if (channelid == null) channelid='1974134150'; var pageOptions = { 'pubId' : 'pub-3031568651010206', 'query' : 'Malaga Flight', 'channel' : channelid, 'linkTarget' : '_blank', 'siteLinks' : true, 'sellerRatings' : true }; var adblock = { 'container' : 'narrow_ad_unit', 'number' : 8, 'width' : '250px', 'lines' : 3, 'fontFamily' : 'verdana', 'colorText' : '#191970', 'fontSizeTitle' : '13px', 'fontSizeDescription' : '11px', 'fontSizeDomainLink' : '11px', 'colorBackground' : '#BFD6F7', 'colorDomainLink' : 'blue', 'colorBorder' : '#BFD6F7' }; var adblock2 = { 'container' : 'wide_ad_unit', 'number' : 5, 'width' : '400px', 'lines' : 3, 'fontFamily' : 'verdana', 'colorText' : '#191970', 'fontSizeTitle' : '13px', 'fontSizeDescription' : '11px', 'fontSizeDomainLink' : '11px', 'colorDomainLink' : 'blue', 'colorBackground' : 'white', 'colorBorder' : 'white' }; new google.ads.search.Ads(pageOptions, adblock); </script><div id="YahooBottomSelectAds"></div><script type="text/javascript"> $(document).ready(function(){ keywordsToUse = "Malaga Flight"; resultsHeader = "Sponsored Listings"; currentLanguage = "en"; currentCulture = "IE"; destination = "Malaga"; YahooAds_SetFrame(); }); </script></div></div></div><div class="clr"></div><div id="footer"><div id="fLinks"><a href="http://www.ryanair.com" title="Home">Home</a> | <a href="http://www.ryanair.com/site/EN/faqs.php" title="F.A.Q." target="_blank">F.A.Q.</a> | <a href="http://www.ryanair.com/site/EN/conditions.php?view=privacy" title="Privacy Policy" target="_blank">Privacy Policy</a> | <a href="http://www.ryanair.com/site/EN/conditions.php" title="General Terms &amp; Conditions of Carriage" target="_blank">General Terms &amp; Conditions of Carriage</a> | <a href="http://www.ryanair.com/en/terms-and-conditions/copywrite" title="Terms of Use" target="_blank">Terms of Use</a> | <a href="http://www.ryanair.com/site/EN/faqs.php?sect=CONTACT&amp;div=int_sup" title="Contact Us" target="_blank">Contact Us</a> | <a href="javascript:infoWin('trvfee',0,0,'EN');" title="Fees">Fees</a></div><div id="copyr">Copyright 2009 Ryanair Ltd.</div><input type="hidden" id="language" value=""><input type="hidden" id="culture" value=""><script type="text/javascript"> xtnv=document; xtsd=(window.location.protocol.indexOf('https:')==0?'https://logs152':'http://logc158'); xtsite=(window.location.hostname.indexOf('www.bookryanair.com')!=-1)?'384235':'385193'; xtn2="3"; xtpage="BookingProcess_IE::Select"; xtdi="1"; xt_multc="&x1=2&x2=20111002&x3=20111005&x4=AAR&x5=AGP&x6=1&x7=3"; if(window.xtparam!=null) window.xtparam+=xt_multc; else window.xtparam=xt_multc; </script><script type="text/javascript" src="js/Ryanair/xtcore.js"></script><noscript><img width="1" height="1" alt="" src="http://logc158.xiti.com/hit.xiti?s=384235&amp;s2=3&amp;p=BookingProcess_IE::Select&amp;di=1"></noscript></div></div></div><div class="clr"></div><script type="text/javascript"> // var theForm = document.forms['SkySales']; if (!theForm) { theForm = document.SkySales; } function __doPostBack(eventTarget, eventArgument) { if (!theForm.onsubmit || (theForm.onsubmit() != false)) { theForm.__EVENTTARGET.value = eventTarget; theForm.__EVENTARGUMENT.value = eventArgument; theForm.submit(); } } // </script><script language="javascript" type="text/javascript"><!-- var events = new Array(); function register(eventName, functionName) { if (eval(events[eventName]) == null) { events[eventName] = new Array(); } events[eventName][events[eventName].length] = functionName; } function raise(eventName, eventArgs) { var undefined; if (events[eventName] != undefined) { for (var ix=0; ix<events[eventName].length; ix++) { if ( eval(events[eventName][ix] + "(eventArgs)") == false) { return false; } } } return true; } // --></script><script language="javascript" type="text/javascript"><!-- function SelectFareEventArgs(marketIndex, fltIndex, classOfService) { this.paxFares = marketPaxFares['mkt'+marketIndex+'|flt'+fltIndex+'|'+classOfService]; this.marketIndex = marketIndex; } // --></script><script language="javascript" type="text/javascript"><!-- function AvailabilityInputFRSelectView_Validate(eventArgs) { var dots; var sel; var numOfMkts = 2; var msg = new Array ( "", "", 0 ); for (var i = 1; i <= numOfMkts; i++) { sel = ''; dots = document['SkySales']["AvailabilityInputFRSelectView$market" + i]; if (dots == null) { alert(""); return false; } else if (dots[0]) // array { for (var j = 0; j < dots.length; j++) { if (dots[j].checked) { sel = dots[j].value; break; } } } else // single { if (dots.checked) { sel = dots.value; } } if (sel == '') { alert(msg[i-1]); return false; } } return true; } function displayPopUpFareRule(classOfService, fareRuleKeys, paxTypes) { var url = '/skysales/FareRules.aspx?fareRuleKeys=' + fareRuleKeys +'&class=' + classOfService + '&paxTypes=' + paxTypes; if (!window.fareRuleWindow || fareRuleWindow.closed) // has not yet been defined { fareRuleWindow = window.open(url,'fareRule','width=250,height=251,toolbar=0,status=0,location=0,menubar=0,scrollbars=1,resizable=0'); } else { fareRuleWindow.open(url,'fareRule','width=250,height=251,toolbar=0,status=0,location=0,menubar=0,scrollbars=1,resizable=0'); fareRuleWindow.focus(); } } // --></script><script language="javascript" type="text/javascript"><!-- function paxFare(paxTypeDesc,classDesc,fareRuleKey) { this.paxTypeDesc = paxTypeDesc; this.classDesc = classDesc; this.fareRuleKey = fareRuleKey; } var marketPaxFares = new Array(); marketPaxFares['mkt1|flt1|K'] = new Array(); marketPaxFares['mkt1|flt1|K'][0] = new paxFare('Adult','Regular Fare','K2LOW|K|FR|BND2||en-IE'); marketPaxFares['mkt2|flt1|C'] = new Array(); marketPaxFares['mkt2|flt1|C'][0] = new paxFare('Adult','No Taxes','C2LOW|C|FR|BND2||en-IE'); // --></script><script language="javascript" type="text/javascript"><!-- function AvailabilityInputFRSelectView_initialize() { } // end of Availability_initialize // --></script><script type="text/javascript"> // var RegisterFunctionsWithEvents = new Array(register('Validate', 'AvailabilityInputFRSelectView_Validate'), register('WindowLoad', 'AvailabilityInputFRSelectView_initialize')); // </script></form><script language="javascript" type="text/javascript" xmlns:ms="urn:schemas-microsoft-com:xslt" xmlns:usr="urn:the-xml-files:xslt"> //defined in common.js $(document).ready(function(){ WindowInitialize(); }); </script></body></html> A: This code will parse through your HTML or destination, load into a string, and then with componentsSeparatedByString below will actually find artifacts in your HTML code, and return whatever is between those two segments. You can build off of this! NSString *request = [NSString stringWithFormat:@"http://www.url.com/test.htm"]; NSString *escapedUrl = [request stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *URL = [NSURL URLWithString:escapedUrl]; NSError *error; NSString *HTML = [NSString stringWithContentsOfURL:URL encoding:NSASCIIStringEncoding error:&error]; NSString *question = [[[[HTML componentsSeparatedByString:@"html tags to find"] objectAtIndex:1] componentsSeparatedByString:@"end of html to find"] objectAtIndex:0]; A: I have successfully used Nolan Waite's HTMLReader project to parse a very complicated HTML5 response easily and reliably. It's easy to setup and use, I highly recommend it. Here's the example from the README: #import <HTMLReader/HTMLReader.h> // Parse a string and find an element. NSString *markup = @"<p><b>Ahoy there sailor!</b></p>"; HTMLDocument *document = [HTMLDocument documentWithString:markup]; NSLog(@"%@", [document firstNodeMatchingSelector:@"b"].textContent); // => Ahoy there sailor! // Wrap one element in another. HTMLElement *b = [document firstNodeMatchingSelector:@"b"]; NSMutableOrderedSet *children = [b.parentNode mutableChildren]; HTMLElement *wrapper = [[HTMLElement alloc] initWithTagName:@"div" attributes:@{@"class": @"special"}]; [children insertObject:wrapper atIndex:[children indexOfObject:b]]; b.parentNode = wrapper; NSLog(@"%@", [document.rootElement serializedFragment]); // => <html><head></head><body><p><div class="special"> \ <b>Ahoy there sailor!</b></div></p></body></html> // Load a web page. NSURL *URL = [NSURL URLWithString:@"https://github.com/nolanw/HTMLReader"]; NSURLSession *session = [NSURLSession sharedSession]; [[session dataTaskWithURL:URL completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) { NSString *contentType = nil; if ([response isKindOfClass:[NSHTTPURLResponse class]]) { NSDictionary *headers = [(NSHTTPURLResponse *)response allHeaderFields]; contentType = headers[@"Content-Type"]; } HTMLDocument *home = [HTMLDocument documentWithData:data contentTypeHeader:contentType]; HTMLElement *div = [home firstNodeMatchingSelector:@".repository-description"]; NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet]; NSLog(@"%@", [div.textContent stringByTrimmingCharactersInSet:whitespace]); // => A WHATWG-compliant HTML parser in Objective-C. }] resume];
{ "language": "en", "url": "https://stackoverflow.com/questions/7593337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: git "lost" my commit, sort of, log giving conflicting results Something really strange here I cannot figure out. Last night I committed some files. About lunch time today I realised that the files has "lost" all the changes I'd committed yesterday. I went back through the git log results and sure enough the commit was there. I checked the contents by doing a git diff and the commit contains the changes. However .... If I do a git log I can see the commit in the list of all commits. If I do a commit log on one of the files in the commit, I see every commit except the one from last night. If I do a git show to display the files in the commit the specific file is there. Sooooo git log - shows the commit git show - shows the files in the commit git log file - list every commit but the one I'm interested in !! I also cannot figure out how to tell what killed the committed changes. Anyone got any clues? I like git, but it's a real pain in the rear to figure out sometimes. A: Try to do a git checkout on the directory and see if that has any effect. If that doesn't update them, delete them and then do a git checkout on the files. A: Make sure you haven't committed those files while being on a detached head. (git branch --all would not mention any current branch) The commit would be there, but not accessible from a branch.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Views in GAE DataStore The application is a simple task management system in which an employee can have multiple tasks and a task can be assigned to multiple employees. So the first Model is Employee, which has the following attributes: Class Employee { Long id; //primary key String name; String employeeCode; String position; } The task Model is as follows: class Task { Long id //primary key String name; String description } and an employee is assigned to tasks in the following relation: Class EmployeeTasks { Long id // primary key Long employeeId; Long TaskId; Date assignedDate; Long assignedBy; //employee ID } I have two list views(through AJAX) for the employee module - The first list has the following columns and it is intended for System Administrators: Employee code | Name | Position | Date Created The second list has the following columns and is for the Managers: Employee Code| Name | Position| No of Tasks assigned | Date of last assignment I know that in GAE we need to consider the queries(views) while designing the database model. So my question is whether the above model is ideal for my requirements? The application is being developed in GAE+Spring+JDO+Jackson+YUI. Does it makes sense to stick on with this model and use Jackson ObjectMapper to change the views? Or is it a good practice to write non-persistent objects for the views?
{ "language": "en", "url": "https://stackoverflow.com/questions/7593348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: update code from github I have commit code from my desktop computer and now I am in another city and want to update my code in my laptop. What is the command to update a code. I was using svn and it is very easy to update a code like right click on svn local repo and click update but in github I don't know the proper command. Regards, A: git pull This is the equivalent of svn checkout, not to be confused with git checkout. Type git help to get a list of git commands and an explanation in the shell.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ImageView image issue What does the following error mean? And how can i avoid this? ImageIO: JPEGNot a JPEG file: starts with 0xff 0xd9 Please advice, Thank you. A: You are trying to load not a JPEG file or corrupted FPEG file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Program that uses while loops to calculate the first n Fibonacci numbers When I run it and input a number it just repeats it over non-stop. for example if i put a 3 it will do this 3 3 3 3 3 BUT NON STOP int main() { int current=0, prev=1, prev2=1, fibnum; cout << "Enter the number of Fibonacci numbers to compute: "; cin >> fibnum; if (fibnum <=0) { cout << "Error: Enter a positive number: "; } while (fibnum > 0){ current = prev + prev2; prev = prev2; prev2 = current; current++; cout << "," << fibnum; cout << endl; } return 0; } A: There are several problems with the code: * *You never assign anything to fibnum inside the body of the loop, so its value never changes. *The purpose of current++ is entirely unclear. Basically, you need to decide on the exact meaning of every variable, and stick to it throughout. The way these variables are being used, there's clearly confusion around the purpose of current and fibnum. A: #include <iostream> using namespace std; int main(){ int current=0, prev=0, prev2=1, fibnum; cout << "Enter the number of Fibonacci numbers to compute: "; cin >> fibnum; if (fibnum <=0){ cout << "Error: Enter a positive number: "; } while (fibnum--){ cout << prev ; current = prev + prev2; prev = prev2; prev2 = current; if(fibnum) cout << ","; } cout << endl; return 0; } A: change to int current_fib_num = 0; .... while (current_fib_num++ != fibNum) { .... // your code here } A: There are a couple of things you need to fix. You need to have a count variable; int current=0, prev=0, prev2=1, fibnum; int count; .... To output the first number before the loop cout<<prev2; You can change this to a for loop to make it easier to count the numbers for(count = 0; count <= fibnum; count++){ current = prev + prev2; prev = prev2; prev2 = current; You need to print current, not fibnum -> fibnum is the total numbers that you need to print cout << "," << current; } A: In addition to previous answers note that you can use benefits of recursion if you need to calculate fib number with some certain number. Something like that: #include <cstddef> std::size_t fib( std::size_t num ) { // For first two numbers if (num <= 2) return 1; return fib(num - 1) + fib(num - 2); } but you must keep in mind that this will lead to redundant calculations 'coz of repeatable recalc of same numbers and stack use for transmitting function args. A: You are trying to print fibnum, but it is not changing inside the while loop. You should be printing current instead. Also you need to set a counter that will see the end of while loop. A: #include <iostream> using std::cin; using std::cout; int main() { int a=1, b=1, nums_to_print; while (1) { cout << "Enter the number of Fibonacci numbers to compute: "; cin >> nums_to_print; if (nums_to_print > 0) { while (1) { cout << a; b += a; a = b - a; if (--nums_to_print) cout << ","; else break; } cout << "\n"; return 0; } cout << "Error: Enter a positive number.\n"; } } Demo: http://ideone.com/3H8Fq A: #include <iostream> using namespace std; int main() { int i=0,j=1; int c,n,count=0,d; cout<<"enter num"; cin>>n; c=i+j; cout<<i<<j; while(count<n-2) { d=j+c; cout<<d; j=c; c=d; count++; } return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7593355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tool to Generate Load using the Database Sample Data I wanted to generate a load on my web application to measure/test that how many requests my web app can handle. Currently I am using Apache Benchmark For POST request. The problem is Apache Benchmark only use static data which is in file. I want such a tool which takes a sample data from database and generate load using that data randomly or sequentially. Can anybody tell me which tool is available for that? And Can that tool be able to provide a benchmark report? A: Have a look at Apache JMeter. It can get dynamic data from textfiles (e.g. a CSV export from your database). It does have a learning curve though, but once you get the hang of it, it is quite powerful.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: undefined method `excluded?' for RailsAdmin::Config:Module I'm working through a rails_admin (on RoR 3.1.0) interface for my site (which is an teacher/event pairing site). There are a few basic models, the important ones are teacher, location, event, and image. Teachers "teach" events (habtm), events are at a location, and photos can be paired to locations, events, and teachers. [ I'm kinda new to RoR architecture... does this make sense? ] I'm getting a undefined method 'excluded?' for RailsAdmin::Config:Module error in .bundler/ruby/1.8/rails_admin-a311e3b833ff/app/views/rails_admin/main/_form_fieldset.html.haml The same error (and similar situation) is answered at http://groups.google.com/group/rails_admin/browse_thread/thread/f517dd1287293a92/970f8433f7e644b9?lnk=raot, but it doesn't seem to apply to me. The "source" of the problem is here (in config/initializers/rails_admin.rb) field :images, :has_and_belongs_to_many_association field :location, :belongs_to_association field :disciplines, :has_and_belongs_to_many_association field :teachers, :has_and_belongs_to_many_association When I comment out the :location and :teachers lines, everything works, but I don't get the right behavior for the teachers. What am I missing? A: Turns out I had a column named :teachers as well as a HABTM relationship named :teachers. Dunno how I missed that for that long...
{ "language": "en", "url": "https://stackoverflow.com/questions/7593358", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to get informed of new song info while retrieving metadata from shoutcast stream Background: I'm streaming radio using double buffering approach for html shoutcast. I get metadata information from stream using http://www.smackfu.com/stuff/programming/shoutcast.html Problem I have three problems. 1- I already use a urlconnection and inputstream for listening radio. I don't want to open a new connection to retrieve metadata. But when I tried to get both from same inputstream, I couldn't listen radio anymore. I guess this is not possible and I have to use two seperate connection? Isn't it bad for performance? 2- When the application started, I retrieve the info of the current song. No problem. However how do I get informed when the song changes. It is said that server will send information when the song changes. But I'm starting the URLconnection, get the input stream, retrieve the metadata and close the connection. I couldn't understand how should I informed by the server? Should I keep the connection open? 3- And last question. AFAIK progressive streaming isn't possible before android 2.2. Is this true just for http? If the protocol was rtsp, could I make progressive streaming before android 2.2? Anyone please make it certain and clear? Thanks a lot, A: * *You're not supposed to open new connection for metadata. Metadata is integrated into MP3 stream (all this is described in the link you posted). *If you close the connection obviously you're no longer be able to receive MP3 stream nor metadata. *See: Streaming Audio from A URL in Android using MediaPlayer? A: You must remember number from icy-metaint header field. After receiving that many bytes from stream (which you send to audio decoder), you must expect metadata part, and read this (also not sending these data to audio decoder). Then you again receive encoded audio from stream, and continue the process of periodically reading metadata after icy-metaint bytes. This means that server sends metadata (info about artist / song title) periodically, and your code must split the input stream to audio and metadata.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using nodejs and knox how do I see the files in an S3 Bucket I upload files in many different ways to my s3 bucket. In python i could use boto like this: from boto.s3.connection import S3Connection conn = S3Connection('access-key','secret-access-key') bucket = conn.get_bucket('bucket') for key in bucket.list(): print key.name In node I have used knox to connect to buckets to get urls, but how could I iterate through the keys in node to see all files in my bucket? A: If your buckets get big, best stream those keys! Check out knox-copy: var knoxCopy = require('knox-copy'); var client = knoxCopy.createClient({ key: '<api-key-here>', secret: '<secret-here>', bucket: 'mrbucket' }); client.streamKeys({ // omit the prefix to list the whole bucket prefix: 'buckets/of/fun' }).on('data', function(key) { console.log(key); }); A: You can do it with AwsSum. It is actively maintained and can perform ALL the S3 operations provided by Amazon. * *https://github.com/appsattic/node-awssum/ There is a fully featured example of exactly what you're looking for in the node-awssum-scripts repo. It gets the first 1000 keys, then keeps doing new requests using the 'marker' parameter to the operation until there are no more keys, so you may want to look at that: * *https://github.com/appsattic/node-awssum-scripts/blob/master/bin/amazon-s3-list.js If you need any help, give me a shout on GitHub. Disclaimer: I'm chilts, author of Awssum. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7593363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Show the listview item clicked location on google map I have created an application which shows the multiple overlay as the result of search button click ,there is one more button result list ,which open a dialog box with list view having the details of those search result overlays... I have created a button on the list item "show on the map" ,now i want when the user click on that button the dialog will dismiss and map-view animate to that particular overlay .. I tried this code ,but it is not working: Button.OnClickListener mOkOnClickListener1 = new Button.OnClickListener() { public void onClick(View v) { dialog2.dismiss(); String list_lat = ""+data.get(position).get("lat"); String list_lon = ""+data.get(position).get("lng"); System.out.println("show map..."+list_lat +list_lon); GeoPoint point = new GeoPoint( (int) Double.parseDouble(list_lat), (int) Double.parseDouble(list_lon)); mapController.animateTo(point); mapController.setZoom(14); mapView.postInvalidate(); } }; btn_sm.setOnClickListener(mOkOnClickListener1); Thanks in advance..!! A: My problem is solved after multiplying 1E6 in the latitude and longitude : GeoPoint point = new GeoPoint( (int)( Double.parseDouble(list_lat)* 1E6), (int) (Double.parseDouble(list_lon)* 1E6)); I am posting this because it may help to others,facing the same problem....
{ "language": "en", "url": "https://stackoverflow.com/questions/7593365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: C# compiler does not find dlls ; solution compiled in VS2010 I have a C# solution and some referenced dll-s. Even though when compiling in visual studio(vs2010) it appears as it succeeded, when using the C# compiler it fails: missing dll apparently.. csc /t:library /out:test.dll test.cs test.cs(22,10): error CS0246: The type or namespace name 'Attribute' could not be found (are you missing a using directive or an assembly reference?) Does anyone know why is this happening? A: As you haven't given the code, it's not clear what type Attribute is meant to be. If it's System.Attribute, I'd expect that to be found automatically via the default assembly references. If it's a type in another assembly, you need to explicitly reference it from the command line: csc /t:library /out:test.dll /r:OtherAssembly.dll test.cs A: CSC knows nothing about the project containing test.cs, nor any libraries which that project is referencing. You have to use the /r switch in order to reference other assemblies. Note that there is a file called csc.rsp in the folder containing csc.exe, which specifies default command line switches. This contains most of the usual .NET framework assemblies, which is why you do not have to explicitly reference mscorlib.dll, for example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: keybd_event doesn't work in activex,postmessage does,but can't simulate VK_BACK I'm developing a browser plugin which would interact with javascript. I used the open-source framework firebreath to develop the plugin which would pack NPAPI(non-ie browsers) plugin and activex(used in ie) in one dll file. The following code works perfectly under non-ie browsers which uses the NPAPI plugin("enter","delete","backspace" keys can be pressed correctly): //VKey stands for the key users pressed like "VK_RETURN","VK_BACK","VK_DELETE",etc keybd_event(Vkey,0, KEYEVENTF_EXTENDEDKEY | 0,0); But if I run the plugin in ie,nothing happens.I tried SendInput too,but still nothing happens: KEYBDINPUT kb={0}; INPUT Input={0}; kb.wScan = VK_BACK; kb.dwFlags = KEYEVENTF_UNICODE; Input.type = INPUT_KEYBOARD; Input.ki = kb; ::SendInput(1,&Input,sizeof(Input)); Which is odd is the combination of keys works correctly in ie. eg(ctrl+x): > keybd_event(VK_CONTROL, MapVirtualKey(VK_CONTROL,0), 0 ,0); > keybd_event(bCharKey,(BYTE)0, 0 ,0); > Sleep(10); > keybd_event(bCharKey,(BYTE)0, KEYEVENTF_KEYUP,0); > keybd_event(VK_CONTROL, MapVirtualKey(VK_CONTROL,0), > KEYEVENTF_KEYUP,0); So I change the keybd_event to PostMessage: ::PostMessage(hbrowser,WM_KEYDOWN,vKey,1); //vKey stands for key pressed ::PostMessage(hbrowser,WM_KEYUP,vKey,1); "VK_TAB","VK_DELETE","VK_RETURN","VK_TAB","VK_SPACE" works,but "VK_BACK" doesn't work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Microsoft Sync framework issue, Data not synced fully for a SqlDbType.Text field I have a table with one of its column ADDRESS with datatype Text . When I sync the data from client to sever all other column values sync properly but only first 16 characters get synced for ADDRESS column . I checked in Data access layer of my sync application , Both ApplyInsert and ApplyUpdate command parameters have the size of 1000 for that field. SAMPLE_TABLEApplyInsertCmd.Parameters.Add("@ASC_ADDRESS", SqlDbType.Text, 1000); and SAMPLE_TABLEApplyUpdateCmd.Parameters.Add("@ASC_ADDRESS", SqlDbType.Text, 1000); In ApplyInsert and ApplyUpdate the parameter specified as @ASC_ADDRESS Text=NULL Can anyone see and suggest what i have done wrong ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7593370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to scan tokens only within context using Flex? I want to create a parser of template engine using Flex & Bison. The thing is that I would like to parse only expressions within {{..}} and ${..}. The template can be any arbitrary text with embedded tokens with code like this: </table:table-row> {{$(/report/row.xml).embed()}} {{$(//Accreditation/AccreditationDocument/Report).each(fragment(row) """ <table:row> <table:table-cell office:value-type="string" office:string-value="${row["name"]}" /> </table:row> """)}} <table:table-row table:number-rows-repeated="1048574" table:style-name="ro1"> <table:table-cell table:number-columns-repeated="16384"/> </table:table-row> </table:table> A: I have found the solution myself. Flex has a feature called Start Conditions. Below is the lexer.l code which returns tokens only from {{ }}. Other text is returned as GENERAL_BODY. %{ #include "bisondef.h" %} %option reentrant noyywrap never-interactive nounistd %option bison-bridge WS [ \t\n]+ ID [A-z_][[:alnum:]]* %x stmt %% int stmt_level = 0; "{{" { stmt_level = 0; BEGIN(stmt); } <stmt>{ "{{" { stmt_level++; printf("stmt {{\n"); } "}}" { if (0 == stmt_level) BEGIN(INITIAL); else stmt_level--; } {WS} {} [0-9]+ { yylval->num = atoi(yytext); return NUM; } "+"|"-"|"*"|"/"|"("|")" { return *yytext; } ";" { return SEMICOLON; } {ID} { yylval->str = strdup(yytext); return ID; } } . { yylval->str = strdup(yytext); return GENERAL_BODY; } %% int yyerror(const char *msg) { fprintf(stderr,"Error: %s\n",msg); return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7593374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Aspnet_Compiler to publish all dlls other than modified In our continuous integration process we are using Aspnet compiler to publish the source. But while doing, it only publishes the modified dlls. Our task is like <AspNetCompiler VirtualPath = "DeployTemp" PhysicalPath = "Physical path" TargetPath = "Target path" Force = "true" Debug = "false" Updateable = "true"/> What we want is to publish the whole dlls not the modified ones. ie we want a rebuild of the whole solution. When we searched we found an option -c in aspnet_compiler for this. But we don't know how to apply it here. Please give your suggestions. A: Use Clean option - its equivalent of -c command line option. For example: <AspNetCompiler VirtualPath = "DeployTemp" PhysicalPath = "Physical path" TargetPath = "Target path" Clean="true" Force = "true" Debug = "false" Updateable = "true"/> For more information, see the documentation for the AspNetCompiler task.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Switch case in C# - a constant value is expected My code is as follows: public static void Output<T>(IEnumerable<T> dataSource) where T : class { dataSourceName = (typeof(T).Name); switch (dataSourceName) { case (string)typeof(CustomerDetails).Name.ToString(); : var t = 123; break; default: Console.WriteLine("Test"); } } But this is not working. The case statement is giving me an error saying that a constant variable is expected. Please help guys thank you! A: There is this trick which was shared with me (don't ask for details - won't be able to provide them, but it works for me): switch (variable_1) { case var value when value == variable_2: // that's the trick DoSomething(); break; default: DoSomethingElse(); break; } A: See C# switch statement limitations - why? Basically Switches cannot have evaluated statements in the case statement. They must be statically evaluated. A: You can only match to constants in switch statements. Example: switch (variable1) { case 1: // A hard-coded value // Code break; default: // Code break; } Successful! switch (variable1) { case variable2: // Code break; default: // Code break; } CS0150 A constant value is expected. A: Now you can use nameof: public static void Output<T>(IEnumerable<T> dataSource) where T : class { string dataSourceName = typeof(T).Name; switch (dataSourceName) { case nameof(CustomerDetails): var t = 123; break; default: Console.WriteLine("Test"); } } nameof(CustomerDetails) is basically identical to the string literal "CustomerDetails", but with a compile-time check that it refers to some symbol (to prevent a typo). nameof appeared in C# 6.0, so after this question was asked. A: switch is very picky in the sense that the values in the switch must be a compile time constant. and also the value that's being compared must be a primitive (or string now). For this you should use an if statement. The reason may go back to the way that C handles them in that it creates a jump table (because the values are compile time constants) and it tries to copy the same semantics by not allowing evaluated values in your cases. A: Johnnie, Please go through msdn guide on switch. Also, the C# language specification clearly defines the compile time error case: • If the type of the switch expression is sbyte, byte, short, ushort, int, uint, long, ulong, bool, char, string, or an enum-type, or if it is the nullable type corresponding to one of these types, then that is the governing type of the switch statement. • Otherwise, exactly one user-defined implicit conversion (§6.4) must exist from the type of the switch expression to one of the following possible governing types: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type corresponding to one of those types. • Otherwise, if no such implicit conversion exists, or if more than one such implicit conversion exists, a compile-time error occurs. Hope this helps. A: You can't use a switch statement for this as the case values cannot be evaluated expressions. For this you have to use an an if/else ... public static void Output<T>(IEnumerable<T> dataSource) where T : class { dataSourceName = (typeof(T).Name); if(string.Compare(dataSourceName, typeof(CustomerDetails).Name.ToString(), true)==0) { var t = 123; } else if (/*case 2 conditional*/) { //blah } else { //default case Console.WriteLine("Test"); } } I also took the liberty of tidying up your conditional statement. There is no need to cast to string after calling ToString(). This will always return a string anyway. When comparing strings for equality, bare in mind that using the == operator will result in a case sensitive comparison. Better to use string compare = 0 with the last argument to set case sensitive on/off. A: This seems to work for me at least when i tried on visual studio 2017. public static class Words { public const string temp = "What"; public const string temp2 = "the"; } var i = "the"; switch (i) { case Words.temp: break; case Words.temp2: break; } A: This does require the latest or close to latest version of C#. The advantage is that the variable 'value' in this example can be manipulated, like this, switch (args[1]) { case var value when string.Equals(value, "SELECT_ALL", StringComparison.OrdinalIgnoreCase): { .... break; } case var value when string.Equals(value, "UNSELECT_ALL", StringComparison.OrdinalIgnoreCase): { ... ... break; } etc. etc. which makes sure that you never match to the wrong literal, in this case, because you forgot to use ToUpper() or whatever...
{ "language": "en", "url": "https://stackoverflow.com/questions/7593377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "106" }
Q: Android: Get intent and reroute it to another class My question is simple: if an intent object exists, I want to merely use that and add putExtra() and then startActivity to go back. However, I have no idea how to do this. Any help is appreciated. Intent intent; if(getIntent() != null) { intent = getIntent(); //reroute to BarActivity class } else {//this part is fine intent = new Intent(FooActivity.this, BarActivity.class); } intent.putExtra("cardHP", "100"); startActivity(intent); A: getIntent() is a part of a larger chain. It will return the ENTIRE intent that was sent. You can retrieve the calling class by using getIntent().getExtras().getString("TheOriginatingClass"); Edit: ok last time I edit this... I am too tired, need to go to sleep after this lol... In the intent that was sent, there is the originating class and the class that is being called (Class1 and Class2). When you use the intent that was sent by Class1 you are essentially trying to call Class1 with the same intent that called Class2. You need to create a new intent and if you need the originating class (Class1) you can get that via the chain I described above. Note: I forgot to add you will need to put the classname in as a string extra in the intent that is called from Class1. AFAIK there isn't a direct way to find out what the calling class was. I might be wrong about that though. -or- If you are using an int (as you are in your example) you could use startActivityForResult(Intent, int) http://developer.android.com/reference/android/app/Activity.html#startActivityForResult(android.content.Intent, int) A: If we use the startActivityForResult method, and detect the returned result on the onActivityResult method, then this works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get method names of un-managed components from Prog Ids using C# I want to get the method names of un-managed components. I would be doing using the prog-id System.Type wiType = System.Type.GetTypeFromProgID("WindowsInstaller.Installer"); object objWI = System.Activator.CreateInstance(wiType); //Type ty = objBLType.GetType(); foreach (MethodInfo mem in wiType.GetMethods()) { Console.WriteLine(mem.Name.ToString()); } Running this doesnt give the method names in WindowsInstaller.Installer. How can this be achieved. Thanks in advance
{ "language": "en", "url": "https://stackoverflow.com/questions/7593383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Coalesce Function in DB2 I am using IBM DB2. I have a query which gives the output as: NAME / AMOUNT CST / - VAT / 1400 ST / - I am trying to write a coalesce function for AMOUNT. The datatype of AMOUNT is decimal(10,2) COALESCE(AMOUNT,'&nbsp') The purpose of me doing is, I want a space if the AMOUNT is null, but all I get is an error like "incompatible argument". How can I achieve a space? Please help! A: The problem is you are saying this... If amount is not NULL, display a decimal value, but if it is, display a character value instead. Try this COALESCE(CAST(AMOUNT as VARCHAR(20)),'&nbsp;') Should solve your problem
{ "language": "en", "url": "https://stackoverflow.com/questions/7593384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to Know the lastVisbile row in wpf toolkit datagrid i have datagrid which has 200 rows of data. i need to display the records in 4 monitors. monitor resolutions may be different. so, i need to display the records in such a way that suppose 40 records can fit in first monitor and the i need to take the remaining records into the second monitor like that. how i can know the last visible row in the screen.so that i can take the count and push the remaining data to next monitor. or Any other approach also will be helpful. A: This is not easy to do! A few months back I wrote a utility method for a Windows Phone 7 application that enumerates the items that are currently visible within an ItemsControl: /// <summary> /// Enumerates all the items that are currently visible in an ItemsControl. This /// implementation works for both virtualized and non-virtualized panels. /// </summary> public static IEnumerable<FrameworkElement> GetItemsInView(this ItemsControl itemsControl) { // find the panel that hosts our items - this is 'cached' // using the ItemsControl.Tag property to minimize visual tree // navigation Panel itemsHostPanel = itemsControl.Tag as Panel; if (itemsHostPanel == null) { itemsHostPanel = itemsControl.Descendants<Panel>() .Cast<Panel>() .Where(p => p.IsItemsHost) .SingleOrDefault(); itemsControl.Tag = itemsHostPanel; } VirtualizingStackPanel vsp = itemsHostPanel as VirtualizingStackPanel; if (vsp != null) { // implementation for virtualizing lists return GetItemsInView(itemsControl, vsp); } else { // implementation for non-virtualizing lists return Enumerable.Range(0, itemsControl.Items.Count) .Select(index => itemsControl.ItemContainerGenerator.ContainerFromIndex(index)) .Cast<FrameworkElement>() .Where(container => container.GetRelativePosition(itemsControl).Y + container.ActualHeight > 0) .Where(container => container.GetRelativePosition(itemsControl).Y < itemsControl.ActualHeight); } } /// <summary> /// Gets the items in view for a virtualizing list /// </summary> private static IEnumerable<FrameworkElement> GetItemsInView(this ItemsControl itemsControl, VirtualizingStackPanel vsp) { // iterate over each of the items in view int firstVisibleItem = (int)vsp.VerticalOffset; int visibleItemCount = (int)vsp.ViewportHeight; for (int index = firstVisibleItem; index <= firstVisibleItem + visibleItemCount + 2; index++) { var item = itemsControl.ItemContainerGenerator.ContainerFromIndex(index) as FrameworkElement; if (item == null) continue; yield return item; } } This should work for a WPF DataGrid. As you can see the implementation depends on whether the view is virtualized or not. Note, this code is part of the WP7Contrib project, and can be seen here. It has dependencies on a few other utility / extension methods.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: I am using form edit using JQ Grid. The data on the 2nd drop box will be populated dynamically based on the value on first Please help, I am a new developer and I am using form edit. There are two drop down boxes in the form using JQ Grid. The data on the second drop down will be populated dynamically based on the value on first drop box. I had been reading related topics here and tried those codes but still it didn't worked for me. Here are my codes. The value of the MedicineName depends on what is the value of the MedicineType choose by the user. Please help, where did I went wrong with my codes? I followed what is posted by others here but still it populate all the lists of medicine names without considering the value of the first drop box. :( You're help is highly appreciated. Thanks var MedicineType = { 'allergy': 'For Allergy / Itchiness', 'asthma': 'For Asthmatic Attacks','colds': 'For Colds / Cough', 'eye': 'For Eye Redness / Irritation','fever': 'For Fever and Pain','hyperacid': 'For Hyperacidity / Abdominal Pain' }; var MedicineName = { '1':'Paracetamol (Tempra 250mg/mL) syrup','2':'Paracetamol (Biogesic 250mg/mL) Syrup','3':'Paracetamol (Biogesic 500mg) tab','4':'Mefenamic Acid 250mg tab','5':'Mefenamic Acid 500mg tab','6':'Neozep Non-drowsy 10mg/500mg tab','7':'Carbocistene 500mg cap','8':'Loratadine (Allerta) 5mg/5ml syrup','9':'Loratidine 10mg tab','10':'Eye mo Eye drops','11':'Isonep Eye drops','12':'Tums 500mg tab','13':'Buscopan 10mg tab','14':'Buscopan Plus 10mg/500mg tab','15':'Salbutamol Nebulization' }; var MedicineTypecode = { fever: { '1': 'Paracetamol (Tempra 250mg/mL) syrup', '2': 'Paracetamol (Biogesic 250mg/mL) Syrup','3': 'Paracetamol (Biogesic 500mg) tab' ,'4': 'Mefenamic Acid 250mg tab','5': 'Mefenamic Acid 500mg tab'}, colds: { '6': 'Neozep Non-drowsy 10mg/500mg tab', '7': 'Carbocistene 500mg cap' }, allergy: { '8': 'Loratadine (Allerta) 5mg/5ml syrup', '9': 'Loratidine 10mg tab' }, eye: { '10': 'Eye mo Eye drops','11': 'Eye mo Eye drops' }, hyperacid: { '12': 'Tums 500mg tabs','13': 'Buscopan 10mg tab','14': 'Buscopan Plus 10mg/500mg tab' }, asthma: { '15': 'Salbutamol Nebulization' }}; var lastSel = -1; var grid = jQuery("#ClinicAvailMed"); var resetMedValues = function () { grid.setColProp('MedicineName', { editoptions: { value: MedicineTypecode } }); }; $("#ClinicAvailMed").jqGrid({ datatype: "local", height: 100, width: 700, colNames: ['ClinicAvailmed','MEDICINE TYPE','MEDICINES'], colModel: [ { name: 'ClinicAvailmed', index: 'ClinicAvailmed', sorttype: "int", editable: true, editoptions: { readonly: true, size: 2} }, { name: 'MedTypeCode', index:'MedTypeCode', width: "50%", editable: true, formatter: 'select', edittype: "select", editoptions: { value: MedicineType ,dataInit: function (elem) { var v = $(elem).val(); grid.setColProp('MedicineName', { editoptions: { value: MedicineTypecode [v]} });},dataEvents: [ {type: 'select', fn: function(e) {resetMedValues(); var v = parseInt($(e.target).val(), 10); var sc = MedicineTypecode [v]; var newOptions = ''; for (var medId in sc) { if (sc.hasOwnProperty(medId)) { newOptions += '<option role="option" value="' + medId + '">' + med[medId] + '</option>'; } } if ($(e.target).is('.FormElement')) { // form editing var form = $(e.target).closest('form.FormGrid'); $("select#MedicineName.FormElement", form[0]).html(newOptions); } else { // inline editing var row = $(e.target).closest('tr.jqgrow'); var rowId = row.attr('id'); $("select#" + rowId + "_MedicineName", row[0]).html(newOptions); } } } ] }}, { name: 'Medcode', index: 'Medcode', width: "50%", editable: true, edittype: "select", editoptions: { value: MedicineName} }, ], onSelectRow: function (id) { if (id && id !== lastSel) { if (lastSel != -1) { resetMedValues(); grid.restoreRow(lastSel); } lastSel = id; } }, ondblClickRow: function (id, ri, ci) { if (id && id !== lastSel) { grid.restoreRow(lastSel); lastSel = id; } resetMedValues(); grid.editRow(id, true, null, null, 'clientArray', null, function (rowid, response) { // aftersavefunc grid.setColProp('MedicineName', { editoptions: { value: MedicineTypecode } }); }); return; }, multiselect: false, caption: " ", editurl: "handlers/store.ashx?table=ClinicAvailMed", ondblClickRow: function(id) { { $("#ClinicAvailMed").editGridRow(id, { modal: true, drag: true, addCaption: "Add Medicine", editCaption: "Edit Medicine", bSubmit: "OK", bCancel: "Close", closeAfterEdit: true }); } } }); $("#ClinicAvailMed").jqGrid('hideCol', 'ClinicAvailmed'); $("#btnAddClinicAmed").click(function() { $("#ClinicAvailMed").editGridRow('new', { modal: true, drag: true, addCaption: "Add Medicine", editCaption: "Edit Medicine", bSubmit: "OK", bCancel: "Close", closeAfterEdit: true, addedrow: 'last' }); }); $("#btnEditClinicAmed").click(function() { var _selectedRow = $("#ClinicAvailMed").getGridParam('selrow'); if (_selectedRow != null) { $("#ClinicAvailMed").editGridRow(_selectedRow, { modal: true, drag: true, addCaption: "Add Medicine", editCaption: "Edit Medicine", bSubmit: "OK", bCancel: "Close", closeAfterEdit: true }); } else { alert("Please select the row which you want to edit."); }}); $("#btnDeleteClinicAmed").click(function() { var _selectedRow = $("#ClinicAvailMed").getGridParam('selrow'); if (_selectedRow != null) { $("#ClinicAvailMed").delGridRow(_selectedRow, { drag: true, msg: "Delete the row(s)?", caption: "Delete", bSubmit: "Yes", bCancel: "Close", modal: true }); } else { alert("Please select the row which you want to edit."); } }); A: Look at the demos: this and this from the old answer and another one. The demos show how one can implement dependent selects in form editing, inline editing and in the toolbar search. A: In resetMedValues you use grid.setColProp('MedicineName'... althought you do not have any column with that name. This is definitely a false.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to stop proguard from obfuscating entire package? I need to prevent Proguard from obfuscating any classes from the package com.foo.*. I have tried: -keep com.foo.** { <fields>; <methods>; <constructors>; } But proguard says : Error: Unexpected keyword 'com.sun.foo.**' in line 32 of file 'obfuscationConfig.pro', included from argument number 1 I get a similar error if I try keep name com.foo** or keep * com.foo.**. A: Try to use the following: -keep class com.foo.** { public protected private *; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7593397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: What does this code segment in python mean? I'm trying to understand what is going on here, specifically how curids is getting set: for idx in xrange(0, int(math.ceil(float(len(mids))/chunk))): curids = mids[int(idx*chunk):int((idx*chunk)+chunk)] I'm not sure what the syntax for mids[int(idx*chunk):int((idx*chunk)+chunk)] is trying to do. A: It extracts blocks of mids into curids, where each block consists of chunk elements. If you change the loop to print out the values of int(idx*chunk) and int((idx*chunk)+chunk)], you'll see that for yourself. For example, if len(mids)==50 and chunk==12, the indices that would get printed are: 0 12 12 24 24 36 36 48 48 60 These are the starting and ending indices of each slice of mids (the start index is inclusive and the end index is not). Note that the last value is allowed to go above len(mids), but that's not a problem given how Python slicing works (it'll just slice to the end of mids). A: It extracts chunk number of elements from mids starting at idx*chunk and places them into curids. A: The code mids[int(idx*chunk):int((idx*chunk)+chunk)] is getting a subset of the list. The resulting int to the left of the : is the start position in the list, the int to the right is the end position. So the format is: list[start:end] A: So then, as far as i can see the loop splits the mids list into chunks the size of chunk and curids is being attribuited those chunks. So for example if mids was a 20 values list and chunk was 4, curids would be attribuited the values mids[0:4],mids[4:8],..mids[16:20] , basically splitting the list in 5
{ "language": "en", "url": "https://stackoverflow.com/questions/7593398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Use 0755 as base-8 number Here is my code: function myChmod($path, $permission, $log) { //this is to overcome umask limitations that mkdir adheres to $result = chmod($path, octdec($permission)); if(!$result) { $log->log("Error failed to chmod '$path' to '$permission'. Exiting."); throw new Exception("Error failed to chmod '$path' to '$permission'. Exiting."); } return $result; } $trml2pdfPath = $c->install_path.'assets/trml2pdf/trml2pdf/trml2pdf.py'; myChmod($trml2pdfPath, 0755, $log); How do I prevent PHP from changing this base-8 number 0755 to base-10 number 493? I wanna use the chmod function in PHP, but it just keeps changing it to 493. A: PHP's chmod() function takes an integer as second parameter. It does not matter whether you pass octal(0755) or dec(493), it's the same number. myChmod($trml2pdfPath, 0755, $log); the 0755 here is a number literal. PHP interprets it as the number oct(755)=dec(493), meaning: you don't need any conversion function in myChmod(). $result = chmod($path, $permission); A: From http://docs.php.net/chmod Note that mode is not automatically assumed to be an octal value, so strings (such as "g+w") will not work properly. To ensure the expected operation, you need to prefix mode with a zero (0): See this example code in php documentation: <?php chmod("/somedir/somefile", 755); // decimal; probably incorrect chmod("/somedir/somefile", "u+rwx,go+rx"); // string; incorrect chmod("/somedir/somefile", 0755); // octal; correct value of mode ?> So I guess you need not use base_convert, instead you can directly use the octal number. This should work for you: $result = chmod($path, str_pad($permission, 4, '0', STR_PAD_LEFT)); A: have a little trick, change : $result = chmod( $path, octdec( $permission ) ); to : $result = chmod( $path, ( ( "0" . octdec( $permission ) ) * 1 ) ); hope this help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to start with phonegap development? Hi I have gone throught the site: phonegap I have also read the documentation provided there, but is there any easy way tutorial available for that? I have less idea about javascript coding and what I found is phonegap is entirely based on javascript. Can anyone guide me from where to start with? Thanks in advance. Mrunal A: * *http://docs.phonegap.com/ : This will give you the insight of PhoneGap APIs with source: *http://drupal.org/project/phonegap : Here you will get the complete source code of Drupal PhoneGap app which runs of Android. iPhone and BlackBerry. This source will help you to understand the PhoneGap development techniques A: they do have detailed set-up instructions and gettin started help. You don't need JavaScript for a basic Phonegap App. What they do is basically translate a WebPage to a App for the desired Plattform. Therefore you just need to know as much Javascript as your app needs. Afaik you can also use frameworks like jQuery. More tutorials are available here: http://wiki.phonegap.com/w/page/35501397/Tutorials Here on UI Development: http://wiki.phonegap.com/w/page/36767911/UI%20Development%20on%20PhoneGap And there is many more. Maybe you can look into general Javascript tutorials first if you look for a special effect or so. A: Amazon has more books on PhoneGap that offers basic tutorials and code walkthroughs. Here is a new book with sample code available for download.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: get the splitcontainer context in user control click event Sir, I have a split container in which in right panel i have a usercontrol.In the user control i have few buttons like view,new,edit etc.Bottom of that user control a form will open based on what link is clicked on the left side navigation pane. now when i click the user control's view button, i should open a new form below it. how to get the context of splitcontainer in the click event?also if i want to retrieve the form values to save in database when i click the save button in user control, how to do it? A: A Click event has a sender parameter, which is the clicked button. You could use the name of the button to resolve which form should be opened. A: To get your button in the click event: Button clickedButton = (Button)sender; To get the parent of your button (if it was SplitContainer, you'll have to use Parent property 3 times, because the first one will get you your UserControl, second - left panel of the SplitPanel, which doesn't have a Name property, third - your SplitPanel, and 4th, if you want, your form name) string splitPanemName = clickedButton.Parent.Parent.Parent.Name; ...or you can just get whole SplitPanel object: SplitPanel currentSplitPanel = (SplitPanel)clickedButton.Parent.Parent.Parent; ...or Form object: Form currentSplitForm = (Form)clickedButton.Parent.Parent.Parent.Parent; To do this, you have to be sure of the composition of your Form, so you can get the right controls at the right place.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Formatting timedelta object python I wrote this little script to format a timedelta object according to my needs: def due_format(self): time_diff = abs((self.due - datetime.datetime.now()).total_seconds()) days = time_diff / 60 / 60 / 24 hours = time_diff / 60 / 60 minutes = time_diff / 60 hours_wo_days = hours - (math.floor(days) * 24) minutes_wo_hours = minutes - (math.floor(hours) * 60) if (days >= 7): self.due_format = '{} Days'.format(int(days)) elif (hours > 48): self.due_format = '{} Days, {} Hours'.format(int(days), int(hours_wo_days)) elif (hours <= 48 and hours >= 10 ): self.due_format = '{} Hours'.format(int(hours)) elif (hours <= 1): self.due_format = '{} Minutes'.format(int(minutes)) elif (hours < 10): self.due_format = '{} Hours, {:.0f} Minutes'.format(int(hours), int(minutes_wo_hours)) I'm getting the feeling that my approach makes things overly complicated and wanted to ask you guys if you would've attacked this problem differently. Are there any shortcuts that I could take advantage of? I hope this question is appropriate for SO. A: timedelta instance have attributes .days and .seconds which save a few lines. They also keep the values small, so you can convert to int once early instead of for each string format. This also removes the need for abs() and .floor.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Show fragment as a dialog or as a usual activity In my app I've got a fragment which is called "About". On handhelds I want this fragment to look like a usual activity but on tablets I want it to be a dialog. Which way is preferred to handle this situation? A: Make a style for this in your styles.xml (two styles.xml files, one in the values folder, the other in a values-large folder) but have the style you put in the values-large folder inherit from Theme.Dialog. Then have your fragment use that style. The system will take care of the rest. Alternatively, make your class a DialogFragment, and then either embed it into a view hierarchy, or show it as a dialog, as explained here: http://developer.android.com/reference/android/app/DialogFragment.html#DialogOrEmbed
{ "language": "en", "url": "https://stackoverflow.com/questions/7593415", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: How to Fetch Last string using jQuery? Let's say I have a string like this Hello World, I am xyz, How are you ? And I need all the characters in the string that comes after last comma. Which is here How are you? How can I do this ? Note : Here space in the beginning should not come. Also I need the remaining string into another variable which will be Hello World, I am xyz Note: here comma in the end should not come. A: you can do with normal javascript - var a= "Hello World, I am xyz, How are you ?" alert(a.substring(a.lastIndexOf(',')+1,a.length)); A: You can do that with a simple regex: s = 'Hello World, I am xyz, How are you ?'; hay = s.replace(/.*,/, ''); // " How are you ?" Or, if you want to take care of the leading space at the same time: s = 'Hello World, I am xyz, How are you ?'; hay = s.replace(/.*,\s*/, ''); // "How are you ?" If you want the first part and the "How are you ?" part, then you could use match instead of replace: var m = s.match(/^(.*),\s*(.*)$/); // m[1] is "Hello World, I am xyz" // m[2] is "How are you ?" A: No jquery required but i would use the trim function in conjunction with the following: var str = 'Hello World, I am xyz, How are you ?' jQuery.trim(str.substring(str.lastIndexOf(',') + 1)); A: you dont really need jquery for that, maybe just for the CSS-selector to find the text, but you can use normal Javascript like split and splice to find the last text: http://jsbin.com/ibugob/2/edit A: Don't think it can be done with jQuery, but simple Javascript will do the trick. var phrase = "Hello World, I am xyz, How are you ?"; var splitPhrase = phrase.split(","); var lastElement = splitPhrase[splitPhrase.length - 1]; A: JavaScript strings actually have a .split() function, so you won't need jquery at all: var str = "Hello world, I am xyz, How are you?"; var parts = str.split(","); // That just gave you an array // ...Now find the last element: var result = parts[parts.length - 1]; A: Probably, like this also. var a = "Hello World, I am xyz, How are you ?" alert(a.split(',')[2]);
{ "language": "en", "url": "https://stackoverflow.com/questions/7593416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Codeigniter Image resize issue I can't re-size a large uploaded image into tow copies one in another size and the other is in another size. I can only resize only one image. What I want to ask is. I want to creat a thumbnail as well as slighter larger image of a user profile photo. if(move_uploaded_file($_FILES['profilepic']['tmp_name'], './profile_pix/'. $profile_pic_name1)){ $config['image_library'] = 'gd2'; $config['source_image'] = './profile_pix/'. $profile_pic_name1; $config['create_thumb'] = false; $config['maintain_ratio'] = TRUE; $config['width'] = 150; $config['height'] = 190; $this->load->library('image_lib', $config); $this->image_lib->resize(); $thumb_name = './profile_pix/thumb_'.$profile_pic_name1; copy('./profile_pix/'. $profile_pic_name1, $thumb_name); $config2['image_library'] = 'gd2'; $config2['source_image'] = $thumb_name; $config2['create_thumb'] = false; $config2['maintain_ratio'] = false; $config2['width'] = 50; $config2['height'] = 50; $this->load->library('image_lib', $config2); $this->image_lib->resize(); } A: It seems that your image library is already loaded. so call the initialize() function instead of load()
{ "language": "en", "url": "https://stackoverflow.com/questions/7593419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I wait for a callback in coffeescript (or javascript)? I'm working on a password manager webapp that uses Parvez Anandam's pbkdf2.js for key generation (that is, turning a text password into a suitable 256 bit key for AES). I'm using the project to learn coffeescript. I'm having trouble getting the data out of the callbacks. Here's my code: keygen = (password, salt, iterations) -> key = 1 pbkdf = new PBKDF2 password, salt, iterations, size_in_bytes pbkdf.deriveKey ((p) ->), ((k) -> key = k console.log "within callback " + key ) console.log "straight line path " + key Since deriveKey returns immediately, I don't have the data -- the last line prints "1". What's the proper way to deal with this? In java I would expect to get a Future-like object back, which I can join or wait on, but I realize that my backend habits may not be appropriate for UI code. Should I call a 'continue' function from the callback that moves on to the encryption and submitting the form? A: The usual approach is to send in a callback function that the asynchronous task can call when it has finished. Something like this: keygen = (password, salt, iterations, finished) -> key = 1 pbkdf = new PBKDF2 password, salt, iterations, size_in_bytes pbkdf.deriveKey ((p) ->), ((k) -> key = k console.log "within callback " + key finished key ) console.log "straight line path " + key So you'd supply the finished function when you call keygen and finished would do whatever needs to be done when the key is available. Your finished would usually be an anonymous closure. You'll see a lot of this sort of thing if you look at any of the AJAX libraries (such as jQuery): you pass functions to functions, functions all the way down.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593424", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: overflow: auto; is it supported for of a html table? There are long texts or string for html table <td>. Now I want to break the line/texts/string. overflow: auto; is it supported for <td> of a html table? I tried it it doesn't work. How can I solve it ? A: add a CSS attribute white-space white-space:normal; A: if your server side language is PHP you can word-wrap your data came from PHP using this function php wordwrap function
{ "language": "en", "url": "https://stackoverflow.com/questions/7593428", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Set subject from ActionMailer template in Rails 3? How do I set the subject from a Rails 3 ActionMailer template? I'd like to keep the subject and body together. In Rails 2 you can do the following: <% controller.subject = 'Change of subject' %> (from http://www.quirkey.com/blog/2008/08/29/actionmailer-changing-the-subject-in-the-template/) A: http://edgeguides.rubyonrails.org/action_mailer_basics.html it says here that: class UserMailer < ActionMailer::Base default :from => "notifications@example.com" def welcome_email(user) @user = user @url = "http://example.com/login" mail(:to => user.email, :subject => "Welcome to My Awesome Site") end end If you want to access it from the view: http://apidock.com/rails/ActionMailer/Base If you need to access the subject, from or the recipients in the view, you can do that through message object: You got a new note from <%= message.from %>! <%= truncate(@note.body, 25) %> So you can do: message.subject A: To set the subject line of an email from the email view itself you can simply put the following at the beginning of the view file: <% message.subject = 'This is my subject line' %> This works for rails 3 and 4.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593431", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Django sqlclear purpose Can any one explain the use of sqlclear ?.I have read the docs A: The way you would use this type of command is when you are doing initial prototyping of an application. During this phase, before any releases have been done, you're pretty free to iterate over the data model. manage.py gives you the ability to automatically create the data model from the python model with no additional steps, so the sqlclear command gives you the ability to generate (and run if you want) sql that resets the database to the state it was in before you installed the app. As a developer, it's always nice to have a repeatable process to create a clean development environment. As another developer suggested, you can pipe the output of this directly into mysql: python manage.py sqlclear <<YOURAPPNAME>> | mysql --user=<<YOURDBUSERNAME>> --password=<<YOURDBPASSWORD>> <<DBNAME>> This is just one possible reason to use this command. A: I suppose the idea is, along with the other sql.. commands, to be able to easily add, edit, delete, or recreate the tables that Django puts in by default when you do a syncdb. This could help with database migration, removing an app from a shared database, or whenever you need to do anything else to the database but can't just drop the entire database and start over. Although I'm open to other points : ), This was always my impression. A: I pipe the output from sqlclean to mysql to clean (or reset using sqlreset) the database python manage.py <<appname>> sqlclean | mysql <<databasename>> Regards, Raggi
{ "language": "en", "url": "https://stackoverflow.com/questions/7593433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to extract metadata from video(m3u8) files? Is there any way to extract metadata from video(m3u8) files, If exist please help me with links or source code. Thanks A: m3u8 is the utf8 version of m3u instead c1252 charset. m3u is a text file as a play list file with a content like: #EXTM3U starts header and must be the first line #EXTINF for each playable file. In this link you can view samples: http://schworak.com/programming/music/playlist_m3u.asp And an overview for generalistic HTTP Streaming Architecture. A: Code for the lazy dudes out there is below and detailed answered is here private HashMap<String, Integer> parseHLSMetadata(InputStream i ){ try { BufferedReader r = new BufferedReader(new InputStreamReader(i, "UTF-8")); String line; HashMap<String, Integer> segmentsMap = null; String digitRegex = "\\d+"; Pattern p = Pattern.compile(digitRegex); while((line = r.readLine())!=null){ if(line.equals("#EXTM3U")){ //start of m3u8 segmentsMap = new HashMap<String, Integer>(); }else if(line.contains("#EXTINF")){ //once found EXTINFO use runner to get the next line which contains the media file, parse duration of the segment Matcher matcher = p.matcher(line); matcher.find(); //find the first matching digit, which represents the duration of the segment, dont call .find() again that will throw digit which may be contained in the description. segmentsMap.put(r.readLine(), Integer.parseInt(matcher.group(0))); } } r.close(); return segmentsMap; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } Cheers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Where is "setTimeout" from JavaScript in Haxe? Is there an implementation of setTimeout() and clearTimeout() in Haxe? It's of course possible to use the Timer class, but for a one-shot execution it's not the best way, I guess. A: In case you're using the kha framework: Kha modifies haxe.Timer to call kha.Scheduler, which in the end doesn't get the timestamps via setTimeout - it gets these via requestAnimationFrame(). This seems to not work while a tab is inactive, so it's not the same function while the tab is inactive. I'm attempting a workaround, but at the moment, it doesn't give the same result as a native setTimeout()-JS does (although I found a workaround which I'll present for inclusion). A: For a one-shot execution I think that Timer.delay() is perfect. You can use the returned instance to stop the timer later: var timer = haxe.Timer.delay(function() trace("Hello World!"), 250); ... timer.stop(); You could also access the native setTimeout() with the js.html.Window extern: var handle = js.Browser.window.setTimeout(function() trace("Hello World!"), 250); ... js.Browser.window.clearTimeout(handle);
{ "language": "en", "url": "https://stackoverflow.com/questions/7593436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: How to replace < and > from the xml response in client side I have a response that comes from server side in xml format (partial like below) <list> <Response> <cfgId>903</cfgId> <recommendations> &lt;Rule&gt; &lt;name&gt;Env SSA_RB_RESTART&lt;/name&gt; &lt;category&gt;none&lt;/category&gt; &lt;severity&gt;warning&lt;/severity&gt; &lt;ruleEvalResult&gt;true&lt;/ruleEvalResult&gt; &lt;actionResult&gt;Setting SSA_RB_RESTART=0 will cause RuleBase corruption.Kindly unset this environment variable and restart the IIR server&lt;/actionResult&gt; &lt;/Rule&gt; </recommendations> </Response> <Response> <cfgId>903</cfgId> <recommendations> &lt;Rule&gt; &lt;name&gt;SSAOPTS (+Ltd) setting&lt;/name&gt; &lt;category&gt;none&lt;/category&gt; &lt;severity&gt;warning&lt;/severity&gt; &lt;ruleEvalResult&gt;true&lt;/ruleEvalResult&gt; &lt;actionResult&gt; Please note that it is not recommended to have SSAOPTS=+Ltd in case of the Production environment.&lt;/actionResult&gt; &lt;/Rule&gt; </recommendations> </Response> </list> update I get the main Response tag with xml=$(xmldata); var resp_x = $(xml).find('Response').text(); and then I am trying to replace with below resp_x = resp_x.replace(/&lt;/g,"<"); resp_x = resp_x.replace(/&gt;/g,">"); var rule_x = $(resp_x).find('name').text(); alert(rule_x); but it gives me blank, please help me fetch severity. UPDATE with my answer var xmlString=xmlToString(xmldata); xmlString=xmlString.replace(/(&lt;)/g,"<").replace(/(&gt;)/g,">"); xml=StringtoXML(xmlString); //now I can do my operations here $(xml).find('Response').each(function(){ console.debug($(this).find('severity').text()); }); function xmlToString(xmlObj) { if (navigator.appName == "Netscape") { return (new XMLSerializer()).serializeToString(xmlObj); } if (navigator.appName == "Microsoft Internet Explorer") { return xmlObj.xml; } } function StringtoXML(text){ if (window.ActiveXObject){ var doc=new ActiveXObject('Microsoft.XMLDOM'); doc.async='false'; doc.loadXML(text); } else { var parser=new DOMParser(); var doc=parser.parseFromString(text,'text/xml'); } return doc; } A: You're converting the returned XML to a jQuery object too early and then doing the replace wrong. Try something like this: $.ajax({ url: 'list.xml', dataType: 'text', success: function(data) { console.debug(data); data = data.replace('&lt;', '<', 'gm') .replace('&gt;', '>', 'gm'); console.debug(data); var $severities = $(data).find('severity'); console.debug($severities); } }); In the replace(), you need both the g (global) and m (multi-line) flags. See the documentation on String.replace() for details. A: Try like this resp_x = resp_x.replace(/(&lt;)/g,"<"); resp_x = resp_x.replace(/(&gt;)/g,">"); var rule_x=$(resp_x).find('name').text(); alert(rule_x); Hope this helps A: Next example can help you: var str="&lt;Rule&gt;&lt;name&gt;Env SSA_RB_RESTART&lt;/name&gt;&lt;category&gt;none&lt;/category&gt;&lt;severity&gt;warning&lt;/severity&gt;&lt;ruleEvalResult&gt;true&lt;/ruleEvalResult&gt;&lt;actionResult&gt;Setting SSA_RB_RESTART=0 will cause RuleBase corruption.Kindly unset this environment variable and restart the IIR server&lt;/actionResult&gt;" str=str.replace(/&lt;|&gt;/g,function(s){return s==="&lt;"?"<":">"}); // str now is: "<Rule><name>Env SSA_RB_RESTART</name><category>none</category><severity>warning</severity><ruleEvalResult>true</ruleEvalResult><actionResult>Setting SSA_RB_RESTART=0 will cause RuleBase corruption.Kindly unset this environment variable and restart the IIR server</actionResult>" Update: next code does not need to replace &lt; and &gt; for getting severity: var response="<list><Response><cfgId>903</cfgId><recommendations>&lt;Rule&gt;&lt;name&gt;Env SSA_RB_RESTART&lt;/name&gt;&lt;category&gt;none&lt;/category&gt;&lt;severity&gt;warning&lt;/severity&gt;&lt;ruleEvalResult&gt;true&lt;/ruleEvalResult&gt;&lt;actionResult&gt;Setting SSA_RB_RESTART=0 will cause RuleBase corruption.Kindly unset this environment variable and restart the IIR server&lt;/actionResult&gt; &lt;/Rule&gt;</recommendations></Response><Response><cfgId>903</cfgId><recommendations>&lt;Rule&gt;&lt;name&gt;SSAOPTS (+Ltd) setting&lt;/name&gt;&lt;category&gt;none&lt;/category&gt;&lt;severity&gt;warning&lt;/severity&gt;&lt;ruleEvalResult&gt;true&lt;/ruleEvalResult&gt;&lt;actionResult&gt; Please note that it is not recommended to have SSAOPTS=+Ltd in case of the Production environment.&lt;/actionResult&gt;&lt;/Rule&gt;</recommendations></Response></list>"; var recs=$(response).find("recommendations"); for(var i=0;i<recs.length;i++) { var xml=$("<recommendations>"+$(recs[i]).text()+"</recommendations>"); alert(xml.find("severity").text()); } http://jsfiddle.net/ZpYac/
{ "language": "en", "url": "https://stackoverflow.com/questions/7593441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Which one is better for social networking integration in iOS development? I have searched on net for social networking integration in iOS projects (For example: Facebook, Twitter, etc) I found there are also SDKs available for particulars and some OpenSource projects/frameworks are also available for the same which combines all into one like (ShareKit). What is the difference in those two? Which one is better to use? Is there any problem to upload an app on AppStore which is using ShareKit framework/code? Thanks in advance. Mrunal A: If you are using ARC in your project ShareKit is a big waste of time. Twitter can be added very easily using the Twitter framework and TWTweetComposeViewController. Not sure about any others. A: @mrunal check Socialize out: http://www.GetSocialize.com and see what you think. Full feautre list at http://go.GetSocialize.com/features DROdio A: If you are only looking to use Twitter and Facebook, then it is simple enough to just use their API and implement it in your code. If you are new to development or want to use more (Delicious, Tumblr, Read It Later, Bit.ly, Mail), then I would highly recommend using ShareKit. It allows for sharing of text, URLs and even images. It takes less than an hour to setup even when using ARC and comes with a sample app to play around with. It is also easy to update when more features are added or the API of one the sites changes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ipython and python are handling my string differently, why? In python (2.7.1): >>> x = u'$€%' >>> x.find('%') 2 >>> len(x) 3 Whereas in ipython: >>> x = u'$€%' >>> x.find('%') 4 >>> len(x) 5 What's going on here? edit: including the additional info requested from the comments below ipython >>> import sys, locale >>> reload(sys) <module 'sys' (built-in)> >>> sys.setdefaultencoding(locale.getdefaultlocale()[1]) >>> sys.getdefaultencoding() 'UTF8' >>> x = u'$€%' >>> x u'$\xe2\x82\xac%' >>> print x $â¬% >>> len(x) 5 python >>> import sys, locale >>> reload(sys) <module 'sys' (built-in)> >>> sys.setdefaultencoding(locale.getdefaultlocale()[1]) >>> sys.getdefaultencoding() 'UTF8' >>> x = u'$€%' >>> x u'$\u20ac%' >>> print x $€% >>> len(x) 3 A: @nye17 It's officially not a good idea to ever call setdefaultencoding() (it is removed from sys after first use for a reason). One common culprit is gtk, which causes all kinds of problems, so if IPython has imported gtk, sys.getdefaultencoding() will return utf8. IPython does not set the default encoding itself. @wim can I ask what version of IPython you are using? Part of the major overhaul in 0.11 was fixing many unicode bugs, but more do crop up (mostly on Windows, now). I ran your test case in IPython 0.11, and the behavior of IPython and Python do appear to be the same, so I think this bug is fixed. Relevant values: * *sys.stdin.encoding = utf8 *sys.getdefaultencoding() = ascii *platforms tested: Ubuntu 10.04+Python2.6.5, OSX 10.7+Python2.7.1 As for an explanation, essentially IPython didn't recognize that input could be unicode. In IPython 0.10, the multibyte utf8 input is not being respected, so each byte = 1 character, which you can see with: In [1]: x = '$€%' In [2]: x Out[2]: '$\xe2\x82\xac%' In [3]: y = u'$€%' In [4]: y Out[4]: u'$\xe2\x82\xac%'# wrong! Whereas, what should happen, and what does happen in 0.11, is that y == x.decode(sys.stdin.encoding), not repr(y) == 'u'+repr(x). A: if you do import sys sys.getdefaultencoding() I think you will get different results in python an ipython, possible one ascii, and the other one being utf-8, so it should only be a matter of which default encoding each one is choosing. The other test you can do is to type the following to enfore it as your default locale, import sys, locale reload(sys) sys.setdefaultencoding(locale.getdefaultlocale()[1]) sys.getdefaultencoding() then try the test of x in your question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to convert a .CATDrawing file to .pdf I want to convert a CATIA V5 file to a pdf file using vc++. How can I convert this. Am I use any third party software or dlls in my application for this operation. I am not familiar with CATIA. A: You can do this if you have access to the Catia V5 api and likely and running instance of Catia itself. Otherwise you need Catia CAA RAID which is the full blown C++ api which is $$$. If you have the first, it's only a few lines of code...
{ "language": "en", "url": "https://stackoverflow.com/questions/7593456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add AdMob as item of ListView in Android ? I have a question about Google Admob (referenced libraries GoogleAdMobAdsSdk-4.1.1.jar) . My question : * *I have a ListView about Football and now I want to add Admob as a item of my ListView *For example: * *Item 1 *Item 2 *Item 3 *<---------------Banner Advertisement of google -----> using Admob *Item 4 *Item 5 *Item 6 *<---------------Banner Advertisement of google ------> .......... How to add Admob into ListView as a item of ListView - Does everyone known that. Please help me... Thank you very much ! A: You do that and you are asking to have your account banned... From: http://helpcenter.admob.com/content/policies-tips-developers-publishers The number of ads on a single page should not exceed one if the ad is fixed to the screen top or screen bottom. If the page scrolls, there should be a maximum of one ad on the top and one ad on the bottom, and both ads should not appear on the same page. A: You probably found a solution, but anyway, please check this link http://googleadsdeveloper.blogspot.com/2012/03/embedding-admob-ads-within-listview-on.html it explains how you can display several ads in a listview. You should not show more than one ad per page view; thus, the idea is that, if your regular list can show 8 items per page, then insert your ad every 8th, 16th, 24th... and so on. I hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Java, regular expressions, String#matches(String) I'm used to regular expressions from Perl. Does anybody know why this doesn't work (eg. "yea" isn't printed)? if ("zip".matches("ip")) System.out.println("yea"); Thank you. A: matches() is a complete match; the string has to match the pattern. if ("zip".matches("zip")) System.out.println("yea"); So you could do: if ("zip".matches(".*ip")) System.out.println("yea"); For partial matching you can use the complete regex classes and the find() method; Pattern p = Pattern.compile("ip"); Matcher m = p.matcher("zip"); if (m.find()) System.out.println("yea"); A: The argument to matches() needs to be a fully-formed regular expression rather than just a substring. Either of the following expressions would cause "yea" to be printed: "zip".matches(".*ip.*") "zip".matches("zip") A: Use: if ("zip".contains("ip")) instead of a RegEx in this case. It's faster, since no RegEx-parser is needed. A: Try endsWith instead of matches for your "zip" case. "zip".endsWith("ip"); If you need regex, "zip".matches(".*ip"); http://www.exampledepot.com/egs/java.lang/HasSubstr.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7593466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using git submodule update --init on a post hook I have this simple hook on /hooks/post-update inside a bare repository: #!/bin/sh git-update-server-info GIT_WORK_TREE=/home/user/apps/application-site/dev git checkout -f develop GIT_WORK_TREE=/home/user/apps/application-site/dev git submodule update --init GIT_WORK_TREE=/home/user/apps/application-site/master git checkout -f master GIT_WORK_TREE=/home/user/apps/application-site/master git submodule update --init The repository has some submodules, that I am expecting is pushing to production server, and checkout the two branches on two directories, so can I have later a dev.myapp.com for the development branch and www.myapp.com for the master branch, and all this updating also the submodules on the branches. Checkout is working as expected, but not the submodule update --init, :'( The remote output raises this errors. remote: Switched to branch 'develop' remote: You need to run this command from the toplevel of the working tree. remote: Switched to branch 'master' remote: You need to run this command from the toplevel of the working tree. I am not quite sure what to do. A: The answer is to do exactly what git is telling you, which is: remote: You need to run this command from the toplevel of the working tree. So do that. Here's a sample post-update hook: #!/bin/sh export GIT_DIR=$(pwd) cd /home/lars/projects/stackoverflow/gitstuff/worktree git checkout -f master git submodule init git submodule update This assumes that: * *core.bare is false *receive.denyCurrentBranch is ignore. You need this because otherwise you'll get an error pushing into a repository with core.bare set to false. ...and seems to work in my limited testing. A: Your first GIT_WORK_TREE variable (line 4) is suspect, considering you are refering in the next lines to a $WORK_TREE variable (which isn't defined in this script). Note that starting git1.8.4 (July 2013), you wouldn't have (for git submodule commands) to go back to the root directory anymore. See commit 091a6eb0feed820a43663ca63dc2bc0bb247bbae: submodule: drop the top-level requirement Use the new rev-parse --prefix option to process all paths given to the submodule command, dropping the requirement that it be run from the top-level of the repository. Since the interpretation of a relative submodule URL depends on whether or not "remote.origin.url" is configured, explicitly block relative URLs in "git submodule add" when not at the top level of the working tree. Signed-off-by: John Keeping Depends on commit 12b9d32790b40bf3ea49134095619700191abf1f This makes 'git rev-parse' behave as if it were invoked from the specified subdirectory of a repository, with the difference that any file paths which it prints are prefixed with the full path from the top of the working tree. This is useful for shell scripts where we may want to cd to the top of the working tree but need to handle relative paths given by the user on the command line.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593467", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Trying to Create An Object in ZF but gives Application Error I am New To Zend Framework. However while go through several tutorials I created a model file user.php where I created a class user extends Zend_Db_Table_Abstract and when i create an object of that class in my controller file it gives the application error as follows: Fatal error: Class 'User' not found in /opt/lampp/htdocs/hello_zend/application/controllers/ShowketController.php on line 17 A: You have to load file where the class User is, or autoload all model class. How to do that, You will find answer here: How mvc works in Zend framework
{ "language": "en", "url": "https://stackoverflow.com/questions/7593469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Converting Char array to int/double/float Thx for the help but maybe I should clarify my problem. I want to read some addresses from a text file, for instance: someFile:: 0xc4fap4424ab1 0xac8374ce93ac ... etc Now I want to take these addresses and convert them to decimal so that I can make address comparisons. So my question is 1. How should I go about storing these addresses 2. Once I have stored the addresses, how can I convert them to decimal. A: Your initializer declares just one element for the temp array, and that value is way beyond the capacity of a char. The maximum value that you can store in a single char is 0xFF. If temp was something in the form of: char temp[] = {0x12, 0x34, 0x56, 0x78}; Then you could do some bit twiddling to produce an int out of the 4 bytes. Actually I would use uint32_t to be platform-independent: uint32_t x = (temp[0] << 24) | (temp[1] << 16) | (temp[2] << 8) | temp[3]; Of course, you have to take care of the endianness as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593470", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Settings in ASPxGridView Skins Can you set settings in ASPxGridView skins? For example: <Settings ShowHeaderFilterBlankItems="false" ShowFilterBar="Visible" ShowFilterRow="True" /> This would be very helpfull because all the grids that are using this style would have filter bar and filter row enabled by default. If it is not possible, could you please explain me why? A: Yes, it is possible to specify the ASPxGridView's properties (for all ASPxGridView instances in the corresponding theme) within the skin file: <%@ Register TagPrefix="dx" Namespace="DevExpress.Data" Assembly="DevExpress.Data.vX.Y, Version=X.Y.Z.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" %> <%@ Register TagPrefix="dx" Namespace="DevExpress.Web.ASPxGridView" Assembly="DevExpress.Web.ASPxGridView.vX.Y, Version=X.Y.Z.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" %> <dx:ASPxGridView runat="server"> <Settings ShowHeaderFilterButton="true" ShowHeaderFilterBlankItems="false" ShowFilterBar="Visible" ShowFilterRow="True" /> </dx:ASPxGridView> However, the skin file is intended more for specifying a visual appearance (styles, images, etc).
{ "language": "en", "url": "https://stackoverflow.com/questions/7593477", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: is there some c++ library / source similar to boost program_options but for *keyboard shortcut auto-gen help* ? So, I have some c++ source with key bindings like: switch( keypressed ) { case 'c': cam_handle->Yaw(min_angle ); break; case 'd': cam_handle->Yaw( -min_angle ); break; case 's': cam_handle->Pitch(min_angle ); break; case 'x': cam_handle->Pitch( -min_angle ); break; case 'z': cam_handle->Roll( min_angle ); break; case 'a': cam_handle->Roll( -min_angle ); I always forget what the stupid keys are and have to guess, and they might change, or new keys get added, etc. Is there some fast way to auto-generate help or an "idiot's guide" popup that that says what the short-cuts are? In case someone doesn't know boost::program_options but can answer, here's an example of that: int options(int ac, char ** av, Options& opts) { // Declare the supported options. po::options_description desc("Allowed options"); desc.add_options() ("help", "Produce help message.") ("width,w", po::value<int>(&opts.frameWidth)->default_value(640),"frame width") ("height,h", po::value<int>(&opts.frameHeight)->default_value(480),"frame height") ("port,p", po::value<string>(&opts.port)->default_value("5001"),"port"); po::variables_map vm; po::store(po::command_line_parser(ac, av).options(desc).allow_unregistered().run(),vm); po::notify(vm); if (vm.count("help")) { cout << desc << "\n"; return 1; } return 0; } So, I don't have to "RTFC" to know how to use the executable, I just say "./myapp --help" and boost has nicely auto-generated help and all that. Is there something like this for keyboard shortcut mapping, where the key strokes replace the role of commandline flags? (In C++ that is. In principle C is OK too but I doubt it could be as elegant as the boost stuff. ) A: In my opinion these are two different pairs of shoes. If you like to create and ship documentation about your application I think it might not be the best to make it accessible via a --help option. It might be okay for small programs, but boost::program_options is certainly not the best way to deal with this. If you want to make a --help switch, you have to look up the argc and argv arguments for your main function: int main(int argc, char** argv) { for(int i = 0; i < argc; ++i) { if(std::string(argv[i]) == "--help") { // TODO print usage keys and quit } } ... } I think, the ideal way would be to make the keys configurable and to save the actions with the according keys into a configuration file which gets interpreted in your application. So the user can always see the actions available for your application and can also configure them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Delete html tags in sed or similar I am trying to fetch contents of table from a wepage. I jsut need the contents but not the tags <tr></tr>. I don't even need "tr" or "td" just the content. for eg: <td> I want only this </td> <tr> and also this </tr> <TABLE> only texts/numbers in between tags and not the tags. </TABLE> also I would like to put the first column output like this in a new csv file column1,info1,info2,info3 coumn2,info1,info2,info3 I tried sed to deleted patters <tr> <td> but when I fetch table there are also other tags like <color> <span> etc. so I want is to delete all the tags; in short everything with < and > . A: Original: Mac Terminal REGEX behaves a bit differently. I was able to do this on my Mac using the following example: $ curl google.com | sed 's/<[^>]*>//g' % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 219 100 219 0 0 385 0 --:--:-- --:--:-- --:--:-- 385 301 Moved 301 Moved The document has moved here. $ bash --version GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin14) Copyright (C) 2007 Free Software Foundation, Inc. Edit: Just for clarification sake the origional looked like: $ curl googl.com <HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8"> <TITLE>301 Moved</TITLE></HEAD><BODY> <H1>301 Moved</H1> The document has moved <A HREF="http://www.google.com/">here</A>. </BODY></HTML> Also the annoying curl header can be rid of using the -s option: $ curl -s google.com | sed 's/<[^>]*>//g' 301 Moved 301 Moved The document has moved here. $ A: sed 's/<[^>]\+>//g' will strip all tags out, but you might want to replace them with a space so tags that are next to each other don't run together: <td>one</td><td>two</td> becoming: onetwo. So you could do sed 's/<[^>]\+>/ /g' so it would output one two (well, actually one two). That said unless you need just the raw text, and it sounds like you are trying to do some transformations to the data after stripping the tags, a scripting language like Perl might be a more fitting tool to do this stuff with. As mu is too short mentioned scraping HTML can be a bit dicey, using something that actually parses the HTML for you would be the best way to do this. PHPs DOM API is pretty good for these kinds of things.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593481", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Facebook Fan Page Id in associated Facebook App I am developing a facebook application which required to get below information while load. * *Facebook Fan Page URL / Id on which the application has been added. *If the user who is accessing this application from specific page is admin of that page or not. I am developing this application in ASP.Net and I am using Facebook Graph API. Any help is highly appreciated. A: Let me share some insights Firstly, I would strongly suggest that you use Microsoft's Facebook C# SDK instead of using plain calls in your .NET project. Steps With the current API, you can do this in your ADMIN Page * *Ask the user to connect and ask for manage pages permission (manage_page) *with the permisions to manage the pages, you can easily fill up a dropdown with all pages that the user have *Ask the user to add your app to it's own page as a tab using http://facebook.com/add.php?api_key=[API_KEY]&pages=1&page=[PAGE_ID] Now that you have your app running on the user page, you need a way to check if that page is running inside Facebook as a Tab or not, and what's the Page Id that is running from. * *In your App Tab Url page that you specified, ask for the signed_request and verify the Data as it has the ["page"]["id"] that you need so you can check against the saves Page_Id that you should have saved on the ADMIN area when your user adds your app to it's facebook page. I hope this helps. Code To login and request all user pages: <select class="facebook-page-list" disabled="disabled"> <option>Facebook pages</option></select> <script> <!-- FB.init({ appId: 'API_KEY', cookie: true, status: true, xfbml: true }); FB.api('/me', function (user) { if (user != null) { if (user.error) { $(".fb-login").show(); } else { // example from Facebook var image = document.getElementById('image'); image.src = 'https://graph.facebook.com/' + user.id + '/picture'; var name = document.getElementById('name'); name.innerHTML = user.name // get all user Pages facebookGetPages(); } } }); function facebookGetPages() { FB.getLoginStatus(function (response) { if (response.session) { access_token = response.session.access_token; FB.api( { method: 'fql.multiquery', access_token: access_token, queries: { query1: 'select page_id from page_admin where type <> "APPLICATION" and uid = ' + response.session.uid, query2: 'select page_id, name, page_url from page where page_id in (select page_id from #query1)' } }, function (queries) { if (queries.error_msg) alert(queries.error_msg); else { pages = queries[1].fql_result_set; $(".facebook-page-list").empty(); for (i = 0; i < pages.length; i++) $(".facebook-page-list").append("<option value='" + pages[i].page_id + "'>" + pages[i].name + "</option>"); $(".facebook-page-list").attr("disabled", false); } }); } else { // no user session available, someone you dont know } }); } //--> </script> To get the Page ID from your app: ViewBag.signed_request = "can't get id"; dynamic signed_request = FacebookWebContext.Current.SignedRequest; if(signed_request != null) { ViewBag.signed_request = signed_request.Data.page.id; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7593484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How avoid the screen move when focus the input box in mobile safari? Focus the input box in iPhone caused the viewport change. How to avoid this?
{ "language": "en", "url": "https://stackoverflow.com/questions/7593485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Error in using ListView in ListActivity I am having trouble using ListActivity. If i change class extend from ListActivity to Activity it works fine. But then the trouble is how will i implement the onListItemClick. It muight be some small mistake i might have done but i am not able to trace it. public class Warehouse extends ListActivity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); System.out.println("Inside Warehouse"); setContentView(R.layout.warehous); LinearLayout linear = (LinearLayout) findViewById(R.id.linearfullview); drawable = setBitMap(background_image); linear.setBackgroundDrawable(drawable); String[] names = new String[] { "Inventory Ageing", "Inventory Carring Cost", "Inventory Turns" }; LinearLayout linearList = (LinearLayout) findViewById(R.id.linearlist); drawable = setBitMap(list_image); linearList.setBackgroundDrawable(drawable); this.setListAdapter(new ArrayAdapter<String>(this,R.layout.warehouse_list,names)); // ListView lv = getListView(); lv.setTextFilterEnabled(true); } public Drawable setBitMap(String imagename) { Bitmap image = BitmapFactory.decodeStream(getClass() .getResourceAsStream(("/com/image/" + imagename + ".png"))); drawable = new BitmapDrawable(image); return drawable; } protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); Object o = this.getListAdapter().getItem(position); String keyword = o.toString(); } } } <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="fill_parent" android:orientation="horizontal" android:layout_width="fill_parent"> <LinearLayout android:layout_width="fill_parent" android:id="@+id/linearfullview" android:layout_height="400sp" android:layout_alignParentTop="true" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="180sp" android:layout_alignParentBottom="true" android:layout_marginTop="20sp"> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id = "@+id/linearlist" android:layout_height="wrap_content" android:layout_width="wrap_content" android:paddingLeft="2dp" android:paddingRight="2dp" android:gravity="bottom" android:layout_marginTop="30dp"> <ListView android:id="@android:id/list" android:layout_width="100dip" android:layout_height="wrap_content"></ListView> </LinearLayout> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:layout_width="wrap_content" android:paddingLeft="2dp" android:paddingRight="2dp" android:paddingTop="4dp" android:gravity="bottom" android:layout_marginTop="30dp"> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:id="@+id/linearFirst" android:layout_alignParentLeft="true" android:layout_width="wrap_content" android:paddingLeft="2dp" android:paddingRight="2dp" android:paddingTop="4dp" android:gravity="bottom" android:layout_marginTop="30dp" android:visibility="invisible"> <com.widget.WheelView android:id="@+id/firstWheel" android:layout_height="wrap_content" android:layout_width="100dp" /> </LinearLayout> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:id="@+id/linearSecond" android:layout_width="wrap_content" android:paddingLeft="2dp" android:paddingRight="2dp" android:layout_alignParentRight="true" android:paddingTop="4dp" android:gravity="bottom" android:layout_marginTop="30dp" android:visibility="invisible"> <com.widget.WheelView android:id="@+id/secondWheel" android:layout_height="wrap_content" android:layout_width="100dp" /> </LinearLayout> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:id="@+id/linearThird" android:layout_width="wrap_content" android:paddingLeft="2dp" android:paddingRight="2dp" android:paddingTop="4dp" android:gravity="bottom" android:layout_marginTop="30dp" android:layout_alignParentLeft="true" android:visibility="invisible"> <com.widget.WheelView android:id="@+id/thirdWheel" android:layout_height="wrap_content" android:layout_width="200dp" /> </LinearLayout> </RelativeLayout> </LinearLayout> </RelativeLayout> A: if you are extending ListActivity then you must take a Listview in main.xml with @+android:id/list <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="fill_parent" android:orientation="horizontal" android:layout_width="fill_parent"> <ListView android:id="@android:id/list" android:layout_width="match_parent" android:layout_height="match_parent" /> ... A: Can you use public class Warehouse extends Activity implements onListItemClick instead ? A: refer http://www.vogella.de/articles/AndroidListView/article.html link. There is a minor mistake ur making Best of Luck...
{ "language": "en", "url": "https://stackoverflow.com/questions/7593491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: A shell script to read a text file and then run a java program I have a java program that stops often due to errors which is logged in a .log file. What can be a simple shell script to detect a particular text line say stream closed and then run the following command java -jar xyz.jar A: Here's a bash script to do something like that (may contain typos): #!/bin/bash tail -f logfile.txt | grep "stream closed" | while read line do java -jar xyz.jar done A: if grep 'stream closed' filename.log >/dev/null then java -jar xyz.jar fi A: T1="`cat youfile.log | grep 'stream closed'`" if [ "$T1" = "stream closed" ]; then java -jar xyz.jar fi
{ "language": "en", "url": "https://stackoverflow.com/questions/7593495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: mysql load data infile permission issue I am using the following query to load into mysql: LOAD DATA INFILE '/var/www/vhosts/httpdocs/xml/insert_feeds.csv' INTO TABLE `deals_items` FIELDS TERMINATED BY '@##!@#' OPTIONALLY ENCLOSED BY '' ESCAPED BY '' LINES TERMINATED BY '@##%@#' IGNORE 1 LINES (@id,dealID,shopid,categoryid,title,permalink,url,startDate,endDate,description,extract,price,previous_price,discount,purchases,image,@location,@lat,@lng,locationText,type,settings,active) SET id = '', lat=@lat, lng=@lng, locationText=@location, location = GeomFromText(CONCAT(POINT(@lat,@lng))) Now this used to work just fine, but ever since an mysql was upgraded from 5.0 to 5.1 it stopped working. It now works only if I add the LOCAL to the statement. The error I'm getting is Can't get stat of /var/www/vhosts/httpdocs/xml/insert_feeds.csv The user was granted with full permissions to test it and the file was given 0777. It won't work from any client (mysql,mysqli,pdo and console). Adding the local solves all problems but there is a lot of queries and I cannot go on and change them all. Further more, as I understand from the manual there are security issues with the LOCAL command. The exact mysql version is 5.1.58-1~dotdeb.0 and the client version 5.0.51a
{ "language": "en", "url": "https://stackoverflow.com/questions/7593498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Comet WEb server implementation I recently asked one question :- Handle Web Server with multiple clients I have gone through the basic techniques to implement comet server like streamhub,Maven/Jetty etc. I have following questions for that : * *After that I found the issues like in case of Maven/Jetty internet connection is required for downloading certain files from net.So it it possible to implement it if no internet connection is there on machine where the web server is hosted ? *Also I want the open source tools/technologies to achieve the thing mentioned in the above question. and I think stream hub is not a open source free version. Please help if you know any tool which is free/open source to use. *Currently the web application is running on apache web server. so if I use comet server what changes I need to do in that ?? Please help... Thanks in advance... A: For comet, pick a server which can handle many open connections. For a chat app I implemented which currently handles 10k open connections, I used Mochiweb. You might want to give that a look. Going along the Mochiweb path, I will also recommend Erlang for implementing you server. It will be a small piece of code. Basically, you will listen on a path and hold the connection open till you have some data to respond with or timeout. On the client side, you would write a simple JS function which will make an AJAX call and handle response timeout and data responses as and when they come. Nothing too different here. However, you may need JSONP instead (crossdomain/subdomain because of different servers for web and long poll), so ensure that your LongPoll server replies accordingly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: He!p with SimpleXML for $response in PHP I am sending a XML to a webserver using PHP, and the server returns an XML response. I need help parsing values from the response! I have read the SimpleXML instructions, but my understanding is that all those are only for when XML data is already created, but needs to be parsed. This is my PHP script so far: <?php $ch = curl_init("http://api.online-convert.com/queue-insert"); $count = $_POST['count']; $file = "testdoc2.txt"; $fh = fopen( $file, 'w' ); $carriageReturn = "\n"; fwrite( $fh, $count ); fclose( $fh ); $request["queue"] = file_get_contents($count); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $request); $response = curl_exec($ch); curl_close ($ch); echo $response; $xmlstr = simplexml_load_string($response); $file = "testdoc.txt"; $fh = fopen( $file, 'w' ); $carriageReturn = "\n"; fwrite( $fh, $xmlstr); fclose( $fh ); ?> The XML response that needs to be parsed is this: <?xml version="1.0" encoding="utf-8"?> <queue-answer> <status> <code>0</code> <message>Successfully inserted job into queue.</message> </status> <params> <downloadUrl>http://www.online-convert.com/result/35f6ddbcc2ca58e7e98addc7c2efd6eb</downloadUrl> <hash>35f6ddbcc2ca58e7e98addc7c2efd6eb</hash> </params> </queue-answer> I just need to extract the value and show it to the user. I am an iPhone developer. A: You can parse the XML file using this $xml=simplexml_load_string($response); foreach($xml->children() AS $child) { echo $child->getName().”:”.$child.”<br/>”; } You can put an if condition and extract the required message only. A: You first have to create the request xml document and send it to the server, e.g. (without error handling et al and without testing because of missing api key): $request = new SimpleXMLElement('<queue><apiKey/><targetType/><targetMethod/><testMode/><sourceUrl/></queue>'); $request->apiKey = 'abcdefghijklmnopqrstuvwx'; $request->targetType = 'image'; $request->targetMethod = 'convert-to-jpg'; $request->testMode = 'false'; $request->sourceUrl = 'http://whatever'; $ch = curl_init("http://api.online-convert.com/queue-insert"); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, array('queue'=>$request->asXml())); $response = curl_exec($ch); // TODO: might want to test the response code here, see curl_get_info/CURLINFO_HTTP_CODE curl_close ($ch); then you need to parse the response $queueAnswer = simplexml_load_string($response); echo 'status code:', $queueAnswer->status->code; // in case of success you should be able to access the values via echo ' url:', queueAnswer->params->downloadUrl; echo ' hash:', queueAnswer->params->hash;
{ "language": "en", "url": "https://stackoverflow.com/questions/7593505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I install XCode in a different location than the default? For the life of me, I cannot figure this out. All the installer seems to let me do is choose between my two hard drives, and there is no option to select a directory on the hard drive. I have seen the similar question here, but this doesn't help me: Install Xcode 4 and keep Xcode 3? I just don't see a dropdown or option of any kind to change the installation directory. Any help? A: Check this post out. U can see here how to change the directory.. Hope it helps. Install Multiple xcodes
{ "language": "en", "url": "https://stackoverflow.com/questions/7593506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to create, start, resume, pause, stop, destroy android activity during testing I wish to capture data from the views in the activity, then pause it, then resume it and ensure that the data has not changed. I tried calling Activity#onPause() in ActivityInstrumentationTestCase2#setUp() but I get an error. A: press back button, press home button, and keep other applications open for some time. most of them you asked for will be called.. and calling those methods explicitly is a wrong move.
{ "language": "en", "url": "https://stackoverflow.com/questions/7593511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Efficient way to update column with arithmetic sequence of numbers after delete operation I have a PresentationSlide table: PresentationSlide PresentationSlideId PresentationId Content Order and example rows: +---------------------+----------------+---------+-------+ | PresentationSlideId | PresentationId | Content | Order | +--------+------------+----------------+---------+-------+ | 123 | 3 | "bla" | 1 | | 23 | 3 | "bla2" | 2 | | 22 | 3 | "bla3" | 3 | | 100 | 3 | "bla4" | 4 | | 150 | 3 | "bla5" | 5 | +---------------------+----------------+---------+-------+ I want to maintain arithmetic sequence of numbers (1,2,3,4,...) in the Order column after DELETE operation. For example, if I delete third row (PresentationSlideId = 22), values in order column will be: (1,2,4,5) I want to update Order this way: PresentationSlideId = 100: update order from 4 to 3 PresentationSlideId = 150: update order from 5 to 4 How is the most efficient way to do this kind of update? Is any way to do this with using only one UPDATE statement? I could do this using cursor and loop, but it doesn't seems efficient. A: ;with C as ( select [Order], row_number() over(order by [Order]) as rn from PresentationSlide ) update C set [Order] = rn A: 1) Order is a very poor name for a column, since it's an SQL Keyword 2) It would be a lot better if you could cope with gaps in the order (and possibly switch to using a float, so you can insert fractional values), because in your current model, every insert, update or delete is potentially going to affect the entire table. This doesn't scale well. Computing an order using ROW_NUMBER() during selects would generally be better. 3) create table #PresentationSlide ( PresentationSlideID int not null, PresentationId int not null, Content varchar(10) not null, [Order] int not null ) insert into #PresentationSlide (PresentationSlideId , PresentationId , Content , [Order]) select 123,3,'bla',1 union all select 23,3,'bla2',2 union all select 22,3,'bla3',3 union all select 100,3,'bla4',4 union all select 150,3,'bla5',5 delete from #PresentationSlide where PresentationSlideId = 22 ;With Reorder as (select PresentationSlideId,ROW_NUMBER() OVER (ORDER BY [Order]) as NewOrder from #PresentationSlide) update ps set [Order] = NewOrder from #PresentationSlide ps inner join Reorder r on ps.PresentationSlideId = r.PresentationSlideId select * from #PresentationSlide order by [Order] drop table #PresentationSlide
{ "language": "en", "url": "https://stackoverflow.com/questions/7593513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: c# failed to upload video This is my code to upload video on server protected void Button1_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) { string fileName = FileUpload1.FileName; string fileExtension = Path.GetExtension(fileName); if (fileExtension == ".flv") { if (!File.Exists(Path.Combine(Server.MapPath("~/Video"), fileName))) { string fullFileName = Path.Combine(Server.MapPath("~/Video1"), fileName); FileUpload1.SaveAs(fullFileName); Label1.Text = "The file has been uploaded"; } else { Label1.Text = "The file already exist! You must delete old version first in order to upload new version"; } } else { Label1.Text = "The file format is not allow"; } }//else if else { Label1.Text = "please select a file to upload"; } } Everything is goes well, but when I upload a .FLV file, It returns me an error message on webpage,here is the error code Output: Error 101 (net::ERR_CONNECTION_RESET): The connection was reset. How can I solve this problem? A: Maybe you are trying to upload a file larger than 4MB which is the default maximum allowed size. You may try increasing it in the web.config: <system.web> <!-- Set the maximum upload file size to 100MB --> <httpRuntime executionTimeout="240" maxRequestLength="102400" /> </system.web> A: Generally, I set below code into my project.. <system.web> <httpRuntime maxRequestLength="102000" executionTimeout="110"/> </system.web> But if you extend than... The 4MB default is set in machine.config, but you can override it in you web.config. For instance, to expand the upload limit to 20MB, you'd do this: <system.web> <httpRuntime executionTimeout="240" maxRequestLength="20480" /> </system.web
{ "language": "en", "url": "https://stackoverflow.com/questions/7593514", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }