text
stringlengths
8
267k
meta
dict
Q: Mongoengine unique_with I am using mongoengine with MongoDB. I have to make a Document in which the tuple (merchant_id, order_id, event_type) has to be a unique key. Till now, I have always dealt with uniqueness being limited to two fields. So the following works- merchant_id = StringField(required = True) order_id = StringField(required = True, unique_with = 'merchant_id') Now, I'm trying to do this for three fields - merchant_id = StringField(required = True) order_id = StringField(required = True) event_type = StringField( required = True, unique_with = ['merchant_id', 'order_id']) But this doesn't work. I'm not getting an error in the module. But if I enter data as - merchant_id = 'Merchant1' order_id = 'Order1' event_type = 'Event1' and then try to add another data with the same merchant_id and order_id but a different event_id, then it gives an error about being a duplicate key. I have also tried: merchant_id = StringField(required = True) order_id = StringField(required = True) event_type = StringField( required = True, unique_with = ('merchant_id', 'order_id')) A: You can specify indexes in the meta dict of the class meta = { 'indexes': [ {'fields': ('merchant_id', 'order_id'), 'unique': True} ] } A: If you want to modify an existing index's parameters, you have to drop the index first and then recreate it. Of course you cannot create a unique index on collections that contain duplicates. Either you must remove the duplicates first, or use the 'dropDups' index creation option.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: which eclipse sdk use for android honeycomb tablet application? i want to make a honeycomb tablate application. For this which sdk version preferable in android app. A: You may always use latest SDK version for development, as SDK comes with lot of development tools. You can develop application for any API level using latest SDK. The way I interpret your questions is, what should be the minimum API level that your application should support. Well as per my understanding Android-SDK supports tablets from the beginning, but since 1.6 onwards multiple screen support was enhanced and made developer friendly. From the market-share perspective you may use Android 2.2 or above. Android 3.0 (Honeycomb) which is specific for Tablets provide really cool features from UI perspective. So in my opinion if your application targets broad category of customers you may support Android 2.2 onwards. A: For Honeycomb development use android sdk version 3.0. See this Link. A: I don't fully understand the question, are you wondering which version of Eclipse you need or which version of the Android SDK you need. Android SDK you need atleast r12 (or higher) as you can see on the Android Developer Page: Android 3.0, Revision 2 (July 2011) Dependencies: Requires SDK Tools r12 or higher. But you can download r13 from here: Android SDK r13 For the Eclipse Version (Eclipse Download Site) I would go for either: * *Eclipse IDE For Java Developers *Eclipse IDE For Java EE Developers
{ "language": "en", "url": "https://stackoverflow.com/questions/7606553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create application session in android My application require timeout of 10 min i.e. if there is no activity on the application from last 10 min, then either the application is terminated or login(Login credential in sqlite db) is shown. I came up with the approach of using thread with maintain perform the task but that approach is untidy approach. Suggest me some better approach. A: I would do this way. * *Save the current time (in millisec) to pref file in onPause(); *Retrieve the time from pref file and compare with current time in onResume(); *If the time difference is more than 10, just finish() the activity and ask for log in. A: Use timer class to do this task / alternatively can use Alarm class for the same. Depends on requirement. Thread will certainly not be a good option. A: You may use AsyncTask to do this job.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to migrate and process data in java with low memory and faster I have an application that receives files with a flat table in DBF, which normalize and convert and insert into a MySQL database, files that grow to between 250,000 to 270,000 records and now consumes about 1.5 - 2 Gb at all I must repeat the process and by parts. I check in the process if there are no prior records, help in HashMaps me the keys that are unique records to not save all the information in them, the problem here is that as to be uploading files to the database DBF total records data grows and every time you import something becomes slower and consume much more memory, easily get to 770,000 records in one table and a call to spend more of the 2,000,000 example: DBF file has 91 fields and I have normalized data base gives 5 ​​main tables and I must repeat the process of remembering the DBF 5 times. nothing can take me about 1 hour migrate all DBF file of 250,000 records. How can you minimize the time and RAM consumption, unless the RAM consumption is lower and I get several Exception in thread "main" java.lang.OutOfMemoryError: Java heap space DBF file structure has many redundant data is like this (columns): * *survey code *overall survey data *group data within the encuenta *details of the persons example: | survey_code | survey_columns | group_survey | more_data | person_details | |:------------|:---------------|:----------------|:----------|:---------------| | 1 | ... | 1 | ... |1-oscar | | 1 | ... | 1 | ... |2-juan | | 1 | ... | 2 | ... |1-catalina | | 2 | ... | 1 | ... |7-john | note: As you can see there is enough data redundancy the structure of the MySQL database is like this: Survery (table) id survey_data Group_in_survey (table) survey_id group_data Person (table) group_id person_details the import process as divided according to the tables and the order defined by their dependence, for each table, runs through all the records in the DBF file. Before I make a request to start the database and then I load into a HashMap information necessary to perform the verification if records exist before being added to the database in MySQL. Also every time you add a record to the MySQL database that record tamibén add to HashMap, since one of the debugging process is duplicated. This latter is done in each of the processes A: From what I understand you are inserting your records first into the HashMap to get rid of duplicates and they you copy it to the MySQL database. If that is the case you can try to use HugeCollections library and their HugeMap instead of simple HashMap A: I think I'd prefer processing the flat-file, stripping duplicates first and saving to a temporary file, then doing a full bulk import. This way you'll never run in to memory issues and you'll have a backup of your first step if there are any issues. A: It seems that you are doing something strange there , it looks that you are parsing whole dbf file loading it in to memory and then inserting one by one in to the database (hopefully not creating connection each time). Now as far as i know dbf is easily read by stream readers so there is no need to load everything in to memory , i think it wold be better to do it in batches read 100 records insert all of them to database , or you can create sql file with inserts and then run whole file on mysql (but it would tale loads of hdd space). now whole process should take only as much memory as processing one row and this should be stable. i would need to know a bit more about structure of the dbf file and your tables to say anything more
{ "language": "en", "url": "https://stackoverflow.com/questions/7606558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: RESTful API Authentication I have found quite a few questions on this topic on SO, but couldn't find any answering this question: Should I validate users with their username and password, or with an API key? And what are the pros and cons of each method. I ask this because in my API, there are a couple of methods I'd like to lock down and verify that the user has access to some document or action. I'm a bit reluctant to authenticate by having the user send an HTTP AUTH header with their username and password because it feels unsecured and a bit more of a hassle for the user. On the other hand, though, if I use an API key, what's the point of the user ever creating a password? As they will no longer be using it to access features of the API. UPDATE If other readers of this are curious what I ended up using, I decided to copy how Amazon does their validation (good explanation here: https://www.ida.liu.se/~TDP024/labs/hmacarticle.pdf) A: you can use HTTP Authentication over SSL and that's secure enough. However it makes consumption of API a bit difficult as it requires the client library to support SSL. SSL can affect the performance too if you're expecting too many calls simultaneously. API key option is just as insecure as HTTP Authentication without SSL. If you're not concerned with security then API Key is the easiest for consumers of the API. A: One good method is to have a login method, taking the username and password (hopefully over TLS). You give them an expiring token if they successfully auth; the rest of their API calls must contain this token to succeed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Get magento meta keywords dynamically? On the Product page of Magento, I want to get the product name, its category name, and sub category name in the meta keywords tag. A: Since products already have an attached MetaKeyword value, you can use an observer to unobtrusively extend that value. This method doesn't involve extending a core class Try this: /app/code/local/YourCompany/YourModule/etc/config.xml <?xml version="1.0"?> <config> <modules> <YourCompany_YourModule> <version>1.0.0</version> </YourCompany_YourModule> </modules> <global> <models> <YourCompany_YourModule> <class>YourCompany_YourModule_Model</class> </YourCompany_YourModule> </models> </global> <frontend> <events> <catalog_controller_product_view> <observers> <YourCompany_YourModule> <class>YourCompany_YourModule/Observer</class> <method>productView</method> </YourCompany_YourModule> </observers> </catalog_controller_product_view> </events> </frontend> </config> /app/code/local/YourCompany/YourModule/Model/Observer.php <?php class YourCompany_YourModule_Model_Observer { public function productView(Varien_Event_Observer $observer) { $product = $observer->getEvent()->getProduct(); /* @var $product Mage_Catalog_Model_Product */ if ($product) { $keywords = $product->getMetaKeyword(); // Add the product name $keywords = ' ' . $product->getName(); // Add the category name $currentCategory = Mage::registry('current_category'); if ($currentCategory && $currentCategory instanceof Mage_Catalog_Model_Category) { $keywords = ' ' . $currentCategory->getName(); } $product->setMetaKeyword($keywords); } } } A: You have to rewrite the Mage_Catalog_Block_Product_View class, especially the __preparelayout() method. Simply add the following code in the _prepareLayout method you will overwrite: protected function _prepareLayout() { $currentCategory = Mage::registry('current_category'); // For accessing current category information $product = $this->getProduct(); if ($headBlock = $this->getLayout()->getBlock('head')) { $headBlock->setTitle("Whatever you want here"); $product->setMetaKeyword("whatever, keywords, you, want, here"); $product->setMetaDescription("Whatever description you want here); } return parent::_prepareLayout(); } It's important that you set the metakeyword and metadescription the way it's described above, else it will be overwritten again by the parent class(es). Regards, Kenny A: Are you meaning product details page ? if yes means very simple Goto your specific product page,there should be tab "Meta Information".here you can add Meta Title, Meta Keywords, Meta Description
{ "language": "en", "url": "https://stackoverflow.com/questions/7606564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Canvas Repaint After Downloading the Image Creating a J2ME application. PROBLEM:how i repainting the displayed canvas without ant user event. Trying to display canvas page,page contains text and image.first time we display text and local image in screen,after displaying it downloading the actuall image form internet and save in RMS,completion of download we are setting one flag.After downloading how can i repaint newly download image with displayed canvas without any user interface. Please give me some solution. Thanks and Regards Raj A: Canvas.repaint() method is invented exactly to serve the purpose like you describe. Check the API javadocs for more details if you're interested
{ "language": "en", "url": "https://stackoverflow.com/questions/7606567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jTable beansbinding I insert data from a util.List into a JTable with beansbinding.I have wrapped an ArrayList into a ObservableList and Observable list assinged to uitl.List.I bound data in Netbeans and set up properties in 'Table Content' in Netbeans 'JTable Beanbinding options'. First time when the list is updated, the JTable is also updated and it is ok. But second time when I set another util.List which is cast into Observable list to the list which is bound to the JTable, the list is updated, but JTable is not updated.(but when I set a list,the System.out.pr.. prints correct values of the list,here I changed the util.List to ObservableList and vise versa to find where the problem is,but no result as I expected)(but when I add objects to the list bound to JTable, then JTable was updated.) How can I update the JTable when the list is updated(That means when I set a new list,the table is also updated every time I set a new list). Here is my code used to set List public List<Customer> getSuggestionList() { return suggestionList; } public void setSuggestionList(ObservableList suggestionList) { try { List oldSuggestionList = this.suggestionList; this.suggestionList = suggestionList; propertySupport.firePropertyChange(PROP_SUGGESTIONLIST, oldSuggestionList, suggestionList); System.out.println("Suggestionlist is setted-----------"); Customer c = (Customer) suggestionList.get(0); System.out.println("sugesstion list customer--------" + c.getCustFname()); } catch (Exception e) { e.printStackTrace(); } } A: Just checked: it's working as expected (manual coding of course, wouldn't touch Netbeans ), sourceBean the class which has the property suggestionList; BindingGroup context = new BindingGroup(); BeanProperty valuesProperty = BeanProperty.create("suggestionList"); JTableBinding tableBinding = SwingBindings.createJTableBinding( UpdateStrategy.READ_WRITE, sourceBean, valuesProperty, table); context.addBinding(tableBinding); tableBinding.addColumnBinding(BeanProperty.create("firstName")); tableBinding.addColumnBinding(BeanProperty.create("lastName")); context.bind(); // add a button which changes the suggestionList Action next = new AbstractAction("new data") { public void actionPerformed(ActionEvent e) { sourceBean.setSuggestionList(createRandomData()); } }; button.setAction(next); summary: something is wrong with the code you are not showing ;-) BTW: the getters/setters signatures should have the same type, which yours dont. Doesn't make a difference in my test, in your context might or might not indicate some unwanted mixup
{ "language": "en", "url": "https://stackoverflow.com/questions/7606570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is Thread.Sleep is not precise for long durations? I have a service written in C#. Service is active around the clock but one thread sleeps via Thread.Sleep till a predetermined time - typically 9PM - 11pm - to perform some housekeeping tasks. First time service starts, it calculates time span in mseconds till the housekeeping time and calls Thread.Sleep using that time span. Next time the thread simply calls Thread.Sleep(24*60*60*1000) to sleep 24 hours. It works just fine except a single installation when Sleep wakes few minutes earlier - 5-8 minutes earlier according to the trace log. Over several weeks, housekeeping time shifts few hours. I can expect that the housekeeping time can shift forward - not backwards. Wondering if anyone can have an explanation. I must admit that I am not looking for a different solution to fix the problem - just trying to explain the behavior. A: Sleep doesn't use wall clock for time calculations. It uses regular interrupt intervals which come approximately every 10ms (adjustable and OS version dependent) for this. The time source which is used for these interrupts is a cheap quartz which was historically was used for some other functions, so its frequency is both not exactly 1/10ms and fluctuates from one machine to another. The correct approach to solving your problem would be sleeping for much shorter periods of time and checking if the time has come to wake up for real. Also, here's hoping that when you say you're using Sleep(), in fact you're waiting for an event with a timeout. A: Thread.Sleep is not designed for long accurate sleeps like you are doing. You should be using somthing like System.Threading.Timer. You can give it a first run time of midnight, and have it go off every 24 hours. the Timer(TimerCallback, Object, TimeSpan, TimeSpan) constructor is exactly what you are looking for.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Tk, how to make a layout with .pack? When I place two buttons in the 'top' part of a TkRoot they are below each other. What are the parameters for '.pack' having them aligned horizontal? (the solution should also apply for n-buttons) Ruby code would be great but anything that works with tk is great. (if you are a python etc. person) Edit: The following thing is needed: inside 'left' is a TkText+TkScrollbar to the right of it, I can only use 'top' to be sure it works as intended (that the buttons are ABOVE the TkText) A: The Tk packer works by taking a slice off the remaining space inside the outer widget and allocating that slice to the inner widget. (The side says which side of the space the slice is taken off, fill says how the inner widget occupies the space, and expand says how things respond when the size of the outer widget changes.) Within the slice, the inner widget is centered. It can take some tweaking to get things right; it's usually easier if you change the widgets' backgrounds to different (garish) colors when doing this, as that makes it easier to see what's happening. If what you want can't be done with the packer, either you need to use nested frames or (better) switch to using the gridder layout engine, which is much more powerful. (Very funky stuff can require listening to <Configure> events or using the placer, but really they're both rare things. 99.9% of all layouts can be done with pack and grid.) A: Unlike many Tk developers, I prefer pack to grid, because it's easier to form a mental model of how it works. It is also possible to create quite sophisticated layouts using pack. The way I approach this conceptually is to use a frame as a container and then pack things in sequence (all right or left) or side-by-side (left/right). Using this container/child approach, you can pack things pretty much anywhere you want. Make sure the things you want to align are within the same container/frame. A: You have to pack the buttons to the left. I modified a Tk example I found online: require 'tk' root = TkRoot.new # button 1 btn_OK = TkButton.new(root) do text "OK" borderwidth 5 underline 0 state "normal" cursor "watch" font TkFont.new('times 20 bold') foreground "red" activebackground "blue" relief "groove" command (proc {}) pack("side" => "left", "padx"=> "50", "pady"=> "10") end # button 2 btn_Cancel = TkButton.new(root) do text "Cancel" borderwidth 5 underline 0 state "normal" cursor "watch" font TkFont.new('times 20 bold') foreground "red" activebackground "blue" relief "groove" command (proc { exit }) pack("side" => "left", "padx"=> "50", "pady"=> "10") end Tk.mainloop A: Pack all by itself is not real good at placing things both horizontally and vertically in tne same container. This isn't a universal truth, but more like a rule of thumb. There are two conventional solutions: use nested frames -- one or more for items arranged horizontally and one or more for items arranged vertically -- or switch to using grid. Note that nested frames doesn't mean you need to change the parent of existing widgets. The in option for pack (and grid and place) is extremely useful.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Updating Recurring payment profile in rails I have implemented Recurring paypal billing in my rails application. It is going on well. I can able to update amount and can cancel profile every thing. Now my problem is, when a user upgraded his package, I would like to charge him the extra amount along with updating the actual amount for the new package. I have strucked with this. Can any one help me. Thanks in advance, Vijju A: "Updating the Billing Amount For profiles created using Express Checkout, you can increase the recurring payment total amount by 20% maximum in a fixed 180-day interval after profile creation. The 20% maximum is based on the total amount of the profile at the beginning of the 180-day interval, including any shipping or tax amount. If, for example, you create a profile on March 10 with a total amount of $100, during the 180-day interval from March 10 to September 6, you can increase the amount to a maximum of $120 (120% of $100). Suppose that during the first 180-day interval, you increased the payment amount to $110. During the next 180-day interval (starting September 7), you can only increase the amount of the payment to a maximum of $132 (120% of $110)." https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_ECRecurringPayments
{ "language": "en", "url": "https://stackoverflow.com/questions/7606574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails dynamic selects - validations not showing errors on fields In my form, I have two selects - state and city. The city drop-down depends upon what the user selects in the state drop-down. In my view, I have the following: <%= f.input :state_id, :collection => @states, :prompt => "Pick Your State" %> <%= render :partial => 'cities', :locals => { :cities => @cities, :user => form } %> The city partial looks like this: <%= simple_fields_for :user do |fields| %> <% if cities.blank? %> <%= fields.input :city_id, :collection => cities, :prompt => "Pick Your State" %> <% else %> <%= fields.input :city_id, :collection => cities, :prompt => "Pick Your City" %> <% end %> <% end %> In my model: validates_presence_of :state_id, :city_id The drop-downs function as expected - I'm using simple_form and jquery if that matters. The validations "work" in that if I don't make a selection, the record won't save, and indeed, I get the error messages explaining the problem. What is not happening, however, is the field_with_errors wrapper around the city. I suspect it has to do with the fact that I am using the partial, but I'm not sure. Do I need to create a custom validation of some kind? edit: I also notice that my password confirmation field is not getting the field_with_errors div as well (again, though the validation itself is still being enforced) A: I moved the city select out of the partial. It's at the cost of the different prompts, but I can live with it. Hope it helps someone. Would like to know the password confirmation field doesn't get the wrapper though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fusion Chart decimal formatting I'm using Fusion Charts. I need to display the data in Y as decimals below zero but they are not appearing kindly help.for example: how to display the decimals like 0.32 .34 in the chart I've placed in my chart the following tags. forceYAxisValueDecimals='1' yAxisValueDecimals='1' decimals='1' A: <chart decimals='3' sDecimals='2' forceDecimals='1' > Main Source For Above Answer is below link http://kb.fusioncharts.com/questions/112/How+do+I+perform+Number+Formatting%3F http://www.fusioncharts.com/docs/advanced/number-format/Number_Basics.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7606577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python unintuitive member variable behaviour This script: class testa(): a = [] class testb(): def __init__(self): self.a = [] ta1 = testa(); ta1.a.append(1); ta2 = testa(); ta2.a.append(2) tb1 = testb(); tb1.a.append(1); tb2 = testb(); tb2.a.append(2) print ta1.a, ta2.a, tb1.a, tb2.a produces this output: [1, 2] [1, 2] [1] [2] but I expected [1] [2] [1] [2] Why was I wrong? The definitions of testa and testb seem equivalent to me, so why should behavior change so drastically?! EDIT: This seems unintuitive because it is different from how other types like int and str behave. For some reason lists are created as class variables when not initialized in init, but ints and strs are created as object variables no matter what. A: In testa the variable a is a class variable and is shared between all instances. ta1.a and ta2.a refer to the same list. In testb the variable a is an object variable. Each instance has its own value. See Class and Object Variables for more details. A: One is a class variable, the other is an instance variable. Class vars are shared between all members of the class, instance vars are unique to each instance. http://docs.python.org/tutorial/classes.html A: It helps to remember that the class statement in Python is much closer to any other block statement than is the case for languages like C++. In Python, a class statement contains a bunch of statements to be executed, just like def, if, or while. The difference is just in what the interpreter does with the block. In the case of flow control block statements like if and while, the interpreter executes the block as specified by the meaning of the flow control statement. In a def, the interpreter saves the block and executes it whenever the function object is called. In the case of a class block, Python executes the block immediately, in a new scope, and then uses whatever is left in that scope after execution finishes as the contents of the class. So for this: class testa(): a = [] Python executes the block a = []. Then at the end, the scope contains a bound to an empty list object. So that's what is in your class. Not any particular instance of the class, that is the class itself. It inherits a do-nothing constructor from object, so that when you instantiate the class with ta1 = testa(), you get an empty instance. Then when you ask for ta1.a, Python finds no instance variable named a (because ta1 has no instance variables at all), and so it looks for a in the class testa. This of course it finds; but it finds the same one for every instance of testa, and so you get the behaviour you observed. On the other hand this: class testb(): def __init__(self): self.a = [] is completely different. Here once the class block has been executed the contents of the class scope is again a single name, but this time it's __init__ bound to a function. That becomes the contents of the class. Now when you instantiate this class with testb(), Python finds __init__ in the class and calls that function with the new instance. The execution of that function creates an a instance variable in the new instance. So every instance of testb() gets its own variable, and you get the behaviour observed. Take home message: a class block in Python is not just a set of declarations of things that are contained in instances of that class, unlike in traditional OO-ish languages like C++ and Java. It is actual code that is actually executed to define the contents of the class. This can be really handy: you can use if statements, the results of function execution, and anything you would use in any other context, inside your class body to decide what to define in your class. (NOTE: I lied for simplicity earlier. Even instances of testa will have some instance variables, because there are some that are automatically created by default for all instances, but you don't see them as much in day-to-day Python). A: The definitions of testa and testb seem equivalent to me, so why should behavior change so drastically?! Python's behaviour is completely logical - more so than that of Java or C++ or C#, in that everything that you declare within the class scope belongs to the class. In Python, a class is logically a template for the objects, but it isn't really physically one. The closest you can get to specifying "instances have exactly this set of members" is to inherit from object, list them in the class' __slots__ and initialize them in __init__. However, Python won't force you to set all the values in __init__, the ones you don't set don't get any default value (attempting to access them results in an AttributeError) and you can even explicitly remove attributes from instances later (via del). All that __init__ does is run upon each new instance (which is a convenient and idiomatic way to set initial values for attributes). All that __slots__ does is prevent adding other attributes. This seems unintuitive because it is different from how other types like int and str behave. For some reason lists are created as class variables when not initialized in init, but ints and strs are created as object variables no matter what. This is not the case. If you put an int or str there, it is still a member of the class. If you could somehow modify an int or str, then those changes would be reflected in every object, just as they are with the list, because looking up the attribute in the object would find it in the class. (Roughly speaking, attribute access checks the object first, then the class.) However, you can't actually do that. What you think is an equivalent test isn't equivalent at all, because your test with an int or str causes an assignment to the object's attribute, which hides the class attribute. ta1.a.append calls a method of the list, which causes the list's internals to change. This is impossible for Python's strings and ints. Even if you write something like ta1.n += 1, this translates to ta.n = ta.n + 1, where the attribute is looked up (and found in the class), the sum calculated and then assigned back to ta.n (assignment will always update the object, unless explicitly forbidden by the class' __slots__, in which case an exception is raised). You can trivially demonstrate that the value belongs to the class by accessing it directly from the class, e.g. testa.a.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Applying an argument list to curried function using foldLeft in Scala Is it possible to do a foldLeft on a list of arguments, where the initial value supplied to the fold is a fully curried function, the operator is apply, and the list is a list of arguments to be passed to function f? For example, let's say f is defined as: scala> val f = (i: Int, j: Int, k: Int, l: Int) => i+j+k+l f: (Int, Int, Int, Int) => Int = <function4> Which we can of course use directly: scala> f(1, 2, 3, 4) res1: Int = 10 Or curry and apply the arguments one at a time: scala> f.curried res2: Int => Int => Int => Int => Int = <function1> scala> f.curried.apply(1).apply(2).apply(3).apply(4) res3: Int = 10 At first glance this looks like a job for foldLeft. My first attempt at describing this sequence of apply using foldLeft looks like: scala> List(1, 2, 3, 4).foldLeft(f.curried)({ (g, x) => g.apply(x) }) However, that yields the following error: <console>:9: error: type mismatch; found : Int => Int => Int => Int required: Int => Int => Int => Int => Int List(1, 2, 3, 4).foldLeft(f.curried)({ (g, x) => g.apply(x) }) My reading of the error message is that type inference would need some hint for g. The solution I'm looking for leaves everything unmodified in my original expression except the type of g: List(1, 2, 3, 4).foldLeft(f.curried)({ (g: ANSWER, x) => g.apply(x) }) My first thought was that a union type would be useful here. I've seen Miles Sabin's derivation of union types using Curry-Howard, so if that first hunch is true, then I appear to have the basic machinery required to solve the problem. However: Even if union types are the answer it would be useful if I could refer to "The union of all types from the fully curried type of a function to the type of the curried function with all but the last argument supplied". In other words, a way to turn the type: T1 => ... => Tn into the union type: (T1 => ... => Tn) |∨| ... |∨| (Tn-1 => Tn) would be useful as the type for g above. Doing a foldLeft on a List limits the discussion to case where T1 through Tn-1 are all the same. A notation like (T1 =>)+ Tn would describe the type I want to provide for g. The specific case I'm asking about doesn't require arbitrarily long chains, so we could provide bounds on the iterator using (T1 =>){1,4} Tn Looking ahead at wanting to do this for chains of types that are not equal, though, perhaps some magical function on types that chops up the chain into the set of all suffixes is more useful: Suffixes(T1 => ... => Tn) Implementing this is well beyond my Scala abilities at the moment. Any hints as to how to go about doing so would be appreciated. Whether this can be done with advanced usage of Scala's existing type system or through a compiler plugin or neither, I do not know. As has been noted in the comments below, calling the result a "union type" is not a perfect fit for this use case. I don't know what else to call it, but that's the closest idea I have at the moment. Do other languages have special support for this idea? How would this work in Coq and Agda? Naming this problem and understanding where it sits with respect to the bigger picture (of type theory, decidability, and so forth) is more important to me than having a working implementation of ANSWER, though both would be nice. Bonus points to anyone who can draw connections to Scalaz, Monoids, or Category Theory in general. A: Your function expects exactly 4 Int arguments. foldLeft is a function that applies to an arbitrary number of elements. You mention List(1,2,3,4) but what if you have List(1,2,3,4,5) or List()? List.foldLeft[B] also expects a function to return the same type B, but in your case Int and some Function1[Int, _] is not the same type. Whatever solution you come up with would not be general either. For instance what if your function is of type (Int, Float, Int, String) => Int? You would then need a List[Any] So it's definitely not a job for List.foldLeft. With that in mind (warning very un-scala code): class Acc[T](f: Function1[T, _]) { private[this] var ff: Any = f def apply(t: T): this.type = { ff = ff.asInstanceOf[Function1[T,_]](t) this } def get = ff match { case _: Function1[_,_] => sys.error("not enough arguments") case res => res.asInstanceOf[T] } } List(1,2,3,4).foldLeft(new Acc(f.curried))((acc, i) => acc(i)).get // res10: Int = 10 A: This turns out to be quite a bit simpler than I initially expected. First we need to define a simple HList, sealed trait HList final case class HCons[H, T <: HList](head : H, tail : T) extends HList { def ::[H1](h : H1) = HCons(h, this) override def toString = head+" :: "+tail.toString } trait HNil extends HList { def ::[H1](h : H1) = HCons(h, this) override def toString = "HNil" } case object HNil extends HNil type ::[H, T <: HList] = HCons[H, T] Then we can define our fold-like function inductively with the aid of a type class, trait FoldCurry[L <: HList, F, Out] { def apply(l : L, f : F) : Out } // Base case for HLists of length one implicit def foldCurry1[H, Out] = new FoldCurry[H :: HNil, H => Out, Out] { def apply(l : H :: HNil, f : H => Out) = f(l.head) } // Case for HLists of length n+1 implicit def foldCurry2[H, T <: HList, FT, Out] (implicit fct : FoldCurry[T, FT, Out]) = new FoldCurry[H :: T, H => FT, Out] { def apply(l : H :: T, f : H => FT) = fct(l.tail, f(l.head)) } // Public interface ... implemented in terms of type class and instances above def foldCurry[L <: HList, F, Out](l : L, f : F) (implicit fc : FoldCurry[L, F, Out]) : Out = fc(l, f) We can use it like this, first for your original example, val f1 = (i : Int, j : Int, k : Int, l : Int) => i+j+k+l val f1c = f1.curried val l1 = 1 :: 2 :: 3 :: 4 :: HNil // In the REPL ... note the inferred result type scala> foldCurry(l1, f1c) res0: Int = 10 And we can also use the same unmodified foldCurry for functions with different arity's and non-uniform argument types, val f2 = (i : Int, s : String, d : Double) => (i+1, s.length, d*2) val f2c = f2.curried val l2 = 23 :: "foo" :: 2.0 :: HNil // In the REPL ... again, note the inferred result type scala> foldCurry(l2, f2c) res1: (Int, Int, Double) = (24,3,4.0) A: Ok no scalaz and no solution but an explanation. If you use your f.curried.apply with 1 and then with 2 arguments in the REPL observe the return-result types DO actually differ each time! FoldLeft is quite simple. It's fixed in it's type with your starting argument which is f.curried and since that has not the same signature as f.curried.apply(1) it doesn't work. So the starting argument and the result HAVE to be of the same type. The type hast to be consistent for the starting-sum element of foldLeft. And your result would be even Int so that would absolutely not work. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: LDAP : Check if a user is member of a group I found several sample on Stackoverflow and over the web but any work. I'd like to check is a user is member of a specific group (or subgroup). When I try with a username who not exist in the Active Directiory, I get an Exception (normal, see the code) Below the current code I use : using System; using System.DirectoryServices; using System.Collections.Generic; static class Program { public static string GetUserContainerName(string userName) { DirectoryEntry entry = new DirectoryEntry("LDAP://xxxxxxx:389/DC=be,DC=kb,DC=int"); DirectorySearcher mySearcher = new DirectorySearcher(entry); mySearcher.Filter = string.Format("(&(sAMAccountName={0}))", userName); mySearcher.SearchScope = SearchScope.Subtree; //Search from base down to ALL children. SearchResultCollection result = mySearcher.FindAll(); if (result.Count == 0) throw new ApplicationException(string.Format("User '{0}' Not Found in Active Directory.", userName)); return result[0].GetDirectoryEntry().Name.Replace("CN=", string.Empty); } public static bool IsUserMemberOfGroup(string username, string groupname) { DirectoryEntry entry = new DirectoryEntry("LDAP://xxxxxxx.be.kb.int:389/DC=be,DC=kb,DC=int"); DirectorySearcher mySearcher = new DirectorySearcher(entry); mySearcher.Filter = string.Format(String.Format("(member:1.2.840.113556.1.4.1941:=(cn={0},cn=users,DC=be,DC=kb,DC=int))", username), GetUserContainerName(username)); mySearcher.SearchScope = SearchScope.Subtree; //Search from base down to ALL children. SearchResultCollection result = mySearcher.FindAll(); for (int i = 0; i < result.Count - 1; i++) { if (result[i].Path.ToUpper().Contains(string.Format("CN={0}", groupname.ToUpper()))) return true; //Success - group found } return false; } static void Main(string[] args) { var res = IsUserMemberOfGroup("MyUSer", "MY_GROUP_TO_CHECK"); Console.WriteLine(res.ToString()); } } A: Why not use what is already in the framework. Take a look at this: http://msdn.microsoft.com/en-us/library/fs485fwh(VS.85).aspx WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); principal.IsInRole("role name"); A: [Have a look in LDAP_MATCHING_RULE_IN_CHAIN in Search Filter Syntax, I also give samples of code si SO. ----Edited------ Here is a proof of concept : user1 is not a direct member of group MonGrpSec2 but belongs to MonGrpSec that belongs to MonGrpSec2. The code show you group MonGrpSec2. You can find all the groups a user belongs to (recursively). static void Main(string[] args) { /* Connection to Active Directory */ string sFromWhere = "LDAP://WM2008R2ENT:389/dc=dom,dc=fr"; DirectoryEntry deBase = new DirectoryEntry(sFromWhere, "dom\\jpb", "passwd"); /* To find all the groups that "user1" is a member of : * Set the base to the groups container DN; for example root DN (dc=dom,dc=fr) * Set the scope to subtree * Use the following filter : * (member:1.2.840.113556.1.4.1941:=cn=user1,cn=users,DC=x) */ DirectorySearcher dsLookFor = new DirectorySearcher(deBase); dsLookFor.Filter = "(member:1.2.840.113556.1.4.1941:=CN=user1 Users,OU=MonOu,DC=dom,DC=fr)"; dsLookFor.SearchScope = SearchScope.Subtree; dsLookFor.PropertiesToLoad.Add("cn"); SearchResultCollection srcGroups = dsLookFor.FindAll(); /* Just to know if user is present in a special group */ foreach (SearchResult srcGroup in srcGroups) { if (srcGroup.Path.Contains("CN=MonGrpSec2")) Console.WriteLine("{0}", srcGroup.Path); } Console.ReadLine(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7606589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CROSS-DOMAIN - Retrieve Page Source Hi I have a project here at work where we need a specific value from another domain I do not have access to change (So I can't do nested iframes, or CORS). We need to keep Session/Cookie state the same to get the required data from the page as the token changes based on the user on the page. So a server side solution wouldn't work. What is the best way to go about this, the following is what the page source is in it's entirety. I need to retrieve the FF321332 value {"<!--":"","token":"FF321332","expire":1317448445,"":"--><body onload=document.body.innerHTML=clear>"} Some things I've tried so far are Dynamic Script Tags "It throws a JS error Unexpected token : error, Jquery (.getScript ) this throws the same error, any other form of .get or xhr will throw a Cross Domain Error. I feel like I was on the right track with the .getScript or Dynamic Script Tags as it almost wants to read it in. But if I can get around the Unexpected token error and just read it in as text (if this is possible) I can just parse out the variable as normal text. Any assistance in this would be greatly appreciated. A: JSONP allows you to do what you are trying to do. Check out the jQuery doc on how to make your .get use JSONP to side step the browser cross-domain enforcement. Essentially, when you do $.getJSON, if the url has a piece that says "callback=" + whatever, then it will treat it as jsonp instead of the standard getjson. Good luck. A: Don't think you can get past the error using script tags, because normally, once the "javascript" specified in the src attribute gets downloaded it also gets executed. You said you can't use a server side solution because you need to preserve state? Well you can do that using curl and a cookie jar. Never tried this before but in theory it should work: Basically all you need to do is setup a curl request to the remote domain to accept cookies and store those in a file (cookie jar) and then do a second request to fetch the page passing along the previous obtained cookies. Give it a try, maybe it will work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible: array in record I have next arrays NAMES1: array[0..1] of string = ('NO1','NAME1'); NAMES2: array[0..1] of string = ('NO2','NAME2'); and a record structure TMyRec = record( Name: ????; ); As result I need to declare a constant array of records like following const StringArraysList: array[0..1] of TMyRec = ( (Name: NAMES1), (Name: NAMES2) ); The question is what type should I select for Name in TMyRec? A: You could declare a new type TName = array[0..1] of string; and use that in your record declaration. Your declaration then becomes type TName = array[0..1] of string; TMyRec = record Name: TName; end; const StringArraysList: array[0..1] of TMyRec = ( (Name: ('NO1','NAME1')), (Name: ('NO2','NAME2')) ); A: You need to do it like this: type TTwoNames = array[0..1] of string; TMyRec = record Names: TTwoNames; end; const StringArraysList: array[0..1] of TMyRec = ( (Names: ('NO1','NAME1')), (Names: ('NO2','NAME2')) ); You would prefer to write the final declaration as const NAMES1: TTwoNames = ('NO1','NAME1'); NAMES2: TTwoNames = ('NO2','NAME2'); StringArraysList: array[0..1] of TMyRec = ( (Names: NAMES1), (Names: NAMES2) ); But that results in [DCC Error] Unit1.pas(38): E2026 Constant expression expected Some Delphi constants are not as constant as you would like them to be! The documentation for record constants states that The values must be represented by constant expressions. The documentation for typed constants states that Typed constants cannot occur in constant expressions. Put these two rules together and we have E2026.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: switch case with display tag I want to display various data in Display Tag column according to what I get from Session. How can I integrate switch case with display tag <display:column>? I want to display AAA if the unit value I get from session is 1 etc. Here is what I want to do. switch(List.unit){ case 1: unit = "AAA"; break; case 2: unit = "BBB"; break; case 3: unit = "CCC"; break; default: unit = "undefined"; break; } Thanks ahead. A: You do it with displaytag exactly as you would do it without it. Just compute the desired unit in the servlet/action dispatching to your JSP and store this unit in some bean in the request. Then access this bean in the JSP : <display:column>${theBeanStoredInTheRequest.unit}</display:column> Or compute it in the JSP itself, using the JSTL, but it's more verbose: <display:column> <c:choose> <c:when test="${sessionScope.unit == 1}">AAA</c:when> <c:when test="${sessionScope.unit == 2}">BBB</c:when> <c:when test="${sessionScope.unit == 3}">CCC</c:when> <c:otherwise>undefined</c:otherwise> </c:choose> </display:column>
{ "language": "en", "url": "https://stackoverflow.com/questions/7606599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Build system for an embedded C/C++ project I am looking for a high-level build system/tool that can help organise my embedded C project into "modules" and "components". Note that these two terms are highly subjective so my definitions are given below. * *A module is a cohesive collection of c and h files but with only one public h file that is visible to other modules. *A component (or a layer) on the other hand is a collection of modules (e.g. Application layer, Library layer, Driver layer, RTOS layer etc.). The build system/tool should - * *Prevent cyclic dependencies between components and modules (cyclic dependencies inside modules is okay) *prevent access to private barriers of a module. If other modules try to include a header file that is private to a module, the build system must throw an error. However, files within a private barrier must be able to include other files inside that barrier. *support building and executing of unit tests automatically (fast feedback loop for TDD) on host *support unit tests to be run on target simulator *support code static analysis *support code generation *support code duplication detection (enforce DRY principle) *support code beautification *support generation of unit test code coverage metrics *support generation of code quality metrics *be platform-independent I could write my own build tool and spend a lot of time on it. However, that is not my area of expertise and I'd rather not re-invent the wheel if someone has already created such a tool. A: The conventional way of achieving that would be to place the source code for each module into a separate directory. Each directory can contain all the source and header files for the module. The public header for each module can be placed into a separate, common directory of headers. I'd probably use a symlink from the common directory to the relevant module directory for each header. The compilation rules simply state that no module may include headers from other modules except for the headers in the common directory. This achieves the result that no module can include headers from another module - except for the public header (thus enforcing the private barriers). Preventing cyclic dependencies automatically is not trivial. The problem is that you can only establish that there is a cyclic dependency by looking at several source files at a time, and the compiler only looks at one at a time. Consider a pair of modules, ModuleA and ModuleB, and a program, Program1, that uses both modules. base/include ModuleA.h ModuleB.h base/ModuleA ModuleA.h ModuleA1.c ModuleA2.c base/ModuleB ModuleB.h ModuleB1.c ModuleB2.c base/Program1 Program1.c When compiling Program1.c, it is perfectly legitimate for it to include both ModuleA.h and ModuleB.h if it makes use of the services of both modules. So, ModuleA.h cannot complain if ModuleB.h is included in the same translation unit (TU), and neither can ModuleB.h complain if ModuleA.h is included in the same TU. Let us suppose it is legitimate for ModuleA to use the facilities of ModuleB. Therefore, when compiling ModuleA1.c or ModuleA2.c, there can be no issue with having both ModuleA.h and ModuleB.h included. However, to prevent cyclic dependencies, you must be able to prohibit the code in ModuleB1.c and ModuleB2.c from using ModuleA.h. As far as I can see, the only way to do this is some technique that requires a private header for ModuleB that says "ModuleA is already included" even though it isn't, and this is included before ModuleA.h is ever included. The skeleton of ModuleA.h will be the standard format (and ModuleB.h will be similar): #ifndef MODULEA_H_INCLUDED #define MODULEA_H_INCLUDED ...contents of ModuleA.h... #endif Now, if the code in ModuleB1.c contains: #define MODULEA_H_INCLUDED #include "ModuleB.h" ...if ModuleA.h is also included, it will declare nothing... ...so anything that depends on its contents will fail to compile... This is far from automatic. You could do an analysis of the included files, and require that there is a loop-less topological sort of the dependencies. There used to be a program tsort on UNIX systems (and a companion program, lorder) which together provided the services needed so that a static (.a) library could be created that contained the object files in an order that did not require rescanning of the archive. The ranlib program, and eventually ar and ld took on the duties of managing the rescanning of a single library, thus making lorder in particular redundant. But tsort has more general uses; it is available on some systems (MacOS X, for instance; RHEL 5 Linux too). So, using the dependency tracking from GCC plus tsort, you should be able to check whether there are cycles between modules. But that would have to be handled with some care. There may be some IDE or other toolset that handles this stuff automatically. But normally programmers can be disciplined enough to avoid problems - as long as the requirements and inter-module dependencies are carefully documented. A: For a general solution, I'd fully recommend to go with Jonathan Leffler's solution. However, if you absolutely need an automated test whether your modules are self-contained and isolated, you might give Debian's build system a try. Package each module into a Debian package (which is done very quickly when it's already autoconf'd), declare Build-Depends properly and build the packages inside a pbuilder environment. This ensures that only public headers of each module are available (because only those are in the .deb packages that are installed by pbuilder to build the other packages) and there are excellent tools to look at Debian package trees and make sure they are cycle-free. However, this is probably over-kill. Just stating it for completeness and the case you definitely need an automated solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to get java version using single command in Windows command prompt? I need to fetch java version 1.6.0_26 from the below java -version output java version "1.6.0_26" Java(TM) SE Runtime Environment (build 1.6.0_26-b03) Java HotSpot(TM) Client VM (build 20.1-b02, mixed mode, sharing) Please help me getting 1.6.0_26 Note: I don't need power shell or any external programs UPDATE I came up with java -version 2>&1 | findstr /i "version" which give me below output java version "1.6.0_22" now even a java way of pattern matching or regex will work for me :) A: You can run the solution from the question Pangea linked to in a single line: c:\>for /f "tokens=3" %g in ('java -version 2^>^&1 ^| findstr /i "version"') do @echo %g "1.6.0_24" c:\>for /f "tokens=3" %g in ('java -version 2^>^&1 ^| findstr /i "version"') do ( @set v=%g & @echo %v:~1,8% ) 1.6.0_24 I just checked and it seems my second example only works with Windows7, the following works for me on Windows XP (so it should work on Windows7 as well) for /f "tokens=3" %g in ('java -version 2^>^&1 ^| findstr /i "version"') do ( @echo %~g ) A: you can do it from single line from command promt C:>java -version A: You can try: java -version 2>&1 | awk '/version/ {print $3}' | egrep -o '[^\"]*' A: for /f tokens^=2-5^ delims^=.-_^" %j in ('java -fullversion 2^>^&1') do @set "jver=%j%k%l%m" This will store the java version into jver variable and as integer And you can use it for comparisons .E.G if %jver% LSS 16000 echo not supported version .You can use more major version by removing %k and %l and %m.This command prompt version. For .bat use this: @echo off PATH %PATH%;%JAVA_HOME%\bin\ for /f tokens^=2-5^ delims^=.-_^" %%j in ('java -fullversion 2^>^&1') do set "jver=%%j%%k%%l%%m" According to my tests this is the fastest way to get the java version from bat (as it uses only internal commands and not external ones as FIND,FINDSTR and does not use GOTO which also can slow the script). Some JDK vendors does not support -fullversion switch or their implementation is not the same as this one provided by Oracle (better avoid them). A: I wrote the below function to fetch java version 1.6.0_26 String regexMatch(String myInput, String myRegex) { String ResultString Pattern regex Matcher regexMatcher regex = Pattern.compile(myRegex, Pattern.DOTALL); regexMatcher = regex.matcher(myInput); List<String> matchList = new ArrayList<String>(); while (regexMatcher.find()) { matchList.add(regexMatcher.group()); } for(int i=0;i<matchList.size();i++) { myInput=myInput.replaceAll( matchList[i], '') } return myInput; } and call rs=regexMatch(rs,"[a-zA-Z\"]+") where rs="java version \"1.6.0_26\"" A: Based on @a_horse_with_no_name but detecting first if command exists. where java > nul if %ERRORLEVEL% neq 0 ( set java_v="Command not found" ) else ( for /f "tokens=3" %%g in ('java -version 2^>^&1 ^| findstr /i "version"') do set java_v=%%g ) echo Java: %java_v:~1,8%
{ "language": "en", "url": "https://stackoverflow.com/questions/7606607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Ruby on Rails timestamp is being converted into numeric by PostgreSQL on Heroku I will start out by saying there is a question similar to mine: heroku Postgres error - operator does not exist timestamp without timezone = integer but it did not solve my problem. What I am looking at is this error in the worker on Heroku: [Worker(host:026e9a98-87ae-4c0c-94c8-315843e68ac1 pid:1)] Buzz#digest! failed with ActiveRecord::StatementInvalid: PGError: ERROR: operator does not exist: timestamp without time zone = numeric LINE 1: ...FROM "buzz_topics" WHERE ("buzz_topics"."version" = 0.069980... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. SELECT * FROM "buzz_topics" WHERE ("buzz_topics"."version" = 0.0699802335812795) AND ("buzz_topics".buzz_id = 696) LIMIT 1 - 0 failed attempts The problem is, somehow Ruby on Rails or PostgreSQL converted a timestamp into this weird decimal. The query it is trying to do in Ruby on Rails looks something like this: BuzzTopic.first( :conditions => [ "version = ?", Feature.current_version ] ) BuzzTopic has a named_scope called current that looks similar to this. Feature.current_version is just a timestamp: >> Feature.current_version => Mon, 26 Sep 2011 07:06:41 UTC +00:00 BuzzTopic.version is also just a timestamp. Using that query in heroku run console works, however it does not work when the worker runs it. Here is a list of things I have tried so far: I tried converting Feature.current_version into a format like "2011-09-26 07:06:41": def self.current_version # original last_feature = enabled.last last_feature.present? ? last_feature.version : nil end def self.current_version last_feature = enabled.last last_feature.present? ? last_feature.version.utc.to_formatted_s( :db ) : nil end and tried different named_scopes for BuzzTopic: named_scope :current, lambda { { :conditions => { :version => Feature.current_version } } } # original named_scope :current, lambda { { :conditions => [ "version = to_timestamp( ? )", Feature.current_version ] } } named_scope :current, lambda { { :conditions => [ "version = timestamp ?", Feature.current_version ] } } None of these worked, and I definitely tried some others that I forgot about. I am stuck and don't know what to do, so I came here. Can anyone help? A: Actually, the problem was due to some code that I left unchanged when I was solving another problem. Instead of passing a timestamp and a decimal in a block, it only passed the decimal. Now that I fixed that, this problem is solved.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606611", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Oracle Apex integration using/from ASP.NET C#; DB-Oracle I'm looking for a simple guide how to use Oracle Apex to show info from DB integrating it with .NET using c#. So I hope you could share any tutorials about APEX & .NET integration, links exmaples, maybe a plan how would you connect these two technologies to show information in a apealing way to User.: My plan: 1.Connect to Oracle db from .net 2.Use webservices(no idea how yet..., I understan how webservices work but...) 3.Integrate with Apex(???), than we could give Oracle DB schemas through .net/webservices and Apex could show information in the Browser I'm looking for practical suggestions! explanation how to do this, tutorials, links, books, examples, links to examples... Peace, WiseMokn p.s. any great, practical, with lots of examples, book about apex&c# would be nice A: See the articles on working with Oracle and Microsoft enterprise library also this tutorial from devstuff see Oracle Forum also One SO question regarding this is here A: If you are only wanting apex for reporting, you can pass parameters in the apex URL to the apex report to do some basic things like filter. I'm not very clear on what you are trying to achieve.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Django ImageField "Upload a valid image. The file you uploaded was either not an image or a corrupted image." I have PIL installed, however whenever I try to upload a .png file to an image field through the Django Admin for my model, I get this error: "Upload a valid image. The file you uploaded was either not an image or a corrupted image." Other image types work fine. I have tried several different PNG files. I have tried rebuilding PIL after installing pypng, libpng-dev, etc.. and am on ubuntu server. A: This issue was solved by using pip to install "pillow" instead of "pil" which allows easy deployment to virtualenv. A: When you compile PIL it should say if it has been compiled with PNG support or not, but if you have problems installing it yourself, I would recommend that you use the version that comes with ubuntu. It's strangely named but easily installed with: apt-get install python-imaging A: I have found that building PIL on Ubuntu can cause problems because libpng is in a non standard location, and PIL can't find it. In the folder that PIL has been downloaded to, edit setup.py. Find the following line: JPEG_ROOT = None and change it to JPEG_ROOT = '/usr/lib/i386-linux-gnu/' then rebuild PIL and check for the messages near the end that PNG support is included. I know it's odd to modify JPEG_ROOT when you want to add PNG support, but setup.py will look in JPEG_ROOT for libpng too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to call generic activity finish I have a public class which has some common generic functions, like e.g. for displaying dialogs in my application. I made a generic alertButtonDialog function and want to call it in activities whenever I'm using dialogs. I am very new to Java so please excuse me if it's very basic. public static class AlertDialogs{ public static void alertButtonDialog(Activity activity, Context context, String title, String message, String positiveButton, String negativeButton) { AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context); alertBuilder.setTitle(title); alertBuilder.setMessage(message); alertBuilder.setPositiveButton(positiveButton, new OnClickListener() { public void onClick(DialogInterface dialog, int which) { Activity.this.finish(); // *?? How to do this part ??* // the activity to be finished is the activity which calls this function } }) } } Later in any other activity, whenever I'm displaying a dialog, I would just do AlertDialogs.alertButtonDialog(...all my Strings...) This is only for convenience accessing. A: In your alertButtonDialog function, define the Activity activity argument as final. Then, from within the onClick listener invoke activity.finish();. public static void alertButtonDialog(final Activity activity, Context context, String title, String message, String positiveButton, String negativeButton) { AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context); ... alertBuilder.setPositiveButton(positiveButton, new OnClickListener() { public void onClick(DialogInterface dialog, int which) { activity.finish(); } }) } Note that you do not need both an Activity and a Context -since the former extends the later-, unless you are expecting to pass activity as null somewhere.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to define thread-local local static variables? How to define local static variables (that keeps its value between function calls) that are not shared among different threads? I am looking for an answer both in C and C++ A: Just use static and __thread in your function. Example: int test(void) { static __thread a; return a++; } A: The current C standard has no model for threads or alike, so you can't get an answer, there. The utility foreseen by POSIX for that is pthread_[gs]etspecific. The next version of the C standard adds threads and has a concept of thread local storage. A: You can also use the C++11 thread local storage additions if you have access to C++11. A: on Windows using Windows API: TlsAlloc()/TlsSetValue()/TlsGetValue() on Windows using compiler intrinsic: use _declspec(thread) on Linux (other POSIX???) : get_thread_area() and related A: You can make your own thread specific local storage as singleton per thread ID. Something like this: struct ThreadLocalStorage { ThreadLocalStorage() { // initialization here } int my_static_variable_1; // more variables }; class StorageManager { std::map<int, ThreadLocalStorage *> m_storages; ~StorageManager() { // storage cleanup std::map<int, ThreadLocalStorage *>::iterator it; for(it = m_storages.begin(); it != m_storages.end(); ++it) delete it->second; } ThreadLocalStorage * getStorage() { int thread_id = GetThreadId(); if(m_storages.find(thread_id) == m_storages.end()) { m_storages[thread_id] = new ThreadLocalStorage; } return m_storages[thread_id]; } public: static ThreadLocalStorage * threadLocalStorage() { static StorageManager instance; return instance.getStorage(); } }; GetThreadId(); is a platform specific function for determining caller's thread id. Something like this: int GetThreadId() { int id; #ifdef linux id = (int)gettid(); #else // windows id = (int)GetCurrentThreadId(); #endif return id; } Now, within a thread function you can use it's local storage: void threadFunction(void*) { StorageManager::threadLocalStorage()->my_static_variable_1 = 5; //every thread will have // his own instance of local storage. }
{ "language": "en", "url": "https://stackoverflow.com/questions/7606624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Android Map View Issues on emulator i have create app wherein i use the MapView to render the google maps on the device. this works fine. though had few issues with the "X" marks appearing on the screen, that was resolved by commenting/removing the setSatelliteView(true) and setStreetView(true). now i mainly want the map to be rendered even on the emulator as few examples portray it. i have done the following: 1. map API key is correct in all pages. 2. apk generated using the debugKeystore 3. added the proxy setting in the emulator and able to access internet using emulator. 4. added -http-proxy http://192.68.100.101:8080/ in the run configuration-->target tab-->additional command line. but again somehow i am unable to get the map rendered on the emulator. pls help. thanks in advance! A: I faced the issue where I was behind corporate firewall. I asked the IT team to provide a proxy server which can connect Internet and does not require any authentication. This was a tough request but was eventually fulfilled. By settig proxy details in Emulator for Android 3.1 I was able to run the map on Emulator. The proxy does not work on any Android version less than 3.1 A: Can you confirm the following Internet is working on your machine Your PC is not behind any corporate \ personel firewall You do not use proxy to connect to Internet You can access Internet using emulator
{ "language": "en", "url": "https://stackoverflow.com/questions/7606625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .NET Entity Framework - IEnumerable VS. IQueryable Please see this line of code. This is an invocation of a stored procedure, which returns an ObjectResult<long?>. In order to extract the long values I added the Select: dbContext.FindCoursesWithKeywords(keywords).Select(l => l.Value); Based on intellisense this Select returns IEnumerable<long>. I'm not sure whether I read it somewhere or maybe just got used to this assumption - I always thought that when the EF API returns an IEnumerable (and not IQueryable) then this means that the results have been materialized. Meaning they've been pulled from the database. I found out today that I was wrong (or maybe that's a bug?). I kept getting the error "New transaction is not allowed because there are other threads running in the session" Basically, this error tells you that you're trying to save changes while the db reader is still reading records. Eventually I solved it by (what I considered a long shot) and added ToArray() call to materialize the IEnumerable<long>... So - the bottom line - should I expect IEnumerable results from EF to contain results that haven't materialized yet? If yes then is there a way to know whether an IEnumerable has been materialized or not? Thanks and apologies if this is one of those 'duhhh' questions... :) A: IQueryable is used when you are using Linq-to-entities = you are building declarative LINQ query in your application which will be interpreted by LINQ provider as SQL and executed on the server. Once the query is executed (iterated) it will turn to become IEnumerable and objects will be materialized as needed for iteration = not immediately. Once you call stored procedure you are not using Linq-to-entities because there is no declarative query built in your application. The query / SQL already exists on database server and you are just invoking it. This will return IEnumerable but again it will not materialize all results immediately. Results will be materialized as iterated. This is principle of database cursor / or .NET data reader when you explicitly ask for fetching object. So if you call something like this: foreach (var keyword in dbContext.FindCoursesWithKeywords(keywords) .Select(l => l.Value)) { ... } You are fetching courses one by one (btw. why to load whole course if you are interested only in keywords?). Until you complete or break the loop your data reader is opened to fetch records. If you instead call this: foreach (var keyword in dbContext.FindCoursesWithKeywords(keywords) .ToList() // or ToArray .Select(l => l.Value)) { ... } You will force query to materialize all results immediately and loop will perform on collection in memory instead of opened database reader. Difference between IEnumerable and IQueryable is not in the way how data are fetched because IQueryable is IEnumerable. The difference is in backing construct (something must implement these interfaces). A: Working on an IEnumerable<T> means that all further operations will happen in C# code, i.e. linq-to-objects. It does not mean that the query has already executed. Once you degrade to linq-to-objects all data left at this point needs to be fetched from the database and sent to .net. This can degrade performance drastically(For example database indexes won't be used by linq-to-objects), but on the other hand linq-to-objects is more flexible, since it can execute arbitrary C# code instead of being limited by what your linq provider can translate to SQL. A IEnumerable<T> can be both a deferred query or already materialized data. The standard linq operators typically are deferred, and ToArray()/ToList() are always materialized. A: IEnumerable will not hydrate until materialized. If calling a stored procedure I would think that there is no further filter required, I mean you send parameters to a stored procedure to produce the desired subset of data returned. IEnumerable tied to a stored procedure is fine. However if you are fetching the entire contents of a table, then filtering in the application you should have a strategy. Like, do not ToList() the IEnumerable of the table, you will materialize all rows. Sometimes this will cause an out of memory exception. Besides why consume memory without reason. Use IQueryable against the context, that way you can filter the table at the Data Source, and not in the application. In answer, you have to materialize it. IEnumerable is an interface, only materializing it will "initialize" its type and produce something in my understanding. A: IEnumerable : LINQ to Object and LINQ to XML. IQueryable : LINQ to SQL
{ "language": "en", "url": "https://stackoverflow.com/questions/7606633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: Blackberrry Twitter Integration to tweet photos I am developing an application where user can share photos to Facebook and Twitter, for BlackBerry Storm and Torch series phones running OS 5.0. For Facebook I used the strawberry project. But for Twitter I am not able to find any library which can authorize the user using oauth 1.0 as well as tweet photos. I tried implementing oauth 1.0 in my code without using any libs but failed. A: Use http://kenai.com/projects/twitterapime/downloads/directory/1.7` to download a RIM Twitter api. Unzip and read index.html for guidance. Update with working example http://kenai.com/projects/twitterapime/downloads/directory/Miscellaneous
{ "language": "en", "url": "https://stackoverflow.com/questions/7606634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why is my clockwise sorting of Vector3s inconsistent? I've attempted to write a Comparer class for Vector3s (or, rather, VertexPositionNormalTextures) which will sort a list of them into clockwise order in order to fix my backface culling issues. I've tried to adapt a very common method on the web which gets a signed angle between two vectors. However, at runtime my list complains that the sorting method is inconsistent, which is to say that either two items are compared inconsistently on different passes, or an item is compared to itself and not found equal. Here's the comparer class: public class ClockwiseSorter : IComparer<VertexPositionNormalTexture> { private Vector3 center; public ClockwiseSorter(Vector3 c) { center = c; } public int Compare(VertexPositionNormalTexture a, VertexPositionNormalTexture b) { Vector3 normal = Vector3.Cross(a.Position - center, b.Position - center); normal.Normalize(); double theta = GetSignedAngleBetween2DVectors(a.Position - center, b.Position - center, Vector3.Cross(a.Position - center, normal)); if (theta > 0) return -1; else if (theta < 0) return 1; else return 0; } /// Find the angle between two vectors. This will not only give the angle difference, but the direction. /// For example, it may give you -1 radian, or 1 radian, depending on the direction. Angle given will be the /// angle from the FromVector to the DestVector, in radians. /// </summary> /// <param name="FromVector">Vector to start at.</param> /// <param name="DestVector">Destination vector.</param> /// <param name="DestVectorsRight">Right vector of the destination vector</param> /// <returns>Signed angle, in radians</returns> /// <remarks>All three vectors must lie along the same plane.</remarks> public static double GetSignedAngleBetween2DVectors(Vector3 FromVector, Vector3 DestVector, Vector3 DestVectorsRight) { FromVector.Normalize(); DestVector.Normalize(); DestVectorsRight.Normalize(); float forwardDot = Vector3.Dot(FromVector, DestVector); float rightDot = Vector3.Dot(FromVector, DestVectorsRight); // Keep dot in range to prevent rounding errors forwardDot = MathHelper.Clamp(forwardDot, -1.0f, 1.0f); double angleBetween = Math.Acos(forwardDot); if (rightDot < 0.0f) angleBetween *= -1.0f; return angleBetween; } } I get the center vector by averaging the values of all the vectors: private Vector3 AverageVectors(List<VertexPositionNormalTexture> vectors) { Vector3 sum = Vector3.Zero; foreach (VertexPositionNormalTexture vector in vectors) sum += vector.Position; return (sum / vectors.Count); } Am I screwing up somewhere, not thinking about this correctly? Or have I calculated the normal or center incorrectly? Backface culling has been nothing but a headache for me, I'm kind of desperate to move on... A: If you have a triangle with vertex A,B and C, the triangle normal is calcultated with the cross product operation N = (B-A) x (C-A) now you have to determine what direction is facing the normal. for this can be useful the center of the mesh as you use in your code, though if mesh is not convex it can provide erroneous results. You have to determine the angle between the normal and the vector build from the center of triangle to the center of the mesh. TriangleCenter= (A+B+C) / 3; P = MeshCenter - TriangleCenter; P.Normalize(); N.Normalize(); the dot product d = P.N = |P||N|.cos(alfa) if (d>0) P and N are in the same direction (AntiClockWise order) if (d<0) P and N are in opposite direction (Clockwise order)
{ "language": "en", "url": "https://stackoverflow.com/questions/7606638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change background color of input text field using JavaScript How do I change the background color of a input text field using java script? I want to insert it in a form validation function like this: function validateForm() { var x=document.forms["form1"]["username"].value; if (x==null || x=="") { document.forms["form1"]["username"].style.backgroundColor = Black } } Also, is there a way to do form validation with php without creating two pages? WHat would you recommend? Using JavaScript or php for validating the user input of a form? I already have a php process form which checks whether the user supplied the correct details like the password etc. Thank you for any help A: You are taking the value of the text input. You need to refer to the control itself: function validateForm() { var ctrl = document.forms["form1"]["username"]; var x=ctrl.value; if (x==null || x=="") { ctrl.style.backgroundColor = color; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7606646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ruby Rails Session timeout I'm using Ruby1.8.7 & rails 3.1.0. I want to increase session timeout. I already gone through the existingg threads but didn't helped me. Please guide. A: You're most likely using devise. In this case, follow these suggestions. Ensure you add :timeoutable as a module in the devise model as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scroll not working in ios5 xcode 4.2 I had an older example which had a scrolling tableview. The scroll bars are not appearing any longer when I moved to the new xcode/ios combination. In fact, I tried the other sample code on developer site which had scrolling and none of them are working. I was wondering if there is anything I am missing out on or if there is an already known bug which I should be aware of.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery Ajax request doesn't return data I have a group of button, I want click each one, send data to a processing page, then return data to the self html and change class click to more. In any case, my code have no reture data. I have checked in chrome - network, I can see the ajax process success, even add an alert in success: function, I also can get it. Where am I wrong? index.php $(document).ready(function(){ $(".click").live('click',function() { $.ajax({ type: "POST", url: "add.php", data: "add=ccc", dataType: "html", success: function(data){ //alert('success'); $(this).html(data).addClass('more').removeClass('click'); } }); }); }); <a class="click">bbb</a> add.php <?php echo $_POST['add']; ?> A: this doesn't point to the link inside the success function. Add var self = this; before the $.ajax call and use self instead of this inside the callback. Another option would be using context: this in the $.ajax options.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: php function to set color by variable Anyway to make a php function out of this? It seems the second set of variables kills any function I try to write. $flow = (15); $low = (10); $good =(20); $high =(30); if ($flow <= $low) $class = "tdy"; else if (($flow > $low) && ($flow <= $good)) $class = "tdg"; else if ($flow >= $high) $class = "tdr"; I've tried to make a function with this but it just fails to the high variable. Alone the if else statement runs fine with the variables. It would save a ton of time if I could just reset the variables and call the if else statement with a function on each instance. A: I think your logic can be more simpler: function getColor($flow, $low, $good) { if ($flow <= $low) return "tdy"; if ($flow <= $good) return "tdg"; return "tdr"; } Since the second check ($flow > $low) in the first else if is useless because if that was true, the first if was executed. And of course, if the first else if not get executed, the only option is the last else if which makes it useless to check on. A: function getColor($flow, $low, $good, $high) { if ($flow <= $low) return "tdy"; else if (($flow > $low) && ($flow <= $good)) return "tdg"; else if ($flow >= $high) return "tdr"; } A: <?php $def = array(10=>'tdy',20=>'tdg',30=>'tdr'); foreach(array(9,10,11,19,20,21,29,30,31) as $i) { printf("%02d %s\n", $i, foo($i, $def)); } function foo($val, $sel) { foreach($sel as $k=>$v) { if ( $val<=$k ) { return $v; } } return end($sel); } prints 09 tdy 10 tdy 11 tdg 19 tdg 20 tdg 21 tdr 29 tdr 30 tdr 31 tdr
{ "language": "en", "url": "https://stackoverflow.com/questions/7606658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to make toggle image button instead of UIBarButtonItem in iphone programming? I have to make a button in UINavigationBar, the button should toggle between restart state and cancel state, and it should call -(void)RestartMethod {} at restart state and should call method -(void) cancelMethod {} at cancel state of UIBarButtonItem,both states are using images like start.png and calcel.png I tried by making two images and add and remove targets,b but facing some bad-exec issues, how can I do it? Help! A: item1=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"DoneUp3.png"] style:UIBarButtonItemStylePlain target:self action:@selector(action1)]; item2=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"Pin.png"] style:UIBarButtonItemStylePlain target:self action:@selector(action2)]; -(void)action1{self.navigationItem.rightBarButtonItem = item2;} -(void)action2{self.navigationItem.rightBarButtonItem = item1;} A: Create two buttons with two different targets. When one button is clicked do whatever you want the action to be and replace the button with button number two. If button number two is clicked, replace that with button number 1. A: Why not use a segment control instead of toggle button? Even if you insist on using a single button to toggle, this is how I would achieve it. * *Have a bool declare the initial state BOOL buttonOn = NO; *Embed the first button with initial image pointing to one selector *Inside selector take action based on this boolean. Change state and change this boolean's value too. No need to have two different selectors. Call appropriate functions to do stuff inside this selector. A: i think this can help you: CGRect frameimg = CGRectMake(0, 0, image3.size.width, image3.size.height); UIButton *someButton = [[UIButton alloc] initWithFrame:frameimg]; [someButton setBackgroundImage:[UIImage imageName:@"start.png"] forState:UIControlStateNormal]; [someButton setBackgroundImage:[UIImage imageName:@"calcel.png"] forState:UIControlStateSelected]; [someButton addTarget:self action:@selector(backButtonPress:)forControlEvents:UIControlEventTouchUpInside]; UIBarButtonItem *mailbutton =[[UIBarButtonItem alloc] initWithCustomView:someButton]; self.navigationItem.leftBarButtonItem=mailbutton; [mailbutton release]; New write backButtonPress: method: -(void)backButtonPress:(id)sender{ UIButton *tmpButton = (UIButton *)sender; tmpButton.selected = [tmpButton isSelected]?NO:YES; if (tmpButton.selected) { // call cancelMethod or write RestartMethod code here } else{ // call RestartMethod or write RestartMethod code here } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7606663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WCF service goes to faulted state while deserializing huge amount of data I have an application which consumes WCF services. My problem is I am fetching around 6000 rows from database, my service shows faulted channel error while deserializing huge amount of data. Infact I have increased the attribute values(like maxStringContentLength,maxArrayLength,maxBytesPerRead,maxNameTableCharCount,CloseTimeOut, SendTimeOut etc..) in service app.config, web.config as well as in the web.config of my web application. But still no luck. Can anyone please suggest me what to do in this scenario, so that my service wont go to faulted state. Thanks A: Enabling tracing will certainly tell you exactly what the problem is. One possible suspect is the maxItemsInObjectGraph quota (default = 65536) which you can increase by using a <dataContractSerializer> element in either a service or an endpoint behavior.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I create liferay iframe from jsp Here is a scenario. I am working on a small project and in this, I will be forming a URL based on some condition checks. When the final URL is ready ( in JSP), I have to invoke the liferay iframe and pass this URL to it so that as the JSP is loaded. It should load the newly created liferay iframe with the URL which I have formed. How to do this in the flow ? Is there any means through which liferay iframe can be created ? (Something from liferay taglib) Thanks -Aj A: Got it. Did something like this. <script> function show(which) { var hide = new Array(); hide = document.getElementsByName(which); for (i=0; i<hide.length; i++) { hide[i].style.display = 'inline'; } } function hide(which) { var hide = new Array(); hide = document.getElementsByName(which); for (i=0; i<hide.length; i++) { hide[i].style.display = 'none'; } } </script> <style type="text/css"> iframe { display: none; } </style> <b>Google</b> <input type="button" value="Show" onclick="show('iframe');"> <input type="button" value="Hide" onclick="hide('iframe');"> <iframe src='http://www.google.com' width='100%' height='100%' scrolling='yes' name='iframe'></iframe> Now I can use the show and hide, as I need and use it. These buttons can be used to maximize and minimize the iframe based on the need and more than 1 iframe can be used in a page too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Achartengine X labels with uneven interval of time I am using TimeChartView of AChartEngine 0.7.0 to draw chart. on x-axis there is date and for y-axis there is value for specific date. i am parsing these values from xml so someday I get value of complete last 5 day but someday only of 3 days so when i get value of 3 days, chart shows x-values shifted compared to y-values. also sometimes there is repetition of date due to fix number of x-labels which i have solved. I think i have similar problem to this SO Quest and mostly to this as I want to set X-intervals by using dates. Here Originally from XML,I am having values of date 28.09,27.09,26.09 but it displays as above. A: When the number of (x,y) values are changed suppose from 5 to 3 or vice versa you should first remove the values that repaint the chart public XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset(); dataset.getSeriesAt(0).clear(); // use this to clear your data set dataset.getSeriesAt(0).add(x, y) // use this to add the new x,y values
{ "language": "en", "url": "https://stackoverflow.com/questions/7606667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I get UI_USER_INTERFACE_IDIOM How can I get UI_USER_INTERFACE_IDIOM, I am not clear that how does it work, can anyone please guide me? A: if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { // iPad device } else { // iPhone / iPod touch device } From the Apple Header files: /* The UI_USER_INTERFACE_IDIOM() macro is provided for use when deploying to a version of the iOS less than 3.2. If the earliest version of iPhone/iOS that you will be deploying for is 3.2 or greater, you may use -[UIDevice userInterfaceIdiom] directly. */ #define UI_USER_INTERFACE_IDIOM() ([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] ? [[UIDevice currentDevice] userInterfaceIdiom] : UIUserInterfaceIdiomPhone)
{ "language": "en", "url": "https://stackoverflow.com/questions/7606670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: iOS application upload after rejection I forgot provide demo account information login and password, and my application was rejected with message: .... While your iTunes Connect Application State will still show as Rejected, we don't require a new binary for this type of issue. Please visit iTunes Connect, Manage Your Applications, revise the appropriate metadata values or settings, then click "Submit New Metadata" I add required information to metadata reviews note. But i have not found "Submit New Metadata". I click "ready upload" button, and now application status "Waiting For Upload" When i try upload application binary from XCode 3.2.4 i have a errors: An error occured while processing the http request for the webDAV upload An exception has occured:401 Unauthorized Questions how fix this erorr? And where is "Waiting For Upload" button? A: we don't require a new binary for this type of issue You should not upload new binary. You should just find button "Submit New Metadata" and press it after demo data was entered in Review Notes. A: After the weekend I tried again to upload binary and upload was successfull. After 5 minutes the application status has changed to "In review". I used mac os on virtual machine and reboot only vm. Maybe computer(not vm) reboot decided the problem or maybe error was in itunes side.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: In an Outlook VSTO addin how do I clear the current selection? From within an Outlook VSTO addin I want to clear the current selection. Is there an API for this? A: My current hack it to temporarily select the sent folder. void ClearSelection(IRibbonControl control) { //Here be dragons //Ok this looks like pointless code but it is necessary. //For multiple items we are doing it in a background thread. //There is a "feature" in outlook that means you cant delete //the current selected item from a background thread. //So we need this to clear the selection //and NO "control.Explorer().ClearSelection();" does not work. var explorer = GetExplorer(control); var currentFolder = explorer.CurrentFolder; var session = ThisAddIn.Application.Session; var sentFolder = session.GetDefaultFolder(OlDefaultFolders.olFolderSentMail); explorer.CurrentFolder = sentFolder; explorer.CurrentFolder = currentFolder; } Explorer GetExplorer(IRibbonControl control) { dynamic context = control.Context; var explorer = context.Parent as Explorer; if (explorer == null) { var application = (ApplicationClass)context.Parent; explorer = application.ActiveExplorer(); } return explorer; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7606672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Most efficient way of storing lots of string messages in SQL Server? My app receiving approximately 2000 string messages per second, each message is about 300 characters long. I need to store all messages in a DB. I'm using SQL Express 2008, and .NET. I'm thinking of holding all data in memory till it reaches a certain limit (10000 messages = 5 seconds , for example), and then write it down all at once. This way the data will be written to the hard drive every 5 seconds, instead of every second. Does my approach is good enough? What approach should I use in order to achieve the following results? * *messages are not piling up in memory *Hard drive won't commit suicide :) Note: there is no need to parse the strings, the only thing is to store them by the order they arrived. A: If you describe more thoroughly what you want to do with these massive amounts of data after you have stored them, it will be easier to make a clear suggestion on what to do with it. At the face of it, it sounds like too much data for a relational database to handle. I would rather devise a solution based on plain text files if all you want is storage. If you want to be able to search the text files, you can slowly index them with a service or console application behind the scenes. The index can be built with Lucene.NET and what you index can be kept to a minimum since I hope you don't need to be able to search for absolutely everything you store in these text files. A: A quick calculation indicates that you may experience up to 50 GB of data per day. If there is no SQL specific processing to be done on this data then it doesn't seem feasible to store it in a database. The next solution would be files on the disk and since you deal with simple text (not binary) then perhaps a quick compression would also help. However since the files would be so small (300 bytes), compression would not yield any sensible results. The data would need to be grouped in larger files, for instance one piece of data per line and one such file per day. This file would be sufficiently large so that compression would give satisfactory results if the disk space would become an issue. If the space is not an issue and/or frequent processing of this data or even simultaneous processing of data from different days is to be expected then one piece of data per file would be a better choice. This solution, in turn, will bring the issue of having a very large number of files inside a folder which will not only bump against file system limitations but also create performance issues when working with these files, and these issues will affect the entire machine performance. Storing and accessing a large number of files in a better manner is to use a partitioned folder storage. That is each file would have to have a unique name and will then be placed in a specific folder hierarchy according to its name. This approach has several advantages: * *keeps the number of files per folder manageable (when this number increases, one only needs to go one folder hierarchy deeper to increase the "storage availability" exponentially) *easy to find a file's location or where to store a file based on the naming convention Sample partitioning: * *file names follow this format: yyyymmddhhss-<counter>.txt (e.g.: 201104252345-1.txt, 201104252345-2.txt, etc) *folder structure follows the time parts: \yyyy\mm\dd\ or yyyy\mm\dd\hh\ etc (as many levels as the solution would need to keep the number of files manageable) *results in: 201104252345-1.txt being stored as 2011\04\25\201104252345-1.txt, etc A: I won't do that in your situation. Assuming: (2000 * 300) / 1024(kb) / 1024(mb) = about 0.54 MB per second. One day have: 60(sec) * 60(min) * 24(hour) = 86400 seconds. 0.54 * 86400 = 43200 MB per day. If you will use UTF-8 encoding the size will be twice bigger! (varchar versus nvarchar) It mean you will get about 40 GB per day groth. Your express server wont survive even if you write insert query each 5 sec even 10 or 20 sec. Consider index rebuilding for good query performance, backuping the database in particular time period and other database stuff you have to carry about. Your database won't handle requests. I would recommend you storing strings in text files(if your text will be rarely read by end user otherwise I recommend using some index engine (Lucene maybe)) and cache them in application server. Store only path of those files in database. Note. It's only my own solution based on some facts and expirience. EDIT Using application you will get more control with your data. You can send files via HTTP to other server you can compress files etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: in java how to get files in a given directory I want to write a java code, where given a directory name, I should be able to get all the files starting with list (so something like list*) and read each file one by one (linewise), and do some processing . What classes are available and recommended to read a directory. Is my option is to read all file names by File.list and then pick the ones which start with list.. Thanks A: Well, the most central class would be File. Besides that there are some classes that File's methods need (like FileFilter etc.) You can also try and have a look at utility libraries like Apache Commons IO. A: You can list using a file filter as described here
{ "language": "en", "url": "https://stackoverflow.com/questions/7606681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I use over by partition in LINQ? I'm confused about how to change this query to LINQ select CONTENT from ( select CONTENT, CAM_ID, max(CAM_ID) over (partition by DOCUMENT_ID) MAX_ID from T_CAM_REVISION where DOCUMENT_ID = '101' ) where CAM_ID = MAX_ID so I can get a single value of content. A: There is no way to do max(...) over (...) in LINQ. Here is an equivalent query: var maxCamID = context.T_CAM_REVISION .Where(rev => rev.DOCUMENT_ID == "101") .Max(rev => rev.CAM_ID); var query = from rev in context.T_CAM_REVISION where rev.CAM_ID == maxCamID where rev.DOCUMENT_ID == "101" select rev.CONTENT; If you want only a single result: var result = context.T_CAM_REVISION .First(rev => rev.CAM_ID == maxCamID && rev.DOCUMENT_ID == "101") .CONTENT;
{ "language": "en", "url": "https://stackoverflow.com/questions/7606684", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to close native Camera automatically, after capturing a photo using camera After capturing a photo using camera, How to close native Camera automatically and redirect to app, without showing a preview with save or discard options . Is this possible with Phonegap API? Thanks Peter A: navigator.camera.getPicture( cameraSuccess, cameraError, [ cameraOptions ] ); Description Function camera.getPicture opens the device's default camera application so that the user can take a picture (if Camera.sourceType = Camera.PictureSourceType.CAMERA, which is the default). Once the photo is taken, the camera application closes and your application is restored. A: As preview is part of the native app, there is no way to skip it. :-(
{ "language": "en", "url": "https://stackoverflow.com/questions/7606685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I parse DefineConstants value in a BeforeBuild target? Related to this question. What I really want of a way of setting key value pairs that is settable from the Vis Studio 2010 IDE. I seem not to be able to set Project property values from within the IDE so I am looking at using compiler constants. So, if I have the compiler constants set to <DefineConstants>Foo=bar;Key=Value 2;</DefineConstants> can I parse this (in a BeforeBuild target say) so that I can extract the values of "bar" and "Value 2"? My MSBuild skills are next to nothing and my Google foo has not found any solutions. A: You can override this value when compiling the project with MSBuild. msbuild.exe myproj.csproj /p:DefineConstants="foo=true" You can't set build properties in a BeforeBuild task, but you can read them using: $(DefineConstants) This would return the raw string, and you would need to parse the string using batch commands to separate them into key/value pairs in a BeforeBuild step. Not really sure what you are trying to do, DefineConstants are just that, and referenced in code for conditional compilation. If you want to add custom build properties you can edit the csproj file and include your own targets file. It depends where and why you want to access them. In the build process the IDE (plugin), or code?
{ "language": "en", "url": "https://stackoverflow.com/questions/7606696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to correctly create a Tablayout now that the Tabactivity is deprecated? Since the introduction of Fragments the TabActivity is deprecated. The Hello Views TabLayout Tutorial however still uses the TabActivity and the API-Documentation has no clear answer on how to create a Tab Layout with Fragments instead of a TabActivity. How are you building Tablayouts now that the TabActivity is deprecated? A: Well, I had that issue and here is the solution example for that FragmentTabs.java. But I am still awaiting for the solution that Fragments provides instead of using ActivityGroup. A: Use TabHost or ActionBar with tabs along with Fragments . I recommend you to use ActionBar with tabs and a ViewPager to hold the fragments for each tabs. in onPageSelected() of onPageChangeListener, set the current tab by getActionBar().setSelectedNavigationItem(position); and in onTabSelected(Tab tab, FragmentTransaction ft) of TabListener set the current page in viewpager by mViewPager.setCurrentItem(tab.getPosition()); Check this example too. Good Luck! A: Since the release of ActionBarSherlock there is no need to use the old tap API. Just use the new tabs with fragments in any way you like on any recent Android Version (2.x)
{ "language": "en", "url": "https://stackoverflow.com/questions/7606700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to display the contents of the xml document retrieved from the jquery.ajax()...? I am invoking a web service through $.ajax(). onsuccess I am getting an xml document, now the problem is I need to see the contents of the retrieved xmlDocument.. Is there anyway to do that.. ?? A: Put it to the textarea field as-is $("#textareaID").val(xmlstr); or display with html-encoding: $("#someDivID").text(xmlstr); // jQuery text() function performs html-encoding automatically Simple demo: http://jsfiddle.net/wKhnF/1/ Note dataType: "text", it is required to process the response contents as a text rather then XML object. A: Use Firebug to check the response. You can use http://api.jquery.com/jQuery.parseXML/ to read, parse the XML, find, and retrieve elements. $.parseXML(xml)
{ "language": "en", "url": "https://stackoverflow.com/questions/7606703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Template class destructors I'm trying to create a simple template class in c++. I've been trying to compile the following but I only get a compile error. This is the code: #include <stdlib.h> #include <stdio.h> template<int size> class array { public: int len; int data[size]; array(void) : len(size) {} virtual ~array(void) {} }; int main() { array<3> a; for (int i=0; i < a.len; ++i) { a.data[i] = i; printf("%d\n", a.data[i]); } return 0; } This is the error g++-4.2.1 is giving me: Undefined symbols: "__Unwind_Resume", referenced from: _main in ccaYob9x.o ld: symbol(s) not found collect2: ld returned 1 exit status If we comment out the line for the destructor then the code compiles as it should and it gives me a list of the number 0, 1, 2. What my ultimate goal is after understanding how template base classes work is to create specialized template classes. I want to create a multidimensional array but I wish to specialize it for the cases when the dimension is 1, 2, and 3. I mainly want to be able to overload the operator() for those cases. In any case, using a template class like this saves me the trouble of allocating memory dynamically when the dimensions are 1, 2, and 3. Does someone know how to change the code to allocate memory dynamically? Doing so will require you to define the destructor, which is the problem I'm currently facing. EDIT: I'm not familiar with template specialization. Does someone know how to make a specialized template when size=1, 2 and 3 to have static memory for data and by default to have dynamic memory? EDIT 2: It seems that I'm having trouble due to my g++ compiler. Does anyone see anything with with this: g++ -v Using built-in specs. Target: i686-apple-darwin10 Configured with: /var/tmp/gcc/gcc-5666.3~6/src/configure --disable-checking --enable- werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^.-]*$/s/$/-4.2/ --with-slibdir=/usr/lib --build=i686-apple-darwin10 --program-prefix=i686-apple-darwin10- --host=x86_64-apple-darwin10 --target=i686-apple- darwin10 --with-gxx-include-dir=/include/c++/4.2.1 Thread model: posix gcc version 4.2.1 (Apple Inc. build 5666) (dot 3) EDIT 3: There has got to be something wrong with my g++ version. I just tried it with g++4.0 in the same machine and with the macports version g++-mp-4.3 and it works fine. I guess it is time to upgrade to the next version. Thank you for your answers and hints. A: Try this: template<int size> class array { public: int len; int *data; array(); virtual ~array(void); }; // 1 dimension specialized array template <> array<1>::array() : len(1) { data = new int; } template <> array<1>::~array() { delete data; } template <int size> array<size>::array() : len(size) { data = new int[size]; } template <int size> array<size>::~array() { delete [] data; } int main(int, char) { array<3> a; for (int i=0; i < a.len; ++i) { a.data[i] = i; printf("%d\n", a.data[i]); } array<1> b; for (int i=0; i < b.len; ++i) { b.data[i] = i; printf("%d\n", b.data[i]); } return 0; } With g++ you will not have compiling errors. You can define specialized operator() for each different array sizes without problems, like constructor and destructor seams. A: This is not stricly related to the question, but let me give you some int hints about yiour code. First: decide if you want to use C or C++. Templates are C++, but you are "coding as a C programmer". Not that this is bad by itself, bu it is out out context. (use iostream, not stdlib.h and stdio.h, don't use function(void) but just function()). May be it's not your case, but check also your source doesn't have "C" extension (this may fool the compiler) and use g++ (not gcc) as a command (the library you'll link are different) Second: pay attention about the use of variables and constant: the inst size as a template parameter, when instantiated is constant. There in no clue in keeping a len variable (in your design, the array size cannot be changed): a static const int len = size is all what you need. Third: if you really want to test, don't use a single for loop to assign and read values: this makes you completely blind in case of indexes misuse: instead of a.data[i] try the wrong a.data[0] and you'll get exactly the same output. Use a loop to fill the array, followed by another loop to read from it. Fourth: In C++, scopes are important: keep open and closing braces {} aligned. This may sound pedantic, but saved me soooo many times....
{ "language": "en", "url": "https://stackoverflow.com/questions/7606705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to add a class to a list item using jQuery I have a vertical list where I am storing the current selected items index in a PHP session variable. Now, when I come back to the same page, I want to apply a CSS Class to that particular list item. Not sure how to set the class of a particular index in a list using jQuery. I am doing something like this: $('ul.selectable1 li').get(3).addClass('myselection'); The UL >li list has a class attached to it called "selectable1: <ul id="items" class="selectable1"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> <li>Item 5</li> <li>Item 6</li> </ul> So if the Item-3 was stored in my session. I would like to make the list appear like this: <ul id="items" class="selectable1"> <li>Item 1</li> <li>Item 2</li> <li class="myselection">Item 3</li> <li>Item 4</li> <li>Item 5</li> <li>Item 6</li> </ul> A: Use .eq(2) - .get() returns a DOM element, not a jQuery object. If you always want the third element you can also select it in the initial selector: $('ul.selectable1 li:eq(2)')
{ "language": "en", "url": "https://stackoverflow.com/questions/7606707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Generic List is not coming This sample uses where to find all products that are out of stock. public void Linq2() { List<Product> products = GetProductList(); var soldOutProducts = from p in products where p.UnitsInStock == 0 select p; Console.WriteLine("Sold out products:"); foreach (var product in soldOutProducts) { Console.WriteLine("{0} is sold out!", product.ProductName); } } Result: Sold out products: * *Chef Anton's Gumbo Mix is sold out! *Alice Mutton is sold out! *Thüringer Rostbratwurst is sold out! *Gorgonzola Telino is sold out! *Perth Pasties is sold out! The above example i got from MSDN Samples, this is Simple2, the problem is when I enter List<Products>, Products is not showing in Intellisense. When I enter it manually, I get the following error: Only assignment, call, increment, decrement and new object expression can be used as a statement What can I do to solve this? A: Ok, your problem is that you copied the linked source. But this source does not contain the definitions for neither Product nor GetProductList() Please take a look at the example here - it has everything you need: List<string> fruits = new List<string> { "apple", "passionfruit", "banana", "mango", "orange", "blueberry", "grape", "strawberry" }; IEnumerable<string> query = fruits.Where(fruit => fruit.Length < 6); foreach (string fruit in query) { Console.WriteLine(fruit); } A: That's because you don't have the class defined. You to add the class definition. You could write the class in the same file, add a new class file and put the definition of Product in it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby on rails complex dynamic forms I have implemented rails complex form from Railscasts tutorial in my Rails app. I want to add ajax inside the complex form, where in I have implemented a prefill functionality inside the complex form. But I need to know the unique id of the div the complex form generates automatically. <div class="inputs"> <span class="input_wrapper"> <input class="text" id="formname_attributes_0_example" name="formname[attributes] [0][example]" size="30" type="text" /> </span> <button type="button" onclick="dinfill(this);" >Pre-fill</button> </div> <div class="inputs"> <span class="input_wrapper"> <input class="text" id="formname_attributes_1_example" name="formname[attributes] [1][example]" size="30" type="text" /> </span> <button type="button" onclick="dinfill(this);" >Pre-fill</button> </div> How do I fetch id="formname_attributes_1_example" the unique id '1' or any id from the above code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606709", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Array in UITextView I have an arrayappdeligate.biblearray. I just want to display this array in a textview. This array contains sql datas of 4 types chapterno, verses, genisis and text. i need to extract only the verses and display it in textview how to do this? A: It seems biblearray has the objects of type bible. You can get the verses from bible objects like this, bible *_bible = (bible *)[appDelegate.bibleArray objectAtIndex:0]; textView.text = [_bible verses]; or directly as, textView.text = [[appDelegate.bibleArray objectAtIndex:0] verses]; If you want to display all the verses in the textView, you can do it like this, NSArray *allVerses = [appDelegate.bibleArray valueForKey:@"verses"]; textView.text = [allVerses componentsJoinedByString:@"\n\n"]; @"\n\n" adds two new lines between the verses. A: You need to do some alteration. Create NSDisctionary instead. Take a dictionary where you are adding data from database NSMutableDictionary *dict = [[NSMutableDictionary alloc]init]; NSMutableArray *chapterno = [[NSMutableArray alloc]init]; NSMutableArray *verses = [[NSMutableArray alloc]init]; NSMutableArray *genisis = [[NSMutableArray alloc]init]; NSMutableArray *text = [[NSMutableArray alloc]init]; //Add data you are getting from database [chapterno addObject:chapternodata]; [verses addObject:versesdata]; [genisis addObject:genisisdata]; [text addObject:textdata]; [dict setValue:chapterno forKey:@"chapterno"]; [dict setValue:verses forKey:@"verses"]; [dict setValue:genisis forKey:@"genisis"]; [dict setValue:text forKey:@"text"]; [chapterno release]; [verses release]; [genisis release]; [text release]; Take one NSDictionary in AppDelegate say appDict and make it equal to dict NSMutableArray *arrVerses = [[objAppDel.appDict objectForKey:@"verses"]; txt.text = [arrVerses description];
{ "language": "en", "url": "https://stackoverflow.com/questions/7606713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Selenium 2.0 Found Element But Unable To Click I am using Selenium 2.0 for C# to find a radio button and click it. The code is as below: IWebElement t = driver.FindElement(By.XPath("//table[@id='ctl00_Main__objObjectivesFeedback_ctl39']/tbody/tr/td[2]/input[@type='radio']")); t.Click(); If I do a Console.Write(t.GetAttribute("name")), it returns the correct element name, however, click does not work. Btw, I am using FireFox 3.6.20. A: Try t.SendKeys(Keys.Space); If it works the only downside is SendKeys does not wait for the page to finish loading if the event caused the page to reload. Usually not a problem for radio buttons but it's something to keep in mind.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to convert the ordinary jpeg image bytes to the DICOM native image bytes using C# Currently I'm writing a module for the conversion of JPEG to DICOM Image Conversion. On analysis I've completed the tag rendering, now the image is not properly rendered in the DICOM file. Is there any algorithm to convert the JPEG to DICOM. A: Continuing from Matthieu's response, here is a very simple way of creating a DICOM envelope for a JPEG stream using the excellent GDCM library and his referenced example (note I have used some helper classes, but is quite simple): ImageReader r = new ImageReader(); gdcm.Image image = r.GetImage(); image.SetNumberOfDimensions(2); DataElement pixeldata = DataElementHelper.PixelData; string file1 = @"D:\testfil.jpeg"; System.IO.FileStream infile = new System.IO.FileStream(file1, System.IO.FileMode.Open, System.IO.FileAccess.Read); //uint fsize = gdcm.PosixEmulation.FileSize(file1); //byte[] jstream = new byte[fsize]; //infile.Read(jstream, 0, jstream.Length); byte[] jstream = System.IO.File.ReadAllBytes(file1); uint fsize = (uint) jstream.Length; SmartPtrFrag sq = SequenceOfFragments.New(); Fragment frag = new Fragment(); frag.SetByteValue(jstream, new gdcm.VL((uint)jstream.Length)); sq.AddFragment(frag); pixeldata.SetValue(sq.__ref__()); // insert: image.SetDataElement(pixeldata); PhotometricInterpretation pi = new PhotometricInterpretation(PhotometricInterpretation.PIType.MONOCHROME2); image.SetPhotometricInterpretation(pi); // FIXME hardcoded: PixelFormat pixeltype = new PixelFormat(PixelFormat.ScalarType.UINT8); image.SetPixelFormat(pixeltype); TransferSyntax ts = new TransferSyntax(TransferSyntax.TSType.JPEGBaselineProcess1); image.SetTransferSyntax(ts); image.SetDimension(0, (uint)1700); image.SetDimension(1, (uint)2200); ImageWriter writer = new ImageWriter(); gdcm.File file = writer.GetFile(); var ds = file.GetDataSet(); DataElement patientID = DataElementHelper.PatientID; DataElement patientName = DataElementHelper.PatientName; DataElement accessionNumber = DataElementHelper.AccessionNumber; DataElement studyDate = DataElementHelper.StudyDate; DataElement studyTime = DataElementHelper.StudyTime; DataElement studyInstanceUID = DataElementHelper.StudyInstanceUID; DataElement seriesInstanceUID = DataElementHelper.SeriesInstanceUID; DataElement mediaStorage = DataElementHelper.SOPClassUID; string studyUID = new gdcm.UIDGenerator().Generate(); string seriesUID = new gdcm.UIDGenerator().Generate(); //pixelData.SetArray(b, (uint)b.Length); DataElementHelper.SetDataElement(ref patientName, "TEST^MARCUS"); DataElementHelper.SetDataElement(ref patientID, "0000000801"); DataElementHelper.SetDataElement(ref accessionNumber, "0000000801-12345"); DataElementHelper.SetDataElement(ref studyDate, DateTime.Now.ToString("yyyyMMdd")); DataElementHelper.SetDataElement(ref studyTime, DateTime.Now.ToString("HHmmss")); DataElementHelper.SetDataElement(ref studyInstanceUID, studyUID); DataElementHelper.SetDataElement(ref seriesInstanceUID, seriesUID); DataElementHelper.SetDataElement(ref mediaStorage, "1.2.840.10008.5.1.4.1.1.7"); ds.Insert(patientID); ds.Insert(patientName); ds.Insert(accessionNumber); ds.Insert(studyDate); ds.Insert(studyTime); ds.Insert(studyInstanceUID); ds.Insert(seriesInstanceUID); ds.Insert(mediaStorage); writer.SetImage(image); writer.SetFileName("gdcm_test.dcm"); bool ret = writer.Write(); A: please have a look at the mdcm C# DICOM library, originally written by Colby Dillion. He has developed managed C++ "bridges" to the IJG/LibJPEG and OpenJPEG code bases, so mdcm provides both 8/12/16-bit lossy and lossless JPEG support as well as JPEG-2000 support. Colby's original library has WinForms dependencies. I have created a Silverlight and WPF targeted fork of mdcm here. The WPF version of the library can fully utilize the same JPEG(-2000) codecs that Colby originally implemented. The Silverlight version on the other hand currently cannot benefit from these codecs. I have made some attempts to apply the FJCore and LibJpeg.Net libraries for lossy JPEG support in Silverlight, but these libraries only support 8-bit images at the moment. Regards, Anders @ Cureos A: There is no functionality in .NET itself for DICOM support. You will need to use a library. I do not know of any free ones but I have used LeadTools and it will do it (for a price). But I would only give it a 4/10, and I would recommenced you look for other options too. A: You do not need to 'convert' JPEG to DICOM. DICOM is simply an 'envelope' for your JPEG stream. Here is what I did in GDCM to encapsulate (= put into a DICOM envelope) an existing MPEG2 file: http://gdcm.sourceforge.net/html/MpegVideoInfo_8cs-example.html Simply adapt that code for an input JPEG file. For instance have a look at: http://gdcm.sourceforge.net/html/DecompressJPEGFile_8cs-example.html No need to decompress/recompress, that would be a waste of resource.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySql query to return avg number od chapters by book per months I would appreciate your help greatly,I'm using php and mysql and I'm getting some unrealistic results, can you check my code if it is alright...btw the tables involved are BOOKS id, book_title, isbn, publisher, price, l1_subject_id, l2_subject_id, description1, description2, description3, call_date, chapter_proposal_date, notification_acceptance_date, publishing_fee_date, final_manuscript_date, 1st_proof_reading, 2nd_proof_reading, book_schedule_date, active, url, pages_num, edited_by, downloaded_num, file_size, unix_name, voted, general_notes, BMcomment, description4, about_the_book, call_started, kw_mandatory, kw_other, ignore_small, show_contributing_authors BOOKS_CHAPTERS id, users_id, books_id, order, books_sections_id, manuscript_title, price, active, paypending, notice, created_at, last_modified, keywords, status, book_editor_comments, hard_copy, invoiceing_data, extended_deadline, next_deadline, technical_notice, number SELECT COUNT(b.book_title) as `Total number of books `, COUNT(bc.manuscript_title) as ` Total number of chapters`, #DATE_FORMAT(b.call_started, '%M %Y') as `Date`, #DATE_FORMAT(b.call_started, '%Y-%m') as `Original date format`, (COUNT(b.book_title)/COUNT(bc.manuscript_title)) as `Average chapter number by book per month`, b.id as book_id FROM books b JOIN books_chapters bc ON (b.id = bc.books_id) WHERE b.call_started IS NOT NULL AND b.call_started != '0000-00-00' #GROUP BY MONTH(b.call_started), YEAR(b.call_started),b.id #ORDER BY YEAR(b.call_started) ASC, MONTH(b.call_started)ASC A: You join on chapters, but you count on book titles. That means that you count the title for each chapter in the total number of books (or per month, if you re-add the group by). Use count(distict b.book_title), or rather count(distinct b.id) or count(distinct b.isbn) to get the number of distinct books in this result set. Same goes for chapters, and there you should also use id, which is probably unique, auto-numbered. Chapter titles may be the same between books.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Linq to SQL - Best way to work with a collection of objects inside another object I have a table of Items for auction and a table of bids made for those items. There's much more to the database but we'll keep it simple. public class Items { public int ItemID { get; set; } public string ItemName { get; set; } public List<Bid> Bids { get; set; } } public class Bids { public int BidID { get; set; } public int ItemID { get; set; } public decimal Amount { get; set; } public datetime BidTime { get; set; } public int CustomerID { get; set; } } I want to return a dataset that includes the ItemID, the ItemName and all of the associated bid records ordered by BidTime, descending. Finally, I'd like to only see Items that a certain Customer has bid on and I'd like to only see their bids for that item. There is a foreign key relationship between Bids.ItemID and Items.ItemID. I'm using Linq to SQL. This works and appears to return the correct dataset: from i in Items from b in i.Bids where i.AuctionID == 2 && b.CustomerID == (Int32?)1165 orderby b.BidTime descending select new { i.ItemID, i.ItemName, i.Bids } I'm a SQL guy trying to wrap my head around the OO nature of Linq. Is this the best way (or even a good way) to get the results I want? Is there a better way? Thanks, BK A: How about this one (slightly more simple syntax): Updated where clause due to comment from i in db.items where i.AuctionID == 2 && i.Bids.Any(c=>c.CustomerID == (Int32?)1165) select new { i.ItemId, i.ItemName, i.Bids.Where(b=>b.CustomerID == (Int32?)1165 ).OrderbyDescending(b=>b.BidTime) } Make sure you profile the sql and verify that you get only ONE sql statement. If not, you need to have to add LoadOptions to your datacontext (that will make sure all the bids are eager loaded with your items). This one will also order the bids per item (not sure if yours will do the same.... but I guess you checked that).
{ "language": "en", "url": "https://stackoverflow.com/questions/7606734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Show incorrect html on page that doesn't influence the rest of the page I have got some detail content pages on my site where I don't have the complete control over the html content that is displayed in a certain div. Now when the content of the external resource contains invalid html, like having no ending my navigation in the right-bar is also italic. I don't want to use iframes, like ebay, and there is probably other ways to fix this. Hope on an answer. <html> <body> <div id="page"> <div id="content">[content of external resource]</div> <div id="right-bar">[My navigation]</div> </div> </body> </html> A simplified structure of my page is above. A: I hate to tell people to use Tables when they aren't necessary, but in this case, I feel that it could solve your problem. The issue that you are facing is one of the browsers well-formed html check, so, you could have some browsers that work as you hope, and others that work the way that bothers you, as each rendering engine is going to perform it's own well-formed html check flavor. If you wrap it inside a td, then I don't think that it will be able to bleed styling the way that you are seeing. Just a thought. The reason that a td container is going to help more than the div container that you are currently using is the following: Since you are wrapping their stuff in a div, and they are most likely wrapping their own stuff in divs, the browser doesn't know where the mistake is at. It doesn't know where the missing div tag should be inserted. So essentially, div in div in div creates problems for the well-formed html check, as it is not sure which of the tag you forgot. However, div in div in td, that is more distinct. If the td open and closes, then it knows that the missing tags belong to a smaller group of possible elements. In other words, you are making it easier on the well-formed check to do it's job by wrapping it inside different tag types. This makes sense to me. I hope that I have explained it ok. A: I think that there is no other way than using iframes. If you don't use an iframe to host the external content means that the external content will be included in the DOM structure of your page, so unless you parse all the external content code to check all the possible things that should affect your page (and this could be a madness), you will never be sure that your page will be safe from collateral effects coming from the external code. And even using iframes, you should parse anyway the external content to look for script tags, to prevent any undesired javascript code been executing inside your page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: showing error generated by validation actionform data separately in struts i am developing a web application using struts, spring and hibernate. One point to be clear first: the code level is limited to jdk1.4. i want to validate inputs from user (actionForm) and store the updates to database through hibernate. I am now using Struts Validation framework to validate the correctness of the form's inputs. The problems is i want to have each error message located next/below to the corresponding input field in the jsp rather than to generated by struts tag which is a . Any help? ps. any other validation framework that accomplish what i want would be welcome too, as i have not implement the validation yet A: The <html:errors> tag takes a property attribute. If given, it only displays the errors for the given property. Just put this tag with the appropriate property next to the field, and you'll have what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606740", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: display html code inside a javascript on a html page I will try my best to explain what I wish to do and do correct me or question me if I did not get my question across correctly. I have a jquery function as follows: function processResult(xData, status) { $(xData.responseXML).find("z\\:row").each(function() { var liHtml = "<a href=" + $(this).attr("ows_Title") + "><img src=" + $(this).attr("ows_snapshot_file_location") + " width=120 height=90><strong>" + $(this).attr("ows_video_description") + "</strong><br /><br />" + $(this).attr("ows_video_description") + "<em>" + $(this).attr("ows_video_length") + "</em></a><br />"; $("#videoplaylist").append(liHtml); }); } I have a HTML code as follows: <div id="playlist"> /*** Something to be derive from #videoplaylist ***/ </div> Actually, I can just call the jquery function as follows: <div id="videoplaylist"> </div> inside the /*** Something to be derive from #videoplaylist ***/ but what I actually want was that the code to reflect all the "lihtml" variable. If the "lihtml" variable contain <em>Hello World</em> it will display "Hello World" in the "/*** Something to be derive from #videoplaylist ***/" and not <em>Hello World</em> Appreciate any insight. A: I will try to interpret this as best I can. My interpretation: You have the following in your code <div id="videoplaylist">/* Something to be derive from #videoplaylist */</div> and then you have a block of html (<b>Something</b>) that you would like to insert there like this <div id="videoplaylist"><b>Something</b></div> but you are getting <div id="videoplaylist">/* Something to be derive from #videoplaylist */<b>Something</b></div> Is that correct? If so simply replace $("#videoplaylist").append(liHtml); with $("#videoplaylist").html(liHtml); The append command will only add the html to the end of the inside content. The html command will replace the complete content. HTH Alex A: Can you use the .text function in jQuery? $("#videoplaylist").text(liHtml); That should output the HTML string in its CDATA form. A: Just a guess, but that html string you are generating may not be well formed var liHtml = "<a href=" + $(this).attr("ows_Title") + "><img src=" + $(this).attr("ows_snapshot_file_location") + " width=120 height=90><strong>" + $(this).attr("ows_video_description") + "</strong><br /><br />" + $(this).attr("ows_video_description") + "<em>" + $(this).attr("ows_video_length") + "</em></a><br />"; It generates an HTML string, but none of the attributes within those elements are quoted. For example, the following string could be generating <a href=title.htm><img src=image.jpg width=120 height=90>.... When you probably want it looking more like this to be properly parsed: <a href='title.htm'><img src='image.jpg' width='120' height='90'>.... So hence, your auto generated html string should generate quotes around the attributes: var liHtml = "<a href='" + $(this).attr("ows_Title") + "'><img src='" + $(this).attr("ows_snapshot_file_location") + "' width='120' height='90'>....
{ "language": "en", "url": "https://stackoverflow.com/questions/7606741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android sprite moves when it is supposed to be stationary I created a sprite that is 18 frames long and it is supposed to be stationary and run through the frames and loop the animation, but when it runs it moves slowly across the screen as it animates until it hits the last frame then jerks back to the original position where it was suppose to stay at. I don't know the reason it does this and have tried to make it smaller sizes and larger sizes, at some sizes it does not move but just animates likes its supposed to do. If anyone has an answer to why this happens and how to stop it from moving and stay where it is supposed to be it would be greatly appreciated. I use only 1 row for the sprite and I used gimp to create the sprite and saved it as a png. A: The code is rather long thats why I didn't add it but it based on this tutorial aquarium live wallpaper tutorial I think I found my answer though, I had the png sprite in a folder I created named drawable, where I put all the images, I tried it again but put the sprite in the other folders this time and it didn't move, I tried scaling the sprite also which made it go a bit wonky, I was hoping on using scaling instead so it stayed the same size for all screens, this works for normal images but for sprites it causes some issues, maybe I'll try that with the largest size in the drawable-large-mdpi folder and see if it causes any issues that way. I'll update with that method and let you know. It would be nice to have just one image and scale it instead according to screen size. Okay I found the answer finally and it might help those creating sprites,the width when divided into the amount frames has to be a whole number since the measurements are in int not float or double, so it moves because when the frame gets divided it came out to a fraction instead which caused it to moves (I guess) whatever that float extra measurement was. Example: if the sprite was 100 pixels high and 1082 px wide and I had 15 frames the width of each frame would then be 72.133333333px wide for each frame causing an error that would move the image that extra length while keeping the animation looking nice. now if it was 1080px wide each frame would then be 72px wide a nice whole number and then would animate perfectly. So for those creating there own sprites make sure the wide equals out to be a whole number when the frames get divided (My problem was I was creating one image scaling it down and not checking the width of each frame so only one image size usually work, sometimes I got lucky and got two, I should of figured this out because it all runs in int not float for measuring the width. Hope this helps out someone else making sprites. Sam
{ "language": "en", "url": "https://stackoverflow.com/questions/7606742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to change the date format from MM/DD/YYYY to YYYY-MM-DD in PL/SQL? I have a date column in a table stored as MM/DD/YYYY format. I have to select and store the same date in another table in YYYY-MM-DD format i.e. XSD Date Format. But I am not able to do it. I am using this query: select to_date(date_column,'YYYY-MM-DD') from table; But still I am not able to do it. Giving me error ORA-01843 : not a valid month A: use select to_char(date_column,'YYYY-MM-DD') from table; A: I assume that you can use the Oracle SQL Developer, which you can download from here. You can define the date format which you want to work with: ALTER SESSION SET nls_date_format='yyyy-mm-dd'; With this, now you can perform a query like this: SELECT * FROM emp_company WHERE JDate = '2014-02-25' If you want to be more specific you can define the date format like this: ALTER SESSION SET nls_date_format='yyyy-mm-dd hh24:mi:ss'; A: To convert a DATE column to another format, just use TO_CHAR() with the desired format, then convert it back to a DATE type: SELECT TO_DATE(TO_CHAR(date_column, 'DD-MM-YYYY'), 'DD-MM-YYYY') from my_table A: select to_date(to_char(ORDER_DATE,'YYYY/MM/DD')) from ORDERS; This might help but, at the end you will get a string not the date. Apparently, your format problem will get solved for sure . A: It sounds like you've got it the wrong way round. If your existing data is in MM/DD/YYYY format, then you want: select to_date(date_column,'MM/DD/YYYY') from table; to convert the existing data to DATE values. (I do wonder why they're not stored as dates, to be honest...) If you want to perform the conversion in one step, you might want: select to_char(to_date(date_column,'MM/DD/YYYY'), 'YYYY-MM-DD') from table; In other words, for each row, parse it in MM/DD/YYYY format, then reformat it to YYYY-MM-DD format. (I'd still suggest trying to keep data in its "natural" type though, rather than storing it as text in the first place.) A: For military time formatting, select TO_CHAR(SYSDATE, 'yyyy-mm-dd hh24:mm:ss') from DUAL --2018-07-10 15:07:15 If you want your date to round DOWN to Month, Day, Hour, Minute, you can try SELECT TO_CHAR( SYSDATE, 'yyyy-mm-dd hh24:mi:ss') "full-date" --2018-07-11 10:40:26 , TO_CHAR( TRUNC(SYSDATE, 'year'), 'yyyy-mm-dd hh24:mi:ss') "trunc-to-year"-- 2018-01-01 00:00:00 , TO_CHAR( TRUNC(SYSDATE, 'month'), 'yyyy-mm-dd hh24:mi:ss') "trunc-to-month" -- 2018-07-01 00:00:00 , TO_CHAR( TRUNC(SYSDATE, 'day'), 'yyyy-mm-dd hh24:mi:ss') "trunc-to-Sunday" -- 2018-07-08 00:00:00 , TO_CHAR( TRUNC(SYSDATE, 'dd'), 'yyyy-mm-dd hh24:mi:ss') "trunc-to-day" -- 2018-07-11 00:00:00 , TO_CHAR( TRUNC(SYSDATE, 'hh'), 'yyyy-mm-dd hh24:mi:ss') "trunc-to-hour" -- 2018-07-11 10:00:00 , TO_CHAR( TRUNC(SYSDATE, 'mi'), 'yyyy-mm-dd hh24:mi:ss') "trunc-to-minute" -- 2018-07-11 10:40:00 from DUAL For formats literals, you can find help in https://docs.oracle.com/cd/B28359_01/server.111/b28286/functions242.htm#SQLRF52037 A: You can do this simply by : select to_char(to_date(date_column, 'MM/DD/YYYY'), 'YYYY-MM-DD') from table A: According to the comments, the data-type in the datatable is DATE. So you should simply use: "select date_column from table;" Now if you execute the select you will get back a date data-type, which should be what you need for the .xsd. Culture-dependent formating of the date should be done in the GUI (most languages have convenient ways to do so), not in the select-statement. A: Basically , Data in a Date column in Oracle can be stored in any user defined format or kept as default. It all depends on NLS parameter. Current format can be seen by : SELECT SYSDATE FROM DUAL; If you try to insert a record and insert statement is NOT in THIS format then it will give : ORA-01843 : not a valid month error. So first change the database date format before insert statements ( I am assuming you have bulk load of insert statements) and then execute insert script. Format can be changed by : ALTER SESSION SET nls_date_format = 'mm/dd/yyyy hh24:mi:ss'; Also You can Change NLS settings from SQL Developer GUI , (Tools > preference> database > NLS) Ref: http://oracle.ittoolbox.com/groups/technical-functional/oracle-sql-l/how-to-view-current-date-format-1992815 A: This worked for me! You can convert to datatype you want be it a date or string to_char(TO_DATE(TO_CHAR(end_date),'MM-DD-YYYY'),'YYYY-MM-DD') AS end_date A: Late reply but for.databse-date-type the following line works. SELECT to_date(t.given_date,'DD/MM/RRRR') response_date FROM Table T given_date's column type is Date A: Just to piggy back off of Yahia, if you have a timestamp you can use this function to cast exclusively as date, removing the timestamps. TO_CHAR(CAST(DateTimeField AS DATE), 'YYYY-MM-DD') AS TrackerKey__C Or in my case I need the below format TO_CHAR(CAST(DateTimeField AS DATE), 'YYYYMMDD') AS TrackerKey__C A: use SELECT STR_TO_DATE(date_column,'%Y-%m-%d') from table; also gothrough http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html A: SELECT TO_DATE(TO_CHAR(date_column,'MM/DD/YYYY'), 'YYYY-MM-DD') FROM table; A: if you need to change your column output date format just use to_char this well get you a string, not a date.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: A callback function with C linkage required from C++ Consider a following C++ singleton implementation, using pthread_once for thread safe initialization: class MySingleton { public: static MySingleton* Instance(); protected: MySingleton() {}; static void InitOnce(); private: static MySingleton* instance; }; MySingleton* MySingleton::instance = NULL; pthread_once_t singleton_once_control = PTHREAD_ONCE_INIT; MySingleton* MySingleton::Instance() { pthread_once(&singleton_once_control, &InitOnce); return instance; } void MySingleton::InitOnce() { instance = new MySingleton; } The problem is that pthread_once needs the callback function to have C-linkage. (Okay, it is just a compiler warning and in the environment I am testing this the code works cause C and C++ function call conventions are binary compatible) But is there any good pattern for a real cross platform solution? You can create a C-linkage wrapper function but it cannot be part of the class and hence call the private init function InitOnce. Any solution that avoids making the InitOnce public? P.S. Yes, singletons are bad. Lets not make this about that... A: Make InitOnce a friend function instead, and give it extern "C" linkage. A: I don't see why this should be a problem. For static member functions this is only a question about name mangling and nothing else. Since all your code is C++ it will always be consistent. The only thing syntatic thing here is that in C, functions without parameters are declare with a (void) parameter list. I think this is usually deprecated for C++ (since unnecessary) but you could try if this silences the warning that you get.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to dynamically load class using namespaces/subdirectory in Ruby/Rails? In my Rails 3.1 app (with Ruby 1.9), I have a Deployer1 class that is in a worker subdirectory below the model directory I am trying to load/instantiate this class dynamically with this code: clazz = item.deployer_class # deployer_class is the class name in a string deployer_class = Object.const_get clazz deployer = deployer_class.new If I dont use namespaces, eg something global like this: class Deployer1 end Then it works fine (deployer_class="Deployer1") - it can load the class and create the object. If I try and put it into a module to namespace it a bit, like this: module Worker class Deployer1 end end It doesnt work (deployer_class="Worker::Deployer1") - gives an error about missing constant, which I believe means it cannot find the class. I can access the class generally in my Rails code in a static way (Worker::Deployer1.new) - so Rails is configured correctly to load this, perhaps I am loading it the wrong way... EDIT: So, as per Vlad's answer, the solution I went for is: deployer_class.constantize.new Thanks Chris A: Object does not know a constant named Worker::Deployer1, which is why Object.const_get 'Worker::Deployer1' doesn't work. Object only knows a constant Worker. What does work is Worker.const_get 'Deployer1'. Vlad Khomisch's answer works, because if you look at the implementation of constantize, this is exactly what it does: it splits the string on '::' and recursively const_get's. A: try using constantize instead: module Wtf class Damm end end #=> nil 'Wtf::Damm'.constantize #=> Wtf::Damm Object.const_get 'Wtf::Damm' #=> Wtf::Damm
{ "language": "en", "url": "https://stackoverflow.com/questions/7606757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: C++ accesing objects far from current class hierarchy I think this is a really newb question, but I never found out the answer. I don't know how exactly to phrase this question, but I often find that I have to access objects that are "far away" from the current object in terms of the current hierarchy. I just want to make sure that this is the right (only) way to do this. This goes along with passing parameters in from main also. I find that some objects far away from main need to be passed in with a parameter multiple times. How does an object far away from main get information from the command line? For example for the first case, for 4 classes... class A{ B b; //need to check status of D //choice 1 b.get_c().get_d().get_status(); //choice 2 const C& c = b.get_c(); const D& d = c.get_d(); d.get_status(); }; class B{ public: C c; const C& get_c() {return c;} }; class C{ public: D d; const D& get_d() {return d;} }; class D{ public: bool check_status(); }; Say something like, A is car, B is door assembly, C is door, D is lock. Then A has to check say, is lock on, otherwise prevent starting. Choice 3 is to directly call D's method from A, I'd have to make a few layers of check_status() in C, B, and A and return D, C, B.check_status(). Don't all these calls to subobjects (if the code was a bit more complicated) get a lot of overhead? Thanks. A: All those functions are inline, since declared within the class definition, and are simple return something;. They return references, so there are no copies involved (note that they should probably be const member functions, otherwise I don't see how your code would compile). There should be no overhead at all, I would recommend you compile your code and take a look at the generated assembly just to be sure. A: The answer to this sort of question is always the same: Don't worry about it unless and until it becomes a problem, and then, take measurements to decide which option is best. Yes, there's an overhead with calls to subobjects but with the example you've given (and with many real-life examples) this overhead is unavoidable (and the compiler may optimize some of it away anyway). A: Well, for symmety you can place in A a const B& get_b() const and do get_b().get_c().get_d().get_status(); The two choiches are perfectly equivalent (and compiler optimization may in fact produce identical code). The only suggestion is to declare the getters as const X& get_x() const, since they don't modify the owner. A: In addition to the answers above getting hold of a copy of Large Scale C++ Software Design may help in this regard. Don't worry that the first chapter is a bit irrelevant these days, the majority of the ideas presented are still applicable. A: Regarding the performance of a chained function call like yours, these days there is not much to worry about when the functions are returning simple const references. However, as a possible design flaw, you generally should work with the immediate objects and avoid digging deep into other object's data. Figuratively, when you want to know when your merchant has a product available again you ask him directly (time = merchant.Availability(product);) and don't ask him for his supply arrival dates (time = merchant. GetSupplyerForProduct(product). SupplySchedule(). NextArrival();)
{ "language": "en", "url": "https://stackoverflow.com/questions/7606760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Visual studio 2010 automatically change project type Does anybody know why VS 10 change himself project type from Web Appliacation to Web Site when this project is downloaded from Team Foundation Server? A: Sounds like someone has changed the application and checked it in that way... Visual Studio won't change the project type on it's own. A: Project type is stored in the project file, not in the solution file. Do a TFS compare (or view the history) on the project file to see if that was changed. For C# project files the extension is .csproj This site says "web applications" have a .csproj or .vbproj , but that a "website project" will not have a project file (http://msdn.microsoft.com/en-us/library/dd547590.aspx). If the Web Application project was blasted away, and a web site created in its place, it may be difficult to track down when the change happened.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Razor C# - Setting up checkbox values I have my form with my checkbox inputs, and user can edit that. I can save these values in database good, but I don't know how to refill the form, so user can edit it. This is my ViewBag var: ViewBag.NewFriends = preferences.NewFriends;// this value is a boolean, false I try to pre-set values like this: @using (Html.BeginForm("SavePreferences", "Conta")) { @Html.HiddenFor(model => model.ID) @Html.CheckBox("newFriends", new { @checked = @ViewBag.NewFriends }) @Html.Label("newFriends", "Solicitações de Amigo de Alma") <p><input type="submit" value="Send" /></p> } As HTML checkbox has the value checked="checked", and not true or false, it doesn't work. @Html.CheckBox has the first parameter as input name, and second a boolean checked(true or false). My question is how can I easily set up this value? I tried: @Html.CheckBox("newFriends", ViewBag.NewFriends) // where ViewBag.NewFriends = false But it doesn't work at all... Any idea? A: Probably extension method CheckBox can't work with dynamic. I tried following example and it works: @{ bool isNewFriends = ViewBag.NewFriends; } @Html.CheckBox("newFriends", isNewFriends);
{ "language": "en", "url": "https://stackoverflow.com/questions/7606772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: PHP String modification Issue I am having one weird problem.I am getting time of the day like 800 , 1200 ... i want output String like 8:00,12:00.. I know alternatives but can anyone suggests me shortest way to complete it ..?plz A: One way to do it: echo preg_replace('^(\d{1,2})(\d{2})$', '$1:$2', $time); A: Another way echo substr($time, 0, 3 === strlen($time) ? 1 : 2) . ':' . substr($time, -2); Or you can normalize the length $time = str_pad($time, 4, 0, STR_PAD_LEFT); echo substr($time, 0, 2) . ':' . substr($time, 2, 2); A: if your source is string like "800" or "1200" then solution by deceze will do : preg_replace('^(\d{1,2})(\d{2})$', '$1:$2', $time); but if it's matter of date formatting then this is the right way to do it date("H:i");
{ "language": "en", "url": "https://stackoverflow.com/questions/7606773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TableLayout in Android Development I am having issues in TableLayout, width issues. I tried searching a lot, but all I get is solution using xml. I am doing it programmatically. Here is what I am doing public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TableLayout table = new TableLayout(this); table.setStretchAllColumns(true); table.setShrinkAllColumns(true); TableRow tableTitle = new TableRow(this); tableTitle.setGravity(Gravity.CENTER_HORIZONTAL); TableRow name = new TableRow(this); TableRow password = new TableRow(this); TableRow button = new TableRow(this); TextView empty = new TextView(this); TextView title = new TextView(this); title.setText("Hello table layout"); title.setGravity(Gravity.CENTER_HORIZONTAL); TextView txtUname = new TextView(this); txtUname.setText("Username"); TextView txtPass = new TextView(this); txtPass.setText("Password"); EditText uname = new EditText(this); EditText pass = new EditText(this); Button login = new Button(this); login.setText("Login"); name.addView(txtUname); name.addView(uname); password.addView(txtPass); password.addView(pass); button.addView(empty); button.addView(login); table.addView(name); table.addView(password); table.addView(button); table.setColumnShrinkable(0, true); setContentView(table); } I want to shrink first column. What should I add in this code? Anyone help! A: You should consider moving your to layout xml file. This would make your life way easier. To make only first column shrinkable replace setShrinkAllColumns(true) with setColumnShrinkable(0, true).
{ "language": "en", "url": "https://stackoverflow.com/questions/7606774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python's setup.py: how to install different files for different platforms I'm writing a cross-platform package which need to include different binary file for different platforms (e.g. Linux/MAC OS/Windows and even 32bit/64bit Windows) I need my package's setup.py to install different binary data files based on the platform. The problem is that I need the data files for all platforms to be included in the package where they may have the same name but different content. Can someone suggest how to do it using distutils / setuptools setup.py? A: It's not too hard, at least in simple cases: you can for instance see how the setup.py of the uncertainties Python package does it (it selects an install directory based on the version of Python, but you would simply check sys.platform and friends, in your case). The key lines are if sys.version_info >= (2, 5): package_dir = 'uncertainties-py25' else: package_dir = 'uncertainties-py23' and distutils.core.setup( … # Where to find the source code: package_dir={'uncertainties': package_dir}, … )
{ "language": "en", "url": "https://stackoverflow.com/questions/7606776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to extend dijit.form.button I am trying to extend dijit.form.Button with an extra attribute but this is not working.Code is given below In file1.js dojo.require('dijit.form.Button'); dojo.extend(dijit.form.Button,{xyz: ''}); In file2.jsp <script type="text/javascript" src="file1.js"></script> <div dojoType="dijit.form.Button" xyz="abc"></div> However when I look at the HTML of the created button (In chrome seen by right click and then selecting 'inspect element' option), it doesn't show xyz attribute. A: You need to keep in mind that there's a distinction between the widget object and its HTML representation. When you extend dijit.form.Button, the xyz attribute is added to the widget class, but not automatically to the HTML that the widget will render. So in your case, if you do console.debug(dijit.byId("yourWidgetId").get("xyz")); .. you'll see that the button object does have the xyz member, but the HTML (like you point out) does not. If you also want it do be visible in the HTML, you have to manually add it to the HTML rendering of the button. One way to do that is to subclass dijit.form.Button and override the buildRendering method. dojo.declare("my.Button", dijit.form.Button, { xyz: '', buildRendering: function() { this.inherited(arguments); this.domNode.setAttribute("xyz", this.xyz); } }); If you add an instance of your new Button class in the HTML, like so: <div dojoType="my.Button" xyz="foobar" id="mybtn"></div> .. then the HTML representation (after Dojo has parsed it and made it into a nice looking widget) will contain the xyz attribute. Probably something like this: <span class="..." xyz="foobar" dir="ltr" widgetid="mybtn"> <span class="..." dojoattachevent="ondijitclick:_onButtonClick"> <input class="dijitOffScreen" type="button" dojoattachpoint="valueNode" ...> </span>
{ "language": "en", "url": "https://stackoverflow.com/questions/7606782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to pass two-dimensional string array into a function of another class I have come across a little dilemma that has stumped me for the last few days. I am working on a project, just for practice, where the objective is to prompt the user to input a word and print out (to the screen) that same word, but in large letters drawn in ASCII characters. For example, if the user typed in the word "Hello", the output would be: H H EEEEE L L OOO H H E L L O O HHHHHH EEE L L O O H H E L L O O H H EEEEE LLLLL LLLLL OOO I created a two dimensional string array called 'letters' inside a namespace called "UpperCaseFont". Then, I created a class called BigWord, whose purpose would be to store a user-input word, and provide several useful functions: printWord(), setWord(), getWord() etc. Rather than storing the two-dimensional string array inside the BigWord class (which is actually what I originally intended to do, but couldn't get working), I later thought that it would be better to pass in the letters array into a function ( setAsciiFont() ) defined in BigWord and have a pointer in the BigWord class point to the address of the letters array. This way, instead of creating a new letters array each time a new BigWord object was created, all BigWord objects could just reference the same letters array. Saving memory and a few clock cycles too (not that it matters in a project of this size, but I still want to develop good coding habits). However, I cannot seem to get it working. My code is below: The main .cpp file: #include <iostream> #include "Characters.h" using namespace std; int main(int argc, char** argv) { BigWord b; char temp[20]; cin >> temp; // prompt user for word b.setWord(temp); cout << "Your word is: " << b.getWord() << endl; //Set the ASCII font for the BigWord object to use b.setAsciiFont(UpperCaseFont::letters); b.printWord(); return 0; } The header file (Characters.h): #ifndef CHARACTERS #define CHARACTERS #include <iostream> using namespace std; namespace UpperCaseFont { // constant; font should not be changeable // all characters will have 5 rows. const string letters[][5] = { { " A ", " A A ", " AAAAA ", " A A ", "A A" }, { " BBBB ", " B B ", " BBB ", " B B ", " BBBB " }, { " CCCC ", " C ", " C ", " C ", " CCCC " } }; // not finished making all letters yet. } class BigWord { private: int wordLength; char word[]; // letters[][5] will point to the location of UpperCaseFont::letters array. const string* letters[][5]; void toUpperCase(char* str); public: void setWord(char w[]); string getWord() { return word; } void setAsciiFont(const string [][5]); // PROBLEM WITH THIS FUNCTION void printWord(void); }; void BigWord::setWord(char* w) { wordLength = strlen(w); // cout << "Word Length: " << wordLength << endl; std::copy(w, w + wordLength, word); BigWord::toUpperCase(word); } void BigWord::toUpperCase(char* str) { // convert a string to Upper case letters for printWord algorithm to work for (int i = 0; i < wordLength; i++) { if (str[i] > 'Z') { str[i] -= ('a' - 'A'); } } } void BigWord::setAsciiFont(const string font[][5]) { // ***PROBLEM*** letters = &font; // How can I get this to work?? } void BigWord::printWord() { // print top line of all ASCII Font letters, move to next line, repeat etc. for (int i = 0; i < 5; i++) { for (int j = 0; j < wordLength; j++) { // subtracts 65 (ASCII 'A') to arrive at index 0 if character == A. cout << *letters[word[j] - 'A'][i]; } cout << endl; } } #endif When I attempt to compile this code, I get the following error: Characters.h:81: error: incompatible types in assignment of const std::string (**)[5]' toconst std::string*[0u][5]' I'm fairly new to C++ (started a couple weeks ago, but I have some Java experience to back me up), and even newer to pointers, so I don't exactly know what I am doing wrong...and any googling has been to no avail. I understand that using the name of an array will act as the pointer to the first index of that array, but how does it work with two-dimensional (or multi-dimensional) arrays? If needed, I can write a function to convert the UpperCaseFont::letters array into a one-dimensional array if it turns out two dimensional arrays are too troublesome to deal with. Essentially, to get down to what I'm really asking: How can I assign a pointer to a two-dimensional string array that has been passed into a function within a class located in a header file? A: The problem is that C++ doesn't support passing arrays as arguments. When you write: void setAsciiFont( std::string const font[][ 5] ); the compiler converts this to: void setAsciiFont( std::string const (*font)[5] ); When you pass an array, a similar conversion occurs. The simplest solution is just to change your variable declaration in the class to reflect this: std::string const (*letters)[5]; Because of the way indexation is defined in C++, this will work exactly as if you had the complete array as a member, i.e. letters['n'][line] will pick up the right string. And BTW: I'd pass the font as a parameter to the constructor of BigWord. That way, there's no way you can accidentally try to output without having set it. A: Arrays can be passed by reference. So following function, void setAsciiFont(const string [][5]); // PROBLEM WITH THIS FUNCTION should be (with declaring both the dimensions), void setAsciiFont(const string (&letters)[3][5]); // ok ^^^^ pass by reference You can templatize this function, if you are not sure of the dimension always: template<size_t ROW, size_t COL> void setAsciiFont(const string (&letters)[ROW][COL]); // ok A: You just need to properly type the letters member variable. You want to assign a const string (*)[5] (which is what const string [][5] decays to) to it, so it should have this type // letters[][5] will point to the location of UpperCaseFont::letters array. const string (*letters)[5]; Otherwise, it should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Getting error neo4j [not found] when trying to generate a model I installed JRuby and the neo4j gem and trying to use a generator to create a model: jruby -S rails generate scaffold User name:string born:date --orm=neo4j However, I get this error: error neo4j [not found] I tried installing neo4j through bundler and just gem install. Either way, which neo4j returns nothing. I tried this with the the neo4j-rails gem as well but I the neo4j rubyforge page says it is no longer needed. I also tried just generating a model rather than a scaffold. Is this error specific to just generators or does it mean that my neo4j installation didn't work? A: Your installation did not work. The problem is that you have probably installed version 0.4.6 which is not specific to the JRuby platform but also installs (incorrectly) on MRI. So the error 'neo4j [not found]' is because you are using JRuby and installed the neo4j.rb gem in MRI. Neo4j.rb version >= 1.0.0 can only be installed on JRuby. I recommend using RVM: * *rvm install jruby *rvm use jruby *gem install bundler *bundle install
{ "language": "en", "url": "https://stackoverflow.com/questions/7606785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Control sub form from another thread c# In my project, I have: Form1, <-- this is the main form, run in main thread Form2, <-- this is the subform 1 background worker experienced problem: when I create a new form inside background worker, and show it using Form2 test = new Form2(); *test.show();* the form shows up, but freezed and I can do nothing to the form the question is: 1. is it able to create a form inside a background worker but, the form will run on the main thread? 2. if yes, how to do it? :) 3. if not, how to control a form that, I declared on the main thread, from backgroundworker A: You should use Control.Invoke to create new Form's . public static class InvokeControl { public static void InvokeIfRequired(this Control c, Action<Control> action) { if (c.InvokeRequired) { c.Invoke(new Action(() => action(c))); } else { action(c); } } } and class this method by InvokeControl.InvokeIfRequired(this, c => {//Create you're form here});
{ "language": "en", "url": "https://stackoverflow.com/questions/7606790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it possible to create an alternative for List in Orchard? I just want to customize List view. is it possible? I think yes. How? How to name alternative for List of Content types, let say, "Question" A: Sure. As the question is a little vague about context, I'll make assumptions. I'll assume that you have a controller action building the list (similar to what the blog is doing). From the action, you are usually building a list shape with code looking something like this: var pager = new Pager(_siteService.GetSiteSettings(), pagerParameters); var things = _someServiceClass.GetThings(something) .Skip(pager.GetStartIndex()).Take(pager.PageSize)) .Select(p => Shape.Thing_Summary( Thing: p, SomethingElseThatIsRelevantToTheTemplate: foo)); Shape list = Shape.List(Pager: pager); list.AddRange(things); list.Metadata.Alternates.Add("list_things"); return new ShapeResult(this, list); See that line near the end? It's adding the alternate, so that you can build a specific template for that particular list by creating a file named list.things.cshtml in the views folder of your theme.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to publish aspnet.mvc site? I have to publish my asp.net mvc site to the customer server. Which files should I publish to avoid to distribute the project source code? A: Have you tried a right-click on your project an build a deployment package? VS will pack all files you need. And for the Client server use msdeploy to publish And next time use the search cause you will find lots of posts about this: Best way to deploy a VS-2008 web project How to deploy my asp.net project in IIS? Is it possible to deploy asp.net mvc project on IIS server without installing of mvc?
{ "language": "en", "url": "https://stackoverflow.com/questions/7606795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create sqlite virtual table in Python I want to create a SQL-like interface for a special data source which I can query using Python. That is, I have a data source with a number of named iterable containers of entities, and I would like to be able to use SQL to filter, join, sort and preferably update/insert/delete as well. To my understanding, sqlite3's virtual table functionality is quite suitable for this task. Is it possible to create the necessary bindings in Python? I understand that the glue has to be c-like, but my hope is someone already wrote a Python wrapper in C or using ctypes. I will also accept an answer for a better/easier way of doing this. A: You can do this by registering a virtual table in SQLite with the APSW Python bindings. An example for talking to CouchDB using APSW. There's a similar capability for Perl, namely: Create SQLite Virtual Table extensions in Perl Finally, if you want to make a Python-based virtual table in PostgreSQL 9.1, check out http://multicorn.org/. A: Sounds like you can use SQLAlchemy to persist these objects to sqlite3, possibly to an in :memory: db, and issue both object and table level (raw sql) queries. You can also update/insert/delete them easily.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: JavaScript Date Object Comparison When comparing date objects in Javascript I found that even comparing the same date does not return true. var startDate1 = new Date("02/10/2012"); var startDate2 = new Date("01/10/2012"); var startDate3 = new Date("01/10/2012"); alert(startDate1>startDate2); // true alert(startDate2==startDate3); //false How could I compare the equality of these dates? I am interested in utilizing the native Date object of JS and not any third party libraries since its not appropriate to use a third party JS just to compare the dates. A: you can compare the actual milliseconds : alert(startDate2.getTime() === startDate3.getTime()); A: Compare dates using getTime() returning number of milliseconds from epoch (i.e. a number): var startDate1 = new Date("02/10/2012"); var startDate2 = new Date("01/10/2012"); var startDate3 = new Date("01/10/2012"); alert(startDate1.getTime() > startDate2.getTime()); // true alert(startDate2.getTime() == startDate3.getTime()); //true Also consider using Date constructor taking explicit year/month/date number rather then relying on string representation (see: Date.parse()). And remember that dates in JavaScript are always represented using client (browser) timezone. A: tl;dr Use date.getTime() for comparisons. Based on my testing, it was at least 25% than the next fastest alternative (date.valueOf()). Details Came across this in 2022. As others have already said, comparing like date1.getTime() === date2.getTime() is the way to go. Someone else shared a jsperf link in an answer that seems broken for me right now, so decided to add some performance comparison of my own. I created two arrays containing 1000 dates each. All dates will naturally be different instances (meaning direct === checks will fail), so what this benchmark does, is test what the fastest way is to convert a date to a primitive. Here's the test data: const data1 = Array.from({length: 1000}, () => new Date()) const data2 = Array.from({length: 1000}, () => new Date()) And here are the test cases (there's more in the link below): // 1 data1.forEach((d1, i) => d1.getTime() === data2[i].getTime()); // 2 data1.forEach((d1, i) => d1.valueOf() === data2[i].valueOf()); // 3 data1.forEach((d1, i) => Number(d1) === Number(data2[i])); // 4 data1.forEach((d1, i) => d1.toISOString() === data2[i].toISOString()); Result (use date.getTime()) Not a surprise that a date.getTime() conversion is much faster. It's around 25% faster than date.valueOf(), and between 10x and 100x faster than everything else (as far as I've checked). Additionally, introducing optional chaining slowed the best case by almost 10% for me. Found that interesting. date.valueOf() also slowed down by 5% compared to its non optional chaining counterpart. data1.forEach((d1, i) => d1?.getTime() === data2[i]?.getTime()); Benchmark link: here Here's an image, in case the above link breaks at some point in the future. A: You do not need to use the getTime method- you can subtract a date object from another date object. It will return the milliseconds difference(negative, if the second is a later date) var startDate1 = new Date("02/10/2012"); var startDate2 = new Date("01/10/2012"); var diff= (startDate1 -startDate2) // evaluates to 0 if the dates have the same timestamp A: That is because in the second case, the actual date objects are compared, and two objects are never equal to each other. Coerce them to number: alert( +startDate2 == +startDate3 ); // true If you want a more explicity conversion to number, use either: alert( startDate2.getTime() == startDate3.getTime() ); // true or alert( Number(startDate2) == Number(startDate3) ); // true Oh, a reference to the spec: §11.9.3 The Abstract Equality Comparison Algorithm which basically says when comparing objects, obj1 == obj2 is true only if they refer to the same object, otherwise the result is false. A: You can also use the function valueOf() var startDate1 = new Date("02/10/2012").valueOf(); var startDate2 = new Date("01/10/2012").valueOf(); var startDate3 = new Date("01/10/2012").valueOf(); alert(startDate1>startDate2); // 1326150000000 > 1328828400000 true alert(startDate2==startDate3); // 1328828400000 > 1326150000000 false A: One more way of comparing two dates would be converting dates to timestamps using "+" operator before the date. So, let's say we have two dates: const dateOne = new Date("10 January 1986") const dateTwo = new Date("10 December 2020") if(+dateOne == +dateTwo){ //do something } and so on. This is really handy if you are sorting date objects too as you can use this in the sorting callback function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "96" }
Q: To get current Instance of the session scoped bean in Jsf 2.0 i referred to this question and i've a similar problem JSF - Get the SessionScoped Bean instance I want to get the current instance of a managed bean in another managed bean. I've a SuperBean which is extended in a base Class - baseBean. I set the value of a list - itemList in baseBean. The getter setter of the list are in SuperBean and I should use this SuperBean in my BackingBean to get the value of the itemList. I tried using - Application app = FacesContext.getCurrentInstance().getApplication(); ValueBinding vb = app.createValueBinding("#{superbean}"); SuperClass superclass = (SuperClass) vb.getValue(FacesContext.getCurrentInstance()); When I try to print superclass.getItems(); - It gives only this - [] And also this - SuperClass superclass = (SuperClass)FacesContext.getCurrentInstance(). getExternalContext().getSessionMap().get("superbean"); When I try to print with this - It throws exception as my superbean entry is not present in the sessionMap even though the entry is placed in facesConfig and also as @ManagedBean and @sessionscoped Kindly help me resolve this. A: You can inject a managed bean into another if the injected bean has the same or broader scope. Here is an example: @ManagedBean(name = "oneBean") @ViewScoped public class OneBean{ // injections @ManagedProperty(value = "#{anotherBean}") private AnotherBean anotherBean; // don't forget to add getter and setter for anotherBean ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7606801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Clear notification in status bar after application crashed In my application I have several services running. When user stop application (UI part) services remain running in the background and display notifications ( each service has one) in status bar. When clicking on it dialog appears with choice to cancel appropriate service. And here is my problem. When something goes wrong and application crashes notifications remains in the status bar area. Is it possible to clear all notifications before showing standard android force close dialog? The real bug is NPE when I try to open activity clicking on notification. It's fixed. But I only want to know how to clear everything when application crashes. Here is my final solution inspired by mice's post. In application in on create method I register Thread.setDefaultUncaughtExceptionHandler() @Override public void onCreate() { super.onCreate(); this.notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); final UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler(); UncaughtExceptionHandler appHandler = new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable ex) { this.notificationManager.cancelAll(); defaultHandler.uncaughtException(thread, ex); } }; Thread.setDefaultUncaughtExceptionHandler(appHandler); } thanks A: You may call Thread.setDefaultUncaughtExceptionHandler() with a handler to be called when some Exception is not handled by your app in the thread. This handler is invoked in case Thread dies due to an unhandled exception. Here you'd do needed cleanup work. This is exactly how ACRA crash reporting library is catching crashes. A: First thing you need to ensure that your application should not get crashed at any cost and answer to your question, you should override onDestroy() method of the service and cancel notification there as it will work for you in both the cases when service stops or it crashes. As you can not use onDestroy() in case of crash, so you need to put try catch block and after getting exception perform your appropriate action.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: I got error PlatformNotSupportedException when I work with date's I work on windows-mobile 6.5 the region is English (United States) date: M/d/yy time: h:mm:ss tt I've this code: DateTime dt_1,dt_2; try { CultureInfo obj = new CultureInfo("en-US"); dt_1 = DateTime.Parse(TmpD_from, obj); } catch { CultureInfo obj = new CultureInfo("he-IL"); dt_1 = DateTime.Parse(TmpD_from, obj); } try { CultureInfo obj = new CultureInfo("en-US"); dt_2 = DateTime.Parse(TmpD_to, obj); } catch { CultureInfo obj = new CultureInfo("he-IL"); dt_2 = DateTime.Parse(TmpD_to, obj); } if (DateTime.Today >= dt_1.Date && DateTime.Today <= dt_2.Date) { return true; } else { return false; } the values: TmpD_to: 31/12/2011 00:00:00 TmpD_from: 31/12/2011 00:00:00 and I got this error: PlatformNotSupportedException A: You probably get the Exception because the culture "he-IL" (Hebrew, right?) is not supported by Windows Mobile 6.5. I would suggest trying another culture, whose formatting results are close (or equal) to what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use max and group by statement on my SQL query? task_name start_time value acc_clock 2010-05-27 4 icc_opy 2010-05-28 5 icc_dtaf 2010-05-29 3 acc_clock 2010-05-25 34 icc_ruty 2010-05-23 33 icc_ruty 2010-05-22 45 This is my output of a SQL query which is coming from two different tables. Note that in this output, task_name is occuring twice. Now I want the output to have only one occurence of task_name and its associated value should be the maximum start_time, like this: task_name start_time value icc_opy 2010-05-28 5 icc_dtaf 2010-05-29 3 acc_clock 2010-05-25 34 icc_ruty 2010-05-23 33 My query is select t.task_name, max(t.start_time) , i.value from task_runs t, integer_values i where i.run_id= t.id and t.username= 'amit' and t.start_time > '2010-05-20' order by t.task_name group by t.task_name????????? Why my query is not working? My values coming from two tables : task_runs, integer_value. I want these three columns but task name with max start_time with associated its value. A: There are two problems with your current statement * *ORDER BYmust be placed after a GROUP BY *You either have to add i.value to the GROUP BY clause or use an aggregate function (MIN, MAX, AVG, ...) on i.value SQL Statement select t.task_name , max(t.start_time) , i.value from task_runs t , integer_values i where i.run_id= t.id and t.username= 'amit' and t.start_time > '2010-05-20' group by t.task_name , i.value order by t.task_name SQL Statement (Edit) select t.task_name , t.start_time , i.value from ( select t.task_name , start_time = max(t.start_time) from task_runs t where t.username= 'amit' and t.start_time > '2010-05-20' group by t.task_name ) tm INNER JOIN task_runst t ON t.task_name = tm.task_name AND t.start_time = tm.start_time INNER JOIN integer_values i ON i.run_id = t.id order by t.task_name A: The GROUP BY must go before ORDER BY and you should choose what value of i.value do you want (max, min, ...). A: On MSSQL try this SELECT t.id , MAX(t.task_name) AS task_name , MAX(t.start_time) AS start_time , (SELECT TOP 1 value FROM integer_values WHERE run_id = t.id) AS value FROM task_runs t WHERE t.username = 'amit' AND t.start_time > '20100520' GROUP BY t.id ORDER BY task_name
{ "language": "en", "url": "https://stackoverflow.com/questions/7606814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Arduino Ethernet and DHCP cannot communicate out to the Internet I have this web client example that gets an IP address via DHCP. It connects to my router at IP address 192.168.0.1 successfully, but then it fails to send a GET HTTP to google.com. Essentially, I cannot allow the traffic from Arduino to go out into the Internet. I have a Linksys/Cisco E2000 router connected to the Arduino. My code is below. #include <SPI.h> #include <Ethernet.h> #include <EthernetDHCP.h> // Enter a MAC address and IP address for your controller below. // The IP address will be dependent on your local network: byte mac[] = {0x90, 0xA2, 0xDA, 0x00, 0x78, 0x0B}; byte ip[] = {192, 168, 0, 125}; byte gateway[] = {192, 168, 0, 1}; byte subnet[] = {255,255,255,0}; byte serverLocal[] = { 192,168,0,1 }; // Google byte serverExternal[] = { 173,194,33,104 }; // Google // Initialize the Ethernet client library // with the IP address and port of the server // that you want to connect to (port 80 is default for HTTP): Client clientLocal(serverLocal, 80); Client clientExternal(serverExternal, 80); const char* ip_to_str(const uint8_t*); void setup() { Serial.begin(9600); Serial.println("Attempting to obtain a DHCP lease..."); // Initiate a DHCP session. The argument is the MAC (hardware) address that // you want your Ethernet shield to use. This call will block until a DHCP // lease has been obtained. The request will be periodically resent until // a lease is granted, but if there is no DHCP server on the network or if // the server fails to respond, this call will block forever. // Thus, you can alternatively use polling mode to check whether a DHCP // lease has been obtained, so that you can react if the server does not // respond (see the PollingDHCP example). EthernetDHCP.begin(mac); // Since we're here, it means that we now have a DHCP lease, so we print // out some information. const byte* ipAddr = EthernetDHCP.ipAddress(); const byte* gatewayAddr = EthernetDHCP.gatewayIpAddress(); const byte* dnsAddr = EthernetDHCP.dnsIpAddress(); Serial.println("A DHCP lease has been obtained."); Serial.print("My IP address is "); Serial.println(ip_to_str(ipAddr)); Serial.print("Gateway IP address is "); Serial.println(ip_to_str(gatewayAddr)); Serial.print("DNS IP address is "); Serial.println(ip_to_str(dnsAddr)); // if you get a connection, report back via serial: if (clientLocal.connect()) { Serial.println("connected internally"); // Make a HTTP request: clientLocal.println("GET /index.html HTTP/1.0"); clientLocal.println(); } else { // kf you didn't get a connection to the server: Serial.println("connection failed internally"); } // if you get a connection, report back via serial: if (clientExternal.connect()) { Serial.println("connected externally"); // Make a HTTP request: clientExternal.println("GET /search?q=arduino HTTP/1.0"); clientExternal.println(); } else { // kf you didn't get a connection to the server: Serial.println("connection failed externally"); } } void loop() { // if there are incoming bytes available // from the server, read them and print them: if (clientLocal.available()) { char c = clientLocal.read(); Serial.print(c); } // if the server's disconnected, stop the client: if (!clientLocal.connected()) { Serial.println(); Serial.println("disconnecting."); clientLocal.stop(); } // if there are incoming bytes available // from the server, read them and print them: if (clientLocal.available()) { char c = clientLocal.read(); Serial.print(c); } // if the server's disconnected, stop the client: if (!clientExternal.connected()) { Serial.println(); Serial.println("disconnecting."); clientExternal.stop(); // do nothing forevermore: for(;;) ; } } // Just a utility function to nicely format an IP address. const char* ip_to_str(const uint8_t* ipAddr) { static char buf[16]; sprintf(buf, "%d.%d.%d.%d\0", ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3]); return buf; } A: Here's an example of working code (maybe you used this as a source?). The only differences I could see are the lines: Serial.begin(9600); delay(1000); just before the line: if (clientLocal.connect()) { I doubt the additional Serial.begin() has any effect but the delay() may be required (although it's a long shot...)
{ "language": "en", "url": "https://stackoverflow.com/questions/7606816", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Python pipe in binary file from command line -u option Is there a decoupled method of passing in a binary file without suffering the penalty of python having unbuffered stdout for the entire duration of running a program (if i intend to use only cmdline and not open(...,'rb')? It seems like -u is the only way to read in a file as binary data (from cmdline) http://docs.python.org/using/cmdline.html -u Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode. A: You could perhaps avoid Python's file mode by instead grabbing the fileno out of the sys.stdin file-like object, and using os.read() to grab data from it? import os import sys stdin_no = sys.stdin.fileno() some_bytes = os.read(stdin_no, 1024) A: This code will change standard input (only) to unbuffered mode. Using this you will not need to invoke the interpreter with -u. Unix only. import fcntl, os, sys def set_fd_nonblocking(fd): u"put an open file descriptor into non-blocking I/O mode" if fcntl.fcntl(fd, fcntl.F_SETFL, os.O_NONBLOCK) != 0: raise IOError, "can't set file descriptor %s option O_NONBLOCK" % (fd,) set_fd_nonblocking(sys.stdin.fileno()) However I am unsure what side effects this could have, for example on the raw_input built-in function. Be careful; even in non-blocking mode, if select tells you the fd is ready to read you will still need to catch OSError and check for e.errno == os.errno.EAGAIN. Such errors should be ignored.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: validate an xpath expression in Java Given an user input string, how can I tell whether it is a valid Xpath expression or not in Java. Just curious, since I cannot find a way to do it using javax.xml.xpath library. Thanks. A: I assume you want to validate the syntax but not if the expression is valid within the context of a your xml or xml schema. You can use the compile(..) method and it will throw an exception if the xpath is incorrect w.r.t the syntax. XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile("//book[author='Abc']/title/text()"); A: Run the XPath against some example XML document (e.g. <a/>). In most cases it won't return anything, but what you care about is whether it will throw an exception.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: c# save trackbar.value I'm trying to save a TrackBar value to a variable but can't manage to do it since the value changed all the time. void VolumeBarScroll(object sender, System.EventArgs e) { int a = VolumeBar.Value; } Is there any way of keeping a value?. A: If you need to set value instantly - use ValueChanged event. If you need to set value only once after finish changing - use MouseCaptureChanged event. Scroll event - it's behaviour event. Occurs when either a mouse or keyboard action moves the scroll box. So, probably you need: int trackValue = 0; private void trackBar1_MouseCaptureChanged(object sender, EventArgs e) { trackValue = this.trackBar1.Value; } Also, you are trying to save value to a local variable inside of event handler, if you need to use it outside of event handler, you need to define variable outside of the handler. A: you should take a look to this blogs... http://www.daniweb.com/software-development/csharp/threads/348366 http://en.csharp-online.net/TrackBar
{ "language": "en", "url": "https://stackoverflow.com/questions/7606826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python: How to read all text file contents in multiple folders and save them into one excel file I am currently working on this task and got stuck. Please give me your advices. The code I am writing below, it returns only the .txt file name from multiple folders, while I would like to print out the content of each .txt file and save in different rows in excel. The contents of each .txt file are numbers. import os, glob,xlwt #create workbook and worksheet wbk = xlwt.Workbook() sheet = wbk.add_sheet('data') path= 'E:\Cag\Data' row = 0 for dir,subdir,files in os.walk(path): for file in files: if glob.fnmatch.fnmatch(file, '*.txt'): L = file.strip() sheet.write(row,5,L) row += 1 wbk.save('read_all_txt_in_folders.xls') print 'success' A: Well, you see the file names because you write them. L contains the file name. (And the L = file.strip() seems unnecessary to me.) If you want to write the file contents, you should do instead L = open(os.path.join(dir, file), "r").read(). A: If you want to write the file contents, you should do instead with open(os.path.join(dir, file), "r") as source: L= source.read() This assures that the file is actually closed when you're done reading them. That releases system resources.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: looking inside a GdkPixbuf structure with ddd or gdb i would like to look inside of a GdkPixbuf structure for debugging purposes. but all i get is a <incomplete type> message. ill show you a little snippet of example code. //load image GtkWidget *image = gtk_image_new_from_file("image.bmp"); //get the GdkPixbuf representation of the image GdkPixbuf *pixbuff = gtk_image_get_pixbuf(GTK_IMAGE(image)); ok now i when i try to look inside the pixbuff structure i get the <incomplete type> message. How do i correctly look inside this structure using ddd or gdb debuggers ? im new a coding c and debugging. ive tried the following in ddd graph display (GdkPixbuf *)pixbuff and also right clicking on the variable and using different display options to no avail. any ideas on how to correctly look inside this structure ? A: Try to cast it to GdkPixbuf * before printing. See also this question How to print <incomplete type> variable in gdb. (gdb) p (GdkPixbuf *)pixbuff A: I can't tell you how to do this in gdb but if you are open for other ideas, you can try this with gtkparasite like this: GTK_MODULES=gtkparasite yourapp. If you ever used Spy++ on Windows, it will fit right in.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Run tests in TFS 2010 with a different identity Is it possible to run the tests on TFS 2010 with a different identity ? The code being tested require higher privileges ( Active Directory, Filesystem manipulations) than the ones the current account has. Right now there there is impersonation in the code but I want to get rid of it as the calling website will have the impersonation active. Thanks ! Vincent A: From the Test agent, Test Controller and MSTEST FAQ: Will Test Agents allow you to impersonate another user? Or does the Test Agent always kick of tests as the user its configured start up as? There is no built in support for impersonation, so by default tests run under the identity of the test agent. If this is something you really need, you could write a unit test extension that does the impersonation for you. You can potentially also turn this behavior into your advantage: run an MSTest agent under an elevated account and dispatch your test runs to be executed by this MSTest agent. To configure this, please read: Create Test Settings to Run Automated Tests from Visual Studio. This will allow you to run your test to be executed under the account ofn desire, without having to explicitly impersonate your user all the time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How regroup all comments on my index page? I use FB Comments with this code <div id="fb-root"></div> <script src="http://connect.facebook.net/fr_FR/all.js#xfbml=1"> </script> <fb:comments publish_feed="true" href="http://infoactu.fr/xxxxxx.html" num_posts="25" width="600"></fb:comments> All my pages have a different URL so I get different comments. But on my index page, I want to show all the comments of the pages. Can you help me? I must develop with php? With what? I don't find on FB comment. A: If you are doing this then you will need to query the facebook data yourself and post the results to the page. so sending requests to: https://graph.facebook.com/comments/?ids={YOUR_URL}. then you will need to merge these results and show them on your index page. I believe you can have multiple urls in one request but have not tested this. you may have to aggregate multiple requests Hope this helps Oh see here for more docs: http://developers.facebook.com/docs/reference/plugins/comments/
{ "language": "en", "url": "https://stackoverflow.com/questions/7606832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Standalone attachments using CouchRest Can some one give me an example of using CouchRest to store a standalone attachment in CouchDB? This is for a non Rails project. So something which does not involve CouchRest::Model would be nice. thanks, mano A: It looks like the CouchRest github UsageOverview wiki page has some basic examples, in the "Attachments" section: contents = "<html><body>If you're happy and you know it, clap your hands.</body></html>" @db.put_attachment(doc, "happy.html", contents, :content_type => "text/html") # => {"ok"=>true, "id"=>"e0d70033da0fad3707fed320bd7e0770", "rev"=>"2-20635570c75e8b20f7a73fd1538f318d"} # NOTE: The document is not updated automatically with the attachment information pp doc.to_hash # {"_id"=>"e0d70033da0fad3707fed320bd7e0770", # "_rev"=>"1-cbb61d1f90f7c01b273737702265b6c8", # "key"=>"value", # "another key"=>"another value"} # If you try to fetch the attachment without getting the new state of the document, you will fail @db.fetch_attachment(doc, "happy.html") # => RestClient::ResourceNotFound: 404 Resource Not Found: {"error":"not_found","reason":"Document is missing attachment"} doc = @db.get(doc["_id"]) pp doc.to_hash # {"_id"=>"e0d70033da0fad3707fed320bd7e0770", # "_rev"=>"2-20635570c75e8b20f7a73fd1538f318d", # "key"=>"value", # "another key"=>"another value", # "_attachments"=> # {"happy.html"=> # {"content_type"=>"text/html", # "revpos"=>2, # "digest"=>"md5-q3MreM1aJgfSLHGrJLdg4g==", # "length"=>75, # "stub"=>true}}} @db.fetch_attachment(doc, "happy.html") => "<html><body>If you're happy and you know it, clap your hands.</body></html>" See the rest of the page for more examples (including deleting attachments).
{ "language": "en", "url": "https://stackoverflow.com/questions/7606838", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Jquery and php, load images and use the src of each image I have a page that display a group of images with the src of each image, but I need to use the src valu of the images. The images loads correctly but when I try to load into input text the src value of the selection image it not work: $("#recurs").click(function(){ $("input[name=''valReturn]").val($("rec").val()); }); the php code: $recu= $objRecur->show_rec_project($aux["IdProject"]); if(!empty($recu)){ while($row = mysql_fetch_array($recu)){ echo'<img src="'.$row["srcrecursos"].'" id="recurs"/><br />'; } }else{ echo 'No items found'; } And the input that need to load the src value: <input type="text" id="valReturn" name="valReturn" width="25px"/> <br/> The php code works but for to load the value into valReturn value not. thanks. A: Try this one: $("#recurs").click(function(){ $("input[name=valReturn]").val($(this).attr('src')); }); or $("#recurs").bind("click", function(){ $("input[name=valReturn]").val($(this).attr('src')); }); In val use $(this) instead $("#recurs") UPDATED $(".recurs").click(function(){ $("input[name=valReturn]").val($(this).attr('src')); }); or $(".recurs").bind("click", function(){ $("input[name=valReturn]").val($(this).attr('src')); }); <img src="'.$row["srcrecursos"].'" class="recurs"/> A: You should do: $("#recurs").click(function(){ $("input[name=valReturn]").val($("#recurs").attr('src')); }); A: You need: <script type="text/javascript"> $(function() { $("#recurs").click(function(){ $("input[name='valReturn']").val($(this).attr('src')); } }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7606840", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error While sending Json data to server with Base64 encoded image string in my code i am sending the json data like this ByteArrayOutputStream baos = new ByteArrayOutputStream(); imgbmp.compress(Bitmap.CompressFormat.PNG, 90, baos); byte[] b = baos.toByteArray(); String encodedImage = Base64.encodeBytes(b); jsonstr = new JSONStringer().object().key("Text") .value(msg).key("Files").array().object().key( "ContentType").value("image/png").key( "Content").value(encodedImage) .endObject().endArray().key("AuthToken").value(token) .endObject(); StringEntity entity = new StringEntity(jsonstr.toString()); entity.setContentType("application/json;charset=UTF-8"); entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8")); request.setEntity(entity); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse res = httpClient.execute(request); and i am getting this error while executing the HttpClient 09-30 11:56:21.571: INFO/Request(22161): org.apache.http.client.methods.HttpPost@468613b0 09-30 11:56:21.586: INFO/JSON ANS(22161): <Fault xmlns="http://schemas.microsoft.com/ws/2005/05/envelope/none"><Code><Value>Receiver</Value><Subcode><Value xmlns:a="http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher">a:InternalServiceFault</Value></Subcode></Code><Reason><Text xml:lang="en-US">The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters. </Text></Reason><Detail><ExceptionDetail xmlns="http://schemas.datacontract.org/2004/07/System.ServiceModel" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><HelpLink i:nil="true"/><InnerException i:nil="true"/><Message>The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters. </Message><StackTrace> at System.Convert.FromBase64String(String s)&#xD; 09-30 11:56:21.586: INFO/JSON ANS(22161): at Zoodig.Core.WebServices.DataContracts.FileContract.GetStream()&#xD; 09-30 11:56:21.586: INFO/JSON ANS(22161): at Zoodig.WebServices.Services.AthletesService.PostUpdate(PostUpdateContract data)&#xD; 09-30 11:56:21.586: INFO/JSON ANS(22161): at SyncInvokePostUpdate(Object , Object[] , Object[] )&#xD; 09-30 11:56:21.586: INFO/JSON ANS(22161): at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]&amp; outputs)&#xD; 09-30 11:56:21.586: INFO/JSON ANS(22161): at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&amp; rpc)&#xD; 09-30 11:56:21.586: INFO/JSON ANS(22161): at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&amp; rpc)&#xD; 09-30 11:56:21.586: INFO/JSON ANS(22161): at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc&amp; rpc)&#xD; 09-30 11:56:21.586: INFO/JSON ANS(22161): at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc&amp; rpc)&#xD; 09-30 11:56:21.586: INFO/JSON ANS(22161): at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc&amp; rpc)&#xD; 09-30 11:56:21.586: INFO/JSON ANS(22161): at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc&amp; rpc)&#xD; 09-30 11:56:21.586: INFO/JSON ANS(22161): at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc&amp; rpc)&#xD; 09-30 11:56:21.586: INFO/JSON ANS(22161): at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc&amp; rpc)&#xD; 09-30 11:56:21.586: INFO/JSON ANS(22161): at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc&amp; rpc)&#xD; 09-30 11:56:21.586: INFO/JSON ANS(22161): at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</StackTrace><Type>System.FormatException</Type></ExceptionDetail></Detail></Fault> Please if anyone can understand this and tell me whats happening here..where are the posibilities that i have made any mistakes..and why i am getting the error? Thank You. MKJParekh A: i got the answer... i was not making any kind of mistakes that was problem with org.json i switched to another..and all it works nesting too deep in JSON... should I switch to XML? A: Looking at your code, you are using enimg to add the image data to your JSON and not encodedImage. If this is a cut & paste error in your question, then I suspect that there may be a problem in your Base64 encoding. Have you tried using the encodeToString() method of android.util.Base64 instead? Even if you need to support API versions earlier than 8, this will prove whether it's a Base64 error, and once you've determined that you'll know what you have to fix. A: Don't pass files/images with json. You will get "out of memory" errors if files/images are big.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Connect PC to Phone I want to know how to connect my PC to phone.I'm doing an Android Programme and want to run it on my phone.How should I "build and run" it in from the android-eclipse to my samsung P500 phone? A: There is a nice guide which illustrates how to do so: Android Docs A: There is no samsung p500 as far as I know... do you mean LG p500? Edit: Okay so you got an LG P500, well too bad you have to go through hell (just kidding). You can do multiple things to make it work, but first try to go to LG and use their usb driver download. Link for guide to instal: http://forums.androidcentral.com/other-android-phones/42678-how-install-usb-drivers-lg-optimus-one.html If that doesn't completely solve it try going to (on windows 7) go to my computer -> right click go to manage -> device manager tab -> find your android device (will have yellow marker indicating some kind of problem) and right click it and find update drivers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7606842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Producing UTF-8 encoded XML in Java This is the code I'm using try { String str = "\uC3BC and \uC3B6 and <&> für"; DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.newDocument(); Element root = doc.createElement("test"); root.setAttribute("attribute", str); doc.appendChild(root); DOMSource domSource = new DOMSource(doc); // FileOutputStream out = new FileOutputStream("test.xml"); Writer out = new OutputStreamWriter(new FileOutputStream("test.xml"), "UTF8"); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(domSource, new StreamResult(out)); out.close(); } catch (Exception e) { e.printStackTrace(); } Output is <?xml version="1.0" encoding="UTF-8" standalone="no"?> <test attribute="쎼 and 쎶 and &lt;&amp;&gt; für"/> I want it to output attribute="&#xc3bc and &#xc3b6 ..." How do I achieve this ? I'm using Java 1.6-20 This is similar to Producing valid XML with Java and UTF-8 encoding A: If you don't want the XML to be encoded as UTF-8, you shouldn't tell the transformer to do so. If I understand your question correctly transformer.setOutputProperty(OutputKeys.ENCODING, "US-ASCII"); should produce the output that you want
{ "language": "en", "url": "https://stackoverflow.com/questions/7606843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a way to check how a macro "expands" in C or Objective-C A macro is a preprocessor right. Sometimes we set things right sometimes we don't. Wouldn't it be nice to once in a while expand the macro and see how it works? A: You can do this with most compilers, e.g. with gcc: $ gcc -E this just runs the preprocessor and then stops, giving you the pre-processed output on stdout. If you're using Xcode though you don't even need to do this - depending on what version of Xcode you're using you can just select Preprocess from the Build menu (that's what its called in Xcode 3.x - if you're using Xcode 4 it may have been moved/renamed). See: Xcode Preprocessor Output
{ "language": "en", "url": "https://stackoverflow.com/questions/7606844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: jQuery grid for mvc3 razor? What are the most recommended free jQuery grid for mvc3 razor? has good documents and samples which one is for mvc3? * *Flexigrid: http://flexigrid.info/ *jQuery Grid: http://www.trirand.com/blog/ *jqGridView: http://plugins.jquery.com/project/jqGridView *Ingrid: http://reconstrukt.com/ingrid/ *SlickGrid http://github.com/mleibman/SlickGrid A: None is for MVC 3 or what version you want. They all target HTML and Javascript using the jQuery Framework. If you want to use any of those in your list, you are able to do so, just see what is the markup they want and create your grid that way. as an example: jQuery TableSorter 2.0 it askes for a grid with this markup <table id="myTable" class="tablesorter"> <thead> <tr> <th>Last Name</th> <th>First Name</th> <th>Email</th> <th>Due</th> <th>Web Site</th> </tr> </thead> <tbody> <tr> <td>Smith</td> <td>John</td> <td>jsmith@gmail.com</td> <td>$50.00</td> <td>http://www.jsmith.com</td> </tr> <tr> <td>Bach</td> <td>Frank</td> <td>fbach@yahoo.com</td> <td>$50.00</td> <td>http://www.frank.com</td> </tr> <tr> <td>Doe</td> <td>Jason</td> <td>jdoe@hotmail.com</td> <td>$100.00</td> <td>http://www.jdoe.com</td> </tr> <tr> <td>Conway</td> <td>Tim</td> <td>tconway@earthlink.net</td> <td>$50.00</td> <td>http://www.timconway.com</td> </tr> </tbody> </table> so, all you need to do is making that markup in your View as a simple example: <table id="myTable" class="tablesorter"> <thead> <tr> <th>Last Name</th> <th>First Name</th> <th>Email</th> <th>Due</th> <th>Web Site</th> </tr> </thead> <tbody> @foreach(var item in Model) { <tr> <td>@item.lastname</td> <td>@item.firstname</td> <td>@item.email</td> <td>@item.due.ToString("c")</td> <td>@item.url</td> </tr> } </table>
{ "language": "en", "url": "https://stackoverflow.com/questions/7606845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to overcome this error:java.lang.OutOfMemoryError: bitmap size exceeds VM budget I am trying to add images in Sqlite DB and listing the images from DB to listview.... I am storing the image path to get image. When I list the images from DB in device I am getting error like java.lang.OutOfMemoryError: bitmap size exceeds VM budget Do I clear heap memory every time. How to correct this.. Here is my code. LView.class mySQLiteAdapter = new SQLiteAdapter(this); mySQLiteAdapter.openToWrite(); mAlbum = (ImageView) findViewById(R.id.iv); mAlbum.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, IMG); } }); Button click = (Button) findViewById(R.id.button); click.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub mySQLiteAdapter.insert(str); System.out.println(str+" Added"); Intent intent = new Intent(LView.this, MyList.class); startActivity(intent); } });` ` @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); switch(requestCode) { case 1: if(resultCode == RESULT_OK) { Uri selectedUri = data.getData(); str = getPath(selectedUri); Bitmap bitmap; try { bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedUri)); mAlbum.setImageBitmap(bitmap); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; } } } // Converting image path Uri to String path to store in DB public String getPath(Uri uri) { String[] projection = { MediaStore.Images.Media.DATA }; Cursor cur = managedQuery(uri, projection, null, null, null); int columnIndex = cur.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cur.moveToFirst(); return cur.getString(columnIndex); }` Pls suggest me... Thanks in advance. A: 1) try to decode the image bound first you get the actual size of the image to prevent the OOM issue. Dont ever decode the image first!!! BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(bitmapByteArray, 0, bitmapByteArray.length, options);' options.outWidth and options.outHeight are what you want. 2) compute a sample size by using the following code from http://hi-android.info/src/com/android/camera/Util.java.html. If you detect the outWidth and outHeight are too big to have OOM issue, just set the outWidth and outHeight to a smaller size. It will give you a sample size that the decoded image will be set to those outWidth and outHeight. The bitmap options here is the same you use in step 1. private static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) { double w = options.outWidth; double h = options.outHeight; int lowerBound = (maxNumOfPixels == IImage.UNCONSTRAINED) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels)); int upperBound = (minSideLength == IImage.UNCONSTRAINED) ? 128 : (int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength)); if (upperBound < lowerBound) { // return the larger one when there is no overlapping zone. return lowerBound; } if ((maxNumOfPixels == IImage.UNCONSTRAINED) && (minSideLength == IImage.UNCONSTRAINED)) { return 1; } else if (minSideLength == IImage.UNCONSTRAINED) { return lowerBound; } else { return upperBound; } } 3) Use the computed sample size Once you get the sample size, use it to decode the real image data. options.inTempStorage = new byte[16*1024]; options.inPreferredConfig = (config == null)?BitmapUtil.DEFAULT_CONFIG:config; options.inSampleSize = BitmapUtil.computeSampleSize(bitmapWidth, bitmapHeight, bitmapWidth < bitmapHeight?targetHeight:targetWidth, bitmapWidth < bitmapHeight?targetWidth:targetHeight, 1); options.inPurgeable = true; options.inInputShareable = true; options.inJustDecodeBounds = false; options.inDither = true; result = BitmapFactory.decodeByteArray(bitmapByteArray, 0, bitmapByteArray.length, options); ~If this still give you OOM issue, you can try to lower the outWidth and outHeight. bitmap is using native heap, not the java heap. So it is hard to detect how much memory left for the new image decoded. ~~If you have to set the outWidth and outHeight too low, then you may have memory leak somewhere in your code. try to release any object from memory that you dont use. e.g bitmap.release(); ~~~the above is just a sample code. adjust what you need. A: see this question bitmap size exceeds VM budget A: Have yout tried using one class-wide Bitmap and re-allocate it in your case clause?
{ "language": "en", "url": "https://stackoverflow.com/questions/7606846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How does HTML5 localstorage work? I have to create one application in which the user is to get some data based on his username and passsword. Is it possible to create single persistant local storage for multiple HTML pages of a website? Do I have to insert records everytime the page loads? My expectation is that inserting records one time for multiple users. Can anyone help? A: Yes, the storage is at domain level so you don't have to 'refresh' or re-populate the data on page load. It'll also survive sessions too, but remember that everything is a key/value pair stored as a string so you'll need to parse it when you read it back out (JSON.parse());
{ "language": "en", "url": "https://stackoverflow.com/questions/7606853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }