text
stringlengths
8
267k
meta
dict
Q: Pixbuf overlapping / merge Is there a way to overlap (but not overwrite) two gtk.gdk.Pixbuf in a gtk.IconView ? For example, I've a cell with this pixbuf image : http://www.pirates-caraibes.com/media/zone/AnimMer.gif I want to add this image : http://www.pirates-caraibes.com/media/objet/plage-coin-test12.gif to the cell, on the previous image (in order to display the previous image by transparency). How i can to do this ? Thanks Edit : I've seen the gtk.gdk.Pixbuf.composite method but it doesn't have a src argument, like the gdk_pixbuf_composite() C function ( http://developer.gnome.org/gdk-pixbuf/unstable//gdk-pixbuf-Scaling.html#gdk-pixbuf-composite ) A: You can do it with the old GDK drawing API, but it disappeared in GTK 3. What works in both GTK 2 and 3 is to use the cairo API for that. http://developer.gnome.org/gdk/stable/gdk-Cairo-Interaction.html http://cairographics.org/samples/ What adds the transparency is called the "alpha" channel, which stands next to RGB channels. This means you need to make sure you're drawing to a ARGB cairo surface. A: As I mentionned above (in comment), I finally found the answer in the PyGTK FAQ.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Customized list in C# I want to create customized list in c#. In my customized list I want only create customized function Add(T), other methods should remain unchanged. When I do: public class MyList<T> : List<T> {} I can only overide 3 functions: Equals, GetHashCode and ToString. When I do public class MyList<T> : IList<T> {} I have to implement all methods. Thanks A: When I do public class MyList : IList {} I have to implement all methods. Yes, but it's easy... just send the call to the original implementation. class MyList<T> : IList<T> { private List<T> list = new List<T>(); public void Add(T item) { // your implementation here } // Other methods public void Clear() { list.Clear(); } // etc... } A: You can have MyList to call List<T> implementation inetrnally, except for Add(T), you'd use Object Composition instead of Class Inheritence, which is also in the preface to the GOF book: "Favor 'object composition' over 'class inheritance'." (Gang of Four 1995:20) A: You can another thing again, by using new keyword: public class MyList<T> : List<T> { public new void Add(T prm) { //my custom implementation. } } Bad: The thing that you're restricted on use only of MyList type. Your customized Add will be called only if used by MyList object type. Good: With this simple code, you done :) A: You could use the decorator pattern for this. Do something like this: public class MyList<T> : IList<T> { // Keep a normal list that does the job. private List<T> m_List = new List<T>(); // Forward the method call to m_List. public Insert(int index, T t) { m_List.Insert(index, t); } public Add(T t) { // Your special handling. } } A: Use a private List<T> rather than inheritance, and implement your methods as you like. EDIT: to get your MyList looped by foreach, all you want is to add GetEnumerator() method
{ "language": "en", "url": "https://stackoverflow.com/questions/7545064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to print in VB? I have a web application build using classic ASP and VB. How do I print a document from within the back end VB code? Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click End Sub What i am trying to do is get user to click on button a letter is generated and sent to printer? A: You could use the window.print javascript function which will open the print dialogon the client browser allowing him to choose the printer and print the page: Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click ClientScript.RegisterStartupScript([GetType](), "print", "window.print();", true) End Sub As a side note, what you have is not a classic ASP application with VB, you have a classic ASP.NET WebForms application using VB.NET as a code behind. UPDATE: As requested in the comments section here's how you could write a generic handler which will dynamically generate the HTML you would like to print: Imports System.Web Imports System.Web.Services Public Class Print Implements System.Web.IHttpHandler Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest context.Response.ContentType = "text/html" context.Response.Write("<html><body onload=""window.print();""><table><tr><td>value1</td><td>value1</td></tr></table></body></html>") End Sub ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable Get Return False End Get End Property End Class Now simply navigate to /Print.ashx. A: you could look into some reports frameworks like CrystalReports (used to come with VS but you have to download it from SAP nowadays. Here is a nice tutorial for the report-engine that comes packed into Visual Studio (I have to admit I don't have much experience with this but it looks fine to me): Creating an ASP.NET Report
{ "language": "en", "url": "https://stackoverflow.com/questions/7545065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: android socket communication through internet I'm experimenting with socket communication between android and windows. Everything works fine till i use the 10.0.2.2 address which is the loopback to the computer on which the emulator is running. But if i give any other address to the Socket constructor the connection is timing out. My goal is to communicate between my phone and my computer through the internet. I also tried it on my phone, so i don't think that it's a firewall problem. Here is my code: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { clientSocket = new Socket("10.0.2.2", 48555); Log.d("Offdroid", "socket connected"); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(e.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(e.toString()); } } public void connectServer(View button) { try { String message = "shutdown"; byte[] messageBytes = message.getBytes("US-ASCII"); int messageByteCount = messageBytes.length; byte[] messageSizeBytes = new byte[2]; messageSizeBytes = intToByteArray(messageByteCount); byte[] sendBytes = concatenateArrays(messageSizeBytes, messageBytes); Log.d("Offdroid", Integer.toString(messageSizeBytes.length)); clientSocket.setReceiveBufferSize(16); clientSocket.setSendBufferSize(512); OutputStream outStream = clientSocket.getOutputStream(); //InputStream inStream = clientSocket.getInputStream(); outStream.write(sendBytes, 0, sendBytes.length); } catch(Exception EX) { Log.e("Offdroid", EX.getMessage()); } } I'm also looking for a java built in function instead of the concatenateArrays function which simply put two byte array together. Edit: Sorry, maybe i not provided enough information. I have already tried my external ip used for the internet connection and my LAN ip. Port on router is forwarded to my computer. So if i write "192.168.1.101" or the ip given by the internet service provider in place of "10.0.2.2", than i cannot connect. Edit: Ok, i figured out it was my firewall. A: Emulator takes uses the same network as that of your computer, so it will be able to route it to the computer. But for your phone to connect with your computer, you have to give a different IP, which is basically the IP of the computer. I am guessing you are using some shared Network, and getting this (10.0.2.2) IP. Your computer should be directly connected to Internet in order for this to work from phone. A: Ok, i figured out it was my firewall. A: When you use a real Android phone as Internet Remote device, don't you have to set up your WiFi router, connected to your PC (or Android), for Port Forwarding? Then you give your Android Client the PC Server's External IP Address and the Server Port Number. Only then, provided the Port Forwarding works on the router, your remote Android Client (on SIM) can communicate with your PC Server connected to your router.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: I've monkey patched after_commit so it works with my test, but it doesn't work on Jenkins I use an after_commit filter in several places in my code. In order to get my cucumber tests working, I had to use a patch - http://outofti.me/post/4777884779/test-after-commit-hooks-with-transactional-fixtures It works fine locally both when run standalone or under Autotest. I also try to run the tests under Jenkins but almost all the tests fail with the following error message. can't dump File (TypeError) /var/lib/jenkins/.rvm/rubies/ree-1.8.7-2011.03/lib/ruby/1.8/monitor.rb:242:in `synchronize' ./features/support/after_commit_monkey_patch.rb:20:in `transaction' ./features/support/after_commit_monkey_patch.rb:18:in `transaction' Can anyone help me figure out what's going on? I'm confused why the same code works in one situation but not another. The environments are as identical as possible using RVM etc. Thanks, Graeme A: After a bit of searching (and thanks to Andy for the clue) it didn't have anything to do with the monkey-patch - it was just reporting the problem. I had the cache for testing set to ... config.cache_store = nil I changed it to ... config.cache_store = :dalli_store, { :namespace => "TEST" } ... instead and it works without fault now. It still doesn't explain why my tests work locally but didn't under Jenkins with a nil cache. A: turned this patch into a gem test after_commit to have a common ground for improvements and to add tests to see it works on all rails versions
{ "language": "en", "url": "https://stackoverflow.com/questions/7545067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Last rule in mod_rewrite returns 404 even though page exists I have the following in my .htacccess file: RewriteBase / ErrorDocument 404 /404.php Options +FollowSymlinks RewriteEngine on RewriteRule ^news/([a-zA-Z]+)/([0-9]+)-([a-zA-Z]+) /news/view-article.php?category=$1&id=$2&title=$3 [NC] RewriteRule ^news/most-viewed/([a-zA-Z]+)/([0-9]+)-([a-zA-Z]+) /news/view-article.php?category=$1&id=$2&title=$3 [NC] RewriteRule ^news/categories/([a-zA-Z]+) /news/categories/view-category.php?category=$1 [NC] Everything works apart from the last rule. I have checked that all the pages exist, the newly added rule follows the same structure as the rules above which work, confused. Do the variables need changing? Am I missing some code? RESOLVED: RewriteBase / ErrorDocument 404 /404.php Options +FollowSymlinks RewriteEngine on RewriteRule ^news/categories/?$ /news/categories.php [NC] RewriteRule ^news/most-viewed/?$ /news/most-viewed.php [NC] RewriteRule ^news/categories/([a-zA-Z]+)/?$ /news/view-category.php?category=$1 [NC] RewriteRule ^news/categories/([a-zA-Z]+)/([0-9]+)-([a-zA-Z]+) /news/view-article.php?category=$1&id=$2&title=$3 [NC] I was missing the $ on the end. A: Try this, and let me know if that works RewriteBase / ErrorDocument 404 /404.php Options +FollowSymlinks RewriteEngine on RewriteRule ^news/([a-zA-Z]+)/([0-9]+)-([a-zA-Z]+)/?$ /news/view-article.php?category=$1&id=$2&title=$3 [NC,L] RewriteRule ^news/most\-viewed/([a-zA-Z]+)/([0-9]+)-([a-zA-Z]+)/?$ /news/view-article.php?category=$1&id=$2&title=$3 [NC,L] RewriteRule ^news/categories/([a-zA-Z]+)/?$ /news/categories/view-category.php?category=$1 [NC,L]
{ "language": "en", "url": "https://stackoverflow.com/questions/7545071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: App freeze while Schedule LocalNotifications in background - (void)applicationDidEnterBackground:(UIApplication *)application { for (int i =0; i<30; i++){ //add a local notification and schedule it } } when app switch to background, these codes will freeze app in a while. A: There's no document about UIApplication is thread safe or not. After a long time test I found most time execute LocalNotification on background works well. but some times it just crash our app. So it seems like all the class with 'UI' prefixed are not thread safe and you should never invoke there's methods on another thread. And my solution is reduced the number of LocalNotification, it still freeze app in a bit, but we thing we can accept this little freeze. A: By default, application processing freezes when the app goes to the background. The execution continues from the same statement where it left when the app comes back to the foreground. To execute code in the background, you have to surround it in the beginBackgroundTaskWithExpirationHandler block. Have a look at the section Completing a Finite-Length Task in the Background at http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/BackgroundExecution/BackgroundExecution.html.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545073", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do i password protect a page in refinery cms? Basically i am trying to set up a password for a single page in refinery. Is there an extension which can do such a thing for me automatically or should i override internal parts? Thanks in advance. A: There is no way to do this with a default install of Refinery, you'll have to write an engine or override some internal methods/before filters to do this. Unpack the refinerycms-core gem and look at the crud.rb file, where all the crudify methods are generated. It should help shed some light on what you'll need to do to make this happen. Or look here: https://github.com/resolve/refinerycms/blob/master/core/lib/refinery/crud.rb
{ "language": "en", "url": "https://stackoverflow.com/questions/7545075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Conditionally resetting input element value before submitting form to MVC3 action this is probably a simple question but I'm new to jQuery with MVC3. I have an MVC3 application where an Index action lists some papers with their authors. Users can filter the list by (among other parameters) author name, so I have an input element using jQueryUI autocomplete to let them type some letters and pick the desired author. When this happens my JS code stores its ID into a hidden element and posts the form; the ID is then passed via the model binder to an object representing all my filters. The filters object is like: public sealed class PaperFilter { public int? AuthorId { get; set; } // ... other params here } The controller action receives page number and sort parameters (the view uses the MvcContrib grid) and this filter. It then creates a view model including the list of papers and a number of properties representing the filter properties, and passes it back to the view: public ViewResult Index(int? page, GridSortOptions sort, PaperFilter filter) { var papers = _repository.GetPapers(filter); if (sort.Column != null) papers = papers.OrderBy(sort.Column, sort.Direction); ViewBag.Sort = sort; PaperIndexModel model = new PaperIndexModel(filter) { Papers = papers.AsPagination(page ?? 1, 10) }; if (filter.AuthorId.HasValue) { Author author = _repository.GetAuthor((int)filter.AuthorId); model.AuthorName = author.FirstName + " " + author.LastName; } return View(model); } where the returned model contains the papers list together with a copy of the filter properties. The view form relevant code is: ... @Html.TextBoxFor(m => m.AuthorName) @Html.HiddenFor(m => m.AuthorId) ... and its JS code: <script type="text/javascript"> $(function () { $("#AuthorName").autocomplete({ source: function (request, response) { $.ajax({ url: "/Author/FindAuthor", type: "POST", dataType: "json", data: { LastName: request.term }, success: function (data) { response($.map(data, function (item) { return { label: item.FirstName + ' ' + item.LastName, value: item.LastName, id: item.Id }; })); } }); }, select: function (event, ui) { $("#AuthorName").val(ui.item.value); $("#AuthorId").val(ui.item.id); $(this).closest("form").submit(); } }); }); </script> This works fine, anyway I'd like my users to reset the author filter by simply clearing the input box (AuthorName) and pressing enter; but to do this I'd need to reset the AuthorId value, i.e. do something like $("#AuthorId").val("") before the form is posted. I tried to do this on keypress but it does not seem to fire before the post happens, because my action still gets the filter with its AuthorId populated. Could anyone suggest a solution? A: check it right before your .ajax() call. If the length is 0 you don't have to .ajax either and just return.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL default charset and collation I am installing MySQL server on FreeBSD. My current port version is 5.5.15 on FreeBSD 7.2. I am wondering how to get it installed with different than latin1 default charset and collation. Currently when I install it with default Makefile I get this: | character_set_client | latin1 | character_set_connection | latin1 | character_set_database | latin1 | character_set_filesystem | binary | character_set_results | latin1 | character_set_server | latin1 | character_set_system | latin1 | character_sets_dir | /usr/local/share/mysql/charsets/ | collation_connection | latin1_swedish_ci | collation_database | latin1_swedish_ci | collation_server | latin1_swedish_ci I can't understand why latin1 is the default charset in the first place, but well, probably not the best place to discuss it. Anyway... I'd like to change the default charsets to utf8 and collation to utf8_unicode_ci. I tried changing Makefile and added following lines to CMAKE_ARGS: -DWITH_CHARSET="utf8" \ -DWITH_COLLATION="utf8_unicode_ci" All that got changed was character_set_system to utf8. How do I change all of those? Could be a compilation param (preferrably) or my.cnf setting. Will appreciate any help. A: Go ahead and install with the wrong defaults, and later change the settings when creating a /etc/my.cnf file. [mysqld] collation_server = utf8_general_ci character_set_server = utf8 A: This website below explains is quite well. http://rentzsch.tumblr.com/post/9133498042/howto-use-utf-8-throughout-your-web-stack
{ "language": "en", "url": "https://stackoverflow.com/questions/7545084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Continuous form selection deselected on command button click I have a continuous access form with record selectors enabled. Here's the code for the btnPrintReceipt click event handler. I want it to get the ReceiptID of each selected record and open the report with those id's. The problem is, when you click the command button, it deselects all the records (I see it happen) and only keeps the top one available. Private Sub btnPrintReceipt_Click() 'Build filter string containing all selected receipt ids Dim FilterString As String 'Move to first record Dim rsReceipts As Recordset Set rsReceipts = Me.RecordsetClone rsReceipts.Move Me.SelTop - 1 'Cycle through and record Dim i As Integer For i = 0 To Me.SelHeight FilterString = FilterString & "([ReceiptNumber]=" & rsReceipts![ReceiptNumber] & ") OR " rsReceipts.MoveNext Next 'Remove trailing or Dim NewStringLenth As Integer NewStringLenth = Len(FilterString) - 4 If NewStringLenth > 0 Then FilterString = Left(FilterString, NewStringLenth) Else FilterString = "" End If 'Open the report DoCmd.OpenReport "rptReceipt", acViewPreview, "", FilterString End Sub A: Microsoft has a fairly long article on How to enumerate selected form records in Access 2000, which will also work with later versions. The article includes code for running on a command button.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Three20 horizontal gradient How can I make horizontal gradient for TTStye? - (TTStyle *) myStyle: (UIControlState)state { return [TTShapeStyle styleWithShape:[TTRectangleShape shape] next: [TTLinearGradientFillStyle styleWithColor1:RGBCOLOR(60, 60, 60) color2:RGBCOLOR(30, 30, 30) next:nil]]; } makes Vertical gradient. Maybe there is some tutorial on Three20 TTStyle's? A: Done by copy-past code from TTLinearGradientFillStyle. Several lines changed for achieve horizontal gradient.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545087", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How exactly does the modal variable in Java Dialogs work? In the JavaDocs for Dialog(Dialog,String,modal) it says the following: modal - if true, dialog blocks input to other app windows when shown If I understand correctly, if I pass a true argument to the constructor of a Dialog, will it just pause all the program until the user gives some kind of input to the application using this dialog? For example suppose that we have this function in a class and a JDialog called test. public void function(){ /*line*/ test t = new test(null, true); while(true){ System.out.println("print stuff"); } } If I call this function, it will pause, at line, then since the initial dialog is empty, if for example I close the dialog, then the while loop will be executed. Is the phrase "the program pauses until the user gives an input using the dialog" is a somewhat correct description of what the modal variable is useful for? A: Its partially correct, but. But it isn't enough to call teh constructor, but you need to show the dialog after the constructor like this: t.setVisible(true); and yes, after this, the while loop does not start till the dialog isn't closed ( setVisible(false) )
{ "language": "en", "url": "https://stackoverflow.com/questions/7545092", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Inserting data doesn't replicate into database I have a written a sample code to insert data into a table and it says successfully inserted, but when I see the data in database in the database explorer, table shows nothing. When I try to retrieve the data, it prints those values. Still I don't find any records in Visual Studio server explorer. I have tried to google this problem, and I found another database in debug folder which replicates those results. When I delete that database, I'm stuck with a "connection failed" error. this is sample code: DomainId_connection = openConnection(); cmd = new SqlCeCommand("INSERT INTO Temp_Table_(Id,StartTime) values(@Id ,@StartTime)"); cmd.Parameters.Add("@Id", SqlDbType.Int, 4); setDomainId_cmd.Parameters.Add("@StartTime", SqlDbType.DateTime, 8); cmd.Parameters["@Id"].Value = Id; cmd.Parameters["@StartTime"].Value = DateTime.Now; cmd.Connection = setDomainId_connection; if (cmd.ExecuteNonQuery() > 0) { Console.WriteLine("Domain id stored"); } closeConnection(setDomainId_connection); Can someone help me making this work? A: Don't share connection, use connection pooling, use using blocks, and many more: using (SqlConnection connection = new SqlConnection(connectionString)) using (SqlCommand command = connection.CreateCommand()) { command.CommandText = commandText; command.Parameters.Add("@Id", SqlDbType.Int, 4).Value = id; command.Parameters.Add("@StartTime", SqlDbType.DateTime, 8).Value = DateTime.Now; if (!(cmd.ExecuteNonQuery() > 0)) throw new Exception("Domain id was not stored"); } A: You have to change the connection string to point to your other database which is used in the server Explorer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: powershell expand-archive cmdlet - problem with unpack split zip files I'm trying to unpack zip file which is in pieces (file.z01, file.z02, file.zip) I use expand-archive cmdlet from PSCX but i get an error PS C:\> expand-archive -format zip -path c:\temp\file.zip -outputpath c:\temp\ -showprogress error message: Expand-Archive : Internal error! hresult: 00000001 At line:1 char:15 + expand-archive <<<< -format zip -path c:\temp\file.zip -outputpath c:\temp\ -showprogress + CategoryInfo : NotSpecified: (C:\temp\file.zip:String) [Expand-Archive], InvalidOperationException + FullyQualifiedErrorId : FileError,Pscx.Commands.IO.Compression.ExpandArchiveCommand when i use the same command for .rar file (file.part1.rar, file.part2.rar) it works fine any ideas ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7545099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best way to search two queries and eliminate rows without a relationship I am working on a property website and have record sets for property and for unit, unit has a one-to-many relationship with property. What I'm trying to figure out is how to best create a search function which will output results based on criteria from both. So if I search for a property with the location Manchester and a unit with a freehold tenure I'd like to eliminate all properties which don't have a unit with the tenure of freehold. A potential solution I've considered is to create a record set for properties which match the property criteria and then create a unit record set for units which match the unit criteria and then finally loop through the property record set in server-side code and eliminate any properties which aren't related to any of the units in the unit record set. Really not sure if this is the best way to do things though so would be keen to hear any suggestions? Thanks EDIT (Added table structure and MySQL): -- -- Table structure for table `property` -- CREATE TABLE IF NOT EXISTS `property` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` text NOT NULL, `street` text NOT NULL, `town` text NOT NULL, `postcode` text NOT NULL, `description` longtext NOT NULL, `team_member` varchar(255) NOT NULL DEFAULT '', `pdf` text NOT NULL, `default_image_id` int(11) DEFAULT NULL, `virtual_tour_link` text NOT NULL, `date` date NOT NULL DEFAULT '0000-00-00', `archive` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='' AUTO_INCREMENT=13 ; -- -- Table structure for table `unit` -- CREATE TABLE IF NOT EXISTS `unit` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` text NOT NULL, `description` text NOT NULL, `size_sq_ft` int(11) DEFAULT NULL, `size_acres` float DEFAULT NULL, `price` float DEFAULT NULL, `rental_price` float DEFAULT NULL, `on_application` tinyint(1) DEFAULT NULL, UNIQUE KEY `id` (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='Stores data for property units' AUTO_INCREMENT=5; -- -- Table structure for table `property_to_unit` -- CREATE TABLE IF NOT EXISTS `property_to_unit` ( `property_id` int(11) NOT NULL, `unit_id` int(11) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- -- MySQL which produces list of properties -- SELECT P.id AS id, P.name AS name, P.street AS street, P.town AS town, P.postcode AS postcode, P.description AS description, P.team_member AS team_member, P.pdf AS pdf, P.virtual_tour_link AS virtual_tour_link, P.date AS date, P.archive AS archive, PI.name as image, P2.image_ids as image_ids, L2.location_ids as location_ids, U2.unit_ids as unit_ids FROM property P -- Get default image and join using property id LEFT JOIN property_image PI ON PI.id = P.default_image_id -- Create a list of image_ids from property_image and -- property_to_property_image tables then join using property_id LEFT JOIN ( SELECT property_id, GROUP_CONCAT(CAST(id AS CHAR)) as image_ids FROM property_to_property_image PTPI LEFT JOIN property_image PI ON PI.id = PTPI.property_image_id GROUP BY property_id ) P2 ON P2.property_id = P.id -- Create a list of locations from property_location table -- and join using property_id LEFT JOIN ( SELECT property_id, property_location_id, GROUP_CONCAT(CAST(property_location.id AS CHAR)) AS location_ids FROM property_to_property_location INNER JOIN property_location ON property_location.id = property_to_property_location.property_location_id GROUP BY property_id ) L2 ON L2.property_id = P.id -- Create a list of units from unit table -- and join using property_id LEFT JOIN ( SELECT property_id, unit_id, GROUP_CONCAT(CAST(unit_id AS CHAR)) AS unit_ids FROM property_to_unit INNER JOIN unit ON unit.id = property_to_unit.unit_id GROUP BY property_id ) U2 ON U2.property_id = P.id -- -- MySQL which produces list of units -- SELECT id, name, description, size_sq_ft, size_acres, price, rental_price, on_application, tenure_ids, tenure_names, type_ids, type_names FROM unit AS U -- join tenure ids and names LEFT JOIN ( SELECT unit_id, GROUP_CONCAT( CAST(UT.id AS CHAR) ) AS tenure_ids, GROUP_CONCAT(UT.name) AS tenure_names FROM unit_to_unit_tenure UTUT INNER JOIN unit_tenure UT ON UT.id = UTUT.unit_tenure_id GROUP BY unit_id ) UT ON UT.unit_id = U.id -- join type ids and names LEFT JOIN ( SELECT unit_id, GROUP_CONCAT( CAST(UTYPE.id AS CHAR) ) AS type_ids, GROUP_CONCAT(UTYPE.name) AS type_names FROM unit_to_unit_type UTUT INNER JOIN unit_type UTYPE ON UTYPE.id = UTUT.unit_type_id GROUP BY unit_id ) UTYPE ON UTYPE.unit_id = U.id WHERE 0=0 I'm currently using a dynamically created WHERE statement appended to each MySQL query to filter the property and unit results. A: Your situation requires a posted foreign key in the property table. Store the unit_id in the property table and use a join in your query such as: select * from property p, unit u where p.unit_id = u.id and p.town = .... EDIT: So I just noticed the rest of your SQL. If you require to keep the many-to-many relationship table for the unit -> property relationship then you will need to join unit and property off of that table. A: You're making it a bit more complicated than it is. If I understand correctly, you can easily do this in a single query. This would search properties that have units with a particlar unit tenure id: select * from property p where p.id in ( select pu.property_id from property_to_unit pu inner join unit u ON pu.unit_id = u.id inner join unit_to_unit_tenure uut ON u.id = uut.unit_id where uut.id = <cfqueryparam value="#uutid#"> ) Using two queries and then looping through to cross-check sounds like it could be dog slow.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trouble installing QT Jambi on a Windows 64 bit system I've been trying to use QT Jambi, but I couldn't manage to install it yet. First of all, this is my system: Windows 7 Home Premium 64 Bit Java 6 32 bit (I often use JDownloader which is not compatible with the 64 bit version of Java) MinGW C++ compiler that comes with Code::Blocks (which sets all required environmental variables during setup) I also have CygWin installed, but I don't understand why it gets mentioned during the error that I get... My first idea was to try the 32 bit version since I have 32-bit Java, so I linked the libraries in Eclipse, tried the classical beginner program found in a tutorial and I got this message: java.lang.ExceptionInInitializerError at com.trolltech.qt.QtJambiObject.<clinit>(Unknown Source) Caused by: java.lang.RuntimeException: Loading library failed, progress so far: Unpacking .jar file: 'qtjambi-win32-msvc2008-4.7.1.jar' Checking Archive 'qtjambi-win32-msvc2008-4.7.1.jar' - skipping because of wrong system: trying to load: 'win32', expected: 'win64' Loading library: 'QtCore4.dll'... - using 'java.library.path' at com.trolltech.qt.internal.NativeLibraryManager.loadNativeLibrary(Unknown Source) at com.trolltech.qt.internal.NativeLibraryManager.loadQtLibrary(Unknown Source) at com.trolltech.qt.Utilities.loadQtLibrary(Unknown Source) at com.trolltech.qt.Utilities.loadQtLibrary(Unknown Source) at com.trolltech.qt.QtJambi_LibraryInitializer.<clinit>(Unknown Source) ... 1 more Caused by: java.lang.RuntimeException: Library 'QtCore4.dll' was not found in 'java.library.path'=C:\Program Files\Java\jre6\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C: \Windows;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Broadcom\Broadcom 802.11\Driver;c:\Program Files (x86)\Microsoft SQL Server\90\Tools\binn\;C:\Program Files (x86)\CodeBlocks\MinGW\bin\;C:\Program Files (x86)\QuickTime\QTSystem\;C:\cygwin\bin;C:\Program Files\Microsoft Windows Performance Toolkit\;. at com.trolltech.qt.internal.NativeLibraryManager.loadLibrary_helper(Unknown Source) ... 6 more Exception in thread "main" Then since it says it expects a 64 bit system I followed the Installation Guide and tried this steps: 1) Downloaded QTJambi source package 2) Downloaded original QT source package 3) Added "C:\QTJambi\QT\qt-qt\bin" (QT source package folder) to the environment PATH variable 4) Opened Visual Studio 2005 Command Prompt 5) cd C:\QTJambi\QT\qt-qt 6) Tried: configure -platform win64-g++ -D QT_JAMBI_BUILD -no-qt3support -plugin-manifests But it didn't work, error: invalid option win64-g++ for -platform 7) Tried configure -platform win32-g++ -D QT_JAMBI_BUILD -no-qt3support -plugin-manifests 8) Digit o for open source 9) Digit y for accepting license But it doesn't work either, getting this error: Running syncqt... perl: warning: Setting locale failed. perl: warning: Please check that your locale settings: LC_ALL = (unset) LANG = "IT" are supported and installed on your system. perl: warning: Falling back to the standard locale ("C"). Can't execute /cygdrive/c/QTJambi/QT/qt-qt/bin//syncqt syncqt failed, return code 2 Anyone able to help? Thanks in advance to anyone! A: This response attempts to explain and address the original problem (i.e. how to make use of the 32bit QtJambi binary distribution on a 64bit Windows system). skipping because of wrong system: trying to load: 'win32', expected: 'win64' This is a message from the QtJambi initialization code that detects a mismatch between the 32/64 bit-ness of the JVM and the 32/64 bit-ness of the QtJambi implementation trying to be loaded into the JVM instance at runtime. In your case this is due to trying to use a 64bit JVM with a 32bit version of QtJambi. This is not a possible feat. To correct the problem find and install directly the Windows 32bit JVM on your system so that you have the file "C:\Program Files (x86)\Java\jre6\bin\java.exe" (you may already have it installed, please check) When they are both installed on a 64bit system take a look at the difference between: C:\>"C:\Program Files (x86)\Java\jre6\bin\java.exe" -version java version "1.6.0_26" Java(TM) SE Runtime Environment (build 1.6.0_26-b03) Java HotSpot(TM) Client VM (build 20.1-b02, mixed mode, sharing) C:\>"C:\Program Files\Java\jre6\bin\java.exe" -version java version "1.6.0_26" Java(TM) SE Runtime Environment (build 1.6.0_26-b03) Java HotSpot(TM) 64-Bit Server VM (build 20.1-b02, mixed mode) The top one is the 32bit JVM; the bottom one is the 64bit JVM. Now try loading the QtJambi binary version you have via the 32bit JVM you have to do this explicitly as the default "java.exe" should be the 64bit one on a Windows 64bit platform: "C:\Program Files (x86)\Java\jre6\bin\java.exe" -cp qtjambi-X.Y.Z.jar;qtjambi-win32-msvc2008-X.Y.Z.jar;myjar.jar mypackage.MyMain You need to fixup the command line above the ClassPath (-cp) to the locations of your JARs you are attempting to run and the main(). If you have problems getting the application to start due to UnsatisfiedLinkError and you are using a msvc2008 build then try installing the "Microsoft Visual C++ 2008 SP1 Redistributable Package (x86)" http://www.microsoft.com/download/en/details.aspx?id=5582 (NOTE: There is also a 64bit version of this as well, this link is for the 32bit version which is relevant to using 32bit QtJambi on a 32bit JVM, if you also want the 64bit version search for the same page with "(x64)" in the title instead of "(x86)" on the microsoft website). Then retry your test. A: Qt Jambi nowadays supports 64 bit compilations too, but getting proper Qt is quite a bit harder. For MinGW there is some resources available in Internet. Maybe they can help you. Building 64-bit Qt 4.7 using MinGW-w64 Only supported (by Nokia) solution at the moment is 64 bit MSVC compilations, but AFAIK there is no such binaries distributed from Nokia because runtimes are not allowed to be freely distributed. When compiling with MSVC, correct profile for MSVC 2010 would be win32-msvc2010. List of those can be found from in mkspecs directory. Note that you don’t usually have to specify the profile in first place; only if there is many available profiles you could use and you want to use certain one (MinGW or MSVC, for example). 64 bit compilation with MSVC works using 64 bit environment, according this page. Using Cygwin with Qt or Qt Jambi is not really suggested; use MSYS if you want unix-like environment.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: UISearchBar - scope bar animated I've found example of animated search-bar with scope bar under "UISearchDisplayDelegate Protocol Reference"(SearchBar-animated-sample ), here is a video preview: SearchBarAnimated-video I've checked sample code, but I can't find the code that triggers animation. Does anyone knows how to create that animation ? Do you have to use UISearchBarDelegate to get that animation ? A: Inorder to control the animations of UISearchBar you have implement the delegates of UISearchDisplayController by extending in your header file. The delegates are as follows; - (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller { [UIView beginAnimations:nil context:NULL]; self.searchDisplayController.searchBar.showsScopeBar = NO; CGRect headerViewFrame = self.searchDisplayController.searchBar.frame; headerViewFrame.origin.y -= 54.0f; self.searchDisplayController.searchBar.frame = headerViewFrame; CGRect tableViewFrame = self.tableView.frame; tableViewFrame.origin.y -= 54.0f; self.tableView.frame = tableViewFrame; [UIView commitAnimations]; } -(void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller { [UIView beginAnimations:nil context:NULL]; CGRect headerViewFrame = self.searchDisplayController.searchBar.frame; headerViewFrame.origin.y += 54.0f; self.searchDisplayController.searchBar.frame = headerViewFrame; CGRect tableViewFrame = self.tableView.frame; tableViewFrame.origin.y += 54.0f; self.tableView.frame = tableViewFrame; [UIView commitAnimations]; } A: It's built right in to UISearchBar. Apple does this for you, you don't have to call any method by yourself. Basically, from the moment you set your search bar's scopeButtonTitles property, Apple will animate the scope bar. A: I found the answer to this question more useful though it doesn't automatically transition the search bar to the top of your view. How do you hide/show UISearchBar's scope bar with animation? A: This works well for me in Xcode 6. If you have auto layout constraints in place then you may need to add in adjustments for them as I've done (didn't work without them). - (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar { searchBar.showsScopeBar = YES; searchBarHeightConstraint.constant = 88; // Changes from 44 to 88 with scope bar tableViewHeightConstraint.constant = 480; // Changes from 524 to 480 with scope bar [UIView animateWithDuration:0.3 animations:^{ CGRect newFrame = tableView.frame; newFrame.origin.y = 88; tableView.frame = newFrame; }]; return YES; } - (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar { searchBar.showsScopeBar = NO; searchBarHeightConstraint.constant = 44; tableViewHeightConstraint.constant = 524; [UIView animateWithDuration:0.3 animations:^{ CGRect newFrame = tableView.frame; newFrame.origin.y = 44; tableView.frame = newFrame; }]; return YES; } A: sizeToFit in an Animation block The UISearchBar w/ scope bar is easily animated. UISearchBar has a height of 44.f before calling sizeToFit with the scope bar and then becomes 88.f. In my case, the UISearchBar was embedded in a UITableView within Interface Builder so it was not possible to add auto layout constraints. #pragma mark - UISearchBarDelegate methods - (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar { searchBar.showsScopeBar = YES; [UIView animateWithDuration:0.2f animations:^{ [searchBar sizeToFit]; }]; [searchBar setShowsCancelButton:YES animated:YES]; return YES; } - (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar { searchBar.showsScopeBar = NO; [searchBar sizeToFit]; [searchBar setShowsCancelButton:NO animated:YES]; return YES; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7545106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can Class be of the Class class and not have Class instance methods? I was studying how the Ruby interpreter is implemented, and one question occurred that didn't get an answer yet for me. That's the one in the title: since Class (r_cClass) has super set to itself (ignoring metaclasses, since actually super is the metaclass of r_cClass), if I send one method to the Class object, this will be looked in the method table of Class' class. But Class' class is Class, so shouldn't I end up looking the instance methods of Class? But that's not the case since in the documentation Class class methods and Class instance methods are separated. In the search_method in eval.c of Ruby, I didn't find any special check for the Class class. Can anyone shed some light on this? A: Your beliefs about the way it should work seem right, but I'm not sure why you think it doesn't work that way. In Ruby 1.8.7: irb> a = Class.new.methods - Object.new.methods => [... 36 element array ...] irb> b = Class.methods - Object.new.methods => [... 37 element array ...] irb> b - a => ["nesting"] A normal class instance (Class.new) has 36 instance methods. If I look at Class itself, which is also a normal class instance, it has the same 36 instance methods, plus 1 additional class method (nesting), which exists only because it is inherited from its superclass Module. Note that adding an instance method to Class automatically adds it as a class method as well, but adding a class to Class's metaclass will not. irb> class Class ; def everywhere ; true ; end ; end irb> class << Class ; def only_singleton ; true ; end ; end irb> Class.everywhere => true irb> Class.new.everywhere => true irb> Class.only_singleton => true irb> Class.new.only_singleton NoMethodError: undefined method 'only_in_singleton' for #<Class:0x4800ac8>
{ "language": "en", "url": "https://stackoverflow.com/questions/7545110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Separate entity for primary keys I have two tables as below. "User Acc" is user's profile details and user's login details(username password) are in a seperate table called login.When I generated the entities in Netbeans IDE, there were 2 tables for login(database) table. One generated entity is "Login", another one is "LoginId".Login entity has a reference to LoginId and UserAcc entity. LoginId entity has username and password which were in login database table.UserAcc has primary key which is INT for each user.That key is the foreign key of login table. Now I want to check the user @ loging. How I do is, I create a LoginId instance and set the user name and password and then check any object which has same LoginId. Here is the code. uName and pw are strings and taken from user input. LoginId id=new LoginId(uName, pw); Session ses = NewHibernateUtil.getSessionFactory().openSession(); Criteria crit = ses.createCriteria(Login.class); crit.add(Restrictions.eq("id", id)); Entities.Login log = (Entities.Login)crit.uniqueResult(); But eventhough there are existing usernames and passwords matching with given username and password, the log is always null. Any one tell me where I should check and what the problem is. Thank you. And my other problem is why a separate entity("LoginId") is created for two columns(primary keys) in one database table and another entity for that its database table . for login; <hibernate-mapping> <class name="Entities.Login" table="login" catalog="pcw"> <composite-id name="id" class="Entities.LoginId"> <key-property name="uname" type="string"> <column name="uname" length="10" /> </key-property> <key-property name="pw" type="string"> <column name="pw" length="10" /> </key-property> </composite-id> <many-to-one name="useracc" class="Entities.Useracc" fetch="select"> <column name="UserAcc_uid" not-null="true" /> </many-to-one> </class> for UserAcc: <hibernate-mapping> <class name="Entities.Useracc" table="useracc" catalog="pcw"> <id name="uid" type="java.lang.Integer"> <column name="uid" /> <generator class="identity" /> </id> <property name="fname" type="string"> <column name="fname" length="45" /> </property> <property name="sname" type="string"> <column name="sname" length="45" /> </property> <property name="RDate" type="date"> <column name="r_date" length="10" /> </property> <property name="street" type="string"> <column name="street" length="45" /> </property> <property name="city" type="string"> <column name="city" length="45" /> </property> <property name="email" type="string"> <column name="email" length="45" /> </property> <property name="tel" type="string"> <column name="tel" length="45" /> </property> <set name="comments" inverse="true" cascade="all"> <key> <column name="UserAcc_uid" not-null="true" /> </key> <one-to-many class="Entities.Comment" /> </set> <set name="logins" inverse="true" cascade="all"> <key> <column name="UserAcc_uid" not-null="true" /> </key> <one-to-many class="Entities.Login" /> </set> </class> A: Anyway you can use HQL to solve it it will look more and less like this: public boolean authenticate(Sting username,String pass){ Session ses = NewHibernateUtil.getSessionFactory().openSession(); String sql = "from Login login where login.username:= username and login.pass = :=pass"; Query query = session.createQuery(sql); query.setString("username",username); query.setString("pass",pass); List<Login> result = query.list(); //close session, transaction,etc.... if (result ==null) return false; else return true; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7545112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Managing loads of web forms I'm currently working on a web project that is on a larger scale than I'm used to. The website has a frontend for registered users which consists of 10 different subpages which all have forms. But my problem is how to create and manage these forms by way of CSS and jQuery. Is there a simple or rather dynamic way to create the forms? I feel that the form creation could easily get out of control and everything becomes a mess. The system is built on the Kohana framework. A: Kohana-Formo looks like what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Silverlight ComboBox in DataGrid Binding SelectedItem problem I have a combobox in datagrid.I use Silverlight 4.0 and MVVM. My code works fine,unless when I removed a record from datagrid and add another one, the SelectedValue binding for combobox in added row doesnt work. <sdk:DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Items, Mode=TwoWay}" Name="dataGrid2" > <sdk:DataGrid.Columns> <sdk:DataGridTemplateColumn Width="50*"> <sdk:DataGridTemplateColumn.CellEditingTemplate> <DataTemplate> <ComboBox ItemsSource="{Binding Path=Products, Mode=OneWay}" SelectedValue="{Binding Path=ProductId,Mode=TwoWay}" DisplayMemberPath="ProductTitle" SelectedValuePath="ProductId"/> </DataTemplate> </sdk:DataGridTemplateColumn.CellEditingTemplate> </sdk:DataGridTemplateColumn> </sdk:DataGrid.Columns> </sdk:DataGrid> Thanks A: Found this piece of code on some site, it helped me in a similar Situation: public class ComboBoxEx : ComboBox { protected override void OnItemsChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { var bindingExpression = GetBindingExpression(SelectedValueProperty); base.OnItemsChanged(e); if (bindingExpression != null) { var binding = bindingExpression.ParentBinding; SetBinding(SelectedValueProperty, bindingExpression.ParentBinding); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7545123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HL7 parsing to get ORC-2 I am having trouble reading the ORC-2 field from ORM^O01 order message. I am using HapiStructures-v23-1.2.jar to read but this method(getFillerOrdersNumber()) is returning null value MSH|^~\\&|recAPP|20010|BIBB|HCL|20110923192607||ORM^O01|11D900220|D|2.3|1\r PID|1|11D900220|11D900220||TEST^FOURTYONE||19980808|M|||\r ZRQ|1|11D900220||CHARTMAXX TESTING ACCOUNT 2|||||||||||||||||Y\r ORC|NW|11D900220||||||||||66662^NOT INDICATED^X^^^^^^^^^^U|||||||||CHARTMAXX TESTING ACCOUNT 2|^695 S.BROADWAY^DENVER^CO^80209\r OBR|1|11D900220||66^BHL, 9P21 GENOTYPE^L|NORMAL||20110920001800| ||NOTAVAILABLE|N||Y|||66662^NOT INDICATED^X^^^^^^^^^^U\r I want to parse this message and read the ORC-2 field and save it in the database public static string getOrderNumber(){ Message hapiMsg = null; Parser p = new GenericParser(); p.setValidationContext(null); try { hapiMsg = p.parse(hl7Message); } catch (Exception e) { Logger.error(e); } Terser terser = new Terser(hapiMsg); try { ORM_O01 getOrc = (ORM_O01)hapiMsg; ORC orc = new ORC(getOrc, null); String fn= orc.getFillerOrderNumber().toString(); }catch(Exception e){ logger.error(e); } return fn; } I read in some posts that I have to ladder through to reach the ORC OBR and NTE segments. can someone help me how to do this with a piece of code. Thanks in advance A: First I have to point out that ORC-2 is Placer Order Number and ORC-3 is Filler Order Number, not the other way round. So, what you might want to do is this: ORM_O01 msg = ... ORC orc = msg.getORDER().getORC(); String placerOrderNumber = orc.getPlacerOrderNumber().getEntityIdentifier().getValue(); String fillerOrderNumber = orc.getFillerOrderNumber().getEntityIdentifier().getValue(); I would suggest you to read Hapi documentation yourself: http://hl7api.sourceforge.net/v23/apidocs/index.html A: Based on this code: ORM_O01 getOrc = (ORM_O01)hapiMsg; ORC orc = new ORC(getOrc, null); String fn= orc.getFillerOrderNumber().toString(); It looks like you are creating a new ORC rather than pulling out the existing one from the message. I unfortunately can't provide the exact code as I'm only familiar with HL7, not HAPI. EDIT: It looks like you may be able to do ORC orc = getOrc.getORDER().getORC();
{ "language": "en", "url": "https://stackoverflow.com/questions/7545131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to switch terminal to new child process of process launched with NSTask? I made a pseudo terminal with method described here: http://lists.apple.com/archives/student-dev/2005/Mar/msg00019.html The terminal itself worked well. Anyway the problem is terminal cannot being switched to child process. For an example, I launched bash with NSTask, and if I execute ftp within the bash, it stops automatically. ftp ftp ftp> [1]+ Stopped ftp bash-3.2$ And if I try to continue the ftp with fg, it terminates quietly. (I checked this with Activity Monitor) fg fg ftp bash-3.2$ fg fg bash: fg: current: no such job bash-3.2$ I think it needs some more infrastructure (which completes pseudo terminal) to switch control to child process. What's required to do this? A: I could finally do this by creating a pty device. To make a program behave like "Terminal", it must be executed in an interactive terminal, and that needs pseudo-terminal device. Unfortunately, AFAIK, NSTask does not support any pty ability, so I had to get down to BSD layer. Here's my current implementation: https://github.com/eonil/PseudoTeletypewriter.Swift sudo is working well, and I believe ssh should also work. A: Have a look at the source code of MFTask and PseudoTTY.app (which works on Mac OS X 10.6). See: http://www.cocoadev.com/index.pl?NSTask For a pty command line tool see here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Multiple JQPL fetch joins fail with Hibernate Using Hibernate 3.6.7 and JPA 2, I cannot have two fetch joins in one query. Entity has a self referencing field called parent. localizedTexts is an @ElementCollection, of Java type of Map. entity.getParent() has a @ManyToOne with EAGER loading strategy. Here is How entity looks like: @Entity public class Entity extends BaseEntity { /* ... */ @ManyToOne(fetch = FetchType.EAGER) public Entity getParent() { return parent; } @ElementCollection @MapKeyColumn(name = "language") @Column(name = "text") public Map<String, String> getLocalizedTexts() { return localizedTexts; } /* ... */ } The following two queries work: select e from Entity e join fetch e.parent.localizedTexts select e from Entity e join fetch e.localizedTexts But this doesn't work: select e from Entity e join fetch e.localizedTexts join fetch e.parent.localizedTexts Hibernate complains: query specified join fetching, but the owner of the fetched association was not present in the select list [FromElement{explicit,collection join,fetch join,fetch non-lazy properties,classAlias=null,role=net.company.project.Entity.localizedTexts,tableName={none},tableAlias=localizedt3_,origin=null,columns={,className=null}}] [select e from net.company.project.Entity e join fetch e.localizedTexts join fetch e.parent.localizedTexts] A: If you want to preload the Entities "parent" associations as well as the parent's "localizedTexts" association you should declare joins that traverse the model tree in the correct order: select e from Entity e join fetch e.parent p joint fetch p.localizedTexts
{ "language": "en", "url": "https://stackoverflow.com/questions/7545137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to write data attributes in zen coding? I use data attributes more every day, and I really miss a simple way to add a data attribute while using zen coding. I mean I can add inline style (not that I ever use it) div[style=color:red;] why can't I add data attribute like div[data-color=pink] Any work arounds? A: you can: div[data-color='pink'] A: I use div[data-color=pink] and it works. Both div[data-color="pink"] and div[data-color='pink'] don't.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I set the rollover strategy in System.Diagnostics trace log I have a project, that using System.Diagnostics for logging, And it creating lots of new logs files, each one starting with GUID, Even when the last log file was very small I want to setup a role that controls the creation of new log file Where can I configure it? And second question: Where can I set the log to write non utc time? Thanks A: See the following link for a discussion about rollover trace listeners: What the best rollover log file tracelistener for .NET The accepted answer recommends the FileLogTraceListener: http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.logging.filelogtracelistener.aspx I would encourage you to also look at Ukadc.Diagnostics as a way to add flexibility (and formatting) to System.Diagnostics tracing/logging: http://ukadcdiagnostics.codeplex.com/ To answer your final question about logging in something other than UTC, I think the only answer is to write your own TraceListener (or use someone else's, such as Ukadc.Diagnostics).  It goes without saying that logging frameworks like NLog and log4net are very popular for a reason:  they provide extremely powerful and flexible logging solutions, allowing you to focus on your application's functionality, not on solving logging problems.  A: I also have been faced with the both issues (filesize -rollover and Timestamps non UTC for events) of the standard implementation of TraceListener and I didn't want to have a third party tool. I found this solution which comes with minimum effort: http://www.geekzilla.co.uk/View2C5161FE-783B-4AB7-90EF-C249CB291746.htm
{ "language": "en", "url": "https://stackoverflow.com/questions/7545140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to clean listitem data in ListActivity when using extends BroadcastReceiver Anyway to clean listitem data inside ListActivity and then show data using setListAdapter(adapter) ? The problem is it continuously appends listitem data inside ListActivity and show many listitem data. I used android.widget.SimpleAdapter for adapter. I want to clean data and then show data. class Receiver extends BroadcastReceiver { public void onReceive(Context c, Intent intent){ adapter.notifyDataSetChanged(); ........ } setListAdapter(adapter); } } A: you should use adapter.notifyDataSetChanged(); http://developer.android.com/reference/android/widget/BaseAdapter.html#notifyDataSetChanged()
{ "language": "en", "url": "https://stackoverflow.com/questions/7545142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: gmail Conversation via smtp how can i send an email as a part of a gmail-conversation via smtp? Taking the same subject doesnt work... tell me if you need more infos... thanks in advance! MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); mail.From = new MailAddress("@googlemail.com"); mail.To.Add("@.com"); mail.Subject = "(Somee.com notification) New order confirmation"; mail.Body = "(Somee.com notification) New order confirmation"; SmtpServer.Port = 587; SmtpServer.Credentials = new System.Net.NetworkCredential("", ""); SmtpServer.EnableSsl = true; SmtpServer.Send(mail); A: You'll need to use the following: mail.Headers.Add("In-Reply-To", <messageid>); The message id you should be able to get from the previous email's headers. Just look for "Message-Id". This answer gives a few more headers you may want to add to try help threading in other clients. It seems maybe gmail is now using these, too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: nodejs synchronization read large file line by line? I have a large file (utf8). I know fs.createReadStream can create stream to read a large file, but not synchronized. So i try to use fs.readSync, but read text is broken like "迈�". var fs = require('fs'); var util = require('util'); var textPath = __dirname + '/people-daily.txt'; var fd = fs.openSync(textPath, "r"); var text = fs.readSync(fd, 4, 0, "utf8"); console.log(util.inspect(text, true, null)); A: use https://github.com/nacholibre/node-readlines var lineByLine = require('n-readlines'); var liner = new lineByLine('./textFile.txt'); var line; var lineNumber = 0; while (line = liner.next()) { console.log('Line ' + lineNumber + ': ' + line.toString('ascii')); lineNumber++; } console.log('end of line reached'); A: Use readFileSync: fs.readFileSync(filename, [encoding]) Synchronous version of fs.readFile. Returns the contents of the filename. If encoding is specified then this function returns a string. Otherwise it returns a buffer. On a side note, since you are using node, I'd recommend using asynchronous functions. A: I built a simpler version JB Kohn's answer that uses split() on the buffer. It works on the larger files I tried. /* * Synchronously call fn(text, lineNum) on each line read from file descriptor fd. */ function forEachLine (fd, fn) { var bufSize = 64 * 1024; var buf = new Buffer(bufSize); var leftOver = ''; var lineNum = 0; var lines, n; while ((n = fs.readSync(fd, buf, 0, bufSize, null)) !== 0) { lines = buf.toString('utf8', 0 , n).split('\n'); lines[0] = leftOver+lines[0]; // add leftover string from previous read while (lines.length > 1) { // process all but the last line fn(lines.shift(), lineNum); lineNum++; } leftOver = lines.shift(); // save last line fragment (may be '') } if (leftOver) { // process any remaining line fn(leftOver, lineNum); } } A: For large files, readFileSync can be inconvenient, as it loads the whole file in memory. A different synchronous approach is to iteratively call readSync, reading small bits of data at a time, and processing the lines as they come. The following bit of code implements this approach and synchronously processes one line at a time from the file 'test.txt': var fs = require('fs'); var filename = 'test.txt' var fd = fs.openSync(filename, 'r'); var bufferSize = 1024; var buffer = new Buffer(bufferSize); var leftOver = ''; var read, line, idxStart, idx; while ((read = fs.readSync(fd, buffer, 0, bufferSize, null)) !== 0) { leftOver += buffer.toString('utf8', 0, read); idxStart = 0 while ((idx = leftOver.indexOf("\n", idxStart)) !== -1) { line = leftOver.substring(idxStart, idx); console.log("one line read: " + line); idxStart = idx + 1; } leftOver = leftOver.substring(idxStart); } A: two potential problems, * *3bytes BOM at the beginning you did not skip *first 4bytes cannot be well format to UTF8's chars( utf8 is not fixed length )
{ "language": "en", "url": "https://stackoverflow.com/questions/7545147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How do I make my banner in tumblr link to another site? I'm trying to make the banner in my tumblr blog link to another site. I can't figure out how to do it. The following is the code I found in the custom html tab but I can't seem to make my banner clickable. Where exactly should I add the website address for the link? Any help will be appreciated. <div id="page" class="{block:IfLeftSidebar}left-sidebar{/block:IfLeftSidebar}{block:IfNotLeftSidebar}right-sidebar{/block:IfNotLeftSidebar}"> {block:IfBannerImage} <div class="banner"> <a href="/"title="{Title}"><img id="banner" src="{image:Banner}" alt="banner"/></a> </div> {block:IfBannerImage} {block:IfNotBannerImage} {block:IfBlogTitleInPageHeader} <div class="banner textual"> <h1 class="blog-title"><a href="/">{Title}</a></h1> {block:IfTagline}<p class="tagline">{text:Tagline}</p>{/block:IfTagline} </div> {/block:IfBlogTitleInPageHeader} {/block:IfNotBannerImage} <div id="content"> A: <div class="banner"> <a href="/"title="{Title}"><img id="banner" src="{image:Banner}" alt="banner"/></a> </div> put your website in the href=""
{ "language": "en", "url": "https://stackoverflow.com/questions/7545154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to create multi level views in NSTableView style? I have got a project which has multiple levels. I do not find a proper way to start. The project mock ups are in hierarchical structure (tree like structure). It has almost 10 levels. So how to implement these levels in multiple table views where one action can open specific table view? Should I have to create different views for all levels? Or I can simply write data structure of my views in plist file (xml) and use that file for all levels. Please suggest me how to start. Thanks A: If user interaction is required at each level & there is considerable information to be displayed to the user, then you should be going with nested UITableViews, where tapping on the row of one leads to the next one. You can have a look at the settings app for an example. Yes, you will have to create a view for each level. However, 10 levels seems like a bit too much from the user experience point of view (Can you think of an existing app that has 10 levels?). You should give a thought to flattening your tree by combining a few levels together. A: Use a CoreData-based "Navigation-based Application" from XCode. Make an entity (e.g. TreeData) that has a one-to-many relationship with itself, called 'children'. Create an inverse relationship (one-to-one) on that, called 'parent'. On the tableView:didSelectRowAtIndexPath: in the delegate you'd need to check to see if 'children' is set in your 'TreeData', if that is the case, then you'd need to push a new instance of the TableViewController you a currently in, with the children on the selected item as the dataSource. This would allow you to keep traversing. A plist would be the simplest way to give the general idea and get something working. You could also achieve the same thing with a plist. Something like this: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Tree Root</key> <array> <dict> <key>title</key> <string>Google (No Children)</string> <key>url</key> <string>www.google.com</string> </dict> <dict> <key>title</key> <string>List of Web Sites</string> <key>children</key> <array> <dict> <key>title</key> <string>digg</string> <key>url</key> <string>digg.com</string> </dict> <dict> <key>title</key> <string>iGoogle</string> <key>url</key> <string>www.google.com/ig</string> </dict> <dict> <key>title</key> <string>Stack Overflow</string> <key>url</key> <string>www.stackoverflow.com</string> </dict> </array> </dict> </array> </dict> </plist> http://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/TableView_iPhone/
{ "language": "en", "url": "https://stackoverflow.com/questions/7545156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to create custom php.ini file for zend? I used PDO_MYSQL connection in application.ini file of zend its work on localhost because extension=php_pdo_mysql.dll is enable. When i run code on server its throws exception Message: SQLSTATE[28000] [1045] Access denied for user 'rdvscoin_main'@'host.indiandns.com' (using password: YES) because pdo_mysql is disable on server and i want enable that extension by custom php.ini file. For this what can i do? I want to create custom php.ini file but i don't known how can i create , where its can store? If any one have alternate idea then suggest me please..... A: This has nothing to do with Zend, really. There is no such thing as a custom php.ini for a single project. You can run VirtualHosts with different settings, but even they all use the same ini file i think. Rather have the administrator enable PDO extension (but EVERYONE has that running Oo) But given the error i'd say its a permission problem, too - tried using 'localhost' instead of the specified?
{ "language": "en", "url": "https://stackoverflow.com/questions/7545159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mysql server integration with Visual Studio 2010 .net 'm Using Visual studio 2010 express edition installed in OS win7(64bit). and I downloaded mysql server 5.5.16 (64bit) which installed successfully. Now all i want to integrate these mysql server with VS 2010. I tried by installing mysql Connector for .Net(32bit) but nothing useful.nd their is no connector of 64bit for .Net. VS database explorer does not show mysql option to connect to mysql server while connecting to database. I'm very new to these technologies. Please help me out.'M trying from past 6 days. A: there is an ODBC connector for 64 bit: Connector/ODBC 5.1.8 for Visual Studio Server Explorer integration, if you manage to configure the ODBC connection string and get it listed all the better but not sure what kind of DB servers VS server explorer supports, even if it won't show up it does not mean it would not work, that is only a UI tool. You should have another UI Tool for mySQL, I used SLQYog in the past and was very satisfied. once you have a mySQL database created and having some tables and few records in it you can try to make a connection from .NET and check how it works, you can do something like this in your .NET code (just one of many using Connection examples...): static private void InsertRow(string connectionString) { string queryString = "INSERT INTO myTable..."; OdbcCommand command = new OdbcCommand(queryString); using (OdbcConnection connection = new OdbcConnection(connectionString)) { command.Connection = connection; connection.Open(); command.ExecuteNonQuery(); // The connection is automatically closed at // the end of the Using block. } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7545160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use AWS CloudFormation from AWS Toolkit targeting "small" instance for ASP.NET I've deployed an ASP.NET on EC2 using AWS Cloudformation. In Visual Studio, the AWS Toolkit adds the 'Publish to CloudFormation' menu item. This creates the required Cloudformation template using a choice of machines, such as Micro and Large, targeting Win 2008 R2. As I would use a 'small' instance (more powerful than Micro but cheaper than Large, and use the convenience of Cloudformation from Visual Studio, I tried copying the template that is generated and use this as a new template for Cloudformation, using an AMI that targets Win 2008 and so runs on a 32bit small machine. However I get an error as the template references config file items created on the fly. What is the best way to use the small instance from within AWS Toolkit on AWS Cloudformation, without having to set up instances, etc. A: not possible as Cloudformation requires Win 2008 R2 and the small instance is 32bit A: This former limitation has meanwhile been remedied by the introduction of 64-bit Ubiquity, see EC2 Updates: New Medium Instance, 64-bit Ubiquity, SSH Client: You can now launch 64-bit operating systems on the Small and Medium instance types. This means that you can now create a single Amazon Machine Image (AMI) and run it on an extremely wide range of instance types, from the Micro all the way up to the High-CPU Extra Large and and the High-Memory Quadruple Extra Large, [...] This will make it easier for you to scale vertically (to larger and smaller instances) without having to maintain parallel (32 and 64-bit) AMIs. [emphasis mine] The AWS Toolkit for Visual Studio supports this significant improvement to vertical scaling as well already, so you can simply Publish to CloudFormation while targeting an Amazon EC2 instance type of your choice, including m1.small. While this should already cover your use case, it may be worth mentioning that AWS also released a new dedicated AMI supporting this OS on AWS CloudFormation specifically, namely the Microsoft Windows Server 2008 R2 - Base for CloudFormation, which contains Microsoft Windows Server 2008 R2 with SP1 intended for CloudFormation on an AMI backed by Amazon EBS in order to to build your own AMIs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Populate form with file name from mysql database I've created a series of forms for users to add and edit records in a database. The database includes audio and image file names (the actual files are moved to folders on submit). My problem is that I can't get the file names to display on the edit forms. Which means that unless the user uploads the files again, those fields are blanked in the database! I understand the "type='file'" does not take a "value" attribute. I was able to get around that in my textareas by simply displaying the php variable in the textarea. I tried that with file names, and they do display, but outside of the input box, which means... see above, blanked fields within the database. Here's the code I'm using: <li> <label for=se_ogg">Sound excerpt (upload .ogg file)</label> <input id="se_ogg" type = "file" name = "se_ogg">' . $row['se_ogg'] . '</input> </li> Any ideas? Can this be done? A: The file input field doesn't allow you to define a value for security reasons otherwise you could hide a file field and use it to grab files from unsuspecting peoples computers. If you just want to display the filename of the file just uploaded just display it as formatted text.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Will a new ActionContext and ValueStack be created for every new action object? My questions are: 1) In Struts2, does every action object have its own corresponding ActionContext and ValueStack? In other words, for every new request a new action object is created. Does this mean every time a new action object is created, a new ActionContext and ValueStack also get created? 2) Consider this scenario: Action1------1st req------->view.jsp------2nd req--------->action2 So when a request comes for action1 a new object of action1 and corresponding ActionContext and ValueStack will get created. From view.jsp (upon clicking hyperlink) a new request goes for action2. Does this mean that previous ActionContext and ValueStack (related to action1) gets destroyed and a new ActionContext and ValueStack (for action2) gets created? 3) Suppose I store something in ActionContext (of action1) in view.jsp and then click on hyperlink for action2 (from view.jsp), will that data along with the ActionContext (of action1) get lost? Thanks. A: A new ActionContext and ValueStack are created for each request. This usually means for each action, but not always (in the case of action chaining). These per-request objects fall out of scope at the end of the request. Anything you store in them is then gone at that point.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I have my CMS upgrade itself? I've built a CMS (using the Codeigniter PHP framework) that we use for all our clients. I'm constantly tweaking it, and it gets hard to keep track of which clients have which version. We really want everyone to always have the latest version. I've written it in a way so that updates and upgrades generally only involve uploading the new version via FTP, and deleting the old one - I just don't touch the /uploads or /themes directories (everything specific to the site is either there or in the database). Everything is a module, and each module has it's own version number (as well as the core CMS), as well as an install and uninstall script for each version, but I have to manually FTP the files first, then run the module's install script from the control panel. I wrote and will continue to write everything personally, so I have complete control over the code. What I'd like is to be able to upgrade the core CMS and individual modules from the control panel of the CMS itself. This is a "CMS for Dummies", so asking people to FTP or do anything remotely technical is out of the question. I'm envisioning something like a message popping up on login, or in the list of installed modules, like "New version available". I'm confident that I can sort out most of the technical details once I get this going, but I'm not sure which direction to take. I can think of ways to attempt this with cURL (to authenticate and pull source files from somewhere on our server) and PHP's native filesystem functions like unlink(), file_put_contents(), etc. to preform the actual updates to files or stuff the "old" CMS in a backup directory and set up the new one, but even as I'm writing this post - it sounds like a recipe for disaster. I don't use git/github or anything, but I have the feeling something like that could help? How should (or shouldn't) I approach this? A: Theres a bunch of ways to do this but the least complicated is just to have Git installedo n your client servers and set up a cron job that runs a git pull origin master every now and then. If your application uses Migrations it should be easy as hell to do. You can do this as it sounds like you are in full control of your clients. For something like PyroCMS or PancakeApp that doesn't work because anyone can have it on any server and we have to be a little smarter. We just download a ZIP which contains all changed files and a list of deleted files, which means the file system is updated nicely. We have a list of installations which we can ping with a HTTP request so the system knows to run the download, or the click can hit "Upgrade" when they log in. A: You can use Git from your CMS: Glip. The cron would be a url on your own system, without installing Git. A: @Obsidian Wouldn't a DNS poisoning attack also compromise most methods being mentioned in this thread? Additionally SSH could be compromised by a man in the middle attack as well. While total paranoia is a good thing when dealing with security, Wordpress being a GPL codebase would make it easy to detect an unauthorized code change in your code if such an attack did occur, so resolution would be easy. SSH and Git does sound like a good solution, but what is the intended audience? A: Have you taken a look at how WordPress does it? That would seem to do what you want. Check this page for a description of how it works. http://tech.ipstenu.org/2011/how-the-wordpress-upgrade-works/
{ "language": "en", "url": "https://stackoverflow.com/questions/7545168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: vim ftp auto upload I am learning VIM. I have a local project, and I want to keep it synchronized on FTP server. So I need: * *turning automated sync on, when i edit files localy *turning it off *forcing to uploading one file (useful when automatic sync off) *forcing to download one file *way to compare local and FTP version of a file I use those features all the time with PHPStorm IDE, and now I wonder is it possible at all in VIM. I was thinking... maybe to use external rsync app or svn, and sync svn with ftp. Is that more like the way to go? A: You can install this plugin which allow you to open a remote file with :e ftp:www.foobax.com/myfile.txt and save it locally :w myfile.txt (use w! to overwrite it) You could diff it using the diffsplit command. Example (on the window containing the remote file) :diffsplit myfile.txt Obviously, if you can use a VCS, that's even better.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to ensure server certificate is created with which private key through java Customer has created key and certificate using openssl command below openssl req -newkey rsa:1024 -sha1 -keyout OCkey.pem -out OCreq.pem -subj "/C=country/L=city/O=OCserver/OU=myLab/CN=OCserverName/" -config req.conf openssl ca -in OCreq.pem -cert CAcert.pem -keyfile CAkey.pem -out OCcert.pem -days 3650 -config sign.conf -extfile sign.ext -md sha1 -notext So they have given me the certificate(OCcert.pem) and private key (OCkey.pem). How to ensure that OCcert.pem is created through OCkey.pem using Java? Note :I can't ask customer to change the ssl command. Please help. A: they have given me the certificate(OCcert.pem) and private key (OCkey.pem) Why? They should throw that private key away immediately, it is compromised. What was the purpose of this exercise?
{ "language": "en", "url": "https://stackoverflow.com/questions/7545176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to add an intent to launch an app for printing any document I have to develop an andriod app which will be used for printing. So, whenever a user opens any document/image and clicks on print option, my app has to be invoked. Have started working on andriod only a week back, can someone please guide me how to add an intent to achieve this. Thanks in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Creating table out from this array structure in php Im having trouble creating a table out from this array: http://pastebin.com/DXFjfhHJ I started out with this: <table style="width: 100%; text-align: center;"> <tr> <td>Time</td> <td>Aktivitet</td> <td>Duration</td> <td>Metabolisation</td> </tr> then i did: foreach{$training as $time => $metabolisation}{ ?> <tr style="text-align: left;"> <td><?php echo $time; ?></td> <td>Activity name</td> <td>Duration</td> <td><?php echo $metabolisation; ?></td> </tr> <?php } Which works almost.. It shows the right $time ( 03:00 etc. ), but nothing in $metabolisation. And I dont know how to call the Activity, it should be the arrays "name" variable. Same with duration, it should be the arrays "duration" How can I do this? A: foreach($training as $time => $metabolisation){ foreach($metabolisation['entries'] as $entry) { ?> <tr style="text-align: left;"> <td><?php echo $time; ?></td> <td><?php echo $entry['name']; ?></td> <td><?php echo $entry['duartion']; ?></td> <td><?php echo $entry['metabolisation']; ?></td> </tr> <?php } } ?> It probably doesn't output the data in an appropriate form, but you get the idea how to access it. A: Well the structure your using in your pastebin is not compatible with your foreach. You realy need to look deeper in your array structure like this. <?php foreach( $training as $time => $data ): ?> <tr style="text-align: left;"> <td><?php echo $time; ?></td> <td>Total <?php echo $data['entries'][0]['name']; ?></td> <td>Duration <?php echo $data['entries'][0]['duration']; ?></td> <td><?php echo $data['entries'][0]['metabolisation']; ?></td> </tr> <?php endforeach; ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7545182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: ksoap2 connection timeout I am trying to call a .net web service from an android emulator but I am getting connection timeout exception. Before I tried to call my webService I called the http://www.w3schools.com/webservices/tempconvert.asmx without problems. So I am assuming that either I have something wrong in my .net webService either in android application. the .net is [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService] public class Pros : System.Web.Services.WebService { [WebMethod] public List<Product> Get(int pageIndex,int pageSize) { var efUnitOfWork = new EFUnitOfWork(); var productsRepos = new ProductRepository(new EFRepository<Product>(), efUnitOfWork); return (List<Product>)productsRepos.GetByPage(pageIndex, pageSize); } } and the java is private static final String METHOD_NAME = "Get"; private static final String NAMESPACE = "http://tempuri.org/"; private static final String URL = "http://10.0.0.2:2807/webservices/webService.asmx"; private static String SOAP_ACTION = NAMESPACE+METHOD_NAME; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); request.addProperty("pageIndex", "0"); request.addProperty("pageSize", "10"); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet=true; envelope.setOutputSoapObject(request); AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL); androidHttpTransport.call(SOAP_ACTION, envelope); SoapObject result=(SoapObject)envelope.getResponse(); String resultData=result.getProperty(0).toString(); } catch (Exception e) { e.printStackTrace(); } } Am I missing something? A: You can try to increase the timeout for the call like this: AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL, 15000); A: You should try to increase the timeout as mentioned but more importantly you have to move your call into a background thread. Use AsyncTask. Also as discussed in the comment there is a blog post linked in the ksoap2-android wiki that explains the connection stuff in detail. You can NOT use localhost or equivalent since that is on the device but your service runs on a server.. now that I look at the code again .. 10.0.0.2 will not work most likely. Do an ifconfig/ipconfig on the server and use that IP address. I bet it will work then.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Find all paths between two nodes Using a gremlin script and neo4j I try to find all paths between two nodes, descending at most 10 levels down. But all I get as response from the REST API is a java.lang.ArrayIndexOutOfBoundsException: -1 Here is the script: x = g.v(2) y = g.v(6) x.both.loop(10){!it.object.equals(y)}.paths I looked through the documentation, but couldnt find anything relevant for this usecase. A: In Gremlin the argument to loop is the number of steps back that you wish to go and the closure is evaluated to determine when to break out of the loop. In this case, because you have loop(10) it's going to go back way too far to a point where the pipeline is not defined. With the respect to the closure, you'll need to check not only if the object is the one in question, in which case you should stop, but also whether or not you've done 10 loops already. What you really want it something like this: x.both.loop(1){!it.object.equals(y) && it.loops < 10}.paths However, I should add that if there is a cycle in the graph, this will gladly traverse the cycle over and over and result in far too many paths. You can apply some clever filter and sideEffect to avoid visiting nodes multiple times. For more information see the Loop Pattern Page on the Gremlin Wiki.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySQL & FK constraints Is there any point in defining FK constraints in MyISAM? MyISAM doesn't enforce referential integrity, right? So maybe there is no point to FK constraints. A: Although MySQL parses and ignores them on MyISAM tables, I think you should write them for three reasons. * *Preparation: Your code will be ready when MyISAM gets there. *Documentation: Everybody will know what you intended. Much better than trying to figure out where foreign keys are supposed to go a year from now. *Insurance: If MyISAM fails you, you can move directly to InnoDB tables. A: http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-foreign-keys.html At the end of second column: At a later stage, foreign key constraints will be implemented for MyISAM tables as well. apparently in mysql 5.0 'latter stage' has not come yet constraints are needed as an additional validation
{ "language": "en", "url": "https://stackoverflow.com/questions/7545190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to generate video at 60 fps and play it back at 60 fps? For a high-performance scientific purpose we need to render video and play it at 60fps on the device. I assume the usual frame rate of H.264 video is lower than that. Is this possible, or is the framerate fixed? If so, what is the maximum frame rate we can get when playing H.264 video in fullscreen on the device? A: Technical specifications will vary from iOS device to iOS device, so you'll need to check for the hardware you'll actually run this on. For the iPad 2, currently the most powerful of the iOS devices, Apple's technical specifications for video list the following: Video formats supported: H.264 video up to 720p, 30 frames per second, Main Profile level 3.1 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second, Simple Profile with AAC-LC audio up to 160 Kbps per channel, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; Motion JPEG (M-JPEG) up to 35 Mbps, 1280 by 720 pixels, 30 frames per second, audio in ulaw, PCM stereo audio in .avi file format It would appear that fullscreen H.264 playback at 60 FPS is not supported on even the robust hardware of the iPad 2. However, you can indeed render content to the screen at 60 FPS. I do this all the time in both Core Animation heavy applications and ones that use OpenGL ES. If you can generate your content in-application fast enough to display at this rate, you could render it to the screen at 60 FPS, then encode every other frame to video. Given that video encoding is a reasonably expensive operation, and it sounds like you want to run some kind of simulation here as well, I'm guessing that you won't be able to render each frame at 60 FPS for display to the screen on current hardware simply due to the load you'll put on the system. A: Yes, it is possible to encode video as a series of images and then display the images very quickly on screen. The upper limit of the video hardware and the time to decode the images and blit the images into the video card are the bottleneck in this process. As long as your image decoding logic is not too slow, it should be possible to push video data to the graphics card at 60FPS. You could try to implement this yourself with a series of PNG images, but I think you will find that decoding the PNG image will not be fast enough to get 60 FPS playback. You can find some free example code that implements that approach with PNG images in my answer to this question If you cannot get the performance you need, then take a look at my AVAnimator library for iOS, as it already fully solves this problem using memory mapped frames that can be sent directly to the video card from mapped memory.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545191", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: WPF Simple Binding I'm trying to convert my console app to a nice WPF GUI. Am getting a little stuck on this code and was wondering if someone can help? In my xaml I have this: <CheckBox IsChecked="{Binding CL.LoggedIn}"></CheckBox> to try and bind the value of the checkbox to the value of CL.LoggedIn. CL is my ConnectionLibrary.cs class in a referenced class library. In the code behind for the xaml page i declare CL as follows : public ConnectionLibrary CL = new ConnectionLibrary(); In the connection library class I have added :INotifyPropertyChanged to the class declaration and added the following code: public event PropertyChangedEventHandler PropertyChanged; // Create the OnPropertyChanged method to raise the event protected void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } I have changed the LoggedIn property to now look like this: private bool loggedIn; public bool LoggedIn { get { return loggedIn; } set { loggedIn = value; OnPropertyChanged("LoggedIn"); } } However, it doesnt seem to work in my xaml? I dont get any binding errors in the output window, but it doesnt reflect the value of LoggedIn correctly. Any ideas? Thanks! A: Have you set the datacontext of your view? In the code-behind of your XAML file, you need to do: this.DataContext = CL; then the binding is: <CheckBox IsChecked="{Binding LoggedIn}"></CheckBox> The binding will find the the named path (i.e. LoggedIn) on the object that is in the DataContext. EDIT: The default binding is one-way, this means it only gets updated from your ViewModel. For controls that can be inputed data (i.e: TextBox, CheckBox...) you can set the Binding as "TwoWay". The Binding expression becomes: <CheckBox IsChecked="{Binding LoggedIn, Mode="TwoWay"}"></CheckBox> Now whenever the Checked state changes in the UI, it is reflected in your ViewModel. A: When you use Binding like this, it binds to the current DataContext, not to the page itself. The easiest way to fix this would be to set DataContext = this at the end of the constructor of the page. The proper way to fix it would be to use MVVM. That would mean having ConnectionLibrary in a property of another class and set the DataContext to this other class. A: <CheckBox IsChecked="{Binding LoggedIn}"></CheckBox>
{ "language": "en", "url": "https://stackoverflow.com/questions/7545193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Stretch the Checkbox to the cell size I'm using WPF and have DataGrid with checkbox column. the problem is that I would like the checkbox to stretch and fill the cell this is my XAML : <Grid> <Controls:DataGrid ItemsSource="{Binding Persons}" AutoGenerateColumns="False"> <Controls:DataGrid.Columns> <Controls:DataGridTextColumn Binding="{Binding Name}"/> <Controls:DataGridTemplateColumn> <Controls:DataGridTemplateColumn.CellTemplate> <DataTemplate> <CheckBox /> </DataTemplate> </Controls:DataGridTemplateColumn.CellTemplate> </Controls:DataGridTemplateColumn> </Controls:DataGrid.Columns> </Controls:DataGrid> </Grid> A: You can put the CheckBox in a Viewbox, there will still be a small margin though which probably belongs to some control's Template, you could either try and change that template or mess with the Margin if you want to. <Viewbox Margin="-1"> <CheckBox/> </Viewbox>
{ "language": "en", "url": "https://stackoverflow.com/questions/7545195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Question Pattern/Matcher I want to extract the value 5342test behind the name="buddyname" from a fieldset tag. But there are multiple fieldsets in the HTML code. Below the example of the string in the HTML. <fieldset style="display:none"><input type="hidden" name="buddyname" value="5342test" /></fieldset> I have some difficulties to put in the different patterns in Pattern.compile and i just want the value 5342test displayed not the other results, could somebody please help? Thank you. My code: String stringToSearch = "5342test"; Pattern pattern = Pattern.compile("(\\value=\\})"); Matcher m = pattern.matcher(stringToSearch); while (m.find()) { // get the matching group String codeGroup = m.group(1); // print the group System.out.format("'%s'\n", codeGroup); // should be 5342test } A: Use this pattern: Pattern pattern = Pattern.compile("<input[^>]*?value\\s*?=\\s*?\\\"(.*?)\\\""); A: Since you want the input values inside a fieldset tag, you can use this regex pattern. Pattern pattern = Pattern.compile("<fieldset[^>]*>[^<]*<input.+?value\\s*=\\s*\\\"([^\\\"]*)\\\""); Matcher matcher = pattern.matcher("<fieldset style=\"display:none\"><input type=\"hidden\" name=\"buddyname\" value=\"5342test\" /></fieldset>"); if (matcher.find()) System.out.println(matcher.group(1)); //this prints 5342test else System.out.println("Input html does not have a fieldset");
{ "language": "en", "url": "https://stackoverflow.com/questions/7545196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to remove sensitive of Transparent png files in Actions? i have Circle And TriAngles or ... png files. i want terminate Transparent Hits of my png files in cocoa-touch when i click on Rectangle Hits and just Call My Mthods When i Click On Direct Shapes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: multiple focused elements in the browser Is it possible to have multiple elements (such as input elements) focused in the browser. I would like to reproduce the effect of Sublime Text 2. A: It doesn't seem possible. Check out this test: $('#one').focus(function(){ $('#one, #two').focus(); }); Example: http://jsfiddle.net/jasongennaro/epBea/ EDIT If you wanted both fields to look like they had focus, you could fake this by adding divs around the inputs and styling with a border on focus. $('#one').focus(function(){ $('#one, #two').parent().css('border','1px solid red'); }); You also need to remove the outline for each input in the css. Example 2: http://jsfiddle.net/jasongennaro/epBea/1/ Warning: I think this is a bad usability idea, as focus is meant to tell people which field they are working in.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to check if a Windows version is Genuine or not? Is it possible to check whether a Windows installation is Genuine or not programmatically? Lets just say I want to check Windows 7 from C, C++, Java or Python. A: this from CodeProject, in C++ ( Check for Windows Genuine in VC++ ) #include <slpublic.h> #pragma comment(lib,"Slwga.lib") bool IsWindowsGenuine() { GUID uid; RPC_WSTR rpc=(RPC_WSTR)_T("55c92734-d682-4d71-983e-d6ec3f16059f"); UuidFromString(rpc,&uid); SL_GENUINE_STATE state; SLIsGenuineLocal(&uid,&state,NULL); return state == SL_GENUINE_STATE::SL_GEN_STATE_IS_GENUINE; } A: From here: Here is a vbscript that does it strComputer = "." Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") Set colWPA = objWMIService.ExecQuery _ ("Select * from Win32_WindowsProductActivation") For Each objWPA in colWPA Wscript.Echo "Activation Required: " & objWPA.ActivationRequired Wscript.Echo "Description: " & objWPA.Description Wscript.Echo "Product ID: " & objWPA.ProductID Wscript.Echo "Remaining Evaluation Period: " & _ objWPA.RemainingEvaluationPeriod Wscript.Echo "Remaining Grace Period: " & objWPA.RemainingGracePeriod Wscript.Echo "Server Name: " & objWPA.ServerName Next A: The Java solution is to use Process to run the C++ or VBScript solution as a child process.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Maven : How to use Maven for generating Spring and CXF Support Application I need to create a Simple web Application with Spring and CXF Setup I am using apache-maven-3.0.3 Support for this. Please tell me what me what number to enter in mvn command prompt , to generate those required artifacts for this. I tried this way , it only generated the Java Interface and Implementation class * *HelloWorld 2. HelloWorldImpl and two xml files inside WEB-INF * *beans 2. web But i don't know why no jar files have been got created. I tried this way Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): 135: 116 Define value for property 'groupId': : com Define value for property 'artifactId': : MyAPP Define value for property 'version': 1.0-SNAPSHOT: : Define value for property 'package': com: : Confirm properties configuration: groupId: com artifactId: MyAPP version: 1.0-SNAPSHOT package: com Y: : y [INFO] ---------------------------------------------------------------------------- [INFO] Using following parameters for creating project from Old (1.x) Archetype: cxf-jaxws-javafirst:2.1.4 [INFO] ---------------------------------------------------------------------------- [INFO] Parameter: groupId, Value: com [INFO] Parameter: packageName, Value: com [INFO] Parameter: package, Value: com [INFO] Parameter: artifactId, Value: MyAPP [INFO] Parameter: basedir, Value: C:\myapp [INFO] Parameter: version, Value: 1.0-SNAPSHOT [INFO] project created from Old (1.x) Archetype in dir: C:\myapp\MyAPP [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 1:49.062s [INFO] Finished at: Sun Sep 25 16:47:29 IST 2011 [INFO] Final Memory: 6M/15M [INFO] ------------------------------------------------------------------------ A: Archetypes are convenient, but I don't think they are going to be helpful to you for this case. This tutorial is a nice, basic example that outputs a running webapp using Spring and Maven. I would suggest you download the code, have a play around and figure out how it works, then start layering in your CXF functionality. Go forth and build something awesome!
{ "language": "en", "url": "https://stackoverflow.com/questions/7545207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Light-weight alternative to MVC 3 for Asp.net? I simply need to iterate through data in a loop and pass some strings through a ViewBag type collection. MVC 3 does the job but in many cases I find it too complex for my needs. Is there anything closer to the Rails View for Asp.net? (I know about Spark). A: Well, there's WebMatrix which is a lightweight version of ASP.NET MVC. It actually represents only the V(iew) part of MVC. A: You can use razor without MVC 3. However, I believe that how light, heavy or complex your MVC 3 code is, depends on the developer, as MVC 3 gives you much more control than Web Forms. if you follow best practices, I would expect an MVC 3 app to be much lighter weight than an equivalent web forms app unless the app is just one or two pages. There is a learning curve but I think that MVC 3, Razor and the Entity Framework are well worth investing the time in learning them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to get first member of an object in javascript Possible Duplicate: Access the first property of an object I have a javascript object like this: var list = { item1: "a", item2: "b", item3: "c", item4: "d" }; Using reflection in JS, I can say list["item1"] to get or set each member programmatically, but I don't want to rely on the name of the member (object may be extended). So I want to get the first member of this object. If I write the following code it returns undefined. Anybody knows how this can be done? var first = list[0]; // this returns undefined A: for(var key in obj) break; // "key" is the first key here A: Even though some implementations of JavaScript uses lists to make object, they are supposed to be unordered maps. So there is no first one. A: var list = { item1: "a", item2: "b", item3: "c", item4: "d" }; is equivalent to var list = { item2: "b", item1: "a", item3: "c", item4: "d" }; So there is no first element. If you want first element you should use array. A: How do I loop through or enumerate a JavaScript object? You can use the following to get the desired key. for (var key in p) { if (p.hasOwnProperty(key)) { alert(key + " -> " + p[key]); } } You need to use an array if you want to access elements in an indexed way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How can I post to my wall while tagging some friends via Facebook C# SDK (5.1.1)? I want to post on the user's wall while tagging a few of his/her friends in it (up to 8 people). Another option is to post on these 8 friends' wall instead. I used the example given here - http://developers.facebook.com/docs/reference/api/post/#publishing And I tried to add "to" section to it (based on what I saw in Facebook Open Graph API) with no luck. Trying to change posting to .Post("[fbid]/feed") didn't work as well. It just posted on my wall instead. What am I doing wrong? can someone publish a full example? A: The Graph API does not currently support tagging users in posts, although it has been requested as a feature. You could make 8 different wall posts but there is a chance that you application will get disabled for too many wall posts if enough users hide your application or mark it as spam. But to do it, you just do an HTTP POST to /friendId/feed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to send a table-type in parameter to T-SQL while using C# IDataReader? I wrote a t-sql sp that gets a table as parameter. I tried to call it from c#, but didn't know what type to use: database.AddInParameter(command, "@ID", DbType.String, id); database.AddInParameter(command, "@TemplatesIds", DbType.WhatType??, dt); using (IDataReader reader = database.ExecuteReader(command)) { while (reader.Read()) { } } What should I use? A: Since you're using a t-sql then you can use SqlDbType.Structured if you're using a SQLCommand under your (I'm guessing) IDbCommand var dt = new DataTable(); ... set up dt ... par = new SqlParameter("@TemplatesIds", SqlDbType.Structured, dt) There are quite a few examples of using this here on the msdn. A: SqlDbType.Structured http://msdn.microsoft.com/en-us/library/system.data.sqldbtype.aspx A: maybe not the best approach, but works: -- Create the data type CREATE TYPE dbo.PlantList AS TABLE ( plant_code char(1) Not Null Primary Key ) GO extension method public static class DatabaseExtensions { public static void AddTableTypeParameter<T>(this Database database, DbCommand command, string name, string sqlType, IEnumerable<T> values) { var table = new DataTable(); PropertyInfo[] members = values.First().GetType().GetProperties(); foreach (var member in members) { table.Columns.Add(member.Name, member.PropertyType); } foreach (var value in values) { var row = table.NewRow(); row.ItemArray = members.Select(m => m.GetValue(value)).ToArray(); table.Rows.Add(row); } var parameter = new SqlParameter(name, SqlDbType.Structured) { TypeName = sqlType, SqlValue = table }; command.Parameters.Add(parameter); } } and call as follows: database.AddTableTypeParameter(command, "@region_filter_plants", "dbo.PlantList", regionFilterPlants.Select(p => new { plant_code = p }));
{ "language": "en", "url": "https://stackoverflow.com/questions/7545215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: database schema of "don't show me again what I saw before" in mysql I'm making a website that shows you images. And special feature of site is "don't show me again what I saw before". It means, if you see a image, it goes to your "archive" category. There will be so many images and categories. And I need to very smooth schema of database to perfomance. When you click a image, it appears on lightbox and in the lightbox code it sends request with ajax to make this image archived just for you. Is that database schema above performanceful for about 5.000 images and 20.000 users? users user_id user_email pictures picture_id picture_url tags archived user_id picture_id images will appear on front of you with excepting archived images for you from all images on this schema... A: This is a diificult question to answer without knowing all the details. You mention how many users and images there will be. How many images will each user (on average) have in their archived list? If that number is small, the archived table won't approach 100M rows. 100M rows should not be a problem by itself, as the database can handle this. The concern may (or will) be with the way you are going to want to query the data. Something like: SELECT * FROM picture WHERE picture_id NOT IN ( SELECT picture_id FROM archived WHERE user_id = [userIdParameter] ) That will likely not perform very well with 100M rows. Another option would be to cross join users and pictures so that the archived table always contains a Cartesian product. So the table would be: archived user_id picture_id visited Then you could query like so: SELECT p.* FROM picture p INNER JOIN archived a ON p.picture_id = a.picture_id WHERE a.user_id = [userIdParameter] AND a.visited = [false] This should perform acceptably with proper indexing, but would present the problem of having to make sure rows are created in the archived table any time a user or picture is added to the system. It also means you would always have a number of rows equal to pictures * users (100M in your example). That may not be desirable in your case. Bottom line, you are going to have to create some test data that approximates your expected volume and do some performance testing that approximates your load. If you think this is the critical potential performance bottleneck for your system, it will be worth the time investment. A: I used "NOT IN" solution for a while and there is performance problems started. Because I don't have a strong server to execute that query with lot of datas. So, I found the most performanceful answer : "Collection Shuffle" I'm shuffleing the collection with a userid seed and saving just users last image index id. After user comes back, looking to where this user's index id left lastly, showing next id from his collection. This is really light and exactly solution. Thanks for everyone :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7545224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: CoreData (storing new object) in AppDelegate = SIGABRT I've intented to make a simple function in AppDelegate to store some data in database (CoreData) which would be called from various ViewController classes connected do AppDelegate. This is the body of this function: - (void) setSetting:(NSString *)setting :(NSString *)value { NSManagedObject* newSetting = [NSEntityDescription insertNewObjectForEntityForName:@"EntityName" inManagedObjectContext:self.managedObjectContext]; [newSetting setValue:value forKey:setting]; NSError* error; [self.managedObjectContext save:&error]; } But calling this function (even from AppDelegate itself) returns SIGABRT on line with setValue But when I implement the function in ViewController class (replacing self. with proper connection to AppDelegate of course) - it works fine. I don't get it and I would really appreciate some help in creating flexible function in AppDelegate to save the data in database. A: This looks a bit like the key part is not an NSString or the value part is not the correct data type. Please check, and perhaps make the order of the arguments in your function the same as in the setValue:forKey method to avoid confusion. Also, according to the documentation, an exception will be raised if the key is not defined in the model - so double-check your key strings. BTW, if this is your error it is a good idea to move away from KVC and create your own NSManagedObject subclasses instead as a habit - makes life much easier. A: The most likely explanation is that this line: NSManagedObject* newSetting = [NSEntityDescription insertNewObjectForEntityForName:@"EntityName" inManagedObjectContext:self.managedObjectContext]; … returns a nil object either because the entity name is incorrect or because the managedObjectContext is itself nil or otherwise invalid. Since the problem only occurs in the app delegate, I would first suspect some issue with self.managedObjectContext.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bean Validation @NotNull, @NotBlank and @NotEmpty does not work in JSF+Tomcat I am using Hibernate Validation annotations in my JSF managed bean. When I use @NotNull, @NotBlank or @NotEmpty they doesn't seem to be triggered in any way. @NotBlank(message = "{name.required}") public String name; View: <h:outputLabel value="Name:" /> <h:inputText id="name" value="#{person.name}" size="20" /> <h:message for="name" style="color:red" /> How is this caused and how can I solve it? A: Introduction Since you didn't give any feedback on my comment with the question what container you're using, I peeked around in your question history to learn what containers you're all using. As far I found only Tomcat. So I'll for this answer assume that you're indeed using Tomcat as I initially guessed while posting the comment. Make sure you install all JARs Tomcat does not ship with any JSR303 Bean Validation API/implementation out the box. You need to download and install it yourself. That you got those annotations to compile means that you've correctly dropped the hibernate-validator.jar file (naming may differ per version) in /WEB-INF/lib folder of your webapp. That those annotations in turn does not seem to work in any way can only mean that you didn't read the readme.txt and/or forgot to add the JARs from the /lib/required folder of the Hibernate Validator library zip/tgz file: slf4j-api.jar and validation-api.jar. The last one is mandatory in order to get the annotations to actually work. So, to get Hibernate Validator to work in Tomcat, you need the following JARs in webapp's /WEB-INF/lib: * *validation-api.jar (contains the abstract API and the annotation scanner) *hibernate-validator.jar (contains the concrete implementation) *slf4j-api.jar (just to get its logger to work as well) This way @NotBlank and @NotEmpty must work. The @NotNull deserves special attention; empty input fields are namely by default received as empty strings from the client (webbrowser) due to the nature of HTTP request parameters. Empty strings are not the same as null, so the @NotNull will by default never kick in. JSF is however configureable to interpret them as null by just adding the following context parameter to web.xml: <context-param> <param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name> <param-value>true</param-value> </context-param> This way the @NotNull must work as well. BV works but only empty fields not If it still doesn't work (i.e. none of the 3 annotations work, but others like @Size(min=5) for a minimum length of 5 works fine), then chances are big that you've the following context parameter in web.xml as well: <context-param> <param-name>javax.faces.VALIDATE_EMPTY_FIELDS</param-name> <param-value>false</param-value> </context-param> You should then remove it (it defaults to auto, i.e. only when JSR303 Bean Validation API is found in runtime classpath) or to set it to true. BV does not work at all When actually nothing of BV works, also not @Size, @Pattern, etc, then you should verify if you do not have the following in your form: <f:validateBean disabled="true" /> You should then remove it (it will just by default kick in) or to set disabled="false". Make sure you use most recent Mojarra When BV still doesn't work, then verify if you're not using an old Mojarra version between 2.2.3 and 2.2.6. Those versions had a classloading delegate bug causing Bean Validation on Tomcat and clones to be completely invisible. This is reported as Mojarra issue 3183 and fixed in Mojarra 2.2.7. A: I had a similar issue and i was able to overcome the problem by including the below three jars in web-inf lib. Just add the hibernate validator jar and the required jars as provided in the zip file: * *hibernate-validator-4.3.0.Final.jar *jboss-logging-3.1.0.CR2.jar *validation-api-1.0.0.GA.jar A: add <context-param> <param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name> <param-value>true</param-value> </context-param> in web.xml and add <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>2.0.1.Final</version> </dependency> <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.23.Final</version> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-api</artifactId> <version>2.2.13</version> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-impl</artifactId> <version>2.2.13</version> </dependency> in pom.xml A: If it still fails to validate even after adding the above indicated jars, then you might have missed adding tag <mvc:annotation-driven /> in the spring configuration file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: Jquery how add an element to dom Hello I have a function that add combobox into the page, and I need to use the values of these combobox. When I try to acces into the jquery code it don't work. I think that I need to add the element to dom but I don't know how to do that. The id of combo is 'selectCombo' A: You have several choices: * *.prepend() http://api.jquery.com/prepend/ *.append() http://api.jquery.com/append/ *.insertAfter() http://api.jquery.com/insertAfter/ *.insertBefore() http://api.jquery.com/insertBefore/ A: Try this way: $("<div/>", { // PROPERTIES HERE text: "Click me", id: "example", "class": "myDiv", // ('class' is still better in quotes) css: { color: "red", fontSize: "3em", cursor: "pointer" }, on: { mouseenter: function() { console.log("PLEASE... "+ $(this).text()); }, click: function() { console.log("Hy! My ID is: "+ this.id); } }, append: "<i>!!</i>", appendTo: "body" // Finally, append to any selector });
{ "language": "en", "url": "https://stackoverflow.com/questions/7545232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Android Development: Game background loop I'm developing a 2d Game using Canvas/Surfaceview and have a problem with thread. So what I want to accomplish is something in the background that is for example: for each second SpawnEnemy() or ticking seconds or attacking. I tried Thread.wait but that just cause pain and make my game 2fps. here is my gameLoop: import android.graphics.Canvas; public class GameLoopThread extends Thread { static final long FPS = 20; private GameView view; private boolean running = false; public GameLoopThread(GameView view) { this.view = view; } public void setRunning(boolean run) { running = run; } @Override public void run() { long ticksPS = 1000 / FPS; long startTime; long sleepTime; while (running) { Canvas c = null; startTime = System.currentTimeMillis(); try { c = view.getHolder().lockCanvas(); synchronized (view.getHolder()) { view.onDraw(c); } } finally { if (c != null) { view.getHolder().unlockCanvasAndPost(c); } } sleepTime = ticksPS - (System.currentTimeMillis() - startTime); try { if (sleepTime > 0) sleep(sleepTime); else sleep(10); } catch (Exception e) {} } } } So I want something that is ticking in the background (seconds) that doesn't thread.wait. A: you could use AsyncTask for something to run in background A: You should make your thread run the game normally about 60fps, see this example: How can I use the animation framework inside the canvas? If you want for each second to do something then you either count frames in onDraw(), on each 60th frame do it, or if you need a greater precision then in each onDraw() check the system time and do something when a second has elapsed. You should also consider using two methods one for drawing onDraw() and another for the game logic which are called from your thread.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP: Replace specified tag values in PHP Take a look at the HTML example below: <iframe width="AnyNumber" height="AnyNumber"> How can i replace AnyNumber with specified number $1 and $2 for width and height? they can be swapped like: <iframe height="AnyNumber" width="AnyNumber"> A: It reminds me of templates. For example you have you html files like this <div class="nav">@navigationMenu</div> <img src="@imgSrc"> <span>@title</title> <p>@article</p> and then with a simple php class you replace with the desired values, for example: $this->registry->main_layout->set('imgSrc', './img/green.jpg'); There are many tutorials along with the source code (usually a single-simple php class) that implement this. A: $exmpl = '<iframe width="AnyNumber" height="AnyNumber">'; $exmpl = preg_replace('/(<iframe.*?width=").*?"/', "\${1}$argv[1]\"", $exmpl); $exmpl = preg_replace('/(<iframe.*?height=").*?"/', "\${1}$argv[2]\"", $exmpl); A: $exmpl = 'iframe width="AnyNumber" height="AnyNumber">'; $exmpl = str_replace('width="AnyNumber"','width="'.$1.'"',$exmpl); $exmpl = str_replace('height="AnyNumber"','width="'.$2.'"',$exmpl);
{ "language": "en", "url": "https://stackoverflow.com/questions/7545237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Client Server data sharing issue I have a webservice with a mobile application. The user, with the application shares the data on the server - have a constraint in the DB that the name of the shared object is unique per user. Also application stores locally all created data (by the user - that is also shared). I have the following scenario: * *User creates data with data-name X. *User shares this data. *Server has in it DB data-name X for this user *User has a new phone and install the application. *NO INTERNET CONNECTION *user creates again data with data-name X. *it is stored only locally - since NO INTERNET CONNECTION. *Internet connection restored. *Now a BG service run and start sharing all u shared data - in the BG. *The problem found because of the constraint. What should be done to solve the problem? I can popup a new window saying that it already shared and ask the user to rename/overwrite it, give option to D/L this data to its local DB etc. But since it is done in the BG - is it user-friendly to show this popup? Any other ideas? Probably there is a common way of doing it. I can really use some help reagrding this issue. A: for this, you generally don't use a name or something of that sort, but UUIDs - i.e. 32-to-64 character long random strings that uniquely identify an object. When you create an object, just create a UUID on the device and sync this to the server. Heres the documentation of the UUID class in android. While it theoretically feasible to have the same UUIDs, it's something you generally don't worry too much about it, as stated here: http://en.wikipedia.org/wiki/Universally_unique_identifier#Random_UUID_probability_of_duplicates For iOS, you can use the CFUUID class to generate UUID Another name for UUIDs ist GUID, Globaly unique identifiers. Hence, you remove any kind of uniqueness constraint. A: Here is how a recent app I've done handles this: * *A user creates a new record on the mobile device. The new record gets assigned a negative primary key _id number. *The app checks for internet connection and, if a connection exists, the app does an HTTP post to the server, creating the record on the server side. The server then sends back a response creating the new PK _id which gets updated in the app. *If no internet connection, the app creates a record in my db_changes table containing the table name and the PK _id of the new record. *A service runs in 5 minute increments which gets updates from the server and posts new data to the server. The db_changes table is polled each time for any existing inserts or updates that yet to be posted to the server. *Once successful, the record from the db_changes table gets deleted. In my situation, this works perfectly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I copy one colum to another new tables Example my table structure current_db ID email name address phone --------------------------------------------- 1 email@email.com John My Address 123456789 2 email@email.net Peter My Address 123456721 new_db ID email column1 column2 column3 column4 ------------------------------------------ How do I copy only email address from current_db to new_db. A: Use the INSERT … SELECT syntax: INSERT INTO `new_db` ( `email` ) SELECT `email` FROM `current_db` A: Think I mis-understood... early for me. You mentioned from one database to another, not table to table. If the tables were actually kept in separate "databases", such as rebuilding, or porting to a new database from an old and you were restructuring tables.... You would have to prefocus to the new database and create your table from an insert of the column desired from database.table from another. use New_db create table x select email from Other_Db.YourTable However, from re-reading and seeing the other answer, that's probably closer to what you want insert into OneTable ( columnX, columnY, columnZ ) values select x, y, z from OtherTable where...
{ "language": "en", "url": "https://stackoverflow.com/questions/7545242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Merge standalone webapp and GAE in Go I'm working on a very simple web app, written in Go language. I have a standalone version and now port it to GAE. It seems like there is very small changes, mainly concerning datastore API (in the standalone version I need just files). I also need to include appengine packages and use init() instead of main(). Is there any simple way to merge both versions? As there is no preprocessor in Go, it seems like I must write a GAE-compatible API for the standalone version and use this mock module for standalone build and use real API for GAE version. But it sounds like an overkill to me. Another problem is that GAE might be using older Go version (e.g. now recent Go release uses new template package, but GAE uses older one, and they are incompatible). So, is there any change to handle such differences at build time or on runtime? Thanks, Serge UPD: Now GAE uses the same Go version (r60), as the stable standalone compiler, so the abstraction level is really simple now. A: In broad terms, use abstraction. Provide interfaces for persistence, and write two implementations for that, one based on the datastore, and one based on local files. Then, write a separate main/init module for each platform, which instantiates the appropriate persistence interface, and passes it to your main application to use. A: My immediate answer would be (if you want to maintain both GAE and non-GAE versions) that you use a reliable VCS which is good at merging (probably git or hg), and maintain separate branches for each version. The GAE API fits in reasonably well with Go, so there shouldn't be too many changes. As for the issue of different versions, you should probably maintain code in the GAE version and use gofix (which is unfortunately one-way) to make a release-compatible version. The only place where this is likely to cause trouble is if you use the template package, which is in the process of being deprecated; if necessary you could include the new template package in your GAE bundle. If you end up with GAE code which you don't want to run on Google's servers, you can also look into AppScale.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: mysqli.dll and mysql.dll not mentioned in phpinfo I have read this post and it didn't really help. My php.ini file (http://www.edisk.cz/stahni/09234/php.ini_69.47KB.html) contains the correct path of ext directory. While my ext directory contains a php_mysql.dll and php_mysqli.dll libraries, there's not a word of that in my phpinfo. Is there a way to make it right? http://prntscr.com/3707m This is my error produced by php.exe. A: You most likely have two separate php.ini files - one for your web server, one for the command line interface. Make sure you're editing the correct file; Run: php.exe --ini which will give you output similar to the one below: C:\>php --ini Configuration File (php.ini) Path: C:\Windows Loaded Configuration File: C:\Path\To\Your\php\php.ini Scan for additional .ini files in: (none) Additional .ini files parsed: (none) Now, edit the php.ini file and make sure that not only the following lines are un-commented: extension=php_mysql.dll extension=php_mysqli.dll but also this one (which, according to the file you've posted, you have commented out at the moment): ; extension_dir = "ext" The above one should be configured to point to your ext directory, where the php_mysql.dll file is stored. Like this (remember about double quotes): extension_dir="C:\Path\To\Your\php\ext" Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery-ui: enabling disabled button doesn't restore event I have a problem: after enable button, it look like enabled but isn't clickable. (reloading page fix this problem, but i won't do it). Firstly, on (document).ready, i disable this button. For enable i do: $("#submit_order").attr('disabled', false).removeClass( 'ui-state-disabled' ); for disable: $("#submit_order").attr('disabled', true).addClass( 'ui-state-disabled' ); HTML code: <button id="submit_order">Send an order</button> button jQuery code: $( "#submit_order" ) .button() .click(function() { $( "#dialog-form" ).dialog( "open" ); }); When i clicked this button after enabling, code above didn't invoke. A: Yes, previous answers may work for you, but for me the events weren't firing when I "re-enabled" the button with .removeAttr("disabled") and using .removeClass("ui-state-disabled"). The official answer appears to be $(".selector").button("option", "disabled", true); to disable, and $(".selector").button("option", "disabled", false); to enable a jQueryUI button() from http://jqueryui.com/demos/button/#option-disabled A: When You are writing $("#submit_order").attr(...) it means that you use stanadard attributes. You are inconsistent: once You are using mentioned above method, and another time you are writing: $( "#submit_order" ).button()..... try this: $("#submit_order").button().attr('disabled', false).removeClass( 'ui-state-disabled' ); $("#submit_order").button().attr('disabled', true).addClass( 'ui-state-disabled' ); A: As I remember jQueryUI extends jQuery library by providing different components where most of them have methods enable() and disable(). You may try alternative (IMHO more preferred) way: $('#submit_order').button().enable(); and $('#submit_order').button().disable(); this will free Your mind from manual managing attributes - JQUI do this self. This is powerful, because you may create buttons using different underlying elements (so that enabling and disabling them will use different methods) ex. Standard button uses attribute disabled="disabled" (browser implementation - standard) But button made from anchor doesn't support this at all. A: To enable try like this: $('#submit_order').removeAttr('disabled').removeClass('ui-state-disabled'); and to disable: $('#submit_order').attr('disabled', 'disabled').addClass('ui-state-disabled');
{ "language": "en", "url": "https://stackoverflow.com/questions/7545248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Can't install the "refinerycms-memberships" gem What can i do if i know there is a github repository for the gem but in the terminal i couldn't install the gem via 'gem install' or 'bundle install' because it fails with the following error: Could not find gem 'refinerycms-memberships (= 1.0)' in any of the gem sources listed in your Gemfile. I couldn't find it on rubygems.org either, so is there any other way of getting it installed :( A: If you're using bundle install then I assume you're installing using a Gemfile. In this case, you can specify a git repo: gem refinerycms-memberships, :git => "git://path.to/git/repo" A: Specifically for this gem, I found this line in my Gemfile to work for me: gem 'refinerycms-memberships', '~> 2.0.0', :git => 'https://github.com/rbriank/refinerycms_membership.git' Depending when you see this post, you might need to modify the version or possible add the :branch => .... option.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Perl syntax error: Bareword found where operator expected As the title suggests how could I accomplish this? I have been following a tutorial, but I get a syntax error: Bareword found where operator expected at arrays_and_variables.pl line 26, near "$2names" (Missing operator before names?) syntax error at arrays_and_variables.pl line 26, near "$2names " Execution of arrays_and_variables.pl aborted due to compilation errors. The code I have so far is: @names = ('james','dylan','max'); # join elements of array into a schalar variable. $2names = join ('', @names); print $s2names; A: 2names is an invalid variable name. Names can't start with a number—they have to begin with a letter or an underscore.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Android and Facebook share intent I'm developing an Android app and am interested to know how you can update the app user's status from within the app using Android's share intents. Having looked through Facebook's SDK it appears that this is easy enough to do, however I'm keen to allow the user to do it via the regular Share Intent pop up window? seen here: I have tried the usual share intent code, however this no longer appears to work for Facebook. public void invokeShare(Activity activity, String quote, String credit) { Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, activity.getString(R.string.share_subject)); shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Example text"); activity.startActivity(Intent.createChooser(shareIntent, activity.getString(R.string.share_title))); } UPDATE: Having done more digging, it looks as though it's a bug with Facebook's app that has yet to be resolved! (facebook bug) For the mean time it looks like I'm just going to have to put up with the negative "Sharing doesn't work!!!" reviews. Cheers Facebook :*( A: The Facebook application does not handle either the EXTRA_SUBJECT or EXTRA_TEXT fields. Here is bug link: https://developers.facebook.com/bugs/332619626816423 Thanks @billynomates: The thing is, if you put a URL in the EXTRA_TEXT field, it does work. It's like they're intentionally stripping out any text. A: I found out you can only share either Text or Image, not both using Intents. Below code shares only Image if exists, or only Text if Image does not exits. If you want to share both, you need to use Facebook SDK from here. If you use other solution instead of below code, don't forget to specify package name com.facebook.lite as well, which is package name of Facebook Lite. I haven't test but com.facebook.orca is package name of Facebook Messenger if you want to target that too. You can add more methods for sharing with WhatsApp, Twitter ... public class IntentShareHelper { /** * <b>Beware,</b> this shares only image if exists, or only text if image does not exits. Can't share both */ public static void shareOnFacebook(AppCompatActivity appCompatActivity, String textBody, Uri fileUri) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT,!TextUtils.isEmpty(textBody) ? textBody : ""); if (fileUri != null) { intent.putExtra(Intent.EXTRA_STREAM, fileUri); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); intent.setType("image/*"); } boolean facebookAppFound = false; List<ResolveInfo> matches = appCompatActivity.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo info : matches) { if (info.activityInfo.packageName.toLowerCase().startsWith("com.facebook.katana") || info.activityInfo.packageName.toLowerCase().startsWith("com.facebook.lite")) { intent.setPackage(info.activityInfo.packageName); facebookAppFound = true; break; } } if (facebookAppFound) { appCompatActivity.startActivity(intent); } else { showWarningDialog(appCompatActivity, appCompatActivity.getString(R.string.error_activity_not_found)); } } public static void shareOnWhatsapp(AppCompatActivity appCompatActivity, String textBody, Uri fileUri){...} private static void showWarningDialog(Context context, String message) { new AlertDialog.Builder(context) .setMessage(message) .setNegativeButton(context.getString(R.string.close), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .setCancelable(true) .create().show(); } } For getting Uri from File, use below class: public class UtilityFile { public static @Nullable Uri getUriFromFile(Context context, @Nullable File file) { if (file == null) return null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { try { return FileProvider.getUriForFile(context, "com.my.package.fileprovider", file); } catch (Exception e) { e.printStackTrace(); return null; } } else { return Uri.fromFile(file); } } // Returns the URI path to the Bitmap displayed in specified ImageView public static Uri getLocalBitmapUri(Context context, ImageView imageView) { Drawable drawable = imageView.getDrawable(); Bitmap bmp = null; if (drawable instanceof BitmapDrawable) { bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap(); } else { return null; } // Store image to default external storage directory Uri bmpUri = null; try { // Use methods on Context to access package-specific directories on external storage. // This way, you don't need to request external read/write permission. File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".png"); FileOutputStream out = new FileOutputStream(file); bmp.compress(Bitmap.CompressFormat.PNG, 90, out); out.close(); bmpUri = getUriFromFile(context, file); } catch (IOException e) { e.printStackTrace(); } return bmpUri; } } For writing FileProvider, use this link: https://github.com/codepath/android_guides/wiki/Sharing-Content-with-Intents A: Here is what I did (for text). In the code, I copy whatever text is needed to clipboard. The first time an individual tries to use the share intent button, I pop up a notification that explains if they wish to share to facebook, they need to click 'Facebook' and then long press to paste (this is to make them aware that Facebook has BROKEN the android intent system). Then the relevant information is in the field. I might also include a link to this post so users can complain too... private void setClipboardText(String text) { // TODO int sdk = android.os.Build.VERSION.SDK_INT; if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(text); } else { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData.newPlainText("text label",text); clipboard.setPrimaryClip(clip); } } Below is a method for dealing w/prior versions public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_item_share: Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, "text here"); ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); //TODO ClipData clip = ClipData.newPlainText("label", "text here"); clipboard.setPrimaryClip(clip); setShareIntent(shareIntent); break; } return super.onOptionsItemSelected(item); } A: In Lollipop (21), you can use Intent.EXTRA_REPLACEMENT_EXTRAS to override the intent for Facebook specifically (and specify a link only) https://developer.android.com/reference/android/content/Intent.html#EXTRA_REPLACEMENT_EXTRAS private void doShareLink(String text, String link) { Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("text/plain"); Intent chooserIntent = Intent.createChooser(shareIntent, getString(R.string.share_via)); // for 21+, we can use EXTRA_REPLACEMENT_EXTRAS to support the specific case of Facebook // (only supports a link) // >=21: facebook=link, other=text+link // <=20: all=link if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { shareIntent.putExtra(Intent.EXTRA_TEXT, text + " " + link); Bundle facebookBundle = new Bundle(); facebookBundle.putString(Intent.EXTRA_TEXT, link); Bundle replacement = new Bundle(); replacement.putBundle("com.facebook.katana", facebookBundle); chooserIntent.putExtra(Intent.EXTRA_REPLACEMENT_EXTRAS, replacement); } else { shareIntent.putExtra(Intent.EXTRA_TEXT, link); } chooserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(chooserIntent); } A: Seems in version 4.0.0 of Facebook so many things has changed. This is my code which is working fine. Hope it helps you. /** * Facebook does not support sharing content without using their SDK however * it is possible to share URL * * @param content * @param url */ private void shareOnFacebook(String content, String url) { try { // TODO: This part does not work properly based on my test Intent fbIntent = new Intent(Intent.ACTION_SEND); fbIntent.setType("text/plain"); fbIntent.putExtra(Intent.EXTRA_TEXT, content); fbIntent.putExtra(Intent.EXTRA_STREAM, url); fbIntent.addCategory(Intent.CATEGORY_LAUNCHER); fbIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); fbIntent.setComponent(new ComponentName("com.facebook.katana", "com.facebook.composer.shareintent.ImplicitShareIntentHandler")); startActivity(fbIntent); return; } catch (Exception e) { // User doesn't have Facebook app installed. Try sharing through browser. } // If we failed (not native FB app installed), try share through SEND String sharerUrl = "https://www.facebook.com/sharer/sharer.php?u=" + url; SupportUtils.doShowUri(this.getActivity(), sharerUrl); } A: This solution works aswell. If there is no Facebook installed, it just runs the normal share-dialog. If there is and you are not logged in, it goes to the login screen. If you are logged in, it will open the share dialog and put in the "Share url" from the Intent Extra. Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_TEXT, "Share url"); intent.setType("text/plain"); List<ResolveInfo> matches = getMainFragmentActivity().getPackageManager().queryIntentActivities(intent, 0); for (ResolveInfo info : matches) { if (info.activityInfo.packageName.toLowerCase().contains("facebook")) { intent.setPackage(info.activityInfo.packageName); } } startActivity(intent); A: The usual way The usual way to create what you're asking for, is to simply do the following: Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, "The status update text"); startActivity(Intent.createChooser(intent, "Dialog title text")); This works without any issues for me. The alternative way (maybe) The potential problem with doing this, is that you're also allowing the message to be sent via e-mail, SMS, etc. The following code is something I'm using in an application, that allows the user to send me an e-mail using Gmail. I'm guessing you could try to change it to make it work with Facebook only. I'm not sure how it responds to any errors or exceptions (I'm guessing that would occur if Facebook is not installed), so you might have to test it a bit. try { Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); String[] recipients = new String[]{"e-mail address"}; emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, recipients); emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "E-mail subject"); emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "E-mail text"); emailIntent.setType("plain/text"); // This is incorrect MIME, but Gmail is one of the only apps that responds to it - this might need to be replaced with text/plain for Facebook final PackageManager pm = getPackageManager(); final List<ResolveInfo> matches = pm.queryIntentActivities(emailIntent, 0); ResolveInfo best = null; for (final ResolveInfo info : matches) if (info.activityInfo.packageName.endsWith(".gm") || info.activityInfo.name.toLowerCase().contains("gmail")) best = info; if (best != null) emailIntent.setClassName(best.activityInfo.packageName, best.activityInfo.name); startActivity(emailIntent); } catch (Exception e) { Toast.makeText(this, "Application not found", Toast.LENGTH_SHORT).show(); } A: Apparently Facebook no longer (as of 2014) allows you to customise the sharing screen, no matter if you are just opening sharer.php URL or using Android intents in more specialised ways. See for example these answers: * *"Sharer.php no longer allows you to customize." *"You need to use Facebook Android SDK or Easy Facebook Android SDK to share." Anyway, using plain Intents, you can still share a URL, but not any default text with it, as billynomates commented. (Also, if you have no URL to share, just launching Facebook app with empty "Write Post" (i.e. status update) dialog is equally easy; use the code below but leave out EXTRA_TEXT.) Here's the best solution I've found that does not involve using any Facebook SDKs. This code opens the official Facebook app directly if it's installed, and otherwise falls back to opening sharer.php in a browser. (Most of the other solutions in this question bring up a huge "Complete action using…" dialog which isn't optimal at all!) String urlToShare = "https://stackoverflow.com/questions/7545254"; Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); // intent.putExtra(Intent.EXTRA_SUBJECT, "Foo bar"); // NB: has no effect! intent.putExtra(Intent.EXTRA_TEXT, urlToShare); // See if official Facebook app is found boolean facebookAppFound = false; List<ResolveInfo> matches = getPackageManager().queryIntentActivities(intent, 0); for (ResolveInfo info : matches) { if (info.activityInfo.packageName.toLowerCase().startsWith("com.facebook.katana")) { intent.setPackage(info.activityInfo.packageName); facebookAppFound = true; break; } } // As fallback, launch sharer.php in a browser if (!facebookAppFound) { String sharerUrl = "https://www.facebook.com/sharer/sharer.php?u=" + urlToShare; intent = new Intent(Intent.ACTION_VIEW, Uri.parse(sharerUrl)); } startActivity(intent); (Regarding the com.facebook.katana package name, see MatheusJardimB's comment.) The result looks like this on my Nexus 7 (Android 4.4) with Facebook app installed: A: Here is something I did which open Facebook App with Link shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setComponent(new ComponentName("com.facebook.katana", "com.facebook.katana.activity.composer.ImplicitShareIntentHandler")); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, videoUrl); A: public void invokeShare(Activity activity, String quote, String credit) { Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, activity.getString(R.string.share_subject)); shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Example text"); shareIntent.putExtra("com.facebook.platform.extra.APPLICATION_ID", activity.getString(R.string.app_id)); activity.startActivity(Intent.createChooser(shareIntent, activity.getString(R.string.share_title))); } A: Facebook does not allow to share plain text data with Intent.EXTRA_TEXT but You can share text+link with facebook messanger using this, this works fine for me Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, text+url link); sendIntent.setType("text/plain"); sendIntent.setPackage("com.facebook.orca"); startActivity(sendIntent); A: The easiest way that I could find to pass a message from my app to facebook was programmatically copy to the clipboard and alert the user that they have the option to paste. It saves the user from manually doing it; my app is not pasting but the user might. ... if (app.equals("facebook")) { // overcome fb 'putExtra' constraint; // copy message to clipboard for user to paste into fb. ClipboardManager cb = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("post", msg); cb.setPrimaryClip(clip); // tell the to PASTE POST with option to stop showing this dialogue showDialog(this, getString(R.string.facebook_post)); } startActivity(appIntent); ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7545254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "89" }
Q: Why isn't there a document.createHTMLNode()? I want to insert html at the current range (a W3C Range). I guess i have to use the method insertNode. And it works great with text. Example: var node = document.createTextNode("some text"); range.insertNode(node); The problem is that i want to insert html (might be something like "<h1>test</h1>some more text"). And there is no createHTMLNode(). I've tried to use createElement('div'), give it an id, and the html as innerHTML and then trying to replace it with it's nodeValue after inserting it but it gives me DOM Errors. Is there a way to do this without getting an extra html-element around the html i want to insert? A: Because "<h1>test</h1>some more text" consists of an HTML element and two pieces of text. It isn't a node. If you want to insert HTML then use innerHTML. Is there a way to do this without getting an extra html-element around the html i want to insert? Create an element (don't add it to the document). Set its innerHTML. Then move all its child nodes by looping over foo.childNodes. A: In some browsers (notably not any version of IE), Range objects have an originally non-standard createContextualFragment() that may help. It's likely that future versions of browsers such as IE will implement this now that it has been standardized. Here's an example: var frag = range.createContextualFragment("<h1>test</h1>some more text"); range.insertNode(frag); A: Try function createHTMLNode(htmlCode, tooltip) { // create html node var htmlNode = document.createElement('span'); htmlNode.innerHTML = htmlCode htmlNode.className = 'treehtml'; htmlNode.setAttribute('title', tooltip); return htmlNode; } From: http://www.koders.com/javascript/fid21CDC3EB9772B0A50EA149866133F0269A1D37FA.aspx A: Instead of innerHTML just use appendChild(element); this may help you. If you want comment here, and I will give you an example. A: The Range.insertNode() method inserts a node at the start of the Range. var range = window.getSelection().getRangeAt(0); var node = document.createElement('b'); node.innerHTML = 'bold text'; range.insertNode(node); Resources https://developer.mozilla.org/en-US/docs/Web/API/range/insertNode
{ "language": "en", "url": "https://stackoverflow.com/questions/7545267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Draw a path on a street Is there a way to draw path along the streets. I'm getting coords from gps and drawing path with overlay by them, but sometimes pathes are little curvy. Can i bind them to streets?
{ "language": "en", "url": "https://stackoverflow.com/questions/7545272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Setting colors in Terminal leads to strange character line limit I found an annoying bug while coloring the prompt of my Terminal. If I set my prompt to a colored one, such as export PS1='\e[1;34m[\e[0;31m\D{%Hh%M} \e[0;32m\u\e[0m@\e[0;35m\h\e[0m:\e[0;36m\w\e[1;34m]\e[0m $ ' then it starts to break when I get some size in the input line: In other words, when my line reaches some limit, it starts over itself! Once I fill the same line again, then it works well, going to the next line. Have anyone seen this problem, too? Do you have a solution? The problem also happens in iTerm. A: This is a duplicate of Mac Terminal.app annoying bug - How to fix it? from StackOverflow. The problem is that you must surround terminal control characters in square brackets \[ … \] so that the bash shell doesn't count them when calculating the length of the command prompt. Since this is a generic shell/terminal question and not specific to Mac OS X or Terminal, this should probably be migrated to StackOverflow and made a duplicate of the other question. (However, I don't have privilege to do either.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7545275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Persistent variable on iframe? I have a <div> being dynamically created, and it contains an <iframe>. The <iframe> may close itself, at which point the <div> is removed. So far I have: var div = document.createElement('div'), ifr = document.createElement('iframe'); // some styles and stuff here, including ifr.src ifr.contentWindow.container = div; // Note that domains are the same // within the iframe's code, possibly a "close" link or after completing an operation container.parentNode.removeChild(container); It works. But only if the page within the iframe is the one that was there to start with. If a link is clicked to another page, window.container is no longer defined. I know I can use window.name to store data persistent to a window, but that it limited to data that can be serialised. To my knowledge, you can't serialise a DOM node, other than by assigning it an ID and storing that. I would like to avoid such arbitrary IDs, so if anyone can suggest a better solution I would be very grateful. A: Use this code: //At the frame: var parentFrames = parent.document.getElementsByTagName("iframe"); for(var i=parentFrames.length-1; i>=0; i--){ if(parentFrames[i].contentWindow == window) { parentFrames[i].parentNode.removeChild(parentFrames[i]); //Removes frame //Add an extra `.parent` at each side of the expression to remove the `div`. break; } } A: Pages loaded into your <iframe> can use "window.parent" to get to the containing page. Thus, instead of keeping some "magic" reference in the <iframe>, keep it on the containing page and have the "child" pages look for it. function closeMe() { // inside the iframe page window.parent.frameContainer.removeChild(window.parent.removableFrame); } In addition to "parent", the "top" property of "window" references the top-most context when there's a chain of windows (frames) longer than just one step (so, an <iframe> in an <iframe> etc).
{ "language": "en", "url": "https://stackoverflow.com/questions/7545277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PhoneGap, jQuery Mobile and Retina Display I am working on a PhoneGap application using jQuery Mobile. Currently I am only testing in the iPhone and iPhone Retina-simulators. When I open up the application in Retina-mode, the application's density is correct but the page is only half the screen size on both dimensions. My own guess is that jQuery Mobile's css does not scale up the widths and heights, but I haven't been able to find anything about this. My HTML has this: <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" /> And then I execute this Javascript: if ($.mobile.media("screen and (min-width: 320px)")) { if ($.mobile.media("screen and (-webkit-min-device-pixel-ratio: 2)")) { $('meta[name=viewport]').attr('content','width=device-width, user-scalable=no,initial-scale=.5, maximum-scale=.5, minimum-scale=.5'); } } What am I missing? A: I think you are guessing correct. Look at the JQM.css file. It only includes media queries for hi-res/lo-res icons. Everything else is "as is" on retina and non-retina devices, so JQM only supports retina in terms of icon-size. By specifying initial-scale=.5, maximum-scale=.5, minimum-scale=.5 you are locking everything in at 50%. So there is your non-scalable half page. The more you tailor for retina ("high-end") devices the more trouble you will have with standard browsers (especially "low end", like IE7). Check the JQM iconsprite positioning in IE7 for example - if you don't include a script like respond.js to support media queries, icons will be off-postion. I think there is currently just not enough retina devices to warrant JQM providing a cross-browser retina and non-retina solution. I found some good info here. I also did a CSS-only iOS tab-bar, which works down to IE7. Check the CSS required in my plugin to just make icons and gradient backgrounds look good on all browsers and the amount of extras CSS necessary to tailor for IE7+8. A retina/non-retina JQM.css file would be nice to have but hard to download :-) A: In your case you have to target images only and not the entire viewport. the images have to half size down than your normal display.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: javascript copy input file and get full file path My first question is: - is it possible to copy from 1 file input data to another file input data? what i mean is: I have this input : <input type="file" name="fileinput1" /> Now I want to take what the user browse and copy the data to <input type="file" name="fileinput2" /> Is that possible? Second question, I have this element on my HTML input multiple="multiple" it let me choose few files. Now I can see in the bottom that the names are getting together like this: "img1" "img2" "img3" "img4" Is there any way to separate this into few inputs? Like to write inputs with JavaScript and with the path to everyone of them, is that possible? A: is it possible to copy from 1 file input data to another file input data? No. File inputs are read only. is there any way to separate this into few inputs? No.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: help me design my login.jsp page I want user to provide login + password to login to my webapp. If he fails some times captcha comes to action. I wonder what can I do, to remove java code from it, and to make it more readable and firstly - safety? If I move my second 'captch'ed' form to different JSP, which would be called by servlet when needed - how can I force user to use it? how can I block data sent via 'normal' login.jsp then? <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@ page import="net.tanesha.recaptcha.ReCaptcha" %> <%@ page import="net.tanesha.recaptcha.ReCaptchaFactory" %> <!DOCTYPE html> <html> <head> <title>User Login JSP</title> <script lang="JavaScript"> function trim(s) { return s.replace( /^\s*/, "" ).replace( /\s*$/, "" ); } function validate() { if(trim(document.frmLogin.userName.value)=="") { alert("Login empty"); document.frmLogin.userName.focus(); return false; } else if(trim(document.frmLogin.userPassword.value)=="") { alert("password empty"); document.frmLogin.userPassword.focus(); return false; } } function validate() { if(trim(document.frmLogin2.userName.value)=="") { alert("Login empty"); document.frmLogin2.userName.focus(); return false; } else if(trim(document.frmLogin2.userPassword.value)=="") { alert("password empty"); document.frmLogin2.userPassword.focus(); return false; } } </script> </head> <body> <% Object failCounter = session.getAttribute("failCounter"); int fails = 0; if (failCounter != null) { fails = (Integer) failCounter; } if (fails < 3) { %> <form name="frmLogin" onSubmit="return validate();" action="validateLogin" method="post"> User Name <input type="text" name="userName" /><br /> Password <input type="password" name="userPassword" /><br /> <input type="submit" name="sSubmit" value="Submit" /> </form> <%} else { %> <form name="frmLogin2" onSubmit="return validate2();" action="validateCaptcha" method="post"> User Name <input type="text" name="userName" /><br /> Password <input type="password" name="userPassword" /><br /> <% ReCaptcha c = ReCaptchaFactory.newReCaptcha(PUBLIC_KEY, PRIVATE_KEY, false); out.print(c.createRecaptchaHtml(null, null)); %> <input type="submit" name="sSubmit2" value="submit" /> </form> <% } %> </body> </html> A: I wonder what can I do, to remove java code from it, and to make it more readable and firstly - safety? Since a servlet is not an option, you have to resort to JSP includes. Add the following to top of your JSP: <jsp:include page="/WEB-INF/loginAction.jsp" /> with <% if ("GET".equals(request.getMethod())) { // Do here the job as you would in a normal servlet doGet() method. // You only don't need to call RequestDispatcher#forward(). } else ("POST".equals(request.getMethod())) { // Do here the job as you would do in a normal servlet doPost() method. // You only don't need to call RequestDispatcher#forward(). } %> Let the form finally just submit to self, i.e. remove action. That bunch of JavaScript can also be refactored into a standalone .js file which you reference in <head>. <script src="validator.js"></script> Finally, you're repeating yourself in the form's code. Don't repeat yourself. <form method="post" onsubmit="validate(this)"> User Name <input type="text" name="username" /><br /> Password <input type="password" name="password" /><br /> <% if (request.getAttribute("captcha") != null) { %> Captcha <input type="text" name="captcha" /><br /> <img src="<%= request.getAttribute("captcha") %>" /><br /> <% } %> <input type="submit" value="Submit" /> </form> Or if you have chance to use JSTL, do <form method="post" onsubmit="validate(this)"> User Name <input type="text" name="username" /><br /> Password <input type="password" name="password" /><br /> <c:if test="${not empty captcha}"> Captcha <input type="text" name="captcha" /><br /> <img src="${captcha}" /><br /> </c:if> <input type="submit" value="Submit" /> </form> Further I fail to understand the safety point. Please be more specific. Note that your validation won't work whenever the enduser disables JS. Check our servlets wiki page for a server side validation example. If I move my second 'captch'ed' form to different JSP, which would be called by servlet when needed - how can I force user to use it? how can I block data sent via 'normal' login.jsp then? Just check the session attribute if the user needs to enter a captcha. A: Thanks to @BalusC i managed to refactor my page to this: <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <title>User Login JSP</title> <script type="text/javascript" src="javascript/formDataValidator.js"></script> </head> <body> <form name="frmLogin" onSubmit="return validate();" action="validateCaptcha" method="post"> User Name <input type="text" name="userName" /><br /> Password <input type="password" name="userPassword" /><br /> <c:if test="${ (sessionScope.failCounter != null) && (sessionScope.failCounter > 2 ) }"> <script type="text/javascript" src="http://api.recaptcha.net/challenge?k=6Ld9k8cSAAAAAB6jx0I_wu4f0n2zUL7QqYOC5JgM"></script> </c:if> <input type="submit" name="sSubmit" value="Submit" /> </form> </body> </html> With external JS file. Using scriptlet for captchha wasn't needed, so i replaced it with this what was created inside out.print which was allways the same String = script call. So IMO it was worth doing this refacor :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7545289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Doctrine2 fetching rows that have manyToMany association by QueryBuilder everyone. I have 2 entities City and POI. Mapping looks like this: class City { /** * @ORM\ManyToMany(targetEntity="POI", mappedBy="cities") * @ORM\OrderBy({"position" = "ASC"}) */ protected $pois; and class POI { /** * @ORM\ManyToMany(targetEntity="City", inversedBy="pois") * @ORM\JoinTable(name="poi_cities") */ protected $cities; I would like to fetch all POIs that have at least 1 association with some City using QueryBuilder. I should probably use exists() function but I don't quiet know how. A: You'd have to Left join them and check if cities is null. $qb->select('p', 'c') ->from('AcmeDemoBundle:POI', 'p') ->leftJoin('p.cities', 'c') ->where('c IS NOT NULL'); I haven't tested it, but I hope it gives you the general direction. You can read more about the QueryBuilder from here. A: Docrine2 was changed in 2013, so the other solution displays error Error: Cannot add having condition on a non result variable. Now we cannot use joined alias just as a condition variable. We should use any of its properties like c.id So you should fix the code to $qb->select('p', 'c') ->from('AcmeDemoBundle:POI', 'p') ->leftJoin('p.cities', 'c') ->where('c.id IS NOT NULL'); $results = $qb->getQuery()->execute(); If you want to select entities that does not have any cities, use IS NULL. $qb->leftJoin('p.cities', 'city') ->where('city.id IS NULL') ->getQuery() ->execute(); Description of a problem and link to the commit that responsible for that - http://www.doctrine-project.org/jira/browse/DDC-2780
{ "language": "en", "url": "https://stackoverflow.com/questions/7545295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Vb.net Read From Console When Using A Windows Form Application Hi all I have a problem with reading and writing to the console from a windows form application. I am running visual studios 2010 and I am coding in visual basic. The current code that I have is as follows: Declare Function AttachConsole Lib "kernel32.dll" (ByVal dwProcessId As Int32) As Boolean Declare Function FreeConsole Lib "kernel32.dll" () As Boolean System.Console.Write("abc") Dim test as string = Console.ReadLine() System.Console.Clear() ect FreeConsole() With the following code I can write to the console but I cannot read from it, any ideas?
{ "language": "en", "url": "https://stackoverflow.com/questions/7545297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: (distutil + shutil) * copytree =? I'd like the ignore pattern that shutil's copytree function provides. And I want the src tree to replace all existent files/folders in the dest directory like distutil.dir_util.copy_tree. I'm a fairly new Python user, and can't seem to find any posts on this. A: I was going to say this earler but I didn't. http://docs.python.org/library/shutil.html has a version of the copytree function. I looked at it to see if it would just replace existing files and from what I could tell it would overwrite existing files, but it fails if any of the directories already exist. Due to os.mkdirs failing if the directories already exist. The needed imports: import os import os.path import shutil taking _mkdir from http://code.activestate.com/recipes/82465-a-friendly-mkdir/ (a commenter over there mentions that os.mkdirs has most of the same behavior but doesn't notice that _mkdir doesn't fail if any of the directories to be made already exist) def _mkdir(newdir): """works the way a good mkdir should :) - already exists, silently complete - regular file in the way, raise an exception - parent directory(ies) does not exist, make them as well """ if os.path.isdir(newdir): pass elif os.path.isfile(newdir): raise OSError("a file with the same name as the desired " \ "dir, '%s', already exists." % newdir) else: head, tail = os.path.split(newdir) if head and not os.path.isdir(head): _mkdir(head) #print "_mkdir %s" % repr(newdir) if tail: os.mkdir(newdir) Although it doesn't take a mode argument like os.mkdirs, copytree doesn't use that so it isn't needed. And then change copytree to call _mkdir instead of os.mkdirs: def copytree(src, dst, symlinks=False): """Recursively copy a directory tree using copy2(). The destination directory must not already exist. If exception(s) occur, an Error is raised with a list of reasons. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are copied. XXX Consider this example code rather than the ultimate tool. """ names = os.listdir(src) # os.makedirs(dst) _mkdir(dst) # XXX errors = [] for name in names: srcname = os.path.join(src, name) dstname = os.path.join(dst, name) try: if symlinks and os.path.islink(srcname): linkto = os.readlink(srcname) os.symlink(linkto, dstname) elif os.path.isdir(srcname): copytree(srcname, dstname, symlinks) else: shutil.copy2(srcname, dstname) # XXX What about devices, sockets etc.? except (IOError, os.error), why: errors.append((srcname, dstname, str(why))) # catch the Error from the recursive copytree so that we can # continue with other files except Error, err: errors.extend(err.args[0]) try: shutil.copystat(src, dst) except WindowsError: # can't copy file access times on Windows pass A: Just extending Dan's answer by incorporating the ignore argument and adding shutil to the 'Error' class (for copytree): def copytree(src, dst, symlinks=False, ignore=None): """Recursively copy a directory tree using copy2(). The destination directory must not already exist. If exception(s) occur, an Error is raised with a list of reasons. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are copied. XXX Consider this example code rather than the ultimate tool. """ names = os.listdir(src) if ignore is not None: ignored_names = ignore(src, names) else: ignored_names = set() _mkdir(dst) # XXX errors = [] for name in names: if name in ignored_names: continue srcname = os.path.join(src, name) dstname = os.path.join(dst, name) try: if symlinks and os.path.islink(srcname): linkto = os.readlink(srcname) os.symlink(linkto, dstname) elif os.path.isdir(srcname): copytree(srcname, dstname, symlinks, ignore) else: shutil.copy2(srcname, dstname) # XXX What about devices, sockets etc.? except (IOError, os.error), why: errors.append((srcname, dstname, str(why))) # catch the Error from the recursive copytree so that we can # continue with other files except shutil.Error, err: errors.extend(err.args[0]) try: shutil.copystat(src, dst) except WindowsError: # can't copy file access times on Windows pass A: This is a wokaround with both distutils and shutil: ignorePatterns=('.git') shutil.copytree(src, "__TMP__", ignore=shutil.ignore_patterns(ignorePatterns)) distutils.dir_util.copy_tree("__TMP__", dest) distutils.dir_util.remove_tree("__TMP__") Note: This is not an efficient method, because it copies same files twice. A: For Python 3.8 and above, shutil.copytree() now has the dirs_exist_ok parameter (defaults to False). To copy the tree without any errors (when the dirs are already existing, set it to True. import shutil shutil.copytree("path/to/src", "path/to/dst", dirs_exist_ok=True)
{ "language": "en", "url": "https://stackoverflow.com/questions/7545299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Popup image does not stay in same place The pop up image for "ice white" and "violet" pop up in different places. How do I make them both pop up in just one position? A: Could you perhaps define a single div that uses absolute position and then on hover over Violet or Ice White, draw the popup image inside that div you created? So something like: var displayDiv = document.getElementById("displayDivID"); // draw popup image in the div displayDiv.innerHTML = "<div id=\"violet\">...</div>"; displayDiv.style.display = "block"; // to show it That way, whenever you need to display an image in the same position, it's always drawn inside that div you specified. I would assume you have a class that controls the formatting of that div like position and borders etc. EDIT I've taken your code from your site and added some more code. Save this code as a html page onto your computer and try it. Look for the last css code snippet right before the closing tag. That block of css there controls the look of the div and position it in the middle of the page. The css only sets a fixed position. You could alternatively, use javascript to dynamically calculate the width and height of the user's browser window, then render the css code accordingly so the div is always in the middle of the browser regardless of the inner image dimension. In your previous javascript code snippet for the displayDiv, I've fixed up a few things and added two functions for when the mouse is over a thumbnail and when it's out of a thumbnail. On mouse over will pass the url of the image to the function that will be used to render an image into the displayDiv. Hope that helps. EDIT 2 - Fade In and Out You certainly can. All you need to do is change the two functions to use jQuery fadeIn() and fadeOut() like so: function changeDisplay(bgImageURL) { var displayDiv = document.getElementById("displayDiv"); // draw popup image in the div displayDiv.innerHTML = '<a class="popup1" href="#v"><img src="' + bgImageURL+ '" alt="" /></a>'; // show the display in case it was hidden before $('#displayDiv').fadeIn(); } function hideDisplay() { // hide it when the mouse rolls off the thumbnail $('#displayDiv').fadeOut(); } This jQuery is a basic one. It will have a problem where if you move your mouse on and off the thumbnail quickly, it causes the display div to come on and off, on and off, on and off even if your mouse is already off the thumbnail. The proper way would be to rework the code and use mouseEnter and mouseLeave on the thubmnail elements.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can the size of an input text box be defined in HTML? Here is an HTML input text box: <input type="text" id="text" name="text_name" /> What are the options to define the size of the box? How can this be implemented in CSS? A: Try this <input type="text" style="font-size:18pt;height:420px;width:200px;"> Or else <input type="text" id="txtbox"> with the css: #txtbox { font-size:18pt; height:420px; width:200px; } A: The size attribute works, as well <input size="25" type="text"> A: You can set the width in pixels via inline styling: <input type="text" name="text" style="width: 195px;"> You can also set the width with a visible character length: <input type="text" name="text" size="35"> A: You could set its width: <input type="text" id="text" name="text_name" style="width: 300px;" /> or even better define a class: <input type="text" id="text" name="text_name" class="mytext" /> and in a separate CSS file apply the necessary styling: .mytext { width: 300px; } If you want to limit the number of characters that the user can type into this textbox you could use the maxlength attribute: <input type="text" id="text" name="text_name" class="mytext" maxlength="25" /> A: <input size="45" type="text" name="name"> The "size" specifies the visible width in characters of the element input. You can also use the height and width from css. <input type="text" name="name" style="height:100px; width:300px;">
{ "language": "en", "url": "https://stackoverflow.com/questions/7545302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "96" }
Q: function inside function in php: error: Cannot redeclare I have this php script: function hoeveelzijner ($jaar, $id) { function hoeveelhoeveel($beginstamp, $endstamp, $id) { $dates = mysql_query('SELECT v_date FROM visitors WHERE id="'.$id.'" AND v_date<"'.$endstamp.'" AND v_date>"'.$beginstamp.'"'); return mysql_num_rows($dates); } $i = 1; while ($i < 13) { $hoeveel[$i-1] = hoeveelhoeveel(mktime(0, 0, 0, $i, 1, $jaar),mktime(0, 0, 0, $i, cal_days_in_month(CAL_GREGORIAN,$i,$jaar),$jaar),$id); $i = $i+1; } return $hoeveel; } When I put this beneath it, it works just fine: $values = hoeveelzijner(2005, 1); However, when I do it twice, for example: $values = hoeveelzijner(2005, 1); $test = hoeveelzijner(2000, 4); I get this error: Fatal error: Cannot redeclare hoeveelhoeveel() (previously declared in ...:69) in ... on line 69. Anyone knows what I am doing wrong? It kinda destroys the purpose of using functions if I can only use it once... Extra info: I do not include any other files, nor do I redeclare the function somewhere else in the script. Thanks a lot! A: You can't only use it once; you can only declare it once. Every time the function hoeveelzijner is used, the function hoeveelhoeveel is declared. If you call it more than once, you'll redeclare it, which is forbidden. You have two options: the first is to take the function definition outside the containing function. The function will be declared when the file is first parsed, then used repeatedly. If you want to restrict the function definition to a particular scope (a good idea in principle), you can use the anonymous function syntax introduced in PHP 5.3: function hoeveelzigner($jaar, $id) { $hoeveelhoeveel = function($beginstamp, $endstamp, $id) { $dates = mysql_query('SELECT v_date FROM visitors WHERE id="'.$id.'" AND v_date<"'.$endstamp.'" AND v_date>"'.$beginstamp.'"'); return mysql_num_rows($dates); }; // etc } You can then use the function as $hoeveelhoeveel(...). A: Although PHP let's you declare a function anywhere I think what you are doing is not considered best practice. For most people it just look wrong. You should just declare the function outside the parent function. Alternatively you could add a function_exists() around the inner function, although again I would just declare the inner function outside the parent function. Are perhaps even make a class for it. A: You can't declare it again, especially if the function calls it more than once. Here's a simple change that should work. function hoeveelhoeveel($beginstamp, $endstamp, $id) $dates = mysql_query('SELECT v_date FROM visitors WHERE id="'.$id.'" AND v_date<"'.$endstamp.'" AND v_date>"'.$beginstamp.'"'); return mysql_num_rows($dates); } function hoeveelzijner ($jaar, $id) { $i = 1; while ($i < 13) { $hoeveel[$i-1] = hoeveelhoeveel(mktime(0, 0, 0, $i, 1, $jaar),mktime(0, 0, 0, $i, cal_days_in_month(CAL_GREGORIAN,$i,$jaar),$jaar),$id); $i = $i+1; } return $hoeveel; } Then you can call either function in a similar way in other functions too, if needed be.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Error when pull from GitHub I am trying to pull a project from GitHub, which I am collaborating on, but I receive the following error: your local changes to the following files would be overwritten by merge I have tried to merge by: git mergetool {pathtofile} But it just respons with "File does not need merging". If I try to push my changes first I receive: To prevent you from losing history, non-fast-forward updates were rejected. What might I be missing? A: You quote the following error moessage in your question: your local changes to the following files would be overwritten by merge This error message is essentially saying that git is stopping you from potentially losing work. You have some changes in your working tree that you haven't committed yet, and the pull would modify those files - this might end up with you losing your local changes. Once you've committed your changes to those files, the pull will work. (Or, you could skip the "fetch" stage of git pull and just run git merge origin/master to try the merge stage again.) Martin Ogden's answer gives an example of using git stash as an alternative, which is more suitable if you're not ready to commit your work yet. The latter error message is: To prevent you from losing history, non-fast-forward updates were rejected. Basically, you're only allowed to push if the commit you're pushing already contains the history of branch you're pushing to. The usual solution is to pull first. This is another error message that is preventing you from losing work - you wouldn't (in general) want to wipe out the work that other people have pushed to that branch. A: You could either: * *Add / commit local changes before pulling from remote repository *Stash local changes before the pull and pop the local changes back in after the pull: git stash --include-untracked git pull git stash pop
{ "language": "en", "url": "https://stackoverflow.com/questions/7545307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Gluing a variadic template to a variadic function In an attempt to bypass GCC's unimplemented always-inlining variadic functions in libc++, I thought I could maybe wrap the variadic functions (like snprintf, more precisely, the *_l variant) in a variadic template to achieve a similar effect. An instantiation would fill in the variadic function's varargs, allowing the function to be nicely inlined. The problem is, I don't know the first thing about writing variadic templates, and I certainly don't know how to turn the template arguments into seperate arguments. The code I'm looking to replace is of the form: int __sprintf_l(char *__s, locale_t __l, const char *__format, ...) { va_list __va; va_start(__va, __format); int __res = vsprintf_l(__s, __l, __format, __va); va_end(__va); return __res; } I'd like to replace is with something of the form: template<typename... Args> int __sprintf_l(char *__s, locale_t __l, const char *__format, Args... args) { int __res = vsprintf_l(__s, __l, __format, args...); return __res; } This is not working, due to the expanded args... which cannot be converted to type to va_list {aka char*}. If there is no way, I'll have to trust Howard and implement one-, and two-argument always-inline templates, which would effectively double the amount of needed code. EDIT: perhaps a way to convert the std::tuple that args is into a va_list would work here? A: I think the question you're asking is confusing so let me restate it. You want to use variadic templates to write a function that simulates inlining a variadic function. It cannot be done. va_args is often implemented as a void* to the first parameter on the stack (note variadic functions are required to have at least one non-variadic argument for exactly this reason). You would need to manipulate the call stack to get the parameters in the right place. Now it might be the case that the variadic template function's arguments are on the stack in the same location as va_args would want them but that would require the template function to not be inlined. I strongly suspect the reason always inlining variadic function is unimplemented is because of the implementation of va_args assume standard stack layout. For the compiler to inline that function it would need to allocate stack space and copy the parameters in place. The only thing it would save is actual jmp and ret instructions. It could be done, but half of the benefits of inlining evaporate. Further the compiler will have to hoist the parameter passing code (compiler code that is) to a more general location for use with regular function calls as forced inline of variadic functions. In other words it complicates the control flow significantly for small to no benefit. A: You could implement your own sprintf_l int __noninlined_sprintf_l(char *__s, locale_t __l, const char *__format, ...) { va_list __va; va_start(__va, __format); int __res = vsprintf_l(__s, __l, __format, __va); va_end(__va); return __res; } And call that instead template<typename... Args> int __sprintf_l(char *__s, locale_t __l, const char *__format, Args... args) { int __res = __noninlined_sprintf_l(__s, __l, __format, args...); return __res; } A: template<typename... T> int variadic(char* s, locale_t locale, const char* format, T&&... t) { return __sprintf_l(s, locale, format, std::forward<T>(t)...); } Then calling variadic(s, l, "%d %s", 42, "Hello") would result in a call to __sprintf_l(s, l, "%d %s", 42, "Hello").
{ "language": "en", "url": "https://stackoverflow.com/questions/7545309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What happens when I create nested DOM elements using jQuery as a string? What happens when I use the following, and is there any semantic difference? Method one: var task = $('<li class="task"><header><h1></h1></header></li>') $('#backlog-tasks').append(task); Method two: var task = $('<li>').attr('class','task'); task.append('<header>'); ..... A secondary question: Is there an approach which you favour over the above? Example http://jsfiddle.net/Zwedh/2/ A: As noted in the jQuery documentation, method 1 is parsed by the browser, while method 2 isn't. This is rather hard to find in the prose, ...jQuery uses the browser's .innerHTML property to parse the passed HTML and insert it into the current document. During this process, some browsers filter out certain elements such as <html>, <title>, or <head> elements. As a result, the elements inserted may not be representative of the original string passed. but it definitely is there. (Emphasis mine.) I tend to use method 2, for several reasons: * *Doesn't rely on possibly-browser-specific stuff. (See above.)] *You don't have to worry about quoting quotes - jQuery does it for you. *What if you need an attribute's contents to be user-defined? More on that last one. Say you need to set the style of some element according to user input (probably implausible, but I couldn't think of a better example). Method 1 $("<p style='" + input + "'>") Now think about an input of ' onclick="$.ajax(/* some evil parameters */)" data-dummy='. (Or I'm sure you can think of worse.) Not the most desirable thing ever. Method 2 $("<p>").attr("style", input) Much better.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get the unique thread ID I need to write the actual user thread ID to a log file. If I use Thread.CurrentThread.ManagedThreadId I don't get the unique ID, but the same one over and over again. The reason is to track log.Info for user across the system, and later if I see a problem, I'll be able to search in the log WHERE threadId = ? and get the entire activity flow from the log. I don't mind getting it inside the code of log4net. I am talking about the server thread and not manual thread. A: That is NOT possible because your threads in ASP.NET/IIS are running on the thread pool of IIS... it is not even guaranteed that a HTTP request runs completely on the same thread (for example if there is some I/O operation it could "go sleep" and get reassigned to another thread from the pool)... What exactly is the goal ? Perhaps there is some other way to achieve that... EDIT - as per comments: To track a request you could try logging the hash code of that request (accessible via GetHashCode()) and/or log a hash of a combination of the values of some of the properties/fields of the http request object... IF you dig deeper you could get your hands on a worker request object which has a (request specific) TraceID property... if you want to track the session that entirely depends on your session management (be it a hidden html form field and/or a cookie and/or user and/or something else...). A: Your original assumption is inaccurate: the "actual thread" is reused again and again, which is why you're getting the same thread ID again and again. Your mistake is to assume that each request will be handled by a separate thread. ManagedThreadId is working fine. Now let's look at what you're trying to do: The reason is to track log.Info for user across the system So you want to track the interactions with a user. Not a thread, a user. The same user may have interactions on multiple threads, and multiple users may use the same thread... so what you want to log is the user ID, not the thread ID.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to get Console input and output from jtextArea or JEditorPane I am trying to build a little IDE that calls a C compiler. When the C compiler compiles, I want to redirect the output to a JTextArea or JEditorPane in the IDE so the user can view the output. Also, after executing the object file from the compiled code, how do i create a console that the user can use to interact with the c program? for instance if the C code requires the user to type an input, the user can do that from the console. Basically, what i want is how to redirect a console input and output operations to a jtextarea or jeditorpane. I am building the IDE with java. A: This question is broad (not concise), but some tips: You can execute the external process by using Process p = Runtime.getRuntime().exec("..."). The process you get represents the external process running and you can get its input and output with: BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); PrintWriter pw = new PrintWriter(p.getOutputStream()); With the br you can read the output of the process, line by line and add it to a JTextArea. With the pw you can print to the input of the process in order to pass some data. You should use a thread to read from the process continuously and add the data to the textarea. The data should be interpreted by the user and when he/she considers the process is requiring some input, should write it to a textarea and click a button (for example) and then you read the textarea and writes the data to the pw.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Tkinter menu for chosing a date I am building a dropdown menu that would be used to choose a starting date. It has 3 cascades named year, month, day. The contents of the day cascade is generated so that the available days are true to the chosen year and month. It is possible/probable that the user is going to change the date several times during a single session. My problem: When the user selects the year/month for the first time, the days commands get generated. Thereafter any new year/month combination, the following code just adds the commands to the cascade. So that the day cascade contains the days of two months. I have been trying to make the code remove the old menubar entry daymenu and recreate it based on the new data. I would like to know, how does one do such changes to a preexisting, running menubar? I have searched the tkinter documentation, but could not out how to implement it. import calendar as cal import Tkinter as tk import datetime import os.path window = tk.Tk() # Menu variables: year = tk.IntVar() month = tk.IntVar() day = tk.IntVar() hour = tk.IntVar() minute = tk.IntVar() dur_hour = tk.IntVar() dur_minute = tk.IntVar() duration = tk.StringVar() start = tk.StringVar() # list initializations list_of_years = [] list_of_months = [] list_of_hours = [] list_of_days = [] list_of_minutes = [] def year_seter(value): year.set(value) all_for_day() def all_for_day(): #checks if the data needed to determine number of days in the month is present list_of_days = [] y = year.get() m = month.get() lenght_of_month = cal.monthrange(y,m) lenght_of_month2 = lenght_of_month[1] if m != 0 and y != 0: make_daylist(lenght_of_month2) make_daymenu() def month_seter(value): month.set(value) all_for_day() def day_seter(value): day.set(value) def time_parameters(): the_date = datetime.datetime(1,1,1,0,0,0,0) the_date = the_date.now() end_year = the_date.year make_yearlist(1995, end_year) make_monthlist() make_hourlist() make_minutelist() def make_yearlist(the_year, end_year): while the_year <= end_year: list_of_years.append(the_year) the_year += 1 def make_monthlist(): for i in range(12): list_of_months.append(i + 1) def make_daylist(num_days): for i in range(num_days): list_of_days.append(i + 1) def make_hourlist(): for i in range(24): list_of_hours.append(i) def make_minutelist(): for i in range(60): list_of_minutes.append(i) def make_daymenu(): for the_day in list_of_days: daymenu.add_command(label=the_day, command=lambda : day_seter(the_day)) window.config(menu=menubar) # The following constructs the menu time_parameters() menubar = tk.Menu(window) yearmenu = tk.Menu(menubar) for the_year in list_of_years: yearmenu.add_command(label=str(the_year), command=lambda the_year=the_year: year_seter(the_year)) menubar.add_cascade(label = 'Year', menu=yearmenu) window.config(menu=menubar) monthmenu = tk.Menu(menubar) for the_month in list_of_months: monthmenu.add_command(label=the_month, command=lambda the_month=the_month: month_seter(the_month)) menubar.add_cascade(label = 'Month', menu=monthmenu) window.config(menu=menubar) daymenu = tk.Menu(menubar) menubar.add_cascade(label = 'Day', menu=daymenu) window.config(menu=menubar) window.mainloop() A: You could delete all entries in daymenu before adding new ones: def make_daymenu(): daymenu.delete(0,31) for the_day in list_of_days: daymenu.add_command(label=the_day, command=lambda : day_setter(the_day)) window.config(menu=menubar) A: came across your code to select a date. Recently had to write a simple calendar for similar purposes. I can offer you that option as an alternative. I think this option is more convenient to choose the date. import calendar, datetime, Tkinter class calendarTk(Tkinter.Frame): # class calendarTk """ Calendar, the current date is exposed today, or transferred to date""" def __init__(self,master=None,date=None,dateformat="%d/%m/%Y",command=lambda i:None): Tkinter.Frame.__init__(self, master) self.dt=datetime.datetime.now() if date is None else datetime.datetime.strptime(date, dateformat) self.showmonth() self.command=command self.dateformat=dateformat def showmonth(self): # Show the calendar for a month sc = calendar.month(self.dt.year, self.dt.month).split('\n') for t,c in [('<<',0),('<',1),('>',5),('>>',6)]: # The buttons to the left to the right year and month Tkinter.Button(self,text=t,relief='flat',command=lambda i=t:self.callback(i)).grid(row=0,column=c) Tkinter.Label(self,text=sc[0]).grid(row=0,column=2,columnspan=3) # year and month for line,lineT in [(i,sc[i+1]) for i in range(1,len(sc)-1)]: # The calendar for col,colT in [(i,lineT[i*3:(i+1)*3-1]) for i in range(7)]: # For each element obj=Tkinter.Button if colT.strip().isdigit() else Tkinter.Label # If this number is a button, or Label args={'command':lambda i=colT:self.callback(i)} if obj==Tkinter.Button else {} # If this button, then fasten it to the command bg='green' if colT.strip()==str(self.dt.day) else 'SystemButtonFace' # If the date coincides with the day of date - make him a green background fg='red' if col>=5 else 'SystemButtonText' # For the past two days, the color red obj(self,text="%s"% colT,relief='flat',bg=bg,fg=fg,**args).grid(row=line, column=col, ipadx=2, sticky='nwse') # Draw Button or Label def callback(self,but): # Event on the button if but.strip().isdigit(): self.dt=self.dt.replace(day=int(but)) # If you clicked on a date - the date change elif but in ['<','>','<<','>>']: day=self.dt.day if but in['<','>']: self.dt=self.dt+datetime.timedelta(days=30 if but=='>' else -30) # Move a month in advance / rewind if but in['<<','>>']: self.dt=self.dt+datetime.timedelta(days=365 if but=='>>' else -365) # Year forward / backward try: self.dt=self.dt.replace(day=day) # We are trying to put the date on which stood except: pass # It is not always possible self.showmonth() # Then always show calendar again if but.strip().isdigit(): self.command(self.dt.strftime(self.dateformat)) # If it was a date, then call the command if __name__ == '__main__': def com(f): print f root = Tkinter.Tk() root.title("Monthly Calendar") c=calendarTk(root,date="21/11/2006",dateformat="%d/%m/%Y",command=com) c.pack() root.mainloop()
{ "language": "en", "url": "https://stackoverflow.com/questions/7545315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to find Index of an array in php while loop I am fetching data from MySQL database... I want to check index of each row... e.g while($row=mysql_fetch_array($result) { i want index of $row in each row... (current Index). } Please Help me. Thanks A: If I understood you correctly you want something like this <?PHP $i=0; while($someThingIsTrue) { echo $i; $i++; } ?> A: If you want the index from the database: <?php ... $result = mysql_query("SELECT * FROM whatever"); while($row = mysql_fetch_array($result)) { echo $row['index']; # Where index is the field name containing the item ID from your database } ... ?> Or, if you want to count the number of items based on the output: <?php .. $result = mysql_query("SELECT * FROM whatever"); $index = 0; while($row = mysql_fetch_array($result)) { echo $index.' '.$row['whatever']; $index++; } .. ?> That's what I understood from your question.. A: $row is not a member of any array. So, it has no index at all. And, I suppose, you don't need it either
{ "language": "en", "url": "https://stackoverflow.com/questions/7545323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: changing pointers in functions, c I'll say in advance that I'm asking about pointers to pointers, so my words may be a bit vague, but try to stay with me :) I am trying to understand how changing a pointer passed as an argument takes effect outside the scope of the function. So far this is what I understand: if a pointer is passed as an argument to a function, I can only change what the pointer points to, and not the pointer itself (I'm talking about a change that will take effect outside the scope of the function, as I said). And if I want to change what the pointer is pointing to, I have to pass a pointer to a pointer. Am I right so far? Also, I've noticed that when I have a struct that holds some pointers, if I want to initialize those pointers I have to pass the struct to the initialization function as a pointer to pointer. Is this for the same reason? A: You are right in the first bit but if you've allocated the struct then you can pass a pointer to it. However, if the function allocated the struct, then either you use the function return to collect the value of the newly allocated struct or you pass in a pointer to a pointer in the parameter list. (I've not got a c compiler to hand but I've tried to write some examples). * *You've allocated the pointer int main() { struct x *px = malloc(...); initx(px); } void intix(struct x* px){ px-> .... } * *The function allocated the pointer int main() { struct x *px = initx(); } struct x* intix(){ struct x *px = malloc(...); px-> .... return px; } * *The function allocated the pointer int main() { struct x *px; initx(&px); } void intix(struct x** ppx){ struct x *px = malloc(...); px-> .... *ppx = px; } A: What you should understand is that a pointer is an address. That means that it says "the data for the object is actually there". Therefore you should seperate whether you are changing a variable or changing memory. When you dereference a pointer and assign to that you are changing memory, not a variable. int **x; int **p; int *q; box diagram time: +-----------+ +------+ +-----+ | x (**int) | -> | *int | -> | int | +-----------+ +------+ +-----+ Say I write to the first box: x = p +-----------+ +------+ +-----+ | x (**int) | XX | *int | -> | int | +-----------+ +------+ +-----+ \ \ +------+ +-----+ -> | *int | -> | int | +------+ +-----+ Say I write to the second box: *x = q +-----------+ +-----------+ +-----+ | x (**int) | -> | (*x) *int | XX | int | +-----------+ +-----------+ +-----+ \ \ +-----+ -> | int | +-----+ A: In C, the pointers are not very much different from numbers. You can see it as the numerical memory address of something. Next, in C everything is passed as value. This means, if you get a pointer passed to your function, and you change it, you change only your local copy of the pointer. The changes you make to the pointer argument are no going to be visible outside. Now, what if I want the function to actually change something? Then I give the address of it to the function! So the function knows the actual location of the information I want it to change, so it can change it. This is the way how it works in C. Hope this explanation makes the things clearer. A: You are right on the first count -- in standard C there are only value parameters, and you must pass a pointer to any outside variable which you wish to modify from within the procedure. The reason for something like a structure initialization functions wanting a pointer to a pointer vary, but mostly it's just for consistency with similar functions that allocate the structure, or because that particular group of functions (I'm thinking of some M$ interfaces) have adopted this style seemingly just to be more cryptic (or, more probably, so that the same interfaces can be used by a pass-by-reference language). But be aware that, if a pointer to pointer is asked for, the function may be doing something different that what you've casually assumed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Proxy with nodejs I develop an webapp, against an api. As the api is not running on my local system, I need to proxy the request so I dont run in cross domain issues. Is there an easy way to do this so my index.html will send from local and all other GET, POST, PUT, DELETE request go to xyz.net/apiEndPoint. Edit: this is my first solution but didnt work var express = require('express'), app = express.createServer(), httpProxy = require('http-proxy'); app.use(express.bodyParser()); app.listen(process.env.PORT || 1235); var proxy = new httpProxy.RoutingProxy(); app.get('/', function(req, res) { res.sendfile(__dirname + '/index.html'); }); app.get('/js/*', function(req, res) { res.sendfile(__dirname + req.url); }); app.get('/css/*', function(req, res) { res.sendfile(__dirname + req.url); }); app.all('/*', function(req, res) { proxy.proxyRequest(req, res, { host: 'http://apiUrl', port: 80 }); }); It will serve the index, js, css files but dont route the rest to the external api. This is the error message I've got: An error has occurred: {"stack":"Error: ENOTFOUND, Domain name not found\n at IOWatcher.callback (dns.js:74:15)","message":"ENOTFOUND, Domain name not found","errno":4,"code":"ENOTFOUND"} A: Take a look at the readme for http-proxy. It has an example of how to call proxyRequest: proxy.proxyRequest(req, res, { host: 'localhost', port: 9000 }); Based on the error message, it sounds like you're passing a bogus domain name into the proxyRequest method. A: Other answers are slightly outdated. Here's how to use http-proxy 1.0 with express: var httpProxy = require('http-proxy'); var apiProxy = httpProxy.createProxyServer(); app.get("/api/*", function(req, res){ apiProxy.web(req, res, { target: 'http://google.com:80' }); }); A: Here is an example of the proxy which can modify request/response body. It evaluates through module which implements transparent read/write stream. var http = require('http'); var through = require('through'); http.createServer(function (clientRequest, clientResponse) { var departureProcessor = through(function write(requestData){ //log or modify requestData here console.log("=======REQUEST FROM CLIENT TO SERVER CAPTURED========"); console.log(requestData); this.queue(requestData); }); var proxy = http.request({ hostname: "myServer.com", port: 80, path: clientRequest.url, method: 'GET'}, function (serverResponse) { var arrivalProcessor = through(function write(responseData){ //log or modify responseData here console.log("======RESPONSE FROM SERVER TO CLIENT CAPTURED======"); console.log(responseData); this.queue(responseData); }); serverResponse.pipe(arrivalProcessor); arrivalProcessor.pipe(clientResponse); }); clientRequest.pipe(departureProcessor, {end: true}); departureProcessor.pipe(proxy, {end: true}); }).listen(3333); A: Maybe you should look at my answer here. Here I use the request package to pipe every request to a proxy and pipe the response back to the requester.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Sql Server Varchar(max) and Text Data Types I am researching varchar(max) data type in sql server and I try to compare with text and varchar(8000) datatype. I read several articles about this. As specified in some articles, we cannot update text column using regular DML statements and instead we need to use updateText, readText, writeText. I tried this in sql server 2008 and I can update text column using reqular DML statements.I wonder, was the situation that specified in articles correct for previous versions of Sql Server? And how does sql server store varchar(max) data if exceeds 8 kb? A: Text datatype is available still just for backwards compatibility. Do not use it, instead use char/varchar/nchar/nvarchar in its place. As the the limit of varchar it is 2GB.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Countdown refresh button I have implemented a refresh button of style UIBarSystemItem which will be disabled for 10s whenever it is pressed. I want to further improve it by showing the time left before it is enabled. What is the quickest way to do it? Many thanks in advance. Called whenever the button is pressed. -(void)refreshButton { [self performSelector:@selector(enableRefreshButton) withObject:nil afterDelay:10]; self.navigationItem.rightBarButtonItem.enabled = NO; } -(void)enableRefreshButton { self.navigationItem.rightBarButtonItem.enabled = YES; } EDIT: The refresh button is of style UIBARSystemItemRefresh. I am currently doing this as the answer suggests I use NSTimer. The button does get enabled and disable accordingly but the text doesn't change. @inteface ... { int count; } -(void)viewDidLoad{ UIBarButtonItem *refresh = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshButtonPressed)]; self.navigationItem.rightBarButtonItem = refresh; } -(void)refreshButtonPressed { //do something here... count = 10; self.myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTimeLeft) userInfo:nil repeats:YES]; } -(void)updateTimeLeft{ count --; NSLog(@"%i", count); self.navigationItem.rightBarButtonItem.title = [NSString stringWithFormat:@"%i", count]; self.navigationItem.rightBarButtonItem.enabled = NO; if (count == 0) { self.navigationItem.rightBarButtonItem.enabled = YES; [self.myTimer invalidate]; } } Can I use the title property with UIBarButtonSystemItem? A: You could use this method + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats A: For this you need to implement NSTimer declare int variable count in .h file. and initialize it with count==10 in viewDidLoad/viewWillAppear as your code goes. call this method in performSelector - (void)updateCount:(NSTimer *)aTimer { count--; self.navigationItem.rightBarButtonItem.enabled = YES; self.navigationItem.rightBarButtonItem.title = [NSString stringWithFormat:@"%d",count]; NSLog(@"%i", count); if (count == 0) { self.navigationItem.rightBarButtonItem.enabled = NO; self.navigationItem.rightBarButtonItem.title = [NSString stringWithFormat:@"YOUR BAR BUTTON NAME"]; [timer invalidate]; timer = nil; } } EDIT I think this link would definitely solved problem. This is almost same as you were asking. Please go through the link. http://www.richardhyland.com/diary/2008/12/21/some-cool-tips-and-tricks-for-the-iphone-sdk/
{ "language": "en", "url": "https://stackoverflow.com/questions/7545330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Hiding UITableViewCells when entering edit mode in UITableViewCell (similar to Contacts app) Does anyone know how to hide a number of cells from the grouped UITableView when entering in edit mode? I would like the rows to hide with animation effect as seen in the Contacts app when going out of editing mode. As you know, when in Contacts editing mode, there are more rows than when switching back to normal mode. I would like to know how the switching is done smoothly. Note that my UITableView subclass is loading static UITableViewCells from the same nib using IBOutlets. A: just an update for the ones who remove or insert more than one group of rows: [self.tableView beginUpdates]; [self.tableView reloadRowsAtIndexPaths: ......]; [self.tableView insertRowsAtIndexPaths: ......]; [self.tableView removeRowsAtIndexPaths: ......]; [self.tableView endUpdates]; :D A: When you set the editing mode of the UITableView, you have to first update your data source and then insert/delete rows. - (void)setEditing:(BOOL)editing animated:(BOOL)animated { [super setEditing:editing animated:animated]; [tableView setEditing:editing animated:animated]; // populate this array with the NSIndexPath's of the rows you want to add/remove NSMutableArray *indexPaths = [NSMutableArray new]; if(editing) [self.tableView deleteRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationFade]; else [self.tableView insertRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationFade]; [indexPaths release]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7545337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Android Phonegap1.0 usePolling I have problem with Android phonegap1.0 my app was working well but suddenly it prompt usePolling messages I don't know what I did that cause this message to appear. Is there any update in that? A: Looking at the source code I suspect that the usePolling message appears if the responses from XHR requests to the server start taking too long. It is prompting the end user to use polling so that the requests do not lock up the phone. This is just a guess. https://github.com/phonegap/phonegap/blob/master/Android/phonegap-1.0.0.js
{ "language": "en", "url": "https://stackoverflow.com/questions/7545339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: java.lang.NoSuchMethodError: org.apache.xerces.impl.xs.XMLSchemaLoader.loadGrammar When i try to build my first project using maven, i get the following exceptions SEVERE: Critical error during deployment: java.lang.NoSuchMethodError: org.apache.xerces.impl.xs.XMLSchemaLoader.loadGrammar([Lorg/apache/xerces/xni/parser/XMLInputSource;)V at org.apache.xerces.jaxp.validation.XMLSchemaFactory.newSchema(Unknown Source) at javax.xml.validation.SchemaFactory.newSchema(SchemaFactory.java:594) at com.sun.faces.config.DbfFactory.initStatics(DbfFactory.java:248) at com.sun.faces.config.DbfFactory.<clinit>(DbfFactory.java:208) at com.sun.faces.config.ConfigManager$ParseTask.<init>(ConfigManager.java:893) at com.sun.faces.config.ConfigManager.getConfigDocuments(ConfigManager.java:653) at com.sun.faces.config.ConfigManager.initialize(ConfigManager.java:322) at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:225) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3972) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4467) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardHost.start(StandardHost.java:785) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443) at org.apache.catalina.core.StandardService.start(StandardService.java:519) at org.apache.catalina.core.StandardServer.start(StandardServer.java:710) at org.apache.catalina.startup.Catalina.start(Catalina.java:581) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414) 25/09/2011 02:40:15 م org.apache.catalina.core.StandardContext listenerStart SEVERE: Exception sending context initialized event to listener instance of class com.sun.faces.config.ConfigureListener java.lang.RuntimeException: java.lang.NoSuchMethodError: org.apache.xerces.impl.xs.XMLSchemaLoader.loadGrammar([Lorg/apache/xerces/xni/parser/XMLInputSource;)V at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:292) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3972) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4467) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardHost.start(StandardHost.java:785) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443) at org.apache.catalina.core.StandardService.start(StandardService.java:519) at org.apache.catalina.core.StandardServer.start(StandardServer.java:710) at org.apache.catalina.startup.Catalina.start(Catalina.java:581) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414) Caused by: java.lang.NoSuchMethodError: org.apache.xerces.impl.xs.XMLSchemaLoader.loadGrammar([Lorg/apache/xerces/xni/parser/XMLInputSource;)V at org.apache.xerces.jaxp.validation.XMLSchemaFactory.newSchema(Unknown Source) at javax.xml.validation.SchemaFactory.newSchema(SchemaFactory.java:594) at com.sun.faces.config.DbfFactory.initStatics(DbfFactory.java:248) at com.sun.faces.config.DbfFactory.<clinit>(DbfFactory.java:208) at com.sun.faces.config.ConfigManager$ParseTask.<init>(ConfigManager.java:893) at com.sun.faces.config.ConfigManager.getConfigDocuments(ConfigManager.java:653) at com.sun.faces.config.ConfigManager.initialize(ConfigManager.java:322) at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:225) ... 15 more 25/09/2011 02:40:15 م org.apache.catalina.core.StandardContext start SEVERE: Error listenerStart 25/09/2011 02:40:15 م org.apache.catalina.core.StandardContext start SEVERE: Context [/spring_faces] startup failed due to previous errors 25/09/2011 02:40:16 م org.icefaces.impl.push.servlet.ICEpushResourceHandler notifyContextShutdown INFO: MainServlet not found in application scope: java.lang.NullPointerException 25/09/2011 02:40:16 م com.sun.faces.config.ConfigureListener contextDestroyed SEVERE: Unexpected exception when attempting to tear down the Mojarra runtime java.lang.IllegalStateException: Application was not properly initialized at startup, could not find Factory: javax.faces.application.ApplicationFactory at javax.faces.FactoryFinder$FactoryManager.getFactory(FactoryFinder.java:894) at javax.faces.FactoryFinder.getFactory(FactoryFinder.java:319) at com.sun.faces.config.InitFacesContext.getApplication(InitFacesContext.java:112) at com.sun.faces.config.ConfigureListener.contextDestroyed(ConfigureListener.java:325) at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4011) at org.apache.catalina.core.StandardContext.stop(StandardContext.java:4615) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4512) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardHost.start(StandardHost.java:785) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443) at org.apache.catalina.core.StandardService.start(StandardService.java:519) at org.apache.catalina.core.StandardServer.start(StandardServer.java:710) at org.apache.catalina.startup.Catalina.start(Catalina.java:581) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414) 25/09/2011 02:40:16 م org.apache.catalina.core.ApplicationContext log INFO: Closing Spring root WebApplicationContext 25/09/2011 02:40:16 م org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc SEVERE: A web application registered the JBDC driver [org.postgresql.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered. 25/09/2011 02:40:16 م org.apache.catalina.loader.WebappClassLoader clearThreadLocalMap SEVERE: A web application created a ThreadLocal with key of type [null] (value [javax.faces.context.FacesContext$1@678fb397]) and a value of type [com.sun.faces.config.InitFacesContext] (value [com.sun.faces.config.InitFacesContext@b57b39f]) but failed to remove it when the web application was stopped. To prevent a memory leak, the ThreadLocal has been forcibly removed. log4j:ERROR LogMananger.repositorySelector was null likely due to error in class reloading, using NOPLoggerRepository. A: Evidently, the stacktrace has nothing to do with maven. Instead it is the error deploying the web application. Quoting from this possibly related discussion thread. You're probably picking up an incompatible mix of classes from Xerces 2.8.1 and some old version of Xerces (something prior to 2.7.0) which is somewhere on your classpath or perhaps in the endorsed directory of your JDK 1.4 installation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Confused about UIBezierPath + applyTransform + CGPath I scale UIBezierPath (built of one [0,0 - 1x1] rect) by factor 2 in both x and y directions. UIBezierPath ".bounds" is alright (i.e. scaled as expected), while ".CGPath" remains unchanged... Code: #import <UIKit/UIKit.h> int main(int argc, char *argv[]) { UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, 1, 1)]; NSLog(@"path.bounds box before transform:%@", NSStringFromCGRect(path.bounds)); NSLog(@"path.CGPath box before transform:%@", NSStringFromCGRect(CGPathGetBoundingBox(path.CGPath))); [path applyTransform:CGAffineTransformMakeScale(2, 2)]; NSLog(@"path.bounds box after transform:%@", NSStringFromCGRect(path.bounds)); NSLog(@"path.CGPath box after transform:%@", NSStringFromCGRect(CGPathGetBoundingBox(path.CGPath))); return 0; } Output: path.bounds box before transform:{{0, 0}, {1, 1}} path.CGPath box before transform:{{0, 0}, {1, 1}} path.bounds box after transform:{{0, 0}, {2, 2}} path.CGPath box after transform:{{0, 0}, {1, 1}} Why? A: As of iOS 5.1, the CGPath returned from UIBezier's .CGPath property is indeed updated when the UIBezierPath has a new transform applied. However, this doesn't preclude a solution for older iOS versions. You can get the CGPath from the UIBezierPath, transform it directly, then set it back onto the UIBezierPath. Lo and behold, all the other properties, like bounds and origins, will update correctly and immediately. UIBezierPath* path = [UIBezierPath bezierPathWithRect:CGRectMake(0.0f, 0.0f, 1.0f, 1.0f)]; CGAffineTransform transform = CGAffineTransformMakeScale(2.0f, 2.0f); CGPathRef intermediatePath = CGPathCreateCopyByTransformingPath(path.CGPath, &transform); path.CGPath = intermediatePath; CGPathRelease(intermediatePath); A: The reason for this difference is because the call to applyTransform simply stores the transform matrix in the path object. It does not cause the path itself to be modified. path.bounds is a calculated property that is derived using the transform, whereas the call the CGPathGetBoundingBox is simply iterating over the elements of the passed in CGPath object. Because there could potentially be a great number of path elements, storing the transform matrix, and not modifying all of the the path elements every time a new matrix is assigned, is done as an optimization. This work is only done once, or minimally, when only certain properties, such as the bounds, of the UIBezierPath are queried.
{ "language": "en", "url": "https://stackoverflow.com/questions/7545344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Migrating MySQL database to Firebird Server 2.5 I have a MySQL 5.5 database that I wish to migrate to Firebird Server 2.5. I have no issues with an existing MySQL database but after MySQL's acquisition, I am worried about the unavailability of Community Edition any time soon. I want to migrate to a true and robust RDBMS like Firebird. PostgreSQL is another choice, but it's .NET provider is sluggish. Is there any free tool to migrate existing MySQL database to Firebird? I also want to know how Firebird fits in terms of performance when compared with MySQL. A: I have used Clever Components' Interbase DataPump with success. I personally haven't used it with MySQL, but there shouldn't be any problems. As of perfomance comparison - as always it comes down to your specific data and use cases. General wisdom is that MySQL is faster in some cases but it comes with the cost of reliability (ie not using transactions). A: I also use Clever Components Interbase DataPump but you can also check IBPhoenix ressource site here
{ "language": "en", "url": "https://stackoverflow.com/questions/7545346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }