text
stringlengths
8
267k
meta
dict
Q: Underlying Type of System.Data.Entity.DynamicProxies.Xyz_123 A link query returns a object of type: System.Data.Entity.DynamicProxies.Person_D82ABAE4682B2BBAB103FDB8673CE2... I need the full type name of the underlying type - here Person object (MyDomainModel.Person) How can i get this? Thanks A: Use static method GetObjectType of ObjectContext
{ "language": "en", "url": "https://stackoverflow.com/questions/7556616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ListBox and ajax in ASP.NET mvc3 i have two Listboxes in mvc3 the first one have all products and the other is empty i want to select some products from the first Listbox to the empty list box using Ajax and when the user click the save button insert the selected items (in the second Listbox) th database i used this example http://www.codeproject.com/KB/aspnet/Mvc2ListBox.aspx but i can convert the submit add to Ajax add the big problem with me the index action have model parameter but the javascript can not see the model object plz help me A: I think your problem is related to this question I made regarding returning a List from the view to the controller: Return a List<E> from a view in view model Also look at this link which helped me a great deal to solve it: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx Hope this helps, If I missundertud your problem, let me know so we can find another answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TinyMce using ASP.NET MVC 3 With Razor View Engine - loads but does not display I have a simple form using the TinyMce jQuery plugin. When I load the page, TinyMce is supposed to replace my textarea with his editor, but this does not happen. Looking at the html generated, my textarea is there (visibility set to hidden) but no iFrame object was created by TinyMce. The TinyMce object exists, but the activeEditor is null. It is as if I have not initialized it, but I am following the sample code exactly as follows: //here is where I load the scripts <script type="text/javascript" src="@Url.Content("~/Scripts/jquery.tinymce.js")"></script> <script type="text/javascript" src="@Url.Content("~/Scripts/tiny_mce_jquery.js")"></script> // here is my text area <textarea id="tinymceId" name="content" class="tinymce" rows="1" cols="50" style="width:100%;" ></textarea> //and here is my script code where I initialize it $(document).ready(function () { $('#tinymceId').tinymce({ doctype: '<!DOCTYPE html>', editor_selector: "tinymce", convert_urls: false, mode: "textareas", }); }); A: Does it make any difference if you comment out the setting editor_selector: "tinymce",? Another thing to mention: I am not a friend of the jquery build (tiny_mce_jquery.js/jquery.tinymce.js) for several reasons (it is slow for example, ...). Does it make any difference to use the tiny_mce.js instead? You may load the regular jquery.js on the page too - that is efficient and works well. A: Well, the most famous way of being cool nowadays is to use Nuget. I have written some partial view templates for TinyMCE. (I also push TinyMCE to the feed when it is being updated) Following article will walk you through for the process : TinyMCE HTML Text Editior & ASP.NET MVC - Setting It Up Has Become Easy With Nuget
{ "language": "en", "url": "https://stackoverflow.com/questions/7556619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Magento Category Flat Data will not reindex error 'There was a problem with reindexing process.' I have recently moved a magento installation of version 1.5.0.1 to a live server however no products are showing on the front end. After inspecting the indexes i see that the Category Flat Data index is needs re-indexing however when trying to re-index this i get an error notice box saying 'There was a problem with reindexing process.' So far i have tried the following * *Resetting file permissions 755 for folders, 664 for files find . -type f -exec chmod 644 {} \; find . -type d -exec chmod 755 {} \; *Deleting the contents of the var folder including cache and locks folders *trying to process the indexes manually through the console using the command below from public_html/shell php indexer.php reindexall I have inspected the error logs and the following is present 2011-09-26T08:16:11+00:00 DEBUG (7): Exception message: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' `store_id` smallint(5) unsigned not null default '0', `all_children` text defau' at line 10 Trace: #0 /home/bboutique/www.bassboutique.co.uk/public_html/lib/Zend/Db/Statement.php(300): Zend_Db_Statement_Pdo->_execute(Array) #1 /home/bboutique/www.bassboutique.co.uk/public_html/lib/Zend/Db/Adapter/Abstract.php(479): Zend_Db_Statement->execute(Array) #2 /home/bboutique/www.bassboutique.co.uk/public_html/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('CREATE TABLE `c...', Array) #3 /home/bboutique/www.bassboutique.co.uk/public_html/lib/Varien/Db/Adapter/Pdo/Mysql.php(333): Zend_Db_Adapter_Pdo_Abstract->query('CREATE TABLE `c...', Array) #4 /home/bboutique/www.bassboutique.co.uk/public_html/app/code/core/Mage/Catalog/Model/Resource/Eav/Mysql4/Category/Flat.php(526): Varien_Db_Adapter_Pdo_Mysql->query('CREATE TABLE `c...') #5 /home/bboutique/www.bassboutique.co.uk/public_html/app/code/core/Mage/Catalog/Model/Resource/Eav/Mysql4/Category/Flat.php(433): Mage_Catalog_Model_Resource_Eav_Mysql4_Category_Flat->_createTable('1') #6 /home/bboutique/www.bassboutique.co.uk/public_html/app/code/core/Mage/Catalog/Model/Category/Indexer/Flat.php(237): Mage_Catalog_Model_Resource_Eav_Mysql4_Category_Flat->rebuild() #7 /home/bboutique/www.bassboutique.co.uk/public_html/app/code/core/Mage/Index/Model/Process.php(139): Mage_Catalog_Model_Category_Indexer_Flat->reindexAll() #8 /home/bboutique/www.bassboutique.co.uk/public_html/app/code/core/Mage/Index/Model/Process.php(167): Mage_Index_Model_Process->reindexAll() #9 /home/bboutique/www.bassboutique.co.uk/public_html/app/code/core/Mage/Index/controllers/Adminhtml/ProcessController.php(124): Mage_Index_Model_Process->reindexEverything() #10 /home/bboutique/www.bassboutique.co.uk/public_html/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Mage_Index_Adminhtml_ProcessController->reindexProcessAction() #11 /home/bboutique/www.bassboutique.co.uk/public_html/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(253): Mage_Core_Controller_Varien_Action->dispatch('reindexProcess') #12 /home/bboutique/www.bassboutique.co.uk/public_html/app/code/core/Mage/Core/Controller/Varien/Front.php(176): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http)) #13 /home/bboutique/www.bassboutique.co.uk/public_html/app/code/core/Mage/Core/Model/App.php(340): Mage_Core_Controller_Varien_Front->dispatch() #14 /home/bboutique/www.bassboutique.co.uk/public_html/app/Mage.php(627): Mage_Core_Model_App->run(Array) #15 /home/bboutique/www.bassboutique.co.uk/public_html/index.php(80): Mage::run('', 'store') #16 {main} Any help would be much appreciated Thanks Ian A: I was getting the same errors loading Magento's sample data into Magento 1.5.1.0 (Despite what Varien say, their sample data does not work with all Magento versions) in /app/code/core/Mage/Catalog/Model/Resource/Eav/Mysql4/Category/Flat.php I found this on line 549: switch ($column['DATA_TYPE']) { case 'smallint': case 'int': $_type = $column['DATA_TYPE'] . '(11)'; $_is_unsigned = (bool)$column['UNSIGNED']; if ($column['DEFAULT'] === '') { $column['DEFAULT'] = null; } break; case 'varchar':......................... there was no case statement for 'timestamp'; a datatype that Magento uses for it's 'updated_at' and 'created_at' columns in Magento 1.6.1.0 I did some alter table statements to change the 'timestamp' columns in catalog_category_entity and catalog_product_entity to 'datetime' and the indexing problem disappeared. I have now done a find and replace on all 'timestamp' columns in the sample data to make it compatible with 1.5.1.0 I hope this helps someone :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7556622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Vertical scroll bar has wrong size after device rotation I have a function where I make a UIScrollView and one more function for resizing UIView if InterfaceOrientation did change, but after rotating my vertical scroll bar has 1/3 the size of the width of my ScrollView. wrapper.frame = CGRectMake(0, cover_h + thumb_border*2, startView.frame.size.width, startView.frame.size.height-(cover_h+thumb_border*3)); wrapper.contentSize = CGSizeMake((int)thumb_w*2+thumb_border-1,(int) thumb_h*(slice/2)+thumb_border*((slice-1)/2)); wrapper.contentInset = UIEdgeInsetsMake(0, thumb_border, 0, thumb_border); Code of formating ScrollView in init and resize is this same A: I'm guessing the way you are resizing it is using the 'thumb' variables (_w, _h, _border). Are these being reset after the view is rotated? If they are set up to position everything correctly say for portrait view, when you switch to landscape view the sizes will all be wrong won't they? You might have to change those variables?
{ "language": "en", "url": "https://stackoverflow.com/questions/7556625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Configuring different physical DBs for same datasource in two JBoss applications I want to deploy the same Java EE enterprise application twice (under two different names)in a JBoss 6.0 server instance. Both of these applications use the same logical datasource as configured in the server. No problem so far. Yet, I'd like to target each of the two applications a different physical database through this one and only logical datasource. Is that possible with JBoss 6.0 somehow (without using two different server instances or changing the application before deployment or packaging different *ds.xml files in each application?) A: (without using two different server instances or changing the application before deployment or packaging different *ds.xml files in each application?) Two different data sources under the same *-ds.xml file: <local-tx-datasource> <jndi-name>DS1</jndi-name> <connection-url>jdbc:mysql://db.server/db?</connection-url> <driver-class>com.mysql.jdbc.Driver</driver-class> <user-name>username</user-name> <password>pass</password> <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name> <metadata> <type-mapping>mySQL</type-mapping> </metadata> </local-tx-datasource> <local-tx-datasource> <jndi-name>DS2</jndi-name> <connection-url>jdbc:mysql://com.db/db2?</connection-url> <driver-class>com.mysql.jdbc.Driver</driver-class> <user-name>username</user-name> <password>pass</password> <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name> <metadata> <type-mapping>mySQL</type-mapping> </metadata> </local-tx-datasource> The only downside is that you have to customize your code if you are using the @Resource annotation: @Resource(mappedName="DS2") private DataSource ds; Haven't tried the following, but you might be able to do a explicit JNDI lookup via InitialContext, and specify the resource to be looked up in a properties file (DS1 / DS2)? If you are using Maven (I am making multiple assumptions now :)) you could filter the properties file and provide the right DB datasource name via profiles during build time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Strange behavior of default constructor in a class inherited from POD struct This question relates to this one. As I mentioned in previous question I've decided to inherit my class from Win structure BITMAP to provide some extended functionality. I've noticed interest detail in compiled program behavior. First I have defined default constructor for my class like below: CPreviewFrame::CPreviewFrame(): m_bufferSize( 0 ) { bmBits = NULL; //ensure that compiler in debug won't init it with 0xccccc... and delete[] will do the job } In idea compiler had to generate code which calls default constructor for base type even if it wasn't called manually in init list. But while debugging I noticed that BITMAP's data members are not initialized! I added manual initialize for BITMAP and it worked - all data members were initialized by zeros: CPreviewFrame::CPreviewFrame(): BITMAP( ), m_bufferSize( 0 ) { //bmBits = NULL; //it's not needed anymore probably } Why does it happen? Isn't compiler obligated to call default constructor or it's applied to classes only? (it can't be so I think - only difference is in default access qualifiers for members and for inheritance) A: If you do not provide an explicit initializer for a POD-struct, then the object has an indeterminate initial value per Section 8.5/9 of the C++ standard. Adding an initializer for BITMAP that is an empty set of parenthesis to the initializer list of your CPreviewFrame constructor value-initializes the BITMAP object per Section 8.5/7. According to Section 8.5/5, that will mean all the non-static members of BITMAP will be zero-initialized since they are not arrays, unions, or class-types. In your initial example though, you only initialized the bmBits member of the BITMAP structure in the actual body of the CPreviewFrame constructor ... that leaves the rest of the data-members of BITMAP with values that are indeterminate since no initializer was specified for the BITMAP structure itself. Since each non-static data-member of a class is initialized before the actual body of the constructor is called, the lack of an explicit initializer for BITMAP, which is a non-static POD-struct data-member of your CPreviewFrame class, means that the behavior described in 8.5/9, where the values are set to an indeterminate initial value, takes effect.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: usage function doesn't work with getopt I have a problem with a usage function in Python. This is a part of my main function: def main(argv): try: opts, args = getopt.getopt(argv, 'hi:o:tbpms:', ['help', 'input=', 'output=']) if not opts: print 'No options supplied' usage() except getopt.GetoptError,e: print e usage() sys.exit(2) for opt, arg in opts: if opt in ('-h', '--help'): usage() sys.exit(2) if __name__ =='__main__': main(sys.argv[1:]) and I define a usage function as well def usage(): print "\nThis is the usage function\n" print 'Usage: '+sys.argv[0]+' -i <file1> [option]' but when I run my code as ./code.py or ./code.py -h (it is executable) I got anything but the Python help. A: The below worked for me. Run it with "python code.py". import getopt, sys def usage(): print "\nThis is the usage function\n" print 'Usage: '+sys.argv[0]+' -i <file1> [option]' def main(argv): try: opts, args = getopt.getopt(argv, 'hi:o:tbpms:', ['help', 'input=', 'output=']) if not opts: print 'No options supplied' usage() except getopt.GetoptError,e: print e usage() sys.exit(2) for opt, arg in opts: if opt in ('-h', '--help'): usage() sys.exit(2) if __name__ =='__main__': main(sys.argv[1:])
{ "language": "en", "url": "https://stackoverflow.com/questions/7556639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: EJB 3 Static reference or Runtime lookup? I am calling an EJB from a POJO making a JNDI lookup.I want to know what is a better way to make the lookup and what are the implications of each way? I have 2 options * *In the static block of POJO ,make a static reference to an EJB and use this static reference in all objects public class MyPojo { static { MyEJB ejb = (MyEJB) EJBServiceLocatorUtil.fetchService(IAppConstants.JNDI_LOCAL); } ..... } *Make a JNDI lookup everytime I create a new object public class MyPojo { public MyPojo(){ MyEJB ejb = (MyEJB) EJBServiceLocatorUtil.fetchService(IAppConstants.JNDI_LOCAL); } } A: Option 1 could fail if the EJB is not deployed yet or if the JNDI context is not available. There could be portability issue from one app server to another. Option 2 could be time consuming (JNDI lookup) depending on how often you instantiate MyPojo. Another option could be to use the implementation of the singleton pattern of Bill Plugh: http://en.wikipedia.org/wiki/Singleton_pattern#The_solution_of_Bill_Pugh where Singleton is your EJB. The JNDI lookup is done only once and lazily (on first call). Note that all these options are only valid for stateless session beans.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Offline Access in PHP SDK w/ a valid accesstoken i asked a last time about offline access in PHP, and i was told that as long as i have a valid accessToken from a user, and if i have offline_access permission i can interact with the user WHILE he is logged out of facebook. but to be honest i have NO idea why its failing on me. first: i have offline_access and the users accessToken. i want to save the accessToken to a secure DB, and then when calling facebook PHP API, i want to be able to supply the accessToken and allow the user to interact with facebook as if the user was signed in to facebook. i tried to manually set the accessToken and userid (both which is saved when a user allows access to the app). the getting of data works (i.e the user can a view their stream/pics etc. but they cannot post statuses (which they can if they are logged in). does the permissions allow that? or no A: To publish statuses you still need the publish_stream permission.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best way to convert Jackson to JDBC Recordset for SQL Server CRUD updates? I'm sucessfully sending JSON from the client using jQuery to the server which has Guice bindings to Jackson using bind: bind(MessageBodyReader.class).to(JacksonJsonProvider.class); bind(MessageBodyWriter.class).to(JacksonJsonProvider.class) Once I have my JSON object, I need to perform CRUD operations to update the database. I can manually parse the JSON or build a JSON object for the getter; but it seems like there should be an automatic way to do this such as serializing to/from the recordset. Thoughts? A: If you happen to have POJOs to use (JSON to/from POJO), I would suggest looking at jDBI library for DB access. It adds convenience methods including data binding between POJOs and ResultSets (similar to how Jackson works between JSON and POJOs). It might even be possible to use Jackson to from JSON to java.util.Map, and jDBI from Map to JDBC objects (bind to statement etc). If one wanted to do it, writing serializers/deserializers between JSON and ResultSet would be totally doable as well, and could be packaged as simple Jackson extension module. I assume quite a few users would find this useful as well; but to my knowledge no such thing exists yet.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wix Conditional WebApplicationExtension I'm trying to install an MVC website with my Wix installer. It should work for IIS 6 and IIS 7. If the target has IIS 6, I want to use <iis:WebApplicationExtension CheckPath="no" Executable="[NETFRAMEWORK40INSTALLROOTDIR]aspnet_isapi.dll" Verbs="GET,HEAD,POST"/> If it's IIS 7+, I don't want to do this (since ASP .NET won't serve static content types by default). How can I make the above line conditional? I know I can set a condition at the containing component...but that's not what I want, because the rest of the component (the Web Application itself) should be installed regardless... Thanks. A: You could try to create two identical components, only with this setting different, and then set the condition on them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556664", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Android - Delay in closing activity with VideoView I have an Activity with a VideoView -- that loads a video from the web. However, when the user clicks the back button before the video has fully loaded, the screen goes black and several seconds pass before it returns to the previous activity. Is there a way to force the VideoView to quit more quickly? Here is the code for setting up the stream. The URL for the video is passed in the Intent: public class VideoPlayer extends Activity { ... @Override public void onCreate(Bundle savedInstanceState) { ... VideoView videoView = (VideoView) findViewById(R.id.video_view); MediaController mediaController = new MediaController(this); mediaController.setAnchorView(videoView); videoView.setMediaController(mediaController); videoView.setOnPreparedListener(videoPreparedListener); videoView.setOnErrorListener(videoErrorListener); Uri video = Uri.parse(<myvideourl>); videoView.setVideoURI(video); } … } A: You actually need to stop the video, before the activity is finished. Otherwise you can even end up getting IllegalStateException in case you rotate your device and you've chosen in your manifest file that the activity is recreated upon device's rotation. Try this: @Override protected void onPause() { super.onPause(); mVideoView.stopPlayback(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7556669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Mp3 Play from Stream on C# I have music urls. Urls like http://site.com/audio.mp3 . I want play this file online, like youtube. Do you know a class or code can do this ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7556672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What happens to the exectuting threads (other than Main thread) of an App when the user presses the "Home" button As far as I know the main thread or UI thread will be paused the moment user presses "Home" button as it comes under Activity Life cycle. But what happens to the other exectuting threads of an App when the user presses the "Home" button? Does they be executing like background processes or will be paused? If they continue with execution can I say these can be the replacement for Services? Thanks A: Yes they will continue to run in the background. Also see this: Application threads vs Service threads
{ "language": "en", "url": "https://stackoverflow.com/questions/7556673", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to check the app version that was originally installed by the user in iOS I have an iOS app which originally had a version 1.0. I then released updated version 2.0. Is it somehow possible in 3.0 update to check when a user originally installed the app in 1.0, or 2.0, or in 3.0? I don't want to use preferences because that will not work in case of user deleting the app and then installing. A: Only if 1.0 or 2.0 left something behind for 3.0 to check (a setting, database record, file in your sandbox). If you want it to survive a delete and reinstall, then that something needs to not be on the phone (it would have had to register with an external service). It's too late if the code isn't in your 1.0 or 2.0 versions -- you will probably need to ask the user. If you are using a database via CoreData, and you have different versions in 1.0 and 2.0, you can check that before you upgrade it for 3.0. Even if you aren't using CoreData, there might be schema differences you can check for.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556684", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Why is checkbox in knockoutJs written to only when checked? I'm using a special extended version of Ko which uses a commit()/peek() type functions on a dependant observable so that I only save the data onto the form if it is committed to the database (on Ok) and reverted on cancel. Problem I'm having is that when I check a checkbox, the write function is called correctly on the protected observable. However, if I uncheck the checkbox, the write function isn't called, so when the model is sent to my MVC controller, the checkbox boolean is still TRUE. Why is knockout not writing the FALSE value? UPDATED QUESTION WITH CODE: Please see this JsFiddle here to demonstrate: http://jsfiddle.net/b2Qu2/3/ Minor issue Note that there is 1 other problem with the demo - for some reason, when I check/uncheck the checkbox, the peeked value is not updated on the UI even though it is chained to a dependentObservable. You can still peek the value by clicking the 'peek' button. Major Issue To reproduce problem: 1) Click 'peek' button: Shows FALSE - CORRECT 2) Check IsAdmin checkbox 3) Click 'peek' again: Shows TRUE - CORRECT 4) Uncheck IsAdmin 5) Click 'peek' again: SHOWS TRUE - INCORRECT!! Example scenario Imagine a dialog is shown with a checkbox for an Admin user. Only 1 admin user can be set, and the server responds with valid/invalid if an admin user already exists. The user then unchecks the checkbox, but now the viewmodel thinks the checkbox is ALWAYS true?? Reason for using the protectedObservable is if the server response succeeds, the commit() method is called so everything is persisted on the UI. If the user cancels the dialog or an error occurs, the original values are not overwritten. A: The reason that the write is only firing on one value is because it will only trigger when it believes that it needs to write a different value to what it is bound against. So, the actual value of your protectedObservable is not changing. If it is true and you try to set it to true, then the write does not fire, since it believes that it has the correct value. I would probably change it up a bit and use something like this: ko.protectedObservable = function (initialValue) { //private variables var _actual = ko.observable(initialValue), _temp = ko.observable(initialValue); //access to temp value _actual.temp = _temp; //commit the temporary value to our observable, if it is different _actual.commit = function () { if (_temp() !== _actual()) { _actual(_temp()); } }; //notify subscribers to update their value with the original _actual.reset = function () { _actual.valueHasMutated(); _temp(_actual()); }; return _actual; }; With this version you can bind against field1 or field1.temp. You don't need a peek even, because both the temp and actual values are observable. It would look like this: http://jsfiddle.net/rniemeyer/BwDYE/
{ "language": "en", "url": "https://stackoverflow.com/questions/7556689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: AlarmManager battery and cpu usage My question refers to the usage of Alarm Manager with partial wake lock. does canceling a repeating task and resetting it cost more cpu/memory/battery than the task assigned to the alarm manager? the task is to send a message to the server if no other messages have been sent in the last 30 seconds. so, in case my app just sends a message, is it better to reset the Alarm Manager, or leave it as it is? Question 2: using the alarm manager alow me to send the message even when the device asleep. my app designed to try to reconnect to the server in case of disconnection and if not succeeded after 3 tries to shutdown. how can I make this work when device is asleep ? A: does canceling a repeating task and resetting it cost more cpu/memory/battery than just running an if statement? What "if statement"? To clarify, my repeated task is to send a message to my server if no message has been sent in the last 30 seconds. That does not seem like a prudent use of the user's battery. Please allow them to configure the period, including an option to not send such messages. Or, better yet, let the server do its own tracking, and eliminate "send a message for no messages" messages completely. so in case my service sends a message to the server, is it better to reset the Alarm Manager, or leave it as it is? Since your code is already running (it just sent a message to the server), cancelling and rescheduling an alarm should be inexpensive.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How does Slideshare.net site works in iPad Safari? I am right now exploring on opening Office documents in Mobile browsers but ensuring users do not have access to the file. I saw that with out even downloading the pps files in to iPad, Slideshare is able to show presentation. Example: Check this out: http://www.slideshare.net/invalidname/advanced-av-foundation-cocoaconf-aug-11 Is there any opensource library to accomplish this? And one another thing is that when I test in iPad and Android, at times I got a pps presentation filled with slides which are images (only option to save) and at times normal slides where I had the option to copy, paste in to it.. Please some one share light on this ? A: It's just like scribd.com, which converts PDF (or other document format) into HTML5, but it seems with a lower conversion ratio in SlideShare. (More text is embedded into images and less text is extracted as selectable text in SlideShare.) With some open source libraries, you can convert almost any popular document formats into PDF and then extract texts and images from the PDF. Then you can try to put these texts and images into the web page and make the layout to look like the original layout. With HTML5, you can use the same fonts from the PDF in your web page, so they should look more similar than without HTML5.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to run standard algorithms on vector in an elegant way? I know if I have a vector<int> I can run algorithms on it like so: int max = *max_element(myints.begin(), myints.end()); But what if I have a vector<MyStruct> where one of the fields within the struct is an int. Is there a nice elegant way to run an algorithm on just the ints in all of my structs? A: It depends on what your definition of "elegant" is, but yes, this can be done. In fact, in many different ways. In Standard C++, you can use a Functor: #include <algorithm> #include <vector> #include <functional> using namespace std; class Gizmo { public: int n_; }; class BiggestGizmo : public std::binary_function<bool, Gizmo, Gizmo> { public: bool operator()(const Gizmo& lhs, const Gizmo& rhs) const { return lhs.n_ > rhs.n_; } }; int main() { typedef vector<Gizmo> Gizmos; Gizmos gizmos; Gizmos::const_iterator it = max_element(gizmos.begin(), gizmos.end(), BiggestGizmo()); } In C++0X, you could use a Lambda: #include <algorithm> #include <vector> using namespace std; class Gizmo { public: int n_; }; int main() { typedef vector<Gizmo> Gizmos; Gizmos gizmos; Gizmos::const_iterator it = max_element(gizmos.begin(), gizmos.end(), [](const Gizmo& lhs, const Gizmo& rhs) -> bool { return lhs.n_ > rhs.n_; }); } A: Another option in the mix: you could write an iterator class of your own whose reference and value types are int& and int, but which acts on top of an iterator with reference type MyStruct&, providing access to that field. It's a bit more work than just supplying an extra comparator to max_element, but if you do it once, then you've done it for all algorithms, not just the ones that act via a comparator. If you can use it, boost::transform_iterator will handle the boilerplate for you. boost::transform_iterator doesn't let you get the underlying iterator back from an instance, but in the case of vector that doesn't matter too much since it's random-access, so it's efficient to compute the distance and apply it to the begin() iterator. A: Provide a comparator to max_element: MyStruct max = *max_element(v.begin(), v.end(), [](const MyStruct & lhs, const MyStruct & rhs) { return lhs.theInt < rhs.theInt; }); If your compiler does not yet support lambdas, you will have to write a separate function or function object class. Alternatively, if you overload operator< for your class to do this same comparison, then you can simply do this: MyStruct max = *max_element(v.begin(), v.end()); A: For structs you can define a comparison function or object. You can also define the < operator for your struct. Here's a example. A: As you said in one of the comments you have many class members and want to address each individually in algorithms. You end up with various possibilities * *lambdas everywhere (either Phoenix or C++11) *functors for every case *member functions for every case I'd prefer the last two solutions only if I would need to repeat the lambdas in different places (or if I had to use Phoenix, but this is just a personal thing). struct Foo { int a; int b; bool less_than_by_a(const Foo&) const; bool less_than_by_b(const Foo&) const; }; std::max_element(begin, end, std::mem_fun_ref(&Foo::less_than_by_a)); std::max_element(begin, end, std::mem_fun_ref(&Foo::less_than_by_b));
{ "language": "en", "url": "https://stackoverflow.com/questions/7556693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: actionscript 3 How to access 'this' in inline function I am trying to do something like: String.prototype.print=function(){trace(??????)} I can't for the life of me figure out a way to get at the string! Yes I know there are other ways to approach this etc. but... A: Not sure what the problem is, using this works fine in anonymous functions. String.prototype.print=function():String{return "printed "+this;} var o:Object = "foo"; trace(o.print()); // traces: printed foo I just tricked the compiler to use an object, because "foo".print() causes Error: Call to a possibly undefined method print through a reference with static type String. A: It looks like you are mixing ActionScript 2 into your ActionScript 3 code. As kapep said, using "this" will work in your example. That is, this is perfectly valid code: String.prototype.print=function(){trace(this)} Of course, you are missing a semi-colon but that shouldn't matter: String.prototype.print=function(){trace(this);} //semi-colon after 'trace(this)' Depending on your development environment, you might be having trouble viewing trace statements, in general. In Flex Builder, for example, trace statements don't show up at all unless you are in Debug mode. Insert another call to trace to verify that you can see trace statements. As you said, there are many other ways to approach this, such as extending the String class and adding your "Print" function. If you really can't get this to work, then trying an ActionScript 3 (i.e. Object-Oriented) approach might be your best option.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556698", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: asp.net code within aspx file between quotation marks doesn't work This is something simple I guess, but I'm stuck with this and can't work further. I have the following code: <asp:CheckBox ID="cbxLevel_s" runat="server" Text='<%=this.rs.get("workshop")%>' /> the method between Text= returns a string. But what I get on the page is <%=this.rs.get("workshop")%> and not the string that should be returned. This same method can be used on places where there are no quotation marks. Any help? A: The quotation marks aren't the problem. The problem is that the control is a server-side control. You can either look in to data binding like James Johnson suggested or you can put this in your code behind: cbxLevel_s.Text = this.rs.get("workshop");
{ "language": "en", "url": "https://stackoverflow.com/questions/7556700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: problem with linkify in android app I have a phone number in a text view (thats the only thing I have there). I am using : Linkify.addLinks(textView, Linkify.ALL); However, the phone number is not being recognized by linkify. The number is of the format: (123) 456-7890. I have also tried 1234567890 and 123.456.7890. Nothing works. Any help ? thanks. A: In your XML file of your Text View add an attribute android:phoneNumber="true" Try this in the Click of the Text View : startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("tel:" + your_phone_number))); Automatically the Text will have the property of Phone number. A: Since you are trying something that is custom refer to this doc http://developer.android.com/resources/articles/wikinotes-linkify.html it will help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Capybara/selenium: wait for element to become hidden I need to wait for loading bar (div#loading) to disappear (become display: none) in a cucumber step. I'd expect the following to do the trick find('#loading').should_not be_visible But it doesn't seem to be waiting. Any ideas how to achieve that? A: You will want to use the wait_until to wait for your condition to be met. wait_until { !page.evaluate_script(%{$('#loading').is(':visible')}) } There might be a better wait to check for visibility, but last time I checked page.has_no_css does not work with things like :visible. (Update) Though has_css does not see selectors like :visible, Capybara::Node::Element does have some methods to make the above a bit prettier. wait_until { !find("#loading").visible? }
{ "language": "en", "url": "https://stackoverflow.com/questions/7556710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Troubleshoot Windows Binary When there is a GUI program not behaving as I expect it to in Linux I run it from the terminal so that I can see what errors are happening in the background, this helps in configuring the system and figuring out dependencies when the problem is not from the program but rather the system. This is especially helpful when the program doesn't give any feedback to the user in the GUI. Is there a way to do the same thing in Windows? A: In general, Windows programs are much less well defined in how they run, and there tends to be a much wider variety in the quality of the application, especially in regards to logging and debugging. Most (all?) windows applications can be run from the command line. You just have to find where the executable is located, and then run it. Looking at the path in an application shortcut can be helpful for this. Some applications have command line switches that do various things, but many don't. If there is documentation for the particular program, you may want to check there. Some well behaved windows programs will log to the System log. Depending on your access level and the version of Windows you are running, the System log can give you some good information about things that might be going wrong with the program, such as file permissions, etc. In general, however, no, there is no way to get error output from a program if it doesn't already output it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get number of values that only appear once in a column Firstly, if it is relevant, I'm using MySQL, though I assume a solution would work across DB products. My problem is thus: I have a simple table with a single column. There are no constraints on the column. Within this column there is some simple data, e.g. a a b c d d I need to get the number/count of values that only appear once. From the example above that would be 2 (since only b and c occur once in the column). Hopefully it's clear I don't want DISTINCT values, but UNIQUE values. I have actually done this before, by creating an additional table with a UNIQUE constraint on the column and simply INSERTing to the new table from the old one, handling the duplicates accordingly. I was hoping to find a solution that did not require the temporary table, and could somehow just be accomplished with a nifty SELECT. A: select count(*) from ( select col1, count(*) from Table group by Col1 Having Count(Col1) = 1 ) A: select field1, count(field1) from my_table group by field1 having count(field1) = 1 select count(*) from (select field1, count(field1) from my_table group by field1 having count(field1) = 1) first one will return the ones that are unique and second one will return the number of unique elements. A: just nest it a little... select count( cnt ) from ( select count(mycol) cnt from mytab group by mycol ) where cnt = 1 A: Assuming your table is called T and your field is called F: SELECT COUNT(F) FROM ( SELECT F FROM T GROUP BY F HAVING COUNT(*) = 1 ) AS ONLY_ONCE A: Could it be as simple as this: Select count(*) From MyTable Group By MyColumn Where Count(MyColumn) = 1 A: This is what I did and it worked: SELECT name FROM people JOIN stars ON stars.person_id = people.id JOIN movies ON movies.id = stars.movie_id WHERE year = 2004 GROUP BY name, person_id ORDER BY birth; note: I was working with several tables here. CS50 Problem Set 7 (pset7) 9.sql fix!!
{ "language": "en", "url": "https://stackoverflow.com/questions/7556713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Default label value for org.eclipse.swt.widgets.Text control; prevent databinding from persisting value Hy, suppose a org.eclipse.swt.widgets.Text control connected via databinding to the model Person. The Text represents the surname of the person. Now, everytime the model is changed, the value is updated, this is ok. Now I want the following: If there is no value for surname in the model, i want the text-control to contain a hint label, s.a. "Insert surname" which is not supposed to be persisted! I could create this behavior by adding a modifyListener to the textcontrol which sets the text if the length of setText is 0, I cannot prevent, however, the databinding then to persist "Insert surname"! I tried extending Text (to override getText), which is not allowed, and wrapping Text into a "LabeledText" requires me to modify the DataBinding! Anyone aware of a solution for this? Thx A: org.eclipse.swt.widgets.Text.setMessage() is a method exactly performing the requested task. A: I think it is quite hard to simulate such behavior with standard SWT widgets. So, probably, you need to create a custom widget, with validation simulation inside. Your validator should return you a validation status, which can be used afterwards.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: XSLT moving items inside other tag at the same level I have this problem for xslt: This is the input file: <root> <header/> <item/> … other n-1 <item/> <header/> <item/> … other m-1 <item/> </root> so header and item are at the same level (/root). it must be converted in something like: <root2> <header2> <item2/> …<item2/> // the first n-items up </header2> <header2> <item2/> …<item2/> // the last m-items up </header2> </root2> so basically the first n-item must be moved in the first header while the second group of items must be moved in the second header. Any idea how to get this? Thanks Randomize A: Sample XML: <root> <header/> <item>1</item> <item>2</item> <item>3</item> <header/> <item>5</item> <item>6</item> <item>7</item> </root> XSLT using grouping: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:key name="k" match="item" use="count(preceding-sibling::header)"/> <xsl:template match="/"> <root2> <xsl:apply-templates select="root/item[generate-id(.) = generate-id(key('k', count(preceding-sibling::header)))]" mode="a"/> </root2> </xsl:template> <xsl:template match="item" mode="a"> <header2> <xsl:apply-templates select="key('k', count(preceding-sibling::header))"/> </header2> </xsl:template> <xsl:template match="@* | node()"> <xsl:copy> <xsl:apply-templates select="@* | node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet> Or simple particular XSLT: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:template match="/"> <root2> <header2> <xsl:apply-templates select="root/item[count(preceding-sibling::header) = 1]"/> </header2> <header2> <xsl:apply-templates select="root/item[count(preceding-sibling::header) = 2]"/> </header2> </root2> </xsl:template> <xsl:template match="@* | node()"> <xsl:copy> <xsl:apply-templates select="@* | node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet> Both produce the same output: <root2> <header2> <item>1</item> <item>2</item> <item>3</item> </header2> <header2> <item>5</item> <item>6</item> <item>7</item> </header2> </root2> A: This is a simpler more efficient XSLT 1.0 solution, than counting all preceding siblings: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:key name="kFollowing" match="item" use="generate-id(preceding-sibling::header[1])"/> <xsl:template match="/*"> <root> <xsl:apply-templates select="header"/> </root> </xsl:template> <xsl:template match="header"> <heather2> <xsl:copy-of select="key('kFollowing', generate-id())"/> </heather2> </xsl:template> </xsl:stylesheet> When this transformation is applied on the following XML document: <root> <header/> <item>1</item> <item>2</item> <item>3</item> <header/> <item>5</item> <item>6</item> <item>7</item> </root> the wanted, correct result is produced: <root> <heather2> <item>1</item> <item>2</item> <item>3</item> </heather2> <heather2> <item>5</item> <item>6</item> <item>7</item> </heather2> </root> Explanation: A key is defined in such a way that for a header any of the immediately-following item elements is matched by the generate-id() of this header. II. XSLT 2.0 solution: <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:template match="/*"> <root> <xsl:for-each-group select="item" group-adjacent= "generate-id(preceding-sibling::header[1])"> <header2> <xsl:sequence select="current-group()"/> </header2> </xsl:for-each-group> </root> </xsl:template> </xsl:stylesheet> when this transformation is applied on the same XML document (above), the same correct result is produced: <root> <header2> <item>1</item> <item>2</item> <item>3</item> </header2> <header2> <item>5</item> <item>6</item> <item>7</item> </header2> </root> Explanation: Use of xsl:for-each-group, group-adjacent, current-group()
{ "language": "en", "url": "https://stackoverflow.com/questions/7556718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do you start a background task in iOS? What I am trying to do is to let application run in the background when a user takes a specific action (pushes a button). On blackberry, there is a method called application.requestbackgtound(); Is there something similar in iOS? A: If your app has requested background activity (via a UIBackgroundModes key for audio, voip, or location in the app's info.plist), or has requested extra background time for a limited period (via calling beginBackgroundTaskWithExpirationHandler:), then launching another app (such as Safari) via openURL: will put your app in the background.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Windows Azure Access Control with ASP.NET Membership I have an existing production application that uses vanilla ASP.Net Membership for authentication. However, I'd like to provide other means of authentication as well as the current ASP.net membership system, such as Facebook. The Windows Azure Access Control Service makes this extremely easy and straight forward. Provided, that is, you're starting a new web application from scratch. So, in this case, how do I * *Integrate the Access Control Service authentication into my app without affecting the current login system and its users? *Migrate users over or Link logins? ( not sure if this is even possible) Thanks all Roberto A: You need to create a custom identity provider based on your membership database. See this article on custom WS-Federation Identity Providers that can be integrated to access control: http://msdn.microsoft.com/en-us/library/windowsazure/gg185933.aspx Also see this article on one that was written on top of the membership database: http://blogs.msdn.com/b/vbertocci/archive/2009/04/23/enhance-your-asp-net-membership-based-website-by-adding-identity-provider-capabilities.aspx A: Approach of creating an identity provider (IP) based on your ASP.NET membership database which Paul Tyng suggested is valid. However, it means that if you just create an IP you'll allow log in to all people who are authorised with other IPs (e.g. Google or Facebook). I'm guessing it's not what you want - you'd still want people to first register (either plainly with username-password or with their external identity). If that's the case then your task is the following: * *Add a data store for users' external identities which is related to your existing Users table. *Modify the ACS login handling within your application to check that the identity returned from ACS actually exists in your members database. *Perform member log in (instead of federated log in) if you found the returned identity in your db. *Add external identity tie in during the registration process so your Identities table can be actually populated. *(optional) Re-use the bulk of the #4 mechanism to provide an ability to attach external identity to existing user accounts (i.e. I already have a normal membership with you and now want to add an ability to log in with Google as well, for example). There is no one single tutorial/walk-through to achieve this (or I have not found one) so I had to pull bits from a variety of sources to make it work. Please let me know in the comment if I understood your requirement correctly and I'll add a guide on how to set this up. Cheers! A: Might be a bit late, but check out the following blog posts by fellow Windows Azure MVP - Dominik Bayer: * *Mixing Forms and Token Authentication in a single ASP.NET Application *Mixing Forms and Token Authentication in a single ASP.NET Application (the Details) *Replacing ASP.NET Forms Authentication with WIF Session Authentication (for the better) Invaluable readings which will help you in any way!
{ "language": "en", "url": "https://stackoverflow.com/questions/7556721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Empty list of generic arguments Section 15.3 of the spec mentions the sequence < > with intervening whitespace is an allowed form. It indicates an empty list of generic arguments, which allows for the following oddity. type A() = class end let a = new A< >() Why is this allowed? Since generic types can be instantiated with type args omitted, is this a type checking optimization of sorts? A: I agree with Ramon that it makes things more consistent, in that you can treat non-generic types as a degenerate case of types of generic arity 0. In the case of types which are "overloaded" by generic arity, this allows you to be more explicit about which type you're referring to: type T(o:obj) = class end type T<'t>(t:'t) = class end let t = T("test") let t' = T< >("test") let t'' = T<_>("test") Without thinking carefully about overload resolution, it's not necessarily obvious what type t has, but it's completely clear what types t' and t'' have. A: I think it is just for consistency. You can do List<int> and Dictionary<string, bool>, so you can also do int< >.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How does this MSDN CompareExchange sample not need a volatile read? I was looking for a thread-safe counter implementation using Interlocked that supported incrementing by arbitrary values, and found this sample straight from the Interlocked.CompareExchange documentation (slightly changed for simplicity): private int totalValue = 0; public int AddToTotal(int addend) { int initialValue, computedValue; do { // How can we get away with not using a volatile read of totalValue here? // Shouldn't we use CompareExchange(ref TotalValue, 0, 0) // or Thread.VolatileRead // or declare totalValue to be volatile? initialValue = totalValue; computedValue = initialValue + addend; } while (initialValue != Interlocked.CompareExchange( ref totalValue, computedValue, initialValue)); return computedValue; } public int Total { // This looks *really* dodgy too, but isn't // the target of my question. get { return totalValue; } } I get what this code is trying to do, but I'm not sure how it can get away with not using a volatile read of the shared variable when assigning to the temporary variable that is added to. Is there a chance that initialValue will hold a stale value throughout the loop, making the function never return? Or does the memory-barrier (?) in CompareExchange eliminate any such possibility? Any insight would be appreciated. EDIT: I should clarify that I understand that if CompareExchange caused the subsequent read of totalValue to be up to date as of the last CompareExchange call, then this code would be fine. But is that guaranteed? A: If we read a stale value, then the CompareExchange won't perform the exchange - we're basically saying, "Only do the operation if the value really is the one we've based our calculation on." So long as at some point we get the right value, it's fine. It would be a problem if we kept reading the same stale value forever, so CompareExchange never passed the check, but I strongly suspect that the CompareExchange memory barriers mean that at least after the time through the loop, we'll read an up-to-date value. The worst that could happen would be cycling forever though - the important point is that we can't possibly update the variable in an incorrect way. (And yes, I think you're right that the Total property is dodgy.) EDIT: To put it another way: CompareExchange(ref totalValue, computedValue, initialValue) means: "If the current state really was initialValue, then my calculations are valid and you should set it to computedValue." The current state could be wrong for at least two reasons: * *The initialValue = totalValue; assignment used a stale read with a different old value *Something changed totalValue after that assignment We don't need to handle those situations differently at all - so it's fine to do a "cheap" read so long as at some point we'll starting seeing up-to-date values... and I believe the memory barriers involved in CompareExchange will ensure that as we loop round, the stale value we see is only ever as stale as the previous CompareExchange call. EDIT: To clarify, I think the sample is correct if and only if CompareExchange constitutes a memory barrier with respect to totalValue. If it doesn't - if we can still read arbitrarily-old values of totalValue when we keep going round the loop - then the code is indeed broken, and may never terminate. A: Edit: Someone gave me an upvote after all this time so I re-read the question and the answer and noticed a problem. I either didn't know about introduced reads or it hasn't crossed my mind. Assuming Interlocked.CompareExchange doesn't introduce any barriers (since it's not documented anywhere), the compiler is allowed to transform your AddToTotal method into the following broken version, where the last two arguments to Interlocked.CompareExchange could see different totalValue values! public int AddToTotal(int addend) { int initialValue; do { initialValue = totalValue; } while (initialValue != Interlocked.CompareExchange( ref totalValue, totalValue + addend, totalValue)); return initialValue + addend; } For this reason, you can use Volatile.Read. On x86, Volatile.Read is just a standard read anyway (it just prevents compiler reorderings) so there's no reason not to do it. Then the worst that the compiler should be able to do is: public int AddToTotal(int addend) { int initialValue; do { initialValue = Volatile.Read (ref totalValue); } while (initialValue != Interlocked.CompareExchange( ref totalValue, initialValue + addend, initialValue)); return initialValue + addend; } Unfortunately, Eric Lippert once claimed volatile read doesn't guarantee protection against introduced reads. I seriously hope he's wrong because that would mean lots of low-lock code is almost impossible to write correctly in C#. He himself did mention somewhere that he doesn't consider himself an expert on low-level synchronization so I just assume his statement was incorrect and hope for the best. Original answer: Contrary to popular misconception, acquire/release semantics don't ensure a new value gets grabbed from the shared memory, they only affect the order of other memory operations around the one with acquire/release semantics. Every memory access must be at least as recent as the last acquire read and at most as stale as the next release write. (Similar for memory barriers.) In this code, you only have a single shared variable to worry about: totalValue. The fact that CompareExchange is an atomic RMW operation is enough to ensure that the variable it operates on will get updated. This is because atomic RMW operations must ensure all processors agree on what the most recent value of the variable is. Regarding the other Total property you mentioned, whether it's correct or not depends on what is required of it. Some points: * *int is guaranteed to be atomic, so you will always get a valid value (in this sense, the code you've shown could be viewed as "correct", if nothing but some valid, possibly stale value is required) *if reading without acquire semantics (Volatile.Read or a read of volatile int) means that all memory operations written after it may actually happen before (reads operating on older values and writes becoming visible to other processors before they should) *if not using an atomic RMW operation to read (like Interlocked.CompareExchange(ref x, 0, 0)), a value received may not be what some other processors see as the most recent value *if both the freshest value and ordering in regards to other memory operations is required, Interlocked.CompareExchange should work (the underlying WinAPI's InterlockedCompareExchange uses a full barrier, not so sure about C# or .Net specifications) but if you wish to be sure, you could add an explicit memory barrier after the read A: The managed Interlocked.CompareExchange maps directly to the InterlockedCompareExchange in the Win32 API (there is also a 64 bit version). As you can see in the function signatures, the native API requires the destination to be volatile and, even though it is not required by the managed API, using volatile is recommended by Joe Duffy in his excellent book Concurrent Programming on Windows.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556727", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Make a div visible from an outside php I'm working on a log in session, and I want to display errors on the same page, for example - "Invalid Password" or "User does not exist". Heres my code: <?php session_start(); mysql_connect('mysql.database.com','user','database')or die ('Connection Failed: '.mysql_error()); mysql_select_db('database')or die ('Error when selecting Database: '.mysql_error()); function remove($mensaje) { $nopermitidos = array("'",'\\','<','>',"\""); $mensaje = str_replace($nopermitidos, "", $mensaje); return $mensaje; } if(trim($_POST["usuario"]) != "" && trim($_POST["password"]) != "") { $usuario = strtolower(htmlentities($_POST["usuario"], ENT_QUOTES)); $password = $_POST["password"]; $result = mysql_query('SELECT password, usuario FROM usuarios WHERE usuario=\''.$usuario.'\''); if($row = mysql_fetch_array($result)){ if($row["password"] == $password){ $_SESSION["k_username"] = $row['usuario']; header( 'Location: diseno.php' ) ; }else{ echo '<p class="message2">Invalid password</p>'; } }else{ echo '<p class="message2"User does not exist</p>'; } mysql_free_result($result); }else{ echo '<p class="message2">Must enter a user and password</p>'; } mysql_close(); ?> <SCRIPT LANGUAGE="javascript"> location.href = "index.php"; </SCRIPT> As you can see that's my validation and action for the log in form. Instead of echoing errors in a new page I want to display it in the same page. I tried with javascript and it didn't work I used. var page = document.URL = "http://www.mysite.com/login.php" page.getElementById( 'wrongpassword' ).style.display = 'block'; All divs I want to display are set as none in the login.php file. Anyone could help me? A: The easiest way to accomplish this is to process the login and then include the PHP code which displays the normal page. I'm not sure how you've designed your site, but including index.php at the end might do the trick. Right now, you are using a JS redirect, which won't give you the result that you want. Instead of echoing the message, I like to set a $message variable which includes the message. When you render the main page, simply echo this variable in the appropriate place if it is set. A: For doing it simply you can make use of JQuery. I have done it on my website so I can say it really works. Start your session, checking the values and either assign the value in global variables of javascript or print it there only eg. <?php session_start(); //checking ur values echo "<script src=\"js/jquery-1.8.3.min.js\"></script> <script type=\"text/javascript\"> $(document).ready(function(){ //you can assign values here or print error messages to any div ('.div_class').html("unuthorised user"); }); </script>"; ?> Here I have used a downloaded JQuery file from http://jquery.com/download/ You can choose other wise to use the online version of this JQuery file. The syntax for that is <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> Feel free to get back in case of any further query/issues regarding the above code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Table spacing issue with IE9 please see http://www.cookandheat.com I have an issue with the spacing of the 4 small images on the right. All ok in Firefox,Chrome but spreading out with IE9.. CSS looks like this: .fixedtable{ width: 90px; overflow: hidden; text-align: right; vertical-align: top; } Thanks for any advice to solve this.. Rich Note - this is the sample HTML (moved from comment): <tr> <td class="fixedtable"> <img src="images/service-now.jpg" alt="aga service" width="90" height="150" align="right" /> </td> <td class="fixedtable"> <img src="images/aga-cosmetics.jpg" alt="aga cosmetics" width="90" height="150" align="right" /> </td> <td class="fixedtable"> <img src="images/aga-installations.jpg" alt="aga installations" width="90" height="150" align="right" /> </td> <td class="fixedtable" > <img src="images/regions-covered.jpg" alt="aga south west" width="90" height="150" align="right" /> </td> </tr> A: I just checked this in broswer lab. It seems you've fixed the problem. As I can see, your issue is not with the images, but with the overall section spreading out too far. I suspect this has something to do with 'transitional' DTD declaration. Try using 'strict' instead and see if you have the same problem. – Aleks G Sep 26 at 19:06 All credit goes to him! You should remove this question or answer it yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Displaying Spring MVC validation errors in Freemarker templates I'm trying to display a list of global validation errors in my freemarker template if a controller returns binding errors. I can display errors that are associated with a field, but I want to detect when an error has occurred within a specific bean and display a message at the top of the page. I've tried using the example below which produces no output: <@spring.bind "webPage" /> .... <#if spring.status.error> There were problems with the data you entered: <ul> <#list spring.status.errorMessages as error> <li>${error?html}</li> </#list> </ul> </#if> The line below always returns 0, despite there being errors with the submitted form: ${spring.status.errorMessages?size} My controller code is below: @RequestMapping(method = RequestMethod.POST) public ModelAndView save(@ModelAttribute("webPage") @Valid WebPage page, BindingResult result, Model model) { if (!model.containsAttribute("site")) { throw new IllegalArgumentException("Model must contain site attribute."); } Site site = (Site) model.asMap().get("site"); if (!result.hasErrors() && !page.isNew()) { this.pageService.save(page, site); } else if (!result.hasErrors() && page.isNew()) { this.pageService.create(page, site); } return createMav(result); } The createMav method is below: public ModelAndView createMav(BindingResult result) { ModelAndView mav = new ModelAndView(); mav.setViewName(getPrimaryControllerView()); mav.addAllObjects(result.getModel()); return mav; } Is there a way to achieve this using Freemarker + Spring MVC? A: I found a roundabout way to do this using the standard MVC JSP taglib. I make this available to Freemarker: <#assign form=JspTaglibs["http://www.springframework.org/tags/form"] /> I then use the following macro to display global error message: <#macro formErrors> <#assign formErrors><@form.errors path="*" /></#assign> <#if formErrors?has_content> <div id="errors"> <@spring.message "admin.error.globalMessage" /> </div> </#if> </#macro> I just place the following line where ever I want this error message to appear (this has to be contained within the form element that submits to the controller): <@form.form method="POST" commandName="webPage"> <@formErrors /> .... </@form.form> A: You can write as follows: <#if spring.status.error> <ul> <#list spring.status.errors.globalErrors as error> <li>${error.defaultMessage}</li> </#list> </ul> </#if> More info at BindStatus and Errors classes. A: Try something like this: <@spring.bind "webPage" /> <#if (spring.status.errors.allErrors?size > 0) > <@spring.message "my.global.error.code"/> </#if> A: See the documentation: http://static.springsource.org/spring/docs/current/spring-framework-reference/html/view.html#view-velocity-forms. It has an example of what you want to do.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Android GPS Location Update Method does not work in OnCreate of Map activity I am facing a problem with the LocationManager class: I want to update my current location in onCreate() of a class extended from MapActivity: LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); MyLocationListener lcs = new MyLocationListener(); lcs.onLocationChanged(lm.getLastKnownLocation(LocationManager.GPS_PROVIDER)); whereas getLastKnownLocation() returns the location but inaccurate, I want to call LocationManager.requestLocationUpdates() which returns null in onCreate(): LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); MyLocationListener lcs=new MyLocationListener(); lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, lcs); Can anyone tell me how I will be able to get my current location in my onCreate()? A: LocationManager only communicates with your code using the supplied listener. When a new location fix is available, onLocationChanged() will be called in the lcs instance of the MyLocationListener class your created. You don't want to risk your app being force closed while waiting for the first location fix in onCreate(). Best practice is to register your LocationListener in onResume() and also unregister it again in onPause() using LocationManager.removeUpdates(LocationListener). Your users will thank you for not draining their battery when your app isn't in the foreground :) A: Thanks, guys for responding and giving very reasonable suggestion but unfortunatly these didnt worked for me. I acheived my goal by implementing little time delay and every thing started working fine and my primary goal of getting location in Oncreate method is acheived. It came up with the understanding that OnCreate method called first and OnResume later if you want to get your current location with map randering then you will have to wait for map to be render first then call the location update code. A: here is the tutorial http://www.androidcompetencycenter.com/?s=GPS or try this http://www.firstdroid.com/2010/04/29/android-development-using-gps-to-get-current-location-2/
{ "language": "en", "url": "https://stackoverflow.com/questions/7556738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP ftp_connect() fail Very simple problem but one which I am unable to solve. Why would I get a ftp_connect() fail? $conn = ftp_connect("www.server.com"); Have tried SSL connect. Intrestingly I had no problem with this ftp_connect() on this server until recently when I started getting error messages. Not too sure what triggered this perhaps an update as the code was not altered. Thanks in advance Edit: Found this in Plesk : Shell access to server with FTP user's credentials - ForbiddenHave no idea if its relevant A: Ok, after lots of fiddling (asking someone else) this is the solution I found... $conn = ftp_connect(localhost); Well the simplest solution is the best. This works as the code is situated on the server to which it is trying to connect.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android getting best location I want the exact location of user. So I created two listeners as: locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mGPSListener); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mNetworkListener); I am listening for location updates from both the network and gps providers and wanted to check the accurary of locations obtained by both so that I can pick the accurate location. I just want to ask am I using the right way of acheiving that...??? if not, please provide some guideline how to do this...??? My example code is: if(MyGPSListener.currentLocation != null) { if(MyNetworkListener.currentLocation != null) { if(MyGPSListener.currentLocation.getAccuracy() <= MyNetworkListener.currentLocation.getAccuracy()) { useGPSLocation(); } else if(MyGPSListener.currentLocation.getAccuracy() > MyNetworkListener.currentLocation.getAccuracy()) { useNetworkLocation(); } } else { useGPSLocation(); } } else if(MyNetworkListener.currentLocation != null){ useNetworkLocation(); } A: You should take a look at: http://developer.android.com/guide/topics/location/obtaining-user-location.html Especially the function: isBetterLocation I would probably use something like the isBetterLocation. Since it's actually quite important to see how old the location updates are. At least if you really want to know where the user is know and not where the user were. But you can surely implement a time check in your own function which you described. A: You can use https://github.com/balwinderSingh1989/androidBestLocationTracker Android Best Location Tracker is an Android library that helps you get user best location with a object named BaseLocationStrategy that would give a accurate location using accuracy alogrithm. It has added support till latest android api levels and can fetch location in background with ease. For usage, refer "READ ME" of project. A: You can check Google's offical document. Define a model for the best performance And Validate the accuracy of a location fix: * *Check if the location retrieved is significantly newer than the previous estimate. *Check if the accuracy claimed by the location is better or worse than the previous estimate. *Check which provider the new location is from and determine if you trust it more.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Apache Axis 1: WSDL2Java - overwrite generated sources? When running org.apache.axis.wsdl.WSDL2Java (Axis 1) against a recently changed wsdl, there is a failure because some sources already exist. Is there a way to force overwrite of existing classes? I don't see anything at http://axis.apache.org/axis/java/reference.html that can help me in this case. I am looking for something like the -or option which can be used in the Axis 2 WSDL2Java command. A: I don't believe there is a way to force the overwrite. At least I can't find one in the code for the ant task so I imagine it doesn't exist. Would using the Axis2 wsdl2java work for you with the -b and -or flags? That should generate Axis 1.x compatible code and give you access to the overwrite option that does exist in the Axis2 version of the command.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ctypes double array encodes wrong (1.35689368162e-312-->0.047098) I have a function that accepts a double array as first parameter cb_type = CFUNCTYPE(c_void_p, c_double * 2, c_int, c_int) def mycb(cube, ndim, nparams): print "cube before", [v for v in cube] for i in range(ndim): cube[i] = cube[i] * 10 * math.pi print "cube after", [v for v in cube] I hand it over to C via the usual cb_type(mycb). C calls it: printf("values before: %f, %f\n", Cube[0], Cube[1]); cb(Cube, *ndim, *npars); printf("values after : %f, %f\n", Cube[0], Cube[1]); When I run the program, there is some packing/unpacking or decoding issue: values before: 0.047098, 0.010474 | C cube before [4.3191267336e-314, 1e-323] | Python, should be the same values cube after [1.35689368162e-312, 3.1e-322] | Python values after : 0.047098, 0.010474 | C How can I fix the encoding issue (receive [0.047098, 0.010474] in the python function)? A: I fixed it by using POINTER(c_double) instead of c_double * 2. The new output looks like this: values before: 0.905349, 0.270400 cube before [0.905348643442958, 0.2703996141057701] cube after [28.44236647177882, 8.494854412082024] values after : 28.442366, 8.494854
{ "language": "en", "url": "https://stackoverflow.com/questions/7556746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to package chrome browser in a branded exe/dmg installer? I'm looking to create an exe (and maybe dmg) installer that simply opens an invisible browser window and navigates to a webpage. Preferably using Google Chrome's rendering/javascript engine. The idea is that I have a web app that I need to disguise as a windows program. A bit like the way iTunes loads it's web store. Any tips/advice? As a additional/separate issue, how complex would it be to package a php & mySQL server into the installer so I can run the app offline? Thanks a lot! A: One popular platform for achieving this is something called Titanium (see http://www.appcelerator.com/), although it is more often used for mobile development. Personally, I found Titanium to be a little clunky. There is an OS X tool called Fluid (http://fluidapp.com/), but that is more aimed at users who want to turn arbitrary websites into apps. This is somewhat of a non-answer, but I would suggest thinking long and hard about whether you can use Chrome Web Store (https://chrome.google.com/webstore) instead, as that is much more convenient for developers and — I might argue — for users as well. Maybe you can start out that way and then look into more complex solutions later if it turns out you really need it. When that time comes, it is likely that a better and cleaner solution for this has appeared. A: There's no official way to do this at the moment. There's a chromium page on this feature, though. You might be able to make a custom launcher that will quietly invoke Chrome and your server stack. Here's a list of command line flags you might find useful. Also see this recently asked question: Can I Create Chrome Application Shortcuts Programmatically from a Web Page? A: Have you considered Adobe Air? It can do just that, and you package it as an exe.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: "Website: Not a valid URL format" when creating an application of twitter I'd like to create an application that can integrate with Twitter. So I went to the website: https://dev.twitter.com/apps/new to create an application. But the WebSite: field always failed. It said that "Website: Not a valid URL format". I tried different "valid" URLs, but failed. Do you have any ideas on the twitter application? Thanks in advance. Michael A: In my case the problem was in trailing whitespace from copy/paste. A: One easy mistake to make is both the callback url and website need to start with http:// This worked for me: WebSite: http://example.com CallbackURL: http://example.com/auth/twitter/callback/ A: I'm able to make applications if I include "http://" at the beginning. Also it might be something browser related (I'm using Chrome) so check that. A: I was trying to set localhost URL and got the same error message. After replacing http://localhost http://localhost/twitter/callback with http://127.0.0.1 http://127.0.0.1/twitter/callback it let me saved my test application A: I was having the same Issue, then after googling, someone said that: "I think your website and callback should match. Some examples: website: http://www.quoteicon.com callback: http://www.quoteicon.com/twitter/callback " summarizing the field callback has to be prefixed with the website, otherwise it gets error that the URL is invalid! and they dont accept local IPs to the webSite fields. It worked for me, hope this help you. A: Old question but I ran into this today. Twitter does not allow localhost or IP addresses in the URL (plus it does require http:// or https:// as a prefix). However this doesn't help with local debugging. So an easy workaround is to add something like myapp.here.com in your /etc/hosts file 127.0.0.1 myapp.here.com and then enter http://myapp.here.com and http://myapp.here.com/auth/twitter in the fields. That should allow local debugging. It is odd as Facebook makes this a bit easier and it seems like a common task for debugging these types of integrations. You could even override your actual domain locally if you wanted to use the same Twitter App ID. A: Mine is working. Save it in this format http://url.com. Even this domain.com works. You can try doing it in a different browser, logout and login. A: Be aware of localhost, if you are developing on local machine. Twitter doesn't allow url with http://localhost:3000 or without http. I'm wonder, why ;] Hope, They will add it. A: I just found that I didn't have a problem with my callback url at all, but the error message was for the Website url! A: Tried everything now, eventually only https://example.com/auth worked. A: I simply added www and the error was gone. Previously http://twitter.com/... After http://www.twitter.com/... A: This issue is resolved when I give my Website & Callback URL same htt://URL.Hope it will help to resolve your solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: How to get value from a repeater in server side on button click <asp:Repeater ID="rptList" runat="server"> <HeaderTemplate> </HeaderTemplate> <ItemTemplate> <tr> <td width="15%"> <b>Subject</b> </td> <td width="60%"> <%#Eval("Title")%> </td> </tr> I do databind to a repeater, and bind the title value. string MysqlStatement = "SELECT Title, RespondBy FROM tbl_message WHERE MsgID = @Value1"; using (DataServer server = new DataServer()) { .. } rptList.DataSource = ds; rptList.DataBind(); How can I get the value of title in server side, when a button in clicked in the same page. A: I would set the value of title to the text of a label that you could call FindControl() on. A: I would put the title in a server control, like a label, and then you can do something like this: <asp:Repeater ID="rptList" runat="server"> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%#Eval("Title")%>' /> </ItemTemplate> </asp:Repeater> And then in the code behind: int itemIndex = 0; Label lbl = rptList.Items[itemIndex].FindControl("Label1") as Label; if (lbl != null) { string labelValue = lbl.Text; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7556763", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Group by the array value I'm using this code: $permissions = array("canview", "canpostthreads", "canpostreplies", "canpostpolls", "all"); foreach($permissions as $permission) { for ($i = 1; $i <= 5; $i++) { $mode = $_POST['permission'][$i][$permission]; if($mode == 1) echo "{$permission} = {$i}:::"; } } And the output if I check some checkboxes is: canview = 1:::canview = 5:::canpostreplies = 3:::canpostpolls = 5::: I wan't the output to be following: instead of canview = 1:::canview = 5: canview = 1,5 and if I'll have for example: canpostpolls = 1:::canpostpolls = 2:::canpostpolls = 3 It'll be: canpostpolls = 1,2,3:::canview = 1,5 I hope you understand it guys. This is my own idea for this, you are free to share your ideas with me, this data will be exported to the mysql table. A: $permissions = array("canview", "canpostthreads", "canpostreplies", "canpostpolls", "all"); $setpermissions = array(); foreach($permissions as $permission) { for ($i = 1; $i <= 5; $i++) { $mode = $_POST['permission'][$i][$permission]; if($mode == 1) { if (!isset($setpermissions[$permission])) { $setpermissions[$permission] = array(); } $setpermissions[$permission][] = $i; } } } $plist = array(); foreach ($setpermissions as $name => $sp) { $plist[] = "$name = " . implode(',', $sp); } echo implode(':::', $plist); A: You need to filter your data a bit more... maybe something like this: $permissions = array("canview", "canpostthreads", "canpostreplies", "canpostpolls", "all"); $filtered_perms = array(); foreach($permissions as $permission) { for ($i = 1; $i <= 5; $i++) { $mode = $_POST['permission'][$i][$permission]; if($mode == 1) { if(!is_array($filtered_perms[$permission])) { $filtered_perms[$permission] = array(); } $filtered_perms[$permission][] = $i; } } Then, you can do something like: $final_perms = array(); foreach($filtered_perms as $key => $val) { $final_perms[$key] = implode(",", $val); } Hope that helps! A: $permissions = array("canview", "canpostthreads", "canpostreplies", "canpostpolls", "all"); $userPermissions = array(); foreach($permissions as $permission) { for ($i = 1; $i <= 5; $i++) { $mode = $_POST['permission'][$i][$permission]; if($mode == 1) $userPermissions[$permission][] = $i; } } foreach($userPermissions as $permission => $values) { echo "{$permission} = " . implode(',', $values) . ":::"; } A: You can do something like this - essentially, combining the values before outputting them. $permissions = array("canview", "canpostthreads", "canpostreplies", "canpostpolls", "all"); foreach($permissions as $permission) { $vals = array(); for ($i = 1; $i <= 5; $i++) { $mode = $_POST['permission'][$i][$permission]; if($mode == 1) $vals[] = $i; } if(count($vals)) echo $permission . ' == ' . implode(',', $vals); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7556767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails sprocket Error compiling CSS assest - CHOWN issue I've been breaking my head over this for over 2 days now, and can't seem to figure out where the problem is. This is mostly a problem related to my setup, but if anyone could help me find a solution to this problem, then I'll be his slave for eternity..! I'm running Snow leopard(host) and VMware fusion running Ubuntu Lucid server (guest OS). Somehow after a lot of head-banging I managed to get my workspace shared from Mac to Ubuntu. So, essentially I've been able to isolate my dev environment on a VM, which makes it easy for the entire dev team to be on the same environment irrespective of their host OS / setting, etc. While, it certainly has made everything easy, I'm stuck with a specific problem occurring due to sprockets (I guess). Every time I make changes to my stylesheets and reload, I get this error: Error compiling CSS asset Errno::EPERM: Operation not permitted - /mnt/hgfs/banjarey/tmp/cache/assets/DCF/780/sprockets%2F5f78b3457def1d02bd3fb75d4e0cfb63 /home/coderboy/.rvm/gems/ruby-1.9.2-p290/gems/activesupport-3.1.0/lib/active_support/core_ext/file/atomic.rb:38:in `chown' The strage thing though is that if I reload the page twice or thrice, the css compiles and everything works alright. It's a real shame to be reloading the page twice or thrice for every single css change I make. I've played around with memberships and permissions a little bit, but been an amateur I've not ventured deep enough I guess. Any idea folks ?? A: I have the same problem. my solution is to modify the File Permission after precompile assets: #chown apache.root yourapp -R #chmod 755 yourapp -R A: A bit late with this answer, but chmod everytime the app is deploy does not seem to be a good solution. I think the issue is your apache instance and your passenger instance are running as different users. So the solution is to check what user your apache server is running as and set the PassengerDefaultUser, For example: PassengerDefaultUser www-data This worked for me. As Passenger was making files only readable by nobody, weird is that if you just refresh a few times it some how works out, but making sure they are the same user stops this error. A: I experienced the same error, but in development! Solved after clean and recompile assets: rake assets:clean && rake assets:precompile A: Make sure the underlying file system supports the requested operation. The following commands fixed it for me. mv public/assets /tmp ln -s /tmp/assets public/assets
{ "language": "en", "url": "https://stackoverflow.com/questions/7556774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: What does this perl line from a "bleached" file do? I have some perl files which have been "bleached" (don't know if it was from ACME::Bleach, or something similar). Not being very fluent in perl, I'd like to understand what the one-liner that starts the file does to decode the whitespace that follows: $_=<<'';y;\r\n;;d;$_=pack'b*',$_;$_=eval;$@&&die$@;$_ The rest of the file is whitespace characters, and the file is executable by itself (it's placed in a /bin directory). [Solution], thanks to @JB. The pack portion of this seems the most complex, and it took me a while to notice what was going on. Pack is taking the LSB only of every 8 characters, and unpacking that as a big-endian character in binary. Tabs hence become '0's, and spaces become '1's. '\t\t \t ' => '#' in binary: 00001001 00001001 00100000 00100000 00100000 00001001 00100000 0100000 every LSB: 1 1 0 0 0 1 0 0 convert from from big-endian format: 0b00100011 == 35 == ord('#') A: You can use unbleach.pl to remove bleaching, if that's what you're really trying to do. A: * *$_ = << ''; reads the rest of the file into the accumulator. *y;\r\n;;d; strips carriage returns and line feeds. *$_ = pack 'b*', $_; converts characters to bits in $_, LSB first. *$_ = eval; executes $_ as Perl code. *$@ && die $@; $_ handles exceptions and the return code gracefully.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Faster Django Pagination App We use django-paging, which is a bit old. One of the big issues is that the app performs a count on the queryset returned by each view, which is slow and doesn't provide us any value in our case. I see that django-pagination has more downloads/repo-watchers. I've also used the Django Digg Style paginator in the past. Should we switch over to a new paginator app or just strip out the count MySQL query? Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7556785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Show Different "Code/Words" Based on URL Referer I'm trying to have my website not show certain code if they come from certain URL's. For example, Wikipedia don't like links to sites that have popups on them. So I need to not show the code for that referer. I found the following code but it doesn't seem to work when code is places instead of text <?php $ref=getenv('HTTP_REFERER'); if (strpos($ref,"google.com")>0) { echo "google"; } else { echo "something else"; }; ?> A: If you want to avoid showing code to google: <?php if (!strstr(strtolower($_SERVER['HTTP_USER_AGENT']),"googlebot")){ ?> //Show what you want, google will not see it }else{ //show other code }?>?> For wikipedia: <?php if (!strstr(strtolower($_SERVER['HTTP_REFERER']),"wikipedia")){ ?> //Show what you want, wikipedia will not see it }else{ //show other code }?> Enjoy ;) A: You were talking about Wikipedia. Probably the problem is that google isn't sending you "google" in their referer string A: it must work, try alternative variable <?php $ref=$_SERVER['HTTP_REFERER']; if (strpos($ref,"google.com")>0) { echo "google"; } else { echo "something else"; }; ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7556786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem with secondary delegate I have two UITableView, each one has a different delegate in the same UIViewController. I'm trying to call control in another delegate, but it failed. Brief: mainViewController contains UITableView (with UITableViewDelegate and UITableViewDataSource) + UIImageView. secondaryTable contains UITableView (with UITableViewDelegate and UITableViewDataSource). I want to call UIImageView from secondaryTable. In .h @interface secondaryTable : UIViewController <UITableViewDataSource,UITableViewDelegate> @end @interface mainViewController : UIViewController <UITableViewDataSource,UITableViewDelegate> { @property (nonatomic,retain) IBOutlet UIImageView *navbar; @property (nonatomic,retain) IBOutlet UITableView *Table1; @property (nonatomic,retain) IBOutlet UITableView *Table2; @end In .m @implementation secondaryTable - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 2; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *MyIdentifier = @"MyIdentifier2"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease]; [cell.textLabel setFont:[UIFont boldSystemFontOfSize:12.0]]; cell.selectionStyle = UITableViewCellSelectionStyleNone; cell.textLabel.textAlignment = UITextAlignmentCenter; } if (indexPath.row == 0) cell.textLabel.text =@"A"; if (indexPath.row == 1) cell.textLabel.text =@"B"; return cell; } -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSLog(@"Selected"); mainViewController *myController = [[mainViewController alloc] init]; [myController.navbar setHidden:NO]; } @end @implementation mainViewController - (void)viewDidLoad { Table1.delegate = self; Table1.dataSource = self; secondaryTable *myDelegate = [secondaryTable alloc]; Table2.delegate = myDelegate; Table2.dataSource = myDelegate; @end } It types "Selected" in console log, but it won't show control. Why can't it call navbar control in mainViewController? A: I would suggest doing this by having both tables point to the same delegate but, within your delegate methods, select behaviour based on which table it is. Example: - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if (tableView == firstTable) { // Do appropriate things here } else if (tableView == secondTable) { // do things for table #2 here } else { assert(no); // error checking } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7556788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Double "Pipes" in title At my job today, I was made aware of a little error in our pages' titles. Our site is built using .jsp pages and for the titles of our product pages we use In our admin (where we can set up the titles for each of the products), we would normally add in * anyone ever run into this issue before, and if so, does anyone know of a way to fix the double pipes issue I have encountered? A: Problem is that the method replaceAll has as the first argument regular expression. The "|" is reserved symbol in regular expressions and you must escape it if you want use it as a string literal. You can create workaround, for example this way. String[] words = str.split(" "); for (int i = 0; i < words.length; i++) { if (words[i].length() > 0) { if (!(words[i].substring(0, 1).equals("|"))) { sb.append(words[i].replaceFirst(words[i].substring(0, 1), words[i].substring(0, 1).toUpperCase()) + " "); } else { sb.append(words[i] + " "); } } } A: Try using the html escape code for the pipe character &brvbar;. Your title would be: "Monkey Thank You &brvbar; Monkey Thank You Cards" A: I think the issue is in the fact that replaceFirst() takes a regex as parameter and a replacement string. Because you push in the first character as is for the regex parameter, what happens with the vertical bar is (omitting adding to the StringBuffer) equivalent to: String addedToBuffer = "|".replaceFirst("|", "|".toUpperCase()); What happens then, is that we have a regex which matches the empty string or the empty string. Well, any string matches the empty string regex. So the match gets replaced by "|" (to upper case). So "|".replaceFirst("|", "|".toUpperCase()) expands to "||". So the append() call is given the parameter of "|| ". You can fix your algorithm in two ways: * *Fix the regex automatically, use literal notation in between \Q and \E. So your regex to pass to replaceFirst() becomes something like "\\Q"+ literal + "\\E". *Realise that you do not need regexes in the first place. Instead use two append() operations. One to append() the case converted first character of the item to add, the other to append the rest. This looks like this: for(String s: items) { if(s.equals("")) { sb.append(" "); } else { sb.append(Character.toUpperCase(s.charAt(0))); if(s.length() > 1) { sb.append(s.substring(1)); } sb.append(" "); } } The second approach is probably much easier to follow as well. PS: For some reason the StackOverflow editor is vehemently disagreeing with code blocks in lists. If someone happens to know how to fix the munged formatting... ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7556789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get rid of the decimal digits on the x axis I want to create a simple plot. year=c(2005,2006,2007) dat=c(1,2,3) plot(year,dat) How can I only show the axis as the year without decimal digits? Thanks A: Specify year as a date, using as.Date. Here is one way, using seq.Date: year=seq(as.Date("2005/01/01"), by="1 year", length.out=3) dat=c(1,2,3) plot(year,dat) A: 3 possible ways: * *Control the label resolution with xaxp: plot(year,dat,xaxp=c(range(year),2)) *Use a Date object for the x axis: year2 <- as.Date(paste(year,"-01-01",sep="")) plot(year2,dat) *Construct the axis yourself: plot(year,dat,xaxt="n") axis(1,at=year)
{ "language": "en", "url": "https://stackoverflow.com/questions/7556791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Connecting Redhat to SQL Server 2008 for Ruby on Rails I'm trying to connect Redhat Linux to a Microsoft SQL Server 2008. I already had trouble setting it up on windows (my test machine) but now I need to deploy it on the Linux machine where it will be in production. So I've installed unixODBC and FreeTDS (with a lot of effort, not even sure if it was installed correctly :S), and the outcome of that is that I have 3 files in /usr/local/etc: odbc.ini odbcinst.ini freetds.conf I then edited the freetds.conf file and this is what I added: [sqlServer] host = servername port = 4113 instance = sqlServer tds version = 8.0 client charset = UTF-8 I had to find out the port number from my DBA, as it is set to dynamic in SQL Server 2008. My odbcinst.ini file looks like this: [FreeTDS] Description = TDS driver (Sybase/MS SQL) Driver = /usr/local/lib/libtdsodbc.so Setup = /usr/local/lib/libtdsS.so CPTimeout = CPReuse = FileUsage = 1 and my odbc.ini files looks like this: [sqlServer] Driver = FreeTDS Description = ODBC connection via FreeTDS Trace = 1 Servername = sqlServer Database = RubyApp So now I tried connecting to see if there is any connection by using tsql -S sqlServer -U test -P test, however that only gives me the following error: locale is "en_US.UTF-8" locale charset is "UTF-8" using default charset "UTF-8" Error 20013 (severity 2): Unknown host machine name. There was a problem connecting to the server When I tried using isql, doing isql -v sqlServer test test, that spat out the following error: [S1000][unixODBC][FreeTDS][SQL Server]Unable to connect to data source [01000][unixODBC][FreeTDS][SQL Server]Unknown host machine name. [ISQL]ERROR: Could not SQLConnect Any ideas what I could be doing wrong? A: If you cannot connect with tsql, then there is a connection issue with your SQL server or in freetds.conf. First verify the port and named instance using tsql -LH [SQL server IP] # tsql -LH 127.0.0.1 ServerName HOME InstanceName INSTANCE1 IsClustered No Version 10.50.2500.0 tcp 1434 If this doesn't work, there is a connection issue between your server and the SQL server. If it does work, then set your port to match tcp above in freetds.conf. [TDS] host = 127.0.0.1 port = 1434 tds version = 7.0 Instance is set in your odbc.ini [MSSQLExample] Description = Example server Driver = FreeTDS Trace = No Server = 127.0.0.1\INSTANCE1 Database = MyDatabase port = 1434 And if all else fails, try using osql to get some feedback on which part is not working. # osql -S MSSQLExample -U USERNAME -P PASSWORD And for some good info on tsql error messages: http://freetds.schemamania.org/userguide/confirminstall.htm A: Won't you need the SQL Server hostname or IP address in the freetds.conf file -- [sqlServer] host = 192.168.0.99 :
{ "language": "en", "url": "https://stackoverflow.com/questions/7556794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Extended Selection in WPF Listbox we need to customise the Extended Selection in WPF ListBox. What I need to do is be able to Drag and Select Multiple items(Similar to selecting in excel) Extended selection in Listbox works fine but for that I have to hold the Shiftkey and drag. Is there a way I can do the multiple selection just by dragging and not holding the shift key down? Thanks for looking. Regards Saurabh Dighade A: This looked promising. I haven't tested it though. http://www.codeproject.com/KB/WPF/MultiSelectListView2.aspx Also, a similar SO post: Drag-select with ListBox
{ "language": "en", "url": "https://stackoverflow.com/questions/7556796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Group javascript xml output by letters or other attributes I have an xml document that looks something like this <?xml version="1.0" encoding="UTF-8"?> <mapPoints> <annotation cat="A" title="123" type="pointer"/> <annotation cat="A" title="333" type="pointer"/> <annotation cat="B" title="555" type="pointer"/> </mapPoints> I am parsing the XML into my javascript document. Now, I want to group the output of my xml file in different divs base on the cat in the xml so that the markup would look something like this <div class="A"> <ul> <li>123 cat A</li> <li>333 cat A</li> </ul> </div> <div class="B"> <ul> <li>555 cat B</li> </ul> </div> My parsing is working properly but I don't know how I would group the entries and then output them into different divs. The solution needs to be dynamic since it could be a lot of categories. A: Using jQuery and assuming you have your xml in a variable xml, try this: $(xml).find('mapPoints annotation').each(function() { var class = $(this).attr('cat'); if ($('div.' + class).length == 0) { $('#annotations').append('<div class="' + class + '"><ul></ul></div>'); } $('div.' + class + ' ul').append(getLiFromXml(this)); }); getLiFromXml is a function that returns <li>123 cat A</li> for <annotation cat="A" title="123" type="pointer"/> - hopefully, you can easily write it. UPDATE Updated the code to add a div first. I assumed that you store all your divs in a container (div, td, whatever...) with id="annotations"
{ "language": "en", "url": "https://stackoverflow.com/questions/7556800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why bind a socket to an address? Before 'listen'ing on a socket I must first bind it to an address. Why? It seems to me that I shouldn't have to pick and should just listen to that port on all addresses. Even if I bind to 127.0.0.1 though, it seems I can still connect to that socket from a remote machine. What does binding to an address really do? A: Binding to an address defines exactly which interface should have that server port open. binding to 0.0.0.0 is a special case when you want to listen to all IP addresses know to the interface. Binding specifically to 127.0.0.1 should make the server port visible only to code that can connect to the localhost (e.g. local processes).
{ "language": "en", "url": "https://stackoverflow.com/questions/7556811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: A confusion in APUE2(about symbolic link in UNIX) The original text is below.It is in Section 4.22 The program in Figure 4.24 changes to a specific directory and then calls getcwd to print the working directory. If we run the program, we get $ ./a.out cwd = /var/spool/uucppublic $ ls -l /usr/spool lrwxrwxrwx 1 root 12 Jan 31 07:57 /usr/spool -> ../var/spool Note that chdir follows the symbolic link as we expect it to, from Figure 4.17 .but when it goes up the directory tree, getcwd has no idea when it hits the /var/spool directory that it is pointed to by the symbolic link /usr/spool. This is a characteristic of symbolic links. What does the author really mean by saying that the program hits the /var/spool? What is the characteristic of symbolic links pointed out by the author? I did not really understand. A: Assume you have a symlink /usr/spool pointing to /var/spool. It says if you follow that symlink (e.g. cd /usr/spool), you end up in the pointed-to directory (/var/spool). Then, the information that you followed a symlink is lost. You are in /var/spool as if you had done cd /var/spool directly. A further cd .. brings you to /var (as opposed to /usr). UPDATE: As pointed out by Keith Thompson and Jonathan Leffler, there are some shells that do remember the path you followed (i.e. /usr/spool). In such shells, cd .. would go to /usr/. However, programs started from such a shell would still see /var/spool as the working directory. This is probably the reason the author let you write a program for displaying cwd (to work-around such shells' internals). A: Expanding on what @undor_gongor wrote: Each process has a current working directory. It's not stored as the path name of the directory; it's a reference to the directory itself. If it were stored as a path name, then the getcwd() function's job would be trivial: just print the path name. Instead, it has to readi the current directory, open its .. entry, then open that directory's .. entry, and so forth until it reaches the root (i.e., a directory whose .. entry points to the directory itself). It builds up the full path of the current directory in reverse order as it does this. Since .. can't be a symlink, this process is not affected by symbolic links. (Shells might have a $PWD or $CWD variable, or a pwd built-in, that is affected by symlinks; these typically work by remembering the string that was passed to cd or pushd.) A: Note that some shells, notably bash, keep track of whether you arrived at a given directory by chasing a symbolic link, and print the current directory accordingly. At least bash has options to cd to do a physical or logical change directory: cd [-L|-P] [dir] Change the current directory to dir. The variable HOME is the default dir. [...] The -P option says to use the physical directory structure instead of following symbolic links (see also the -P option to the set builtin command); the -L option forces symbolic links to be followed. An argument of - is equivalent to $OLDPWD. If a non-empty directory name from CDPATH is used, or if - is the first argument, and the directory change is successful, the absolute pathname of the new working directory is written to the standard output. The return value is true if the directory was successfully changed; false otherwise. In the scenario shown, where /usr/spool is a symbolic link to /var/spool, then: $ pwd / $ cd /usr/spool/uucppublic /usr/spool/uucppublic $ cd -L .. /usr/spool $ cd /usr/spool/uucppublic /usr/spool/uucppublic $ cd -P .. /var/spool $ For most people, a plain cd .. would do the same as cd -L ... You can choose to have bash do the same as cd -P .. instead if you prefer (using set -P or set -L). The process of finding the pathname of the current directory should be understood too. Logically, the process (kernel) opens the current directory (.) and reads the inode number (and device number). It then opens the parent directory (..), and reads entries from that until it finds one with the matching inode number (and device number). This then gives it the last component of the pathname. It can now repeat the process, finding the the inode number of the next directory up, and opening its parent directory (../..), etc, until it reaches the root directory (where the inode number for both . and .. is the same, and the value is conventionally 2). Note that this even works across mount points. Beware of auto-mounted remote (NFS) file systems, though; it can be really slow if you scan through a directory containing several hundred automounted machines - as the naïve search outline above mounts all the machines until it finds the correct one. So, actual getcwd() functions are cleverer than this, but it explains how the path of the current directory is found. And it also shows why the process will not encounter /usr/spool when evaluating the directory under /var/spool/uucppublic - it simply never opens the /usr directory. Note that the realpath() function (system call) takes a name possibly referencing symlinks and resolves it to a name that contains no symlinks at all. Passed /usr/spool/uucppublic, it would return /var/spool/uucppublic, for example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556816", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Embedding YouTube Playlist using SWFObject.embedSWF() I'm trying to use YouTube's JavaScript API to embed a playlist to my Facebook app. I tried using the standard code as shown by Google here to embed a simple video and it worked. The code is: function loadPlayer() { // The video to load var videoID = "[My Video ID]"; // Lets Flash from another domain call JavaScript var params = { allowScriptAccess: "always" }; // The element id of the Flash embed var atts = { id: "ytPlayer" }; // All of the magic handled by SWFObject (http://code.google.com/p/swfobject/) swfobject.embedSWF("http://www.youtube.com/v/" + videoID + "?fs=1&version=3&enablejsapi=1&playerapiid=player1", "videoDiv", "420", "315", "9", null, null, params, atts); } But how do I use the YouTube API to embed a Playlist? I'm aware of the playlist parameter on the embedSWF URL parameter, but what it does is append videos as to make a playlist on the fly. I already have a playlist on my YouTube account, now I want to embed it using the API. How can this be done? Thanks! A: I'm working on something similar and in looking for the solution to my problem may have found yours... In the place where you have; swfobject.embedSWF("http://www.youtube.com/v/" + videoID + Change that to: swfobject.embedSWF("http://www.youtube.com/p/" + playlistID + I do believe that will work. That's what puts our playlist on the player. And yet, it is not the way we are hoping to display it. We would like a list below the player, so I am still searching for that answer. I hope this helps you! A: You dont need javascript or anything, you just go into your playlist, and next to the play all button it says share, click that then click embed and copy and past the code on your site. A: This may help you to try on your own... http://jsfiddle.net/masiha/tFQEN/1/
{ "language": "en", "url": "https://stackoverflow.com/questions/7556818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adobe AIR history.back() doesnt work when calling from html javascript I'm working on air app (html/ajax/javascript). I need to make a navigation feature, like a browser back and forward button in a page with iframe, all pages are on same domain. I have the following scenario: Adobe AIR (version 2.7.1) app that loads (air.HTMLLoader) index.php from mydomain.com http://mydomain.com/index.php file has following design: <html> <body> <input type="button" value="< BACK" onclick="iframeID.history.back();"> <input type="button" value="FORWARD >" onclick="iframeID.history.forward();"> <ul> <li><a href="http://mydomain.com/page1.php" target="iframeNAME">page 1</a></li> <li><a href="http://mydomain.com/page2.php" target="iframeNAME">page 2</a></li> </ul> <iframe src="page_default.php" id="iframeID" name="iframeNAME"></iframe> </body> </html> So, this code works in FireFox, Chrome, Safari, but not in Adobe AIR app I can't find any documentation about this issue, really cant understand where is the problem, as i know adobe air uses webkit for web pages browsing like chrome and safari but only in air app this code doesnt work. I hope someone can help me. Thanks! A: My app is basically an HTML site in dreamweaver with flash intros, and linked navigation between HTML pages, which is then converted into an air app. All HTML files are in the same directory. So page2.html is in the same root site folder as page3.html. Some of my pages require navigating back to the previous page. However, because you could arrive at that page through various paths, I really needed the back capability. So after struggling through alot of very complex suggestions, I dropped this very basic example from w3schools in: <html> <head> <script type="text/javascript"> function goBack()   {   window.history.back()   } </script> </head> <body> <input type="button" value="Back" onclick="goBack()" /> </body> </html> And it works. For my app, it works in all browsers, and as a desktop AIR app for Mac and windows. I'm just working my way into air, but I thought this might help you fix your problem. A: I feel like you have a few concepts mixed up. So I will try to help. First, is the statement: "all pages are on same domain" There is no domain in an Adobe AIR application. You are not browsing http://localhost/. You are loading a file fromt he file system and it is being rendered as HTML. There are no URLs in AIR (unless you are accessing a remote system) so, as I understand it, history.back() is not going to work. Second, I am concerned about these lines: <li><a href="/page1.php" target="iframeNAME">page 1</a></li> <li><a href="/page2.php" target="iframeNAME">page 2</a></li> Those are not going to render. AIR does not have PHP support built in. And like I said, AIR is browsing http://localhost, so your local PHP install (if you have one) is not going to parse and process those files before they are delivered to AIR. Building desktop applications is very different than building web applications. And relying only on HTML and JS presents some challenges. You lose a lot of the benefits of a server-side solution like PHP or ColdFusion. There's no session store, there are no cookies (except for when accessing remote services), there are no URL parameters, etc. You do pick up a lot of additional benefits with AIR though. You have access to the local file system, you get an encrypted local store, you are not restricted by the same-origin policy of the browser, you can use a local database (even an encrypted one), and much more. If you really need to browse and render PHP files from within an iframe in AIR and you need to have a back and forward button, then you'll need to host the PHP somewhere remotely (or have all of your users install it locally) and you'll need to have that iframe call the page remotely. Then I suspect that history.back() would work. You could create your own back/forward functionality simply by storing the history of the pages being viewed using one of AIRs many local storage options (ELS, StorageObject, SQLite, File System) and then implement back and forward buttons that use those stores to reload content. But I think the better option is to simply have quality navigation in your application. Good luck. A: In AIR applications are "sandboxes" based on where content is loaded from. Your main application is in the "application sandbox" and remotely loaded content is in the "non-application sandbox". Each sandbox is restricted as to what it can do. Content in each sandbox cannot talk to content in another sandbox without a bridge. Since you are loading your iframe with remote content your application-sandboxes HTML file that is trying to access it is likely being restricted. I think you need to look into what is called a sandbox bridge. Specifically a parent-to-child sandbox bridge. I did a presentation on that once. The slides are available on my blog. . I would give you a direct link, but I am on my phone. Just search for AIR Security or CFUnited 2010.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556819", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is the best way to connect an iphone app to a mysql database? I want the way with the fastest execution time. I'm not feeling comfortable of using web service because i need to create separate php pages and retrieve data as xml. If you think its good to use web service please tell me why. I want to code my database queries right on my c/objective c pages. I've been searching for libraries. I saw this sequel pro - won't i have any problems on using this - like licensing issues? I also saw this libmysqlclient of cocoa but some say its not working well. I've also read about a library developed by Karl Kraft found here http://www.karlkraft.com/index.php/2010/06/02/mysql-and-objective-c/ but don't know if i could trust this. I would really appreciate you help. A: Definitely build a web service to act as an abstraction layer to your database. Here are some significant reasons in my opinion: Since you want speed, you will be able to add caching when using the webservice, so you will essentially eliminate the need for identical queries to run (sometimes). If you need to change your data model later, you just have to modify the webservice backend and don't have to update your app. You can better control security by not exposing the database to the world, and keep it safe behind the web service. Your database credentials should not be stored in an app. What if you needed to change those? I strongly suggest a web service. Hope this helps. A: Connect to your DB by PHP and output the result as JSON is much better and faster then xml and less coding if use JSON Framework. and never never try to connect to your DB from your iphone because it easy to sniff out the request from iphone. Being safe then Sorry, keep that in mind
{ "language": "en", "url": "https://stackoverflow.com/questions/7556822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: how to manage the ajax response in Dojo Ok, this may be a dumb question, but I can't find a way to solve my problem. I have this function: function getActivityObj(sysId, date) { var activityObj = dojo.xhrGet({ url: 'calendar/display-subactivities', content: {'sysId': sysId, 'date': date}, handleAs: 'json', load: function(result) { console.log(result); }, error: function(){ alert("error"); } }); var ajaxResponse = activityObj.ioArgs.xhr.response; return ajaxResponse; } The problem is that my ajaxResponse variable is always empty, but if in firebug, the xhr object the response property is not empty. I will use the ajax response in several places in my code so what am I doing wrong or what would be a better way to call the ajax response? Thank you. (Sorry for my bad english) A: I suspect the ajaxResponse variable is empty when you call it because the xhrGet() call is made asynchronously, and the result is not actually available yet when you set ajaxResponse and return it from your function. By the time you view it in firebug, the XHR response has completed but it just isn't there when your code executes. xhrGet() returns a dojo.Deferred object. You can use that to add a callback function for when it actually completes: function getActivityObj(sysId, date) { var activityObj = dojo.xhrGet({ url: 'calendar/display-subactivities', content: {'sysId': sysId, 'date': date}, handleAs: 'json', load: function(result) { console.log(result); }, error: function(){ alert("error"); } }); var ajaxResponse; // activityObj is a Deferred activityObj.addCallback(function() { // Use your deferred response ajaxResponse = activityObj.ioArgs.xrh.response; // Now inside this function, do whatever you were going to do // with the xhr return data that you intended to return from // the wrapping function. }); } I am not certain if there's a good way to wrap the xhrGet() call in a function and attempt to return the response though, since it will always be deferred if called asynchronously. If it is safe to block further execution until the xhrGet() call has actually returned data, you can call it synchronously. Then your code as you have it will work without a deferred callback. Instead you would typically do whatever work the returned data was intended for in the xhrGet()'s load() function. var activityObj = dojo.xhrGet({ // Call synchronously sync: true, url: 'calendar/display- subactivities', content: {'sysId': sysId, 'date': date}, // etc...
{ "language": "en", "url": "https://stackoverflow.com/questions/7556826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Round to sensible location in rails I'd like to round my floats to get rid of all trailing zeros after the decimal place in rails, inside a model method. So, 30.0 becomes 30 but 10.5 stays 10.5. I know about number_with_precision and it works if I do include ActionView::Helpers::NumberHelper in my model. Is this poor design? Is there a better alternative that doesn't involve moving the rounding into a helper? A: This is the source code of the number_with_precision method. # File actionpack/lib/action_view/helpers/number_helper.rb, line 199 def number_with_delimiter(number, options = {}) options.symbolize_keys! begin Float(number) rescue ArgumentError, TypeError if options[:raise] raise InvalidNumberError, number else return number end end defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {}) options = options.reverse_merge(defaults) parts = number.to_s.to_str.split('.') parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{options[:delimiter]}") parts.join(options[:separator]).html_safe end Nothing prevents you to clone this method into your model. You might want to remove the unnecessary parts.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I hide the row separators in a UITableView without hiding the group borders? I have a grouped UITableView, and I want to hide the lines between the rows. When I set the separatorColor to clearColor, the lines disappear; but so does the border around the groups. Is there a way for me to hide the lines between the rows, but keep the border around the groups? A: Writing this out of my head, and not sure if it would work. Give it a try self.tableView.layer.borderColor = [UIColor grayColor].CGColor; self.tableView.layer.borderWidth = 1.0f; You need to import and add the necessary framework to the Build Phases section of your target. A: Maybe is a bit later but I have a little "fix". In your cell view you have to add a UIView with the same color than your cell background and put it at the botton of your cell. This new view will put over the separator line. So you have to show it in every cell less the last one, using setHidden method. And here you have, no separator!
{ "language": "en", "url": "https://stackoverflow.com/questions/7556832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: java draw polyline from an arraylist of points Is it possible to draw a polyline by passing the method an array list of Point values? something like this: ArrayList<Point> projectilePoints=new ArrayList<Point>(); Projectile p = new Projectile(11, 17, 73, 37); for (int i = 0; i < 11; i++) { Point point = p.getPositionAt(i); projectilePoints.add(point); } g.drawPolyline(projectilePoints, projectilePoints, 11); What is the correct way to pass in the parameters of x and y points for the polyline? A: No, there is no such method takes Arraylist of Point reference parameter. The Syntax is, Graphics.drawPolyline(int[] xPoints, int[] yPoints, int nPoints) A: The JavaDpc on Graphics#drawPolyLine states that you need to pass 2 int arrays that represent the x and y coordinates. Alternatively, you might use Graphics2d#draw(Shape) and pass a Path2D shape, that can be prefilled using your points (e.g. by calling lineTo(x,y) for all points but the first - for which you might call moveTo(x,y)). A: Call method Graphics2D.drawPolyline. This method takes an int array of X coordinate values, an int array of Y coordinate values and the number of points. There is no line drawing method that takes Point objects, you have to create int arrays of coordinates. See http://download.oracle.com/javase/1,5.0/docs/api/java/awt/Graphics2D.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7556837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: upgrade blackberry database In my application, I have a database that gets written out to the sdcard. We have had to make a lot of big changes to the database, so when the user upgrades the application, is there a way to delete and reinstall the database, but only on upgrade? A: The best way to do this is to have a chunk of code in the upgrade that checks for the old database and if it finds an old database, do the upgrade. This lets you control what happens, and also how it happens.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556838", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I serialize an javascript array into html attribute and fetch it back with jquery? var arr=[...]; var html = '<input attr="' + serialize(arr) + '">'; I can't simply join(' ') the arr as there may be white space or other special characters. How do I do it properly? A: You probably want .data, using which you can store any data on a DOM element. var html = $("<input>"); html.data("something", arr); Then you can append it somewhere using the insertion methods like .append. Fetch the data again with: var arr = html.data("something"); http://jsfiddle.net/UKRcs/ An alternative would be using JSON to convert things into a string and setting that as an attribute: var html = $("<input>").attr("data-something", JSON.stringify(arr)); And the other way round: var arr = JSON.parse(html.attr("data-something")); http://jsfiddle.net/UKRcs/1/ A: You may want to look at the .data() method. This allows you to attach arbitrary objects to DOM elements. http://api.jquery.com/data/
{ "language": "en", "url": "https://stackoverflow.com/questions/7556840", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Unpivoting Data in SSIS I am attempting to normalize data using SSIS in the following format: SerialNumber Date R01 R02 R03 R04 ------------------------------------------- 1 9/25/2011 9 6 1 2 1 9/26/2011 4 1 3 5 2 9/25/2011 7 3 2 1 2 9/26/2011 2 4 10 6 Each "R" column represents a reading for an hour. R01 is 12:00 AM, R02 is 1:00 AM, R03 is 2:00 AM and R04 is 3:00 AM. I would like to transform the data and store it in another table in this format (line breaks for readability): SerialNumber Date Reading ----------------------------------------- 1 9/25/2011 12:00 AM 9 1 9/25/2011 1:00 AM 6 1 9/25/2011 2:00 AM 1 1 9/25/2011 3:00 AM 2 1 9/26/2011 12:00 AM 4 1 9/26/2011 1:00 AM 1 1 9/26/2011 2:00 AM 3 1 9/26/2011 3:00 AM 5 2 9/25/2011 12:00 AM 7 2 9/25/2011 1:00 AM 3 2 9/25/2011 2:00 AM 2 2 9/25/2011 3:00 AM 1 2 9/26/2011 12:00 AM 2 2 9/26/2011 1:00 AM 4 2 9/26/2011 2:00 AM 10 2 9/26/2011 3:00 AM 6 I am using the unpivot transformation in an SSIS 2008 package to accomplish most of this but the issue I am having is adding the hour to the date based on the column of the value I am working with. Is there a way to accomplish this in SSIS? Keep in mind that this is a small subset of data of around 30 million records so performance is an issue. Thanks for the help. A: * *Create a SSIS package and add a new Data Flow Task and configure this DFT (Edit...) *Add a new data source *Add UNPIVOT component and configure it thus: *Add DATA CONVERSION component: Temporary results: *Add DERIVED COLUMN component: For NewData derived column you can use this expression: DATEADD("HOUR",(Type == "R01" ? 0 : (Type == "R02" ? 1 : (Type == "R03" ? 2 : 3))),Date). «boolean_expression» ? «when_true» : «when_false» operator is like IIF() function (from VBA/VB) and is used to calculate number of hours to add: for "R01" -> 0 hours, for "R02" -> 1 hour, for "R03" -> 2 hours or else 3 hours (for "R04"). Results:
{ "language": "en", "url": "https://stackoverflow.com/questions/7556842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to use StrongNameKeyPair with a password protected keyfile (pfx)? I am trying to programatically sign an assembly using a password protected keyfile (pfx). However when I try to use the StrongNameKeyPair I get the following exception. Unable to obtain public key for StrongNameKeyPair. at System.Reflection.StrongNameKeyPair.ComputePublicKey() at System.Reflection.StrongNameKeyPair.get_PublicKey() A: Here is a piece of C# code that creates a StrongNameKeyPair object from a password-protected .PFX file: public static StrongNameKeyPair GetStrongNameKeyPairFromPfx(string pfxFile, string password) { X509Certificate2Collection certs = new X509Certificate2Collection(); certs.Import(pfxFile, password, X509KeyStorageFlags.Exportable); if (certs.Count == 0) throw new ArgumentException(null, "pfxFile"); RSACryptoServiceProvider provider = certs[0].PrivateKey as RSACryptoServiceProvider; if (provider == null) // not a good pfx file throw new ArgumentException(null, "pfxFile"); return new StrongNameKeyPair(provider.ExportCspBlob(false)); } NOTE: I assume the PFX here has been created by the .NET Framework tools (for example the Visual Studio Strong Name UI form) to support an assembly strong name creation. It may not be ok with any PFX. A: It does not look like Microsoft updated StrongNameKeyPair to support anything other than the snk file format - as there's, sadly, no constructor accepting an RSA instance. In fact my understanding is that the PKCS#12 support for strongnaming assemblies is an indirect one, i.e. provided by the tools (msbuild or VS.NET) and not directly by the framework. However you can still programatically sign an assembly using any RSA instance by re-using the (MIT.X11 licensed) code from Mono.Security StrongName class, available in github. It's a bit more work - but it will work on any framework version and any (future) format that gets promoted :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7556846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: No module named resource (installing Flask-Mail) A little new to python and the wonderful world of Flask. I'm trying to install Flask-Mail (http://packages.python.org/flask-mail/) and coming up against a bit of a wall. Using a virutalenv (on WINDOWS7) I can't get the flask-mail to install, each time I recieve 'No module named resource'. I'm using pip to install... any ideas? A: as Flask-Mail documentation says: Flask-Mail requires the use of the Lamson library, which unfortunately has dependencies that do not work on Windows. You can install Flask-Mail, Lamson and other libraries with the no dependencies option: easy_install -N lamson chardet Flask-Mail Source: http://packages.python.org/Flask-Mail/#windows-issues A: I encountered this error, too. And I searched Python index found this: http://docs.python.org/2/library/resource.html , It seems that resource is platform-dependent module, and to be specific, on Unix. And also this: http://code.activestate.com/pypm/lamson/ (can not insert image here? suck!) lamson is not built on any version(32 or 64-bit) of Windows(suck, too).
{ "language": "en", "url": "https://stackoverflow.com/questions/7556850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Set Jackson Timezone for Date deserialization I'm using Jackson (via Spring MVC Annotations) to deserialize a field into a java.util.Date from JSON. The POST looks like - {"enrollDate":"2011-09-28T00:00:00.000Z"}, but when the Object is created by Spring & Jackson it sets the date as "2011-09-27 20:00:00". How can I set the proper timezone in Jackson? Or if that is not the problem, how do I send EST from the JSON message? Javascript/jQuery: var personDataView = { enrollDate : new Date($("#enrollDate").val()), //...other members }; $.postJSON('/some/path/', personDataView, function(data){ //... handle the response here }); JSON Message: {"enrollDate":"2011-09-28T00:00:00.000Z"} Spring Controller: @RequestMapping(value="/", method=RequestMethod.POST) public @ResponseBody String saveProfile(@RequestBody personDataView persondataView, HttpServletRequest request) { //...dataView has a java.util.Date enrollDate field //...other code } A: In Jackson 2+, you can also use the @JsonFormat annotation: @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone="America/Phoenix") private Date date; If it doesn't work this way then try wrapping Z with single quotes, i.e. pattern="yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" A: I am using Jackson 1.9.7 and I found that doing the following does not solve my serialization/deserialization timezone issue: DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ"); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); objectMapper.setDateFormat(dateFormat); Instead of "2014-02-13T20:09:09.859Z" I get "2014-02-13T08:09:09.859+0000" in the JSON message which is obviously incorrect. I don't have time to step through the Jackson library source code to figure out why this occurs, however I found that if I just specify the Jackson provided ISO8601DateFormat class to the ObjectMapper.setDateFormat method the date is correct. Except this doesn't put the milliseconds in the format which is what I want so I sub-classed the ISO8601DateFormat class and overrode the format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) method. /** * Provides a ISO8601 date format implementation that includes milliseconds * */ public class ISO8601DateFormatWithMillis extends ISO8601DateFormat { /** * For serialization */ private static final long serialVersionUID = 2672976499021731672L; @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { String value = ISO8601Utils.format(date, true); toAppendTo.append(value); return toAppendTo; } } A: Looks like older answers were fine for older Jackson versions, but since objectMapper has method setTimeZone(tz), setting time zone on a dateFormat is totally ignored. How to properly setup timeZone to the ObjectMapper in Jackson version 2.11.0: ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setTimeZone(TimeZone.getTimeZone("Europe/Warsaw")); Full example @Test void test() throws Exception { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); JavaTimeModule module = new JavaTimeModule(); objectMapper.registerModule(module); objectMapper.setTimeZone(TimeZone.getTimeZone("Europe/Warsaw")); ZonedDateTime now = ZonedDateTime.now(); String converted = objectMapper.writeValueAsString(now); ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class); System.out.println("serialized: " + now); System.out.println("converted: " + converted); System.out.println("restored: " + restored); Assertions.assertThat(now).isEqualTo(restored); } ` A: Have you tried this in your application.properties? spring.jackson.time-zone= # Time zone used when formatting dates. For instance `America/Los_Angeles` A: If you really want Jackson to return a date with another time zone than UTC (and I myself have several good arguments for that, especially when some clients just don't get the timezone part) then I usually do: ObjectMapper mapper = new ObjectMapper(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); dateFormat.setTimeZone(TimeZone.getTimeZone("CET")); mapper.getSerializationConfig().setDateFormat(dateFormat); // ... etc It has no adverse effects on those that understand the timezone-p A: Just came into this issue and finally realised that LocalDateTime doesn't have any timezone information. If you received a date string with timezone information, you need to use this as the type: ZonedDateTime Check this link A: Your date object is probably ok, since you sent your date encoded in ISO format with GMT timezone and you are in EST when you print your date. Note that Date objects perform timezone translation at the moment they are printed. You can check if your date object is correct with: Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); cal.setTime(date); System.out.println (cal); A: I had same problem with Calendar deserialization, solved extending CalendarDeserializer. It forces UTC Timezone I paste the code if someone need it: @JacksonStdImpl public class UtcCalendarDeserializer extends CalendarDeserializer { TimeZone TZ_UTC = TimeZone.getTimeZone("UTC"); @Override public Calendar deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonToken t = jp.getCurrentToken(); if (t == JsonToken.VALUE_NUMBER_INT) { Calendar cal = Calendar.getInstance(TZ_UTC); cal.clear(); cal.setTimeInMillis(jp.getLongValue()); return cal; } return super.deserialize(jp, ctxt); } } in JSON model class just annotate the field with: @JsonDeserialize(using = UtcCalendarDeserializer.class) private Calendar myCalendar; A: For anyone struggling with this problem in the now (Feb 2020), the following Medium post was crucial to overcoming it for us. https://medium.com/@ttulka/spring-http-message-converters-customizing-770814eb2b55 In our case, the app uses @EnableWebMvc and would break if removed so, the section on 'The Life without Spring Boot' was critical. Here's what ended up solving this for us. It allows us to still consume and produce JSON and XML as well as format our datetime during serialization to suit the app's needs. @Configuration @ComponentScan("com.company.branch") @EnableWebMvc public class WebMvcConfig implements WebMvcConfigurer { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(0, new MappingJackson2XmlHttpMessageConverter( new Jackson2ObjectMapperBuilder() .defaultUseWrapper(false) .createXmlMapper(true) .simpleDateFormat("yyyy-mm-dd'T'HH:mm:ss'Z'") .build() )); converters.add(1, new MappingJackson2HttpMessageConverter( new Jackson2ObjectMapperBuilder() .build() )); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7556851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "58" }
Q: MSPaint-like app writing. How to do BitBlt right? I'm writing now simple mspaint-like program in C++ using windows.h (GDI). For my program I need only pen tool. So, I need to store somewhere main window's picture (for ex. in memory HDC and HBITMAP) to draw it after in WM_PAINT message. * *When I first have to store window's HDC to my memory HDC and HBITMAP? In what message I should store window? For example, I think we can't do it in WM_CREATE because we have no window yet. *What is the difference between PatBlt and BitBlt? What should I use for my app? *How to copy window's HDC content to my memory HDC and Bitmap? I'm trying to do something like this: LPRECT lpRect; GetClientRect(hwnd, lpRect); width = lpRect->right - lpRect->left; height = lpRect->bottom - lpRect->top; HDC hDC = GetDC(hwnd); memoryDC = CreateCompatibleDC(hDC); memoryBitmap = CreateCompatibleBitmap(hDC, width, height); SelectObject(memoryDC, memoryBitmap); PatBlt(memoryDC, 0, 0, width, height, PATCOPY); ReleaseDC(hwnd, hDC); But this don't work: program crashes. * *How to restore window in WM_PAINT after that? *How to clear my window with white color? A: 1: I would recommend you lazy load your off-screen canvas as late as possible. If you need it in WM_PAINT and you haven't created it yet, create it then. If you need it at the point someone begins drawing, create it then. If it exists when you need it, then use it. 2: PatBlt fills a region of a bitmap using the device context's current brush. Brushes define patterns, which is why it's called PatBlt. BitBlt copies data from a source bitmap to a destination bitmap. You would use a BitBlt when you wanted to move the image from the off-screen bitmap to the frame buffer. 3: The lpRect parameter of GetClientRect is an output parameter. That means you have to supply the memory. In this case, GetClientRect is trying to write the rectangle to a null pointer and causing the crash. RECT clientRect; GetClientRect(hwnd, &clientRect); width = clientRect.right - clientRect.left; height = clientRect.bottom - clientRect.top; A: WM_PAINT: seems to be the best place to create the memory hdc. You can do something like this WM_PAINT: if (!first_paint) { ...code first_paint = true; } ...more code break;
{ "language": "en", "url": "https://stackoverflow.com/questions/7556852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: change width of image on toggle I need to change the width of an image with in a toggled div. The problem is that I have multiple toggles on the page and that all the image width's change when I click on the toggle link and not just the on one within the div that I want $('.toggle').click(function() { $(this).prev('.guidebox').slideToggle(400); $('.toggle').toggleClass("active") if ($(this).html() === 'less') { $(this).html('more'); $('.guideImage img').animate({ width: '187px', height: '124px' }, 50, function() { }); } else { $(this).html('less'); $('.guideImage img').animate({ width: '300px', height: '124px' }, 50, function() { }); } return false; }); }); A: $('.guideImage img', this).animate({ Possibly? A: Hard to tell without all the code, but I think this might work. Change $('.guideImage img').animate( to $(this).prev('.guidebox').find('.guideImage img').animate(
{ "language": "en", "url": "https://stackoverflow.com/questions/7556856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: import a dbf file in oracle I have snapshots of two oracle database tablespaces in amazon ec2. Currently we are able to start a database against one of the tablespaces. Is there any way to import the second tablespace into the oracle with a separate user. We tried creating a new tablespace pointing at the same dbf file and associate it to a new user but the user does not have any access to any objects. The dbf contents are not loaded into the database. Any help ? Thanks. A: You might be able to get there using transportable tablespace. That said, is there a reason you cannot simply create a new tablespace and then copy the data to the new tablespace? You could do that either via data pump or SQL. I am assuming you are more interested in duplicating the data held in that tablespace versus the tablespace itself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Open File in Directory from Webpage I am working on a file management application which parses excel files from the business and uploads the latest data to the database. Is it possible to link back to that file from the webpage so that when they open it to make changes they can save it without having to look up the path to that file? For example, if i upload the file "C:\some\nested\directory\file.xlsx", is there a way to open the file from online so that when I click "Save" in Excel it will pull up that path by default? This is the code I have to open the file, which works, just without the correct path since it is downloading it as a tempororary file. [HttpGet] public FileStreamResult ViewFile(int id) { var report = _reportRepository.GetById(id); var file = System.IO.File.Open(report.FilePath, FileMode.Open); return File(file, "application/vnd-ms-excel", report.FileName); } A: Yes but not the way you are trying to. The server needs WebDAV support to be able to do this. Here is an example of download. http://www.eggheadcafe.com/community/aspnet/2/10241992/downloading-file-from-webdav-with-c.aspx MS talks about it a bit here http://msdn.microsoft.com/en-us/library/bb397370%28v=office.12%29.aspx https://serverfault.com/questions/52626/excel-file-always-opens-in-read-only-mode-over-webdav
{ "language": "en", "url": "https://stackoverflow.com/questions/7556861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQLite: Optimize Count In my app I need to display search results. It fetches the first 250 results, but also needs to display the total number of results. This slows everything down, because I can't just stop fetching results after the first 250 rows, I need to loop through them all (millions) just to count them. Another approach is to exit the loop after the first 250 rows, and do a second COUNT() query after that. But some quick benchmarking showed that the COUNT() query doesn't take advantage of the fact that it has executed the same query before. Is there any way to optimize a scenario like this? Would it help if I combined the counting and the fetching in one query instead of two seperate ones? And if so, how would I do that? Edit: Sorry, duplicate of How do I count the number of rows returned in my SQLite reader in C#? A: If this is within a single table, you can use a trigger to keep the count updated. Each insert trigger increments the count; each delete trigger decrements it. See this similar SO question & answer
{ "language": "en", "url": "https://stackoverflow.com/questions/7556868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Spring MVC 3 SimpleFormController In Spring 2.5; there is SimpleFormController having method @Override protected Object formBackingObject(HttpServletRequest request) throws Exception { //logic for command object } What is its alternative in Spring mvc 3. I want to load command object in a jsp page form. A: Use @ModelAttribute @ModelAttribute public MyFormObject createForm(HttpServletRequest request){ } Would work without the request also @ModelAttribute public MyFormObject createForm(){ }
{ "language": "en", "url": "https://stackoverflow.com/questions/7556872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Excel Interop Control Panel UI Elements Don't appear I created a document level addin to programatically create excel charts. I would like the user to be able to save the file as a different name , reopen the excel file at a later time and be able to manipulate the data using the UI controls I created in the control panel that I added to the document. Everything great when the user loads from the published source (UI controls appear as expected.... but when I load the excel file the second time, The "Document Actions" pane appears but none of my UI controls are present. What am I missing or forgetting to do ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7556876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Own function (round for NSString) in NSPredicate I got problem with NSPredicate. I got predicate: NSPredicate* pr = [NSPredicate predicateWithFormat:@"FUNCTION('12.12345','round',3) = 12.123"]; and defined extension for NSString: -(double) round:(NSNumber*) precision; When I call manually: NSLog(@"%f",[s round:3]) where s is NSString, it's working prefectly, but used in NSPredicate rise: NSInvalidArgumentException: rease -[NSCFString round]: unrecognized selector sent to instance. I use solution used on page: http://funwithobjc.tumblr.com/post/2922267976/using-custom-functions-with-nsexpression The main question is to make round function in NSPredicate, so any other solutions are welcome A: The colon (:) must be part of the selector in the FUNCTION, so it should be FUNCTION('12.12345', 'round:', 3) Also, I believe the round: method should return an NSNumber *, not a primitive type.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to mix or append mp3 or wave files one after the other and save the resulting file onto the SD card in android? I have some mp3 files in my /res/raw folder. What I am doing is that, whenever a user clicks on a button a respective sound is played and after he is finished with pressing all the buttons, I want to club all those mp3 files together and a make a new audio file out of it and save it to sd card. I googled a lot and found AudioTrack and SoundPoolclasses useful but they couldn't resolve the issue. Please Help. A: If that are plain mp3 streams in these files (no id3 tags), and their bitrate and other mp3 characteristics match, you can do as simple thing as to append all files into one resulting mp3 file. This means opening InputStream of source files one after another, and write them to one FileOutputStream. I tested this with 2 mp3 files and this works just fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Play Framework - Pagination using JPA It seems to be the following syntax didn't work. Do we have any alternate query for this? JPA.em().createQuery(queryStr).getResultList().from(startAt).fetch(offset); As we know, from() and fetch() will work only on JPAQueryobject and the above code will produce List instead of JPAQueryobject. Please note that queryStr combines 2 different models. Is there anyway to get JPAQueryobject from the above query? So that I can use from and fetch. A: Could you be a little more precise about the "didn't work" part? Do you have any error, or something like that? On my application, I implemented some pagination features, and an example of the JPA query is this one (News is one model of my application): public static void news(int size, int page) { // 'size' is the number of elements displayed per page // 'page' is the current page index, starting from 1. int start = page * size; List<News> allNews = News.find("order by date desc").from(start).fetch(size); // Once the list of news is found, we return them in Json format... renderJSON(allNews, new NewsJsonSerializer()); } Regarding your edit: The method createQuery returns a Query object. Thus, you can use setFirstResult() method and setMaxResults() instead of from() and fetch(). Applied on your code, your query now looks like: JPA.em().createQuery(queryStr).setFirstResult(startAt).setMaxResults(offset).getResultList();
{ "language": "en", "url": "https://stackoverflow.com/questions/7556889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problem about double dispatch with fixed class I have 3 classes: **Parent**, **Child1**, and **Child2**. Both Child1 & Child 2 extend Parent and they **cannot** be modified. There is a class Action defined as follows: public class Action { public static void perform(Parent p) { if (p instanceof Child1) { action((Child1)p); } else if (p instanceof Child2) { action((Child2)p); } else { action(p); } } private static void action(Parent p) { ... } private static void action(Child1 c1) { ... } private static void action(Child2 c2) { ... } } Parent p = new Child1(); Action.perform(p); Without instanceof operator, is there any way to get the same behavior as above ? ====== (modified) PS: the given argument type of Action.perform is Parent, but its value is Child1, so I think method overloading doesn't work .... A: Unfortunately, I think you would have to resort to reflection to solve this. A: Here are two C# solutions, one basically is the same but more neat and is good when you have small number of child classes. public class Parent { } public class Child1 : Parent { } public class Child2 : Parent { } public class Action { private static Dictionary<Type, Action<Parent>> _d = new Dictionary<Type, Action<Parent>>() { {typeof(Child1), p=>action((Child1)p)}, {typeof(Child2), p=>action((Child2)p)}, {typeof(Parent), p=>action(p)} }; public static void perform(Parent p) { _d[p.GetType()](p); } private static void action(Parent p) { } private static void action(Child1 c1) { } private static void action(Child2 c2) { } } class Program { static void Main(string[] args) { Parent p = new Child1(); Action.perform(p); } }`enter code here` Anyhow it breaks OCP but is faster than using reflection. This one does not break OCP but uses reflection to fill the dictionary: public class Action { private static Dictionary<Type, Action<Parent>> _d; static Action() { Initialize(); } private static void Initialize() { var methods = typeof(Action) .GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) .Where(IsActionMethod) .ToList(); _d = methods.ToDictionary(m => m.GetParameters().First().ParameterType, m => (Action<Parent>) (x => m.Invoke(null, new[] {x}))); } private static bool IsActionMethod(MethodInfo methodInfo) { var parameters = methodInfo.GetParameters(); return parameters.Length == 1 && typeof(Parent).IsAssignableFrom(parameters.First().ParameterType) && methodInfo.ReturnType == typeof(void); } public static void perform(Parent p) { _d[p.GetType()](p); } private static void action(Parent p) { } private static void action(Child1 c1) { } private static void action(Child2 c2) { } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7556892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Jquery help adding ajax function to input field I am trying to add the same ajax call that gets triggered when a checkbox is changed to a input field. Here is the function that I also want to add when the value of the input field is changed: $('#left input:checkbox').change(function() { $('#formcontent').empty().html('<p style="margin-top:20px;text-align:center;font-family:verdana;font-size:14px;">Vent venligst, henter webhosts.</p><p style="margin-top:20px;margin-bottom:20px;text-align:center;"><img src="../images/ajax.gif" /></p>'); var form = $(this).closest('form'); $.ajax({ type: form.attr('method'), url: form.attr('action'), data: form.serialize(), success:function(msg){ $('#formcontent').html(msg); } }); Here is my slider code. Which updates the input field: $("#slider").slider({ value:'', min: 0, max: 5000, step: 250, slide: function(event, ui) { if (ui.value == $(this).slider('option', 'max')) { $(ui.handle).html('Ubegrænset'); $('#sliderValueplads').val('99999'); } else { $(ui.handle).html(ui.value + ' MB'); $('#sliderValueplads').val(ui.value); } } }).find('a').html($('#slider').slider('value')); $('#sliderValueplads').val($('#slider').slider('value')); Here is my html: <div class="sliderdiv"> <div id="slider"></div> <input type="text" style="display:none;" size="30" name="search[prisar_greater_than]" id="sliderValueplads"> </div> I have tried to replace this line in the code: $('#left input:checkbox').change(function() { With this (not working): $('#left input:checkbox', '#sliderdiv input').change(function() { Update I have tried clean up the code. The problem is that the callpage does not get triggerhed: function callpage() { $('#formcontent').empty().html('<p style="margin-top:20px;text-align:center;font-family:verdana;font-size:14px;">Vent venligst, henter webhosts.</p><p style="margin-top:20px;margin-bottom:20px;text-align:center;"><img src="../images/ajax.gif" /></p>'); var form = $(this).closest('form'); $.ajax({ type: form.attr('method'), url: form.attr('action'), data: form.serialize(), success:function(msg){ $('#formcontent').html(msg); } $('#left input:checkbox').change(callpage); And I get this error in firebug: missing } after property list [Break ved denne fejl] $('#left input:checkbox').change(callpage) A: The change event won't fire on the text box if you change the value via the jQuery code, you'd need to do something like this in your code - $('#sliderValue').trigger('change') to trigger the change event.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OpenCV - only working with g++. Not gcc or nvcc I have installed OpenCV. I have been able to compile some code but sometimes it does not work. The example below does not work. #include <iostream> #include "opencv2/opencv.hpp" #include "opencv2/gpu/gpu.hpp" int main (int argc, char* argv[]) { try { cv::Mat src_host = cv::imread("building.jpg", CV_LOAD_IMAGE_GRAYSCALE); cv::gpu::GpuMat dst, src; src.upload(src_host); cv::gpu::threshold(src, dst, 128.0, 255.0, CV_THRESH_BINARY); cv::Mat result_host = dst; cv::imshow("Result", result_host); cv::waitKey(); } catch(const cv::Exception& ex) { std::cout << "Error: " << ex.what() << std::endl; } return 0; } I get the following errors when I compile with gcc Test.cpp $(pkg-config --cflags --libs opencv) gcc Test.cpp $(pkg-config --cflags --libs opencv) Undefined symbols for architecture x86_64: "std::allocator<char>::allocator()", referenced from: _main in ccnzUIww.o "std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&)", referenced from: _main in ccnzUIww.o "std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()", referenced from: _main in ccnzUIww.o "std::terminate()", referenced from: _main in ccnzUIww.o "std::allocator<char>::~allocator()", referenced from: _main in ccnzUIww.o "cv::gpu::GpuMat::upload(cv::Mat const&)", referenced from: _main in ccnzUIww.o "cv::gpu::Stream::Null()", referenced from: _main in ccnzUIww.o "cv::gpu::threshold(cv::gpu::GpuMat const&, cv::gpu::GpuMat&, double, double, int, cv::gpu::Stream&)", referenced from: _main in ccnzUIww.o "cv::gpu::GpuMat::operator cv::Mat() const", referenced from: _main in ccnzUIww.o "___cxa_begin_catch", referenced from: _main in ccnzUIww.o "std::cout", referenced from: _main in ccnzUIww.o "std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)", referenced from: _main in ccnzUIww.o "std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)", referenced from: _main in ccnzUIww.o "std::basic_ostream<char, std::char_traits<char> >::operator<<(std::basic_ostream<char, std::char_traits<char> >& (*)(std::basic_ostream<char, std::char_traits<char> >&))", referenced from: _main in ccnzUIww.o "___cxa_end_catch", referenced from: _main in ccnzUIww.o "std::ios_base::Init::Init()", referenced from: __static_initialization_and_destruction_0(int, int)in ccnzUIww.o "std::ios_base::Init::~Init()", referenced from: ___tcf_0 in ccnzUIww.o "cv::gpu::GpuMat::release()", referenced from: cv::gpu::GpuMat::~GpuMat()in ccnzUIww.o "___gxx_personality_v0", referenced from: Dwarf Exception Unwind Info (__eh_frame) in ccnzUIww.o ld: symbol(s) not found for architecture x86_64 collect2: ld returned 1 exit status I have also tried: * *gcc Test.cpp $(pkg-config --cflags --libs opencv) -m32 *gcc Test.cpp $(pkg-config --cflags --libs opencv) -m64 *nvcc Test.cpp $(pkg-config --cflags --libs opencv) But this also give errors. I have looked for answers on stackoverflow and found this. Compiling OpenCV CUDA program In this answer the solution is to use this command: g++ Test.cpp `pkg-config --cflags --libs opencv` -lopencv_gpu And it works! I have tried giving the same argument to the gcc and nvcc compiler but then I get errors again. This is a problem since I have to use the nvcc compiler because I want to use OpenCV in a CUDA project. I have little experience with C and C++ so there is a possibility that it is something obvious :) A: For compiling and linking C code you should use gcc For compiling and linking C++ code you should use g++ Although gcc can often correctly guess what language to compile a file as, it can usually not link to the needed libraries. A: I think that these commands will work, because it worked in my computer (Ubuntu+OpenCV +Eclipse) huynhngoctan@ubuntu:~/workspace$ g++ SiftDescriptor.cpp $(pkg-config --cflags --libs opencv) -lopencv_gpu huynhngoctan@ubuntu:~/workspace$ ./a.out box.png box_in_scene.png
{ "language": "en", "url": "https://stackoverflow.com/questions/7556895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ListPicker not working with MVVM Light I am building a simple windown phone 7 Page. I'm doing MVVM (using MVVM light) and binding a List<Category> type property to ListPicker. This property is defined in a view model named AddExpenseViewModel like below public class AddExpenseViewModel:ViewModelBase { public List<Category> Categories { get { return categories; } set { categories = value; RaisePropertyChanged("Categories"); } } } Category class is defined as public class Category { public string Name { get; set; } } In my XAML I first define a resource as <UserControl.Resources> <bs:ViewModelLocator x:Key="ViewModelLocator" /> </UserControl.Resources> Then set the DataContext of the grid that contains the ListPicker as <Grid x:Name="ContentPanel" Grid.Row="1" Margin="13,1,11,-1" DataContext="{Binding Path=AddExpenseViewModel, Source={StaticResource ViewModelLocator}}"> And here is my XAML for ListPicker <toolkit:ListPicker HorizontalAlignment="Left" Height="50" Width="200" Grid.Row="2" Grid.Column="1" DataContext="{Binding AddExpenseViewModel}" ItemsSource="{Binding Path=Categories, Mode=OneWay}" > <toolkit:ListPicker.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <Border Background="LightGreen" Width="*" Height="*"> <TextBlock Text="{Binding Name}"></TextBlock> </Border> </StackPanel> </DataTemplate> </toolkit:ListPicker.ItemTemplate> </toolkit:ListPicker>` This does not work. The ListPicker is always empty. Am I doing anything wrong here? A: Do you see any Xaml binding errors in the output while running your application? You also shouldn't have to bind the DataContext on the ListPicker if you are doing it on a parent element (your Grid). This could be your issue, but the binding errors should give some detailed info. A: After lot of fire-fighting I got this to work myself. Here is what I changed to get this to work I introduced a new class as below public class Categories : ObservableCollection<Category> { } Then I changed the property Categories on my AddExpenseViewModel as below public Categories Categories { get { return categories; } set { categories = value; RaisePropertyChanged("Categories"); } } private Categories categories; Then I changed the ItemsSource on listpicker as ItemsSource="{Binding Path=Categories}" This has got it working. A: Having the Key of your resource being the same as the type is likely the issue. You could change the case or rename entirely. Try: <bs:ViewModelLocator x:Key="locator" /> and DataContext="{Binding AddExpenseViewModel, Source={StaticResource locator}}" You also shouldn't need to set the DataContext of the Grid and the ListPicker to the same thing. If you're only using the VML in the ListPicker I wouldn't set it on the grid also. You should use a TwoWay binding with a ListPicker as it needs to track the selected Item
{ "language": "en", "url": "https://stackoverflow.com/questions/7556899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Linux wildcard not behaving correctly I will be running a list of processes that will have the following naming conventions: a_feed b_feed c_feed ... I have written a bash shell script that will allow me to filter out the processes with these naming patterns. Please look at the one line in my shell script below: ps -ef | grep -i *_feed | grep -v grep | awk '{print $2, " ", $8, " ", $10}' For some reason, grep -i *_feed is unable to find any process that conforms to the pattern *_feed. Does anyone have any ideas why? Thanks. A: grep users regular expression, in which * means matches 0 or more times, and not any character. You should replace it with grep -i .*_feed A: * need something in front of it. Also, if you have a file with the pattern *_feed in your working directory bash will do wildcard expansion. Use: grep -i '.*_feed' A: from grep man page: -G, --basic-regexp Interpret PATTERN as a basic regular expression (BRE, see below). This is the default. so, by default the pattern would be regular expression. in your example, you could use grep -i ".*_feed" A: I usually save the output of the list of processes in a shell variable and then search for the matching lines as a new command. This avoids needing a grep -v to remove the running grep command. I also match the lines inside awk so that no grep is needed at all. I think this is easier to read and understand: p="$(ps -ef)" echo "$p" | awk '/_feed/ {print $2, " ", $8, " ", $10}'
{ "language": "en", "url": "https://stackoverflow.com/questions/7556901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What does ||= mean? I have a protected method in my application contoller def current_user @current_user ||= User.find_by_id(session[:user_id]) end I was wondering what ||= means? I've been trying to search and find out, but to no avail. A: ||= is a ruby idiom. It means if @current_user is nil (or false) then try to find it by id and assign it to @current_user, otherwise do nothing. See these related questions. A: This is part of Ruby. If @current_user is nil or false, it will be set to User.find_by_id(session[:user_id]) A: Basically, a ||= b means assign b to a if a is null or undefined or false (i.e. false-ish value in ruby), it is similar to a = b unless a, except it will always evaluate to the final value of a (whereas a = b unless a would result in nil if a was true-ish). A: Notice the parallels with a += b, which is equivalent to a = a + b. So a ||= b is equivalent to a = a || b. As others have mentioned, this is the same as a = b unless a. A: In ruby 'a ||= b' is called "or - equal" operator. It is a short way of saying if a has a boolean value of true(if it is neither false or nil) it has the value of a. If not it has the value of b. A: Basically, a ||= b means assign b to a if a is null or undefined or false (i.e. false-ish value in ruby), it is a shortcut to a = b unless a. share|edit answered Sep 26 '11 at 14:48 Romain 6,9711330 In addition to this answer here`s an example - arr = nil || [] arr0 ||= [] arr <=> arr0 *#=> 0* This means arr expression and arr0 expression are equal. Hope this helps to understand better ||= operator.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: What is this "overlay" in a MinGW g++ executable? I have this C++ file: #include <iostream> int main(int argc, char *argv[]) { std::cout << "Hello world!\n"; return 0; } After compiling with g++ I get a 913KiB big executable. I was astonished, because I thought g++ would be smart enough to not include any code or data not used by the program from the STL. Next I used UPX with these settings: upx --overlay=strip. After this the executable size was reduced to 142KiB, a reduction of 85% with no speed penalty (I tested this with more complex, mathematical programs). According to the upx man page: An "overlay" means auxillary data atached after the logical end of an executable, and it often contains application specific data (this is a common practice to avoid an extra data file, though it would be better to use resource sections). I couldn't find any info that was more specific and was left with the following questions: - What exactly is this overlay? - Is it safe to strip? - If yes, why doesn't g++ do it, even with -Os? Contextual information: * *Windows 7 Home Premium SP1 64 bit *MinGW installed with TDM-GCC *g++ version 4.5.2 *Compiling with g++ -Os test.cpp A: -Os optimises the generated code for size, it doesn't say anything about other non-code segments in the executable file. Did you try the -s linker option to strip debug symbols, suggested here?
{ "language": "en", "url": "https://stackoverflow.com/questions/7556903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Calling a C/assembly function from OCaml more directly than with caml_c_call OCaml allows C functions to be called from OCaml programs, as long as the programmer follows the instructions in the "Interfacing C with OCaml" chapter of the manual. When following these instructions, a call to a C function is translated by the native compiler to: movq ml_as_z_sub@GOTPCREL(%rip), %rax call caml_c_call@PLT (amd64 instruction set here, but looking at other architectures, the scheme seems to be rather uniform). The function caml_c_call eventually does a computed jump call *%rax, but it does a lot of things before and after. From asmrun/amd64.S: /* Call a C function from Caml */ FUNCTION(G(caml_c_call)) .Lcaml_c_call: /* Record lowest stack address and return address */ popq %r12 STORE_VAR(%r12, caml_last_return_address) STORE_VAR(%rsp, caml_bottom_of_stack) /* Make the exception handler and alloc ptr available to the C code */ STORE_VAR(%r15, caml_young_ptr) STORE_VAR(%r14, caml_exception_pointer) /* Call the function (address in %rax) */ call *%rax /* Reload alloc ptr */ LOAD_VAR(caml_young_ptr, %r15) /* Return to caller */ pushq %r12 ret When one wants to frequently execute a couple of instructions that neither allocate nor raise exceptions, the above is a little bit overkill. Does anyone have any experience in calling a small assembly routine directly from OCaml, without going through the caml_c_call stub? This probably involves tricking the native compiler into thinking that it is calling an ML function, or modifying the compiler. The question is in the context of the library Zarith, where small assembly bits of code could compute and return most results directly, without having to go through caml_c_call, and only jump to caml_c_code for the difficult arguments that require allocation or exceptions. See this file for examples of assembly bits that could be executed directly. A: Maybe "noalloc" and "float" could be of some use? PS some more related links. A: It sounds like you wouldn't mind the overhead of an OCaml function call if the function you were calling could be written in assembly. I just did some experimentation, and you can do this by the method I outlined above. Here's what I did. To get a workable assembly language template, I defined a simple function in OCaml and compiled with the -S flag. $ cat sep.ml let addto x = x + 1 $ /usr/local/ocaml312/bin/ocamlopt -inline 0 -c -S sep.ml Note: you need to specify -inline 0 to assure that ocamlopt takes the code from your generated .o file and not from the inline definition in the .cmx file. Now you have a file named sep.s. The addto function looks like this (amazingly good code, actually): _camlSep__addto_1030: .L100: addq $2, %rax ret Just for a test, I changed the 2 (which represents 1 in OCaml) to 4 (which represents 2 in OCaml). So you now have: _camlSep__addto_1030: .L100: addq $4, %rax ret Now assemble this file, producing a deviant version of sep.o. $ as -o sep.o sep.s In essence, you have tricked ocamlopt into treating the code in sep.o as if it was coded in OCaml. But you can write the code yourself in assembly (if you're careful not to violate any of the architectural assumptions). You can link it into a main program and run it: $ cat main.ml let main () = Printf.printf "%d\n" (Sep.addto 19) let () = main () $ /usr/local/ocaml312/bin/ocamlopt -o main sep.cmx main.ml $ main 21 As you can see, it runs the modified assembly code. You could follow this procedure to create any OCaml-callable functions in assembly code. As long as you don't mind the overhead of an OCaml function call, this approach might do what you want. I don't know how this trickery will affect the handling of debugging and garbage collection, so I wouldn't try this with a function that does any allocations. These tests were run on Mac OS X 10.6.8 using OCaml 3.12.0 (the stock 64-bit build). When I run "as", I'm running the stock OS X assembler from Xcode 4.0.2, which uses x86_64 architecture by default. A: It seems to me it doesn't help to trick the compiler into thinking it's calling an OCaml function, unless you also trick it into inlining the call. As far as I can tell by perusing sources, inlined functions are expressed in something called Ulambda code, which in turn contains primitives. So this line of thinking, anyway, leads to adding primitives for your Zarith operations. If you do that, you have a good (not at all tricky) solution, but it might be more work than you want to do. For a really tricky approach, you could try post-processing the generated asm code to remove function calls and replace them with in-line code. This kind of trick has been used many times. It usually doesn't hold up for long, but it might be good enough for the short term. To do this, you'd just give the OCaml compiler the name of a different assembler to run, one that does your modifications before assembling.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: android - number formatting based on locale being a newbie to android I have some code combined as below in the aim of displaying a specific number 12345.66 differently according to the custom locale. However it just crashed my test application and I couldn't figure out why...Appreciate some help here. Thanks a lot in advance! //get current locale and display number Configuration sysConfig = getResources().getConfiguration(); Locale curLocale = sysConfig.locale; String aNumber = "12345.66"; NumberFormat nf = NumberFormat.getInstance(curLocale); aNumber = nf.format(aNumber); numberText.setText(R.string.numberText + aNumber); Layout.xml: <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/nbumberText" /> A: According to Android/Java documentation, you can use java.text.NumberFormat: NumberFormat.getInstance().format(myNumber); This will use the current user's locale. More information on http://developer.android.com/reference/java/text/NumberFormat.html A: This statement is very suspicious: numberText.setText(R.string.numberText + aNumber); What do you mean by that? Is it a typo? To display the formatted number, probably you should only need: numberText.setText(aNumber); By the way, I guess you have not used the debugger. A serious developer definitely need that. A: It crashes because NumberFormat.format() takes in Double or a Long, but not a String. So: aNumber = nf.format(aNumber); Should be: aNumber = nf.format(new Double(aNumber));
{ "language": "en", "url": "https://stackoverflow.com/questions/7556914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Return numbers from String input, Java I am kind of stumped here and have been trying to figure this out for some time. This is homework, although I want to learn to code regardless. Here I have to convert the string input by the user to uppercase letters, then those uppercase letters to numbers using the phone keypad system(2 = ABC etc.). I have gotten this far but am unsure as to what my next step should be. Any ideas are greatly appreciated, thanks in advance. package chapter_9; import java.util.Scanner; public class Nine_Seven { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter a string: "); String s = input.next(); // unsure what to do here, know i need some sort of output/return // statement } public static int getNumber(char uppercaseLetter) { String[] Keypad = new String[10]; Keypad[2] = "ABC"; Keypad[3] = "DEF"; Keypad[4] = "GHI"; Keypad[5] = "JKL"; Keypad[6] = "MNO"; Keypad[7] = "PQRS"; Keypad[8] = "TUV"; Keypad[9] = "WXYZ"; for (int i = 0; i < Keypad.length; i++) { // unsure what to do here } return (uppercaseLetter); } } A: To get the number for a char, you should probably do your array the other way around. You method could look like this: public static int getNumber(char uppercaseLetter) { int[] keys = {2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,9}; return keys[(int)uppercaseLetter - 65]; //65 is the code for 'A' } It may also be a good idea to pull the keys array into a member variable for the class so that you don't initialise it on every call. As for the output/conversion, I suggest you have a look at java.lang.System class. Also note that you haven't converted the string to uppercase - and are not checking for the validity of input (that it's a string made from just the 26 letters). A: String.IndexOf // unsure what to do here can be: for(int i = 2;i < Keypad.length;i++) { if(Keypad[i].indexOf(uppercaseLetter) != -1) { return i; } } There are many other, better ways to accomplish this, but this is one way. A: Here is the whole program. public class Mobile Key Pad{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter a string: "); String s = sc.next(); char ch[]=s.toCharArray(); int n[]=new int[s.length()]; for(int i=0;i<ch.length;i++) { n[i]= getNumber(ch[i]); System.out.print(n[i]); } } public static int getNumber(char uppercaseLetter) { String[] Keypad = new String[10]; Keypad[2] = "ABC"; Keypad[3] = "DEF"; Keypad[4] = "GHI"; Keypad[5] = "JKL"; Keypad[6] = "MNO"; Keypad[7] = "PQRS"; Keypad[8] = "TUV"; Keypad[9] = "WXYZ"; for(int i = 2;i < Keypad.length;i++) { if(Keypad[i].indexOf(uppercaseLetter) != -1) { return i; } } return (uppercaseLetter); } } A: Look into Map and see if it gives you any ideas. A: Your requirement seems to be to find the entered character in your Keypad array. The naive way to do this is to use the indexOf() method in the String class, which returns a value > -1 if a substring exists in the referenced string. So "ABC".indexOf("A") would return 0, "ABC".indexOf("C") would return 2, and "ABC".indexOf("D") would return -1; Use the for loop to address every string in the Keypad array, and use the above method to check whether the entered character maps to the current selection. A: First of all, I'd not put the mapping into the method but into the class itself. Next, you might try and use a Map<String, Integer> like this: Map<Character, Integer> charToNum = new HashMap<Character, Integer>(); charToNum.put('A', 2); charToNum.put('B', 2); charToNum.put('C', 2); charToNum.put('D', 3); ... If you then need to get the number for a character, just call: public static int getNumber(char uppercaseLetter) { return charToNum.get(uppercaseLetter); } Note that I make use of auto(un)boxing here: char get's automatically converted to Character and vice versa (like int <-> Integer). That's why using a map works here. A: In your getNumber function, it looks like you want to go through your Keypad array. The logical question to ask is: "At each step of the for loop, what are you looking for and are you done?". For example, suppose your uppecaseLetter is 'E'. Then going through the steps: first, (i=0), you don't know anything since Keypad[0] is unused. next, (i=1). Still nothing, since Keypad[1] is unused next, (i=2). Keypad[2] = "ABC" but the letter is E (and it isn't in "ABC") so nothing here next, (i=3). Keypad[3] = "DEF" letter E is here, so you know you could return i (i=3) here A: * - * *List item // unsure what to do here, know i need some sort of output/return // statement char ch[]=s.toCharArray(); int n[]=new int[s.length()]; for(int i=0;i<ch.length;i++) { n[i]= getNumber(ch[i]); System.out.print(n[i]); } A: A complete program for this question. import java.util.Scanner; public class PhonePad { public static void main(String[] args) { System.out.println("Mobile Phone key Pad ( Considering 2 to 9 as keys)"); System.out.println("Enter the Switch Number" + " 1st and no of times it got pressed " + "\n Press any word to exit"); StringBuilder str = new StringBuilder(); try { while (true) { Scanner s = new Scanner(System.in); int swNum = s.nextInt(); int no = s.nextInt(); if ((swNum > 9 ||swNum <2) ||(no > 4||no <1)) break; else if ((swNum>7&&swNum<10) || (swNum >1 &&swNum<7) || (swNum ==7 && no ==4)){ // 7 has PQRS if(swNum > 7){ no++; } int temp = swNum * 3 + (no - 1) + 59; System.out.println("Entered char is "+(char) temp); str.append((char) temp); } else break; } } catch (Exception e) { System.out.println("Exiting terminal"); } finally { System.out.println("Thanks for using my Keypad... visit again"); System.out.println("Entered keyword is " + str.toString()); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7556915", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: emulator-arm.exe (Not Responding) Windows 7 x86 Currently I am using the following programs for Android development: * *JRE 6.27 *Eclipse Classic Indigo 3.71 *Android SDK revision 12 *Windows 7 Enterprise x86 *Dell Optiplex 780 *Processor Intel Q8400 2.66 GHz *RAM 4 GB AVD Settings * *Android 2.3.3: API Level 10 *SD Card: 32 MiB *Resolution: Built-in (WVGA800) *Density: 240 (High Density) *Max VM Heap: 24 *Device RAM size: 512 Everything installs fine, but when I create an AVD and launch it I go straight to the skin with a blank black screen and then it goes to not responding in about 10 seconds. This is lab wide on 17 computers running Windows 7 Enterprise x86. I can take one of the installs and copy it to my work laptop and launch it and all runs fine. I have done the same copy from this install to many other devices and they are fine. Just seem to be having trouble in the lab only. I check the Application Event log and all I receive is a vague Application Hang error. Have checked numerous threads on here and I am still at a loss. Thanks for any insight into this issue. A: I was facing the same problem, but with a configuration of Eclipse 3.6 (Helios) and ADT plug-in v15.0, and Windows XP Pro (I hope you got a solution to your problem, but still, here is my view on it)- Many people have reported problems occuring with the use of any versions of Eclipse above 3.5 (Galileo) with any version of ADT. Post switching to Eclipse Galileo, the things seem to be fine, and I've not seen a "not responding" issue with any avd since then. So, you could probably try down-grading to Eclipse Galileo (the only one with support, since they've stopped support for any versions below 3.5). Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556918", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is this plugin framework IoC/DI? I am working on a way for my ASP.NET C# application to allow plugins without recompiling the host application when new plugins are installed. Here's my plugin loader class (based on tutorials found online.) public class PluginLoader { public static IList<IPlugin> Load(string folder) { IList<IPlugin> plugins = new List<IPlugin>(); // Get files in folder string[] files = Directory.GetFiles(folder, "*.plug.dll"); foreach(string file in files) { Assembly assembly = Assembly.LoadFile(file); var types = assembly.GetExportedTypes(); foreach (Type type in types) { if (type.GetInterfaces().Contains(typeof(IPlugin))) { object instance = Activator.CreateInstance(type); plugins.Add(instance as IPlugin); } } } return plugins; } } The concept is to create a IPlugin interface in the host application that new plugins can use. The loader then searches through the available DLLs and finds the classes that are of the IPlugin type. then those get instantiated and my host application can use them how it sees fit. For example it could do this: protected void Page_Load(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); string folder = Server.MapPath("~/bin/"); path.Text = folder; var plugins = PluginLoader.Load(folder); if (plugins.Count == 0) sb.Append("No plugins found"); else { sb.Append("<ul>"); foreach (var plug in plugins) { sb.AppendFormat("<li>Default: {0}</li>", plug.Label); plug.SetLabel("Overwrote default label."); sb.AppendFormat("<li>New: {0}</li>", plug.Label); } sb.Append("</ul>"); } message.Text = sb.ToString(); } Is this structure what IoC or DI is? The plugin is referencing the host, rather than the other way around. This seems to be consistent with the Inversion Of Control concept. Is there a fundamental difference between this code and IoC/DI? A: This looks like a plugin architecture that utilises Inversion of Control, but not using Dependency Injection. It appears to be similar to the way MEF works. A: Agree with Richard's answer. I think what you have ends up being a rudimentary service locator. A DI container would provide the actual auto-instantiation of types based on other types in the container.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Create a numeric navigation How do I create a menu which automatecaly names the involved page into a numeric navigation? This would be my page tree: News |--- Newsarticle tom (contains 9 content elements) |--- Skeet's stuff (contains 9 content elements) |--- Jessicas 5 articles (contains 4 content elements) In the frontent all 3 pages will be simply displayed as a numeric navi: (Imagin the 9 textpic elements of "Newsarticle tom" in here) 1 - 2 - 3 A: {register:count_HMENU_MENUOBJ} should do the trick - I found it in the comments here http://www.typo3wizard.com/de/snippets/menus/nummeriertes-menue.html. (german) Here I used @konsolenfreddies HMENU example, modified for your demands. (Untested). temp.menu = HMENU temp.menu { 1 = TMENU 1 { noBlur = 1 wrap = <ul>|</ul> NO = 1 NO { wrapItemAndSub = <li>|</li> altText = subtitle // title title = subtitle // title } CUR < .NO CUR.wrapItemAndSub = <li class="active">|</li> ACT < .CUR } 2 < .1 2 { wrap = <ol>|</ol> NO { allWrap = <span>Nr.{register:count_HMENU_MENUOBJ}|</span> allWrap.insertData = 1 ATagBeforeWrap = 1 } CUR < .NO CUR.wrapItemAndSub = <li class="active"><span>|</span></li> ACT < .CUR } } In this case, I guess all subpages are taken in account when numbering. And the full setup as described on the site is far more complicated. But if you know your typoscript, you'll understand. A: First off, you could use the alternative navigation title to name them individually, but that might be tedious in a larger page tree. a solution would be to create a OL navigation and remove the title via CSS. That way the navigation is still accessible and gives some hints about what's behind the numbers: temp.menu = HMENU temp.menu { 1 = TMENU 1 { noBlur = 1 wrap = <ul>|</ul> NO = 1 NO { wrapItemAndSub = <li>|</li> altText = subtitle // title title = subtitle // title } CUR < .NO CUR.wrapItemAndSub = <li class="active">|</li> ACT < .CUR } 2 < .1 2 { wrap = <ol>|</ol> NO.wrapItemAndSub = <li><span>|</span></li> CUR < .NO CUR.wrapItemAndSub = <li class="active"><span>|</span></li> ACT < .CUR } } The corresponding CSS: ol li span {display:none;} A: untested: You can override the link text via: NO.stdWrap.cObject.10 = TEXT NO.stdWrap.cObject.10.data = register:count_HMENU_MENUOBJ # if the register starts with 0, add 1: NO.stdWrap.cObject.10.stdWrap.wrap = |+1 NO.stdWrap.cObject.10.prioriCalc = int Instead of the title, you should get now the number. Relevant TSref: http://typo3.org/documentation/document-library/core-documentation/doc_core_tsref/4.5.1/view/1/9/#id2649360
{ "language": "en", "url": "https://stackoverflow.com/questions/7556923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Why doesn't my schemas update in my map? I have a map in Biztalk which has a source-schema and a target-schema and I right-click each one and point to the reference, but schemas does not update, even when I have added some fields for them and built them. Maybe I should place them in the GAC also or something? A: Delete the reference and re-add it. Doesn't need to be GAC'd.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: NSCopying, copyWithZone and NSDictionary Firstly I would like confirmation that I have understood NSCopying correctly ... In order to use a simple NSObject subclass as a key in an NSDictionary I must have it implement the NSCopying protocol. In the copied instance's copyWithZone method I must alloc/init a new instance of my class, set its properties to be identical to the copied instance and return it. Secondly, why does an NSDictionary use a copy of the instance added to it rather than the instance itself? A: The subclass does not need to implement NSCopying if it is the object, the key should usually be NSStrings, which are copied. A: * *You have to implement NSCopying protocol for every custom class if you want make them copyable *It must use a copy because if you will modify an object contained in the original dictionary it's copy won't be affected by the change
{ "language": "en", "url": "https://stackoverflow.com/questions/7556925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: pygame.MOUSEBUTTONDOWN pygame.VIDEORESIZE ERROR? I posted a similar question a few days ago but i have refined the problem: when i have both MOUSEBUTTONDOWN and VIDEORESIZE in the same event loop it doent work... when i click the mouse down it also prints the statement which should only get printed when the MOUSEBUTTONUP event occurs.... TRY it your selves this problem is killing me.. import pygame from pygame.locals import * from sys import exit LEFT = 1 size = 520,630 running = 1 screen = pygame.display.set_mode(size, RESIZABLE, 32) #screen = pygame.display.set_mode((size)) while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = 0 if event.type == pygame.VIDEORESIZE: size = event.size pygame.display.set_caption("Window resized to "+str(event.size)) if event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT: print "You pressed the left mouse button at (%d, %d)" % event.pos if event.type == pygame.MOUSEBUTTONUP and event.button == LEFT: print "You released the left mouse button at (%d, %d)" % event.pos screen = pygame.display.set_mode(size, RESIZABLE, 32) screen.fill((0, 0, 0)) pygame.display.flip() A: Don't update the screen at every event, it slows down your program considerably. It's so slow on my computer I can't make any sense of the mouse events. Just moving a couple of lines of your code fixes that and it runs fine. import pygame from pygame.locals import * from sys import exit LEFT = 1 size = 520,630 running = 1 screen = pygame.display.set_mode(size, RESIZABLE, 32) while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = 0 if event.type == pygame.VIDEORESIZE: size = event.size pygame.display.set_caption("Window resized to "+str(event.size)) screen.fill((0, 0, 0)) pygame.display.flip() if event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT: print "You pressed the left mouse button at (%d, %d)" % event.pos if event.type == pygame.MOUSEBUTTONUP and event.button == LEFT: print "You released the left mouse button at (%d, %d)" % event.pos
{ "language": "en", "url": "https://stackoverflow.com/questions/7556940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery: why doesn't jQuery.inArray() work? As shown in the image, I just do inArray on an array, looking for a node. and $previously_selected_node and the item at index 37 in $shapes are the same object.... so... why isn't it working? EDIT: I found another way to search after one of the aswerers postedd his answer: var result = -1; jQuery.each(shapes, function(key, value){ if (value.id == shape.id){ result = key; } }); return result; apparently, part of my problem is that I can't return in the middle of a loop. (I was returning the instant a match was found, which was causing some issues.) A: Your object is not an array. $.inArray only work on array-like objects with a length and a set of properties named 0 through length - 1. You need to search your non-array manually. For example, you could use a for / in loop to loop through all properties that actually exist and see if any of them match your object: for (var key in $shapes) { if ($shapes[key] === yourObject) { //Match! } } A: You're doing it the wrong way round. It's actually $.inArray(value, array). And as others already stated: inArray is for arrays, not for objects.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Merge 2 xcode projects I have 2 xcode projects and i want to merge them into 1. But i stucked at the Delegates as both project has their own delegates. First project has a Splitview (Master/Detail) view and the second project is a carousel. I want to replace the detail view with the carousel project. I already linked the framework and the related files and nibs. But im stucked at the appdelegate of the MasterDetail, how do i call the appdelegate and the ViewController of the carousel project and pass the selected item to the carousel? #import "iPadAppDelegate.h" #import "MasterViewController.h" #import "DetailViewController.h" //iCarousel #import "CarouselExampleAppDelegate.h" #import "CarouselExampleViewController.h" // @implementation iPadAppDelegate @synthesize window, splitViewController, masterViewController, detailViewController; //iCarousel @synthesize carouselExampleViewController; // #pragma mark - #pragma mark Application lifecycle - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after app launch masterViewController = [[MasterViewController alloc] initWithStyle:UITableViewStylePlain]; UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:masterViewController]; /* detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailView" bundle:nil]; masterViewController.detailViewController = detailViewController; */ **//iCarousel ??? Call the Carousel delegate? And also the Carousel Controller? //** splitViewController = [[UISplitViewController alloc] init]; splitViewController.viewControllers = [NSArray arrayWithObjects:navigationController, detailViewController, nil]; splitViewController.delegate = detailViewController; // Add the split view controller's view to the window and display. [window addSubview:splitViewController.view]; [window makeKeyAndVisible]; return YES; } Thanks, Kevin
{ "language": "en", "url": "https://stackoverflow.com/questions/7556948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Casting string encoding to UTF-8 I am building my own PHP framework, and I want on each request to convert each get and post variable to utf8 (I don't use other encodings anywhere in my current project) to prevent my projects from "Invalid Encoding Attack" or binary atack. I found utf8_encode in php.net, but it says that converts ISO-8859-1 to UTF8 only. I want to know is it a big deal to cast everything to utf8, or this cannot do anything in common with security (I want to decrease the security holes as much as possible). A: @nikolay, mb_convert_encoding() is your friend. Have a look here. Additionally, if you set the encoding of all web-pages to UTF-8, there's no need to convert manually. Add this to each page's head section: <meta charset="utf-8" /> A: If your goal is to protect yourself from invalid encoding attacks, then you should use mb_check_encoding() on your GET/POST values before using them. But you don't need to convert anything - e.g. using mb_convert_encoding(): if you use the appropriate Content-Type and <meta> tag, specifying your page is in UTF-8, you are guaranteed that normal users will send you only UTF-8. A: iconv > http://php.net/manual/en/book.iconv.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7556951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create Round Telephone screen in Android? I am new to Android and I want to create a Round Telephone dialing screen? so how to create a screen? Which component need to use LinearLayout/FrameLayout/RelativeLayout, and how to set images for all resolution? A: If I were you I would look into creating your own custom UI component. The documentation can be found here Android Custom Components. You can use the onDraw() method to draw ellipses and pretty much anything else you need. Then potentially add the numbers to form a dial pad. You can output text via onDraw(). Something that might help is the Vintage Thermometer Tutorial this actually draws a round thermometer with numbers on a scale, so it might get you 65% of the way there, while providing a good learning experience. You'll need to strip out the sensor related stuff however that is not too difficult. As for the dialing, I am not too sure although I would store the numbers pressed somewhere in the activity then have a "dial" button that when pressed does something like try { Intent intent = new Intent(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:+436641234567")); startActivity(intent); } catch (Exception e) { Log.e("Dialer", "Something went wrong dialing...", e); } Although with the above the user might have to press dial on your app/widget then again on the actual dial screen where the number will have been populated. Someone here might be able to add some additional information but I haven't seen anything yet to suggest you can dial a number without the user explicitly pressing dial on the phone's dialing app. You will also need this permission in your manifest: <uses-permission android:name="android.permission.CALL_PHONE"></uses-permission> I hope this gets your project underway. If you are struggling I would suggest you start with making a call then sort out the custom UI.
{ "language": "en", "url": "https://stackoverflow.com/questions/7556953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: CAKeyframeAnimation and audio sync I am using CAKeyframeAnimation to perform few animations in my app. I would like to play an audio file (sometimes during and sometimes after) along with the animations. How can I achieve this? Is there a AnimationDidStopSelector for CAKeyframeAnimation or is there another approach for doing this? UIBezierPath *movePath = [UIBezierPath bezierPath]; [movePath moveToPoint:imageAnimation.center]; [movePath addQuadCurveToPoint:CGPointMake(839, 339) controlPoint:CGPointMake(671, 316)]; CAKeyframeAnimation *moveAnim = [CAKeyframeAnimation animationWithKeyPath:@"position"]; moveAnim.path = movePath.CGPath; CAAnimationGroup *animGroup = [CAAnimationGroup animation]; animGroup.animations = [NSArray arrayWithObjects:moveAnim, nil]; animGroup.duration = 0.5; imageAnimation.layer.position = CGPointMake(839, 339); imageAnimation.tag = 0; [imageAnimation.layer addAnimation:animGroup forKey:nil]; break; A: Actually there is. First assign yourself as delegate: animGroup.delegate = self If you want to use different animations you can use KVC to differentiate between them: [yourAnimation setValue:@"firstAnimation" forKey:@"animationName"]; Then implement this method - (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag { if (flag && [[anim valueForKey:@"animationName"] isEqualToString:@"firstAnimation"]) { //play your sound } else if (flag && [[anim valueForKey:@"animationName"] isEqualToString:@"secondAnimation"]) { //do something else } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7556955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }